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_sv; /* The SV that is the regexp. */
106 regexp *rx; /* perl core regexp structure */
107 regexp_internal *rxi; /* internal data for regexp object pprivate field */
108 char *start; /* Start of input for compile */
109 char *end; /* End of input for compile */
110 char *parse; /* Input-scan pointer. */
111 I32 whilem_seen; /* number of WHILEM in this expr */
112 regnode *emit_start; /* Start of emitted-code area */
113 regnode *emit_bound; /* First regnode outside of the allocated space */
114 regnode *emit; /* Code-emit pointer; ®dummy = don't = compiling */
115 I32 naughty; /* How bad is this pattern? */
116 I32 sawback; /* Did we see \1, ...? */
118 I32 size; /* Code size. */
119 I32 npar; /* Capture buffer count, (OPEN). */
120 I32 cpar; /* Capture buffer count, (CLOSE). */
121 I32 nestroot; /* root parens we are in - used by accept */
125 regnode **open_parens; /* pointers to open parens */
126 regnode **close_parens; /* pointers to close parens */
127 regnode *opend; /* END node in program */
128 I32 utf8; /* whether the pattern is utf8 or not */
129 I32 orig_utf8; /* whether the pattern was originally in utf8 */
130 /* XXX use this for future optimisation of case
131 * where pattern must be upgraded to utf8. */
132 HV *charnames; /* cache of named sequences */
133 HV *paren_names; /* Paren names */
135 regnode **recurse; /* Recurse regops */
136 I32 recurse_count; /* Number of recurse regops */
138 char *starttry; /* -Dr: where regtry was called. */
139 #define RExC_starttry (pRExC_state->starttry)
142 const char *lastparse;
144 AV *paren_name_list; /* idx -> name */
145 #define RExC_lastparse (pRExC_state->lastparse)
146 #define RExC_lastnum (pRExC_state->lastnum)
147 #define RExC_paren_name_list (pRExC_state->paren_name_list)
151 #define RExC_flags (pRExC_state->flags)
152 #define RExC_precomp (pRExC_state->precomp)
153 #define RExC_rx_sv (pRExC_state->rx_sv)
154 #define RExC_rx (pRExC_state->rx)
155 #define RExC_rxi (pRExC_state->rxi)
156 #define RExC_start (pRExC_state->start)
157 #define RExC_end (pRExC_state->end)
158 #define RExC_parse (pRExC_state->parse)
159 #define RExC_whilem_seen (pRExC_state->whilem_seen)
160 #ifdef RE_TRACK_PATTERN_OFFSETS
161 #define RExC_offsets (pRExC_state->rxi->u.offsets) /* I am not like the others */
163 #define RExC_emit (pRExC_state->emit)
164 #define RExC_emit_start (pRExC_state->emit_start)
165 #define RExC_emit_bound (pRExC_state->emit_bound)
166 #define RExC_naughty (pRExC_state->naughty)
167 #define RExC_sawback (pRExC_state->sawback)
168 #define RExC_seen (pRExC_state->seen)
169 #define RExC_size (pRExC_state->size)
170 #define RExC_npar (pRExC_state->npar)
171 #define RExC_nestroot (pRExC_state->nestroot)
172 #define RExC_extralen (pRExC_state->extralen)
173 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
174 #define RExC_seen_evals (pRExC_state->seen_evals)
175 #define RExC_utf8 (pRExC_state->utf8)
176 #define RExC_orig_utf8 (pRExC_state->orig_utf8)
177 #define RExC_charnames (pRExC_state->charnames)
178 #define RExC_open_parens (pRExC_state->open_parens)
179 #define RExC_close_parens (pRExC_state->close_parens)
180 #define RExC_opend (pRExC_state->opend)
181 #define RExC_paren_names (pRExC_state->paren_names)
182 #define RExC_recurse (pRExC_state->recurse)
183 #define RExC_recurse_count (pRExC_state->recurse_count)
186 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
187 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
188 ((*s) == '{' && regcurly(s)))
191 #undef SPSTART /* dratted cpp namespace... */
194 * Flags to be passed up and down.
196 #define WORST 0 /* Worst case. */
197 #define HASWIDTH 0x01 /* Known to match non-null strings. */
198 #define SIMPLE 0x02 /* Simple enough to be STAR/PLUS operand. */
199 #define SPSTART 0x04 /* Starts with * or +. */
200 #define TRYAGAIN 0x08 /* Weeded out a declaration. */
201 #define POSTPONED 0x10 /* (?1),(?&name), (??{...}) or similar */
203 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
205 /* whether trie related optimizations are enabled */
206 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
207 #define TRIE_STUDY_OPT
208 #define FULL_TRIE_STUDY
214 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
215 #define PBITVAL(paren) (1 << ((paren) & 7))
216 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
217 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
218 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
221 /* About scan_data_t.
223 During optimisation we recurse through the regexp program performing
224 various inplace (keyhole style) optimisations. In addition study_chunk
225 and scan_commit populate this data structure with information about
226 what strings MUST appear in the pattern. We look for the longest
227 string that must appear for at a fixed location, and we look for the
228 longest string that may appear at a floating location. So for instance
233 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
234 strings (because they follow a .* construct). study_chunk will identify
235 both FOO and BAR as being the longest fixed and floating strings respectively.
237 The strings can be composites, for instance
241 will result in a composite fixed substring 'foo'.
243 For each string some basic information is maintained:
245 - offset or min_offset
246 This is the position the string must appear at, or not before.
247 It also implicitly (when combined with minlenp) tells us how many
248 character must match before the string we are searching.
249 Likewise when combined with minlenp and the length of the string
250 tells us how many characters must appear after the string we have
254 Only used for floating strings. This is the rightmost point that
255 the string can appear at. Ifset to I32 max it indicates that the
256 string can occur infinitely far to the right.
259 A pointer to the minimum length of the pattern that the string
260 was found inside. This is important as in the case of positive
261 lookahead or positive lookbehind we can have multiple patterns
266 The minimum length of the pattern overall is 3, the minimum length
267 of the lookahead part is 3, but the minimum length of the part that
268 will actually match is 1. So 'FOO's minimum length is 3, but the
269 minimum length for the F is 1. This is important as the minimum length
270 is used to determine offsets in front of and behind the string being
271 looked for. Since strings can be composites this is the length of the
272 pattern at the time it was commited with a scan_commit. Note that
273 the length is calculated by study_chunk, so that the minimum lengths
274 are not known until the full pattern has been compiled, thus the
275 pointer to the value.
279 In the case of lookbehind the string being searched for can be
280 offset past the start point of the final matching string.
281 If this value was just blithely removed from the min_offset it would
282 invalidate some of the calculations for how many chars must match
283 before or after (as they are derived from min_offset and minlen and
284 the length of the string being searched for).
285 When the final pattern is compiled and the data is moved from the
286 scan_data_t structure into the regexp structure the information
287 about lookbehind is factored in, with the information that would
288 have been lost precalculated in the end_shift field for the
291 The fields pos_min and pos_delta are used to store the minimum offset
292 and the delta to the maximum offset at the current point in the pattern.
296 typedef struct scan_data_t {
297 /*I32 len_min; unused */
298 /*I32 len_delta; unused */
302 I32 last_end; /* min value, <0 unless valid. */
305 SV **longest; /* Either &l_fixed, or &l_float. */
306 SV *longest_fixed; /* longest fixed string found in pattern */
307 I32 offset_fixed; /* offset where it starts */
308 I32 *minlen_fixed; /* pointer to the minlen relevent to the string */
309 I32 lookbehind_fixed; /* is the position of the string modfied by LB */
310 SV *longest_float; /* longest floating string found in pattern */
311 I32 offset_float_min; /* earliest point in string it can appear */
312 I32 offset_float_max; /* latest point in string it can appear */
313 I32 *minlen_float; /* pointer to the minlen relevent to the string */
314 I32 lookbehind_float; /* is the position of the string modified by LB */
318 struct regnode_charclass_class *start_class;
322 * Forward declarations for pregcomp()'s friends.
325 static const scan_data_t zero_scan_data =
326 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
328 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
329 #define SF_BEFORE_SEOL 0x0001
330 #define SF_BEFORE_MEOL 0x0002
331 #define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
332 #define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
335 # define SF_FIX_SHIFT_EOL (0+2)
336 # define SF_FL_SHIFT_EOL (0+4)
338 # define SF_FIX_SHIFT_EOL (+2)
339 # define SF_FL_SHIFT_EOL (+4)
342 #define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
343 #define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
345 #define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
346 #define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
347 #define SF_IS_INF 0x0040
348 #define SF_HAS_PAR 0x0080
349 #define SF_IN_PAR 0x0100
350 #define SF_HAS_EVAL 0x0200
351 #define SCF_DO_SUBSTR 0x0400
352 #define SCF_DO_STCLASS_AND 0x0800
353 #define SCF_DO_STCLASS_OR 0x1000
354 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
355 #define SCF_WHILEM_VISITED_POS 0x2000
357 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
358 #define SCF_SEEN_ACCEPT 0x8000
360 #define UTF (RExC_utf8 != 0)
361 #define LOC ((RExC_flags & RXf_PMf_LOCALE) != 0)
362 #define FOLD ((RExC_flags & RXf_PMf_FOLD) != 0)
364 #define OOB_UNICODE 12345678
365 #define OOB_NAMEDCLASS -1
367 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
368 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
371 /* length of regex to show in messages that don't mark a position within */
372 #define RegexLengthToShowInErrorMessages 127
375 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
376 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
377 * op/pragma/warn/regcomp.
379 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
380 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
382 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
385 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
386 * arg. Show regex, up to a maximum length. If it's too long, chop and add
389 #define _FAIL(code) STMT_START { \
390 const char *ellipses = ""; \
391 IV len = RExC_end - RExC_precomp; \
394 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
395 if (len > RegexLengthToShowInErrorMessages) { \
396 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
397 len = RegexLengthToShowInErrorMessages - 10; \
403 #define FAIL(msg) _FAIL( \
404 Perl_croak(aTHX_ "%s in regex m/%.*s%s/", \
405 msg, (int)len, RExC_precomp, ellipses))
407 #define FAIL2(msg,arg) _FAIL( \
408 Perl_croak(aTHX_ msg " in regex m/%.*s%s/", \
409 arg, (int)len, RExC_precomp, ellipses))
412 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
414 #define Simple_vFAIL(m) STMT_START { \
415 const IV offset = RExC_parse - RExC_precomp; \
416 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
417 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
421 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
423 #define vFAIL(m) STMT_START { \
425 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
430 * Like Simple_vFAIL(), but accepts two arguments.
432 #define Simple_vFAIL2(m,a1) STMT_START { \
433 const IV offset = RExC_parse - RExC_precomp; \
434 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, \
435 (int)offset, RExC_precomp, RExC_precomp + offset); \
439 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
441 #define vFAIL2(m,a1) STMT_START { \
443 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
444 Simple_vFAIL2(m, a1); \
449 * Like Simple_vFAIL(), but accepts three arguments.
451 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
452 const IV offset = RExC_parse - RExC_precomp; \
453 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, \
454 (int)offset, RExC_precomp, RExC_precomp + offset); \
458 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
460 #define vFAIL3(m,a1,a2) STMT_START { \
462 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
463 Simple_vFAIL3(m, a1, a2); \
467 * Like Simple_vFAIL(), but accepts four arguments.
469 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
470 const IV offset = RExC_parse - RExC_precomp; \
471 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, \
472 (int)offset, RExC_precomp, RExC_precomp + offset); \
475 #define vWARN(loc,m) STMT_START { \
476 const IV offset = loc - RExC_precomp; \
477 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s" REPORT_LOCATION, \
478 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
481 #define vWARNdep(loc,m) STMT_START { \
482 const IV offset = loc - RExC_precomp; \
483 Perl_warner(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
484 "%s" REPORT_LOCATION, \
485 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
489 #define vWARN2(loc, m, a1) STMT_START { \
490 const IV offset = loc - RExC_precomp; \
491 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
492 a1, (int)offset, RExC_precomp, RExC_precomp + offset); \
495 #define vWARN3(loc, m, a1, a2) STMT_START { \
496 const IV offset = loc - RExC_precomp; \
497 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
498 a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
501 #define vWARN4(loc, m, a1, a2, a3) STMT_START { \
502 const IV offset = loc - RExC_precomp; \
503 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
504 a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
507 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START { \
508 const IV offset = loc - RExC_precomp; \
509 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
510 a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
514 /* Allow for side effects in s */
515 #define REGC(c,s) STMT_START { \
516 if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
519 /* Macros for recording node offsets. 20001227 mjd@plover.com
520 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
521 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
522 * Element 0 holds the number n.
523 * Position is 1 indexed.
525 #ifndef RE_TRACK_PATTERN_OFFSETS
526 #define Set_Node_Offset_To_R(node,byte)
527 #define Set_Node_Offset(node,byte)
528 #define Set_Cur_Node_Offset
529 #define Set_Node_Length_To_R(node,len)
530 #define Set_Node_Length(node,len)
531 #define Set_Node_Cur_Length(node)
532 #define Node_Offset(n)
533 #define Node_Length(n)
534 #define Set_Node_Offset_Length(node,offset,len)
535 #define ProgLen(ri) ri->u.proglen
536 #define SetProgLen(ri,x) ri->u.proglen = x
538 #define ProgLen(ri) ri->u.offsets[0]
539 #define SetProgLen(ri,x) ri->u.offsets[0] = x
540 #define Set_Node_Offset_To_R(node,byte) STMT_START { \
542 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
543 __LINE__, (int)(node), (int)(byte))); \
545 Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
547 RExC_offsets[2*(node)-1] = (byte); \
552 #define Set_Node_Offset(node,byte) \
553 Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
554 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
556 #define Set_Node_Length_To_R(node,len) STMT_START { \
558 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
559 __LINE__, (int)(node), (int)(len))); \
561 Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
563 RExC_offsets[2*(node)] = (len); \
568 #define Set_Node_Length(node,len) \
569 Set_Node_Length_To_R((node)-RExC_emit_start, len)
570 #define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
571 #define Set_Node_Cur_Length(node) \
572 Set_Node_Length(node, RExC_parse - parse_start)
574 /* Get offsets and lengths */
575 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
576 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
578 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
579 Set_Node_Offset_To_R((node)-RExC_emit_start, (offset)); \
580 Set_Node_Length_To_R((node)-RExC_emit_start, (len)); \
584 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
585 #define EXPERIMENTAL_INPLACESCAN
586 #endif /*RE_TRACK_PATTERN_OFFSETS*/
588 #define DEBUG_STUDYDATA(str,data,depth) \
589 DEBUG_OPTIMISE_MORE_r(if(data){ \
590 PerlIO_printf(Perl_debug_log, \
591 "%*s" str "Pos:%"IVdf"/%"IVdf \
592 " Flags: 0x%"UVXf" Whilem_c: %"IVdf" Lcp: %"IVdf" %s", \
593 (int)(depth)*2, "", \
594 (IV)((data)->pos_min), \
595 (IV)((data)->pos_delta), \
596 (UV)((data)->flags), \
597 (IV)((data)->whilem_c), \
598 (IV)((data)->last_closep ? *((data)->last_closep) : -1), \
599 is_inf ? "INF " : "" \
601 if ((data)->last_found) \
602 PerlIO_printf(Perl_debug_log, \
603 "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
604 " %sFloat: '%s' @ %"IVdf"/%"IVdf"", \
605 SvPVX_const((data)->last_found), \
606 (IV)((data)->last_end), \
607 (IV)((data)->last_start_min), \
608 (IV)((data)->last_start_max), \
609 ((data)->longest && \
610 (data)->longest==&((data)->longest_fixed)) ? "*" : "", \
611 SvPVX_const((data)->longest_fixed), \
612 (IV)((data)->offset_fixed), \
613 ((data)->longest && \
614 (data)->longest==&((data)->longest_float)) ? "*" : "", \
615 SvPVX_const((data)->longest_float), \
616 (IV)((data)->offset_float_min), \
617 (IV)((data)->offset_float_max) \
619 PerlIO_printf(Perl_debug_log,"\n"); \
622 static void clear_re(pTHX_ void *r);
624 /* Mark that we cannot extend a found fixed substring at this point.
625 Update the longest found anchored substring and the longest found
626 floating substrings if needed. */
629 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp, int is_inf)
631 const STRLEN l = CHR_SVLEN(data->last_found);
632 const STRLEN old_l = CHR_SVLEN(*data->longest);
633 GET_RE_DEBUG_FLAGS_DECL;
635 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
636 SvSetMagicSV(*data->longest, data->last_found);
637 if (*data->longest == data->longest_fixed) {
638 data->offset_fixed = l ? data->last_start_min : data->pos_min;
639 if (data->flags & SF_BEFORE_EOL)
641 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
643 data->flags &= ~SF_FIX_BEFORE_EOL;
644 data->minlen_fixed=minlenp;
645 data->lookbehind_fixed=0;
647 else { /* *data->longest == data->longest_float */
648 data->offset_float_min = l ? data->last_start_min : data->pos_min;
649 data->offset_float_max = (l
650 ? data->last_start_max
651 : data->pos_min + data->pos_delta);
652 if (is_inf || (U32)data->offset_float_max > (U32)I32_MAX)
653 data->offset_float_max = I32_MAX;
654 if (data->flags & SF_BEFORE_EOL)
656 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
658 data->flags &= ~SF_FL_BEFORE_EOL;
659 data->minlen_float=minlenp;
660 data->lookbehind_float=0;
663 SvCUR_set(data->last_found, 0);
665 SV * const sv = data->last_found;
666 if (SvUTF8(sv) && SvMAGICAL(sv)) {
667 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
673 data->flags &= ~SF_BEFORE_EOL;
674 DEBUG_STUDYDATA("commit: ",data,0);
677 /* Can match anything (initialization) */
679 S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
681 ANYOF_CLASS_ZERO(cl);
682 ANYOF_BITMAP_SETALL(cl);
683 cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL;
685 cl->flags |= ANYOF_LOCALE;
688 /* Can match anything (initialization) */
690 S_cl_is_anything(const struct regnode_charclass_class *cl)
694 for (value = 0; value <= ANYOF_MAX; value += 2)
695 if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
697 if (!(cl->flags & ANYOF_UNICODE_ALL))
699 if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
704 /* Can match anything (initialization) */
706 S_cl_init(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);
714 S_cl_init_zero(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
716 Zero(cl, 1, struct regnode_charclass_class);
718 cl_anything(pRExC_state, cl);
720 cl->flags |= ANYOF_LOCALE;
723 /* 'And' a given class with another one. Can create false positives */
724 /* We assume that cl is not inverted */
726 S_cl_and(struct regnode_charclass_class *cl,
727 const struct regnode_charclass_class *and_with)
730 assert(and_with->type == ANYOF);
731 if (!(and_with->flags & ANYOF_CLASS)
732 && !(cl->flags & ANYOF_CLASS)
733 && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
734 && !(and_with->flags & ANYOF_FOLD)
735 && !(cl->flags & ANYOF_FOLD)) {
738 if (and_with->flags & ANYOF_INVERT)
739 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
740 cl->bitmap[i] &= ~and_with->bitmap[i];
742 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
743 cl->bitmap[i] &= and_with->bitmap[i];
744 } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
745 if (!(and_with->flags & ANYOF_EOS))
746 cl->flags &= ~ANYOF_EOS;
748 if (cl->flags & ANYOF_UNICODE_ALL && and_with->flags & ANYOF_UNICODE &&
749 !(and_with->flags & ANYOF_INVERT)) {
750 cl->flags &= ~ANYOF_UNICODE_ALL;
751 cl->flags |= ANYOF_UNICODE;
752 ARG_SET(cl, ARG(and_with));
754 if (!(and_with->flags & ANYOF_UNICODE_ALL) &&
755 !(and_with->flags & ANYOF_INVERT))
756 cl->flags &= ~ANYOF_UNICODE_ALL;
757 if (!(and_with->flags & (ANYOF_UNICODE|ANYOF_UNICODE_ALL)) &&
758 !(and_with->flags & ANYOF_INVERT))
759 cl->flags &= ~ANYOF_UNICODE;
762 /* 'OR' a given class with another one. Can create false positives */
763 /* We assume that cl is not inverted */
765 S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
767 if (or_with->flags & ANYOF_INVERT) {
769 * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
770 * <= (B1 | !B2) | (CL1 | !CL2)
771 * which is wasteful if CL2 is small, but we ignore CL2:
772 * (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
773 * XXXX Can we handle case-fold? Unclear:
774 * (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
775 * (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
777 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
778 && !(or_with->flags & ANYOF_FOLD)
779 && !(cl->flags & ANYOF_FOLD) ) {
782 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
783 cl->bitmap[i] |= ~or_with->bitmap[i];
784 } /* XXXX: logic is complicated otherwise */
786 cl_anything(pRExC_state, cl);
789 /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
790 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
791 && (!(or_with->flags & ANYOF_FOLD)
792 || (cl->flags & ANYOF_FOLD)) ) {
795 /* OR char bitmap and class bitmap separately */
796 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
797 cl->bitmap[i] |= or_with->bitmap[i];
798 if (or_with->flags & ANYOF_CLASS) {
799 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
800 cl->classflags[i] |= or_with->classflags[i];
801 cl->flags |= ANYOF_CLASS;
804 else { /* XXXX: logic is complicated, leave it along for a moment. */
805 cl_anything(pRExC_state, cl);
808 if (or_with->flags & ANYOF_EOS)
809 cl->flags |= ANYOF_EOS;
811 if (cl->flags & ANYOF_UNICODE && or_with->flags & ANYOF_UNICODE &&
812 ARG(cl) != ARG(or_with)) {
813 cl->flags |= ANYOF_UNICODE_ALL;
814 cl->flags &= ~ANYOF_UNICODE;
816 if (or_with->flags & ANYOF_UNICODE_ALL) {
817 cl->flags |= ANYOF_UNICODE_ALL;
818 cl->flags &= ~ANYOF_UNICODE;
822 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
823 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
824 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
825 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
830 dump_trie(trie,widecharmap,revcharmap)
831 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
832 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
834 These routines dump out a trie in a somewhat readable format.
835 The _interim_ variants are used for debugging the interim
836 tables that are used to generate the final compressed
837 representation which is what dump_trie expects.
839 Part of the reason for their existance is to provide a form
840 of documentation as to how the different representations function.
845 Dumps the final compressed table form of the trie to Perl_debug_log.
846 Used for debugging make_trie().
850 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
851 AV *revcharmap, U32 depth)
854 SV *sv=sv_newmortal();
855 int colwidth= widecharmap ? 6 : 4;
856 GET_RE_DEBUG_FLAGS_DECL;
859 PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
860 (int)depth * 2 + 2,"",
861 "Match","Base","Ofs" );
863 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
864 SV ** const tmp = av_fetch( revcharmap, state, 0);
866 PerlIO_printf( Perl_debug_log, "%*s",
868 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
869 PL_colors[0], PL_colors[1],
870 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
871 PERL_PV_ESCAPE_FIRSTCHAR
876 PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
877 (int)depth * 2 + 2,"");
879 for( state = 0 ; state < trie->uniquecharcount ; state++ )
880 PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
881 PerlIO_printf( Perl_debug_log, "\n");
883 for( state = 1 ; state < trie->statecount ; state++ ) {
884 const U32 base = trie->states[ state ].trans.base;
886 PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
888 if ( trie->states[ state ].wordnum ) {
889 PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
891 PerlIO_printf( Perl_debug_log, "%6s", "" );
894 PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
899 while( ( base + ofs < trie->uniquecharcount ) ||
900 ( base + ofs - trie->uniquecharcount < trie->lasttrans
901 && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
904 PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
906 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
907 if ( ( base + ofs >= trie->uniquecharcount ) &&
908 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
909 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
911 PerlIO_printf( Perl_debug_log, "%*"UVXf,
913 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
915 PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
919 PerlIO_printf( Perl_debug_log, "]");
922 PerlIO_printf( Perl_debug_log, "\n" );
926 Dumps a fully constructed but uncompressed trie in list form.
927 List tries normally only are used for construction when the number of
928 possible chars (trie->uniquecharcount) is very high.
929 Used for debugging make_trie().
932 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
933 HV *widecharmap, AV *revcharmap, U32 next_alloc,
937 SV *sv=sv_newmortal();
938 int colwidth= widecharmap ? 6 : 4;
939 GET_RE_DEBUG_FLAGS_DECL;
940 /* print out the table precompression. */
941 PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
942 (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
943 "------:-----+-----------------\n" );
945 for( state=1 ; state < next_alloc ; state ++ ) {
948 PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
949 (int)depth * 2 + 2,"", (UV)state );
950 if ( ! trie->states[ state ].wordnum ) {
951 PerlIO_printf( Perl_debug_log, "%5s| ","");
953 PerlIO_printf( Perl_debug_log, "W%4x| ",
954 trie->states[ state ].wordnum
957 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
958 SV ** const tmp = av_fetch( revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
960 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
962 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
963 PL_colors[0], PL_colors[1],
964 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
965 PERL_PV_ESCAPE_FIRSTCHAR
967 TRIE_LIST_ITEM(state,charid).forid,
968 (UV)TRIE_LIST_ITEM(state,charid).newstate
971 PerlIO_printf(Perl_debug_log, "\n%*s| ",
972 (int)((depth * 2) + 14), "");
975 PerlIO_printf( Perl_debug_log, "\n");
980 Dumps a fully constructed but uncompressed trie in table form.
981 This is the normal DFA style state transition table, with a few
982 twists to facilitate compression later.
983 Used for debugging make_trie().
986 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
987 HV *widecharmap, AV *revcharmap, U32 next_alloc,
992 SV *sv=sv_newmortal();
993 int colwidth= widecharmap ? 6 : 4;
994 GET_RE_DEBUG_FLAGS_DECL;
997 print out the table precompression so that we can do a visual check
998 that they are identical.
1001 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
1003 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1004 SV ** const tmp = av_fetch( revcharmap, charid, 0);
1006 PerlIO_printf( Perl_debug_log, "%*s",
1008 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
1009 PL_colors[0], PL_colors[1],
1010 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1011 PERL_PV_ESCAPE_FIRSTCHAR
1017 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
1019 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
1020 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
1023 PerlIO_printf( Perl_debug_log, "\n" );
1025 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
1027 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
1028 (int)depth * 2 + 2,"",
1029 (UV)TRIE_NODENUM( state ) );
1031 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1032 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
1034 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
1036 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
1038 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
1039 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
1041 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
1042 trie->states[ TRIE_NODENUM( state ) ].wordnum );
1049 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1050 startbranch: the first branch in the whole branch sequence
1051 first : start branch of sequence of branch-exact nodes.
1052 May be the same as startbranch
1053 last : Thing following the last branch.
1054 May be the same as tail.
1055 tail : item following the branch sequence
1056 count : words in the sequence
1057 flags : currently the OP() type we will be building one of /EXACT(|F|Fl)/
1058 depth : indent depth
1060 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
1062 A trie is an N'ary tree where the branches are determined by digital
1063 decomposition of the key. IE, at the root node you look up the 1st character and
1064 follow that branch repeat until you find the end of the branches. Nodes can be
1065 marked as "accepting" meaning they represent a complete word. Eg:
1069 would convert into the following structure. Numbers represent states, letters
1070 following numbers represent valid transitions on the letter from that state, if
1071 the number is in square brackets it represents an accepting state, otherwise it
1072 will be in parenthesis.
1074 +-h->+-e->[3]-+-r->(8)-+-s->[9]
1078 (1) +-i->(6)-+-s->[7]
1080 +-s->(3)-+-h->(4)-+-e->[5]
1082 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1084 This shows that when matching against the string 'hers' we will begin at state 1
1085 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1086 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1087 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1088 single traverse. We store a mapping from accepting to state to which word was
1089 matched, and then when we have multiple possibilities we try to complete the
1090 rest of the regex in the order in which they occured in the alternation.
1092 The only prior NFA like behaviour that would be changed by the TRIE support is
1093 the silent ignoring of duplicate alternations which are of the form:
1095 / (DUPE|DUPE) X? (?{ ... }) Y /x
1097 Thus EVAL blocks follwing a trie may be called a different number of times with
1098 and without the optimisation. With the optimisations dupes will be silently
1099 ignored. This inconsistant behaviour of EVAL type nodes is well established as
1100 the following demonstrates:
1102 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1104 which prints out 'word' three times, but
1106 'words'=~/(word|word|word)(?{ print $1 })S/
1108 which doesnt print it out at all. This is due to other optimisations kicking in.
1110 Example of what happens on a structural level:
1112 The regexp /(ac|ad|ab)+/ will produce the folowing debug output:
1114 1: CURLYM[1] {1,32767}(18)
1125 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1126 and should turn into:
1128 1: CURLYM[1] {1,32767}(18)
1130 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1138 Cases where tail != last would be like /(?foo|bar)baz/:
1148 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1149 and would end up looking like:
1152 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1159 d = uvuni_to_utf8_flags(d, uv, 0);
1161 is the recommended Unicode-aware way of saying
1166 #define TRIE_STORE_REVCHAR \
1169 SV *zlopp = newSV(2); \
1170 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
1171 unsigned const char *const kapow = uvuni_to_utf8(flrbbbbb, uvc & 0xFF); \
1172 SvCUR_set(zlopp, kapow - flrbbbbb); \
1175 av_push(revcharmap, zlopp); \
1177 char ooooff = (char)uvc; \
1178 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
1182 #define TRIE_READ_CHAR STMT_START { \
1186 if ( foldlen > 0 ) { \
1187 uvc = utf8n_to_uvuni( scan, UTF8_MAXLEN, &len, uniflags ); \
1192 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1193 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1194 foldlen -= UNISKIP( uvc ); \
1195 scan = foldbuf + UNISKIP( uvc ); \
1198 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1208 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
1209 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
1210 U32 ging = TRIE_LIST_LEN( state ) *= 2; \
1211 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
1213 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
1214 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
1215 TRIE_LIST_CUR( state )++; \
1218 #define TRIE_LIST_NEW(state) STMT_START { \
1219 Newxz( trie->states[ state ].trans.list, \
1220 4, reg_trie_trans_le ); \
1221 TRIE_LIST_CUR( state ) = 1; \
1222 TRIE_LIST_LEN( state ) = 4; \
1225 #define TRIE_HANDLE_WORD(state) STMT_START { \
1226 U16 dupe= trie->states[ state ].wordnum; \
1227 regnode * const noper_next = regnext( noper ); \
1229 if (trie->wordlen) \
1230 trie->wordlen[ curword ] = wordlen; \
1232 /* store the word for dumping */ \
1234 if (OP(noper) != NOTHING) \
1235 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
1237 tmp = newSVpvn_utf8( "", 0, UTF ); \
1238 av_push( trie_words, tmp ); \
1243 if ( noper_next < tail ) { \
1245 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, sizeof(U16) ); \
1246 trie->jump[curword] = (U16)(noper_next - convert); \
1248 jumper = noper_next; \
1250 nextbranch= regnext(cur); \
1254 /* So it's a dupe. This means we need to maintain a */\
1255 /* linked-list from the first to the next. */\
1256 /* we only allocate the nextword buffer when there */\
1257 /* a dupe, so first time we have to do the allocation */\
1258 if (!trie->nextword) \
1259 trie->nextword = (U16 *) \
1260 PerlMemShared_calloc( word_count + 1, sizeof(U16)); \
1261 while ( trie->nextword[dupe] ) \
1262 dupe= trie->nextword[dupe]; \
1263 trie->nextword[dupe]= curword; \
1265 /* we haven't inserted this word yet. */ \
1266 trie->states[ state ].wordnum = curword; \
1271 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
1272 ( ( base + charid >= ucharcount \
1273 && base + charid < ubound \
1274 && state == trie->trans[ base - ucharcount + charid ].check \
1275 && trie->trans[ base - ucharcount + charid ].next ) \
1276 ? trie->trans[ base - ucharcount + charid ].next \
1277 : ( state==1 ? special : 0 ) \
1281 #define MADE_JUMP_TRIE 2
1282 #define MADE_EXACT_TRIE 4
1285 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
1288 /* first pass, loop through and scan words */
1289 reg_trie_data *trie;
1290 HV *widecharmap = NULL;
1291 AV *revcharmap = newAV();
1293 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1298 regnode *jumper = NULL;
1299 regnode *nextbranch = NULL;
1300 regnode *convert = NULL;
1301 /* we just use folder as a flag in utf8 */
1302 const U8 * const folder = ( flags == EXACTF
1304 : ( flags == EXACTFL
1311 const U32 data_slot = add_data( pRExC_state, 4, "tuuu" );
1312 AV *trie_words = NULL;
1313 /* along with revcharmap, this only used during construction but both are
1314 * useful during debugging so we store them in the struct when debugging.
1317 const U32 data_slot = add_data( pRExC_state, 2, "tu" );
1318 STRLEN trie_charcount=0;
1320 SV *re_trie_maxbuff;
1321 GET_RE_DEBUG_FLAGS_DECL;
1323 PERL_UNUSED_ARG(depth);
1326 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
1328 trie->startstate = 1;
1329 trie->wordcount = word_count;
1330 RExC_rxi->data->data[ data_slot ] = (void*)trie;
1331 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
1332 if (!(UTF && folder))
1333 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
1335 trie_words = newAV();
1338 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
1339 if (!SvIOK(re_trie_maxbuff)) {
1340 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
1343 PerlIO_printf( Perl_debug_log,
1344 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
1345 (int)depth * 2 + 2, "",
1346 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
1347 REG_NODE_NUM(last), REG_NODE_NUM(tail),
1351 /* Find the node we are going to overwrite */
1352 if ( first == startbranch && OP( last ) != BRANCH ) {
1353 /* whole branch chain */
1356 /* branch sub-chain */
1357 convert = NEXTOPER( first );
1360 /* -- First loop and Setup --
1362 We first traverse the branches and scan each word to determine if it
1363 contains widechars, and how many unique chars there are, this is
1364 important as we have to build a table with at least as many columns as we
1367 We use an array of integers to represent the character codes 0..255
1368 (trie->charmap) and we use a an HV* to store Unicode characters. We use the
1369 native representation of the character value as the key and IV's for the
1372 *TODO* If we keep track of how many times each character is used we can
1373 remap the columns so that the table compression later on is more
1374 efficient in terms of memory by ensuring most common value is in the
1375 middle and the least common are on the outside. IMO this would be better
1376 than a most to least common mapping as theres a decent chance the most
1377 common letter will share a node with the least common, meaning the node
1378 will not be compressable. With a middle is most common approach the worst
1379 case is when we have the least common nodes twice.
1383 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1384 regnode * const noper = NEXTOPER( cur );
1385 const U8 *uc = (U8*)STRING( noper );
1386 const U8 * const e = uc + STR_LEN( noper );
1388 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1389 const U8 *scan = (U8*)NULL;
1390 U32 wordlen = 0; /* required init */
1392 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the bitmap?*/
1394 if (OP(noper) == NOTHING) {
1398 if ( set_bit ) /* bitmap only alloced when !(UTF&&Folding) */
1399 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
1400 regardless of encoding */
1402 for ( ; uc < e ; uc += len ) {
1403 TRIE_CHARCOUNT(trie)++;
1407 if ( !trie->charmap[ uvc ] ) {
1408 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1410 trie->charmap[ folder[ uvc ] ] = trie->charmap[ uvc ];
1414 /* store the codepoint in the bitmap, and if its ascii
1415 also store its folded equivelent. */
1416 TRIE_BITMAP_SET(trie,uvc);
1418 /* store the folded codepoint */
1419 if ( folder ) TRIE_BITMAP_SET(trie,folder[ uvc ]);
1422 /* store first byte of utf8 representation of
1423 codepoints in the 127 < uvc < 256 range */
1424 if (127 < uvc && uvc < 192) {
1425 TRIE_BITMAP_SET(trie,194);
1426 } else if (191 < uvc ) {
1427 TRIE_BITMAP_SET(trie,195);
1428 /* && uvc < 256 -- we know uvc is < 256 already */
1431 set_bit = 0; /* We've done our bit :-) */
1436 widecharmap = newHV();
1438 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
1441 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
1443 if ( !SvTRUE( *svpp ) ) {
1444 sv_setiv( *svpp, ++trie->uniquecharcount );
1449 if( cur == first ) {
1452 } else if (chars < trie->minlen) {
1454 } else if (chars > trie->maxlen) {
1458 } /* end first pass */
1459 DEBUG_TRIE_COMPILE_r(
1460 PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1461 (int)depth * 2 + 2,"",
1462 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
1463 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1464 (int)trie->minlen, (int)trie->maxlen )
1466 trie->wordlen = (U32 *) PerlMemShared_calloc( word_count, sizeof(U32) );
1469 We now know what we are dealing with in terms of unique chars and
1470 string sizes so we can calculate how much memory a naive
1471 representation using a flat table will take. If it's over a reasonable
1472 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
1473 conservative but potentially much slower representation using an array
1476 At the end we convert both representations into the same compressed
1477 form that will be used in regexec.c for matching with. The latter
1478 is a form that cannot be used to construct with but has memory
1479 properties similar to the list form and access properties similar
1480 to the table form making it both suitable for fast searches and
1481 small enough that its feasable to store for the duration of a program.
1483 See the comment in the code where the compressed table is produced
1484 inplace from the flat tabe representation for an explanation of how
1485 the compression works.
1490 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
1492 Second Pass -- Array Of Lists Representation
1494 Each state will be represented by a list of charid:state records
1495 (reg_trie_trans_le) the first such element holds the CUR and LEN
1496 points of the allocated array. (See defines above).
1498 We build the initial structure using the lists, and then convert
1499 it into the compressed table form which allows faster lookups
1500 (but cant be modified once converted).
1503 STRLEN transcount = 1;
1505 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1506 "%*sCompiling trie using list compiler\n",
1507 (int)depth * 2 + 2, ""));
1509 trie->states = (reg_trie_state *)
1510 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1511 sizeof(reg_trie_state) );
1515 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1517 regnode * const noper = NEXTOPER( cur );
1518 U8 *uc = (U8*)STRING( noper );
1519 const U8 * const e = uc + STR_LEN( noper );
1520 U32 state = 1; /* required init */
1521 U16 charid = 0; /* sanity init */
1522 U8 *scan = (U8*)NULL; /* sanity init */
1523 STRLEN foldlen = 0; /* required init */
1524 U32 wordlen = 0; /* required init */
1525 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1527 if (OP(noper) != NOTHING) {
1528 for ( ; uc < e ; uc += len ) {
1533 charid = trie->charmap[ uvc ];
1535 SV** const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
1539 charid=(U16)SvIV( *svpp );
1542 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1549 if ( !trie->states[ state ].trans.list ) {
1550 TRIE_LIST_NEW( state );
1552 for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1553 if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1554 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1559 newstate = next_alloc++;
1560 TRIE_LIST_PUSH( state, charid, newstate );
1565 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1569 TRIE_HANDLE_WORD(state);
1571 } /* end second pass */
1573 /* next alloc is the NEXT state to be allocated */
1574 trie->statecount = next_alloc;
1575 trie->states = (reg_trie_state *)
1576 PerlMemShared_realloc( trie->states,
1578 * sizeof(reg_trie_state) );
1580 /* and now dump it out before we compress it */
1581 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
1582 revcharmap, next_alloc,
1586 trie->trans = (reg_trie_trans *)
1587 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
1594 for( state=1 ; state < next_alloc ; state ++ ) {
1598 DEBUG_TRIE_COMPILE_MORE_r(
1599 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1603 if (trie->states[state].trans.list) {
1604 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1608 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1609 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1610 if ( forid < minid ) {
1612 } else if ( forid > maxid ) {
1616 if ( transcount < tp + maxid - minid + 1) {
1618 trie->trans = (reg_trie_trans *)
1619 PerlMemShared_realloc( trie->trans,
1621 * sizeof(reg_trie_trans) );
1622 Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1624 base = trie->uniquecharcount + tp - minid;
1625 if ( maxid == minid ) {
1627 for ( ; zp < tp ; zp++ ) {
1628 if ( ! trie->trans[ zp ].next ) {
1629 base = trie->uniquecharcount + zp - minid;
1630 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1631 trie->trans[ zp ].check = state;
1637 trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1638 trie->trans[ tp ].check = state;
1643 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1644 const U32 tid = base - trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
1645 trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1646 trie->trans[ tid ].check = state;
1648 tp += ( maxid - minid + 1 );
1650 Safefree(trie->states[ state ].trans.list);
1653 DEBUG_TRIE_COMPILE_MORE_r(
1654 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1657 trie->states[ state ].trans.base=base;
1659 trie->lasttrans = tp + 1;
1663 Second Pass -- Flat Table Representation.
1665 we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1666 We know that we will need Charcount+1 trans at most to store the data
1667 (one row per char at worst case) So we preallocate both structures
1668 assuming worst case.
1670 We then construct the trie using only the .next slots of the entry
1673 We use the .check field of the first entry of the node temporarily to
1674 make compression both faster and easier by keeping track of how many non
1675 zero fields are in the node.
1677 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1680 There are two terms at use here: state as a TRIE_NODEIDX() which is a
1681 number representing the first entry of the node, and state as a
1682 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1683 TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1684 are 2 entrys per node. eg:
1692 The table is internally in the right hand, idx form. However as we also
1693 have to deal with the states array which is indexed by nodenum we have to
1694 use TRIE_NODENUM() to convert.
1697 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1698 "%*sCompiling trie using table compiler\n",
1699 (int)depth * 2 + 2, ""));
1701 trie->trans = (reg_trie_trans *)
1702 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
1703 * trie->uniquecharcount + 1,
1704 sizeof(reg_trie_trans) );
1705 trie->states = (reg_trie_state *)
1706 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1707 sizeof(reg_trie_state) );
1708 next_alloc = trie->uniquecharcount + 1;
1711 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1713 regnode * const noper = NEXTOPER( cur );
1714 const U8 *uc = (U8*)STRING( noper );
1715 const U8 * const e = uc + STR_LEN( noper );
1717 U32 state = 1; /* required init */
1719 U16 charid = 0; /* sanity init */
1720 U32 accept_state = 0; /* sanity init */
1721 U8 *scan = (U8*)NULL; /* sanity init */
1723 STRLEN foldlen = 0; /* required init */
1724 U32 wordlen = 0; /* required init */
1725 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1727 if ( OP(noper) != NOTHING ) {
1728 for ( ; uc < e ; uc += len ) {
1733 charid = trie->charmap[ uvc ];
1735 SV* const * const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
1736 charid = svpp ? (U16)SvIV(*svpp) : 0;
1740 if ( !trie->trans[ state + charid ].next ) {
1741 trie->trans[ state + charid ].next = next_alloc;
1742 trie->trans[ state ].check++;
1743 next_alloc += trie->uniquecharcount;
1745 state = trie->trans[ state + charid ].next;
1747 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1749 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1752 accept_state = TRIE_NODENUM( state );
1753 TRIE_HANDLE_WORD(accept_state);
1755 } /* end second pass */
1757 /* and now dump it out before we compress it */
1758 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
1760 next_alloc, depth+1));
1764 * Inplace compress the table.*
1766 For sparse data sets the table constructed by the trie algorithm will
1767 be mostly 0/FAIL transitions or to put it another way mostly empty.
1768 (Note that leaf nodes will not contain any transitions.)
1770 This algorithm compresses the tables by eliminating most such
1771 transitions, at the cost of a modest bit of extra work during lookup:
1773 - Each states[] entry contains a .base field which indicates the
1774 index in the state[] array wheres its transition data is stored.
1776 - If .base is 0 there are no valid transitions from that node.
1778 - If .base is nonzero then charid is added to it to find an entry in
1781 -If trans[states[state].base+charid].check!=state then the
1782 transition is taken to be a 0/Fail transition. Thus if there are fail
1783 transitions at the front of the node then the .base offset will point
1784 somewhere inside the previous nodes data (or maybe even into a node
1785 even earlier), but the .check field determines if the transition is
1789 The following process inplace converts the table to the compressed
1790 table: We first do not compress the root node 1,and mark its all its
1791 .check pointers as 1 and set its .base pointer as 1 as well. This
1792 allows to do a DFA construction from the compressed table later, and
1793 ensures that any .base pointers we calculate later are greater than
1796 - We set 'pos' to indicate the first entry of the second node.
1798 - We then iterate over the columns of the node, finding the first and
1799 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
1800 and set the .check pointers accordingly, and advance pos
1801 appropriately and repreat for the next node. Note that when we copy
1802 the next pointers we have to convert them from the original
1803 NODEIDX form to NODENUM form as the former is not valid post
1806 - If a node has no transitions used we mark its base as 0 and do not
1807 advance the pos pointer.
1809 - If a node only has one transition we use a second pointer into the
1810 structure to fill in allocated fail transitions from other states.
1811 This pointer is independent of the main pointer and scans forward
1812 looking for null transitions that are allocated to a state. When it
1813 finds one it writes the single transition into the "hole". If the
1814 pointer doesnt find one the single transition is appended as normal.
1816 - Once compressed we can Renew/realloc the structures to release the
1819 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
1820 specifically Fig 3.47 and the associated pseudocode.
1824 const U32 laststate = TRIE_NODENUM( next_alloc );
1827 trie->statecount = laststate;
1829 for ( state = 1 ; state < laststate ; state++ ) {
1831 const U32 stateidx = TRIE_NODEIDX( state );
1832 const U32 o_used = trie->trans[ stateidx ].check;
1833 U32 used = trie->trans[ stateidx ].check;
1834 trie->trans[ stateidx ].check = 0;
1836 for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
1837 if ( flag || trie->trans[ stateidx + charid ].next ) {
1838 if ( trie->trans[ stateidx + charid ].next ) {
1840 for ( ; zp < pos ; zp++ ) {
1841 if ( ! trie->trans[ zp ].next ) {
1845 trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
1846 trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1847 trie->trans[ zp ].check = state;
1848 if ( ++zp > pos ) pos = zp;
1855 trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
1857 trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1858 trie->trans[ pos ].check = state;
1863 trie->lasttrans = pos + 1;
1864 trie->states = (reg_trie_state *)
1865 PerlMemShared_realloc( trie->states, laststate
1866 * sizeof(reg_trie_state) );
1867 DEBUG_TRIE_COMPILE_MORE_r(
1868 PerlIO_printf( Perl_debug_log,
1869 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
1870 (int)depth * 2 + 2,"",
1871 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
1874 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
1877 } /* end table compress */
1879 DEBUG_TRIE_COMPILE_MORE_r(
1880 PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
1881 (int)depth * 2 + 2, "",
1882 (UV)trie->statecount,
1883 (UV)trie->lasttrans)
1885 /* resize the trans array to remove unused space */
1886 trie->trans = (reg_trie_trans *)
1887 PerlMemShared_realloc( trie->trans, trie->lasttrans
1888 * sizeof(reg_trie_trans) );
1890 /* and now dump out the compressed format */
1891 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
1893 { /* Modify the program and insert the new TRIE node*/
1894 U8 nodetype =(U8)(flags & 0xFF);
1898 regnode *optimize = NULL;
1899 #ifdef RE_TRACK_PATTERN_OFFSETS
1902 U32 mjd_nodelen = 0;
1903 #endif /* RE_TRACK_PATTERN_OFFSETS */
1904 #endif /* DEBUGGING */
1906 This means we convert either the first branch or the first Exact,
1907 depending on whether the thing following (in 'last') is a branch
1908 or not and whther first is the startbranch (ie is it a sub part of
1909 the alternation or is it the whole thing.)
1910 Assuming its a sub part we conver the EXACT otherwise we convert
1911 the whole branch sequence, including the first.
1913 /* Find the node we are going to overwrite */
1914 if ( first != startbranch || OP( last ) == BRANCH ) {
1915 /* branch sub-chain */
1916 NEXT_OFF( first ) = (U16)(last - first);
1917 #ifdef RE_TRACK_PATTERN_OFFSETS
1919 mjd_offset= Node_Offset((convert));
1920 mjd_nodelen= Node_Length((convert));
1923 /* whole branch chain */
1925 #ifdef RE_TRACK_PATTERN_OFFSETS
1928 const regnode *nop = NEXTOPER( convert );
1929 mjd_offset= Node_Offset((nop));
1930 mjd_nodelen= Node_Length((nop));
1934 PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
1935 (int)depth * 2 + 2, "",
1936 (UV)mjd_offset, (UV)mjd_nodelen)
1939 /* But first we check to see if there is a common prefix we can
1940 split out as an EXACT and put in front of the TRIE node. */
1941 trie->startstate= 1;
1942 if ( trie->bitmap && !widecharmap && !trie->jump ) {
1944 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
1948 const U32 base = trie->states[ state ].trans.base;
1950 if ( trie->states[state].wordnum )
1953 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1954 if ( ( base + ofs >= trie->uniquecharcount ) &&
1955 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
1956 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
1958 if ( ++count > 1 ) {
1959 SV **tmp = av_fetch( revcharmap, ofs, 0);
1960 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
1961 if ( state == 1 ) break;
1963 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
1965 PerlIO_printf(Perl_debug_log,
1966 "%*sNew Start State=%"UVuf" Class: [",
1967 (int)depth * 2 + 2, "",
1970 SV ** const tmp = av_fetch( revcharmap, idx, 0);
1971 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
1973 TRIE_BITMAP_SET(trie,*ch);
1975 TRIE_BITMAP_SET(trie, folder[ *ch ]);
1977 PerlIO_printf(Perl_debug_log, (char*)ch)
1981 TRIE_BITMAP_SET(trie,*ch);
1983 TRIE_BITMAP_SET(trie,folder[ *ch ]);
1984 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
1990 SV **tmp = av_fetch( revcharmap, idx, 0);
1992 char *ch = SvPV( *tmp, len );
1994 SV *sv=sv_newmortal();
1995 PerlIO_printf( Perl_debug_log,
1996 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
1997 (int)depth * 2 + 2, "",
1999 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
2000 PL_colors[0], PL_colors[1],
2001 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2002 PERL_PV_ESCAPE_FIRSTCHAR
2007 OP( convert ) = nodetype;
2008 str=STRING(convert);
2011 STR_LEN(convert) += len;
2017 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
2023 regnode *n = convert+NODE_SZ_STR(convert);
2024 NEXT_OFF(convert) = NODE_SZ_STR(convert);
2025 trie->startstate = state;
2026 trie->minlen -= (state - 1);
2027 trie->maxlen -= (state - 1);
2029 /* At least the UNICOS C compiler choked on this
2030 * being argument to DEBUG_r(), so let's just have
2033 #ifdef PERL_EXT_RE_BUILD
2039 regnode *fix = convert;
2040 U32 word = trie->wordcount;
2042 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
2043 while( ++fix < n ) {
2044 Set_Node_Offset_Length(fix, 0, 0);
2047 SV ** const tmp = av_fetch( trie_words, word, 0 );
2049 if ( STR_LEN(convert) <= SvCUR(*tmp) )
2050 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
2052 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
2060 NEXT_OFF(convert) = (U16)(tail - convert);
2061 DEBUG_r(optimize= n);
2067 if ( trie->maxlen ) {
2068 NEXT_OFF( convert ) = (U16)(tail - convert);
2069 ARG_SET( convert, data_slot );
2070 /* Store the offset to the first unabsorbed branch in
2071 jump[0], which is otherwise unused by the jump logic.
2072 We use this when dumping a trie and during optimisation. */
2074 trie->jump[0] = (U16)(nextbranch - convert);
2077 if ( !trie->states[trie->startstate].wordnum && trie->bitmap &&
2078 ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
2080 OP( convert ) = TRIEC;
2081 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
2082 PerlMemShared_free(trie->bitmap);
2085 OP( convert ) = TRIE;
2087 /* store the type in the flags */
2088 convert->flags = nodetype;
2092 + regarglen[ OP( convert ) ];
2094 /* XXX We really should free up the resource in trie now,
2095 as we won't use them - (which resources?) dmq */
2097 /* needed for dumping*/
2098 DEBUG_r(if (optimize) {
2099 regnode *opt = convert;
2101 while ( ++opt < optimize) {
2102 Set_Node_Offset_Length(opt,0,0);
2105 Try to clean up some of the debris left after the
2108 while( optimize < jumper ) {
2109 mjd_nodelen += Node_Length((optimize));
2110 OP( optimize ) = OPTIMIZED;
2111 Set_Node_Offset_Length(optimize,0,0);
2114 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
2116 } /* end node insert */
2117 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
2119 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
2120 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
2122 SvREFCNT_dec(revcharmap);
2126 : trie->startstate>1
2132 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source, regnode *stclass, U32 depth)
2134 /* The Trie is constructed and compressed now so we can build a fail array now if its needed
2136 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
2137 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
2140 We find the fail state for each state in the trie, this state is the longest proper
2141 suffix of the current states 'word' that is also a proper prefix of another word in our
2142 trie. State 1 represents the word '' and is the thus the default fail state. This allows
2143 the DFA not to have to restart after its tried and failed a word at a given point, it
2144 simply continues as though it had been matching the other word in the first place.
2146 'abcdgu'=~/abcdefg|cdgu/
2147 When we get to 'd' we are still matching the first word, we would encounter 'g' which would
2148 fail, which would bring use to the state representing 'd' in the second word where we would
2149 try 'g' and succeed, prodceding to match 'cdgu'.
2151 /* add a fail transition */
2152 const U32 trie_offset = ARG(source);
2153 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
2155 const U32 ucharcount = trie->uniquecharcount;
2156 const U32 numstates = trie->statecount;
2157 const U32 ubound = trie->lasttrans + ucharcount;
2161 U32 base = trie->states[ 1 ].trans.base;
2164 const U32 data_slot = add_data( pRExC_state, 1, "T" );
2165 GET_RE_DEBUG_FLAGS_DECL;
2167 PERL_UNUSED_ARG(depth);
2171 ARG_SET( stclass, data_slot );
2172 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
2173 RExC_rxi->data->data[ data_slot ] = (void*)aho;
2174 aho->trie=trie_offset;
2175 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
2176 Copy( trie->states, aho->states, numstates, reg_trie_state );
2177 Newxz( q, numstates, U32);
2178 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
2181 /* initialize fail[0..1] to be 1 so that we always have
2182 a valid final fail state */
2183 fail[ 0 ] = fail[ 1 ] = 1;
2185 for ( charid = 0; charid < ucharcount ; charid++ ) {
2186 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2188 q[ q_write ] = newstate;
2189 /* set to point at the root */
2190 fail[ q[ q_write++ ] ]=1;
2193 while ( q_read < q_write) {
2194 const U32 cur = q[ q_read++ % numstates ];
2195 base = trie->states[ cur ].trans.base;
2197 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2198 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2200 U32 fail_state = cur;
2203 fail_state = fail[ fail_state ];
2204 fail_base = aho->states[ fail_state ].trans.base;
2205 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2207 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2208 fail[ ch_state ] = fail_state;
2209 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2211 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
2213 q[ q_write++ % numstates] = ch_state;
2217 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2218 when we fail in state 1, this allows us to use the
2219 charclass scan to find a valid start char. This is based on the principle
2220 that theres a good chance the string being searched contains lots of stuff
2221 that cant be a start char.
2223 fail[ 0 ] = fail[ 1 ] = 0;
2224 DEBUG_TRIE_COMPILE_r({
2225 PerlIO_printf(Perl_debug_log,
2226 "%*sStclass Failtable (%"UVuf" states): 0",
2227 (int)(depth * 2), "", (UV)numstates
2229 for( q_read=1; q_read<numstates; q_read++ ) {
2230 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2232 PerlIO_printf(Perl_debug_log, "\n");
2235 /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2240 * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2241 * These need to be revisited when a newer toolchain becomes available.
2243 #if defined(__sparc64__) && defined(__GNUC__)
2244 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2245 # undef SPARC64_GCC_WORKAROUND
2246 # define SPARC64_GCC_WORKAROUND 1
2250 #define DEBUG_PEEP(str,scan,depth) \
2251 DEBUG_OPTIMISE_r({if (scan){ \
2252 SV * const mysv=sv_newmortal(); \
2253 regnode *Next = regnext(scan); \
2254 regprop(RExC_rx, mysv, scan); \
2255 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
2256 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2257 Next ? (REG_NODE_NUM(Next)) : 0 ); \
2264 #define JOIN_EXACT(scan,min,flags) \
2265 if (PL_regkind[OP(scan)] == EXACT) \
2266 join_exact(pRExC_state,(scan),(min),(flags),NULL,depth+1)
2269 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, I32 *min, U32 flags,regnode *val, U32 depth) {
2270 /* Merge several consecutive EXACTish nodes into one. */
2271 regnode *n = regnext(scan);
2273 regnode *next = scan + NODE_SZ_STR(scan);
2277 regnode *stop = scan;
2278 GET_RE_DEBUG_FLAGS_DECL;
2280 PERL_UNUSED_ARG(depth);
2282 #ifndef EXPERIMENTAL_INPLACESCAN
2283 PERL_UNUSED_ARG(flags);
2284 PERL_UNUSED_ARG(val);
2286 DEBUG_PEEP("join",scan,depth);
2288 /* Skip NOTHING, merge EXACT*. */
2290 ( PL_regkind[OP(n)] == NOTHING ||
2291 (stringok && (OP(n) == OP(scan))))
2293 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
2295 if (OP(n) == TAIL || n > next)
2297 if (PL_regkind[OP(n)] == NOTHING) {
2298 DEBUG_PEEP("skip:",n,depth);
2299 NEXT_OFF(scan) += NEXT_OFF(n);
2300 next = n + NODE_STEP_REGNODE;
2307 else if (stringok) {
2308 const unsigned int oldl = STR_LEN(scan);
2309 regnode * const nnext = regnext(n);
2311 DEBUG_PEEP("merg",n,depth);
2314 if (oldl + STR_LEN(n) > U8_MAX)
2316 NEXT_OFF(scan) += NEXT_OFF(n);
2317 STR_LEN(scan) += STR_LEN(n);
2318 next = n + NODE_SZ_STR(n);
2319 /* Now we can overwrite *n : */
2320 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2328 #ifdef EXPERIMENTAL_INPLACESCAN
2329 if (flags && !NEXT_OFF(n)) {
2330 DEBUG_PEEP("atch", val, depth);
2331 if (reg_off_by_arg[OP(n)]) {
2332 ARG_SET(n, val - n);
2335 NEXT_OFF(n) = val - n;
2342 if (UTF && ( OP(scan) == EXACTF ) && ( STR_LEN(scan) >= 6 ) ) {
2344 Two problematic code points in Unicode casefolding of EXACT nodes:
2346 U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2347 U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2353 U+03B9 U+0308 U+0301 0xCE 0xB9 0xCC 0x88 0xCC 0x81
2354 U+03C5 U+0308 U+0301 0xCF 0x85 0xCC 0x88 0xCC 0x81
2356 This means that in case-insensitive matching (or "loose matching",
2357 as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte
2358 length of the above casefolded versions) can match a target string
2359 of length two (the byte length of UTF-8 encoded U+0390 or U+03B0).
2360 This would rather mess up the minimum length computation.
2362 What we'll do is to look for the tail four bytes, and then peek
2363 at the preceding two bytes to see whether we need to decrease
2364 the minimum length by four (six minus two).
2366 Thanks to the design of UTF-8, there cannot be false matches:
2367 A sequence of valid UTF-8 bytes cannot be a subsequence of
2368 another valid sequence of UTF-8 bytes.
2371 char * const s0 = STRING(scan), *s, *t;
2372 char * const s1 = s0 + STR_LEN(scan) - 1;
2373 char * const s2 = s1 - 4;
2374 #ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2375 const char t0[] = "\xaf\x49\xaf\x42";
2377 const char t0[] = "\xcc\x88\xcc\x81";
2379 const char * const t1 = t0 + 3;
2382 s < s2 && (t = ninstr(s, s1, t0, t1));
2385 if (((U8)t[-1] == 0x68 && (U8)t[-2] == 0xB4) ||
2386 ((U8)t[-1] == 0x46 && (U8)t[-2] == 0xB5))
2388 if (((U8)t[-1] == 0xB9 && (U8)t[-2] == 0xCE) ||
2389 ((U8)t[-1] == 0x85 && (U8)t[-2] == 0xCF))
2397 n = scan + NODE_SZ_STR(scan);
2399 if (PL_regkind[OP(n)] != NOTHING || OP(n) == NOTHING) {
2406 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2410 /* REx optimizer. Converts nodes into quickier variants "in place".
2411 Finds fixed substrings. */
2413 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
2414 to the position after last scanned or to NULL. */
2416 #define INIT_AND_WITHP \
2417 assert(!and_withp); \
2418 Newx(and_withp,1,struct regnode_charclass_class); \
2419 SAVEFREEPV(and_withp)
2421 /* this is a chain of data about sub patterns we are processing that
2422 need to be handled seperately/specially in study_chunk. Its so
2423 we can simulate recursion without losing state. */
2425 typedef struct scan_frame {
2426 regnode *last; /* last node to process in this frame */
2427 regnode *next; /* next node to process when last is reached */
2428 struct scan_frame *prev; /*previous frame*/
2429 I32 stop; /* what stopparen do we use */
2433 #define SCAN_COMMIT(s, data, m) scan_commit(s, data, m, is_inf)
2435 #define CASE_SYNST_FNC(nAmE) \
2437 if (flags & SCF_DO_STCLASS_AND) { \
2438 for (value = 0; value < 256; value++) \
2439 if (!is_ ## nAmE ## _cp(value)) \
2440 ANYOF_BITMAP_CLEAR(data->start_class, value); \
2443 for (value = 0; value < 256; value++) \
2444 if (is_ ## nAmE ## _cp(value)) \
2445 ANYOF_BITMAP_SET(data->start_class, value); \
2449 if (flags & SCF_DO_STCLASS_AND) { \
2450 for (value = 0; value < 256; value++) \
2451 if (is_ ## nAmE ## _cp(value)) \
2452 ANYOF_BITMAP_CLEAR(data->start_class, value); \
2455 for (value = 0; value < 256; value++) \
2456 if (!is_ ## nAmE ## _cp(value)) \
2457 ANYOF_BITMAP_SET(data->start_class, value); \
2464 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
2465 I32 *minlenp, I32 *deltap,
2470 struct regnode_charclass_class *and_withp,
2471 U32 flags, U32 depth)
2472 /* scanp: Start here (read-write). */
2473 /* deltap: Write maxlen-minlen here. */
2474 /* last: Stop before this one. */
2475 /* data: string data about the pattern */
2476 /* stopparen: treat close N as END */
2477 /* recursed: which subroutines have we recursed into */
2478 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
2481 I32 min = 0, pars = 0, code;
2482 regnode *scan = *scanp, *next;
2484 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
2485 int is_inf_internal = 0; /* The studied chunk is infinite */
2486 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2487 scan_data_t data_fake;
2488 SV *re_trie_maxbuff = NULL;
2489 regnode *first_non_open = scan;
2490 I32 stopmin = I32_MAX;
2491 scan_frame *frame = NULL;
2493 GET_RE_DEBUG_FLAGS_DECL;
2496 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
2500 while (first_non_open && OP(first_non_open) == OPEN)
2501 first_non_open=regnext(first_non_open);
2506 while ( scan && OP(scan) != END && scan < last ){
2507 /* Peephole optimizer: */
2508 DEBUG_STUDYDATA("Peep:", data,depth);
2509 DEBUG_PEEP("Peep",scan,depth);
2510 JOIN_EXACT(scan,&min,0);
2512 /* Follow the next-chain of the current node and optimize
2513 away all the NOTHINGs from it. */
2514 if (OP(scan) != CURLYX) {
2515 const int max = (reg_off_by_arg[OP(scan)]
2517 /* I32 may be smaller than U16 on CRAYs! */
2518 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
2519 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
2523 /* Skip NOTHING and LONGJMP. */
2524 while ((n = regnext(n))
2525 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
2526 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
2527 && off + noff < max)
2529 if (reg_off_by_arg[OP(scan)])
2532 NEXT_OFF(scan) = off;
2537 /* The principal pseudo-switch. Cannot be a switch, since we
2538 look into several different things. */
2539 if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
2540 || OP(scan) == IFTHEN) {
2541 next = regnext(scan);
2543 /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
2545 if (OP(next) == code || code == IFTHEN) {
2546 /* NOTE - There is similar code to this block below for handling
2547 TRIE nodes on a re-study. If you change stuff here check there
2549 I32 max1 = 0, min1 = I32_MAX, num = 0;
2550 struct regnode_charclass_class accum;
2551 regnode * const startbranch=scan;
2553 if (flags & SCF_DO_SUBSTR)
2554 SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
2555 if (flags & SCF_DO_STCLASS)
2556 cl_init_zero(pRExC_state, &accum);
2558 while (OP(scan) == code) {
2559 I32 deltanext, minnext, f = 0, fake;
2560 struct regnode_charclass_class this_class;
2563 data_fake.flags = 0;
2565 data_fake.whilem_c = data->whilem_c;
2566 data_fake.last_closep = data->last_closep;
2569 data_fake.last_closep = &fake;
2571 data_fake.pos_delta = delta;
2572 next = regnext(scan);
2573 scan = NEXTOPER(scan);
2575 scan = NEXTOPER(scan);
2576 if (flags & SCF_DO_STCLASS) {
2577 cl_init(pRExC_state, &this_class);
2578 data_fake.start_class = &this_class;
2579 f = SCF_DO_STCLASS_AND;
2581 if (flags & SCF_WHILEM_VISITED_POS)
2582 f |= SCF_WHILEM_VISITED_POS;
2584 /* we suppose the run is continuous, last=next...*/
2585 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2587 stopparen, recursed, NULL, f,depth+1);
2590 if (max1 < minnext + deltanext)
2591 max1 = minnext + deltanext;
2592 if (deltanext == I32_MAX)
2593 is_inf = is_inf_internal = 1;
2595 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
2597 if (data_fake.flags & SCF_SEEN_ACCEPT) {
2598 if ( stopmin > minnext)
2599 stopmin = min + min1;
2600 flags &= ~SCF_DO_SUBSTR;
2602 data->flags |= SCF_SEEN_ACCEPT;
2605 if (data_fake.flags & SF_HAS_EVAL)
2606 data->flags |= SF_HAS_EVAL;
2607 data->whilem_c = data_fake.whilem_c;
2609 if (flags & SCF_DO_STCLASS)
2610 cl_or(pRExC_state, &accum, &this_class);
2612 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
2614 if (flags & SCF_DO_SUBSTR) {
2615 data->pos_min += min1;
2616 data->pos_delta += max1 - min1;
2617 if (max1 != min1 || is_inf)
2618 data->longest = &(data->longest_float);
2621 delta += max1 - min1;
2622 if (flags & SCF_DO_STCLASS_OR) {
2623 cl_or(pRExC_state, data->start_class, &accum);
2625 cl_and(data->start_class, and_withp);
2626 flags &= ~SCF_DO_STCLASS;
2629 else if (flags & SCF_DO_STCLASS_AND) {
2631 cl_and(data->start_class, &accum);
2632 flags &= ~SCF_DO_STCLASS;
2635 /* Switch to OR mode: cache the old value of
2636 * data->start_class */
2638 StructCopy(data->start_class, and_withp,
2639 struct regnode_charclass_class);
2640 flags &= ~SCF_DO_STCLASS_AND;
2641 StructCopy(&accum, data->start_class,
2642 struct regnode_charclass_class);
2643 flags |= SCF_DO_STCLASS_OR;
2644 data->start_class->flags |= ANYOF_EOS;
2648 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
2651 Assuming this was/is a branch we are dealing with: 'scan' now
2652 points at the item that follows the branch sequence, whatever
2653 it is. We now start at the beginning of the sequence and look
2660 which would be constructed from a pattern like /A|LIST|OF|WORDS/
2662 If we can find such a subseqence we need to turn the first
2663 element into a trie and then add the subsequent branch exact
2664 strings to the trie.
2668 1. patterns where the whole set of branch can be converted.
2670 2. patterns where only a subset can be converted.
2672 In case 1 we can replace the whole set with a single regop
2673 for the trie. In case 2 we need to keep the start and end
2676 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
2677 becomes BRANCH TRIE; BRANCH X;
2679 There is an additional case, that being where there is a
2680 common prefix, which gets split out into an EXACT like node
2681 preceding the TRIE node.
2683 If x(1..n)==tail then we can do a simple trie, if not we make
2684 a "jump" trie, such that when we match the appropriate word
2685 we "jump" to the appopriate tail node. Essentailly we turn
2686 a nested if into a case structure of sorts.
2691 if (!re_trie_maxbuff) {
2692 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2693 if (!SvIOK(re_trie_maxbuff))
2694 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2696 if ( SvIV(re_trie_maxbuff)>=0 ) {
2698 regnode *first = (regnode *)NULL;
2699 regnode *last = (regnode *)NULL;
2700 regnode *tail = scan;
2705 SV * const mysv = sv_newmortal(); /* for dumping */
2707 /* var tail is used because there may be a TAIL
2708 regop in the way. Ie, the exacts will point to the
2709 thing following the TAIL, but the last branch will
2710 point at the TAIL. So we advance tail. If we
2711 have nested (?:) we may have to move through several
2715 while ( OP( tail ) == TAIL ) {
2716 /* this is the TAIL generated by (?:) */
2717 tail = regnext( tail );
2722 regprop(RExC_rx, mysv, tail );
2723 PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
2724 (int)depth * 2 + 2, "",
2725 "Looking for TRIE'able sequences. Tail node is: ",
2726 SvPV_nolen_const( mysv )
2732 step through the branches, cur represents each
2733 branch, noper is the first thing to be matched
2734 as part of that branch and noper_next is the
2735 regnext() of that node. if noper is an EXACT
2736 and noper_next is the same as scan (our current
2737 position in the regex) then the EXACT branch is
2738 a possible optimization target. Once we have
2739 two or more consequetive such branches we can
2740 create a trie of the EXACT's contents and stich
2741 it in place. If the sequence represents all of
2742 the branches we eliminate the whole thing and
2743 replace it with a single TRIE. If it is a
2744 subsequence then we need to stitch it in. This
2745 means the first branch has to remain, and needs
2746 to be repointed at the item on the branch chain
2747 following the last branch optimized. This could
2748 be either a BRANCH, in which case the
2749 subsequence is internal, or it could be the
2750 item following the branch sequence in which
2751 case the subsequence is at the end.
2755 /* dont use tail as the end marker for this traverse */
2756 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
2757 regnode * const noper = NEXTOPER( cur );
2758 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
2759 regnode * const noper_next = regnext( noper );
2763 regprop(RExC_rx, mysv, cur);
2764 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
2765 (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
2767 regprop(RExC_rx, mysv, noper);
2768 PerlIO_printf( Perl_debug_log, " -> %s",
2769 SvPV_nolen_const(mysv));
2772 regprop(RExC_rx, mysv, noper_next );
2773 PerlIO_printf( Perl_debug_log,"\t=> %s\t",
2774 SvPV_nolen_const(mysv));
2776 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
2777 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
2779 if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
2780 : PL_regkind[ OP( noper ) ] == EXACT )
2781 || OP(noper) == NOTHING )
2783 && noper_next == tail
2788 if ( !first || optype == NOTHING ) {
2789 if (!first) first = cur;
2790 optype = OP( noper );
2796 Currently we assume that the trie can handle unicode and ascii
2797 matches fold cased matches. If this proves true then the following
2798 define will prevent tries in this situation.
2800 #define TRIE_TYPE_IS_SAFE (UTF || optype==EXACT)
2802 #define TRIE_TYPE_IS_SAFE 1
2803 if ( last && TRIE_TYPE_IS_SAFE ) {
2804 make_trie( pRExC_state,
2805 startbranch, first, cur, tail, count,
2808 if ( PL_regkind[ OP( noper ) ] == EXACT
2810 && noper_next == tail
2815 optype = OP( noper );
2825 regprop(RExC_rx, mysv, cur);
2826 PerlIO_printf( Perl_debug_log,
2827 "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
2828 "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
2832 if ( last && TRIE_TYPE_IS_SAFE ) {
2833 made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
2834 #ifdef TRIE_STUDY_OPT
2835 if ( ((made == MADE_EXACT_TRIE &&
2836 startbranch == first)
2837 || ( first_non_open == first )) &&
2839 flags |= SCF_TRIE_RESTUDY;
2840 if ( startbranch == first
2843 RExC_seen &=~REG_TOP_LEVEL_BRANCHES;
2853 else if ( code == BRANCHJ ) { /* single branch is optimized. */
2854 scan = NEXTOPER(NEXTOPER(scan));
2855 } else /* single branch is optimized. */
2856 scan = NEXTOPER(scan);
2858 } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
2859 scan_frame *newframe = NULL;
2864 if (OP(scan) != SUSPEND) {
2865 /* set the pointer */
2866 if (OP(scan) == GOSUB) {
2868 RExC_recurse[ARG2L(scan)] = scan;
2869 start = RExC_open_parens[paren-1];
2870 end = RExC_close_parens[paren-1];
2873 start = RExC_rxi->program + 1;
2877 Newxz(recursed, (((RExC_npar)>>3) +1), U8);
2878 SAVEFREEPV(recursed);
2880 if (!PAREN_TEST(recursed,paren+1)) {
2881 PAREN_SET(recursed,paren+1);
2882 Newx(newframe,1,scan_frame);
2884 if (flags & SCF_DO_SUBSTR) {
2885 SCAN_COMMIT(pRExC_state,data,minlenp);
2886 data->longest = &(data->longest_float);
2888 is_inf = is_inf_internal = 1;
2889 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
2890 cl_anything(pRExC_state, data->start_class);
2891 flags &= ~SCF_DO_STCLASS;
2894 Newx(newframe,1,scan_frame);
2897 end = regnext(scan);
2902 SAVEFREEPV(newframe);
2903 newframe->next = regnext(scan);
2904 newframe->last = last;
2905 newframe->stop = stopparen;
2906 newframe->prev = frame;
2916 else if (OP(scan) == EXACT) {
2917 I32 l = STR_LEN(scan);
2920 const U8 * const s = (U8*)STRING(scan);
2921 l = utf8_length(s, s + l);
2922 uc = utf8_to_uvchr(s, NULL);
2924 uc = *((U8*)STRING(scan));
2927 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
2928 /* The code below prefers earlier match for fixed
2929 offset, later match for variable offset. */
2930 if (data->last_end == -1) { /* Update the start info. */
2931 data->last_start_min = data->pos_min;
2932 data->last_start_max = is_inf
2933 ? I32_MAX : data->pos_min + data->pos_delta;
2935 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
2937 SvUTF8_on(data->last_found);
2939 SV * const sv = data->last_found;
2940 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
2941 mg_find(sv, PERL_MAGIC_utf8) : NULL;
2942 if (mg && mg->mg_len >= 0)
2943 mg->mg_len += utf8_length((U8*)STRING(scan),
2944 (U8*)STRING(scan)+STR_LEN(scan));
2946 data->last_end = data->pos_min + l;
2947 data->pos_min += l; /* As in the first entry. */
2948 data->flags &= ~SF_BEFORE_EOL;
2950 if (flags & SCF_DO_STCLASS_AND) {
2951 /* Check whether it is compatible with what we know already! */
2955 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2956 && !ANYOF_BITMAP_TEST(data->start_class, uc)
2957 && (!(data->start_class->flags & ANYOF_FOLD)
2958 || !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2961 ANYOF_CLASS_ZERO(data->start_class);
2962 ANYOF_BITMAP_ZERO(data->start_class);
2964 ANYOF_BITMAP_SET(data->start_class, uc);
2965 data->start_class->flags &= ~ANYOF_EOS;
2967 data->start_class->flags &= ~ANYOF_UNICODE_ALL;
2969 else if (flags & SCF_DO_STCLASS_OR) {
2970 /* false positive possible if the class is case-folded */
2972 ANYOF_BITMAP_SET(data->start_class, uc);
2974 data->start_class->flags |= ANYOF_UNICODE_ALL;
2975 data->start_class->flags &= ~ANYOF_EOS;
2976 cl_and(data->start_class, and_withp);
2978 flags &= ~SCF_DO_STCLASS;
2980 else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
2981 I32 l = STR_LEN(scan);
2982 UV uc = *((U8*)STRING(scan));
2984 /* Search for fixed substrings supports EXACT only. */
2985 if (flags & SCF_DO_SUBSTR) {
2987 SCAN_COMMIT(pRExC_state, data, minlenp);
2990 const U8 * const s = (U8 *)STRING(scan);
2991 l = utf8_length(s, s + l);
2992 uc = utf8_to_uvchr(s, NULL);
2995 if (flags & SCF_DO_SUBSTR)
2997 if (flags & SCF_DO_STCLASS_AND) {
2998 /* Check whether it is compatible with what we know already! */
3002 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
3003 && !ANYOF_BITMAP_TEST(data->start_class, uc)
3004 && !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
3006 ANYOF_CLASS_ZERO(data->start_class);
3007 ANYOF_BITMAP_ZERO(data->start_class);
3009 ANYOF_BITMAP_SET(data->start_class, uc);
3010 data->start_class->flags &= ~ANYOF_EOS;
3011 data->start_class->flags |= ANYOF_FOLD;
3012 if (OP(scan) == EXACTFL)
3013 data->start_class->flags |= ANYOF_LOCALE;
3016 else if (flags & SCF_DO_STCLASS_OR) {
3017 if (data->start_class->flags & ANYOF_FOLD) {
3018 /* false positive possible if the class is case-folded.
3019 Assume that the locale settings are the same... */
3021 ANYOF_BITMAP_SET(data->start_class, uc);
3022 data->start_class->flags &= ~ANYOF_EOS;
3024 cl_and(data->start_class, and_withp);
3026 flags &= ~SCF_DO_STCLASS;
3028 else if (strchr((const char*)PL_varies,OP(scan))) {
3029 I32 mincount, maxcount, minnext, deltanext, fl = 0;
3030 I32 f = flags, pos_before = 0;
3031 regnode * const oscan = scan;
3032 struct regnode_charclass_class this_class;
3033 struct regnode_charclass_class *oclass = NULL;
3034 I32 next_is_eval = 0;
3036 switch (PL_regkind[OP(scan)]) {
3037 case WHILEM: /* End of (?:...)* . */
3038 scan = NEXTOPER(scan);
3041 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
3042 next = NEXTOPER(scan);
3043 if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
3045 maxcount = REG_INFTY;
3046 next = regnext(scan);
3047 scan = NEXTOPER(scan);
3051 if (flags & SCF_DO_SUBSTR)
3056 if (flags & SCF_DO_STCLASS) {
3058 maxcount = REG_INFTY;
3059 next = regnext(scan);
3060 scan = NEXTOPER(scan);
3063 is_inf = is_inf_internal = 1;
3064 scan = regnext(scan);
3065 if (flags & SCF_DO_SUBSTR) {
3066 SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
3067 data->longest = &(data->longest_float);
3069 goto optimize_curly_tail;
3071 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
3072 && (scan->flags == stopparen))
3077 mincount = ARG1(scan);
3078 maxcount = ARG2(scan);
3080 next = regnext(scan);
3081 if (OP(scan) == CURLYX) {
3082 I32 lp = (data ? *(data->last_closep) : 0);
3083 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
3085 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
3086 next_is_eval = (OP(scan) == EVAL);
3088 if (flags & SCF_DO_SUBSTR) {
3089 if (mincount == 0) SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
3090 pos_before = data->pos_min;
3094 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
3096 data->flags |= SF_IS_INF;
3098 if (flags & SCF_DO_STCLASS) {
3099 cl_init(pRExC_state, &this_class);
3100 oclass = data->start_class;
3101 data->start_class = &this_class;
3102 f |= SCF_DO_STCLASS_AND;
3103 f &= ~SCF_DO_STCLASS_OR;
3105 /* These are the cases when once a subexpression
3106 fails at a particular position, it cannot succeed
3107 even after backtracking at the enclosing scope.
3109 XXXX what if minimal match and we are at the
3110 initial run of {n,m}? */
3111 if ((mincount != maxcount - 1) && (maxcount != REG_INFTY))
3112 f &= ~SCF_WHILEM_VISITED_POS;
3114 /* This will finish on WHILEM, setting scan, or on NULL: */
3115 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
3116 last, data, stopparen, recursed, NULL,
3118 ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
3120 if (flags & SCF_DO_STCLASS)
3121 data->start_class = oclass;
3122 if (mincount == 0 || minnext == 0) {
3123 if (flags & SCF_DO_STCLASS_OR) {
3124 cl_or(pRExC_state, data->start_class, &this_class);
3126 else if (flags & SCF_DO_STCLASS_AND) {
3127 /* Switch to OR mode: cache the old value of
3128 * data->start_class */
3130 StructCopy(data->start_class, and_withp,
3131 struct regnode_charclass_class);
3132 flags &= ~SCF_DO_STCLASS_AND;
3133 StructCopy(&this_class, data->start_class,
3134 struct regnode_charclass_class);
3135 flags |= SCF_DO_STCLASS_OR;
3136 data->start_class->flags |= ANYOF_EOS;
3138 } else { /* Non-zero len */
3139 if (flags & SCF_DO_STCLASS_OR) {
3140 cl_or(pRExC_state, data->start_class, &this_class);
3141 cl_and(data->start_class, and_withp);
3143 else if (flags & SCF_DO_STCLASS_AND)
3144 cl_and(data->start_class, &this_class);
3145 flags &= ~SCF_DO_STCLASS;
3147 if (!scan) /* It was not CURLYX, but CURLY. */
3149 if ( /* ? quantifier ok, except for (?{ ... }) */
3150 (next_is_eval || !(mincount == 0 && maxcount == 1))
3151 && (minnext == 0) && (deltanext == 0)
3152 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
3153 && maxcount <= REG_INFTY/3 /* Complement check for big count */
3154 && ckWARN(WARN_REGEXP))
3157 "Quantifier unexpected on zero-length expression");
3160 min += minnext * mincount;
3161 is_inf_internal |= ((maxcount == REG_INFTY
3162 && (minnext + deltanext) > 0)
3163 || deltanext == I32_MAX);
3164 is_inf |= is_inf_internal;
3165 delta += (minnext + deltanext) * maxcount - minnext * mincount;
3167 /* Try powerful optimization CURLYX => CURLYN. */
3168 if ( OP(oscan) == CURLYX && data
3169 && data->flags & SF_IN_PAR
3170 && !(data->flags & SF_HAS_EVAL)
3171 && !deltanext && minnext == 1 ) {
3172 /* Try to optimize to CURLYN. */
3173 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
3174 regnode * const nxt1 = nxt;
3181 if (!strchr((const char*)PL_simple,OP(nxt))
3182 && !(PL_regkind[OP(nxt)] == EXACT
3183 && STR_LEN(nxt) == 1))
3189 if (OP(nxt) != CLOSE)
3191 if (RExC_open_parens) {
3192 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3193 RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
3195 /* Now we know that nxt2 is the only contents: */
3196 oscan->flags = (U8)ARG(nxt);
3198 OP(nxt1) = NOTHING; /* was OPEN. */
3201 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3202 NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
3203 NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
3204 OP(nxt) = OPTIMIZED; /* was CLOSE. */
3205 OP(nxt + 1) = OPTIMIZED; /* was count. */
3206 NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
3211 /* Try optimization CURLYX => CURLYM. */
3212 if ( OP(oscan) == CURLYX && data
3213 && !(data->flags & SF_HAS_PAR)
3214 && !(data->flags & SF_HAS_EVAL)
3215 && !deltanext /* atom is fixed width */
3216 && minnext != 0 /* CURLYM can't handle zero width */
3218 /* XXXX How to optimize if data == 0? */
3219 /* Optimize to a simpler form. */
3220 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
3224 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
3225 && (OP(nxt2) != WHILEM))
3227 OP(nxt2) = SUCCEED; /* Whas WHILEM */
3228 /* Need to optimize away parenths. */
3229 if (data->flags & SF_IN_PAR) {
3230 /* Set the parenth number. */
3231 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
3233 if (OP(nxt) != CLOSE)
3234 FAIL("Panic opt close");
3235 oscan->flags = (U8)ARG(nxt);
3236 if (RExC_open_parens) {
3237 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3238 RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
3240 OP(nxt1) = OPTIMIZED; /* was OPEN. */
3241 OP(nxt) = OPTIMIZED; /* was CLOSE. */
3244 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3245 OP(nxt + 1) = OPTIMIZED; /* was count. */
3246 NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
3247 NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
3250 while ( nxt1 && (OP(nxt1) != WHILEM)) {
3251 regnode *nnxt = regnext(nxt1);
3254 if (reg_off_by_arg[OP(nxt1)])
3255 ARG_SET(nxt1, nxt2 - nxt1);
3256 else if (nxt2 - nxt1 < U16_MAX)
3257 NEXT_OFF(nxt1) = nxt2 - nxt1;
3259 OP(nxt) = NOTHING; /* Cannot beautify */
3264 /* Optimize again: */
3265 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
3266 NULL, stopparen, recursed, NULL, 0,depth+1);
3271 else if ((OP(oscan) == CURLYX)
3272 && (flags & SCF_WHILEM_VISITED_POS)
3273 /* See the comment on a similar expression above.
3274 However, this time it not a subexpression
3275 we care about, but the expression itself. */
3276 && (maxcount == REG_INFTY)
3277 && data && ++data->whilem_c < 16) {
3278 /* This stays as CURLYX, we can put the count/of pair. */
3279 /* Find WHILEM (as in regexec.c) */
3280 regnode *nxt = oscan + NEXT_OFF(oscan);
3282 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
3284 PREVOPER(nxt)->flags = (U8)(data->whilem_c
3285 | (RExC_whilem_seen << 4)); /* On WHILEM */
3287 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
3289 if (flags & SCF_DO_SUBSTR) {
3290 SV *last_str = NULL;
3291 int counted = mincount != 0;
3293 if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
3294 #if defined(SPARC64_GCC_WORKAROUND)
3297 const char *s = NULL;
3300 if (pos_before >= data->last_start_min)
3303 b = data->last_start_min;
3306 s = SvPV_const(data->last_found, l);
3307 old = b - data->last_start_min;
3310 I32 b = pos_before >= data->last_start_min
3311 ? pos_before : data->last_start_min;
3313 const char * const s = SvPV_const(data->last_found, l);
3314 I32 old = b - data->last_start_min;
3318 old = utf8_hop((U8*)s, old) - (U8*)s;
3321 /* Get the added string: */
3322 last_str = newSVpvn_utf8(s + old, l, UTF);
3323 if (deltanext == 0 && pos_before == b) {
3324 /* What was added is a constant string */
3326 SvGROW(last_str, (mincount * l) + 1);
3327 repeatcpy(SvPVX(last_str) + l,
3328 SvPVX_const(last_str), l, mincount - 1);
3329 SvCUR_set(last_str, SvCUR(last_str) * mincount);
3330 /* Add additional parts. */
3331 SvCUR_set(data->last_found,
3332 SvCUR(data->last_found) - l);
3333 sv_catsv(data->last_found, last_str);
3335 SV * sv = data->last_found;
3337 SvUTF8(sv) && SvMAGICAL(sv) ?
3338 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3339 if (mg && mg->mg_len >= 0)
3340 mg->mg_len += CHR_SVLEN(last_str) - l;
3342 data->last_end += l * (mincount - 1);
3345 /* start offset must point into the last copy */
3346 data->last_start_min += minnext * (mincount - 1);
3347 data->last_start_max += is_inf ? I32_MAX
3348 : (maxcount - 1) * (minnext + data->pos_delta);
3351 /* It is counted once already... */
3352 data->pos_min += minnext * (mincount - counted);
3353 data->pos_delta += - counted * deltanext +
3354 (minnext + deltanext) * maxcount - minnext * mincount;
3355 if (mincount != maxcount) {
3356 /* Cannot extend fixed substrings found inside
3358 SCAN_COMMIT(pRExC_state,data,minlenp);
3359 if (mincount && last_str) {
3360 SV * const sv = data->last_found;
3361 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3362 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3366 sv_setsv(sv, last_str);
3367 data->last_end = data->pos_min;
3368 data->last_start_min =
3369 data->pos_min - CHR_SVLEN(last_str);
3370 data->last_start_max = is_inf
3372 : data->pos_min + data->pos_delta
3373 - CHR_SVLEN(last_str);
3375 data->longest = &(data->longest_float);
3377 SvREFCNT_dec(last_str);
3379 if (data && (fl & SF_HAS_EVAL))
3380 data->flags |= SF_HAS_EVAL;
3381 optimize_curly_tail:
3382 if (OP(oscan) != CURLYX) {
3383 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
3385 NEXT_OFF(oscan) += NEXT_OFF(next);
3388 default: /* REF and CLUMP only? */
3389 if (flags & SCF_DO_SUBSTR) {
3390 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3391 data->longest = &(data->longest_float);
3393 is_inf = is_inf_internal = 1;
3394 if (flags & SCF_DO_STCLASS_OR)
3395 cl_anything(pRExC_state, data->start_class);
3396 flags &= ~SCF_DO_STCLASS;
3400 else if (OP(scan) == LNBREAK) {
3401 if (flags & SCF_DO_STCLASS) {
3403 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3404 if (flags & SCF_DO_STCLASS_AND) {
3405 for (value = 0; value < 256; value++)
3406 if (!is_VERTWS_cp(value))
3407 ANYOF_BITMAP_CLEAR(data->start_class, value);
3410 for (value = 0; value < 256; value++)
3411 if (is_VERTWS_cp(value))
3412 ANYOF_BITMAP_SET(data->start_class, value);
3414 if (flags & SCF_DO_STCLASS_OR)
3415 cl_and(data->start_class, and_withp);
3416 flags &= ~SCF_DO_STCLASS;
3420 if (flags & SCF_DO_SUBSTR) {
3421 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3423 data->pos_delta += 1;
3424 data->longest = &(data->longest_float);
3428 else if (OP(scan) == FOLDCHAR) {
3429 int d = ARG(scan)==0xDF ? 1 : 2;
3430 flags &= ~SCF_DO_STCLASS;
3433 if (flags & SCF_DO_SUBSTR) {
3434 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3436 data->pos_delta += d;
3437 data->longest = &(data->longest_float);
3440 else if (strchr((const char*)PL_simple,OP(scan))) {
3443 if (flags & SCF_DO_SUBSTR) {
3444 SCAN_COMMIT(pRExC_state,data,minlenp);
3448 if (flags & SCF_DO_STCLASS) {
3449 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3451 /* Some of the logic below assumes that switching
3452 locale on will only add false positives. */
3453 switch (PL_regkind[OP(scan)]) {
3457 /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
3458 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3459 cl_anything(pRExC_state, data->start_class);
3462 if (OP(scan) == SANY)
3464 if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
3465 value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
3466 || (data->start_class->flags & ANYOF_CLASS));
3467 cl_anything(pRExC_state, data->start_class);
3469 if (flags & SCF_DO_STCLASS_AND || !value)
3470 ANYOF_BITMAP_CLEAR(data->start_class,'\n');
3473 if (flags & SCF_DO_STCLASS_AND)
3474 cl_and(data->start_class,
3475 (struct regnode_charclass_class*)scan);
3477 cl_or(pRExC_state, data->start_class,
3478 (struct regnode_charclass_class*)scan);
3481 if (flags & SCF_DO_STCLASS_AND) {
3482 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3483 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3484 for (value = 0; value < 256; value++)
3485 if (!isALNUM(value))
3486 ANYOF_BITMAP_CLEAR(data->start_class, value);
3490 if (data->start_class->flags & ANYOF_LOCALE)
3491 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3493 for (value = 0; value < 256; value++)
3495 ANYOF_BITMAP_SET(data->start_class, value);
3500 if (flags & SCF_DO_STCLASS_AND) {
3501 if (data->start_class->flags & ANYOF_LOCALE)
3502 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3505 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3506 data->start_class->flags |= ANYOF_LOCALE;
3510 if (flags & SCF_DO_STCLASS_AND) {
3511 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3512 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3513 for (value = 0; value < 256; value++)
3515 ANYOF_BITMAP_CLEAR(data->start_class, value);
3519 if (data->start_class->flags & ANYOF_LOCALE)
3520 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3522 for (value = 0; value < 256; value++)
3523 if (!isALNUM(value))
3524 ANYOF_BITMAP_SET(data->start_class, value);
3529 if (flags & SCF_DO_STCLASS_AND) {
3530 if (data->start_class->flags & ANYOF_LOCALE)
3531 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3534 data->start_class->flags |= ANYOF_LOCALE;
3535 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3539 if (flags & SCF_DO_STCLASS_AND) {
3540 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3541 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3542 for (value = 0; value < 256; value++)
3543 if (!isSPACE(value))
3544 ANYOF_BITMAP_CLEAR(data->start_class, value);
3548 if (data->start_class->flags & ANYOF_LOCALE)
3549 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3551 for (value = 0; value < 256; value++)
3553 ANYOF_BITMAP_SET(data->start_class, value);
3558 if (flags & SCF_DO_STCLASS_AND) {
3559 if (data->start_class->flags & ANYOF_LOCALE)
3560 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3563 data->start_class->flags |= ANYOF_LOCALE;
3564 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3568 if (flags & SCF_DO_STCLASS_AND) {
3569 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3570 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3571 for (value = 0; value < 256; value++)
3573 ANYOF_BITMAP_CLEAR(data->start_class, value);
3577 if (data->start_class->flags & ANYOF_LOCALE)
3578 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3580 for (value = 0; value < 256; value++)
3581 if (!isSPACE(value))
3582 ANYOF_BITMAP_SET(data->start_class, value);
3587 if (flags & SCF_DO_STCLASS_AND) {
3588 if (data->start_class->flags & ANYOF_LOCALE) {
3589 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3590 for (value = 0; value < 256; value++)
3591 if (!isSPACE(value))
3592 ANYOF_BITMAP_CLEAR(data->start_class, value);
3596 data->start_class->flags |= ANYOF_LOCALE;
3597 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3601 if (flags & SCF_DO_STCLASS_AND) {
3602 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
3603 for (value = 0; value < 256; value++)
3604 if (!isDIGIT(value))
3605 ANYOF_BITMAP_CLEAR(data->start_class, value);
3608 if (data->start_class->flags & ANYOF_LOCALE)
3609 ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
3611 for (value = 0; value < 256; value++)
3613 ANYOF_BITMAP_SET(data->start_class, value);
3618 if (flags & SCF_DO_STCLASS_AND) {
3619 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
3620 for (value = 0; value < 256; value++)
3622 ANYOF_BITMAP_CLEAR(data->start_class, value);
3625 if (data->start_class->flags & ANYOF_LOCALE)
3626 ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
3628 for (value = 0; value < 256; value++)
3629 if (!isDIGIT(value))
3630 ANYOF_BITMAP_SET(data->start_class, value);
3634 CASE_SYNST_FNC(VERTWS);
3635 CASE_SYNST_FNC(HORIZWS);
3638 if (flags & SCF_DO_STCLASS_OR)
3639 cl_and(data->start_class, and_withp);
3640 flags &= ~SCF_DO_STCLASS;
3643 else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
3644 data->flags |= (OP(scan) == MEOL
3648 else if ( PL_regkind[OP(scan)] == BRANCHJ
3649 /* Lookbehind, or need to calculate parens/evals/stclass: */
3650 && (scan->flags || data || (flags & SCF_DO_STCLASS))
3651 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
3652 if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3653 || OP(scan) == UNLESSM )
3655 /* Negative Lookahead/lookbehind
3656 In this case we can't do fixed string optimisation.
3659 I32 deltanext, minnext, fake = 0;
3661 struct regnode_charclass_class intrnl;
3664 data_fake.flags = 0;
3666 data_fake.whilem_c = data->whilem_c;
3667 data_fake.last_closep = data->last_closep;
3670 data_fake.last_closep = &fake;
3671 data_fake.pos_delta = delta;
3672 if ( flags & SCF_DO_STCLASS && !scan->flags
3673 && OP(scan) == IFMATCH ) { /* Lookahead */
3674 cl_init(pRExC_state, &intrnl);
3675 data_fake.start_class = &intrnl;
3676 f |= SCF_DO_STCLASS_AND;
3678 if (flags & SCF_WHILEM_VISITED_POS)
3679 f |= SCF_WHILEM_VISITED_POS;
3680 next = regnext(scan);
3681 nscan = NEXTOPER(NEXTOPER(scan));
3682 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
3683 last, &data_fake, stopparen, recursed, NULL, f, depth+1);
3686 FAIL("Variable length lookbehind not implemented");
3688 else if (minnext > (I32)U8_MAX) {
3689 FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3691 scan->flags = (U8)minnext;
3694 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3696 if (data_fake.flags & SF_HAS_EVAL)
3697 data->flags |= SF_HAS_EVAL;
3698 data->whilem_c = data_fake.whilem_c;
3700 if (f & SCF_DO_STCLASS_AND) {
3701 const int was = (data->start_class->flags & ANYOF_EOS);
3703 cl_and(data->start_class, &intrnl);
3705 data->start_class->flags |= ANYOF_EOS;
3708 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3710 /* Positive Lookahead/lookbehind
3711 In this case we can do fixed string optimisation,
3712 but we must be careful about it. Note in the case of
3713 lookbehind the positions will be offset by the minimum
3714 length of the pattern, something we won't know about
3715 until after the recurse.
3717 I32 deltanext, fake = 0;
3719 struct regnode_charclass_class intrnl;
3721 /* We use SAVEFREEPV so that when the full compile
3722 is finished perl will clean up the allocated
3723 minlens when its all done. This was we don't
3724 have to worry about freeing them when we know
3725 they wont be used, which would be a pain.
3728 Newx( minnextp, 1, I32 );
3729 SAVEFREEPV(minnextp);
3732 StructCopy(data, &data_fake, scan_data_t);
3733 if ((flags & SCF_DO_SUBSTR) && data->last_found) {
3736 SCAN_COMMIT(pRExC_state, &data_fake,minlenp);
3737 data_fake.last_found=newSVsv(data->last_found);
3741 data_fake.last_closep = &fake;
3742 data_fake.flags = 0;
3743 data_fake.pos_delta = delta;
3745 data_fake.flags |= SF_IS_INF;
3746 if ( flags & SCF_DO_STCLASS && !scan->flags
3747 && OP(scan) == IFMATCH ) { /* Lookahead */
3748 cl_init(pRExC_state, &intrnl);
3749 data_fake.start_class = &intrnl;
3750 f |= SCF_DO_STCLASS_AND;
3752 if (flags & SCF_WHILEM_VISITED_POS)
3753 f |= SCF_WHILEM_VISITED_POS;
3754 next = regnext(scan);
3755 nscan = NEXTOPER(NEXTOPER(scan));
3757 *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext,
3758 last, &data_fake, stopparen, recursed, NULL, f,depth+1);
3761 FAIL("Variable length lookbehind not implemented");
3763 else if (*minnextp > (I32)U8_MAX) {
3764 FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3766 scan->flags = (U8)*minnextp;
3771 if (f & SCF_DO_STCLASS_AND) {
3772 const int was = (data->start_class->flags & ANYOF_EOS);
3774 cl_and(data->start_class, &intrnl);
3776 data->start_class->flags |= ANYOF_EOS;
3779 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3781 if (data_fake.flags & SF_HAS_EVAL)
3782 data->flags |= SF_HAS_EVAL;
3783 data->whilem_c = data_fake.whilem_c;
3784 if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
3785 if (RExC_rx->minlen<*minnextp)
3786 RExC_rx->minlen=*minnextp;
3787 SCAN_COMMIT(pRExC_state, &data_fake, minnextp);
3788 SvREFCNT_dec(data_fake.last_found);
3790 if ( data_fake.minlen_fixed != minlenp )
3792 data->offset_fixed= data_fake.offset_fixed;
3793 data->minlen_fixed= data_fake.minlen_fixed;
3794 data->lookbehind_fixed+= scan->flags;
3796 if ( data_fake.minlen_float != minlenp )
3798 data->minlen_float= data_fake.minlen_float;
3799 data->offset_float_min=data_fake.offset_float_min;
3800 data->offset_float_max=data_fake.offset_float_max;
3801 data->lookbehind_float+= scan->flags;
3810 else if (OP(scan) == OPEN) {
3811 if (stopparen != (I32)ARG(scan))
3814 else if (OP(scan) == CLOSE) {
3815 if (stopparen == (I32)ARG(scan)) {
3818 if ((I32)ARG(scan) == is_par) {
3819 next = regnext(scan);
3821 if ( next && (OP(next) != WHILEM) && next < last)
3822 is_par = 0; /* Disable optimization */
3825 *(data->last_closep) = ARG(scan);
3827 else if (OP(scan) == EVAL) {
3829 data->flags |= SF_HAS_EVAL;
3831 else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
3832 if (flags & SCF_DO_SUBSTR) {
3833 SCAN_COMMIT(pRExC_state,data,minlenp);
3834 flags &= ~SCF_DO_SUBSTR;
3836 if (data && OP(scan)==ACCEPT) {
3837 data->flags |= SCF_SEEN_ACCEPT;
3842 else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
3844 if (flags & SCF_DO_SUBSTR) {
3845 SCAN_COMMIT(pRExC_state,data,minlenp);
3846 data->longest = &(data->longest_float);
3848 is_inf = is_inf_internal = 1;
3849 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3850 cl_anything(pRExC_state, data->start_class);
3851 flags &= ~SCF_DO_STCLASS;
3853 else if (OP(scan) == GPOS) {
3854 if (!(RExC_rx->extflags & RXf_GPOS_FLOAT) &&
3855 !(delta || is_inf || (data && data->pos_delta)))
3857 if (!(RExC_rx->extflags & RXf_ANCH) && (flags & SCF_DO_SUBSTR))
3858 RExC_rx->extflags |= RXf_ANCH_GPOS;
3859 if (RExC_rx->gofs < (U32)min)
3860 RExC_rx->gofs = min;
3862 RExC_rx->extflags |= RXf_GPOS_FLOAT;
3866 #ifdef TRIE_STUDY_OPT
3867 #ifdef FULL_TRIE_STUDY
3868 else if (PL_regkind[OP(scan)] == TRIE) {
3869 /* NOTE - There is similar code to this block above for handling
3870 BRANCH nodes on the initial study. If you change stuff here
3872 regnode *trie_node= scan;
3873 regnode *tail= regnext(scan);
3874 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
3875 I32 max1 = 0, min1 = I32_MAX;
3876 struct regnode_charclass_class accum;
3878 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
3879 SCAN_COMMIT(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
3880 if (flags & SCF_DO_STCLASS)
3881 cl_init_zero(pRExC_state, &accum);
3887 const regnode *nextbranch= NULL;
3890 for ( word=1 ; word <= trie->wordcount ; word++)
3892 I32 deltanext=0, minnext=0, f = 0, fake;
3893 struct regnode_charclass_class this_class;
3895 data_fake.flags = 0;
3897 data_fake.whilem_c = data->whilem_c;
3898 data_fake.last_closep = data->last_closep;
3901 data_fake.last_closep = &fake;
3902 data_fake.pos_delta = delta;
3903 if (flags & SCF_DO_STCLASS) {
3904 cl_init(pRExC_state, &this_class);
3905 data_fake.start_class = &this_class;
3906 f = SCF_DO_STCLASS_AND;
3908 if (flags & SCF_WHILEM_VISITED_POS)
3909 f |= SCF_WHILEM_VISITED_POS;
3911 if (trie->jump[word]) {
3913 nextbranch = trie_node + trie->jump[0];
3914 scan= trie_node + trie->jump[word];
3915 /* We go from the jump point to the branch that follows
3916 it. Note this means we need the vestigal unused branches
3917 even though they arent otherwise used.
3919 minnext = study_chunk(pRExC_state, &scan, minlenp,
3920 &deltanext, (regnode *)nextbranch, &data_fake,
3921 stopparen, recursed, NULL, f,depth+1);
3923 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
3924 nextbranch= regnext((regnode*)nextbranch);
3926 if (min1 > (I32)(minnext + trie->minlen))
3927 min1 = minnext + trie->minlen;
3928 if (max1 < (I32)(minnext + deltanext + trie->maxlen))
3929 max1 = minnext + deltanext + trie->maxlen;
3930 if (deltanext == I32_MAX)
3931 is_inf = is_inf_internal = 1;
3933 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3935 if (data_fake.flags & SCF_SEEN_ACCEPT) {
3936 if ( stopmin > min + min1)
3937 stopmin = min + min1;
3938 flags &= ~SCF_DO_SUBSTR;
3940 data->flags |= SCF_SEEN_ACCEPT;
3943 if (data_fake.flags & SF_HAS_EVAL)
3944 data->flags |= SF_HAS_EVAL;
3945 data->whilem_c = data_fake.whilem_c;
3947 if (flags & SCF_DO_STCLASS)
3948 cl_or(pRExC_state, &accum, &this_class);
3951 if (flags & SCF_DO_SUBSTR) {
3952 data->pos_min += min1;
3953 data->pos_delta += max1 - min1;
3954 if (max1 != min1 || is_inf)
3955 data->longest = &(data->longest_float);
3958 delta += max1 - min1;
3959 if (flags & SCF_DO_STCLASS_OR) {
3960 cl_or(pRExC_state, data->start_class, &accum);
3962 cl_and(data->start_class, and_withp);
3963 flags &= ~SCF_DO_STCLASS;
3966 else if (flags & SCF_DO_STCLASS_AND) {
3968 cl_and(data->start_class, &accum);
3969 flags &= ~SCF_DO_STCLASS;
3972 /* Switch to OR mode: cache the old value of
3973 * data->start_class */
3975 StructCopy(data->start_class, and_withp,
3976 struct regnode_charclass_class);
3977 flags &= ~SCF_DO_STCLASS_AND;
3978 StructCopy(&accum, data->start_class,
3979 struct regnode_charclass_class);
3980 flags |= SCF_DO_STCLASS_OR;
3981 data->start_class->flags |= ANYOF_EOS;
3988 else if (PL_regkind[OP(scan)] == TRIE) {
3989 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
3992 min += trie->minlen;
3993 delta += (trie->maxlen - trie->minlen);
3994 flags &= ~SCF_DO_STCLASS; /* xxx */
3995 if (flags & SCF_DO_SUBSTR) {
3996 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3997 data->pos_min += trie->minlen;
3998 data->pos_delta += (trie->maxlen - trie->minlen);
3999 if (trie->maxlen != trie->minlen)
4000 data->longest = &(data->longest_float);
4002 if (trie->jump) /* no more substrings -- for now /grr*/
4003 flags &= ~SCF_DO_SUBSTR;
4005 #endif /* old or new */
4006 #endif /* TRIE_STUDY_OPT */
4008 /* Else: zero-length, ignore. */
4009 scan = regnext(scan);
4014 stopparen = frame->stop;
4015 frame = frame->prev;
4016 goto fake_study_recurse;
4021 DEBUG_STUDYDATA("pre-fin:",data,depth);
4024 *deltap = is_inf_internal ? I32_MAX : delta;
4025 if (flags & SCF_DO_SUBSTR && is_inf)
4026 data->pos_delta = I32_MAX - data->pos_min;
4027 if (is_par > (I32)U8_MAX)
4029 if (is_par && pars==1 && data) {
4030 data->flags |= SF_IN_PAR;
4031 data->flags &= ~SF_HAS_PAR;
4033 else if (pars && data) {
4034 data->flags |= SF_HAS_PAR;
4035 data->flags &= ~SF_IN_PAR;
4037 if (flags & SCF_DO_STCLASS_OR)
4038 cl_and(data->start_class, and_withp);
4039 if (flags & SCF_TRIE_RESTUDY)
4040 data->flags |= SCF_TRIE_RESTUDY;
4042 DEBUG_STUDYDATA("post-fin:",data,depth);
4044 return min < stopmin ? min : stopmin;
4048 S_add_data(RExC_state_t *pRExC_state, U32 n, const char *s)
4050 U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
4052 Renewc(RExC_rxi->data,
4053 sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
4054 char, struct reg_data);
4056 Renew(RExC_rxi->data->what, count + n, U8);
4058 Newx(RExC_rxi->data->what, n, U8);
4059 RExC_rxi->data->count = count + n;
4060 Copy(s, RExC_rxi->data->what + count, n, U8);
4064 /*XXX: todo make this not included in a non debugging perl */
4065 #ifndef PERL_IN_XSUB_RE
4067 Perl_reginitcolors(pTHX)
4070 const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
4072 char *t = savepv(s);
4076 t = strchr(t, '\t');
4082 PL_colors[i] = t = (char *)"";
4087 PL_colors[i++] = (char *)"";
4094 #ifdef TRIE_STUDY_OPT
4095 #define CHECK_RESTUDY_GOTO \
4097 (data.flags & SCF_TRIE_RESTUDY) \
4101 #define CHECK_RESTUDY_GOTO
4105 - pregcomp - compile a regular expression into internal code
4107 * We can't allocate space until we know how big the compiled form will be,
4108 * but we can't compile it (and thus know how big it is) until we've got a
4109 * place to put the code. So we cheat: we compile it twice, once with code
4110 * generation turned off and size counting turned on, and once "for real".
4111 * This also means that we don't allocate space until we are sure that the
4112 * thing really will compile successfully, and we never have to move the
4113 * code and thus invalidate pointers into it. (Note that it has to be in
4114 * one piece because free() must be able to free it all.) [NB: not true in perl]
4116 * Beware that the optimization-preparation code in here knows about some
4117 * of the structure of the compiled regexp. [I'll say.]
4122 #ifndef PERL_IN_XSUB_RE
4123 #define RE_ENGINE_PTR &PL_core_reg_engine
4125 extern const struct regexp_engine my_reg_engine;
4126 #define RE_ENGINE_PTR &my_reg_engine
4129 #ifndef PERL_IN_XSUB_RE
4131 Perl_pregcomp(pTHX_ const SV * const pattern, const U32 flags)
4134 HV * const table = GvHV(PL_hintgv);
4135 /* Dispatch a request to compile a regexp to correct
4138 SV **ptr= hv_fetchs(table, "regcomp", FALSE);
4139 GET_RE_DEBUG_FLAGS_DECL;
4140 if (ptr && SvIOK(*ptr) && SvIV(*ptr)) {
4141 const regexp_engine *eng=INT2PTR(regexp_engine*,SvIV(*ptr));
4143 PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
4146 return CALLREGCOMP_ENG(eng, pattern, flags);
4149 return Perl_re_compile(aTHX_ pattern, flags);
4154 Perl_re_compile(pTHX_ const SV * const pattern, U32 pm_flags)
4159 register regexp_internal *ri;
4161 char* exp = SvPV((SV*)pattern, plen);
4162 char* xend = exp + plen;
4169 RExC_state_t RExC_state;
4170 RExC_state_t * const pRExC_state = &RExC_state;
4171 #ifdef TRIE_STUDY_OPT
4173 RExC_state_t copyRExC_state;
4175 GET_RE_DEBUG_FLAGS_DECL;
4176 DEBUG_r(if (!PL_colorset) reginitcolors());
4178 RExC_utf8 = RExC_orig_utf8 = SvUTF8(pattern);
4179 assert(!(pm_flags & RXf_UTF8));
4181 pm_flags |= RXf_UTF8;
4184 SV *dsv= sv_newmortal();
4185 RE_PV_QUOTED_DECL(s, RExC_utf8,
4186 dsv, exp, plen, 60);
4187 PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
4188 PL_colors[4],PL_colors[5],s);
4193 RExC_flags = pm_flags;
4197 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
4198 RExC_seen_evals = 0;
4201 /* First pass: determine size, legality. */
4209 RExC_emit = &PL_regdummy;
4210 RExC_whilem_seen = 0;
4211 RExC_charnames = NULL;
4212 RExC_open_parens = NULL;
4213 RExC_close_parens = NULL;
4215 RExC_paren_names = NULL;
4217 RExC_paren_name_list = NULL;
4219 RExC_recurse = NULL;
4220 RExC_recurse_count = 0;
4222 #if 0 /* REGC() is (currently) a NOP at the first pass.
4223 * Clever compilers notice this and complain. --jhi */
4224 REGC((U8)REG_MAGIC, (char*)RExC_emit);
4226 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n"));
4227 if (reg(pRExC_state, 0, &flags,1) == NULL) {
4228 RExC_precomp = NULL;
4231 if (RExC_utf8 && !RExC_orig_utf8) {
4232 /* It's possible to write a regexp in ascii that represents Unicode
4233 codepoints outside of the byte range, such as via \x{100}. If we
4234 detect such a sequence we have to convert the entire pattern to utf8
4235 and then recompile, as our sizing calculation will have been based
4236 on 1 byte == 1 character, but we will need to use utf8 to encode
4237 at least some part of the pattern, and therefore must convert the whole
4239 XXX: somehow figure out how to make this less expensive...
4242 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
4243 "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
4244 exp = (char*)Perl_bytes_to_utf8(aTHX_ (U8*)exp, &len);
4246 RExC_orig_utf8 = RExC_utf8;
4248 goto redo_first_pass;
4251 PerlIO_printf(Perl_debug_log,
4252 "Required size %"IVdf" nodes\n"
4253 "Starting second pass (creation)\n",
4256 RExC_lastparse=NULL;
4258 /* Small enough for pointer-storage convention?
4259 If extralen==0, this means that we will not need long jumps. */
4260 if (RExC_size >= 0x10000L && RExC_extralen)
4261 RExC_size += RExC_extralen;
4264 if (RExC_whilem_seen > 15)
4265 RExC_whilem_seen = 15;
4267 /* Allocate space and zero-initialize. Note, the two step process
4268 of zeroing when in debug mode, thus anything assigned has to
4269 happen after that */
4270 rx = newSV_type(SVt_REGEXP);
4271 r = (struct regexp*)SvANY(rx);
4272 Newxc(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
4273 char, regexp_internal);
4274 if ( r == NULL || ri == NULL )
4275 FAIL("Regexp out of space");
4277 /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
4278 Zero(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode), char);
4280 /* bulk initialize base fields with 0. */
4281 Zero(ri, sizeof(regexp_internal), char);
4284 /* non-zero initialization begins here */
4286 r->engine= RE_ENGINE_PTR;
4287 r->extflags = pm_flags;
4289 bool has_p = ((r->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
4290 bool has_minus = ((r->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD);
4291 bool has_runon = ((RExC_seen & REG_SEEN_RUN_ON_COMMENT)==REG_SEEN_RUN_ON_COMMENT);
4292 U16 reganch = (U16)((r->extflags & RXf_PMf_STD_PMMOD)
4293 >> RXf_PMf_STD_PMMOD_SHIFT);
4294 const char *fptr = STD_PAT_MODS; /*"msix"*/
4296 const STRLEN wraplen = plen + has_minus + has_p + has_runon
4297 + (sizeof(STD_PAT_MODS) - 1)
4298 + (sizeof("(?:)") - 1);
4300 p = sv_grow(rx, wraplen + 1);
4301 SvCUR_set(rx, wraplen);
4305 *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
4307 char *r = p + (sizeof(STD_PAT_MODS) - 1) + has_minus - 1;
4308 char *colon = r + 1;
4311 while((ch = *fptr++)) {
4325 Copy(RExC_precomp, p, plen, char);
4326 assert ((RX_WRAPPED(rx) - p) < 16);
4327 r->pre_prefix = p - RX_WRAPPED(rx);
4336 r->nparens = RExC_npar - 1; /* set early to validate backrefs */
4338 if (RExC_seen & REG_SEEN_RECURSE) {
4339 Newxz(RExC_open_parens, RExC_npar,regnode *);
4340 SAVEFREEPV(RExC_open_parens);
4341 Newxz(RExC_close_parens,RExC_npar,regnode *);
4342 SAVEFREEPV(RExC_close_parens);
4345 /* Useful during FAIL. */
4346 #ifdef RE_TRACK_PATTERN_OFFSETS
4347 Newxz(ri->u.offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
4348 DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
4349 "%s %"UVuf" bytes for offset annotations.\n",
4350 ri->u.offsets ? "Got" : "Couldn't get",
4351 (UV)((2*RExC_size+1) * sizeof(U32))));
4353 SetProgLen(ri,RExC_size);
4358 /* Second pass: emit code. */
4359 RExC_flags = pm_flags; /* don't let top level (?i) bleed */
4364 RExC_emit_start = ri->program;
4365 RExC_emit = ri->program;
4366 RExC_emit_bound = ri->program + RExC_size + 1;
4368 /* Store the count of eval-groups for security checks: */
4369 RExC_rx->seen_evals = RExC_seen_evals;
4370 REGC((U8)REG_MAGIC, (char*) RExC_emit++);
4371 if (reg(pRExC_state, 0, &flags,1) == NULL) {
4375 /* XXXX To minimize changes to RE engine we always allocate
4376 3-units-long substrs field. */
4377 Newx(r->substrs, 1, struct reg_substr_data);
4378 if (RExC_recurse_count) {
4379 Newxz(RExC_recurse,RExC_recurse_count,regnode *);
4380 SAVEFREEPV(RExC_recurse);
4384 r->minlen = minlen = sawplus = sawopen = 0;
4385 Zero(r->substrs, 1, struct reg_substr_data);
4387 #ifdef TRIE_STUDY_OPT
4390 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
4392 RExC_state = copyRExC_state;
4393 if (seen & REG_TOP_LEVEL_BRANCHES)
4394 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
4396 RExC_seen &= ~REG_TOP_LEVEL_BRANCHES;
4397 if (data.last_found) {
4398 SvREFCNT_dec(data.longest_fixed);
4399 SvREFCNT_dec(data.longest_float);
4400 SvREFCNT_dec(data.last_found);
4402 StructCopy(&zero_scan_data, &data, scan_data_t);
4404 StructCopy(&zero_scan_data, &data, scan_data_t);
4405 copyRExC_state = RExC_state;
4408 StructCopy(&zero_scan_data, &data, scan_data_t);
4411 /* Dig out information for optimizations. */
4412 r->extflags = RExC_flags; /* was pm_op */
4413 /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
4416 r->extflags |= RXf_UTF8; /* Unicode in it? */
4417 ri->regstclass = NULL;
4418 if (RExC_naughty >= 10) /* Probably an expensive pattern. */
4419 r->intflags |= PREGf_NAUGHTY;
4420 scan = ri->program + 1; /* First BRANCH. */
4422 /* testing for BRANCH here tells us whether there is "must appear"
4423 data in the pattern. If there is then we can use it for optimisations */
4424 if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES)) { /* Only one top-level choice. */
4426 STRLEN longest_float_length, longest_fixed_length;
4427 struct regnode_charclass_class ch_class; /* pointed to by data */
4429 I32 last_close = 0; /* pointed to by data */
4430 regnode *first= scan;
4431 regnode *first_next= regnext(first);
4433 /* Skip introductions and multiplicators >= 1. */
4434 while ((OP(first) == OPEN && (sawopen = 1)) ||
4435 /* An OR of *one* alternative - should not happen now. */
4436 (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
4437 /* for now we can't handle lookbehind IFMATCH*/
4438 (OP(first) == IFMATCH && !first->flags) ||
4439 (OP(first) == PLUS) ||
4440 (OP(first) == MINMOD) ||
4441 /* An {n,m} with n>0 */
4442 (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
4443 (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
4446 if (OP(first) == PLUS)
4449 first += regarglen[OP(first)];
4450 if (OP(first) == IFMATCH) {
4451 first = NEXTOPER(first);
4452 first += EXTRA_STEP_2ARGS;
4453 } else /* XXX possible optimisation for /(?=)/ */
4454 first = NEXTOPER(first);
4455 first_next= regnext(first);
4458 /* Starting-point info. */
4460 DEBUG_PEEP("first:",first,0);
4461 /* Ignore EXACT as we deal with it later. */
4462 if (PL_regkind[OP(first)] == EXACT) {
4463 if (OP(first) == EXACT)
4464 NOOP; /* Empty, get anchored substr later. */
4465 else if ((OP(first) == EXACTF || OP(first) == EXACTFL))
4466 ri->regstclass = first;
4469 else if (PL_regkind[OP(first)] == TRIE &&
4470 ((reg_trie_data *)ri->data->data[ ARG(first) ])->minlen>0)
4473 /* this can happen only on restudy */
4474 if ( OP(first) == TRIE ) {
4475 struct regnode_1 *trieop = (struct regnode_1 *)
4476 PerlMemShared_calloc(1, sizeof(struct regnode_1));
4477 StructCopy(first,trieop,struct regnode_1);
4478 trie_op=(regnode *)trieop;
4480 struct regnode_charclass *trieop = (struct regnode_charclass *)
4481 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
4482 StructCopy(first,trieop,struct regnode_charclass);
4483 trie_op=(regnode *)trieop;
4486 make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
4487 ri->regstclass = trie_op;
4490 else if (strchr((const char*)PL_simple,OP(first)))
4491 ri->regstclass = first;
4492 else if (PL_regkind[OP(first)] == BOUND ||
4493 PL_regkind[OP(first)] == NBOUND)
4494 ri->regstclass = first;
4495 else if (PL_regkind[OP(first)] == BOL) {
4496 r->extflags |= (OP(first) == MBOL
4498 : (OP(first) == SBOL
4501 first = NEXTOPER(first);
4504 else if (OP(first) == GPOS) {
4505 r->extflags |= RXf_ANCH_GPOS;
4506 first = NEXTOPER(first);
4509 else if ((!sawopen || !RExC_sawback) &&
4510 (OP(first) == STAR &&
4511 PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
4512 !(r->extflags & RXf_ANCH) && !(RExC_seen & REG_SEEN_EVAL))
4514 /* turn .* into ^.* with an implied $*=1 */
4516 (OP(NEXTOPER(first)) == REG_ANY)
4519 r->extflags |= type;
4520 r->intflags |= PREGf_IMPLICIT;
4521 first = NEXTOPER(first);
4524 if (sawplus && (!sawopen || !RExC_sawback)
4525 && !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
4526 /* x+ must match at the 1st pos of run of x's */
4527 r->intflags |= PREGf_SKIP;
4529 /* Scan is after the zeroth branch, first is atomic matcher. */
4530 #ifdef TRIE_STUDY_OPT
4533 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4534 (IV)(first - scan + 1))
4538 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4539 (IV)(first - scan + 1))
4545 * If there's something expensive in the r.e., find the
4546 * longest literal string that must appear and make it the
4547 * regmust. Resolve ties in favor of later strings, since
4548 * the regstart check works with the beginning of the r.e.
4549 * and avoiding duplication strengthens checking. Not a
4550 * strong reason, but sufficient in the absence of others.
4551 * [Now we resolve ties in favor of the earlier string if
4552 * it happens that c_offset_min has been invalidated, since the
4553 * earlier string may buy us something the later one won't.]
4556 data.longest_fixed = newSVpvs("");
4557 data.longest_float = newSVpvs("");
4558 data.last_found = newSVpvs("");
4559 data.longest = &(data.longest_fixed);
4561 if (!ri->regstclass) {
4562 cl_init(pRExC_state, &ch_class);
4563 data.start_class = &ch_class;
4564 stclass_flag = SCF_DO_STCLASS_AND;
4565 } else /* XXXX Check for BOUND? */
4567 data.last_closep = &last_close;
4569 minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
4570 &data, -1, NULL, NULL,
4571 SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag,0);
4577 if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
4578 && data.last_start_min == 0 && data.last_end > 0
4579 && !RExC_seen_zerolen
4580 && !(RExC_seen & REG_SEEN_VERBARG)
4581 && (!(RExC_seen & REG_SEEN_GPOS) || (r->extflags & RXf_ANCH_GPOS)))
4582 r->extflags |= RXf_CHECK_ALL;
4583 scan_commit(pRExC_state, &data,&minlen,0);
4584 SvREFCNT_dec(data.last_found);
4586 /* Note that code very similar to this but for anchored string
4587 follows immediately below, changes may need to be made to both.
4590 longest_float_length = CHR_SVLEN(data.longest_float);
4591 if (longest_float_length
4592 || (data.flags & SF_FL_BEFORE_EOL
4593 && (!(data.flags & SF_FL_BEFORE_MEOL)
4594 || (RExC_flags & RXf_PMf_MULTILINE))))
4598 if (SvCUR(data.longest_fixed) /* ok to leave SvCUR */
4599 && data.offset_fixed == data.offset_float_min
4600 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
4601 goto remove_float; /* As in (a)+. */
4603 /* copy the information about the longest float from the reg_scan_data
4604 over to the program. */
4605 if (SvUTF8(data.longest_float)) {
4606 r->float_utf8 = data.longest_float;
4607 r->float_substr = NULL;
4609 r->float_substr = data.longest_float;
4610 r->float_utf8 = NULL;
4612 /* float_end_shift is how many chars that must be matched that
4613 follow this item. We calculate it ahead of time as once the
4614 lookbehind offset is added in we lose the ability to correctly
4616 ml = data.minlen_float ? *(data.minlen_float)
4617 : (I32)longest_float_length;
4618 r->float_end_shift = ml - data.offset_float_min
4619 - longest_float_length + (SvTAIL(data.longest_float) != 0)
4620 + data.lookbehind_float;
4621 r->float_min_offset = data.offset_float_min - data.lookbehind_float;
4622 r->float_max_offset = data.offset_float_max;
4623 if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
4624 r->float_max_offset -= data.lookbehind_float;
4626 t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
4627 && (!(data.flags & SF_FL_BEFORE_MEOL)
4628 || (RExC_flags & RXf_PMf_MULTILINE)));
4629 fbm_compile(data.longest_float, t ? FBMcf_TAIL : 0);
4633 r->float_substr = r->float_utf8 = NULL;
4634 SvREFCNT_dec(data.longest_float);
4635 longest_float_length = 0;
4638 /* Note that code very similar to this but for floating string
4639 is immediately above, changes may need to be made to both.
4642 longest_fixed_length = CHR_SVLEN(data.longest_fixed);
4643 if (longest_fixed_length
4644 || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
4645 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4646 || (RExC_flags & RXf_PMf_MULTILINE))))
4650 /* copy the information about the longest fixed
4651 from the reg_scan_data over to the program. */
4652 if (SvUTF8(data.longest_fixed)) {
4653 r->anchored_utf8 = data.longest_fixed;
4654 r->anchored_substr = NULL;
4656 r->anchored_substr = data.longest_fixed;
4657 r->anchored_utf8 = NULL;
4659 /* fixed_end_shift is how many chars that must be matched that
4660 follow this item. We calculate it ahead of time as once the
4661 lookbehind offset is added in we lose the ability to correctly
4663 ml = data.minlen_fixed ? *(data.minlen_fixed)
4664 : (I32)longest_fixed_length;
4665 r->anchored_end_shift = ml - data.offset_fixed
4666 - longest_fixed_length + (SvTAIL(data.longest_fixed) != 0)
4667 + data.lookbehind_fixed;
4668 r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
4670 t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
4671 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4672 || (RExC_flags & RXf_PMf_MULTILINE)));
4673 fbm_compile(data.longest_fixed, t ? FBMcf_TAIL : 0);
4676 r->anchored_substr = r->anchored_utf8 = NULL;
4677 SvREFCNT_dec(data.longest_fixed);
4678 longest_fixed_length = 0;
4681 && (OP(ri->regstclass) == REG_ANY || OP(ri->regstclass) == SANY))
4682 ri->regstclass = NULL;
4683 if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
4685 && !(data.start_class->flags & ANYOF_EOS)
4686 && !cl_is_anything(data.start_class))
4688 const U32 n = add_data(pRExC_state, 1, "f");
4690 Newx(RExC_rxi->data->data[n], 1,
4691 struct regnode_charclass_class);
4692 StructCopy(data.start_class,
4693 (struct regnode_charclass_class*)RExC_rxi->data->data[n],
4694 struct regnode_charclass_class);
4695 ri->regstclass = (regnode*)RExC_rxi->data->data[n];
4696 r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
4697 DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
4698 regprop(r, sv, (regnode*)data.start_class);
4699 PerlIO_printf(Perl_debug_log,
4700 "synthetic stclass \"%s\".\n",
4701 SvPVX_const(sv));});
4704 /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
4705 if (longest_fixed_length > longest_float_length) {
4706 r->check_end_shift = r->anchored_end_shift;
4707 r->check_substr = r->anchored_substr;
4708 r->check_utf8 = r->anchored_utf8;
4709 r->check_offset_min = r->check_offset_max = r->anchored_offset;
4710 if (r->extflags & RXf_ANCH_SINGLE)
4711 r->extflags |= RXf_NOSCAN;
4714 r->check_end_shift = r->float_end_shift;
4715 r->check_substr = r->float_substr;
4716 r->check_utf8 = r->float_utf8;
4717 r->check_offset_min = r->float_min_offset;
4718 r->check_offset_max = r->float_max_offset;
4720 /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
4721 This should be changed ASAP! */
4722 if ((r->check_substr || r->check_utf8) && !(r->extflags & RXf_ANCH_GPOS)) {
4723 r->extflags |= RXf_USE_INTUIT;
4724 if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
4725 r->extflags |= RXf_INTUIT_TAIL;
4727 /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
4728 if ( (STRLEN)minlen < longest_float_length )
4729 minlen= longest_float_length;
4730 if ( (STRLEN)minlen < longest_fixed_length )
4731 minlen= longest_fixed_length;
4735 /* Several toplevels. Best we can is to set minlen. */
4737 struct regnode_charclass_class ch_class;
4740 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "\nMulti Top Level\n"));
4742 scan = ri->program + 1;
4743 cl_init(pRExC_state, &ch_class);
4744 data.start_class = &ch_class;
4745 data.last_closep = &last_close;
4748 minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
4749 &data, -1, NULL, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS,0);
4753 r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
4754 = r->float_substr = r->float_utf8 = NULL;
4755 if (!(data.start_class->flags & ANYOF_EOS)
4756 && !cl_is_anything(data.start_class))
4758 const U32 n = add_data(pRExC_state, 1, "f");
4760 Newx(RExC_rxi->data->data[n], 1,
4761 struct regnode_charclass_class);
4762 StructCopy(data.start_class,
4763 (struct regnode_charclass_class*)RExC_rxi->data->data[n],
4764 struct regnode_charclass_class);
4765 ri->regstclass = (regnode*)RExC_rxi->data->data[n];
4766 r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
4767 DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
4768 regprop(r, sv, (regnode*)data.start_class);
4769 PerlIO_printf(Perl_debug_log,
4770 "synthetic stclass \"%s\".\n",
4771 SvPVX_const(sv));});
4775 /* Guard against an embedded (?=) or (?<=) with a longer minlen than
4776 the "real" pattern. */
4778 PerlIO_printf(Perl_debug_log,"minlen: %"IVdf" r->minlen:%"IVdf"\n",
4779 (IV)minlen, (IV)r->minlen);
4781 r->minlenret = minlen;
4782 if (r->minlen < minlen)
4785 if (RExC_seen & REG_SEEN_GPOS)
4786 r->extflags |= RXf_GPOS_SEEN;
4787 if (RExC_seen & REG_SEEN_LOOKBEHIND)
4788 r->extflags |= RXf_LOOKBEHIND_SEEN;
4789 if (RExC_seen & REG_SEEN_EVAL)
4790 r->extflags |= RXf_EVAL_SEEN;
4791 if (RExC_seen & REG_SEEN_CANY)
4792 r->extflags |= RXf_CANY_SEEN;
4793 if (RExC_seen & REG_SEEN_VERBARG)
4794 r->intflags |= PREGf_VERBARG_SEEN;
4795 if (RExC_seen & REG_SEEN_CUTGROUP)
4796 r->intflags |= PREGf_CUTGROUP_SEEN;
4797 if (RExC_paren_names)
4798 r->paren_names = (HV*)SvREFCNT_inc(RExC_paren_names);
4800 r->paren_names = NULL;
4802 #ifdef STUPID_PATTERN_CHECKS
4803 if (RX_PRELEN(rx) == 0)
4804 r->extflags |= RXf_NULL;
4805 if (r->extflags & RXf_SPLIT && RX_PRELEN(rx) == 1 && RX_PRECOMP(rx)[0] == ' ')
4806 /* XXX: this should happen BEFORE we compile */
4807 r->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
4808 else if (RX_PRELEN(rx) == 3 && memEQ("\\s+", RX_PRECOMP(rx), 3))
4809 r->extflags |= RXf_WHITE;
4810 else if (RX_PRELEN(rx) == 1 && RXp_PRECOMP(rx)[0] == '^')
4811 r->extflags |= RXf_START_ONLY;
4813 if (r->extflags & RXf_SPLIT && RX_PRELEN(rx) == 1 && RX_PRECOMP(rx)[0] == ' ')
4814 /* XXX: this should happen BEFORE we compile */
4815 r->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
4817 regnode *first = ri->program + 1;
4819 U8 nop = OP(NEXTOPER(first));
4821 if (PL_regkind[fop] == NOTHING && nop == END)
4822 r->extflags |= RXf_NULL;
4823 else if (PL_regkind[fop] == BOL && nop == END)
4824 r->extflags |= RXf_START_ONLY;
4825 else if (fop == PLUS && nop ==SPACE && OP(regnext(first))==END)
4826 r->extflags |= RXf_WHITE;
4830 if (RExC_paren_names) {
4831 ri->name_list_idx = add_data( pRExC_state, 1, "p" );
4832 ri->data->data[ri->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list);
4835 ri->name_list_idx = 0;
4837 if (RExC_recurse_count) {
4838 for ( ; RExC_recurse_count ; RExC_recurse_count-- ) {
4839 const regnode *scan = RExC_recurse[RExC_recurse_count-1];
4840 ARG2L_SET( scan, RExC_open_parens[ARG(scan)-1] - scan );
4843 Newxz(r->offs, RExC_npar, regexp_paren_pair);
4844 /* assume we don't need to swap parens around before we match */
4847 PerlIO_printf(Perl_debug_log,"Final program:\n");
4850 #ifdef RE_TRACK_PATTERN_OFFSETS
4851 DEBUG_OFFSETS_r(if (ri->u.offsets) {
4852 const U32 len = ri->u.offsets[0];
4854 GET_RE_DEBUG_FLAGS_DECL;
4855 PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)ri->u.offsets[0]);
4856 for (i = 1; i <= len; i++) {
4857 if (ri->u.offsets[i*2-1] || ri->u.offsets[i*2])
4858 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
4859 (UV)i, (UV)ri->u.offsets[i*2-1], (UV)ri->u.offsets[i*2]);
4861 PerlIO_printf(Perl_debug_log, "\n");
4867 #undef RE_ENGINE_PTR
4871 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
4874 PERL_UNUSED_ARG(value);
4876 if (flags & RXapif_FETCH) {
4877 return reg_named_buff_fetch(rx, key, flags);
4878 } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
4879 Perl_croak(aTHX_ PL_no_modify);
4881 } else if (flags & RXapif_EXISTS) {
4882 return reg_named_buff_exists(rx, key, flags)
4885 } else if (flags & RXapif_REGNAMES) {
4886 return reg_named_buff_all(rx, flags);
4887 } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
4888 return reg_named_buff_scalar(rx, flags);
4890 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
4896 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
4899 PERL_UNUSED_ARG(lastkey);
4901 if (flags & RXapif_FIRSTKEY)
4902 return reg_named_buff_firstkey(rx, flags);
4903 else if (flags & RXapif_NEXTKEY)
4904 return reg_named_buff_nextkey(rx, flags);
4906 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter", (int)flags);
4912 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
4915 AV *retarray = NULL;
4917 struct regexp *const rx = (struct regexp *)SvANY(r);
4918 if (flags & RXapif_ALL)
4921 if (rx && rx->paren_names) {
4922 HE *he_str = hv_fetch_ent( rx->paren_names, namesv, 0, 0 );
4925 SV* sv_dat=HeVAL(he_str);
4926 I32 *nums=(I32*)SvPVX(sv_dat);
4927 for ( i=0; i<SvIVX(sv_dat); i++ ) {
4928 if ((I32)(rx->nparens) >= nums[i]
4929 && rx->offs[nums[i]].start != -1
4930 && rx->offs[nums[i]].end != -1)
4933 CALLREG_NUMBUF_FETCH(r,nums[i],ret);
4937 ret = newSVsv(&PL_sv_undef);
4940 SvREFCNT_inc_simple_void(ret);
4941 av_push(retarray, ret);
4945 return newRV((SV*)retarray);
4952 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
4955 struct regexp *const rx = (struct regexp *)SvANY(r);
4956 if (rx && rx->paren_names) {
4957 if (flags & RXapif_ALL) {
4958 return hv_exists_ent(rx->paren_names, key, 0);
4960 SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
4974 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
4976 struct regexp *const rx = (struct regexp *)SvANY(r);
4977 if ( rx && rx->paren_names ) {
4978 (void)hv_iterinit(rx->paren_names);
4980 return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
4987 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
4989 struct regexp *const rx = (struct regexp *)SvANY(r);
4990 if (rx && rx->paren_names) {
4991 HV *hv = rx->paren_names;
4993 while ( (temphe = hv_iternext_flags(hv,0)) ) {
4996 SV* sv_dat = HeVAL(temphe);
4997 I32 *nums = (I32*)SvPVX(sv_dat);
4998 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
4999 if ((I32)(rx->lastcloseparen) >= nums[i] &&
5000 rx->offs[nums[i]].start != -1 &&
5001 rx->offs[nums[i]].end != -1)
5007 if (parno || flags & RXapif_ALL) {
5008 return newSVhek(HeKEY_hek(temphe));
5016 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
5021 struct regexp *const rx = (struct regexp *)SvANY(r);
5023 if (rx && rx->paren_names) {
5024 if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
5025 return newSViv(HvTOTALKEYS(rx->paren_names));
5026 } else if (flags & RXapif_ONE) {
5027 ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
5028 av = (AV*)SvRV(ret);
5029 length = av_len(av);
5030 return newSViv(length + 1);
5032 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar", (int)flags);
5036 return &PL_sv_undef;
5040 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
5042 struct regexp *const rx = (struct regexp *)SvANY(r);
5045 if (rx && rx->paren_names) {
5046 HV *hv= rx->paren_names;
5048 (void)hv_iterinit(hv);
5049 while ( (temphe = hv_iternext_flags(hv,0)) ) {
5052 SV* sv_dat = HeVAL(temphe);
5053 I32 *nums = (I32*)SvPVX(sv_dat);
5054 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
5055 if ((I32)(rx->lastcloseparen) >= nums[i] &&
5056 rx->offs[nums[i]].start != -1 &&
5057 rx->offs[nums[i]].end != -1)
5063 if (parno || flags & RXapif_ALL) {
5064 av_push(av, newSVhek(HeKEY_hek(temphe)));
5069 return newRV((SV*)av);
5073 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
5076 struct regexp *const rx = (struct regexp *)SvANY(r);
5082 sv_setsv(sv,&PL_sv_undef);
5086 if (paren == RX_BUFF_IDX_PREMATCH && rx->offs[0].start != -1) {
5088 i = rx->offs[0].start;
5092 if (paren == RX_BUFF_IDX_POSTMATCH && rx->offs[0].end != -1) {
5094 s = rx->subbeg + rx->offs[0].end;
5095 i = rx->sublen - rx->offs[0].end;
5098 if ( 0 <= paren && paren <= (I32)rx->nparens &&
5099 (s1 = rx->offs[paren].start) != -1 &&
5100 (t1 = rx->offs[paren].end) != -1)
5104 s = rx->subbeg + s1;
5106 sv_setsv(sv,&PL_sv_undef);
5109 assert(rx->sublen >= (s - rx->subbeg) + i );
5111 const int oldtainted = PL_tainted;
5113 sv_setpvn(sv, s, i);
5114 PL_tainted = oldtainted;
5115 if ( (rx->extflags & RXf_CANY_SEEN)
5116 ? (RXp_MATCH_UTF8(rx)
5117 && (!i || is_utf8_string((U8*)s, i)))
5118 : (RXp_MATCH_UTF8(rx)) )
5125 if (RXp_MATCH_TAINTED(rx)) {
5126 if (SvTYPE(sv) >= SVt_PVMG) {
5127 MAGIC* const mg = SvMAGIC(sv);
5130 SvMAGIC_set(sv, mg->mg_moremagic);
5132 if ((mgt = SvMAGIC(sv))) {
5133 mg->mg_moremagic = mgt;
5134 SvMAGIC_set(sv, mg);
5144 sv_setsv(sv,&PL_sv_undef);
5150 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
5151 SV const * const value)
5153 PERL_UNUSED_ARG(rx);
5154 PERL_UNUSED_ARG(paren);
5155 PERL_UNUSED_ARG(value);
5158 Perl_croak(aTHX_ PL_no_modify);
5162 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
5165 struct regexp *const rx = (struct regexp *)SvANY(r);
5169 /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
5171 /* $` / ${^PREMATCH} */
5172 case RX_BUFF_IDX_PREMATCH:
5173 if (rx->offs[0].start != -1) {
5174 i = rx->offs[0].start;
5182 /* $' / ${^POSTMATCH} */
5183 case RX_BUFF_IDX_POSTMATCH:
5184 if (rx->offs[0].end != -1) {
5185 i = rx->sublen - rx->offs[0].end;
5187 s1 = rx->offs[0].end;
5193 /* $& / ${^MATCH}, $1, $2, ... */
5195 if (paren <= (I32)rx->nparens &&
5196 (s1 = rx->offs[paren].start) != -1 &&
5197 (t1 = rx->offs[paren].end) != -1)
5202 if (ckWARN(WARN_UNINITIALIZED))
5203 report_uninit((SV*)sv);
5208 if (i > 0 && RXp_MATCH_UTF8(rx)) {
5209 const char * const s = rx->subbeg + s1;
5214 if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
5221 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
5223 PERL_UNUSED_ARG(rx);
5227 /* Scans the name of a named buffer from the pattern.
5228 * If flags is REG_RSN_RETURN_NULL returns null.
5229 * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
5230 * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
5231 * to the parsed name as looked up in the RExC_paren_names hash.
5232 * If there is an error throws a vFAIL().. type exception.
5235 #define REG_RSN_RETURN_NULL 0
5236 #define REG_RSN_RETURN_NAME 1
5237 #define REG_RSN_RETURN_DATA 2
5240 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags) {
5241 char *name_start = RExC_parse;
5243 if (isIDFIRST_lazy_if(RExC_parse, UTF)) {
5244 /* skip IDFIRST by using do...while */
5247 RExC_parse += UTF8SKIP(RExC_parse);
5248 } while (isALNUM_utf8((U8*)RExC_parse));
5252 } while (isALNUM(*RExC_parse));
5257 = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
5258 SVs_TEMP | (UTF ? SVf_UTF8 : 0));
5259 if ( flags == REG_RSN_RETURN_NAME)
5261 else if (flags==REG_RSN_RETURN_DATA) {
5264 if ( ! sv_name ) /* should not happen*/
5265 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
5266 if (RExC_paren_names)
5267 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
5269 sv_dat = HeVAL(he_str);
5271 vFAIL("Reference to nonexistent named group");
5275 Perl_croak(aTHX_ "panic: bad flag in reg_scan_name");
5282 #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
5283 int rem=(int)(RExC_end - RExC_parse); \
5292 if (RExC_lastparse!=RExC_parse) \
5293 PerlIO_printf(Perl_debug_log," >%.*s%-*s", \
5296 iscut ? "..." : "<" \
5299 PerlIO_printf(Perl_debug_log,"%16s",""); \
5302 num = RExC_size + 1; \
5304 num=REG_NODE_NUM(RExC_emit); \
5305 if (RExC_lastnum!=num) \
5306 PerlIO_printf(Perl_debug_log,"|%4d",num); \
5308 PerlIO_printf(Perl_debug_log,"|%4s",""); \
5309 PerlIO_printf(Perl_debug_log,"|%*s%-4s", \
5310 (int)((depth*2)), "", \
5314 RExC_lastparse=RExC_parse; \
5319 #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
5320 DEBUG_PARSE_MSG((funcname)); \
5321 PerlIO_printf(Perl_debug_log,"%4s","\n"); \
5323 #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({ \
5324 DEBUG_PARSE_MSG((funcname)); \
5325 PerlIO_printf(Perl_debug_log,fmt "\n",args); \
5328 - reg - regular expression, i.e. main body or parenthesized thing
5330 * Caller must absorb opening parenthesis.
5332 * Combining parenthesis handling with the base level of regular expression
5333 * is a trifle forced, but the need to tie the tails of the branches to what
5334 * follows makes it hard to avoid.
5336 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
5338 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
5340 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
5344 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
5345 /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
5348 register regnode *ret; /* Will be the head of the group. */
5349 register regnode *br;
5350 register regnode *lastbr;
5351 register regnode *ender = NULL;
5352 register I32 parno = 0;
5354 U32 oregflags = RExC_flags;
5355 bool have_branch = 0;
5357 I32 freeze_paren = 0;
5358 I32 after_freeze = 0;
5360 /* for (?g), (?gc), and (?o) warnings; warning
5361 about (?c) will warn about (?g) -- japhy */
5363 #define WASTED_O 0x01
5364 #define WASTED_G 0x02
5365 #define WASTED_C 0x04
5366 #define WASTED_GC (0x02|0x04)
5367 I32 wastedflags = 0x00;
5369 char * parse_start = RExC_parse; /* MJD */
5370 char * const oregcomp_parse = RExC_parse;
5372 GET_RE_DEBUG_FLAGS_DECL;
5373 DEBUG_PARSE("reg ");
5375 *flagp = 0; /* Tentatively. */
5378 /* Make an OPEN node, if parenthesized. */
5380 if ( *RExC_parse == '*') { /* (*VERB:ARG) */
5381 char *start_verb = RExC_parse;
5382 STRLEN verb_len = 0;
5383 char *start_arg = NULL;
5384 unsigned char op = 0;
5386 int internal_argval = 0; /* internal_argval is only useful if !argok */
5387 while ( *RExC_parse && *RExC_parse != ')' ) {
5388 if ( *RExC_parse == ':' ) {
5389 start_arg = RExC_parse + 1;
5395 verb_len = RExC_parse - start_verb;
5398 while ( *RExC_parse && *RExC_parse != ')' )
5400 if ( *RExC_parse != ')' )
5401 vFAIL("Unterminated verb pattern argument");
5402 if ( RExC_parse == start_arg )
5405 if ( *RExC_parse != ')' )
5406 vFAIL("Unterminated verb pattern");
5409 switch ( *start_verb ) {
5410 case 'A': /* (*ACCEPT) */
5411 if ( memEQs(start_verb,verb_len,"ACCEPT") ) {
5413 internal_argval = RExC_nestroot;
5416 case 'C': /* (*COMMIT) */
5417 if ( memEQs(start_verb,verb_len,"COMMIT") )
5420 case 'F': /* (*FAIL) */
5421 if ( verb_len==1 || memEQs(start_verb,verb_len,"FAIL") ) {
5426 case ':': /* (*:NAME) */
5427 case 'M': /* (*MARK:NAME) */
5428 if ( verb_len==0 || memEQs(start_verb,verb_len,"MARK") ) {
5433 case 'P': /* (*PRUNE) */
5434 if ( memEQs(start_verb,verb_len,"PRUNE") )
5437 case 'S': /* (*SKIP) */
5438 if ( memEQs(start_verb,verb_len,"SKIP") )
5441 case 'T': /* (*THEN) */
5442 /* [19:06] <TimToady> :: is then */
5443 if ( memEQs(start_verb,verb_len,"THEN") ) {
5445 RExC_seen |= REG_SEEN_CUTGROUP;
5451 vFAIL3("Unknown verb pattern '%.*s'",
5452 verb_len, start_verb);
5455 if ( start_arg && internal_argval ) {
5456 vFAIL3("Verb pattern '%.*s' may not have an argument",
5457 verb_len, start_verb);
5458 } else if ( argok < 0 && !start_arg ) {
5459 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
5460 verb_len, start_verb);
5462 ret = reganode(pRExC_state, op, internal_argval);
5463 if ( ! internal_argval && ! SIZE_ONLY ) {
5465 SV *sv = newSVpvn( start_arg, RExC_parse - start_arg);
5466 ARG(ret) = add_data( pRExC_state, 1, "S" );
5467 RExC_rxi->data->data[ARG(ret)]=(void*)sv;
5474 if (!internal_argval)
5475 RExC_seen |= REG_SEEN_VERBARG;
5476 } else if ( start_arg ) {
5477 vFAIL3("Verb pattern '%.*s' may not have an argument",
5478 verb_len, start_verb);
5480 ret = reg_node(pRExC_state, op);
5482 nextchar(pRExC_state);
5485 if (*RExC_parse == '?') { /* (?...) */
5486 bool is_logical = 0;
5487 const char * const seqstart = RExC_parse;
5490 paren = *RExC_parse++;
5491 ret = NULL; /* For look-ahead/behind. */
5494 case 'P': /* (?P...) variants for those used to PCRE/Python */
5495 paren = *RExC_parse++;
5496 if ( paren == '<') /* (?P<...>) named capture */
5498 else if (paren == '>') { /* (?P>name) named recursion */
5499 goto named_recursion;
5501 else if (paren == '=') { /* (?P=...) named backref */
5502 /* this pretty much dupes the code for \k<NAME> in regatom(), if
5503 you change this make sure you change that */
5504 char* name_start = RExC_parse;
5506 SV *sv_dat = reg_scan_name(pRExC_state,
5507 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5508 if (RExC_parse == name_start || *RExC_parse != ')')
5509 vFAIL2("Sequence %.3s... not terminated",parse_start);
5512 num = add_data( pRExC_state, 1, "S" );
5513 RExC_rxi->data->data[num]=(void*)sv_dat;
5514 SvREFCNT_inc_simple_void(sv_dat);
5517 ret = reganode(pRExC_state,
5518 (U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
5522 Set_Node_Offset(ret, parse_start+1);
5523 Set_Node_Cur_Length(ret); /* MJD */
5525 nextchar(pRExC_state);
5529 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5531 case '<': /* (?<...) */
5532 if (*RExC_parse == '!')
5534 else if (*RExC_parse != '=')
5540 case '\'': /* (?'...') */
5541 name_start= RExC_parse;
5542 svname = reg_scan_name(pRExC_state,
5543 SIZE_ONLY ? /* reverse test from the others */
5544 REG_RSN_RETURN_NAME :
5545 REG_RSN_RETURN_NULL);
5546 if (RExC_parse == name_start) {
5548 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5551 if (*RExC_parse != paren)
5552 vFAIL2("Sequence (?%c... not terminated",
5553 paren=='>' ? '<' : paren);
5557 if (!svname) /* shouldnt happen */
5559 "panic: reg_scan_name returned NULL");
5560 if (!RExC_paren_names) {
5561 RExC_paren_names= newHV();
5562 sv_2mortal((SV*)RExC_paren_names);
5564 RExC_paren_name_list= newAV();
5565 sv_2mortal((SV*)RExC_paren_name_list);
5568 he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
5570 sv_dat = HeVAL(he_str);
5572 /* croak baby croak */
5574 "panic: paren_name hash element allocation failed");
5575 } else if ( SvPOK(sv_dat) ) {
5576 /* (?|...) can mean we have dupes so scan to check
5577 its already been stored. Maybe a flag indicating
5578 we are inside such a construct would be useful,
5579 but the arrays are likely to be quite small, so
5580 for now we punt -- dmq */
5581 IV count = SvIV(sv_dat);
5582 I32 *pv = (I32*)SvPVX(sv_dat);
5584 for ( i = 0 ; i < count ; i++ ) {
5585 if ( pv[i] == RExC_npar ) {
5591 pv = (I32*)SvGROW(sv_dat, SvCUR(sv_dat) + sizeof(I32)+1);
5592 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
5593 pv[count] = RExC_npar;
5597 (void)SvUPGRADE(sv_dat,SVt_PVNV);
5598 sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32));
5603 if (!av_store(RExC_paren_name_list, RExC_npar, SvREFCNT_inc(svname)))
5604 SvREFCNT_dec(svname);
5607 /*sv_dump(sv_dat);*/
5609 nextchar(pRExC_state);
5611 goto capturing_parens;
5613 RExC_seen |= REG_SEEN_LOOKBEHIND;
5615 case '=': /* (?=...) */
5616 case '!': /* (?!...) */
5617 RExC_seen_zerolen++;
5618 if (*RExC_parse == ')') {
5619 ret=reg_node(pRExC_state, OPFAIL);
5620 nextchar(pRExC_state);
5624 case '|': /* (?|...) */
5625 /* branch reset, behave like a (?:...) except that
5626 buffers in alternations share the same numbers */
5628 after_freeze = freeze_paren = RExC_npar;
5630 case ':': /* (?:...) */
5631 case '>': /* (?>...) */
5633 case '$': /* (?$...) */
5634 case '@': /* (?@...) */
5635 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
5637 case '#': /* (?#...) */
5638 while (*RExC_parse && *RExC_parse != ')')
5640 if (*RExC_parse != ')')
5641 FAIL("Sequence (?#... not terminated");
5642 nextchar(pRExC_state);
5645 case '0' : /* (?0) */
5646 case 'R' : /* (?R) */
5647 if (*RExC_parse != ')')
5648 FAIL("Sequence (?R) not terminated");
5649 ret = reg_node(pRExC_state, GOSTART);
5650 *flagp |= POSTPONED;
5651 nextchar(pRExC_state);
5654 { /* named and numeric backreferences */
5656 case '&': /* (?&NAME) */
5657 parse_start = RExC_parse - 1;
5660 SV *sv_dat = reg_scan_name(pRExC_state,
5661 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5662 num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
5664 goto gen_recurse_regop;
5667 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
5669 vFAIL("Illegal pattern");
5671 goto parse_recursion;
5673 case '-': /* (?-1) */
5674 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
5675 RExC_parse--; /* rewind to let it be handled later */
5679 case '1': case '2': case '3': case '4': /* (?1) */
5680 case '5': case '6': case '7': case '8': case '9':
5683 num = atoi(RExC_parse);
5684 parse_start = RExC_parse - 1; /* MJD */
5685 if (*RExC_parse == '-')
5687 while (isDIGIT(*RExC_parse))
5689 if (*RExC_parse!=')')
5690 vFAIL("Expecting close bracket");
5693 if ( paren == '-' ) {
5695 Diagram of capture buffer numbering.
5696 Top line is the normal capture buffer numbers
5697 Botton line is the negative indexing as from
5701 /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
5705 num = RExC_npar + num;
5708 vFAIL("Reference to nonexistent group");
5710 } else if ( paren == '+' ) {
5711 num = RExC_npar + num - 1;
5714 ret = reganode(pRExC_state, GOSUB, num);
5716 if (num > (I32)RExC_rx->nparens) {
5718 vFAIL("Reference to nonexistent group");
5720 ARG2L_SET( ret, RExC_recurse_count++);
5722 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5723 "Recurse #%"UVuf" to %"IVdf"\n", (UV)ARG(ret), (IV)ARG2L(ret)));
5727 RExC_seen |= REG_SEEN_RECURSE;
5728 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
5729 Set_Node_Offset(ret, parse_start); /* MJD */
5731 *flagp |= POSTPONED;
5732 nextchar(pRExC_state);
5734 } /* named and numeric backreferences */
5737 case '?': /* (??...) */
5739 if (*RExC_parse != '{') {
5741 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5744 *flagp |= POSTPONED;
5745 paren = *RExC_parse++;
5747 case '{': /* (?{...}) */
5752 char *s = RExC_parse;
5754 RExC_seen_zerolen++;
5755 RExC_seen |= REG_SEEN_EVAL;
5756 while (count && (c = *RExC_parse)) {
5767 if (*RExC_parse != ')') {
5769 vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
5773 OP_4tree *sop, *rop;
5774 SV * const sv = newSVpvn(s, RExC_parse - 1 - s);
5777 Perl_save_re_context(aTHX);
5778 rop = sv_compile_2op(sv, &sop, "re", &pad);
5779 sop->op_private |= OPpREFCOUNTED;
5780 /* re_dup will OpREFCNT_inc */
5781 OpREFCNT_set(sop, 1);
5784 n = add_data(pRExC_state, 3, "nop");
5785 RExC_rxi->data->data[n] = (void*)rop;
5786 RExC_rxi->data->data[n+1] = (void*)sop;
5787 RExC_rxi->data->data[n+2] = (void*)pad;
5790 else { /* First pass */
5791 if (PL_reginterp_cnt < ++RExC_seen_evals
5793 /* No compiled RE interpolated, has runtime
5794 components ===> unsafe. */
5795 FAIL("Eval-group not allowed at runtime, use re 'eval'");
5796 if (PL_tainting && PL_tainted)
5797 FAIL("Eval-group in insecure regular expression");
5798 #if PERL_VERSION > 8
5799 if (IN_PERL_COMPILETIME)
5804 nextchar(pRExC_state);
5806 ret = reg_node(pRExC_state, LOGICAL);
5809 REGTAIL(pRExC_state, ret, reganode(pRExC_state, EVAL, n));
5810 /* deal with the length of this later - MJD */
5813 ret = reganode(pRExC_state, EVAL, n);
5814 Set_Node_Length(ret, RExC_parse - parse_start + 1);
5815 Set_Node_Offset(ret, parse_start);
5818 case '(': /* (?(?{...})...) and (?(?=...)...) */
5821 if (RExC_parse[0] == '?') { /* (?(?...)) */
5822 if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
5823 || RExC_parse[1] == '<'
5824 || RExC_parse[1] == '{') { /* Lookahead or eval. */
5827 ret = reg_node(pRExC_state, LOGICAL);
5830 REGTAIL(pRExC_state, ret, reg(pRExC_state, 1, &flag,depth+1));
5834 else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
5835 || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
5837 char ch = RExC_parse[0] == '<' ? '>' : '\'';
5838 char *name_start= RExC_parse++;
5840 SV *sv_dat=reg_scan_name(pRExC_state,
5841 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5842 if (RExC_parse == name_start || *RExC_parse != ch)
5843 vFAIL2("Sequence (?(%c... not terminated",
5844 (ch == '>' ? '<' : ch));
5847 num = add_data( pRExC_state, 1, "S" );
5848 RExC_rxi->data->data[num]=(void*)sv_dat;
5849 SvREFCNT_inc_simple_void(sv_dat);
5851 ret = reganode(pRExC_state,NGROUPP,num);
5852 goto insert_if_check_paren;
5854 else if (RExC_parse[0] == 'D' &&
5855 RExC_parse[1] == 'E' &&
5856 RExC_parse[2] == 'F' &&
5857 RExC_parse[3] == 'I' &&
5858 RExC_parse[4] == 'N' &&
5859 RExC_parse[5] == 'E')
5861 ret = reganode(pRExC_state,DEFINEP,0);
5864 goto insert_if_check_paren;
5866 else if (RExC_parse[0] == 'R') {
5869 if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
5870 parno = atoi(RExC_parse++);
5871 while (isDIGIT(*RExC_parse))
5873 } else if (RExC_parse[0] == '&') {
5876 sv_dat = reg_scan_name(pRExC_state,
5877 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5878 parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
5880 ret = reganode(pRExC_state,INSUBP,parno);
5881 goto insert_if_check_paren;
5883 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
5886 parno = atoi(RExC_parse++);
5888 while (isDIGIT(*RExC_parse))
5890 ret = reganode(pRExC_state, GROUPP, parno);
5892 insert_if_check_paren:
5893 if ((c = *nextchar(pRExC_state)) != ')')
5894 vFAIL("Switch condition not recognized");
5896 REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
5897 br = regbranch(pRExC_state, &flags, 1,depth+1);
5899 br = reganode(pRExC_state, LONGJMP, 0);
5901 REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
5902 c = *nextchar(pRExC_state);
5907 vFAIL("(?(DEFINE)....) does not allow branches");
5908 lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
5909 regbranch(pRExC_state, &flags, 1,depth+1);
5910 REGTAIL(pRExC_state, ret, lastbr);
5913 c = *nextchar(pRExC_state);
5918 vFAIL("Switch (?(condition)... contains too many branches");
5919 ender = reg_node(pRExC_state, TAIL);
5920 REGTAIL(pRExC_state, br, ender);
5922 REGTAIL(pRExC_state, lastbr, ender);
5923 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
5926 REGTAIL(pRExC_state, ret, ender);
5927 RExC_size++; /* XXX WHY do we need this?!!
5928 For large programs it seems to be required
5929 but I can't figure out why. -- dmq*/
5933 vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
5937 RExC_parse--; /* for vFAIL to print correctly */
5938 vFAIL("Sequence (? incomplete");
5942 parse_flags: /* (?i) */
5944 U32 posflags = 0, negflags = 0;
5945 U32 *flagsp = &posflags;
5947 while (*RExC_parse) {
5948 /* && strchr("iogcmsx", *RExC_parse) */
5949 /* (?g), (?gc) and (?o) are useless here
5950 and must be globally applied -- japhy */
5951 switch (*RExC_parse) {
5952 CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp);
5953 case ONCE_PAT_MOD: /* 'o' */
5954 case GLOBAL_PAT_MOD: /* 'g' */
5955 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5956 const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
5957 if (! (wastedflags & wflagbit) ) {
5958 wastedflags |= wflagbit;
5961 "Useless (%s%c) - %suse /%c modifier",
5962 flagsp == &negflags ? "?-" : "?",
5964 flagsp == &negflags ? "don't " : "",
5971 case CONTINUE_PAT_MOD: /* 'c' */
5972 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5973 if (! (wastedflags & WASTED_C) ) {
5974 wastedflags |= WASTED_GC;
5977 "Useless (%sc) - %suse /gc modifier",
5978 flagsp == &negflags ? "?-" : "?",
5979 flagsp == &negflags ? "don't " : ""
5984 case KEEPCOPY_PAT_MOD: /* 'p' */
5985 if (flagsp == &negflags) {
5986 if (SIZE_ONLY && ckWARN(WARN_REGEXP))
5987 vWARN(RExC_parse + 1,"Useless use of (?-p)");
5989 *flagsp |= RXf_PMf_KEEPCOPY;
5993 if (flagsp == &negflags) {
5995 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5999 wastedflags = 0; /* reset so (?g-c) warns twice */
6005 RExC_flags |= posflags;
6006 RExC_flags &= ~negflags;
6008 oregflags |= posflags;
6009 oregflags &= ~negflags;
6011 nextchar(pRExC_state);
6022 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
6027 }} /* one for the default block, one for the switch */
6034 ret = reganode(pRExC_state, OPEN, parno);
6037 RExC_nestroot = parno;
6038 if (RExC_seen & REG_SEEN_RECURSE
6039 && !RExC_open_parens[parno-1])
6041 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
6042 "Setting open paren #%"IVdf" to %d\n",
6043 (IV)parno, REG_NODE_NUM(ret)));
6044 RExC_open_parens[parno-1]= ret;
6047 Set_Node_Length(ret, 1); /* MJD */
6048 Set_Node_Offset(ret, RExC_parse); /* MJD */
6056 /* Pick up the branches, linking them together. */
6057 parse_start = RExC_parse; /* MJD */
6058 br = regbranch(pRExC_state, &flags, 1,depth+1);
6059 /* branch_len = (paren != 0); */
6063 if (*RExC_parse == '|') {
6064 if (!SIZE_ONLY && RExC_extralen) {
6065 reginsert(pRExC_state, BRANCHJ, br, depth+1);
6068 reginsert(pRExC_state, BRANCH, br, depth+1);
6069 Set_Node_Length(br, paren != 0);
6070 Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
6074 RExC_extralen += 1; /* For BRANCHJ-BRANCH. */
6076 else if (paren == ':') {
6077 *flagp |= flags&SIMPLE;
6079 if (is_open) { /* Starts with OPEN. */
6080 REGTAIL(pRExC_state, ret, br); /* OPEN -> first. */
6082 else if (paren != '?') /* Not Conditional */
6084 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
6086 while (*RExC_parse == '|') {
6087 if (!SIZE_ONLY && RExC_extralen) {
6088 ender = reganode(pRExC_state, LONGJMP,0);
6089 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
6092 RExC_extralen += 2; /* Account for LONGJMP. */
6093 nextchar(pRExC_state);
6095 if (RExC_npar > after_freeze)
6096 after_freeze = RExC_npar;
6097 RExC_npar = freeze_paren;
6099 br = regbranch(pRExC_state, &flags, 0, depth+1);
6103 REGTAIL(pRExC_state, lastbr, br); /* BRANCH -> BRANCH. */
6105 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
6108 if (have_branch || paren != ':') {
6109 /* Make a closing node, and hook it on the end. */
6112 ender = reg_node(pRExC_state, TAIL);
6115 ender = reganode(pRExC_state, CLOSE, parno);
6116 if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
6117 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
6118 "Setting close paren #%"IVdf" to %d\n",
6119 (IV)parno, REG_NODE_NUM(ender)));
6120 RExC_close_parens[parno-1]= ender;
6121 if (RExC_nestroot == parno)
6124 Set_Node_Offset(ender,RExC_parse+1); /* MJD */
6125 Set_Node_Length(ender,1); /* MJD */
6131 *flagp &= ~HASWIDTH;
6134 ender = reg_node(pRExC_state, SUCCEED);
6137 ender = reg_node(pRExC_state, END);
6139 assert(!RExC_opend); /* there can only be one! */
6144 REGTAIL(pRExC_state, lastbr, ender);
6146 if (have_branch && !SIZE_ONLY) {
6148 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
6150 /* Hook the tails of the branches to the closing node. */
6151 for (br = ret; br; br = regnext(br)) {
6152 const U8 op = PL_regkind[OP(br)];
6154 REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
6156 else if (op == BRANCHJ) {
6157 REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
6165 static const char parens[] = "=!<,>";
6167 if (paren && (p = strchr(parens, paren))) {
6168 U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
6169 int flag = (p - parens) > 1;
6172 node = SUSPEND, flag = 0;
6173 reginsert(pRExC_state, node,ret, depth+1);
6174 Set_Node_Cur_Length(ret);
6175 Set_Node_Offset(ret, parse_start + 1);
6177 REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
6181 /* Check for proper termination. */
6183 RExC_flags = oregflags;
6184 if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
6185 RExC_parse = oregcomp_parse;
6186 vFAIL("Unmatched (");
6189 else if (!paren && RExC_parse < RExC_end) {
6190 if (*RExC_parse == ')') {
6192 vFAIL("Unmatched )");
6195 FAIL("Junk on end of regexp"); /* "Can't happen". */
6199 RExC_npar = after_freeze;
6204 - regbranch - one alternative of an | operator
6206 * Implements the concatenation operator.
6209 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
6212 register regnode *ret;
6213 register regnode *chain = NULL;
6214 register regnode *latest;
6215 I32 flags = 0, c = 0;
6216 GET_RE_DEBUG_FLAGS_DECL;
6217 DEBUG_PARSE("brnc");
6222 if (!SIZE_ONLY && RExC_extralen)
6223 ret = reganode(pRExC_state, BRANCHJ,0);
6225 ret = reg_node(pRExC_state, BRANCH);
6226 Set_Node_Length(ret, 1);
6230 if (!first && SIZE_ONLY)
6231 RExC_extralen += 1; /* BRANCHJ */
6233 *flagp = WORST; /* Tentatively. */
6236 nextchar(pRExC_state);
6237 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
6239 latest = regpiece(pRExC_state, &flags,depth+1);
6240 if (latest == NULL) {
6241 if (flags & TRYAGAIN)
6245 else if (ret == NULL)
6247 *flagp |= flags&(HASWIDTH|POSTPONED);
6248 if (chain == NULL) /* First piece. */
6249 *flagp |= flags&SPSTART;
6252 REGTAIL(pRExC_state, chain, latest);
6257 if (chain == NULL) { /* Loop ran zero times. */
6258 chain = reg_node(pRExC_state, NOTHING);
6263 *flagp |= flags&SIMPLE;
6270 - regpiece - something followed by possible [*+?]
6272 * Note that the branching code sequences used for ? and the general cases
6273 * of * and + are somewhat optimized: they use the same NOTHING node as
6274 * both the endmarker for their branch list and the body of the last branch.
6275 * It might seem that this node could be dispensed with entirely, but the
6276 * endmarker role is not redundant.
6279 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
6282 register regnode *ret;
6284 register char *next;
6286 const char * const origparse = RExC_parse;
6288 I32 max = REG_INFTY;
6290 const char *maxpos = NULL;
6291 GET_RE_DEBUG_FLAGS_DECL;
6292 DEBUG_PARSE("piec");
6294 ret = regatom(pRExC_state, &flags,depth+1);
6296 if (flags & TRYAGAIN)
6303 if (op == '{' && regcurly(RExC_parse)) {
6305 parse_start = RExC_parse; /* MJD */
6306 next = RExC_parse + 1;
6307 while (isDIGIT(*next) || *next == ',') {
6316 if (*next == '}') { /* got one */
6320 min = atoi(RExC_parse);
6324 maxpos = RExC_parse;
6326 if (!max && *maxpos != '0')
6327 max = REG_INFTY; /* meaning "infinity" */
6328 else if (max >= REG_INFTY)
6329 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
6331 nextchar(pRExC_state);
6334 if ((flags&SIMPLE)) {
6335 RExC_naughty += 2 + RExC_naughty / 2;
6336 reginsert(pRExC_state, CURLY, ret, depth+1);
6337 Set_Node_Offset(ret, parse_start+1); /* MJD */
6338 Set_Node_Cur_Length(ret);
6341 regnode * const w = reg_node(pRExC_state, WHILEM);
6344 REGTAIL(pRExC_state, ret, w);
6345 if (!SIZE_ONLY && RExC_extralen) {
6346 reginsert(pRExC_state, LONGJMP,ret, depth+1);
6347 reginsert(pRExC_state, NOTHING,ret, depth+1);
6348 NEXT_OFF(ret) = 3; /* Go over LONGJMP. */
6350 reginsert(pRExC_state, CURLYX,ret, depth+1);
6352 Set_Node_Offset(ret, parse_start+1);
6353 Set_Node_Length(ret,
6354 op == '{' ? (RExC_parse - parse_start) : 1);
6356 if (!SIZE_ONLY && RExC_extralen)
6357 NEXT_OFF(ret) = 3; /* Go over NOTHING to LONGJMP. */
6358 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
6360 RExC_whilem_seen++, RExC_extralen += 3;
6361 RExC_naughty += 4 + RExC_naughty; /* compound interest */
6369 if (max && max < min)
6370 vFAIL("Can't do {n,m} with n > m");
6372 ARG1_SET(ret, (U16)min);
6373 ARG2_SET(ret, (U16)max);
6385 #if 0 /* Now runtime fix should be reliable. */
6387 /* if this is reinstated, don't forget to put this back into perldiag:
6389 =item Regexp *+ operand could be empty at {#} in regex m/%s/
6391 (F) The part of the regexp subject to either the * or + quantifier
6392 could match an empty string. The {#} shows in the regular
6393 expression about where the problem was discovered.
6397 if (!(flags&HASWIDTH) && op != '?')
6398 vFAIL("Regexp *+ operand could be empty");
6401 parse_start = RExC_parse;
6402 nextchar(pRExC_state);
6404 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
6406 if (op == '*' && (flags&SIMPLE)) {
6407 reginsert(pRExC_state, STAR, ret, depth+1);
6411 else if (op == '*') {
6415 else if (op == '+' && (flags&SIMPLE)) {
6416 reginsert(pRExC_state, PLUS, ret, depth+1);
6420 else if (op == '+') {
6424 else if (op == '?') {
6429 if (!SIZE_ONLY && !(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3 && ckWARN(WARN_REGEXP)) {
6431 "%.*s matches null string many times",
6432 (int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
6436 if (RExC_parse < RExC_end && *RExC_parse == '?') {
6437 nextchar(pRExC_state);
6438 reginsert(pRExC_state, MINMOD, ret, depth+1);
6439 REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
6441 #ifndef REG_ALLOW_MINMOD_SUSPEND
6444 if (RExC_parse < RExC_end && *RExC_parse == '+') {
6446 nextchar(pRExC_state);
6447 ender = reg_node(pRExC_state, SUCCEED);
6448 REGTAIL(pRExC_state, ret, ender);
6449 reginsert(pRExC_state, SUSPEND, ret, depth+1);
6451 ender = reg_node(pRExC_state, TAIL);
6452 REGTAIL(pRExC_state, ret, ender);
6456 if (RExC_parse < RExC_end && ISMULT2(RExC_parse)) {
6458 vFAIL("Nested quantifiers");
6465 /* reg_namedseq(pRExC_state,UVp)
6467 This is expected to be called by a parser routine that has
6468 recognized'\N' and needs to handle the rest. RExC_parse is
6469 expected to point at the first char following the N at the time
6472 If valuep is non-null then it is assumed that we are parsing inside
6473 of a charclass definition and the first codepoint in the resolved
6474 string is returned via *valuep and the routine will return NULL.
6475 In this mode if a multichar string is returned from the charnames
6476 handler a warning will be issued, and only the first char in the
6477 sequence will be examined. If the string returned is zero length
6478 then the value of *valuep is undefined and NON-NULL will
6479 be returned to indicate failure. (This will NOT be a valid pointer
6482 If value is null then it is assumed that we are parsing normal text
6483 and inserts a new EXACT node into the program containing the resolved
6484 string and returns a pointer to the new node. If the string is
6485 zerolength a NOTHING node is emitted.
6487 On success RExC_parse is set to the char following the endbrace.
6488 Parsing failures will generate a fatal errorvia vFAIL(...)
6490 NOTE: We cache all results from the charnames handler locally in
6491 the RExC_charnames hash (created on first use) to prevent a charnames
6492 handler from playing silly-buggers and returning a short string and
6493 then a long string for a given pattern. Since the regexp program
6494 size is calculated during an initial parse this would result
6495 in a buffer overrun so we cache to prevent the charname result from
6496 changing during the course of the parse.
6500 S_reg_namedseq(pTHX_ RExC_state_t *pRExC_state, UV *valuep)
6502 char * name; /* start of the content of the name */
6503 char * endbrace; /* endbrace following the name */
6506 STRLEN len; /* this has various purposes throughout the code */
6507 bool cached = 0; /* if this is true then we shouldn't refcount dev sv_str */
6508 regnode *ret = NULL;
6510 if (*RExC_parse != '{') {
6511 vFAIL("Missing braces on \\N{}");
6513 name = RExC_parse+1;
6514 endbrace = strchr(RExC_parse, '}');
6517 vFAIL("Missing right brace on \\N{}");
6519 RExC_parse = endbrace + 1;
6522 /* RExC_parse points at the beginning brace,
6523 endbrace points at the last */
6524 if ( name[0]=='U' && name[1]=='+' ) {
6525 /* its a "Unicode hex" notation {U+89AB} */
6526 I32 fl = PERL_SCAN_ALLOW_UNDERSCORES
6527 | PERL_SCAN_DISALLOW_PREFIX
6528 | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
6531 len = (STRLEN)(endbrace - name - 2);
6532 cp = grok_hex(name + 2, &len, &fl, NULL);
6533 if ( len != (STRLEN)(endbrace - name - 2) ) {
6543 sv_str= newSVpvn(&string, 1);
6545 /* fetch the charnames handler for this scope */
6546 HV * const table = GvHV(PL_hintgv);
6548 hv_fetchs(table, "charnames", FALSE) :
6550 SV *cv= cvp ? *cvp : NULL;
6553 /* create an SV with the name as argument */
6554 sv_name = newSVpvn(name, endbrace - name);
6556 if (!table || !(PL_hints & HINT_LOCALIZE_HH)) {
6557 vFAIL2("Constant(\\N{%s}) unknown: "
6558 "(possibly a missing \"use charnames ...\")",
6561 if (!cvp || !SvOK(*cvp)) { /* when $^H{charnames} = undef; */
6562 vFAIL2("Constant(\\N{%s}): "
6563 "$^H{charnames} is not defined",SvPVX(sv_name));
6568 if (!RExC_charnames) {
6569 /* make sure our cache is allocated */
6570 RExC_charnames = newHV();
6571 sv_2mortal((SV*)RExC_charnames);
6573 /* see if we have looked this one up before */
6574 he_str = hv_fetch_ent( RExC_charnames, sv_name, 0, 0 );
6576 sv_str = HeVAL(he_str);
6589 count= call_sv(cv, G_SCALAR);
6591 if (count == 1) { /* XXXX is this right? dmq */
6593 SvREFCNT_inc_simple_void(sv_str);
6601 if ( !sv_str || !SvOK(sv_str) ) {
6602 vFAIL2("Constant(\\N{%s}): Call to &{$^H{charnames}} "
6603 "did not return a defined value",SvPVX(sv_name));
6605 if (hv_store_ent( RExC_charnames, sv_name, sv_str, 0))
6610 char *p = SvPV(sv_str, len);
6613 if ( SvUTF8(sv_str) ) {
6614 *valuep = utf8_to_uvchr((U8*)p, &numlen);
6618 We have to turn on utf8 for high bit chars otherwise
6619 we get failures with
6621 "ss" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
6622 "SS" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
6624 This is different from what \x{} would do with the same
6625 codepoint, where the condition is > 0xFF.
6632 /* warn if we havent used the whole string? */
6634 if (numlen<len && SIZE_ONLY && ckWARN(WARN_REGEXP)) {
6636 "Ignoring excess chars from \\N{%s} in character class",
6640 } else if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
6642 "Ignoring zero length \\N{%s} in character class",
6647 SvREFCNT_dec(sv_name);
6649 SvREFCNT_dec(sv_str);
6650 return len ? NULL : (regnode *)&len;
6651 } else if(SvCUR(sv_str)) {
6657 char * parse_start = name-3; /* needed for the offsets */
6659 GET_RE_DEBUG_FLAGS_DECL; /* needed for the offsets */
6661 ret = reg_node(pRExC_state,
6662 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
6665 if ( RExC_utf8 && !SvUTF8(sv_str) ) {
6666 sv_utf8_upgrade(sv_str);
6667 } else if ( !RExC_utf8 && SvUTF8(sv_str) ) {
6671 p = SvPV(sv_str, len);
6673 /* len is the length written, charlen is the size the char read */
6674 for ( len = 0; p < pend; p += charlen ) {
6676 UV uvc = utf8_to_uvchr((U8*)p, &charlen);
6678 STRLEN foldlen,numlen;
6679 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
6680 uvc = toFOLD_uni(uvc, tmpbuf, &foldlen);
6681 /* Emit all the Unicode characters. */
6683 for (foldbuf = tmpbuf;
6687 uvc = utf8_to_uvchr(foldbuf, &numlen);
6689 const STRLEN unilen = reguni(pRExC_state, uvc, s);
6692 /* In EBCDIC the numlen
6693 * and unilen can differ. */
6695 if (numlen >= foldlen)
6699 break; /* "Can't happen." */
6702 const STRLEN unilen = reguni(pRExC_state, uvc, s);
6714 RExC_size += STR_SZ(len);
6717 RExC_emit += STR_SZ(len);
6719 Set_Node_Cur_Length(ret); /* MJD */
6721 nextchar(pRExC_state);
6723 ret = reg_node(pRExC_state,NOTHING);
6726 SvREFCNT_dec(sv_str);
6729 SvREFCNT_dec(sv_name);
6739 * It returns the code point in utf8 for the value in *encp.
6740 * value: a code value in the source encoding
6741 * encp: a pointer to an Encode object
6743 * If the result from Encode is not a single character,
6744 * it returns U+FFFD (Replacement character) and sets *encp to NULL.
6747 S_reg_recode(pTHX_ const char value, SV **encp)
6750 SV * const sv = newSVpvn_flags(&value, numlen, SVs_TEMP);
6751 const char * const s = *encp ? sv_recode_to_utf8(sv, *encp) : SvPVX(sv);
6752 const STRLEN newlen = SvCUR(sv);
6753 UV uv = UNICODE_REPLACEMENT;
6757 ? utf8n_to_uvchr((U8*)s, newlen, &numlen, UTF8_ALLOW_DEFAULT)
6760 if (!newlen || numlen != newlen) {
6761 uv = UNICODE_REPLACEMENT;
6769 - regatom - the lowest level
6771 Try to identify anything special at the start of the pattern. If there
6772 is, then handle it as required. This may involve generating a single regop,
6773 such as for an assertion; or it may involve recursing, such as to
6774 handle a () structure.
6776 If the string doesn't start with something special then we gobble up
6777 as much literal text as we can.
6779 Once we have been able to handle whatever type of thing started the
6780 sequence, we return.
6782 Note: we have to be careful with escapes, as they can be both literal
6783 and special, and in the case of \10 and friends can either, depending
6784 on context. Specifically there are two seperate switches for handling
6785 escape sequences, with the one for handling literal escapes requiring
6786 a dummy entry for all of the special escapes that are actually handled
6791 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
6794 register regnode *ret = NULL;
6796 char *parse_start = RExC_parse;
6797 GET_RE_DEBUG_FLAGS_DECL;
6798 DEBUG_PARSE("atom");
6799 *flagp = WORST; /* Tentatively. */
6803 switch ((U8)*RExC_parse) {
6805 RExC_seen_zerolen++;
6806 nextchar(pRExC_state);
6807 if (RExC_flags & RXf_PMf_MULTILINE)
6808 ret = reg_node(pRExC_state, MBOL);
6809 else if (RExC_flags & RXf_PMf_SINGLELINE)
6810 ret = reg_node(pRExC_state, SBOL);
6812 ret = reg_node(pRExC_state, BOL);
6813 Set_Node_Length(ret, 1); /* MJD */
6816 nextchar(pRExC_state);
6818 RExC_seen_zerolen++;
6819 if (RExC_flags & RXf_PMf_MULTILINE)
6820 ret = reg_node(pRExC_state, MEOL);
6821 else if (RExC_flags & RXf_PMf_SINGLELINE)
6822 ret = reg_node(pRExC_state, SEOL);
6824 ret = reg_node(pRExC_state, EOL);
6825 Set_Node_Length(ret, 1); /* MJD */
6828 nextchar(pRExC_state);
6829 if (RExC_flags & RXf_PMf_SINGLELINE)
6830 ret = reg_node(pRExC_state, SANY);
6832 ret = reg_node(pRExC_state, REG_ANY);
6833 *flagp |= HASWIDTH|SIMPLE;
6835 Set_Node_Length(ret, 1); /* MJD */
6839 char * const oregcomp_parse = ++RExC_parse;
6840 ret = regclass(pRExC_state,depth+1);
6841 if (*RExC_parse != ']') {
6842 RExC_parse = oregcomp_parse;
6843 vFAIL("Unmatched [");
6845 nextchar(pRExC_state);
6846 *flagp |= HASWIDTH|SIMPLE;
6847 Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
6851 nextchar(pRExC_state);
6852 ret = reg(pRExC_state, 1, &flags,depth+1);
6854 if (flags & TRYAGAIN) {
6855 if (RExC_parse == RExC_end) {
6856 /* Make parent create an empty node if needed. */
6864 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
6868 if (flags & TRYAGAIN) {
6872 vFAIL("Internal urp");
6873 /* Supposed to be caught earlier. */
6876 if (!regcurly(RExC_parse)) {
6885 vFAIL("Quantifier follows nothing");
6893 len=0; /* silence a spurious compiler warning */
6894 if ((cp = what_len_TRICKYFOLD_safe(RExC_parse,RExC_end,UTF,len))) {
6895 *flagp |= HASWIDTH; /* could be SIMPLE too, but needs a handler in regexec.regrepeat */
6896 RExC_parse+=len-1; /* we get one from nextchar() as well. :-( */
6897 ret = reganode(pRExC_state, FOLDCHAR, cp);
6898 Set_Node_Length(ret, 1); /* MJD */
6899 nextchar(pRExC_state); /* kill whitespace under /x */
6907 This switch handles escape sequences that resolve to some kind
6908 of special regop and not to literal text. Escape sequnces that
6909 resolve to literal text are handled below in the switch marked
6912 Every entry in this switch *must* have a corresponding entry
6913 in the literal escape switch. However, the opposite is not
6914 required, as the default for this switch is to jump to the
6915 literal text handling code.
6917 switch ((U8)*++RExC_parse) {
6922 /* Special Escapes */
6924 RExC_seen_zerolen++;
6925 ret = reg_node(pRExC_state, SBOL);
6927 goto finish_meta_pat;
6929 ret = reg_node(pRExC_state, GPOS);
6930 RExC_seen |= REG_SEEN_GPOS;
6932 goto finish_meta_pat;
6934 RExC_seen_zerolen++;
6935 ret = reg_node(pRExC_state, KEEPS);
6937 /* XXX:dmq : disabling in-place substitution seems to
6938 * be necessary here to avoid cases of memory corruption, as
6939 * with: C<$_="x" x 80; s/x\K/y/> -- rgs
6941 RExC_seen |= REG_SEEN_LOOKBEHIND;
6942 goto finish_meta_pat;
6944 ret = reg_node(pRExC_state, SEOL);
6946 RExC_seen_zerolen++; /* Do not optimize RE away */
6947 goto finish_meta_pat;
6949 ret = reg_node(pRExC_state, EOS);
6951 RExC_seen_zerolen++; /* Do not optimize RE away */
6952 goto finish_meta_pat;
6954 ret = reg_node(pRExC_state, CANY);
6955 RExC_seen |= REG_SEEN_CANY;
6956 *flagp |= HASWIDTH|SIMPLE;
6957 goto finish_meta_pat;
6959 ret = reg_node(pRExC_state, CLUMP);
6961 goto finish_meta_pat;
6963 ret = reg_node(pRExC_state, (U8)(LOC ? ALNUML : ALNUM));
6964 *flagp |= HASWIDTH|SIMPLE;
6965 goto finish_meta_pat;
6967 ret = reg_node(pRExC_state, (U8)(LOC ? NALNUML : NALNUM));
6968 *flagp |= HASWIDTH|SIMPLE;
6969 goto finish_meta_pat;
6971 RExC_seen_zerolen++;
6972 RExC_seen |= REG_SEEN_LOOKBEHIND;
6973 ret = reg_node(pRExC_state, (U8)(LOC ? BOUNDL : BOUND));
6975 goto finish_meta_pat;
6977 RExC_seen_zerolen++;
6978 RExC_seen |= REG_SEEN_LOOKBEHIND;
6979 ret = reg_node(pRExC_state, (U8)(LOC ? NBOUNDL : NBOUND));
6981 goto finish_meta_pat;
6983 ret = reg_node(pRExC_state, (U8)(LOC ? SPACEL : SPACE));
6984 *flagp |= HASWIDTH|SIMPLE;
6985 goto finish_meta_pat;
6987 ret = reg_node(pRExC_state, (U8)(LOC ? NSPACEL : NSPACE));
6988 *flagp |= HASWIDTH|SIMPLE;
6989 goto finish_meta_pat;
6991 ret = reg_node(pRExC_state, DIGIT);
6992 *flagp |= HASWIDTH|SIMPLE;
6993 goto finish_meta_pat;
6995 ret = reg_node(pRExC_state, NDIGIT);
6996 *flagp |= HASWIDTH|SIMPLE;
6997 goto finish_meta_pat;
6999 ret = reg_node(pRExC_state, LNBREAK);
7000 *flagp |= HASWIDTH|SIMPLE;
7001 goto finish_meta_pat;
7003 ret = reg_node(pRExC_state, HORIZWS);
7004 *flagp |= HASWIDTH|SIMPLE;
7005 goto finish_meta_pat;
7007 ret = reg_node(pRExC_state, NHORIZWS);
7008 *flagp |= HASWIDTH|SIMPLE;
7009 goto finish_meta_pat;
7011 ret = reg_node(pRExC_state, VERTWS);
7012 *flagp |= HASWIDTH|SIMPLE;
7013 goto finish_meta_pat;
7015 ret = reg_node(pRExC_state, NVERTWS);
7016 *flagp |= HASWIDTH|SIMPLE;
7018 nextchar(pRExC_state);
7019 Set_Node_Length(ret, 2); /* MJD */
7024 char* const oldregxend = RExC_end;
7026 char* parse_start = RExC_parse - 2;
7029 if (RExC_parse[1] == '{') {
7030 /* a lovely hack--pretend we saw [\pX] instead */
7031 RExC_end = strchr(RExC_parse, '}');
7033 const U8 c = (U8)*RExC_parse;
7035 RExC_end = oldregxend;
7036 vFAIL2("Missing right brace on \\%c{}", c);
7041 RExC_end = RExC_parse + 2;
7042 if (RExC_end > oldregxend)
7043 RExC_end = oldregxend;
7047 ret = regclass(pRExC_state,depth+1);
7049 RExC_end = oldregxend;
7052 Set_Node_Offset(ret, parse_start + 2);
7053 Set_Node_Cur_Length(ret);
7054 nextchar(pRExC_state);
7055 *flagp |= HASWIDTH|SIMPLE;
7059 /* Handle \N{NAME} here and not below because it can be
7060 multicharacter. join_exact() will join them up later on.
7061 Also this makes sure that things like /\N{BLAH}+/ and
7062 \N{BLAH} being multi char Just Happen. dmq*/
7064 ret= reg_namedseq(pRExC_state, NULL);
7066 case 'k': /* Handle \k<NAME> and \k'NAME' */
7069 char ch= RExC_parse[1];
7070 if (ch != '<' && ch != '\'' && ch != '{') {
7072 vFAIL2("Sequence %.2s... not terminated",parse_start);
7074 /* this pretty much dupes the code for (?P=...) in reg(), if
7075 you change this make sure you change that */
7076 char* name_start = (RExC_parse += 2);
7078 SV *sv_dat = reg_scan_name(pRExC_state,
7079 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
7080 ch= (ch == '<') ? '>' : (ch == '{') ? '}' : '\'';
7081 if (RExC_parse == name_start || *RExC_parse != ch)
7082 vFAIL2("Sequence %.3s... not terminated",parse_start);
7085 num = add_data( pRExC_state, 1, "S" );
7086 RExC_rxi->data->data[num]=(void*)sv_dat;
7087 SvREFCNT_inc_simple_void(sv_dat);
7091 ret = reganode(pRExC_state,
7092 (U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
7096 /* override incorrect value set in reganode MJD */
7097 Set_Node_Offset(ret, parse_start+1);
7098 Set_Node_Cur_Length(ret); /* MJD */
7099 nextchar(pRExC_state);
7105 case '1': case '2': case '3': case '4':
7106 case '5': case '6': case '7': case '8': case '9':
7109 bool isg = *RExC_parse == 'g';
7114 if (*RExC_parse == '{') {
7118 if (*RExC_parse == '-') {
7122 if (hasbrace && !isDIGIT(*RExC_parse)) {
7123 if (isrel) RExC_parse--;
7125 goto parse_named_seq;
7127 num = atoi(RExC_parse);
7128 if (isg && num == 0)
7129 vFAIL("Reference to invalid group 0");
7131 num = RExC_npar - num;
7133 vFAIL("Reference to nonexistent or unclosed group");
7135 if (!isg && num > 9 && num >= RExC_npar)
7138 char * const parse_start = RExC_parse - 1; /* MJD */
7139 while (isDIGIT(*RExC_parse))
7141 if (parse_start == RExC_parse - 1)
7142 vFAIL("Unterminated \\g... pattern");
7144 if (*RExC_parse != '}')
7145 vFAIL("Unterminated \\g{...} pattern");
7149 if (num > (I32)RExC_rx->nparens)
7150 vFAIL("Reference to nonexistent group");
7153 ret = reganode(pRExC_state,
7154 (U8)(FOLD ? (LOC ? REFFL : REFF) : REF),
7158 /* override incorrect value set in reganode MJD */
7159 Set_Node_Offset(ret, parse_start+1);
7160 Set_Node_Cur_Length(ret); /* MJD */
7162 nextchar(pRExC_state);
7167 if (RExC_parse >= RExC_end)
7168 FAIL("Trailing \\");
7171 /* Do not generate "unrecognized" warnings here, we fall
7172 back into the quick-grab loop below */
7179 if (RExC_flags & RXf_PMf_EXTENDED) {
7180 if ( reg_skipcomment( pRExC_state ) )
7187 register STRLEN len;
7192 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
7194 parse_start = RExC_parse - 1;
7200 ret = reg_node(pRExC_state,
7201 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
7203 for (len = 0, p = RExC_parse - 1;
7204 len < 127 && p < RExC_end;
7207 char * const oldp = p;
7209 if (RExC_flags & RXf_PMf_EXTENDED)
7210 p = regwhite( pRExC_state, p );
7215 if (LOC || !FOLD || !is_TRICKYFOLD_safe(p,RExC_end,UTF))
7216 goto normal_default;
7226 /* Literal Escapes Switch
7228 This switch is meant to handle escape sequences that
7229 resolve to a literal character.
7231 Every escape sequence that represents something
7232 else, like an assertion or a char class, is handled
7233 in the switch marked 'Special Escapes' above in this
7234 routine, but also has an entry here as anything that
7235 isn't explicitly mentioned here will be treated as
7236 an unescaped equivalent literal.
7240 /* These are all the special escapes. */
7244 if (LOC || !FOLD || !is_TRICKYFOLD_safe(p,RExC_end,UTF))
7245 goto normal_default;
7246 case 'A': /* Start assertion */
7247 case 'b': case 'B': /* Word-boundary assertion*/
7248 case 'C': /* Single char !DANGEROUS! */
7249 case 'd': case 'D': /* digit class */
7250 case 'g': case 'G': /* generic-backref, pos assertion */
7251 case 'h': case 'H': /* HORIZWS */
7252 case 'k': case 'K': /* named backref, keep marker */
7253 case 'N': /* named char sequence */
7254 case 'p': case 'P': /* Unicode property */
7255 case 'R': /* LNBREAK */
7256 case 's': case 'S': /* space class */
7257 case 'v': case 'V': /* VERTWS */
7258 case 'w': case 'W': /* word class */
7259 case 'X': /* eXtended Unicode "combining character sequence" */
7260 case 'z': case 'Z': /* End of line/string assertion */
7264 /* Anything after here is an escape that resolves to a
7265 literal. (Except digits, which may or may not)
7284 ender = ASCII_TO_NATIVE('\033');
7288 ender = ASCII_TO_NATIVE('\007');
7293 char* const e = strchr(p, '}');
7297 vFAIL("Missing right brace on \\x{}");
7300 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
7301 | PERL_SCAN_DISALLOW_PREFIX;
7302 STRLEN numlen = e - p - 1;
7303 ender = grok_hex(p + 1, &numlen, &flags, NULL);
7310 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
7312 ender = grok_hex(p, &numlen, &flags, NULL);
7315 if (PL_encoding && ender < 0x100)
7316 goto recode_encoding;
7320 ender = UCHARAT(p++);
7321 ender = toCTRL(ender);
7323 case '0': case '1': case '2': case '3':case '4':
7324 case '5': case '6': case '7': case '8':case '9':
7326 (isDIGIT(p[1]) && atoi(p) >= RExC_npar) ) {
7329 ender = grok_oct(p, &numlen, &flags, NULL);
7336 if (PL_encoding && ender < 0x100)
7337 goto recode_encoding;
7341 SV* enc = PL_encoding;
7342 ender = reg_recode((const char)(U8)ender, &enc);
7343 if (!enc && SIZE_ONLY && ckWARN(WARN_REGEXP))
7344 vWARN(p, "Invalid escape in the specified encoding");
7350 FAIL("Trailing \\");
7353 if (!SIZE_ONLY&& isALPHA(*p) && ckWARN(WARN_REGEXP))
7354 vWARN2(p + 1, "Unrecognized escape \\%c passed through", UCHARAT(p));
7355 goto normal_default;
7360 if (UTF8_IS_START(*p) && UTF) {
7362 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
7363 &numlen, UTF8_ALLOW_DEFAULT);
7370 if ( RExC_flags & RXf_PMf_EXTENDED)
7371 p = regwhite( pRExC_state, p );
7373 /* Prime the casefolded buffer. */
7374 ender = toFOLD_uni(ender, tmpbuf, &foldlen);
7376 if (p < RExC_end && ISMULT2(p)) { /* Back off on ?+*. */
7381 /* Emit all the Unicode characters. */
7383 for (foldbuf = tmpbuf;
7385 foldlen -= numlen) {
7386 ender = utf8_to_uvchr(foldbuf, &numlen);
7388 const STRLEN unilen = reguni(pRExC_state, ender, s);
7391 /* In EBCDIC the numlen
7392 * and unilen can differ. */
7394 if (numlen >= foldlen)
7398 break; /* "Can't happen." */
7402 const STRLEN unilen = reguni(pRExC_state, ender, s);
7411 REGC((char)ender, s++);
7417 /* Emit all the Unicode characters. */
7419 for (foldbuf = tmpbuf;
7421 foldlen -= numlen) {
7422 ender = utf8_to_uvchr(foldbuf, &numlen);
7424 const STRLEN unilen = reguni(pRExC_state, ender, s);
7427 /* In EBCDIC the numlen
7428 * and unilen can differ. */
7430 if (numlen >= foldlen)
7438 const STRLEN unilen = reguni(pRExC_state, ender, s);
7447 REGC((char)ender, s++);
7451 Set_Node_Cur_Length(ret); /* MJD */
7452 nextchar(pRExC_state);
7454 /* len is STRLEN which is unsigned, need to copy to signed */
7457 vFAIL("Internal disaster");
7461 if (len == 1 && UNI_IS_INVARIANT(ender))
7465 RExC_size += STR_SZ(len);
7468 RExC_emit += STR_SZ(len);
7478 S_regwhite( RExC_state_t *pRExC_state, char *p )
7480 const char *e = RExC_end;
7484 else if (*p == '#') {
7493 RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
7501 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
7502 Character classes ([:foo:]) can also be negated ([:^foo:]).
7503 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
7504 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
7505 but trigger failures because they are currently unimplemented. */
7507 #define POSIXCC_DONE(c) ((c) == ':')
7508 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
7509 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
7512 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
7515 I32 namedclass = OOB_NAMEDCLASS;
7517 if (value == '[' && RExC_parse + 1 < RExC_end &&
7518 /* I smell either [: or [= or [. -- POSIX has been here, right? */
7519 POSIXCC(UCHARAT(RExC_parse))) {
7520 const char c = UCHARAT(RExC_parse);
7521 char* const s = RExC_parse++;
7523 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
7525 if (RExC_parse == RExC_end)
7526 /* Grandfather lone [:, [=, [. */
7529 const char* const t = RExC_parse++; /* skip over the c */
7532 if (UCHARAT(RExC_parse) == ']') {
7533 const char *posixcc = s + 1;
7534 RExC_parse++; /* skip over the ending ] */
7537 const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
7538 const I32 skip = t - posixcc;
7540 /* Initially switch on the length of the name. */
7543 if (memEQ(posixcc, "word", 4)) /* this is not POSIX, this is the Perl \w */
7544 namedclass = complement ? ANYOF_NALNUM : ANYOF_ALNUM;
7547 /* Names all of length 5. */
7548 /* alnum alpha ascii blank cntrl digit graph lower
7549 print punct space upper */
7550 /* Offset 4 gives the best switch position. */
7551 switch (posixcc[4]) {
7553 if (memEQ(posixcc, "alph", 4)) /* alpha */
7554 namedclass = complement ? ANYOF_NALPHA : ANYOF_ALPHA;
7557 if (memEQ(posixcc, "spac", 4)) /* space */
7558 namedclass = complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
7561 if (memEQ(posixcc, "grap", 4)) /* graph */
7562 namedclass = complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
7565 if (memEQ(posixcc, "asci", 4)) /* ascii */
7566 namedclass = complement ? ANYOF_NASCII : ANYOF_ASCII;
7569 if (memEQ(posixcc, "blan", 4)) /* blank */
7570 namedclass = complement ? ANYOF_NBLANK : ANYOF_BLANK;
7573 if (memEQ(posixcc, "cntr", 4)) /* cntrl */
7574 namedclass = complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
7577 if (memEQ(posixcc, "alnu", 4)) /* alnum */
7578 namedclass = complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
7581 if (memEQ(posixcc, "lowe", 4)) /* lower */
7582 namedclass = complement ? ANYOF_NLOWER : ANYOF_LOWER;
7583 else if (memEQ(posixcc, "uppe", 4)) /* upper */
7584 namedclass = complement ? ANYOF_NUPPER : ANYOF_UPPER;
7587 if (memEQ(posixcc, "digi", 4)) /* digit */
7588 namedclass = complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
7589 else if (memEQ(posixcc, "prin", 4)) /* print */
7590 namedclass = complement ? ANYOF_NPRINT : ANYOF_PRINT;
7591 else if (memEQ(posixcc, "punc", 4)) /* punct */
7592 namedclass = complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
7597 if (memEQ(posixcc, "xdigit", 6))
7598 namedclass = complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
7602 if (namedclass == OOB_NAMEDCLASS)
7603 Simple_vFAIL3("POSIX class [:%.*s:] unknown",
7605 assert (posixcc[skip] == ':');
7606 assert (posixcc[skip+1] == ']');
7607 } else if (!SIZE_ONLY) {
7608 /* [[=foo=]] and [[.foo.]] are still future. */
7610 /* adjust RExC_parse so the warning shows after
7612 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
7614 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
7617 /* Maternal grandfather:
7618 * "[:" ending in ":" but not in ":]" */
7628 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
7631 if (POSIXCC(UCHARAT(RExC_parse))) {
7632 const char *s = RExC_parse;
7633 const char c = *s++;
7637 if (*s && c == *s && s[1] == ']') {
7638 if (ckWARN(WARN_REGEXP))
7640 "POSIX syntax [%c %c] belongs inside character classes",
7643 /* [[=foo=]] and [[.foo.]] are still future. */
7644 if (POSIXCC_NOTYET(c)) {
7645 /* adjust RExC_parse so the error shows after
7647 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
7649 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
7656 #define _C_C_T_(NAME,TEST,WORD) \
7659 ANYOF_CLASS_SET(ret, ANYOF_##NAME); \
7661 for (value = 0; value < 256; value++) \
7663 ANYOF_BITMAP_SET(ret, value); \
7668 case ANYOF_N##NAME: \
7670 ANYOF_CLASS_SET(ret, ANYOF_N##NAME); \
7672 for (value = 0; value < 256; value++) \
7674 ANYOF_BITMAP_SET(ret, value); \
7680 #define _C_C_T_NOLOC_(NAME,TEST,WORD) \
7682 for (value = 0; value < 256; value++) \
7684 ANYOF_BITMAP_SET(ret, value); \
7688 case ANYOF_N##NAME: \
7689 for (value = 0; value < 256; value++) \
7691 ANYOF_BITMAP_SET(ret, value); \
7697 parse a class specification and produce either an ANYOF node that
7698 matches the pattern or if the pattern matches a single char only and
7699 that char is < 256 and we are case insensitive then we produce an
7704 S_regclass(pTHX_ RExC_state_t *pRExC_state, U32 depth)
7707 register UV nextvalue;
7708 register IV prevvalue = OOB_UNICODE;
7709 register IV range = 0;
7710 UV value = 0; /* XXX:dmq: needs to be referenceable (unfortunately) */
7711 register regnode *ret;
7714 char *rangebegin = NULL;
7715 bool need_class = 0;
7718 bool optimize_invert = TRUE;
7719 AV* unicode_alternate = NULL;
7721 UV literal_endpoint = 0;
7723 UV stored = 0; /* number of chars stored in the class */
7725 regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
7726 case we need to change the emitted regop to an EXACT. */
7727 const char * orig_parse = RExC_parse;
7728 GET_RE_DEBUG_FLAGS_DECL;
7730 PERL_UNUSED_ARG(depth);
7733 DEBUG_PARSE("clas");
7735 /* Assume we are going to generate an ANYOF node. */
7736 ret = reganode(pRExC_state, ANYOF, 0);
7739 ANYOF_FLAGS(ret) = 0;
7741 if (UCHARAT(RExC_parse) == '^') { /* Complement of range. */
7745 ANYOF_FLAGS(ret) |= ANYOF_INVERT;
7749 RExC_size += ANYOF_SKIP;
7750 listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
7753 RExC_emit += ANYOF_SKIP;
7755 ANYOF_FLAGS(ret) |= ANYOF_FOLD;
7757 ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
7758 ANYOF_BITMAP_ZERO(ret);
7759 listsv = newSVpvs("# comment\n");
7762 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
7764 if (!SIZE_ONLY && POSIXCC(nextvalue))
7765 checkposixcc(pRExC_state);
7767 /* allow 1st char to be ] (allowing it to be - is dealt with later) */
7768 if (UCHARAT(RExC_parse) == ']')
7772 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
7776 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
7779 rangebegin = RExC_parse;
7781 value = utf8n_to_uvchr((U8*)RExC_parse,
7782 RExC_end - RExC_parse,
7783 &numlen, UTF8_ALLOW_DEFAULT);
7784 RExC_parse += numlen;
7787 value = UCHARAT(RExC_parse++);
7789 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
7790 if (value == '[' && POSIXCC(nextvalue))
7791 namedclass = regpposixcc(pRExC_state, value);
7792 else if (value == '\\') {
7794 value = utf8n_to_uvchr((U8*)RExC_parse,
7795 RExC_end - RExC_parse,
7796 &numlen, UTF8_ALLOW_DEFAULT);
7797 RExC_parse += numlen;
7800 value = UCHARAT(RExC_parse++);
7801 /* Some compilers cannot handle switching on 64-bit integer
7802 * values, therefore value cannot be an UV. Yes, this will
7803 * be a problem later if we want switch on Unicode.
7804 * A similar issue a little bit later when switching on
7805 * namedclass. --jhi */
7806 switch ((I32)value) {
7807 case 'w': namedclass = ANYOF_ALNUM; break;
7808 case 'W': namedclass = ANYOF_NALNUM; break;
7809 case 's': namedclass = ANYOF_SPACE; break;
7810 case 'S': namedclass = ANYOF_NSPACE; break;
7811 case 'd': namedclass = ANYOF_DIGIT; break;
7812 case 'D': namedclass = ANYOF_NDIGIT; break;
7813 case 'v': namedclass = ANYOF_VERTWS; break;
7814 case 'V': namedclass = ANYOF_NVERTWS; break;
7815 case 'h': namedclass = ANYOF_HORIZWS; break;
7816 case 'H': namedclass = ANYOF_NHORIZWS; break;
7817 case 'N': /* Handle \N{NAME} in class */
7819 /* We only pay attention to the first char of
7820 multichar strings being returned. I kinda wonder
7821 if this makes sense as it does change the behaviour
7822 from earlier versions, OTOH that behaviour was broken
7824 UV v; /* value is register so we cant & it /grrr */
7825 if (reg_namedseq(pRExC_state, &v)) {
7835 if (RExC_parse >= RExC_end)
7836 vFAIL2("Empty \\%c{}", (U8)value);
7837 if (*RExC_parse == '{') {
7838 const U8 c = (U8)value;
7839 e = strchr(RExC_parse++, '}');
7841 vFAIL2("Missing right brace on \\%c{}", c);
7842 while (isSPACE(UCHARAT(RExC_parse)))
7844 if (e == RExC_parse)
7845 vFAIL2("Empty \\%c{}", c);
7847 while (isSPACE(UCHARAT(RExC_parse + n - 1)))
7855 if (UCHARAT(RExC_parse) == '^') {
7858 value = value == 'p' ? 'P' : 'p'; /* toggle */
7859 while (isSPACE(UCHARAT(RExC_parse))) {
7864 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%.*s\n",
7865 (value=='p' ? '+' : '!'), (int)n, RExC_parse);
7868 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
7869 namedclass = ANYOF_MAX; /* no official name, but it's named */
7872 case 'n': value = '\n'; break;
7873 case 'r': value = '\r'; break;
7874 case 't': value = '\t'; break;
7875 case 'f': value = '\f'; break;
7876 case 'b': value = '\b'; break;
7877 case 'e': value = ASCII_TO_NATIVE('\033');break;
7878 case 'a': value = ASCII_TO_NATIVE('\007');break;
7880 if (*RExC_parse == '{') {
7881 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
7882 | PERL_SCAN_DISALLOW_PREFIX;
7883 char * const e = strchr(RExC_parse++, '}');
7885 vFAIL("Missing right brace on \\x{}");
7887 numlen = e - RExC_parse;
7888 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
7892 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
7894 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
7895 RExC_parse += numlen;
7897 if (PL_encoding && value < 0x100)
7898 goto recode_encoding;
7901 value = UCHARAT(RExC_parse++);
7902 value = toCTRL(value);
7904 case '0': case '1': case '2': case '3': case '4':
7905 case '5': case '6': case '7': case '8': case '9':
7909 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
7910 RExC_parse += numlen;
7911 if (PL_encoding && value < 0x100)
7912 goto recode_encoding;
7917 SV* enc = PL_encoding;
7918 value = reg_recode((const char)(U8)value, &enc);
7919 if (!enc && SIZE_ONLY && ckWARN(WARN_REGEXP))
7921 "Invalid escape in the specified encoding");
7925 if (!SIZE_ONLY && isALPHA(value) && ckWARN(WARN_REGEXP))
7927 "Unrecognized escape \\%c in character class passed through",
7931 } /* end of \blah */
7937 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
7939 if (!SIZE_ONLY && !need_class)
7940 ANYOF_CLASS_ZERO(ret);
7944 /* a bad range like a-\d, a-[:digit:] ? */
7947 if (ckWARN(WARN_REGEXP)) {
7949 RExC_parse >= rangebegin ?
7950 RExC_parse - rangebegin : 0;
7952 "False [] range \"%*.*s\"",
7955 if (prevvalue < 256) {
7956 ANYOF_BITMAP_SET(ret, prevvalue);
7957 ANYOF_BITMAP_SET(ret, '-');
7960 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
7961 Perl_sv_catpvf(aTHX_ listsv,
7962 "%04"UVxf"\n%04"UVxf"\n", (UV)prevvalue, (UV) '-');
7966 range = 0; /* this was not a true range */
7972 const char *what = NULL;
7975 if (namedclass > OOB_NAMEDCLASS)
7976 optimize_invert = FALSE;
7977 /* Possible truncation here but in some 64-bit environments
7978 * the compiler gets heartburn about switch on 64-bit values.
7979 * A similar issue a little earlier when switching on value.
7981 switch ((I32)namedclass) {
7982 case _C_C_T_(ALNUM, isALNUM(value), "Word");
7983 case _C_C_T_(ALNUMC, isALNUMC(value), "Alnum");
7984 case _C_C_T_(ALPHA, isALPHA(value), "Alpha");
7985 case _C_C_T_(BLANK, isBLANK(value), "Blank");
7986 case _C_C_T_(CNTRL, isCNTRL(value), "Cntrl");
7987 case _C_C_T_(GRAPH, isGRAPH(value), "Graph");
7988 case _C_C_T_(LOWER, isLOWER(value), "Lower");
7989 case _C_C_T_(PRINT, isPRINT(value), "Print");
7990 case _C_C_T_(PSXSPC, isPSXSPC(value), "Space");
7991 case _C_C_T_(PUNCT, isPUNCT(value), "Punct");
7992 case _C_C_T_(SPACE, isSPACE(value), "SpacePerl");
7993 case _C_C_T_(UPPER, isUPPER(value), "Upper");
7994 case _C_C_T_(XDIGIT, isXDIGIT(value), "XDigit");
7995 case _C_C_T_NOLOC_(VERTWS, is_VERTWS_latin1(&value), "VertSpace");
7996 case _C_C_T_NOLOC_(HORIZWS, is_HORIZWS_latin1(&value), "HorizSpace");
7999 ANYOF_CLASS_SET(ret, ANYOF_ASCII);
8002 for (value = 0; value < 128; value++)
8003 ANYOF_BITMAP_SET(ret, value);
8005 for (value = 0; value < 256; value++) {
8007 ANYOF_BITMAP_SET(ret, value);
8016 ANYOF_CLASS_SET(ret, ANYOF_NASCII);
8019 for (value = 128; value < 256; value++)
8020 ANYOF_BITMAP_SET(ret, value);
8022 for (value = 0; value < 256; value++) {
8023 if (!isASCII(value))
8024 ANYOF_BITMAP_SET(ret, value);
8033 ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
8035 /* consecutive digits assumed */
8036 for (value = '0'; value <= '9'; value++)
8037 ANYOF_BITMAP_SET(ret, value);
8044 ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
8046 /* consecutive digits assumed */
8047 for (value = 0; value < '0'; value++)
8048 ANYOF_BITMAP_SET(ret, value);
8049 for (value = '9' + 1; value < 256; value++)
8050 ANYOF_BITMAP_SET(ret, value);
8056 /* this is to handle \p and \P */
8059 vFAIL("Invalid [::] class");
8063 /* Strings such as "+utf8::isWord\n" */
8064 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::Is%s\n", yesno, what);
8067 ANYOF_FLAGS(ret) |= ANYOF_CLASS;
8070 } /* end of namedclass \blah */
8073 if (prevvalue > (IV)value) /* b-a */ {
8074 const int w = RExC_parse - rangebegin;
8075 Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
8076 range = 0; /* not a valid range */
8080 prevvalue = value; /* save the beginning of the range */
8081 if (*RExC_parse == '-' && RExC_parse+1 < RExC_end &&
8082 RExC_parse[1] != ']') {
8085 /* a bad range like \w-, [:word:]- ? */
8086 if (namedclass > OOB_NAMEDCLASS) {
8087 if (ckWARN(WARN_REGEXP)) {
8089 RExC_parse >= rangebegin ?
8090 RExC_parse - rangebegin : 0;
8092 "False [] range \"%*.*s\"",
8096 ANYOF_BITMAP_SET(ret, '-');
8098 range = 1; /* yeah, it's a range! */
8099 continue; /* but do it the next time */
8103 /* now is the next time */
8104 /*stored += (value - prevvalue + 1);*/
8106 if (prevvalue < 256) {
8107 const IV ceilvalue = value < 256 ? value : 255;
8110 /* In EBCDIC [\x89-\x91] should include
8111 * the \x8e but [i-j] should not. */
8112 if (literal_endpoint == 2 &&
8113 ((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
8114 (isUPPER(prevvalue) && isUPPER(ceilvalue))))
8116 if (isLOWER(prevvalue)) {
8117 for (i = prevvalue; i <= ceilvalue; i++)
8118 if (isLOWER(i) && !ANYOF_BITMAP_TEST(ret,i)) {
8120 ANYOF_BITMAP_SET(ret, i);
8123 for (i = prevvalue; i <= ceilvalue; i++)
8124 if (isUPPER(i) && !ANYOF_BITMAP_TEST(ret,i)) {
8126 ANYOF_BITMAP_SET(ret, i);
8132 for (i = prevvalue; i <= ceilvalue; i++) {
8133 if (!ANYOF_BITMAP_TEST(ret,i)) {
8135 ANYOF_BITMAP_SET(ret, i);
8139 if (value > 255 || UTF) {
8140 const UV prevnatvalue = NATIVE_TO_UNI(prevvalue);
8141 const UV natvalue = NATIVE_TO_UNI(value);
8142 stored+=2; /* can't optimize this class */
8143 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
8144 if (prevnatvalue < natvalue) { /* what about > ? */
8145 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
8146 prevnatvalue, natvalue);
8148 else if (prevnatvalue == natvalue) {
8149 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n", natvalue);
8151 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
8153 const UV f = to_uni_fold(natvalue, foldbuf, &foldlen);
8155 #ifdef EBCDIC /* RD t/uni/fold ff and 6b */
8156 if (RExC_precomp[0] == ':' &&
8157 RExC_precomp[1] == '[' &&
8158 (f == 0xDF || f == 0x92)) {
8159 f = NATIVE_TO_UNI(f);
8162 /* If folding and foldable and a single
8163 * character, insert also the folded version
8164 * to the charclass. */
8166 #ifdef EBCDIC /* RD tunifold ligatures s,t fb05, fb06 */
8167 if ((RExC_precomp[0] == ':' &&
8168 RExC_precomp[1] == '[' &&
8170 (value == 0xFB05 || value == 0xFB06))) ?
8171 foldlen == ((STRLEN)UNISKIP(f) - 1) :
8172 foldlen == (STRLEN)UNISKIP(f) )
8174 if (foldlen == (STRLEN)UNISKIP(f))
8176 Perl_sv_catpvf(aTHX_ listsv,
8179 /* Any multicharacter foldings
8180 * require the following transform:
8181 * [ABCDEF] -> (?:[ABCabcDEFd]|pq|rst)
8182 * where E folds into "pq" and F folds
8183 * into "rst", all other characters
8184 * fold to single characters. We save
8185 * away these multicharacter foldings,
8186 * to be later saved as part of the
8187 * additional "s" data. */
8190 if (!unicode_alternate)
8191 unicode_alternate = newAV();
8192 sv = newSVpvn_utf8((char*)foldbuf, foldlen,
8194 av_push(unicode_alternate, sv);
8198 /* If folding and the value is one of the Greek
8199 * sigmas insert a few more sigmas to make the
8200 * folding rules of the sigmas to work right.
8201 * Note that not all the possible combinations
8202 * are handled here: some of them are handled
8203 * by the standard folding rules, and some of
8204 * them (literal or EXACTF cases) are handled
8205 * during runtime in regexec.c:S_find_byclass(). */
8206 if (value == UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA) {
8207 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
8208 (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA);
8209 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
8210 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
8212 else if (value == UNICODE_GREEK_CAPITAL_LETTER_SIGMA)
8213 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
8214 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
8219 literal_endpoint = 0;
8223 range = 0; /* this range (if it was one) is done now */
8227 ANYOF_FLAGS(ret) |= ANYOF_LARGE;
8229 RExC_size += ANYOF_CLASS_ADD_SKIP;
8231 RExC_emit += ANYOF_CLASS_ADD_SKIP;
8237 /****** !SIZE_ONLY AFTER HERE *********/
8239 if( stored == 1 && (value < 128 || (value < 256 && !UTF))
8240 && !( ANYOF_FLAGS(ret) & ( ANYOF_FLAGS_ALL ^ ANYOF_FOLD ) )
8242 /* optimize single char class to an EXACT node
8243 but *only* when its not a UTF/high char */
8244 const char * cur_parse= RExC_parse;
8245 RExC_emit = (regnode *)orig_emit;
8246 RExC_parse = (char *)orig_parse;
8247 ret = reg_node(pRExC_state,
8248 (U8)((ANYOF_FLAGS(ret) & ANYOF_FOLD) ? EXACTF : EXACT));
8249 RExC_parse = (char *)cur_parse;
8250 *STRING(ret)= (char)value;
8252 RExC_emit += STR_SZ(1);
8255 /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
8256 if ( /* If the only flag is folding (plus possibly inversion). */
8257 ((ANYOF_FLAGS(ret) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD)
8259 for (value = 0; value < 256; ++value) {
8260 if (ANYOF_BITMAP_TEST(ret, value)) {
8261 UV fold = PL_fold[value];
8264 ANYOF_BITMAP_SET(ret, fold);
8267 ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
8270 /* optimize inverted simple patterns (e.g. [^a-z]) */
8271 if (optimize_invert &&
8272 /* If the only flag is inversion. */
8273 (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
8274 for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
8275 ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
8276 ANYOF_FLAGS(ret) = ANYOF_UNICODE_ALL;
8279 AV * const av = newAV();
8281 /* The 0th element stores the character class description
8282 * in its textual form: used later (regexec.c:Perl_regclass_swash())
8283 * to initialize the appropriate swash (which gets stored in
8284 * the 1st element), and also useful for dumping the regnode.
8285 * The 2nd element stores the multicharacter foldings,
8286 * used later (regexec.c:S_reginclass()). */
8287 av_store(av, 0, listsv);
8288 av_store(av, 1, NULL);
8289 av_store(av, 2, (SV*)unicode_alternate);
8290 rv = newRV_noinc((SV*)av);
8291 n = add_data(pRExC_state, 1, "s");
8292 RExC_rxi->data->data[n] = (void*)rv;
8300 /* reg_skipcomment()
8302 Absorbs an /x style # comments from the input stream.
8303 Returns true if there is more text remaining in the stream.
8304 Will set the REG_SEEN_RUN_ON_COMMENT flag if the comment
8305 terminates the pattern without including a newline.
8307 Note its the callers responsibility to ensure that we are
8313 S_reg_skipcomment(pTHX_ RExC_state_t *pRExC_state)
8316 while (RExC_parse < RExC_end)
8317 if (*RExC_parse++ == '\n') {
8322 /* we ran off the end of the pattern without ending
8323 the comment, so we have to add an \n when wrapping */
8324 RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
8332 Advance that parse position, and optionall absorbs
8333 "whitespace" from the inputstream.
8335 Without /x "whitespace" means (?#...) style comments only,
8336 with /x this means (?#...) and # comments and whitespace proper.
8338 Returns the RExC_parse point from BEFORE the scan occurs.
8340 This is the /x friendly way of saying RExC_parse++.
8344 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
8346 char* const retval = RExC_parse++;
8349 if (*RExC_parse == '(' && RExC_parse[1] == '?' &&
8350 RExC_parse[2] == '#') {
8351 while (*RExC_parse != ')') {
8352 if (RExC_parse == RExC_end)
8353 FAIL("Sequence (?#... not terminated");
8359 if (RExC_flags & RXf_PMf_EXTENDED) {
8360 if (isSPACE(*RExC_parse)) {
8364 else if (*RExC_parse == '#') {
8365 if ( reg_skipcomment( pRExC_state ) )
8374 - reg_node - emit a node
8376 STATIC regnode * /* Location. */
8377 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
8380 register regnode *ptr;
8381 regnode * const ret = RExC_emit;
8382 GET_RE_DEBUG_FLAGS_DECL;
8385 SIZE_ALIGN(RExC_size);
8389 if (RExC_emit >= RExC_emit_bound)
8390 Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d", op);
8392 NODE_ALIGN_FILL(ret);
8394 FILL_ADVANCE_NODE(ptr, op);
8395 #ifdef RE_TRACK_PATTERN_OFFSETS
8396 if (RExC_offsets) { /* MJD */
8397 MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n",
8398 "reg_node", __LINE__,
8400 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0]
8401 ? "Overwriting end of array!\n" : "OK",
8402 (UV)(RExC_emit - RExC_emit_start),
8403 (UV)(RExC_parse - RExC_start),
8404 (UV)RExC_offsets[0]));
8405 Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
8413 - reganode - emit a node with an argument
8415 STATIC regnode * /* Location. */
8416 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
8419 register regnode *ptr;
8420 regnode * const ret = RExC_emit;
8421 GET_RE_DEBUG_FLAGS_DECL;
8424 SIZE_ALIGN(RExC_size);
8429 assert(2==regarglen[op]+1);
8431 Anything larger than this has to allocate the extra amount.
8432 If we changed this to be:
8434 RExC_size += (1 + regarglen[op]);
8436 then it wouldn't matter. Its not clear what side effect
8437 might come from that so its not done so far.
8442 if (RExC_emit >= RExC_emit_bound)
8443 Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d", op);
8445 NODE_ALIGN_FILL(ret);
8447 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
8448 #ifdef RE_TRACK_PATTERN_OFFSETS
8449 if (RExC_offsets) { /* MJD */
8450 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
8454 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ?
8455 "Overwriting end of array!\n" : "OK",
8456 (UV)(RExC_emit - RExC_emit_start),
8457 (UV)(RExC_parse - RExC_start),
8458 (UV)RExC_offsets[0]));
8459 Set_Cur_Node_Offset;
8467 - reguni - emit (if appropriate) a Unicode character
8470 S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
8473 return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
8477 - reginsert - insert an operator in front of already-emitted operand
8479 * Means relocating the operand.
8482 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
8485 register regnode *src;
8486 register regnode *dst;
8487 register regnode *place;
8488 const int offset = regarglen[(U8)op];
8489 const int size = NODE_STEP_REGNODE + offset;
8490 GET_RE_DEBUG_FLAGS_DECL;
8491 PERL_UNUSED_ARG(depth);
8492 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
8493 DEBUG_PARSE_FMT("inst"," - %s",PL_reg_name[op]);
8502 if (RExC_open_parens) {
8504 /*DEBUG_PARSE_FMT("inst"," - %"IVdf, (IV)RExC_npar);*/
8505 for ( paren=0 ; paren < RExC_npar ; paren++ ) {
8506 if ( RExC_open_parens[paren] >= opnd ) {
8507 /*DEBUG_PARSE_FMT("open"," - %d",size);*/
8508 RExC_open_parens[paren] += size;
8510 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
8512 if ( RExC_close_parens[paren] >= opnd ) {
8513 /*DEBUG_PARSE_FMT("close"," - %d",size);*/
8514 RExC_close_parens[paren] += size;
8516 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
8521 while (src > opnd) {
8522 StructCopy(--src, --dst, regnode);
8523 #ifdef RE_TRACK_PATTERN_OFFSETS
8524 if (RExC_offsets) { /* MJD 20010112 */
8525 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
8529 (UV)(dst - RExC_emit_start) > RExC_offsets[0]
8530 ? "Overwriting end of array!\n" : "OK",
8531 (UV)(src - RExC_emit_start),
8532 (UV)(dst - RExC_emit_start),
8533 (UV)RExC_offsets[0]));
8534 Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
8535 Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
8541 place = opnd; /* Op node, where operand used to be. */
8542 #ifdef RE_TRACK_PATTERN_OFFSETS
8543 if (RExC_offsets) { /* MJD */
8544 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
8548 (UV)(place - RExC_emit_start) > RExC_offsets[0]
8549 ? "Overwriting end of array!\n" : "OK",
8550 (UV)(place - RExC_emit_start),
8551 (UV)(RExC_parse - RExC_start),
8552 (UV)RExC_offsets[0]));
8553 Set_Node_Offset(place, RExC_parse);
8554 Set_Node_Length(place, 1);
8557 src = NEXTOPER(place);
8558 FILL_ADVANCE_NODE(place, op);
8559 Zero(src, offset, regnode);
8563 - regtail - set the next-pointer at the end of a node chain of p to val.
8564 - SEE ALSO: regtail_study
8566 /* TODO: All three parms should be const */
8568 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
8571 register regnode *scan;
8572 GET_RE_DEBUG_FLAGS_DECL;
8574 PERL_UNUSED_ARG(depth);
8580 /* Find last node. */
8583 regnode * const temp = regnext(scan);
8585 SV * const mysv=sv_newmortal();
8586 DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
8587 regprop(RExC_rx, mysv, scan);
8588 PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
8589 SvPV_nolen_const(mysv), REG_NODE_NUM(scan),
8590 (temp == NULL ? "->" : ""),
8591 (temp == NULL ? PL_reg_name[OP(val)] : "")
8599 if (reg_off_by_arg[OP(scan)]) {
8600 ARG_SET(scan, val - scan);
8603 NEXT_OFF(scan) = val - scan;
8609 - regtail_study - set the next-pointer at the end of a node chain of p to val.
8610 - Look for optimizable sequences at the same time.
8611 - currently only looks for EXACT chains.
8613 This is expermental code. The idea is to use this routine to perform
8614 in place optimizations on branches and groups as they are constructed,
8615 with the long term intention of removing optimization from study_chunk so
8616 that it is purely analytical.
8618 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
8619 to control which is which.
8622 /* TODO: All four parms should be const */
8625 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
8628 register regnode *scan;
8630 #ifdef EXPERIMENTAL_INPLACESCAN
8634 GET_RE_DEBUG_FLAGS_DECL;
8640 /* Find last node. */
8644 regnode * const temp = regnext(scan);
8645 #ifdef EXPERIMENTAL_INPLACESCAN
8646 if (PL_regkind[OP(scan)] == EXACT)
8647 if (join_exact(pRExC_state,scan,&min,1,val,depth+1))
8655 if( exact == PSEUDO )
8657 else if ( exact != OP(scan) )
8666 SV * const mysv=sv_newmortal();
8667 DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
8668 regprop(RExC_rx, mysv, scan);
8669 PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
8670 SvPV_nolen_const(mysv),
8672 PL_reg_name[exact]);
8679 SV * const mysv_val=sv_newmortal();
8680 DEBUG_PARSE_MSG("");
8681 regprop(RExC_rx, mysv_val, val);
8682 PerlIO_printf(Perl_debug_log, "~ attach to %s (%"IVdf") offset to %"IVdf"\n",
8683 SvPV_nolen_const(mysv_val),
8684 (IV)REG_NODE_NUM(val),
8688 if (reg_off_by_arg[OP(scan)]) {
8689 ARG_SET(scan, val - scan);
8692 NEXT_OFF(scan) = val - scan;
8700 - regcurly - a little FSA that accepts {\d+,?\d*}
8703 S_regcurly(register const char *s)
8722 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
8726 S_regdump_extflags(pTHX_ const char *lead, const U32 flags) {
8729 for (bit=0; bit<32; bit++) {
8730 if (flags & (1<<bit)) {
8732 PerlIO_printf(Perl_debug_log, "%s",lead);
8733 PerlIO_printf(Perl_debug_log, "%s ",PL_reg_extflags_name[bit]);
8738 PerlIO_printf(Perl_debug_log, "\n");
8740 PerlIO_printf(Perl_debug_log, "%s[none-set]\n",lead);
8746 Perl_regdump(pTHX_ const regexp *r)
8750 SV * const sv = sv_newmortal();
8751 SV *dsv= sv_newmortal();
8753 GET_RE_DEBUG_FLAGS_DECL;
8755 (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
8757 /* Header fields of interest. */
8758 if (r->anchored_substr) {
8759 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr),
8760 RE_SV_DUMPLEN(r->anchored_substr), 30);
8761 PerlIO_printf(Perl_debug_log,
8762 "anchored %s%s at %"IVdf" ",
8763 s, RE_SV_TAIL(r->anchored_substr),
8764 (IV)r->anchored_offset);
8765 } else if (r->anchored_utf8) {
8766 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8),
8767 RE_SV_DUMPLEN(r->anchored_utf8), 30);
8768 PerlIO_printf(Perl_debug_log,
8769 "anchored utf8 %s%s at %"IVdf" ",
8770 s, RE_SV_TAIL(r->anchored_utf8),
8771 (IV)r->anchored_offset);
8773 if (r->float_substr) {
8774 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr),
8775 RE_SV_DUMPLEN(r->float_substr), 30);
8776 PerlIO_printf(Perl_debug_log,
8777 "floating %s%s at %"IVdf"..%"UVuf" ",
8778 s, RE_SV_TAIL(r->float_substr),
8779 (IV)r->float_min_offset, (UV)r->float_max_offset);
8780 } else if (r->float_utf8) {
8781 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8),
8782 RE_SV_DUMPLEN(r->float_utf8), 30);
8783 PerlIO_printf(Perl_debug_log,
8784 "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
8785 s, RE_SV_TAIL(r->float_utf8),
8786 (IV)r->float_min_offset, (UV)r->float_max_offset);
8788 if (r->check_substr || r->check_utf8)
8789 PerlIO_printf(Perl_debug_log,
8791 (r->check_substr == r->float_substr
8792 && r->check_utf8 == r->float_utf8
8793 ? "(checking floating" : "(checking anchored"));
8794 if (r->extflags & RXf_NOSCAN)
8795 PerlIO_printf(Perl_debug_log, " noscan");
8796 if (r->extflags & RXf_CHECK_ALL)
8797 PerlIO_printf(Perl_debug_log, " isall");
8798 if (r->check_substr || r->check_utf8)
8799 PerlIO_printf(Perl_debug_log, ") ");
8801 if (ri->regstclass) {
8802 regprop(r, sv, ri->regstclass);
8803 PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
8805 if (r->extflags & RXf_ANCH) {
8806 PerlIO_printf(Perl_debug_log, "anchored");
8807 if (r->extflags & RXf_ANCH_BOL)
8808 PerlIO_printf(Perl_debug_log, "(BOL)");
8809 if (r->extflags & RXf_ANCH_MBOL)
8810 PerlIO_printf(Perl_debug_log, "(MBOL)");
8811 if (r->extflags & RXf_ANCH_SBOL)
8812 PerlIO_printf(Perl_debug_log, "(SBOL)");
8813 if (r->extflags & RXf_ANCH_GPOS)
8814 PerlIO_printf(Perl_debug_log, "(GPOS)");
8815 PerlIO_putc(Perl_debug_log, ' ');
8817 if (r->extflags & RXf_GPOS_SEEN)
8818 PerlIO_printf(Perl_debug_log, "GPOS:%"UVuf" ", (UV)r->gofs);
8819 if (r->intflags & PREGf_SKIP)
8820 PerlIO_printf(Perl_debug_log, "plus ");
8821 if (r->intflags & PREGf_IMPLICIT)
8822 PerlIO_printf(Perl_debug_log, "implicit ");
8823 PerlIO_printf(Perl_debug_log, "minlen %"IVdf" ", (IV)r->minlen);
8824 if (r->extflags & RXf_EVAL_SEEN)
8825 PerlIO_printf(Perl_debug_log, "with eval ");
8826 PerlIO_printf(Perl_debug_log, "\n");
8827 DEBUG_FLAGS_r(regdump_extflags("r->extflags: ",r->extflags));
8829 PERL_UNUSED_CONTEXT;
8831 #endif /* DEBUGGING */
8835 - regprop - printable representation of opcode
8838 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
8843 RXi_GET_DECL(prog,progi);
8844 GET_RE_DEBUG_FLAGS_DECL;
8847 sv_setpvn(sv, "", 0);
8849 if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */
8850 /* It would be nice to FAIL() here, but this may be called from
8851 regexec.c, and it would be hard to supply pRExC_state. */
8852 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
8853 sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
8855 k = PL_regkind[OP(o)];
8859 /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
8860 * is a crude hack but it may be the best for now since
8861 * we have no flag "this EXACTish node was UTF-8"
8863 pv_pretty(sv, STRING(o), STR_LEN(o), 60, PL_colors[0], PL_colors[1],
8864 PERL_PV_ESCAPE_UNI_DETECT |
8865 PERL_PV_PRETTY_ELLIPSES |
8866 PERL_PV_PRETTY_LTGT |
8867 PERL_PV_PRETTY_NOCLEAR
8869 } else if (k == TRIE) {
8870 /* print the details of the trie in dumpuntil instead, as
8871 * progi->data isn't available here */
8872 const char op = OP(o);
8873 const U32 n = ARG(o);
8874 const reg_ac_data * const ac = IS_TRIE_AC(op) ?
8875 (reg_ac_data *)progi->data->data[n] :
8877 const reg_trie_data * const trie
8878 = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
8880 Perl_sv_catpvf(aTHX_ sv, "-%s",PL_reg_name[o->flags]);
8881 DEBUG_TRIE_COMPILE_r(
8882 Perl_sv_catpvf(aTHX_ sv,
8883 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
8884 (UV)trie->startstate,
8885 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
8886 (UV)trie->wordcount,
8889 (UV)TRIE_CHARCOUNT(trie),
8890 (UV)trie->uniquecharcount
8893 if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
8895 int rangestart = -1;
8896 U8* bitmap = IS_ANYOF_TRIE(op) ? (U8*)ANYOF_BITMAP(o) : (U8*)TRIE_BITMAP(trie);
8898 for (i = 0; i <= 256; i++) {
8899 if (i < 256 && BITMAP_TEST(bitmap,i)) {
8900 if (rangestart == -1)
8902 } else if (rangestart != -1) {
8903 if (i <= rangestart + 3)
8904 for (; rangestart < i; rangestart++)
8905 put_byte(sv, rangestart);
8907 put_byte(sv, rangestart);
8909 put_byte(sv, i - 1);
8917 } else if (k == CURLY) {
8918 if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
8919 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
8920 Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
8922 else if (k == WHILEM && o->flags) /* Ordinal/of */
8923 Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
8924 else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP || OP(o)==ACCEPT) {
8925 Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o)); /* Parenth number */
8926 if ( prog->paren_names ) {
8927 if ( k != REF || OP(o) < NREF) {
8928 AV *list= (AV *)progi->data->data[progi->name_list_idx];
8929 SV **name= av_fetch(list, ARG(o), 0 );
8931 Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
8934 AV *list= (AV *)progi->data->data[ progi->name_list_idx ];
8935 SV *sv_dat=(SV*)progi->data->data[ ARG( o ) ];
8936 I32 *nums=(I32*)SvPVX(sv_dat);
8937 SV **name= av_fetch(list, nums[0], 0 );
8940 for ( n=0; n<SvIVX(sv_dat); n++ ) {
8941 Perl_sv_catpvf(aTHX_ sv, "%s%"IVdf,
8942 (n ? "," : ""), (IV)nums[n]);
8944 Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
8948 } else if (k == GOSUB)
8949 Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
8950 else if (k == VERB) {
8952 Perl_sv_catpvf(aTHX_ sv, ":%"SVf,
8953 SVfARG((SV*)progi->data->data[ ARG( o ) ]));
8954 } else if (k == LOGICAL)
8955 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* 2: embedded, otherwise 1 */
8956 else if (k == FOLDCHAR)
8957 Perl_sv_catpvf(aTHX_ sv, "[0x%"UVXf"]", PTR2UV(ARG(o)) );
8958 else if (k == ANYOF) {
8959 int i, rangestart = -1;
8960 const U8 flags = ANYOF_FLAGS(o);
8962 /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
8963 static const char * const anyofs[] = {
8996 if (flags & ANYOF_LOCALE)
8997 sv_catpvs(sv, "{loc}");
8998 if (flags & ANYOF_FOLD)
8999 sv_catpvs(sv, "{i}");
9000 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
9001 if (flags & ANYOF_INVERT)
9003 for (i = 0; i <= 256; i++) {
9004 if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
9005 if (rangestart == -1)
9007 } else if (rangestart != -1) {
9008 if (i <= rangestart + 3)
9009 for (; rangestart < i; rangestart++)
9010 put_byte(sv, rangestart);
9012 put_byte(sv, rangestart);
9014 put_byte(sv, i - 1);
9020 if (o->flags & ANYOF_CLASS)
9021 for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++)
9022 if (ANYOF_CLASS_TEST(o,i))
9023 sv_catpv(sv, anyofs[i]);
9025 if (flags & ANYOF_UNICODE)
9026 sv_catpvs(sv, "{unicode}");
9027 else if (flags & ANYOF_UNICODE_ALL)
9028 sv_catpvs(sv, "{unicode_all}");
9032 SV * const sw = regclass_swash(prog, o, FALSE, &lv, 0);
9036 U8 s[UTF8_MAXBYTES_CASE+1];
9038 for (i = 0; i <= 256; i++) { /* just the first 256 */
9039 uvchr_to_utf8(s, i);
9041 if (i < 256 && swash_fetch(sw, s, TRUE)) {
9042 if (rangestart == -1)
9044 } else if (rangestart != -1) {
9045 if (i <= rangestart + 3)
9046 for (; rangestart < i; rangestart++) {
9047 const U8 * const e = uvchr_to_utf8(s,rangestart);
9049 for(p = s; p < e; p++)
9053 const U8 *e = uvchr_to_utf8(s,rangestart);
9055 for (p = s; p < e; p++)
9058 e = uvchr_to_utf8(s, i-1);
9059 for (p = s; p < e; p++)
9066 sv_catpvs(sv, "..."); /* et cetera */
9070 char *s = savesvpv(lv);
9071 char * const origs = s;
9073 while (*s && *s != '\n')
9077 const char * const t = ++s;
9095 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
9097 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
9098 Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
9100 PERL_UNUSED_CONTEXT;
9101 PERL_UNUSED_ARG(sv);
9103 PERL_UNUSED_ARG(prog);
9104 #endif /* DEBUGGING */
9108 Perl_re_intuit_string(pTHX_ REGEXP * const r)
9109 { /* Assume that RE_INTUIT is set */
9111 struct regexp *const prog = (struct regexp *)SvANY(r);
9112 GET_RE_DEBUG_FLAGS_DECL;
9113 PERL_UNUSED_CONTEXT;
9117 const char * const s = SvPV_nolen_const(prog->check_substr
9118 ? prog->check_substr : prog->check_utf8);
9120 if (!PL_colorset) reginitcolors();
9121 PerlIO_printf(Perl_debug_log,
9122 "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
9124 prog->check_substr ? "" : "utf8 ",
9125 PL_colors[5],PL_colors[0],
9128 (strlen(s) > 60 ? "..." : ""));
9131 return prog->check_substr ? prog->check_substr : prog->check_utf8;
9137 handles refcounting and freeing the perl core regexp structure. When
9138 it is necessary to actually free the structure the first thing it
9139 does is call the 'free' method of the regexp_engine associated to to
9140 the regexp, allowing the handling of the void *pprivate; member
9141 first. (This routine is not overridable by extensions, which is why
9142 the extensions free is called first.)
9144 See regdupe and regdupe_internal if you change anything here.
9146 #ifndef PERL_IN_XSUB_RE
9148 Perl_pregfree(pTHX_ REGEXP *r)
9154 Perl_pregfree2(pTHX_ REGEXP *rx)
9157 struct regexp *const r = (struct regexp *)SvANY(rx);
9158 GET_RE_DEBUG_FLAGS_DECL;
9161 ReREFCNT_dec(r->mother_re);
9163 CALLREGFREE_PVT(rx); /* free the private data */
9165 SvREFCNT_dec(r->paren_names);
9168 if (r->anchored_substr)
9169 SvREFCNT_dec(r->anchored_substr);
9170 if (r->anchored_utf8)
9171 SvREFCNT_dec(r->anchored_utf8);
9172 if (r->float_substr)
9173 SvREFCNT_dec(r->float_substr);
9175 SvREFCNT_dec(r->float_utf8);
9176 Safefree(r->substrs);
9178 RX_MATCH_COPY_FREE(rx);
9179 #ifdef PERL_OLD_COPY_ON_WRITE
9181 SvREFCNT_dec(r->saved_copy);
9189 This is a hacky workaround to the structural issue of match results
9190 being stored in the regexp structure which is in turn stored in
9191 PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
9192 could be PL_curpm in multiple contexts, and could require multiple
9193 result sets being associated with the pattern simultaneously, such
9194 as when doing a recursive match with (??{$qr})
9196 The solution is to make a lightweight copy of the regexp structure
9197 when a qr// is returned from the code executed by (??{$qr}) this
9198 lightweight copy doesnt actually own any of its data except for
9199 the starp/end and the actual regexp structure itself.
9205 Perl_reg_temp_copy (pTHX_ REGEXP *rx) {
9206 REGEXP *ret_x = newSV_type(SVt_REGEXP);
9207 struct regexp *ret = (struct regexp *)SvANY(ret_x);
9208 struct regexp *const r = (struct regexp *)SvANY(rx);
9209 register const I32 npar = r->nparens+1;
9210 (void)ReREFCNT_inc(rx);
9211 /* FIXME ORANGE (once we start actually using the regular SV fields.) */
9212 /* We can take advantage of the existing "copied buffer" mechanism in SVs
9213 by pointing directly at the buffer, but flagging that the allocated
9214 space in the copy is zero. As we've just done a struct copy, it's now
9215 a case of zero-ing that, rather than copying the current length. */
9216 SvPV_set(ret_x, RX_WRAPPED(rx));
9217 StructCopy(r, ret, regexp);
9218 SvLEN_set(ret_x, 0);
9219 Newx(ret->offs, npar, regexp_paren_pair);
9220 Copy(r->offs, ret->offs, npar, regexp_paren_pair);
9222 Newx(ret->substrs, 1, struct reg_substr_data);
9223 StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
9225 SvREFCNT_inc_void(ret->anchored_substr);
9226 SvREFCNT_inc_void(ret->anchored_utf8);
9227 SvREFCNT_inc_void(ret->float_substr);
9228 SvREFCNT_inc_void(ret->float_utf8);
9230 /* check_substr and check_utf8, if non-NULL, point to either their
9231 anchored or float namesakes, and don't hold a second reference. */
9233 RX_MATCH_COPIED_off(ret_x);
9234 #ifdef PERL_OLD_COPY_ON_WRITE
9235 ret->saved_copy = NULL;
9237 ret->mother_re = rx;
9244 /* regfree_internal()
9246 Free the private data in a regexp. This is overloadable by
9247 extensions. Perl takes care of the regexp structure in pregfree(),
9248 this covers the *pprivate pointer which technically perldoesnt
9249 know about, however of course we have to handle the
9250 regexp_internal structure when no extension is in use.
9252 Note this is called before freeing anything in the regexp
9257 Perl_regfree_internal(pTHX_ REGEXP * const rx)
9260 struct regexp *const r = (struct regexp *)SvANY(rx);
9262 GET_RE_DEBUG_FLAGS_DECL;
9268 SV *dsv= sv_newmortal();
9269 RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
9270 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), 60);
9271 PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n",
9272 PL_colors[4],PL_colors[5],s);
9275 #ifdef RE_TRACK_PATTERN_OFFSETS
9277 Safefree(ri->u.offsets); /* 20010421 MJD */
9280 int n = ri->data->count;
9281 PAD* new_comppad = NULL;
9286 /* If you add a ->what type here, update the comment in regcomp.h */
9287 switch (ri->data->what[n]) {
9291 SvREFCNT_dec((SV*)ri->data->data[n]);
9294 Safefree(ri->data->data[n]);
9297 new_comppad = (AV*)ri->data->data[n];
9300 if (new_comppad == NULL)
9301 Perl_croak(aTHX_ "panic: pregfree comppad");
9302 PAD_SAVE_LOCAL(old_comppad,
9303 /* Watch out for global destruction's random ordering. */
9304 (SvTYPE(new_comppad) == SVt_PVAV) ? new_comppad : NULL
9307 refcnt = OpREFCNT_dec((OP_4tree*)ri->data->data[n]);
9310 op_free((OP_4tree*)ri->data->data[n]);
9312 PAD_RESTORE_LOCAL(old_comppad);
9313 SvREFCNT_dec((SV*)new_comppad);
9319 { /* Aho Corasick add-on structure for a trie node.
9320 Used in stclass optimization only */
9322 reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
9324 refcount = --aho->refcount;
9327 PerlMemShared_free(aho->states);
9328 PerlMemShared_free(aho->fail);
9329 /* do this last!!!! */
9330 PerlMemShared_free(ri->data->data[n]);
9331 PerlMemShared_free(ri->regstclass);
9337 /* trie structure. */
9339 reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
9341 refcount = --trie->refcount;
9344 PerlMemShared_free(trie->charmap);
9345 PerlMemShared_free(trie->states);
9346 PerlMemShared_free(trie->trans);
9348 PerlMemShared_free(trie->bitmap);
9350 PerlMemShared_free(trie->wordlen);
9352 PerlMemShared_free(trie->jump);
9354 PerlMemShared_free(trie->nextword);
9355 /* do this last!!!! */
9356 PerlMemShared_free(ri->data->data[n]);
9361 Perl_croak(aTHX_ "panic: regfree data code '%c'", ri->data->what[n]);
9364 Safefree(ri->data->what);
9371 #define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
9372 #define av_dup_inc(s,t) (AV*)SvREFCNT_inc(sv_dup((SV*)s,t))
9373 #define hv_dup_inc(s,t) (HV*)SvREFCNT_inc(sv_dup((SV*)s,t))
9374 #define SAVEPVN(p,n) ((p) ? savepvn(p,n) : NULL)
9377 re_dup - duplicate a regexp.
9379 This routine is expected to clone a given regexp structure. It is not
9380 compiler under USE_ITHREADS.
9382 After all of the core data stored in struct regexp is duplicated
9383 the regexp_engine.dupe method is used to copy any private data
9384 stored in the *pprivate pointer. This allows extensions to handle
9385 any duplication it needs to do.
9387 See pregfree() and regfree_internal() if you change anything here.
9389 #if defined(USE_ITHREADS)
9390 #ifndef PERL_IN_XSUB_RE
9392 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
9396 const struct regexp *r = (const struct regexp *)SvANY(sstr);
9397 struct regexp *ret = (struct regexp *)SvANY(dstr);
9399 npar = r->nparens+1;
9400 Newx(ret->offs, npar, regexp_paren_pair);
9401 Copy(r->offs, ret->offs, npar, regexp_paren_pair);
9403 /* no need to copy these */
9404 Newx(ret->swap, npar, regexp_paren_pair);
9408 /* Do it this way to avoid reading from *r after the StructCopy().
9409 That way, if any of the sv_dup_inc()s dislodge *r from the L1
9410 cache, it doesn't matter. */
9411 const bool anchored = r->check_substr == r->anchored_substr;
9412 Newx(ret->substrs, 1, struct reg_substr_data);
9413 StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
9415 ret->anchored_substr = sv_dup_inc(ret->anchored_substr, param);
9416 ret->anchored_utf8 = sv_dup_inc(ret->anchored_utf8, param);
9417 ret->float_substr = sv_dup_inc(ret->float_substr, param);
9418 ret->float_utf8 = sv_dup_inc(ret->float_utf8, param);
9420 /* check_substr and check_utf8, if non-NULL, point to either their
9421 anchored or float namesakes, and don't hold a second reference. */
9423 if (ret->check_substr) {
9425 assert(r->check_utf8 == r->anchored_utf8);
9426 ret->check_substr = ret->anchored_substr;
9427 ret->check_utf8 = ret->anchored_utf8;
9429 assert(r->check_substr == r->float_substr);
9430 assert(r->check_utf8 == r->float_utf8);
9431 ret->check_substr = ret->float_substr;
9432 ret->check_utf8 = ret->float_utf8;
9437 ret->paren_names = hv_dup_inc(ret->paren_names, param);
9440 RXi_SET(ret,CALLREGDUPE_PVT(dstr,param));
9442 if (RX_MATCH_COPIED(dstr))
9443 ret->subbeg = SAVEPVN(ret->subbeg, ret->sublen);
9446 #ifdef PERL_OLD_COPY_ON_WRITE
9447 ret->saved_copy = NULL;
9450 ret->mother_re = NULL;
9452 ret->seen_evals = 0;
9454 #endif /* PERL_IN_XSUB_RE */
9459 This is the internal complement to regdupe() which is used to copy
9460 the structure pointed to by the *pprivate pointer in the regexp.
9461 This is the core version of the extension overridable cloning hook.
9462 The regexp structure being duplicated will be copied by perl prior
9463 to this and will be provided as the regexp *r argument, however
9464 with the /old/ structures pprivate pointer value. Thus this routine
9465 may override any copying normally done by perl.
9467 It returns a pointer to the new regexp_internal structure.
9471 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
9474 struct regexp *const r = (struct regexp *)SvANY(rx);
9475 regexp_internal *reti;
9479 npar = r->nparens+1;
9482 Newxc(reti, sizeof(regexp_internal) + (len+1)*sizeof(regnode), char, regexp_internal);
9483 Copy(ri->program, reti->program, len+1, regnode);
9486 reti->regstclass = NULL;
9490 const int count = ri->data->count;
9493 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
9494 char, struct reg_data);
9495 Newx(d->what, count, U8);
9498 for (i = 0; i < count; i++) {
9499 d->what[i] = ri->data->what[i];
9500 switch (d->what[i]) {
9501 /* legal options are one of: sSfpontTu
9502 see also regcomp.h and pregfree() */
9505 case 'p': /* actually an AV, but the dup function is identical. */
9506 case 'u': /* actually an HV, but the dup function is identical. */
9507 d->data[i] = sv_dup_inc((SV *)ri->data->data[i], param);
9510 /* This is cheating. */
9511 Newx(d->data[i], 1, struct regnode_charclass_class);
9512 StructCopy(ri->data->data[i], d->data[i],
9513 struct regnode_charclass_class);
9514 reti->regstclass = (regnode*)d->data[i];
9517 /* Compiled op trees are readonly and in shared memory,
9518 and can thus be shared without duplication. */
9520 d->data[i] = (void*)OpREFCNT_inc((OP*)ri->data->data[i]);
9524 /* Trie stclasses are readonly and can thus be shared
9525 * without duplication. We free the stclass in pregfree
9526 * when the corresponding reg_ac_data struct is freed.
9528 reti->regstclass= ri->regstclass;
9532 ((reg_trie_data*)ri->data->data[i])->refcount++;
9536 d->data[i] = ri->data->data[i];
9539 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", ri->data->what[i]);
9548 reti->name_list_idx = ri->name_list_idx;
9550 #ifdef RE_TRACK_PATTERN_OFFSETS
9551 if (ri->u.offsets) {
9552 Newx(reti->u.offsets, 2*len+1, U32);
9553 Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
9556 SetProgLen(reti,len);
9562 #endif /* USE_ITHREADS */
9567 converts a regexp embedded in a MAGIC struct to its stringified form,
9568 caching the converted form in the struct and returns the cached
9571 If lp is nonnull then it is used to return the length of the
9574 If flags is nonnull and the returned string contains UTF8 then
9575 (*flags & 1) will be true.
9577 If haseval is nonnull then it is used to return whether the pattern
9580 Normally called via macro:
9582 CALLREG_STRINGIFY(mg,&len,&utf8);
9586 CALLREG_AS_STR(mg,&lp,&flags,&haseval)
9588 See sv_2pv_flags() in sv.c for an example of internal usage.
9591 #ifndef PERL_IN_XSUB_RE
9594 Perl_reg_stringify(pTHX_ MAGIC *mg, STRLEN *lp, U32 *flags, I32 *haseval ) {
9596 const REGEXP * const re = (REGEXP *)mg->mg_obj;
9598 *haseval = RX_SEEN_EVALS(re);
9600 *flags = RX_UTF8(re) ? 1 : 0;
9602 *lp = RX_WRAPLEN(re);
9603 return RX_WRAPPED(re);
9607 - regnext - dig the "next" pointer out of a node
9610 Perl_regnext(pTHX_ register regnode *p)
9613 register I32 offset;
9618 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
9627 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
9630 STRLEN l1 = strlen(pat1);
9631 STRLEN l2 = strlen(pat2);
9634 const char *message;
9640 Copy(pat1, buf, l1 , char);
9641 Copy(pat2, buf + l1, l2 , char);
9642 buf[l1 + l2] = '\n';
9643 buf[l1 + l2 + 1] = '\0';
9645 /* ANSI variant takes additional second argument */
9646 va_start(args, pat2);
9650 msv = vmess(buf, &args);
9652 message = SvPV_const(msv,l1);
9655 Copy(message, buf, l1 , char);
9656 buf[l1-1] = '\0'; /* Overwrite \n */
9657 Perl_croak(aTHX_ "%s", buf);
9660 /* XXX Here's a total kludge. But we need to re-enter for swash routines. */
9662 #ifndef PERL_IN_XSUB_RE
9664 Perl_save_re_context(pTHX)
9668 struct re_save_state *state;
9670 SAVEVPTR(PL_curcop);
9671 SSGROW(SAVESTACK_ALLOC_FOR_RE_SAVE_STATE + 1);
9673 state = (struct re_save_state *)(PL_savestack + PL_savestack_ix);
9674 PL_savestack_ix += SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
9675 SSPUSHINT(SAVEt_RE_STATE);
9677 Copy(&PL_reg_state, state, 1, struct re_save_state);
9679 PL_reg_start_tmp = 0;
9680 PL_reg_start_tmpl = 0;
9681 PL_reg_oldsaved = NULL;
9682 PL_reg_oldsavedlen = 0;
9684 PL_reg_leftiter = 0;
9685 PL_reg_poscache = NULL;
9686 PL_reg_poscache_size = 0;
9687 #ifdef PERL_OLD_COPY_ON_WRITE
9691 /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
9693 const REGEXP * const rx = PM_GETRE(PL_curpm);
9696 for (i = 1; i <= RX_NPARENS(rx); i++) {
9697 char digits[TYPE_CHARS(long)];
9698 const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
9699 GV *const *const gvp
9700 = (GV**)hv_fetch(PL_defstash, digits, len, 0);
9703 GV * const gv = *gvp;
9704 if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
9714 clear_re(pTHX_ void *r)
9717 ReREFCNT_dec((REGEXP *)r);
9723 S_put_byte(pTHX_ SV *sv, int c)
9725 /* Our definition of isPRINT() ignores locales, so only bytes that are
9726 not part of UTF-8 are considered printable. I assume that the same
9727 holds for UTF-EBCDIC.
9728 Also, code point 255 is not printable in either (it's E0 in EBCDIC,
9729 which Wikipedia says:
9731 EO, or Eight Ones, is an 8-bit EBCDIC character code represented as all
9732 ones (binary 1111 1111, hexadecimal FF). It is similar, but not
9733 identical, to the ASCII delete (DEL) or rubout control character.
9734 ) So the old condition can be simplified to !isPRINT(c) */
9736 Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
9738 const char string = c;
9739 if (c == '-' || c == ']' || c == '\\' || c == '^')
9740 sv_catpvs(sv, "\\");
9741 sv_catpvn(sv, &string, 1);
9746 #define CLEAR_OPTSTART \
9747 if (optstart) STMT_START { \
9748 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%"IVdf" nodes)\n", (IV)(node - optstart))); \
9752 #define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
9754 STATIC const regnode *
9755 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
9756 const regnode *last, const regnode *plast,
9757 SV* sv, I32 indent, U32 depth)
9760 register U8 op = PSEUDO; /* Arbitrary non-END op. */
9761 register const regnode *next;
9762 const regnode *optstart= NULL;
9765 GET_RE_DEBUG_FLAGS_DECL;
9767 #ifdef DEBUG_DUMPUNTIL
9768 PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
9769 last ? last-start : 0,plast ? plast-start : 0);
9772 if (plast && plast < last)
9775 while (PL_regkind[op] != END && (!last || node < last)) {
9776 /* While that wasn't END last time... */
9779 if (op == CLOSE || op == WHILEM)
9781 next = regnext((regnode *)node);
9784 if (OP(node) == OPTIMIZED) {
9785 if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
9792 regprop(r, sv, node);
9793 PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
9794 (int)(2*indent + 1), "", SvPVX_const(sv));
9796 if (OP(node) != OPTIMIZED) {
9797 if (next == NULL) /* Next ptr. */
9798 PerlIO_printf(Perl_debug_log, " (0)");
9799 else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
9800 PerlIO_printf(Perl_debug_log, " (FAIL)");
9802 PerlIO_printf(Perl_debug_log, " (%"IVdf")", (IV)(next - start));
9803 (void)PerlIO_putc(Perl_debug_log, '\n');
9807 if (PL_regkind[(U8)op] == BRANCHJ) {
9810 register const regnode *nnode = (OP(next) == LONGJMP
9811 ? regnext((regnode *)next)
9813 if (last && nnode > last)
9815 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
9818 else if (PL_regkind[(U8)op] == BRANCH) {
9820 DUMPUNTIL(NEXTOPER(node), next);
9822 else if ( PL_regkind[(U8)op] == TRIE ) {
9823 const regnode *this_trie = node;
9824 const char op = OP(node);
9825 const U32 n = ARG(node);
9826 const reg_ac_data * const ac = op>=AHOCORASICK ?
9827 (reg_ac_data *)ri->data->data[n] :
9829 const reg_trie_data * const trie =
9830 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
9832 AV *const trie_words = (AV *) ri->data->data[n + TRIE_WORDS_OFFSET];
9834 const regnode *nextbranch= NULL;
9836 sv_setpvn(sv, "", 0);
9837 for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
9838 SV ** const elem_ptr = av_fetch(trie_words,word_idx,0);
9840 PerlIO_printf(Perl_debug_log, "%*s%s ",
9841 (int)(2*(indent+3)), "",
9842 elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
9843 PL_colors[0], PL_colors[1],
9844 (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
9845 PERL_PV_PRETTY_ELLIPSES |
9851 U16 dist= trie->jump[word_idx+1];
9852 PerlIO_printf(Perl_debug_log, "(%"UVuf")\n",
9853 (UV)((dist ? this_trie + dist : next) - start));
9856 nextbranch= this_trie + trie->jump[0];
9857 DUMPUNTIL(this_trie + dist, nextbranch);
9859 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
9860 nextbranch= regnext((regnode *)nextbranch);
9862 PerlIO_printf(Perl_debug_log, "\n");
9865 if (last && next > last)
9870 else if ( op == CURLY ) { /* "next" might be very big: optimizer */
9871 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
9872 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
9874 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
9876 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
9878 else if ( op == PLUS || op == STAR) {
9879 DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
9881 else if (op == ANYOF) {
9882 /* arglen 1 + class block */
9883 node += 1 + ((ANYOF_FLAGS(node) & ANYOF_LARGE)
9884 ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
9885 node = NEXTOPER(node);
9887 else if (PL_regkind[(U8)op] == EXACT) {
9888 /* Literal string, where present. */
9889 node += NODE_SZ_STR(node) - 1;
9890 node = NEXTOPER(node);
9893 node = NEXTOPER(node);
9894 node += regarglen[(U8)op];
9896 if (op == CURLYX || op == OPEN)
9900 #ifdef DEBUG_DUMPUNTIL
9901 PerlIO_printf(Perl_debug_log, "--- %d\n", (int)indent);
9906 #endif /* DEBUGGING */
9910 * c-indentation-style: bsd
9912 * indent-tabs-mode: t
9915 * ex: set ts=8 sts=4 sw=4 noet: