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, 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. */
106 char *start; /* Start of input for compile */
107 char *end; /* End of input for compile */
108 char *parse; /* Input-scan pointer. */
109 I32 whilem_seen; /* number of WHILEM in this expr */
110 regnode *emit_start; /* Start of emitted-code area */
111 regnode *emit; /* Code-emit pointer; ®dummy = don't = compiling */
112 I32 naughty; /* How bad is this pattern? */
113 I32 sawback; /* Did we see \1, ...? */
115 I32 size; /* Code size. */
116 I32 npar; /* () count. */
120 regnode **parens; /* offsets of each paren */
122 HV *charnames; /* cache of named sequences */
123 HV *paren_names; /* Paren names */
125 char *starttry; /* -Dr: where regtry was called. */
126 #define RExC_starttry (pRExC_state->starttry)
129 const char *lastparse;
131 #define RExC_lastparse (pRExC_state->lastparse)
132 #define RExC_lastnum (pRExC_state->lastnum)
136 #define RExC_flags (pRExC_state->flags)
137 #define RExC_precomp (pRExC_state->precomp)
138 #define RExC_rx (pRExC_state->rx)
139 #define RExC_start (pRExC_state->start)
140 #define RExC_end (pRExC_state->end)
141 #define RExC_parse (pRExC_state->parse)
142 #define RExC_whilem_seen (pRExC_state->whilem_seen)
143 #define RExC_offsets (pRExC_state->rx->offsets) /* I am not like the others */
144 #define RExC_emit (pRExC_state->emit)
145 #define RExC_emit_start (pRExC_state->emit_start)
146 #define RExC_naughty (pRExC_state->naughty)
147 #define RExC_sawback (pRExC_state->sawback)
148 #define RExC_seen (pRExC_state->seen)
149 #define RExC_size (pRExC_state->size)
150 #define RExC_npar (pRExC_state->npar)
151 #define RExC_extralen (pRExC_state->extralen)
152 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
153 #define RExC_seen_evals (pRExC_state->seen_evals)
154 #define RExC_utf8 (pRExC_state->utf8)
155 #define RExC_charnames (pRExC_state->charnames)
156 #define RExC_parens (pRExC_state->parens)
157 #define RExC_paren_names (pRExC_state->paren_names)
159 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
160 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
161 ((*s) == '{' && regcurly(s)))
164 #undef SPSTART /* dratted cpp namespace... */
167 * Flags to be passed up and down.
169 #define WORST 0 /* Worst case. */
170 #define HASWIDTH 0x1 /* Known to match non-null strings. */
171 #define SIMPLE 0x2 /* Simple enough to be STAR/PLUS operand. */
172 #define SPSTART 0x4 /* Starts with * or +. */
173 #define TRYAGAIN 0x8 /* Weeded out a declaration. */
175 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
177 /* whether trie related optimizations are enabled */
178 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
179 #define TRIE_STUDY_OPT
180 #define FULL_TRIE_STUDY
185 /* About scan_data_t.
187 During optimisation we recurse through the regexp program performing
188 various inplace (keyhole style) optimisations. In addition study_chunk
189 and scan_commit populate this data structure with information about
190 what strings MUST appear in the pattern. We look for the longest
191 string that must appear for at a fixed location, and we look for the
192 longest string that may appear at a floating location. So for instance
197 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
198 strings (because they follow a .* construct). study_chunk will identify
199 both FOO and BAR as being the longest fixed and floating strings respectively.
201 The strings can be composites, for instance
205 will result in a composite fixed substring 'foo'.
207 For each string some basic information is maintained:
209 - offset or min_offset
210 This is the position the string must appear at, or not before.
211 It also implicitly (when combined with minlenp) tells us how many
212 character must match before the string we are searching.
213 Likewise when combined with minlenp and the length of the string
214 tells us how many characters must appear after the string we have
218 Only used for floating strings. This is the rightmost point that
219 the string can appear at. Ifset to I32 max it indicates that the
220 string can occur infinitely far to the right.
223 A pointer to the minimum length of the pattern that the string
224 was found inside. This is important as in the case of positive
225 lookahead or positive lookbehind we can have multiple patterns
230 The minimum length of the pattern overall is 3, the minimum length
231 of the lookahead part is 3, but the minimum length of the part that
232 will actually match is 1. So 'FOO's minimum length is 3, but the
233 minimum length for the F is 1. This is important as the minimum length
234 is used to determine offsets in front of and behind the string being
235 looked for. Since strings can be composites this is the length of the
236 pattern at the time it was commited with a scan_commit. Note that
237 the length is calculated by study_chunk, so that the minimum lengths
238 are not known until the full pattern has been compiled, thus the
239 pointer to the value.
243 In the case of lookbehind the string being searched for can be
244 offset past the start point of the final matching string.
245 If this value was just blithely removed from the min_offset it would
246 invalidate some of the calculations for how many chars must match
247 before or after (as they are derived from min_offset and minlen and
248 the length of the string being searched for).
249 When the final pattern is compiled and the data is moved from the
250 scan_data_t structure into the regexp structure the information
251 about lookbehind is factored in, with the information that would
252 have been lost precalculated in the end_shift field for the
255 The fields pos_min and pos_delta are used to store the minimum offset
256 and the delta to the maximum offset at the current point in the pattern.
260 typedef struct scan_data_t {
261 /*I32 len_min; unused */
262 /*I32 len_delta; unused */
266 I32 last_end; /* min value, <0 unless valid. */
269 SV **longest; /* Either &l_fixed, or &l_float. */
270 SV *longest_fixed; /* longest fixed string found in pattern */
271 I32 offset_fixed; /* offset where it starts */
272 I32 *minlen_fixed; /* pointer to the minlen relevent to the string */
273 I32 lookbehind_fixed; /* is the position of the string modfied by LB */
274 SV *longest_float; /* longest floating string found in pattern */
275 I32 offset_float_min; /* earliest point in string it can appear */
276 I32 offset_float_max; /* latest point in string it can appear */
277 I32 *minlen_float; /* pointer to the minlen relevent to the string */
278 I32 lookbehind_float; /* is the position of the string modified by LB */
282 struct regnode_charclass_class *start_class;
286 * Forward declarations for pregcomp()'s friends.
289 static const scan_data_t zero_scan_data =
290 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
292 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
293 #define SF_BEFORE_SEOL 0x0001
294 #define SF_BEFORE_MEOL 0x0002
295 #define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
296 #define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
299 # define SF_FIX_SHIFT_EOL (0+2)
300 # define SF_FL_SHIFT_EOL (0+4)
302 # define SF_FIX_SHIFT_EOL (+2)
303 # define SF_FL_SHIFT_EOL (+4)
306 #define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
307 #define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
309 #define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
310 #define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
311 #define SF_IS_INF 0x0040
312 #define SF_HAS_PAR 0x0080
313 #define SF_IN_PAR 0x0100
314 #define SF_HAS_EVAL 0x0200
315 #define SCF_DO_SUBSTR 0x0400
316 #define SCF_DO_STCLASS_AND 0x0800
317 #define SCF_DO_STCLASS_OR 0x1000
318 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
319 #define SCF_WHILEM_VISITED_POS 0x2000
321 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
324 #define UTF (RExC_utf8 != 0)
325 #define LOC ((RExC_flags & PMf_LOCALE) != 0)
326 #define FOLD ((RExC_flags & PMf_FOLD) != 0)
328 #define OOB_UNICODE 12345678
329 #define OOB_NAMEDCLASS -1
331 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
332 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
335 /* length of regex to show in messages that don't mark a position within */
336 #define RegexLengthToShowInErrorMessages 127
339 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
340 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
341 * op/pragma/warn/regcomp.
343 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
344 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
346 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
349 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
350 * arg. Show regex, up to a maximum length. If it's too long, chop and add
353 #define FAIL(msg) STMT_START { \
354 const char *ellipses = ""; \
355 IV len = RExC_end - RExC_precomp; \
358 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
359 if (len > RegexLengthToShowInErrorMessages) { \
360 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
361 len = RegexLengthToShowInErrorMessages - 10; \
364 Perl_croak(aTHX_ "%s in regex m/%.*s%s/", \
365 msg, (int)len, RExC_precomp, ellipses); \
369 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
371 #define Simple_vFAIL(m) STMT_START { \
372 const IV offset = RExC_parse - RExC_precomp; \
373 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
374 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
378 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
380 #define vFAIL(m) STMT_START { \
382 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
387 * Like Simple_vFAIL(), but accepts two arguments.
389 #define Simple_vFAIL2(m,a1) STMT_START { \
390 const IV offset = RExC_parse - RExC_precomp; \
391 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, \
392 (int)offset, RExC_precomp, RExC_precomp + offset); \
396 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
398 #define vFAIL2(m,a1) STMT_START { \
400 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
401 Simple_vFAIL2(m, a1); \
406 * Like Simple_vFAIL(), but accepts three arguments.
408 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
409 const IV offset = RExC_parse - RExC_precomp; \
410 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, \
411 (int)offset, RExC_precomp, RExC_precomp + offset); \
415 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
417 #define vFAIL3(m,a1,a2) STMT_START { \
419 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
420 Simple_vFAIL3(m, a1, a2); \
424 * Like Simple_vFAIL(), but accepts four arguments.
426 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
427 const IV offset = RExC_parse - RExC_precomp; \
428 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, \
429 (int)offset, RExC_precomp, RExC_precomp + offset); \
432 #define vWARN(loc,m) STMT_START { \
433 const IV offset = loc - RExC_precomp; \
434 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s" REPORT_LOCATION, \
435 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
438 #define vWARNdep(loc,m) STMT_START { \
439 const IV offset = loc - RExC_precomp; \
440 Perl_warner(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
441 "%s" REPORT_LOCATION, \
442 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
446 #define vWARN2(loc, m, a1) STMT_START { \
447 const IV offset = loc - RExC_precomp; \
448 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
449 a1, (int)offset, RExC_precomp, RExC_precomp + offset); \
452 #define vWARN3(loc, m, a1, a2) STMT_START { \
453 const IV offset = loc - RExC_precomp; \
454 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
455 a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
458 #define vWARN4(loc, m, a1, a2, a3) STMT_START { \
459 const IV offset = loc - RExC_precomp; \
460 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
461 a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
464 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START { \
465 const IV offset = loc - RExC_precomp; \
466 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
467 a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
471 /* Allow for side effects in s */
472 #define REGC(c,s) STMT_START { \
473 if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
476 /* Macros for recording node offsets. 20001227 mjd@plover.com
477 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
478 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
479 * Element 0 holds the number n.
480 * Position is 1 indexed.
483 #define Set_Node_Offset_To_R(node,byte) STMT_START { \
485 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
486 __LINE__, (node), (int)(byte))); \
488 Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
490 RExC_offsets[2*(node)-1] = (byte); \
495 #define Set_Node_Offset(node,byte) \
496 Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
497 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
499 #define Set_Node_Length_To_R(node,len) STMT_START { \
501 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
502 __LINE__, (int)(node), (int)(len))); \
504 Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
506 RExC_offsets[2*(node)] = (len); \
511 #define Set_Node_Length(node,len) \
512 Set_Node_Length_To_R((node)-RExC_emit_start, len)
513 #define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
514 #define Set_Node_Cur_Length(node) \
515 Set_Node_Length(node, RExC_parse - parse_start)
517 /* Get offsets and lengths */
518 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
519 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
521 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
522 Set_Node_Offset_To_R((node)-RExC_emit_start, (offset)); \
523 Set_Node_Length_To_R((node)-RExC_emit_start, (len)); \
527 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
528 #define EXPERIMENTAL_INPLACESCAN
531 #define DEBUG_STUDYDATA(data,depth) \
532 DEBUG_OPTIMISE_MORE_r(if(data){ \
533 PerlIO_printf(Perl_debug_log, \
534 "%*s"/* Len:%"IVdf"/%"IVdf" */" Pos:%"IVdf"/%"IVdf \
535 " Flags: %"IVdf" Whilem_c: %"IVdf" Lcp: %"IVdf" ", \
536 (int)(depth)*2, "", \
537 (IV)((data)->pos_min), \
538 (IV)((data)->pos_delta), \
539 (IV)((data)->flags), \
540 (IV)((data)->whilem_c), \
541 (IV)((data)->last_closep ? *((data)->last_closep) : -1) \
543 if ((data)->last_found) \
544 PerlIO_printf(Perl_debug_log, \
545 "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
546 " %sFloat: '%s' @ %"IVdf"/%"IVdf"", \
547 SvPVX_const((data)->last_found), \
548 (IV)((data)->last_end), \
549 (IV)((data)->last_start_min), \
550 (IV)((data)->last_start_max), \
551 ((data)->longest && \
552 (data)->longest==&((data)->longest_fixed)) ? "*" : "", \
553 SvPVX_const((data)->longest_fixed), \
554 (IV)((data)->offset_fixed), \
555 ((data)->longest && \
556 (data)->longest==&((data)->longest_float)) ? "*" : "", \
557 SvPVX_const((data)->longest_float), \
558 (IV)((data)->offset_float_min), \
559 (IV)((data)->offset_float_max) \
561 PerlIO_printf(Perl_debug_log,"\n"); \
564 static void clear_re(pTHX_ void *r);
566 /* Mark that we cannot extend a found fixed substring at this point.
567 Update the longest found anchored substring and the longest found
568 floating substrings if needed. */
571 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp)
573 const STRLEN l = CHR_SVLEN(data->last_found);
574 const STRLEN old_l = CHR_SVLEN(*data->longest);
575 GET_RE_DEBUG_FLAGS_DECL;
577 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
578 SvSetMagicSV(*data->longest, data->last_found);
579 if (*data->longest == data->longest_fixed) {
580 data->offset_fixed = l ? data->last_start_min : data->pos_min;
581 if (data->flags & SF_BEFORE_EOL)
583 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
585 data->flags &= ~SF_FIX_BEFORE_EOL;
586 data->minlen_fixed=minlenp;
587 data->lookbehind_fixed=0;
590 data->offset_float_min = l ? data->last_start_min : data->pos_min;
591 data->offset_float_max = (l
592 ? data->last_start_max
593 : data->pos_min + data->pos_delta);
594 if ((U32)data->offset_float_max > (U32)I32_MAX)
595 data->offset_float_max = I32_MAX;
596 if (data->flags & SF_BEFORE_EOL)
598 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
600 data->flags &= ~SF_FL_BEFORE_EOL;
601 data->minlen_float=minlenp;
602 data->lookbehind_float=0;
605 SvCUR_set(data->last_found, 0);
607 SV * const sv = data->last_found;
608 if (SvUTF8(sv) && SvMAGICAL(sv)) {
609 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
615 data->flags &= ~SF_BEFORE_EOL;
616 DEBUG_STUDYDATA(data,0);
619 /* Can match anything (initialization) */
621 S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
623 ANYOF_CLASS_ZERO(cl);
624 ANYOF_BITMAP_SETALL(cl);
625 cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL;
627 cl->flags |= ANYOF_LOCALE;
630 /* Can match anything (initialization) */
632 S_cl_is_anything(const struct regnode_charclass_class *cl)
636 for (value = 0; value <= ANYOF_MAX; value += 2)
637 if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
639 if (!(cl->flags & ANYOF_UNICODE_ALL))
641 if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
646 /* Can match anything (initialization) */
648 S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
650 Zero(cl, 1, struct regnode_charclass_class);
652 cl_anything(pRExC_state, cl);
656 S_cl_init_zero(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
658 Zero(cl, 1, struct regnode_charclass_class);
660 cl_anything(pRExC_state, cl);
662 cl->flags |= ANYOF_LOCALE;
665 /* 'And' a given class with another one. Can create false positives */
666 /* We assume that cl is not inverted */
668 S_cl_and(struct regnode_charclass_class *cl,
669 const struct regnode_charclass_class *and_with)
671 if (!(and_with->flags & ANYOF_CLASS)
672 && !(cl->flags & ANYOF_CLASS)
673 && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
674 && !(and_with->flags & ANYOF_FOLD)
675 && !(cl->flags & ANYOF_FOLD)) {
678 if (and_with->flags & ANYOF_INVERT)
679 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
680 cl->bitmap[i] &= ~and_with->bitmap[i];
682 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
683 cl->bitmap[i] &= and_with->bitmap[i];
684 } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
685 if (!(and_with->flags & ANYOF_EOS))
686 cl->flags &= ~ANYOF_EOS;
688 if (cl->flags & ANYOF_UNICODE_ALL && and_with->flags & ANYOF_UNICODE &&
689 !(and_with->flags & ANYOF_INVERT)) {
690 cl->flags &= ~ANYOF_UNICODE_ALL;
691 cl->flags |= ANYOF_UNICODE;
692 ARG_SET(cl, ARG(and_with));
694 if (!(and_with->flags & ANYOF_UNICODE_ALL) &&
695 !(and_with->flags & ANYOF_INVERT))
696 cl->flags &= ~ANYOF_UNICODE_ALL;
697 if (!(and_with->flags & (ANYOF_UNICODE|ANYOF_UNICODE_ALL)) &&
698 !(and_with->flags & ANYOF_INVERT))
699 cl->flags &= ~ANYOF_UNICODE;
702 /* 'OR' a given class with another one. Can create false positives */
703 /* We assume that cl is not inverted */
705 S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
707 if (or_with->flags & ANYOF_INVERT) {
709 * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
710 * <= (B1 | !B2) | (CL1 | !CL2)
711 * which is wasteful if CL2 is small, but we ignore CL2:
712 * (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
713 * XXXX Can we handle case-fold? Unclear:
714 * (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
715 * (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
717 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
718 && !(or_with->flags & ANYOF_FOLD)
719 && !(cl->flags & ANYOF_FOLD) ) {
722 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
723 cl->bitmap[i] |= ~or_with->bitmap[i];
724 } /* XXXX: logic is complicated otherwise */
726 cl_anything(pRExC_state, cl);
729 /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
730 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
731 && (!(or_with->flags & ANYOF_FOLD)
732 || (cl->flags & ANYOF_FOLD)) ) {
735 /* OR char bitmap and class bitmap separately */
736 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
737 cl->bitmap[i] |= or_with->bitmap[i];
738 if (or_with->flags & ANYOF_CLASS) {
739 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
740 cl->classflags[i] |= or_with->classflags[i];
741 cl->flags |= ANYOF_CLASS;
744 else { /* XXXX: logic is complicated, leave it along for a moment. */
745 cl_anything(pRExC_state, cl);
748 if (or_with->flags & ANYOF_EOS)
749 cl->flags |= ANYOF_EOS;
751 if (cl->flags & ANYOF_UNICODE && or_with->flags & ANYOF_UNICODE &&
752 ARG(cl) != ARG(or_with)) {
753 cl->flags |= ANYOF_UNICODE_ALL;
754 cl->flags &= ~ANYOF_UNICODE;
756 if (or_with->flags & ANYOF_UNICODE_ALL) {
757 cl->flags |= ANYOF_UNICODE_ALL;
758 cl->flags &= ~ANYOF_UNICODE;
762 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
763 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
764 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
765 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
771 dump_trie_interim_list(trie,next_alloc)
772 dump_trie_interim_table(trie,next_alloc)
774 These routines dump out a trie in a somewhat readable format.
775 The _interim_ variants are used for debugging the interim
776 tables that are used to generate the final compressed
777 representation which is what dump_trie expects.
779 Part of the reason for their existance is to provide a form
780 of documentation as to how the different representations function.
786 Dumps the final compressed table form of the trie to Perl_debug_log.
787 Used for debugging make_trie().
791 S_dump_trie(pTHX_ const struct _reg_trie_data *trie,U32 depth)
794 SV *sv=sv_newmortal();
795 int colwidth= trie->widecharmap ? 6 : 4;
796 GET_RE_DEBUG_FLAGS_DECL;
799 PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
800 (int)depth * 2 + 2,"",
801 "Match","Base","Ofs" );
803 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
804 SV ** const tmp = av_fetch( trie->revcharmap, state, 0);
806 PerlIO_printf( Perl_debug_log, "%*s",
808 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
809 PL_colors[0], PL_colors[1],
810 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
811 PERL_PV_ESCAPE_FIRSTCHAR
816 PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
817 (int)depth * 2 + 2,"");
819 for( state = 0 ; state < trie->uniquecharcount ; state++ )
820 PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
821 PerlIO_printf( Perl_debug_log, "\n");
823 for( state = 1 ; state < trie->statecount ; state++ ) {
824 const U32 base = trie->states[ state ].trans.base;
826 PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
828 if ( trie->states[ state ].wordnum ) {
829 PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
831 PerlIO_printf( Perl_debug_log, "%6s", "" );
834 PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
839 while( ( base + ofs < trie->uniquecharcount ) ||
840 ( base + ofs - trie->uniquecharcount < trie->lasttrans
841 && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
844 PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
846 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
847 if ( ( base + ofs >= trie->uniquecharcount ) &&
848 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
849 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
851 PerlIO_printf( Perl_debug_log, "%*"UVXf,
853 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
855 PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
859 PerlIO_printf( Perl_debug_log, "]");
862 PerlIO_printf( Perl_debug_log, "\n" );
866 dump_trie_interim_list(trie,next_alloc)
867 Dumps a fully constructed but uncompressed trie in list form.
868 List tries normally only are used for construction when the number of
869 possible chars (trie->uniquecharcount) is very high.
870 Used for debugging make_trie().
873 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie, U32 next_alloc,U32 depth)
876 SV *sv=sv_newmortal();
877 int colwidth= trie->widecharmap ? 6 : 4;
878 GET_RE_DEBUG_FLAGS_DECL;
879 /* print out the table precompression. */
880 PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
881 (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
882 "------:-----+-----------------\n" );
884 for( state=1 ; state < next_alloc ; state ++ ) {
887 PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
888 (int)depth * 2 + 2,"", (UV)state );
889 if ( ! trie->states[ state ].wordnum ) {
890 PerlIO_printf( Perl_debug_log, "%5s| ","");
892 PerlIO_printf( Perl_debug_log, "W%4x| ",
893 trie->states[ state ].wordnum
896 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
897 SV ** const tmp = av_fetch( trie->revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
899 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
901 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
902 PL_colors[0], PL_colors[1],
903 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
904 PERL_PV_ESCAPE_FIRSTCHAR
906 TRIE_LIST_ITEM(state,charid).forid,
907 (UV)TRIE_LIST_ITEM(state,charid).newstate
910 PerlIO_printf(Perl_debug_log, "\n%*s| ",
911 (int)((depth * 2) + 14), "");
914 PerlIO_printf( Perl_debug_log, "\n");
919 dump_trie_interim_table(trie,next_alloc)
920 Dumps a fully constructed but uncompressed trie in table form.
921 This is the normal DFA style state transition table, with a few
922 twists to facilitate compression later.
923 Used for debugging make_trie().
926 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie, U32 next_alloc, U32 depth)
930 SV *sv=sv_newmortal();
931 int colwidth= trie->widecharmap ? 6 : 4;
932 GET_RE_DEBUG_FLAGS_DECL;
935 print out the table precompression so that we can do a visual check
936 that they are identical.
939 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
941 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
942 SV ** const tmp = av_fetch( trie->revcharmap, charid, 0);
944 PerlIO_printf( Perl_debug_log, "%*s",
946 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
947 PL_colors[0], PL_colors[1],
948 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
949 PERL_PV_ESCAPE_FIRSTCHAR
955 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
957 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
958 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
961 PerlIO_printf( Perl_debug_log, "\n" );
963 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
965 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
966 (int)depth * 2 + 2,"",
967 (UV)TRIE_NODENUM( state ) );
969 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
970 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
972 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
974 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
976 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
977 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
979 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
980 trie->states[ TRIE_NODENUM( state ) ].wordnum );
987 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
988 startbranch: the first branch in the whole branch sequence
989 first : start branch of sequence of branch-exact nodes.
990 May be the same as startbranch
991 last : Thing following the last branch.
992 May be the same as tail.
993 tail : item following the branch sequence
994 count : words in the sequence
995 flags : currently the OP() type we will be building one of /EXACT(|F|Fl)/
998 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
1000 A trie is an N'ary tree where the branches are determined by digital
1001 decomposition of the key. IE, at the root node you look up the 1st character and
1002 follow that branch repeat until you find the end of the branches. Nodes can be
1003 marked as "accepting" meaning they represent a complete word. Eg:
1007 would convert into the following structure. Numbers represent states, letters
1008 following numbers represent valid transitions on the letter from that state, if
1009 the number is in square brackets it represents an accepting state, otherwise it
1010 will be in parenthesis.
1012 +-h->+-e->[3]-+-r->(8)-+-s->[9]
1016 (1) +-i->(6)-+-s->[7]
1018 +-s->(3)-+-h->(4)-+-e->[5]
1020 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1022 This shows that when matching against the string 'hers' we will begin at state 1
1023 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1024 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1025 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1026 single traverse. We store a mapping from accepting to state to which word was
1027 matched, and then when we have multiple possibilities we try to complete the
1028 rest of the regex in the order in which they occured in the alternation.
1030 The only prior NFA like behaviour that would be changed by the TRIE support is
1031 the silent ignoring of duplicate alternations which are of the form:
1033 / (DUPE|DUPE) X? (?{ ... }) Y /x
1035 Thus EVAL blocks follwing a trie may be called a different number of times with
1036 and without the optimisation. With the optimisations dupes will be silently
1037 ignored. This inconsistant behaviour of EVAL type nodes is well established as
1038 the following demonstrates:
1040 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1042 which prints out 'word' three times, but
1044 'words'=~/(word|word|word)(?{ print $1 })S/
1046 which doesnt print it out at all. This is due to other optimisations kicking in.
1048 Example of what happens on a structural level:
1050 The regexp /(ac|ad|ab)+/ will produce the folowing debug output:
1052 1: CURLYM[1] {1,32767}(18)
1063 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1064 and should turn into:
1066 1: CURLYM[1] {1,32767}(18)
1068 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1076 Cases where tail != last would be like /(?foo|bar)baz/:
1086 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1087 and would end up looking like:
1090 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1097 d = uvuni_to_utf8_flags(d, uv, 0);
1099 is the recommended Unicode-aware way of saying
1104 #define TRIE_STORE_REVCHAR \
1106 SV *tmp = newSVpvs(""); \
1107 if (UTF) SvUTF8_on(tmp); \
1108 Perl_sv_catpvf( aTHX_ tmp, "%c", (int)uvc ); \
1109 av_push( TRIE_REVCHARMAP(trie), tmp ); \
1112 #define TRIE_READ_CHAR STMT_START { \
1116 if ( foldlen > 0 ) { \
1117 uvc = utf8n_to_uvuni( scan, UTF8_MAXLEN, &len, uniflags ); \
1122 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1123 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1124 foldlen -= UNISKIP( uvc ); \
1125 scan = foldbuf + UNISKIP( uvc ); \
1128 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1138 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
1139 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
1140 U32 ging = TRIE_LIST_LEN( state ) *= 2; \
1141 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
1143 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
1144 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
1145 TRIE_LIST_CUR( state )++; \
1148 #define TRIE_LIST_NEW(state) STMT_START { \
1149 Newxz( trie->states[ state ].trans.list, \
1150 4, reg_trie_trans_le ); \
1151 TRIE_LIST_CUR( state ) = 1; \
1152 TRIE_LIST_LEN( state ) = 4; \
1155 #define TRIE_HANDLE_WORD(state) STMT_START { \
1156 U16 dupe= trie->states[ state ].wordnum; \
1157 regnode * const noper_next = regnext( noper ); \
1159 if (trie->wordlen) \
1160 trie->wordlen[ curword ] = wordlen; \
1162 /* store the word for dumping */ \
1164 if (OP(noper) != NOTHING) \
1165 tmp = newSVpvn(STRING(noper), STR_LEN(noper)); \
1167 tmp = newSVpvn( "", 0 ); \
1168 if ( UTF ) SvUTF8_on( tmp ); \
1169 av_push( trie->words, tmp ); \
1174 if ( noper_next < tail ) { \
1176 Newxz( trie->jump, word_count + 1, U16); \
1177 trie->jump[curword] = (U16)(noper_next - convert); \
1179 jumper = noper_next; \
1181 nextbranch= regnext(cur); \
1185 /* So it's a dupe. This means we need to maintain a */\
1186 /* linked-list from the first to the next. */\
1187 /* we only allocate the nextword buffer when there */\
1188 /* a dupe, so first time we have to do the allocation */\
1189 if (!trie->nextword) \
1190 Newxz( trie->nextword, word_count + 1, U16); \
1191 while ( trie->nextword[dupe] ) \
1192 dupe= trie->nextword[dupe]; \
1193 trie->nextword[dupe]= curword; \
1195 /* we haven't inserted this word yet. */ \
1196 trie->states[ state ].wordnum = curword; \
1201 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
1202 ( ( base + charid >= ucharcount \
1203 && base + charid < ubound \
1204 && state == trie->trans[ base - ucharcount + charid ].check \
1205 && trie->trans[ base - ucharcount + charid ].next ) \
1206 ? trie->trans[ base - ucharcount + charid ].next \
1207 : ( state==1 ? special : 0 ) \
1211 #define MADE_JUMP_TRIE 2
1212 #define MADE_EXACT_TRIE 4
1215 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
1218 /* first pass, loop through and scan words */
1219 reg_trie_data *trie;
1221 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1226 regnode *jumper = NULL;
1227 regnode *nextbranch = NULL;
1228 regnode *convert = NULL;
1229 /* we just use folder as a flag in utf8 */
1230 const U8 * const folder = ( flags == EXACTF
1232 : ( flags == EXACTFL
1238 const U32 data_slot = add_data( pRExC_state, 1, "t" );
1239 SV *re_trie_maxbuff;
1241 /* these are only used during construction but are useful during
1242 * debugging so we store them in the struct when debugging.
1244 STRLEN trie_charcount=0;
1245 AV *trie_revcharmap;
1247 GET_RE_DEBUG_FLAGS_DECL;
1249 PERL_UNUSED_ARG(depth);
1252 Newxz( trie, 1, reg_trie_data );
1254 trie->startstate = 1;
1255 trie->wordcount = word_count;
1256 RExC_rx->data->data[ data_slot ] = (void*)trie;
1257 Newxz( trie->charmap, 256, U16 );
1258 if (!(UTF && folder))
1259 Newxz( trie->bitmap, ANYOF_BITMAP_SIZE, char );
1261 trie->words = newAV();
1263 TRIE_REVCHARMAP(trie) = newAV();
1265 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
1266 if (!SvIOK(re_trie_maxbuff)) {
1267 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
1270 PerlIO_printf( Perl_debug_log,
1271 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
1272 (int)depth * 2 + 2, "",
1273 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
1274 REG_NODE_NUM(last), REG_NODE_NUM(tail),
1278 /* Find the node we are going to overwrite */
1279 if ( first == startbranch && OP( last ) != BRANCH ) {
1280 /* whole branch chain */
1283 /* branch sub-chain */
1284 convert = NEXTOPER( first );
1287 /* -- First loop and Setup --
1289 We first traverse the branches and scan each word to determine if it
1290 contains widechars, and how many unique chars there are, this is
1291 important as we have to build a table with at least as many columns as we
1294 We use an array of integers to represent the character codes 0..255
1295 (trie->charmap) and we use a an HV* to store unicode characters. We use the
1296 native representation of the character value as the key and IV's for the
1299 *TODO* If we keep track of how many times each character is used we can
1300 remap the columns so that the table compression later on is more
1301 efficient in terms of memory by ensuring most common value is in the
1302 middle and the least common are on the outside. IMO this would be better
1303 than a most to least common mapping as theres a decent chance the most
1304 common letter will share a node with the least common, meaning the node
1305 will not be compressable. With a middle is most common approach the worst
1306 case is when we have the least common nodes twice.
1310 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1311 regnode * const noper = NEXTOPER( cur );
1312 const U8 *uc = (U8*)STRING( noper );
1313 const U8 * const e = uc + STR_LEN( noper );
1315 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1316 const U8 *scan = (U8*)NULL;
1317 U32 wordlen = 0; /* required init */
1320 if (OP(noper) == NOTHING) {
1325 TRIE_BITMAP_SET(trie,*uc);
1326 if ( folder ) TRIE_BITMAP_SET(trie,folder[ *uc ]);
1328 for ( ; uc < e ; uc += len ) {
1329 TRIE_CHARCOUNT(trie)++;
1333 if ( !trie->charmap[ uvc ] ) {
1334 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1336 trie->charmap[ folder[ uvc ] ] = trie->charmap[ uvc ];
1341 if ( !trie->widecharmap )
1342 trie->widecharmap = newHV();
1344 svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 1 );
1347 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
1349 if ( !SvTRUE( *svpp ) ) {
1350 sv_setiv( *svpp, ++trie->uniquecharcount );
1355 if( cur == first ) {
1358 } else if (chars < trie->minlen) {
1360 } else if (chars > trie->maxlen) {
1364 } /* end first pass */
1365 DEBUG_TRIE_COMPILE_r(
1366 PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1367 (int)depth * 2 + 2,"",
1368 ( trie->widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
1369 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1370 (int)trie->minlen, (int)trie->maxlen )
1372 Newxz( trie->wordlen, word_count, U32 );
1375 We now know what we are dealing with in terms of unique chars and
1376 string sizes so we can calculate how much memory a naive
1377 representation using a flat table will take. If it's over a reasonable
1378 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
1379 conservative but potentially much slower representation using an array
1382 At the end we convert both representations into the same compressed
1383 form that will be used in regexec.c for matching with. The latter
1384 is a form that cannot be used to construct with but has memory
1385 properties similar to the list form and access properties similar
1386 to the table form making it both suitable for fast searches and
1387 small enough that its feasable to store for the duration of a program.
1389 See the comment in the code where the compressed table is produced
1390 inplace from the flat tabe representation for an explanation of how
1391 the compression works.
1396 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
1398 Second Pass -- Array Of Lists Representation
1400 Each state will be represented by a list of charid:state records
1401 (reg_trie_trans_le) the first such element holds the CUR and LEN
1402 points of the allocated array. (See defines above).
1404 We build the initial structure using the lists, and then convert
1405 it into the compressed table form which allows faster lookups
1406 (but cant be modified once converted).
1409 STRLEN transcount = 1;
1411 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1412 "%*sCompiling trie using list compiler\n",
1413 (int)depth * 2 + 2, ""));
1415 Newxz( trie->states, TRIE_CHARCOUNT(trie) + 2, reg_trie_state );
1419 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1421 regnode * const noper = NEXTOPER( cur );
1422 U8 *uc = (U8*)STRING( noper );
1423 const U8 * const e = uc + STR_LEN( noper );
1424 U32 state = 1; /* required init */
1425 U16 charid = 0; /* sanity init */
1426 U8 *scan = (U8*)NULL; /* sanity init */
1427 STRLEN foldlen = 0; /* required init */
1428 U32 wordlen = 0; /* required init */
1429 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1431 if (OP(noper) != NOTHING) {
1432 for ( ; uc < e ; uc += len ) {
1437 charid = trie->charmap[ uvc ];
1439 SV** const svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 0);
1443 charid=(U16)SvIV( *svpp );
1446 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1453 if ( !trie->states[ state ].trans.list ) {
1454 TRIE_LIST_NEW( state );
1456 for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1457 if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1458 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1463 newstate = next_alloc++;
1464 TRIE_LIST_PUSH( state, charid, newstate );
1469 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1473 TRIE_HANDLE_WORD(state);
1475 } /* end second pass */
1477 /* next alloc is the NEXT state to be allocated */
1478 trie->statecount = next_alloc;
1479 Renew( trie->states, next_alloc, reg_trie_state );
1481 /* and now dump it out before we compress it */
1482 DEBUG_TRIE_COMPILE_MORE_r(
1483 dump_trie_interim_list(trie,next_alloc,depth+1)
1486 Newxz( trie->trans, transcount ,reg_trie_trans );
1493 for( state=1 ; state < next_alloc ; state ++ ) {
1497 DEBUG_TRIE_COMPILE_MORE_r(
1498 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1502 if (trie->states[state].trans.list) {
1503 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1507 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1508 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1509 if ( forid < minid ) {
1511 } else if ( forid > maxid ) {
1515 if ( transcount < tp + maxid - minid + 1) {
1517 Renew( trie->trans, transcount, reg_trie_trans );
1518 Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1520 base = trie->uniquecharcount + tp - minid;
1521 if ( maxid == minid ) {
1523 for ( ; zp < tp ; zp++ ) {
1524 if ( ! trie->trans[ zp ].next ) {
1525 base = trie->uniquecharcount + zp - minid;
1526 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1527 trie->trans[ zp ].check = state;
1533 trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1534 trie->trans[ tp ].check = state;
1539 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1540 const U32 tid = base - trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
1541 trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1542 trie->trans[ tid ].check = state;
1544 tp += ( maxid - minid + 1 );
1546 Safefree(trie->states[ state ].trans.list);
1549 DEBUG_TRIE_COMPILE_MORE_r(
1550 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1553 trie->states[ state ].trans.base=base;
1555 trie->lasttrans = tp + 1;
1559 Second Pass -- Flat Table Representation.
1561 we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1562 We know that we will need Charcount+1 trans at most to store the data
1563 (one row per char at worst case) So we preallocate both structures
1564 assuming worst case.
1566 We then construct the trie using only the .next slots of the entry
1569 We use the .check field of the first entry of the node temporarily to
1570 make compression both faster and easier by keeping track of how many non
1571 zero fields are in the node.
1573 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1576 There are two terms at use here: state as a TRIE_NODEIDX() which is a
1577 number representing the first entry of the node, and state as a
1578 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1579 TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1580 are 2 entrys per node. eg:
1588 The table is internally in the right hand, idx form. However as we also
1589 have to deal with the states array which is indexed by nodenum we have to
1590 use TRIE_NODENUM() to convert.
1593 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1594 "%*sCompiling trie using table compiler\n",
1595 (int)depth * 2 + 2, ""));
1597 Newxz( trie->trans, ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1,
1599 Newxz( trie->states, TRIE_CHARCOUNT(trie) + 2, reg_trie_state );
1600 next_alloc = trie->uniquecharcount + 1;
1603 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1605 regnode * const noper = NEXTOPER( cur );
1606 const U8 *uc = (U8*)STRING( noper );
1607 const U8 * const e = uc + STR_LEN( noper );
1609 U32 state = 1; /* required init */
1611 U16 charid = 0; /* sanity init */
1612 U32 accept_state = 0; /* sanity init */
1613 U8 *scan = (U8*)NULL; /* sanity init */
1615 STRLEN foldlen = 0; /* required init */
1616 U32 wordlen = 0; /* required init */
1617 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1619 if ( OP(noper) != NOTHING ) {
1620 for ( ; uc < e ; uc += len ) {
1625 charid = trie->charmap[ uvc ];
1627 SV* const * const svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 0);
1628 charid = svpp ? (U16)SvIV(*svpp) : 0;
1632 if ( !trie->trans[ state + charid ].next ) {
1633 trie->trans[ state + charid ].next = next_alloc;
1634 trie->trans[ state ].check++;
1635 next_alloc += trie->uniquecharcount;
1637 state = trie->trans[ state + charid ].next;
1639 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1641 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1644 accept_state = TRIE_NODENUM( state );
1645 TRIE_HANDLE_WORD(accept_state);
1647 } /* end second pass */
1649 /* and now dump it out before we compress it */
1650 DEBUG_TRIE_COMPILE_MORE_r(
1651 dump_trie_interim_table(trie,next_alloc,depth+1)
1656 * Inplace compress the table.*
1658 For sparse data sets the table constructed by the trie algorithm will
1659 be mostly 0/FAIL transitions or to put it another way mostly empty.
1660 (Note that leaf nodes will not contain any transitions.)
1662 This algorithm compresses the tables by eliminating most such
1663 transitions, at the cost of a modest bit of extra work during lookup:
1665 - Each states[] entry contains a .base field which indicates the
1666 index in the state[] array wheres its transition data is stored.
1668 - If .base is 0 there are no valid transitions from that node.
1670 - If .base is nonzero then charid is added to it to find an entry in
1673 -If trans[states[state].base+charid].check!=state then the
1674 transition is taken to be a 0/Fail transition. Thus if there are fail
1675 transitions at the front of the node then the .base offset will point
1676 somewhere inside the previous nodes data (or maybe even into a node
1677 even earlier), but the .check field determines if the transition is
1681 The following process inplace converts the table to the compressed
1682 table: We first do not compress the root node 1,and mark its all its
1683 .check pointers as 1 and set its .base pointer as 1 as well. This
1684 allows to do a DFA construction from the compressed table later, and
1685 ensures that any .base pointers we calculate later are greater than
1688 - We set 'pos' to indicate the first entry of the second node.
1690 - We then iterate over the columns of the node, finding the first and
1691 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
1692 and set the .check pointers accordingly, and advance pos
1693 appropriately and repreat for the next node. Note that when we copy
1694 the next pointers we have to convert them from the original
1695 NODEIDX form to NODENUM form as the former is not valid post
1698 - If a node has no transitions used we mark its base as 0 and do not
1699 advance the pos pointer.
1701 - If a node only has one transition we use a second pointer into the
1702 structure to fill in allocated fail transitions from other states.
1703 This pointer is independent of the main pointer and scans forward
1704 looking for null transitions that are allocated to a state. When it
1705 finds one it writes the single transition into the "hole". If the
1706 pointer doesnt find one the single transition is appended as normal.
1708 - Once compressed we can Renew/realloc the structures to release the
1711 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
1712 specifically Fig 3.47 and the associated pseudocode.
1716 const U32 laststate = TRIE_NODENUM( next_alloc );
1719 trie->statecount = laststate;
1721 for ( state = 1 ; state < laststate ; state++ ) {
1723 const U32 stateidx = TRIE_NODEIDX( state );
1724 const U32 o_used = trie->trans[ stateidx ].check;
1725 U32 used = trie->trans[ stateidx ].check;
1726 trie->trans[ stateidx ].check = 0;
1728 for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
1729 if ( flag || trie->trans[ stateidx + charid ].next ) {
1730 if ( trie->trans[ stateidx + charid ].next ) {
1732 for ( ; zp < pos ; zp++ ) {
1733 if ( ! trie->trans[ zp ].next ) {
1737 trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
1738 trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1739 trie->trans[ zp ].check = state;
1740 if ( ++zp > pos ) pos = zp;
1747 trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
1749 trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1750 trie->trans[ pos ].check = state;
1755 trie->lasttrans = pos + 1;
1756 Renew( trie->states, laststate, reg_trie_state);
1757 DEBUG_TRIE_COMPILE_MORE_r(
1758 PerlIO_printf( Perl_debug_log,
1759 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
1760 (int)depth * 2 + 2,"",
1761 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
1764 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
1767 } /* end table compress */
1769 DEBUG_TRIE_COMPILE_MORE_r(
1770 PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
1771 (int)depth * 2 + 2, "",
1772 (UV)trie->statecount,
1773 (UV)trie->lasttrans)
1775 /* resize the trans array to remove unused space */
1776 Renew( trie->trans, trie->lasttrans, reg_trie_trans);
1778 /* and now dump out the compressed format */
1779 DEBUG_TRIE_COMPILE_r(
1780 dump_trie(trie,depth+1)
1783 { /* Modify the program and insert the new TRIE node*/
1784 U8 nodetype =(U8)(flags & 0xFF);
1788 regnode *optimize = NULL;
1790 U32 mjd_nodelen = 0;
1793 This means we convert either the first branch or the first Exact,
1794 depending on whether the thing following (in 'last') is a branch
1795 or not and whther first is the startbranch (ie is it a sub part of
1796 the alternation or is it the whole thing.)
1797 Assuming its a sub part we conver the EXACT otherwise we convert
1798 the whole branch sequence, including the first.
1800 /* Find the node we are going to overwrite */
1801 if ( first != startbranch || OP( last ) == BRANCH ) {
1802 /* branch sub-chain */
1803 NEXT_OFF( first ) = (U16)(last - first);
1805 mjd_offset= Node_Offset((convert));
1806 mjd_nodelen= Node_Length((convert));
1808 /* whole branch chain */
1811 const regnode *nop = NEXTOPER( convert );
1812 mjd_offset= Node_Offset((nop));
1813 mjd_nodelen= Node_Length((nop));
1818 PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
1819 (int)depth * 2 + 2, "",
1820 (UV)mjd_offset, (UV)mjd_nodelen)
1823 /* But first we check to see if there is a common prefix we can
1824 split out as an EXACT and put in front of the TRIE node. */
1825 trie->startstate= 1;
1826 if ( trie->bitmap && !trie->widecharmap && !trie->jump ) {
1828 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
1832 const U32 base = trie->states[ state ].trans.base;
1834 if ( trie->states[state].wordnum )
1837 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1838 if ( ( base + ofs >= trie->uniquecharcount ) &&
1839 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
1840 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
1842 if ( ++count > 1 ) {
1843 SV **tmp = av_fetch( TRIE_REVCHARMAP(trie), ofs, 0);
1844 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
1845 if ( state == 1 ) break;
1847 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
1849 PerlIO_printf(Perl_debug_log,
1850 "%*sNew Start State=%"UVuf" Class: [",
1851 (int)depth * 2 + 2, "",
1854 SV ** const tmp = av_fetch( TRIE_REVCHARMAP(trie), idx, 0);
1855 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
1857 TRIE_BITMAP_SET(trie,*ch);
1859 TRIE_BITMAP_SET(trie, folder[ *ch ]);
1861 PerlIO_printf(Perl_debug_log, (char*)ch)
1865 TRIE_BITMAP_SET(trie,*ch);
1867 TRIE_BITMAP_SET(trie,folder[ *ch ]);
1868 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
1874 SV **tmp = av_fetch( TRIE_REVCHARMAP(trie), idx, 0);
1875 const char *ch = SvPV_nolen_const( *tmp );
1877 PerlIO_printf( Perl_debug_log,
1878 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
1879 (int)depth * 2 + 2, "",
1880 (UV)state, (UV)idx, ch)
1883 OP( convert ) = nodetype;
1884 str=STRING(convert);
1893 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
1899 regnode *n = convert+NODE_SZ_STR(convert);
1900 NEXT_OFF(convert) = NODE_SZ_STR(convert);
1901 trie->startstate = state;
1902 trie->minlen -= (state - 1);
1903 trie->maxlen -= (state - 1);
1905 regnode *fix = convert;
1907 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
1908 while( ++fix < n ) {
1909 Set_Node_Offset_Length(fix, 0, 0);
1915 NEXT_OFF(convert) = (U16)(tail - convert);
1916 DEBUG_r(optimize= n);
1922 if ( trie->maxlen ) {
1923 NEXT_OFF( convert ) = (U16)(tail - convert);
1924 ARG_SET( convert, data_slot );
1925 /* Store the offset to the first unabsorbed branch in
1926 jump[0], which is otherwise unused by the jump logic.
1927 We use this when dumping a trie and during optimisation. */
1929 trie->jump[0] = (U16)(nextbranch - convert);
1932 if ( !trie->states[trie->startstate].wordnum && trie->bitmap &&
1933 ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
1935 OP( convert ) = TRIEC;
1936 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
1937 Safefree(trie->bitmap);
1940 OP( convert ) = TRIE;
1942 /* store the type in the flags */
1943 convert->flags = nodetype;
1947 + regarglen[ OP( convert ) ];
1949 /* XXX We really should free up the resource in trie now,
1950 as we won't use them - (which resources?) dmq */
1952 /* needed for dumping*/
1953 DEBUG_r(if (optimize) {
1954 regnode *opt = convert;
1955 while ( ++opt < optimize) {
1956 Set_Node_Offset_Length(opt,0,0);
1959 Try to clean up some of the debris left after the
1962 while( optimize < jumper ) {
1963 mjd_nodelen += Node_Length((optimize));
1964 OP( optimize ) = OPTIMIZED;
1965 Set_Node_Offset_Length(optimize,0,0);
1968 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
1970 } /* end node insert */
1972 SvREFCNT_dec(TRIE_REVCHARMAP(trie));
1976 : trie->startstate>1
1982 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source, regnode *stclass, U32 depth)
1984 /* The Trie is constructed and compressed now so we can build a fail array now if its needed
1986 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
1987 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
1990 We find the fail state for each state in the trie, this state is the longest proper
1991 suffix of the current states 'word' that is also a proper prefix of another word in our
1992 trie. State 1 represents the word '' and is the thus the default fail state. This allows
1993 the DFA not to have to restart after its tried and failed a word at a given point, it
1994 simply continues as though it had been matching the other word in the first place.
1996 'abcdgu'=~/abcdefg|cdgu/
1997 When we get to 'd' we are still matching the first word, we would encounter 'g' which would
1998 fail, which would bring use to the state representing 'd' in the second word where we would
1999 try 'g' and succeed, prodceding to match 'cdgu'.
2001 /* add a fail transition */
2002 reg_trie_data *trie=(reg_trie_data *)RExC_rx->data->data[ARG(source)];
2004 const U32 ucharcount = trie->uniquecharcount;
2005 const U32 numstates = trie->statecount;
2006 const U32 ubound = trie->lasttrans + ucharcount;
2010 U32 base = trie->states[ 1 ].trans.base;
2013 const U32 data_slot = add_data( pRExC_state, 1, "T" );
2014 GET_RE_DEBUG_FLAGS_DECL;
2016 PERL_UNUSED_ARG(depth);
2020 ARG_SET( stclass, data_slot );
2021 Newxz( aho, 1, reg_ac_data );
2022 RExC_rx->data->data[ data_slot ] = (void*)aho;
2024 aho->states=(reg_trie_state *)savepvn((const char*)trie->states,
2025 numstates * sizeof(reg_trie_state));
2026 Newxz( q, numstates, U32);
2027 Newxz( aho->fail, numstates, U32 );
2030 /* initialize fail[0..1] to be 1 so that we always have
2031 a valid final fail state */
2032 fail[ 0 ] = fail[ 1 ] = 1;
2034 for ( charid = 0; charid < ucharcount ; charid++ ) {
2035 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2037 q[ q_write ] = newstate;
2038 /* set to point at the root */
2039 fail[ q[ q_write++ ] ]=1;
2042 while ( q_read < q_write) {
2043 const U32 cur = q[ q_read++ % numstates ];
2044 base = trie->states[ cur ].trans.base;
2046 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2047 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2049 U32 fail_state = cur;
2052 fail_state = fail[ fail_state ];
2053 fail_base = aho->states[ fail_state ].trans.base;
2054 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2056 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2057 fail[ ch_state ] = fail_state;
2058 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2060 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
2062 q[ q_write++ % numstates] = ch_state;
2066 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2067 when we fail in state 1, this allows us to use the
2068 charclass scan to find a valid start char. This is based on the principle
2069 that theres a good chance the string being searched contains lots of stuff
2070 that cant be a start char.
2072 fail[ 0 ] = fail[ 1 ] = 0;
2073 DEBUG_TRIE_COMPILE_r({
2074 PerlIO_printf(Perl_debug_log, "%*sStclass Failtable (%"UVuf" states): 0",
2075 (int)(depth * 2), "", numstates
2077 for( q_read=1; q_read<numstates; q_read++ ) {
2078 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2080 PerlIO_printf(Perl_debug_log, "\n");
2083 /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2088 * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2089 * These need to be revisited when a newer toolchain becomes available.
2091 #if defined(__sparc64__) && defined(__GNUC__)
2092 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2093 # undef SPARC64_GCC_WORKAROUND
2094 # define SPARC64_GCC_WORKAROUND 1
2098 #define DEBUG_PEEP(str,scan,depth) \
2099 DEBUG_OPTIMISE_r({ \
2100 SV * const mysv=sv_newmortal(); \
2101 regnode *Next = regnext(scan); \
2102 regprop(RExC_rx, mysv, scan); \
2103 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
2104 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2105 Next ? (REG_NODE_NUM(Next)) : 0 ); \
2112 #define JOIN_EXACT(scan,min,flags) \
2113 if (PL_regkind[OP(scan)] == EXACT) \
2114 join_exact(pRExC_state,(scan),(min),(flags),NULL,depth+1)
2117 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, I32 *min, U32 flags,regnode *val, U32 depth) {
2118 /* Merge several consecutive EXACTish nodes into one. */
2119 regnode *n = regnext(scan);
2121 regnode *next = scan + NODE_SZ_STR(scan);
2125 regnode *stop = scan;
2126 GET_RE_DEBUG_FLAGS_DECL;
2128 PERL_UNUSED_ARG(depth);
2130 #ifndef EXPERIMENTAL_INPLACESCAN
2131 PERL_UNUSED_ARG(flags);
2132 PERL_UNUSED_ARG(val);
2134 DEBUG_PEEP("join",scan,depth);
2136 /* Skip NOTHING, merge EXACT*. */
2138 ( PL_regkind[OP(n)] == NOTHING ||
2139 (stringok && (OP(n) == OP(scan))))
2141 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
2143 if (OP(n) == TAIL || n > next)
2145 if (PL_regkind[OP(n)] == NOTHING) {
2146 DEBUG_PEEP("skip:",n,depth);
2147 NEXT_OFF(scan) += NEXT_OFF(n);
2148 next = n + NODE_STEP_REGNODE;
2155 else if (stringok) {
2156 const unsigned int oldl = STR_LEN(scan);
2157 regnode * const nnext = regnext(n);
2159 DEBUG_PEEP("merg",n,depth);
2162 if (oldl + STR_LEN(n) > U8_MAX)
2164 NEXT_OFF(scan) += NEXT_OFF(n);
2165 STR_LEN(scan) += STR_LEN(n);
2166 next = n + NODE_SZ_STR(n);
2167 /* Now we can overwrite *n : */
2168 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2176 #ifdef EXPERIMENTAL_INPLACESCAN
2177 if (flags && !NEXT_OFF(n)) {
2178 DEBUG_PEEP("atch", val, depth);
2179 if (reg_off_by_arg[OP(n)]) {
2180 ARG_SET(n, val - n);
2183 NEXT_OFF(n) = val - n;
2190 if (UTF && ( OP(scan) == EXACTF ) && ( STR_LEN(scan) >= 6 ) ) {
2192 Two problematic code points in Unicode casefolding of EXACT nodes:
2194 U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2195 U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2201 U+03B9 U+0308 U+0301 0xCE 0xB9 0xCC 0x88 0xCC 0x81
2202 U+03C5 U+0308 U+0301 0xCF 0x85 0xCC 0x88 0xCC 0x81
2204 This means that in case-insensitive matching (or "loose matching",
2205 as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte
2206 length of the above casefolded versions) can match a target string
2207 of length two (the byte length of UTF-8 encoded U+0390 or U+03B0).
2208 This would rather mess up the minimum length computation.
2210 What we'll do is to look for the tail four bytes, and then peek
2211 at the preceding two bytes to see whether we need to decrease
2212 the minimum length by four (six minus two).
2214 Thanks to the design of UTF-8, there cannot be false matches:
2215 A sequence of valid UTF-8 bytes cannot be a subsequence of
2216 another valid sequence of UTF-8 bytes.
2219 char * const s0 = STRING(scan), *s, *t;
2220 char * const s1 = s0 + STR_LEN(scan) - 1;
2221 char * const s2 = s1 - 4;
2222 #ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2223 const char t0[] = "\xaf\x49\xaf\x42";
2225 const char t0[] = "\xcc\x88\xcc\x81";
2227 const char * const t1 = t0 + 3;
2230 s < s2 && (t = ninstr(s, s1, t0, t1));
2233 if (((U8)t[-1] == 0x68 && (U8)t[-2] == 0xB4) ||
2234 ((U8)t[-1] == 0x46 && (U8)t[-2] == 0xB5))
2236 if (((U8)t[-1] == 0xB9 && (U8)t[-2] == 0xCE) ||
2237 ((U8)t[-1] == 0x85 && (U8)t[-2] == 0xCF))
2245 n = scan + NODE_SZ_STR(scan);
2247 if (PL_regkind[OP(n)] != NOTHING || OP(n) == NOTHING) {
2254 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2258 /* REx optimizer. Converts nodes into quickier variants "in place".
2259 Finds fixed substrings. */
2261 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
2262 to the position after last scanned or to NULL. */
2267 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
2268 I32 *minlenp, I32 *deltap,
2269 regnode *last, scan_data_t *data, U32 flags, U32 depth)
2270 /* scanp: Start here (read-write). */
2271 /* deltap: Write maxlen-minlen here. */
2272 /* last: Stop before this one. */
2275 I32 min = 0, pars = 0, code;
2276 regnode *scan = *scanp, *next;
2278 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
2279 int is_inf_internal = 0; /* The studied chunk is infinite */
2280 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2281 scan_data_t data_fake;
2282 struct regnode_charclass_class and_with; /* Valid if flags & SCF_DO_STCLASS_OR */
2283 SV *re_trie_maxbuff = NULL;
2284 regnode *first_non_open = scan;
2287 GET_RE_DEBUG_FLAGS_DECL;
2289 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
2292 while (first_non_open && OP(first_non_open) == OPEN)
2293 first_non_open=regnext(first_non_open);
2297 while (scan && OP(scan) != END && scan < last) {
2298 /* Peephole optimizer: */
2299 DEBUG_STUDYDATA(data,depth);
2300 DEBUG_PEEP("Peep",scan,depth);
2301 JOIN_EXACT(scan,&min,0);
2303 /* Follow the next-chain of the current node and optimize
2304 away all the NOTHINGs from it. */
2305 if (OP(scan) != CURLYX) {
2306 const int max = (reg_off_by_arg[OP(scan)]
2308 /* I32 may be smaller than U16 on CRAYs! */
2309 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
2310 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
2314 /* Skip NOTHING and LONGJMP. */
2315 while ((n = regnext(n))
2316 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
2317 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
2318 && off + noff < max)
2320 if (reg_off_by_arg[OP(scan)])
2323 NEXT_OFF(scan) = off;
2328 /* The principal pseudo-switch. Cannot be a switch, since we
2329 look into several different things. */
2330 if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
2331 || OP(scan) == IFTHEN || OP(scan) == SUSPEND) {
2332 next = regnext(scan);
2334 /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
2336 if (OP(next) == code || code == IFTHEN || code == SUSPEND) {
2337 /* NOTE - There is similar code to this block below for handling
2338 TRIE nodes on a re-study. If you change stuff here check there
2340 I32 max1 = 0, min1 = I32_MAX, num = 0;
2341 struct regnode_charclass_class accum;
2342 regnode * const startbranch=scan;
2344 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
2345 scan_commit(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
2346 if (flags & SCF_DO_STCLASS)
2347 cl_init_zero(pRExC_state, &accum);
2349 while (OP(scan) == code) {
2350 I32 deltanext, minnext, f = 0, fake;
2351 struct regnode_charclass_class this_class;
2354 data_fake.flags = 0;
2356 data_fake.whilem_c = data->whilem_c;
2357 data_fake.last_closep = data->last_closep;
2360 data_fake.last_closep = &fake;
2361 next = regnext(scan);
2362 scan = NEXTOPER(scan);
2364 scan = NEXTOPER(scan);
2365 if (flags & SCF_DO_STCLASS) {
2366 cl_init(pRExC_state, &this_class);
2367 data_fake.start_class = &this_class;
2368 f = SCF_DO_STCLASS_AND;
2370 if (flags & SCF_WHILEM_VISITED_POS)
2371 f |= SCF_WHILEM_VISITED_POS;
2373 /* we suppose the run is continuous, last=next...*/
2374 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2375 next, &data_fake, f,depth+1);
2378 if (max1 < minnext + deltanext)
2379 max1 = minnext + deltanext;
2380 if (deltanext == I32_MAX)
2381 is_inf = is_inf_internal = 1;
2383 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
2386 if (data_fake.flags & SF_HAS_EVAL)
2387 data->flags |= SF_HAS_EVAL;
2388 data->whilem_c = data_fake.whilem_c;
2390 if (flags & SCF_DO_STCLASS)
2391 cl_or(pRExC_state, &accum, &this_class);
2392 if (code == SUSPEND)
2395 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
2397 if (flags & SCF_DO_SUBSTR) {
2398 data->pos_min += min1;
2399 data->pos_delta += max1 - min1;
2400 if (max1 != min1 || is_inf)
2401 data->longest = &(data->longest_float);
2404 delta += max1 - min1;
2405 if (flags & SCF_DO_STCLASS_OR) {
2406 cl_or(pRExC_state, data->start_class, &accum);
2408 cl_and(data->start_class, &and_with);
2409 flags &= ~SCF_DO_STCLASS;
2412 else if (flags & SCF_DO_STCLASS_AND) {
2414 cl_and(data->start_class, &accum);
2415 flags &= ~SCF_DO_STCLASS;
2418 /* Switch to OR mode: cache the old value of
2419 * data->start_class */
2420 StructCopy(data->start_class, &and_with,
2421 struct regnode_charclass_class);
2422 flags &= ~SCF_DO_STCLASS_AND;
2423 StructCopy(&accum, data->start_class,
2424 struct regnode_charclass_class);
2425 flags |= SCF_DO_STCLASS_OR;
2426 data->start_class->flags |= ANYOF_EOS;
2430 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
2433 Assuming this was/is a branch we are dealing with: 'scan' now
2434 points at the item that follows the branch sequence, whatever
2435 it is. We now start at the beginning of the sequence and look
2442 which would be constructed from a pattern like /A|LIST|OF|WORDS/
2444 If we can find such a subseqence we need to turn the first
2445 element into a trie and then add the subsequent branch exact
2446 strings to the trie.
2450 1. patterns where the whole set of branch can be converted.
2452 2. patterns where only a subset can be converted.
2454 In case 1 we can replace the whole set with a single regop
2455 for the trie. In case 2 we need to keep the start and end
2458 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
2459 becomes BRANCH TRIE; BRANCH X;
2461 There is an additional case, that being where there is a
2462 common prefix, which gets split out into an EXACT like node
2463 preceding the TRIE node.
2465 If x(1..n)==tail then we can do a simple trie, if not we make
2466 a "jump" trie, such that when we match the appropriate word
2467 we "jump" to the appopriate tail node. Essentailly we turn
2468 a nested if into a case structure of sorts.
2473 if (!re_trie_maxbuff) {
2474 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2475 if (!SvIOK(re_trie_maxbuff))
2476 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2478 if ( SvIV(re_trie_maxbuff)>=0 ) {
2480 regnode *first = (regnode *)NULL;
2481 regnode *last = (regnode *)NULL;
2482 regnode *tail = scan;
2487 SV * const mysv = sv_newmortal(); /* for dumping */
2489 /* var tail is used because there may be a TAIL
2490 regop in the way. Ie, the exacts will point to the
2491 thing following the TAIL, but the last branch will
2492 point at the TAIL. So we advance tail. If we
2493 have nested (?:) we may have to move through several
2497 while ( OP( tail ) == TAIL ) {
2498 /* this is the TAIL generated by (?:) */
2499 tail = regnext( tail );
2504 regprop(RExC_rx, mysv, tail );
2505 PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
2506 (int)depth * 2 + 2, "",
2507 "Looking for TRIE'able sequences. Tail node is: ",
2508 SvPV_nolen_const( mysv )
2514 step through the branches, cur represents each
2515 branch, noper is the first thing to be matched
2516 as part of that branch and noper_next is the
2517 regnext() of that node. if noper is an EXACT
2518 and noper_next is the same as scan (our current
2519 position in the regex) then the EXACT branch is
2520 a possible optimization target. Once we have
2521 two or more consequetive such branches we can
2522 create a trie of the EXACT's contents and stich
2523 it in place. If the sequence represents all of
2524 the branches we eliminate the whole thing and
2525 replace it with a single TRIE. If it is a
2526 subsequence then we need to stitch it in. This
2527 means the first branch has to remain, and needs
2528 to be repointed at the item on the branch chain
2529 following the last branch optimized. This could
2530 be either a BRANCH, in which case the
2531 subsequence is internal, or it could be the
2532 item following the branch sequence in which
2533 case the subsequence is at the end.
2537 /* dont use tail as the end marker for this traverse */
2538 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
2539 regnode * const noper = NEXTOPER( cur );
2540 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
2541 regnode * const noper_next = regnext( noper );
2545 regprop(RExC_rx, mysv, cur);
2546 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
2547 (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
2549 regprop(RExC_rx, mysv, noper);
2550 PerlIO_printf( Perl_debug_log, " -> %s",
2551 SvPV_nolen_const(mysv));
2554 regprop(RExC_rx, mysv, noper_next );
2555 PerlIO_printf( Perl_debug_log,"\t=> %s\t",
2556 SvPV_nolen_const(mysv));
2558 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
2559 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
2561 if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
2562 : PL_regkind[ OP( noper ) ] == EXACT )
2563 || OP(noper) == NOTHING )
2565 && noper_next == tail
2570 if ( !first || optype == NOTHING ) {
2571 if (!first) first = cur;
2572 optype = OP( noper );
2578 make_trie( pRExC_state,
2579 startbranch, first, cur, tail, count,
2582 if ( PL_regkind[ OP( noper ) ] == EXACT
2584 && noper_next == tail
2589 optype = OP( noper );
2599 regprop(RExC_rx, mysv, cur);
2600 PerlIO_printf( Perl_debug_log,
2601 "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
2602 "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
2606 made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
2607 #ifdef TRIE_STUDY_OPT
2608 if ( ((made == MADE_EXACT_TRIE &&
2609 startbranch == first)
2610 || ( first_non_open == first )) &&
2612 flags |= SCF_TRIE_RESTUDY;
2620 else if ( code == BRANCHJ ) { /* single branch is optimized. */
2621 scan = NEXTOPER(NEXTOPER(scan));
2622 } else /* single branch is optimized. */
2623 scan = NEXTOPER(scan);
2626 else if (OP(scan) == EXACT) {
2627 I32 l = STR_LEN(scan);
2630 const U8 * const s = (U8*)STRING(scan);
2631 l = utf8_length(s, s + l);
2632 uc = utf8_to_uvchr(s, NULL);
2634 uc = *((U8*)STRING(scan));
2637 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
2638 /* The code below prefers earlier match for fixed
2639 offset, later match for variable offset. */
2640 if (data->last_end == -1) { /* Update the start info. */
2641 data->last_start_min = data->pos_min;
2642 data->last_start_max = is_inf
2643 ? I32_MAX : data->pos_min + data->pos_delta;
2645 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
2647 SvUTF8_on(data->last_found);
2649 SV * const sv = data->last_found;
2650 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
2651 mg_find(sv, PERL_MAGIC_utf8) : NULL;
2652 if (mg && mg->mg_len >= 0)
2653 mg->mg_len += utf8_length((U8*)STRING(scan),
2654 (U8*)STRING(scan)+STR_LEN(scan));
2656 data->last_end = data->pos_min + l;
2657 data->pos_min += l; /* As in the first entry. */
2658 data->flags &= ~SF_BEFORE_EOL;
2660 if (flags & SCF_DO_STCLASS_AND) {
2661 /* Check whether it is compatible with what we know already! */
2665 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2666 && !ANYOF_BITMAP_TEST(data->start_class, uc)
2667 && (!(data->start_class->flags & ANYOF_FOLD)
2668 || !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2671 ANYOF_CLASS_ZERO(data->start_class);
2672 ANYOF_BITMAP_ZERO(data->start_class);
2674 ANYOF_BITMAP_SET(data->start_class, uc);
2675 data->start_class->flags &= ~ANYOF_EOS;
2677 data->start_class->flags &= ~ANYOF_UNICODE_ALL;
2679 else if (flags & SCF_DO_STCLASS_OR) {
2680 /* false positive possible if the class is case-folded */
2682 ANYOF_BITMAP_SET(data->start_class, uc);
2684 data->start_class->flags |= ANYOF_UNICODE_ALL;
2685 data->start_class->flags &= ~ANYOF_EOS;
2686 cl_and(data->start_class, &and_with);
2688 flags &= ~SCF_DO_STCLASS;
2690 else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
2691 I32 l = STR_LEN(scan);
2692 UV uc = *((U8*)STRING(scan));
2694 /* Search for fixed substrings supports EXACT only. */
2695 if (flags & SCF_DO_SUBSTR) {
2697 scan_commit(pRExC_state, data, minlenp);
2700 const U8 * const s = (U8 *)STRING(scan);
2701 l = utf8_length(s, s + l);
2702 uc = utf8_to_uvchr(s, NULL);
2705 if (flags & SCF_DO_SUBSTR)
2707 if (flags & SCF_DO_STCLASS_AND) {
2708 /* Check whether it is compatible with what we know already! */
2712 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2713 && !ANYOF_BITMAP_TEST(data->start_class, uc)
2714 && !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2716 ANYOF_CLASS_ZERO(data->start_class);
2717 ANYOF_BITMAP_ZERO(data->start_class);
2719 ANYOF_BITMAP_SET(data->start_class, uc);
2720 data->start_class->flags &= ~ANYOF_EOS;
2721 data->start_class->flags |= ANYOF_FOLD;
2722 if (OP(scan) == EXACTFL)
2723 data->start_class->flags |= ANYOF_LOCALE;
2726 else if (flags & SCF_DO_STCLASS_OR) {
2727 if (data->start_class->flags & ANYOF_FOLD) {
2728 /* false positive possible if the class is case-folded.
2729 Assume that the locale settings are the same... */
2731 ANYOF_BITMAP_SET(data->start_class, uc);
2732 data->start_class->flags &= ~ANYOF_EOS;
2734 cl_and(data->start_class, &and_with);
2736 flags &= ~SCF_DO_STCLASS;
2738 else if (strchr((const char*)PL_varies,OP(scan))) {
2739 I32 mincount, maxcount, minnext, deltanext, fl = 0;
2740 I32 f = flags, pos_before = 0;
2741 regnode * const oscan = scan;
2742 struct regnode_charclass_class this_class;
2743 struct regnode_charclass_class *oclass = NULL;
2744 I32 next_is_eval = 0;
2746 switch (PL_regkind[OP(scan)]) {
2747 case WHILEM: /* End of (?:...)* . */
2748 scan = NEXTOPER(scan);
2751 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
2752 next = NEXTOPER(scan);
2753 if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
2755 maxcount = REG_INFTY;
2756 next = regnext(scan);
2757 scan = NEXTOPER(scan);
2761 if (flags & SCF_DO_SUBSTR)
2766 if (flags & SCF_DO_STCLASS) {
2768 maxcount = REG_INFTY;
2769 next = regnext(scan);
2770 scan = NEXTOPER(scan);
2773 is_inf = is_inf_internal = 1;
2774 scan = regnext(scan);
2775 if (flags & SCF_DO_SUBSTR) {
2776 scan_commit(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
2777 data->longest = &(data->longest_float);
2779 goto optimize_curly_tail;
2781 mincount = ARG1(scan);
2782 maxcount = ARG2(scan);
2783 next = regnext(scan);
2784 if (OP(scan) == CURLYX) {
2785 I32 lp = (data ? *(data->last_closep) : 0);
2786 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
2788 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
2789 next_is_eval = (OP(scan) == EVAL);
2791 if (flags & SCF_DO_SUBSTR) {
2792 if (mincount == 0) scan_commit(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
2793 pos_before = data->pos_min;
2797 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
2799 data->flags |= SF_IS_INF;
2801 if (flags & SCF_DO_STCLASS) {
2802 cl_init(pRExC_state, &this_class);
2803 oclass = data->start_class;
2804 data->start_class = &this_class;
2805 f |= SCF_DO_STCLASS_AND;
2806 f &= ~SCF_DO_STCLASS_OR;
2808 /* These are the cases when once a subexpression
2809 fails at a particular position, it cannot succeed
2810 even after backtracking at the enclosing scope.
2812 XXXX what if minimal match and we are at the
2813 initial run of {n,m}? */
2814 if ((mincount != maxcount - 1) && (maxcount != REG_INFTY))
2815 f &= ~SCF_WHILEM_VISITED_POS;
2817 /* This will finish on WHILEM, setting scan, or on NULL: */
2818 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, last, data,
2820 ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
2822 if (flags & SCF_DO_STCLASS)
2823 data->start_class = oclass;
2824 if (mincount == 0 || minnext == 0) {
2825 if (flags & SCF_DO_STCLASS_OR) {
2826 cl_or(pRExC_state, data->start_class, &this_class);
2828 else if (flags & SCF_DO_STCLASS_AND) {
2829 /* Switch to OR mode: cache the old value of
2830 * data->start_class */
2831 StructCopy(data->start_class, &and_with,
2832 struct regnode_charclass_class);
2833 flags &= ~SCF_DO_STCLASS_AND;
2834 StructCopy(&this_class, data->start_class,
2835 struct regnode_charclass_class);
2836 flags |= SCF_DO_STCLASS_OR;
2837 data->start_class->flags |= ANYOF_EOS;
2839 } else { /* Non-zero len */
2840 if (flags & SCF_DO_STCLASS_OR) {
2841 cl_or(pRExC_state, data->start_class, &this_class);
2842 cl_and(data->start_class, &and_with);
2844 else if (flags & SCF_DO_STCLASS_AND)
2845 cl_and(data->start_class, &this_class);
2846 flags &= ~SCF_DO_STCLASS;
2848 if (!scan) /* It was not CURLYX, but CURLY. */
2850 if ( /* ? quantifier ok, except for (?{ ... }) */
2851 (next_is_eval || !(mincount == 0 && maxcount == 1))
2852 && (minnext == 0) && (deltanext == 0)
2853 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
2854 && maxcount <= REG_INFTY/3 /* Complement check for big count */
2855 && ckWARN(WARN_REGEXP))
2858 "Quantifier unexpected on zero-length expression");
2861 min += minnext * mincount;
2862 is_inf_internal |= ((maxcount == REG_INFTY
2863 && (minnext + deltanext) > 0)
2864 || deltanext == I32_MAX);
2865 is_inf |= is_inf_internal;
2866 delta += (minnext + deltanext) * maxcount - minnext * mincount;
2868 /* Try powerful optimization CURLYX => CURLYN. */
2869 if ( OP(oscan) == CURLYX && data
2870 && data->flags & SF_IN_PAR
2871 && !(data->flags & SF_HAS_EVAL)
2872 && !deltanext && minnext == 1 ) {
2873 /* Try to optimize to CURLYN. */
2874 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
2875 regnode * const nxt1 = nxt;
2882 if (!strchr((const char*)PL_simple,OP(nxt))
2883 && !(PL_regkind[OP(nxt)] == EXACT
2884 && STR_LEN(nxt) == 1))
2890 if (OP(nxt) != CLOSE)
2892 /* Now we know that nxt2 is the only contents: */
2893 oscan->flags = (U8)ARG(nxt);
2895 OP(nxt1) = NOTHING; /* was OPEN. */
2897 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
2898 NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
2899 NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
2900 OP(nxt) = OPTIMIZED; /* was CLOSE. */
2901 OP(nxt + 1) = OPTIMIZED; /* was count. */
2902 NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
2907 /* Try optimization CURLYX => CURLYM. */
2908 if ( OP(oscan) == CURLYX && data
2909 && !(data->flags & SF_HAS_PAR)
2910 && !(data->flags & SF_HAS_EVAL)
2911 && !deltanext /* atom is fixed width */
2912 && minnext != 0 /* CURLYM can't handle zero width */
2914 /* XXXX How to optimize if data == 0? */
2915 /* Optimize to a simpler form. */
2916 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
2920 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
2921 && (OP(nxt2) != WHILEM))
2923 OP(nxt2) = SUCCEED; /* Whas WHILEM */
2924 /* Need to optimize away parenths. */
2925 if (data->flags & SF_IN_PAR) {
2926 /* Set the parenth number. */
2927 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
2929 if (OP(nxt) != CLOSE)
2930 FAIL("Panic opt close");
2931 oscan->flags = (U8)ARG(nxt);
2932 OP(nxt1) = OPTIMIZED; /* was OPEN. */
2933 OP(nxt) = OPTIMIZED; /* was CLOSE. */
2935 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
2936 OP(nxt + 1) = OPTIMIZED; /* was count. */
2937 NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
2938 NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
2941 while ( nxt1 && (OP(nxt1) != WHILEM)) {
2942 regnode *nnxt = regnext(nxt1);
2945 if (reg_off_by_arg[OP(nxt1)])
2946 ARG_SET(nxt1, nxt2 - nxt1);
2947 else if (nxt2 - nxt1 < U16_MAX)
2948 NEXT_OFF(nxt1) = nxt2 - nxt1;
2950 OP(nxt) = NOTHING; /* Cannot beautify */
2955 /* Optimize again: */
2956 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
2962 else if ((OP(oscan) == CURLYX)
2963 && (flags & SCF_WHILEM_VISITED_POS)
2964 /* See the comment on a similar expression above.
2965 However, this time it not a subexpression
2966 we care about, but the expression itself. */
2967 && (maxcount == REG_INFTY)
2968 && data && ++data->whilem_c < 16) {
2969 /* This stays as CURLYX, we can put the count/of pair. */
2970 /* Find WHILEM (as in regexec.c) */
2971 regnode *nxt = oscan + NEXT_OFF(oscan);
2973 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
2975 PREVOPER(nxt)->flags = (U8)(data->whilem_c
2976 | (RExC_whilem_seen << 4)); /* On WHILEM */
2978 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
2980 if (flags & SCF_DO_SUBSTR) {
2981 SV *last_str = NULL;
2982 int counted = mincount != 0;
2984 if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
2985 #if defined(SPARC64_GCC_WORKAROUND)
2988 const char *s = NULL;
2991 if (pos_before >= data->last_start_min)
2994 b = data->last_start_min;
2997 s = SvPV_const(data->last_found, l);
2998 old = b - data->last_start_min;
3001 I32 b = pos_before >= data->last_start_min
3002 ? pos_before : data->last_start_min;
3004 const char * const s = SvPV_const(data->last_found, l);
3005 I32 old = b - data->last_start_min;
3009 old = utf8_hop((U8*)s, old) - (U8*)s;
3012 /* Get the added string: */
3013 last_str = newSVpvn(s + old, l);
3015 SvUTF8_on(last_str);
3016 if (deltanext == 0 && pos_before == b) {
3017 /* What was added is a constant string */
3019 SvGROW(last_str, (mincount * l) + 1);
3020 repeatcpy(SvPVX(last_str) + l,
3021 SvPVX_const(last_str), l, mincount - 1);
3022 SvCUR_set(last_str, SvCUR(last_str) * mincount);
3023 /* Add additional parts. */
3024 SvCUR_set(data->last_found,
3025 SvCUR(data->last_found) - l);
3026 sv_catsv(data->last_found, last_str);
3028 SV * sv = data->last_found;
3030 SvUTF8(sv) && SvMAGICAL(sv) ?
3031 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3032 if (mg && mg->mg_len >= 0)
3033 mg->mg_len += CHR_SVLEN(last_str);
3035 data->last_end += l * (mincount - 1);
3038 /* start offset must point into the last copy */
3039 data->last_start_min += minnext * (mincount - 1);
3040 data->last_start_max += is_inf ? I32_MAX
3041 : (maxcount - 1) * (minnext + data->pos_delta);
3044 /* It is counted once already... */
3045 data->pos_min += minnext * (mincount - counted);
3046 data->pos_delta += - counted * deltanext +
3047 (minnext + deltanext) * maxcount - minnext * mincount;
3048 if (mincount != maxcount) {
3049 /* Cannot extend fixed substrings found inside
3051 scan_commit(pRExC_state,data,minlenp);
3052 if (mincount && last_str) {
3053 SV * const sv = data->last_found;
3054 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3055 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3059 sv_setsv(sv, last_str);
3060 data->last_end = data->pos_min;
3061 data->last_start_min =
3062 data->pos_min - CHR_SVLEN(last_str);
3063 data->last_start_max = is_inf
3065 : data->pos_min + data->pos_delta
3066 - CHR_SVLEN(last_str);
3068 data->longest = &(data->longest_float);
3070 SvREFCNT_dec(last_str);
3072 if (data && (fl & SF_HAS_EVAL))
3073 data->flags |= SF_HAS_EVAL;
3074 optimize_curly_tail:
3075 if (OP(oscan) != CURLYX) {
3076 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
3078 NEXT_OFF(oscan) += NEXT_OFF(next);
3081 default: /* REF and CLUMP only? */
3082 if (flags & SCF_DO_SUBSTR) {
3083 scan_commit(pRExC_state,data,minlenp); /* Cannot expect anything... */
3084 data->longest = &(data->longest_float);
3086 is_inf = is_inf_internal = 1;
3087 if (flags & SCF_DO_STCLASS_OR)
3088 cl_anything(pRExC_state, data->start_class);
3089 flags &= ~SCF_DO_STCLASS;
3093 else if (strchr((const char*)PL_simple,OP(scan))) {
3096 if (flags & SCF_DO_SUBSTR) {
3097 scan_commit(pRExC_state,data,minlenp);
3101 if (flags & SCF_DO_STCLASS) {
3102 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3104 /* Some of the logic below assumes that switching
3105 locale on will only add false positives. */
3106 switch (PL_regkind[OP(scan)]) {
3110 /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
3111 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3112 cl_anything(pRExC_state, data->start_class);
3115 if (OP(scan) == SANY)
3117 if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
3118 value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
3119 || (data->start_class->flags & ANYOF_CLASS));
3120 cl_anything(pRExC_state, data->start_class);
3122 if (flags & SCF_DO_STCLASS_AND || !value)
3123 ANYOF_BITMAP_CLEAR(data->start_class,'\n');
3126 if (flags & SCF_DO_STCLASS_AND)
3127 cl_and(data->start_class,
3128 (struct regnode_charclass_class*)scan);
3130 cl_or(pRExC_state, data->start_class,
3131 (struct regnode_charclass_class*)scan);
3134 if (flags & SCF_DO_STCLASS_AND) {
3135 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3136 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3137 for (value = 0; value < 256; value++)
3138 if (!isALNUM(value))
3139 ANYOF_BITMAP_CLEAR(data->start_class, value);
3143 if (data->start_class->flags & ANYOF_LOCALE)
3144 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3146 for (value = 0; value < 256; value++)
3148 ANYOF_BITMAP_SET(data->start_class, value);
3153 if (flags & SCF_DO_STCLASS_AND) {
3154 if (data->start_class->flags & ANYOF_LOCALE)
3155 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3158 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3159 data->start_class->flags |= ANYOF_LOCALE;
3163 if (flags & SCF_DO_STCLASS_AND) {
3164 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3165 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3166 for (value = 0; value < 256; value++)
3168 ANYOF_BITMAP_CLEAR(data->start_class, value);
3172 if (data->start_class->flags & ANYOF_LOCALE)
3173 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3175 for (value = 0; value < 256; value++)
3176 if (!isALNUM(value))
3177 ANYOF_BITMAP_SET(data->start_class, value);
3182 if (flags & SCF_DO_STCLASS_AND) {
3183 if (data->start_class->flags & ANYOF_LOCALE)
3184 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3187 data->start_class->flags |= ANYOF_LOCALE;
3188 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3192 if (flags & SCF_DO_STCLASS_AND) {
3193 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3194 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3195 for (value = 0; value < 256; value++)
3196 if (!isSPACE(value))
3197 ANYOF_BITMAP_CLEAR(data->start_class, value);
3201 if (data->start_class->flags & ANYOF_LOCALE)
3202 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3204 for (value = 0; value < 256; value++)
3206 ANYOF_BITMAP_SET(data->start_class, value);
3211 if (flags & SCF_DO_STCLASS_AND) {
3212 if (data->start_class->flags & ANYOF_LOCALE)
3213 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3216 data->start_class->flags |= ANYOF_LOCALE;
3217 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3221 if (flags & SCF_DO_STCLASS_AND) {
3222 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3223 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3224 for (value = 0; value < 256; value++)
3226 ANYOF_BITMAP_CLEAR(data->start_class, value);
3230 if (data->start_class->flags & ANYOF_LOCALE)
3231 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3233 for (value = 0; value < 256; value++)
3234 if (!isSPACE(value))
3235 ANYOF_BITMAP_SET(data->start_class, value);
3240 if (flags & SCF_DO_STCLASS_AND) {
3241 if (data->start_class->flags & ANYOF_LOCALE) {
3242 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3243 for (value = 0; value < 256; value++)
3244 if (!isSPACE(value))
3245 ANYOF_BITMAP_CLEAR(data->start_class, value);
3249 data->start_class->flags |= ANYOF_LOCALE;
3250 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3254 if (flags & SCF_DO_STCLASS_AND) {
3255 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
3256 for (value = 0; value < 256; value++)
3257 if (!isDIGIT(value))
3258 ANYOF_BITMAP_CLEAR(data->start_class, value);
3261 if (data->start_class->flags & ANYOF_LOCALE)
3262 ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
3264 for (value = 0; value < 256; value++)
3266 ANYOF_BITMAP_SET(data->start_class, value);
3271 if (flags & SCF_DO_STCLASS_AND) {
3272 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
3273 for (value = 0; value < 256; value++)
3275 ANYOF_BITMAP_CLEAR(data->start_class, value);
3278 if (data->start_class->flags & ANYOF_LOCALE)
3279 ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
3281 for (value = 0; value < 256; value++)
3282 if (!isDIGIT(value))
3283 ANYOF_BITMAP_SET(data->start_class, value);
3288 if (flags & SCF_DO_STCLASS_OR)
3289 cl_and(data->start_class, &and_with);
3290 flags &= ~SCF_DO_STCLASS;
3293 else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
3294 data->flags |= (OP(scan) == MEOL
3298 else if ( PL_regkind[OP(scan)] == BRANCHJ
3299 /* Lookbehind, or need to calculate parens/evals/stclass: */
3300 && (scan->flags || data || (flags & SCF_DO_STCLASS))
3301 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
3302 if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3303 || OP(scan) == UNLESSM )
3305 /* Negative Lookahead/lookbehind
3306 In this case we can't do fixed string optimisation.
3309 I32 deltanext, minnext, fake = 0;
3311 struct regnode_charclass_class intrnl;
3314 data_fake.flags = 0;
3316 data_fake.whilem_c = data->whilem_c;
3317 data_fake.last_closep = data->last_closep;
3320 data_fake.last_closep = &fake;
3321 if ( flags & SCF_DO_STCLASS && !scan->flags
3322 && OP(scan) == IFMATCH ) { /* Lookahead */
3323 cl_init(pRExC_state, &intrnl);
3324 data_fake.start_class = &intrnl;
3325 f |= SCF_DO_STCLASS_AND;
3327 if (flags & SCF_WHILEM_VISITED_POS)
3328 f |= SCF_WHILEM_VISITED_POS;
3329 next = regnext(scan);
3330 nscan = NEXTOPER(NEXTOPER(scan));
3331 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, last, &data_fake, f,depth+1);
3334 vFAIL("Variable length lookbehind not implemented");
3336 else if (minnext > (I32)U8_MAX) {
3337 vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3339 scan->flags = (U8)minnext;
3342 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3344 if (data_fake.flags & SF_HAS_EVAL)
3345 data->flags |= SF_HAS_EVAL;
3346 data->whilem_c = data_fake.whilem_c;
3348 if (f & SCF_DO_STCLASS_AND) {
3349 const int was = (data->start_class->flags & ANYOF_EOS);
3351 cl_and(data->start_class, &intrnl);
3353 data->start_class->flags |= ANYOF_EOS;
3356 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3358 /* Positive Lookahead/lookbehind
3359 In this case we can do fixed string optimisation,
3360 but we must be careful about it. Note in the case of
3361 lookbehind the positions will be offset by the minimum
3362 length of the pattern, something we won't know about
3363 until after the recurse.
3365 I32 deltanext, fake = 0;
3367 struct regnode_charclass_class intrnl;
3369 /* We use SAVEFREEPV so that when the full compile
3370 is finished perl will clean up the allocated
3371 minlens when its all done. This was we don't
3372 have to worry about freeing them when we know
3373 they wont be used, which would be a pain.
3376 Newx( minnextp, 1, I32 );
3377 SAVEFREEPV(minnextp);
3380 StructCopy(data, &data_fake, scan_data_t);
3381 if ((flags & SCF_DO_SUBSTR) && data->last_found) {
3384 scan_commit(pRExC_state, &data_fake,minlenp);
3385 data_fake.last_found=newSVsv(data->last_found);
3389 data_fake.last_closep = &fake;
3390 data_fake.flags = 0;
3392 data_fake.flags |= SF_IS_INF;
3393 if ( flags & SCF_DO_STCLASS && !scan->flags
3394 && OP(scan) == IFMATCH ) { /* Lookahead */
3395 cl_init(pRExC_state, &intrnl);
3396 data_fake.start_class = &intrnl;
3397 f |= SCF_DO_STCLASS_AND;
3399 if (flags & SCF_WHILEM_VISITED_POS)
3400 f |= SCF_WHILEM_VISITED_POS;
3401 next = regnext(scan);
3402 nscan = NEXTOPER(NEXTOPER(scan));
3404 *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext, last, &data_fake, f,depth+1);
3407 vFAIL("Variable length lookbehind not implemented");
3409 else if (*minnextp > (I32)U8_MAX) {
3410 vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3412 scan->flags = (U8)*minnextp;
3418 if (f & SCF_DO_STCLASS_AND) {
3419 const int was = (data->start_class->flags & ANYOF_EOS);
3421 cl_and(data->start_class, &intrnl);
3423 data->start_class->flags |= ANYOF_EOS;
3426 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3428 if (data_fake.flags & SF_HAS_EVAL)
3429 data->flags |= SF_HAS_EVAL;
3430 data->whilem_c = data_fake.whilem_c;
3431 if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
3432 if (RExC_rx->minlen<*minnextp)
3433 RExC_rx->minlen=*minnextp;
3434 scan_commit(pRExC_state, &data_fake, minnextp);
3435 SvREFCNT_dec(data_fake.last_found);
3437 if ( data_fake.minlen_fixed != minlenp )
3439 data->offset_fixed= data_fake.offset_fixed;
3440 data->minlen_fixed= data_fake.minlen_fixed;
3441 data->lookbehind_fixed+= scan->flags;
3443 if ( data_fake.minlen_float != minlenp )
3445 data->minlen_float= data_fake.minlen_float;
3446 data->offset_float_min=data_fake.offset_float_min;
3447 data->offset_float_max=data_fake.offset_float_max;
3448 data->lookbehind_float+= scan->flags;
3457 else if (OP(scan) == OPEN) {
3460 else if (OP(scan) == CLOSE) {
3461 if ((I32)ARG(scan) == is_par) {
3462 next = regnext(scan);
3464 if ( next && (OP(next) != WHILEM) && next < last)
3465 is_par = 0; /* Disable optimization */
3468 *(data->last_closep) = ARG(scan);
3470 else if (OP(scan) == EVAL) {
3472 data->flags |= SF_HAS_EVAL;
3474 else if ( (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
3475 || OP(scan)==RECURSE) /* recursion */
3477 if (OP(scan)==RECURSE) {
3478 ARG2L_SET( scan, RExC_parens[ARG(scan)-1] - scan );
3480 if (flags & SCF_DO_SUBSTR) {
3481 scan_commit(pRExC_state,data,minlenp);
3482 data->longest = &(data->longest_float);
3484 is_inf = is_inf_internal = 1;
3485 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3486 cl_anything(pRExC_state, data->start_class);
3487 flags &= ~SCF_DO_STCLASS;
3489 #ifdef TRIE_STUDY_OPT
3490 #ifdef FULL_TRIE_STUDY
3491 else if (PL_regkind[OP(scan)] == TRIE) {
3492 /* NOTE - There is similar code to this block above for handling
3493 BRANCH nodes on the initial study. If you change stuff here
3495 regnode *trie_node= scan;
3496 regnode *tail= regnext(scan);
3497 reg_trie_data *trie = (reg_trie_data*)RExC_rx->data->data[ ARG(scan) ];
3498 I32 max1 = 0, min1 = I32_MAX;
3499 struct regnode_charclass_class accum;
3501 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
3502 scan_commit(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
3503 if (flags & SCF_DO_STCLASS)
3504 cl_init_zero(pRExC_state, &accum);
3510 const regnode *nextbranch= NULL;
3513 for ( word=1 ; word <= trie->wordcount ; word++)
3515 I32 deltanext=0, minnext=0, f = 0, fake;
3516 struct regnode_charclass_class this_class;
3518 data_fake.flags = 0;
3520 data_fake.whilem_c = data->whilem_c;
3521 data_fake.last_closep = data->last_closep;
3524 data_fake.last_closep = &fake;
3526 if (flags & SCF_DO_STCLASS) {
3527 cl_init(pRExC_state, &this_class);
3528 data_fake.start_class = &this_class;
3529 f = SCF_DO_STCLASS_AND;
3531 if (flags & SCF_WHILEM_VISITED_POS)
3532 f |= SCF_WHILEM_VISITED_POS;
3534 if (trie->jump[word]) {
3536 nextbranch = trie_node + trie->jump[0];
3537 scan= trie_node + trie->jump[word];
3538 /* We go from the jump point to the branch that follows
3539 it. Note this means we need the vestigal unused branches
3540 even though they arent otherwise used.
3542 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
3543 (regnode *)nextbranch, &data_fake, f,depth+1);
3545 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
3546 nextbranch= regnext((regnode*)nextbranch);
3548 if (min1 > (I32)(minnext + trie->minlen))
3549 min1 = minnext + trie->minlen;
3550 if (max1 < (I32)(minnext + deltanext + trie->maxlen))
3551 max1 = minnext + deltanext + trie->maxlen;
3552 if (deltanext == I32_MAX)
3553 is_inf = is_inf_internal = 1;
3555 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3559 if (data_fake.flags & SF_HAS_EVAL)
3560 data->flags |= SF_HAS_EVAL;
3561 data->whilem_c = data_fake.whilem_c;
3563 if (flags & SCF_DO_STCLASS)
3564 cl_or(pRExC_state, &accum, &this_class);
3567 if (flags & SCF_DO_SUBSTR) {
3568 data->pos_min += min1;
3569 data->pos_delta += max1 - min1;
3570 if (max1 != min1 || is_inf)
3571 data->longest = &(data->longest_float);
3574 delta += max1 - min1;
3575 if (flags & SCF_DO_STCLASS_OR) {
3576 cl_or(pRExC_state, data->start_class, &accum);
3578 cl_and(data->start_class, &and_with);
3579 flags &= ~SCF_DO_STCLASS;
3582 else if (flags & SCF_DO_STCLASS_AND) {
3584 cl_and(data->start_class, &accum);
3585 flags &= ~SCF_DO_STCLASS;
3588 /* Switch to OR mode: cache the old value of
3589 * data->start_class */
3590 StructCopy(data->start_class, &and_with,
3591 struct regnode_charclass_class);
3592 flags &= ~SCF_DO_STCLASS_AND;
3593 StructCopy(&accum, data->start_class,
3594 struct regnode_charclass_class);
3595 flags |= SCF_DO_STCLASS_OR;
3596 data->start_class->flags |= ANYOF_EOS;
3603 else if (PL_regkind[OP(scan)] == TRIE) {
3604 reg_trie_data *trie = (reg_trie_data*)RExC_rx->data->data[ ARG(scan) ];
3607 min += trie->minlen;
3608 delta += (trie->maxlen - trie->minlen);
3609 flags &= ~SCF_DO_STCLASS; /* xxx */
3610 if (flags & SCF_DO_SUBSTR) {
3611 scan_commit(pRExC_state,data,minlenp); /* Cannot expect anything... */
3612 data->pos_min += trie->minlen;
3613 data->pos_delta += (trie->maxlen - trie->minlen);
3614 if (trie->maxlen != trie->minlen)
3615 data->longest = &(data->longest_float);
3617 if (trie->jump) /* no more substrings -- for now /grr*/
3618 flags &= ~SCF_DO_SUBSTR;
3620 #endif /* old or new */
3621 #endif /* TRIE_STUDY_OPT */
3622 /* Else: zero-length, ignore. */
3623 scan = regnext(scan);
3628 *deltap = is_inf_internal ? I32_MAX : delta;
3629 if (flags & SCF_DO_SUBSTR && is_inf)
3630 data->pos_delta = I32_MAX - data->pos_min;
3631 if (is_par > (I32)U8_MAX)
3633 if (is_par && pars==1 && data) {
3634 data->flags |= SF_IN_PAR;
3635 data->flags &= ~SF_HAS_PAR;
3637 else if (pars && data) {
3638 data->flags |= SF_HAS_PAR;
3639 data->flags &= ~SF_IN_PAR;
3641 if (flags & SCF_DO_STCLASS_OR)
3642 cl_and(data->start_class, &and_with);
3643 if (flags & SCF_TRIE_RESTUDY)
3644 data->flags |= SCF_TRIE_RESTUDY;
3646 DEBUG_STUDYDATA(data,depth);
3652 S_add_data(RExC_state_t *pRExC_state, I32 n, const char *s)
3654 if (RExC_rx->data) {
3655 const U32 count = RExC_rx->data->count;
3656 Renewc(RExC_rx->data,
3657 sizeof(*RExC_rx->data) + sizeof(void*) * (count + n - 1),
3658 char, struct reg_data);
3659 Renew(RExC_rx->data->what, count + n, U8);
3660 RExC_rx->data->count += n;
3663 Newxc(RExC_rx->data, sizeof(*RExC_rx->data) + sizeof(void*) * (n - 1),
3664 char, struct reg_data);
3665 Newx(RExC_rx->data->what, n, U8);
3666 RExC_rx->data->count = n;
3668 Copy(s, RExC_rx->data->what + RExC_rx->data->count - n, n, U8);
3669 return RExC_rx->data->count - n;
3672 #ifndef PERL_IN_XSUB_RE
3674 Perl_reginitcolors(pTHX)
3677 const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
3679 char *t = savepv(s);
3683 t = strchr(t, '\t');
3689 PL_colors[i] = t = (char *)"";
3694 PL_colors[i++] = (char *)"";
3701 #ifdef TRIE_STUDY_OPT
3702 #define CHECK_RESTUDY_GOTO \
3704 (data.flags & SCF_TRIE_RESTUDY) \
3708 #define CHECK_RESTUDY_GOTO
3712 - pregcomp - compile a regular expression into internal code
3714 * We can't allocate space until we know how big the compiled form will be,
3715 * but we can't compile it (and thus know how big it is) until we've got a
3716 * place to put the code. So we cheat: we compile it twice, once with code
3717 * generation turned off and size counting turned on, and once "for real".
3718 * This also means that we don't allocate space until we are sure that the
3719 * thing really will compile successfully, and we never have to move the
3720 * code and thus invalidate pointers into it. (Note that it has to be in
3721 * one piece because free() must be able to free it all.) [NB: not true in perl]
3723 * Beware that the optimization-preparation code in here knows about some
3724 * of the structure of the compiled regexp. [I'll say.]
3729 #ifndef PERL_IN_XSUB_RE
3730 #define RE_ENGINE_PTR &PL_core_reg_engine
3732 extern const struct regexp_engine my_reg_engine;
3733 #define RE_ENGINE_PTR &my_reg_engine
3735 /* these make a few things look better, to avoid indentation */
3736 #define BEGIN_BLOCK {
3740 Perl_pregcomp(pTHX_ char *exp, char *xend, PMOP *pm)
3743 GET_RE_DEBUG_FLAGS_DECL;
3744 DEBUG_r(if (!PL_colorset) reginitcolors());
3745 #ifndef PERL_IN_XSUB_RE
3747 /* Dispatch a request to compile a regexp to correct
3749 HV * const table = GvHV(PL_hintgv);
3751 SV **ptr= hv_fetchs(table, "regcomp", FALSE);
3752 if (ptr && SvIOK(*ptr) && SvIV(*ptr)) {
3753 const regexp_engine *eng=INT2PTR(regexp_engine*,SvIV(*ptr));
3755 PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
3758 return CALLREGCOMP_ENG(eng, exp, xend, pm);
3772 RExC_state_t RExC_state;
3773 RExC_state_t * const pRExC_state = &RExC_state;
3774 #ifdef TRIE_STUDY_OPT
3776 RExC_state_t copyRExC_state;
3779 FAIL("NULL regexp argument");
3781 RExC_utf8 = pm->op_pmdynflags & PMdf_CMP_UTF8;
3785 SV *dsv= sv_newmortal();
3786 RE_PV_QUOTED_DECL(s, RExC_utf8,
3787 dsv, RExC_precomp, (xend - exp), 60);
3788 PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
3789 PL_colors[4],PL_colors[5],s);
3791 RExC_flags = pm->op_pmflags;
3795 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
3796 RExC_seen_evals = 0;
3799 /* First pass: determine size, legality. */
3806 RExC_emit = &PL_regdummy;
3807 RExC_whilem_seen = 0;
3808 RExC_charnames = NULL;
3810 RExC_paren_names = NULL;
3812 #if 0 /* REGC() is (currently) a NOP at the first pass.
3813 * Clever compilers notice this and complain. --jhi */
3814 REGC((U8)REG_MAGIC, (char*)RExC_emit);
3816 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n"));
3817 if (reg(pRExC_state, 0, &flags,1) == NULL) {
3818 RExC_precomp = NULL;
3822 PerlIO_printf(Perl_debug_log,
3823 "Required size %"IVdf" nodes\n"
3824 "Starting second pass (creation)\n",
3827 RExC_lastparse=NULL;
3829 /* Small enough for pointer-storage convention?
3830 If extralen==0, this means that we will not need long jumps. */
3831 if (RExC_size >= 0x10000L && RExC_extralen)
3832 RExC_size += RExC_extralen;
3835 if (RExC_whilem_seen > 15)
3836 RExC_whilem_seen = 15;
3838 /* Allocate space and zero-initialize. Note, the two step process
3839 of zeroing when in debug mode, thus anything assigned has to
3840 happen after that */
3841 Newxc(r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode),
3844 FAIL("Regexp out of space");
3846 /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
3847 Zero(r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode), char);
3849 /* initialization begins here */
3850 r->engine= RE_ENGINE_PTR;
3852 r->prelen = xend - exp;
3853 r->precomp = savepvn(RExC_precomp, r->prelen);
3855 #ifdef PERL_OLD_COPY_ON_WRITE
3856 r->saved_copy = NULL;
3858 r->reganch = pm->op_pmflags & PMf_COMPILETIME;
3859 r->nparens = RExC_npar - 1; /* set early to validate backrefs */
3860 r->lastparen = 0; /* mg.c reads this. */
3862 r->substrs = 0; /* Useful during FAIL. */
3863 r->startp = 0; /* Useful during FAIL. */
3867 if (RExC_seen & REG_SEEN_RECURSE) {
3868 Newxz(RExC_parens, RExC_npar,regnode *);
3869 SAVEFREEPV(RExC_parens);
3872 /* Useful during FAIL. */
3873 Newxz(r->offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
3875 r->offsets[0] = RExC_size;
3877 DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
3878 "%s %"UVuf" bytes for offset annotations.\n",
3879 r->offsets ? "Got" : "Couldn't get",
3880 (UV)((2*RExC_size+1) * sizeof(U32))));
3884 /* Second pass: emit code. */
3885 RExC_flags = pm->op_pmflags; /* don't let top level (?i) bleed */
3890 RExC_emit_start = r->program;
3891 RExC_emit = r->program;
3892 /* Store the count of eval-groups for security checks: */
3893 RExC_emit->next_off = (RExC_seen_evals > (I32)U16_MAX) ? U16_MAX : (U16)RExC_seen_evals;
3894 REGC((U8)REG_MAGIC, (char*) RExC_emit++);
3896 if (reg(pRExC_state, 0, &flags,1) == NULL)
3899 /* XXXX To minimize changes to RE engine we always allocate
3900 3-units-long substrs field. */
3901 Newx(r->substrs, 1, struct reg_substr_data);
3904 r->minlen = minlen = sawplus = sawopen = 0;
3905 Zero(r->substrs, 1, struct reg_substr_data);
3906 StructCopy(&zero_scan_data, &data, scan_data_t);
3908 #ifdef TRIE_STUDY_OPT
3910 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
3911 RExC_state=copyRExC_state;
3912 if (data.last_found) {
3913 SvREFCNT_dec(data.longest_fixed);
3914 SvREFCNT_dec(data.longest_float);
3915 SvREFCNT_dec(data.last_found);
3918 copyRExC_state=RExC_state;
3922 /* Dig out information for optimizations. */
3923 r->reganch = pm->op_pmflags & PMf_COMPILETIME; /* Again? */
3924 pm->op_pmflags = RExC_flags;
3926 r->reganch |= ROPT_UTF8; /* Unicode in it? */
3927 r->regstclass = NULL;
3928 if (RExC_naughty >= 10) /* Probably an expensive pattern. */
3929 r->reganch |= ROPT_NAUGHTY;
3930 scan = r->program + 1; /* First BRANCH. */
3932 /* testing for BRANCH here tells us whether there is "must appear"
3933 data in the pattern. If there is then we can use it for optimisations */
3934 if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES)) { /* Only one top-level choice. */
3936 STRLEN longest_float_length, longest_fixed_length;
3937 struct regnode_charclass_class ch_class; /* pointed to by data */
3939 I32 last_close = 0; /* pointed to by data */
3942 /* Skip introductions and multiplicators >= 1. */
3943 while ((OP(first) == OPEN && (sawopen = 1)) ||
3944 /* An OR of *one* alternative - should not happen now. */
3945 (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
3946 /* for now we can't handle lookbehind IFMATCH*/
3947 (OP(first) == IFMATCH && !first->flags) ||
3948 (OP(first) == PLUS) ||
3949 (OP(first) == MINMOD) ||
3950 /* An {n,m} with n>0 */
3951 (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) )
3954 if (OP(first) == PLUS)
3957 first += regarglen[OP(first)];
3958 if (OP(first) == IFMATCH) {
3959 first = NEXTOPER(first);
3960 first += EXTRA_STEP_2ARGS;
3961 } else /* XXX possible optimisation for /(?=)/ */
3962 first = NEXTOPER(first);
3965 /* Starting-point info. */
3967 DEBUG_PEEP("first:",first,0);
3968 /* Ignore EXACT as we deal with it later. */
3969 if (PL_regkind[OP(first)] == EXACT) {
3970 if (OP(first) == EXACT)
3971 NOOP; /* Empty, get anchored substr later. */
3972 else if ((OP(first) == EXACTF || OP(first) == EXACTFL))
3973 r->regstclass = first;
3976 else if (PL_regkind[OP(first)] == TRIE &&
3977 ((reg_trie_data *)r->data->data[ ARG(first) ])->minlen>0)
3980 /* this can happen only on restudy */
3981 if ( OP(first) == TRIE ) {
3982 struct regnode_1 *trieop;
3983 Newxz(trieop,1,struct regnode_1);
3984 StructCopy(first,trieop,struct regnode_1);
3985 trie_op=(regnode *)trieop;
3987 struct regnode_charclass *trieop;
3988 Newxz(trieop,1,struct regnode_charclass);
3989 StructCopy(first,trieop,struct regnode_charclass);
3990 trie_op=(regnode *)trieop;
3993 make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
3994 r->regstclass = trie_op;
3997 else if (strchr((const char*)PL_simple,OP(first)))
3998 r->regstclass = first;
3999 else if (PL_regkind[OP(first)] == BOUND ||
4000 PL_regkind[OP(first)] == NBOUND)
4001 r->regstclass = first;
4002 else if (PL_regkind[OP(first)] == BOL) {
4003 r->reganch |= (OP(first) == MBOL
4005 : (OP(first) == SBOL
4008 first = NEXTOPER(first);
4011 else if (OP(first) == GPOS) {
4012 r->reganch |= ROPT_ANCH_GPOS;
4013 first = NEXTOPER(first);
4016 else if (!sawopen && (OP(first) == STAR &&
4017 PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
4018 !(r->reganch & ROPT_ANCH) )
4020 /* turn .* into ^.* with an implied $*=1 */
4022 (OP(NEXTOPER(first)) == REG_ANY)
4025 r->reganch |= type | ROPT_IMPLICIT;
4026 first = NEXTOPER(first);
4029 if (sawplus && (!sawopen || !RExC_sawback)
4030 && !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
4031 /* x+ must match at the 1st pos of run of x's */
4032 r->reganch |= ROPT_SKIP;
4034 /* Scan is after the zeroth branch, first is atomic matcher. */
4035 #ifdef TRIE_STUDY_OPT
4038 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4039 (IV)(first - scan + 1))
4043 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4044 (IV)(first - scan + 1))
4050 * If there's something expensive in the r.e., find the
4051 * longest literal string that must appear and make it the
4052 * regmust. Resolve ties in favor of later strings, since
4053 * the regstart check works with the beginning of the r.e.
4054 * and avoiding duplication strengthens checking. Not a
4055 * strong reason, but sufficient in the absence of others.
4056 * [Now we resolve ties in favor of the earlier string if
4057 * it happens that c_offset_min has been invalidated, since the
4058 * earlier string may buy us something the later one won't.]
4062 data.longest_fixed = newSVpvs("");
4063 data.longest_float = newSVpvs("");
4064 data.last_found = newSVpvs("");
4065 data.longest = &(data.longest_fixed);
4067 if (!r->regstclass) {
4068 cl_init(pRExC_state, &ch_class);
4069 data.start_class = &ch_class;
4070 stclass_flag = SCF_DO_STCLASS_AND;
4071 } else /* XXXX Check for BOUND? */
4073 data.last_closep = &last_close;
4075 minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
4076 &data, SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag,0);
4082 if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
4083 && data.last_start_min == 0 && data.last_end > 0
4084 && !RExC_seen_zerolen
4085 && (!(RExC_seen & REG_SEEN_GPOS) || (r->reganch & ROPT_ANCH_GPOS)))
4086 r->reganch |= ROPT_CHECK_ALL;
4087 scan_commit(pRExC_state, &data,&minlen);
4088 SvREFCNT_dec(data.last_found);
4090 /* Note that code very similar to this but for anchored string
4091 follows immediately below, changes may need to be made to both.
4094 longest_float_length = CHR_SVLEN(data.longest_float);
4095 if (longest_float_length
4096 || (data.flags & SF_FL_BEFORE_EOL
4097 && (!(data.flags & SF_FL_BEFORE_MEOL)
4098 || (RExC_flags & PMf_MULTILINE))))
4102 if (SvCUR(data.longest_fixed) /* ok to leave SvCUR */
4103 && data.offset_fixed == data.offset_float_min
4104 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
4105 goto remove_float; /* As in (a)+. */
4107 /* copy the information about the longest float from the reg_scan_data
4108 over to the program. */
4109 if (SvUTF8(data.longest_float)) {
4110 r->float_utf8 = data.longest_float;
4111 r->float_substr = NULL;
4113 r->float_substr = data.longest_float;
4114 r->float_utf8 = NULL;
4116 /* float_end_shift is how many chars that must be matched that
4117 follow this item. We calculate it ahead of time as once the
4118 lookbehind offset is added in we lose the ability to correctly
4120 ml = data.minlen_float ? *(data.minlen_float)
4121 : (I32)longest_float_length;
4122 r->float_end_shift = ml - data.offset_float_min
4123 - longest_float_length + (SvTAIL(data.longest_float) != 0)
4124 + data.lookbehind_float;
4125 r->float_min_offset = data.offset_float_min - data.lookbehind_float;
4126 r->float_max_offset = data.offset_float_max;
4127 if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
4128 r->float_max_offset -= data.lookbehind_float;
4130 t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
4131 && (!(data.flags & SF_FL_BEFORE_MEOL)
4132 || (RExC_flags & PMf_MULTILINE)));
4133 fbm_compile(data.longest_float, t ? FBMcf_TAIL : 0);
4137 r->float_substr = r->float_utf8 = NULL;
4138 SvREFCNT_dec(data.longest_float);
4139 longest_float_length = 0;
4142 /* Note that code very similar to this but for floating string
4143 is immediately above, changes may need to be made to both.
4146 longest_fixed_length = CHR_SVLEN(data.longest_fixed);
4147 if (longest_fixed_length
4148 || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
4149 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4150 || (RExC_flags & PMf_MULTILINE))))
4154 /* copy the information about the longest fixed
4155 from the reg_scan_data over to the program. */
4156 if (SvUTF8(data.longest_fixed)) {
4157 r->anchored_utf8 = data.longest_fixed;
4158 r->anchored_substr = NULL;
4160 r->anchored_substr = data.longest_fixed;
4161 r->anchored_utf8 = NULL;
4163 /* fixed_end_shift is how many chars that must be matched that
4164 follow this item. We calculate it ahead of time as once the
4165 lookbehind offset is added in we lose the ability to correctly
4167 ml = data.minlen_fixed ? *(data.minlen_fixed)
4168 : (I32)longest_fixed_length;
4169 r->anchored_end_shift = ml - data.offset_fixed
4170 - longest_fixed_length + (SvTAIL(data.longest_fixed) != 0)
4171 + data.lookbehind_fixed;
4172 r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
4174 t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
4175 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4176 || (RExC_flags & PMf_MULTILINE)));
4177 fbm_compile(data.longest_fixed, t ? FBMcf_TAIL : 0);
4180 r->anchored_substr = r->anchored_utf8 = NULL;
4181 SvREFCNT_dec(data.longest_fixed);
4182 longest_fixed_length = 0;
4185 && (OP(r->regstclass) == REG_ANY || OP(r->regstclass) == SANY))
4186 r->regstclass = NULL;
4187 if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
4189 && !(data.start_class->flags & ANYOF_EOS)
4190 && !cl_is_anything(data.start_class))
4192 const I32 n = add_data(pRExC_state, 1, "f");
4194 Newx(RExC_rx->data->data[n], 1,
4195 struct regnode_charclass_class);
4196 StructCopy(data.start_class,
4197 (struct regnode_charclass_class*)RExC_rx->data->data[n],
4198 struct regnode_charclass_class);
4199 r->regstclass = (regnode*)RExC_rx->data->data[n];
4200 r->reganch &= ~ROPT_SKIP; /* Used in find_byclass(). */
4201 DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
4202 regprop(r, sv, (regnode*)data.start_class);
4203 PerlIO_printf(Perl_debug_log,
4204 "synthetic stclass \"%s\".\n",
4205 SvPVX_const(sv));});
4208 /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
4209 if (longest_fixed_length > longest_float_length) {
4210 r->check_end_shift = r->anchored_end_shift;
4211 r->check_substr = r->anchored_substr;
4212 r->check_utf8 = r->anchored_utf8;
4213 r->check_offset_min = r->check_offset_max = r->anchored_offset;
4214 if (r->reganch & ROPT_ANCH_SINGLE)
4215 r->reganch |= ROPT_NOSCAN;
4218 r->check_end_shift = r->float_end_shift;
4219 r->check_substr = r->float_substr;
4220 r->check_utf8 = r->float_utf8;
4221 r->check_offset_min = r->float_min_offset;
4222 r->check_offset_max = r->float_max_offset;
4224 /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
4225 This should be changed ASAP! */
4226 if ((r->check_substr || r->check_utf8) && !(r->reganch & ROPT_ANCH_GPOS)) {
4227 r->reganch |= RE_USE_INTUIT;
4228 if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
4229 r->reganch |= RE_INTUIT_TAIL;
4231 /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
4232 if ( (STRLEN)minlen < longest_float_length )
4233 minlen= longest_float_length;
4234 if ( (STRLEN)minlen < longest_fixed_length )
4235 minlen= longest_fixed_length;
4239 /* Several toplevels. Best we can is to set minlen. */
4241 struct regnode_charclass_class ch_class;
4244 DEBUG_COMPILE_r(PerlIO_printf(Perl_debug_log, "\n"));
4246 scan = r->program + 1;
4247 cl_init(pRExC_state, &ch_class);
4248 data.start_class = &ch_class;
4249 data.last_closep = &last_close;
4251 minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
4252 &data, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS,0);
4256 r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
4257 = r->float_substr = r->float_utf8 = NULL;
4258 if (!(data.start_class->flags & ANYOF_EOS)
4259 && !cl_is_anything(data.start_class))
4261 const I32 n = add_data(pRExC_state, 1, "f");
4263 Newx(RExC_rx->data->data[n], 1,
4264 struct regnode_charclass_class);
4265 StructCopy(data.start_class,
4266 (struct regnode_charclass_class*)RExC_rx->data->data[n],
4267 struct regnode_charclass_class);
4268 r->regstclass = (regnode*)RExC_rx->data->data[n];
4269 r->reganch &= ~ROPT_SKIP; /* Used in find_byclass(). */
4270 DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
4271 regprop(r, sv, (regnode*)data.start_class);
4272 PerlIO_printf(Perl_debug_log,
4273 "synthetic stclass \"%s\".\n",
4274 SvPVX_const(sv));});
4278 /* Guard against an embedded (?=) or (?<=) with a longer minlen than
4279 the "real" pattern. */
4280 if (r->minlen < minlen)
4283 if (RExC_seen & REG_SEEN_GPOS)
4284 r->reganch |= ROPT_GPOS_SEEN;
4285 if (RExC_seen & REG_SEEN_LOOKBEHIND)
4286 r->reganch |= ROPT_LOOKBEHIND_SEEN;
4287 if (RExC_seen & REG_SEEN_EVAL)
4288 r->reganch |= ROPT_EVAL_SEEN;
4289 if (RExC_seen & REG_SEEN_CANY)
4290 r->reganch |= ROPT_CANY_SEEN;
4291 if (RExC_paren_names)
4292 r->paren_names = (HV*)SvREFCNT_inc(RExC_paren_names);
4294 r->paren_names = NULL;
4296 Newxz(r->startp, RExC_npar, I32);
4297 Newxz(r->endp, RExC_npar, I32);
4299 DEBUG_r( RX_DEBUG_on(r) );
4301 PerlIO_printf(Perl_debug_log,"Final program:\n");
4304 DEBUG_OFFSETS_r(if (r->offsets) {
4305 const U32 len = r->offsets[0];
4307 GET_RE_DEBUG_FLAGS_DECL;
4308 PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)r->offsets[0]);
4309 for (i = 1; i <= len; i++) {
4310 if (r->offsets[i*2-1] || r->offsets[i*2])
4311 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
4312 (UV)i, (UV)r->offsets[i*2-1], (UV)r->offsets[i*2]);
4314 PerlIO_printf(Perl_debug_log, "\n");
4320 #undef CORE_ONLY_BLOCK
4322 #undef RE_ENGINE_PTR
4324 #ifndef PERL_IN_XSUB_RE
4326 Perl_reg_named_buff_sv(pTHX_ SV* namesv)
4328 I32 parno = 0; /* no match */
4330 const REGEXP * const rx = PM_GETRE(PL_curpm);
4331 if (rx && rx->paren_names) {
4332 HE *he_str = hv_fetch_ent( rx->paren_names, namesv, 0, 0 );
4335 SV* sv_dat=HeVAL(he_str);
4336 I32 *nums=(I32*)SvPVX(sv_dat);
4337 for ( i=0; i<SvIVX(sv_dat); i++ ) {
4338 if ((I32)(rx->lastparen) >= nums[i] &&
4339 rx->endp[nums[i]] != -1)
4352 SV *sv= sv_newmortal();
4353 Perl_sv_setpvf(aTHX_ sv, "%"IVdf,(IV)parno);
4354 gv_paren= Perl_gv_fetchsv(aTHX_ sv, GV_ADD, SVt_PVGV);
4355 return GvSVn(gv_paren);
4360 /* Scans the name of a named buffer from the pattern.
4361 * If flags is REG_RSN_RETURN_NULL returns null.
4362 * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
4363 * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
4364 * to the parsed name as looked up in the RExC_paren_names hash.
4365 * If there is an error throws a vFAIL().. type exception.
4368 #define REG_RSN_RETURN_NULL 0
4369 #define REG_RSN_RETURN_NAME 1
4370 #define REG_RSN_RETURN_DATA 2
4373 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags) {
4374 char *name_start = RExC_parse;
4377 while( isIDFIRST_uni(utf8n_to_uvchr((U8*)RExC_parse,
4378 RExC_end - RExC_parse, &numlen, UTF8_ALLOW_DEFAULT)))
4380 RExC_parse += numlen;
4383 while( isIDFIRST(*RExC_parse) )
4387 SV* sv_name = sv_2mortal(Perl_newSVpvn(aTHX_ name_start,
4388 (int)(RExC_parse - name_start)));
4391 if ( flags == REG_RSN_RETURN_NAME)
4393 else if (flags==REG_RSN_RETURN_DATA) {
4396 if ( ! sv_name ) /* should not happen*/
4397 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
4398 if (RExC_paren_names)
4399 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
4401 sv_dat = HeVAL(he_str);
4403 vFAIL("Reference to nonexistent named group");
4407 Perl_croak(aTHX_ "panic: bad flag in reg_scan_name");
4414 #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
4415 int rem=(int)(RExC_end - RExC_parse); \
4424 if (RExC_lastparse!=RExC_parse) \
4425 PerlIO_printf(Perl_debug_log," >%.*s%-*s", \
4428 iscut ? "..." : "<" \
4431 PerlIO_printf(Perl_debug_log,"%16s",""); \
4436 num=REG_NODE_NUM(RExC_emit); \
4437 if (RExC_lastnum!=num) \
4438 PerlIO_printf(Perl_debug_log,"|%4d",num); \
4440 PerlIO_printf(Perl_debug_log,"|%4s",""); \
4441 PerlIO_printf(Perl_debug_log,"|%*s%-4s", \
4442 (int)((depth*2)), "", \
4446 RExC_lastparse=RExC_parse; \
4451 #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
4452 DEBUG_PARSE_MSG((funcname)); \
4453 PerlIO_printf(Perl_debug_log,"%4s","\n"); \
4455 #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({ \
4456 DEBUG_PARSE_MSG((funcname)); \
4457 PerlIO_printf(Perl_debug_log,fmt "\n",args); \
4460 - reg - regular expression, i.e. main body or parenthesized thing
4462 * Caller must absorb opening parenthesis.
4464 * Combining parenthesis handling with the base level of regular expression
4465 * is a trifle forced, but the need to tie the tails of the branches to what
4466 * follows makes it hard to avoid.
4468 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
4470 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
4472 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
4476 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
4477 /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
4480 register regnode *ret; /* Will be the head of the group. */
4481 register regnode *br;
4482 register regnode *lastbr;
4483 register regnode *ender = NULL;
4484 register I32 parno = 0;
4486 const I32 oregflags = RExC_flags;
4487 bool have_branch = 0;
4490 /* for (?g), (?gc), and (?o) warnings; warning
4491 about (?c) will warn about (?g) -- japhy */
4493 #define WASTED_O 0x01
4494 #define WASTED_G 0x02
4495 #define WASTED_C 0x04
4496 #define WASTED_GC (0x02|0x04)
4497 I32 wastedflags = 0x00;
4499 char * parse_start = RExC_parse; /* MJD */
4500 char * const oregcomp_parse = RExC_parse;
4502 GET_RE_DEBUG_FLAGS_DECL;
4503 DEBUG_PARSE("reg ");
4506 *flagp = 0; /* Tentatively. */
4509 /* Make an OPEN node, if parenthesized. */
4511 if (*RExC_parse == '?') { /* (?...) */
4512 U32 posflags = 0, negflags = 0;
4513 U32 *flagsp = &posflags;
4514 bool is_logical = 0;
4515 const char * const seqstart = RExC_parse;
4518 paren = *RExC_parse++;
4519 ret = NULL; /* For look-ahead/behind. */
4522 case '<': /* (?<...) */
4523 if (*RExC_parse == '!')
4525 else if (*RExC_parse != '=')
4530 case '\'': /* (?'...') */
4531 name_start= RExC_parse;
4532 svname = reg_scan_name(pRExC_state,
4533 SIZE_ONLY ? /* reverse test from the others */
4534 REG_RSN_RETURN_NAME :
4535 REG_RSN_RETURN_NULL);
4536 if (RExC_parse == name_start)
4538 if (*RExC_parse != paren)
4539 vFAIL2("Sequence (?%c... not terminated",
4540 paren=='>' ? '<' : paren);
4544 if (!svname) /* shouldnt happen */
4546 "panic: reg_scan_name returned NULL");
4547 if (!RExC_paren_names) {
4548 RExC_paren_names= newHV();
4549 sv_2mortal((SV*)RExC_paren_names);
4551 he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
4553 sv_dat = HeVAL(he_str);
4555 /* croak baby croak */
4557 "panic: paren_name hash element allocation failed");
4558 } else if ( SvPOK(sv_dat) ) {
4559 IV count=SvIV(sv_dat);
4560 I32 *pv=(I32*)SvGROW(sv_dat,SvCUR(sv_dat)+sizeof(I32)+1);
4561 SvCUR_set(sv_dat,SvCUR(sv_dat)+sizeof(I32));
4562 pv[count]=RExC_npar;
4565 (void)SvUPGRADE(sv_dat,SVt_PVNV);
4566 sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32));
4571 /*sv_dump(sv_dat);*/
4573 nextchar(pRExC_state);
4575 goto capturing_parens;
4577 RExC_seen |= REG_SEEN_LOOKBEHIND;
4579 case '=': /* (?=...) */
4580 case '!': /* (?!...) */
4581 if (*RExC_parse == ')')
4583 RExC_seen_zerolen++;
4584 case ':': /* (?:...) */
4585 case '>': /* (?>...) */
4588 if (RExC_parse[0] == 'A' &&
4589 RExC_parse[1] == 'I' &&
4590 RExC_parse[2] == 'L')
4592 if (*RExC_parse != ')')
4593 vFAIL("Sequence (?FAIL) or (?F) not terminated");
4595 ret = reg_node(pRExC_state, OPFAIL);
4596 nextchar(pRExC_state);
4599 case '$': /* (?$...) */
4600 case '@': /* (?@...) */
4601 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
4603 case '#': /* (?#...) */
4604 while (*RExC_parse && *RExC_parse != ')')
4606 if (*RExC_parse != ')')
4607 FAIL("Sequence (?#... not terminated");
4608 nextchar(pRExC_state);
4611 case '0' : /* (?0) */
4612 case 'R' : /* (?R) */
4613 if (*RExC_parse != ')')
4614 FAIL("Sequence (?R) not terminated");
4615 ret = reg_node(pRExC_state, SRECURSE);
4616 nextchar(pRExC_state);
4619 { /* named and numeric backreferences */
4622 case '&': /* (?&NAME) */
4623 parse_start = RExC_parse - 1;
4625 SV *sv_dat = reg_scan_name(pRExC_state,
4626 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
4627 num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
4629 goto gen_recurse_regop;
4631 case '1': case '2': case '3': case '4': /* (?1) */
4632 case '5': case '6': case '7': case '8': case '9':
4634 num = atoi(RExC_parse);
4635 parse_start = RExC_parse - 1; /* MJD */
4636 while (isDIGIT(*RExC_parse))
4638 if (*RExC_parse!=')')
4639 vFAIL("Expecting close bracket");
4642 ret = reganode(pRExC_state, RECURSE, num);
4644 if (num > (I32)RExC_rx->nparens) {
4646 vFAIL("Reference to nonexistent group");
4650 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
4651 "Recurse #%"UVuf" to %"IVdf"\n", (UV)ARG(ret), (IV)ARG2L(ret)));
4655 RExC_seen |= REG_SEEN_RECURSE;
4656 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
4657 Set_Node_Offset(ret, parse_start); /* MJD */
4659 nextchar(pRExC_state);
4661 } /* named and numeric backreferences */
4664 case 'p': /* (?p...) */
4665 if (SIZE_ONLY && ckWARN2(WARN_DEPRECATED, WARN_REGEXP))
4666 vWARNdep(RExC_parse, "(?p{}) is deprecated - use (??{})");
4668 case '?': /* (??...) */
4670 if (*RExC_parse != '{')
4672 paren = *RExC_parse++;
4674 case '{': /* (?{...}) */
4676 I32 count = 1, n = 0;
4678 char *s = RExC_parse;
4680 RExC_seen_zerolen++;
4681 RExC_seen |= REG_SEEN_EVAL;
4682 while (count && (c = *RExC_parse)) {
4693 if (*RExC_parse != ')') {
4695 vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
4699 OP_4tree *sop, *rop;
4700 SV * const sv = newSVpvn(s, RExC_parse - 1 - s);
4703 Perl_save_re_context(aTHX);
4704 rop = sv_compile_2op(sv, &sop, "re", &pad);
4705 sop->op_private |= OPpREFCOUNTED;
4706 /* re_dup will OpREFCNT_inc */
4707 OpREFCNT_set(sop, 1);
4710 n = add_data(pRExC_state, 3, "nop");
4711 RExC_rx->data->data[n] = (void*)rop;
4712 RExC_rx->data->data[n+1] = (void*)sop;
4713 RExC_rx->data->data[n+2] = (void*)pad;
4716 else { /* First pass */
4717 if (PL_reginterp_cnt < ++RExC_seen_evals
4719 /* No compiled RE interpolated, has runtime
4720 components ===> unsafe. */
4721 FAIL("Eval-group not allowed at runtime, use re 'eval'");
4722 if (PL_tainting && PL_tainted)
4723 FAIL("Eval-group in insecure regular expression");
4724 #if PERL_VERSION > 8
4725 if (IN_PERL_COMPILETIME)
4730 nextchar(pRExC_state);
4732 ret = reg_node(pRExC_state, LOGICAL);
4735 REGTAIL(pRExC_state, ret, reganode(pRExC_state, EVAL, n));
4736 /* deal with the length of this later - MJD */
4739 ret = reganode(pRExC_state, EVAL, n);
4740 Set_Node_Length(ret, RExC_parse - parse_start + 1);
4741 Set_Node_Offset(ret, parse_start);
4744 case '(': /* (?(?{...})...) and (?(?=...)...) */
4747 if (RExC_parse[0] == '?') { /* (?(?...)) */
4748 if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
4749 || RExC_parse[1] == '<'
4750 || RExC_parse[1] == '{') { /* Lookahead or eval. */
4753 ret = reg_node(pRExC_state, LOGICAL);
4756 REGTAIL(pRExC_state, ret, reg(pRExC_state, 1, &flag,depth+1));
4760 else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
4761 || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
4763 char ch = RExC_parse[0] == '<' ? '>' : '\'';
4764 char *name_start= RExC_parse++;
4766 SV *sv_dat=reg_scan_name(pRExC_state,
4767 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
4768 if (RExC_parse == name_start || *RExC_parse != ch)
4769 vFAIL2("Sequence (?(%c... not terminated",
4770 (ch == '>' ? '<' : ch));
4773 num = add_data( pRExC_state, 1, "S" );
4774 RExC_rx->data->data[num]=(void*)sv_dat;
4775 SvREFCNT_inc(sv_dat);
4777 ret = reganode(pRExC_state,NGROUPP,num);
4778 goto insert_if_check_paren;
4780 else if (RExC_parse[0] == 'D' &&
4781 RExC_parse[1] == 'E' &&
4782 RExC_parse[2] == 'F' &&
4783 RExC_parse[3] == 'I' &&
4784 RExC_parse[4] == 'N' &&
4785 RExC_parse[5] == 'E')
4787 ret = reganode(pRExC_state,DEFINEP,0);
4790 goto insert_if_check_paren;
4792 else if (RExC_parse[0] == 'R') {
4795 if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
4796 parno = atoi(RExC_parse++);
4797 while (isDIGIT(*RExC_parse))
4799 } else if (RExC_parse[0] == '&') {
4802 sv_dat = reg_scan_name(pRExC_state,
4803 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
4804 parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
4806 ret = reganode(pRExC_state,RECURSEP,parno);
4807 goto insert_if_check_paren;
4809 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
4812 parno = atoi(RExC_parse++);
4814 while (isDIGIT(*RExC_parse))
4816 ret = reganode(pRExC_state, GROUPP, parno);
4818 insert_if_check_paren:
4819 if ((c = *nextchar(pRExC_state)) != ')')
4820 vFAIL("Switch condition not recognized");
4822 REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
4823 br = regbranch(pRExC_state, &flags, 1,depth+1);
4825 br = reganode(pRExC_state, LONGJMP, 0);
4827 REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
4828 c = *nextchar(pRExC_state);
4833 vFAIL("(?(DEFINE)....) does not allow branches");
4834 lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
4835 regbranch(pRExC_state, &flags, 1,depth+1);
4836 REGTAIL(pRExC_state, ret, lastbr);
4839 c = *nextchar(pRExC_state);
4844 vFAIL("Switch (?(condition)... contains too many branches");
4845 ender = reg_node(pRExC_state, TAIL);
4846 REGTAIL(pRExC_state, br, ender);
4848 REGTAIL(pRExC_state, lastbr, ender);
4849 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
4852 REGTAIL(pRExC_state, ret, ender);
4856 vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
4860 RExC_parse--; /* for vFAIL to print correctly */
4861 vFAIL("Sequence (? incomplete");
4865 parse_flags: /* (?i) */
4866 while (*RExC_parse && strchr("iogcmsx", *RExC_parse)) {
4867 /* (?g), (?gc) and (?o) are useless here
4868 and must be globally applied -- japhy */
4870 if (*RExC_parse == 'o' || *RExC_parse == 'g') {
4871 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
4872 const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
4873 if (! (wastedflags & wflagbit) ) {
4874 wastedflags |= wflagbit;
4877 "Useless (%s%c) - %suse /%c modifier",
4878 flagsp == &negflags ? "?-" : "?",
4880 flagsp == &negflags ? "don't " : "",
4886 else if (*RExC_parse == 'c') {
4887 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
4888 if (! (wastedflags & WASTED_C) ) {
4889 wastedflags |= WASTED_GC;
4892 "Useless (%sc) - %suse /gc modifier",
4893 flagsp == &negflags ? "?-" : "?",
4894 flagsp == &negflags ? "don't " : ""
4899 else { pmflag(flagsp, *RExC_parse); }
4903 if (*RExC_parse == '-') {
4905 wastedflags = 0; /* reset so (?g-c) warns twice */
4909 RExC_flags |= posflags;
4910 RExC_flags &= ~negflags;
4911 if (*RExC_parse == ':') {
4917 if (*RExC_parse != ')') {
4919 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
4921 nextchar(pRExC_state);
4930 ret = reganode(pRExC_state, OPEN, parno);
4931 if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
4932 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
4933 "Setting paren #%"IVdf" to %d\n", (IV)parno, REG_NODE_NUM(ret)));
4934 RExC_parens[parno-1]= ret;
4937 Set_Node_Length(ret, 1); /* MJD */
4938 Set_Node_Offset(ret, RExC_parse); /* MJD */
4945 /* Pick up the branches, linking them together. */
4946 parse_start = RExC_parse; /* MJD */
4947 br = regbranch(pRExC_state, &flags, 1,depth+1);
4948 /* branch_len = (paren != 0); */
4952 if (*RExC_parse == '|') {
4953 if (!SIZE_ONLY && RExC_extralen) {
4954 reginsert(pRExC_state, BRANCHJ, br, depth+1);
4957 reginsert(pRExC_state, BRANCH, br, depth+1);
4958 Set_Node_Length(br, paren != 0);
4959 Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
4963 RExC_extralen += 1; /* For BRANCHJ-BRANCH. */
4965 else if (paren == ':') {
4966 *flagp |= flags&SIMPLE;
4968 if (is_open) { /* Starts with OPEN. */
4969 REGTAIL(pRExC_state, ret, br); /* OPEN -> first. */
4971 else if (paren != '?') /* Not Conditional */
4973 *flagp |= flags & (SPSTART | HASWIDTH);
4975 while (*RExC_parse == '|') {
4976 if (!SIZE_ONLY && RExC_extralen) {
4977 ender = reganode(pRExC_state, LONGJMP,0);
4978 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
4981 RExC_extralen += 2; /* Account for LONGJMP. */
4982 nextchar(pRExC_state);
4983 br = regbranch(pRExC_state, &flags, 0, depth+1);
4987 REGTAIL(pRExC_state, lastbr, br); /* BRANCH -> BRANCH. */
4991 *flagp |= flags&SPSTART;
4994 if (have_branch || paren != ':') {
4995 /* Make a closing node, and hook it on the end. */
4998 ender = reg_node(pRExC_state, TAIL);
5001 ender = reganode(pRExC_state, CLOSE, parno);
5002 Set_Node_Offset(ender,RExC_parse+1); /* MJD */
5003 Set_Node_Length(ender,1); /* MJD */
5009 *flagp &= ~HASWIDTH;
5012 ender = reg_node(pRExC_state, SUCCEED);
5015 ender = reg_node(pRExC_state, END);
5018 REGTAIL(pRExC_state, lastbr, ender);
5020 if (have_branch && !SIZE_ONLY) {
5022 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
5024 /* Hook the tails of the branches to the closing node. */
5025 for (br = ret; br; br = regnext(br)) {
5026 const U8 op = PL_regkind[OP(br)];
5028 REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
5030 else if (op == BRANCHJ) {
5031 REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
5039 static const char parens[] = "=!<,>";
5041 if (paren && (p = strchr(parens, paren))) {
5042 U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
5043 int flag = (p - parens) > 1;
5046 node = SUSPEND, flag = 0;
5047 reginsert(pRExC_state, node,ret, depth+1);
5048 Set_Node_Cur_Length(ret);
5049 Set_Node_Offset(ret, parse_start + 1);
5051 REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
5055 /* Check for proper termination. */
5057 RExC_flags = oregflags;
5058 if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
5059 RExC_parse = oregcomp_parse;
5060 vFAIL("Unmatched (");
5063 else if (!paren && RExC_parse < RExC_end) {
5064 if (*RExC_parse == ')') {
5066 vFAIL("Unmatched )");
5069 FAIL("Junk on end of regexp"); /* "Can't happen". */
5077 - regbranch - one alternative of an | operator
5079 * Implements the concatenation operator.
5082 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
5085 register regnode *ret;
5086 register regnode *chain = NULL;
5087 register regnode *latest;
5088 I32 flags = 0, c = 0;
5089 GET_RE_DEBUG_FLAGS_DECL;
5090 DEBUG_PARSE("brnc");
5094 if (!SIZE_ONLY && RExC_extralen)
5095 ret = reganode(pRExC_state, BRANCHJ,0);
5097 ret = reg_node(pRExC_state, BRANCH);
5098 Set_Node_Length(ret, 1);
5102 if (!first && SIZE_ONLY)
5103 RExC_extralen += 1; /* BRANCHJ */
5105 *flagp = WORST; /* Tentatively. */
5108 nextchar(pRExC_state);
5109 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
5111 latest = regpiece(pRExC_state, &flags,depth+1);
5112 if (latest == NULL) {
5113 if (flags & TRYAGAIN)
5117 else if (ret == NULL)
5119 *flagp |= flags&HASWIDTH;
5120 if (chain == NULL) /* First piece. */
5121 *flagp |= flags&SPSTART;
5124 REGTAIL(pRExC_state, chain, latest);
5129 if (chain == NULL) { /* Loop ran zero times. */
5130 chain = reg_node(pRExC_state, NOTHING);
5135 *flagp |= flags&SIMPLE;
5142 - regpiece - something followed by possible [*+?]
5144 * Note that the branching code sequences used for ? and the general cases
5145 * of * and + are somewhat optimized: they use the same NOTHING node as
5146 * both the endmarker for their branch list and the body of the last branch.
5147 * It might seem that this node could be dispensed with entirely, but the
5148 * endmarker role is not redundant.
5151 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
5154 register regnode *ret;
5156 register char *next;
5158 const char * const origparse = RExC_parse;
5160 I32 max = REG_INFTY;
5162 const char *maxpos = NULL;
5163 GET_RE_DEBUG_FLAGS_DECL;
5164 DEBUG_PARSE("piec");
5166 ret = regatom(pRExC_state, &flags,depth+1);
5168 if (flags & TRYAGAIN)
5175 if (op == '{' && regcurly(RExC_parse)) {
5177 parse_start = RExC_parse; /* MJD */
5178 next = RExC_parse + 1;
5179 while (isDIGIT(*next) || *next == ',') {
5188 if (*next == '}') { /* got one */
5192 min = atoi(RExC_parse);
5196 maxpos = RExC_parse;
5198 if (!max && *maxpos != '0')
5199 max = REG_INFTY; /* meaning "infinity" */
5200 else if (max >= REG_INFTY)
5201 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
5203 nextchar(pRExC_state);
5206 if ((flags&SIMPLE)) {
5207 RExC_naughty += 2 + RExC_naughty / 2;
5208 reginsert(pRExC_state, CURLY, ret, depth+1);
5209 Set_Node_Offset(ret, parse_start+1); /* MJD */
5210 Set_Node_Cur_Length(ret);
5213 regnode * const w = reg_node(pRExC_state, WHILEM);
5216 REGTAIL(pRExC_state, ret, w);
5217 if (!SIZE_ONLY && RExC_extralen) {
5218 reginsert(pRExC_state, LONGJMP,ret, depth+1);
5219 reginsert(pRExC_state, NOTHING,ret, depth+1);
5220 NEXT_OFF(ret) = 3; /* Go over LONGJMP. */
5222 reginsert(pRExC_state, CURLYX,ret, depth+1);
5224 Set_Node_Offset(ret, parse_start+1);
5225 Set_Node_Length(ret,
5226 op == '{' ? (RExC_parse - parse_start) : 1);
5228 if (!SIZE_ONLY && RExC_extralen)
5229 NEXT_OFF(ret) = 3; /* Go over NOTHING to LONGJMP. */
5230 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
5232 RExC_whilem_seen++, RExC_extralen += 3;
5233 RExC_naughty += 4 + RExC_naughty; /* compound interest */
5241 if (max && max < min)
5242 vFAIL("Can't do {n,m} with n > m");
5244 ARG1_SET(ret, (U16)min);
5245 ARG2_SET(ret, (U16)max);
5257 #if 0 /* Now runtime fix should be reliable. */
5259 /* if this is reinstated, don't forget to put this back into perldiag:
5261 =item Regexp *+ operand could be empty at {#} in regex m/%s/
5263 (F) The part of the regexp subject to either the * or + quantifier
5264 could match an empty string. The {#} shows in the regular
5265 expression about where the problem was discovered.
5269 if (!(flags&HASWIDTH) && op != '?')
5270 vFAIL("Regexp *+ operand could be empty");
5273 parse_start = RExC_parse;
5274 nextchar(pRExC_state);
5276 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
5278 if (op == '*' && (flags&SIMPLE)) {
5279 reginsert(pRExC_state, STAR, ret, depth+1);
5283 else if (op == '*') {
5287 else if (op == '+' && (flags&SIMPLE)) {
5288 reginsert(pRExC_state, PLUS, ret, depth+1);
5292 else if (op == '+') {
5296 else if (op == '?') {
5301 if (!SIZE_ONLY && !(flags&HASWIDTH) && max > REG_INFTY/3 && ckWARN(WARN_REGEXP)) {
5303 "%.*s matches null string many times",
5304 (int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
5308 if (RExC_parse < RExC_end && *RExC_parse == '?') {
5309 nextchar(pRExC_state);
5310 reginsert(pRExC_state, MINMOD, ret, depth+1);
5311 REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
5313 #ifndef REG_ALLOW_MINMOD_SUSPEND
5316 if (RExC_parse < RExC_end && *RExC_parse == '+') {
5318 nextchar(pRExC_state);
5319 ender = reg_node(pRExC_state, SUCCEED);
5320 REGTAIL(pRExC_state, ret, ender);
5321 reginsert(pRExC_state, SUSPEND, ret, depth+1);
5323 ender = reg_node(pRExC_state, TAIL);
5324 REGTAIL(pRExC_state, ret, ender);
5328 if (RExC_parse < RExC_end && ISMULT2(RExC_parse)) {
5330 vFAIL("Nested quantifiers");
5337 /* reg_namedseq(pRExC_state,UVp)
5339 This is expected to be called by a parser routine that has
5340 recognized'\N' and needs to handle the rest. RExC_parse is
5341 expected to point at the first char following the N at the time
5344 If valuep is non-null then it is assumed that we are parsing inside
5345 of a charclass definition and the first codepoint in the resolved
5346 string is returned via *valuep and the routine will return NULL.
5347 In this mode if a multichar string is returned from the charnames
5348 handler a warning will be issued, and only the first char in the
5349 sequence will be examined. If the string returned is zero length
5350 then the value of *valuep is undefined and NON-NULL will
5351 be returned to indicate failure. (This will NOT be a valid pointer
5354 If value is null then it is assumed that we are parsing normal text
5355 and inserts a new EXACT node into the program containing the resolved
5356 string and returns a pointer to the new node. If the string is
5357 zerolength a NOTHING node is emitted.
5359 On success RExC_parse is set to the char following the endbrace.
5360 Parsing failures will generate a fatal errorvia vFAIL(...)
5362 NOTE: We cache all results from the charnames handler locally in
5363 the RExC_charnames hash (created on first use) to prevent a charnames
5364 handler from playing silly-buggers and returning a short string and
5365 then a long string for a given pattern. Since the regexp program
5366 size is calculated during an initial parse this would result
5367 in a buffer overrun so we cache to prevent the charname result from
5368 changing during the course of the parse.
5372 S_reg_namedseq(pTHX_ RExC_state_t *pRExC_state, UV *valuep)
5374 char * name; /* start of the content of the name */
5375 char * endbrace; /* endbrace following the name */
5378 STRLEN len; /* this has various purposes throughout the code */
5379 bool cached = 0; /* if this is true then we shouldn't refcount dev sv_str */
5380 regnode *ret = NULL;
5382 if (*RExC_parse != '{') {
5383 vFAIL("Missing braces on \\N{}");
5385 name = RExC_parse+1;
5386 endbrace = strchr(RExC_parse, '}');
5389 vFAIL("Missing right brace on \\N{}");
5391 RExC_parse = endbrace + 1;
5394 /* RExC_parse points at the beginning brace,
5395 endbrace points at the last */
5396 if ( name[0]=='U' && name[1]=='+' ) {
5397 /* its a "unicode hex" notation {U+89AB} */
5398 I32 fl = PERL_SCAN_ALLOW_UNDERSCORES
5399 | PERL_SCAN_DISALLOW_PREFIX
5400 | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
5402 len = (STRLEN)(endbrace - name - 2);
5403 cp = grok_hex(name + 2, &len, &fl, NULL);
5404 if ( len != (STRLEN)(endbrace - name - 2) ) {
5413 sv_str= Perl_newSVpvf_nocontext("%c",(int)cp);
5415 /* fetch the charnames handler for this scope */
5416 HV * const table = GvHV(PL_hintgv);
5418 hv_fetchs(table, "charnames", FALSE) :
5420 SV *cv= cvp ? *cvp : NULL;
5423 /* create an SV with the name as argument */
5424 sv_name = newSVpvn(name, endbrace - name);
5426 if (!table || !(PL_hints & HINT_LOCALIZE_HH)) {
5427 vFAIL2("Constant(\\N{%s}) unknown: "
5428 "(possibly a missing \"use charnames ...\")",
5431 if (!cvp || !SvOK(*cvp)) { /* when $^H{charnames} = undef; */
5432 vFAIL2("Constant(\\N{%s}): "
5433 "$^H{charnames} is not defined",SvPVX(sv_name));
5438 if (!RExC_charnames) {
5439 /* make sure our cache is allocated */
5440 RExC_charnames = newHV();
5441 sv_2mortal((SV*)RExC_charnames);
5443 /* see if we have looked this one up before */
5444 he_str = hv_fetch_ent( RExC_charnames, sv_name, 0, 0 );
5446 sv_str = HeVAL(he_str);
5459 count= call_sv(cv, G_SCALAR);
5461 if (count == 1) { /* XXXX is this right? dmq */
5463 SvREFCNT_inc_simple_void(sv_str);
5471 if ( !sv_str || !SvOK(sv_str) ) {
5472 vFAIL2("Constant(\\N{%s}): Call to &{$^H{charnames}} "
5473 "did not return a defined value",SvPVX(sv_name));
5475 if (hv_store_ent( RExC_charnames, sv_name, sv_str, 0))
5480 char *p = SvPV(sv_str, len);
5483 if ( SvUTF8(sv_str) ) {
5484 *valuep = utf8_to_uvchr((U8*)p, &numlen);
5488 We have to turn on utf8 for high bit chars otherwise
5489 we get failures with
5491 "ss" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
5492 "SS" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
5494 This is different from what \x{} would do with the same
5495 codepoint, where the condition is > 0xFF.
5502 /* warn if we havent used the whole string? */
5504 if (numlen<len && SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5506 "Ignoring excess chars from \\N{%s} in character class",
5510 } else if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5512 "Ignoring zero length \\N{%s} in character class",
5517 SvREFCNT_dec(sv_name);
5519 SvREFCNT_dec(sv_str);
5520 return len ? NULL : (regnode *)&len;
5521 } else if(SvCUR(sv_str)) {
5526 char * parse_start = name-3; /* needed for the offsets */
5527 GET_RE_DEBUG_FLAGS_DECL; /* needed for the offsets */
5529 ret = reg_node(pRExC_state,
5530 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
5533 if ( RExC_utf8 && !SvUTF8(sv_str) ) {
5534 sv_utf8_upgrade(sv_str);
5535 } else if ( !RExC_utf8 && SvUTF8(sv_str) ) {
5539 p = SvPV(sv_str, len);
5541 /* len is the length written, charlen is the size the char read */
5542 for ( len = 0; p < pend; p += charlen ) {
5544 UV uvc = utf8_to_uvchr((U8*)p, &charlen);
5546 STRLEN foldlen,numlen;
5547 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
5548 uvc = toFOLD_uni(uvc, tmpbuf, &foldlen);
5549 /* Emit all the Unicode characters. */
5551 for (foldbuf = tmpbuf;
5555 uvc = utf8_to_uvchr(foldbuf, &numlen);
5557 const STRLEN unilen = reguni(pRExC_state, uvc, s);
5560 /* In EBCDIC the numlen
5561 * and unilen can differ. */
5563 if (numlen >= foldlen)
5567 break; /* "Can't happen." */
5570 const STRLEN unilen = reguni(pRExC_state, uvc, s);
5582 RExC_size += STR_SZ(len);
5585 RExC_emit += STR_SZ(len);
5587 Set_Node_Cur_Length(ret); /* MJD */
5589 nextchar(pRExC_state);
5591 ret = reg_node(pRExC_state,NOTHING);
5594 SvREFCNT_dec(sv_str);
5597 SvREFCNT_dec(sv_name);
5606 - regatom - the lowest level
5608 * Optimization: gobbles an entire sequence of ordinary characters so that
5609 * it can turn them into a single node, which is smaller to store and
5610 * faster to run. Backslashed characters are exceptions, each becoming a
5611 * separate node; the code is simpler that way and it's not worth fixing.
5613 * [Yes, it is worth fixing, some scripts can run twice the speed.]
5614 * [It looks like its ok, as in S_study_chunk we merge adjacent EXACT nodes]
5617 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
5620 register regnode *ret = NULL;
5622 char *parse_start = RExC_parse;
5623 GET_RE_DEBUG_FLAGS_DECL;
5624 DEBUG_PARSE("atom");
5625 *flagp = WORST; /* Tentatively. */
5628 switch (*RExC_parse) {
5630 RExC_seen_zerolen++;
5631 nextchar(pRExC_state);
5632 if (RExC_flags & PMf_MULTILINE)
5633 ret = reg_node(pRExC_state, MBOL);
5634 else if (RExC_flags & PMf_SINGLELINE)
5635 ret = reg_node(pRExC_state, SBOL);
5637 ret = reg_node(pRExC_state, BOL);
5638 Set_Node_Length(ret, 1); /* MJD */
5641 nextchar(pRExC_state);
5643 RExC_seen_zerolen++;
5644 if (RExC_flags & PMf_MULTILINE)
5645 ret = reg_node(pRExC_state, MEOL);
5646 else if (RExC_flags & PMf_SINGLELINE)
5647 ret = reg_node(pRExC_state, SEOL);
5649 ret = reg_node(pRExC_state, EOL);
5650 Set_Node_Length(ret, 1); /* MJD */
5653 nextchar(pRExC_state);
5654 if (RExC_flags & PMf_SINGLELINE)
5655 ret = reg_node(pRExC_state, SANY);
5657 ret = reg_node(pRExC_state, REG_ANY);
5658 *flagp |= HASWIDTH|SIMPLE;
5660 Set_Node_Length(ret, 1); /* MJD */
5664 char * const oregcomp_parse = ++RExC_parse;
5665 ret = regclass(pRExC_state,depth+1);
5666 if (*RExC_parse != ']') {
5667 RExC_parse = oregcomp_parse;
5668 vFAIL("Unmatched [");
5670 nextchar(pRExC_state);
5671 *flagp |= HASWIDTH|SIMPLE;
5672 Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
5676 nextchar(pRExC_state);
5677 ret = reg(pRExC_state, 1, &flags,depth+1);
5679 if (flags & TRYAGAIN) {
5680 if (RExC_parse == RExC_end) {
5681 /* Make parent create an empty node if needed. */
5689 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE);
5693 if (flags & TRYAGAIN) {
5697 vFAIL("Internal urp");
5698 /* Supposed to be caught earlier. */
5701 if (!regcurly(RExC_parse)) {
5710 vFAIL("Quantifier follows nothing");
5713 switch (*++RExC_parse) {
5715 RExC_seen_zerolen++;
5716 ret = reg_node(pRExC_state, SBOL);
5718 nextchar(pRExC_state);
5719 Set_Node_Length(ret, 2); /* MJD */
5722 ret = reg_node(pRExC_state, GPOS);
5723 RExC_seen |= REG_SEEN_GPOS;
5725 nextchar(pRExC_state);
5726 Set_Node_Length(ret, 2); /* MJD */
5729 ret = reg_node(pRExC_state, SEOL);
5731 RExC_seen_zerolen++; /* Do not optimize RE away */
5732 nextchar(pRExC_state);
5735 ret = reg_node(pRExC_state, EOS);
5737 RExC_seen_zerolen++; /* Do not optimize RE away */
5738 nextchar(pRExC_state);
5739 Set_Node_Length(ret, 2); /* MJD */
5742 ret = reg_node(pRExC_state, CANY);
5743 RExC_seen |= REG_SEEN_CANY;
5744 *flagp |= HASWIDTH|SIMPLE;
5745 nextchar(pRExC_state);
5746 Set_Node_Length(ret, 2); /* MJD */
5749 ret = reg_node(pRExC_state, CLUMP);
5751 nextchar(pRExC_state);
5752 Set_Node_Length(ret, 2); /* MJD */
5755 ret = reg_node(pRExC_state, (U8)(LOC ? ALNUML : ALNUM));
5756 *flagp |= HASWIDTH|SIMPLE;
5757 nextchar(pRExC_state);
5758 Set_Node_Length(ret, 2); /* MJD */
5761 ret = reg_node(pRExC_state, (U8)(LOC ? NALNUML : NALNUM));
5762 *flagp |= HASWIDTH|SIMPLE;
5763 nextchar(pRExC_state);
5764 Set_Node_Length(ret, 2); /* MJD */
5767 RExC_seen_zerolen++;
5768 RExC_seen |= REG_SEEN_LOOKBEHIND;
5769 ret = reg_node(pRExC_state, (U8)(LOC ? BOUNDL : BOUND));
5771 nextchar(pRExC_state);
5772 Set_Node_Length(ret, 2); /* MJD */
5775 RExC_seen_zerolen++;
5776 RExC_seen |= REG_SEEN_LOOKBEHIND;
5777 ret = reg_node(pRExC_state, (U8)(LOC ? NBOUNDL : NBOUND));
5779 nextchar(pRExC_state);
5780 Set_Node_Length(ret, 2); /* MJD */
5783 ret = reg_node(pRExC_state, (U8)(LOC ? SPACEL : SPACE));
5784 *flagp |= HASWIDTH|SIMPLE;
5785 nextchar(pRExC_state);
5786 Set_Node_Length(ret, 2); /* MJD */
5789 ret = reg_node(pRExC_state, (U8)(LOC ? NSPACEL : NSPACE));
5790 *flagp |= HASWIDTH|SIMPLE;
5791 nextchar(pRExC_state);
5792 Set_Node_Length(ret, 2); /* MJD */
5795 ret = reg_node(pRExC_state, DIGIT);
5796 *flagp |= HASWIDTH|SIMPLE;
5797 nextchar(pRExC_state);
5798 Set_Node_Length(ret, 2); /* MJD */
5801 ret = reg_node(pRExC_state, NDIGIT);
5802 *flagp |= HASWIDTH|SIMPLE;
5803 nextchar(pRExC_state);
5804 Set_Node_Length(ret, 2); /* MJD */
5809 char* const oldregxend = RExC_end;
5810 char* parse_start = RExC_parse - 2;
5812 if (RExC_parse[1] == '{') {
5813 /* a lovely hack--pretend we saw [\pX] instead */
5814 RExC_end = strchr(RExC_parse, '}');
5816 const U8 c = (U8)*RExC_parse;
5818 RExC_end = oldregxend;
5819 vFAIL2("Missing right brace on \\%c{}", c);
5824 RExC_end = RExC_parse + 2;
5825 if (RExC_end > oldregxend)
5826 RExC_end = oldregxend;
5830 ret = regclass(pRExC_state,depth+1);
5832 RExC_end = oldregxend;
5835 Set_Node_Offset(ret, parse_start + 2);
5836 Set_Node_Cur_Length(ret);
5837 nextchar(pRExC_state);
5838 *flagp |= HASWIDTH|SIMPLE;
5842 /* Handle \N{NAME} here and not below because it can be
5843 multicharacter. join_exact() will join them up later on.
5844 Also this makes sure that things like /\N{BLAH}+/ and
5845 \N{BLAH} being multi char Just Happen. dmq*/
5847 ret= reg_namedseq(pRExC_state, NULL);
5849 case 'k': /* Handle \k<NAME> and \k'NAME' */
5851 char ch= RExC_parse[1];
5852 if (ch != '<' && ch != '\'') {
5854 vWARN( RExC_parse + 1,
5855 "Possible broken named back reference treated as literal k");
5859 char* name_start = (RExC_parse += 2);
5861 SV *sv_dat = reg_scan_name(pRExC_state,
5862 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5863 ch= (ch == '<') ? '>' : '\'';
5865 if (RExC_parse == name_start || *RExC_parse != ch)
5866 vFAIL2("Sequence \\k%c... not terminated",
5867 (ch == '>' ? '<' : ch));
5870 ret = reganode(pRExC_state,
5871 (U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
5877 num = add_data( pRExC_state, 1, "S" );
5879 RExC_rx->data->data[num]=(void*)sv_dat;
5880 SvREFCNT_inc(sv_dat);
5882 /* override incorrect value set in reganode MJD */
5883 Set_Node_Offset(ret, parse_start+1);
5884 Set_Node_Cur_Length(ret); /* MJD */
5885 nextchar(pRExC_state);
5900 case '1': case '2': case '3': case '4':
5901 case '5': case '6': case '7': case '8': case '9':
5903 const I32 num = atoi(RExC_parse);
5905 if (num > 9 && num >= RExC_npar)
5908 char * const parse_start = RExC_parse - 1; /* MJD */
5909 while (isDIGIT(*RExC_parse))
5912 if (!SIZE_ONLY && num > (I32)RExC_rx->nparens)
5913 vFAIL("Reference to nonexistent group");
5915 ret = reganode(pRExC_state,
5916 (U8)(FOLD ? (LOC ? REFFL : REFF) : REF),
5920 /* override incorrect value set in reganode MJD */
5921 Set_Node_Offset(ret, parse_start+1);
5922 Set_Node_Cur_Length(ret); /* MJD */
5924 nextchar(pRExC_state);
5929 if (RExC_parse >= RExC_end)
5930 FAIL("Trailing \\");
5933 /* Do not generate "unrecognized" warnings here, we fall
5934 back into the quick-grab loop below */
5941 if (RExC_flags & PMf_EXTENDED) {
5942 while (RExC_parse < RExC_end && *RExC_parse != '\n')
5944 if (RExC_parse < RExC_end)
5950 register STRLEN len;
5955 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
5957 parse_start = RExC_parse - 1;
5963 ret = reg_node(pRExC_state,
5964 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
5966 for (len = 0, p = RExC_parse - 1;
5967 len < 127 && p < RExC_end;
5970 char * const oldp = p;
5972 if (RExC_flags & PMf_EXTENDED)
5973 p = regwhite(p, RExC_end);
6021 ender = ASCII_TO_NATIVE('\033');
6025 ender = ASCII_TO_NATIVE('\007');
6030 char* const e = strchr(p, '}');
6034 vFAIL("Missing right brace on \\x{}");
6037 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
6038 | PERL_SCAN_DISALLOW_PREFIX;
6039 STRLEN numlen = e - p - 1;
6040 ender = grok_hex(p + 1, &numlen, &flags, NULL);
6047 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
6049 ender = grok_hex(p, &numlen, &flags, NULL);
6055 ender = UCHARAT(p++);
6056 ender = toCTRL(ender);
6058 case '0': case '1': case '2': case '3':case '4':
6059 case '5': case '6': case '7': case '8':case '9':
6061 (isDIGIT(p[1]) && atoi(p) >= RExC_npar) ) {
6064 ender = grok_oct(p, &numlen, &flags, NULL);
6074 FAIL("Trailing \\");
6077 if (!SIZE_ONLY&& isALPHA(*p) && ckWARN(WARN_REGEXP))
6078 vWARN2(p + 1, "Unrecognized escape \\%c passed through", UCHARAT(p));
6079 goto normal_default;
6084 if (UTF8_IS_START(*p) && UTF) {
6086 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
6087 &numlen, UTF8_ALLOW_DEFAULT);
6094 if (RExC_flags & PMf_EXTENDED)
6095 p = regwhite(p, RExC_end);
6097 /* Prime the casefolded buffer. */
6098 ender = toFOLD_uni(ender, tmpbuf, &foldlen);
6100 if (ISMULT2(p)) { /* Back off on ?+*. */
6105 /* Emit all the Unicode characters. */
6107 for (foldbuf = tmpbuf;
6109 foldlen -= numlen) {
6110 ender = utf8_to_uvchr(foldbuf, &numlen);
6112 const STRLEN unilen = reguni(pRExC_state, ender, s);
6115 /* In EBCDIC the numlen
6116 * and unilen can differ. */
6118 if (numlen >= foldlen)
6122 break; /* "Can't happen." */
6126 const STRLEN unilen = reguni(pRExC_state, ender, s);
6135 REGC((char)ender, s++);
6141 /* Emit all the Unicode characters. */
6143 for (foldbuf = tmpbuf;
6145 foldlen -= numlen) {
6146 ender = utf8_to_uvchr(foldbuf, &numlen);
6148 const STRLEN unilen = reguni(pRExC_state, ender, s);
6151 /* In EBCDIC the numlen
6152 * and unilen can differ. */
6154 if (numlen >= foldlen)
6162 const STRLEN unilen = reguni(pRExC_state, ender, s);
6171 REGC((char)ender, s++);
6175 Set_Node_Cur_Length(ret); /* MJD */
6176 nextchar(pRExC_state);
6178 /* len is STRLEN which is unsigned, need to copy to signed */
6181 vFAIL("Internal disaster");
6185 if (len == 1 && UNI_IS_INVARIANT(ender))
6189 RExC_size += STR_SZ(len);
6192 RExC_emit += STR_SZ(len);
6198 /* If the encoding pragma is in effect recode the text of
6199 * any EXACT-kind nodes. */
6200 if (ret && PL_encoding && PL_regkind[OP(ret)] == EXACT) {
6201 const STRLEN oldlen = STR_LEN(ret);
6202 SV * const sv = sv_2mortal(newSVpvn(STRING(ret), oldlen));
6206 if (sv_utf8_downgrade(sv, TRUE)) {
6207 const char * const s = sv_recode_to_utf8(sv, PL_encoding);
6208 const STRLEN newlen = SvCUR(sv);
6213 GET_RE_DEBUG_FLAGS_DECL;
6214 DEBUG_COMPILE_r(PerlIO_printf(Perl_debug_log, "recode %*s to %*s\n",
6215 (int)oldlen, STRING(ret),
6217 Copy(s, STRING(ret), newlen, char);
6218 STR_LEN(ret) += newlen - oldlen;
6219 RExC_emit += STR_SZ(newlen) - STR_SZ(oldlen);
6221 RExC_size += STR_SZ(newlen) - STR_SZ(oldlen);
6229 S_regwhite(char *p, const char *e)
6234 else if (*p == '#') {
6237 } while (p < e && *p != '\n');
6245 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
6246 Character classes ([:foo:]) can also be negated ([:^foo:]).
6247 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
6248 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
6249 but trigger failures because they are currently unimplemented. */
6251 #define POSIXCC_DONE(c) ((c) == ':')
6252 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
6253 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
6256 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
6259 I32 namedclass = OOB_NAMEDCLASS;
6261 if (value == '[' && RExC_parse + 1 < RExC_end &&
6262 /* I smell either [: or [= or [. -- POSIX has been here, right? */
6263 POSIXCC(UCHARAT(RExC_parse))) {
6264 const char c = UCHARAT(RExC_parse);
6265 char* const s = RExC_parse++;
6267 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
6269 if (RExC_parse == RExC_end)
6270 /* Grandfather lone [:, [=, [. */
6273 const char* const t = RExC_parse++; /* skip over the c */
6276 if (UCHARAT(RExC_parse) == ']') {
6277 const char *posixcc = s + 1;
6278 RExC_parse++; /* skip over the ending ] */
6281 const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
6282 const I32 skip = t - posixcc;
6284 /* Initially switch on the length of the name. */
6287 if (memEQ(posixcc, "word", 4)) /* this is not POSIX, this is the Perl \w */
6288 namedclass = complement ? ANYOF_NALNUM : ANYOF_ALNUM;
6291 /* Names all of length 5. */
6292 /* alnum alpha ascii blank cntrl digit graph lower
6293 print punct space upper */
6294 /* Offset 4 gives the best switch position. */
6295 switch (posixcc[4]) {
6297 if (memEQ(posixcc, "alph", 4)) /* alpha */
6298 namedclass = complement ? ANYOF_NALPHA : ANYOF_ALPHA;
6301 if (memEQ(posixcc, "spac", 4)) /* space */
6302 namedclass = complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
6305 if (memEQ(posixcc, "grap", 4)) /* graph */
6306 namedclass = complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
6309 if (memEQ(posixcc, "asci", 4)) /* ascii */
6310 namedclass = complement ? ANYOF_NASCII : ANYOF_ASCII;
6313 if (memEQ(posixcc, "blan", 4)) /* blank */
6314 namedclass = complement ? ANYOF_NBLANK : ANYOF_BLANK;
6317 if (memEQ(posixcc, "cntr", 4)) /* cntrl */
6318 namedclass = complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
6321 if (memEQ(posixcc, "alnu", 4)) /* alnum */
6322 namedclass = complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
6325 if (memEQ(posixcc, "lowe", 4)) /* lower */
6326 namedclass = complement ? ANYOF_NLOWER : ANYOF_LOWER;
6327 else if (memEQ(posixcc, "uppe", 4)) /* upper */
6328 namedclass = complement ? ANYOF_NUPPER : ANYOF_UPPER;
6331 if (memEQ(posixcc, "digi", 4)) /* digit */
6332 namedclass = complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
6333 else if (memEQ(posixcc, "prin", 4)) /* print */
6334 namedclass = complement ? ANYOF_NPRINT : ANYOF_PRINT;
6335 else if (memEQ(posixcc, "punc", 4)) /* punct */
6336 namedclass = complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
6341 if (memEQ(posixcc, "xdigit", 6))
6342 namedclass = complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
6346 if (namedclass == OOB_NAMEDCLASS)
6347 Simple_vFAIL3("POSIX class [:%.*s:] unknown",
6349 assert (posixcc[skip] == ':');
6350 assert (posixcc[skip+1] == ']');
6351 } else if (!SIZE_ONLY) {
6352 /* [[=foo=]] and [[.foo.]] are still future. */
6354 /* adjust RExC_parse so the warning shows after
6356 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
6358 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
6361 /* Maternal grandfather:
6362 * "[:" ending in ":" but not in ":]" */
6372 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
6375 if (POSIXCC(UCHARAT(RExC_parse))) {
6376 const char *s = RExC_parse;
6377 const char c = *s++;
6381 if (*s && c == *s && s[1] == ']') {
6382 if (ckWARN(WARN_REGEXP))
6384 "POSIX syntax [%c %c] belongs inside character classes",
6387 /* [[=foo=]] and [[.foo.]] are still future. */
6388 if (POSIXCC_NOTYET(c)) {
6389 /* adjust RExC_parse so the error shows after
6391 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
6393 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
6401 parse a class specification and produce either an ANYOF node that
6402 matches the pattern. If the pattern matches a single char only and
6403 that char is < 256 then we produce an EXACT node instead.
6406 S_regclass(pTHX_ RExC_state_t *pRExC_state, U32 depth)
6409 register UV value = 0;
6410 register UV nextvalue;
6411 register IV prevvalue = OOB_UNICODE;
6412 register IV range = 0;
6413 register regnode *ret;
6416 char *rangebegin = NULL;
6417 bool need_class = 0;
6420 bool optimize_invert = TRUE;
6421 AV* unicode_alternate = NULL;
6423 UV literal_endpoint = 0;
6425 UV stored = 0; /* number of chars stored in the class */
6427 regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
6428 case we need to change the emitted regop to an EXACT. */
6429 const char * orig_parse = RExC_parse;
6430 GET_RE_DEBUG_FLAGS_DECL;
6432 PERL_UNUSED_ARG(depth);
6435 DEBUG_PARSE("clas");
6437 /* Assume we are going to generate an ANYOF node. */
6438 ret = reganode(pRExC_state, ANYOF, 0);
6441 ANYOF_FLAGS(ret) = 0;
6443 if (UCHARAT(RExC_parse) == '^') { /* Complement of range. */
6447 ANYOF_FLAGS(ret) |= ANYOF_INVERT;
6451 RExC_size += ANYOF_SKIP;
6452 listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
6455 RExC_emit += ANYOF_SKIP;
6457 ANYOF_FLAGS(ret) |= ANYOF_FOLD;
6459 ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
6460 ANYOF_BITMAP_ZERO(ret);
6461 listsv = newSVpvs("# comment\n");
6464 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
6466 if (!SIZE_ONLY && POSIXCC(nextvalue))
6467 checkposixcc(pRExC_state);
6469 /* allow 1st char to be ] (allowing it to be - is dealt with later) */
6470 if (UCHARAT(RExC_parse) == ']')
6474 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
6478 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
6481 rangebegin = RExC_parse;
6483 value = utf8n_to_uvchr((U8*)RExC_parse,
6484 RExC_end - RExC_parse,
6485 &numlen, UTF8_ALLOW_DEFAULT);
6486 RExC_parse += numlen;
6489 value = UCHARAT(RExC_parse++);
6491 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
6492 if (value == '[' && POSIXCC(nextvalue))
6493 namedclass = regpposixcc(pRExC_state, value);
6494 else if (value == '\\') {
6496 value = utf8n_to_uvchr((U8*)RExC_parse,
6497 RExC_end - RExC_parse,
6498 &numlen, UTF8_ALLOW_DEFAULT);
6499 RExC_parse += numlen;
6502 value = UCHARAT(RExC_parse++);
6503 /* Some compilers cannot handle switching on 64-bit integer
6504 * values, therefore value cannot be an UV. Yes, this will
6505 * be a problem later if we want switch on Unicode.
6506 * A similar issue a little bit later when switching on
6507 * namedclass. --jhi */
6508 switch ((I32)value) {
6509 case 'w': namedclass = ANYOF_ALNUM; break;
6510 case 'W': namedclass = ANYOF_NALNUM; break;
6511 case 's': namedclass = ANYOF_SPACE; break;
6512 case 'S': namedclass = ANYOF_NSPACE; break;
6513 case 'd': namedclass = ANYOF_DIGIT; break;
6514 case 'D': namedclass = ANYOF_NDIGIT; break;
6515 case 'N': /* Handle \N{NAME} in class */
6517 /* We only pay attention to the first char of
6518 multichar strings being returned. I kinda wonder
6519 if this makes sense as it does change the behaviour
6520 from earlier versions, OTOH that behaviour was broken
6522 UV v; /* value is register so we cant & it /grrr */
6523 if (reg_namedseq(pRExC_state, &v)) {
6533 if (RExC_parse >= RExC_end)
6534 vFAIL2("Empty \\%c{}", (U8)value);
6535 if (*RExC_parse == '{') {
6536 const U8 c = (U8)value;
6537 e = strchr(RExC_parse++, '}');
6539 vFAIL2("Missing right brace on \\%c{}", c);
6540 while (isSPACE(UCHARAT(RExC_parse)))
6542 if (e == RExC_parse)
6543 vFAIL2("Empty \\%c{}", c);
6545 while (isSPACE(UCHARAT(RExC_parse + n - 1)))
6553 if (UCHARAT(RExC_parse) == '^') {
6556 value = value == 'p' ? 'P' : 'p'; /* toggle */
6557 while (isSPACE(UCHARAT(RExC_parse))) {
6562 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%.*s\n",
6563 (value=='p' ? '+' : '!'), (int)n, RExC_parse);
6566 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
6567 namedclass = ANYOF_MAX; /* no official name, but it's named */
6570 case 'n': value = '\n'; break;
6571 case 'r': value = '\r'; break;
6572 case 't': value = '\t'; break;
6573 case 'f': value = '\f'; break;
6574 case 'b': value = '\b'; break;
6575 case 'e': value = ASCII_TO_NATIVE('\033');break;
6576 case 'a': value = ASCII_TO_NATIVE('\007');break;
6578 if (*RExC_parse == '{') {
6579 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
6580 | PERL_SCAN_DISALLOW_PREFIX;
6581 char * const e = strchr(RExC_parse++, '}');
6583 vFAIL("Missing right brace on \\x{}");
6585 numlen = e - RExC_parse;
6586 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
6590 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
6592 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
6593 RExC_parse += numlen;
6597 value = UCHARAT(RExC_parse++);
6598 value = toCTRL(value);
6600 case '0': case '1': case '2': case '3': case '4':
6601 case '5': case '6': case '7': case '8': case '9':
6605 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
6606 RExC_parse += numlen;
6610 if (!SIZE_ONLY && isALPHA(value) && ckWARN(WARN_REGEXP))
6612 "Unrecognized escape \\%c in character class passed through",
6616 } /* end of \blah */
6622 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
6624 if (!SIZE_ONLY && !need_class)
6625 ANYOF_CLASS_ZERO(ret);
6629 /* a bad range like a-\d, a-[:digit:] ? */
6632 if (ckWARN(WARN_REGEXP)) {
6634 RExC_parse >= rangebegin ?
6635 RExC_parse - rangebegin : 0;
6637 "False [] range \"%*.*s\"",
6640 if (prevvalue < 256) {
6641 ANYOF_BITMAP_SET(ret, prevvalue);
6642 ANYOF_BITMAP_SET(ret, '-');
6645 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
6646 Perl_sv_catpvf(aTHX_ listsv,
6647 "%04"UVxf"\n%04"UVxf"\n", (UV)prevvalue, (UV) '-');
6651 range = 0; /* this was not a true range */
6655 const char *what = NULL;
6658 if (namedclass > OOB_NAMEDCLASS)
6659 optimize_invert = FALSE;
6660 /* Possible truncation here but in some 64-bit environments
6661 * the compiler gets heartburn about switch on 64-bit values.
6662 * A similar issue a little earlier when switching on value.
6664 switch ((I32)namedclass) {
6667 ANYOF_CLASS_SET(ret, ANYOF_ALNUM);
6669 for (value = 0; value < 256; value++)
6671 ANYOF_BITMAP_SET(ret, value);
6678 ANYOF_CLASS_SET(ret, ANYOF_NALNUM);
6680 for (value = 0; value < 256; value++)
6681 if (!isALNUM(value))
6682 ANYOF_BITMAP_SET(ret, value);
6689 ANYOF_CLASS_SET(ret, ANYOF_ALNUMC);
6691 for (value = 0; value < 256; value++)
6692 if (isALNUMC(value))
6693 ANYOF_BITMAP_SET(ret, value);
6700 ANYOF_CLASS_SET(ret, ANYOF_NALNUMC);
6702 for (value = 0; value < 256; value++)
6703 if (!isALNUMC(value))
6704 ANYOF_BITMAP_SET(ret, value);
6711 ANYOF_CLASS_SET(ret, ANYOF_ALPHA);
6713 for (value = 0; value < 256; value++)
6715 ANYOF_BITMAP_SET(ret, value);
6722 ANYOF_CLASS_SET(ret, ANYOF_NALPHA);
6724 for (value = 0; value < 256; value++)
6725 if (!isALPHA(value))
6726 ANYOF_BITMAP_SET(ret, value);
6733 ANYOF_CLASS_SET(ret, ANYOF_ASCII);
6736 for (value = 0; value < 128; value++)
6737 ANYOF_BITMAP_SET(ret, value);
6739 for (value = 0; value < 256; value++) {
6741 ANYOF_BITMAP_SET(ret, value);
6750 ANYOF_CLASS_SET(ret, ANYOF_NASCII);
6753 for (value = 128; value < 256; value++)
6754 ANYOF_BITMAP_SET(ret, value);
6756 for (value = 0; value < 256; value++) {
6757 if (!isASCII(value))
6758 ANYOF_BITMAP_SET(ret, value);
6767 ANYOF_CLASS_SET(ret, ANYOF_BLANK);
6769 for (value = 0; value < 256; value++)
6771 ANYOF_BITMAP_SET(ret, value);
6778 ANYOF_CLASS_SET(ret, ANYOF_NBLANK);
6780 for (value = 0; value < 256; value++)
6781 if (!isBLANK(value))
6782 ANYOF_BITMAP_SET(ret, value);
6789 ANYOF_CLASS_SET(ret, ANYOF_CNTRL);
6791 for (value = 0; value < 256; value++)
6793 ANYOF_BITMAP_SET(ret, value);
6800 ANYOF_CLASS_SET(ret, ANYOF_NCNTRL);
6802 for (value = 0; value < 256; value++)
6803 if (!isCNTRL(value))
6804 ANYOF_BITMAP_SET(ret, value);
6811 ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
6813 /* consecutive digits assumed */
6814 for (value = '0'; value <= '9'; value++)
6815 ANYOF_BITMAP_SET(ret, value);
6822 ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
6824 /* consecutive digits assumed */
6825 for (value = 0; value < '0'; value++)
6826 ANYOF_BITMAP_SET(ret, value);
6827 for (value = '9' + 1; value < 256; value++)
6828 ANYOF_BITMAP_SET(ret, value);
6835 ANYOF_CLASS_SET(ret, ANYOF_GRAPH);
6837 for (value = 0; value < 256; value++)
6839 ANYOF_BITMAP_SET(ret, value);
6846 ANYOF_CLASS_SET(ret, ANYOF_NGRAPH);
6848 for (value = 0; value < 256; value++)
6849 if (!isGRAPH(value))
6850 ANYOF_BITMAP_SET(ret, value);
6857 ANYOF_CLASS_SET(ret, ANYOF_LOWER);
6859 for (value = 0; value < 256; value++)
6861 ANYOF_BITMAP_SET(ret, value);
6868 ANYOF_CLASS_SET(ret, ANYOF_NLOWER);
6870 for (value = 0; value < 256; value++)
6871 if (!isLOWER(value))
6872 ANYOF_BITMAP_SET(ret, value);
6879 ANYOF_CLASS_SET(ret, ANYOF_PRINT);
6881 for (value = 0; value < 256; value++)
6883 ANYOF_BITMAP_SET(ret, value);
6890 ANYOF_CLASS_SET(ret, ANYOF_NPRINT);
6892 for (value = 0; value < 256; value++)
6893 if (!isPRINT(value))
6894 ANYOF_BITMAP_SET(ret, value);
6901 ANYOF_CLASS_SET(ret, ANYOF_PSXSPC);
6903 for (value = 0; value < 256; value++)
6904 if (isPSXSPC(value))
6905 ANYOF_BITMAP_SET(ret, value);
6912 ANYOF_CLASS_SET(ret, ANYOF_NPSXSPC);
6914 for (value = 0; value < 256; value++)
6915 if (!isPSXSPC(value))
6916 ANYOF_BITMAP_SET(ret, value);
6923 ANYOF_CLASS_SET(ret, ANYOF_PUNCT);
6925 for (value = 0; value < 256; value++)
6927 ANYOF_BITMAP_SET(ret, value);
6934 ANYOF_CLASS_SET(ret, ANYOF_NPUNCT);
6936 for (value = 0; value < 256; value++)
6937 if (!isPUNCT(value))
6938 ANYOF_BITMAP_SET(ret, value);
6945 ANYOF_CLASS_SET(ret, ANYOF_SPACE);
6947 for (value = 0; value < 256; value++)
6949 ANYOF_BITMAP_SET(ret, value);
6956 ANYOF_CLASS_SET(ret, ANYOF_NSPACE);
6958 for (value = 0; value < 256; value++)
6959 if (!isSPACE(value))
6960 ANYOF_BITMAP_SET(ret, value);
6967 ANYOF_CLASS_SET(ret, ANYOF_UPPER);
6969 for (value = 0; value < 256; value++)
6971 ANYOF_BITMAP_SET(ret, value);
6978 ANYOF_CLASS_SET(ret, ANYOF_NUPPER);
6980 for (value = 0; value < 256; value++)
6981 if (!isUPPER(value))
6982 ANYOF_BITMAP_SET(ret, value);
6989 ANYOF_CLASS_SET(ret, ANYOF_XDIGIT);
6991 for (value = 0; value < 256; value++)
6992 if (isXDIGIT(value))
6993 ANYOF_BITMAP_SET(ret, value);
7000 ANYOF_CLASS_SET(ret, ANYOF_NXDIGIT);
7002 for (value = 0; value < 256; value++)
7003 if (!isXDIGIT(value))
7004 ANYOF_BITMAP_SET(ret, value);
7010 /* this is to handle \p and \P */
7013 vFAIL("Invalid [::] class");
7017 /* Strings such as "+utf8::isWord\n" */
7018 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::Is%s\n", yesno, what);
7021 ANYOF_FLAGS(ret) |= ANYOF_CLASS;
7024 } /* end of namedclass \blah */
7027 if (prevvalue > (IV)value) /* b-a */ {
7028 const int w = RExC_parse - rangebegin;
7029 Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
7030 range = 0; /* not a valid range */
7034 prevvalue = value; /* save the beginning of the range */
7035 if (*RExC_parse == '-' && RExC_parse+1 < RExC_end &&
7036 RExC_parse[1] != ']') {
7039 /* a bad range like \w-, [:word:]- ? */
7040 if (namedclass > OOB_NAMEDCLASS) {
7041 if (ckWARN(WARN_REGEXP)) {
7043 RExC_parse >= rangebegin ?
7044 RExC_parse - rangebegin : 0;
7046 "False [] range \"%*.*s\"",
7050 ANYOF_BITMAP_SET(ret, '-');
7052 range = 1; /* yeah, it's a range! */
7053 continue; /* but do it the next time */
7057 /* now is the next time */
7058 /*stored += (value - prevvalue + 1);*/
7060 if (prevvalue < 256) {
7061 const IV ceilvalue = value < 256 ? value : 255;
7064 /* In EBCDIC [\x89-\x91] should include
7065 * the \x8e but [i-j] should not. */
7066 if (literal_endpoint == 2 &&
7067 ((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
7068 (isUPPER(prevvalue) && isUPPER(ceilvalue))))
7070 if (isLOWER(prevvalue)) {
7071 for (i = prevvalue; i <= ceilvalue; i++)
7073 ANYOF_BITMAP_SET(ret, i);
7075 for (i = prevvalue; i <= ceilvalue; i++)
7077 ANYOF_BITMAP_SET(ret, i);
7082 for (i = prevvalue; i <= ceilvalue; i++) {
7083 if (!ANYOF_BITMAP_TEST(ret,i)) {
7085 ANYOF_BITMAP_SET(ret, i);
7089 if (value > 255 || UTF) {
7090 const UV prevnatvalue = NATIVE_TO_UNI(prevvalue);
7091 const UV natvalue = NATIVE_TO_UNI(value);
7092 stored+=2; /* can't optimize this class */
7093 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
7094 if (prevnatvalue < natvalue) { /* what about > ? */
7095 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
7096 prevnatvalue, natvalue);
7098 else if (prevnatvalue == natvalue) {
7099 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n", natvalue);
7101 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
7103 const UV f = to_uni_fold(natvalue, foldbuf, &foldlen);
7105 #ifdef EBCDIC /* RD t/uni/fold ff and 6b */
7106 if (RExC_precomp[0] == ':' &&
7107 RExC_precomp[1] == '[' &&
7108 (f == 0xDF || f == 0x92)) {
7109 f = NATIVE_TO_UNI(f);
7112 /* If folding and foldable and a single
7113 * character, insert also the folded version
7114 * to the charclass. */
7116 #ifdef EBCDIC /* RD tunifold ligatures s,t fb05, fb06 */
7117 if ((RExC_precomp[0] == ':' &&
7118 RExC_precomp[1] == '[' &&
7120 (value == 0xFB05 || value == 0xFB06))) ?
7121 foldlen == ((STRLEN)UNISKIP(f) - 1) :
7122 foldlen == (STRLEN)UNISKIP(f) )
7124 if (foldlen == (STRLEN)UNISKIP(f))
7126 Perl_sv_catpvf(aTHX_ listsv,
7129 /* Any multicharacter foldings
7130 * require the following transform:
7131 * [ABCDEF] -> (?:[ABCabcDEFd]|pq|rst)
7132 * where E folds into "pq" and F folds
7133 * into "rst", all other characters
7134 * fold to single characters. We save
7135 * away these multicharacter foldings,
7136 * to be later saved as part of the
7137 * additional "s" data. */
7140 if (!unicode_alternate)
7141 unicode_alternate = newAV();
7142 sv = newSVpvn((char*)foldbuf, foldlen);
7144 av_push(unicode_alternate, sv);
7148 /* If folding and the value is one of the Greek
7149 * sigmas insert a few more sigmas to make the
7150 * folding rules of the sigmas to work right.
7151 * Note that not all the possible combinations
7152 * are handled here: some of them are handled
7153 * by the standard folding rules, and some of
7154 * them (literal or EXACTF cases) are handled
7155 * during runtime in regexec.c:S_find_byclass(). */
7156 if (value == UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA) {
7157 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7158 (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA);
7159 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7160 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
7162 else if (value == UNICODE_GREEK_CAPITAL_LETTER_SIGMA)
7163 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7164 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
7169 literal_endpoint = 0;
7173 range = 0; /* this range (if it was one) is done now */
7177 ANYOF_FLAGS(ret) |= ANYOF_LARGE;
7179 RExC_size += ANYOF_CLASS_ADD_SKIP;
7181 RExC_emit += ANYOF_CLASS_ADD_SKIP;
7187 /****** !SIZE_ONLY AFTER HERE *********/
7189 if( stored == 1 && value < 256
7190 && !( ANYOF_FLAGS(ret) & ( ANYOF_FLAGS_ALL ^ ANYOF_FOLD ) )
7192 /* optimize single char class to an EXACT node
7193 but *only* when its not a UTF/high char */
7194 const char * cur_parse= RExC_parse;
7195 RExC_emit = (regnode *)orig_emit;
7196 RExC_parse = (char *)orig_parse;
7197 ret = reg_node(pRExC_state,
7198 (U8)((ANYOF_FLAGS(ret) & ANYOF_FOLD) ? EXACTF : EXACT));
7199 RExC_parse = (char *)cur_parse;
7200 *STRING(ret)= (char)value;
7202 RExC_emit += STR_SZ(1);
7205 /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
7206 if ( /* If the only flag is folding (plus possibly inversion). */
7207 ((ANYOF_FLAGS(ret) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD)
7209 for (value = 0; value < 256; ++value) {
7210 if (ANYOF_BITMAP_TEST(ret, value)) {
7211 UV fold = PL_fold[value];
7214 ANYOF_BITMAP_SET(ret, fold);
7217 ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
7220 /* optimize inverted simple patterns (e.g. [^a-z]) */
7221 if (optimize_invert &&
7222 /* If the only flag is inversion. */
7223 (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
7224 for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
7225 ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
7226 ANYOF_FLAGS(ret) = ANYOF_UNICODE_ALL;
7229 AV * const av = newAV();
7231 /* The 0th element stores the character class description
7232 * in its textual form: used later (regexec.c:Perl_regclass_swash())
7233 * to initialize the appropriate swash (which gets stored in
7234 * the 1st element), and also useful for dumping the regnode.
7235 * The 2nd element stores the multicharacter foldings,
7236 * used later (regexec.c:S_reginclass()). */
7237 av_store(av, 0, listsv);
7238 av_store(av, 1, NULL);
7239 av_store(av, 2, (SV*)unicode_alternate);
7240 rv = newRV_noinc((SV*)av);
7241 n = add_data(pRExC_state, 1, "s");
7242 RExC_rx->data->data[n] = (void*)rv;
7249 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
7251 char* const retval = RExC_parse++;
7254 if (*RExC_parse == '(' && RExC_parse[1] == '?' &&
7255 RExC_parse[2] == '#') {
7256 while (*RExC_parse != ')') {
7257 if (RExC_parse == RExC_end)
7258 FAIL("Sequence (?#... not terminated");
7264 if (RExC_flags & PMf_EXTENDED) {
7265 if (isSPACE(*RExC_parse)) {
7269 else if (*RExC_parse == '#') {
7270 while (RExC_parse < RExC_end)
7271 if (*RExC_parse++ == '\n') break;
7280 - reg_node - emit a node
7282 STATIC regnode * /* Location. */
7283 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
7286 register regnode *ptr;
7287 regnode * const ret = RExC_emit;
7288 GET_RE_DEBUG_FLAGS_DECL;
7291 SIZE_ALIGN(RExC_size);
7295 NODE_ALIGN_FILL(ret);
7297 FILL_ADVANCE_NODE(ptr, op);
7298 if (RExC_offsets) { /* MJD */
7299 MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n",
7300 "reg_node", __LINE__,
7302 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0]
7303 ? "Overwriting end of array!\n" : "OK",
7304 (UV)(RExC_emit - RExC_emit_start),
7305 (UV)(RExC_parse - RExC_start),
7306 (UV)RExC_offsets[0]));
7307 Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
7316 - reganode - emit a node with an argument
7318 STATIC regnode * /* Location. */
7319 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
7322 register regnode *ptr;
7323 regnode * const ret = RExC_emit;
7324 GET_RE_DEBUG_FLAGS_DECL;
7327 SIZE_ALIGN(RExC_size);
7332 assert(2==regarglen[op]+1);
7334 Anything larger than this has to allocate the extra amount.
7335 If we changed this to be:
7337 RExC_size += (1 + regarglen[op]);
7339 then it wouldn't matter. Its not clear what side effect
7340 might come from that so its not done so far.
7346 NODE_ALIGN_FILL(ret);
7348 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
7349 if (RExC_offsets) { /* MJD */
7350 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
7354 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ?
7355 "Overwriting end of array!\n" : "OK",
7356 (UV)(RExC_emit - RExC_emit_start),
7357 (UV)(RExC_parse - RExC_start),
7358 (UV)RExC_offsets[0]));
7359 Set_Cur_Node_Offset;
7368 - reguni - emit (if appropriate) a Unicode character
7371 S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
7374 return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
7378 - reginsert - insert an operator in front of already-emitted operand
7380 * Means relocating the operand.
7383 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
7386 register regnode *src;
7387 register regnode *dst;
7388 register regnode *place;
7389 const int offset = regarglen[(U8)op];
7390 const int size = NODE_STEP_REGNODE + offset;
7391 GET_RE_DEBUG_FLAGS_DECL;
7392 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
7393 DEBUG_PARSE_FMT("inst"," - %s",reg_name[op]);
7404 for ( paren=0 ; paren < RExC_npar ; paren++ ) {
7405 if ( RExC_parens[paren] >= src )
7406 RExC_parens[paren] += size;
7410 while (src > opnd) {
7411 StructCopy(--src, --dst, regnode);
7412 if (RExC_offsets) { /* MJD 20010112 */
7413 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
7417 (UV)(dst - RExC_emit_start) > RExC_offsets[0]
7418 ? "Overwriting end of array!\n" : "OK",
7419 (UV)(src - RExC_emit_start),
7420 (UV)(dst - RExC_emit_start),
7421 (UV)RExC_offsets[0]));
7422 Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
7423 Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
7428 place = opnd; /* Op node, where operand used to be. */
7429 if (RExC_offsets) { /* MJD */
7430 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
7434 (UV)(place - RExC_emit_start) > RExC_offsets[0]
7435 ? "Overwriting end of array!\n" : "OK",
7436 (UV)(place - RExC_emit_start),
7437 (UV)(RExC_parse - RExC_start),
7438 (UV)RExC_offsets[0]));
7439 Set_Node_Offset(place, RExC_parse);
7440 Set_Node_Length(place, 1);
7442 src = NEXTOPER(place);
7443 FILL_ADVANCE_NODE(place, op);
7444 Zero(src, offset, regnode);
7448 - regtail - set the next-pointer at the end of a node chain of p to val.
7449 - SEE ALSO: regtail_study
7451 /* TODO: All three parms should be const */
7453 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
7456 register regnode *scan;
7457 GET_RE_DEBUG_FLAGS_DECL;
7459 PERL_UNUSED_ARG(depth);
7465 /* Find last node. */
7468 regnode * const temp = regnext(scan);
7470 SV * const mysv=sv_newmortal();
7471 DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
7472 regprop(RExC_rx, mysv, scan);
7473 PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
7474 SvPV_nolen_const(mysv), REG_NODE_NUM(scan),
7475 (temp == NULL ? "->" : ""),
7476 (temp == NULL ? reg_name[OP(val)] : "")
7484 if (reg_off_by_arg[OP(scan)]) {
7485 ARG_SET(scan, val - scan);
7488 NEXT_OFF(scan) = val - scan;
7494 - regtail_study - set the next-pointer at the end of a node chain of p to val.
7495 - Look for optimizable sequences at the same time.
7496 - currently only looks for EXACT chains.
7498 This is expermental code. The idea is to use this routine to perform
7499 in place optimizations on branches and groups as they are constructed,
7500 with the long term intention of removing optimization from study_chunk so
7501 that it is purely analytical.
7503 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
7504 to control which is which.
7507 /* TODO: All four parms should be const */
7510 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
7513 register regnode *scan;
7515 #ifdef EXPERIMENTAL_INPLACESCAN
7519 GET_RE_DEBUG_FLAGS_DECL;
7525 /* Find last node. */
7529 regnode * const temp = regnext(scan);
7530 #ifdef EXPERIMENTAL_INPLACESCAN
7531 if (PL_regkind[OP(scan)] == EXACT)
7532 if (join_exact(pRExC_state,scan,&min,1,val,depth+1))
7540 if( exact == PSEUDO )
7542 else if ( exact != OP(scan) )
7551 SV * const mysv=sv_newmortal();
7552 DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
7553 regprop(RExC_rx, mysv, scan);
7554 PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
7555 SvPV_nolen_const(mysv),
7564 SV * const mysv_val=sv_newmortal();
7565 DEBUG_PARSE_MSG("");
7566 regprop(RExC_rx, mysv_val, val);
7567 PerlIO_printf(Perl_debug_log, "~ attach to %s (%d) offset to %d\n",
7568 SvPV_nolen_const(mysv_val),
7573 if (reg_off_by_arg[OP(scan)]) {
7574 ARG_SET(scan, val - scan);
7577 NEXT_OFF(scan) = val - scan;
7585 - regcurly - a little FSA that accepts {\d+,?\d*}
7588 S_regcurly(register const char *s)
7607 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
7610 Perl_regdump(pTHX_ const regexp *r)
7614 SV * const sv = sv_newmortal();
7615 SV *dsv= sv_newmortal();
7617 (void)dumpuntil(r, r->program, r->program + 1, NULL, NULL, sv, 0, 0);
7619 /* Header fields of interest. */
7620 if (r->anchored_substr) {
7621 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr),
7622 RE_SV_DUMPLEN(r->anchored_substr), 30);
7623 PerlIO_printf(Perl_debug_log,
7624 "anchored %s%s at %"IVdf" ",
7625 s, RE_SV_TAIL(r->anchored_substr),
7626 (IV)r->anchored_offset);
7627 } else if (r->anchored_utf8) {
7628 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8),
7629 RE_SV_DUMPLEN(r->anchored_utf8), 30);
7630 PerlIO_printf(Perl_debug_log,
7631 "anchored utf8 %s%s at %"IVdf" ",
7632 s, RE_SV_TAIL(r->anchored_utf8),
7633 (IV)r->anchored_offset);
7635 if (r->float_substr) {
7636 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr),
7637 RE_SV_DUMPLEN(r->float_substr), 30);
7638 PerlIO_printf(Perl_debug_log,
7639 "floating %s%s at %"IVdf"..%"UVuf" ",
7640 s, RE_SV_TAIL(r->float_substr),
7641 (IV)r->float_min_offset, (UV)r->float_max_offset);
7642 } else if (r->float_utf8) {
7643 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8),
7644 RE_SV_DUMPLEN(r->float_utf8), 30);
7645 PerlIO_printf(Perl_debug_log,
7646 "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
7647 s, RE_SV_TAIL(r->float_utf8),
7648 (IV)r->float_min_offset, (UV)r->float_max_offset);
7650 if (r->check_substr || r->check_utf8)
7651 PerlIO_printf(Perl_debug_log,
7653 (r->check_substr == r->float_substr
7654 && r->check_utf8 == r->float_utf8
7655 ? "(checking floating" : "(checking anchored"));
7656 if (r->reganch & ROPT_NOSCAN)
7657 PerlIO_printf(Perl_debug_log, " noscan");
7658 if (r->reganch & ROPT_CHECK_ALL)
7659 PerlIO_printf(Perl_debug_log, " isall");
7660 if (r->check_substr || r->check_utf8)
7661 PerlIO_printf(Perl_debug_log, ") ");
7663 if (r->regstclass) {
7664 regprop(r, sv, r->regstclass);
7665 PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
7667 if (r->reganch & ROPT_ANCH) {
7668 PerlIO_printf(Perl_debug_log, "anchored");
7669 if (r->reganch & ROPT_ANCH_BOL)
7670 PerlIO_printf(Perl_debug_log, "(BOL)");
7671 if (r->reganch & ROPT_ANCH_MBOL)
7672 PerlIO_printf(Perl_debug_log, "(MBOL)");
7673 if (r->reganch & ROPT_ANCH_SBOL)
7674 PerlIO_printf(Perl_debug_log, "(SBOL)");
7675 if (r->reganch & ROPT_ANCH_GPOS)
7676 PerlIO_printf(Perl_debug_log, "(GPOS)");
7677 PerlIO_putc(Perl_debug_log, ' ');
7679 if (r->reganch & ROPT_GPOS_SEEN)
7680 PerlIO_printf(Perl_debug_log, "GPOS ");
7681 if (r->reganch & ROPT_SKIP)
7682 PerlIO_printf(Perl_debug_log, "plus ");
7683 if (r->reganch & ROPT_IMPLICIT)
7684 PerlIO_printf(Perl_debug_log, "implicit ");
7685 PerlIO_printf(Perl_debug_log, "minlen %ld ", (long) r->minlen);
7686 if (r->reganch & ROPT_EVAL_SEEN)
7687 PerlIO_printf(Perl_debug_log, "with eval ");
7688 PerlIO_printf(Perl_debug_log, "\n");
7690 PERL_UNUSED_CONTEXT;
7692 #endif /* DEBUGGING */
7696 - regprop - printable representation of opcode
7699 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
7704 GET_RE_DEBUG_FLAGS_DECL;
7706 sv_setpvn(sv, "", 0);
7707 if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */
7708 /* It would be nice to FAIL() here, but this may be called from
7709 regexec.c, and it would be hard to supply pRExC_state. */
7710 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
7711 sv_catpv(sv, reg_name[OP(o)]); /* Take off const! */
7713 k = PL_regkind[OP(o)];
7716 SV * const dsv = sv_2mortal(newSVpvs(""));
7717 /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
7718 * is a crude hack but it may be the best for now since
7719 * we have no flag "this EXACTish node was UTF-8"
7721 const char * const s =
7722 pv_pretty(dsv, STRING(o), STR_LEN(o), 60,
7723 PL_colors[0], PL_colors[1],
7724 PERL_PV_ESCAPE_UNI_DETECT |
7725 PERL_PV_PRETTY_ELIPSES |
7728 Perl_sv_catpvf(aTHX_ sv, " %s", s );
7729 } else if (k == TRIE) {
7730 /* print the details of the trie in dumpuntil instead, as
7731 * prog->data isn't available here */
7732 const char op = OP(o);
7733 const I32 n = ARG(o);
7734 const reg_ac_data * const ac = IS_TRIE_AC(op) ?
7735 (reg_ac_data *)prog->data->data[n] :
7737 const reg_trie_data * const trie = !IS_TRIE_AC(op) ?
7738 (reg_trie_data*)prog->data->data[n] :
7741 Perl_sv_catpvf(aTHX_ sv, "-%s",reg_name[o->flags]);
7742 DEBUG_TRIE_COMPILE_r(
7743 Perl_sv_catpvf(aTHX_ sv,
7744 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
7745 (UV)trie->startstate,
7746 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
7747 (UV)trie->wordcount,
7750 (UV)TRIE_CHARCOUNT(trie),
7751 (UV)trie->uniquecharcount
7754 if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
7756 int rangestart = -1;
7757 U8* bitmap = IS_ANYOF_TRIE(op) ? (U8*)ANYOF_BITMAP(o) : (U8*)TRIE_BITMAP(trie);
7758 Perl_sv_catpvf(aTHX_ sv, "[");
7759 for (i = 0; i <= 256; i++) {
7760 if (i < 256 && BITMAP_TEST(bitmap,i)) {
7761 if (rangestart == -1)
7763 } else if (rangestart != -1) {
7764 if (i <= rangestart + 3)
7765 for (; rangestart < i; rangestart++)
7766 put_byte(sv, rangestart);
7768 put_byte(sv, rangestart);
7770 put_byte(sv, i - 1);
7775 Perl_sv_catpvf(aTHX_ sv, "]");
7778 } else if (k == CURLY) {
7779 if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
7780 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
7781 Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
7783 else if (k == WHILEM && o->flags) /* Ordinal/of */
7784 Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
7785 else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP)
7786 Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o)); /* Parenth number */
7787 else if (k == RECURSE)
7788 Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
7789 else if (k == LOGICAL)
7790 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* 2: embedded, otherwise 1 */
7791 else if (k == ANYOF) {
7792 int i, rangestart = -1;
7793 const U8 flags = ANYOF_FLAGS(o);
7795 /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
7796 static const char * const anyofs[] = {
7829 if (flags & ANYOF_LOCALE)
7830 sv_catpvs(sv, "{loc}");
7831 if (flags & ANYOF_FOLD)
7832 sv_catpvs(sv, "{i}");
7833 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
7834 if (flags & ANYOF_INVERT)
7836 for (i = 0; i <= 256; i++) {
7837 if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
7838 if (rangestart == -1)
7840 } else if (rangestart != -1) {
7841 if (i <= rangestart + 3)
7842 for (; rangestart < i; rangestart++)
7843 put_byte(sv, rangestart);
7845 put_byte(sv, rangestart);
7847 put_byte(sv, i - 1);
7853 if (o->flags & ANYOF_CLASS)
7854 for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++)
7855 if (ANYOF_CLASS_TEST(o,i))
7856 sv_catpv(sv, anyofs[i]);
7858 if (flags & ANYOF_UNICODE)
7859 sv_catpvs(sv, "{unicode}");
7860 else if (flags & ANYOF_UNICODE_ALL)
7861 sv_catpvs(sv, "{unicode_all}");
7865 SV * const sw = regclass_swash(prog, o, FALSE, &lv, 0);
7869 U8 s[UTF8_MAXBYTES_CASE+1];
7871 for (i = 0; i <= 256; i++) { /* just the first 256 */
7872 uvchr_to_utf8(s, i);
7874 if (i < 256 && swash_fetch(sw, s, TRUE)) {
7875 if (rangestart == -1)
7877 } else if (rangestart != -1) {
7878 if (i <= rangestart + 3)
7879 for (; rangestart < i; rangestart++) {
7880 const U8 * const e = uvchr_to_utf8(s,rangestart);
7882 for(p = s; p < e; p++)
7886 const U8 *e = uvchr_to_utf8(s,rangestart);
7888 for (p = s; p < e; p++)
7891 e = uvchr_to_utf8(s, i-1);
7892 for (p = s; p < e; p++)
7899 sv_catpvs(sv, "..."); /* et cetera */
7903 char *s = savesvpv(lv);
7904 char * const origs = s;
7906 while (*s && *s != '\n')
7910 const char * const t = ++s;
7928 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
7930 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
7931 Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
7933 PERL_UNUSED_CONTEXT;
7934 PERL_UNUSED_ARG(sv);
7936 PERL_UNUSED_ARG(prog);
7937 #endif /* DEBUGGING */
7941 Perl_re_intuit_string(pTHX_ regexp *prog)
7942 { /* Assume that RE_INTUIT is set */
7944 GET_RE_DEBUG_FLAGS_DECL;
7945 PERL_UNUSED_CONTEXT;
7949 const char * const s = SvPV_nolen_const(prog->check_substr
7950 ? prog->check_substr : prog->check_utf8);
7952 if (!PL_colorset) reginitcolors();
7953 PerlIO_printf(Perl_debug_log,
7954 "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
7956 prog->check_substr ? "" : "utf8 ",
7957 PL_colors[5],PL_colors[0],
7960 (strlen(s) > 60 ? "..." : ""));
7963 return prog->check_substr ? prog->check_substr : prog->check_utf8;
7967 pregfree - free a regexp
7969 See regdupe below if you change anything here.
7973 Perl_pregfree(pTHX_ struct regexp *r)
7977 GET_RE_DEBUG_FLAGS_DECL;
7979 if (!r || (--r->refcnt > 0))
7985 SV *dsv= sv_newmortal();
7986 RE_PV_QUOTED_DECL(s, (r->reganch & ROPT_UTF8),
7987 dsv, r->precomp, r->prelen, 60);
7988 PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n",
7989 PL_colors[4],PL_colors[5],s);
7993 /* gcov results gave these as non-null 100% of the time, so there's no
7994 optimisation in checking them before calling Safefree */
7995 Safefree(r->precomp);
7996 Safefree(r->offsets); /* 20010421 MJD */
7997 RX_MATCH_COPY_FREE(r);
7998 #ifdef PERL_OLD_COPY_ON_WRITE
8000 SvREFCNT_dec(r->saved_copy);
8003 if (r->anchored_substr)
8004 SvREFCNT_dec(r->anchored_substr);
8005 if (r->anchored_utf8)
8006 SvREFCNT_dec(r->anchored_utf8);
8007 if (r->float_substr)
8008 SvREFCNT_dec(r->float_substr);
8010 SvREFCNT_dec(r->float_utf8);
8011 Safefree(r->substrs);
8014 SvREFCNT_dec(r->paren_names);
8016 int n = r->data->count;
8017 PAD* new_comppad = NULL;
8022 /* If you add a ->what type here, update the comment in regcomp.h */
8023 switch (r->data->what[n]) {
8026 SvREFCNT_dec((SV*)r->data->data[n]);
8029 Safefree(r->data->data[n]);
8032 new_comppad = (AV*)r->data->data[n];
8035 if (new_comppad == NULL)
8036 Perl_croak(aTHX_ "panic: pregfree comppad");
8037 PAD_SAVE_LOCAL(old_comppad,
8038 /* Watch out for global destruction's random ordering. */
8039 (SvTYPE(new_comppad) == SVt_PVAV) ? new_comppad : NULL
8042 refcnt = OpREFCNT_dec((OP_4tree*)r->data->data[n]);
8045 op_free((OP_4tree*)r->data->data[n]);
8047 PAD_RESTORE_LOCAL(old_comppad);
8048 SvREFCNT_dec((SV*)new_comppad);
8054 { /* Aho Corasick add-on structure for a trie node.
8055 Used in stclass optimization only */
8057 reg_ac_data *aho=(reg_ac_data*)r->data->data[n];
8059 refcount = --aho->refcount;
8062 Safefree(aho->states);
8063 Safefree(aho->fail);
8064 aho->trie=NULL; /* not necessary to free this as it is
8065 handled by the 't' case */
8066 Safefree(r->data->data[n]); /* do this last!!!! */
8067 Safefree(r->regstclass);
8073 /* trie structure. */
8075 reg_trie_data *trie=(reg_trie_data*)r->data->data[n];
8077 refcount = --trie->refcount;
8080 Safefree(trie->charmap);
8081 if (trie->widecharmap)
8082 SvREFCNT_dec((SV*)trie->widecharmap);
8083 Safefree(trie->states);
8084 Safefree(trie->trans);
8086 Safefree(trie->bitmap);
8088 Safefree(trie->wordlen);
8090 Safefree(trie->jump);
8092 Safefree(trie->nextword);
8096 SvREFCNT_dec((SV*)trie->words);
8097 if (trie->revcharmap)
8098 SvREFCNT_dec((SV*)trie->revcharmap);
8101 Safefree(r->data->data[n]); /* do this last!!!! */
8106 Perl_croak(aTHX_ "panic: regfree data code '%c'", r->data->what[n]);
8109 Safefree(r->data->what);
8112 Safefree(r->startp);
8117 #define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
8118 #define av_dup_inc(s,t) (AV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8119 #define hv_dup_inc(s,t) (HV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8120 #define SAVEPVN(p,n) ((p) ? savepvn(p,n) : NULL)
8123 regdupe - duplicate a regexp.
8125 This routine is called by sv.c's re_dup and is expected to clone a
8126 given regexp structure. It is a no-op when not under USE_ITHREADS.
8127 (Originally this *was* re_dup() for change history see sv.c)
8129 See pregfree() above if you change anything here.
8131 #if defined(USE_ITHREADS)
8133 Perl_regdupe(pTHX_ const regexp *r, CLONE_PARAMS *param)
8138 struct reg_substr_datum *s;
8141 return (REGEXP *)NULL;
8143 if ((ret = (REGEXP *)ptr_table_fetch(PL_ptr_table, r)))
8146 len = r->offsets[0];
8147 npar = r->nparens+1;
8149 Newxc(ret, sizeof(regexp) + (len+1)*sizeof(regnode), char, regexp);
8150 Copy(r->program, ret->program, len+1, regnode);
8152 Newx(ret->startp, npar, I32);
8153 Copy(r->startp, ret->startp, npar, I32);
8154 Newx(ret->endp, npar, I32);
8155 Copy(r->startp, ret->startp, npar, I32);
8157 Newx(ret->substrs, 1, struct reg_substr_data);
8158 for (s = ret->substrs->data, i = 0; i < 3; i++, s++) {
8159 s->min_offset = r->substrs->data[i].min_offset;
8160 s->max_offset = r->substrs->data[i].max_offset;
8161 s->end_shift = r->substrs->data[i].end_shift;
8162 s->substr = sv_dup_inc(r->substrs->data[i].substr, param);
8163 s->utf8_substr = sv_dup_inc(r->substrs->data[i].utf8_substr, param);
8166 ret->regstclass = NULL;
8169 const int count = r->data->count;
8172 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
8173 char, struct reg_data);
8174 Newx(d->what, count, U8);
8177 for (i = 0; i < count; i++) {
8178 d->what[i] = r->data->what[i];
8179 switch (d->what[i]) {
8180 /* legal options are one of: sfpont
8181 see also regcomp.h and pregfree() */
8184 d->data[i] = sv_dup_inc((SV *)r->data->data[i], param);
8187 d->data[i] = av_dup_inc((AV *)r->data->data[i], param);
8190 /* This is cheating. */
8191 Newx(d->data[i], 1, struct regnode_charclass_class);
8192 StructCopy(r->data->data[i], d->data[i],
8193 struct regnode_charclass_class);
8194 ret->regstclass = (regnode*)d->data[i];
8197 /* Compiled op trees are readonly, and can thus be
8198 shared without duplication. */
8200 d->data[i] = (void*)OpREFCNT_inc((OP*)r->data->data[i]);
8204 d->data[i] = r->data->data[i];
8207 d->data[i] = r->data->data[i];
8209 ((reg_trie_data*)d->data[i])->refcount++;
8213 d->data[i] = r->data->data[i];
8215 ((reg_ac_data*)d->data[i])->refcount++;
8217 /* Trie stclasses are readonly and can thus be shared
8218 * without duplication. We free the stclass in pregfree
8219 * when the corresponding reg_ac_data struct is freed.
8221 ret->regstclass= r->regstclass;
8224 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", r->data->what[i]);
8233 Newx(ret->offsets, 2*len+1, U32);
8234 Copy(r->offsets, ret->offsets, 2*len+1, U32);
8236 ret->precomp = SAVEPVN(r->precomp, r->prelen);
8237 ret->refcnt = r->refcnt;
8238 ret->minlen = r->minlen;
8239 ret->prelen = r->prelen;
8240 ret->nparens = r->nparens;
8241 ret->lastparen = r->lastparen;
8242 ret->lastcloseparen = r->lastcloseparen;
8243 ret->reganch = r->reganch;
8245 ret->sublen = r->sublen;
8247 ret->engine = r->engine;
8249 ret->paren_names = hv_dup_inc(r->paren_names, param);
8251 if (RX_MATCH_COPIED(ret))
8252 ret->subbeg = SAVEPVN(r->subbeg, r->sublen);
8255 #ifdef PERL_OLD_COPY_ON_WRITE
8256 ret->saved_copy = NULL;
8259 ptr_table_store(PL_ptr_table, r, ret);
8264 #ifndef PERL_IN_XSUB_RE
8266 - regnext - dig the "next" pointer out of a node
8269 Perl_regnext(pTHX_ register regnode *p)
8272 register I32 offset;
8274 if (p == &PL_regdummy)
8277 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
8286 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
8289 STRLEN l1 = strlen(pat1);
8290 STRLEN l2 = strlen(pat2);
8293 const char *message;
8299 Copy(pat1, buf, l1 , char);
8300 Copy(pat2, buf + l1, l2 , char);
8301 buf[l1 + l2] = '\n';
8302 buf[l1 + l2 + 1] = '\0';
8304 /* ANSI variant takes additional second argument */
8305 va_start(args, pat2);
8309 msv = vmess(buf, &args);
8311 message = SvPV_const(msv,l1);
8314 Copy(message, buf, l1 , char);
8315 buf[l1-1] = '\0'; /* Overwrite \n */
8316 Perl_croak(aTHX_ "%s", buf);
8319 /* XXX Here's a total kludge. But we need to re-enter for swash routines. */
8321 #ifndef PERL_IN_XSUB_RE
8323 Perl_save_re_context(pTHX)
8327 struct re_save_state *state;
8329 SAVEVPTR(PL_curcop);
8330 SSGROW(SAVESTACK_ALLOC_FOR_RE_SAVE_STATE + 1);
8332 state = (struct re_save_state *)(PL_savestack + PL_savestack_ix);
8333 PL_savestack_ix += SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
8334 SSPUSHINT(SAVEt_RE_STATE);
8336 Copy(&PL_reg_state, state, 1, struct re_save_state);
8338 PL_reg_start_tmp = 0;
8339 PL_reg_start_tmpl = 0;
8340 PL_reg_oldsaved = NULL;
8341 PL_reg_oldsavedlen = 0;
8343 PL_reg_leftiter = 0;
8344 PL_reg_poscache = NULL;
8345 PL_reg_poscache_size = 0;
8346 #ifdef PERL_OLD_COPY_ON_WRITE
8350 /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
8352 const REGEXP * const rx = PM_GETRE(PL_curpm);
8355 for (i = 1; i <= rx->nparens; i++) {
8356 char digits[TYPE_CHARS(long)];
8357 const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
8358 GV *const *const gvp
8359 = (GV**)hv_fetch(PL_defstash, digits, len, 0);
8362 GV * const gv = *gvp;
8363 if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
8373 clear_re(pTHX_ void *r)
8376 ReREFCNT_dec((regexp *)r);
8382 S_put_byte(pTHX_ SV *sv, int c)
8384 if (isCNTRL(c) || c == 255 || !isPRINT(c))
8385 Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
8386 else if (c == '-' || c == ']' || c == '\\' || c == '^')
8387 Perl_sv_catpvf(aTHX_ sv, "\\%c", c);
8389 Perl_sv_catpvf(aTHX_ sv, "%c", c);
8393 #define CLEAR_OPTSTART \
8394 if (optstart) STMT_START { \
8395 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%d nodes)\n", node - optstart)); \
8399 #define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
8401 STATIC const regnode *
8402 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
8403 const regnode *last, const regnode *plast,
8404 SV* sv, I32 indent, U32 depth)
8407 register U8 op = PSEUDO; /* Arbitrary non-END op. */
8408 register const regnode *next;
8409 const regnode *optstart= NULL;
8410 GET_RE_DEBUG_FLAGS_DECL;
8412 #ifdef DEBUG_DUMPUNTIL
8413 PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
8414 last ? last-start : 0,plast ? plast-start : 0);
8417 if (plast && plast < last)
8420 while (PL_regkind[op] != END && (!last || node < last)) {
8421 /* While that wasn't END last time... */
8427 next = regnext((regnode *)node);
8430 if (OP(node) == OPTIMIZED) {
8431 if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
8438 regprop(r, sv, node);
8439 PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
8440 (int)(2*indent + 1), "", SvPVX_const(sv));
8442 if (OP(node) != OPTIMIZED) {
8443 if (next == NULL) /* Next ptr. */
8444 PerlIO_printf(Perl_debug_log, "(0)");
8445 else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
8446 PerlIO_printf(Perl_debug_log, "(FAIL)");
8448 PerlIO_printf(Perl_debug_log, "(%"IVdf")", (IV)(next - start));
8450 /*if (PL_regkind[(U8)op] != TRIE)*/
8451 (void)PerlIO_putc(Perl_debug_log, '\n');
8455 if (PL_regkind[(U8)op] == BRANCHJ) {
8458 register const regnode *nnode = (OP(next) == LONGJMP
8459 ? regnext((regnode *)next)
8461 if (last && nnode > last)
8463 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
8466 else if (PL_regkind[(U8)op] == BRANCH) {
8468 DUMPUNTIL(NEXTOPER(node), next);
8470 else if ( PL_regkind[(U8)op] == TRIE ) {
8471 const regnode *this_trie = node;
8472 const char op = OP(node);
8473 const I32 n = ARG(node);
8474 const reg_ac_data * const ac = op>=AHOCORASICK ?
8475 (reg_ac_data *)r->data->data[n] :
8477 const reg_trie_data * const trie = op<AHOCORASICK ?
8478 (reg_trie_data*)r->data->data[n] :
8480 const regnode *nextbranch= NULL;
8482 sv_setpvn(sv, "", 0);
8483 for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
8484 SV ** const elem_ptr = av_fetch(trie->words,word_idx,0);
8486 PerlIO_printf(Perl_debug_log, "%*s%s ",
8487 (int)(2*(indent+3)), "",
8488 elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
8489 PL_colors[0], PL_colors[1],
8490 (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
8491 PERL_PV_PRETTY_ELIPSES |
8497 U16 dist = trie->jump[word_idx+1];
8498 PerlIO_printf(Perl_debug_log, "(%u)\n",
8499 (dist ? this_trie + dist : next) - start);
8502 nextbranch = this_trie + trie->jump[0];
8503 DUMPUNTIL(this_trie + dist, nextbranch);
8505 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
8506 nextbranch= regnext((regnode *)nextbranch);
8508 PerlIO_printf(Perl_debug_log, "\n");
8511 if (last && next > last)
8516 else if ( op == CURLY ) { /* "next" might be very big: optimizer */
8517 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
8518 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
8520 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
8522 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
8524 else if ( op == PLUS || op == STAR) {
8525 DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
8527 else if (op == ANYOF) {
8528 /* arglen 1 + class block */
8529 node += 1 + ((ANYOF_FLAGS(node) & ANYOF_LARGE)
8530 ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
8531 node = NEXTOPER(node);
8533 else if (PL_regkind[(U8)op] == EXACT) {
8534 /* Literal string, where present. */
8535 node += NODE_SZ_STR(node) - 1;
8536 node = NEXTOPER(node);
8539 node = NEXTOPER(node);
8540 node += regarglen[(U8)op];
8542 if (op == CURLYX || op == OPEN)
8544 else if (op == WHILEM)
8548 #ifdef DEBUG_DUMPUNTIL
8549 PerlIO_printf(Perl_debug_log, "--- %d\n",indent);
8554 #endif /* DEBUGGING */
8558 * c-indentation-style: bsd
8560 * indent-tabs-mode: t
8563 * ex: set ts=8 sts=4 sw=4 noet: