5 * "A fair jaw-cracker dwarf-language must be." --Samwise Gamgee
8 /* This file contains functions for compiling a regular expression. See
9 * also regexec.c which funnily enough, contains functions for executing
10 * a regular expression.
12 * This file is also copied at build time to ext/re/re_comp.c, where
13 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
14 * This causes the main functions to be compiled under new names and with
15 * debugging support added, which makes "use re 'debug'" work.
18 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
19 * confused with the original package (see point 3 below). Thanks, Henry!
22 /* Additional note: this code is very heavily munged from Henry's version
23 * in places. In some spots I've traded clarity for efficiency, so don't
24 * blame Henry for some of the lack of readability.
27 /* The names of the functions have been changed from regcomp and
28 * regexec to pregcomp and pregexec in order to avoid conflicts
29 * with the POSIX routines of the same names.
32 #ifdef PERL_EXT_RE_BUILD
37 * pregcomp and pregexec -- regsub and regerror are not used in perl
39 * Copyright (c) 1986 by University of Toronto.
40 * Written by Henry Spencer. Not derived from licensed software.
42 * Permission is granted to anyone to use this software for any
43 * purpose on any computer system, and to redistribute it freely,
44 * subject to the following restrictions:
46 * 1. The author is not responsible for the consequences of use of
47 * this software, no matter how awful, even if they arise
50 * 2. The origin of this software must not be misrepresented, either
51 * by explicit claim or by omission.
53 * 3. Altered versions must be plainly marked as such, and must not
54 * be misrepresented as being the original software.
57 **** Alterations to Henry's code are...
59 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
60 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 by Larry Wall and others
62 **** You may distribute under the terms of either the GNU General Public
63 **** License or the Artistic License, as specified in the README file.
66 * Beware that some of this code is subtly aware of the way operator
67 * precedence is structured in regular expressions. Serious changes in
68 * regular-expression syntax might require a total rethink.
71 #define PERL_IN_REGCOMP_C
74 #ifndef PERL_IN_XSUB_RE
79 #ifdef PERL_IN_XSUB_RE
90 # if defined(BUGGY_MSC6)
91 /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
92 # pragma optimize("a",off)
93 /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
94 # pragma optimize("w",on )
95 # endif /* BUGGY_MSC6 */
102 typedef struct RExC_state_t {
103 U32 flags; /* are we folding, multilining? */
104 char *precomp; /* uncompiled string. */
105 regexp *rx; /* perl core regexp structure */
106 regexp_internal *rxi; /* internal data for regexp object pprivate field */
107 char *start; /* Start of input for compile */
108 char *end; /* End of input for compile */
109 char *parse; /* Input-scan pointer. */
110 I32 whilem_seen; /* number of WHILEM in this expr */
111 regnode *emit_start; /* Start of emitted-code area */
112 regnode *emit; /* Code-emit pointer; ®dummy = don't = compiling */
113 I32 naughty; /* How bad is this pattern? */
114 I32 sawback; /* Did we see \1, ...? */
116 I32 size; /* Code size. */
117 I32 npar; /* Capture buffer count, (OPEN). */
118 I32 cpar; /* Capture buffer count, (CLOSE). */
119 I32 nestroot; /* root parens we are in - used by accept */
123 regnode **open_parens; /* pointers to open parens */
124 regnode **close_parens; /* pointers to close parens */
125 regnode *opend; /* END node in program */
127 HV *charnames; /* cache of named sequences */
128 HV *paren_names; /* Paren names */
130 regnode **recurse; /* Recurse regops */
131 I32 recurse_count; /* Number of recurse regops */
133 char *starttry; /* -Dr: where regtry was called. */
134 #define RExC_starttry (pRExC_state->starttry)
137 const char *lastparse;
139 AV *paren_name_list; /* idx -> name */
140 #define RExC_lastparse (pRExC_state->lastparse)
141 #define RExC_lastnum (pRExC_state->lastnum)
142 #define RExC_paren_name_list (pRExC_state->paren_name_list)
146 #define RExC_flags (pRExC_state->flags)
147 #define RExC_precomp (pRExC_state->precomp)
148 #define RExC_rx (pRExC_state->rx)
149 #define RExC_rxi (pRExC_state->rxi)
150 #define RExC_start (pRExC_state->start)
151 #define RExC_end (pRExC_state->end)
152 #define RExC_parse (pRExC_state->parse)
153 #define RExC_whilem_seen (pRExC_state->whilem_seen)
154 #ifdef RE_TRACK_PATTERN_OFFSETS
155 #define RExC_offsets (pRExC_state->rxi->u.offsets) /* I am not like the others */
157 #define RExC_emit (pRExC_state->emit)
158 #define RExC_emit_start (pRExC_state->emit_start)
159 #define RExC_naughty (pRExC_state->naughty)
160 #define RExC_sawback (pRExC_state->sawback)
161 #define RExC_seen (pRExC_state->seen)
162 #define RExC_size (pRExC_state->size)
163 #define RExC_npar (pRExC_state->npar)
164 #define RExC_nestroot (pRExC_state->nestroot)
165 #define RExC_extralen (pRExC_state->extralen)
166 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
167 #define RExC_seen_evals (pRExC_state->seen_evals)
168 #define RExC_utf8 (pRExC_state->utf8)
169 #define RExC_charnames (pRExC_state->charnames)
170 #define RExC_open_parens (pRExC_state->open_parens)
171 #define RExC_close_parens (pRExC_state->close_parens)
172 #define RExC_opend (pRExC_state->opend)
173 #define RExC_paren_names (pRExC_state->paren_names)
174 #define RExC_recurse (pRExC_state->recurse)
175 #define RExC_recurse_count (pRExC_state->recurse_count)
178 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
179 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
180 ((*s) == '{' && regcurly(s)))
183 #undef SPSTART /* dratted cpp namespace... */
186 * Flags to be passed up and down.
188 #define WORST 0 /* Worst case. */
189 #define HASWIDTH 0x1 /* Known to match non-null strings. */
190 #define SIMPLE 0x2 /* Simple enough to be STAR/PLUS operand. */
191 #define SPSTART 0x4 /* Starts with * or +. */
192 #define TRYAGAIN 0x8 /* Weeded out a declaration. */
194 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
196 /* whether trie related optimizations are enabled */
197 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
198 #define TRIE_STUDY_OPT
199 #define FULL_TRIE_STUDY
205 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
206 #define PBITVAL(paren) (1 << ((paren) & 7))
207 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
208 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
209 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
212 /* About scan_data_t.
214 During optimisation we recurse through the regexp program performing
215 various inplace (keyhole style) optimisations. In addition study_chunk
216 and scan_commit populate this data structure with information about
217 what strings MUST appear in the pattern. We look for the longest
218 string that must appear for at a fixed location, and we look for the
219 longest string that may appear at a floating location. So for instance
224 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
225 strings (because they follow a .* construct). study_chunk will identify
226 both FOO and BAR as being the longest fixed and floating strings respectively.
228 The strings can be composites, for instance
232 will result in a composite fixed substring 'foo'.
234 For each string some basic information is maintained:
236 - offset or min_offset
237 This is the position the string must appear at, or not before.
238 It also implicitly (when combined with minlenp) tells us how many
239 character must match before the string we are searching.
240 Likewise when combined with minlenp and the length of the string
241 tells us how many characters must appear after the string we have
245 Only used for floating strings. This is the rightmost point that
246 the string can appear at. Ifset to I32 max it indicates that the
247 string can occur infinitely far to the right.
250 A pointer to the minimum length of the pattern that the string
251 was found inside. This is important as in the case of positive
252 lookahead or positive lookbehind we can have multiple patterns
257 The minimum length of the pattern overall is 3, the minimum length
258 of the lookahead part is 3, but the minimum length of the part that
259 will actually match is 1. So 'FOO's minimum length is 3, but the
260 minimum length for the F is 1. This is important as the minimum length
261 is used to determine offsets in front of and behind the string being
262 looked for. Since strings can be composites this is the length of the
263 pattern at the time it was commited with a scan_commit. Note that
264 the length is calculated by study_chunk, so that the minimum lengths
265 are not known until the full pattern has been compiled, thus the
266 pointer to the value.
270 In the case of lookbehind the string being searched for can be
271 offset past the start point of the final matching string.
272 If this value was just blithely removed from the min_offset it would
273 invalidate some of the calculations for how many chars must match
274 before or after (as they are derived from min_offset and minlen and
275 the length of the string being searched for).
276 When the final pattern is compiled and the data is moved from the
277 scan_data_t structure into the regexp structure the information
278 about lookbehind is factored in, with the information that would
279 have been lost precalculated in the end_shift field for the
282 The fields pos_min and pos_delta are used to store the minimum offset
283 and the delta to the maximum offset at the current point in the pattern.
287 typedef struct scan_data_t {
288 /*I32 len_min; unused */
289 /*I32 len_delta; unused */
293 I32 last_end; /* min value, <0 unless valid. */
296 SV **longest; /* Either &l_fixed, or &l_float. */
297 SV *longest_fixed; /* longest fixed string found in pattern */
298 I32 offset_fixed; /* offset where it starts */
299 I32 *minlen_fixed; /* pointer to the minlen relevent to the string */
300 I32 lookbehind_fixed; /* is the position of the string modfied by LB */
301 SV *longest_float; /* longest floating string found in pattern */
302 I32 offset_float_min; /* earliest point in string it can appear */
303 I32 offset_float_max; /* latest point in string it can appear */
304 I32 *minlen_float; /* pointer to the minlen relevent to the string */
305 I32 lookbehind_float; /* is the position of the string modified by LB */
309 struct regnode_charclass_class *start_class;
313 * Forward declarations for pregcomp()'s friends.
316 static const scan_data_t zero_scan_data =
317 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
319 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
320 #define SF_BEFORE_SEOL 0x0001
321 #define SF_BEFORE_MEOL 0x0002
322 #define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
323 #define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
326 # define SF_FIX_SHIFT_EOL (0+2)
327 # define SF_FL_SHIFT_EOL (0+4)
329 # define SF_FIX_SHIFT_EOL (+2)
330 # define SF_FL_SHIFT_EOL (+4)
333 #define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
334 #define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
336 #define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
337 #define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
338 #define SF_IS_INF 0x0040
339 #define SF_HAS_PAR 0x0080
340 #define SF_IN_PAR 0x0100
341 #define SF_HAS_EVAL 0x0200
342 #define SCF_DO_SUBSTR 0x0400
343 #define SCF_DO_STCLASS_AND 0x0800
344 #define SCF_DO_STCLASS_OR 0x1000
345 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
346 #define SCF_WHILEM_VISITED_POS 0x2000
348 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
349 #define SCF_SEEN_ACCEPT 0x8000
351 #define UTF (RExC_utf8 != 0)
352 #define LOC ((RExC_flags & RXf_PMf_LOCALE) != 0)
353 #define FOLD ((RExC_flags & RXf_PMf_FOLD) != 0)
355 #define OOB_UNICODE 12345678
356 #define OOB_NAMEDCLASS -1
358 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
359 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
362 /* length of regex to show in messages that don't mark a position within */
363 #define RegexLengthToShowInErrorMessages 127
366 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
367 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
368 * op/pragma/warn/regcomp.
370 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
371 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
373 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
376 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
377 * arg. Show regex, up to a maximum length. If it's too long, chop and add
380 #define _FAIL(code) STMT_START { \
381 const char *ellipses = ""; \
382 IV len = RExC_end - RExC_precomp; \
385 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
386 if (len > RegexLengthToShowInErrorMessages) { \
387 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
388 len = RegexLengthToShowInErrorMessages - 10; \
394 #define FAIL(msg) _FAIL( \
395 Perl_croak(aTHX_ "%s in regex m/%.*s%s/", \
396 msg, (int)len, RExC_precomp, ellipses))
398 #define FAIL2(msg,arg) _FAIL( \
399 Perl_croak(aTHX_ msg " in regex m/%.*s%s/", \
400 arg, (int)len, RExC_precomp, ellipses))
403 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
405 #define Simple_vFAIL(m) STMT_START { \
406 const IV offset = RExC_parse - RExC_precomp; \
407 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
408 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
412 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
414 #define vFAIL(m) STMT_START { \
416 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
421 * Like Simple_vFAIL(), but accepts two arguments.
423 #define Simple_vFAIL2(m,a1) STMT_START { \
424 const IV offset = RExC_parse - RExC_precomp; \
425 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, \
426 (int)offset, RExC_precomp, RExC_precomp + offset); \
430 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
432 #define vFAIL2(m,a1) STMT_START { \
434 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
435 Simple_vFAIL2(m, a1); \
440 * Like Simple_vFAIL(), but accepts three arguments.
442 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
443 const IV offset = RExC_parse - RExC_precomp; \
444 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, \
445 (int)offset, RExC_precomp, RExC_precomp + offset); \
449 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
451 #define vFAIL3(m,a1,a2) STMT_START { \
453 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
454 Simple_vFAIL3(m, a1, a2); \
458 * Like Simple_vFAIL(), but accepts four arguments.
460 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
461 const IV offset = RExC_parse - RExC_precomp; \
462 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, \
463 (int)offset, RExC_precomp, RExC_precomp + offset); \
466 #define vWARN(loc,m) STMT_START { \
467 const IV offset = loc - RExC_precomp; \
468 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s" REPORT_LOCATION, \
469 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
472 #define vWARNdep(loc,m) STMT_START { \
473 const IV offset = loc - RExC_precomp; \
474 Perl_warner(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
475 "%s" REPORT_LOCATION, \
476 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
480 #define vWARN2(loc, m, a1) STMT_START { \
481 const IV offset = loc - RExC_precomp; \
482 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
483 a1, (int)offset, RExC_precomp, RExC_precomp + offset); \
486 #define vWARN3(loc, m, a1, a2) STMT_START { \
487 const IV offset = loc - RExC_precomp; \
488 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
489 a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
492 #define vWARN4(loc, m, a1, a2, a3) STMT_START { \
493 const IV offset = loc - RExC_precomp; \
494 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
495 a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
498 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START { \
499 const IV offset = loc - RExC_precomp; \
500 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
501 a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
505 /* Allow for side effects in s */
506 #define REGC(c,s) STMT_START { \
507 if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
510 /* Macros for recording node offsets. 20001227 mjd@plover.com
511 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
512 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
513 * Element 0 holds the number n.
514 * Position is 1 indexed.
516 #ifndef RE_TRACK_PATTERN_OFFSETS
517 #define Set_Node_Offset_To_R(node,byte)
518 #define Set_Node_Offset(node,byte)
519 #define Set_Cur_Node_Offset
520 #define Set_Node_Length_To_R(node,len)
521 #define Set_Node_Length(node,len)
522 #define Set_Node_Cur_Length(node)
523 #define Node_Offset(n)
524 #define Node_Length(n)
525 #define Set_Node_Offset_Length(node,offset,len)
526 #define ProgLen(ri) ri->u.proglen
527 #define SetProgLen(ri,x) ri->u.proglen = x
529 #define ProgLen(ri) ri->u.offsets[0]
530 #define SetProgLen(ri,x) ri->u.offsets[0] = x
531 #define Set_Node_Offset_To_R(node,byte) STMT_START { \
533 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
534 __LINE__, (int)(node), (int)(byte))); \
536 Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
538 RExC_offsets[2*(node)-1] = (byte); \
543 #define Set_Node_Offset(node,byte) \
544 Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
545 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
547 #define Set_Node_Length_To_R(node,len) STMT_START { \
549 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
550 __LINE__, (int)(node), (int)(len))); \
552 Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
554 RExC_offsets[2*(node)] = (len); \
559 #define Set_Node_Length(node,len) \
560 Set_Node_Length_To_R((node)-RExC_emit_start, len)
561 #define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
562 #define Set_Node_Cur_Length(node) \
563 Set_Node_Length(node, RExC_parse - parse_start)
565 /* Get offsets and lengths */
566 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
567 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
569 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
570 Set_Node_Offset_To_R((node)-RExC_emit_start, (offset)); \
571 Set_Node_Length_To_R((node)-RExC_emit_start, (len)); \
575 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
576 #define EXPERIMENTAL_INPLACESCAN
577 #endif /*RE_TRACK_PATTERN_OFFSETS*/
579 #define DEBUG_STUDYDATA(str,data,depth) \
580 DEBUG_OPTIMISE_MORE_r(if(data){ \
581 PerlIO_printf(Perl_debug_log, \
582 "%*s" str "Pos:%"IVdf"/%"IVdf \
583 " Flags: 0x%"UVXf" Whilem_c: %"IVdf" Lcp: %"IVdf" %s", \
584 (int)(depth)*2, "", \
585 (IV)((data)->pos_min), \
586 (IV)((data)->pos_delta), \
587 (UV)((data)->flags), \
588 (IV)((data)->whilem_c), \
589 (IV)((data)->last_closep ? *((data)->last_closep) : -1), \
590 is_inf ? "INF " : "" \
592 if ((data)->last_found) \
593 PerlIO_printf(Perl_debug_log, \
594 "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
595 " %sFloat: '%s' @ %"IVdf"/%"IVdf"", \
596 SvPVX_const((data)->last_found), \
597 (IV)((data)->last_end), \
598 (IV)((data)->last_start_min), \
599 (IV)((data)->last_start_max), \
600 ((data)->longest && \
601 (data)->longest==&((data)->longest_fixed)) ? "*" : "", \
602 SvPVX_const((data)->longest_fixed), \
603 (IV)((data)->offset_fixed), \
604 ((data)->longest && \
605 (data)->longest==&((data)->longest_float)) ? "*" : "", \
606 SvPVX_const((data)->longest_float), \
607 (IV)((data)->offset_float_min), \
608 (IV)((data)->offset_float_max) \
610 PerlIO_printf(Perl_debug_log,"\n"); \
613 static void clear_re(pTHX_ void *r);
615 /* Mark that we cannot extend a found fixed substring at this point.
616 Update the longest found anchored substring and the longest found
617 floating substrings if needed. */
620 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp, int is_inf)
622 const STRLEN l = CHR_SVLEN(data->last_found);
623 const STRLEN old_l = CHR_SVLEN(*data->longest);
624 GET_RE_DEBUG_FLAGS_DECL;
626 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
627 SvSetMagicSV(*data->longest, data->last_found);
628 if (*data->longest == data->longest_fixed) {
629 data->offset_fixed = l ? data->last_start_min : data->pos_min;
630 if (data->flags & SF_BEFORE_EOL)
632 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
634 data->flags &= ~SF_FIX_BEFORE_EOL;
635 data->minlen_fixed=minlenp;
636 data->lookbehind_fixed=0;
638 else { /* *data->longest == data->longest_float */
639 data->offset_float_min = l ? data->last_start_min : data->pos_min;
640 data->offset_float_max = (l
641 ? data->last_start_max
642 : data->pos_min + data->pos_delta);
643 if (is_inf || (U32)data->offset_float_max > (U32)I32_MAX)
644 data->offset_float_max = I32_MAX;
645 if (data->flags & SF_BEFORE_EOL)
647 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
649 data->flags &= ~SF_FL_BEFORE_EOL;
650 data->minlen_float=minlenp;
651 data->lookbehind_float=0;
654 SvCUR_set(data->last_found, 0);
656 SV * const sv = data->last_found;
657 if (SvUTF8(sv) && SvMAGICAL(sv)) {
658 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
664 data->flags &= ~SF_BEFORE_EOL;
665 DEBUG_STUDYDATA("commit: ",data,0);
668 /* Can match anything (initialization) */
670 S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
672 ANYOF_CLASS_ZERO(cl);
673 ANYOF_BITMAP_SETALL(cl);
674 cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL;
676 cl->flags |= ANYOF_LOCALE;
679 /* Can match anything (initialization) */
681 S_cl_is_anything(const struct regnode_charclass_class *cl)
685 for (value = 0; value <= ANYOF_MAX; value += 2)
686 if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
688 if (!(cl->flags & ANYOF_UNICODE_ALL))
690 if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
695 /* Can match anything (initialization) */
697 S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
699 Zero(cl, 1, struct regnode_charclass_class);
701 cl_anything(pRExC_state, cl);
705 S_cl_init_zero(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
707 Zero(cl, 1, struct regnode_charclass_class);
709 cl_anything(pRExC_state, cl);
711 cl->flags |= ANYOF_LOCALE;
714 /* 'And' a given class with another one. Can create false positives */
715 /* We assume that cl is not inverted */
717 S_cl_and(struct regnode_charclass_class *cl,
718 const struct regnode_charclass_class *and_with)
721 assert(and_with->type == ANYOF);
722 if (!(and_with->flags & ANYOF_CLASS)
723 && !(cl->flags & ANYOF_CLASS)
724 && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
725 && !(and_with->flags & ANYOF_FOLD)
726 && !(cl->flags & ANYOF_FOLD)) {
729 if (and_with->flags & ANYOF_INVERT)
730 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
731 cl->bitmap[i] &= ~and_with->bitmap[i];
733 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
734 cl->bitmap[i] &= and_with->bitmap[i];
735 } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
736 if (!(and_with->flags & ANYOF_EOS))
737 cl->flags &= ~ANYOF_EOS;
739 if (cl->flags & ANYOF_UNICODE_ALL && and_with->flags & ANYOF_UNICODE &&
740 !(and_with->flags & ANYOF_INVERT)) {
741 cl->flags &= ~ANYOF_UNICODE_ALL;
742 cl->flags |= ANYOF_UNICODE;
743 ARG_SET(cl, ARG(and_with));
745 if (!(and_with->flags & ANYOF_UNICODE_ALL) &&
746 !(and_with->flags & ANYOF_INVERT))
747 cl->flags &= ~ANYOF_UNICODE_ALL;
748 if (!(and_with->flags & (ANYOF_UNICODE|ANYOF_UNICODE_ALL)) &&
749 !(and_with->flags & ANYOF_INVERT))
750 cl->flags &= ~ANYOF_UNICODE;
753 /* 'OR' a given class with another one. Can create false positives */
754 /* We assume that cl is not inverted */
756 S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
758 if (or_with->flags & ANYOF_INVERT) {
760 * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
761 * <= (B1 | !B2) | (CL1 | !CL2)
762 * which is wasteful if CL2 is small, but we ignore CL2:
763 * (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
764 * XXXX Can we handle case-fold? Unclear:
765 * (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
766 * (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
768 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
769 && !(or_with->flags & ANYOF_FOLD)
770 && !(cl->flags & ANYOF_FOLD) ) {
773 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
774 cl->bitmap[i] |= ~or_with->bitmap[i];
775 } /* XXXX: logic is complicated otherwise */
777 cl_anything(pRExC_state, cl);
780 /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
781 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
782 && (!(or_with->flags & ANYOF_FOLD)
783 || (cl->flags & ANYOF_FOLD)) ) {
786 /* OR char bitmap and class bitmap separately */
787 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
788 cl->bitmap[i] |= or_with->bitmap[i];
789 if (or_with->flags & ANYOF_CLASS) {
790 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
791 cl->classflags[i] |= or_with->classflags[i];
792 cl->flags |= ANYOF_CLASS;
795 else { /* XXXX: logic is complicated, leave it along for a moment. */
796 cl_anything(pRExC_state, cl);
799 if (or_with->flags & ANYOF_EOS)
800 cl->flags |= ANYOF_EOS;
802 if (cl->flags & ANYOF_UNICODE && or_with->flags & ANYOF_UNICODE &&
803 ARG(cl) != ARG(or_with)) {
804 cl->flags |= ANYOF_UNICODE_ALL;
805 cl->flags &= ~ANYOF_UNICODE;
807 if (or_with->flags & ANYOF_UNICODE_ALL) {
808 cl->flags |= ANYOF_UNICODE_ALL;
809 cl->flags &= ~ANYOF_UNICODE;
813 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
814 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
815 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
816 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
821 dump_trie(trie,widecharmap,revcharmap)
822 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
823 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
825 These routines dump out a trie in a somewhat readable format.
826 The _interim_ variants are used for debugging the interim
827 tables that are used to generate the final compressed
828 representation which is what dump_trie expects.
830 Part of the reason for their existance is to provide a form
831 of documentation as to how the different representations function.
836 Dumps the final compressed table form of the trie to Perl_debug_log.
837 Used for debugging make_trie().
841 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
842 AV *revcharmap, U32 depth)
845 SV *sv=sv_newmortal();
846 int colwidth= widecharmap ? 6 : 4;
847 GET_RE_DEBUG_FLAGS_DECL;
850 PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
851 (int)depth * 2 + 2,"",
852 "Match","Base","Ofs" );
854 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
855 SV ** const tmp = av_fetch( revcharmap, state, 0);
857 PerlIO_printf( Perl_debug_log, "%*s",
859 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
860 PL_colors[0], PL_colors[1],
861 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
862 PERL_PV_ESCAPE_FIRSTCHAR
867 PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
868 (int)depth * 2 + 2,"");
870 for( state = 0 ; state < trie->uniquecharcount ; state++ )
871 PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
872 PerlIO_printf( Perl_debug_log, "\n");
874 for( state = 1 ; state < trie->statecount ; state++ ) {
875 const U32 base = trie->states[ state ].trans.base;
877 PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
879 if ( trie->states[ state ].wordnum ) {
880 PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
882 PerlIO_printf( Perl_debug_log, "%6s", "" );
885 PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
890 while( ( base + ofs < trie->uniquecharcount ) ||
891 ( base + ofs - trie->uniquecharcount < trie->lasttrans
892 && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
895 PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
897 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
898 if ( ( base + ofs >= trie->uniquecharcount ) &&
899 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
900 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
902 PerlIO_printf( Perl_debug_log, "%*"UVXf,
904 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
906 PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
910 PerlIO_printf( Perl_debug_log, "]");
913 PerlIO_printf( Perl_debug_log, "\n" );
917 Dumps a fully constructed but uncompressed trie in list form.
918 List tries normally only are used for construction when the number of
919 possible chars (trie->uniquecharcount) is very high.
920 Used for debugging make_trie().
923 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
924 HV *widecharmap, AV *revcharmap, U32 next_alloc,
928 SV *sv=sv_newmortal();
929 int colwidth= widecharmap ? 6 : 4;
930 GET_RE_DEBUG_FLAGS_DECL;
931 /* print out the table precompression. */
932 PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
933 (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
934 "------:-----+-----------------\n" );
936 for( state=1 ; state < next_alloc ; state ++ ) {
939 PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
940 (int)depth * 2 + 2,"", (UV)state );
941 if ( ! trie->states[ state ].wordnum ) {
942 PerlIO_printf( Perl_debug_log, "%5s| ","");
944 PerlIO_printf( Perl_debug_log, "W%4x| ",
945 trie->states[ state ].wordnum
948 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
949 SV ** const tmp = av_fetch( revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
951 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
953 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
954 PL_colors[0], PL_colors[1],
955 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
956 PERL_PV_ESCAPE_FIRSTCHAR
958 TRIE_LIST_ITEM(state,charid).forid,
959 (UV)TRIE_LIST_ITEM(state,charid).newstate
962 PerlIO_printf(Perl_debug_log, "\n%*s| ",
963 (int)((depth * 2) + 14), "");
966 PerlIO_printf( Perl_debug_log, "\n");
971 Dumps a fully constructed but uncompressed trie in table form.
972 This is the normal DFA style state transition table, with a few
973 twists to facilitate compression later.
974 Used for debugging make_trie().
977 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
978 HV *widecharmap, AV *revcharmap, U32 next_alloc,
983 SV *sv=sv_newmortal();
984 int colwidth= widecharmap ? 6 : 4;
985 GET_RE_DEBUG_FLAGS_DECL;
988 print out the table precompression so that we can do a visual check
989 that they are identical.
992 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
994 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
995 SV ** const tmp = av_fetch( revcharmap, charid, 0);
997 PerlIO_printf( Perl_debug_log, "%*s",
999 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
1000 PL_colors[0], PL_colors[1],
1001 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1002 PERL_PV_ESCAPE_FIRSTCHAR
1008 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
1010 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
1011 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
1014 PerlIO_printf( Perl_debug_log, "\n" );
1016 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
1018 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
1019 (int)depth * 2 + 2,"",
1020 (UV)TRIE_NODENUM( state ) );
1022 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1023 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
1025 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
1027 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
1029 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
1030 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
1032 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
1033 trie->states[ TRIE_NODENUM( state ) ].wordnum );
1040 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1041 startbranch: the first branch in the whole branch sequence
1042 first : start branch of sequence of branch-exact nodes.
1043 May be the same as startbranch
1044 last : Thing following the last branch.
1045 May be the same as tail.
1046 tail : item following the branch sequence
1047 count : words in the sequence
1048 flags : currently the OP() type we will be building one of /EXACT(|F|Fl)/
1049 depth : indent depth
1051 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
1053 A trie is an N'ary tree where the branches are determined by digital
1054 decomposition of the key. IE, at the root node you look up the 1st character and
1055 follow that branch repeat until you find the end of the branches. Nodes can be
1056 marked as "accepting" meaning they represent a complete word. Eg:
1060 would convert into the following structure. Numbers represent states, letters
1061 following numbers represent valid transitions on the letter from that state, if
1062 the number is in square brackets it represents an accepting state, otherwise it
1063 will be in parenthesis.
1065 +-h->+-e->[3]-+-r->(8)-+-s->[9]
1069 (1) +-i->(6)-+-s->[7]
1071 +-s->(3)-+-h->(4)-+-e->[5]
1073 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1075 This shows that when matching against the string 'hers' we will begin at state 1
1076 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1077 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1078 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1079 single traverse. We store a mapping from accepting to state to which word was
1080 matched, and then when we have multiple possibilities we try to complete the
1081 rest of the regex in the order in which they occured in the alternation.
1083 The only prior NFA like behaviour that would be changed by the TRIE support is
1084 the silent ignoring of duplicate alternations which are of the form:
1086 / (DUPE|DUPE) X? (?{ ... }) Y /x
1088 Thus EVAL blocks follwing a trie may be called a different number of times with
1089 and without the optimisation. With the optimisations dupes will be silently
1090 ignored. This inconsistant behaviour of EVAL type nodes is well established as
1091 the following demonstrates:
1093 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1095 which prints out 'word' three times, but
1097 'words'=~/(word|word|word)(?{ print $1 })S/
1099 which doesnt print it out at all. This is due to other optimisations kicking in.
1101 Example of what happens on a structural level:
1103 The regexp /(ac|ad|ab)+/ will produce the folowing debug output:
1105 1: CURLYM[1] {1,32767}(18)
1116 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1117 and should turn into:
1119 1: CURLYM[1] {1,32767}(18)
1121 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1129 Cases where tail != last would be like /(?foo|bar)baz/:
1139 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1140 and would end up looking like:
1143 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1150 d = uvuni_to_utf8_flags(d, uv, 0);
1152 is the recommended Unicode-aware way of saying
1157 #define TRIE_STORE_REVCHAR \
1159 SV *tmp = newSVpvs(""); \
1160 if (UTF) SvUTF8_on(tmp); \
1161 Perl_sv_catpvf( aTHX_ tmp, "%c", (int)uvc ); \
1162 av_push( revcharmap, tmp ); \
1165 #define TRIE_READ_CHAR STMT_START { \
1169 if ( foldlen > 0 ) { \
1170 uvc = utf8n_to_uvuni( scan, UTF8_MAXLEN, &len, uniflags ); \
1175 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1176 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1177 foldlen -= UNISKIP( uvc ); \
1178 scan = foldbuf + UNISKIP( uvc ); \
1181 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1191 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
1192 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
1193 U32 ging = TRIE_LIST_LEN( state ) *= 2; \
1194 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
1196 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
1197 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
1198 TRIE_LIST_CUR( state )++; \
1201 #define TRIE_LIST_NEW(state) STMT_START { \
1202 Newxz( trie->states[ state ].trans.list, \
1203 4, reg_trie_trans_le ); \
1204 TRIE_LIST_CUR( state ) = 1; \
1205 TRIE_LIST_LEN( state ) = 4; \
1208 #define TRIE_HANDLE_WORD(state) STMT_START { \
1209 U16 dupe= trie->states[ state ].wordnum; \
1210 regnode * const noper_next = regnext( noper ); \
1212 if (trie->wordlen) \
1213 trie->wordlen[ curword ] = wordlen; \
1215 /* store the word for dumping */ \
1217 if (OP(noper) != NOTHING) \
1218 tmp = newSVpvn(STRING(noper), STR_LEN(noper)); \
1220 tmp = newSVpvn( "", 0 ); \
1221 if ( UTF ) SvUTF8_on( tmp ); \
1222 av_push( trie_words, tmp ); \
1227 if ( noper_next < tail ) { \
1229 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, sizeof(U16) ); \
1230 trie->jump[curword] = (U16)(noper_next - convert); \
1232 jumper = noper_next; \
1234 nextbranch= regnext(cur); \
1238 /* So it's a dupe. This means we need to maintain a */\
1239 /* linked-list from the first to the next. */\
1240 /* we only allocate the nextword buffer when there */\
1241 /* a dupe, so first time we have to do the allocation */\
1242 if (!trie->nextword) \
1243 trie->nextword = (U16 *) \
1244 PerlMemShared_calloc( word_count + 1, sizeof(U16)); \
1245 while ( trie->nextword[dupe] ) \
1246 dupe= trie->nextword[dupe]; \
1247 trie->nextword[dupe]= curword; \
1249 /* we haven't inserted this word yet. */ \
1250 trie->states[ state ].wordnum = curword; \
1255 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
1256 ( ( base + charid >= ucharcount \
1257 && base + charid < ubound \
1258 && state == trie->trans[ base - ucharcount + charid ].check \
1259 && trie->trans[ base - ucharcount + charid ].next ) \
1260 ? trie->trans[ base - ucharcount + charid ].next \
1261 : ( state==1 ? special : 0 ) \
1265 #define MADE_JUMP_TRIE 2
1266 #define MADE_EXACT_TRIE 4
1269 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
1272 /* first pass, loop through and scan words */
1273 reg_trie_data *trie;
1274 HV *widecharmap = NULL;
1275 AV *revcharmap = newAV();
1277 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1282 regnode *jumper = NULL;
1283 regnode *nextbranch = NULL;
1284 regnode *convert = NULL;
1285 /* we just use folder as a flag in utf8 */
1286 const U8 * const folder = ( flags == EXACTF
1288 : ( flags == EXACTFL
1295 const U32 data_slot = add_data( pRExC_state, 4, "tuuu" );
1296 AV *trie_words = NULL;
1297 /* along with revcharmap, this only used during construction but both are
1298 * useful during debugging so we store them in the struct when debugging.
1301 const U32 data_slot = add_data( pRExC_state, 2, "tu" );
1302 STRLEN trie_charcount=0;
1304 SV *re_trie_maxbuff;
1305 GET_RE_DEBUG_FLAGS_DECL;
1307 PERL_UNUSED_ARG(depth);
1310 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
1312 trie->startstate = 1;
1313 trie->wordcount = word_count;
1314 RExC_rxi->data->data[ data_slot ] = (void*)trie;
1315 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
1316 if (!(UTF && folder))
1317 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
1319 trie_words = newAV();
1322 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
1323 if (!SvIOK(re_trie_maxbuff)) {
1324 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
1327 PerlIO_printf( Perl_debug_log,
1328 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
1329 (int)depth * 2 + 2, "",
1330 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
1331 REG_NODE_NUM(last), REG_NODE_NUM(tail),
1335 /* Find the node we are going to overwrite */
1336 if ( first == startbranch && OP( last ) != BRANCH ) {
1337 /* whole branch chain */
1340 /* branch sub-chain */
1341 convert = NEXTOPER( first );
1344 /* -- First loop and Setup --
1346 We first traverse the branches and scan each word to determine if it
1347 contains widechars, and how many unique chars there are, this is
1348 important as we have to build a table with at least as many columns as we
1351 We use an array of integers to represent the character codes 0..255
1352 (trie->charmap) and we use a an HV* to store unicode characters. We use the
1353 native representation of the character value as the key and IV's for the
1356 *TODO* If we keep track of how many times each character is used we can
1357 remap the columns so that the table compression later on is more
1358 efficient in terms of memory by ensuring most common value is in the
1359 middle and the least common are on the outside. IMO this would be better
1360 than a most to least common mapping as theres a decent chance the most
1361 common letter will share a node with the least common, meaning the node
1362 will not be compressable. With a middle is most common approach the worst
1363 case is when we have the least common nodes twice.
1367 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1368 regnode * const noper = NEXTOPER( cur );
1369 const U8 *uc = (U8*)STRING( noper );
1370 const U8 * const e = uc + STR_LEN( noper );
1372 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1373 const U8 *scan = (U8*)NULL;
1374 U32 wordlen = 0; /* required init */
1377 if (OP(noper) == NOTHING) {
1382 TRIE_BITMAP_SET(trie,*uc);
1383 if ( folder ) TRIE_BITMAP_SET(trie,folder[ *uc ]);
1385 for ( ; uc < e ; uc += len ) {
1386 TRIE_CHARCOUNT(trie)++;
1390 if ( !trie->charmap[ uvc ] ) {
1391 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1393 trie->charmap[ folder[ uvc ] ] = trie->charmap[ uvc ];
1399 widecharmap = newHV();
1401 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
1404 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
1406 if ( !SvTRUE( *svpp ) ) {
1407 sv_setiv( *svpp, ++trie->uniquecharcount );
1412 if( cur == first ) {
1415 } else if (chars < trie->minlen) {
1417 } else if (chars > trie->maxlen) {
1421 } /* end first pass */
1422 DEBUG_TRIE_COMPILE_r(
1423 PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1424 (int)depth * 2 + 2,"",
1425 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
1426 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1427 (int)trie->minlen, (int)trie->maxlen )
1429 trie->wordlen = (U32 *) PerlMemShared_calloc( word_count, sizeof(U32) );
1432 We now know what we are dealing with in terms of unique chars and
1433 string sizes so we can calculate how much memory a naive
1434 representation using a flat table will take. If it's over a reasonable
1435 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
1436 conservative but potentially much slower representation using an array
1439 At the end we convert both representations into the same compressed
1440 form that will be used in regexec.c for matching with. The latter
1441 is a form that cannot be used to construct with but has memory
1442 properties similar to the list form and access properties similar
1443 to the table form making it both suitable for fast searches and
1444 small enough that its feasable to store for the duration of a program.
1446 See the comment in the code where the compressed table is produced
1447 inplace from the flat tabe representation for an explanation of how
1448 the compression works.
1453 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
1455 Second Pass -- Array Of Lists Representation
1457 Each state will be represented by a list of charid:state records
1458 (reg_trie_trans_le) the first such element holds the CUR and LEN
1459 points of the allocated array. (See defines above).
1461 We build the initial structure using the lists, and then convert
1462 it into the compressed table form which allows faster lookups
1463 (but cant be modified once converted).
1466 STRLEN transcount = 1;
1468 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1469 "%*sCompiling trie using list compiler\n",
1470 (int)depth * 2 + 2, ""));
1472 trie->states = (reg_trie_state *)
1473 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1474 sizeof(reg_trie_state) );
1478 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1480 regnode * const noper = NEXTOPER( cur );
1481 U8 *uc = (U8*)STRING( noper );
1482 const U8 * const e = uc + STR_LEN( noper );
1483 U32 state = 1; /* required init */
1484 U16 charid = 0; /* sanity init */
1485 U8 *scan = (U8*)NULL; /* sanity init */
1486 STRLEN foldlen = 0; /* required init */
1487 U32 wordlen = 0; /* required init */
1488 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1490 if (OP(noper) != NOTHING) {
1491 for ( ; uc < e ; uc += len ) {
1496 charid = trie->charmap[ uvc ];
1498 SV** const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
1502 charid=(U16)SvIV( *svpp );
1505 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1512 if ( !trie->states[ state ].trans.list ) {
1513 TRIE_LIST_NEW( state );
1515 for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1516 if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1517 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1522 newstate = next_alloc++;
1523 TRIE_LIST_PUSH( state, charid, newstate );
1528 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1532 TRIE_HANDLE_WORD(state);
1534 } /* end second pass */
1536 /* next alloc is the NEXT state to be allocated */
1537 trie->statecount = next_alloc;
1538 trie->states = (reg_trie_state *)
1539 PerlMemShared_realloc( trie->states,
1541 * sizeof(reg_trie_state) );
1543 /* and now dump it out before we compress it */
1544 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
1545 revcharmap, next_alloc,
1549 trie->trans = (reg_trie_trans *)
1550 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
1557 for( state=1 ; state < next_alloc ; state ++ ) {
1561 DEBUG_TRIE_COMPILE_MORE_r(
1562 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1566 if (trie->states[state].trans.list) {
1567 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1571 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1572 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1573 if ( forid < minid ) {
1575 } else if ( forid > maxid ) {
1579 if ( transcount < tp + maxid - minid + 1) {
1581 trie->trans = (reg_trie_trans *)
1582 PerlMemShared_realloc( trie->trans,
1584 * sizeof(reg_trie_trans) );
1585 Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1587 base = trie->uniquecharcount + tp - minid;
1588 if ( maxid == minid ) {
1590 for ( ; zp < tp ; zp++ ) {
1591 if ( ! trie->trans[ zp ].next ) {
1592 base = trie->uniquecharcount + zp - minid;
1593 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1594 trie->trans[ zp ].check = state;
1600 trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1601 trie->trans[ tp ].check = state;
1606 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1607 const U32 tid = base - trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
1608 trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1609 trie->trans[ tid ].check = state;
1611 tp += ( maxid - minid + 1 );
1613 Safefree(trie->states[ state ].trans.list);
1616 DEBUG_TRIE_COMPILE_MORE_r(
1617 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1620 trie->states[ state ].trans.base=base;
1622 trie->lasttrans = tp + 1;
1626 Second Pass -- Flat Table Representation.
1628 we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1629 We know that we will need Charcount+1 trans at most to store the data
1630 (one row per char at worst case) So we preallocate both structures
1631 assuming worst case.
1633 We then construct the trie using only the .next slots of the entry
1636 We use the .check field of the first entry of the node temporarily to
1637 make compression both faster and easier by keeping track of how many non
1638 zero fields are in the node.
1640 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1643 There are two terms at use here: state as a TRIE_NODEIDX() which is a
1644 number representing the first entry of the node, and state as a
1645 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1646 TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1647 are 2 entrys per node. eg:
1655 The table is internally in the right hand, idx form. However as we also
1656 have to deal with the states array which is indexed by nodenum we have to
1657 use TRIE_NODENUM() to convert.
1660 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1661 "%*sCompiling trie using table compiler\n",
1662 (int)depth * 2 + 2, ""));
1664 trie->trans = (reg_trie_trans *)
1665 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
1666 * trie->uniquecharcount + 1,
1667 sizeof(reg_trie_trans) );
1668 trie->states = (reg_trie_state *)
1669 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1670 sizeof(reg_trie_state) );
1671 next_alloc = trie->uniquecharcount + 1;
1674 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1676 regnode * const noper = NEXTOPER( cur );
1677 const U8 *uc = (U8*)STRING( noper );
1678 const U8 * const e = uc + STR_LEN( noper );
1680 U32 state = 1; /* required init */
1682 U16 charid = 0; /* sanity init */
1683 U32 accept_state = 0; /* sanity init */
1684 U8 *scan = (U8*)NULL; /* sanity init */
1686 STRLEN foldlen = 0; /* required init */
1687 U32 wordlen = 0; /* required init */
1688 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1690 if ( OP(noper) != NOTHING ) {
1691 for ( ; uc < e ; uc += len ) {
1696 charid = trie->charmap[ uvc ];
1698 SV* const * const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
1699 charid = svpp ? (U16)SvIV(*svpp) : 0;
1703 if ( !trie->trans[ state + charid ].next ) {
1704 trie->trans[ state + charid ].next = next_alloc;
1705 trie->trans[ state ].check++;
1706 next_alloc += trie->uniquecharcount;
1708 state = trie->trans[ state + charid ].next;
1710 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1712 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1715 accept_state = TRIE_NODENUM( state );
1716 TRIE_HANDLE_WORD(accept_state);
1718 } /* end second pass */
1720 /* and now dump it out before we compress it */
1721 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
1723 next_alloc, depth+1));
1727 * Inplace compress the table.*
1729 For sparse data sets the table constructed by the trie algorithm will
1730 be mostly 0/FAIL transitions or to put it another way mostly empty.
1731 (Note that leaf nodes will not contain any transitions.)
1733 This algorithm compresses the tables by eliminating most such
1734 transitions, at the cost of a modest bit of extra work during lookup:
1736 - Each states[] entry contains a .base field which indicates the
1737 index in the state[] array wheres its transition data is stored.
1739 - If .base is 0 there are no valid transitions from that node.
1741 - If .base is nonzero then charid is added to it to find an entry in
1744 -If trans[states[state].base+charid].check!=state then the
1745 transition is taken to be a 0/Fail transition. Thus if there are fail
1746 transitions at the front of the node then the .base offset will point
1747 somewhere inside the previous nodes data (or maybe even into a node
1748 even earlier), but the .check field determines if the transition is
1752 The following process inplace converts the table to the compressed
1753 table: We first do not compress the root node 1,and mark its all its
1754 .check pointers as 1 and set its .base pointer as 1 as well. This
1755 allows to do a DFA construction from the compressed table later, and
1756 ensures that any .base pointers we calculate later are greater than
1759 - We set 'pos' to indicate the first entry of the second node.
1761 - We then iterate over the columns of the node, finding the first and
1762 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
1763 and set the .check pointers accordingly, and advance pos
1764 appropriately and repreat for the next node. Note that when we copy
1765 the next pointers we have to convert them from the original
1766 NODEIDX form to NODENUM form as the former is not valid post
1769 - If a node has no transitions used we mark its base as 0 and do not
1770 advance the pos pointer.
1772 - If a node only has one transition we use a second pointer into the
1773 structure to fill in allocated fail transitions from other states.
1774 This pointer is independent of the main pointer and scans forward
1775 looking for null transitions that are allocated to a state. When it
1776 finds one it writes the single transition into the "hole". If the
1777 pointer doesnt find one the single transition is appended as normal.
1779 - Once compressed we can Renew/realloc the structures to release the
1782 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
1783 specifically Fig 3.47 and the associated pseudocode.
1787 const U32 laststate = TRIE_NODENUM( next_alloc );
1790 trie->statecount = laststate;
1792 for ( state = 1 ; state < laststate ; state++ ) {
1794 const U32 stateidx = TRIE_NODEIDX( state );
1795 const U32 o_used = trie->trans[ stateidx ].check;
1796 U32 used = trie->trans[ stateidx ].check;
1797 trie->trans[ stateidx ].check = 0;
1799 for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
1800 if ( flag || trie->trans[ stateidx + charid ].next ) {
1801 if ( trie->trans[ stateidx + charid ].next ) {
1803 for ( ; zp < pos ; zp++ ) {
1804 if ( ! trie->trans[ zp ].next ) {
1808 trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
1809 trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1810 trie->trans[ zp ].check = state;
1811 if ( ++zp > pos ) pos = zp;
1818 trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
1820 trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1821 trie->trans[ pos ].check = state;
1826 trie->lasttrans = pos + 1;
1827 trie->states = (reg_trie_state *)
1828 PerlMemShared_realloc( trie->states, laststate
1829 * sizeof(reg_trie_state) );
1830 DEBUG_TRIE_COMPILE_MORE_r(
1831 PerlIO_printf( Perl_debug_log,
1832 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
1833 (int)depth * 2 + 2,"",
1834 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
1837 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
1840 } /* end table compress */
1842 DEBUG_TRIE_COMPILE_MORE_r(
1843 PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
1844 (int)depth * 2 + 2, "",
1845 (UV)trie->statecount,
1846 (UV)trie->lasttrans)
1848 /* resize the trans array to remove unused space */
1849 trie->trans = (reg_trie_trans *)
1850 PerlMemShared_realloc( trie->trans, trie->lasttrans
1851 * sizeof(reg_trie_trans) );
1853 /* and now dump out the compressed format */
1854 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
1856 { /* Modify the program and insert the new TRIE node*/
1857 U8 nodetype =(U8)(flags & 0xFF);
1861 regnode *optimize = NULL;
1862 #ifdef RE_TRACK_PATTERN_OFFSETS
1865 U32 mjd_nodelen = 0;
1866 #endif /* RE_TRACK_PATTERN_OFFSETS */
1867 #endif /* DEBUGGING */
1869 This means we convert either the first branch or the first Exact,
1870 depending on whether the thing following (in 'last') is a branch
1871 or not and whther first is the startbranch (ie is it a sub part of
1872 the alternation or is it the whole thing.)
1873 Assuming its a sub part we conver the EXACT otherwise we convert
1874 the whole branch sequence, including the first.
1876 /* Find the node we are going to overwrite */
1877 if ( first != startbranch || OP( last ) == BRANCH ) {
1878 /* branch sub-chain */
1879 NEXT_OFF( first ) = (U16)(last - first);
1880 #ifdef RE_TRACK_PATTERN_OFFSETS
1882 mjd_offset= Node_Offset((convert));
1883 mjd_nodelen= Node_Length((convert));
1886 /* whole branch chain */
1888 #ifdef RE_TRACK_PATTERN_OFFSETS
1891 const regnode *nop = NEXTOPER( convert );
1892 mjd_offset= Node_Offset((nop));
1893 mjd_nodelen= Node_Length((nop));
1897 PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
1898 (int)depth * 2 + 2, "",
1899 (UV)mjd_offset, (UV)mjd_nodelen)
1902 /* But first we check to see if there is a common prefix we can
1903 split out as an EXACT and put in front of the TRIE node. */
1904 trie->startstate= 1;
1905 if ( trie->bitmap && !widecharmap && !trie->jump ) {
1907 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
1911 const U32 base = trie->states[ state ].trans.base;
1913 if ( trie->states[state].wordnum )
1916 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1917 if ( ( base + ofs >= trie->uniquecharcount ) &&
1918 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
1919 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
1921 if ( ++count > 1 ) {
1922 SV **tmp = av_fetch( revcharmap, ofs, 0);
1923 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
1924 if ( state == 1 ) break;
1926 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
1928 PerlIO_printf(Perl_debug_log,
1929 "%*sNew Start State=%"UVuf" Class: [",
1930 (int)depth * 2 + 2, "",
1933 SV ** const tmp = av_fetch( revcharmap, idx, 0);
1934 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
1936 TRIE_BITMAP_SET(trie,*ch);
1938 TRIE_BITMAP_SET(trie, folder[ *ch ]);
1940 PerlIO_printf(Perl_debug_log, (char*)ch)
1944 TRIE_BITMAP_SET(trie,*ch);
1946 TRIE_BITMAP_SET(trie,folder[ *ch ]);
1947 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
1953 SV **tmp = av_fetch( revcharmap, idx, 0);
1954 char *ch = SvPV_nolen( *tmp );
1956 SV *sv=sv_newmortal();
1957 PerlIO_printf( Perl_debug_log,
1958 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
1959 (int)depth * 2 + 2, "",
1961 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
1962 PL_colors[0], PL_colors[1],
1963 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1964 PERL_PV_ESCAPE_FIRSTCHAR
1969 OP( convert ) = nodetype;
1970 str=STRING(convert);
1981 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
1987 regnode *n = convert+NODE_SZ_STR(convert);
1988 NEXT_OFF(convert) = NODE_SZ_STR(convert);
1989 trie->startstate = state;
1990 trie->minlen -= (state - 1);
1991 trie->maxlen -= (state - 1);
1993 regnode *fix = convert;
1994 U32 word = trie->wordcount;
1996 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
1997 while( ++fix < n ) {
1998 Set_Node_Offset_Length(fix, 0, 0);
2001 SV ** const tmp = av_fetch( trie_words, word, 0 );
2003 if ( STR_LEN(convert) <= SvCUR(*tmp) )
2004 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
2006 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
2013 NEXT_OFF(convert) = (U16)(tail - convert);
2014 DEBUG_r(optimize= n);
2020 if ( trie->maxlen ) {
2021 NEXT_OFF( convert ) = (U16)(tail - convert);
2022 ARG_SET( convert, data_slot );
2023 /* Store the offset to the first unabsorbed branch in
2024 jump[0], which is otherwise unused by the jump logic.
2025 We use this when dumping a trie and during optimisation. */
2027 trie->jump[0] = (U16)(nextbranch - convert);
2030 if ( !trie->states[trie->startstate].wordnum && trie->bitmap &&
2031 ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
2033 OP( convert ) = TRIEC;
2034 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
2035 PerlMemShared_free(trie->bitmap);
2038 OP( convert ) = TRIE;
2040 /* store the type in the flags */
2041 convert->flags = nodetype;
2045 + regarglen[ OP( convert ) ];
2047 /* XXX We really should free up the resource in trie now,
2048 as we won't use them - (which resources?) dmq */
2050 /* needed for dumping*/
2051 DEBUG_r(if (optimize) {
2052 regnode *opt = convert;
2054 while ( ++opt < optimize) {
2055 Set_Node_Offset_Length(opt,0,0);
2058 Try to clean up some of the debris left after the
2061 while( optimize < jumper ) {
2062 mjd_nodelen += Node_Length((optimize));
2063 OP( optimize ) = OPTIMIZED;
2064 Set_Node_Offset_Length(optimize,0,0);
2067 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
2069 } /* end node insert */
2070 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
2072 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
2073 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
2075 SvREFCNT_dec(revcharmap);
2079 : trie->startstate>1
2085 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source, regnode *stclass, U32 depth)
2087 /* The Trie is constructed and compressed now so we can build a fail array now if its needed
2089 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
2090 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
2093 We find the fail state for each state in the trie, this state is the longest proper
2094 suffix of the current states 'word' that is also a proper prefix of another word in our
2095 trie. State 1 represents the word '' and is the thus the default fail state. This allows
2096 the DFA not to have to restart after its tried and failed a word at a given point, it
2097 simply continues as though it had been matching the other word in the first place.
2099 'abcdgu'=~/abcdefg|cdgu/
2100 When we get to 'd' we are still matching the first word, we would encounter 'g' which would
2101 fail, which would bring use to the state representing 'd' in the second word where we would
2102 try 'g' and succeed, prodceding to match 'cdgu'.
2104 /* add a fail transition */
2105 const U32 trie_offset = ARG(source);
2106 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
2108 const U32 ucharcount = trie->uniquecharcount;
2109 const U32 numstates = trie->statecount;
2110 const U32 ubound = trie->lasttrans + ucharcount;
2114 U32 base = trie->states[ 1 ].trans.base;
2117 const U32 data_slot = add_data( pRExC_state, 1, "T" );
2118 GET_RE_DEBUG_FLAGS_DECL;
2120 PERL_UNUSED_ARG(depth);
2124 ARG_SET( stclass, data_slot );
2125 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
2126 RExC_rxi->data->data[ data_slot ] = (void*)aho;
2127 aho->trie=trie_offset;
2128 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
2129 Copy( trie->states, aho->states, numstates, reg_trie_state );
2130 Newxz( q, numstates, U32);
2131 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
2134 /* initialize fail[0..1] to be 1 so that we always have
2135 a valid final fail state */
2136 fail[ 0 ] = fail[ 1 ] = 1;
2138 for ( charid = 0; charid < ucharcount ; charid++ ) {
2139 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2141 q[ q_write ] = newstate;
2142 /* set to point at the root */
2143 fail[ q[ q_write++ ] ]=1;
2146 while ( q_read < q_write) {
2147 const U32 cur = q[ q_read++ % numstates ];
2148 base = trie->states[ cur ].trans.base;
2150 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2151 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2153 U32 fail_state = cur;
2156 fail_state = fail[ fail_state ];
2157 fail_base = aho->states[ fail_state ].trans.base;
2158 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2160 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2161 fail[ ch_state ] = fail_state;
2162 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2164 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
2166 q[ q_write++ % numstates] = ch_state;
2170 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2171 when we fail in state 1, this allows us to use the
2172 charclass scan to find a valid start char. This is based on the principle
2173 that theres a good chance the string being searched contains lots of stuff
2174 that cant be a start char.
2176 fail[ 0 ] = fail[ 1 ] = 0;
2177 DEBUG_TRIE_COMPILE_r({
2178 PerlIO_printf(Perl_debug_log,
2179 "%*sStclass Failtable (%"UVuf" states): 0",
2180 (int)(depth * 2), "", (UV)numstates
2182 for( q_read=1; q_read<numstates; q_read++ ) {
2183 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2185 PerlIO_printf(Perl_debug_log, "\n");
2188 /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2193 * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2194 * These need to be revisited when a newer toolchain becomes available.
2196 #if defined(__sparc64__) && defined(__GNUC__)
2197 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2198 # undef SPARC64_GCC_WORKAROUND
2199 # define SPARC64_GCC_WORKAROUND 1
2203 #define DEBUG_PEEP(str,scan,depth) \
2204 DEBUG_OPTIMISE_r({if (scan){ \
2205 SV * const mysv=sv_newmortal(); \
2206 regnode *Next = regnext(scan); \
2207 regprop(RExC_rx, mysv, scan); \
2208 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
2209 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2210 Next ? (REG_NODE_NUM(Next)) : 0 ); \
2217 #define JOIN_EXACT(scan,min,flags) \
2218 if (PL_regkind[OP(scan)] == EXACT) \
2219 join_exact(pRExC_state,(scan),(min),(flags),NULL,depth+1)
2222 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, I32 *min, U32 flags,regnode *val, U32 depth) {
2223 /* Merge several consecutive EXACTish nodes into one. */
2224 regnode *n = regnext(scan);
2226 regnode *next = scan + NODE_SZ_STR(scan);
2230 regnode *stop = scan;
2231 GET_RE_DEBUG_FLAGS_DECL;
2233 PERL_UNUSED_ARG(depth);
2235 #ifndef EXPERIMENTAL_INPLACESCAN
2236 PERL_UNUSED_ARG(flags);
2237 PERL_UNUSED_ARG(val);
2239 DEBUG_PEEP("join",scan,depth);
2241 /* Skip NOTHING, merge EXACT*. */
2243 ( PL_regkind[OP(n)] == NOTHING ||
2244 (stringok && (OP(n) == OP(scan))))
2246 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
2248 if (OP(n) == TAIL || n > next)
2250 if (PL_regkind[OP(n)] == NOTHING) {
2251 DEBUG_PEEP("skip:",n,depth);
2252 NEXT_OFF(scan) += NEXT_OFF(n);
2253 next = n + NODE_STEP_REGNODE;
2260 else if (stringok) {
2261 const unsigned int oldl = STR_LEN(scan);
2262 regnode * const nnext = regnext(n);
2264 DEBUG_PEEP("merg",n,depth);
2267 if (oldl + STR_LEN(n) > U8_MAX)
2269 NEXT_OFF(scan) += NEXT_OFF(n);
2270 STR_LEN(scan) += STR_LEN(n);
2271 next = n + NODE_SZ_STR(n);
2272 /* Now we can overwrite *n : */
2273 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2281 #ifdef EXPERIMENTAL_INPLACESCAN
2282 if (flags && !NEXT_OFF(n)) {
2283 DEBUG_PEEP("atch", val, depth);
2284 if (reg_off_by_arg[OP(n)]) {
2285 ARG_SET(n, val - n);
2288 NEXT_OFF(n) = val - n;
2295 if (UTF && ( OP(scan) == EXACTF ) && ( STR_LEN(scan) >= 6 ) ) {
2297 Two problematic code points in Unicode casefolding of EXACT nodes:
2299 U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2300 U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2306 U+03B9 U+0308 U+0301 0xCE 0xB9 0xCC 0x88 0xCC 0x81
2307 U+03C5 U+0308 U+0301 0xCF 0x85 0xCC 0x88 0xCC 0x81
2309 This means that in case-insensitive matching (or "loose matching",
2310 as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte
2311 length of the above casefolded versions) can match a target string
2312 of length two (the byte length of UTF-8 encoded U+0390 or U+03B0).
2313 This would rather mess up the minimum length computation.
2315 What we'll do is to look for the tail four bytes, and then peek
2316 at the preceding two bytes to see whether we need to decrease
2317 the minimum length by four (six minus two).
2319 Thanks to the design of UTF-8, there cannot be false matches:
2320 A sequence of valid UTF-8 bytes cannot be a subsequence of
2321 another valid sequence of UTF-8 bytes.
2324 char * const s0 = STRING(scan), *s, *t;
2325 char * const s1 = s0 + STR_LEN(scan) - 1;
2326 char * const s2 = s1 - 4;
2327 #ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2328 const char t0[] = "\xaf\x49\xaf\x42";
2330 const char t0[] = "\xcc\x88\xcc\x81";
2332 const char * const t1 = t0 + 3;
2335 s < s2 && (t = ninstr(s, s1, t0, t1));
2338 if (((U8)t[-1] == 0x68 && (U8)t[-2] == 0xB4) ||
2339 ((U8)t[-1] == 0x46 && (U8)t[-2] == 0xB5))
2341 if (((U8)t[-1] == 0xB9 && (U8)t[-2] == 0xCE) ||
2342 ((U8)t[-1] == 0x85 && (U8)t[-2] == 0xCF))
2350 n = scan + NODE_SZ_STR(scan);
2352 if (PL_regkind[OP(n)] != NOTHING || OP(n) == NOTHING) {
2359 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2363 /* REx optimizer. Converts nodes into quickier variants "in place".
2364 Finds fixed substrings. */
2366 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
2367 to the position after last scanned or to NULL. */
2369 #define INIT_AND_WITHP \
2370 assert(!and_withp); \
2371 Newx(and_withp,1,struct regnode_charclass_class); \
2372 SAVEFREEPV(and_withp)
2374 /* this is a chain of data about sub patterns we are processing that
2375 need to be handled seperately/specially in study_chunk. Its so
2376 we can simulate recursion without losing state. */
2378 typedef struct scan_frame {
2379 regnode *last; /* last node to process in this frame */
2380 regnode *next; /* next node to process when last is reached */
2381 struct scan_frame *prev; /*previous frame*/
2382 I32 stop; /* what stopparen do we use */
2386 #define SCAN_COMMIT(s, data, m) scan_commit(s, data, m, is_inf)
2389 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
2390 I32 *minlenp, I32 *deltap,
2395 struct regnode_charclass_class *and_withp,
2396 U32 flags, U32 depth)
2397 /* scanp: Start here (read-write). */
2398 /* deltap: Write maxlen-minlen here. */
2399 /* last: Stop before this one. */
2400 /* data: string data about the pattern */
2401 /* stopparen: treat close N as END */
2402 /* recursed: which subroutines have we recursed into */
2403 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
2406 I32 min = 0, pars = 0, code;
2407 regnode *scan = *scanp, *next;
2409 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
2410 int is_inf_internal = 0; /* The studied chunk is infinite */
2411 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2412 scan_data_t data_fake;
2413 SV *re_trie_maxbuff = NULL;
2414 regnode *first_non_open = scan;
2415 I32 stopmin = I32_MAX;
2416 scan_frame *frame = NULL;
2418 GET_RE_DEBUG_FLAGS_DECL;
2421 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
2425 while (first_non_open && OP(first_non_open) == OPEN)
2426 first_non_open=regnext(first_non_open);
2431 while ( scan && OP(scan) != END && scan < last ){
2432 /* Peephole optimizer: */
2433 DEBUG_STUDYDATA("Peep:", data,depth);
2434 DEBUG_PEEP("Peep",scan,depth);
2435 JOIN_EXACT(scan,&min,0);
2437 /* Follow the next-chain of the current node and optimize
2438 away all the NOTHINGs from it. */
2439 if (OP(scan) != CURLYX) {
2440 const int max = (reg_off_by_arg[OP(scan)]
2442 /* I32 may be smaller than U16 on CRAYs! */
2443 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
2444 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
2448 /* Skip NOTHING and LONGJMP. */
2449 while ((n = regnext(n))
2450 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
2451 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
2452 && off + noff < max)
2454 if (reg_off_by_arg[OP(scan)])
2457 NEXT_OFF(scan) = off;
2462 /* The principal pseudo-switch. Cannot be a switch, since we
2463 look into several different things. */
2464 if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
2465 || OP(scan) == IFTHEN) {
2466 next = regnext(scan);
2468 /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
2470 if (OP(next) == code || code == IFTHEN) {
2471 /* NOTE - There is similar code to this block below for handling
2472 TRIE nodes on a re-study. If you change stuff here check there
2474 I32 max1 = 0, min1 = I32_MAX, num = 0;
2475 struct regnode_charclass_class accum;
2476 regnode * const startbranch=scan;
2478 if (flags & SCF_DO_SUBSTR)
2479 SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
2480 if (flags & SCF_DO_STCLASS)
2481 cl_init_zero(pRExC_state, &accum);
2483 while (OP(scan) == code) {
2484 I32 deltanext, minnext, f = 0, fake;
2485 struct regnode_charclass_class this_class;
2488 data_fake.flags = 0;
2490 data_fake.whilem_c = data->whilem_c;
2491 data_fake.last_closep = data->last_closep;
2494 data_fake.last_closep = &fake;
2496 data_fake.pos_delta = delta;
2497 next = regnext(scan);
2498 scan = NEXTOPER(scan);
2500 scan = NEXTOPER(scan);
2501 if (flags & SCF_DO_STCLASS) {
2502 cl_init(pRExC_state, &this_class);
2503 data_fake.start_class = &this_class;
2504 f = SCF_DO_STCLASS_AND;
2506 if (flags & SCF_WHILEM_VISITED_POS)
2507 f |= SCF_WHILEM_VISITED_POS;
2509 /* we suppose the run is continuous, last=next...*/
2510 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2512 stopparen, recursed, NULL, f,depth+1);
2515 if (max1 < minnext + deltanext)
2516 max1 = minnext + deltanext;
2517 if (deltanext == I32_MAX)
2518 is_inf = is_inf_internal = 1;
2520 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
2522 if (data_fake.flags & SCF_SEEN_ACCEPT) {
2523 if ( stopmin > minnext)
2524 stopmin = min + min1;
2525 flags &= ~SCF_DO_SUBSTR;
2527 data->flags |= SCF_SEEN_ACCEPT;
2530 if (data_fake.flags & SF_HAS_EVAL)
2531 data->flags |= SF_HAS_EVAL;
2532 data->whilem_c = data_fake.whilem_c;
2534 if (flags & SCF_DO_STCLASS)
2535 cl_or(pRExC_state, &accum, &this_class);
2537 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
2539 if (flags & SCF_DO_SUBSTR) {
2540 data->pos_min += min1;
2541 data->pos_delta += max1 - min1;
2542 if (max1 != min1 || is_inf)
2543 data->longest = &(data->longest_float);
2546 delta += max1 - min1;
2547 if (flags & SCF_DO_STCLASS_OR) {
2548 cl_or(pRExC_state, data->start_class, &accum);
2550 cl_and(data->start_class, and_withp);
2551 flags &= ~SCF_DO_STCLASS;
2554 else if (flags & SCF_DO_STCLASS_AND) {
2556 cl_and(data->start_class, &accum);
2557 flags &= ~SCF_DO_STCLASS;
2560 /* Switch to OR mode: cache the old value of
2561 * data->start_class */
2563 StructCopy(data->start_class, and_withp,
2564 struct regnode_charclass_class);
2565 flags &= ~SCF_DO_STCLASS_AND;
2566 StructCopy(&accum, data->start_class,
2567 struct regnode_charclass_class);
2568 flags |= SCF_DO_STCLASS_OR;
2569 data->start_class->flags |= ANYOF_EOS;
2573 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
2576 Assuming this was/is a branch we are dealing with: 'scan' now
2577 points at the item that follows the branch sequence, whatever
2578 it is. We now start at the beginning of the sequence and look
2585 which would be constructed from a pattern like /A|LIST|OF|WORDS/
2587 If we can find such a subseqence we need to turn the first
2588 element into a trie and then add the subsequent branch exact
2589 strings to the trie.
2593 1. patterns where the whole set of branch can be converted.
2595 2. patterns where only a subset can be converted.
2597 In case 1 we can replace the whole set with a single regop
2598 for the trie. In case 2 we need to keep the start and end
2601 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
2602 becomes BRANCH TRIE; BRANCH X;
2604 There is an additional case, that being where there is a
2605 common prefix, which gets split out into an EXACT like node
2606 preceding the TRIE node.
2608 If x(1..n)==tail then we can do a simple trie, if not we make
2609 a "jump" trie, such that when we match the appropriate word
2610 we "jump" to the appopriate tail node. Essentailly we turn
2611 a nested if into a case structure of sorts.
2616 if (!re_trie_maxbuff) {
2617 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2618 if (!SvIOK(re_trie_maxbuff))
2619 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2621 if ( SvIV(re_trie_maxbuff)>=0 ) {
2623 regnode *first = (regnode *)NULL;
2624 regnode *last = (regnode *)NULL;
2625 regnode *tail = scan;
2630 SV * const mysv = sv_newmortal(); /* for dumping */
2632 /* var tail is used because there may be a TAIL
2633 regop in the way. Ie, the exacts will point to the
2634 thing following the TAIL, but the last branch will
2635 point at the TAIL. So we advance tail. If we
2636 have nested (?:) we may have to move through several
2640 while ( OP( tail ) == TAIL ) {
2641 /* this is the TAIL generated by (?:) */
2642 tail = regnext( tail );
2647 regprop(RExC_rx, mysv, tail );
2648 PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
2649 (int)depth * 2 + 2, "",
2650 "Looking for TRIE'able sequences. Tail node is: ",
2651 SvPV_nolen_const( mysv )
2657 step through the branches, cur represents each
2658 branch, noper is the first thing to be matched
2659 as part of that branch and noper_next is the
2660 regnext() of that node. if noper is an EXACT
2661 and noper_next is the same as scan (our current
2662 position in the regex) then the EXACT branch is
2663 a possible optimization target. Once we have
2664 two or more consequetive such branches we can
2665 create a trie of the EXACT's contents and stich
2666 it in place. If the sequence represents all of
2667 the branches we eliminate the whole thing and
2668 replace it with a single TRIE. If it is a
2669 subsequence then we need to stitch it in. This
2670 means the first branch has to remain, and needs
2671 to be repointed at the item on the branch chain
2672 following the last branch optimized. This could
2673 be either a BRANCH, in which case the
2674 subsequence is internal, or it could be the
2675 item following the branch sequence in which
2676 case the subsequence is at the end.
2680 /* dont use tail as the end marker for this traverse */
2681 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
2682 regnode * const noper = NEXTOPER( cur );
2683 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
2684 regnode * const noper_next = regnext( noper );
2688 regprop(RExC_rx, mysv, cur);
2689 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
2690 (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
2692 regprop(RExC_rx, mysv, noper);
2693 PerlIO_printf( Perl_debug_log, " -> %s",
2694 SvPV_nolen_const(mysv));
2697 regprop(RExC_rx, mysv, noper_next );
2698 PerlIO_printf( Perl_debug_log,"\t=> %s\t",
2699 SvPV_nolen_const(mysv));
2701 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
2702 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
2704 if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
2705 : PL_regkind[ OP( noper ) ] == EXACT )
2706 || OP(noper) == NOTHING )
2708 && noper_next == tail
2713 if ( !first || optype == NOTHING ) {
2714 if (!first) first = cur;
2715 optype = OP( noper );
2721 make_trie( pRExC_state,
2722 startbranch, first, cur, tail, count,
2725 if ( PL_regkind[ OP( noper ) ] == EXACT
2727 && noper_next == tail
2732 optype = OP( noper );
2742 regprop(RExC_rx, mysv, cur);
2743 PerlIO_printf( Perl_debug_log,
2744 "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
2745 "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
2749 made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
2750 #ifdef TRIE_STUDY_OPT
2751 if ( ((made == MADE_EXACT_TRIE &&
2752 startbranch == first)
2753 || ( first_non_open == first )) &&
2755 flags |= SCF_TRIE_RESTUDY;
2756 if ( startbranch == first
2759 RExC_seen &=~REG_TOP_LEVEL_BRANCHES;
2769 else if ( code == BRANCHJ ) { /* single branch is optimized. */
2770 scan = NEXTOPER(NEXTOPER(scan));
2771 } else /* single branch is optimized. */
2772 scan = NEXTOPER(scan);
2774 } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
2775 scan_frame *newframe = NULL;
2780 if (OP(scan) != SUSPEND) {
2781 /* set the pointer */
2782 if (OP(scan) == GOSUB) {
2784 RExC_recurse[ARG2L(scan)] = scan;
2785 start = RExC_open_parens[paren-1];
2786 end = RExC_close_parens[paren-1];
2789 start = RExC_rxi->program + 1;
2793 Newxz(recursed, (((RExC_npar)>>3) +1), U8);
2794 SAVEFREEPV(recursed);
2796 if (!PAREN_TEST(recursed,paren+1)) {
2797 PAREN_SET(recursed,paren+1);
2798 Newx(newframe,1,scan_frame);
2800 if (flags & SCF_DO_SUBSTR) {
2801 SCAN_COMMIT(pRExC_state,data,minlenp);
2802 data->longest = &(data->longest_float);
2804 is_inf = is_inf_internal = 1;
2805 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
2806 cl_anything(pRExC_state, data->start_class);
2807 flags &= ~SCF_DO_STCLASS;
2810 Newx(newframe,1,scan_frame);
2813 end = regnext(scan);
2818 SAVEFREEPV(newframe);
2819 newframe->next = regnext(scan);
2820 newframe->last = last;
2821 newframe->stop = stopparen;
2822 newframe->prev = frame;
2832 else if (OP(scan) == EXACT) {
2833 I32 l = STR_LEN(scan);
2836 const U8 * const s = (U8*)STRING(scan);
2837 l = utf8_length(s, s + l);
2838 uc = utf8_to_uvchr(s, NULL);
2840 uc = *((U8*)STRING(scan));
2843 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
2844 /* The code below prefers earlier match for fixed
2845 offset, later match for variable offset. */
2846 if (data->last_end == -1) { /* Update the start info. */
2847 data->last_start_min = data->pos_min;
2848 data->last_start_max = is_inf
2849 ? I32_MAX : data->pos_min + data->pos_delta;
2851 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
2853 SvUTF8_on(data->last_found);
2855 SV * const sv = data->last_found;
2856 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
2857 mg_find(sv, PERL_MAGIC_utf8) : NULL;
2858 if (mg && mg->mg_len >= 0)
2859 mg->mg_len += utf8_length((U8*)STRING(scan),
2860 (U8*)STRING(scan)+STR_LEN(scan));
2862 data->last_end = data->pos_min + l;
2863 data->pos_min += l; /* As in the first entry. */
2864 data->flags &= ~SF_BEFORE_EOL;
2866 if (flags & SCF_DO_STCLASS_AND) {
2867 /* Check whether it is compatible with what we know already! */
2871 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2872 && !ANYOF_BITMAP_TEST(data->start_class, uc)
2873 && (!(data->start_class->flags & ANYOF_FOLD)
2874 || !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2877 ANYOF_CLASS_ZERO(data->start_class);
2878 ANYOF_BITMAP_ZERO(data->start_class);
2880 ANYOF_BITMAP_SET(data->start_class, uc);
2881 data->start_class->flags &= ~ANYOF_EOS;
2883 data->start_class->flags &= ~ANYOF_UNICODE_ALL;
2885 else if (flags & SCF_DO_STCLASS_OR) {
2886 /* false positive possible if the class is case-folded */
2888 ANYOF_BITMAP_SET(data->start_class, uc);
2890 data->start_class->flags |= ANYOF_UNICODE_ALL;
2891 data->start_class->flags &= ~ANYOF_EOS;
2892 cl_and(data->start_class, and_withp);
2894 flags &= ~SCF_DO_STCLASS;
2896 else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
2897 I32 l = STR_LEN(scan);
2898 UV uc = *((U8*)STRING(scan));
2900 /* Search for fixed substrings supports EXACT only. */
2901 if (flags & SCF_DO_SUBSTR) {
2903 SCAN_COMMIT(pRExC_state, data, minlenp);
2906 const U8 * const s = (U8 *)STRING(scan);
2907 l = utf8_length(s, s + l);
2908 uc = utf8_to_uvchr(s, NULL);
2911 if (flags & SCF_DO_SUBSTR)
2913 if (flags & SCF_DO_STCLASS_AND) {
2914 /* Check whether it is compatible with what we know already! */
2918 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2919 && !ANYOF_BITMAP_TEST(data->start_class, uc)
2920 && !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2922 ANYOF_CLASS_ZERO(data->start_class);
2923 ANYOF_BITMAP_ZERO(data->start_class);
2925 ANYOF_BITMAP_SET(data->start_class, uc);
2926 data->start_class->flags &= ~ANYOF_EOS;
2927 data->start_class->flags |= ANYOF_FOLD;
2928 if (OP(scan) == EXACTFL)
2929 data->start_class->flags |= ANYOF_LOCALE;
2932 else if (flags & SCF_DO_STCLASS_OR) {
2933 if (data->start_class->flags & ANYOF_FOLD) {
2934 /* false positive possible if the class is case-folded.
2935 Assume that the locale settings are the same... */
2937 ANYOF_BITMAP_SET(data->start_class, uc);
2938 data->start_class->flags &= ~ANYOF_EOS;
2940 cl_and(data->start_class, and_withp);
2942 flags &= ~SCF_DO_STCLASS;
2944 else if (strchr((const char*)PL_varies,OP(scan))) {
2945 I32 mincount, maxcount, minnext, deltanext, fl = 0;
2946 I32 f = flags, pos_before = 0;
2947 regnode * const oscan = scan;
2948 struct regnode_charclass_class this_class;
2949 struct regnode_charclass_class *oclass = NULL;
2950 I32 next_is_eval = 0;
2952 switch (PL_regkind[OP(scan)]) {
2953 case WHILEM: /* End of (?:...)* . */
2954 scan = NEXTOPER(scan);
2957 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
2958 next = NEXTOPER(scan);
2959 if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
2961 maxcount = REG_INFTY;
2962 next = regnext(scan);
2963 scan = NEXTOPER(scan);
2967 if (flags & SCF_DO_SUBSTR)
2972 if (flags & SCF_DO_STCLASS) {
2974 maxcount = REG_INFTY;
2975 next = regnext(scan);
2976 scan = NEXTOPER(scan);
2979 is_inf = is_inf_internal = 1;
2980 scan = regnext(scan);
2981 if (flags & SCF_DO_SUBSTR) {
2982 SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
2983 data->longest = &(data->longest_float);
2985 goto optimize_curly_tail;
2987 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
2988 && (scan->flags == stopparen))
2993 mincount = ARG1(scan);
2994 maxcount = ARG2(scan);
2996 next = regnext(scan);
2997 if (OP(scan) == CURLYX) {
2998 I32 lp = (data ? *(data->last_closep) : 0);
2999 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
3001 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
3002 next_is_eval = (OP(scan) == EVAL);
3004 if (flags & SCF_DO_SUBSTR) {
3005 if (mincount == 0) SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
3006 pos_before = data->pos_min;
3010 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
3012 data->flags |= SF_IS_INF;
3014 if (flags & SCF_DO_STCLASS) {
3015 cl_init(pRExC_state, &this_class);
3016 oclass = data->start_class;
3017 data->start_class = &this_class;
3018 f |= SCF_DO_STCLASS_AND;
3019 f &= ~SCF_DO_STCLASS_OR;
3021 /* These are the cases when once a subexpression
3022 fails at a particular position, it cannot succeed
3023 even after backtracking at the enclosing scope.
3025 XXXX what if minimal match and we are at the
3026 initial run of {n,m}? */
3027 if ((mincount != maxcount - 1) && (maxcount != REG_INFTY))
3028 f &= ~SCF_WHILEM_VISITED_POS;
3030 /* This will finish on WHILEM, setting scan, or on NULL: */
3031 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
3032 last, data, stopparen, recursed, NULL,
3034 ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
3036 if (flags & SCF_DO_STCLASS)
3037 data->start_class = oclass;
3038 if (mincount == 0 || minnext == 0) {
3039 if (flags & SCF_DO_STCLASS_OR) {
3040 cl_or(pRExC_state, data->start_class, &this_class);
3042 else if (flags & SCF_DO_STCLASS_AND) {
3043 /* Switch to OR mode: cache the old value of
3044 * data->start_class */
3046 StructCopy(data->start_class, and_withp,
3047 struct regnode_charclass_class);
3048 flags &= ~SCF_DO_STCLASS_AND;
3049 StructCopy(&this_class, data->start_class,
3050 struct regnode_charclass_class);
3051 flags |= SCF_DO_STCLASS_OR;
3052 data->start_class->flags |= ANYOF_EOS;
3054 } else { /* Non-zero len */
3055 if (flags & SCF_DO_STCLASS_OR) {
3056 cl_or(pRExC_state, data->start_class, &this_class);
3057 cl_and(data->start_class, and_withp);
3059 else if (flags & SCF_DO_STCLASS_AND)
3060 cl_and(data->start_class, &this_class);
3061 flags &= ~SCF_DO_STCLASS;
3063 if (!scan) /* It was not CURLYX, but CURLY. */
3065 if ( /* ? quantifier ok, except for (?{ ... }) */
3066 (next_is_eval || !(mincount == 0 && maxcount == 1))
3067 && (minnext == 0) && (deltanext == 0)
3068 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
3069 && maxcount <= REG_INFTY/3 /* Complement check for big count */
3070 && ckWARN(WARN_REGEXP))
3073 "Quantifier unexpected on zero-length expression");
3076 min += minnext * mincount;
3077 is_inf_internal |= ((maxcount == REG_INFTY
3078 && (minnext + deltanext) > 0)
3079 || deltanext == I32_MAX);
3080 is_inf |= is_inf_internal;
3081 delta += (minnext + deltanext) * maxcount - minnext * mincount;
3083 /* Try powerful optimization CURLYX => CURLYN. */
3084 if ( OP(oscan) == CURLYX && data
3085 && data->flags & SF_IN_PAR
3086 && !(data->flags & SF_HAS_EVAL)
3087 && !deltanext && minnext == 1 ) {
3088 /* Try to optimize to CURLYN. */
3089 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
3090 regnode * const nxt1 = nxt;
3097 if (!strchr((const char*)PL_simple,OP(nxt))
3098 && !(PL_regkind[OP(nxt)] == EXACT
3099 && STR_LEN(nxt) == 1))
3105 if (OP(nxt) != CLOSE)
3107 if (RExC_open_parens) {
3108 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3109 RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
3111 /* Now we know that nxt2 is the only contents: */
3112 oscan->flags = (U8)ARG(nxt);
3114 OP(nxt1) = NOTHING; /* was OPEN. */
3117 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3118 NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
3119 NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
3120 OP(nxt) = OPTIMIZED; /* was CLOSE. */
3121 OP(nxt + 1) = OPTIMIZED; /* was count. */
3122 NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
3127 /* Try optimization CURLYX => CURLYM. */
3128 if ( OP(oscan) == CURLYX && data
3129 && !(data->flags & SF_HAS_PAR)
3130 && !(data->flags & SF_HAS_EVAL)
3131 && !deltanext /* atom is fixed width */
3132 && minnext != 0 /* CURLYM can't handle zero width */
3134 /* XXXX How to optimize if data == 0? */
3135 /* Optimize to a simpler form. */
3136 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
3140 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
3141 && (OP(nxt2) != WHILEM))
3143 OP(nxt2) = SUCCEED; /* Whas WHILEM */
3144 /* Need to optimize away parenths. */
3145 if (data->flags & SF_IN_PAR) {
3146 /* Set the parenth number. */
3147 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
3149 if (OP(nxt) != CLOSE)
3150 FAIL("Panic opt close");
3151 oscan->flags = (U8)ARG(nxt);
3152 if (RExC_open_parens) {
3153 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3154 RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
3156 OP(nxt1) = OPTIMIZED; /* was OPEN. */
3157 OP(nxt) = OPTIMIZED; /* was CLOSE. */
3160 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3161 OP(nxt + 1) = OPTIMIZED; /* was count. */
3162 NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
3163 NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
3166 while ( nxt1 && (OP(nxt1) != WHILEM)) {
3167 regnode *nnxt = regnext(nxt1);
3170 if (reg_off_by_arg[OP(nxt1)])
3171 ARG_SET(nxt1, nxt2 - nxt1);
3172 else if (nxt2 - nxt1 < U16_MAX)
3173 NEXT_OFF(nxt1) = nxt2 - nxt1;
3175 OP(nxt) = NOTHING; /* Cannot beautify */
3180 /* Optimize again: */
3181 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
3182 NULL, stopparen, recursed, NULL, 0,depth+1);
3187 else if ((OP(oscan) == CURLYX)
3188 && (flags & SCF_WHILEM_VISITED_POS)
3189 /* See the comment on a similar expression above.
3190 However, this time it not a subexpression
3191 we care about, but the expression itself. */
3192 && (maxcount == REG_INFTY)
3193 && data && ++data->whilem_c < 16) {
3194 /* This stays as CURLYX, we can put the count/of pair. */
3195 /* Find WHILEM (as in regexec.c) */
3196 regnode *nxt = oscan + NEXT_OFF(oscan);
3198 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
3200 PREVOPER(nxt)->flags = (U8)(data->whilem_c
3201 | (RExC_whilem_seen << 4)); /* On WHILEM */
3203 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
3205 if (flags & SCF_DO_SUBSTR) {
3206 SV *last_str = NULL;
3207 int counted = mincount != 0;
3209 if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
3210 #if defined(SPARC64_GCC_WORKAROUND)
3213 const char *s = NULL;
3216 if (pos_before >= data->last_start_min)
3219 b = data->last_start_min;
3222 s = SvPV_const(data->last_found, l);
3223 old = b - data->last_start_min;
3226 I32 b = pos_before >= data->last_start_min
3227 ? pos_before : data->last_start_min;
3229 const char * const s = SvPV_const(data->last_found, l);
3230 I32 old = b - data->last_start_min;
3234 old = utf8_hop((U8*)s, old) - (U8*)s;
3237 /* Get the added string: */
3238 last_str = newSVpvn(s + old, l);
3240 SvUTF8_on(last_str);
3241 if (deltanext == 0 && pos_before == b) {
3242 /* What was added is a constant string */
3244 SvGROW(last_str, (mincount * l) + 1);
3245 repeatcpy(SvPVX(last_str) + l,
3246 SvPVX_const(last_str), l, mincount - 1);
3247 SvCUR_set(last_str, SvCUR(last_str) * mincount);
3248 /* Add additional parts. */
3249 SvCUR_set(data->last_found,
3250 SvCUR(data->last_found) - l);
3251 sv_catsv(data->last_found, last_str);
3253 SV * sv = data->last_found;
3255 SvUTF8(sv) && SvMAGICAL(sv) ?
3256 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3257 if (mg && mg->mg_len >= 0)
3258 mg->mg_len += CHR_SVLEN(last_str);
3260 data->last_end += l * (mincount - 1);
3263 /* start offset must point into the last copy */
3264 data->last_start_min += minnext * (mincount - 1);
3265 data->last_start_max += is_inf ? I32_MAX
3266 : (maxcount - 1) * (minnext + data->pos_delta);
3269 /* It is counted once already... */
3270 data->pos_min += minnext * (mincount - counted);
3271 data->pos_delta += - counted * deltanext +
3272 (minnext + deltanext) * maxcount - minnext * mincount;
3273 if (mincount != maxcount) {
3274 /* Cannot extend fixed substrings found inside
3276 SCAN_COMMIT(pRExC_state,data,minlenp);
3277 if (mincount && last_str) {
3278 SV * const sv = data->last_found;
3279 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3280 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3284 sv_setsv(sv, last_str);
3285 data->last_end = data->pos_min;
3286 data->last_start_min =
3287 data->pos_min - CHR_SVLEN(last_str);
3288 data->last_start_max = is_inf
3290 : data->pos_min + data->pos_delta
3291 - CHR_SVLEN(last_str);
3293 data->longest = &(data->longest_float);
3295 SvREFCNT_dec(last_str);
3297 if (data && (fl & SF_HAS_EVAL))
3298 data->flags |= SF_HAS_EVAL;
3299 optimize_curly_tail:
3300 if (OP(oscan) != CURLYX) {
3301 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
3303 NEXT_OFF(oscan) += NEXT_OFF(next);
3306 default: /* REF and CLUMP only? */
3307 if (flags & SCF_DO_SUBSTR) {
3308 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3309 data->longest = &(data->longest_float);
3311 is_inf = is_inf_internal = 1;
3312 if (flags & SCF_DO_STCLASS_OR)
3313 cl_anything(pRExC_state, data->start_class);
3314 flags &= ~SCF_DO_STCLASS;
3318 else if (strchr((const char*)PL_simple,OP(scan))) {
3321 if (flags & SCF_DO_SUBSTR) {
3322 SCAN_COMMIT(pRExC_state,data,minlenp);
3326 if (flags & SCF_DO_STCLASS) {
3327 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3329 /* Some of the logic below assumes that switching
3330 locale on will only add false positives. */
3331 switch (PL_regkind[OP(scan)]) {
3335 /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
3336 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3337 cl_anything(pRExC_state, data->start_class);
3340 if (OP(scan) == SANY)
3342 if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
3343 value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
3344 || (data->start_class->flags & ANYOF_CLASS));
3345 cl_anything(pRExC_state, data->start_class);
3347 if (flags & SCF_DO_STCLASS_AND || !value)
3348 ANYOF_BITMAP_CLEAR(data->start_class,'\n');
3351 if (flags & SCF_DO_STCLASS_AND)
3352 cl_and(data->start_class,
3353 (struct regnode_charclass_class*)scan);
3355 cl_or(pRExC_state, data->start_class,
3356 (struct regnode_charclass_class*)scan);
3359 if (flags & SCF_DO_STCLASS_AND) {
3360 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3361 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3362 for (value = 0; value < 256; value++)
3363 if (!isALNUM(value))
3364 ANYOF_BITMAP_CLEAR(data->start_class, value);
3368 if (data->start_class->flags & ANYOF_LOCALE)
3369 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3371 for (value = 0; value < 256; value++)
3373 ANYOF_BITMAP_SET(data->start_class, value);
3378 if (flags & SCF_DO_STCLASS_AND) {
3379 if (data->start_class->flags & ANYOF_LOCALE)
3380 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3383 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3384 data->start_class->flags |= ANYOF_LOCALE;
3388 if (flags & SCF_DO_STCLASS_AND) {
3389 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3390 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3391 for (value = 0; value < 256; value++)
3393 ANYOF_BITMAP_CLEAR(data->start_class, value);
3397 if (data->start_class->flags & ANYOF_LOCALE)
3398 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3400 for (value = 0; value < 256; value++)
3401 if (!isALNUM(value))
3402 ANYOF_BITMAP_SET(data->start_class, value);
3407 if (flags & SCF_DO_STCLASS_AND) {
3408 if (data->start_class->flags & ANYOF_LOCALE)
3409 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3412 data->start_class->flags |= ANYOF_LOCALE;
3413 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3417 if (flags & SCF_DO_STCLASS_AND) {
3418 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3419 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3420 for (value = 0; value < 256; value++)
3421 if (!isSPACE(value))
3422 ANYOF_BITMAP_CLEAR(data->start_class, value);
3426 if (data->start_class->flags & ANYOF_LOCALE)
3427 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3429 for (value = 0; value < 256; value++)
3431 ANYOF_BITMAP_SET(data->start_class, value);
3436 if (flags & SCF_DO_STCLASS_AND) {
3437 if (data->start_class->flags & ANYOF_LOCALE)
3438 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3441 data->start_class->flags |= ANYOF_LOCALE;
3442 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3446 if (flags & SCF_DO_STCLASS_AND) {
3447 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3448 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3449 for (value = 0; value < 256; value++)
3451 ANYOF_BITMAP_CLEAR(data->start_class, value);
3455 if (data->start_class->flags & ANYOF_LOCALE)
3456 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3458 for (value = 0; value < 256; value++)
3459 if (!isSPACE(value))
3460 ANYOF_BITMAP_SET(data->start_class, value);
3465 if (flags & SCF_DO_STCLASS_AND) {
3466 if (data->start_class->flags & ANYOF_LOCALE) {
3467 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3468 for (value = 0; value < 256; value++)
3469 if (!isSPACE(value))
3470 ANYOF_BITMAP_CLEAR(data->start_class, value);
3474 data->start_class->flags |= ANYOF_LOCALE;
3475 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3479 if (flags & SCF_DO_STCLASS_AND) {
3480 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
3481 for (value = 0; value < 256; value++)
3482 if (!isDIGIT(value))
3483 ANYOF_BITMAP_CLEAR(data->start_class, value);
3486 if (data->start_class->flags & ANYOF_LOCALE)
3487 ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
3489 for (value = 0; value < 256; value++)
3491 ANYOF_BITMAP_SET(data->start_class, value);
3496 if (flags & SCF_DO_STCLASS_AND) {
3497 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
3498 for (value = 0; value < 256; value++)
3500 ANYOF_BITMAP_CLEAR(data->start_class, value);
3503 if (data->start_class->flags & ANYOF_LOCALE)
3504 ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
3506 for (value = 0; value < 256; value++)
3507 if (!isDIGIT(value))
3508 ANYOF_BITMAP_SET(data->start_class, value);
3513 if (flags & SCF_DO_STCLASS_OR)
3514 cl_and(data->start_class, and_withp);
3515 flags &= ~SCF_DO_STCLASS;
3518 else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
3519 data->flags |= (OP(scan) == MEOL
3523 else if ( PL_regkind[OP(scan)] == BRANCHJ
3524 /* Lookbehind, or need to calculate parens/evals/stclass: */
3525 && (scan->flags || data || (flags & SCF_DO_STCLASS))
3526 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
3527 if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3528 || OP(scan) == UNLESSM )
3530 /* Negative Lookahead/lookbehind
3531 In this case we can't do fixed string optimisation.
3534 I32 deltanext, minnext, fake = 0;
3536 struct regnode_charclass_class intrnl;
3539 data_fake.flags = 0;
3541 data_fake.whilem_c = data->whilem_c;
3542 data_fake.last_closep = data->last_closep;
3545 data_fake.last_closep = &fake;
3546 data_fake.pos_delta = delta;
3547 if ( flags & SCF_DO_STCLASS && !scan->flags
3548 && OP(scan) == IFMATCH ) { /* Lookahead */
3549 cl_init(pRExC_state, &intrnl);
3550 data_fake.start_class = &intrnl;
3551 f |= SCF_DO_STCLASS_AND;
3553 if (flags & SCF_WHILEM_VISITED_POS)
3554 f |= SCF_WHILEM_VISITED_POS;
3555 next = regnext(scan);
3556 nscan = NEXTOPER(NEXTOPER(scan));
3557 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
3558 last, &data_fake, stopparen, recursed, NULL, f, depth+1);
3561 FAIL("Variable length lookbehind not implemented");
3563 else if (minnext > (I32)U8_MAX) {
3564 FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3566 scan->flags = (U8)minnext;
3569 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3571 if (data_fake.flags & SF_HAS_EVAL)
3572 data->flags |= SF_HAS_EVAL;
3573 data->whilem_c = data_fake.whilem_c;
3575 if (f & SCF_DO_STCLASS_AND) {
3576 const int was = (data->start_class->flags & ANYOF_EOS);
3578 cl_and(data->start_class, &intrnl);
3580 data->start_class->flags |= ANYOF_EOS;
3583 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3585 /* Positive Lookahead/lookbehind
3586 In this case we can do fixed string optimisation,
3587 but we must be careful about it. Note in the case of
3588 lookbehind the positions will be offset by the minimum
3589 length of the pattern, something we won't know about
3590 until after the recurse.
3592 I32 deltanext, fake = 0;
3594 struct regnode_charclass_class intrnl;
3596 /* We use SAVEFREEPV so that when the full compile
3597 is finished perl will clean up the allocated
3598 minlens when its all done. This was we don't
3599 have to worry about freeing them when we know
3600 they wont be used, which would be a pain.
3603 Newx( minnextp, 1, I32 );
3604 SAVEFREEPV(minnextp);
3607 StructCopy(data, &data_fake, scan_data_t);
3608 if ((flags & SCF_DO_SUBSTR) && data->last_found) {
3611 SCAN_COMMIT(pRExC_state, &data_fake,minlenp);
3612 data_fake.last_found=newSVsv(data->last_found);
3616 data_fake.last_closep = &fake;
3617 data_fake.flags = 0;
3618 data_fake.pos_delta = delta;
3620 data_fake.flags |= SF_IS_INF;
3621 if ( flags & SCF_DO_STCLASS && !scan->flags
3622 && OP(scan) == IFMATCH ) { /* Lookahead */
3623 cl_init(pRExC_state, &intrnl);
3624 data_fake.start_class = &intrnl;
3625 f |= SCF_DO_STCLASS_AND;
3627 if (flags & SCF_WHILEM_VISITED_POS)
3628 f |= SCF_WHILEM_VISITED_POS;
3629 next = regnext(scan);
3630 nscan = NEXTOPER(NEXTOPER(scan));
3632 *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext,
3633 last, &data_fake, stopparen, recursed, NULL, f,depth+1);
3636 FAIL("Variable length lookbehind not implemented");
3638 else if (*minnextp > (I32)U8_MAX) {
3639 FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3641 scan->flags = (U8)*minnextp;
3646 if (f & SCF_DO_STCLASS_AND) {
3647 const int was = (data->start_class->flags & ANYOF_EOS);
3649 cl_and(data->start_class, &intrnl);
3651 data->start_class->flags |= ANYOF_EOS;
3654 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3656 if (data_fake.flags & SF_HAS_EVAL)
3657 data->flags |= SF_HAS_EVAL;
3658 data->whilem_c = data_fake.whilem_c;
3659 if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
3660 if (RExC_rx->minlen<*minnextp)
3661 RExC_rx->minlen=*minnextp;
3662 SCAN_COMMIT(pRExC_state, &data_fake, minnextp);
3663 SvREFCNT_dec(data_fake.last_found);
3665 if ( data_fake.minlen_fixed != minlenp )
3667 data->offset_fixed= data_fake.offset_fixed;
3668 data->minlen_fixed= data_fake.minlen_fixed;
3669 data->lookbehind_fixed+= scan->flags;
3671 if ( data_fake.minlen_float != minlenp )
3673 data->minlen_float= data_fake.minlen_float;
3674 data->offset_float_min=data_fake.offset_float_min;
3675 data->offset_float_max=data_fake.offset_float_max;
3676 data->lookbehind_float+= scan->flags;
3685 else if (OP(scan) == OPEN) {
3686 if (stopparen != (I32)ARG(scan))
3689 else if (OP(scan) == CLOSE) {
3690 if (stopparen == (I32)ARG(scan)) {
3693 if ((I32)ARG(scan) == is_par) {
3694 next = regnext(scan);
3696 if ( next && (OP(next) != WHILEM) && next < last)
3697 is_par = 0; /* Disable optimization */
3700 *(data->last_closep) = ARG(scan);
3702 else if (OP(scan) == EVAL) {
3704 data->flags |= SF_HAS_EVAL;
3706 else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
3707 if (flags & SCF_DO_SUBSTR) {
3708 SCAN_COMMIT(pRExC_state,data,minlenp);
3709 flags &= ~SCF_DO_SUBSTR;
3711 if (data && OP(scan)==ACCEPT) {
3712 data->flags |= SCF_SEEN_ACCEPT;
3717 else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
3719 if (flags & SCF_DO_SUBSTR) {
3720 SCAN_COMMIT(pRExC_state,data,minlenp);
3721 data->longest = &(data->longest_float);
3723 is_inf = is_inf_internal = 1;
3724 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3725 cl_anything(pRExC_state, data->start_class);
3726 flags &= ~SCF_DO_STCLASS;
3728 else if (OP(scan) == GPOS) {
3729 if (!(RExC_rx->extflags & RXf_GPOS_FLOAT) &&
3730 !(delta || is_inf || (data && data->pos_delta)))
3732 if (!(RExC_rx->extflags & RXf_ANCH) && (flags & SCF_DO_SUBSTR))
3733 RExC_rx->extflags |= RXf_ANCH_GPOS;
3734 if (RExC_rx->gofs < (U32)min)
3735 RExC_rx->gofs = min;
3737 RExC_rx->extflags |= RXf_GPOS_FLOAT;
3741 #ifdef TRIE_STUDY_OPT
3742 #ifdef FULL_TRIE_STUDY
3743 else if (PL_regkind[OP(scan)] == TRIE) {
3744 /* NOTE - There is similar code to this block above for handling
3745 BRANCH nodes on the initial study. If you change stuff here
3747 regnode *trie_node= scan;
3748 regnode *tail= regnext(scan);
3749 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
3750 I32 max1 = 0, min1 = I32_MAX;
3751 struct regnode_charclass_class accum;
3753 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
3754 SCAN_COMMIT(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
3755 if (flags & SCF_DO_STCLASS)
3756 cl_init_zero(pRExC_state, &accum);
3762 const regnode *nextbranch= NULL;
3765 for ( word=1 ; word <= trie->wordcount ; word++)
3767 I32 deltanext=0, minnext=0, f = 0, fake;
3768 struct regnode_charclass_class this_class;
3770 data_fake.flags = 0;
3772 data_fake.whilem_c = data->whilem_c;
3773 data_fake.last_closep = data->last_closep;
3776 data_fake.last_closep = &fake;
3777 data_fake.pos_delta = delta;
3778 if (flags & SCF_DO_STCLASS) {
3779 cl_init(pRExC_state, &this_class);
3780 data_fake.start_class = &this_class;
3781 f = SCF_DO_STCLASS_AND;
3783 if (flags & SCF_WHILEM_VISITED_POS)
3784 f |= SCF_WHILEM_VISITED_POS;
3786 if (trie->jump[word]) {
3788 nextbranch = trie_node + trie->jump[0];
3789 scan= trie_node + trie->jump[word];
3790 /* We go from the jump point to the branch that follows
3791 it. Note this means we need the vestigal unused branches
3792 even though they arent otherwise used.
3794 minnext = study_chunk(pRExC_state, &scan, minlenp,
3795 &deltanext, (regnode *)nextbranch, &data_fake,
3796 stopparen, recursed, NULL, f,depth+1);
3798 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
3799 nextbranch= regnext((regnode*)nextbranch);
3801 if (min1 > (I32)(minnext + trie->minlen))
3802 min1 = minnext + trie->minlen;
3803 if (max1 < (I32)(minnext + deltanext + trie->maxlen))
3804 max1 = minnext + deltanext + trie->maxlen;
3805 if (deltanext == I32_MAX)
3806 is_inf = is_inf_internal = 1;
3808 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3810 if (data_fake.flags & SCF_SEEN_ACCEPT) {
3811 if ( stopmin > min + min1)
3812 stopmin = min + min1;
3813 flags &= ~SCF_DO_SUBSTR;
3815 data->flags |= SCF_SEEN_ACCEPT;
3818 if (data_fake.flags & SF_HAS_EVAL)
3819 data->flags |= SF_HAS_EVAL;
3820 data->whilem_c = data_fake.whilem_c;
3822 if (flags & SCF_DO_STCLASS)
3823 cl_or(pRExC_state, &accum, &this_class);
3826 if (flags & SCF_DO_SUBSTR) {
3827 data->pos_min += min1;
3828 data->pos_delta += max1 - min1;
3829 if (max1 != min1 || is_inf)
3830 data->longest = &(data->longest_float);
3833 delta += max1 - min1;
3834 if (flags & SCF_DO_STCLASS_OR) {
3835 cl_or(pRExC_state, data->start_class, &accum);
3837 cl_and(data->start_class, and_withp);
3838 flags &= ~SCF_DO_STCLASS;
3841 else if (flags & SCF_DO_STCLASS_AND) {
3843 cl_and(data->start_class, &accum);
3844 flags &= ~SCF_DO_STCLASS;
3847 /* Switch to OR mode: cache the old value of
3848 * data->start_class */
3850 StructCopy(data->start_class, and_withp,
3851 struct regnode_charclass_class);
3852 flags &= ~SCF_DO_STCLASS_AND;
3853 StructCopy(&accum, data->start_class,
3854 struct regnode_charclass_class);
3855 flags |= SCF_DO_STCLASS_OR;
3856 data->start_class->flags |= ANYOF_EOS;
3863 else if (PL_regkind[OP(scan)] == TRIE) {
3864 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
3867 min += trie->minlen;
3868 delta += (trie->maxlen - trie->minlen);
3869 flags &= ~SCF_DO_STCLASS; /* xxx */
3870 if (flags & SCF_DO_SUBSTR) {
3871 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
3872 data->pos_min += trie->minlen;
3873 data->pos_delta += (trie->maxlen - trie->minlen);
3874 if (trie->maxlen != trie->minlen)
3875 data->longest = &(data->longest_float);
3877 if (trie->jump) /* no more substrings -- for now /grr*/
3878 flags &= ~SCF_DO_SUBSTR;
3880 #endif /* old or new */
3881 #endif /* TRIE_STUDY_OPT */
3882 /* Else: zero-length, ignore. */
3883 scan = regnext(scan);
3888 stopparen = frame->stop;
3889 frame = frame->prev;
3890 goto fake_study_recurse;
3895 DEBUG_STUDYDATA("pre-fin:",data,depth);
3898 *deltap = is_inf_internal ? I32_MAX : delta;
3899 if (flags & SCF_DO_SUBSTR && is_inf)
3900 data->pos_delta = I32_MAX - data->pos_min;
3901 if (is_par > (I32)U8_MAX)
3903 if (is_par && pars==1 && data) {
3904 data->flags |= SF_IN_PAR;
3905 data->flags &= ~SF_HAS_PAR;
3907 else if (pars && data) {
3908 data->flags |= SF_HAS_PAR;
3909 data->flags &= ~SF_IN_PAR;
3911 if (flags & SCF_DO_STCLASS_OR)
3912 cl_and(data->start_class, and_withp);
3913 if (flags & SCF_TRIE_RESTUDY)
3914 data->flags |= SCF_TRIE_RESTUDY;
3916 DEBUG_STUDYDATA("post-fin:",data,depth);
3918 return min < stopmin ? min : stopmin;
3922 S_add_data(RExC_state_t *pRExC_state, U32 n, const char *s)
3924 U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
3926 Renewc(RExC_rxi->data,
3927 sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
3928 char, struct reg_data);
3930 Renew(RExC_rxi->data->what, count + n, U8);
3932 Newx(RExC_rxi->data->what, n, U8);
3933 RExC_rxi->data->count = count + n;
3934 Copy(s, RExC_rxi->data->what + count, n, U8);
3938 /*XXX: todo make this not included in a non debugging perl */
3939 #ifndef PERL_IN_XSUB_RE
3941 Perl_reginitcolors(pTHX)
3944 const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
3946 char *t = savepv(s);
3950 t = strchr(t, '\t');
3956 PL_colors[i] = t = (char *)"";
3961 PL_colors[i++] = (char *)"";
3968 #ifdef TRIE_STUDY_OPT
3969 #define CHECK_RESTUDY_GOTO \
3971 (data.flags & SCF_TRIE_RESTUDY) \
3975 #define CHECK_RESTUDY_GOTO
3979 - pregcomp - compile a regular expression into internal code
3981 * We can't allocate space until we know how big the compiled form will be,
3982 * but we can't compile it (and thus know how big it is) until we've got a
3983 * place to put the code. So we cheat: we compile it twice, once with code
3984 * generation turned off and size counting turned on, and once "for real".
3985 * This also means that we don't allocate space until we are sure that the
3986 * thing really will compile successfully, and we never have to move the
3987 * code and thus invalidate pointers into it. (Note that it has to be in
3988 * one piece because free() must be able to free it all.) [NB: not true in perl]
3990 * Beware that the optimization-preparation code in here knows about some
3991 * of the structure of the compiled regexp. [I'll say.]
3996 #ifndef PERL_IN_XSUB_RE
3997 #define RE_ENGINE_PTR &PL_core_reg_engine
3999 extern const struct regexp_engine my_reg_engine;
4000 #define RE_ENGINE_PTR &my_reg_engine
4003 #ifndef PERL_IN_XSUB_RE
4005 Perl_pregcomp(pTHX_ char *exp, char *xend, PMOP *pm)
4008 HV * const table = GvHV(PL_hintgv);
4009 /* Dispatch a request to compile a regexp to correct
4012 SV **ptr= hv_fetchs(table, "regcomp", FALSE);
4013 GET_RE_DEBUG_FLAGS_DECL;
4014 if (ptr && SvIOK(*ptr) && SvIV(*ptr)) {
4015 const regexp_engine *eng=INT2PTR(regexp_engine*,SvIV(*ptr));
4017 PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
4020 return CALLREGCOMP_ENG(eng, exp, xend, pm);
4023 return Perl_re_compile(aTHX_ exp, xend, pm);
4028 Perl_re_compile(pTHX_ char *exp, char *xend, PMOP *pm)
4032 register regexp_internal *ri;
4040 RExC_state_t RExC_state;
4041 RExC_state_t * const pRExC_state = &RExC_state;
4042 #ifdef TRIE_STUDY_OPT
4044 RExC_state_t copyRExC_state;
4046 GET_RE_DEBUG_FLAGS_DECL;
4047 DEBUG_r(if (!PL_colorset) reginitcolors());
4050 FAIL("NULL regexp argument");
4052 RExC_utf8 = pm->op_pmdynflags & PMdf_CMP_UTF8;
4056 SV *dsv= sv_newmortal();
4057 RE_PV_QUOTED_DECL(s, RExC_utf8,
4058 dsv, RExC_precomp, (xend - exp), 60);
4059 PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
4060 PL_colors[4],PL_colors[5],s);
4062 RExC_flags = pm->op_pmflags;
4066 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
4067 RExC_seen_evals = 0;
4070 /* First pass: determine size, legality. */
4078 RExC_emit = &PL_regdummy;
4079 RExC_whilem_seen = 0;
4080 RExC_charnames = NULL;
4081 RExC_open_parens = NULL;
4082 RExC_close_parens = NULL;
4084 RExC_paren_names = NULL;
4086 RExC_paren_name_list = NULL;
4088 RExC_recurse = NULL;
4089 RExC_recurse_count = 0;
4091 #if 0 /* REGC() is (currently) a NOP at the first pass.
4092 * Clever compilers notice this and complain. --jhi */
4093 REGC((U8)REG_MAGIC, (char*)RExC_emit);
4095 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n"));
4096 if (reg(pRExC_state, 0, &flags,1) == NULL) {
4097 RExC_precomp = NULL;
4101 PerlIO_printf(Perl_debug_log,
4102 "Required size %"IVdf" nodes\n"
4103 "Starting second pass (creation)\n",
4106 RExC_lastparse=NULL;
4108 /* Small enough for pointer-storage convention?
4109 If extralen==0, this means that we will not need long jumps. */
4110 if (RExC_size >= 0x10000L && RExC_extralen)
4111 RExC_size += RExC_extralen;
4114 if (RExC_whilem_seen > 15)
4115 RExC_whilem_seen = 15;
4118 /* Make room for a sentinel value at the end of the program */
4122 /* Allocate space and zero-initialize. Note, the two step process
4123 of zeroing when in debug mode, thus anything assigned has to
4124 happen after that */
4125 Newxz(r, 1, regexp);
4126 Newxc(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
4127 char, regexp_internal);
4128 if ( r == NULL || ri == NULL )
4129 FAIL("Regexp out of space");
4131 /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
4132 Zero(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode), char);
4134 /* bulk initialize base fields with 0. */
4135 Zero(ri, sizeof(regexp_internal), char);
4138 /* non-zero initialization begins here */
4140 r->engine= RE_ENGINE_PTR;
4142 r->prelen = xend - exp;
4143 r->extflags = pm->op_pmflags & RXf_PMf_COMPILETIME;
4145 bool has_k = ((r->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
4146 bool has_minus = ((r->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD);
4147 bool has_runon = ((RExC_seen & REG_SEEN_RUN_ON_COMMENT)==REG_SEEN_RUN_ON_COMMENT);
4148 U16 reganch = (U16)((r->extflags & RXf_PMf_STD_PMMOD) >> 12);
4149 const char *fptr = STD_PAT_MODS; /*"msix"*/
4151 r->wraplen = r->prelen + has_minus + has_k + has_runon
4152 + (sizeof(STD_PAT_MODS) - 1)
4153 + (sizeof("(?:)") - 1);
4155 Newx(r->wrapped, r->wraplen, char );
4159 *p++ = KEEPCOPY_PAT_MOD; /*'k'*/
4161 char *r = p + (sizeof(STD_PAT_MODS) - 1) + has_minus - 1;
4162 char *colon = r + 1;
4165 while((ch = *fptr++)) {
4179 Copy(RExC_precomp, p, r->prelen, char);
4188 r->nparens = RExC_npar - 1; /* set early to validate backrefs */
4190 if (RExC_seen & REG_SEEN_RECURSE) {
4191 Newxz(RExC_open_parens, RExC_npar,regnode *);
4192 SAVEFREEPV(RExC_open_parens);
4193 Newxz(RExC_close_parens,RExC_npar,regnode *);
4194 SAVEFREEPV(RExC_close_parens);
4197 /* Useful during FAIL. */
4198 #ifdef RE_TRACK_PATTERN_OFFSETS
4199 Newxz(ri->u.offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
4200 DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
4201 "%s %"UVuf" bytes for offset annotations.\n",
4202 ri->u.offsets ? "Got" : "Couldn't get",
4203 (UV)((2*RExC_size+1) * sizeof(U32))));
4205 SetProgLen(ri,RExC_size);
4209 /* Second pass: emit code. */
4210 RExC_flags = pm->op_pmflags; /* don't let top level (?i) bleed */
4215 RExC_emit_start = ri->program;
4216 RExC_emit = ri->program;
4218 /* put a sentinal on the end of the program so we can check for
4220 ri->program[RExC_size].type = 255;
4222 /* Store the count of eval-groups for security checks: */
4223 RExC_rx->seen_evals = RExC_seen_evals;
4224 REGC((U8)REG_MAGIC, (char*) RExC_emit++);
4225 if (reg(pRExC_state, 0, &flags,1) == NULL)
4228 /* XXXX To minimize changes to RE engine we always allocate
4229 3-units-long substrs field. */
4230 Newx(r->substrs, 1, struct reg_substr_data);
4231 if (RExC_recurse_count) {
4232 Newxz(RExC_recurse,RExC_recurse_count,regnode *);
4233 SAVEFREEPV(RExC_recurse);
4237 r->minlen = minlen = sawplus = sawopen = 0;
4238 Zero(r->substrs, 1, struct reg_substr_data);
4240 #ifdef TRIE_STUDY_OPT
4243 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
4245 RExC_state = copyRExC_state;
4246 if (seen & REG_TOP_LEVEL_BRANCHES)
4247 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
4249 RExC_seen &= ~REG_TOP_LEVEL_BRANCHES;
4250 if (data.last_found) {
4251 SvREFCNT_dec(data.longest_fixed);
4252 SvREFCNT_dec(data.longest_float);
4253 SvREFCNT_dec(data.last_found);
4255 StructCopy(&zero_scan_data, &data, scan_data_t);
4257 StructCopy(&zero_scan_data, &data, scan_data_t);
4258 copyRExC_state = RExC_state;
4261 StructCopy(&zero_scan_data, &data, scan_data_t);
4264 /* Dig out information for optimizations. */
4265 r->extflags = pm->op_pmflags & RXf_PMf_COMPILETIME; /* Again? */
4266 pm->op_pmflags = RExC_flags;
4268 r->extflags |= RXf_UTF8; /* Unicode in it? */
4269 ri->regstclass = NULL;
4270 if (RExC_naughty >= 10) /* Probably an expensive pattern. */
4271 r->intflags |= PREGf_NAUGHTY;
4272 scan = ri->program + 1; /* First BRANCH. */
4274 /* testing for BRANCH here tells us whether there is "must appear"
4275 data in the pattern. If there is then we can use it for optimisations */
4276 if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES)) { /* Only one top-level choice. */
4278 STRLEN longest_float_length, longest_fixed_length;
4279 struct regnode_charclass_class ch_class; /* pointed to by data */
4281 I32 last_close = 0; /* pointed to by data */
4284 /* Skip introductions and multiplicators >= 1. */
4285 while ((OP(first) == OPEN && (sawopen = 1)) ||
4286 /* An OR of *one* alternative - should not happen now. */
4287 (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
4288 /* for now we can't handle lookbehind IFMATCH*/
4289 (OP(first) == IFMATCH && !first->flags) ||
4290 (OP(first) == PLUS) ||
4291 (OP(first) == MINMOD) ||
4292 /* An {n,m} with n>0 */
4293 (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) )
4296 if (OP(first) == PLUS)
4299 first += regarglen[OP(first)];
4300 if (OP(first) == IFMATCH) {
4301 first = NEXTOPER(first);
4302 first += EXTRA_STEP_2ARGS;
4303 } else /* XXX possible optimisation for /(?=)/ */
4304 first = NEXTOPER(first);
4307 /* Starting-point info. */
4309 DEBUG_PEEP("first:",first,0);
4310 /* Ignore EXACT as we deal with it later. */
4311 if (PL_regkind[OP(first)] == EXACT) {
4312 if (OP(first) == EXACT)
4313 NOOP; /* Empty, get anchored substr later. */
4314 else if ((OP(first) == EXACTF || OP(first) == EXACTFL))
4315 ri->regstclass = first;
4318 else if (PL_regkind[OP(first)] == TRIE &&
4319 ((reg_trie_data *)ri->data->data[ ARG(first) ])->minlen>0)
4322 /* this can happen only on restudy */
4323 if ( OP(first) == TRIE ) {
4324 struct regnode_1 *trieop = (struct regnode_1 *)
4325 PerlMemShared_calloc(1, sizeof(struct regnode_1));
4326 StructCopy(first,trieop,struct regnode_1);
4327 trie_op=(regnode *)trieop;
4329 struct regnode_charclass *trieop = (struct regnode_charclass *)
4330 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
4331 StructCopy(first,trieop,struct regnode_charclass);
4332 trie_op=(regnode *)trieop;
4335 make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
4336 ri->regstclass = trie_op;
4339 else if (strchr((const char*)PL_simple,OP(first)))
4340 ri->regstclass = first;
4341 else if (PL_regkind[OP(first)] == BOUND ||
4342 PL_regkind[OP(first)] == NBOUND)
4343 ri->regstclass = first;
4344 else if (PL_regkind[OP(first)] == BOL) {
4345 r->extflags |= (OP(first) == MBOL
4347 : (OP(first) == SBOL
4350 first = NEXTOPER(first);
4353 else if (OP(first) == GPOS) {
4354 r->extflags |= RXf_ANCH_GPOS;
4355 first = NEXTOPER(first);
4358 else if ((!sawopen || !RExC_sawback) &&
4359 (OP(first) == STAR &&
4360 PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
4361 !(r->extflags & RXf_ANCH) && !(RExC_seen & REG_SEEN_EVAL))
4363 /* turn .* into ^.* with an implied $*=1 */
4365 (OP(NEXTOPER(first)) == REG_ANY)
4368 r->extflags |= type;
4369 r->intflags |= PREGf_IMPLICIT;
4370 first = NEXTOPER(first);
4373 if (sawplus && (!sawopen || !RExC_sawback)
4374 && !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
4375 /* x+ must match at the 1st pos of run of x's */
4376 r->intflags |= PREGf_SKIP;
4378 /* Scan is after the zeroth branch, first is atomic matcher. */
4379 #ifdef TRIE_STUDY_OPT
4382 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4383 (IV)(first - scan + 1))
4387 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4388 (IV)(first - scan + 1))
4394 * If there's something expensive in the r.e., find the
4395 * longest literal string that must appear and make it the
4396 * regmust. Resolve ties in favor of later strings, since
4397 * the regstart check works with the beginning of the r.e.
4398 * and avoiding duplication strengthens checking. Not a
4399 * strong reason, but sufficient in the absence of others.
4400 * [Now we resolve ties in favor of the earlier string if
4401 * it happens that c_offset_min has been invalidated, since the
4402 * earlier string may buy us something the later one won't.]
4405 data.longest_fixed = newSVpvs("");
4406 data.longest_float = newSVpvs("");
4407 data.last_found = newSVpvs("");
4408 data.longest = &(data.longest_fixed);
4410 if (!ri->regstclass) {
4411 cl_init(pRExC_state, &ch_class);
4412 data.start_class = &ch_class;
4413 stclass_flag = SCF_DO_STCLASS_AND;
4414 } else /* XXXX Check for BOUND? */
4416 data.last_closep = &last_close;
4418 minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
4419 &data, -1, NULL, NULL,
4420 SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag,0);
4426 if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
4427 && data.last_start_min == 0 && data.last_end > 0
4428 && !RExC_seen_zerolen
4429 && !(RExC_seen & REG_SEEN_VERBARG)
4430 && (!(RExC_seen & REG_SEEN_GPOS) || (r->extflags & RXf_ANCH_GPOS)))
4431 r->extflags |= RXf_CHECK_ALL;
4432 scan_commit(pRExC_state, &data,&minlen,0);
4433 SvREFCNT_dec(data.last_found);
4435 /* Note that code very similar to this but for anchored string
4436 follows immediately below, changes may need to be made to both.
4439 longest_float_length = CHR_SVLEN(data.longest_float);
4440 if (longest_float_length
4441 || (data.flags & SF_FL_BEFORE_EOL
4442 && (!(data.flags & SF_FL_BEFORE_MEOL)
4443 || (RExC_flags & RXf_PMf_MULTILINE))))
4447 if (SvCUR(data.longest_fixed) /* ok to leave SvCUR */
4448 && data.offset_fixed == data.offset_float_min
4449 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
4450 goto remove_float; /* As in (a)+. */
4452 /* copy the information about the longest float from the reg_scan_data
4453 over to the program. */
4454 if (SvUTF8(data.longest_float)) {
4455 r->float_utf8 = data.longest_float;
4456 r->float_substr = NULL;
4458 r->float_substr = data.longest_float;
4459 r->float_utf8 = NULL;
4461 /* float_end_shift is how many chars that must be matched that
4462 follow this item. We calculate it ahead of time as once the
4463 lookbehind offset is added in we lose the ability to correctly
4465 ml = data.minlen_float ? *(data.minlen_float)
4466 : (I32)longest_float_length;
4467 r->float_end_shift = ml - data.offset_float_min
4468 - longest_float_length + (SvTAIL(data.longest_float) != 0)
4469 + data.lookbehind_float;
4470 r->float_min_offset = data.offset_float_min - data.lookbehind_float;
4471 r->float_max_offset = data.offset_float_max;
4472 if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
4473 r->float_max_offset -= data.lookbehind_float;
4475 t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
4476 && (!(data.flags & SF_FL_BEFORE_MEOL)
4477 || (RExC_flags & RXf_PMf_MULTILINE)));
4478 fbm_compile(data.longest_float, t ? FBMcf_TAIL : 0);
4482 r->float_substr = r->float_utf8 = NULL;
4483 SvREFCNT_dec(data.longest_float);
4484 longest_float_length = 0;
4487 /* Note that code very similar to this but for floating string
4488 is immediately above, changes may need to be made to both.
4491 longest_fixed_length = CHR_SVLEN(data.longest_fixed);
4492 if (longest_fixed_length
4493 || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
4494 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4495 || (RExC_flags & RXf_PMf_MULTILINE))))
4499 /* copy the information about the longest fixed
4500 from the reg_scan_data over to the program. */
4501 if (SvUTF8(data.longest_fixed)) {
4502 r->anchored_utf8 = data.longest_fixed;
4503 r->anchored_substr = NULL;
4505 r->anchored_substr = data.longest_fixed;
4506 r->anchored_utf8 = NULL;
4508 /* fixed_end_shift is how many chars that must be matched that
4509 follow this item. We calculate it ahead of time as once the
4510 lookbehind offset is added in we lose the ability to correctly
4512 ml = data.minlen_fixed ? *(data.minlen_fixed)
4513 : (I32)longest_fixed_length;
4514 r->anchored_end_shift = ml - data.offset_fixed
4515 - longest_fixed_length + (SvTAIL(data.longest_fixed) != 0)
4516 + data.lookbehind_fixed;
4517 r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
4519 t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
4520 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4521 || (RExC_flags & RXf_PMf_MULTILINE)));
4522 fbm_compile(data.longest_fixed, t ? FBMcf_TAIL : 0);
4525 r->anchored_substr = r->anchored_utf8 = NULL;
4526 SvREFCNT_dec(data.longest_fixed);
4527 longest_fixed_length = 0;
4530 && (OP(ri->regstclass) == REG_ANY || OP(ri->regstclass) == SANY))
4531 ri->regstclass = NULL;
4532 if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
4534 && !(data.start_class->flags & ANYOF_EOS)
4535 && !cl_is_anything(data.start_class))
4537 const U32 n = add_data(pRExC_state, 1, "f");
4539 Newx(RExC_rxi->data->data[n], 1,
4540 struct regnode_charclass_class);
4541 StructCopy(data.start_class,
4542 (struct regnode_charclass_class*)RExC_rxi->data->data[n],
4543 struct regnode_charclass_class);
4544 ri->regstclass = (regnode*)RExC_rxi->data->data[n];
4545 r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
4546 DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
4547 regprop(r, sv, (regnode*)data.start_class);
4548 PerlIO_printf(Perl_debug_log,
4549 "synthetic stclass \"%s\".\n",
4550 SvPVX_const(sv));});
4553 /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
4554 if (longest_fixed_length > longest_float_length) {
4555 r->check_end_shift = r->anchored_end_shift;
4556 r->check_substr = r->anchored_substr;
4557 r->check_utf8 = r->anchored_utf8;
4558 r->check_offset_min = r->check_offset_max = r->anchored_offset;
4559 if (r->extflags & RXf_ANCH_SINGLE)
4560 r->extflags |= RXf_NOSCAN;
4563 r->check_end_shift = r->float_end_shift;
4564 r->check_substr = r->float_substr;
4565 r->check_utf8 = r->float_utf8;
4566 r->check_offset_min = r->float_min_offset;
4567 r->check_offset_max = r->float_max_offset;
4569 /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
4570 This should be changed ASAP! */
4571 if ((r->check_substr || r->check_utf8) && !(r->extflags & RXf_ANCH_GPOS)) {
4572 r->extflags |= RXf_USE_INTUIT;
4573 if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
4574 r->extflags |= RXf_INTUIT_TAIL;
4576 /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
4577 if ( (STRLEN)minlen < longest_float_length )
4578 minlen= longest_float_length;
4579 if ( (STRLEN)minlen < longest_fixed_length )
4580 minlen= longest_fixed_length;
4584 /* Several toplevels. Best we can is to set minlen. */
4586 struct regnode_charclass_class ch_class;
4589 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "\nMulti Top Level\n"));
4591 scan = ri->program + 1;
4592 cl_init(pRExC_state, &ch_class);
4593 data.start_class = &ch_class;
4594 data.last_closep = &last_close;
4597 minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
4598 &data, -1, NULL, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS,0);
4602 r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
4603 = r->float_substr = r->float_utf8 = NULL;
4604 if (!(data.start_class->flags & ANYOF_EOS)
4605 && !cl_is_anything(data.start_class))
4607 const U32 n = add_data(pRExC_state, 1, "f");
4609 Newx(RExC_rxi->data->data[n], 1,
4610 struct regnode_charclass_class);
4611 StructCopy(data.start_class,
4612 (struct regnode_charclass_class*)RExC_rxi->data->data[n],
4613 struct regnode_charclass_class);
4614 ri->regstclass = (regnode*)RExC_rxi->data->data[n];
4615 r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
4616 DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
4617 regprop(r, sv, (regnode*)data.start_class);
4618 PerlIO_printf(Perl_debug_log,
4619 "synthetic stclass \"%s\".\n",
4620 SvPVX_const(sv));});
4624 /* Guard against an embedded (?=) or (?<=) with a longer minlen than
4625 the "real" pattern. */
4627 PerlIO_printf(Perl_debug_log,"minlen: %"IVdf" r->minlen:%"IVdf"\n",
4628 (IV)minlen, (IV)r->minlen);
4630 r->minlenret = minlen;
4631 if (r->minlen < minlen)
4634 if (RExC_seen & REG_SEEN_GPOS)
4635 r->extflags |= RXf_GPOS_SEEN;
4636 if (RExC_seen & REG_SEEN_LOOKBEHIND)
4637 r->extflags |= RXf_LOOKBEHIND_SEEN;
4638 if (RExC_seen & REG_SEEN_EVAL)
4639 r->extflags |= RXf_EVAL_SEEN;
4640 if (RExC_seen & REG_SEEN_CANY)
4641 r->extflags |= RXf_CANY_SEEN;
4642 if (RExC_seen & REG_SEEN_VERBARG)
4643 r->intflags |= PREGf_VERBARG_SEEN;
4644 if (RExC_seen & REG_SEEN_CUTGROUP)
4645 r->intflags |= PREGf_CUTGROUP_SEEN;
4646 if (RExC_paren_names)
4647 r->paren_names = (HV*)SvREFCNT_inc(RExC_paren_names);
4649 r->paren_names = NULL;
4650 if (r->prelen == 3 && strEQ("\\s+", r->precomp))
4651 r->extflags |= RXf_WHITE;
4652 else if (r->prelen == 1 && r->precomp[0] == '^')
4653 r->extflags |= RXf_START_ONLY;
4656 if (RExC_paren_names) {
4657 ri->name_list_idx = add_data( pRExC_state, 1, "p" );
4658 ri->data->data[ri->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list);
4661 ri->name_list_idx = 0;
4663 if (RExC_recurse_count) {
4664 for ( ; RExC_recurse_count ; RExC_recurse_count-- ) {
4665 const regnode *scan = RExC_recurse[RExC_recurse_count-1];
4666 ARG2L_SET( scan, RExC_open_parens[ARG(scan)-1] - scan );
4669 Newxz(r->startp, RExC_npar, I32);
4670 Newxz(r->endp, RExC_npar, I32);
4671 /* assume we don't need to swap parens around before we match */
4674 PerlIO_printf(Perl_debug_log,"Final program:\n");
4677 #ifdef RE_TRACK_PATTERN_OFFSETS
4678 DEBUG_OFFSETS_r(if (ri->u.offsets) {
4679 const U32 len = ri->u.offsets[0];
4681 GET_RE_DEBUG_FLAGS_DECL;
4682 PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)ri->u.offsets[0]);
4683 for (i = 1; i <= len; i++) {
4684 if (ri->u.offsets[i*2-1] || ri->u.offsets[i*2])
4685 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
4686 (UV)i, (UV)ri->u.offsets[i*2-1], (UV)ri->u.offsets[i*2]);
4688 PerlIO_printf(Perl_debug_log, "\n");
4694 #undef CORE_ONLY_BLOCK
4695 #undef RE_ENGINE_PTR
4697 #ifndef PERL_IN_XSUB_RE
4699 Perl_reg_named_buff_get(pTHX_ SV* namesv, const REGEXP * const from_re, U32 flags)
4701 AV *retarray = NULL;
4706 if (from_re || PL_curpm) {
4707 const REGEXP * const rx = from_re ? from_re : PM_GETRE(PL_curpm);
4708 if (rx && rx->paren_names) {
4709 HE *he_str = hv_fetch_ent( rx->paren_names, namesv, 0, 0 );
4712 SV* sv_dat=HeVAL(he_str);
4713 I32 *nums=(I32*)SvPVX(sv_dat);
4714 for ( i=0; i<SvIVX(sv_dat); i++ ) {
4715 if ((I32)(rx->nparens) >= nums[i]
4716 && rx->startp[nums[i]] != -1
4717 && rx->endp[nums[i]] != -1)
4719 ret = reg_numbered_buff_get(nums[i],rx,NULL,0);
4723 ret = newSVsv(&PL_sv_undef);
4727 av_push(retarray, ret);
4731 return (SV*)retarray;
4739 Perl_reg_numbered_buff_get(pTHX_ I32 paren, const REGEXP * const rx, SV* usesv, U32 flags)
4744 SV *sv = usesv ? usesv : newSVpvs("");
4745 PERL_UNUSED_ARG(flags);
4748 sv_setsv(sv,&PL_sv_undef);
4752 if (paren == -2 && rx->startp[0] != -1) {
4758 if (paren == -1 && rx->endp[0] != -1) {
4760 s = rx->subbeg + rx->endp[0];
4761 i = rx->sublen - rx->endp[0];
4764 if ( 0 <= paren && paren <= (I32)rx->nparens &&
4765 (s1 = rx->startp[paren]) != -1 &&
4766 (t1 = rx->endp[paren]) != -1)
4770 s = rx->subbeg + s1;
4772 sv_setsv(sv,&PL_sv_undef);
4775 assert(rx->sublen >= (s - rx->subbeg) + i );
4777 const int oldtainted = PL_tainted;
4779 sv_setpvn(sv, s, i);
4780 PL_tainted = oldtainted;
4781 if ( (rx->extflags & RXf_CANY_SEEN)
4782 ? (RX_MATCH_UTF8(rx)
4783 && (!i || is_utf8_string((U8*)s, i)))
4784 : (RX_MATCH_UTF8(rx)) )
4791 if (RX_MATCH_TAINTED(rx)) {
4792 if (SvTYPE(sv) >= SVt_PVMG) {
4793 MAGIC* const mg = SvMAGIC(sv);
4796 SvMAGIC_set(sv, mg->mg_moremagic);
4798 if ((mgt = SvMAGIC(sv))) {
4799 mg->mg_moremagic = mgt;
4800 SvMAGIC_set(sv, mg);
4810 sv_setsv(sv,&PL_sv_undef);
4816 /* Scans the name of a named buffer from the pattern.
4817 * If flags is REG_RSN_RETURN_NULL returns null.
4818 * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
4819 * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
4820 * to the parsed name as looked up in the RExC_paren_names hash.
4821 * If there is an error throws a vFAIL().. type exception.
4824 #define REG_RSN_RETURN_NULL 0
4825 #define REG_RSN_RETURN_NAME 1
4826 #define REG_RSN_RETURN_DATA 2
4829 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags) {
4830 char *name_start = RExC_parse;
4832 if (isIDFIRST_lazy_if(RExC_parse, UTF)) {
4833 /* skip IDFIRST by using do...while */
4836 RExC_parse += UTF8SKIP(RExC_parse);
4837 } while (isALNUM_utf8((U8*)RExC_parse));
4841 } while (isALNUM(*RExC_parse));
4845 SV* sv_name = sv_2mortal(Perl_newSVpvn(aTHX_ name_start,
4846 (int)(RExC_parse - name_start)));
4849 if ( flags == REG_RSN_RETURN_NAME)
4851 else if (flags==REG_RSN_RETURN_DATA) {
4854 if ( ! sv_name ) /* should not happen*/
4855 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
4856 if (RExC_paren_names)
4857 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
4859 sv_dat = HeVAL(he_str);
4861 vFAIL("Reference to nonexistent named group");
4865 Perl_croak(aTHX_ "panic: bad flag in reg_scan_name");
4872 #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
4873 int rem=(int)(RExC_end - RExC_parse); \
4882 if (RExC_lastparse!=RExC_parse) \
4883 PerlIO_printf(Perl_debug_log," >%.*s%-*s", \
4886 iscut ? "..." : "<" \
4889 PerlIO_printf(Perl_debug_log,"%16s",""); \
4894 num=REG_NODE_NUM(RExC_emit); \
4895 if (RExC_lastnum!=num) \
4896 PerlIO_printf(Perl_debug_log,"|%4d",num); \
4898 PerlIO_printf(Perl_debug_log,"|%4s",""); \
4899 PerlIO_printf(Perl_debug_log,"|%*s%-4s", \
4900 (int)((depth*2)), "", \
4904 RExC_lastparse=RExC_parse; \
4909 #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
4910 DEBUG_PARSE_MSG((funcname)); \
4911 PerlIO_printf(Perl_debug_log,"%4s","\n"); \
4913 #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({ \
4914 DEBUG_PARSE_MSG((funcname)); \
4915 PerlIO_printf(Perl_debug_log,fmt "\n",args); \
4918 - reg - regular expression, i.e. main body or parenthesized thing
4920 * Caller must absorb opening parenthesis.
4922 * Combining parenthesis handling with the base level of regular expression
4923 * is a trifle forced, but the need to tie the tails of the branches to what
4924 * follows makes it hard to avoid.
4926 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
4928 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
4930 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
4933 /* this idea is borrowed from STR_WITH_LEN in handy.h */
4934 #define CHECK_WORD(s,v,l) \
4935 (((sizeof(s)-1)==(l)) && (strnEQ(start_verb, (s ""), (sizeof(s)-1))))
4938 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
4939 /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
4942 register regnode *ret; /* Will be the head of the group. */
4943 register regnode *br;
4944 register regnode *lastbr;
4945 register regnode *ender = NULL;
4946 register I32 parno = 0;
4948 const I32 oregflags = RExC_flags;
4949 bool have_branch = 0;
4951 I32 freeze_paren = 0;
4952 I32 after_freeze = 0;
4954 /* for (?g), (?gc), and (?o) warnings; warning
4955 about (?c) will warn about (?g) -- japhy */
4957 #define WASTED_O 0x01
4958 #define WASTED_G 0x02
4959 #define WASTED_C 0x04
4960 #define WASTED_GC (0x02|0x04)
4961 I32 wastedflags = 0x00;
4963 char * parse_start = RExC_parse; /* MJD */
4964 char * const oregcomp_parse = RExC_parse;
4966 GET_RE_DEBUG_FLAGS_DECL;
4967 DEBUG_PARSE("reg ");
4970 *flagp = 0; /* Tentatively. */
4973 /* Make an OPEN node, if parenthesized. */
4975 if ( *RExC_parse == '*') { /* (*VERB:ARG) */
4976 char *start_verb = RExC_parse;
4977 STRLEN verb_len = 0;
4978 char *start_arg = NULL;
4979 unsigned char op = 0;
4981 int internal_argval = 0; /* internal_argval is only useful if !argok */
4982 while ( *RExC_parse && *RExC_parse != ')' ) {
4983 if ( *RExC_parse == ':' ) {
4984 start_arg = RExC_parse + 1;
4990 verb_len = RExC_parse - start_verb;
4993 while ( *RExC_parse && *RExC_parse != ')' )
4995 if ( *RExC_parse != ')' )
4996 vFAIL("Unterminated verb pattern argument");
4997 if ( RExC_parse == start_arg )
5000 if ( *RExC_parse != ')' )
5001 vFAIL("Unterminated verb pattern");
5004 switch ( *start_verb ) {
5005 case 'A': /* (*ACCEPT) */
5006 if ( CHECK_WORD("ACCEPT",start_verb,verb_len) ) {
5008 internal_argval = RExC_nestroot;
5011 case 'C': /* (*COMMIT) */
5012 if ( CHECK_WORD("COMMIT",start_verb,verb_len) )
5015 case 'F': /* (*FAIL) */
5016 if ( verb_len==1 || CHECK_WORD("FAIL",start_verb,verb_len) ) {
5021 case ':': /* (*:NAME) */
5022 case 'M': /* (*MARK:NAME) */
5023 if ( verb_len==0 || CHECK_WORD("MARK",start_verb,verb_len) ) {
5028 case 'P': /* (*PRUNE) */
5029 if ( CHECK_WORD("PRUNE",start_verb,verb_len) )
5032 case 'S': /* (*SKIP) */
5033 if ( CHECK_WORD("SKIP",start_verb,verb_len) )
5036 case 'T': /* (*THEN) */
5037 /* [19:06] <TimToady> :: is then */
5038 if ( CHECK_WORD("THEN",start_verb,verb_len) ) {
5040 RExC_seen |= REG_SEEN_CUTGROUP;
5046 vFAIL3("Unknown verb pattern '%.*s'",
5047 verb_len, start_verb);
5050 if ( start_arg && internal_argval ) {
5051 vFAIL3("Verb pattern '%.*s' may not have an argument",
5052 verb_len, start_verb);
5053 } else if ( argok < 0 && !start_arg ) {
5054 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
5055 verb_len, start_verb);
5057 ret = reganode(pRExC_state, op, internal_argval);
5058 if ( ! internal_argval && ! SIZE_ONLY ) {
5060 SV *sv = newSVpvn( start_arg, RExC_parse - start_arg);
5061 ARG(ret) = add_data( pRExC_state, 1, "S" );
5062 RExC_rxi->data->data[ARG(ret)]=(void*)sv;
5069 if (!internal_argval)
5070 RExC_seen |= REG_SEEN_VERBARG;
5071 } else if ( start_arg ) {
5072 vFAIL3("Verb pattern '%.*s' may not have an argument",
5073 verb_len, start_verb);
5075 ret = reg_node(pRExC_state, op);
5077 nextchar(pRExC_state);
5080 if (*RExC_parse == '?') { /* (?...) */
5081 bool is_logical = 0;
5082 const char * const seqstart = RExC_parse;
5085 paren = *RExC_parse++;
5086 ret = NULL; /* For look-ahead/behind. */
5089 case 'P': /* (?P...) variants for those used to PCRE/Python */
5090 paren = *RExC_parse++;
5091 if ( paren == '<') /* (?P<...>) named capture */
5093 else if (paren == '>') { /* (?P>name) named recursion */
5094 goto named_recursion;
5096 else if (paren == '=') { /* (?P=...) named backref */
5097 /* this pretty much dupes the code for \k<NAME> in regatom(), if
5098 you change this make sure you change that */
5099 char* name_start = RExC_parse;
5101 SV *sv_dat = reg_scan_name(pRExC_state,
5102 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5103 if (RExC_parse == name_start || *RExC_parse != ')')
5104 vFAIL2("Sequence %.3s... not terminated",parse_start);
5107 num = add_data( pRExC_state, 1, "S" );
5108 RExC_rxi->data->data[num]=(void*)sv_dat;
5109 SvREFCNT_inc(sv_dat);
5112 ret = reganode(pRExC_state,
5113 (U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
5117 Set_Node_Offset(ret, parse_start+1);
5118 Set_Node_Cur_Length(ret); /* MJD */
5120 nextchar(pRExC_state);
5124 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5126 case '<': /* (?<...) */
5127 if (*RExC_parse == '!')
5129 else if (*RExC_parse != '=')
5135 case '\'': /* (?'...') */
5136 name_start= RExC_parse;
5137 svname = reg_scan_name(pRExC_state,
5138 SIZE_ONLY ? /* reverse test from the others */
5139 REG_RSN_RETURN_NAME :
5140 REG_RSN_RETURN_NULL);
5141 if (RExC_parse == name_start) {
5143 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5146 if (*RExC_parse != paren)
5147 vFAIL2("Sequence (?%c... not terminated",
5148 paren=='>' ? '<' : paren);
5152 if (!svname) /* shouldnt happen */
5154 "panic: reg_scan_name returned NULL");
5155 if (!RExC_paren_names) {
5156 RExC_paren_names= newHV();
5157 sv_2mortal((SV*)RExC_paren_names);
5159 RExC_paren_name_list= newAV();
5160 sv_2mortal((SV*)RExC_paren_name_list);
5163 he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
5165 sv_dat = HeVAL(he_str);
5167 /* croak baby croak */
5169 "panic: paren_name hash element allocation failed");
5170 } else if ( SvPOK(sv_dat) ) {
5171 /* (?|...) can mean we have dupes so scan to check
5172 its already been stored. Maybe a flag indicating
5173 we are inside such a construct would be useful,
5174 but the arrays are likely to be quite small, so
5175 for now we punt -- dmq */
5176 IV count = SvIV(sv_dat);
5177 I32 *pv = (I32*)SvPVX(sv_dat);
5179 for ( i = 0 ; i < count ; i++ ) {
5180 if ( pv[i] == RExC_npar ) {
5186 pv = (I32*)SvGROW(sv_dat, SvCUR(sv_dat) + sizeof(I32)+1);
5187 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
5188 pv[count] = RExC_npar;
5192 (void)SvUPGRADE(sv_dat,SVt_PVNV);
5193 sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32));
5198 if (!av_store(RExC_paren_name_list, RExC_npar, SvREFCNT_inc(svname)))
5199 SvREFCNT_dec(svname);
5202 /*sv_dump(sv_dat);*/
5204 nextchar(pRExC_state);
5206 goto capturing_parens;
5208 RExC_seen |= REG_SEEN_LOOKBEHIND;
5210 case '=': /* (?=...) */
5211 case '!': /* (?!...) */
5212 RExC_seen_zerolen++;
5213 if (*RExC_parse == ')') {
5214 ret=reg_node(pRExC_state, OPFAIL);
5215 nextchar(pRExC_state);
5219 case '|': /* (?|...) */
5220 /* branch reset, behave like a (?:...) except that
5221 buffers in alternations share the same numbers */
5223 after_freeze = freeze_paren = RExC_npar;
5225 case ':': /* (?:...) */
5226 case '>': /* (?>...) */
5228 case '$': /* (?$...) */
5229 case '@': /* (?@...) */
5230 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
5232 case '#': /* (?#...) */
5233 while (*RExC_parse && *RExC_parse != ')')
5235 if (*RExC_parse != ')')
5236 FAIL("Sequence (?#... not terminated");
5237 nextchar(pRExC_state);
5240 case '0' : /* (?0) */
5241 case 'R' : /* (?R) */
5242 if (*RExC_parse != ')')
5243 FAIL("Sequence (?R) not terminated");
5244 ret = reg_node(pRExC_state, GOSTART);
5245 nextchar(pRExC_state);
5248 { /* named and numeric backreferences */
5250 case '&': /* (?&NAME) */
5251 parse_start = RExC_parse - 1;
5254 SV *sv_dat = reg_scan_name(pRExC_state,
5255 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5256 num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
5258 goto gen_recurse_regop;
5261 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
5263 vFAIL("Illegal pattern");
5265 goto parse_recursion;
5267 case '-': /* (?-1) */
5268 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
5269 RExC_parse--; /* rewind to let it be handled later */
5273 case '1': case '2': case '3': case '4': /* (?1) */
5274 case '5': case '6': case '7': case '8': case '9':
5277 num = atoi(RExC_parse);
5278 parse_start = RExC_parse - 1; /* MJD */
5279 if (*RExC_parse == '-')
5281 while (isDIGIT(*RExC_parse))
5283 if (*RExC_parse!=')')
5284 vFAIL("Expecting close bracket");
5287 if ( paren == '-' ) {
5289 Diagram of capture buffer numbering.
5290 Top line is the normal capture buffer numbers
5291 Botton line is the negative indexing as from
5295 /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
5299 num = RExC_npar + num;
5302 vFAIL("Reference to nonexistent group");
5304 } else if ( paren == '+' ) {
5305 num = RExC_npar + num - 1;
5308 ret = reganode(pRExC_state, GOSUB, num);
5310 if (num > (I32)RExC_rx->nparens) {
5312 vFAIL("Reference to nonexistent group");
5314 ARG2L_SET( ret, RExC_recurse_count++);
5316 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5317 "Recurse #%"UVuf" to %"IVdf"\n", (UV)ARG(ret), (IV)ARG2L(ret)));
5321 RExC_seen |= REG_SEEN_RECURSE;
5322 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
5323 Set_Node_Offset(ret, parse_start); /* MJD */
5325 nextchar(pRExC_state);
5327 } /* named and numeric backreferences */
5330 case 'p': /* (?p...) */
5331 if (SIZE_ONLY && ckWARN2(WARN_DEPRECATED, WARN_REGEXP))
5332 vWARNdep(RExC_parse, "(?p{}) is deprecated - use (??{})");
5334 case '?': /* (??...) */
5336 if (*RExC_parse != '{') {
5338 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5341 paren = *RExC_parse++;
5343 case '{': /* (?{...}) */
5348 char *s = RExC_parse;
5350 RExC_seen_zerolen++;
5351 RExC_seen |= REG_SEEN_EVAL;
5352 while (count && (c = *RExC_parse)) {
5363 if (*RExC_parse != ')') {
5365 vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
5369 OP_4tree *sop, *rop;
5370 SV * const sv = newSVpvn(s, RExC_parse - 1 - s);
5373 Perl_save_re_context(aTHX);
5374 rop = sv_compile_2op(sv, &sop, "re", &pad);
5375 sop->op_private |= OPpREFCOUNTED;
5376 /* re_dup will OpREFCNT_inc */
5377 OpREFCNT_set(sop, 1);
5380 n = add_data(pRExC_state, 3, "nop");
5381 RExC_rxi->data->data[n] = (void*)rop;
5382 RExC_rxi->data->data[n+1] = (void*)sop;
5383 RExC_rxi->data->data[n+2] = (void*)pad;
5386 else { /* First pass */
5387 if (PL_reginterp_cnt < ++RExC_seen_evals
5389 /* No compiled RE interpolated, has runtime
5390 components ===> unsafe. */
5391 FAIL("Eval-group not allowed at runtime, use re 'eval'");
5392 if (PL_tainting && PL_tainted)
5393 FAIL("Eval-group in insecure regular expression");
5394 #if PERL_VERSION > 8
5395 if (IN_PERL_COMPILETIME)
5400 nextchar(pRExC_state);
5402 ret = reg_node(pRExC_state, LOGICAL);
5405 REGTAIL(pRExC_state, ret, reganode(pRExC_state, EVAL, n));
5406 /* deal with the length of this later - MJD */
5409 ret = reganode(pRExC_state, EVAL, n);
5410 Set_Node_Length(ret, RExC_parse - parse_start + 1);
5411 Set_Node_Offset(ret, parse_start);
5414 case '(': /* (?(?{...})...) and (?(?=...)...) */
5417 if (RExC_parse[0] == '?') { /* (?(?...)) */
5418 if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
5419 || RExC_parse[1] == '<'
5420 || RExC_parse[1] == '{') { /* Lookahead or eval. */
5423 ret = reg_node(pRExC_state, LOGICAL);
5426 REGTAIL(pRExC_state, ret, reg(pRExC_state, 1, &flag,depth+1));
5430 else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
5431 || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
5433 char ch = RExC_parse[0] == '<' ? '>' : '\'';
5434 char *name_start= RExC_parse++;
5436 SV *sv_dat=reg_scan_name(pRExC_state,
5437 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5438 if (RExC_parse == name_start || *RExC_parse != ch)
5439 vFAIL2("Sequence (?(%c... not terminated",
5440 (ch == '>' ? '<' : ch));
5443 num = add_data( pRExC_state, 1, "S" );
5444 RExC_rxi->data->data[num]=(void*)sv_dat;
5445 SvREFCNT_inc(sv_dat);
5447 ret = reganode(pRExC_state,NGROUPP,num);
5448 goto insert_if_check_paren;
5450 else if (RExC_parse[0] == 'D' &&
5451 RExC_parse[1] == 'E' &&
5452 RExC_parse[2] == 'F' &&
5453 RExC_parse[3] == 'I' &&
5454 RExC_parse[4] == 'N' &&
5455 RExC_parse[5] == 'E')
5457 ret = reganode(pRExC_state,DEFINEP,0);
5460 goto insert_if_check_paren;
5462 else if (RExC_parse[0] == 'R') {
5465 if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
5466 parno = atoi(RExC_parse++);
5467 while (isDIGIT(*RExC_parse))
5469 } else if (RExC_parse[0] == '&') {
5472 sv_dat = reg_scan_name(pRExC_state,
5473 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5474 parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
5476 ret = reganode(pRExC_state,INSUBP,parno);
5477 goto insert_if_check_paren;
5479 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
5482 parno = atoi(RExC_parse++);
5484 while (isDIGIT(*RExC_parse))
5486 ret = reganode(pRExC_state, GROUPP, parno);
5488 insert_if_check_paren:
5489 if ((c = *nextchar(pRExC_state)) != ')')
5490 vFAIL("Switch condition not recognized");
5492 REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
5493 br = regbranch(pRExC_state, &flags, 1,depth+1);
5495 br = reganode(pRExC_state, LONGJMP, 0);
5497 REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
5498 c = *nextchar(pRExC_state);
5503 vFAIL("(?(DEFINE)....) does not allow branches");
5504 lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
5505 regbranch(pRExC_state, &flags, 1,depth+1);
5506 REGTAIL(pRExC_state, ret, lastbr);
5509 c = *nextchar(pRExC_state);
5514 vFAIL("Switch (?(condition)... contains too many branches");
5515 ender = reg_node(pRExC_state, TAIL);
5516 REGTAIL(pRExC_state, br, ender);
5518 REGTAIL(pRExC_state, lastbr, ender);
5519 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
5522 REGTAIL(pRExC_state, ret, ender);
5526 vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
5530 RExC_parse--; /* for vFAIL to print correctly */
5531 vFAIL("Sequence (? incomplete");
5535 parse_flags: /* (?i) */
5537 U32 posflags = 0, negflags = 0;
5538 U32 *flagsp = &posflags;
5540 while (*RExC_parse) {
5541 /* && strchr("iogcmsx", *RExC_parse) */
5542 /* (?g), (?gc) and (?o) are useless here
5543 and must be globally applied -- japhy */
5544 switch (*RExC_parse) {
5545 CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp);
5548 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5549 const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
5550 if (! (wastedflags & wflagbit) ) {
5551 wastedflags |= wflagbit;
5554 "Useless (%s%c) - %suse /%c modifier",
5555 flagsp == &negflags ? "?-" : "?",
5557 flagsp == &negflags ? "don't " : "",
5565 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5566 if (! (wastedflags & WASTED_C) ) {
5567 wastedflags |= WASTED_GC;
5570 "Useless (%sc) - %suse /gc modifier",
5571 flagsp == &negflags ? "?-" : "?",
5572 flagsp == &negflags ? "don't " : ""
5578 if (flagsp == &negflags) {
5579 if (SIZE_ONLY && ckWARN(WARN_REGEXP))
5580 vWARN(RExC_parse + 1,"Useless use of (?-k)");
5582 *flagsp |= RXf_PMf_KEEPCOPY;
5586 if (flagsp == &negflags) {
5588 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5592 wastedflags = 0; /* reset so (?g-c) warns twice */
5598 RExC_flags |= posflags;
5599 RExC_flags &= ~negflags;
5600 nextchar(pRExC_state);
5611 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5616 }} /* one for the default block, one for the switch */
5623 ret = reganode(pRExC_state, OPEN, parno);
5626 RExC_nestroot = parno;
5627 if (RExC_seen & REG_SEEN_RECURSE
5628 && !RExC_open_parens[parno-1])
5630 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5631 "Setting open paren #%"IVdf" to %d\n",
5632 (IV)parno, REG_NODE_NUM(ret)));
5633 RExC_open_parens[parno-1]= ret;
5636 Set_Node_Length(ret, 1); /* MJD */
5637 Set_Node_Offset(ret, RExC_parse); /* MJD */
5645 /* Pick up the branches, linking them together. */
5646 parse_start = RExC_parse; /* MJD */
5647 br = regbranch(pRExC_state, &flags, 1,depth+1);
5648 /* branch_len = (paren != 0); */
5652 if (*RExC_parse == '|') {
5653 if (!SIZE_ONLY && RExC_extralen) {
5654 reginsert(pRExC_state, BRANCHJ, br, depth+1);
5657 reginsert(pRExC_state, BRANCH, br, depth+1);
5658 Set_Node_Length(br, paren != 0);
5659 Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
5663 RExC_extralen += 1; /* For BRANCHJ-BRANCH. */
5665 else if (paren == ':') {
5666 *flagp |= flags&SIMPLE;
5668 if (is_open) { /* Starts with OPEN. */
5669 REGTAIL(pRExC_state, ret, br); /* OPEN -> first. */
5671 else if (paren != '?') /* Not Conditional */
5673 *flagp |= flags & (SPSTART | HASWIDTH);
5675 while (*RExC_parse == '|') {
5676 if (!SIZE_ONLY && RExC_extralen) {
5677 ender = reganode(pRExC_state, LONGJMP,0);
5678 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
5681 RExC_extralen += 2; /* Account for LONGJMP. */
5682 nextchar(pRExC_state);
5684 if (RExC_npar > after_freeze)
5685 after_freeze = RExC_npar;
5686 RExC_npar = freeze_paren;
5688 br = regbranch(pRExC_state, &flags, 0, depth+1);
5692 REGTAIL(pRExC_state, lastbr, br); /* BRANCH -> BRANCH. */
5696 *flagp |= flags&SPSTART;
5699 if (have_branch || paren != ':') {
5700 /* Make a closing node, and hook it on the end. */
5703 ender = reg_node(pRExC_state, TAIL);
5706 ender = reganode(pRExC_state, CLOSE, parno);
5707 if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
5708 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5709 "Setting close paren #%"IVdf" to %d\n",
5710 (IV)parno, REG_NODE_NUM(ender)));
5711 RExC_close_parens[parno-1]= ender;
5712 if (RExC_nestroot == parno)
5715 Set_Node_Offset(ender,RExC_parse+1); /* MJD */
5716 Set_Node_Length(ender,1); /* MJD */
5722 *flagp &= ~HASWIDTH;
5725 ender = reg_node(pRExC_state, SUCCEED);
5728 ender = reg_node(pRExC_state, END);
5730 assert(!RExC_opend); /* there can only be one! */
5735 REGTAIL(pRExC_state, lastbr, ender);
5737 if (have_branch && !SIZE_ONLY) {
5739 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
5741 /* Hook the tails of the branches to the closing node. */
5742 for (br = ret; br; br = regnext(br)) {
5743 const U8 op = PL_regkind[OP(br)];
5745 REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
5747 else if (op == BRANCHJ) {
5748 REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
5756 static const char parens[] = "=!<,>";
5758 if (paren && (p = strchr(parens, paren))) {
5759 U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
5760 int flag = (p - parens) > 1;
5763 node = SUSPEND, flag = 0;
5764 reginsert(pRExC_state, node,ret, depth+1);
5765 Set_Node_Cur_Length(ret);
5766 Set_Node_Offset(ret, parse_start + 1);
5768 REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
5772 /* Check for proper termination. */
5774 RExC_flags = oregflags;
5775 if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
5776 RExC_parse = oregcomp_parse;
5777 vFAIL("Unmatched (");
5780 else if (!paren && RExC_parse < RExC_end) {
5781 if (*RExC_parse == ')') {
5783 vFAIL("Unmatched )");
5786 FAIL("Junk on end of regexp"); /* "Can't happen". */
5790 RExC_npar = after_freeze;
5795 - regbranch - one alternative of an | operator
5797 * Implements the concatenation operator.
5800 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
5803 register regnode *ret;
5804 register regnode *chain = NULL;
5805 register regnode *latest;
5806 I32 flags = 0, c = 0;
5807 GET_RE_DEBUG_FLAGS_DECL;
5808 DEBUG_PARSE("brnc");
5812 if (!SIZE_ONLY && RExC_extralen)
5813 ret = reganode(pRExC_state, BRANCHJ,0);
5815 ret = reg_node(pRExC_state, BRANCH);
5816 Set_Node_Length(ret, 1);
5820 if (!first && SIZE_ONLY)
5821 RExC_extralen += 1; /* BRANCHJ */
5823 *flagp = WORST; /* Tentatively. */
5826 nextchar(pRExC_state);
5827 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
5829 latest = regpiece(pRExC_state, &flags,depth+1);
5830 if (latest == NULL) {
5831 if (flags & TRYAGAIN)
5835 else if (ret == NULL)
5837 *flagp |= flags&HASWIDTH;
5838 if (chain == NULL) /* First piece. */
5839 *flagp |= flags&SPSTART;
5842 REGTAIL(pRExC_state, chain, latest);
5847 if (chain == NULL) { /* Loop ran zero times. */
5848 chain = reg_node(pRExC_state, NOTHING);
5853 *flagp |= flags&SIMPLE;
5860 - regpiece - something followed by possible [*+?]
5862 * Note that the branching code sequences used for ? and the general cases
5863 * of * and + are somewhat optimized: they use the same NOTHING node as
5864 * both the endmarker for their branch list and the body of the last branch.
5865 * It might seem that this node could be dispensed with entirely, but the
5866 * endmarker role is not redundant.
5869 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
5872 register regnode *ret;
5874 register char *next;
5876 const char * const origparse = RExC_parse;
5878 I32 max = REG_INFTY;
5880 const char *maxpos = NULL;
5881 GET_RE_DEBUG_FLAGS_DECL;
5882 DEBUG_PARSE("piec");
5884 ret = regatom(pRExC_state, &flags,depth+1);
5886 if (flags & TRYAGAIN)
5893 if (op == '{' && regcurly(RExC_parse)) {
5895 parse_start = RExC_parse; /* MJD */
5896 next = RExC_parse + 1;
5897 while (isDIGIT(*next) || *next == ',') {
5906 if (*next == '}') { /* got one */
5910 min = atoi(RExC_parse);
5914 maxpos = RExC_parse;
5916 if (!max && *maxpos != '0')
5917 max = REG_INFTY; /* meaning "infinity" */
5918 else if (max >= REG_INFTY)
5919 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
5921 nextchar(pRExC_state);
5924 if ((flags&SIMPLE)) {
5925 RExC_naughty += 2 + RExC_naughty / 2;
5926 reginsert(pRExC_state, CURLY, ret, depth+1);
5927 Set_Node_Offset(ret, parse_start+1); /* MJD */
5928 Set_Node_Cur_Length(ret);
5931 regnode * const w = reg_node(pRExC_state, WHILEM);
5934 REGTAIL(pRExC_state, ret, w);
5935 if (!SIZE_ONLY && RExC_extralen) {
5936 reginsert(pRExC_state, LONGJMP,ret, depth+1);
5937 reginsert(pRExC_state, NOTHING,ret, depth+1);
5938 NEXT_OFF(ret) = 3; /* Go over LONGJMP. */
5940 reginsert(pRExC_state, CURLYX,ret, depth+1);
5942 Set_Node_Offset(ret, parse_start+1);
5943 Set_Node_Length(ret,
5944 op == '{' ? (RExC_parse - parse_start) : 1);
5946 if (!SIZE_ONLY && RExC_extralen)
5947 NEXT_OFF(ret) = 3; /* Go over NOTHING to LONGJMP. */
5948 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
5950 RExC_whilem_seen++, RExC_extralen += 3;
5951 RExC_naughty += 4 + RExC_naughty; /* compound interest */
5959 if (max && max < min)
5960 vFAIL("Can't do {n,m} with n > m");
5962 ARG1_SET(ret, (U16)min);
5963 ARG2_SET(ret, (U16)max);
5975 #if 0 /* Now runtime fix should be reliable. */
5977 /* if this is reinstated, don't forget to put this back into perldiag:
5979 =item Regexp *+ operand could be empty at {#} in regex m/%s/
5981 (F) The part of the regexp subject to either the * or + quantifier
5982 could match an empty string. The {#} shows in the regular
5983 expression about where the problem was discovered.
5987 if (!(flags&HASWIDTH) && op != '?')
5988 vFAIL("Regexp *+ operand could be empty");
5991 parse_start = RExC_parse;
5992 nextchar(pRExC_state);
5994 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
5996 if (op == '*' && (flags&SIMPLE)) {
5997 reginsert(pRExC_state, STAR, ret, depth+1);
6001 else if (op == '*') {
6005 else if (op == '+' && (flags&SIMPLE)) {
6006 reginsert(pRExC_state, PLUS, ret, depth+1);
6010 else if (op == '+') {
6014 else if (op == '?') {
6019 if (!SIZE_ONLY && !(flags&HASWIDTH) && max > REG_INFTY/3 && ckWARN(WARN_REGEXP)) {
6021 "%.*s matches null string many times",
6022 (int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
6026 if (RExC_parse < RExC_end && *RExC_parse == '?') {
6027 nextchar(pRExC_state);
6028 reginsert(pRExC_state, MINMOD, ret, depth+1);
6029 REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
6031 #ifndef REG_ALLOW_MINMOD_SUSPEND
6034 if (RExC_parse < RExC_end && *RExC_parse == '+') {
6036 nextchar(pRExC_state);
6037 ender = reg_node(pRExC_state, SUCCEED);
6038 REGTAIL(pRExC_state, ret, ender);
6039 reginsert(pRExC_state, SUSPEND, ret, depth+1);
6041 ender = reg_node(pRExC_state, TAIL);
6042 REGTAIL(pRExC_state, ret, ender);
6046 if (RExC_parse < RExC_end && ISMULT2(RExC_parse)) {
6048 vFAIL("Nested quantifiers");
6055 /* reg_namedseq(pRExC_state,UVp)
6057 This is expected to be called by a parser routine that has
6058 recognized'\N' and needs to handle the rest. RExC_parse is
6059 expected to point at the first char following the N at the time
6062 If valuep is non-null then it is assumed that we are parsing inside
6063 of a charclass definition and the first codepoint in the resolved
6064 string is returned via *valuep and the routine will return NULL.
6065 In this mode if a multichar string is returned from the charnames
6066 handler a warning will be issued, and only the first char in the
6067 sequence will be examined. If the string returned is zero length
6068 then the value of *valuep is undefined and NON-NULL will
6069 be returned to indicate failure. (This will NOT be a valid pointer
6072 If value is null then it is assumed that we are parsing normal text
6073 and inserts a new EXACT node into the program containing the resolved
6074 string and returns a pointer to the new node. If the string is
6075 zerolength a NOTHING node is emitted.
6077 On success RExC_parse is set to the char following the endbrace.
6078 Parsing failures will generate a fatal errorvia vFAIL(...)
6080 NOTE: We cache all results from the charnames handler locally in
6081 the RExC_charnames hash (created on first use) to prevent a charnames
6082 handler from playing silly-buggers and returning a short string and
6083 then a long string for a given pattern. Since the regexp program
6084 size is calculated during an initial parse this would result
6085 in a buffer overrun so we cache to prevent the charname result from
6086 changing during the course of the parse.
6090 S_reg_namedseq(pTHX_ RExC_state_t *pRExC_state, UV *valuep)
6092 char * name; /* start of the content of the name */
6093 char * endbrace; /* endbrace following the name */
6096 STRLEN len; /* this has various purposes throughout the code */
6097 bool cached = 0; /* if this is true then we shouldn't refcount dev sv_str */
6098 regnode *ret = NULL;
6100 if (*RExC_parse != '{') {
6101 vFAIL("Missing braces on \\N{}");
6103 name = RExC_parse+1;
6104 endbrace = strchr(RExC_parse, '}');
6107 vFAIL("Missing right brace on \\N{}");
6109 RExC_parse = endbrace + 1;
6112 /* RExC_parse points at the beginning brace,
6113 endbrace points at the last */
6114 if ( name[0]=='U' && name[1]=='+' ) {
6115 /* its a "unicode hex" notation {U+89AB} */
6116 I32 fl = PERL_SCAN_ALLOW_UNDERSCORES
6117 | PERL_SCAN_DISALLOW_PREFIX
6118 | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
6120 len = (STRLEN)(endbrace - name - 2);
6121 cp = grok_hex(name + 2, &len, &fl, NULL);
6122 if ( len != (STRLEN)(endbrace - name - 2) ) {
6131 sv_str= Perl_newSVpvf_nocontext("%c",(int)cp);
6133 /* fetch the charnames handler for this scope */
6134 HV * const table = GvHV(PL_hintgv);
6136 hv_fetchs(table, "charnames", FALSE) :
6138 SV *cv= cvp ? *cvp : NULL;
6141 /* create an SV with the name as argument */
6142 sv_name = newSVpvn(name, endbrace - name);
6144 if (!table || !(PL_hints & HINT_LOCALIZE_HH)) {
6145 vFAIL2("Constant(\\N{%s}) unknown: "
6146 "(possibly a missing \"use charnames ...\")",
6149 if (!cvp || !SvOK(*cvp)) { /* when $^H{charnames} = undef; */
6150 vFAIL2("Constant(\\N{%s}): "
6151 "$^H{charnames} is not defined",SvPVX(sv_name));
6156 if (!RExC_charnames) {
6157 /* make sure our cache is allocated */
6158 RExC_charnames = newHV();
6159 sv_2mortal((SV*)RExC_charnames);
6161 /* see if we have looked this one up before */
6162 he_str = hv_fetch_ent( RExC_charnames, sv_name, 0, 0 );
6164 sv_str = HeVAL(he_str);
6177 count= call_sv(cv, G_SCALAR);
6179 if (count == 1) { /* XXXX is this right? dmq */
6181 SvREFCNT_inc_simple_void(sv_str);
6189 if ( !sv_str || !SvOK(sv_str) ) {
6190 vFAIL2("Constant(\\N{%s}): Call to &{$^H{charnames}} "
6191 "did not return a defined value",SvPVX(sv_name));
6193 if (hv_store_ent( RExC_charnames, sv_name, sv_str, 0))
6198 char *p = SvPV(sv_str, len);
6201 if ( SvUTF8(sv_str) ) {
6202 *valuep = utf8_to_uvchr((U8*)p, &numlen);
6206 We have to turn on utf8 for high bit chars otherwise
6207 we get failures with
6209 "ss" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
6210 "SS" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
6212 This is different from what \x{} would do with the same
6213 codepoint, where the condition is > 0xFF.
6220 /* warn if we havent used the whole string? */
6222 if (numlen<len && SIZE_ONLY && ckWARN(WARN_REGEXP)) {
6224 "Ignoring excess chars from \\N{%s} in character class",
6228 } else if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
6230 "Ignoring zero length \\N{%s} in character class",
6235 SvREFCNT_dec(sv_name);
6237 SvREFCNT_dec(sv_str);
6238 return len ? NULL : (regnode *)&len;
6239 } else if(SvCUR(sv_str)) {
6245 char * parse_start = name-3; /* needed for the offsets */
6247 GET_RE_DEBUG_FLAGS_DECL; /* needed for the offsets */
6249 ret = reg_node(pRExC_state,
6250 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
6253 if ( RExC_utf8 && !SvUTF8(sv_str) ) {
6254 sv_utf8_upgrade(sv_str);
6255 } else if ( !RExC_utf8 && SvUTF8(sv_str) ) {
6259 p = SvPV(sv_str, len);
6261 /* len is the length written, charlen is the size the char read */
6262 for ( len = 0; p < pend; p += charlen ) {
6264 UV uvc = utf8_to_uvchr((U8*)p, &charlen);
6266 STRLEN foldlen,numlen;
6267 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
6268 uvc = toFOLD_uni(uvc, tmpbuf, &foldlen);
6269 /* Emit all the Unicode characters. */
6271 for (foldbuf = tmpbuf;
6275 uvc = utf8_to_uvchr(foldbuf, &numlen);
6277 const STRLEN unilen = reguni(pRExC_state, uvc, s);
6280 /* In EBCDIC the numlen
6281 * and unilen can differ. */
6283 if (numlen >= foldlen)
6287 break; /* "Can't happen." */
6290 const STRLEN unilen = reguni(pRExC_state, uvc, s);
6302 RExC_size += STR_SZ(len);
6305 RExC_emit += STR_SZ(len);
6307 Set_Node_Cur_Length(ret); /* MJD */
6309 nextchar(pRExC_state);
6311 ret = reg_node(pRExC_state,NOTHING);
6314 SvREFCNT_dec(sv_str);
6317 SvREFCNT_dec(sv_name);
6327 * It returns the code point in utf8 for the value in *encp.
6328 * value: a code value in the source encoding
6329 * encp: a pointer to an Encode object
6331 * If the result from Encode is not a single character,
6332 * it returns U+FFFD (Replacement character) and sets *encp to NULL.
6335 S_reg_recode(pTHX_ const char value, SV **encp)
6338 SV * const sv = sv_2mortal(newSVpvn(&value, numlen));
6339 const char * const s = encp && *encp ? sv_recode_to_utf8(sv, *encp)
6341 const STRLEN newlen = SvCUR(sv);
6342 UV uv = UNICODE_REPLACEMENT;
6346 ? utf8n_to_uvchr((U8*)s, newlen, &numlen, UTF8_ALLOW_DEFAULT)
6349 if (!newlen || numlen != newlen) {
6350 uv = UNICODE_REPLACEMENT;
6359 - regatom - the lowest level
6361 Try to identify anything special at the start of the pattern. If there
6362 is, then handle it as required. This may involve generating a single regop,
6363 such as for an assertion; or it may involve recursing, such as to
6364 handle a () structure.
6366 If the string doesn't start with something special then we gobble up
6367 as much literal text as we can.
6369 Once we have been able to handle whatever type of thing started the
6370 sequence, we return.
6372 Note: we have to be careful with escapes, as they can be both literal
6373 and special, and in the case of \10 and friends can either, depending
6374 on context. Specifically there are two seperate switches for handling
6375 escape sequences, with the one for handling literal escapes requiring
6376 a dummy entry for all of the special escapes that are actually handled
6381 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
6384 register regnode *ret = NULL;
6386 char *parse_start = RExC_parse;
6387 GET_RE_DEBUG_FLAGS_DECL;
6388 DEBUG_PARSE("atom");
6389 *flagp = WORST; /* Tentatively. */
6393 switch (*RExC_parse) {
6395 RExC_seen_zerolen++;
6396 nextchar(pRExC_state);
6397 if (RExC_flags & RXf_PMf_MULTILINE)
6398 ret = reg_node(pRExC_state, MBOL);
6399 else if (RExC_flags & RXf_PMf_SINGLELINE)
6400 ret = reg_node(pRExC_state, SBOL);
6402 ret = reg_node(pRExC_state, BOL);
6403 Set_Node_Length(ret, 1); /* MJD */
6406 nextchar(pRExC_state);
6408 RExC_seen_zerolen++;
6409 if (RExC_flags & RXf_PMf_MULTILINE)
6410 ret = reg_node(pRExC_state, MEOL);
6411 else if (RExC_flags & RXf_PMf_SINGLELINE)
6412 ret = reg_node(pRExC_state, SEOL);
6414 ret = reg_node(pRExC_state, EOL);
6415 Set_Node_Length(ret, 1); /* MJD */
6418 nextchar(pRExC_state);
6419 if (RExC_flags & RXf_PMf_SINGLELINE)
6420 ret = reg_node(pRExC_state, SANY);
6422 ret = reg_node(pRExC_state, REG_ANY);
6423 *flagp |= HASWIDTH|SIMPLE;
6425 Set_Node_Length(ret, 1); /* MJD */
6429 char * const oregcomp_parse = ++RExC_parse;
6430 ret = regclass(pRExC_state,depth+1);
6431 if (*RExC_parse != ']') {
6432 RExC_parse = oregcomp_parse;
6433 vFAIL("Unmatched [");
6435 nextchar(pRExC_state);
6436 *flagp |= HASWIDTH|SIMPLE;
6437 Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
6441 nextchar(pRExC_state);
6442 ret = reg(pRExC_state, 1, &flags,depth+1);
6444 if (flags & TRYAGAIN) {
6445 if (RExC_parse == RExC_end) {
6446 /* Make parent create an empty node if needed. */
6454 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE);
6458 if (flags & TRYAGAIN) {
6462 vFAIL("Internal urp");
6463 /* Supposed to be caught earlier. */
6466 if (!regcurly(RExC_parse)) {
6475 vFAIL("Quantifier follows nothing");
6480 This switch handles escape sequences that resolve to some kind
6481 of special regop and not to literal text. Escape sequnces that
6482 resolve to literal text are handled below in the switch marked
6485 Every entry in this switch *must* have a corresponding entry
6486 in the literal escape switch. However, the opposite is not
6487 required, as the default for this switch is to jump to the
6488 literal text handling code.
6490 switch (*++RExC_parse) {
6491 /* Special Escapes */
6493 RExC_seen_zerolen++;
6494 ret = reg_node(pRExC_state, SBOL);
6496 goto finish_meta_pat;
6498 ret = reg_node(pRExC_state, GPOS);
6499 RExC_seen |= REG_SEEN_GPOS;
6501 goto finish_meta_pat;
6503 RExC_seen_zerolen++;
6504 ret = reg_node(pRExC_state, KEEPS);
6506 goto finish_meta_pat;
6508 ret = reg_node(pRExC_state, SEOL);
6510 RExC_seen_zerolen++; /* Do not optimize RE away */
6511 goto finish_meta_pat;
6513 ret = reg_node(pRExC_state, EOS);
6515 RExC_seen_zerolen++; /* Do not optimize RE away */
6516 goto finish_meta_pat;
6518 ret = reg_node(pRExC_state, CANY);
6519 RExC_seen |= REG_SEEN_CANY;
6520 *flagp |= HASWIDTH|SIMPLE;
6521 goto finish_meta_pat;
6523 ret = reg_node(pRExC_state, CLUMP);
6525 goto finish_meta_pat;
6527 ret = reg_node(pRExC_state, (U8)(LOC ? ALNUML : ALNUM));
6528 *flagp |= HASWIDTH|SIMPLE;
6529 goto finish_meta_pat;
6531 ret = reg_node(pRExC_state, (U8)(LOC ? NALNUML : NALNUM));
6532 *flagp |= HASWIDTH|SIMPLE;
6533 goto finish_meta_pat;
6535 RExC_seen_zerolen++;
6536 RExC_seen |= REG_SEEN_LOOKBEHIND;
6537 ret = reg_node(pRExC_state, (U8)(LOC ? BOUNDL : BOUND));
6539 goto finish_meta_pat;
6541 RExC_seen_zerolen++;
6542 RExC_seen |= REG_SEEN_LOOKBEHIND;
6543 ret = reg_node(pRExC_state, (U8)(LOC ? NBOUNDL : NBOUND));
6545 goto finish_meta_pat;
6547 ret = reg_node(pRExC_state, (U8)(LOC ? SPACEL : SPACE));
6548 *flagp |= HASWIDTH|SIMPLE;
6549 goto finish_meta_pat;
6551 ret = reg_node(pRExC_state, (U8)(LOC ? NSPACEL : NSPACE));
6552 *flagp |= HASWIDTH|SIMPLE;
6553 goto finish_meta_pat;
6555 ret = reg_node(pRExC_state, DIGIT);
6556 *flagp |= HASWIDTH|SIMPLE;
6557 goto finish_meta_pat;
6559 ret = reg_node(pRExC_state, NDIGIT);
6560 *flagp |= HASWIDTH|SIMPLE;
6561 goto finish_meta_pat;
6563 ret = reganode(pRExC_state, PRUNE, 0);
6566 goto finish_meta_pat;
6568 ret = reganode(pRExC_state, SKIP, 0);
6572 nextchar(pRExC_state);
6573 Set_Node_Length(ret, 2); /* MJD */
6578 char* const oldregxend = RExC_end;
6580 char* parse_start = RExC_parse - 2;
6583 if (RExC_parse[1] == '{') {
6584 /* a lovely hack--pretend we saw [\pX] instead */
6585 RExC_end = strchr(RExC_parse, '}');
6587 const U8 c = (U8)*RExC_parse;
6589 RExC_end = oldregxend;
6590 vFAIL2("Missing right brace on \\%c{}", c);
6595 RExC_end = RExC_parse + 2;
6596 if (RExC_end > oldregxend)
6597 RExC_end = oldregxend;
6601 ret = regclass(pRExC_state,depth+1);
6603 RExC_end = oldregxend;
6606 Set_Node_Offset(ret, parse_start + 2);
6607 Set_Node_Cur_Length(ret);
6608 nextchar(pRExC_state);
6609 *flagp |= HASWIDTH|SIMPLE;
6613 /* Handle \N{NAME} here and not below because it can be
6614 multicharacter. join_exact() will join them up later on.
6615 Also this makes sure that things like /\N{BLAH}+/ and
6616 \N{BLAH} being multi char Just Happen. dmq*/
6618 ret= reg_namedseq(pRExC_state, NULL);
6620 case 'k': /* Handle \k<NAME> and \k'NAME' */
6623 char ch= RExC_parse[1];
6624 if (ch != '<' && ch != '\'' && ch != '{') {
6626 vFAIL2("Sequence %.2s... not terminated",parse_start);
6628 /* this pretty much dupes the code for (?P=...) in reg(), if
6629 you change this make sure you change that */
6630 char* name_start = (RExC_parse += 2);
6632 SV *sv_dat = reg_scan_name(pRExC_state,
6633 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
6634 ch= (ch == '<') ? '>' : (ch == '{') ? '}' : '\'';
6635 if (RExC_parse == name_start || *RExC_parse != ch)
6636 vFAIL2("Sequence %.3s... not terminated",parse_start);
6639 num = add_data( pRExC_state, 1, "S" );
6640 RExC_rxi->data->data[num]=(void*)sv_dat;
6641 SvREFCNT_inc(sv_dat);
6645 ret = reganode(pRExC_state,
6646 (U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
6650 /* override incorrect value set in reganode MJD */
6651 Set_Node_Offset(ret, parse_start+1);
6652 Set_Node_Cur_Length(ret); /* MJD */
6653 nextchar(pRExC_state);
6659 case '1': case '2': case '3': case '4':
6660 case '5': case '6': case '7': case '8': case '9':
6663 bool isg = *RExC_parse == 'g';
6668 if (*RExC_parse == '{') {
6672 if (*RExC_parse == '-') {
6676 if (hasbrace && !isDIGIT(*RExC_parse)) {
6677 if (isrel) RExC_parse--;
6679 goto parse_named_seq;
6681 num = atoi(RExC_parse);
6683 num = RExC_npar - num;
6685 vFAIL("Reference to nonexistent or unclosed group");
6687 if (!isg && num > 9 && num >= RExC_npar)
6690 char * const parse_start = RExC_parse - 1; /* MJD */
6691 while (isDIGIT(*RExC_parse))
6693 if (parse_start == RExC_parse - 1)
6694 vFAIL("Unterminated \\g... pattern");
6696 if (*RExC_parse != '}')
6697 vFAIL("Unterminated \\g{...} pattern");
6701 if (num > (I32)RExC_rx->nparens)
6702 vFAIL("Reference to nonexistent group");
6705 ret = reganode(pRExC_state,
6706 (U8)(FOLD ? (LOC ? REFFL : REFF) : REF),
6710 /* override incorrect value set in reganode MJD */
6711 Set_Node_Offset(ret, parse_start+1);
6712 Set_Node_Cur_Length(ret); /* MJD */
6714 nextchar(pRExC_state);
6719 if (RExC_parse >= RExC_end)
6720 FAIL("Trailing \\");
6723 /* Do not generate "unrecognized" warnings here, we fall
6724 back into the quick-grab loop below */
6731 if (RExC_flags & RXf_PMf_EXTENDED) {
6732 if ( reg_skipcomment( pRExC_state ) )
6738 register STRLEN len;
6743 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
6745 parse_start = RExC_parse - 1;
6751 ret = reg_node(pRExC_state,
6752 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
6754 for (len = 0, p = RExC_parse - 1;
6755 len < 127 && p < RExC_end;
6758 char * const oldp = p;
6760 if (RExC_flags & RXf_PMf_EXTENDED)
6761 p = regwhite( pRExC_state, p );
6772 /* Literal Escapes Switch
6774 This switch is meant to handle escape sequences that
6775 resolve to a literal character.
6777 Every escape sequence that represents something
6778 else, like an assertion or a char class, is handled
6779 in the switch marked 'Special Escapes' above in this
6780 routine, but also has an entry here as anything that
6781 isn't explicitly mentioned here will be treated as
6782 an unescaped equivalent literal.
6786 /* These are all the special escapes. */
6787 case 'A': /* Start assertion */
6788 case 'b': case 'B': /* Word-boundary assertion*/
6789 case 'C': /* Single char !DANGEROUS! */
6790 case 'd': case 'D': /* digit class */
6791 case 'g': case 'G': /* generic-backref, pos assertion */
6792 case 'k': case 'K': /* named backref, keep marker */
6793 case 'N': /* named char sequence */
6794 case 'p': case 'P': /* unicode property */
6795 case 's': case 'S': /* space class */
6796 case 'v': case 'V': /* (*PRUNE) and (*SKIP) */
6797 case 'w': case 'W': /* word class */
6798 case 'X': /* eXtended Unicode "combining character sequence" */
6799 case 'z': case 'Z': /* End of line/string assertion */
6803 /* Anything after here is an escape that resolves to a
6804 literal. (Except digits, which may or may not)
6823 ender = ASCII_TO_NATIVE('\033');
6827 ender = ASCII_TO_NATIVE('\007');
6832 char* const e = strchr(p, '}');
6836 vFAIL("Missing right brace on \\x{}");
6839 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
6840 | PERL_SCAN_DISALLOW_PREFIX;
6841 STRLEN numlen = e - p - 1;
6842 ender = grok_hex(p + 1, &numlen, &flags, NULL);
6849 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
6851 ender = grok_hex(p, &numlen, &flags, NULL);
6854 if (PL_encoding && ender < 0x100)
6855 goto recode_encoding;
6859 ender = UCHARAT(p++);
6860 ender = toCTRL(ender);
6862 case '0': case '1': case '2': case '3':case '4':
6863 case '5': case '6': case '7': case '8':case '9':
6865 (isDIGIT(p[1]) && atoi(p) >= RExC_npar) ) {
6868 ender = grok_oct(p, &numlen, &flags, NULL);
6875 if (PL_encoding && ender < 0x100)
6876 goto recode_encoding;
6880 SV* enc = PL_encoding;
6881 ender = reg_recode((const char)(U8)ender, &enc);
6882 if (!enc && SIZE_ONLY && ckWARN(WARN_REGEXP))
6883 vWARN(p, "Invalid escape in the specified encoding");
6889 FAIL("Trailing \\");
6892 if (!SIZE_ONLY&& isALPHA(*p) && ckWARN(WARN_REGEXP))
6893 vWARN2(p + 1, "Unrecognized escape \\%c passed through", UCHARAT(p));
6894 goto normal_default;
6899 if (UTF8_IS_START(*p) && UTF) {
6901 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
6902 &numlen, UTF8_ALLOW_DEFAULT);
6909 if ( RExC_flags & RXf_PMf_EXTENDED)
6910 p = regwhite( pRExC_state, p );
6912 /* Prime the casefolded buffer. */
6913 ender = toFOLD_uni(ender, tmpbuf, &foldlen);
6915 if (p < RExC_end && ISMULT2(p)) { /* Back off on ?+*. */
6920 /* Emit all the Unicode characters. */
6922 for (foldbuf = tmpbuf;
6924 foldlen -= numlen) {
6925 ender = utf8_to_uvchr(foldbuf, &numlen);
6927 const STRLEN unilen = reguni(pRExC_state, ender, s);
6930 /* In EBCDIC the numlen
6931 * and unilen can differ. */
6933 if (numlen >= foldlen)
6937 break; /* "Can't happen." */
6941 const STRLEN unilen = reguni(pRExC_state, ender, s);
6950 REGC((char)ender, s++);
6956 /* Emit all the Unicode characters. */
6958 for (foldbuf = tmpbuf;
6960 foldlen -= numlen) {
6961 ender = utf8_to_uvchr(foldbuf, &numlen);
6963 const STRLEN unilen = reguni(pRExC_state, ender, s);
6966 /* In EBCDIC the numlen
6967 * and unilen can differ. */
6969 if (numlen >= foldlen)
6977 const STRLEN unilen = reguni(pRExC_state, ender, s);
6986 REGC((char)ender, s++);
6990 Set_Node_Cur_Length(ret); /* MJD */
6991 nextchar(pRExC_state);
6993 /* len is STRLEN which is unsigned, need to copy to signed */
6996 vFAIL("Internal disaster");
7000 if (len == 1 && UNI_IS_INVARIANT(ender))
7004 RExC_size += STR_SZ(len);
7007 RExC_emit += STR_SZ(len);
7017 S_regwhite( RExC_state_t *pRExC_state, char *p )
7019 const char *e = RExC_end;
7023 else if (*p == '#') {
7032 RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
7040 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
7041 Character classes ([:foo:]) can also be negated ([:^foo:]).
7042 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
7043 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
7044 but trigger failures because they are currently unimplemented. */
7046 #define POSIXCC_DONE(c) ((c) == ':')
7047 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
7048 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
7051 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
7054 I32 namedclass = OOB_NAMEDCLASS;
7056 if (value == '[' && RExC_parse + 1 < RExC_end &&
7057 /* I smell either [: or [= or [. -- POSIX has been here, right? */
7058 POSIXCC(UCHARAT(RExC_parse))) {
7059 const char c = UCHARAT(RExC_parse);
7060 char* const s = RExC_parse++;
7062 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
7064 if (RExC_parse == RExC_end)
7065 /* Grandfather lone [:, [=, [. */
7068 const char* const t = RExC_parse++; /* skip over the c */
7071 if (UCHARAT(RExC_parse) == ']') {
7072 const char *posixcc = s + 1;
7073 RExC_parse++; /* skip over the ending ] */
7076 const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
7077 const I32 skip = t - posixcc;
7079 /* Initially switch on the length of the name. */
7082 if (memEQ(posixcc, "word", 4)) /* this is not POSIX, this is the Perl \w */
7083 namedclass = complement ? ANYOF_NALNUM : ANYOF_ALNUM;
7086 /* Names all of length 5. */
7087 /* alnum alpha ascii blank cntrl digit graph lower
7088 print punct space upper */
7089 /* Offset 4 gives the best switch position. */
7090 switch (posixcc[4]) {
7092 if (memEQ(posixcc, "alph", 4)) /* alpha */
7093 namedclass = complement ? ANYOF_NALPHA : ANYOF_ALPHA;
7096 if (memEQ(posixcc, "spac", 4)) /* space */
7097 namedclass = complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
7100 if (memEQ(posixcc, "grap", 4)) /* graph */
7101 namedclass = complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
7104 if (memEQ(posixcc, "asci", 4)) /* ascii */
7105 namedclass = complement ? ANYOF_NASCII : ANYOF_ASCII;
7108 if (memEQ(posixcc, "blan", 4)) /* blank */
7109 namedclass = complement ? ANYOF_NBLANK : ANYOF_BLANK;
7112 if (memEQ(posixcc, "cntr", 4)) /* cntrl */
7113 namedclass = complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
7116 if (memEQ(posixcc, "alnu", 4)) /* alnum */
7117 namedclass = complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
7120 if (memEQ(posixcc, "lowe", 4)) /* lower */
7121 namedclass = complement ? ANYOF_NLOWER : ANYOF_LOWER;
7122 else if (memEQ(posixcc, "uppe", 4)) /* upper */
7123 namedclass = complement ? ANYOF_NUPPER : ANYOF_UPPER;
7126 if (memEQ(posixcc, "digi", 4)) /* digit */
7127 namedclass = complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
7128 else if (memEQ(posixcc, "prin", 4)) /* print */
7129 namedclass = complement ? ANYOF_NPRINT : ANYOF_PRINT;
7130 else if (memEQ(posixcc, "punc", 4)) /* punct */
7131 namedclass = complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
7136 if (memEQ(posixcc, "xdigit", 6))
7137 namedclass = complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
7141 if (namedclass == OOB_NAMEDCLASS)
7142 Simple_vFAIL3("POSIX class [:%.*s:] unknown",
7144 assert (posixcc[skip] == ':');
7145 assert (posixcc[skip+1] == ']');
7146 } else if (!SIZE_ONLY) {
7147 /* [[=foo=]] and [[.foo.]] are still future. */
7149 /* adjust RExC_parse so the warning shows after
7151 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
7153 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
7156 /* Maternal grandfather:
7157 * "[:" ending in ":" but not in ":]" */
7167 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
7170 if (POSIXCC(UCHARAT(RExC_parse))) {
7171 const char *s = RExC_parse;
7172 const char c = *s++;
7176 if (*s && c == *s && s[1] == ']') {
7177 if (ckWARN(WARN_REGEXP))
7179 "POSIX syntax [%c %c] belongs inside character classes",
7182 /* [[=foo=]] and [[.foo.]] are still future. */
7183 if (POSIXCC_NOTYET(c)) {
7184 /* adjust RExC_parse so the error shows after
7186 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
7188 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
7195 #define _C_C_T_(NAME,TEST,WORD) \
7198 ANYOF_CLASS_SET(ret, ANYOF_##NAME); \
7200 for (value = 0; value < 256; value++) \
7202 ANYOF_BITMAP_SET(ret, value); \
7207 case ANYOF_N##NAME: \
7209 ANYOF_CLASS_SET(ret, ANYOF_N##NAME); \
7211 for (value = 0; value < 256; value++) \
7213 ANYOF_BITMAP_SET(ret, value); \
7221 parse a class specification and produce either an ANYOF node that
7222 matches the pattern or if the pattern matches a single char only and
7223 that char is < 256 and we are case insensitive then we produce an
7228 S_regclass(pTHX_ RExC_state_t *pRExC_state, U32 depth)
7231 register UV value = 0;
7232 register UV nextvalue;
7233 register IV prevvalue = OOB_UNICODE;
7234 register IV range = 0;
7235 register regnode *ret;
7238 char *rangebegin = NULL;
7239 bool need_class = 0;
7242 bool optimize_invert = TRUE;
7243 AV* unicode_alternate = NULL;
7245 UV literal_endpoint = 0;
7247 UV stored = 0; /* number of chars stored in the class */
7249 regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
7250 case we need to change the emitted regop to an EXACT. */
7251 const char * orig_parse = RExC_parse;
7252 GET_RE_DEBUG_FLAGS_DECL;
7254 PERL_UNUSED_ARG(depth);
7257 DEBUG_PARSE("clas");
7259 /* Assume we are going to generate an ANYOF node. */
7260 ret = reganode(pRExC_state, ANYOF, 0);
7263 ANYOF_FLAGS(ret) = 0;
7265 if (UCHARAT(RExC_parse) == '^') { /* Complement of range. */
7269 ANYOF_FLAGS(ret) |= ANYOF_INVERT;
7273 RExC_size += ANYOF_SKIP;
7274 listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
7277 RExC_emit += ANYOF_SKIP;
7279 ANYOF_FLAGS(ret) |= ANYOF_FOLD;
7281 ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
7282 ANYOF_BITMAP_ZERO(ret);
7283 listsv = newSVpvs("# comment\n");
7286 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
7288 if (!SIZE_ONLY && POSIXCC(nextvalue))
7289 checkposixcc(pRExC_state);
7291 /* allow 1st char to be ] (allowing it to be - is dealt with later) */
7292 if (UCHARAT(RExC_parse) == ']')
7296 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
7300 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
7303 rangebegin = RExC_parse;
7305 value = utf8n_to_uvchr((U8*)RExC_parse,
7306 RExC_end - RExC_parse,
7307 &numlen, UTF8_ALLOW_DEFAULT);
7308 RExC_parse += numlen;
7311 value = UCHARAT(RExC_parse++);
7313 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
7314 if (value == '[' && POSIXCC(nextvalue))
7315 namedclass = regpposixcc(pRExC_state, value);
7316 else if (value == '\\') {
7318 value = utf8n_to_uvchr((U8*)RExC_parse,
7319 RExC_end - RExC_parse,
7320 &numlen, UTF8_ALLOW_DEFAULT);
7321 RExC_parse += numlen;
7324 value = UCHARAT(RExC_parse++);
7325 /* Some compilers cannot handle switching on 64-bit integer
7326 * values, therefore value cannot be an UV. Yes, this will
7327 * be a problem later if we want switch on Unicode.
7328 * A similar issue a little bit later when switching on
7329 * namedclass. --jhi */
7330 switch ((I32)value) {
7331 case 'w': namedclass = ANYOF_ALNUM; break;
7332 case 'W': namedclass = ANYOF_NALNUM; break;
7333 case 's': namedclass = ANYOF_SPACE; break;
7334 case 'S': namedclass = ANYOF_NSPACE; break;
7335 case 'd': namedclass = ANYOF_DIGIT; break;
7336 case 'D': namedclass = ANYOF_NDIGIT; break;
7337 case 'N': /* Handle \N{NAME} in class */
7339 /* We only pay attention to the first char of
7340 multichar strings being returned. I kinda wonder
7341 if this makes sense as it does change the behaviour
7342 from earlier versions, OTOH that behaviour was broken
7344 UV v; /* value is register so we cant & it /grrr */
7345 if (reg_namedseq(pRExC_state, &v)) {
7355 if (RExC_parse >= RExC_end)
7356 vFAIL2("Empty \\%c{}", (U8)value);
7357 if (*RExC_parse == '{') {
7358 const U8 c = (U8)value;
7359 e = strchr(RExC_parse++, '}');
7361 vFAIL2("Missing right brace on \\%c{}", c);
7362 while (isSPACE(UCHARAT(RExC_parse)))
7364 if (e == RExC_parse)
7365 vFAIL2("Empty \\%c{}", c);
7367 while (isSPACE(UCHARAT(RExC_parse + n - 1)))
7375 if (UCHARAT(RExC_parse) == '^') {
7378 value = value == 'p' ? 'P' : 'p'; /* toggle */
7379 while (isSPACE(UCHARAT(RExC_parse))) {
7384 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%.*s\n",
7385 (value=='p' ? '+' : '!'), (int)n, RExC_parse);
7388 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
7389 namedclass = ANYOF_MAX; /* no official name, but it's named */
7392 case 'n': value = '\n'; break;
7393 case 'r': value = '\r'; break;
7394 case 't': value = '\t'; break;
7395 case 'f': value = '\f'; break;
7396 case 'b': value = '\b'; break;
7397 case 'e': value = ASCII_TO_NATIVE('\033');break;
7398 case 'a': value = ASCII_TO_NATIVE('\007');break;
7400 if (*RExC_parse == '{') {
7401 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
7402 | PERL_SCAN_DISALLOW_PREFIX;
7403 char * const e = strchr(RExC_parse++, '}');
7405 vFAIL("Missing right brace on \\x{}");
7407 numlen = e - RExC_parse;
7408 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
7412 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
7414 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
7415 RExC_parse += numlen;
7417 if (PL_encoding && value < 0x100)
7418 goto recode_encoding;
7421 value = UCHARAT(RExC_parse++);
7422 value = toCTRL(value);
7424 case '0': case '1': case '2': case '3': case '4':
7425 case '5': case '6': case '7': case '8': case '9':
7429 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
7430 RExC_parse += numlen;
7431 if (PL_encoding && value < 0x100)
7432 goto recode_encoding;
7437 SV* enc = PL_encoding;
7438 value = reg_recode((const char)(U8)value, &enc);
7439 if (!enc && SIZE_ONLY && ckWARN(WARN_REGEXP))
7441 "Invalid escape in the specified encoding");
7445 if (!SIZE_ONLY && isALPHA(value) && ckWARN(WARN_REGEXP))
7447 "Unrecognized escape \\%c in character class passed through",
7451 } /* end of \blah */
7457 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
7459 if (!SIZE_ONLY && !need_class)
7460 ANYOF_CLASS_ZERO(ret);
7464 /* a bad range like a-\d, a-[:digit:] ? */
7467 if (ckWARN(WARN_REGEXP)) {
7469 RExC_parse >= rangebegin ?
7470 RExC_parse - rangebegin : 0;
7472 "False [] range \"%*.*s\"",
7475 if (prevvalue < 256) {
7476 ANYOF_BITMAP_SET(ret, prevvalue);
7477 ANYOF_BITMAP_SET(ret, '-');
7480 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
7481 Perl_sv_catpvf(aTHX_ listsv,
7482 "%04"UVxf"\n%04"UVxf"\n", (UV)prevvalue, (UV) '-');
7486 range = 0; /* this was not a true range */
7492 const char *what = NULL;
7495 if (namedclass > OOB_NAMEDCLASS)
7496 optimize_invert = FALSE;
7497 /* Possible truncation here but in some 64-bit environments
7498 * the compiler gets heartburn about switch on 64-bit values.
7499 * A similar issue a little earlier when switching on value.
7501 switch ((I32)namedclass) {
7502 case _C_C_T_(ALNUM, isALNUM(value), "Word");
7503 case _C_C_T_(ALNUMC, isALNUMC(value), "Alnum");
7504 case _C_C_T_(ALPHA, isALPHA(value), "Alpha");
7505 case _C_C_T_(BLANK, isBLANK(value), "Blank");
7506 case _C_C_T_(CNTRL, isCNTRL(value), "Cntrl");
7507 case _C_C_T_(GRAPH, isGRAPH(value), "Graph");
7508 case _C_C_T_(LOWER, isLOWER(value), "Lower");
7509 case _C_C_T_(PRINT, isPRINT(value), "Print");
7510 case _C_C_T_(PSXSPC, isPSXSPC(value), "Space");
7511 case _C_C_T_(PUNCT, isPUNCT(value), "Punct");
7512 case _C_C_T_(SPACE, isSPACE(value), "SpacePerl");
7513 case _C_C_T_(UPPER, isUPPER(value), "Upper");
7514 case _C_C_T_(XDIGIT, isXDIGIT(value), "XDigit");
7517 ANYOF_CLASS_SET(ret, ANYOF_ASCII);
7520 for (value = 0; value < 128; value++)
7521 ANYOF_BITMAP_SET(ret, value);
7523 for (value = 0; value < 256; value++) {
7525 ANYOF_BITMAP_SET(ret, value);
7534 ANYOF_CLASS_SET(ret, ANYOF_NASCII);
7537 for (value = 128; value < 256; value++)
7538 ANYOF_BITMAP_SET(ret, value);
7540 for (value = 0; value < 256; value++) {
7541 if (!isASCII(value))
7542 ANYOF_BITMAP_SET(ret, value);
7551 ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
7553 /* consecutive digits assumed */
7554 for (value = '0'; value <= '9'; value++)
7555 ANYOF_BITMAP_SET(ret, value);
7562 ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
7564 /* consecutive digits assumed */
7565 for (value = 0; value < '0'; value++)
7566 ANYOF_BITMAP_SET(ret, value);
7567 for (value = '9' + 1; value < 256; value++)
7568 ANYOF_BITMAP_SET(ret, value);
7574 /* this is to handle \p and \P */
7577 vFAIL("Invalid [::] class");
7581 /* Strings such as "+utf8::isWord\n" */
7582 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::Is%s\n", yesno, what);
7585 ANYOF_FLAGS(ret) |= ANYOF_CLASS;
7588 } /* end of namedclass \blah */
7591 if (prevvalue > (IV)value) /* b-a */ {
7592 const int w = RExC_parse - rangebegin;
7593 Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
7594 range = 0; /* not a valid range */
7598 prevvalue = value; /* save the beginning of the range */
7599 if (*RExC_parse == '-' && RExC_parse+1 < RExC_end &&
7600 RExC_parse[1] != ']') {
7603 /* a bad range like \w-, [:word:]- ? */
7604 if (namedclass > OOB_NAMEDCLASS) {
7605 if (ckWARN(WARN_REGEXP)) {
7607 RExC_parse >= rangebegin ?
7608 RExC_parse - rangebegin : 0;
7610 "False [] range \"%*.*s\"",
7614 ANYOF_BITMAP_SET(ret, '-');
7616 range = 1; /* yeah, it's a range! */
7617 continue; /* but do it the next time */
7621 /* now is the next time */
7622 /*stored += (value - prevvalue + 1);*/
7624 if (prevvalue < 256) {
7625 const IV ceilvalue = value < 256 ? value : 255;
7628 /* In EBCDIC [\x89-\x91] should include
7629 * the \x8e but [i-j] should not. */
7630 if (literal_endpoint == 2 &&
7631 ((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
7632 (isUPPER(prevvalue) && isUPPER(ceilvalue))))
7634 if (isLOWER(prevvalue)) {
7635 for (i = prevvalue; i <= ceilvalue; i++)
7637 ANYOF_BITMAP_SET(ret, i);
7639 for (i = prevvalue; i <= ceilvalue; i++)
7641 ANYOF_BITMAP_SET(ret, i);
7646 for (i = prevvalue; i <= ceilvalue; i++) {
7647 if (!ANYOF_BITMAP_TEST(ret,i)) {
7649 ANYOF_BITMAP_SET(ret, i);
7653 if (value > 255 || UTF) {
7654 const UV prevnatvalue = NATIVE_TO_UNI(prevvalue);
7655 const UV natvalue = NATIVE_TO_UNI(value);
7656 stored+=2; /* can't optimize this class */
7657 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
7658 if (prevnatvalue < natvalue) { /* what about > ? */
7659 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
7660 prevnatvalue, natvalue);
7662 else if (prevnatvalue == natvalue) {
7663 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n", natvalue);
7665 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
7667 const UV f = to_uni_fold(natvalue, foldbuf, &foldlen);
7669 #ifdef EBCDIC /* RD t/uni/fold ff and 6b */
7670 if (RExC_precomp[0] == ':' &&
7671 RExC_precomp[1] == '[' &&
7672 (f == 0xDF || f == 0x92)) {
7673 f = NATIVE_TO_UNI(f);
7676 /* If folding and foldable and a single
7677 * character, insert also the folded version
7678 * to the charclass. */
7680 #ifdef EBCDIC /* RD tunifold ligatures s,t fb05, fb06 */
7681 if ((RExC_precomp[0] == ':' &&
7682 RExC_precomp[1] == '[' &&
7684 (value == 0xFB05 || value == 0xFB06))) ?
7685 foldlen == ((STRLEN)UNISKIP(f) - 1) :
7686 foldlen == (STRLEN)UNISKIP(f) )
7688 if (foldlen == (STRLEN)UNISKIP(f))
7690 Perl_sv_catpvf(aTHX_ listsv,
7693 /* Any multicharacter foldings
7694 * require the following transform:
7695 * [ABCDEF] -> (?:[ABCabcDEFd]|pq|rst)
7696 * where E folds into "pq" and F folds
7697 * into "rst", all other characters
7698 * fold to single characters. We save
7699 * away these multicharacter foldings,
7700 * to be later saved as part of the
7701 * additional "s" data. */
7704 if (!unicode_alternate)
7705 unicode_alternate = newAV();
7706 sv = newSVpvn((char*)foldbuf, foldlen);
7708 av_push(unicode_alternate, sv);
7712 /* If folding and the value is one of the Greek
7713 * sigmas insert a few more sigmas to make the
7714 * folding rules of the sigmas to work right.
7715 * Note that not all the possible combinations
7716 * are handled here: some of them are handled
7717 * by the standard folding rules, and some of
7718 * them (literal or EXACTF cases) are handled
7719 * during runtime in regexec.c:S_find_byclass(). */
7720 if (value == UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA) {
7721 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7722 (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA);
7723 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7724 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
7726 else if (value == UNICODE_GREEK_CAPITAL_LETTER_SIGMA)
7727 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7728 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
7733 literal_endpoint = 0;
7737 range = 0; /* this range (if it was one) is done now */
7741 ANYOF_FLAGS(ret) |= ANYOF_LARGE;
7743 RExC_size += ANYOF_CLASS_ADD_SKIP;
7745 RExC_emit += ANYOF_CLASS_ADD_SKIP;
7751 /****** !SIZE_ONLY AFTER HERE *********/
7753 if( stored == 1 && value < 256
7754 && !( ANYOF_FLAGS(ret) & ( ANYOF_FLAGS_ALL ^ ANYOF_FOLD ) )
7756 /* optimize single char class to an EXACT node
7757 but *only* when its not a UTF/high char */
7758 const char * cur_parse= RExC_parse;
7759 RExC_emit = (regnode *)orig_emit;
7760 RExC_parse = (char *)orig_parse;
7761 ret = reg_node(pRExC_state,
7762 (U8)((ANYOF_FLAGS(ret) & ANYOF_FOLD) ? EXACTF : EXACT));
7763 RExC_parse = (char *)cur_parse;
7764 *STRING(ret)= (char)value;
7766 RExC_emit += STR_SZ(1);
7769 /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
7770 if ( /* If the only flag is folding (plus possibly inversion). */
7771 ((ANYOF_FLAGS(ret) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD)
7773 for (value = 0; value < 256; ++value) {
7774 if (ANYOF_BITMAP_TEST(ret, value)) {
7775 UV fold = PL_fold[value];
7778 ANYOF_BITMAP_SET(ret, fold);
7781 ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
7784 /* optimize inverted simple patterns (e.g. [^a-z]) */
7785 if (optimize_invert &&
7786 /* If the only flag is inversion. */
7787 (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
7788 for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
7789 ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
7790 ANYOF_FLAGS(ret) = ANYOF_UNICODE_ALL;
7793 AV * const av = newAV();
7795 /* The 0th element stores the character class description
7796 * in its textual form: used later (regexec.c:Perl_regclass_swash())
7797 * to initialize the appropriate swash (which gets stored in
7798 * the 1st element), and also useful for dumping the regnode.
7799 * The 2nd element stores the multicharacter foldings,
7800 * used later (regexec.c:S_reginclass()). */
7801 av_store(av, 0, listsv);
7802 av_store(av, 1, NULL);
7803 av_store(av, 2, (SV*)unicode_alternate);
7804 rv = newRV_noinc((SV*)av);
7805 n = add_data(pRExC_state, 1, "s");
7806 RExC_rxi->data->data[n] = (void*)rv;
7814 /* reg_skipcomment()
7816 Absorbs an /x style # comments from the input stream.
7817 Returns true if there is more text remaining in the stream.
7818 Will set the REG_SEEN_RUN_ON_COMMENT flag if the comment
7819 terminates the pattern without including a newline.
7821 Note its the callers responsibility to ensure that we are
7827 S_reg_skipcomment(pTHX_ RExC_state_t *pRExC_state)
7830 while (RExC_parse < RExC_end)
7831 if (*RExC_parse++ == '\n') {
7836 /* we ran off the end of the pattern without ending
7837 the comment, so we have to add an \n when wrapping */
7838 RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
7846 Advance that parse position, and optionall absorbs
7847 "whitespace" from the inputstream.
7849 Without /x "whitespace" means (?#...) style comments only,
7850 with /x this means (?#...) and # comments and whitespace proper.
7852 Returns the RExC_parse point from BEFORE the scan occurs.
7854 This is the /x friendly way of saying RExC_parse++.
7858 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
7860 char* const retval = RExC_parse++;
7863 if (*RExC_parse == '(' && RExC_parse[1] == '?' &&
7864 RExC_parse[2] == '#') {
7865 while (*RExC_parse != ')') {
7866 if (RExC_parse == RExC_end)
7867 FAIL("Sequence (?#... not terminated");
7873 if (RExC_flags & RXf_PMf_EXTENDED) {
7874 if (isSPACE(*RExC_parse)) {
7878 else if (*RExC_parse == '#') {
7879 if ( reg_skipcomment( pRExC_state ) )
7888 - reg_node - emit a node
7890 STATIC regnode * /* Location. */
7891 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
7894 register regnode *ptr;
7895 regnode * const ret = RExC_emit;
7896 GET_RE_DEBUG_FLAGS_DECL;
7899 SIZE_ALIGN(RExC_size);
7904 if (OP(RExC_emit) == 255)
7905 Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %s: %d ",
7906 reg_name[op], OP(RExC_emit));
7908 NODE_ALIGN_FILL(ret);
7910 FILL_ADVANCE_NODE(ptr, op);
7911 #ifdef RE_TRACK_PATTERN_OFFSETS
7912 if (RExC_offsets) { /* MJD */
7913 MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n",
7914 "reg_node", __LINE__,
7916 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0]
7917 ? "Overwriting end of array!\n" : "OK",
7918 (UV)(RExC_emit - RExC_emit_start),
7919 (UV)(RExC_parse - RExC_start),
7920 (UV)RExC_offsets[0]));
7921 Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
7929 - reganode - emit a node with an argument
7931 STATIC regnode * /* Location. */
7932 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
7935 register regnode *ptr;
7936 regnode * const ret = RExC_emit;
7937 GET_RE_DEBUG_FLAGS_DECL;
7940 SIZE_ALIGN(RExC_size);
7945 assert(2==regarglen[op]+1);
7947 Anything larger than this has to allocate the extra amount.
7948 If we changed this to be:
7950 RExC_size += (1 + regarglen[op]);
7952 then it wouldn't matter. Its not clear what side effect
7953 might come from that so its not done so far.
7959 if (OP(RExC_emit) == 255)
7960 Perl_croak(aTHX_ "panic: reganode overwriting end of allocated program space");
7962 NODE_ALIGN_FILL(ret);
7964 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
7965 #ifdef RE_TRACK_PATTERN_OFFSETS
7966 if (RExC_offsets) { /* MJD */
7967 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
7971 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ?
7972 "Overwriting end of array!\n" : "OK",
7973 (UV)(RExC_emit - RExC_emit_start),
7974 (UV)(RExC_parse - RExC_start),
7975 (UV)RExC_offsets[0]));
7976 Set_Cur_Node_Offset;
7984 - reguni - emit (if appropriate) a Unicode character
7987 S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
7990 return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
7994 - reginsert - insert an operator in front of already-emitted operand
7996 * Means relocating the operand.
7999 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
8002 register regnode *src;
8003 register regnode *dst;
8004 register regnode *place;
8005 const int offset = regarglen[(U8)op];
8006 const int size = NODE_STEP_REGNODE + offset;
8007 GET_RE_DEBUG_FLAGS_DECL;
8008 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
8009 DEBUG_PARSE_FMT("inst"," - %s",reg_name[op]);
8018 if (RExC_open_parens) {
8020 DEBUG_PARSE_FMT("inst"," - %"IVdf, (IV)RExC_npar);
8021 for ( paren=0 ; paren < RExC_npar ; paren++ ) {
8022 if ( RExC_open_parens[paren] >= opnd ) {
8023 DEBUG_PARSE_FMT("open"," - %d",size);
8024 RExC_open_parens[paren] += size;
8026 DEBUG_PARSE_FMT("open"," - %s","ok");
8028 if ( RExC_close_parens[paren] >= opnd ) {
8029 DEBUG_PARSE_FMT("close"," - %d",size);
8030 RExC_close_parens[paren] += size;
8032 DEBUG_PARSE_FMT("close"," - %s","ok");
8037 while (src > opnd) {
8038 StructCopy(--src, --dst, regnode);
8039 #ifdef RE_TRACK_PATTERN_OFFSETS
8040 if (RExC_offsets) { /* MJD 20010112 */
8041 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
8045 (UV)(dst - RExC_emit_start) > RExC_offsets[0]
8046 ? "Overwriting end of array!\n" : "OK",
8047 (UV)(src - RExC_emit_start),
8048 (UV)(dst - RExC_emit_start),
8049 (UV)RExC_offsets[0]));
8050 Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
8051 Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
8057 place = opnd; /* Op node, where operand used to be. */
8058 #ifdef RE_TRACK_PATTERN_OFFSETS
8059 if (RExC_offsets) { /* MJD */
8060 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
8064 (UV)(place - RExC_emit_start) > RExC_offsets[0]
8065 ? "Overwriting end of array!\n" : "OK",
8066 (UV)(place - RExC_emit_start),
8067 (UV)(RExC_parse - RExC_start),
8068 (UV)RExC_offsets[0]));
8069 Set_Node_Offset(place, RExC_parse);
8070 Set_Node_Length(place, 1);
8073 src = NEXTOPER(place);
8074 FILL_ADVANCE_NODE(place, op);
8075 Zero(src, offset, regnode);
8079 - regtail - set the next-pointer at the end of a node chain of p to val.
8080 - SEE ALSO: regtail_study
8082 /* TODO: All three parms should be const */
8084 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
8087 register regnode *scan;
8088 GET_RE_DEBUG_FLAGS_DECL;
8090 PERL_UNUSED_ARG(depth);
8096 /* Find last node. */
8099 regnode * const temp = regnext(scan);
8101 SV * const mysv=sv_newmortal();
8102 DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
8103 regprop(RExC_rx, mysv, scan);
8104 PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
8105 SvPV_nolen_const(mysv), REG_NODE_NUM(scan),
8106 (temp == NULL ? "->" : ""),
8107 (temp == NULL ? reg_name[OP(val)] : "")
8115 if (reg_off_by_arg[OP(scan)]) {
8116 ARG_SET(scan, val - scan);
8119 NEXT_OFF(scan) = val - scan;
8125 - regtail_study - set the next-pointer at the end of a node chain of p to val.
8126 - Look for optimizable sequences at the same time.
8127 - currently only looks for EXACT chains.
8129 This is expermental code. The idea is to use this routine to perform
8130 in place optimizations on branches and groups as they are constructed,
8131 with the long term intention of removing optimization from study_chunk so
8132 that it is purely analytical.
8134 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
8135 to control which is which.
8138 /* TODO: All four parms should be const */
8141 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
8144 register regnode *scan;
8146 #ifdef EXPERIMENTAL_INPLACESCAN
8150 GET_RE_DEBUG_FLAGS_DECL;
8156 /* Find last node. */
8160 regnode * const temp = regnext(scan);
8161 #ifdef EXPERIMENTAL_INPLACESCAN
8162 if (PL_regkind[OP(scan)] == EXACT)
8163 if (join_exact(pRExC_state,scan,&min,1,val,depth+1))
8171 if( exact == PSEUDO )
8173 else if ( exact != OP(scan) )
8182 SV * const mysv=sv_newmortal();
8183 DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
8184 regprop(RExC_rx, mysv, scan);
8185 PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
8186 SvPV_nolen_const(mysv),
8195 SV * const mysv_val=sv_newmortal();
8196 DEBUG_PARSE_MSG("");
8197 regprop(RExC_rx, mysv_val, val);
8198 PerlIO_printf(Perl_debug_log, "~ attach to %s (%"IVdf") offset to %"IVdf"\n",
8199 SvPV_nolen_const(mysv_val),
8200 (IV)REG_NODE_NUM(val),
8204 if (reg_off_by_arg[OP(scan)]) {
8205 ARG_SET(scan, val - scan);
8208 NEXT_OFF(scan) = val - scan;
8216 - regcurly - a little FSA that accepts {\d+,?\d*}
8219 S_regcurly(register const char *s)
8238 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
8241 Perl_regdump(pTHX_ const regexp *r)
8245 SV * const sv = sv_newmortal();
8246 SV *dsv= sv_newmortal();
8249 (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
8251 /* Header fields of interest. */
8252 if (r->anchored_substr) {
8253 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr),
8254 RE_SV_DUMPLEN(r->anchored_substr), 30);
8255 PerlIO_printf(Perl_debug_log,
8256 "anchored %s%s at %"IVdf" ",
8257 s, RE_SV_TAIL(r->anchored_substr),
8258 (IV)r->anchored_offset);
8259 } else if (r->anchored_utf8) {
8260 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8),
8261 RE_SV_DUMPLEN(r->anchored_utf8), 30);
8262 PerlIO_printf(Perl_debug_log,
8263 "anchored utf8 %s%s at %"IVdf" ",
8264 s, RE_SV_TAIL(r->anchored_utf8),
8265 (IV)r->anchored_offset);
8267 if (r->float_substr) {
8268 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr),
8269 RE_SV_DUMPLEN(r->float_substr), 30);
8270 PerlIO_printf(Perl_debug_log,
8271 "floating %s%s at %"IVdf"..%"UVuf" ",
8272 s, RE_SV_TAIL(r->float_substr),
8273 (IV)r->float_min_offset, (UV)r->float_max_offset);
8274 } else if (r->float_utf8) {
8275 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8),
8276 RE_SV_DUMPLEN(r->float_utf8), 30);
8277 PerlIO_printf(Perl_debug_log,
8278 "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
8279 s, RE_SV_TAIL(r->float_utf8),
8280 (IV)r->float_min_offset, (UV)r->float_max_offset);
8282 if (r->check_substr || r->check_utf8)
8283 PerlIO_printf(Perl_debug_log,
8285 (r->check_substr == r->float_substr
8286 && r->check_utf8 == r->float_utf8
8287 ? "(checking floating" : "(checking anchored"));
8288 if (r->extflags & RXf_NOSCAN)
8289 PerlIO_printf(Perl_debug_log, " noscan");
8290 if (r->extflags & RXf_CHECK_ALL)
8291 PerlIO_printf(Perl_debug_log, " isall");
8292 if (r->check_substr || r->check_utf8)
8293 PerlIO_printf(Perl_debug_log, ") ");
8295 if (ri->regstclass) {
8296 regprop(r, sv, ri->regstclass);
8297 PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
8299 if (r->extflags & RXf_ANCH) {
8300 PerlIO_printf(Perl_debug_log, "anchored");
8301 if (r->extflags & RXf_ANCH_BOL)
8302 PerlIO_printf(Perl_debug_log, "(BOL)");
8303 if (r->extflags & RXf_ANCH_MBOL)
8304 PerlIO_printf(Perl_debug_log, "(MBOL)");
8305 if (r->extflags & RXf_ANCH_SBOL)
8306 PerlIO_printf(Perl_debug_log, "(SBOL)");
8307 if (r->extflags & RXf_ANCH_GPOS)
8308 PerlIO_printf(Perl_debug_log, "(GPOS)");
8309 PerlIO_putc(Perl_debug_log, ' ');
8311 if (r->extflags & RXf_GPOS_SEEN)
8312 PerlIO_printf(Perl_debug_log, "GPOS:%"UVuf" ", (UV)r->gofs);
8313 if (r->intflags & PREGf_SKIP)
8314 PerlIO_printf(Perl_debug_log, "plus ");
8315 if (r->intflags & PREGf_IMPLICIT)
8316 PerlIO_printf(Perl_debug_log, "implicit ");
8317 PerlIO_printf(Perl_debug_log, "minlen %"IVdf" ", (IV)r->minlen);
8318 if (r->extflags & RXf_EVAL_SEEN)
8319 PerlIO_printf(Perl_debug_log, "with eval ");
8320 PerlIO_printf(Perl_debug_log, "\n");
8322 PERL_UNUSED_CONTEXT;
8324 #endif /* DEBUGGING */
8328 - regprop - printable representation of opcode
8331 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
8336 RXi_GET_DECL(prog,progi);
8337 GET_RE_DEBUG_FLAGS_DECL;
8340 sv_setpvn(sv, "", 0);
8342 if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */
8343 /* It would be nice to FAIL() here, but this may be called from
8344 regexec.c, and it would be hard to supply pRExC_state. */
8345 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
8346 sv_catpv(sv, reg_name[OP(o)]); /* Take off const! */
8348 k = PL_regkind[OP(o)];
8351 SV * const dsv = sv_2mortal(newSVpvs(""));
8352 /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
8353 * is a crude hack but it may be the best for now since
8354 * we have no flag "this EXACTish node was UTF-8"
8356 const char * const s =
8357 pv_pretty(dsv, STRING(o), STR_LEN(o), 60,
8358 PL_colors[0], PL_colors[1],
8359 PERL_PV_ESCAPE_UNI_DETECT |
8360 PERL_PV_PRETTY_ELIPSES |
8363 Perl_sv_catpvf(aTHX_ sv, " %s", s );
8364 } else if (k == TRIE) {
8365 /* print the details of the trie in dumpuntil instead, as
8366 * progi->data isn't available here */
8367 const char op = OP(o);
8368 const U32 n = ARG(o);
8369 const reg_ac_data * const ac = IS_TRIE_AC(op) ?
8370 (reg_ac_data *)progi->data->data[n] :
8372 const reg_trie_data * const trie
8373 = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
8375 Perl_sv_catpvf(aTHX_ sv, "-%s",reg_name[o->flags]);
8376 DEBUG_TRIE_COMPILE_r(
8377 Perl_sv_catpvf(aTHX_ sv,
8378 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
8379 (UV)trie->startstate,
8380 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
8381 (UV)trie->wordcount,
8384 (UV)TRIE_CHARCOUNT(trie),
8385 (UV)trie->uniquecharcount
8388 if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
8390 int rangestart = -1;
8391 U8* bitmap = IS_ANYOF_TRIE(op) ? (U8*)ANYOF_BITMAP(o) : (U8*)TRIE_BITMAP(trie);
8392 Perl_sv_catpvf(aTHX_ sv, "[");
8393 for (i = 0; i <= 256; i++) {
8394 if (i < 256 && BITMAP_TEST(bitmap,i)) {
8395 if (rangestart == -1)
8397 } else if (rangestart != -1) {
8398 if (i <= rangestart + 3)
8399 for (; rangestart < i; rangestart++)
8400 put_byte(sv, rangestart);
8402 put_byte(sv, rangestart);
8404 put_byte(sv, i - 1);
8409 Perl_sv_catpvf(aTHX_ sv, "]");
8412 } else if (k == CURLY) {
8413 if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
8414 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
8415 Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
8417 else if (k == WHILEM && o->flags) /* Ordinal/of */
8418 Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
8419 else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP || OP(o)==ACCEPT) {
8420 Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o)); /* Parenth number */
8421 if ( prog->paren_names ) {
8422 if ( k != REF || OP(o) < NREF) {
8423 AV *list= (AV *)progi->data->data[progi->name_list_idx];
8424 SV **name= av_fetch(list, ARG(o), 0 );
8426 Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
8429 AV *list= (AV *)progi->data->data[ progi->name_list_idx ];
8430 SV *sv_dat=(SV*)progi->data->data[ ARG( o ) ];
8431 I32 *nums=(I32*)SvPVX(sv_dat);
8432 SV **name= av_fetch(list, nums[0], 0 );
8435 for ( n=0; n<SvIVX(sv_dat); n++ ) {
8436 Perl_sv_catpvf(aTHX_ sv, "%s%"IVdf,
8437 (n ? "," : ""), (IV)nums[n]);
8439 Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
8443 } else if (k == GOSUB)
8444 Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
8445 else if (k == VERB) {
8447 Perl_sv_catpvf(aTHX_ sv, ":%"SVf,
8448 SVfARG((SV*)progi->data->data[ ARG( o ) ]));
8449 } else if (k == LOGICAL)
8450 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* 2: embedded, otherwise 1 */
8451 else if (k == ANYOF) {
8452 int i, rangestart = -1;
8453 const U8 flags = ANYOF_FLAGS(o);
8455 /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
8456 static const char * const anyofs[] = {
8489 if (flags & ANYOF_LOCALE)
8490 sv_catpvs(sv, "{loc}");
8491 if (flags & ANYOF_FOLD)
8492 sv_catpvs(sv, "{i}");
8493 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
8494 if (flags & ANYOF_INVERT)
8496 for (i = 0; i <= 256; i++) {
8497 if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
8498 if (rangestart == -1)
8500 } else if (rangestart != -1) {
8501 if (i <= rangestart + 3)
8502 for (; rangestart < i; rangestart++)
8503 put_byte(sv, rangestart);
8505 put_byte(sv, rangestart);
8507 put_byte(sv, i - 1);
8513 if (o->flags & ANYOF_CLASS)
8514 for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++)
8515 if (ANYOF_CLASS_TEST(o,i))
8516 sv_catpv(sv, anyofs[i]);
8518 if (flags & ANYOF_UNICODE)
8519 sv_catpvs(sv, "{unicode}");
8520 else if (flags & ANYOF_UNICODE_ALL)
8521 sv_catpvs(sv, "{unicode_all}");
8525 SV * const sw = regclass_swash(prog, o, FALSE, &lv, 0);
8529 U8 s[UTF8_MAXBYTES_CASE+1];
8531 for (i = 0; i <= 256; i++) { /* just the first 256 */
8532 uvchr_to_utf8(s, i);
8534 if (i < 256 && swash_fetch(sw, s, TRUE)) {
8535 if (rangestart == -1)
8537 } else if (rangestart != -1) {
8538 if (i <= rangestart + 3)
8539 for (; rangestart < i; rangestart++) {
8540 const U8 * const e = uvchr_to_utf8(s,rangestart);
8542 for(p = s; p < e; p++)
8546 const U8 *e = uvchr_to_utf8(s,rangestart);
8548 for (p = s; p < e; p++)
8551 e = uvchr_to_utf8(s, i-1);
8552 for (p = s; p < e; p++)
8559 sv_catpvs(sv, "..."); /* et cetera */
8563 char *s = savesvpv(lv);
8564 char * const origs = s;
8566 while (*s && *s != '\n')
8570 const char * const t = ++s;
8588 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
8590 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
8591 Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
8593 PERL_UNUSED_CONTEXT;
8594 PERL_UNUSED_ARG(sv);
8596 PERL_UNUSED_ARG(prog);
8597 #endif /* DEBUGGING */
8601 Perl_re_intuit_string(pTHX_ regexp *prog)
8602 { /* Assume that RE_INTUIT is set */
8604 GET_RE_DEBUG_FLAGS_DECL;
8605 PERL_UNUSED_CONTEXT;
8609 const char * const s = SvPV_nolen_const(prog->check_substr
8610 ? prog->check_substr : prog->check_utf8);
8612 if (!PL_colorset) reginitcolors();
8613 PerlIO_printf(Perl_debug_log,
8614 "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
8616 prog->check_substr ? "" : "utf8 ",
8617 PL_colors[5],PL_colors[0],
8620 (strlen(s) > 60 ? "..." : ""));
8623 return prog->check_substr ? prog->check_substr : prog->check_utf8;
8629 handles refcounting and freeing the perl core regexp structure. When
8630 it is necessary to actually free the structure the first thing it
8631 does is call the 'free' method of the regexp_engine associated to to
8632 the regexp, allowing the handling of the void *pprivate; member
8633 first. (This routine is not overridable by extensions, which is why
8634 the extensions free is called first.)
8636 See regdupe and regdupe_internal if you change anything here.
8638 #ifndef PERL_IN_XSUB_RE
8640 Perl_pregfree(pTHX_ struct regexp *r)
8643 GET_RE_DEBUG_FLAGS_DECL;
8645 if (!r || (--r->refcnt > 0))
8648 CALLREGFREE_PVT(r); /* free the private data */
8649 RX_MATCH_COPY_FREE(r);
8650 #ifdef PERL_OLD_COPY_ON_WRITE
8652 SvREFCNT_dec(r->saved_copy);
8655 if (r->anchored_substr)
8656 SvREFCNT_dec(r->anchored_substr);
8657 if (r->anchored_utf8)
8658 SvREFCNT_dec(r->anchored_utf8);
8659 if (r->float_substr)
8660 SvREFCNT_dec(r->float_substr);
8662 SvREFCNT_dec(r->float_utf8);
8663 Safefree(r->substrs);
8666 SvREFCNT_dec(r->paren_names);
8667 Safefree(r->wrapped);
8668 Safefree(r->startp);
8674 /* regfree_internal()
8676 Free the private data in a regexp. This is overloadable by
8677 extensions. Perl takes care of the regexp structure in pregfree(),
8678 this covers the *pprivate pointer which technically perldoesnt
8679 know about, however of course we have to handle the
8680 regexp_internal structure when no extension is in use.
8682 Note this is called before freeing anything in the regexp
8687 Perl_regfree_internal(pTHX_ struct regexp *r)
8691 GET_RE_DEBUG_FLAGS_DECL;
8697 SV *dsv= sv_newmortal();
8698 RE_PV_QUOTED_DECL(s, (r->extflags & RXf_UTF8),
8699 dsv, r->precomp, r->prelen, 60);
8700 PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n",
8701 PL_colors[4],PL_colors[5],s);
8704 #ifdef RE_TRACK_PATTERN_OFFSETS
8706 Safefree(ri->u.offsets); /* 20010421 MJD */
8709 int n = ri->data->count;
8710 PAD* new_comppad = NULL;
8715 /* If you add a ->what type here, update the comment in regcomp.h */
8716 switch (ri->data->what[n]) {
8720 SvREFCNT_dec((SV*)ri->data->data[n]);
8723 Safefree(ri->data->data[n]);
8726 new_comppad = (AV*)ri->data->data[n];
8729 if (new_comppad == NULL)
8730 Perl_croak(aTHX_ "panic: pregfree comppad");
8731 PAD_SAVE_LOCAL(old_comppad,
8732 /* Watch out for global destruction's random ordering. */
8733 (SvTYPE(new_comppad) == SVt_PVAV) ? new_comppad : NULL
8736 refcnt = OpREFCNT_dec((OP_4tree*)ri->data->data[n]);
8739 op_free((OP_4tree*)ri->data->data[n]);
8741 PAD_RESTORE_LOCAL(old_comppad);
8742 SvREFCNT_dec((SV*)new_comppad);
8748 { /* Aho Corasick add-on structure for a trie node.
8749 Used in stclass optimization only */
8751 reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
8753 refcount = --aho->refcount;
8756 PerlMemShared_free(aho->states);
8757 PerlMemShared_free(aho->fail);
8758 /* do this last!!!! */
8759 PerlMemShared_free(ri->data->data[n]);
8760 PerlMemShared_free(ri->regstclass);
8766 /* trie structure. */
8768 reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
8770 refcount = --trie->refcount;
8773 PerlMemShared_free(trie->charmap);
8774 PerlMemShared_free(trie->states);
8775 PerlMemShared_free(trie->trans);
8777 PerlMemShared_free(trie->bitmap);
8779 PerlMemShared_free(trie->wordlen);
8781 PerlMemShared_free(trie->jump);
8783 PerlMemShared_free(trie->nextword);
8784 /* do this last!!!! */
8785 PerlMemShared_free(ri->data->data[n]);
8790 Perl_croak(aTHX_ "panic: regfree data code '%c'", ri->data->what[n]);
8793 Safefree(ri->data->what);
8797 Safefree(ri->swap->startp);
8798 Safefree(ri->swap->endp);
8804 #define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
8805 #define av_dup_inc(s,t) (AV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8806 #define hv_dup_inc(s,t) (HV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8807 #define SAVEPVN(p,n) ((p) ? savepvn(p,n) : NULL)
8810 regdupe - duplicate a regexp.
8812 This routine is called by sv.c's re_dup and is expected to clone a
8813 given regexp structure. It is a no-op when not under USE_ITHREADS.
8814 (Originally this *was* re_dup() for change history see sv.c)
8816 After all of the core data stored in struct regexp is duplicated
8817 the regexp_engine.dupe method is used to copy any private data
8818 stored in the *pprivate pointer. This allows extensions to handle
8819 any duplication it needs to do.
8821 See pregfree() and regfree_internal() if you change anything here.
8823 #if defined(USE_ITHREADS)
8824 #ifndef PERL_IN_XSUB_RE
8826 Perl_re_dup(pTHX_ const regexp *r, CLONE_PARAMS *param)
8831 struct reg_substr_datum *s;
8834 return (REGEXP *)NULL;
8836 if ((ret = (REGEXP *)ptr_table_fetch(PL_ptr_table, r)))
8840 npar = r->nparens+1;
8841 Newxz(ret, 1, regexp);
8842 Newx(ret->startp, npar, I32);
8843 Copy(r->startp, ret->startp, npar, I32);
8844 Newx(ret->endp, npar, I32);
8845 Copy(r->endp, ret->endp, npar, I32);
8848 Newx(ret->substrs, 1, struct reg_substr_data);
8849 for (s = ret->substrs->data, i = 0; i < 3; i++, s++) {
8850 s->min_offset = r->substrs->data[i].min_offset;
8851 s->max_offset = r->substrs->data[i].max_offset;
8852 s->end_shift = r->substrs->data[i].end_shift;
8853 s->substr = sv_dup_inc(r->substrs->data[i].substr, param);
8854 s->utf8_substr = sv_dup_inc(r->substrs->data[i].utf8_substr, param);
8857 ret->substrs = NULL;
8859 ret->wrapped = SAVEPVN(r->wrapped, r->wraplen);
8860 ret->precomp = ret->wrapped + (r->precomp - r->wrapped);
8861 ret->prelen = r->prelen;
8862 ret->wraplen = r->wraplen;
8864 ret->refcnt = r->refcnt;
8865 ret->minlen = r->minlen;
8866 ret->minlenret = r->minlenret;
8867 ret->nparens = r->nparens;
8868 ret->lastparen = r->lastparen;
8869 ret->lastcloseparen = r->lastcloseparen;
8870 ret->intflags = r->intflags;
8871 ret->extflags = r->extflags;
8873 ret->sublen = r->sublen;
8875 ret->engine = r->engine;
8877 ret->paren_names = hv_dup_inc(r->paren_names, param);
8879 if (RX_MATCH_COPIED(ret))
8880 ret->subbeg = SAVEPVN(r->subbeg, r->sublen);
8883 #ifdef PERL_OLD_COPY_ON_WRITE
8884 ret->saved_copy = NULL;
8887 ret->pprivate = r->pprivate;
8889 RXi_SET(ret,CALLREGDUPE_PVT(ret,param));
8891 ptr_table_store(PL_ptr_table, r, ret);
8894 #endif /* PERL_IN_XSUB_RE */
8899 This is the internal complement to regdupe() which is used to copy
8900 the structure pointed to by the *pprivate pointer in the regexp.
8901 This is the core version of the extension overridable cloning hook.
8902 The regexp structure being duplicated will be copied by perl prior
8903 to this and will be provided as the regexp *r argument, however
8904 with the /old/ structures pprivate pointer value. Thus this routine
8905 may override any copying normally done by perl.
8907 It returns a pointer to the new regexp_internal structure.
8911 Perl_regdupe_internal(pTHX_ const regexp *r, CLONE_PARAMS *param)
8914 regexp_internal *reti;
8918 npar = r->nparens+1;
8921 Newxc(reti, sizeof(regexp_internal) + (len+1)*sizeof(regnode), char, regexp_internal);
8922 Copy(ri->program, reti->program, len+1, regnode);
8925 Newx(reti->swap, 1, regexp_paren_ofs);
8926 /* no need to copy these */
8927 Newx(reti->swap->startp, npar, I32);
8928 Newx(reti->swap->endp, npar, I32);
8933 reti->regstclass = NULL;
8937 const int count = ri->data->count;
8940 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
8941 char, struct reg_data);
8942 Newx(d->what, count, U8);
8945 for (i = 0; i < count; i++) {
8946 d->what[i] = ri->data->what[i];
8947 switch (d->what[i]) {
8948 /* legal options are one of: sSfpontTu
8949 see also regcomp.h and pregfree() */
8952 case 'p': /* actually an AV, but the dup function is identical. */
8953 case 'u': /* actually an HV, but the dup function is identical. */
8954 d->data[i] = sv_dup_inc((SV *)ri->data->data[i], param);
8957 /* This is cheating. */
8958 Newx(d->data[i], 1, struct regnode_charclass_class);
8959 StructCopy(ri->data->data[i], d->data[i],
8960 struct regnode_charclass_class);
8961 reti->regstclass = (regnode*)d->data[i];
8964 /* Compiled op trees are readonly and in shared memory,
8965 and can thus be shared without duplication. */
8967 d->data[i] = (void*)OpREFCNT_inc((OP*)ri->data->data[i]);
8971 /* Trie stclasses are readonly and can thus be shared
8972 * without duplication. We free the stclass in pregfree
8973 * when the corresponding reg_ac_data struct is freed.
8975 reti->regstclass= ri->regstclass;
8979 ((reg_trie_data*)ri->data->data[i])->refcount++;
8983 d->data[i] = ri->data->data[i];
8986 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", ri->data->what[i]);
8995 reti->name_list_idx = ri->name_list_idx;
8997 #ifdef RE_TRACK_PATTERN_OFFSETS
8998 if (ri->u.offsets) {
8999 Newx(reti->u.offsets, 2*len+1, U32);
9000 Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
9003 SetProgLen(reti,len);
9009 #endif /* USE_ITHREADS */
9014 converts a regexp embedded in a MAGIC struct to its stringified form,
9015 caching the converted form in the struct and returns the cached
9018 If lp is nonnull then it is used to return the length of the
9021 If flags is nonnull and the returned string contains UTF8 then
9022 (*flags & 1) will be true.
9024 If haseval is nonnull then it is used to return whether the pattern
9027 Normally called via macro:
9029 CALLREG_STRINGIFY(mg,&len,&utf8);
9033 CALLREG_AS_STR(mg,&lp,&flags,&haseval)
9035 See sv_2pv_flags() in sv.c for an example of internal usage.
9038 #ifndef PERL_IN_XSUB_RE
9041 Perl_reg_stringify(pTHX_ MAGIC *mg, STRLEN *lp, U32 *flags, I32 *haseval ) {
9043 const regexp * const re = (regexp *)mg->mg_obj;
9045 *haseval = re->seen_evals;
9047 *flags = ((re->extflags & RXf_UTF8) ? 1 : 0);
9054 - regnext - dig the "next" pointer out of a node
9057 Perl_regnext(pTHX_ register regnode *p)
9060 register I32 offset;
9065 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
9074 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
9077 STRLEN l1 = strlen(pat1);
9078 STRLEN l2 = strlen(pat2);
9081 const char *message;
9087 Copy(pat1, buf, l1 , char);
9088 Copy(pat2, buf + l1, l2 , char);
9089 buf[l1 + l2] = '\n';
9090 buf[l1 + l2 + 1] = '\0';
9092 /* ANSI variant takes additional second argument */
9093 va_start(args, pat2);
9097 msv = vmess(buf, &args);
9099 message = SvPV_const(msv,l1);
9102 Copy(message, buf, l1 , char);
9103 buf[l1-1] = '\0'; /* Overwrite \n */
9104 Perl_croak(aTHX_ "%s", buf);
9107 /* XXX Here's a total kludge. But we need to re-enter for swash routines. */
9109 #ifndef PERL_IN_XSUB_RE
9111 Perl_save_re_context(pTHX)
9115 struct re_save_state *state;
9117 SAVEVPTR(PL_curcop);
9118 SSGROW(SAVESTACK_ALLOC_FOR_RE_SAVE_STATE + 1);
9120 state = (struct re_save_state *)(PL_savestack + PL_savestack_ix);
9121 PL_savestack_ix += SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
9122 SSPUSHINT(SAVEt_RE_STATE);
9124 Copy(&PL_reg_state, state, 1, struct re_save_state);
9126 PL_reg_start_tmp = 0;
9127 PL_reg_start_tmpl = 0;
9128 PL_reg_oldsaved = NULL;
9129 PL_reg_oldsavedlen = 0;
9131 PL_reg_leftiter = 0;
9132 PL_reg_poscache = NULL;
9133 PL_reg_poscache_size = 0;
9134 #ifdef PERL_OLD_COPY_ON_WRITE
9138 /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
9140 const REGEXP * const rx = PM_GETRE(PL_curpm);
9143 for (i = 1; i <= rx->nparens; i++) {
9144 char digits[TYPE_CHARS(long)];
9145 const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
9146 GV *const *const gvp
9147 = (GV**)hv_fetch(PL_defstash, digits, len, 0);
9150 GV * const gv = *gvp;
9151 if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
9161 clear_re(pTHX_ void *r)
9164 ReREFCNT_dec((regexp *)r);
9170 S_put_byte(pTHX_ SV *sv, int c)
9172 if (isCNTRL(c) || c == 255 || !isPRINT(c))
9173 Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
9174 else if (c == '-' || c == ']' || c == '\\' || c == '^')
9175 Perl_sv_catpvf(aTHX_ sv, "\\%c", c);
9177 Perl_sv_catpvf(aTHX_ sv, "%c", c);
9181 #define CLEAR_OPTSTART \
9182 if (optstart) STMT_START { \
9183 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%"IVdf" nodes)\n", (IV)(node - optstart))); \
9187 #define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
9189 STATIC const regnode *
9190 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
9191 const regnode *last, const regnode *plast,
9192 SV* sv, I32 indent, U32 depth)
9195 register U8 op = PSEUDO; /* Arbitrary non-END op. */
9196 register const regnode *next;
9197 const regnode *optstart= NULL;
9200 GET_RE_DEBUG_FLAGS_DECL;
9202 #ifdef DEBUG_DUMPUNTIL
9203 PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
9204 last ? last-start : 0,plast ? plast-start : 0);
9207 if (plast && plast < last)
9210 while (PL_regkind[op] != END && (!last || node < last)) {
9211 /* While that wasn't END last time... */
9214 if (op == CLOSE || op == WHILEM)
9216 next = regnext((regnode *)node);
9219 if (OP(node) == OPTIMIZED) {
9220 if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
9227 regprop(r, sv, node);
9228 PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
9229 (int)(2*indent + 1), "", SvPVX_const(sv));
9231 if (OP(node) != OPTIMIZED) {
9232 if (next == NULL) /* Next ptr. */
9233 PerlIO_printf(Perl_debug_log, " (0)");
9234 else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
9235 PerlIO_printf(Perl_debug_log, " (FAIL)");
9237 PerlIO_printf(Perl_debug_log, " (%"IVdf")", (IV)(next - start));
9238 (void)PerlIO_putc(Perl_debug_log, '\n');
9242 if (PL_regkind[(U8)op] == BRANCHJ) {
9245 register const regnode *nnode = (OP(next) == LONGJMP
9246 ? regnext((regnode *)next)
9248 if (last && nnode > last)
9250 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
9253 else if (PL_regkind[(U8)op] == BRANCH) {
9255 DUMPUNTIL(NEXTOPER(node), next);
9257 else if ( PL_regkind[(U8)op] == TRIE ) {
9258 const regnode *this_trie = node;
9259 const char op = OP(node);
9260 const U32 n = ARG(node);
9261 const reg_ac_data * const ac = op>=AHOCORASICK ?
9262 (reg_ac_data *)ri->data->data[n] :
9264 const reg_trie_data * const trie =
9265 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
9267 AV *const trie_words = (AV *) ri->data->data[n + TRIE_WORDS_OFFSET];
9269 const regnode *nextbranch= NULL;
9271 sv_setpvn(sv, "", 0);
9272 for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
9273 SV ** const elem_ptr = av_fetch(trie_words,word_idx,0);
9275 PerlIO_printf(Perl_debug_log, "%*s%s ",
9276 (int)(2*(indent+3)), "",
9277 elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
9278 PL_colors[0], PL_colors[1],
9279 (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
9280 PERL_PV_PRETTY_ELIPSES |
9286 U16 dist= trie->jump[word_idx+1];
9287 PerlIO_printf(Perl_debug_log, "(%"UVuf")\n",
9288 (UV)((dist ? this_trie + dist : next) - start));
9291 nextbranch= this_trie + trie->jump[0];
9292 DUMPUNTIL(this_trie + dist, nextbranch);
9294 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
9295 nextbranch= regnext((regnode *)nextbranch);
9297 PerlIO_printf(Perl_debug_log, "\n");
9300 if (last && next > last)
9305 else if ( op == CURLY ) { /* "next" might be very big: optimizer */
9306 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
9307 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
9309 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
9311 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
9313 else if ( op == PLUS || op == STAR) {
9314 DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
9316 else if (op == ANYOF) {
9317 /* arglen 1 + class block */
9318 node += 1 + ((ANYOF_FLAGS(node) & ANYOF_LARGE)
9319 ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
9320 node = NEXTOPER(node);
9322 else if (PL_regkind[(U8)op] == EXACT) {
9323 /* Literal string, where present. */
9324 node += NODE_SZ_STR(node) - 1;
9325 node = NEXTOPER(node);
9328 node = NEXTOPER(node);
9329 node += regarglen[(U8)op];
9331 if (op == CURLYX || op == OPEN)
9335 #ifdef DEBUG_DUMPUNTIL
9336 PerlIO_printf(Perl_debug_log, "--- %d\n", (int)indent);
9341 #endif /* DEBUGGING */
9345 * c-indentation-style: bsd
9347 * indent-tabs-mode: t
9350 * ex: set ts=8 sts=4 sw=4 noet: