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->laststate ; 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
911 PerlIO_printf( Perl_debug_log, "\n");
916 dump_trie_interim_table(trie,next_alloc)
917 Dumps a fully constructed but uncompressed trie in table form.
918 This is the normal DFA style state transition table, with a few
919 twists to facilitate compression later.
920 Used for debugging make_trie().
923 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie, U32 next_alloc, U32 depth)
927 SV *sv=sv_newmortal();
928 int colwidth= trie->widecharmap ? 6 : 4;
929 GET_RE_DEBUG_FLAGS_DECL;
932 print out the table precompression so that we can do a visual check
933 that they are identical.
936 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
938 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
939 SV ** const tmp = av_fetch( trie->revcharmap, charid, 0);
941 PerlIO_printf( Perl_debug_log, "%*s",
943 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
944 PL_colors[0], PL_colors[1],
945 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
946 PERL_PV_ESCAPE_FIRSTCHAR
952 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
954 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
955 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
958 PerlIO_printf( Perl_debug_log, "\n" );
960 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
962 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
963 (int)depth * 2 + 2,"",
964 (UV)TRIE_NODENUM( state ) );
966 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
967 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
969 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
971 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
973 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
974 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
976 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
977 trie->states[ TRIE_NODENUM( state ) ].wordnum );
984 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
985 startbranch: the first branch in the whole branch sequence
986 first : start branch of sequence of branch-exact nodes.
987 May be the same as startbranch
988 last : Thing following the last branch.
989 May be the same as tail.
990 tail : item following the branch sequence
991 count : words in the sequence
992 flags : currently the OP() type we will be building one of /EXACT(|F|Fl)/
995 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
997 A trie is an N'ary tree where the branches are determined by digital
998 decomposition of the key. IE, at the root node you look up the 1st character and
999 follow that branch repeat until you find the end of the branches. Nodes can be
1000 marked as "accepting" meaning they represent a complete word. Eg:
1004 would convert into the following structure. Numbers represent states, letters
1005 following numbers represent valid transitions on the letter from that state, if
1006 the number is in square brackets it represents an accepting state, otherwise it
1007 will be in parenthesis.
1009 +-h->+-e->[3]-+-r->(8)-+-s->[9]
1013 (1) +-i->(6)-+-s->[7]
1015 +-s->(3)-+-h->(4)-+-e->[5]
1017 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1019 This shows that when matching against the string 'hers' we will begin at state 1
1020 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1021 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1022 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1023 single traverse. We store a mapping from accepting to state to which word was
1024 matched, and then when we have multiple possibilities we try to complete the
1025 rest of the regex in the order in which they occured in the alternation.
1027 The only prior NFA like behaviour that would be changed by the TRIE support is
1028 the silent ignoring of duplicate alternations which are of the form:
1030 / (DUPE|DUPE) X? (?{ ... }) Y /x
1032 Thus EVAL blocks follwing a trie may be called a different number of times with
1033 and without the optimisation. With the optimisations dupes will be silently
1034 ignored. This inconsistant behaviour of EVAL type nodes is well established as
1035 the following demonstrates:
1037 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1039 which prints out 'word' three times, but
1041 'words'=~/(word|word|word)(?{ print $1 })S/
1043 which doesnt print it out at all. This is due to other optimisations kicking in.
1045 Example of what happens on a structural level:
1047 The regexp /(ac|ad|ab)+/ will produce the folowing debug output:
1049 1: CURLYM[1] {1,32767}(18)
1060 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1061 and should turn into:
1063 1: CURLYM[1] {1,32767}(18)
1065 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1073 Cases where tail != last would be like /(?foo|bar)baz/:
1083 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1084 and would end up looking like:
1087 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1094 d = uvuni_to_utf8_flags(d, uv, 0);
1096 is the recommended Unicode-aware way of saying
1101 #define TRIE_STORE_REVCHAR \
1103 SV *tmp = Perl_newSVpvf_nocontext( "%c", (int)uvc ); \
1104 if (UTF) SvUTF8_on(tmp); \
1105 av_push( TRIE_REVCHARMAP(trie), tmp ); \
1108 #define TRIE_READ_CHAR STMT_START { \
1112 if ( foldlen > 0 ) { \
1113 uvc = utf8n_to_uvuni( scan, UTF8_MAXLEN, &len, uniflags ); \
1118 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1119 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1120 foldlen -= UNISKIP( uvc ); \
1121 scan = foldbuf + UNISKIP( uvc ); \
1124 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1134 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
1135 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
1136 TRIE_LIST_LEN( state ) *= 2; \
1137 Renew( trie->states[ state ].trans.list, \
1138 TRIE_LIST_LEN( state ), reg_trie_trans_le ); \
1140 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
1141 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
1142 TRIE_LIST_CUR( state )++; \
1145 #define TRIE_LIST_NEW(state) STMT_START { \
1146 Newxz( trie->states[ state ].trans.list, \
1147 4, reg_trie_trans_le ); \
1148 TRIE_LIST_CUR( state ) = 1; \
1149 TRIE_LIST_LEN( state ) = 4; \
1152 #define TRIE_HANDLE_WORD(state) STMT_START { \
1153 U16 dupe= trie->states[ state ].wordnum; \
1154 regnode * const noper_next = regnext( noper ); \
1156 if (trie->wordlen) \
1157 trie->wordlen[ curword ] = wordlen; \
1159 /* store the word for dumping */ \
1161 if (OP(noper) != NOTHING) \
1162 tmp = newSVpvn(STRING(noper), STR_LEN(noper)); \
1164 tmp = newSVpvn( "", 0 ); \
1165 if ( UTF ) SvUTF8_on( tmp ); \
1166 av_push( trie->words, tmp ); \
1171 if ( noper_next < tail ) { \
1173 Newxz( trie->jump, word_count + 1, U16); \
1174 trie->jump[curword] = (U16)(tail - noper_next); \
1176 jumper = noper_next; \
1178 nextbranch= regnext(cur); \
1182 /* So it's a dupe. This means we need to maintain a */\
1183 /* linked-list from the first to the next. */\
1184 /* we only allocate the nextword buffer when there */\
1185 /* a dupe, so first time we have to do the allocation */\
1186 if (!trie->nextword) \
1187 Newxz( trie->nextword, word_count + 1, U16); \
1188 while ( trie->nextword[dupe] ) \
1189 dupe= trie->nextword[dupe]; \
1190 trie->nextword[dupe]= curword; \
1192 /* we haven't inserted this word yet. */ \
1193 trie->states[ state ].wordnum = curword; \
1198 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
1199 ( ( base + charid >= ucharcount \
1200 && base + charid < ubound \
1201 && state == trie->trans[ base - ucharcount + charid ].check \
1202 && trie->trans[ base - ucharcount + charid ].next ) \
1203 ? trie->trans[ base - ucharcount + charid ].next \
1204 : ( state==1 ? special : 0 ) \
1208 #define MADE_JUMP_TRIE 2
1209 #define MADE_EXACT_TRIE 4
1212 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
1215 /* first pass, loop through and scan words */
1216 reg_trie_data *trie;
1218 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1223 regnode *jumper = NULL;
1224 regnode *nextbranch = NULL;
1225 /* we just use folder as a flag in utf8 */
1226 const U8 * const folder = ( flags == EXACTF
1228 : ( flags == EXACTFL
1234 const U32 data_slot = add_data( pRExC_state, 1, "t" );
1235 SV *re_trie_maxbuff;
1237 /* these are only used during construction but are useful during
1238 * debugging so we store them in the struct when debugging.
1240 STRLEN trie_charcount=0;
1241 AV *trie_revcharmap;
1243 GET_RE_DEBUG_FLAGS_DECL;
1245 PERL_UNUSED_ARG(depth);
1248 Newxz( trie, 1, reg_trie_data );
1250 trie->startstate = 1;
1251 trie->wordcount = word_count;
1252 RExC_rx->data->data[ data_slot ] = (void*)trie;
1253 Newxz( trie->charmap, 256, U16 );
1254 if (!(UTF && folder))
1255 Newxz( trie->bitmap, ANYOF_BITMAP_SIZE, char );
1257 trie->words = newAV();
1259 TRIE_REVCHARMAP(trie) = newAV();
1261 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
1262 if (!SvIOK(re_trie_maxbuff)) {
1263 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
1266 PerlIO_printf( Perl_debug_log,
1267 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
1268 (int)depth * 2 + 2, "",
1269 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
1270 REG_NODE_NUM(last), REG_NODE_NUM(tail),
1273 /* -- First loop and Setup --
1275 We first traverse the branches and scan each word to determine if it
1276 contains widechars, and how many unique chars there are, this is
1277 important as we have to build a table with at least as many columns as we
1280 We use an array of integers to represent the character codes 0..255
1281 (trie->charmap) and we use a an HV* to store unicode characters. We use the
1282 native representation of the character value as the key and IV's for the
1285 *TODO* If we keep track of how many times each character is used we can
1286 remap the columns so that the table compression later on is more
1287 efficient in terms of memory by ensuring most common value is in the
1288 middle and the least common are on the outside. IMO this would be better
1289 than a most to least common mapping as theres a decent chance the most
1290 common letter will share a node with the least common, meaning the node
1291 will not be compressable. With a middle is most common approach the worst
1292 case is when we have the least common nodes twice.
1296 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1297 regnode * const noper = NEXTOPER( cur );
1298 const U8 *uc = (U8*)STRING( noper );
1299 const U8 * const e = uc + STR_LEN( noper );
1301 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1302 const U8 *scan = (U8*)NULL;
1303 U32 wordlen = 0; /* required init */
1306 if (OP(noper) == NOTHING) {
1311 TRIE_BITMAP_SET(trie,*uc);
1312 if ( folder ) TRIE_BITMAP_SET(trie,folder[ *uc ]);
1314 for ( ; uc < e ; uc += len ) {
1315 TRIE_CHARCOUNT(trie)++;
1319 if ( !trie->charmap[ uvc ] ) {
1320 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1322 trie->charmap[ folder[ uvc ] ] = trie->charmap[ uvc ];
1327 if ( !trie->widecharmap )
1328 trie->widecharmap = newHV();
1330 svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 1 );
1333 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
1335 if ( !SvTRUE( *svpp ) ) {
1336 sv_setiv( *svpp, ++trie->uniquecharcount );
1341 if( cur == first ) {
1344 } else if (chars < trie->minlen) {
1346 } else if (chars > trie->maxlen) {
1350 } /* end first pass */
1351 DEBUG_TRIE_COMPILE_r(
1352 PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1353 (int)depth * 2 + 2,"",
1354 ( trie->widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
1355 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1356 (int)trie->minlen, (int)trie->maxlen )
1358 Newxz( trie->wordlen, word_count, U32 );
1361 We now know what we are dealing with in terms of unique chars and
1362 string sizes so we can calculate how much memory a naive
1363 representation using a flat table will take. If it's over a reasonable
1364 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
1365 conservative but potentially much slower representation using an array
1368 At the end we convert both representations into the same compressed
1369 form that will be used in regexec.c for matching with. The latter
1370 is a form that cannot be used to construct with but has memory
1371 properties similar to the list form and access properties similar
1372 to the table form making it both suitable for fast searches and
1373 small enough that its feasable to store for the duration of a program.
1375 See the comment in the code where the compressed table is produced
1376 inplace from the flat tabe representation for an explanation of how
1377 the compression works.
1382 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
1384 Second Pass -- Array Of Lists Representation
1386 Each state will be represented by a list of charid:state records
1387 (reg_trie_trans_le) the first such element holds the CUR and LEN
1388 points of the allocated array. (See defines above).
1390 We build the initial structure using the lists, and then convert
1391 it into the compressed table form which allows faster lookups
1392 (but cant be modified once converted).
1395 STRLEN transcount = 1;
1397 Newxz( trie->states, TRIE_CHARCOUNT(trie) + 2, reg_trie_state );
1401 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1403 regnode * const noper = NEXTOPER( cur );
1404 U8 *uc = (U8*)STRING( noper );
1405 const U8 * const e = uc + STR_LEN( noper );
1406 U32 state = 1; /* required init */
1407 U16 charid = 0; /* sanity init */
1408 U8 *scan = (U8*)NULL; /* sanity init */
1409 STRLEN foldlen = 0; /* required init */
1410 U32 wordlen = 0; /* required init */
1411 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1413 if (OP(noper) != NOTHING) {
1414 for ( ; uc < e ; uc += len ) {
1419 charid = trie->charmap[ uvc ];
1421 SV** const svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 0);
1425 charid=(U16)SvIV( *svpp );
1428 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1435 if ( !trie->states[ state ].trans.list ) {
1436 TRIE_LIST_NEW( state );
1438 for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1439 if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1440 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1445 newstate = next_alloc++;
1446 TRIE_LIST_PUSH( state, charid, newstate );
1451 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1455 TRIE_HANDLE_WORD(state);
1457 } /* end second pass */
1459 trie->laststate = next_alloc;
1460 Renew( trie->states, next_alloc, reg_trie_state );
1462 /* and now dump it out before we compress it */
1463 DEBUG_TRIE_COMPILE_MORE_r(
1464 dump_trie_interim_list(trie,next_alloc,depth+1)
1467 Newxz( trie->trans, transcount ,reg_trie_trans );
1474 for( state=1 ; state < next_alloc ; state ++ ) {
1478 DEBUG_TRIE_COMPILE_MORE_r(
1479 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1483 if (trie->states[state].trans.list) {
1484 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1488 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1489 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1490 if ( forid < minid ) {
1492 } else if ( forid > maxid ) {
1496 if ( transcount < tp + maxid - minid + 1) {
1498 Renew( trie->trans, transcount, reg_trie_trans );
1499 Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1501 base = trie->uniquecharcount + tp - minid;
1502 if ( maxid == minid ) {
1504 for ( ; zp < tp ; zp++ ) {
1505 if ( ! trie->trans[ zp ].next ) {
1506 base = trie->uniquecharcount + zp - minid;
1507 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1508 trie->trans[ zp ].check = state;
1514 trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1515 trie->trans[ tp ].check = state;
1520 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1521 const U32 tid = base - trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
1522 trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1523 trie->trans[ tid ].check = state;
1525 tp += ( maxid - minid + 1 );
1527 Safefree(trie->states[ state ].trans.list);
1530 DEBUG_TRIE_COMPILE_MORE_r(
1531 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1534 trie->states[ state ].trans.base=base;
1536 trie->lasttrans = tp + 1;
1540 Second Pass -- Flat Table Representation.
1542 we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1543 We know that we will need Charcount+1 trans at most to store the data
1544 (one row per char at worst case) So we preallocate both structures
1545 assuming worst case.
1547 We then construct the trie using only the .next slots of the entry
1550 We use the .check field of the first entry of the node temporarily to
1551 make compression both faster and easier by keeping track of how many non
1552 zero fields are in the node.
1554 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1557 There are two terms at use here: state as a TRIE_NODEIDX() which is a
1558 number representing the first entry of the node, and state as a
1559 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1560 TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1561 are 2 entrys per node. eg:
1569 The table is internally in the right hand, idx form. However as we also
1570 have to deal with the states array which is indexed by nodenum we have to
1571 use TRIE_NODENUM() to convert.
1576 Newxz( trie->trans, ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1,
1578 Newxz( trie->states, TRIE_CHARCOUNT(trie) + 2, reg_trie_state );
1579 next_alloc = trie->uniquecharcount + 1;
1582 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1584 regnode * const noper = NEXTOPER( cur );
1585 const U8 *uc = (U8*)STRING( noper );
1586 const U8 * const e = uc + STR_LEN( noper );
1588 U32 state = 1; /* required init */
1590 U16 charid = 0; /* sanity init */
1591 U32 accept_state = 0; /* sanity init */
1592 U8 *scan = (U8*)NULL; /* sanity init */
1594 STRLEN foldlen = 0; /* required init */
1595 U32 wordlen = 0; /* required init */
1596 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1598 if ( OP(noper) != NOTHING ) {
1599 for ( ; uc < e ; uc += len ) {
1604 charid = trie->charmap[ uvc ];
1606 SV* const * const svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 0);
1607 charid = svpp ? (U16)SvIV(*svpp) : 0;
1611 if ( !trie->trans[ state + charid ].next ) {
1612 trie->trans[ state + charid ].next = next_alloc;
1613 trie->trans[ state ].check++;
1614 next_alloc += trie->uniquecharcount;
1616 state = trie->trans[ state + charid ].next;
1618 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1620 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1623 accept_state = TRIE_NODENUM( state );
1624 TRIE_HANDLE_WORD(accept_state);
1626 } /* end second pass */
1628 /* and now dump it out before we compress it */
1629 DEBUG_TRIE_COMPILE_MORE_r(
1630 dump_trie_interim_table(trie,next_alloc,depth+1)
1635 * Inplace compress the table.*
1637 For sparse data sets the table constructed by the trie algorithm will
1638 be mostly 0/FAIL transitions or to put it another way mostly empty.
1639 (Note that leaf nodes will not contain any transitions.)
1641 This algorithm compresses the tables by eliminating most such
1642 transitions, at the cost of a modest bit of extra work during lookup:
1644 - Each states[] entry contains a .base field which indicates the
1645 index in the state[] array wheres its transition data is stored.
1647 - If .base is 0 there are no valid transitions from that node.
1649 - If .base is nonzero then charid is added to it to find an entry in
1652 -If trans[states[state].base+charid].check!=state then the
1653 transition is taken to be a 0/Fail transition. Thus if there are fail
1654 transitions at the front of the node then the .base offset will point
1655 somewhere inside the previous nodes data (or maybe even into a node
1656 even earlier), but the .check field determines if the transition is
1660 The following process inplace converts the table to the compressed
1661 table: We first do not compress the root node 1,and mark its all its
1662 .check pointers as 1 and set its .base pointer as 1 as well. This
1663 allows to do a DFA construction from the compressed table later, and
1664 ensures that any .base pointers we calculate later are greater than
1667 - We set 'pos' to indicate the first entry of the second node.
1669 - We then iterate over the columns of the node, finding the first and
1670 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
1671 and set the .check pointers accordingly, and advance pos
1672 appropriately and repreat for the next node. Note that when we copy
1673 the next pointers we have to convert them from the original
1674 NODEIDX form to NODENUM form as the former is not valid post
1677 - If a node has no transitions used we mark its base as 0 and do not
1678 advance the pos pointer.
1680 - If a node only has one transition we use a second pointer into the
1681 structure to fill in allocated fail transitions from other states.
1682 This pointer is independent of the main pointer and scans forward
1683 looking for null transitions that are allocated to a state. When it
1684 finds one it writes the single transition into the "hole". If the
1685 pointer doesnt find one the single transition is appended as normal.
1687 - Once compressed we can Renew/realloc the structures to release the
1690 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
1691 specifically Fig 3.47 and the associated pseudocode.
1695 const U32 laststate = TRIE_NODENUM( next_alloc );
1698 trie->laststate = laststate;
1700 for ( state = 1 ; state < laststate ; state++ ) {
1702 const U32 stateidx = TRIE_NODEIDX( state );
1703 const U32 o_used = trie->trans[ stateidx ].check;
1704 U32 used = trie->trans[ stateidx ].check;
1705 trie->trans[ stateidx ].check = 0;
1707 for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
1708 if ( flag || trie->trans[ stateidx + charid ].next ) {
1709 if ( trie->trans[ stateidx + charid ].next ) {
1711 for ( ; zp < pos ; zp++ ) {
1712 if ( ! trie->trans[ zp ].next ) {
1716 trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
1717 trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1718 trie->trans[ zp ].check = state;
1719 if ( ++zp > pos ) pos = zp;
1726 trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
1728 trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1729 trie->trans[ pos ].check = state;
1734 trie->lasttrans = pos + 1;
1735 Renew( trie->states, laststate + 1, reg_trie_state);
1736 DEBUG_TRIE_COMPILE_MORE_r(
1737 PerlIO_printf( Perl_debug_log,
1738 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
1739 (int)depth * 2 + 2,"",
1740 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
1743 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
1746 } /* end table compress */
1748 /* resize the trans array to remove unused space */
1749 Renew( trie->trans, trie->lasttrans, reg_trie_trans);
1751 /* and now dump out the compressed format */
1752 DEBUG_TRIE_COMPILE_r(
1753 dump_trie(trie,depth+1)
1756 { /* Modify the program and insert the new TRIE node*/
1758 U8 nodetype =(U8)(flags & 0xFF);
1762 regnode *optimize = NULL;
1764 U32 mjd_nodelen = 0;
1767 This means we convert either the first branch or the first Exact,
1768 depending on whether the thing following (in 'last') is a branch
1769 or not and whther first is the startbranch (ie is it a sub part of
1770 the alternation or is it the whole thing.)
1771 Assuming its a sub part we conver the EXACT otherwise we convert
1772 the whole branch sequence, including the first.
1774 /* Find the node we are going to overwrite */
1775 if ( first == startbranch && OP( last ) != BRANCH ) {
1776 /* whole branch chain */
1779 const regnode *nop = NEXTOPER( convert );
1780 mjd_offset= Node_Offset((nop));
1781 mjd_nodelen= Node_Length((nop));
1784 /* branch sub-chain */
1785 convert = NEXTOPER( first );
1786 NEXT_OFF( first ) = (U16)(last - first);
1788 mjd_offset= Node_Offset((convert));
1789 mjd_nodelen= Node_Length((convert));
1793 PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
1794 (int)depth * 2 + 2, "",
1795 (UV)mjd_offset, (UV)mjd_nodelen)
1798 /* But first we check to see if there is a common prefix we can
1799 split out as an EXACT and put in front of the TRIE node. */
1800 trie->startstate= 1;
1801 if ( trie->bitmap && !trie->widecharmap && !trie->jump ) {
1804 PerlIO_printf(Perl_debug_log, "%*sLaststate:%"UVuf"\n",
1805 (int)depth * 2 + 2, "",
1806 (UV)trie->laststate)
1808 for ( state = 1 ; state < trie->laststate-1 ; state++ ) {
1812 const U32 base = trie->states[ state ].trans.base;
1814 if ( trie->states[state].wordnum )
1817 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1818 if ( ( base + ofs >= trie->uniquecharcount ) &&
1819 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
1820 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
1822 if ( ++count > 1 ) {
1823 SV **tmp = av_fetch( TRIE_REVCHARMAP(trie), ofs, 0);
1824 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
1825 if ( state == 1 ) break;
1827 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
1829 PerlIO_printf(Perl_debug_log,
1830 "%*sNew Start State=%"UVuf" Class: [",
1831 (int)depth * 2 + 2, "",
1834 SV ** const tmp = av_fetch( TRIE_REVCHARMAP(trie), idx, 0);
1835 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
1837 TRIE_BITMAP_SET(trie,*ch);
1839 TRIE_BITMAP_SET(trie, folder[ *ch ]);
1841 PerlIO_printf(Perl_debug_log, (char*)ch)
1845 TRIE_BITMAP_SET(trie,*ch);
1847 TRIE_BITMAP_SET(trie,folder[ *ch ]);
1848 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
1854 SV **tmp = av_fetch( TRIE_REVCHARMAP(trie), idx, 0);
1855 const char *ch = SvPV_nolen_const( *tmp );
1857 PerlIO_printf( Perl_debug_log,
1858 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
1859 (int)depth * 2 + 2, "",
1860 (UV)state, (UV)idx, ch)
1863 OP( convert ) = nodetype;
1864 str=STRING(convert);
1873 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
1879 regnode *n = convert+NODE_SZ_STR(convert);
1880 NEXT_OFF(convert) = NODE_SZ_STR(convert);
1881 trie->startstate = state;
1882 trie->minlen -= (state - 1);
1883 trie->maxlen -= (state - 1);
1885 regnode *fix = convert;
1887 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
1888 while( ++fix < n ) {
1889 Set_Node_Offset_Length(fix, 0, 0);
1895 NEXT_OFF(convert) = (U16)(tail - convert);
1896 DEBUG_r(optimize= n);
1902 if ( trie->maxlen ) {
1903 NEXT_OFF( convert ) = (U16)(tail - convert);
1904 ARG_SET( convert, data_slot );
1905 /* Store the offset to the first unabsorbed branch in
1906 jump[0], which is otherwise unused by the jump logic.
1907 We use this when dumping a trie and during optimisation. */
1909 trie->jump[0] = (U16)(tail - nextbranch);
1912 if ( !trie->states[trie->startstate].wordnum && trie->bitmap &&
1913 ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
1915 OP( convert ) = TRIEC;
1916 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
1917 Safefree(trie->bitmap);
1920 OP( convert ) = TRIE;
1922 /* store the type in the flags */
1923 convert->flags = nodetype;
1927 + regarglen[ OP( convert ) ];
1929 /* XXX We really should free up the resource in trie now,
1930 as we won't use them - (which resources?) dmq */
1932 /* needed for dumping*/
1933 DEBUG_r(if (optimize) {
1934 regnode *opt = convert;
1935 while ( ++opt < optimize) {
1936 Set_Node_Offset_Length(opt,0,0);
1939 Try to clean up some of the debris left after the
1942 while( optimize < jumper ) {
1943 mjd_nodelen += Node_Length((optimize));
1944 OP( optimize ) = OPTIMIZED;
1945 Set_Node_Offset_Length(optimize,0,0);
1948 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
1950 } /* end node insert */
1952 SvREFCNT_dec(TRIE_REVCHARMAP(trie));
1956 : trie->startstate>1
1962 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source, regnode *stclass, U32 depth)
1964 /* The Trie is constructed and compressed now so we can build a fail array now if its needed
1966 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
1967 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
1970 We find the fail state for each state in the trie, this state is the longest proper
1971 suffix of the current states 'word' that is also a proper prefix of another word in our
1972 trie. State 1 represents the word '' and is the thus the default fail state. This allows
1973 the DFA not to have to restart after its tried and failed a word at a given point, it
1974 simply continues as though it had been matching the other word in the first place.
1976 'abcdgu'=~/abcdefg|cdgu/
1977 When we get to 'd' we are still matching the first word, we would encounter 'g' which would
1978 fail, which would bring use to the state representing 'd' in the second word where we would
1979 try 'g' and succeed, prodceding to match 'cdgu'.
1981 /* add a fail transition */
1982 reg_trie_data *trie=(reg_trie_data *)RExC_rx->data->data[ARG(source)];
1984 const U32 ucharcount = trie->uniquecharcount;
1985 const U32 numstates = trie->laststate;
1986 const U32 ubound = trie->lasttrans + ucharcount;
1990 U32 base = trie->states[ 1 ].trans.base;
1993 const U32 data_slot = add_data( pRExC_state, 1, "T" );
1994 GET_RE_DEBUG_FLAGS_DECL;
1996 PERL_UNUSED_ARG(depth);
2000 ARG_SET( stclass, data_slot );
2001 Newxz( aho, 1, reg_ac_data );
2002 RExC_rx->data->data[ data_slot ] = (void*)aho;
2004 aho->states=(reg_trie_state *)savepvn((const char*)trie->states,
2005 (trie->laststate+1)*sizeof(reg_trie_state));
2006 Newxz( q, numstates, U32);
2007 Newxz( aho->fail, numstates, U32 );
2010 /* initialize fail[0..1] to be 1 so that we always have
2011 a valid final fail state */
2012 fail[ 0 ] = fail[ 1 ] = 1;
2014 for ( charid = 0; charid < ucharcount ; charid++ ) {
2015 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2017 q[ q_write ] = newstate;
2018 /* set to point at the root */
2019 fail[ q[ q_write++ ] ]=1;
2022 while ( q_read < q_write) {
2023 const U32 cur = q[ q_read++ % numstates ];
2024 base = trie->states[ cur ].trans.base;
2026 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2027 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2029 U32 fail_state = cur;
2032 fail_state = fail[ fail_state ];
2033 fail_base = aho->states[ fail_state ].trans.base;
2034 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2036 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2037 fail[ ch_state ] = fail_state;
2038 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2040 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
2042 q[ q_write++ % numstates] = ch_state;
2046 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2047 when we fail in state 1, this allows us to use the
2048 charclass scan to find a valid start char. This is based on the principle
2049 that theres a good chance the string being searched contains lots of stuff
2050 that cant be a start char.
2052 fail[ 0 ] = fail[ 1 ] = 0;
2053 DEBUG_TRIE_COMPILE_r({
2054 PerlIO_printf(Perl_debug_log, "%*sStclass Failtable: 0", (int)(depth * 2), "");
2055 for( q_read=1; q_read<numstates; q_read++ ) {
2056 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2058 PerlIO_printf(Perl_debug_log, "\n");
2061 /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2066 * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2067 * These need to be revisited when a newer toolchain becomes available.
2069 #if defined(__sparc64__) && defined(__GNUC__)
2070 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2071 # undef SPARC64_GCC_WORKAROUND
2072 # define SPARC64_GCC_WORKAROUND 1
2076 #define DEBUG_PEEP(str,scan,depth) \
2077 DEBUG_OPTIMISE_r({ \
2078 SV * const mysv=sv_newmortal(); \
2079 regnode *Next = regnext(scan); \
2080 regprop(RExC_rx, mysv, scan); \
2081 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s [%d]\n", \
2082 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2083 Next ? (REG_NODE_NUM(Next)) : 0 ); \
2090 #define JOIN_EXACT(scan,min,flags) \
2091 if (PL_regkind[OP(scan)] == EXACT) \
2092 join_exact(pRExC_state,(scan),(min),(flags),NULL,depth+1)
2095 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, I32 *min, U32 flags,regnode *val, U32 depth) {
2096 /* Merge several consecutive EXACTish nodes into one. */
2097 regnode *n = regnext(scan);
2099 regnode *next = scan + NODE_SZ_STR(scan);
2103 regnode *stop = scan;
2104 GET_RE_DEBUG_FLAGS_DECL;
2106 PERL_UNUSED_ARG(depth);
2108 #ifndef EXPERIMENTAL_INPLACESCAN
2109 PERL_UNUSED_ARG(flags);
2110 PERL_UNUSED_ARG(val);
2112 DEBUG_PEEP("join",scan,depth);
2114 /* Skip NOTHING, merge EXACT*. */
2116 ( PL_regkind[OP(n)] == NOTHING ||
2117 (stringok && (OP(n) == OP(scan))))
2119 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
2121 if (OP(n) == TAIL || n > next)
2123 if (PL_regkind[OP(n)] == NOTHING) {
2124 DEBUG_PEEP("skip:",n,depth);
2125 NEXT_OFF(scan) += NEXT_OFF(n);
2126 next = n + NODE_STEP_REGNODE;
2133 else if (stringok) {
2134 const unsigned int oldl = STR_LEN(scan);
2135 regnode * const nnext = regnext(n);
2137 DEBUG_PEEP("merg",n,depth);
2140 if (oldl + STR_LEN(n) > U8_MAX)
2142 NEXT_OFF(scan) += NEXT_OFF(n);
2143 STR_LEN(scan) += STR_LEN(n);
2144 next = n + NODE_SZ_STR(n);
2145 /* Now we can overwrite *n : */
2146 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2154 #ifdef EXPERIMENTAL_INPLACESCAN
2155 if (flags && !NEXT_OFF(n)) {
2156 DEBUG_PEEP("atch", val, depth);
2157 if (reg_off_by_arg[OP(n)]) {
2158 ARG_SET(n, val - n);
2161 NEXT_OFF(n) = val - n;
2168 if (UTF && ( OP(scan) == EXACTF ) && ( STR_LEN(scan) >= 6 ) ) {
2170 Two problematic code points in Unicode casefolding of EXACT nodes:
2172 U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2173 U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2179 U+03B9 U+0308 U+0301 0xCE 0xB9 0xCC 0x88 0xCC 0x81
2180 U+03C5 U+0308 U+0301 0xCF 0x85 0xCC 0x88 0xCC 0x81
2182 This means that in case-insensitive matching (or "loose matching",
2183 as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte
2184 length of the above casefolded versions) can match a target string
2185 of length two (the byte length of UTF-8 encoded U+0390 or U+03B0).
2186 This would rather mess up the minimum length computation.
2188 What we'll do is to look for the tail four bytes, and then peek
2189 at the preceding two bytes to see whether we need to decrease
2190 the minimum length by four (six minus two).
2192 Thanks to the design of UTF-8, there cannot be false matches:
2193 A sequence of valid UTF-8 bytes cannot be a subsequence of
2194 another valid sequence of UTF-8 bytes.
2197 char * const s0 = STRING(scan), *s, *t;
2198 char * const s1 = s0 + STR_LEN(scan) - 1;
2199 char * const s2 = s1 - 4;
2200 #ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2201 const char t0[] = "\xaf\x49\xaf\x42";
2203 const char t0[] = "\xcc\x88\xcc\x81";
2205 const char * const t1 = t0 + 3;
2208 s < s2 && (t = ninstr(s, s1, t0, t1));
2211 if (((U8)t[-1] == 0x68 && (U8)t[-2] == 0xB4) ||
2212 ((U8)t[-1] == 0x46 && (U8)t[-2] == 0xB5))
2214 if (((U8)t[-1] == 0xB9 && (U8)t[-2] == 0xCE) ||
2215 ((U8)t[-1] == 0x85 && (U8)t[-2] == 0xCF))
2223 n = scan + NODE_SZ_STR(scan);
2225 if (PL_regkind[OP(n)] != NOTHING || OP(n) == NOTHING) {
2232 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2236 /* REx optimizer. Converts nodes into quickier variants "in place".
2237 Finds fixed substrings. */
2239 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
2240 to the position after last scanned or to NULL. */
2245 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
2246 I32 *minlenp, I32 *deltap,
2247 regnode *last, scan_data_t *data, U32 flags, U32 depth)
2248 /* scanp: Start here (read-write). */
2249 /* deltap: Write maxlen-minlen here. */
2250 /* last: Stop before this one. */
2253 I32 min = 0, pars = 0, code;
2254 regnode *scan = *scanp, *next;
2256 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
2257 int is_inf_internal = 0; /* The studied chunk is infinite */
2258 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2259 scan_data_t data_fake;
2260 struct regnode_charclass_class and_with; /* Valid if flags & SCF_DO_STCLASS_OR */
2261 SV *re_trie_maxbuff = NULL;
2262 regnode *first_non_open = scan;
2265 GET_RE_DEBUG_FLAGS_DECL;
2267 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
2270 while (first_non_open && OP(first_non_open) == OPEN)
2271 first_non_open=regnext(first_non_open);
2275 while (scan && OP(scan) != END && scan < last) {
2276 /* Peephole optimizer: */
2277 DEBUG_STUDYDATA(data,depth);
2278 DEBUG_PEEP("Peep",scan,depth);
2279 JOIN_EXACT(scan,&min,0);
2281 /* Follow the next-chain of the current node and optimize
2282 away all the NOTHINGs from it. */
2283 if (OP(scan) != CURLYX) {
2284 const int max = (reg_off_by_arg[OP(scan)]
2286 /* I32 may be smaller than U16 on CRAYs! */
2287 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
2288 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
2292 /* Skip NOTHING and LONGJMP. */
2293 while ((n = regnext(n))
2294 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
2295 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
2296 && off + noff < max)
2298 if (reg_off_by_arg[OP(scan)])
2301 NEXT_OFF(scan) = off;
2306 /* The principal pseudo-switch. Cannot be a switch, since we
2307 look into several different things. */
2308 if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
2309 || OP(scan) == IFTHEN || OP(scan) == SUSPEND) {
2310 next = regnext(scan);
2312 /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
2314 if (OP(next) == code || code == IFTHEN || code == SUSPEND) {
2315 /* NOTE - There is similar code to this block below for handling
2316 TRIE nodes on a re-study. If you change stuff here check there
2318 I32 max1 = 0, min1 = I32_MAX, num = 0;
2319 struct regnode_charclass_class accum;
2320 regnode * const startbranch=scan;
2322 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
2323 scan_commit(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
2324 if (flags & SCF_DO_STCLASS)
2325 cl_init_zero(pRExC_state, &accum);
2327 while (OP(scan) == code) {
2328 I32 deltanext, minnext, f = 0, fake;
2329 struct regnode_charclass_class this_class;
2332 data_fake.flags = 0;
2334 data_fake.whilem_c = data->whilem_c;
2335 data_fake.last_closep = data->last_closep;
2338 data_fake.last_closep = &fake;
2339 next = regnext(scan);
2340 scan = NEXTOPER(scan);
2342 scan = NEXTOPER(scan);
2343 if (flags & SCF_DO_STCLASS) {
2344 cl_init(pRExC_state, &this_class);
2345 data_fake.start_class = &this_class;
2346 f = SCF_DO_STCLASS_AND;
2348 if (flags & SCF_WHILEM_VISITED_POS)
2349 f |= SCF_WHILEM_VISITED_POS;
2351 /* we suppose the run is continuous, last=next...*/
2352 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2353 next, &data_fake, f,depth+1);
2356 if (max1 < minnext + deltanext)
2357 max1 = minnext + deltanext;
2358 if (deltanext == I32_MAX)
2359 is_inf = is_inf_internal = 1;
2361 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
2364 if (data_fake.flags & SF_HAS_EVAL)
2365 data->flags |= SF_HAS_EVAL;
2366 data->whilem_c = data_fake.whilem_c;
2368 if (flags & SCF_DO_STCLASS)
2369 cl_or(pRExC_state, &accum, &this_class);
2370 if (code == SUSPEND)
2373 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
2375 if (flags & SCF_DO_SUBSTR) {
2376 data->pos_min += min1;
2377 data->pos_delta += max1 - min1;
2378 if (max1 != min1 || is_inf)
2379 data->longest = &(data->longest_float);
2382 delta += max1 - min1;
2383 if (flags & SCF_DO_STCLASS_OR) {
2384 cl_or(pRExC_state, data->start_class, &accum);
2386 cl_and(data->start_class, &and_with);
2387 flags &= ~SCF_DO_STCLASS;
2390 else if (flags & SCF_DO_STCLASS_AND) {
2392 cl_and(data->start_class, &accum);
2393 flags &= ~SCF_DO_STCLASS;
2396 /* Switch to OR mode: cache the old value of
2397 * data->start_class */
2398 StructCopy(data->start_class, &and_with,
2399 struct regnode_charclass_class);
2400 flags &= ~SCF_DO_STCLASS_AND;
2401 StructCopy(&accum, data->start_class,
2402 struct regnode_charclass_class);
2403 flags |= SCF_DO_STCLASS_OR;
2404 data->start_class->flags |= ANYOF_EOS;
2408 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
2411 Assuming this was/is a branch we are dealing with: 'scan' now
2412 points at the item that follows the branch sequence, whatever
2413 it is. We now start at the beginning of the sequence and look
2420 which would be constructed from a pattern like /A|LIST|OF|WORDS/
2422 If we can find such a subseqence we need to turn the first
2423 element into a trie and then add the subsequent branch exact
2424 strings to the trie.
2428 1. patterns where the whole set of branch can be converted.
2430 2. patterns where only a subset can be converted.
2432 In case 1 we can replace the whole set with a single regop
2433 for the trie. In case 2 we need to keep the start and end
2436 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
2437 becomes BRANCH TRIE; BRANCH X;
2439 There is an additional case, that being where there is a
2440 common prefix, which gets split out into an EXACT like node
2441 preceding the TRIE node.
2443 If x(1..n)==tail then we can do a simple trie, if not we make
2444 a "jump" trie, such that when we match the appropriate word
2445 we "jump" to the appopriate tail node. Essentailly we turn
2446 a nested if into a case structure of sorts.
2451 if (!re_trie_maxbuff) {
2452 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2453 if (!SvIOK(re_trie_maxbuff))
2454 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2456 if ( SvIV(re_trie_maxbuff)>=0 ) {
2458 regnode *first = (regnode *)NULL;
2459 regnode *last = (regnode *)NULL;
2460 regnode *tail = scan;
2465 SV * const mysv = sv_newmortal(); /* for dumping */
2467 /* var tail is used because there may be a TAIL
2468 regop in the way. Ie, the exacts will point to the
2469 thing following the TAIL, but the last branch will
2470 point at the TAIL. So we advance tail. If we
2471 have nested (?:) we may have to move through several
2475 while ( OP( tail ) == TAIL ) {
2476 /* this is the TAIL generated by (?:) */
2477 tail = regnext( tail );
2482 regprop(RExC_rx, mysv, tail );
2483 PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
2484 (int)depth * 2 + 2, "",
2485 "Looking for TRIE'able sequences. Tail node is: ",
2486 SvPV_nolen_const( mysv )
2492 step through the branches, cur represents each
2493 branch, noper is the first thing to be matched
2494 as part of that branch and noper_next is the
2495 regnext() of that node. if noper is an EXACT
2496 and noper_next is the same as scan (our current
2497 position in the regex) then the EXACT branch is
2498 a possible optimization target. Once we have
2499 two or more consequetive such branches we can
2500 create a trie of the EXACT's contents and stich
2501 it in place. If the sequence represents all of
2502 the branches we eliminate the whole thing and
2503 replace it with a single TRIE. If it is a
2504 subsequence then we need to stitch it in. This
2505 means the first branch has to remain, and needs
2506 to be repointed at the item on the branch chain
2507 following the last branch optimized. This could
2508 be either a BRANCH, in which case the
2509 subsequence is internal, or it could be the
2510 item following the branch sequence in which
2511 case the subsequence is at the end.
2515 /* dont use tail as the end marker for this traverse */
2516 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
2517 regnode * const noper = NEXTOPER( cur );
2518 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
2519 regnode * const noper_next = regnext( noper );
2523 regprop(RExC_rx, mysv, cur);
2524 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
2525 (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
2527 regprop(RExC_rx, mysv, noper);
2528 PerlIO_printf( Perl_debug_log, " -> %s",
2529 SvPV_nolen_const(mysv));
2532 regprop(RExC_rx, mysv, noper_next );
2533 PerlIO_printf( Perl_debug_log,"\t=> %s\t",
2534 SvPV_nolen_const(mysv));
2536 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
2537 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
2539 if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
2540 : PL_regkind[ OP( noper ) ] == EXACT )
2541 || OP(noper) == NOTHING )
2543 && noper_next == tail
2548 if ( !first || optype == NOTHING ) {
2549 if (!first) first = cur;
2550 optype = OP( noper );
2556 make_trie( pRExC_state,
2557 startbranch, first, cur, tail, count,
2560 if ( PL_regkind[ OP( noper ) ] == EXACT
2562 && noper_next == tail
2567 optype = OP( noper );
2577 regprop(RExC_rx, mysv, cur);
2578 PerlIO_printf( Perl_debug_log,
2579 "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
2580 "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
2584 made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
2585 #ifdef TRIE_STUDY_OPT
2586 if ( ((made == MADE_EXACT_TRIE &&
2587 startbranch == first)
2588 || ( first_non_open == first )) &&
2590 flags |= SCF_TRIE_RESTUDY;
2598 else if ( code == BRANCHJ ) { /* single branch is optimized. */
2599 scan = NEXTOPER(NEXTOPER(scan));
2600 } else /* single branch is optimized. */
2601 scan = NEXTOPER(scan);
2604 else if (OP(scan) == EXACT) {
2605 I32 l = STR_LEN(scan);
2608 const U8 * const s = (U8*)STRING(scan);
2609 l = utf8_length(s, s + l);
2610 uc = utf8_to_uvchr(s, NULL);
2612 uc = *((U8*)STRING(scan));
2615 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
2616 /* The code below prefers earlier match for fixed
2617 offset, later match for variable offset. */
2618 if (data->last_end == -1) { /* Update the start info. */
2619 data->last_start_min = data->pos_min;
2620 data->last_start_max = is_inf
2621 ? I32_MAX : data->pos_min + data->pos_delta;
2623 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
2625 SvUTF8_on(data->last_found);
2627 SV * const sv = data->last_found;
2628 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
2629 mg_find(sv, PERL_MAGIC_utf8) : NULL;
2630 if (mg && mg->mg_len >= 0)
2631 mg->mg_len += utf8_length((U8*)STRING(scan),
2632 (U8*)STRING(scan)+STR_LEN(scan));
2634 data->last_end = data->pos_min + l;
2635 data->pos_min += l; /* As in the first entry. */
2636 data->flags &= ~SF_BEFORE_EOL;
2638 if (flags & SCF_DO_STCLASS_AND) {
2639 /* Check whether it is compatible with what we know already! */
2643 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2644 && !ANYOF_BITMAP_TEST(data->start_class, uc)
2645 && (!(data->start_class->flags & ANYOF_FOLD)
2646 || !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2649 ANYOF_CLASS_ZERO(data->start_class);
2650 ANYOF_BITMAP_ZERO(data->start_class);
2652 ANYOF_BITMAP_SET(data->start_class, uc);
2653 data->start_class->flags &= ~ANYOF_EOS;
2655 data->start_class->flags &= ~ANYOF_UNICODE_ALL;
2657 else if (flags & SCF_DO_STCLASS_OR) {
2658 /* false positive possible if the class is case-folded */
2660 ANYOF_BITMAP_SET(data->start_class, uc);
2662 data->start_class->flags |= ANYOF_UNICODE_ALL;
2663 data->start_class->flags &= ~ANYOF_EOS;
2664 cl_and(data->start_class, &and_with);
2666 flags &= ~SCF_DO_STCLASS;
2668 else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
2669 I32 l = STR_LEN(scan);
2670 UV uc = *((U8*)STRING(scan));
2672 /* Search for fixed substrings supports EXACT only. */
2673 if (flags & SCF_DO_SUBSTR) {
2675 scan_commit(pRExC_state, data, minlenp);
2678 const U8 * const s = (U8 *)STRING(scan);
2679 l = utf8_length(s, s + l);
2680 uc = utf8_to_uvchr(s, NULL);
2683 if (flags & SCF_DO_SUBSTR)
2685 if (flags & SCF_DO_STCLASS_AND) {
2686 /* Check whether it is compatible with what we know already! */
2690 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2691 && !ANYOF_BITMAP_TEST(data->start_class, uc)
2692 && !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2694 ANYOF_CLASS_ZERO(data->start_class);
2695 ANYOF_BITMAP_ZERO(data->start_class);
2697 ANYOF_BITMAP_SET(data->start_class, uc);
2698 data->start_class->flags &= ~ANYOF_EOS;
2699 data->start_class->flags |= ANYOF_FOLD;
2700 if (OP(scan) == EXACTFL)
2701 data->start_class->flags |= ANYOF_LOCALE;
2704 else if (flags & SCF_DO_STCLASS_OR) {
2705 if (data->start_class->flags & ANYOF_FOLD) {
2706 /* false positive possible if the class is case-folded.
2707 Assume that the locale settings are the same... */
2709 ANYOF_BITMAP_SET(data->start_class, uc);
2710 data->start_class->flags &= ~ANYOF_EOS;
2712 cl_and(data->start_class, &and_with);
2714 flags &= ~SCF_DO_STCLASS;
2716 else if (OP(scan)==RECURSE) {
2717 ARG2L_SET( scan, RExC_parens[ARG(scan)-1] - scan );
2719 else if (strchr((const char*)PL_varies,OP(scan))) {
2720 I32 mincount, maxcount, minnext, deltanext, fl = 0;
2721 I32 f = flags, pos_before = 0;
2722 regnode * const oscan = scan;
2723 struct regnode_charclass_class this_class;
2724 struct regnode_charclass_class *oclass = NULL;
2725 I32 next_is_eval = 0;
2727 switch (PL_regkind[OP(scan)]) {
2728 case WHILEM: /* End of (?:...)* . */
2729 scan = NEXTOPER(scan);
2732 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
2733 next = NEXTOPER(scan);
2734 if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
2736 maxcount = REG_INFTY;
2737 next = regnext(scan);
2738 scan = NEXTOPER(scan);
2742 if (flags & SCF_DO_SUBSTR)
2747 if (flags & SCF_DO_STCLASS) {
2749 maxcount = REG_INFTY;
2750 next = regnext(scan);
2751 scan = NEXTOPER(scan);
2754 is_inf = is_inf_internal = 1;
2755 scan = regnext(scan);
2756 if (flags & SCF_DO_SUBSTR) {
2757 scan_commit(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
2758 data->longest = &(data->longest_float);
2760 goto optimize_curly_tail;
2762 mincount = ARG1(scan);
2763 maxcount = ARG2(scan);
2764 next = regnext(scan);
2765 if (OP(scan) == CURLYX) {
2766 I32 lp = (data ? *(data->last_closep) : 0);
2767 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
2769 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
2770 next_is_eval = (OP(scan) == EVAL);
2772 if (flags & SCF_DO_SUBSTR) {
2773 if (mincount == 0) scan_commit(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
2774 pos_before = data->pos_min;
2778 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
2780 data->flags |= SF_IS_INF;
2782 if (flags & SCF_DO_STCLASS) {
2783 cl_init(pRExC_state, &this_class);
2784 oclass = data->start_class;
2785 data->start_class = &this_class;
2786 f |= SCF_DO_STCLASS_AND;
2787 f &= ~SCF_DO_STCLASS_OR;
2789 /* These are the cases when once a subexpression
2790 fails at a particular position, it cannot succeed
2791 even after backtracking at the enclosing scope.
2793 XXXX what if minimal match and we are at the
2794 initial run of {n,m}? */
2795 if ((mincount != maxcount - 1) && (maxcount != REG_INFTY))
2796 f &= ~SCF_WHILEM_VISITED_POS;
2798 /* This will finish on WHILEM, setting scan, or on NULL: */
2799 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, last, data,
2801 ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
2803 if (flags & SCF_DO_STCLASS)
2804 data->start_class = oclass;
2805 if (mincount == 0 || minnext == 0) {
2806 if (flags & SCF_DO_STCLASS_OR) {
2807 cl_or(pRExC_state, data->start_class, &this_class);
2809 else if (flags & SCF_DO_STCLASS_AND) {
2810 /* Switch to OR mode: cache the old value of
2811 * data->start_class */
2812 StructCopy(data->start_class, &and_with,
2813 struct regnode_charclass_class);
2814 flags &= ~SCF_DO_STCLASS_AND;
2815 StructCopy(&this_class, data->start_class,
2816 struct regnode_charclass_class);
2817 flags |= SCF_DO_STCLASS_OR;
2818 data->start_class->flags |= ANYOF_EOS;
2820 } else { /* Non-zero len */
2821 if (flags & SCF_DO_STCLASS_OR) {
2822 cl_or(pRExC_state, data->start_class, &this_class);
2823 cl_and(data->start_class, &and_with);
2825 else if (flags & SCF_DO_STCLASS_AND)
2826 cl_and(data->start_class, &this_class);
2827 flags &= ~SCF_DO_STCLASS;
2829 if (!scan) /* It was not CURLYX, but CURLY. */
2831 if ( /* ? quantifier ok, except for (?{ ... }) */
2832 (next_is_eval || !(mincount == 0 && maxcount == 1))
2833 && (minnext == 0) && (deltanext == 0)
2834 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
2835 && maxcount <= REG_INFTY/3 /* Complement check for big count */
2836 && ckWARN(WARN_REGEXP))
2839 "Quantifier unexpected on zero-length expression");
2842 min += minnext * mincount;
2843 is_inf_internal |= ((maxcount == REG_INFTY
2844 && (minnext + deltanext) > 0)
2845 || deltanext == I32_MAX);
2846 is_inf |= is_inf_internal;
2847 delta += (minnext + deltanext) * maxcount - minnext * mincount;
2849 /* Try powerful optimization CURLYX => CURLYN. */
2850 if ( OP(oscan) == CURLYX && data
2851 && data->flags & SF_IN_PAR
2852 && !(data->flags & SF_HAS_EVAL)
2853 && !deltanext && minnext == 1 ) {
2854 /* Try to optimize to CURLYN. */
2855 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
2856 regnode * const nxt1 = nxt;
2863 if (!strchr((const char*)PL_simple,OP(nxt))
2864 && !(PL_regkind[OP(nxt)] == EXACT
2865 && STR_LEN(nxt) == 1))
2871 if (OP(nxt) != CLOSE)
2873 /* Now we know that nxt2 is the only contents: */
2874 oscan->flags = (U8)ARG(nxt);
2876 OP(nxt1) = NOTHING; /* was OPEN. */
2878 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
2879 NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
2880 NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
2881 OP(nxt) = OPTIMIZED; /* was CLOSE. */
2882 OP(nxt + 1) = OPTIMIZED; /* was count. */
2883 NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
2888 /* Try optimization CURLYX => CURLYM. */
2889 if ( OP(oscan) == CURLYX && data
2890 && !(data->flags & SF_HAS_PAR)
2891 && !(data->flags & SF_HAS_EVAL)
2892 && !deltanext /* atom is fixed width */
2893 && minnext != 0 /* CURLYM can't handle zero width */
2895 /* XXXX How to optimize if data == 0? */
2896 /* Optimize to a simpler form. */
2897 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
2901 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
2902 && (OP(nxt2) != WHILEM))
2904 OP(nxt2) = SUCCEED; /* Whas WHILEM */
2905 /* Need to optimize away parenths. */
2906 if (data->flags & SF_IN_PAR) {
2907 /* Set the parenth number. */
2908 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
2910 if (OP(nxt) != CLOSE)
2911 FAIL("Panic opt close");
2912 oscan->flags = (U8)ARG(nxt);
2913 OP(nxt1) = OPTIMIZED; /* was OPEN. */
2914 OP(nxt) = OPTIMIZED; /* was CLOSE. */
2916 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
2917 OP(nxt + 1) = OPTIMIZED; /* was count. */
2918 NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
2919 NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
2922 while ( nxt1 && (OP(nxt1) != WHILEM)) {
2923 regnode *nnxt = regnext(nxt1);
2926 if (reg_off_by_arg[OP(nxt1)])
2927 ARG_SET(nxt1, nxt2 - nxt1);
2928 else if (nxt2 - nxt1 < U16_MAX)
2929 NEXT_OFF(nxt1) = nxt2 - nxt1;
2931 OP(nxt) = NOTHING; /* Cannot beautify */
2936 /* Optimize again: */
2937 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
2943 else if ((OP(oscan) == CURLYX)
2944 && (flags & SCF_WHILEM_VISITED_POS)
2945 /* See the comment on a similar expression above.
2946 However, this time it not a subexpression
2947 we care about, but the expression itself. */
2948 && (maxcount == REG_INFTY)
2949 && data && ++data->whilem_c < 16) {
2950 /* This stays as CURLYX, we can put the count/of pair. */
2951 /* Find WHILEM (as in regexec.c) */
2952 regnode *nxt = oscan + NEXT_OFF(oscan);
2954 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
2956 PREVOPER(nxt)->flags = (U8)(data->whilem_c
2957 | (RExC_whilem_seen << 4)); /* On WHILEM */
2959 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
2961 if (flags & SCF_DO_SUBSTR) {
2962 SV *last_str = NULL;
2963 int counted = mincount != 0;
2965 if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
2966 #if defined(SPARC64_GCC_WORKAROUND)
2969 const char *s = NULL;
2972 if (pos_before >= data->last_start_min)
2975 b = data->last_start_min;
2978 s = SvPV_const(data->last_found, l);
2979 old = b - data->last_start_min;
2982 I32 b = pos_before >= data->last_start_min
2983 ? pos_before : data->last_start_min;
2985 const char * const s = SvPV_const(data->last_found, l);
2986 I32 old = b - data->last_start_min;
2990 old = utf8_hop((U8*)s, old) - (U8*)s;
2993 /* Get the added string: */
2994 last_str = newSVpvn(s + old, l);
2996 SvUTF8_on(last_str);
2997 if (deltanext == 0 && pos_before == b) {
2998 /* What was added is a constant string */
3000 SvGROW(last_str, (mincount * l) + 1);
3001 repeatcpy(SvPVX(last_str) + l,
3002 SvPVX_const(last_str), l, mincount - 1);
3003 SvCUR_set(last_str, SvCUR(last_str) * mincount);
3004 /* Add additional parts. */
3005 SvCUR_set(data->last_found,
3006 SvCUR(data->last_found) - l);
3007 sv_catsv(data->last_found, last_str);
3009 SV * sv = data->last_found;
3011 SvUTF8(sv) && SvMAGICAL(sv) ?
3012 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3013 if (mg && mg->mg_len >= 0)
3014 mg->mg_len += CHR_SVLEN(last_str);
3016 data->last_end += l * (mincount - 1);
3019 /* start offset must point into the last copy */
3020 data->last_start_min += minnext * (mincount - 1);
3021 data->last_start_max += is_inf ? I32_MAX
3022 : (maxcount - 1) * (minnext + data->pos_delta);
3025 /* It is counted once already... */
3026 data->pos_min += minnext * (mincount - counted);
3027 data->pos_delta += - counted * deltanext +
3028 (minnext + deltanext) * maxcount - minnext * mincount;
3029 if (mincount != maxcount) {
3030 /* Cannot extend fixed substrings found inside
3032 scan_commit(pRExC_state,data,minlenp);
3033 if (mincount && last_str) {
3034 SV * const sv = data->last_found;
3035 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3036 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3040 sv_setsv(sv, last_str);
3041 data->last_end = data->pos_min;
3042 data->last_start_min =
3043 data->pos_min - CHR_SVLEN(last_str);
3044 data->last_start_max = is_inf
3046 : data->pos_min + data->pos_delta
3047 - CHR_SVLEN(last_str);
3049 data->longest = &(data->longest_float);
3051 SvREFCNT_dec(last_str);
3053 if (data && (fl & SF_HAS_EVAL))
3054 data->flags |= SF_HAS_EVAL;
3055 optimize_curly_tail:
3056 if (OP(oscan) != CURLYX) {
3057 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
3059 NEXT_OFF(oscan) += NEXT_OFF(next);
3062 default: /* REF and CLUMP only? */
3063 if (flags & SCF_DO_SUBSTR) {
3064 scan_commit(pRExC_state,data,minlenp); /* Cannot expect anything... */
3065 data->longest = &(data->longest_float);
3067 is_inf = is_inf_internal = 1;
3068 if (flags & SCF_DO_STCLASS_OR)
3069 cl_anything(pRExC_state, data->start_class);
3070 flags &= ~SCF_DO_STCLASS;
3074 else if (strchr((const char*)PL_simple,OP(scan))) {
3077 if (flags & SCF_DO_SUBSTR) {
3078 scan_commit(pRExC_state,data,minlenp);
3082 if (flags & SCF_DO_STCLASS) {
3083 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3085 /* Some of the logic below assumes that switching
3086 locale on will only add false positives. */
3087 switch (PL_regkind[OP(scan)]) {
3091 /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
3092 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3093 cl_anything(pRExC_state, data->start_class);
3096 if (OP(scan) == SANY)
3098 if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
3099 value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
3100 || (data->start_class->flags & ANYOF_CLASS));
3101 cl_anything(pRExC_state, data->start_class);
3103 if (flags & SCF_DO_STCLASS_AND || !value)
3104 ANYOF_BITMAP_CLEAR(data->start_class,'\n');
3107 if (flags & SCF_DO_STCLASS_AND)
3108 cl_and(data->start_class,
3109 (struct regnode_charclass_class*)scan);
3111 cl_or(pRExC_state, data->start_class,
3112 (struct regnode_charclass_class*)scan);
3115 if (flags & SCF_DO_STCLASS_AND) {
3116 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3117 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3118 for (value = 0; value < 256; value++)
3119 if (!isALNUM(value))
3120 ANYOF_BITMAP_CLEAR(data->start_class, value);
3124 if (data->start_class->flags & ANYOF_LOCALE)
3125 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3127 for (value = 0; value < 256; value++)
3129 ANYOF_BITMAP_SET(data->start_class, value);
3134 if (flags & SCF_DO_STCLASS_AND) {
3135 if (data->start_class->flags & ANYOF_LOCALE)
3136 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3139 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3140 data->start_class->flags |= ANYOF_LOCALE;
3144 if (flags & SCF_DO_STCLASS_AND) {
3145 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3146 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3147 for (value = 0; value < 256; value++)
3149 ANYOF_BITMAP_CLEAR(data->start_class, value);
3153 if (data->start_class->flags & ANYOF_LOCALE)
3154 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3156 for (value = 0; value < 256; value++)
3157 if (!isALNUM(value))
3158 ANYOF_BITMAP_SET(data->start_class, value);
3163 if (flags & SCF_DO_STCLASS_AND) {
3164 if (data->start_class->flags & ANYOF_LOCALE)
3165 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3168 data->start_class->flags |= ANYOF_LOCALE;
3169 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3173 if (flags & SCF_DO_STCLASS_AND) {
3174 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3175 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3176 for (value = 0; value < 256; value++)
3177 if (!isSPACE(value))
3178 ANYOF_BITMAP_CLEAR(data->start_class, value);
3182 if (data->start_class->flags & ANYOF_LOCALE)
3183 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3185 for (value = 0; value < 256; value++)
3187 ANYOF_BITMAP_SET(data->start_class, value);
3192 if (flags & SCF_DO_STCLASS_AND) {
3193 if (data->start_class->flags & ANYOF_LOCALE)
3194 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3197 data->start_class->flags |= ANYOF_LOCALE;
3198 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3202 if (flags & SCF_DO_STCLASS_AND) {
3203 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3204 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3205 for (value = 0; value < 256; value++)
3207 ANYOF_BITMAP_CLEAR(data->start_class, value);
3211 if (data->start_class->flags & ANYOF_LOCALE)
3212 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3214 for (value = 0; value < 256; value++)
3215 if (!isSPACE(value))
3216 ANYOF_BITMAP_SET(data->start_class, value);
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++)
3225 if (!isSPACE(value))
3226 ANYOF_BITMAP_CLEAR(data->start_class, value);
3230 data->start_class->flags |= ANYOF_LOCALE;
3231 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3235 if (flags & SCF_DO_STCLASS_AND) {
3236 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
3237 for (value = 0; value < 256; value++)
3238 if (!isDIGIT(value))
3239 ANYOF_BITMAP_CLEAR(data->start_class, value);
3242 if (data->start_class->flags & ANYOF_LOCALE)
3243 ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
3245 for (value = 0; value < 256; value++)
3247 ANYOF_BITMAP_SET(data->start_class, value);
3252 if (flags & SCF_DO_STCLASS_AND) {
3253 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
3254 for (value = 0; value < 256; value++)
3256 ANYOF_BITMAP_CLEAR(data->start_class, value);
3259 if (data->start_class->flags & ANYOF_LOCALE)
3260 ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
3262 for (value = 0; value < 256; value++)
3263 if (!isDIGIT(value))
3264 ANYOF_BITMAP_SET(data->start_class, value);
3269 if (flags & SCF_DO_STCLASS_OR)
3270 cl_and(data->start_class, &and_with);
3271 flags &= ~SCF_DO_STCLASS;
3274 else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
3275 data->flags |= (OP(scan) == MEOL
3279 else if ( PL_regkind[OP(scan)] == BRANCHJ
3280 /* Lookbehind, or need to calculate parens/evals/stclass: */
3281 && (scan->flags || data || (flags & SCF_DO_STCLASS))
3282 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
3283 if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3284 || OP(scan) == UNLESSM )
3286 /* Negative Lookahead/lookbehind
3287 In this case we can't do fixed string optimisation.
3290 I32 deltanext, minnext, fake = 0;
3292 struct regnode_charclass_class intrnl;
3295 data_fake.flags = 0;
3297 data_fake.whilem_c = data->whilem_c;
3298 data_fake.last_closep = data->last_closep;
3301 data_fake.last_closep = &fake;
3302 if ( flags & SCF_DO_STCLASS && !scan->flags
3303 && OP(scan) == IFMATCH ) { /* Lookahead */
3304 cl_init(pRExC_state, &intrnl);
3305 data_fake.start_class = &intrnl;
3306 f |= SCF_DO_STCLASS_AND;
3308 if (flags & SCF_WHILEM_VISITED_POS)
3309 f |= SCF_WHILEM_VISITED_POS;
3310 next = regnext(scan);
3311 nscan = NEXTOPER(NEXTOPER(scan));
3312 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, last, &data_fake, f,depth+1);
3315 vFAIL("Variable length lookbehind not implemented");
3317 else if (minnext > (I32)U8_MAX) {
3318 vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3320 scan->flags = (U8)minnext;
3323 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3325 if (data_fake.flags & SF_HAS_EVAL)
3326 data->flags |= SF_HAS_EVAL;
3327 data->whilem_c = data_fake.whilem_c;
3329 if (f & SCF_DO_STCLASS_AND) {
3330 const int was = (data->start_class->flags & ANYOF_EOS);
3332 cl_and(data->start_class, &intrnl);
3334 data->start_class->flags |= ANYOF_EOS;
3337 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3339 /* Positive Lookahead/lookbehind
3340 In this case we can do fixed string optimisation,
3341 but we must be careful about it. Note in the case of
3342 lookbehind the positions will be offset by the minimum
3343 length of the pattern, something we won't know about
3344 until after the recurse.
3346 I32 deltanext, fake = 0;
3348 struct regnode_charclass_class intrnl;
3350 /* We use SAVEFREEPV so that when the full compile
3351 is finished perl will clean up the allocated
3352 minlens when its all done. This was we don't
3353 have to worry about freeing them when we know
3354 they wont be used, which would be a pain.
3357 Newx( minnextp, 1, I32 );
3358 SAVEFREEPV(minnextp);
3361 StructCopy(data, &data_fake, scan_data_t);
3362 if ((flags & SCF_DO_SUBSTR) && data->last_found) {
3365 scan_commit(pRExC_state, &data_fake,minlenp);
3366 data_fake.last_found=newSVsv(data->last_found);
3370 data_fake.last_closep = &fake;
3371 data_fake.flags = 0;
3373 data_fake.flags |= SF_IS_INF;
3374 if ( flags & SCF_DO_STCLASS && !scan->flags
3375 && OP(scan) == IFMATCH ) { /* Lookahead */
3376 cl_init(pRExC_state, &intrnl);
3377 data_fake.start_class = &intrnl;
3378 f |= SCF_DO_STCLASS_AND;
3380 if (flags & SCF_WHILEM_VISITED_POS)
3381 f |= SCF_WHILEM_VISITED_POS;
3382 next = regnext(scan);
3383 nscan = NEXTOPER(NEXTOPER(scan));
3385 *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext, last, &data_fake, f,depth+1);
3388 vFAIL("Variable length lookbehind not implemented");
3390 else if (*minnextp > (I32)U8_MAX) {
3391 vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3393 scan->flags = (U8)*minnextp;
3399 if (f & SCF_DO_STCLASS_AND) {
3400 const int was = (data->start_class->flags & ANYOF_EOS);
3402 cl_and(data->start_class, &intrnl);
3404 data->start_class->flags |= ANYOF_EOS;
3407 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3409 if (data_fake.flags & SF_HAS_EVAL)
3410 data->flags |= SF_HAS_EVAL;
3411 data->whilem_c = data_fake.whilem_c;
3412 if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
3413 if (RExC_rx->minlen<*minnextp)
3414 RExC_rx->minlen=*minnextp;
3415 scan_commit(pRExC_state, &data_fake, minnextp);
3416 SvREFCNT_dec(data_fake.last_found);
3418 if ( data_fake.minlen_fixed != minlenp )
3420 data->offset_fixed= data_fake.offset_fixed;
3421 data->minlen_fixed= data_fake.minlen_fixed;
3422 data->lookbehind_fixed+= scan->flags;
3424 if ( data_fake.minlen_float != minlenp )
3426 data->minlen_float= data_fake.minlen_float;
3427 data->offset_float_min=data_fake.offset_float_min;
3428 data->offset_float_max=data_fake.offset_float_max;
3429 data->lookbehind_float+= scan->flags;
3438 else if (OP(scan) == OPEN) {
3441 else if (OP(scan) == CLOSE) {
3442 if ((I32)ARG(scan) == is_par) {
3443 next = regnext(scan);
3445 if ( next && (OP(next) != WHILEM) && next < last)
3446 is_par = 0; /* Disable optimization */
3449 *(data->last_closep) = ARG(scan);
3451 else if (OP(scan) == EVAL) {
3453 data->flags |= SF_HAS_EVAL;
3455 else if (OP(scan) == LOGICAL && scan->flags == 2) { /* Embedded follows */
3456 if (flags & SCF_DO_SUBSTR) {
3457 scan_commit(pRExC_state,data,minlenp);
3458 data->longest = &(data->longest_float);
3460 is_inf = is_inf_internal = 1;
3461 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3462 cl_anything(pRExC_state, data->start_class);
3463 flags &= ~SCF_DO_STCLASS;
3465 #ifdef TRIE_STUDY_OPT
3466 #ifdef FULL_TRIE_STUDY
3467 else if (PL_regkind[OP(scan)] == TRIE) {
3468 /* NOTE - There is similar code to this block above for handling
3469 BRANCH nodes on the initial study. If you change stuff here
3471 regnode *tail= regnext(scan);
3472 reg_trie_data *trie = (reg_trie_data*)RExC_rx->data->data[ ARG(scan) ];
3473 I32 max1 = 0, min1 = I32_MAX;
3474 struct regnode_charclass_class accum;
3476 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
3477 scan_commit(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
3478 if (flags & SCF_DO_STCLASS)
3479 cl_init_zero(pRExC_state, &accum);
3485 const regnode *nextbranch= NULL;
3488 for ( word=1 ; word <= trie->wordcount ; word++)
3490 I32 deltanext=0, minnext=0, f = 0, fake;
3491 struct regnode_charclass_class this_class;
3493 data_fake.flags = 0;
3495 data_fake.whilem_c = data->whilem_c;
3496 data_fake.last_closep = data->last_closep;
3499 data_fake.last_closep = &fake;
3501 if (flags & SCF_DO_STCLASS) {
3502 cl_init(pRExC_state, &this_class);
3503 data_fake.start_class = &this_class;
3504 f = SCF_DO_STCLASS_AND;
3506 if (flags & SCF_WHILEM_VISITED_POS)
3507 f |= SCF_WHILEM_VISITED_POS;
3509 if (trie->jump[word]) {
3511 nextbranch = tail - trie->jump[0];
3512 scan= tail - trie->jump[word];
3513 /* We go from the jump point to the branch that follows
3514 it. Note this means we need the vestigal unused branches
3515 even though they arent otherwise used.
3517 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
3518 (regnode *)nextbranch, &data_fake, f,depth+1);
3520 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
3521 nextbranch= regnext((regnode*)nextbranch);
3523 if (min1 > (I32)(minnext + trie->minlen))
3524 min1 = minnext + trie->minlen;
3525 if (max1 < (I32)(minnext + deltanext + trie->maxlen))
3526 max1 = minnext + deltanext + trie->maxlen;
3527 if (deltanext == I32_MAX)
3528 is_inf = is_inf_internal = 1;
3530 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3534 if (data_fake.flags & SF_HAS_EVAL)
3535 data->flags |= SF_HAS_EVAL;
3536 data->whilem_c = data_fake.whilem_c;
3538 if (flags & SCF_DO_STCLASS)
3539 cl_or(pRExC_state, &accum, &this_class);
3542 if (flags & SCF_DO_SUBSTR) {
3543 data->pos_min += min1;
3544 data->pos_delta += max1 - min1;
3545 if (max1 != min1 || is_inf)
3546 data->longest = &(data->longest_float);
3549 delta += max1 - min1;
3550 if (flags & SCF_DO_STCLASS_OR) {
3551 cl_or(pRExC_state, data->start_class, &accum);
3553 cl_and(data->start_class, &and_with);
3554 flags &= ~SCF_DO_STCLASS;
3557 else if (flags & SCF_DO_STCLASS_AND) {
3559 cl_and(data->start_class, &accum);
3560 flags &= ~SCF_DO_STCLASS;
3563 /* Switch to OR mode: cache the old value of
3564 * data->start_class */
3565 StructCopy(data->start_class, &and_with,
3566 struct regnode_charclass_class);
3567 flags &= ~SCF_DO_STCLASS_AND;
3568 StructCopy(&accum, data->start_class,
3569 struct regnode_charclass_class);
3570 flags |= SCF_DO_STCLASS_OR;
3571 data->start_class->flags |= ANYOF_EOS;
3578 else if (PL_regkind[OP(scan)] == TRIE) {
3579 reg_trie_data *trie = (reg_trie_data*)RExC_rx->data->data[ ARG(scan) ];
3582 min += trie->minlen;
3583 delta += (trie->maxlen - trie->minlen);
3584 flags &= ~SCF_DO_STCLASS; /* xxx */
3585 if (flags & SCF_DO_SUBSTR) {
3586 scan_commit(pRExC_state,data,minlenp); /* Cannot expect anything... */
3587 data->pos_min += trie->minlen;
3588 data->pos_delta += (trie->maxlen - trie->minlen);
3589 if (trie->maxlen != trie->minlen)
3590 data->longest = &(data->longest_float);
3592 if (trie->jump) /* no more substrings -- for now /grr*/
3593 flags &= ~SCF_DO_SUBSTR;
3595 #endif /* old or new */
3596 #endif /* TRIE_STUDY_OPT */
3597 /* Else: zero-length, ignore. */
3598 scan = regnext(scan);
3603 *deltap = is_inf_internal ? I32_MAX : delta;
3604 if (flags & SCF_DO_SUBSTR && is_inf)
3605 data->pos_delta = I32_MAX - data->pos_min;
3606 if (is_par > (I32)U8_MAX)
3608 if (is_par && pars==1 && data) {
3609 data->flags |= SF_IN_PAR;
3610 data->flags &= ~SF_HAS_PAR;
3612 else if (pars && data) {
3613 data->flags |= SF_HAS_PAR;
3614 data->flags &= ~SF_IN_PAR;
3616 if (flags & SCF_DO_STCLASS_OR)
3617 cl_and(data->start_class, &and_with);
3618 if (flags & SCF_TRIE_RESTUDY)
3619 data->flags |= SCF_TRIE_RESTUDY;
3621 DEBUG_STUDYDATA(data,depth);
3627 S_add_data(RExC_state_t *pRExC_state, I32 n, const char *s)
3629 if (RExC_rx->data) {
3630 Renewc(RExC_rx->data,
3631 sizeof(*RExC_rx->data) + sizeof(void*) * (RExC_rx->data->count + n - 1),
3632 char, struct reg_data);
3633 Renew(RExC_rx->data->what, RExC_rx->data->count + n, U8);
3634 RExC_rx->data->count += n;
3637 Newxc(RExC_rx->data, sizeof(*RExC_rx->data) + sizeof(void*) * (n - 1),
3638 char, struct reg_data);
3639 Newx(RExC_rx->data->what, n, U8);
3640 RExC_rx->data->count = n;
3642 Copy(s, RExC_rx->data->what + RExC_rx->data->count - n, n, U8);
3643 return RExC_rx->data->count - n;
3646 #ifndef PERL_IN_XSUB_RE
3648 Perl_reginitcolors(pTHX)
3651 const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
3653 char *t = savepv(s);
3657 t = strchr(t, '\t');
3663 PL_colors[i] = t = (char *)"";
3668 PL_colors[i++] = (char *)"";
3675 #ifdef TRIE_STUDY_OPT
3676 #define CHECK_RESTUDY_GOTO \
3678 (data.flags & SCF_TRIE_RESTUDY) \
3682 #define CHECK_RESTUDY_GOTO
3686 - pregcomp - compile a regular expression into internal code
3688 * We can't allocate space until we know how big the compiled form will be,
3689 * but we can't compile it (and thus know how big it is) until we've got a
3690 * place to put the code. So we cheat: we compile it twice, once with code
3691 * generation turned off and size counting turned on, and once "for real".
3692 * This also means that we don't allocate space until we are sure that the
3693 * thing really will compile successfully, and we never have to move the
3694 * code and thus invalidate pointers into it. (Note that it has to be in
3695 * one piece because free() must be able to free it all.) [NB: not true in perl]
3697 * Beware that the optimization-preparation code in here knows about some
3698 * of the structure of the compiled regexp. [I'll say.]
3700 #ifndef PERL_IN_XSUB_RE
3701 #define CORE_ONLY_BLOCK(c) {c}{
3702 #define RE_ENGINE_PTR &PL_core_reg_engine
3704 #define CORE_ONLY_BLOCK(c) {
3705 extern const struct regexp_engine my_reg_engine;
3706 #define RE_ENGINE_PTR &my_reg_engine
3711 Perl_pregcomp(pTHX_ char *exp, char *xend, PMOP *pm)
3714 GET_RE_DEBUG_FLAGS_DECL;
3715 DEBUG_r(if (!PL_colorset) reginitcolors());
3717 /* Dispatch a request to compile a regexp to correct
3719 HV * const table = GvHV(PL_hintgv);
3721 SV **ptr= hv_fetchs(table, "regcomp", FALSE);
3722 if (ptr && SvIOK(*ptr)) {
3723 const regexp_engine *eng=INT2PTR(regexp_engine*,SvIV(*ptr));
3725 PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
3728 return CALLREGCOMP_ENG(eng, exp, xend, pm);
3739 RExC_state_t RExC_state;
3740 RExC_state_t * const pRExC_state = &RExC_state;
3741 #ifdef TRIE_STUDY_OPT
3743 RExC_state_t copyRExC_state;
3746 FAIL("NULL regexp argument");
3748 RExC_utf8 = pm->op_pmdynflags & PMdf_CMP_UTF8;
3752 SV *dsv= sv_newmortal();
3753 RE_PV_QUOTED_DECL(s, RExC_utf8,
3754 dsv, RExC_precomp, (xend - exp), 60);
3755 PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
3756 PL_colors[4],PL_colors[5],s);
3758 RExC_flags = pm->op_pmflags;
3762 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
3763 RExC_seen_evals = 0;
3766 /* First pass: determine size, legality. */
3773 RExC_emit = &PL_regdummy;
3774 RExC_whilem_seen = 0;
3775 RExC_charnames = NULL;
3777 RExC_paren_names = NULL;
3779 #if 0 /* REGC() is (currently) a NOP at the first pass.
3780 * Clever compilers notice this and complain. --jhi */
3781 REGC((U8)REG_MAGIC, (char*)RExC_emit);
3783 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n"));
3784 if (reg(pRExC_state, 0, &flags,1) == NULL) {
3785 RExC_precomp = NULL;
3789 PerlIO_printf(Perl_debug_log,
3790 "Required size %"IVdf" nodes\n"
3791 "Starting second pass (creation)\n",
3794 RExC_lastparse=NULL;
3796 /* Small enough for pointer-storage convention?
3797 If extralen==0, this means that we will not need long jumps. */
3798 if (RExC_size >= 0x10000L && RExC_extralen)
3799 RExC_size += RExC_extralen;
3802 if (RExC_whilem_seen > 15)
3803 RExC_whilem_seen = 15;
3805 /* Allocate space and zero-initialize. Note, the two step process
3806 of zeroing when in debug mode, thus anything assigned has to
3807 happen after that */
3808 Newxc(r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode),
3811 FAIL("Regexp out of space");
3813 /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
3814 Zero(r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode), char);
3816 /* initialization begins here */
3817 r->engine= RE_ENGINE_PTR;
3819 r->prelen = xend - exp;
3820 r->precomp = savepvn(RExC_precomp, r->prelen);
3822 #ifdef PERL_OLD_COPY_ON_WRITE
3823 r->saved_copy = NULL;
3825 r->reganch = pm->op_pmflags & PMf_COMPILETIME;
3826 r->nparens = RExC_npar - 1; /* set early to validate backrefs */
3827 r->lastparen = 0; /* mg.c reads this. */
3829 r->substrs = 0; /* Useful during FAIL. */
3830 r->startp = 0; /* Useful during FAIL. */
3834 if (RExC_seen & REG_SEEN_RECURSE) {
3835 Newx(RExC_parens, RExC_npar,regnode *);
3836 SAVEFREEPV(RExC_parens);
3839 /* Useful during FAIL. */
3840 Newxz(r->offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
3842 r->offsets[0] = RExC_size;
3844 DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
3845 "%s %"UVuf" bytes for offset annotations.\n",
3846 r->offsets ? "Got" : "Couldn't get",
3847 (UV)((2*RExC_size+1) * sizeof(U32))));
3851 /* Second pass: emit code. */
3852 RExC_flags = pm->op_pmflags; /* don't let top level (?i) bleed */
3857 RExC_emit_start = r->program;
3858 RExC_emit = r->program;
3859 /* Store the count of eval-groups for security checks: */
3860 RExC_emit->next_off = (RExC_seen_evals > (I32)U16_MAX) ? U16_MAX : (U16)RExC_seen_evals;
3861 REGC((U8)REG_MAGIC, (char*) RExC_emit++);
3863 if (reg(pRExC_state, 0, &flags,1) == NULL)
3866 /* XXXX To minimize changes to RE engine we always allocate
3867 3-units-long substrs field. */
3868 Newx(r->substrs, 1, struct reg_substr_data);
3871 r->minlen = minlen = sawplus = sawopen = 0;
3872 Zero(r->substrs, 1, struct reg_substr_data);
3873 StructCopy(&zero_scan_data, &data, scan_data_t);
3875 #ifdef TRIE_STUDY_OPT
3877 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
3878 RExC_state=copyRExC_state;
3879 if (data.last_found) {
3880 SvREFCNT_dec(data.longest_fixed);
3881 SvREFCNT_dec(data.longest_float);
3882 SvREFCNT_dec(data.last_found);
3885 copyRExC_state=RExC_state;
3889 /* Dig out information for optimizations. */
3890 r->reganch = pm->op_pmflags & PMf_COMPILETIME; /* Again? */
3891 pm->op_pmflags = RExC_flags;
3893 r->reganch |= ROPT_UTF8; /* Unicode in it? */
3894 r->regstclass = NULL;
3895 if (RExC_naughty >= 10) /* Probably an expensive pattern. */
3896 r->reganch |= ROPT_NAUGHTY;
3897 scan = r->program + 1; /* First BRANCH. */
3899 /* testing for BRANCH here tells us whether there is "must appear"
3900 data in the pattern. If there is then we can use it for optimisations */
3901 if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES)) { /* Only one top-level choice. */
3903 STRLEN longest_float_length, longest_fixed_length;
3904 struct regnode_charclass_class ch_class; /* pointed to by data */
3906 I32 last_close = 0; /* pointed to by data */
3909 /* Skip introductions and multiplicators >= 1. */
3910 while ((OP(first) == OPEN && (sawopen = 1)) ||
3911 /* An OR of *one* alternative - should not happen now. */
3912 (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
3913 /* for now we can't handle lookbehind IFMATCH*/
3914 (OP(first) == IFMATCH && !first->flags) ||
3915 (OP(first) == PLUS) ||
3916 (OP(first) == MINMOD) ||
3917 /* An {n,m} with n>0 */
3918 (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) )
3921 if (OP(first) == PLUS)
3924 first += regarglen[OP(first)];
3925 if (OP(first) == IFMATCH) {
3926 first = NEXTOPER(first);
3927 first += EXTRA_STEP_2ARGS;
3928 } else /* XXX possible optimisation for /(?=)/ */
3929 first = NEXTOPER(first);
3932 /* Starting-point info. */
3934 DEBUG_PEEP("first:",first,0);
3935 /* Ignore EXACT as we deal with it later. */
3936 if (PL_regkind[OP(first)] == EXACT) {
3937 if (OP(first) == EXACT)
3938 NOOP; /* Empty, get anchored substr later. */
3939 else if ((OP(first) == EXACTF || OP(first) == EXACTFL))
3940 r->regstclass = first;
3943 else if (PL_regkind[OP(first)] == TRIE &&
3944 ((reg_trie_data *)r->data->data[ ARG(first) ])->minlen>0)
3947 /* this can happen only on restudy */
3948 if ( OP(first) == TRIE ) {
3949 struct regnode_1 *trieop;
3950 Newxz(trieop,1,struct regnode_1);
3951 StructCopy(first,trieop,struct regnode_1);
3952 trie_op=(regnode *)trieop;
3954 struct regnode_charclass *trieop;
3955 Newxz(trieop,1,struct regnode_charclass);
3956 StructCopy(first,trieop,struct regnode_charclass);
3957 trie_op=(regnode *)trieop;
3960 make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
3961 r->regstclass = trie_op;
3964 else if (strchr((const char*)PL_simple,OP(first)))
3965 r->regstclass = first;
3966 else if (PL_regkind[OP(first)] == BOUND ||
3967 PL_regkind[OP(first)] == NBOUND)
3968 r->regstclass = first;
3969 else if (PL_regkind[OP(first)] == BOL) {
3970 r->reganch |= (OP(first) == MBOL
3972 : (OP(first) == SBOL
3975 first = NEXTOPER(first);
3978 else if (OP(first) == GPOS) {
3979 r->reganch |= ROPT_ANCH_GPOS;
3980 first = NEXTOPER(first);
3983 else if (!sawopen && (OP(first) == STAR &&
3984 PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
3985 !(r->reganch & ROPT_ANCH) )
3987 /* turn .* into ^.* with an implied $*=1 */
3989 (OP(NEXTOPER(first)) == REG_ANY)
3992 r->reganch |= type | ROPT_IMPLICIT;
3993 first = NEXTOPER(first);
3996 if (sawplus && (!sawopen || !RExC_sawback)
3997 && !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
3998 /* x+ must match at the 1st pos of run of x's */
3999 r->reganch |= ROPT_SKIP;
4001 /* Scan is after the zeroth branch, first is atomic matcher. */
4002 #ifdef TRIE_STUDY_OPT
4005 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4006 (IV)(first - scan + 1))
4010 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4011 (IV)(first - scan + 1))
4017 * If there's something expensive in the r.e., find the
4018 * longest literal string that must appear and make it the
4019 * regmust. Resolve ties in favor of later strings, since
4020 * the regstart check works with the beginning of the r.e.
4021 * and avoiding duplication strengthens checking. Not a
4022 * strong reason, but sufficient in the absence of others.
4023 * [Now we resolve ties in favor of the earlier string if
4024 * it happens that c_offset_min has been invalidated, since the
4025 * earlier string may buy us something the later one won't.]
4029 data.longest_fixed = newSVpvs("");
4030 data.longest_float = newSVpvs("");
4031 data.last_found = newSVpvs("");
4032 data.longest = &(data.longest_fixed);
4034 if (!r->regstclass) {
4035 cl_init(pRExC_state, &ch_class);
4036 data.start_class = &ch_class;
4037 stclass_flag = SCF_DO_STCLASS_AND;
4038 } else /* XXXX Check for BOUND? */
4040 data.last_closep = &last_close;
4042 minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
4043 &data, SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag,0);
4049 if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
4050 && data.last_start_min == 0 && data.last_end > 0
4051 && !RExC_seen_zerolen
4052 && (!(RExC_seen & REG_SEEN_GPOS) || (r->reganch & ROPT_ANCH_GPOS)))
4053 r->reganch |= ROPT_CHECK_ALL;
4054 scan_commit(pRExC_state, &data,&minlen);
4055 SvREFCNT_dec(data.last_found);
4057 /* Note that code very similar to this but for anchored string
4058 follows immediately below, changes may need to be made to both.
4061 longest_float_length = CHR_SVLEN(data.longest_float);
4062 if (longest_float_length
4063 || (data.flags & SF_FL_BEFORE_EOL
4064 && (!(data.flags & SF_FL_BEFORE_MEOL)
4065 || (RExC_flags & PMf_MULTILINE))))
4069 if (SvCUR(data.longest_fixed) /* ok to leave SvCUR */
4070 && data.offset_fixed == data.offset_float_min
4071 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
4072 goto remove_float; /* As in (a)+. */
4074 /* copy the information about the longest float from the reg_scan_data
4075 over to the program. */
4076 if (SvUTF8(data.longest_float)) {
4077 r->float_utf8 = data.longest_float;
4078 r->float_substr = NULL;
4080 r->float_substr = data.longest_float;
4081 r->float_utf8 = NULL;
4083 /* float_end_shift is how many chars that must be matched that
4084 follow this item. We calculate it ahead of time as once the
4085 lookbehind offset is added in we lose the ability to correctly
4087 ml = data.minlen_float ? *(data.minlen_float)
4088 : (I32)longest_float_length;
4089 r->float_end_shift = ml - data.offset_float_min
4090 - longest_float_length + (SvTAIL(data.longest_float) != 0)
4091 + data.lookbehind_float;
4092 r->float_min_offset = data.offset_float_min - data.lookbehind_float;
4093 r->float_max_offset = data.offset_float_max;
4094 if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
4095 r->float_max_offset -= data.lookbehind_float;
4097 t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
4098 && (!(data.flags & SF_FL_BEFORE_MEOL)
4099 || (RExC_flags & PMf_MULTILINE)));
4100 fbm_compile(data.longest_float, t ? FBMcf_TAIL : 0);
4104 r->float_substr = r->float_utf8 = NULL;
4105 SvREFCNT_dec(data.longest_float);
4106 longest_float_length = 0;
4109 /* Note that code very similar to this but for floating string
4110 is immediately above, changes may need to be made to both.
4113 longest_fixed_length = CHR_SVLEN(data.longest_fixed);
4114 if (longest_fixed_length
4115 || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
4116 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4117 || (RExC_flags & PMf_MULTILINE))))
4121 /* copy the information about the longest fixed
4122 from the reg_scan_data over to the program. */
4123 if (SvUTF8(data.longest_fixed)) {
4124 r->anchored_utf8 = data.longest_fixed;
4125 r->anchored_substr = NULL;
4127 r->anchored_substr = data.longest_fixed;
4128 r->anchored_utf8 = NULL;
4130 /* fixed_end_shift is how many chars that must be matched that
4131 follow this item. We calculate it ahead of time as once the
4132 lookbehind offset is added in we lose the ability to correctly
4134 ml = data.minlen_fixed ? *(data.minlen_fixed)
4135 : (I32)longest_fixed_length;
4136 r->anchored_end_shift = ml - data.offset_fixed
4137 - longest_fixed_length + (SvTAIL(data.longest_fixed) != 0)
4138 + data.lookbehind_fixed;
4139 r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
4141 t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
4142 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4143 || (RExC_flags & PMf_MULTILINE)));
4144 fbm_compile(data.longest_fixed, t ? FBMcf_TAIL : 0);
4147 r->anchored_substr = r->anchored_utf8 = NULL;
4148 SvREFCNT_dec(data.longest_fixed);
4149 longest_fixed_length = 0;
4152 && (OP(r->regstclass) == REG_ANY || OP(r->regstclass) == SANY))
4153 r->regstclass = NULL;
4154 if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
4156 && !(data.start_class->flags & ANYOF_EOS)
4157 && !cl_is_anything(data.start_class))
4159 const I32 n = add_data(pRExC_state, 1, "f");
4161 Newx(RExC_rx->data->data[n], 1,
4162 struct regnode_charclass_class);
4163 StructCopy(data.start_class,
4164 (struct regnode_charclass_class*)RExC_rx->data->data[n],
4165 struct regnode_charclass_class);
4166 r->regstclass = (regnode*)RExC_rx->data->data[n];
4167 r->reganch &= ~ROPT_SKIP; /* Used in find_byclass(). */
4168 DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
4169 regprop(r, sv, (regnode*)data.start_class);
4170 PerlIO_printf(Perl_debug_log,
4171 "synthetic stclass \"%s\".\n",
4172 SvPVX_const(sv));});
4175 /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
4176 if (longest_fixed_length > longest_float_length) {
4177 r->check_end_shift = r->anchored_end_shift;
4178 r->check_substr = r->anchored_substr;
4179 r->check_utf8 = r->anchored_utf8;
4180 r->check_offset_min = r->check_offset_max = r->anchored_offset;
4181 if (r->reganch & ROPT_ANCH_SINGLE)
4182 r->reganch |= ROPT_NOSCAN;
4185 r->check_end_shift = r->float_end_shift;
4186 r->check_substr = r->float_substr;
4187 r->check_utf8 = r->float_utf8;
4188 r->check_offset_min = r->float_min_offset;
4189 r->check_offset_max = r->float_max_offset;
4191 /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
4192 This should be changed ASAP! */
4193 if ((r->check_substr || r->check_utf8) && !(r->reganch & ROPT_ANCH_GPOS)) {
4194 r->reganch |= RE_USE_INTUIT;
4195 if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
4196 r->reganch |= RE_INTUIT_TAIL;
4198 /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
4199 if ( (STRLEN)minlen < longest_float_length )
4200 minlen= longest_float_length;
4201 if ( (STRLEN)minlen < longest_fixed_length )
4202 minlen= longest_fixed_length;
4206 /* Several toplevels. Best we can is to set minlen. */
4208 struct regnode_charclass_class ch_class;
4211 DEBUG_COMPILE_r(PerlIO_printf(Perl_debug_log, "\n"));
4213 scan = r->program + 1;
4214 cl_init(pRExC_state, &ch_class);
4215 data.start_class = &ch_class;
4216 data.last_closep = &last_close;
4218 minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
4219 &data, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS,0);
4223 r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
4224 = r->float_substr = r->float_utf8 = NULL;
4225 if (!(data.start_class->flags & ANYOF_EOS)
4226 && !cl_is_anything(data.start_class))
4228 const I32 n = add_data(pRExC_state, 1, "f");
4230 Newx(RExC_rx->data->data[n], 1,
4231 struct regnode_charclass_class);
4232 StructCopy(data.start_class,
4233 (struct regnode_charclass_class*)RExC_rx->data->data[n],
4234 struct regnode_charclass_class);
4235 r->regstclass = (regnode*)RExC_rx->data->data[n];
4236 r->reganch &= ~ROPT_SKIP; /* Used in find_byclass(). */
4237 DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
4238 regprop(r, sv, (regnode*)data.start_class);
4239 PerlIO_printf(Perl_debug_log,
4240 "synthetic stclass \"%s\".\n",
4241 SvPVX_const(sv));});
4245 /* Guard against an embedded (?=) or (?<=) with a longer minlen than
4246 the "real" pattern. */
4247 if (r->minlen < minlen)
4250 if (RExC_seen & REG_SEEN_GPOS)
4251 r->reganch |= ROPT_GPOS_SEEN;
4252 if (RExC_seen & REG_SEEN_LOOKBEHIND)
4253 r->reganch |= ROPT_LOOKBEHIND_SEEN;
4254 if (RExC_seen & REG_SEEN_EVAL)
4255 r->reganch |= ROPT_EVAL_SEEN;
4256 if (RExC_seen & REG_SEEN_CANY)
4257 r->reganch |= ROPT_CANY_SEEN;
4258 if (RExC_paren_names)
4259 r->paren_names = (HV*)SvREFCNT_inc(RExC_paren_names);
4261 r->paren_names = NULL;
4263 Newxz(r->startp, RExC_npar, I32);
4264 Newxz(r->endp, RExC_npar, I32);
4266 DEBUG_r( RX_DEBUG_on(r) );
4268 PerlIO_printf(Perl_debug_log,"Final program:\n");
4271 DEBUG_OFFSETS_r(if (r->offsets) {
4272 const U32 len = r->offsets[0];
4274 GET_RE_DEBUG_FLAGS_DECL;
4275 PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)r->offsets[0]);
4276 for (i = 1; i <= len; i++) {
4277 if (r->offsets[i*2-1] || r->offsets[i*2])
4278 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
4279 (UV)i, (UV)r->offsets[i*2-1], (UV)r->offsets[i*2]);
4281 PerlIO_printf(Perl_debug_log, "\n");
4287 #undef CORE_ONLY_BLOCK
4289 #undef RE_ENGINE_PTR
4292 Perl_reg_named_buff_sv(pTHX_ SV* namesv)
4294 I32 parno = 0; /* no match */
4296 const REGEXP * const rx = PM_GETRE(PL_curpm);
4297 if (rx && rx->paren_names) {
4298 HE *he_str = hv_fetch_ent( rx->paren_names, namesv, 0, 0 );
4301 SV* sv_dat=HeVAL(he_str);
4302 I32 *nums=(I32*)SvPVX(sv_dat);
4303 for ( i=0; i<SvIVX(sv_dat); i++ ) {
4304 if ((I32)(rx->lastcloseparen) >= nums[i] &&
4305 rx->startp[nums[i]] != -1 &&
4306 rx->endp[nums[i]] != -1)
4319 SV *sv= sv_newmortal();
4320 Perl_sv_setpvf(aTHX_ sv, "%"IVdf,(IV)parno);
4321 gv_paren= Perl_gv_fetchsv(aTHX_ sv, GV_ADD, SVt_PVGV);
4322 return GvSVn(gv_paren);
4326 /* Scans the name of a named buffer from the pattern.
4327 * If flags is true then returns an SV containing the name.
4330 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags) {
4331 char *name_start = RExC_parse;
4334 while (isIDFIRST_uni(utf8n_to_uvchr((U8*)RExC_parse,
4335 RExC_end - RExC_parse,
4336 &numlen, UTF8_ALLOW_DEFAULT)))
4337 RExC_parse += numlen;
4340 while (isIDFIRST(*RExC_parse))
4344 SV* svname = sv_2mortal(Perl_newSVpvn(aTHX_ name_start,
4345 (int)(RExC_parse - name_start)));
4355 #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
4356 int rem=(int)(RExC_end - RExC_parse); \
4365 if (RExC_lastparse!=RExC_parse) \
4366 PerlIO_printf(Perl_debug_log," >%.*s%-*s", \
4369 iscut ? "..." : "<" \
4372 PerlIO_printf(Perl_debug_log,"%16s",""); \
4377 num=REG_NODE_NUM(RExC_emit); \
4378 if (RExC_lastnum!=num) \
4379 PerlIO_printf(Perl_debug_log,"|%4d",num); \
4381 PerlIO_printf(Perl_debug_log,"|%4s",""); \
4382 PerlIO_printf(Perl_debug_log,"|%*s%-4s", \
4383 (int)((depth*2)), "", \
4387 RExC_lastparse=RExC_parse; \
4392 #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
4393 DEBUG_PARSE_MSG((funcname)); \
4394 PerlIO_printf(Perl_debug_log,"%4s","\n"); \
4396 #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({ \
4397 DEBUG_PARSE_MSG((funcname)); \
4398 PerlIO_printf(Perl_debug_log,fmt "\n",args); \
4401 - reg - regular expression, i.e. main body or parenthesized thing
4403 * Caller must absorb opening parenthesis.
4405 * Combining parenthesis handling with the base level of regular expression
4406 * is a trifle forced, but the need to tie the tails of the branches to what
4407 * follows makes it hard to avoid.
4409 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
4411 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
4413 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
4417 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
4418 /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
4421 register regnode *ret; /* Will be the head of the group. */
4422 register regnode *br;
4423 register regnode *lastbr;
4424 register regnode *ender = NULL;
4425 register I32 parno = 0;
4427 const I32 oregflags = RExC_flags;
4428 bool have_branch = 0;
4431 /* for (?g), (?gc), and (?o) warnings; warning
4432 about (?c) will warn about (?g) -- japhy */
4434 #define WASTED_O 0x01
4435 #define WASTED_G 0x02
4436 #define WASTED_C 0x04
4437 #define WASTED_GC (0x02|0x04)
4438 I32 wastedflags = 0x00;
4440 char * parse_start = RExC_parse; /* MJD */
4441 char * const oregcomp_parse = RExC_parse;
4443 GET_RE_DEBUG_FLAGS_DECL;
4444 DEBUG_PARSE("reg ");
4447 *flagp = 0; /* Tentatively. */
4450 /* Make an OPEN node, if parenthesized. */
4452 if (*RExC_parse == '?') { /* (?...) */
4453 U32 posflags = 0, negflags = 0;
4454 U32 *flagsp = &posflags;
4455 bool is_logical = 0;
4456 const char * const seqstart = RExC_parse;
4459 paren = *RExC_parse++;
4460 ret = NULL; /* For look-ahead/behind. */
4463 case '<': /* (?<...) */
4464 if (*RExC_parse == '!')
4466 else if (*RExC_parse != '=') { /* (?<...>) */
4470 case '\'': /* (?'...') */
4471 name_start= RExC_parse;
4472 svname = reg_scan_name(pRExC_state,SIZE_ONLY);
4473 if (RExC_parse == name_start)
4475 if (*RExC_parse != paren)
4476 vFAIL2("Sequence (?%c... not terminated",
4477 paren=='>' ? '<' : paren);
4481 if (!svname) /* shouldnt happen */
4483 "panic: reg_scan_name returned NULL");
4484 if (!RExC_paren_names) {
4485 RExC_paren_names= newHV();
4486 sv_2mortal((SV*)RExC_paren_names);
4488 he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
4490 sv_dat = HeVAL(he_str);
4492 /* croak baby croak */
4494 "panic: paren_name hash element allocation failed");
4495 } else if ( SvPOK(sv_dat) ) {
4496 IV count=SvIV(sv_dat);
4497 I32 *pv=(I32*)SvGROW(sv_dat,SvCUR(sv_dat)+sizeof(I32)+1);
4498 SvCUR_set(sv_dat,SvCUR(sv_dat)+sizeof(I32));
4499 pv[count]=RExC_npar;
4502 (void)SvUPGRADE(sv_dat,SVt_PVNV);
4503 sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32));
4508 /*sv_dump(sv_dat);*/
4510 nextchar(pRExC_state);
4512 goto capturing_parens;
4514 RExC_seen |= REG_SEEN_LOOKBEHIND;
4516 case '=': /* (?=...) */
4517 case '!': /* (?!...) */
4518 RExC_seen_zerolen++;
4519 case ':': /* (?:...) */
4520 case '>': /* (?>...) */
4522 case '$': /* (?$...) */
4523 case '@': /* (?@...) */
4524 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
4526 case '#': /* (?#...) */
4527 while (*RExC_parse && *RExC_parse != ')')
4529 if (*RExC_parse != ')')
4530 FAIL("Sequence (?#... not terminated");
4531 nextchar(pRExC_state);
4534 case '0' : /* (?0) */
4535 case 'R' : /* (?R) */
4536 if (*RExC_parse != ')')
4537 FAIL("Sequence (?R) not terminated");
4538 reg_node(pRExC_state, SRECURSE);
4539 break; /* (?PARNO) */
4540 { /* named and numeric backreferences */
4543 case '&': /* (?&NAME) */
4544 parse_start = RExC_parse - 1;
4546 char *name_start = RExC_parse;
4547 SV *svname = reg_scan_name(pRExC_state, !SIZE_ONLY);
4548 if (RExC_parse == name_start)
4550 if (*RExC_parse != ')')
4551 vFAIL("Expecting close bracket");
4555 if (!svname) /* shouldn't happen*/
4556 Perl_croak(aTHX_ "panic: reg_scan_name returned NULL");
4557 if (RExC_paren_names)
4558 he_str = hv_fetch_ent( RExC_paren_names, svname, 0, 0 );
4560 sv_dat = HeVAL(he_str);
4562 vFAIL("Reference to nonexistent group");
4563 num = *((I32 *)SvPVX(sv_dat));
4568 goto gen_recurse_regop;
4570 case '1': case '2': case '3': case '4': /* (?1) */
4571 case '5': case '6': case '7': case '8': case '9':
4573 num = atoi(RExC_parse);
4574 parse_start = RExC_parse - 1; /* MJD */
4575 while (isDIGIT(*RExC_parse))
4577 if (*RExC_parse!=')')
4578 vFAIL("Expecting close bracket");
4581 ret = reganode(pRExC_state, RECURSE, num);
4583 if (num > (I32)RExC_rx->nparens) {
4585 vFAIL("Reference to nonexistent group");
4589 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
4590 "Recurse #%"UVuf" to %"IVdf"\n", ARG(ret), ARG2L(ret)));
4593 RExC_seen|=REG_SEEN_RECURSE;
4595 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
4596 Set_Node_Offset(ret, parse_start); /* MJD */
4598 nextchar(pRExC_state);
4600 } /* named and numeric backreferences */
4603 case 'p': /* (?p...) */
4604 if (SIZE_ONLY && ckWARN2(WARN_DEPRECATED, WARN_REGEXP))
4605 vWARNdep(RExC_parse, "(?p{}) is deprecated - use (??{})");
4607 case '?': /* (??...) */
4609 if (*RExC_parse != '{')
4611 paren = *RExC_parse++;
4613 case '{': /* (?{...}) */
4615 I32 count = 1, n = 0;
4617 char *s = RExC_parse;
4619 RExC_seen_zerolen++;
4620 RExC_seen |= REG_SEEN_EVAL;
4621 while (count && (c = *RExC_parse)) {
4632 if (*RExC_parse != ')') {
4634 vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
4638 OP_4tree *sop, *rop;
4639 SV * const sv = newSVpvn(s, RExC_parse - 1 - s);
4642 Perl_save_re_context(aTHX);
4643 rop = sv_compile_2op(sv, &sop, "re", &pad);
4644 sop->op_private |= OPpREFCOUNTED;
4645 /* re_dup will OpREFCNT_inc */
4646 OpREFCNT_set(sop, 1);
4649 n = add_data(pRExC_state, 3, "nop");
4650 RExC_rx->data->data[n] = (void*)rop;
4651 RExC_rx->data->data[n+1] = (void*)sop;
4652 RExC_rx->data->data[n+2] = (void*)pad;
4655 else { /* First pass */
4656 if (PL_reginterp_cnt < ++RExC_seen_evals
4658 /* No compiled RE interpolated, has runtime
4659 components ===> unsafe. */
4660 FAIL("Eval-group not allowed at runtime, use re 'eval'");
4661 if (PL_tainting && PL_tainted)
4662 FAIL("Eval-group in insecure regular expression");
4663 #if PERL_VERSION > 8
4664 if (IN_PERL_COMPILETIME)
4669 nextchar(pRExC_state);
4671 ret = reg_node(pRExC_state, LOGICAL);
4674 REGTAIL(pRExC_state, ret, reganode(pRExC_state, EVAL, n));
4675 /* deal with the length of this later - MJD */
4678 ret = reganode(pRExC_state, EVAL, n);
4679 Set_Node_Length(ret, RExC_parse - parse_start + 1);
4680 Set_Node_Offset(ret, parse_start);
4683 case '(': /* (?(?{...})...) and (?(?=...)...) */
4685 if (RExC_parse[0] == '?') { /* (?(?...)) */
4686 if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
4687 || RExC_parse[1] == '<'
4688 || RExC_parse[1] == '{') { /* Lookahead or eval. */
4691 ret = reg_node(pRExC_state, LOGICAL);
4694 REGTAIL(pRExC_state, ret, reg(pRExC_state, 1, &flag,depth+1));
4698 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
4701 parno = atoi(RExC_parse++);
4703 while (isDIGIT(*RExC_parse))
4705 ret = reganode(pRExC_state, GROUPP, parno);
4707 if ((c = *nextchar(pRExC_state)) != ')')
4708 vFAIL("Switch condition not recognized");
4710 REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
4711 br = regbranch(pRExC_state, &flags, 1,depth+1);
4713 br = reganode(pRExC_state, LONGJMP, 0);
4715 REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
4716 c = *nextchar(pRExC_state);
4720 lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
4721 regbranch(pRExC_state, &flags, 1,depth+1);
4722 REGTAIL(pRExC_state, ret, lastbr);
4725 c = *nextchar(pRExC_state);
4730 vFAIL("Switch (?(condition)... contains too many branches");
4731 ender = reg_node(pRExC_state, TAIL);
4732 REGTAIL(pRExC_state, br, ender);
4734 REGTAIL(pRExC_state, lastbr, ender);
4735 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
4738 REGTAIL(pRExC_state, ret, ender);
4742 vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
4746 RExC_parse--; /* for vFAIL to print correctly */
4747 vFAIL("Sequence (? incomplete");
4751 parse_flags: /* (?i) */
4752 while (*RExC_parse && strchr("iogcmsx", *RExC_parse)) {
4753 /* (?g), (?gc) and (?o) are useless here
4754 and must be globally applied -- japhy */
4756 if (*RExC_parse == 'o' || *RExC_parse == 'g') {
4757 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
4758 const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
4759 if (! (wastedflags & wflagbit) ) {
4760 wastedflags |= wflagbit;
4763 "Useless (%s%c) - %suse /%c modifier",
4764 flagsp == &negflags ? "?-" : "?",
4766 flagsp == &negflags ? "don't " : "",
4772 else if (*RExC_parse == 'c') {
4773 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
4774 if (! (wastedflags & WASTED_C) ) {
4775 wastedflags |= WASTED_GC;
4778 "Useless (%sc) - %suse /gc modifier",
4779 flagsp == &negflags ? "?-" : "?",
4780 flagsp == &negflags ? "don't " : ""
4785 else { pmflag(flagsp, *RExC_parse); }
4789 if (*RExC_parse == '-') {
4791 wastedflags = 0; /* reset so (?g-c) warns twice */
4795 RExC_flags |= posflags;
4796 RExC_flags &= ~negflags;
4797 if (*RExC_parse == ':') {
4803 if (*RExC_parse != ')') {
4805 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
4807 nextchar(pRExC_state);
4816 ret = reganode(pRExC_state, OPEN, parno);
4817 if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
4818 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
4819 "Setting paren #%"IVdf" to %d\n", parno, REG_NODE_NUM(ret)));
4820 RExC_parens[parno-1]= ret;
4823 Set_Node_Length(ret, 1); /* MJD */
4824 Set_Node_Offset(ret, RExC_parse); /* MJD */
4831 /* Pick up the branches, linking them together. */
4832 parse_start = RExC_parse; /* MJD */
4833 br = regbranch(pRExC_state, &flags, 1,depth+1);
4834 /* branch_len = (paren != 0); */
4838 if (*RExC_parse == '|') {
4839 if (!SIZE_ONLY && RExC_extralen) {
4840 reginsert(pRExC_state, BRANCHJ, br, depth+1);
4843 reginsert(pRExC_state, BRANCH, br, depth+1);
4844 Set_Node_Length(br, paren != 0);
4845 Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
4849 RExC_extralen += 1; /* For BRANCHJ-BRANCH. */
4851 else if (paren == ':') {
4852 *flagp |= flags&SIMPLE;
4854 if (is_open) { /* Starts with OPEN. */
4855 REGTAIL(pRExC_state, ret, br); /* OPEN -> first. */
4857 else if (paren != '?') /* Not Conditional */
4859 *flagp |= flags & (SPSTART | HASWIDTH);
4861 while (*RExC_parse == '|') {
4862 if (!SIZE_ONLY && RExC_extralen) {
4863 ender = reganode(pRExC_state, LONGJMP,0);
4864 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
4867 RExC_extralen += 2; /* Account for LONGJMP. */
4868 nextchar(pRExC_state);
4869 br = regbranch(pRExC_state, &flags, 0, depth+1);
4873 REGTAIL(pRExC_state, lastbr, br); /* BRANCH -> BRANCH. */
4877 *flagp |= flags&SPSTART;
4880 if (have_branch || paren != ':') {
4881 /* Make a closing node, and hook it on the end. */
4884 ender = reg_node(pRExC_state, TAIL);
4887 ender = reganode(pRExC_state, CLOSE, parno);
4888 Set_Node_Offset(ender,RExC_parse+1); /* MJD */
4889 Set_Node_Length(ender,1); /* MJD */
4895 *flagp &= ~HASWIDTH;
4898 ender = reg_node(pRExC_state, SUCCEED);
4901 ender = reg_node(pRExC_state, END);
4904 REGTAIL(pRExC_state, lastbr, ender);
4906 if (have_branch && !SIZE_ONLY) {
4908 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
4910 /* Hook the tails of the branches to the closing node. */
4911 for (br = ret; br; br = regnext(br)) {
4912 const U8 op = PL_regkind[OP(br)];
4914 REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
4916 else if (op == BRANCHJ) {
4917 REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
4925 static const char parens[] = "=!<,>";
4927 if (paren && (p = strchr(parens, paren))) {
4928 U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
4929 int flag = (p - parens) > 1;
4932 node = SUSPEND, flag = 0;
4933 reginsert(pRExC_state, node,ret, depth+1);
4934 Set_Node_Cur_Length(ret);
4935 Set_Node_Offset(ret, parse_start + 1);
4937 REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
4941 /* Check for proper termination. */
4943 RExC_flags = oregflags;
4944 if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
4945 RExC_parse = oregcomp_parse;
4946 vFAIL("Unmatched (");
4949 else if (!paren && RExC_parse < RExC_end) {
4950 if (*RExC_parse == ')') {
4952 vFAIL("Unmatched )");
4955 FAIL("Junk on end of regexp"); /* "Can't happen". */
4963 - regbranch - one alternative of an | operator
4965 * Implements the concatenation operator.
4968 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
4971 register regnode *ret;
4972 register regnode *chain = NULL;
4973 register regnode *latest;
4974 I32 flags = 0, c = 0;
4975 GET_RE_DEBUG_FLAGS_DECL;
4976 DEBUG_PARSE("brnc");
4980 if (!SIZE_ONLY && RExC_extralen)
4981 ret = reganode(pRExC_state, BRANCHJ,0);
4983 ret = reg_node(pRExC_state, BRANCH);
4984 Set_Node_Length(ret, 1);
4988 if (!first && SIZE_ONLY)
4989 RExC_extralen += 1; /* BRANCHJ */
4991 *flagp = WORST; /* Tentatively. */
4994 nextchar(pRExC_state);
4995 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
4997 latest = regpiece(pRExC_state, &flags,depth+1);
4998 if (latest == NULL) {
4999 if (flags & TRYAGAIN)
5003 else if (ret == NULL)
5005 *flagp |= flags&HASWIDTH;
5006 if (chain == NULL) /* First piece. */
5007 *flagp |= flags&SPSTART;
5010 REGTAIL(pRExC_state, chain, latest);
5015 if (chain == NULL) { /* Loop ran zero times. */
5016 chain = reg_node(pRExC_state, NOTHING);
5021 *flagp |= flags&SIMPLE;
5028 - regpiece - something followed by possible [*+?]
5030 * Note that the branching code sequences used for ? and the general cases
5031 * of * and + are somewhat optimized: they use the same NOTHING node as
5032 * both the endmarker for their branch list and the body of the last branch.
5033 * It might seem that this node could be dispensed with entirely, but the
5034 * endmarker role is not redundant.
5037 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
5040 register regnode *ret;
5042 register char *next;
5044 const char * const origparse = RExC_parse;
5046 I32 max = REG_INFTY;
5048 const char *maxpos = NULL;
5049 GET_RE_DEBUG_FLAGS_DECL;
5050 DEBUG_PARSE("piec");
5052 ret = regatom(pRExC_state, &flags,depth+1);
5054 if (flags & TRYAGAIN)
5061 if (op == '{' && regcurly(RExC_parse)) {
5063 parse_start = RExC_parse; /* MJD */
5064 next = RExC_parse + 1;
5065 while (isDIGIT(*next) || *next == ',') {
5074 if (*next == '}') { /* got one */
5078 min = atoi(RExC_parse);
5082 maxpos = RExC_parse;
5084 if (!max && *maxpos != '0')
5085 max = REG_INFTY; /* meaning "infinity" */
5086 else if (max >= REG_INFTY)
5087 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
5089 nextchar(pRExC_state);
5092 if ((flags&SIMPLE)) {
5093 RExC_naughty += 2 + RExC_naughty / 2;
5094 reginsert(pRExC_state, CURLY, ret, depth+1);
5095 Set_Node_Offset(ret, parse_start+1); /* MJD */
5096 Set_Node_Cur_Length(ret);
5099 regnode * const w = reg_node(pRExC_state, WHILEM);
5102 REGTAIL(pRExC_state, ret, w);
5103 if (!SIZE_ONLY && RExC_extralen) {
5104 reginsert(pRExC_state, LONGJMP,ret, depth+1);
5105 reginsert(pRExC_state, NOTHING,ret, depth+1);
5106 NEXT_OFF(ret) = 3; /* Go over LONGJMP. */
5108 reginsert(pRExC_state, CURLYX,ret, depth+1);
5110 Set_Node_Offset(ret, parse_start+1);
5111 Set_Node_Length(ret,
5112 op == '{' ? (RExC_parse - parse_start) : 1);
5114 if (!SIZE_ONLY && RExC_extralen)
5115 NEXT_OFF(ret) = 3; /* Go over NOTHING to LONGJMP. */
5116 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
5118 RExC_whilem_seen++, RExC_extralen += 3;
5119 RExC_naughty += 4 + RExC_naughty; /* compound interest */
5127 if (max && max < min)
5128 vFAIL("Can't do {n,m} with n > m");
5130 ARG1_SET(ret, (U16)min);
5131 ARG2_SET(ret, (U16)max);
5142 /* else if (OP(ret)==RECURSE) {
5144 vFAIL("Illegal quantifier on recursion group");
5147 #if 0 /* Now runtime fix should be reliable. */
5149 /* if this is reinstated, don't forget to put this back into perldiag:
5151 =item Regexp *+ operand could be empty at {#} in regex m/%s/
5153 (F) The part of the regexp subject to either the * or + quantifier
5154 could match an empty string. The {#} shows in the regular
5155 expression about where the problem was discovered.
5159 if (!(flags&HASWIDTH) && op != '?')
5160 vFAIL("Regexp *+ operand could be empty");
5163 parse_start = RExC_parse;
5164 nextchar(pRExC_state);
5166 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
5168 if (op == '*' && (flags&SIMPLE)) {
5169 reginsert(pRExC_state, STAR, ret, depth+1);
5173 else if (op == '*') {
5177 else if (op == '+' && (flags&SIMPLE)) {
5178 reginsert(pRExC_state, PLUS, ret, depth+1);
5182 else if (op == '+') {
5186 else if (op == '?') {
5191 if (!SIZE_ONLY && !(flags&HASWIDTH) && max > REG_INFTY/3 && ckWARN(WARN_REGEXP)) {
5193 "%.*s matches null string many times",
5194 (int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
5198 if (*RExC_parse == '?') {
5199 nextchar(pRExC_state);
5200 reginsert(pRExC_state, MINMOD, ret, depth+1);
5201 REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
5203 if (ISMULT2(RExC_parse)) {
5205 vFAIL("Nested quantifiers");
5212 /* reg_namedseq(pRExC_state,UVp)
5214 This is expected to be called by a parser routine that has
5215 recognized'\N' and needs to handle the rest. RExC_parse is
5216 expected to point at the first char following the N at the time
5219 If valuep is non-null then it is assumed that we are parsing inside
5220 of a charclass definition and the first codepoint in the resolved
5221 string is returned via *valuep and the routine will return NULL.
5222 In this mode if a multichar string is returned from the charnames
5223 handler a warning will be issued, and only the first char in the
5224 sequence will be examined. If the string returned is zero length
5225 then the value of *valuep is undefined and NON-NULL will
5226 be returned to indicate failure. (This will NOT be a valid pointer
5229 If value is null then it is assumed that we are parsing normal text
5230 and inserts a new EXACT node into the program containing the resolved
5231 string and returns a pointer to the new node. If the string is
5232 zerolength a NOTHING node is emitted.
5234 On success RExC_parse is set to the char following the endbrace.
5235 Parsing failures will generate a fatal errorvia vFAIL(...)
5237 NOTE: We cache all results from the charnames handler locally in
5238 the RExC_charnames hash (created on first use) to prevent a charnames
5239 handler from playing silly-buggers and returning a short string and
5240 then a long string for a given pattern. Since the regexp program
5241 size is calculated during an initial parse this would result
5242 in a buffer overrun so we cache to prevent the charname result from
5243 changing during the course of the parse.
5247 S_reg_namedseq(pTHX_ RExC_state_t *pRExC_state, UV *valuep)
5249 char * name; /* start of the content of the name */
5250 char * endbrace; /* endbrace following the name */
5253 STRLEN len; /* this has various purposes throughout the code */
5254 bool cached = 0; /* if this is true then we shouldn't refcount dev sv_str */
5255 regnode *ret = NULL;
5257 if (*RExC_parse != '{') {
5258 vFAIL("Missing braces on \\N{}");
5260 name = RExC_parse+1;
5261 endbrace = strchr(RExC_parse, '}');
5264 vFAIL("Missing right brace on \\N{}");
5266 RExC_parse = endbrace + 1;
5269 /* RExC_parse points at the beginning brace,
5270 endbrace points at the last */
5271 if ( name[0]=='U' && name[1]=='+' ) {
5272 /* its a "unicode hex" notation {U+89AB} */
5273 I32 fl = PERL_SCAN_ALLOW_UNDERSCORES
5274 | PERL_SCAN_DISALLOW_PREFIX
5275 | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
5277 len = (STRLEN)(endbrace - name - 2);
5278 cp = grok_hex(name + 2, &len, &fl, NULL);
5279 if ( len != (STRLEN)(endbrace - name - 2) ) {
5288 sv_str= Perl_newSVpvf_nocontext("%c",(int)cp);
5290 /* fetch the charnames handler for this scope */
5291 HV * const table = GvHV(PL_hintgv);
5293 hv_fetchs(table, "charnames", FALSE) :
5295 SV *cv= cvp ? *cvp : NULL;
5298 /* create an SV with the name as argument */
5299 sv_name = newSVpvn(name, endbrace - name);
5301 if (!table || !(PL_hints & HINT_LOCALIZE_HH)) {
5302 vFAIL2("Constant(\\N{%s}) unknown: "
5303 "(possibly a missing \"use charnames ...\")",
5306 if (!cvp || !SvOK(*cvp)) { /* when $^H{charnames} = undef; */
5307 vFAIL2("Constant(\\N{%s}): "
5308 "$^H{charnames} is not defined",SvPVX(sv_name));
5313 if (!RExC_charnames) {
5314 /* make sure our cache is allocated */
5315 RExC_charnames = newHV();
5316 sv_2mortal((SV*)RExC_charnames);
5318 /* see if we have looked this one up before */
5319 he_str = hv_fetch_ent( RExC_charnames, sv_name, 0, 0 );
5321 sv_str = HeVAL(he_str);
5334 count= call_sv(cv, G_SCALAR);
5336 if (count == 1) { /* XXXX is this right? dmq */
5338 SvREFCNT_inc_simple_void(sv_str);
5346 if ( !sv_str || !SvOK(sv_str) ) {
5347 vFAIL2("Constant(\\N{%s}): Call to &{$^H{charnames}} "
5348 "did not return a defined value",SvPVX(sv_name));
5350 if (hv_store_ent( RExC_charnames, sv_name, sv_str, 0))
5355 char *p = SvPV(sv_str, len);
5358 if ( SvUTF8(sv_str) ) {
5359 *valuep = utf8_to_uvchr((U8*)p, &numlen);
5363 We have to turn on utf8 for high bit chars otherwise
5364 we get failures with
5366 "ss" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
5367 "SS" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
5369 This is different from what \x{} would do with the same
5370 codepoint, where the condition is > 0xFF.
5377 /* warn if we havent used the whole string? */
5379 if (numlen<len && SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5381 "Ignoring excess chars from \\N{%s} in character class",
5385 } else if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5387 "Ignoring zero length \\N{%s} in character class",
5392 SvREFCNT_dec(sv_name);
5394 SvREFCNT_dec(sv_str);
5395 return len ? NULL : (regnode *)&len;
5396 } else if(SvCUR(sv_str)) {
5401 char * parse_start = name-3; /* needed for the offsets */
5402 GET_RE_DEBUG_FLAGS_DECL; /* needed for the offsets */
5404 ret = reg_node(pRExC_state,
5405 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
5408 if ( RExC_utf8 && !SvUTF8(sv_str) ) {
5409 sv_utf8_upgrade(sv_str);
5410 } else if ( !RExC_utf8 && SvUTF8(sv_str) ) {
5414 p = SvPV(sv_str, len);
5416 /* len is the length written, charlen is the size the char read */
5417 for ( len = 0; p < pend; p += charlen ) {
5419 UV uvc = utf8_to_uvchr((U8*)p, &charlen);
5421 STRLEN foldlen,numlen;
5422 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
5423 uvc = toFOLD_uni(uvc, tmpbuf, &foldlen);
5424 /* Emit all the Unicode characters. */
5426 for (foldbuf = tmpbuf;
5430 uvc = utf8_to_uvchr(foldbuf, &numlen);
5432 const STRLEN unilen = reguni(pRExC_state, uvc, s);
5435 /* In EBCDIC the numlen
5436 * and unilen can differ. */
5438 if (numlen >= foldlen)
5442 break; /* "Can't happen." */
5445 const STRLEN unilen = reguni(pRExC_state, uvc, s);
5457 RExC_size += STR_SZ(len);
5460 RExC_emit += STR_SZ(len);
5462 Set_Node_Cur_Length(ret); /* MJD */
5464 nextchar(pRExC_state);
5466 ret = reg_node(pRExC_state,NOTHING);
5469 SvREFCNT_dec(sv_str);
5472 SvREFCNT_dec(sv_name);
5481 - regatom - the lowest level
5483 * Optimization: gobbles an entire sequence of ordinary characters so that
5484 * it can turn them into a single node, which is smaller to store and
5485 * faster to run. Backslashed characters are exceptions, each becoming a
5486 * separate node; the code is simpler that way and it's not worth fixing.
5488 * [Yes, it is worth fixing, some scripts can run twice the speed.]
5489 * [It looks like its ok, as in S_study_chunk we merge adjacent EXACT nodes]
5492 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
5495 register regnode *ret = NULL;
5497 char *parse_start = RExC_parse;
5498 GET_RE_DEBUG_FLAGS_DECL;
5499 DEBUG_PARSE("atom");
5500 *flagp = WORST; /* Tentatively. */
5503 switch (*RExC_parse) {
5505 RExC_seen_zerolen++;
5506 nextchar(pRExC_state);
5507 if (RExC_flags & PMf_MULTILINE)
5508 ret = reg_node(pRExC_state, MBOL);
5509 else if (RExC_flags & PMf_SINGLELINE)
5510 ret = reg_node(pRExC_state, SBOL);
5512 ret = reg_node(pRExC_state, BOL);
5513 Set_Node_Length(ret, 1); /* MJD */
5516 nextchar(pRExC_state);
5518 RExC_seen_zerolen++;
5519 if (RExC_flags & PMf_MULTILINE)
5520 ret = reg_node(pRExC_state, MEOL);
5521 else if (RExC_flags & PMf_SINGLELINE)
5522 ret = reg_node(pRExC_state, SEOL);
5524 ret = reg_node(pRExC_state, EOL);
5525 Set_Node_Length(ret, 1); /* MJD */
5528 nextchar(pRExC_state);
5529 if (RExC_flags & PMf_SINGLELINE)
5530 ret = reg_node(pRExC_state, SANY);
5532 ret = reg_node(pRExC_state, REG_ANY);
5533 *flagp |= HASWIDTH|SIMPLE;
5535 Set_Node_Length(ret, 1); /* MJD */
5539 char * const oregcomp_parse = ++RExC_parse;
5540 ret = regclass(pRExC_state,depth+1);
5541 if (*RExC_parse != ']') {
5542 RExC_parse = oregcomp_parse;
5543 vFAIL("Unmatched [");
5545 nextchar(pRExC_state);
5546 *flagp |= HASWIDTH|SIMPLE;
5547 Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
5551 nextchar(pRExC_state);
5552 ret = reg(pRExC_state, 1, &flags,depth+1);
5554 if (flags & TRYAGAIN) {
5555 if (RExC_parse == RExC_end) {
5556 /* Make parent create an empty node if needed. */
5564 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE);
5568 if (flags & TRYAGAIN) {
5572 vFAIL("Internal urp");
5573 /* Supposed to be caught earlier. */
5576 if (!regcurly(RExC_parse)) {
5585 vFAIL("Quantifier follows nothing");
5588 switch (*++RExC_parse) {
5590 RExC_seen_zerolen++;
5591 ret = reg_node(pRExC_state, SBOL);
5593 nextchar(pRExC_state);
5594 Set_Node_Length(ret, 2); /* MJD */
5597 ret = reg_node(pRExC_state, GPOS);
5598 RExC_seen |= REG_SEEN_GPOS;
5600 nextchar(pRExC_state);
5601 Set_Node_Length(ret, 2); /* MJD */
5604 ret = reg_node(pRExC_state, SEOL);
5606 RExC_seen_zerolen++; /* Do not optimize RE away */
5607 nextchar(pRExC_state);
5610 ret = reg_node(pRExC_state, EOS);
5612 RExC_seen_zerolen++; /* Do not optimize RE away */
5613 nextchar(pRExC_state);
5614 Set_Node_Length(ret, 2); /* MJD */
5617 ret = reg_node(pRExC_state, CANY);
5618 RExC_seen |= REG_SEEN_CANY;
5619 *flagp |= HASWIDTH|SIMPLE;
5620 nextchar(pRExC_state);
5621 Set_Node_Length(ret, 2); /* MJD */
5624 ret = reg_node(pRExC_state, CLUMP);
5626 nextchar(pRExC_state);
5627 Set_Node_Length(ret, 2); /* MJD */
5630 ret = reg_node(pRExC_state, (U8)(LOC ? ALNUML : ALNUM));
5631 *flagp |= HASWIDTH|SIMPLE;
5632 nextchar(pRExC_state);
5633 Set_Node_Length(ret, 2); /* MJD */
5636 ret = reg_node(pRExC_state, (U8)(LOC ? NALNUML : NALNUM));
5637 *flagp |= HASWIDTH|SIMPLE;
5638 nextchar(pRExC_state);
5639 Set_Node_Length(ret, 2); /* MJD */
5642 RExC_seen_zerolen++;
5643 RExC_seen |= REG_SEEN_LOOKBEHIND;
5644 ret = reg_node(pRExC_state, (U8)(LOC ? BOUNDL : BOUND));
5646 nextchar(pRExC_state);
5647 Set_Node_Length(ret, 2); /* MJD */
5650 RExC_seen_zerolen++;
5651 RExC_seen |= REG_SEEN_LOOKBEHIND;
5652 ret = reg_node(pRExC_state, (U8)(LOC ? NBOUNDL : NBOUND));
5654 nextchar(pRExC_state);
5655 Set_Node_Length(ret, 2); /* MJD */
5658 ret = reg_node(pRExC_state, (U8)(LOC ? SPACEL : SPACE));
5659 *flagp |= HASWIDTH|SIMPLE;
5660 nextchar(pRExC_state);
5661 Set_Node_Length(ret, 2); /* MJD */
5664 ret = reg_node(pRExC_state, (U8)(LOC ? NSPACEL : NSPACE));
5665 *flagp |= HASWIDTH|SIMPLE;
5666 nextchar(pRExC_state);
5667 Set_Node_Length(ret, 2); /* MJD */
5670 ret = reg_node(pRExC_state, DIGIT);
5671 *flagp |= HASWIDTH|SIMPLE;
5672 nextchar(pRExC_state);
5673 Set_Node_Length(ret, 2); /* MJD */
5676 ret = reg_node(pRExC_state, NDIGIT);
5677 *flagp |= HASWIDTH|SIMPLE;
5678 nextchar(pRExC_state);
5679 Set_Node_Length(ret, 2); /* MJD */
5684 char* const oldregxend = RExC_end;
5685 char* parse_start = RExC_parse - 2;
5687 if (RExC_parse[1] == '{') {
5688 /* a lovely hack--pretend we saw [\pX] instead */
5689 RExC_end = strchr(RExC_parse, '}');
5691 const U8 c = (U8)*RExC_parse;
5693 RExC_end = oldregxend;
5694 vFAIL2("Missing right brace on \\%c{}", c);
5699 RExC_end = RExC_parse + 2;
5700 if (RExC_end > oldregxend)
5701 RExC_end = oldregxend;
5705 ret = regclass(pRExC_state,depth+1);
5707 RExC_end = oldregxend;
5710 Set_Node_Offset(ret, parse_start + 2);
5711 Set_Node_Cur_Length(ret);
5712 nextchar(pRExC_state);
5713 *flagp |= HASWIDTH|SIMPLE;
5717 /* Handle \N{NAME} here and not below because it can be
5718 multicharacter. join_exact() will join them up later on.
5719 Also this makes sure that things like /\N{BLAH}+/ and
5720 \N{BLAH} being multi char Just Happen. dmq*/
5722 ret= reg_namedseq(pRExC_state, NULL);
5726 char ch= RExC_parse[1];
5727 if (ch != '<' && ch != '\'') {
5729 vWARN( RExC_parse + 1,
5730 "Possible broken named back reference treated as literal k");
5734 char* name_start = (RExC_parse += 2);
5736 SV *svname = reg_scan_name(pRExC_state,!SIZE_ONLY);
5737 ch= (ch == '<') ? '>' : '\'';
5739 if (RExC_parse == name_start || *RExC_parse != ch)
5740 vFAIL2("Sequence \\k%c... not terminated",
5741 (ch == '>' ? '<' : ch));
5744 ret = reganode(pRExC_state,
5745 (U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
5755 "panic: reg_scan_name returned NULL");
5756 if (RExC_paren_names)
5757 he_str = hv_fetch_ent( RExC_paren_names, svname, 0, 0 );
5759 sv_dat = HeVAL(he_str);
5761 vFAIL("Reference to nonexistent group");
5763 num = add_data( pRExC_state, 1, "S" );
5765 RExC_rx->data->data[num]=(void*)sv_dat;
5766 SvREFCNT_inc(sv_dat);
5768 /* override incorrect value set in reganode MJD */
5769 Set_Node_Offset(ret, parse_start+1);
5770 Set_Node_Cur_Length(ret); /* MJD */
5771 nextchar(pRExC_state);
5786 case '1': case '2': case '3': case '4':
5787 case '5': case '6': case '7': case '8': case '9':
5789 const I32 num = atoi(RExC_parse);
5791 if (num > 9 && num >= RExC_npar)
5794 char * const parse_start = RExC_parse - 1; /* MJD */
5795 while (isDIGIT(*RExC_parse))
5798 if (!SIZE_ONLY && num > (I32)RExC_rx->nparens)
5799 vFAIL("Reference to nonexistent group");
5801 ret = reganode(pRExC_state,
5802 (U8)(FOLD ? (LOC ? REFFL : REFF) : REF),
5806 /* override incorrect value set in reganode MJD */
5807 Set_Node_Offset(ret, parse_start+1);
5808 Set_Node_Cur_Length(ret); /* MJD */
5810 nextchar(pRExC_state);
5815 if (RExC_parse >= RExC_end)
5816 FAIL("Trailing \\");
5819 /* Do not generate "unrecognized" warnings here, we fall
5820 back into the quick-grab loop below */
5827 if (RExC_flags & PMf_EXTENDED) {
5828 while (RExC_parse < RExC_end && *RExC_parse != '\n')
5830 if (RExC_parse < RExC_end)
5836 register STRLEN len;
5841 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
5843 parse_start = RExC_parse - 1;
5849 ret = reg_node(pRExC_state,
5850 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
5852 for (len = 0, p = RExC_parse - 1;
5853 len < 127 && p < RExC_end;
5856 char * const oldp = p;
5858 if (RExC_flags & PMf_EXTENDED)
5859 p = regwhite(p, RExC_end);
5907 ender = ASCII_TO_NATIVE('\033');
5911 ender = ASCII_TO_NATIVE('\007');
5916 char* const e = strchr(p, '}');
5920 vFAIL("Missing right brace on \\x{}");
5923 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
5924 | PERL_SCAN_DISALLOW_PREFIX;
5925 STRLEN numlen = e - p - 1;
5926 ender = grok_hex(p + 1, &numlen, &flags, NULL);
5933 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
5935 ender = grok_hex(p, &numlen, &flags, NULL);
5941 ender = UCHARAT(p++);
5942 ender = toCTRL(ender);
5944 case '0': case '1': case '2': case '3':case '4':
5945 case '5': case '6': case '7': case '8':case '9':
5947 (isDIGIT(p[1]) && atoi(p) >= RExC_npar) ) {
5950 ender = grok_oct(p, &numlen, &flags, NULL);
5960 FAIL("Trailing \\");
5963 if (!SIZE_ONLY&& isALPHA(*p) && ckWARN(WARN_REGEXP))
5964 vWARN2(p + 1, "Unrecognized escape \\%c passed through", UCHARAT(p));
5965 goto normal_default;
5970 if (UTF8_IS_START(*p) && UTF) {
5972 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
5973 &numlen, UTF8_ALLOW_DEFAULT);
5980 if (RExC_flags & PMf_EXTENDED)
5981 p = regwhite(p, RExC_end);
5983 /* Prime the casefolded buffer. */
5984 ender = toFOLD_uni(ender, tmpbuf, &foldlen);
5986 if (ISMULT2(p)) { /* Back off on ?+*. */
5991 /* Emit all the Unicode characters. */
5993 for (foldbuf = tmpbuf;
5995 foldlen -= numlen) {
5996 ender = utf8_to_uvchr(foldbuf, &numlen);
5998 const STRLEN unilen = reguni(pRExC_state, ender, s);
6001 /* In EBCDIC the numlen
6002 * and unilen can differ. */
6004 if (numlen >= foldlen)
6008 break; /* "Can't happen." */
6012 const STRLEN unilen = reguni(pRExC_state, ender, s);
6021 REGC((char)ender, s++);
6027 /* Emit all the Unicode characters. */
6029 for (foldbuf = tmpbuf;
6031 foldlen -= numlen) {
6032 ender = utf8_to_uvchr(foldbuf, &numlen);
6034 const STRLEN unilen = reguni(pRExC_state, ender, s);
6037 /* In EBCDIC the numlen
6038 * and unilen can differ. */
6040 if (numlen >= foldlen)
6048 const STRLEN unilen = reguni(pRExC_state, ender, s);
6057 REGC((char)ender, s++);
6061 Set_Node_Cur_Length(ret); /* MJD */
6062 nextchar(pRExC_state);
6064 /* len is STRLEN which is unsigned, need to copy to signed */
6067 vFAIL("Internal disaster");
6071 if (len == 1 && UNI_IS_INVARIANT(ender))
6075 RExC_size += STR_SZ(len);
6078 RExC_emit += STR_SZ(len);
6084 /* If the encoding pragma is in effect recode the text of
6085 * any EXACT-kind nodes. */
6086 if (ret && PL_encoding && PL_regkind[OP(ret)] == EXACT) {
6087 const STRLEN oldlen = STR_LEN(ret);
6088 SV * const sv = sv_2mortal(newSVpvn(STRING(ret), oldlen));
6092 if (sv_utf8_downgrade(sv, TRUE)) {
6093 const char * const s = sv_recode_to_utf8(sv, PL_encoding);
6094 const STRLEN newlen = SvCUR(sv);
6099 GET_RE_DEBUG_FLAGS_DECL;
6100 DEBUG_COMPILE_r(PerlIO_printf(Perl_debug_log, "recode %*s to %*s\n",
6101 (int)oldlen, STRING(ret),
6103 Copy(s, STRING(ret), newlen, char);
6104 STR_LEN(ret) += newlen - oldlen;
6105 RExC_emit += STR_SZ(newlen) - STR_SZ(oldlen);
6107 RExC_size += STR_SZ(newlen) - STR_SZ(oldlen);
6115 S_regwhite(char *p, const char *e)
6120 else if (*p == '#') {
6123 } while (p < e && *p != '\n');
6131 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
6132 Character classes ([:foo:]) can also be negated ([:^foo:]).
6133 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
6134 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
6135 but trigger failures because they are currently unimplemented. */
6137 #define POSIXCC_DONE(c) ((c) == ':')
6138 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
6139 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
6142 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
6145 I32 namedclass = OOB_NAMEDCLASS;
6147 if (value == '[' && RExC_parse + 1 < RExC_end &&
6148 /* I smell either [: or [= or [. -- POSIX has been here, right? */
6149 POSIXCC(UCHARAT(RExC_parse))) {
6150 const char c = UCHARAT(RExC_parse);
6151 char* const s = RExC_parse++;
6153 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
6155 if (RExC_parse == RExC_end)
6156 /* Grandfather lone [:, [=, [. */
6159 const char* const t = RExC_parse++; /* skip over the c */
6162 if (UCHARAT(RExC_parse) == ']') {
6163 const char *posixcc = s + 1;
6164 RExC_parse++; /* skip over the ending ] */
6167 const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
6168 const I32 skip = t - posixcc;
6170 /* Initially switch on the length of the name. */
6173 if (memEQ(posixcc, "word", 4)) /* this is not POSIX, this is the Perl \w */
6174 namedclass = complement ? ANYOF_NALNUM : ANYOF_ALNUM;
6177 /* Names all of length 5. */
6178 /* alnum alpha ascii blank cntrl digit graph lower
6179 print punct space upper */
6180 /* Offset 4 gives the best switch position. */
6181 switch (posixcc[4]) {
6183 if (memEQ(posixcc, "alph", 4)) /* alpha */
6184 namedclass = complement ? ANYOF_NALPHA : ANYOF_ALPHA;
6187 if (memEQ(posixcc, "spac", 4)) /* space */
6188 namedclass = complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
6191 if (memEQ(posixcc, "grap", 4)) /* graph */
6192 namedclass = complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
6195 if (memEQ(posixcc, "asci", 4)) /* ascii */
6196 namedclass = complement ? ANYOF_NASCII : ANYOF_ASCII;
6199 if (memEQ(posixcc, "blan", 4)) /* blank */
6200 namedclass = complement ? ANYOF_NBLANK : ANYOF_BLANK;
6203 if (memEQ(posixcc, "cntr", 4)) /* cntrl */
6204 namedclass = complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
6207 if (memEQ(posixcc, "alnu", 4)) /* alnum */
6208 namedclass = complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
6211 if (memEQ(posixcc, "lowe", 4)) /* lower */
6212 namedclass = complement ? ANYOF_NLOWER : ANYOF_LOWER;
6213 else if (memEQ(posixcc, "uppe", 4)) /* upper */
6214 namedclass = complement ? ANYOF_NUPPER : ANYOF_UPPER;
6217 if (memEQ(posixcc, "digi", 4)) /* digit */
6218 namedclass = complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
6219 else if (memEQ(posixcc, "prin", 4)) /* print */
6220 namedclass = complement ? ANYOF_NPRINT : ANYOF_PRINT;
6221 else if (memEQ(posixcc, "punc", 4)) /* punct */
6222 namedclass = complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
6227 if (memEQ(posixcc, "xdigit", 6))
6228 namedclass = complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
6232 if (namedclass == OOB_NAMEDCLASS)
6233 Simple_vFAIL3("POSIX class [:%.*s:] unknown",
6235 assert (posixcc[skip] == ':');
6236 assert (posixcc[skip+1] == ']');
6237 } else if (!SIZE_ONLY) {
6238 /* [[=foo=]] and [[.foo.]] are still future. */
6240 /* adjust RExC_parse so the warning shows after
6242 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
6244 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
6247 /* Maternal grandfather:
6248 * "[:" ending in ":" but not in ":]" */
6258 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
6261 if (POSIXCC(UCHARAT(RExC_parse))) {
6262 const char *s = RExC_parse;
6263 const char c = *s++;
6267 if (*s && c == *s && s[1] == ']') {
6268 if (ckWARN(WARN_REGEXP))
6270 "POSIX syntax [%c %c] belongs inside character classes",
6273 /* [[=foo=]] and [[.foo.]] are still future. */
6274 if (POSIXCC_NOTYET(c)) {
6275 /* adjust RExC_parse so the error shows after
6277 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
6279 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
6287 parse a class specification and produce either an ANYOF node that
6288 matches the pattern. If the pattern matches a single char only and
6289 that char is < 256 then we produce an EXACT node instead.
6292 S_regclass(pTHX_ RExC_state_t *pRExC_state, U32 depth)
6295 register UV value = 0;
6296 register UV nextvalue;
6297 register IV prevvalue = OOB_UNICODE;
6298 register IV range = 0;
6299 register regnode *ret;
6302 char *rangebegin = NULL;
6303 bool need_class = 0;
6306 bool optimize_invert = TRUE;
6307 AV* unicode_alternate = NULL;
6309 UV literal_endpoint = 0;
6311 UV stored = 0; /* number of chars stored in the class */
6313 regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
6314 case we need to change the emitted regop to an EXACT. */
6315 const char * orig_parse = RExC_parse;
6316 GET_RE_DEBUG_FLAGS_DECL;
6318 PERL_UNUSED_ARG(depth);
6321 DEBUG_PARSE("clas");
6323 /* Assume we are going to generate an ANYOF node. */
6324 ret = reganode(pRExC_state, ANYOF, 0);
6327 ANYOF_FLAGS(ret) = 0;
6329 if (UCHARAT(RExC_parse) == '^') { /* Complement of range. */
6333 ANYOF_FLAGS(ret) |= ANYOF_INVERT;
6337 RExC_size += ANYOF_SKIP;
6338 listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
6341 RExC_emit += ANYOF_SKIP;
6343 ANYOF_FLAGS(ret) |= ANYOF_FOLD;
6345 ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
6346 ANYOF_BITMAP_ZERO(ret);
6347 listsv = newSVpvs("# comment\n");
6350 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
6352 if (!SIZE_ONLY && POSIXCC(nextvalue))
6353 checkposixcc(pRExC_state);
6355 /* allow 1st char to be ] (allowing it to be - is dealt with later) */
6356 if (UCHARAT(RExC_parse) == ']')
6360 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
6364 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
6367 rangebegin = RExC_parse;
6369 value = utf8n_to_uvchr((U8*)RExC_parse,
6370 RExC_end - RExC_parse,
6371 &numlen, UTF8_ALLOW_DEFAULT);
6372 RExC_parse += numlen;
6375 value = UCHARAT(RExC_parse++);
6377 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
6378 if (value == '[' && POSIXCC(nextvalue))
6379 namedclass = regpposixcc(pRExC_state, value);
6380 else if (value == '\\') {
6382 value = utf8n_to_uvchr((U8*)RExC_parse,
6383 RExC_end - RExC_parse,
6384 &numlen, UTF8_ALLOW_DEFAULT);
6385 RExC_parse += numlen;
6388 value = UCHARAT(RExC_parse++);
6389 /* Some compilers cannot handle switching on 64-bit integer
6390 * values, therefore value cannot be an UV. Yes, this will
6391 * be a problem later if we want switch on Unicode.
6392 * A similar issue a little bit later when switching on
6393 * namedclass. --jhi */
6394 switch ((I32)value) {
6395 case 'w': namedclass = ANYOF_ALNUM; break;
6396 case 'W': namedclass = ANYOF_NALNUM; break;
6397 case 's': namedclass = ANYOF_SPACE; break;
6398 case 'S': namedclass = ANYOF_NSPACE; break;
6399 case 'd': namedclass = ANYOF_DIGIT; break;
6400 case 'D': namedclass = ANYOF_NDIGIT; break;
6401 case 'N': /* Handle \N{NAME} in class */
6403 /* We only pay attention to the first char of
6404 multichar strings being returned. I kinda wonder
6405 if this makes sense as it does change the behaviour
6406 from earlier versions, OTOH that behaviour was broken
6408 UV v; /* value is register so we cant & it /grrr */
6409 if (reg_namedseq(pRExC_state, &v)) {
6419 if (RExC_parse >= RExC_end)
6420 vFAIL2("Empty \\%c{}", (U8)value);
6421 if (*RExC_parse == '{') {
6422 const U8 c = (U8)value;
6423 e = strchr(RExC_parse++, '}');
6425 vFAIL2("Missing right brace on \\%c{}", c);
6426 while (isSPACE(UCHARAT(RExC_parse)))
6428 if (e == RExC_parse)
6429 vFAIL2("Empty \\%c{}", c);
6431 while (isSPACE(UCHARAT(RExC_parse + n - 1)))
6439 if (UCHARAT(RExC_parse) == '^') {
6442 value = value == 'p' ? 'P' : 'p'; /* toggle */
6443 while (isSPACE(UCHARAT(RExC_parse))) {
6448 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%.*s\n",
6449 (value=='p' ? '+' : '!'), (int)n, RExC_parse);
6452 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
6453 namedclass = ANYOF_MAX; /* no official name, but it's named */
6456 case 'n': value = '\n'; break;
6457 case 'r': value = '\r'; break;
6458 case 't': value = '\t'; break;
6459 case 'f': value = '\f'; break;
6460 case 'b': value = '\b'; break;
6461 case 'e': value = ASCII_TO_NATIVE('\033');break;
6462 case 'a': value = ASCII_TO_NATIVE('\007');break;
6464 if (*RExC_parse == '{') {
6465 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
6466 | PERL_SCAN_DISALLOW_PREFIX;
6467 char * const e = strchr(RExC_parse++, '}');
6469 vFAIL("Missing right brace on \\x{}");
6471 numlen = e - RExC_parse;
6472 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
6476 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
6478 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
6479 RExC_parse += numlen;
6483 value = UCHARAT(RExC_parse++);
6484 value = toCTRL(value);
6486 case '0': case '1': case '2': case '3': case '4':
6487 case '5': case '6': case '7': case '8': case '9':
6491 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
6492 RExC_parse += numlen;
6496 if (!SIZE_ONLY && isALPHA(value) && ckWARN(WARN_REGEXP))
6498 "Unrecognized escape \\%c in character class passed through",
6502 } /* end of \blah */
6508 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
6510 if (!SIZE_ONLY && !need_class)
6511 ANYOF_CLASS_ZERO(ret);
6515 /* a bad range like a-\d, a-[:digit:] ? */
6518 if (ckWARN(WARN_REGEXP)) {
6520 RExC_parse >= rangebegin ?
6521 RExC_parse - rangebegin : 0;
6523 "False [] range \"%*.*s\"",
6526 if (prevvalue < 256) {
6527 ANYOF_BITMAP_SET(ret, prevvalue);
6528 ANYOF_BITMAP_SET(ret, '-');
6531 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
6532 Perl_sv_catpvf(aTHX_ listsv,
6533 "%04"UVxf"\n%04"UVxf"\n", (UV)prevvalue, (UV) '-');
6537 range = 0; /* this was not a true range */
6541 const char *what = NULL;
6544 if (namedclass > OOB_NAMEDCLASS)
6545 optimize_invert = FALSE;
6546 /* Possible truncation here but in some 64-bit environments
6547 * the compiler gets heartburn about switch on 64-bit values.
6548 * A similar issue a little earlier when switching on value.
6550 switch ((I32)namedclass) {
6553 ANYOF_CLASS_SET(ret, ANYOF_ALNUM);
6555 for (value = 0; value < 256; value++)
6557 ANYOF_BITMAP_SET(ret, value);
6564 ANYOF_CLASS_SET(ret, ANYOF_NALNUM);
6566 for (value = 0; value < 256; value++)
6567 if (!isALNUM(value))
6568 ANYOF_BITMAP_SET(ret, value);
6575 ANYOF_CLASS_SET(ret, ANYOF_ALNUMC);
6577 for (value = 0; value < 256; value++)
6578 if (isALNUMC(value))
6579 ANYOF_BITMAP_SET(ret, value);
6586 ANYOF_CLASS_SET(ret, ANYOF_NALNUMC);
6588 for (value = 0; value < 256; value++)
6589 if (!isALNUMC(value))
6590 ANYOF_BITMAP_SET(ret, value);
6597 ANYOF_CLASS_SET(ret, ANYOF_ALPHA);
6599 for (value = 0; value < 256; value++)
6601 ANYOF_BITMAP_SET(ret, value);
6608 ANYOF_CLASS_SET(ret, ANYOF_NALPHA);
6610 for (value = 0; value < 256; value++)
6611 if (!isALPHA(value))
6612 ANYOF_BITMAP_SET(ret, value);
6619 ANYOF_CLASS_SET(ret, ANYOF_ASCII);
6622 for (value = 0; value < 128; value++)
6623 ANYOF_BITMAP_SET(ret, value);
6625 for (value = 0; value < 256; value++) {
6627 ANYOF_BITMAP_SET(ret, value);
6636 ANYOF_CLASS_SET(ret, ANYOF_NASCII);
6639 for (value = 128; value < 256; value++)
6640 ANYOF_BITMAP_SET(ret, value);
6642 for (value = 0; value < 256; value++) {
6643 if (!isASCII(value))
6644 ANYOF_BITMAP_SET(ret, value);
6653 ANYOF_CLASS_SET(ret, ANYOF_BLANK);
6655 for (value = 0; value < 256; value++)
6657 ANYOF_BITMAP_SET(ret, value);
6664 ANYOF_CLASS_SET(ret, ANYOF_NBLANK);
6666 for (value = 0; value < 256; value++)
6667 if (!isBLANK(value))
6668 ANYOF_BITMAP_SET(ret, value);
6675 ANYOF_CLASS_SET(ret, ANYOF_CNTRL);
6677 for (value = 0; value < 256; value++)
6679 ANYOF_BITMAP_SET(ret, value);
6686 ANYOF_CLASS_SET(ret, ANYOF_NCNTRL);
6688 for (value = 0; value < 256; value++)
6689 if (!isCNTRL(value))
6690 ANYOF_BITMAP_SET(ret, value);
6697 ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
6699 /* consecutive digits assumed */
6700 for (value = '0'; value <= '9'; value++)
6701 ANYOF_BITMAP_SET(ret, value);
6708 ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
6710 /* consecutive digits assumed */
6711 for (value = 0; value < '0'; value++)
6712 ANYOF_BITMAP_SET(ret, value);
6713 for (value = '9' + 1; value < 256; value++)
6714 ANYOF_BITMAP_SET(ret, value);
6721 ANYOF_CLASS_SET(ret, ANYOF_GRAPH);
6723 for (value = 0; value < 256; value++)
6725 ANYOF_BITMAP_SET(ret, value);
6732 ANYOF_CLASS_SET(ret, ANYOF_NGRAPH);
6734 for (value = 0; value < 256; value++)
6735 if (!isGRAPH(value))
6736 ANYOF_BITMAP_SET(ret, value);
6743 ANYOF_CLASS_SET(ret, ANYOF_LOWER);
6745 for (value = 0; value < 256; value++)
6747 ANYOF_BITMAP_SET(ret, value);
6754 ANYOF_CLASS_SET(ret, ANYOF_NLOWER);
6756 for (value = 0; value < 256; value++)
6757 if (!isLOWER(value))
6758 ANYOF_BITMAP_SET(ret, value);
6765 ANYOF_CLASS_SET(ret, ANYOF_PRINT);
6767 for (value = 0; value < 256; value++)
6769 ANYOF_BITMAP_SET(ret, value);
6776 ANYOF_CLASS_SET(ret, ANYOF_NPRINT);
6778 for (value = 0; value < 256; value++)
6779 if (!isPRINT(value))
6780 ANYOF_BITMAP_SET(ret, value);
6787 ANYOF_CLASS_SET(ret, ANYOF_PSXSPC);
6789 for (value = 0; value < 256; value++)
6790 if (isPSXSPC(value))
6791 ANYOF_BITMAP_SET(ret, value);
6798 ANYOF_CLASS_SET(ret, ANYOF_NPSXSPC);
6800 for (value = 0; value < 256; value++)
6801 if (!isPSXSPC(value))
6802 ANYOF_BITMAP_SET(ret, value);
6809 ANYOF_CLASS_SET(ret, ANYOF_PUNCT);
6811 for (value = 0; value < 256; value++)
6813 ANYOF_BITMAP_SET(ret, value);
6820 ANYOF_CLASS_SET(ret, ANYOF_NPUNCT);
6822 for (value = 0; value < 256; value++)
6823 if (!isPUNCT(value))
6824 ANYOF_BITMAP_SET(ret, value);
6831 ANYOF_CLASS_SET(ret, ANYOF_SPACE);
6833 for (value = 0; value < 256; value++)
6835 ANYOF_BITMAP_SET(ret, value);
6842 ANYOF_CLASS_SET(ret, ANYOF_NSPACE);
6844 for (value = 0; value < 256; value++)
6845 if (!isSPACE(value))
6846 ANYOF_BITMAP_SET(ret, value);
6853 ANYOF_CLASS_SET(ret, ANYOF_UPPER);
6855 for (value = 0; value < 256; value++)
6857 ANYOF_BITMAP_SET(ret, value);
6864 ANYOF_CLASS_SET(ret, ANYOF_NUPPER);
6866 for (value = 0; value < 256; value++)
6867 if (!isUPPER(value))
6868 ANYOF_BITMAP_SET(ret, value);
6875 ANYOF_CLASS_SET(ret, ANYOF_XDIGIT);
6877 for (value = 0; value < 256; value++)
6878 if (isXDIGIT(value))
6879 ANYOF_BITMAP_SET(ret, value);
6886 ANYOF_CLASS_SET(ret, ANYOF_NXDIGIT);
6888 for (value = 0; value < 256; value++)
6889 if (!isXDIGIT(value))
6890 ANYOF_BITMAP_SET(ret, value);
6896 /* this is to handle \p and \P */
6899 vFAIL("Invalid [::] class");
6903 /* Strings such as "+utf8::isWord\n" */
6904 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::Is%s\n", yesno, what);
6907 ANYOF_FLAGS(ret) |= ANYOF_CLASS;
6910 } /* end of namedclass \blah */
6913 if (prevvalue > (IV)value) /* b-a */ {
6914 const int w = RExC_parse - rangebegin;
6915 Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
6916 range = 0; /* not a valid range */
6920 prevvalue = value; /* save the beginning of the range */
6921 if (*RExC_parse == '-' && RExC_parse+1 < RExC_end &&
6922 RExC_parse[1] != ']') {
6925 /* a bad range like \w-, [:word:]- ? */
6926 if (namedclass > OOB_NAMEDCLASS) {
6927 if (ckWARN(WARN_REGEXP)) {
6929 RExC_parse >= rangebegin ?
6930 RExC_parse - rangebegin : 0;
6932 "False [] range \"%*.*s\"",
6936 ANYOF_BITMAP_SET(ret, '-');
6938 range = 1; /* yeah, it's a range! */
6939 continue; /* but do it the next time */
6943 /* now is the next time */
6944 /*stored += (value - prevvalue + 1);*/
6946 if (prevvalue < 256) {
6947 const IV ceilvalue = value < 256 ? value : 255;
6950 /* In EBCDIC [\x89-\x91] should include
6951 * the \x8e but [i-j] should not. */
6952 if (literal_endpoint == 2 &&
6953 ((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
6954 (isUPPER(prevvalue) && isUPPER(ceilvalue))))
6956 if (isLOWER(prevvalue)) {
6957 for (i = prevvalue; i <= ceilvalue; i++)
6959 ANYOF_BITMAP_SET(ret, i);
6961 for (i = prevvalue; i <= ceilvalue; i++)
6963 ANYOF_BITMAP_SET(ret, i);
6968 for (i = prevvalue; i <= ceilvalue; i++) {
6969 if (!ANYOF_BITMAP_TEST(ret,i)) {
6971 ANYOF_BITMAP_SET(ret, i);
6975 if (value > 255 || UTF) {
6976 const UV prevnatvalue = NATIVE_TO_UNI(prevvalue);
6977 const UV natvalue = NATIVE_TO_UNI(value);
6978 stored+=2; /* can't optimize this class */
6979 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
6980 if (prevnatvalue < natvalue) { /* what about > ? */
6981 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
6982 prevnatvalue, natvalue);
6984 else if (prevnatvalue == natvalue) {
6985 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n", natvalue);
6987 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
6989 const UV f = to_uni_fold(natvalue, foldbuf, &foldlen);
6991 #ifdef EBCDIC /* RD t/uni/fold ff and 6b */
6992 if (RExC_precomp[0] == ':' &&
6993 RExC_precomp[1] == '[' &&
6994 (f == 0xDF || f == 0x92)) {
6995 f = NATIVE_TO_UNI(f);
6998 /* If folding and foldable and a single
6999 * character, insert also the folded version
7000 * to the charclass. */
7002 #ifdef EBCDIC /* RD tunifold ligatures s,t fb05, fb06 */
7003 if ((RExC_precomp[0] == ':' &&
7004 RExC_precomp[1] == '[' &&
7006 (value == 0xFB05 || value == 0xFB06))) ?
7007 foldlen == ((STRLEN)UNISKIP(f) - 1) :
7008 foldlen == (STRLEN)UNISKIP(f) )
7010 if (foldlen == (STRLEN)UNISKIP(f))
7012 Perl_sv_catpvf(aTHX_ listsv,
7015 /* Any multicharacter foldings
7016 * require the following transform:
7017 * [ABCDEF] -> (?:[ABCabcDEFd]|pq|rst)
7018 * where E folds into "pq" and F folds
7019 * into "rst", all other characters
7020 * fold to single characters. We save
7021 * away these multicharacter foldings,
7022 * to be later saved as part of the
7023 * additional "s" data. */
7026 if (!unicode_alternate)
7027 unicode_alternate = newAV();
7028 sv = newSVpvn((char*)foldbuf, foldlen);
7030 av_push(unicode_alternate, sv);
7034 /* If folding and the value is one of the Greek
7035 * sigmas insert a few more sigmas to make the
7036 * folding rules of the sigmas to work right.
7037 * Note that not all the possible combinations
7038 * are handled here: some of them are handled
7039 * by the standard folding rules, and some of
7040 * them (literal or EXACTF cases) are handled
7041 * during runtime in regexec.c:S_find_byclass(). */
7042 if (value == UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA) {
7043 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7044 (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA);
7045 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7046 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
7048 else if (value == UNICODE_GREEK_CAPITAL_LETTER_SIGMA)
7049 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7050 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
7055 literal_endpoint = 0;
7059 range = 0; /* this range (if it was one) is done now */
7063 ANYOF_FLAGS(ret) |= ANYOF_LARGE;
7065 RExC_size += ANYOF_CLASS_ADD_SKIP;
7067 RExC_emit += ANYOF_CLASS_ADD_SKIP;
7073 /****** !SIZE_ONLY AFTER HERE *********/
7075 if( stored == 1 && value < 256
7076 && !( ANYOF_FLAGS(ret) & ( ANYOF_FLAGS_ALL ^ ANYOF_FOLD ) )
7078 /* optimize single char class to an EXACT node
7079 but *only* when its not a UTF/high char */
7080 const char * cur_parse= RExC_parse;
7081 RExC_emit = (regnode *)orig_emit;
7082 RExC_parse = (char *)orig_parse;
7083 ret = reg_node(pRExC_state,
7084 (U8)((ANYOF_FLAGS(ret) & ANYOF_FOLD) ? EXACTF : EXACT));
7085 RExC_parse = (char *)cur_parse;
7086 *STRING(ret)= (char)value;
7088 RExC_emit += STR_SZ(1);
7091 /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
7092 if ( /* If the only flag is folding (plus possibly inversion). */
7093 ((ANYOF_FLAGS(ret) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD)
7095 for (value = 0; value < 256; ++value) {
7096 if (ANYOF_BITMAP_TEST(ret, value)) {
7097 UV fold = PL_fold[value];
7100 ANYOF_BITMAP_SET(ret, fold);
7103 ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
7106 /* optimize inverted simple patterns (e.g. [^a-z]) */
7107 if (optimize_invert &&
7108 /* If the only flag is inversion. */
7109 (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
7110 for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
7111 ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
7112 ANYOF_FLAGS(ret) = ANYOF_UNICODE_ALL;
7115 AV * const av = newAV();
7117 /* The 0th element stores the character class description
7118 * in its textual form: used later (regexec.c:Perl_regclass_swash())
7119 * to initialize the appropriate swash (which gets stored in
7120 * the 1st element), and also useful for dumping the regnode.
7121 * The 2nd element stores the multicharacter foldings,
7122 * used later (regexec.c:S_reginclass()). */
7123 av_store(av, 0, listsv);
7124 av_store(av, 1, NULL);
7125 av_store(av, 2, (SV*)unicode_alternate);
7126 rv = newRV_noinc((SV*)av);
7127 n = add_data(pRExC_state, 1, "s");
7128 RExC_rx->data->data[n] = (void*)rv;
7135 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
7137 char* const retval = RExC_parse++;
7140 if (*RExC_parse == '(' && RExC_parse[1] == '?' &&
7141 RExC_parse[2] == '#') {
7142 while (*RExC_parse != ')') {
7143 if (RExC_parse == RExC_end)
7144 FAIL("Sequence (?#... not terminated");
7150 if (RExC_flags & PMf_EXTENDED) {
7151 if (isSPACE(*RExC_parse)) {
7155 else if (*RExC_parse == '#') {
7156 while (RExC_parse < RExC_end)
7157 if (*RExC_parse++ == '\n') break;
7166 - reg_node - emit a node
7168 STATIC regnode * /* Location. */
7169 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
7172 register regnode *ptr;
7173 regnode * const ret = RExC_emit;
7174 GET_RE_DEBUG_FLAGS_DECL;
7177 SIZE_ALIGN(RExC_size);
7181 NODE_ALIGN_FILL(ret);
7183 FILL_ADVANCE_NODE(ptr, op);
7184 if (RExC_offsets) { /* MJD */
7185 MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n",
7186 "reg_node", __LINE__,
7188 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0]
7189 ? "Overwriting end of array!\n" : "OK",
7190 (UV)(RExC_emit - RExC_emit_start),
7191 (UV)(RExC_parse - RExC_start),
7192 (UV)RExC_offsets[0]));
7193 Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
7202 - reganode - emit a node with an argument
7204 STATIC regnode * /* Location. */
7205 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
7208 register regnode *ptr;
7209 regnode * const ret = RExC_emit;
7210 GET_RE_DEBUG_FLAGS_DECL;
7213 SIZE_ALIGN(RExC_size);
7218 assert(2==regarglen[op]+1);
7220 Anything larger than this has to allocate the extra amount.
7221 If we changed this to be:
7223 RExC_size += (1 + regarglen[op]);
7225 then it wouldn't matter. Its not clear what side effect
7226 might come from that so its not done so far.
7232 NODE_ALIGN_FILL(ret);
7234 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
7235 if (RExC_offsets) { /* MJD */
7236 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
7240 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ?
7241 "Overwriting end of array!\n" : "OK",
7242 (UV)(RExC_emit - RExC_emit_start),
7243 (UV)(RExC_parse - RExC_start),
7244 (UV)RExC_offsets[0]));
7245 Set_Cur_Node_Offset;
7254 - reguni - emit (if appropriate) a Unicode character
7257 S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
7260 return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
7264 - reginsert - insert an operator in front of already-emitted operand
7266 * Means relocating the operand.
7269 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
7272 register regnode *src;
7273 register regnode *dst;
7274 register regnode *place;
7275 const int offset = regarglen[(U8)op];
7276 const int size = NODE_STEP_REGNODE + offset;
7277 GET_RE_DEBUG_FLAGS_DECL;
7278 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
7279 DEBUG_PARSE_FMT("inst"," - %s",reg_name[op]);
7290 for ( paren=0 ; paren < RExC_npar ; paren++ ) {
7291 if ( RExC_parens[paren] >= src )
7292 RExC_parens[paren] += size;
7296 while (src > opnd) {
7297 StructCopy(--src, --dst, regnode);
7298 if (RExC_offsets) { /* MJD 20010112 */
7299 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
7303 (UV)(dst - RExC_emit_start) > RExC_offsets[0]
7304 ? "Overwriting end of array!\n" : "OK",
7305 (UV)(src - RExC_emit_start),
7306 (UV)(dst - RExC_emit_start),
7307 (UV)RExC_offsets[0]));
7308 Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
7309 Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
7314 place = opnd; /* Op node, where operand used to be. */
7315 if (RExC_offsets) { /* MJD */
7316 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
7320 (UV)(place - RExC_emit_start) > RExC_offsets[0]
7321 ? "Overwriting end of array!\n" : "OK",
7322 (UV)(place - RExC_emit_start),
7323 (UV)(RExC_parse - RExC_start),
7324 (UV)RExC_offsets[0]));
7325 Set_Node_Offset(place, RExC_parse);
7326 Set_Node_Length(place, 1);
7328 src = NEXTOPER(place);
7329 FILL_ADVANCE_NODE(place, op);
7330 Zero(src, offset, regnode);
7334 - regtail - set the next-pointer at the end of a node chain of p to val.
7335 - SEE ALSO: regtail_study
7337 /* TODO: All three parms should be const */
7339 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
7342 register regnode *scan;
7343 GET_RE_DEBUG_FLAGS_DECL;
7345 PERL_UNUSED_ARG(depth);
7351 /* Find last node. */
7354 regnode * const temp = regnext(scan);
7356 SV * const mysv=sv_newmortal();
7357 DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
7358 regprop(RExC_rx, mysv, scan);
7359 PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
7360 SvPV_nolen_const(mysv), REG_NODE_NUM(scan),
7361 (temp == NULL ? "->" : ""),
7362 (temp == NULL ? reg_name[OP(val)] : "")
7370 if (reg_off_by_arg[OP(scan)]) {
7371 ARG_SET(scan, val - scan);
7374 NEXT_OFF(scan) = val - scan;
7380 - regtail_study - set the next-pointer at the end of a node chain of p to val.
7381 - Look for optimizable sequences at the same time.
7382 - currently only looks for EXACT chains.
7384 This is expermental code. The idea is to use this routine to perform
7385 in place optimizations on branches and groups as they are constructed,
7386 with the long term intention of removing optimization from study_chunk so
7387 that it is purely analytical.
7389 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
7390 to control which is which.
7393 /* TODO: All four parms should be const */
7396 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
7399 register regnode *scan;
7401 #ifdef EXPERIMENTAL_INPLACESCAN
7405 GET_RE_DEBUG_FLAGS_DECL;
7411 /* Find last node. */
7415 regnode * const temp = regnext(scan);
7416 #ifdef EXPERIMENTAL_INPLACESCAN
7417 if (PL_regkind[OP(scan)] == EXACT)
7418 if (join_exact(pRExC_state,scan,&min,1,val,depth+1))
7426 if( exact == PSEUDO )
7428 else if ( exact != OP(scan) )
7437 SV * const mysv=sv_newmortal();
7438 DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
7439 regprop(RExC_rx, mysv, scan);
7440 PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
7441 SvPV_nolen_const(mysv),
7450 SV * const mysv_val=sv_newmortal();
7451 DEBUG_PARSE_MSG("");
7452 regprop(RExC_rx, mysv_val, val);
7453 PerlIO_printf(Perl_debug_log, "~ attach to %s (%d) offset to %d\n",
7454 SvPV_nolen_const(mysv_val),
7459 if (reg_off_by_arg[OP(scan)]) {
7460 ARG_SET(scan, val - scan);
7463 NEXT_OFF(scan) = val - scan;
7471 - regcurly - a little FSA that accepts {\d+,?\d*}
7474 S_regcurly(register const char *s)
7493 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
7496 Perl_regdump(pTHX_ const regexp *r)
7500 SV * const sv = sv_newmortal();
7501 SV *dsv= sv_newmortal();
7503 (void)dumpuntil(r, r->program, r->program + 1, NULL, NULL, sv, 0, 0);
7505 /* Header fields of interest. */
7506 if (r->anchored_substr) {
7507 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr),
7508 RE_SV_DUMPLEN(r->anchored_substr), 30);
7509 PerlIO_printf(Perl_debug_log,
7510 "anchored %s%s at %"IVdf" ",
7511 s, RE_SV_TAIL(r->anchored_substr),
7512 (IV)r->anchored_offset);
7513 } else if (r->anchored_utf8) {
7514 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8),
7515 RE_SV_DUMPLEN(r->anchored_utf8), 30);
7516 PerlIO_printf(Perl_debug_log,
7517 "anchored utf8 %s%s at %"IVdf" ",
7518 s, RE_SV_TAIL(r->anchored_utf8),
7519 (IV)r->anchored_offset);
7521 if (r->float_substr) {
7522 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr),
7523 RE_SV_DUMPLEN(r->float_substr), 30);
7524 PerlIO_printf(Perl_debug_log,
7525 "floating %s%s at %"IVdf"..%"UVuf" ",
7526 s, RE_SV_TAIL(r->float_substr),
7527 (IV)r->float_min_offset, (UV)r->float_max_offset);
7528 } else if (r->float_utf8) {
7529 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8),
7530 RE_SV_DUMPLEN(r->float_utf8), 30);
7531 PerlIO_printf(Perl_debug_log,
7532 "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
7533 s, RE_SV_TAIL(r->float_utf8),
7534 (IV)r->float_min_offset, (UV)r->float_max_offset);
7536 if (r->check_substr || r->check_utf8)
7537 PerlIO_printf(Perl_debug_log,
7539 (r->check_substr == r->float_substr
7540 && r->check_utf8 == r->float_utf8
7541 ? "(checking floating" : "(checking anchored"));
7542 if (r->reganch & ROPT_NOSCAN)
7543 PerlIO_printf(Perl_debug_log, " noscan");
7544 if (r->reganch & ROPT_CHECK_ALL)
7545 PerlIO_printf(Perl_debug_log, " isall");
7546 if (r->check_substr || r->check_utf8)
7547 PerlIO_printf(Perl_debug_log, ") ");
7549 if (r->regstclass) {
7550 regprop(r, sv, r->regstclass);
7551 PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
7553 if (r->reganch & ROPT_ANCH) {
7554 PerlIO_printf(Perl_debug_log, "anchored");
7555 if (r->reganch & ROPT_ANCH_BOL)
7556 PerlIO_printf(Perl_debug_log, "(BOL)");
7557 if (r->reganch & ROPT_ANCH_MBOL)
7558 PerlIO_printf(Perl_debug_log, "(MBOL)");
7559 if (r->reganch & ROPT_ANCH_SBOL)
7560 PerlIO_printf(Perl_debug_log, "(SBOL)");
7561 if (r->reganch & ROPT_ANCH_GPOS)
7562 PerlIO_printf(Perl_debug_log, "(GPOS)");
7563 PerlIO_putc(Perl_debug_log, ' ');
7565 if (r->reganch & ROPT_GPOS_SEEN)
7566 PerlIO_printf(Perl_debug_log, "GPOS ");
7567 if (r->reganch & ROPT_SKIP)
7568 PerlIO_printf(Perl_debug_log, "plus ");
7569 if (r->reganch & ROPT_IMPLICIT)
7570 PerlIO_printf(Perl_debug_log, "implicit ");
7571 PerlIO_printf(Perl_debug_log, "minlen %ld ", (long) r->minlen);
7572 if (r->reganch & ROPT_EVAL_SEEN)
7573 PerlIO_printf(Perl_debug_log, "with eval ");
7574 PerlIO_printf(Perl_debug_log, "\n");
7576 PERL_UNUSED_CONTEXT;
7578 #endif /* DEBUGGING */
7582 - regprop - printable representation of opcode
7585 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
7590 GET_RE_DEBUG_FLAGS_DECL;
7592 sv_setpvn(sv, "", 0);
7593 if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */
7594 /* It would be nice to FAIL() here, but this may be called from
7595 regexec.c, and it would be hard to supply pRExC_state. */
7596 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
7597 sv_catpv(sv, reg_name[OP(o)]); /* Take off const! */
7599 k = PL_regkind[OP(o)];
7602 SV * const dsv = sv_2mortal(newSVpvs(""));
7603 /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
7604 * is a crude hack but it may be the best for now since
7605 * we have no flag "this EXACTish node was UTF-8"
7607 const char * const s =
7608 pv_pretty(dsv, STRING(o), STR_LEN(o), 60,
7609 PL_colors[0], PL_colors[1],
7610 PERL_PV_ESCAPE_UNI_DETECT |
7611 PERL_PV_PRETTY_ELIPSES |
7614 Perl_sv_catpvf(aTHX_ sv, " %s", s );
7615 } else if (k == TRIE) {
7616 /* print the details of the trie in dumpuntil instead, as
7617 * prog->data isn't available here */
7618 const char op = OP(o);
7619 const I32 n = ARG(o);
7620 const reg_ac_data * const ac = IS_TRIE_AC(op) ?
7621 (reg_ac_data *)prog->data->data[n] :
7623 const reg_trie_data * const trie = !IS_TRIE_AC(op) ?
7624 (reg_trie_data*)prog->data->data[n] :
7627 Perl_sv_catpvf(aTHX_ sv, "-%s",reg_name[o->flags]);
7628 DEBUG_TRIE_COMPILE_r(
7629 Perl_sv_catpvf(aTHX_ sv,
7630 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
7631 (UV)trie->startstate,
7632 (IV)trie->laststate-1,
7633 (UV)trie->wordcount,
7636 (UV)TRIE_CHARCOUNT(trie),
7637 (UV)trie->uniquecharcount
7640 if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
7642 int rangestart = -1;
7643 U8* bitmap = IS_ANYOF_TRIE(op) ? (U8*)ANYOF_BITMAP(o) : (U8*)TRIE_BITMAP(trie);
7644 Perl_sv_catpvf(aTHX_ sv, "[");
7645 for (i = 0; i <= 256; i++) {
7646 if (i < 256 && BITMAP_TEST(bitmap,i)) {
7647 if (rangestart == -1)
7649 } else if (rangestart != -1) {
7650 if (i <= rangestart + 3)
7651 for (; rangestart < i; rangestart++)
7652 put_byte(sv, rangestart);
7654 put_byte(sv, rangestart);
7656 put_byte(sv, i - 1);
7661 Perl_sv_catpvf(aTHX_ sv, "]");
7664 } else if (k == CURLY) {
7665 if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
7666 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
7667 Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
7669 else if (k == WHILEM && o->flags) /* Ordinal/of */
7670 Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
7671 else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP)
7672 Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o)); /* Parenth number */
7673 else if (k == RECURSE)
7674 Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
7675 else if (k == LOGICAL)
7676 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* 2: embedded, otherwise 1 */
7677 else if (k == ANYOF) {
7678 int i, rangestart = -1;
7679 const U8 flags = ANYOF_FLAGS(o);
7681 /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
7682 static const char * const anyofs[] = {
7715 if (flags & ANYOF_LOCALE)
7716 sv_catpvs(sv, "{loc}");
7717 if (flags & ANYOF_FOLD)
7718 sv_catpvs(sv, "{i}");
7719 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
7720 if (flags & ANYOF_INVERT)
7722 for (i = 0; i <= 256; i++) {
7723 if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
7724 if (rangestart == -1)
7726 } else if (rangestart != -1) {
7727 if (i <= rangestart + 3)
7728 for (; rangestart < i; rangestart++)
7729 put_byte(sv, rangestart);
7731 put_byte(sv, rangestart);
7733 put_byte(sv, i - 1);
7739 if (o->flags & ANYOF_CLASS)
7740 for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++)
7741 if (ANYOF_CLASS_TEST(o,i))
7742 sv_catpv(sv, anyofs[i]);
7744 if (flags & ANYOF_UNICODE)
7745 sv_catpvs(sv, "{unicode}");
7746 else if (flags & ANYOF_UNICODE_ALL)
7747 sv_catpvs(sv, "{unicode_all}");
7751 SV * const sw = regclass_swash(prog, o, FALSE, &lv, 0);
7755 U8 s[UTF8_MAXBYTES_CASE+1];
7757 for (i = 0; i <= 256; i++) { /* just the first 256 */
7758 uvchr_to_utf8(s, i);
7760 if (i < 256 && swash_fetch(sw, s, TRUE)) {
7761 if (rangestart == -1)
7763 } else if (rangestart != -1) {
7764 if (i <= rangestart + 3)
7765 for (; rangestart < i; rangestart++) {
7766 const U8 * const e = uvchr_to_utf8(s,rangestart);
7768 for(p = s; p < e; p++)
7772 const U8 *e = uvchr_to_utf8(s,rangestart);
7774 for (p = s; p < e; p++)
7777 e = uvchr_to_utf8(s, i-1);
7778 for (p = s; p < e; p++)
7785 sv_catpvs(sv, "..."); /* et cetera */
7789 char *s = savesvpv(lv);
7790 char * const origs = s;
7792 while (*s && *s != '\n')
7796 const char * const t = ++s;
7814 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
7816 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
7817 Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
7819 PERL_UNUSED_CONTEXT;
7820 PERL_UNUSED_ARG(sv);
7822 PERL_UNUSED_ARG(prog);
7823 #endif /* DEBUGGING */
7827 Perl_re_intuit_string(pTHX_ regexp *prog)
7828 { /* Assume that RE_INTUIT is set */
7830 GET_RE_DEBUG_FLAGS_DECL;
7831 PERL_UNUSED_CONTEXT;
7835 const char * const s = SvPV_nolen_const(prog->check_substr
7836 ? prog->check_substr : prog->check_utf8);
7838 if (!PL_colorset) reginitcolors();
7839 PerlIO_printf(Perl_debug_log,
7840 "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
7842 prog->check_substr ? "" : "utf8 ",
7843 PL_colors[5],PL_colors[0],
7846 (strlen(s) > 60 ? "..." : ""));
7849 return prog->check_substr ? prog->check_substr : prog->check_utf8;
7853 pregfree - free a regexp
7855 See regdupe below if you change anything here.
7859 Perl_pregfree(pTHX_ struct regexp *r)
7863 GET_RE_DEBUG_FLAGS_DECL;
7865 if (!r || (--r->refcnt > 0))
7871 SV *dsv= sv_newmortal();
7872 RE_PV_QUOTED_DECL(s, (r->reganch & ROPT_UTF8),
7873 dsv, r->precomp, r->prelen, 60);
7874 PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n",
7875 PL_colors[4],PL_colors[5],s);
7879 /* gcov results gave these as non-null 100% of the time, so there's no
7880 optimisation in checking them before calling Safefree */
7881 Safefree(r->precomp);
7882 Safefree(r->offsets); /* 20010421 MJD */
7883 RX_MATCH_COPY_FREE(r);
7884 #ifdef PERL_OLD_COPY_ON_WRITE
7886 SvREFCNT_dec(r->saved_copy);
7889 if (r->anchored_substr)
7890 SvREFCNT_dec(r->anchored_substr);
7891 if (r->anchored_utf8)
7892 SvREFCNT_dec(r->anchored_utf8);
7893 if (r->float_substr)
7894 SvREFCNT_dec(r->float_substr);
7896 SvREFCNT_dec(r->float_utf8);
7897 Safefree(r->substrs);
7900 SvREFCNT_dec(r->paren_names);
7902 int n = r->data->count;
7903 PAD* new_comppad = NULL;
7908 /* If you add a ->what type here, update the comment in regcomp.h */
7909 switch (r->data->what[n]) {
7912 SvREFCNT_dec((SV*)r->data->data[n]);
7915 Safefree(r->data->data[n]);
7918 new_comppad = (AV*)r->data->data[n];
7921 if (new_comppad == NULL)
7922 Perl_croak(aTHX_ "panic: pregfree comppad");
7923 PAD_SAVE_LOCAL(old_comppad,
7924 /* Watch out for global destruction's random ordering. */
7925 (SvTYPE(new_comppad) == SVt_PVAV) ? new_comppad : NULL
7928 refcnt = OpREFCNT_dec((OP_4tree*)r->data->data[n]);
7931 op_free((OP_4tree*)r->data->data[n]);
7933 PAD_RESTORE_LOCAL(old_comppad);
7934 SvREFCNT_dec((SV*)new_comppad);
7940 { /* Aho Corasick add-on structure for a trie node.
7941 Used in stclass optimization only */
7943 reg_ac_data *aho=(reg_ac_data*)r->data->data[n];
7945 refcount = --aho->refcount;
7948 Safefree(aho->states);
7949 Safefree(aho->fail);
7950 aho->trie=NULL; /* not necessary to free this as it is
7951 handled by the 't' case */
7952 Safefree(r->data->data[n]); /* do this last!!!! */
7953 Safefree(r->regstclass);
7959 /* trie structure. */
7961 reg_trie_data *trie=(reg_trie_data*)r->data->data[n];
7963 refcount = --trie->refcount;
7966 Safefree(trie->charmap);
7967 if (trie->widecharmap)
7968 SvREFCNT_dec((SV*)trie->widecharmap);
7969 Safefree(trie->states);
7970 Safefree(trie->trans);
7972 Safefree(trie->bitmap);
7974 Safefree(trie->wordlen);
7976 Safefree(trie->jump);
7978 Safefree(trie->nextword);
7982 SvREFCNT_dec((SV*)trie->words);
7983 if (trie->revcharmap)
7984 SvREFCNT_dec((SV*)trie->revcharmap);
7987 Safefree(r->data->data[n]); /* do this last!!!! */
7992 Perl_croak(aTHX_ "panic: regfree data code '%c'", r->data->what[n]);
7995 Safefree(r->data->what);
7998 Safefree(r->startp);
8003 #define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
8004 #define av_dup_inc(s,t) (AV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8005 #define hv_dup_inc(s,t) (HV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8006 #define SAVEPVN(p,n) ((p) ? savepvn(p,n) : NULL)
8009 regdupe - duplicate a regexp.
8011 This routine is called by sv.c's re_dup and is expected to clone a
8012 given regexp structure. It is a no-op when not under USE_ITHREADS.
8013 (Originally this *was* re_dup() for change history see sv.c)
8015 See pregfree() above if you change anything here.
8017 #if defined(USE_ITHREADS)
8019 Perl_regdupe(pTHX_ const regexp *r, CLONE_PARAMS *param)
8024 struct reg_substr_datum *s;
8027 return (REGEXP *)NULL;
8029 if ((ret = (REGEXP *)ptr_table_fetch(PL_ptr_table, r)))
8032 len = r->offsets[0];
8033 npar = r->nparens+1;
8035 Newxc(ret, sizeof(regexp) + (len+1)*sizeof(regnode), char, regexp);
8036 Copy(r->program, ret->program, len+1, regnode);
8038 Newx(ret->startp, npar, I32);
8039 Copy(r->startp, ret->startp, npar, I32);
8040 Newx(ret->endp, npar, I32);
8041 Copy(r->startp, ret->startp, npar, I32);
8043 Newx(ret->substrs, 1, struct reg_substr_data);
8044 for (s = ret->substrs->data, i = 0; i < 3; i++, s++) {
8045 s->min_offset = r->substrs->data[i].min_offset;
8046 s->max_offset = r->substrs->data[i].max_offset;
8047 s->end_shift = r->substrs->data[i].end_shift;
8048 s->substr = sv_dup_inc(r->substrs->data[i].substr, param);
8049 s->utf8_substr = sv_dup_inc(r->substrs->data[i].utf8_substr, param);
8052 ret->regstclass = NULL;
8055 const int count = r->data->count;
8058 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
8059 char, struct reg_data);
8060 Newx(d->what, count, U8);
8063 for (i = 0; i < count; i++) {
8064 d->what[i] = r->data->what[i];
8065 switch (d->what[i]) {
8066 /* legal options are one of: sfpont
8067 see also regcomp.h and pregfree() */
8070 d->data[i] = sv_dup_inc((SV *)r->data->data[i], param);
8073 d->data[i] = av_dup_inc((AV *)r->data->data[i], param);
8076 /* This is cheating. */
8077 Newx(d->data[i], 1, struct regnode_charclass_class);
8078 StructCopy(r->data->data[i], d->data[i],
8079 struct regnode_charclass_class);
8080 ret->regstclass = (regnode*)d->data[i];
8083 /* Compiled op trees are readonly, and can thus be
8084 shared without duplication. */
8086 d->data[i] = (void*)OpREFCNT_inc((OP*)r->data->data[i]);
8090 d->data[i] = r->data->data[i];
8093 d->data[i] = r->data->data[i];
8095 ((reg_trie_data*)d->data[i])->refcount++;
8099 d->data[i] = r->data->data[i];
8101 ((reg_ac_data*)d->data[i])->refcount++;
8103 /* Trie stclasses are readonly and can thus be shared
8104 * without duplication. We free the stclass in pregfree
8105 * when the corresponding reg_ac_data struct is freed.
8107 ret->regstclass= r->regstclass;
8110 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", r->data->what[i]);
8119 Newx(ret->offsets, 2*len+1, U32);
8120 Copy(r->offsets, ret->offsets, 2*len+1, U32);
8122 ret->precomp = SAVEPVN(r->precomp, r->prelen);
8123 ret->refcnt = r->refcnt;
8124 ret->minlen = r->minlen;
8125 ret->prelen = r->prelen;
8126 ret->nparens = r->nparens;
8127 ret->lastparen = r->lastparen;
8128 ret->lastcloseparen = r->lastcloseparen;
8129 ret->reganch = r->reganch;
8131 ret->sublen = r->sublen;
8133 ret->engine = r->engine;
8135 ret->paren_names = hv_dup_inc(r->paren_names, param);
8137 if (RX_MATCH_COPIED(ret))
8138 ret->subbeg = SAVEPVN(r->subbeg, r->sublen);
8141 #ifdef PERL_OLD_COPY_ON_WRITE
8142 ret->saved_copy = NULL;
8145 ptr_table_store(PL_ptr_table, r, ret);
8150 #ifndef PERL_IN_XSUB_RE
8152 - regnext - dig the "next" pointer out of a node
8155 Perl_regnext(pTHX_ register regnode *p)
8158 register I32 offset;
8160 if (p == &PL_regdummy)
8163 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
8172 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
8175 STRLEN l1 = strlen(pat1);
8176 STRLEN l2 = strlen(pat2);
8179 const char *message;
8185 Copy(pat1, buf, l1 , char);
8186 Copy(pat2, buf + l1, l2 , char);
8187 buf[l1 + l2] = '\n';
8188 buf[l1 + l2 + 1] = '\0';
8190 /* ANSI variant takes additional second argument */
8191 va_start(args, pat2);
8195 msv = vmess(buf, &args);
8197 message = SvPV_const(msv,l1);
8200 Copy(message, buf, l1 , char);
8201 buf[l1-1] = '\0'; /* Overwrite \n */
8202 Perl_croak(aTHX_ "%s", buf);
8205 /* XXX Here's a total kludge. But we need to re-enter for swash routines. */
8207 #ifndef PERL_IN_XSUB_RE
8209 Perl_save_re_context(pTHX)
8213 struct re_save_state *state;
8215 SAVEVPTR(PL_curcop);
8216 SSGROW(SAVESTACK_ALLOC_FOR_RE_SAVE_STATE + 1);
8218 state = (struct re_save_state *)(PL_savestack + PL_savestack_ix);
8219 PL_savestack_ix += SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
8220 SSPUSHINT(SAVEt_RE_STATE);
8222 Copy(&PL_reg_state, state, 1, struct re_save_state);
8224 PL_reg_start_tmp = 0;
8225 PL_reg_start_tmpl = 0;
8226 PL_reg_oldsaved = NULL;
8227 PL_reg_oldsavedlen = 0;
8229 PL_reg_leftiter = 0;
8230 PL_reg_poscache = NULL;
8231 PL_reg_poscache_size = 0;
8232 #ifdef PERL_OLD_COPY_ON_WRITE
8236 /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
8238 const REGEXP * const rx = PM_GETRE(PL_curpm);
8241 for (i = 1; i <= rx->nparens; i++) {
8242 char digits[TYPE_CHARS(long)];
8243 const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
8244 GV *const *const gvp
8245 = (GV**)hv_fetch(PL_defstash, digits, len, 0);
8248 GV * const gv = *gvp;
8249 if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
8259 clear_re(pTHX_ void *r)
8262 ReREFCNT_dec((regexp *)r);
8268 S_put_byte(pTHX_ SV *sv, int c)
8270 if (isCNTRL(c) || c == 255 || !isPRINT(c))
8271 Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
8272 else if (c == '-' || c == ']' || c == '\\' || c == '^')
8273 Perl_sv_catpvf(aTHX_ sv, "\\%c", c);
8275 Perl_sv_catpvf(aTHX_ sv, "%c", c);
8279 #define CLEAR_OPTSTART \
8280 if (optstart) STMT_START { \
8281 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%d nodes)\n", node - optstart)); \
8285 #define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
8287 STATIC const regnode *
8288 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
8289 const regnode *last, const regnode *plast,
8290 SV* sv, I32 indent, U32 depth)
8293 register U8 op = PSEUDO; /* Arbitrary non-END op. */
8294 register const regnode *next;
8295 const regnode *optstart= NULL;
8296 GET_RE_DEBUG_FLAGS_DECL;
8298 #ifdef DEBUG_DUMPUNTIL
8299 PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
8300 last ? last-start : 0,plast ? plast-start : 0);
8303 if (plast && plast < last)
8306 while (PL_regkind[op] != END && (!last || node < last)) {
8307 /* While that wasn't END last time... */
8313 next = regnext((regnode *)node);
8316 if (OP(node) == OPTIMIZED) {
8317 if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
8324 regprop(r, sv, node);
8325 PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
8326 (int)(2*indent + 1), "", SvPVX_const(sv));
8328 if (OP(node) != OPTIMIZED) {
8329 if (next == NULL) /* Next ptr. */
8330 PerlIO_printf(Perl_debug_log, "(0)");
8331 else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
8332 PerlIO_printf(Perl_debug_log, "(FAIL)");
8334 PerlIO_printf(Perl_debug_log, "(%"IVdf")", (IV)(next - start));
8336 /*if (PL_regkind[(U8)op] != TRIE)*/
8337 (void)PerlIO_putc(Perl_debug_log, '\n');
8341 if (PL_regkind[(U8)op] == BRANCHJ) {
8344 register const regnode *nnode = (OP(next) == LONGJMP
8345 ? regnext((regnode *)next)
8347 if (last && nnode > last)
8349 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
8352 else if (PL_regkind[(U8)op] == BRANCH) {
8354 DUMPUNTIL(NEXTOPER(node), next);
8356 else if ( PL_regkind[(U8)op] == TRIE ) {
8357 const char op = OP(node);
8358 const I32 n = ARG(node);
8359 const reg_ac_data * const ac = op>=AHOCORASICK ?
8360 (reg_ac_data *)r->data->data[n] :
8362 const reg_trie_data * const trie = op<AHOCORASICK ?
8363 (reg_trie_data*)r->data->data[n] :
8365 const regnode *nextbranch= NULL;
8367 sv_setpvn(sv, "", 0);
8368 for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
8369 SV ** const elem_ptr = av_fetch(trie->words,word_idx,0);
8371 PerlIO_printf(Perl_debug_log, "%*s%s ",
8372 (int)(2*(indent+3)), "",
8373 elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
8374 PL_colors[0], PL_colors[1],
8375 (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
8376 PERL_PV_PRETTY_ELIPSES |
8382 U16 dist= trie->jump[word_idx+1];
8383 PerlIO_printf(Perl_debug_log, "(%u)\n",(next - dist) - start);
8386 nextbranch= next - trie->jump[0];
8387 DUMPUNTIL(next - dist, nextbranch);
8389 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
8390 nextbranch= regnext((regnode *)nextbranch);
8392 PerlIO_printf(Perl_debug_log, "\n");
8395 if (last && next > last)
8400 else if ( op == CURLY ) { /* "next" might be very big: optimizer */
8401 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
8402 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
8404 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
8406 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
8408 else if ( op == PLUS || op == STAR) {
8409 DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
8411 else if (op == ANYOF) {
8412 /* arglen 1 + class block */
8413 node += 1 + ((ANYOF_FLAGS(node) & ANYOF_LARGE)
8414 ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
8415 node = NEXTOPER(node);
8417 else if (PL_regkind[(U8)op] == EXACT) {
8418 /* Literal string, where present. */
8419 node += NODE_SZ_STR(node) - 1;
8420 node = NEXTOPER(node);
8423 node = NEXTOPER(node);
8424 node += regarglen[(U8)op];
8426 if (op == CURLYX || op == OPEN)
8428 else if (op == WHILEM)
8432 #ifdef DEBUG_DUMPUNTIL
8433 PerlIO_printf(Perl_debug_log, "--- %d\n",indent);
8438 #endif /* DEBUGGING */
8442 * c-indentation-style: bsd
8444 * indent-tabs-mode: t
8447 * ex: set ts=8 sts=4 sw=4 noet: