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 */
124 char *starttry; /* -Dr: where regtry was called. */
125 #define RExC_starttry (pRExC_state->starttry)
128 const char *lastparse;
130 #define RExC_lastparse (pRExC_state->lastparse)
131 #define RExC_lastnum (pRExC_state->lastnum)
135 #define RExC_flags (pRExC_state->flags)
136 #define RExC_precomp (pRExC_state->precomp)
137 #define RExC_rx (pRExC_state->rx)
138 #define RExC_start (pRExC_state->start)
139 #define RExC_end (pRExC_state->end)
140 #define RExC_parse (pRExC_state->parse)
141 #define RExC_whilem_seen (pRExC_state->whilem_seen)
142 #define RExC_offsets (pRExC_state->rx->offsets) /* I am not like the others */
143 #define RExC_emit (pRExC_state->emit)
144 #define RExC_emit_start (pRExC_state->emit_start)
145 #define RExC_naughty (pRExC_state->naughty)
146 #define RExC_sawback (pRExC_state->sawback)
147 #define RExC_seen (pRExC_state->seen)
148 #define RExC_size (pRExC_state->size)
149 #define RExC_npar (pRExC_state->npar)
150 #define RExC_extralen (pRExC_state->extralen)
151 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
152 #define RExC_seen_evals (pRExC_state->seen_evals)
153 #define RExC_utf8 (pRExC_state->utf8)
154 #define RExC_charnames (pRExC_state->charnames)
155 #define RExC_parens (pRExC_state->parens)
157 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
158 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
159 ((*s) == '{' && regcurly(s)))
162 #undef SPSTART /* dratted cpp namespace... */
165 * Flags to be passed up and down.
167 #define WORST 0 /* Worst case. */
168 #define HASWIDTH 0x1 /* Known to match non-null strings. */
169 #define SIMPLE 0x2 /* Simple enough to be STAR/PLUS operand. */
170 #define SPSTART 0x4 /* Starts with * or +. */
171 #define TRYAGAIN 0x8 /* Weeded out a declaration. */
173 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
175 /* whether trie related optimizations are enabled */
176 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
177 #define TRIE_STUDY_OPT
178 #define FULL_TRIE_STUDY
183 /* About scan_data_t.
185 During optimisation we recurse through the regexp program performing
186 various inplace (keyhole style) optimisations. In addition study_chunk
187 and scan_commit populate this data structure with information about
188 what strings MUST appear in the pattern. We look for the longest
189 string that must appear for at a fixed location, and we look for the
190 longest string that may appear at a floating location. So for instance
195 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
196 strings (because they follow a .* construct). study_chunk will identify
197 both FOO and BAR as being the longest fixed and floating strings respectively.
199 The strings can be composites, for instance
203 will result in a composite fixed substring 'foo'.
205 For each string some basic information is maintained:
207 - offset or min_offset
208 This is the position the string must appear at, or not before.
209 It also implicitly (when combined with minlenp) tells us how many
210 character must match before the string we are searching.
211 Likewise when combined with minlenp and the length of the string
212 tells us how many characters must appear after the string we have
216 Only used for floating strings. This is the rightmost point that
217 the string can appear at. Ifset to I32 max it indicates that the
218 string can occur infinitely far to the right.
221 A pointer to the minimum length of the pattern that the string
222 was found inside. This is important as in the case of positive
223 lookahead or positive lookbehind we can have multiple patterns
228 The minimum length of the pattern overall is 3, the minimum length
229 of the lookahead part is 3, but the minimum length of the part that
230 will actually match is 1. So 'FOO's minimum length is 3, but the
231 minimum length for the F is 1. This is important as the minimum length
232 is used to determine offsets in front of and behind the string being
233 looked for. Since strings can be composites this is the length of the
234 pattern at the time it was commited with a scan_commit. Note that
235 the length is calculated by study_chunk, so that the minimum lengths
236 are not known until the full pattern has been compiled, thus the
237 pointer to the value.
241 In the case of lookbehind the string being searched for can be
242 offset past the start point of the final matching string.
243 If this value was just blithely removed from the min_offset it would
244 invalidate some of the calculations for how many chars must match
245 before or after (as they are derived from min_offset and minlen and
246 the length of the string being searched for).
247 When the final pattern is compiled and the data is moved from the
248 scan_data_t structure into the regexp structure the information
249 about lookbehind is factored in, with the information that would
250 have been lost precalculated in the end_shift field for the
253 The fields pos_min and pos_delta are used to store the minimum offset
254 and the delta to the maximum offset at the current point in the pattern.
258 typedef struct scan_data_t {
259 /*I32 len_min; unused */
260 /*I32 len_delta; unused */
264 I32 last_end; /* min value, <0 unless valid. */
267 SV **longest; /* Either &l_fixed, or &l_float. */
268 SV *longest_fixed; /* longest fixed string found in pattern */
269 I32 offset_fixed; /* offset where it starts */
270 I32 *minlen_fixed; /* pointer to the minlen relevent to the string */
271 I32 lookbehind_fixed; /* is the position of the string modfied by LB */
272 SV *longest_float; /* longest floating string found in pattern */
273 I32 offset_float_min; /* earliest point in string it can appear */
274 I32 offset_float_max; /* latest point in string it can appear */
275 I32 *minlen_float; /* pointer to the minlen relevent to the string */
276 I32 lookbehind_float; /* is the position of the string modified by LB */
280 struct regnode_charclass_class *start_class;
284 * Forward declarations for pregcomp()'s friends.
287 static const scan_data_t zero_scan_data =
288 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
290 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
291 #define SF_BEFORE_SEOL 0x0001
292 #define SF_BEFORE_MEOL 0x0002
293 #define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
294 #define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
297 # define SF_FIX_SHIFT_EOL (0+2)
298 # define SF_FL_SHIFT_EOL (0+4)
300 # define SF_FIX_SHIFT_EOL (+2)
301 # define SF_FL_SHIFT_EOL (+4)
304 #define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
305 #define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
307 #define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
308 #define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
309 #define SF_IS_INF 0x0040
310 #define SF_HAS_PAR 0x0080
311 #define SF_IN_PAR 0x0100
312 #define SF_HAS_EVAL 0x0200
313 #define SCF_DO_SUBSTR 0x0400
314 #define SCF_DO_STCLASS_AND 0x0800
315 #define SCF_DO_STCLASS_OR 0x1000
316 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
317 #define SCF_WHILEM_VISITED_POS 0x2000
319 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
322 #define UTF (RExC_utf8 != 0)
323 #define LOC ((RExC_flags & PMf_LOCALE) != 0)
324 #define FOLD ((RExC_flags & PMf_FOLD) != 0)
326 #define OOB_UNICODE 12345678
327 #define OOB_NAMEDCLASS -1
329 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
330 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
333 /* length of regex to show in messages that don't mark a position within */
334 #define RegexLengthToShowInErrorMessages 127
337 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
338 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
339 * op/pragma/warn/regcomp.
341 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
342 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
344 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
347 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
348 * arg. Show regex, up to a maximum length. If it's too long, chop and add
351 #define FAIL(msg) STMT_START { \
352 const char *ellipses = ""; \
353 IV len = RExC_end - RExC_precomp; \
356 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
357 if (len > RegexLengthToShowInErrorMessages) { \
358 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
359 len = RegexLengthToShowInErrorMessages - 10; \
362 Perl_croak(aTHX_ "%s in regex m/%.*s%s/", \
363 msg, (int)len, RExC_precomp, ellipses); \
367 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
369 #define Simple_vFAIL(m) STMT_START { \
370 const IV offset = RExC_parse - RExC_precomp; \
371 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
372 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
376 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
378 #define vFAIL(m) STMT_START { \
380 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
385 * Like Simple_vFAIL(), but accepts two arguments.
387 #define Simple_vFAIL2(m,a1) STMT_START { \
388 const IV offset = RExC_parse - RExC_precomp; \
389 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, \
390 (int)offset, RExC_precomp, RExC_precomp + offset); \
394 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
396 #define vFAIL2(m,a1) STMT_START { \
398 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
399 Simple_vFAIL2(m, a1); \
404 * Like Simple_vFAIL(), but accepts three arguments.
406 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
407 const IV offset = RExC_parse - RExC_precomp; \
408 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, \
409 (int)offset, RExC_precomp, RExC_precomp + offset); \
413 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
415 #define vFAIL3(m,a1,a2) STMT_START { \
417 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
418 Simple_vFAIL3(m, a1, a2); \
422 * Like Simple_vFAIL(), but accepts four arguments.
424 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
425 const IV offset = RExC_parse - RExC_precomp; \
426 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, \
427 (int)offset, RExC_precomp, RExC_precomp + offset); \
430 #define vWARN(loc,m) STMT_START { \
431 const IV offset = loc - RExC_precomp; \
432 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s" REPORT_LOCATION, \
433 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
436 #define vWARNdep(loc,m) STMT_START { \
437 const IV offset = loc - RExC_precomp; \
438 Perl_warner(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
439 "%s" REPORT_LOCATION, \
440 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
444 #define vWARN2(loc, m, a1) STMT_START { \
445 const IV offset = loc - RExC_precomp; \
446 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
447 a1, (int)offset, RExC_precomp, RExC_precomp + offset); \
450 #define vWARN3(loc, m, a1, a2) STMT_START { \
451 const IV offset = loc - RExC_precomp; \
452 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
453 a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
456 #define vWARN4(loc, m, a1, a2, a3) STMT_START { \
457 const IV offset = loc - RExC_precomp; \
458 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
459 a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
462 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START { \
463 const IV offset = loc - RExC_precomp; \
464 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
465 a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
469 /* Allow for side effects in s */
470 #define REGC(c,s) STMT_START { \
471 if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
474 /* Macros for recording node offsets. 20001227 mjd@plover.com
475 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
476 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
477 * Element 0 holds the number n.
478 * Position is 1 indexed.
481 #define Set_Node_Offset_To_R(node,byte) STMT_START { \
483 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
484 __LINE__, (node), (int)(byte))); \
486 Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
488 RExC_offsets[2*(node)-1] = (byte); \
493 #define Set_Node_Offset(node,byte) \
494 Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
495 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
497 #define Set_Node_Length_To_R(node,len) STMT_START { \
499 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
500 __LINE__, (int)(node), (int)(len))); \
502 Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
504 RExC_offsets[2*(node)] = (len); \
509 #define Set_Node_Length(node,len) \
510 Set_Node_Length_To_R((node)-RExC_emit_start, len)
511 #define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
512 #define Set_Node_Cur_Length(node) \
513 Set_Node_Length(node, RExC_parse - parse_start)
515 /* Get offsets and lengths */
516 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
517 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
519 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
520 Set_Node_Offset_To_R((node)-RExC_emit_start, (offset)); \
521 Set_Node_Length_To_R((node)-RExC_emit_start, (len)); \
525 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
526 #define EXPERIMENTAL_INPLACESCAN
529 #define DEBUG_STUDYDATA(data,depth) \
530 DEBUG_OPTIMISE_MORE_r(if(data){ \
531 PerlIO_printf(Perl_debug_log, \
532 "%*s"/* Len:%"IVdf"/%"IVdf" */" Pos:%"IVdf"/%"IVdf \
533 " Flags: %"IVdf" Whilem_c: %"IVdf" Lcp: %"IVdf" ", \
534 (int)(depth)*2, "", \
535 (IV)((data)->pos_min), \
536 (IV)((data)->pos_delta), \
537 (IV)((data)->flags), \
538 (IV)((data)->whilem_c), \
539 (IV)((data)->last_closep ? *((data)->last_closep) : -1) \
541 if ((data)->last_found) \
542 PerlIO_printf(Perl_debug_log, \
543 "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
544 " %sFloat: '%s' @ %"IVdf"/%"IVdf"", \
545 SvPVX_const((data)->last_found), \
546 (IV)((data)->last_end), \
547 (IV)((data)->last_start_min), \
548 (IV)((data)->last_start_max), \
549 ((data)->longest && \
550 (data)->longest==&((data)->longest_fixed)) ? "*" : "", \
551 SvPVX_const((data)->longest_fixed), \
552 (IV)((data)->offset_fixed), \
553 ((data)->longest && \
554 (data)->longest==&((data)->longest_float)) ? "*" : "", \
555 SvPVX_const((data)->longest_float), \
556 (IV)((data)->offset_float_min), \
557 (IV)((data)->offset_float_max) \
559 PerlIO_printf(Perl_debug_log,"\n"); \
562 static void clear_re(pTHX_ void *r);
564 /* Mark that we cannot extend a found fixed substring at this point.
565 Update the longest found anchored substring and the longest found
566 floating substrings if needed. */
569 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp)
571 const STRLEN l = CHR_SVLEN(data->last_found);
572 const STRLEN old_l = CHR_SVLEN(*data->longest);
573 GET_RE_DEBUG_FLAGS_DECL;
575 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
576 SvSetMagicSV(*data->longest, data->last_found);
577 if (*data->longest == data->longest_fixed) {
578 data->offset_fixed = l ? data->last_start_min : data->pos_min;
579 if (data->flags & SF_BEFORE_EOL)
581 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
583 data->flags &= ~SF_FIX_BEFORE_EOL;
584 data->minlen_fixed=minlenp;
585 data->lookbehind_fixed=0;
588 data->offset_float_min = l ? data->last_start_min : data->pos_min;
589 data->offset_float_max = (l
590 ? data->last_start_max
591 : data->pos_min + data->pos_delta);
592 if ((U32)data->offset_float_max > (U32)I32_MAX)
593 data->offset_float_max = I32_MAX;
594 if (data->flags & SF_BEFORE_EOL)
596 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
598 data->flags &= ~SF_FL_BEFORE_EOL;
599 data->minlen_float=minlenp;
600 data->lookbehind_float=0;
603 SvCUR_set(data->last_found, 0);
605 SV * const sv = data->last_found;
606 if (SvUTF8(sv) && SvMAGICAL(sv)) {
607 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
613 data->flags &= ~SF_BEFORE_EOL;
614 DEBUG_STUDYDATA(data,0);
617 /* Can match anything (initialization) */
619 S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
621 ANYOF_CLASS_ZERO(cl);
622 ANYOF_BITMAP_SETALL(cl);
623 cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL;
625 cl->flags |= ANYOF_LOCALE;
628 /* Can match anything (initialization) */
630 S_cl_is_anything(const struct regnode_charclass_class *cl)
634 for (value = 0; value <= ANYOF_MAX; value += 2)
635 if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
637 if (!(cl->flags & ANYOF_UNICODE_ALL))
639 if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
644 /* Can match anything (initialization) */
646 S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
648 Zero(cl, 1, struct regnode_charclass_class);
650 cl_anything(pRExC_state, cl);
654 S_cl_init_zero(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
656 Zero(cl, 1, struct regnode_charclass_class);
658 cl_anything(pRExC_state, cl);
660 cl->flags |= ANYOF_LOCALE;
663 /* 'And' a given class with another one. Can create false positives */
664 /* We assume that cl is not inverted */
666 S_cl_and(struct regnode_charclass_class *cl,
667 const struct regnode_charclass_class *and_with)
669 if (!(and_with->flags & ANYOF_CLASS)
670 && !(cl->flags & ANYOF_CLASS)
671 && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
672 && !(and_with->flags & ANYOF_FOLD)
673 && !(cl->flags & ANYOF_FOLD)) {
676 if (and_with->flags & ANYOF_INVERT)
677 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
678 cl->bitmap[i] &= ~and_with->bitmap[i];
680 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
681 cl->bitmap[i] &= and_with->bitmap[i];
682 } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
683 if (!(and_with->flags & ANYOF_EOS))
684 cl->flags &= ~ANYOF_EOS;
686 if (cl->flags & ANYOF_UNICODE_ALL && and_with->flags & ANYOF_UNICODE &&
687 !(and_with->flags & ANYOF_INVERT)) {
688 cl->flags &= ~ANYOF_UNICODE_ALL;
689 cl->flags |= ANYOF_UNICODE;
690 ARG_SET(cl, ARG(and_with));
692 if (!(and_with->flags & ANYOF_UNICODE_ALL) &&
693 !(and_with->flags & ANYOF_INVERT))
694 cl->flags &= ~ANYOF_UNICODE_ALL;
695 if (!(and_with->flags & (ANYOF_UNICODE|ANYOF_UNICODE_ALL)) &&
696 !(and_with->flags & ANYOF_INVERT))
697 cl->flags &= ~ANYOF_UNICODE;
700 /* 'OR' a given class with another one. Can create false positives */
701 /* We assume that cl is not inverted */
703 S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
705 if (or_with->flags & ANYOF_INVERT) {
707 * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
708 * <= (B1 | !B2) | (CL1 | !CL2)
709 * which is wasteful if CL2 is small, but we ignore CL2:
710 * (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
711 * XXXX Can we handle case-fold? Unclear:
712 * (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
713 * (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
715 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
716 && !(or_with->flags & ANYOF_FOLD)
717 && !(cl->flags & ANYOF_FOLD) ) {
720 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
721 cl->bitmap[i] |= ~or_with->bitmap[i];
722 } /* XXXX: logic is complicated otherwise */
724 cl_anything(pRExC_state, cl);
727 /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
728 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
729 && (!(or_with->flags & ANYOF_FOLD)
730 || (cl->flags & ANYOF_FOLD)) ) {
733 /* OR char bitmap and class bitmap separately */
734 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
735 cl->bitmap[i] |= or_with->bitmap[i];
736 if (or_with->flags & ANYOF_CLASS) {
737 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
738 cl->classflags[i] |= or_with->classflags[i];
739 cl->flags |= ANYOF_CLASS;
742 else { /* XXXX: logic is complicated, leave it along for a moment. */
743 cl_anything(pRExC_state, cl);
746 if (or_with->flags & ANYOF_EOS)
747 cl->flags |= ANYOF_EOS;
749 if (cl->flags & ANYOF_UNICODE && or_with->flags & ANYOF_UNICODE &&
750 ARG(cl) != ARG(or_with)) {
751 cl->flags |= ANYOF_UNICODE_ALL;
752 cl->flags &= ~ANYOF_UNICODE;
754 if (or_with->flags & ANYOF_UNICODE_ALL) {
755 cl->flags |= ANYOF_UNICODE_ALL;
756 cl->flags &= ~ANYOF_UNICODE;
760 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
761 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
762 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
763 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
769 dump_trie_interim_list(trie,next_alloc)
770 dump_trie_interim_table(trie,next_alloc)
772 These routines dump out a trie in a somewhat readable format.
773 The _interim_ variants are used for debugging the interim
774 tables that are used to generate the final compressed
775 representation which is what dump_trie expects.
777 Part of the reason for their existance is to provide a form
778 of documentation as to how the different representations function.
784 Dumps the final compressed table form of the trie to Perl_debug_log.
785 Used for debugging make_trie().
789 S_dump_trie(pTHX_ const struct _reg_trie_data *trie,U32 depth)
792 SV *sv=sv_newmortal();
793 int colwidth= trie->widecharmap ? 6 : 4;
794 GET_RE_DEBUG_FLAGS_DECL;
797 PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
798 (int)depth * 2 + 2,"",
799 "Match","Base","Ofs" );
801 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
802 SV ** const tmp = av_fetch( trie->revcharmap, state, 0);
804 PerlIO_printf( Perl_debug_log, "%*s",
806 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
807 PL_colors[0], PL_colors[1],
808 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
809 PERL_PV_ESCAPE_FIRSTCHAR
814 PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
815 (int)depth * 2 + 2,"");
817 for( state = 0 ; state < trie->uniquecharcount ; state++ )
818 PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
819 PerlIO_printf( Perl_debug_log, "\n");
821 for( state = 1 ; state < trie->laststate ; state++ ) {
822 const U32 base = trie->states[ state ].trans.base;
824 PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
826 if ( trie->states[ state ].wordnum ) {
827 PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
829 PerlIO_printf( Perl_debug_log, "%6s", "" );
832 PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
837 while( ( base + ofs < trie->uniquecharcount ) ||
838 ( base + ofs - trie->uniquecharcount < trie->lasttrans
839 && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
842 PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
844 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
845 if ( ( base + ofs >= trie->uniquecharcount ) &&
846 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
847 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
849 PerlIO_printf( Perl_debug_log, "%*"UVXf,
851 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
853 PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
857 PerlIO_printf( Perl_debug_log, "]");
860 PerlIO_printf( Perl_debug_log, "\n" );
864 dump_trie_interim_list(trie,next_alloc)
865 Dumps a fully constructed but uncompressed trie in list form.
866 List tries normally only are used for construction when the number of
867 possible chars (trie->uniquecharcount) is very high.
868 Used for debugging make_trie().
871 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie, U32 next_alloc,U32 depth)
874 SV *sv=sv_newmortal();
875 int colwidth= trie->widecharmap ? 6 : 4;
876 GET_RE_DEBUG_FLAGS_DECL;
877 /* print out the table precompression. */
878 PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
879 (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
880 "------:-----+-----------------\n" );
882 for( state=1 ; state < next_alloc ; state ++ ) {
885 PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
886 (int)depth * 2 + 2,"", (UV)state );
887 if ( ! trie->states[ state ].wordnum ) {
888 PerlIO_printf( Perl_debug_log, "%5s| ","");
890 PerlIO_printf( Perl_debug_log, "W%4x| ",
891 trie->states[ state ].wordnum
894 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
895 SV ** const tmp = av_fetch( trie->revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
897 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
899 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
900 PL_colors[0], PL_colors[1],
901 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
902 PERL_PV_ESCAPE_FIRSTCHAR
904 TRIE_LIST_ITEM(state,charid).forid,
905 (UV)TRIE_LIST_ITEM(state,charid).newstate
909 PerlIO_printf( Perl_debug_log, "\n");
914 dump_trie_interim_table(trie,next_alloc)
915 Dumps a fully constructed but uncompressed trie in table form.
916 This is the normal DFA style state transition table, with a few
917 twists to facilitate compression later.
918 Used for debugging make_trie().
921 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie, U32 next_alloc, U32 depth)
925 SV *sv=sv_newmortal();
926 int colwidth= trie->widecharmap ? 6 : 4;
927 GET_RE_DEBUG_FLAGS_DECL;
930 print out the table precompression so that we can do a visual check
931 that they are identical.
934 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
936 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
937 SV ** const tmp = av_fetch( trie->revcharmap, charid, 0);
939 PerlIO_printf( Perl_debug_log, "%*s",
941 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
942 PL_colors[0], PL_colors[1],
943 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
944 PERL_PV_ESCAPE_FIRSTCHAR
950 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
952 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
953 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
956 PerlIO_printf( Perl_debug_log, "\n" );
958 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
960 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
961 (int)depth * 2 + 2,"",
962 (UV)TRIE_NODENUM( state ) );
964 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
965 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
967 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
969 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
971 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
972 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
974 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
975 trie->states[ TRIE_NODENUM( state ) ].wordnum );
982 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
983 startbranch: the first branch in the whole branch sequence
984 first : start branch of sequence of branch-exact nodes.
985 May be the same as startbranch
986 last : Thing following the last branch.
987 May be the same as tail.
988 tail : item following the branch sequence
989 count : words in the sequence
990 flags : currently the OP() type we will be building one of /EXACT(|F|Fl)/
993 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
995 A trie is an N'ary tree where the branches are determined by digital
996 decomposition of the key. IE, at the root node you look up the 1st character and
997 follow that branch repeat until you find the end of the branches. Nodes can be
998 marked as "accepting" meaning they represent a complete word. Eg:
1002 would convert into the following structure. Numbers represent states, letters
1003 following numbers represent valid transitions on the letter from that state, if
1004 the number is in square brackets it represents an accepting state, otherwise it
1005 will be in parenthesis.
1007 +-h->+-e->[3]-+-r->(8)-+-s->[9]
1011 (1) +-i->(6)-+-s->[7]
1013 +-s->(3)-+-h->(4)-+-e->[5]
1015 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1017 This shows that when matching against the string 'hers' we will begin at state 1
1018 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1019 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1020 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1021 single traverse. We store a mapping from accepting to state to which word was
1022 matched, and then when we have multiple possibilities we try to complete the
1023 rest of the regex in the order in which they occured in the alternation.
1025 The only prior NFA like behaviour that would be changed by the TRIE support is
1026 the silent ignoring of duplicate alternations which are of the form:
1028 / (DUPE|DUPE) X? (?{ ... }) Y /x
1030 Thus EVAL blocks follwing a trie may be called a different number of times with
1031 and without the optimisation. With the optimisations dupes will be silently
1032 ignored. This inconsistant behaviour of EVAL type nodes is well established as
1033 the following demonstrates:
1035 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1037 which prints out 'word' three times, but
1039 'words'=~/(word|word|word)(?{ print $1 })S/
1041 which doesnt print it out at all. This is due to other optimisations kicking in.
1043 Example of what happens on a structural level:
1045 The regexp /(ac|ad|ab)+/ will produce the folowing debug output:
1047 1: CURLYM[1] {1,32767}(18)
1058 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1059 and should turn into:
1061 1: CURLYM[1] {1,32767}(18)
1063 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1071 Cases where tail != last would be like /(?foo|bar)baz/:
1081 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1082 and would end up looking like:
1085 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1092 d = uvuni_to_utf8_flags(d, uv, 0);
1094 is the recommended Unicode-aware way of saying
1099 #define TRIE_STORE_REVCHAR \
1101 SV *tmp = Perl_newSVpvf_nocontext( "%c", (int)uvc ); \
1102 if (UTF) SvUTF8_on(tmp); \
1103 av_push( TRIE_REVCHARMAP(trie), tmp ); \
1106 #define TRIE_READ_CHAR STMT_START { \
1110 if ( foldlen > 0 ) { \
1111 uvc = utf8n_to_uvuni( scan, UTF8_MAXLEN, &len, uniflags ); \
1116 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1117 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1118 foldlen -= UNISKIP( uvc ); \
1119 scan = foldbuf + UNISKIP( uvc ); \
1122 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1132 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
1133 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
1134 TRIE_LIST_LEN( state ) *= 2; \
1135 Renew( trie->states[ state ].trans.list, \
1136 TRIE_LIST_LEN( state ), reg_trie_trans_le ); \
1138 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
1139 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
1140 TRIE_LIST_CUR( state )++; \
1143 #define TRIE_LIST_NEW(state) STMT_START { \
1144 Newxz( trie->states[ state ].trans.list, \
1145 4, reg_trie_trans_le ); \
1146 TRIE_LIST_CUR( state ) = 1; \
1147 TRIE_LIST_LEN( state ) = 4; \
1150 #define TRIE_HANDLE_WORD(state) STMT_START { \
1151 U16 dupe= trie->states[ state ].wordnum; \
1152 regnode * const noper_next = regnext( noper ); \
1154 if (trie->wordlen) \
1155 trie->wordlen[ curword ] = wordlen; \
1157 /* store the word for dumping */ \
1159 if (OP(noper) != NOTHING) \
1160 tmp = newSVpvn(STRING(noper), STR_LEN(noper)); \
1162 tmp = newSVpvn( "", 0 ); \
1163 if ( UTF ) SvUTF8_on( tmp ); \
1164 av_push( trie->words, tmp ); \
1169 if ( noper_next < tail ) { \
1171 Newxz( trie->jump, word_count + 1, U16); \
1172 trie->jump[curword] = (U16)(tail - noper_next); \
1174 jumper = noper_next; \
1176 nextbranch= regnext(cur); \
1180 /* So it's a dupe. This means we need to maintain a */\
1181 /* linked-list from the first to the next. */\
1182 /* we only allocate the nextword buffer when there */\
1183 /* a dupe, so first time we have to do the allocation */\
1184 if (!trie->nextword) \
1185 Newxz( trie->nextword, word_count + 1, U16); \
1186 while ( trie->nextword[dupe] ) \
1187 dupe= trie->nextword[dupe]; \
1188 trie->nextword[dupe]= curword; \
1190 /* we haven't inserted this word yet. */ \
1191 trie->states[ state ].wordnum = curword; \
1196 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
1197 ( ( base + charid >= ucharcount \
1198 && base + charid < ubound \
1199 && state == trie->trans[ base - ucharcount + charid ].check \
1200 && trie->trans[ base - ucharcount + charid ].next ) \
1201 ? trie->trans[ base - ucharcount + charid ].next \
1202 : ( state==1 ? special : 0 ) \
1206 #define MADE_JUMP_TRIE 2
1207 #define MADE_EXACT_TRIE 4
1210 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
1213 /* first pass, loop through and scan words */
1214 reg_trie_data *trie;
1216 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1221 regnode *jumper = NULL;
1222 regnode *nextbranch = NULL;
1223 /* we just use folder as a flag in utf8 */
1224 const U8 * const folder = ( flags == EXACTF
1226 : ( flags == EXACTFL
1232 const U32 data_slot = add_data( pRExC_state, 1, "t" );
1233 SV *re_trie_maxbuff;
1235 /* these are only used during construction but are useful during
1236 * debugging so we store them in the struct when debugging.
1238 STRLEN trie_charcount=0;
1239 AV *trie_revcharmap;
1241 GET_RE_DEBUG_FLAGS_DECL;
1243 PERL_UNUSED_ARG(depth);
1246 Newxz( trie, 1, reg_trie_data );
1248 trie->startstate = 1;
1249 trie->wordcount = word_count;
1250 RExC_rx->data->data[ data_slot ] = (void*)trie;
1251 Newxz( trie->charmap, 256, U16 );
1252 if (!(UTF && folder))
1253 Newxz( trie->bitmap, ANYOF_BITMAP_SIZE, char );
1255 trie->words = newAV();
1257 TRIE_REVCHARMAP(trie) = newAV();
1259 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
1260 if (!SvIOK(re_trie_maxbuff)) {
1261 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
1264 PerlIO_printf( Perl_debug_log,
1265 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
1266 (int)depth * 2 + 2, "",
1267 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
1268 REG_NODE_NUM(last), REG_NODE_NUM(tail),
1271 /* -- First loop and Setup --
1273 We first traverse the branches and scan each word to determine if it
1274 contains widechars, and how many unique chars there are, this is
1275 important as we have to build a table with at least as many columns as we
1278 We use an array of integers to represent the character codes 0..255
1279 (trie->charmap) and we use a an HV* to store unicode characters. We use the
1280 native representation of the character value as the key and IV's for the
1283 *TODO* If we keep track of how many times each character is used we can
1284 remap the columns so that the table compression later on is more
1285 efficient in terms of memory by ensuring most common value is in the
1286 middle and the least common are on the outside. IMO this would be better
1287 than a most to least common mapping as theres a decent chance the most
1288 common letter will share a node with the least common, meaning the node
1289 will not be compressable. With a middle is most common approach the worst
1290 case is when we have the least common nodes twice.
1294 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1295 regnode * const noper = NEXTOPER( cur );
1296 const U8 *uc = (U8*)STRING( noper );
1297 const U8 * const e = uc + STR_LEN( noper );
1299 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1300 const U8 *scan = (U8*)NULL;
1301 U32 wordlen = 0; /* required init */
1304 if (OP(noper) == NOTHING) {
1309 TRIE_BITMAP_SET(trie,*uc);
1310 if ( folder ) TRIE_BITMAP_SET(trie,folder[ *uc ]);
1312 for ( ; uc < e ; uc += len ) {
1313 TRIE_CHARCOUNT(trie)++;
1317 if ( !trie->charmap[ uvc ] ) {
1318 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1320 trie->charmap[ folder[ uvc ] ] = trie->charmap[ uvc ];
1325 if ( !trie->widecharmap )
1326 trie->widecharmap = newHV();
1328 svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 1 );
1331 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
1333 if ( !SvTRUE( *svpp ) ) {
1334 sv_setiv( *svpp, ++trie->uniquecharcount );
1339 if( cur == first ) {
1342 } else if (chars < trie->minlen) {
1344 } else if (chars > trie->maxlen) {
1348 } /* end first pass */
1349 DEBUG_TRIE_COMPILE_r(
1350 PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1351 (int)depth * 2 + 2,"",
1352 ( trie->widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
1353 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1354 (int)trie->minlen, (int)trie->maxlen )
1356 Newxz( trie->wordlen, word_count, U32 );
1359 We now know what we are dealing with in terms of unique chars and
1360 string sizes so we can calculate how much memory a naive
1361 representation using a flat table will take. If it's over a reasonable
1362 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
1363 conservative but potentially much slower representation using an array
1366 At the end we convert both representations into the same compressed
1367 form that will be used in regexec.c for matching with. The latter
1368 is a form that cannot be used to construct with but has memory
1369 properties similar to the list form and access properties similar
1370 to the table form making it both suitable for fast searches and
1371 small enough that its feasable to store for the duration of a program.
1373 See the comment in the code where the compressed table is produced
1374 inplace from the flat tabe representation for an explanation of how
1375 the compression works.
1380 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
1382 Second Pass -- Array Of Lists Representation
1384 Each state will be represented by a list of charid:state records
1385 (reg_trie_trans_le) the first such element holds the CUR and LEN
1386 points of the allocated array. (See defines above).
1388 We build the initial structure using the lists, and then convert
1389 it into the compressed table form which allows faster lookups
1390 (but cant be modified once converted).
1393 STRLEN transcount = 1;
1395 Newxz( trie->states, TRIE_CHARCOUNT(trie) + 2, reg_trie_state );
1399 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1401 regnode * const noper = NEXTOPER( cur );
1402 U8 *uc = (U8*)STRING( noper );
1403 const U8 * const e = uc + STR_LEN( noper );
1404 U32 state = 1; /* required init */
1405 U16 charid = 0; /* sanity init */
1406 U8 *scan = (U8*)NULL; /* sanity init */
1407 STRLEN foldlen = 0; /* required init */
1408 U32 wordlen = 0; /* required init */
1409 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1411 if (OP(noper) != NOTHING) {
1412 for ( ; uc < e ; uc += len ) {
1417 charid = trie->charmap[ uvc ];
1419 SV** const svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 0);
1423 charid=(U16)SvIV( *svpp );
1426 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1433 if ( !trie->states[ state ].trans.list ) {
1434 TRIE_LIST_NEW( state );
1436 for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1437 if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1438 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1443 newstate = next_alloc++;
1444 TRIE_LIST_PUSH( state, charid, newstate );
1449 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1453 TRIE_HANDLE_WORD(state);
1455 } /* end second pass */
1457 trie->laststate = next_alloc;
1458 Renew( trie->states, next_alloc, reg_trie_state );
1460 /* and now dump it out before we compress it */
1461 DEBUG_TRIE_COMPILE_MORE_r(
1462 dump_trie_interim_list(trie,next_alloc,depth+1)
1465 Newxz( trie->trans, transcount ,reg_trie_trans );
1472 for( state=1 ; state < next_alloc ; state ++ ) {
1476 DEBUG_TRIE_COMPILE_MORE_r(
1477 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1481 if (trie->states[state].trans.list) {
1482 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1486 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1487 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1488 if ( forid < minid ) {
1490 } else if ( forid > maxid ) {
1494 if ( transcount < tp + maxid - minid + 1) {
1496 Renew( trie->trans, transcount, reg_trie_trans );
1497 Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1499 base = trie->uniquecharcount + tp - minid;
1500 if ( maxid == minid ) {
1502 for ( ; zp < tp ; zp++ ) {
1503 if ( ! trie->trans[ zp ].next ) {
1504 base = trie->uniquecharcount + zp - minid;
1505 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1506 trie->trans[ zp ].check = state;
1512 trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1513 trie->trans[ tp ].check = state;
1518 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1519 const U32 tid = base - trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
1520 trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1521 trie->trans[ tid ].check = state;
1523 tp += ( maxid - minid + 1 );
1525 Safefree(trie->states[ state ].trans.list);
1528 DEBUG_TRIE_COMPILE_MORE_r(
1529 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1532 trie->states[ state ].trans.base=base;
1534 trie->lasttrans = tp + 1;
1538 Second Pass -- Flat Table Representation.
1540 we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1541 We know that we will need Charcount+1 trans at most to store the data
1542 (one row per char at worst case) So we preallocate both structures
1543 assuming worst case.
1545 We then construct the trie using only the .next slots of the entry
1548 We use the .check field of the first entry of the node temporarily to
1549 make compression both faster and easier by keeping track of how many non
1550 zero fields are in the node.
1552 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1555 There are two terms at use here: state as a TRIE_NODEIDX() which is a
1556 number representing the first entry of the node, and state as a
1557 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1558 TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1559 are 2 entrys per node. eg:
1567 The table is internally in the right hand, idx form. However as we also
1568 have to deal with the states array which is indexed by nodenum we have to
1569 use TRIE_NODENUM() to convert.
1574 Newxz( trie->trans, ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1,
1576 Newxz( trie->states, TRIE_CHARCOUNT(trie) + 2, reg_trie_state );
1577 next_alloc = trie->uniquecharcount + 1;
1580 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1582 regnode * const noper = NEXTOPER( cur );
1583 const U8 *uc = (U8*)STRING( noper );
1584 const U8 * const e = uc + STR_LEN( noper );
1586 U32 state = 1; /* required init */
1588 U16 charid = 0; /* sanity init */
1589 U32 accept_state = 0; /* sanity init */
1590 U8 *scan = (U8*)NULL; /* sanity init */
1592 STRLEN foldlen = 0; /* required init */
1593 U32 wordlen = 0; /* required init */
1594 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1596 if ( OP(noper) != NOTHING ) {
1597 for ( ; uc < e ; uc += len ) {
1602 charid = trie->charmap[ uvc ];
1604 SV* const * const svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 0);
1605 charid = svpp ? (U16)SvIV(*svpp) : 0;
1609 if ( !trie->trans[ state + charid ].next ) {
1610 trie->trans[ state + charid ].next = next_alloc;
1611 trie->trans[ state ].check++;
1612 next_alloc += trie->uniquecharcount;
1614 state = trie->trans[ state + charid ].next;
1616 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1618 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1621 accept_state = TRIE_NODENUM( state );
1622 TRIE_HANDLE_WORD(accept_state);
1624 } /* end second pass */
1626 /* and now dump it out before we compress it */
1627 DEBUG_TRIE_COMPILE_MORE_r(
1628 dump_trie_interim_table(trie,next_alloc,depth+1)
1633 * Inplace compress the table.*
1635 For sparse data sets the table constructed by the trie algorithm will
1636 be mostly 0/FAIL transitions or to put it another way mostly empty.
1637 (Note that leaf nodes will not contain any transitions.)
1639 This algorithm compresses the tables by eliminating most such
1640 transitions, at the cost of a modest bit of extra work during lookup:
1642 - Each states[] entry contains a .base field which indicates the
1643 index in the state[] array wheres its transition data is stored.
1645 - If .base is 0 there are no valid transitions from that node.
1647 - If .base is nonzero then charid is added to it to find an entry in
1650 -If trans[states[state].base+charid].check!=state then the
1651 transition is taken to be a 0/Fail transition. Thus if there are fail
1652 transitions at the front of the node then the .base offset will point
1653 somewhere inside the previous nodes data (or maybe even into a node
1654 even earlier), but the .check field determines if the transition is
1658 The following process inplace converts the table to the compressed
1659 table: We first do not compress the root node 1,and mark its all its
1660 .check pointers as 1 and set its .base pointer as 1 as well. This
1661 allows to do a DFA construction from the compressed table later, and
1662 ensures that any .base pointers we calculate later are greater than
1665 - We set 'pos' to indicate the first entry of the second node.
1667 - We then iterate over the columns of the node, finding the first and
1668 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
1669 and set the .check pointers accordingly, and advance pos
1670 appropriately and repreat for the next node. Note that when we copy
1671 the next pointers we have to convert them from the original
1672 NODEIDX form to NODENUM form as the former is not valid post
1675 - If a node has no transitions used we mark its base as 0 and do not
1676 advance the pos pointer.
1678 - If a node only has one transition we use a second pointer into the
1679 structure to fill in allocated fail transitions from other states.
1680 This pointer is independent of the main pointer and scans forward
1681 looking for null transitions that are allocated to a state. When it
1682 finds one it writes the single transition into the "hole". If the
1683 pointer doesnt find one the single transition is appended as normal.
1685 - Once compressed we can Renew/realloc the structures to release the
1688 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
1689 specifically Fig 3.47 and the associated pseudocode.
1693 const U32 laststate = TRIE_NODENUM( next_alloc );
1696 trie->laststate = laststate;
1698 for ( state = 1 ; state < laststate ; state++ ) {
1700 const U32 stateidx = TRIE_NODEIDX( state );
1701 const U32 o_used = trie->trans[ stateidx ].check;
1702 U32 used = trie->trans[ stateidx ].check;
1703 trie->trans[ stateidx ].check = 0;
1705 for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
1706 if ( flag || trie->trans[ stateidx + charid ].next ) {
1707 if ( trie->trans[ stateidx + charid ].next ) {
1709 for ( ; zp < pos ; zp++ ) {
1710 if ( ! trie->trans[ zp ].next ) {
1714 trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
1715 trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1716 trie->trans[ zp ].check = state;
1717 if ( ++zp > pos ) pos = zp;
1724 trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
1726 trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1727 trie->trans[ pos ].check = state;
1732 trie->lasttrans = pos + 1;
1733 Renew( trie->states, laststate + 1, reg_trie_state);
1734 DEBUG_TRIE_COMPILE_MORE_r(
1735 PerlIO_printf( Perl_debug_log,
1736 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
1737 (int)depth * 2 + 2,"",
1738 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
1741 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
1744 } /* end table compress */
1746 /* resize the trans array to remove unused space */
1747 Renew( trie->trans, trie->lasttrans, reg_trie_trans);
1749 /* and now dump out the compressed format */
1750 DEBUG_TRIE_COMPILE_r(
1751 dump_trie(trie,depth+1)
1754 { /* Modify the program and insert the new TRIE node*/
1756 U8 nodetype =(U8)(flags & 0xFF);
1762 U32 mjd_nodelen = 0;
1765 This means we convert either the first branch or the first Exact,
1766 depending on whether the thing following (in 'last') is a branch
1767 or not and whther first is the startbranch (ie is it a sub part of
1768 the alternation or is it the whole thing.)
1769 Assuming its a sub part we conver the EXACT otherwise we convert
1770 the whole branch sequence, including the first.
1772 /* Find the node we are going to overwrite */
1773 if ( first == startbranch && OP( last ) != BRANCH ) {
1774 /* whole branch chain */
1777 const regnode *nop = NEXTOPER( convert );
1778 mjd_offset= Node_Offset((nop));
1779 mjd_nodelen= Node_Length((nop));
1782 /* branch sub-chain */
1783 convert = NEXTOPER( first );
1784 NEXT_OFF( first ) = (U16)(last - first);
1786 mjd_offset= Node_Offset((convert));
1787 mjd_nodelen= Node_Length((convert));
1791 PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
1792 (int)depth * 2 + 2, "",
1793 (UV)mjd_offset, (UV)mjd_nodelen)
1796 /* But first we check to see if there is a common prefix we can
1797 split out as an EXACT and put in front of the TRIE node. */
1798 trie->startstate= 1;
1799 if ( trie->bitmap && !trie->widecharmap && !trie->jump ) {
1802 PerlIO_printf(Perl_debug_log, "%*sLaststate:%"UVuf"\n",
1803 (int)depth * 2 + 2, "",
1804 (UV)trie->laststate)
1806 for ( state = 1 ; state < trie->laststate-1 ; state++ ) {
1810 const U32 base = trie->states[ state ].trans.base;
1812 if ( trie->states[state].wordnum )
1815 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1816 if ( ( base + ofs >= trie->uniquecharcount ) &&
1817 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
1818 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
1820 if ( ++count > 1 ) {
1821 SV **tmp = av_fetch( TRIE_REVCHARMAP(trie), ofs, 0);
1822 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
1823 if ( state == 1 ) break;
1825 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
1827 PerlIO_printf(Perl_debug_log,
1828 "%*sNew Start State=%"UVuf" Class: [",
1829 (int)depth * 2 + 2, "",
1832 SV ** const tmp = av_fetch( TRIE_REVCHARMAP(trie), idx, 0);
1833 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
1835 TRIE_BITMAP_SET(trie,*ch);
1837 TRIE_BITMAP_SET(trie, folder[ *ch ]);
1839 PerlIO_printf(Perl_debug_log, (char*)ch)
1843 TRIE_BITMAP_SET(trie,*ch);
1845 TRIE_BITMAP_SET(trie,folder[ *ch ]);
1846 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
1852 SV **tmp = av_fetch( TRIE_REVCHARMAP(trie), idx, 0);
1853 const char *ch = SvPV_nolen_const( *tmp );
1855 PerlIO_printf( Perl_debug_log,
1856 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
1857 (int)depth * 2 + 2, "",
1858 (UV)state, (UV)idx, ch)
1861 OP( convert ) = nodetype;
1862 str=STRING(convert);
1871 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
1877 regnode *n = convert+NODE_SZ_STR(convert);
1878 NEXT_OFF(convert) = NODE_SZ_STR(convert);
1879 trie->startstate = state;
1880 trie->minlen -= (state - 1);
1881 trie->maxlen -= (state - 1);
1883 regnode *fix = convert;
1885 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
1886 while( ++fix < n ) {
1887 Set_Node_Offset_Length(fix, 0, 0);
1893 NEXT_OFF(convert) = (U16)(tail - convert);
1894 DEBUG_r(optimize= n);
1900 if ( trie->maxlen ) {
1901 NEXT_OFF( convert ) = (U16)(tail - convert);
1902 ARG_SET( convert, data_slot );
1903 /* Store the offset to the first unabsorbed branch in
1904 jump[0], which is otherwise unused by the jump logic.
1905 We use this when dumping a trie and during optimisation. */
1907 trie->jump[0] = (U16)(tail - nextbranch);
1910 if ( !trie->states[trie->startstate].wordnum && trie->bitmap &&
1911 ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
1913 OP( convert ) = TRIEC;
1914 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
1915 Safefree(trie->bitmap);
1918 OP( convert ) = TRIE;
1920 /* store the type in the flags */
1921 convert->flags = nodetype;
1925 + regarglen[ OP( convert ) ];
1927 /* XXX We really should free up the resource in trie now,
1928 as we won't use them - (which resources?) dmq */
1930 /* needed for dumping*/
1932 regnode *opt = convert;
1933 while (++opt<optimize) {
1934 Set_Node_Offset_Length(opt,0,0);
1937 Try to clean up some of the debris left after the
1940 while( optimize < jumper ) {
1941 mjd_nodelen += Node_Length((optimize));
1942 OP( optimize ) = OPTIMIZED;
1943 Set_Node_Offset_Length(optimize,0,0);
1946 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
1948 } /* end node insert */
1950 SvREFCNT_dec(TRIE_REVCHARMAP(trie));
1954 : trie->startstate>1
1960 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source, regnode *stclass, U32 depth)
1962 /* The Trie is constructed and compressed now so we can build a fail array now if its needed
1964 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
1965 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
1968 We find the fail state for each state in the trie, this state is the longest proper
1969 suffix of the current states 'word' that is also a proper prefix of another word in our
1970 trie. State 1 represents the word '' and is the thus the default fail state. This allows
1971 the DFA not to have to restart after its tried and failed a word at a given point, it
1972 simply continues as though it had been matching the other word in the first place.
1974 'abcdgu'=~/abcdefg|cdgu/
1975 When we get to 'd' we are still matching the first word, we would encounter 'g' which would
1976 fail, which would bring use to the state representing 'd' in the second word where we would
1977 try 'g' and succeed, prodceding to match 'cdgu'.
1979 /* add a fail transition */
1980 reg_trie_data *trie=(reg_trie_data *)RExC_rx->data->data[ARG(source)];
1982 const U32 ucharcount = trie->uniquecharcount;
1983 const U32 numstates = trie->laststate;
1984 const U32 ubound = trie->lasttrans + ucharcount;
1988 U32 base = trie->states[ 1 ].trans.base;
1991 const U32 data_slot = add_data( pRExC_state, 1, "T" );
1992 GET_RE_DEBUG_FLAGS_DECL;
1994 PERL_UNUSED_ARG(depth);
1998 ARG_SET( stclass, data_slot );
1999 Newxz( aho, 1, reg_ac_data );
2000 RExC_rx->data->data[ data_slot ] = (void*)aho;
2002 aho->states=(reg_trie_state *)savepvn((const char*)trie->states,
2003 (trie->laststate+1)*sizeof(reg_trie_state));
2004 Newxz( q, numstates, U32);
2005 Newxz( aho->fail, numstates, U32 );
2008 /* initialize fail[0..1] to be 1 so that we always have
2009 a valid final fail state */
2010 fail[ 0 ] = fail[ 1 ] = 1;
2012 for ( charid = 0; charid < ucharcount ; charid++ ) {
2013 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2015 q[ q_write ] = newstate;
2016 /* set to point at the root */
2017 fail[ q[ q_write++ ] ]=1;
2020 while ( q_read < q_write) {
2021 const U32 cur = q[ q_read++ % numstates ];
2022 base = trie->states[ cur ].trans.base;
2024 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2025 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2027 U32 fail_state = cur;
2030 fail_state = fail[ fail_state ];
2031 fail_base = aho->states[ fail_state ].trans.base;
2032 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2034 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2035 fail[ ch_state ] = fail_state;
2036 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2038 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
2040 q[ q_write++ % numstates] = ch_state;
2044 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2045 when we fail in state 1, this allows us to use the
2046 charclass scan to find a valid start char. This is based on the principle
2047 that theres a good chance the string being searched contains lots of stuff
2048 that cant be a start char.
2050 fail[ 0 ] = fail[ 1 ] = 0;
2051 DEBUG_TRIE_COMPILE_r({
2052 PerlIO_printf(Perl_debug_log, "%*sStclass Failtable: 0", (int)(depth * 2), "");
2053 for( q_read=1; q_read<numstates; q_read++ ) {
2054 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2056 PerlIO_printf(Perl_debug_log, "\n");
2059 /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2064 * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2065 * These need to be revisited when a newer toolchain becomes available.
2067 #if defined(__sparc64__) && defined(__GNUC__)
2068 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2069 # undef SPARC64_GCC_WORKAROUND
2070 # define SPARC64_GCC_WORKAROUND 1
2074 #define DEBUG_PEEP(str,scan,depth) \
2075 DEBUG_OPTIMISE_r({ \
2076 SV * const mysv=sv_newmortal(); \
2077 regnode *Next = regnext(scan); \
2078 regprop(RExC_rx, mysv, scan); \
2079 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s [%d]\n", \
2080 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2081 Next ? (REG_NODE_NUM(Next)) : 0 ); \
2088 #define JOIN_EXACT(scan,min,flags) \
2089 if (PL_regkind[OP(scan)] == EXACT) \
2090 join_exact(pRExC_state,(scan),(min),(flags),NULL,depth+1)
2093 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, I32 *min, U32 flags,regnode *val, U32 depth) {
2094 /* Merge several consecutive EXACTish nodes into one. */
2095 regnode *n = regnext(scan);
2097 regnode *next = scan + NODE_SZ_STR(scan);
2101 regnode *stop = scan;
2102 GET_RE_DEBUG_FLAGS_DECL;
2104 PERL_UNUSED_ARG(depth);
2106 #ifndef EXPERIMENTAL_INPLACESCAN
2107 PERL_UNUSED_ARG(flags);
2108 PERL_UNUSED_ARG(val);
2110 DEBUG_PEEP("join",scan,depth);
2112 /* Skip NOTHING, merge EXACT*. */
2114 ( PL_regkind[OP(n)] == NOTHING ||
2115 (stringok && (OP(n) == OP(scan))))
2117 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
2119 if (OP(n) == TAIL || n > next)
2121 if (PL_regkind[OP(n)] == NOTHING) {
2122 DEBUG_PEEP("skip:",n,depth);
2123 NEXT_OFF(scan) += NEXT_OFF(n);
2124 next = n + NODE_STEP_REGNODE;
2131 else if (stringok) {
2132 const unsigned int oldl = STR_LEN(scan);
2133 regnode * const nnext = regnext(n);
2135 DEBUG_PEEP("merg",n,depth);
2138 if (oldl + STR_LEN(n) > U8_MAX)
2140 NEXT_OFF(scan) += NEXT_OFF(n);
2141 STR_LEN(scan) += STR_LEN(n);
2142 next = n + NODE_SZ_STR(n);
2143 /* Now we can overwrite *n : */
2144 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2152 #ifdef EXPERIMENTAL_INPLACESCAN
2153 if (flags && !NEXT_OFF(n)) {
2154 DEBUG_PEEP("atch", val, depth);
2155 if (reg_off_by_arg[OP(n)]) {
2156 ARG_SET(n, val - n);
2159 NEXT_OFF(n) = val - n;
2166 if (UTF && ( OP(scan) == EXACTF ) && ( STR_LEN(scan) >= 6 ) ) {
2168 Two problematic code points in Unicode casefolding of EXACT nodes:
2170 U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2171 U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2177 U+03B9 U+0308 U+0301 0xCE 0xB9 0xCC 0x88 0xCC 0x81
2178 U+03C5 U+0308 U+0301 0xCF 0x85 0xCC 0x88 0xCC 0x81
2180 This means that in case-insensitive matching (or "loose matching",
2181 as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte
2182 length of the above casefolded versions) can match a target string
2183 of length two (the byte length of UTF-8 encoded U+0390 or U+03B0).
2184 This would rather mess up the minimum length computation.
2186 What we'll do is to look for the tail four bytes, and then peek
2187 at the preceding two bytes to see whether we need to decrease
2188 the minimum length by four (six minus two).
2190 Thanks to the design of UTF-8, there cannot be false matches:
2191 A sequence of valid UTF-8 bytes cannot be a subsequence of
2192 another valid sequence of UTF-8 bytes.
2195 char * const s0 = STRING(scan), *s, *t;
2196 char * const s1 = s0 + STR_LEN(scan) - 1;
2197 char * const s2 = s1 - 4;
2198 #ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2199 const char t0[] = "\xaf\x49\xaf\x42";
2201 const char t0[] = "\xcc\x88\xcc\x81";
2203 const char * const t1 = t0 + 3;
2206 s < s2 && (t = ninstr(s, s1, t0, t1));
2209 if (((U8)t[-1] == 0x68 && (U8)t[-2] == 0xB4) ||
2210 ((U8)t[-1] == 0x46 && (U8)t[-2] == 0xB5))
2212 if (((U8)t[-1] == 0xB9 && (U8)t[-2] == 0xCE) ||
2213 ((U8)t[-1] == 0x85 && (U8)t[-2] == 0xCF))
2221 n = scan + NODE_SZ_STR(scan);
2223 if (PL_regkind[OP(n)] != NOTHING || OP(n) == NOTHING) {
2230 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2234 /* REx optimizer. Converts nodes into quickier variants "in place".
2235 Finds fixed substrings. */
2237 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
2238 to the position after last scanned or to NULL. */
2243 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
2244 I32 *minlenp, I32 *deltap,
2245 regnode *last, scan_data_t *data, U32 flags, U32 depth)
2246 /* scanp: Start here (read-write). */
2247 /* deltap: Write maxlen-minlen here. */
2248 /* last: Stop before this one. */
2251 I32 min = 0, pars = 0, code;
2252 regnode *scan = *scanp, *next;
2254 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
2255 int is_inf_internal = 0; /* The studied chunk is infinite */
2256 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2257 scan_data_t data_fake;
2258 struct regnode_charclass_class and_with; /* Valid if flags & SCF_DO_STCLASS_OR */
2259 SV *re_trie_maxbuff = NULL;
2260 regnode *first_non_open = scan;
2263 GET_RE_DEBUG_FLAGS_DECL;
2265 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
2268 while (first_non_open && OP(first_non_open) == OPEN)
2269 first_non_open=regnext(first_non_open);
2273 while (scan && OP(scan) != END && scan < last) {
2274 /* Peephole optimizer: */
2275 DEBUG_STUDYDATA(data,depth);
2276 DEBUG_PEEP("Peep",scan,depth);
2277 JOIN_EXACT(scan,&min,0);
2279 /* Follow the next-chain of the current node and optimize
2280 away all the NOTHINGs from it. */
2281 if (OP(scan) != CURLYX) {
2282 const int max = (reg_off_by_arg[OP(scan)]
2284 /* I32 may be smaller than U16 on CRAYs! */
2285 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
2286 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
2290 /* Skip NOTHING and LONGJMP. */
2291 while ((n = regnext(n))
2292 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
2293 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
2294 && off + noff < max)
2296 if (reg_off_by_arg[OP(scan)])
2299 NEXT_OFF(scan) = off;
2304 /* The principal pseudo-switch. Cannot be a switch, since we
2305 look into several different things. */
2306 if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
2307 || OP(scan) == IFTHEN || OP(scan) == SUSPEND) {
2308 next = regnext(scan);
2310 /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
2312 if (OP(next) == code || code == IFTHEN || code == SUSPEND) {
2313 /* NOTE - There is similar code to this block below for handling
2314 TRIE nodes on a re-study. If you change stuff here check there
2316 I32 max1 = 0, min1 = I32_MAX, num = 0;
2317 struct regnode_charclass_class accum;
2318 regnode * const startbranch=scan;
2320 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
2321 scan_commit(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
2322 if (flags & SCF_DO_STCLASS)
2323 cl_init_zero(pRExC_state, &accum);
2325 while (OP(scan) == code) {
2326 I32 deltanext, minnext, f = 0, fake;
2327 struct regnode_charclass_class this_class;
2330 data_fake.flags = 0;
2332 data_fake.whilem_c = data->whilem_c;
2333 data_fake.last_closep = data->last_closep;
2336 data_fake.last_closep = &fake;
2337 next = regnext(scan);
2338 scan = NEXTOPER(scan);
2340 scan = NEXTOPER(scan);
2341 if (flags & SCF_DO_STCLASS) {
2342 cl_init(pRExC_state, &this_class);
2343 data_fake.start_class = &this_class;
2344 f = SCF_DO_STCLASS_AND;
2346 if (flags & SCF_WHILEM_VISITED_POS)
2347 f |= SCF_WHILEM_VISITED_POS;
2349 /* we suppose the run is continuous, last=next...*/
2350 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2351 next, &data_fake, f,depth+1);
2354 if (max1 < minnext + deltanext)
2355 max1 = minnext + deltanext;
2356 if (deltanext == I32_MAX)
2357 is_inf = is_inf_internal = 1;
2359 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
2362 if (data_fake.flags & SF_HAS_EVAL)
2363 data->flags |= SF_HAS_EVAL;
2364 data->whilem_c = data_fake.whilem_c;
2366 if (flags & SCF_DO_STCLASS)
2367 cl_or(pRExC_state, &accum, &this_class);
2368 if (code == SUSPEND)
2371 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
2373 if (flags & SCF_DO_SUBSTR) {
2374 data->pos_min += min1;
2375 data->pos_delta += max1 - min1;
2376 if (max1 != min1 || is_inf)
2377 data->longest = &(data->longest_float);
2380 delta += max1 - min1;
2381 if (flags & SCF_DO_STCLASS_OR) {
2382 cl_or(pRExC_state, data->start_class, &accum);
2384 cl_and(data->start_class, &and_with);
2385 flags &= ~SCF_DO_STCLASS;
2388 else if (flags & SCF_DO_STCLASS_AND) {
2390 cl_and(data->start_class, &accum);
2391 flags &= ~SCF_DO_STCLASS;
2394 /* Switch to OR mode: cache the old value of
2395 * data->start_class */
2396 StructCopy(data->start_class, &and_with,
2397 struct regnode_charclass_class);
2398 flags &= ~SCF_DO_STCLASS_AND;
2399 StructCopy(&accum, data->start_class,
2400 struct regnode_charclass_class);
2401 flags |= SCF_DO_STCLASS_OR;
2402 data->start_class->flags |= ANYOF_EOS;
2406 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
2409 Assuming this was/is a branch we are dealing with: 'scan' now
2410 points at the item that follows the branch sequence, whatever
2411 it is. We now start at the beginning of the sequence and look
2418 which would be constructed from a pattern like /A|LIST|OF|WORDS/
2420 If we can find such a subseqence we need to turn the first
2421 element into a trie and then add the subsequent branch exact
2422 strings to the trie.
2426 1. patterns where the whole set of branch can be converted.
2428 2. patterns where only a subset can be converted.
2430 In case 1 we can replace the whole set with a single regop
2431 for the trie. In case 2 we need to keep the start and end
2434 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
2435 becomes BRANCH TRIE; BRANCH X;
2437 There is an additional case, that being where there is a
2438 common prefix, which gets split out into an EXACT like node
2439 preceding the TRIE node.
2441 If x(1..n)==tail then we can do a simple trie, if not we make
2442 a "jump" trie, such that when we match the appropriate word
2443 we "jump" to the appopriate tail node. Essentailly we turn
2444 a nested if into a case structure of sorts.
2449 if (!re_trie_maxbuff) {
2450 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2451 if (!SvIOK(re_trie_maxbuff))
2452 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2454 if ( SvIV(re_trie_maxbuff)>=0 ) {
2456 regnode *first = (regnode *)NULL;
2457 regnode *last = (regnode *)NULL;
2458 regnode *tail = scan;
2463 SV * const mysv = sv_newmortal(); /* for dumping */
2465 /* var tail is used because there may be a TAIL
2466 regop in the way. Ie, the exacts will point to the
2467 thing following the TAIL, but the last branch will
2468 point at the TAIL. So we advance tail. If we
2469 have nested (?:) we may have to move through several
2473 while ( OP( tail ) == TAIL ) {
2474 /* this is the TAIL generated by (?:) */
2475 tail = regnext( tail );
2480 regprop(RExC_rx, mysv, tail );
2481 PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
2482 (int)depth * 2 + 2, "",
2483 "Looking for TRIE'able sequences. Tail node is: ",
2484 SvPV_nolen_const( mysv )
2490 step through the branches, cur represents each
2491 branch, noper is the first thing to be matched
2492 as part of that branch and noper_next is the
2493 regnext() of that node. if noper is an EXACT
2494 and noper_next is the same as scan (our current
2495 position in the regex) then the EXACT branch is
2496 a possible optimization target. Once we have
2497 two or more consequetive such branches we can
2498 create a trie of the EXACT's contents and stich
2499 it in place. If the sequence represents all of
2500 the branches we eliminate the whole thing and
2501 replace it with a single TRIE. If it is a
2502 subsequence then we need to stitch it in. This
2503 means the first branch has to remain, and needs
2504 to be repointed at the item on the branch chain
2505 following the last branch optimized. This could
2506 be either a BRANCH, in which case the
2507 subsequence is internal, or it could be the
2508 item following the branch sequence in which
2509 case the subsequence is at the end.
2513 /* dont use tail as the end marker for this traverse */
2514 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
2515 regnode * const noper = NEXTOPER( cur );
2516 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
2517 regnode * const noper_next = regnext( noper );
2521 regprop(RExC_rx, mysv, cur);
2522 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
2523 (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
2525 regprop(RExC_rx, mysv, noper);
2526 PerlIO_printf( Perl_debug_log, " -> %s",
2527 SvPV_nolen_const(mysv));
2530 regprop(RExC_rx, mysv, noper_next );
2531 PerlIO_printf( Perl_debug_log,"\t=> %s\t",
2532 SvPV_nolen_const(mysv));
2534 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
2535 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
2537 if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
2538 : PL_regkind[ OP( noper ) ] == EXACT )
2539 || OP(noper) == NOTHING )
2541 && noper_next == tail
2546 if ( !first || optype == NOTHING ) {
2547 if (!first) first = cur;
2548 optype = OP( noper );
2554 make_trie( pRExC_state,
2555 startbranch, first, cur, tail, count,
2558 if ( PL_regkind[ OP( noper ) ] == EXACT
2560 && noper_next == tail
2565 optype = OP( noper );
2575 regprop(RExC_rx, mysv, cur);
2576 PerlIO_printf( Perl_debug_log,
2577 "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
2578 "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
2582 made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
2583 #ifdef TRIE_STUDY_OPT
2584 if ( ((made == MADE_EXACT_TRIE &&
2585 startbranch == first)
2586 || ( first_non_open == first )) &&
2588 flags |= SCF_TRIE_RESTUDY;
2596 else if ( code == BRANCHJ ) { /* single branch is optimized. */
2597 scan = NEXTOPER(NEXTOPER(scan));
2598 } else /* single branch is optimized. */
2599 scan = NEXTOPER(scan);
2602 else if (OP(scan) == EXACT) {
2603 I32 l = STR_LEN(scan);
2606 const U8 * const s = (U8*)STRING(scan);
2607 l = utf8_length(s, s + l);
2608 uc = utf8_to_uvchr(s, NULL);
2610 uc = *((U8*)STRING(scan));
2613 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
2614 /* The code below prefers earlier match for fixed
2615 offset, later match for variable offset. */
2616 if (data->last_end == -1) { /* Update the start info. */
2617 data->last_start_min = data->pos_min;
2618 data->last_start_max = is_inf
2619 ? I32_MAX : data->pos_min + data->pos_delta;
2621 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
2623 SvUTF8_on(data->last_found);
2625 SV * const sv = data->last_found;
2626 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
2627 mg_find(sv, PERL_MAGIC_utf8) : NULL;
2628 if (mg && mg->mg_len >= 0)
2629 mg->mg_len += utf8_length((U8*)STRING(scan),
2630 (U8*)STRING(scan)+STR_LEN(scan));
2632 data->last_end = data->pos_min + l;
2633 data->pos_min += l; /* As in the first entry. */
2634 data->flags &= ~SF_BEFORE_EOL;
2636 if (flags & SCF_DO_STCLASS_AND) {
2637 /* Check whether it is compatible with what we know already! */
2641 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2642 && !ANYOF_BITMAP_TEST(data->start_class, uc)
2643 && (!(data->start_class->flags & ANYOF_FOLD)
2644 || !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2647 ANYOF_CLASS_ZERO(data->start_class);
2648 ANYOF_BITMAP_ZERO(data->start_class);
2650 ANYOF_BITMAP_SET(data->start_class, uc);
2651 data->start_class->flags &= ~ANYOF_EOS;
2653 data->start_class->flags &= ~ANYOF_UNICODE_ALL;
2655 else if (flags & SCF_DO_STCLASS_OR) {
2656 /* false positive possible if the class is case-folded */
2658 ANYOF_BITMAP_SET(data->start_class, uc);
2660 data->start_class->flags |= ANYOF_UNICODE_ALL;
2661 data->start_class->flags &= ~ANYOF_EOS;
2662 cl_and(data->start_class, &and_with);
2664 flags &= ~SCF_DO_STCLASS;
2666 else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
2667 I32 l = STR_LEN(scan);
2668 UV uc = *((U8*)STRING(scan));
2670 /* Search for fixed substrings supports EXACT only. */
2671 if (flags & SCF_DO_SUBSTR) {
2673 scan_commit(pRExC_state, data, minlenp);
2676 const U8 * const s = (U8 *)STRING(scan);
2677 l = utf8_length(s, s + l);
2678 uc = utf8_to_uvchr(s, NULL);
2681 if (flags & SCF_DO_SUBSTR)
2683 if (flags & SCF_DO_STCLASS_AND) {
2684 /* Check whether it is compatible with what we know already! */
2688 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2689 && !ANYOF_BITMAP_TEST(data->start_class, uc)
2690 && !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2692 ANYOF_CLASS_ZERO(data->start_class);
2693 ANYOF_BITMAP_ZERO(data->start_class);
2695 ANYOF_BITMAP_SET(data->start_class, uc);
2696 data->start_class->flags &= ~ANYOF_EOS;
2697 data->start_class->flags |= ANYOF_FOLD;
2698 if (OP(scan) == EXACTFL)
2699 data->start_class->flags |= ANYOF_LOCALE;
2702 else if (flags & SCF_DO_STCLASS_OR) {
2703 if (data->start_class->flags & ANYOF_FOLD) {
2704 /* false positive possible if the class is case-folded.
2705 Assume that the locale settings are the same... */
2707 ANYOF_BITMAP_SET(data->start_class, uc);
2708 data->start_class->flags &= ~ANYOF_EOS;
2710 cl_and(data->start_class, &and_with);
2712 flags &= ~SCF_DO_STCLASS;
2714 else if (OP(scan)==RECURSE) {
2715 ARG2L_SET( scan, RExC_parens[ARG(scan)-1] - scan );
2717 else if (strchr((const char*)PL_varies,OP(scan))) {
2718 I32 mincount, maxcount, minnext, deltanext, fl = 0;
2719 I32 f = flags, pos_before = 0;
2720 regnode * const oscan = scan;
2721 struct regnode_charclass_class this_class;
2722 struct regnode_charclass_class *oclass = NULL;
2723 I32 next_is_eval = 0;
2725 switch (PL_regkind[OP(scan)]) {
2726 case WHILEM: /* End of (?:...)* . */
2727 scan = NEXTOPER(scan);
2730 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
2731 next = NEXTOPER(scan);
2732 if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
2734 maxcount = REG_INFTY;
2735 next = regnext(scan);
2736 scan = NEXTOPER(scan);
2740 if (flags & SCF_DO_SUBSTR)
2745 if (flags & SCF_DO_STCLASS) {
2747 maxcount = REG_INFTY;
2748 next = regnext(scan);
2749 scan = NEXTOPER(scan);
2752 is_inf = is_inf_internal = 1;
2753 scan = regnext(scan);
2754 if (flags & SCF_DO_SUBSTR) {
2755 scan_commit(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
2756 data->longest = &(data->longest_float);
2758 goto optimize_curly_tail;
2760 mincount = ARG1(scan);
2761 maxcount = ARG2(scan);
2762 next = regnext(scan);
2763 if (OP(scan) == CURLYX) {
2764 I32 lp = (data ? *(data->last_closep) : 0);
2765 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
2767 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
2768 next_is_eval = (OP(scan) == EVAL);
2770 if (flags & SCF_DO_SUBSTR) {
2771 if (mincount == 0) scan_commit(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
2772 pos_before = data->pos_min;
2776 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
2778 data->flags |= SF_IS_INF;
2780 if (flags & SCF_DO_STCLASS) {
2781 cl_init(pRExC_state, &this_class);
2782 oclass = data->start_class;
2783 data->start_class = &this_class;
2784 f |= SCF_DO_STCLASS_AND;
2785 f &= ~SCF_DO_STCLASS_OR;
2787 /* These are the cases when once a subexpression
2788 fails at a particular position, it cannot succeed
2789 even after backtracking at the enclosing scope.
2791 XXXX what if minimal match and we are at the
2792 initial run of {n,m}? */
2793 if ((mincount != maxcount - 1) && (maxcount != REG_INFTY))
2794 f &= ~SCF_WHILEM_VISITED_POS;
2796 /* This will finish on WHILEM, setting scan, or on NULL: */
2797 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, last, data,
2799 ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
2801 if (flags & SCF_DO_STCLASS)
2802 data->start_class = oclass;
2803 if (mincount == 0 || minnext == 0) {
2804 if (flags & SCF_DO_STCLASS_OR) {
2805 cl_or(pRExC_state, data->start_class, &this_class);
2807 else if (flags & SCF_DO_STCLASS_AND) {
2808 /* Switch to OR mode: cache the old value of
2809 * data->start_class */
2810 StructCopy(data->start_class, &and_with,
2811 struct regnode_charclass_class);
2812 flags &= ~SCF_DO_STCLASS_AND;
2813 StructCopy(&this_class, data->start_class,
2814 struct regnode_charclass_class);
2815 flags |= SCF_DO_STCLASS_OR;
2816 data->start_class->flags |= ANYOF_EOS;
2818 } else { /* Non-zero len */
2819 if (flags & SCF_DO_STCLASS_OR) {
2820 cl_or(pRExC_state, data->start_class, &this_class);
2821 cl_and(data->start_class, &and_with);
2823 else if (flags & SCF_DO_STCLASS_AND)
2824 cl_and(data->start_class, &this_class);
2825 flags &= ~SCF_DO_STCLASS;
2827 if (!scan) /* It was not CURLYX, but CURLY. */
2829 if ( /* ? quantifier ok, except for (?{ ... }) */
2830 (next_is_eval || !(mincount == 0 && maxcount == 1))
2831 && (minnext == 0) && (deltanext == 0)
2832 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
2833 && maxcount <= REG_INFTY/3 /* Complement check for big count */
2834 && ckWARN(WARN_REGEXP))
2837 "Quantifier unexpected on zero-length expression");
2840 min += minnext * mincount;
2841 is_inf_internal |= ((maxcount == REG_INFTY
2842 && (minnext + deltanext) > 0)
2843 || deltanext == I32_MAX);
2844 is_inf |= is_inf_internal;
2845 delta += (minnext + deltanext) * maxcount - minnext * mincount;
2847 /* Try powerful optimization CURLYX => CURLYN. */
2848 if ( OP(oscan) == CURLYX && data
2849 && data->flags & SF_IN_PAR
2850 && !(data->flags & SF_HAS_EVAL)
2851 && !deltanext && minnext == 1 ) {
2852 /* Try to optimize to CURLYN. */
2853 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
2854 regnode * const nxt1 = nxt;
2861 if (!strchr((const char*)PL_simple,OP(nxt))
2862 && !(PL_regkind[OP(nxt)] == EXACT
2863 && STR_LEN(nxt) == 1))
2869 if (OP(nxt) != CLOSE)
2871 /* Now we know that nxt2 is the only contents: */
2872 oscan->flags = (U8)ARG(nxt);
2874 OP(nxt1) = NOTHING; /* was OPEN. */
2876 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
2877 NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
2878 NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
2879 OP(nxt) = OPTIMIZED; /* was CLOSE. */
2880 OP(nxt + 1) = OPTIMIZED; /* was count. */
2881 NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
2886 /* Try optimization CURLYX => CURLYM. */
2887 if ( OP(oscan) == CURLYX && data
2888 && !(data->flags & SF_HAS_PAR)
2889 && !(data->flags & SF_HAS_EVAL)
2890 && !deltanext /* atom is fixed width */
2891 && minnext != 0 /* CURLYM can't handle zero width */
2893 /* XXXX How to optimize if data == 0? */
2894 /* Optimize to a simpler form. */
2895 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
2899 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
2900 && (OP(nxt2) != WHILEM))
2902 OP(nxt2) = SUCCEED; /* Whas WHILEM */
2903 /* Need to optimize away parenths. */
2904 if (data->flags & SF_IN_PAR) {
2905 /* Set the parenth number. */
2906 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
2908 if (OP(nxt) != CLOSE)
2909 FAIL("Panic opt close");
2910 oscan->flags = (U8)ARG(nxt);
2911 OP(nxt1) = OPTIMIZED; /* was OPEN. */
2912 OP(nxt) = OPTIMIZED; /* was CLOSE. */
2914 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
2915 OP(nxt + 1) = OPTIMIZED; /* was count. */
2916 NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
2917 NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
2920 while ( nxt1 && (OP(nxt1) != WHILEM)) {
2921 regnode *nnxt = regnext(nxt1);
2924 if (reg_off_by_arg[OP(nxt1)])
2925 ARG_SET(nxt1, nxt2 - nxt1);
2926 else if (nxt2 - nxt1 < U16_MAX)
2927 NEXT_OFF(nxt1) = nxt2 - nxt1;
2929 OP(nxt) = NOTHING; /* Cannot beautify */
2934 /* Optimize again: */
2935 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
2941 else if ((OP(oscan) == CURLYX)
2942 && (flags & SCF_WHILEM_VISITED_POS)
2943 /* See the comment on a similar expression above.
2944 However, this time it not a subexpression
2945 we care about, but the expression itself. */
2946 && (maxcount == REG_INFTY)
2947 && data && ++data->whilem_c < 16) {
2948 /* This stays as CURLYX, we can put the count/of pair. */
2949 /* Find WHILEM (as in regexec.c) */
2950 regnode *nxt = oscan + NEXT_OFF(oscan);
2952 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
2954 PREVOPER(nxt)->flags = (U8)(data->whilem_c
2955 | (RExC_whilem_seen << 4)); /* On WHILEM */
2957 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
2959 if (flags & SCF_DO_SUBSTR) {
2960 SV *last_str = NULL;
2961 int counted = mincount != 0;
2963 if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
2964 #if defined(SPARC64_GCC_WORKAROUND)
2967 const char *s = NULL;
2970 if (pos_before >= data->last_start_min)
2973 b = data->last_start_min;
2976 s = SvPV_const(data->last_found, l);
2977 old = b - data->last_start_min;
2980 I32 b = pos_before >= data->last_start_min
2981 ? pos_before : data->last_start_min;
2983 const char * const s = SvPV_const(data->last_found, l);
2984 I32 old = b - data->last_start_min;
2988 old = utf8_hop((U8*)s, old) - (U8*)s;
2991 /* Get the added string: */
2992 last_str = newSVpvn(s + old, l);
2994 SvUTF8_on(last_str);
2995 if (deltanext == 0 && pos_before == b) {
2996 /* What was added is a constant string */
2998 SvGROW(last_str, (mincount * l) + 1);
2999 repeatcpy(SvPVX(last_str) + l,
3000 SvPVX_const(last_str), l, mincount - 1);
3001 SvCUR_set(last_str, SvCUR(last_str) * mincount);
3002 /* Add additional parts. */
3003 SvCUR_set(data->last_found,
3004 SvCUR(data->last_found) - l);
3005 sv_catsv(data->last_found, last_str);
3007 SV * sv = data->last_found;
3009 SvUTF8(sv) && SvMAGICAL(sv) ?
3010 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3011 if (mg && mg->mg_len >= 0)
3012 mg->mg_len += CHR_SVLEN(last_str);
3014 data->last_end += l * (mincount - 1);
3017 /* start offset must point into the last copy */
3018 data->last_start_min += minnext * (mincount - 1);
3019 data->last_start_max += is_inf ? I32_MAX
3020 : (maxcount - 1) * (minnext + data->pos_delta);
3023 /* It is counted once already... */
3024 data->pos_min += minnext * (mincount - counted);
3025 data->pos_delta += - counted * deltanext +
3026 (minnext + deltanext) * maxcount - minnext * mincount;
3027 if (mincount != maxcount) {
3028 /* Cannot extend fixed substrings found inside
3030 scan_commit(pRExC_state,data,minlenp);
3031 if (mincount && last_str) {
3032 SV * const sv = data->last_found;
3033 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3034 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3038 sv_setsv(sv, last_str);
3039 data->last_end = data->pos_min;
3040 data->last_start_min =
3041 data->pos_min - CHR_SVLEN(last_str);
3042 data->last_start_max = is_inf
3044 : data->pos_min + data->pos_delta
3045 - CHR_SVLEN(last_str);
3047 data->longest = &(data->longest_float);
3049 SvREFCNT_dec(last_str);
3051 if (data && (fl & SF_HAS_EVAL))
3052 data->flags |= SF_HAS_EVAL;
3053 optimize_curly_tail:
3054 if (OP(oscan) != CURLYX) {
3055 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
3057 NEXT_OFF(oscan) += NEXT_OFF(next);
3060 default: /* REF and CLUMP only? */
3061 if (flags & SCF_DO_SUBSTR) {
3062 scan_commit(pRExC_state,data,minlenp); /* Cannot expect anything... */
3063 data->longest = &(data->longest_float);
3065 is_inf = is_inf_internal = 1;
3066 if (flags & SCF_DO_STCLASS_OR)
3067 cl_anything(pRExC_state, data->start_class);
3068 flags &= ~SCF_DO_STCLASS;
3072 else if (strchr((const char*)PL_simple,OP(scan))) {
3075 if (flags & SCF_DO_SUBSTR) {
3076 scan_commit(pRExC_state,data,minlenp);
3080 if (flags & SCF_DO_STCLASS) {
3081 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3083 /* Some of the logic below assumes that switching
3084 locale on will only add false positives. */
3085 switch (PL_regkind[OP(scan)]) {
3089 /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
3090 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3091 cl_anything(pRExC_state, data->start_class);
3094 if (OP(scan) == SANY)
3096 if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
3097 value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
3098 || (data->start_class->flags & ANYOF_CLASS));
3099 cl_anything(pRExC_state, data->start_class);
3101 if (flags & SCF_DO_STCLASS_AND || !value)
3102 ANYOF_BITMAP_CLEAR(data->start_class,'\n');
3105 if (flags & SCF_DO_STCLASS_AND)
3106 cl_and(data->start_class,
3107 (struct regnode_charclass_class*)scan);
3109 cl_or(pRExC_state, data->start_class,
3110 (struct regnode_charclass_class*)scan);
3113 if (flags & SCF_DO_STCLASS_AND) {
3114 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3115 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3116 for (value = 0; value < 256; value++)
3117 if (!isALNUM(value))
3118 ANYOF_BITMAP_CLEAR(data->start_class, value);
3122 if (data->start_class->flags & ANYOF_LOCALE)
3123 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3125 for (value = 0; value < 256; value++)
3127 ANYOF_BITMAP_SET(data->start_class, value);
3132 if (flags & SCF_DO_STCLASS_AND) {
3133 if (data->start_class->flags & ANYOF_LOCALE)
3134 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3137 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3138 data->start_class->flags |= ANYOF_LOCALE;
3142 if (flags & SCF_DO_STCLASS_AND) {
3143 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3144 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3145 for (value = 0; value < 256; value++)
3147 ANYOF_BITMAP_CLEAR(data->start_class, value);
3151 if (data->start_class->flags & ANYOF_LOCALE)
3152 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3154 for (value = 0; value < 256; value++)
3155 if (!isALNUM(value))
3156 ANYOF_BITMAP_SET(data->start_class, value);
3161 if (flags & SCF_DO_STCLASS_AND) {
3162 if (data->start_class->flags & ANYOF_LOCALE)
3163 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3166 data->start_class->flags |= ANYOF_LOCALE;
3167 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3171 if (flags & SCF_DO_STCLASS_AND) {
3172 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3173 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3174 for (value = 0; value < 256; value++)
3175 if (!isSPACE(value))
3176 ANYOF_BITMAP_CLEAR(data->start_class, value);
3180 if (data->start_class->flags & ANYOF_LOCALE)
3181 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3183 for (value = 0; value < 256; value++)
3185 ANYOF_BITMAP_SET(data->start_class, value);
3190 if (flags & SCF_DO_STCLASS_AND) {
3191 if (data->start_class->flags & ANYOF_LOCALE)
3192 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3195 data->start_class->flags |= ANYOF_LOCALE;
3196 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3200 if (flags & SCF_DO_STCLASS_AND) {
3201 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3202 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3203 for (value = 0; value < 256; value++)
3205 ANYOF_BITMAP_CLEAR(data->start_class, value);
3209 if (data->start_class->flags & ANYOF_LOCALE)
3210 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3212 for (value = 0; value < 256; value++)
3213 if (!isSPACE(value))
3214 ANYOF_BITMAP_SET(data->start_class, value);
3219 if (flags & SCF_DO_STCLASS_AND) {
3220 if (data->start_class->flags & ANYOF_LOCALE) {
3221 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3222 for (value = 0; value < 256; value++)
3223 if (!isSPACE(value))
3224 ANYOF_BITMAP_CLEAR(data->start_class, value);
3228 data->start_class->flags |= ANYOF_LOCALE;
3229 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3233 if (flags & SCF_DO_STCLASS_AND) {
3234 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
3235 for (value = 0; value < 256; value++)
3236 if (!isDIGIT(value))
3237 ANYOF_BITMAP_CLEAR(data->start_class, value);
3240 if (data->start_class->flags & ANYOF_LOCALE)
3241 ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
3243 for (value = 0; value < 256; value++)
3245 ANYOF_BITMAP_SET(data->start_class, value);
3250 if (flags & SCF_DO_STCLASS_AND) {
3251 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
3252 for (value = 0; value < 256; value++)
3254 ANYOF_BITMAP_CLEAR(data->start_class, value);
3257 if (data->start_class->flags & ANYOF_LOCALE)
3258 ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
3260 for (value = 0; value < 256; value++)
3261 if (!isDIGIT(value))
3262 ANYOF_BITMAP_SET(data->start_class, value);
3267 if (flags & SCF_DO_STCLASS_OR)
3268 cl_and(data->start_class, &and_with);
3269 flags &= ~SCF_DO_STCLASS;
3272 else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
3273 data->flags |= (OP(scan) == MEOL
3277 else if ( PL_regkind[OP(scan)] == BRANCHJ
3278 /* Lookbehind, or need to calculate parens/evals/stclass: */
3279 && (scan->flags || data || (flags & SCF_DO_STCLASS))
3280 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
3281 if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3282 || OP(scan) == UNLESSM )
3284 /* Negative Lookahead/lookbehind
3285 In this case we can't do fixed string optimisation.
3288 I32 deltanext, minnext, fake = 0;
3290 struct regnode_charclass_class intrnl;
3293 data_fake.flags = 0;
3295 data_fake.whilem_c = data->whilem_c;
3296 data_fake.last_closep = data->last_closep;
3299 data_fake.last_closep = &fake;
3300 if ( flags & SCF_DO_STCLASS && !scan->flags
3301 && OP(scan) == IFMATCH ) { /* Lookahead */
3302 cl_init(pRExC_state, &intrnl);
3303 data_fake.start_class = &intrnl;
3304 f |= SCF_DO_STCLASS_AND;
3306 if (flags & SCF_WHILEM_VISITED_POS)
3307 f |= SCF_WHILEM_VISITED_POS;
3308 next = regnext(scan);
3309 nscan = NEXTOPER(NEXTOPER(scan));
3310 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, last, &data_fake, f,depth+1);
3313 vFAIL("Variable length lookbehind not implemented");
3315 else if (minnext > (I32)U8_MAX) {
3316 vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3318 scan->flags = (U8)minnext;
3321 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3323 if (data_fake.flags & SF_HAS_EVAL)
3324 data->flags |= SF_HAS_EVAL;
3325 data->whilem_c = data_fake.whilem_c;
3327 if (f & SCF_DO_STCLASS_AND) {
3328 const int was = (data->start_class->flags & ANYOF_EOS);
3330 cl_and(data->start_class, &intrnl);
3332 data->start_class->flags |= ANYOF_EOS;
3335 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3337 /* Positive Lookahead/lookbehind
3338 In this case we can do fixed string optimisation,
3339 but we must be careful about it. Note in the case of
3340 lookbehind the positions will be offset by the minimum
3341 length of the pattern, something we won't know about
3342 until after the recurse.
3344 I32 deltanext, fake = 0;
3346 struct regnode_charclass_class intrnl;
3348 /* We use SAVEFREEPV so that when the full compile
3349 is finished perl will clean up the allocated
3350 minlens when its all done. This was we don't
3351 have to worry about freeing them when we know
3352 they wont be used, which would be a pain.
3355 Newx( minnextp, 1, I32 );
3356 SAVEFREEPV(minnextp);
3359 StructCopy(data, &data_fake, scan_data_t);
3360 if ((flags & SCF_DO_SUBSTR) && data->last_found) {
3363 scan_commit(pRExC_state, &data_fake,minlenp);
3364 data_fake.last_found=newSVsv(data->last_found);
3368 data_fake.last_closep = &fake;
3369 data_fake.flags = 0;
3371 data_fake.flags |= SF_IS_INF;
3372 if ( flags & SCF_DO_STCLASS && !scan->flags
3373 && OP(scan) == IFMATCH ) { /* Lookahead */
3374 cl_init(pRExC_state, &intrnl);
3375 data_fake.start_class = &intrnl;
3376 f |= SCF_DO_STCLASS_AND;
3378 if (flags & SCF_WHILEM_VISITED_POS)
3379 f |= SCF_WHILEM_VISITED_POS;
3380 next = regnext(scan);
3381 nscan = NEXTOPER(NEXTOPER(scan));
3383 *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext, last, &data_fake, f,depth+1);
3386 vFAIL("Variable length lookbehind not implemented");
3388 else if (*minnextp > (I32)U8_MAX) {
3389 vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3391 scan->flags = (U8)*minnextp;
3397 if (f & SCF_DO_STCLASS_AND) {
3398 const int was = (data->start_class->flags & ANYOF_EOS);
3400 cl_and(data->start_class, &intrnl);
3402 data->start_class->flags |= ANYOF_EOS;
3405 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3407 if (data_fake.flags & SF_HAS_EVAL)
3408 data->flags |= SF_HAS_EVAL;
3409 data->whilem_c = data_fake.whilem_c;
3410 if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
3411 if (RExC_rx->minlen<*minnextp)
3412 RExC_rx->minlen=*minnextp;
3413 scan_commit(pRExC_state, &data_fake, minnextp);
3414 SvREFCNT_dec(data_fake.last_found);
3416 if ( data_fake.minlen_fixed != minlenp )
3418 data->offset_fixed= data_fake.offset_fixed;
3419 data->minlen_fixed= data_fake.minlen_fixed;
3420 data->lookbehind_fixed+= scan->flags;
3422 if ( data_fake.minlen_float != minlenp )
3424 data->minlen_float= data_fake.minlen_float;
3425 data->offset_float_min=data_fake.offset_float_min;
3426 data->offset_float_max=data_fake.offset_float_max;
3427 data->lookbehind_float+= scan->flags;
3436 else if (OP(scan) == OPEN) {
3439 else if (OP(scan) == CLOSE) {
3440 if ((I32)ARG(scan) == is_par) {
3441 next = regnext(scan);
3443 if ( next && (OP(next) != WHILEM) && next < last)
3444 is_par = 0; /* Disable optimization */
3447 *(data->last_closep) = ARG(scan);
3449 else if (OP(scan) == EVAL) {
3451 data->flags |= SF_HAS_EVAL;
3453 else if (OP(scan) == LOGICAL && scan->flags == 2) { /* Embedded follows */
3454 if (flags & SCF_DO_SUBSTR) {
3455 scan_commit(pRExC_state,data,minlenp);
3456 data->longest = &(data->longest_float);
3458 is_inf = is_inf_internal = 1;
3459 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3460 cl_anything(pRExC_state, data->start_class);
3461 flags &= ~SCF_DO_STCLASS;
3463 #ifdef TRIE_STUDY_OPT
3464 #ifdef FULL_TRIE_STUDY
3465 else if (PL_regkind[OP(scan)] == TRIE) {
3466 /* NOTE - There is similar code to this block above for handling
3467 BRANCH nodes on the initial study. If you change stuff here
3469 regnode *tail= regnext(scan);
3470 reg_trie_data *trie = (reg_trie_data*)RExC_rx->data->data[ ARG(scan) ];
3471 I32 max1 = 0, min1 = I32_MAX;
3472 struct regnode_charclass_class accum;
3474 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
3475 scan_commit(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
3476 if (flags & SCF_DO_STCLASS)
3477 cl_init_zero(pRExC_state, &accum);
3483 const regnode *nextbranch= NULL;
3486 for ( word=1 ; word <= trie->wordcount ; word++)
3488 I32 deltanext=0, minnext=0, f = 0, fake;
3489 struct regnode_charclass_class this_class;
3491 data_fake.flags = 0;
3493 data_fake.whilem_c = data->whilem_c;
3494 data_fake.last_closep = data->last_closep;
3497 data_fake.last_closep = &fake;
3499 if (flags & SCF_DO_STCLASS) {
3500 cl_init(pRExC_state, &this_class);
3501 data_fake.start_class = &this_class;
3502 f = SCF_DO_STCLASS_AND;
3504 if (flags & SCF_WHILEM_VISITED_POS)
3505 f |= SCF_WHILEM_VISITED_POS;
3507 if (trie->jump[word]) {
3509 nextbranch = tail - trie->jump[0];
3510 scan= tail - trie->jump[word];
3511 /* We go from the jump point to the branch that follows
3512 it. Note this means we need the vestigal unused branches
3513 even though they arent otherwise used.
3515 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
3516 (regnode *)nextbranch, &data_fake, f,depth+1);
3518 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
3519 nextbranch= regnext((regnode*)nextbranch);
3521 if (min1 > (I32)(minnext + trie->minlen))
3522 min1 = minnext + trie->minlen;
3523 if (max1 < (I32)(minnext + deltanext + trie->maxlen))
3524 max1 = minnext + deltanext + trie->maxlen;
3525 if (deltanext == I32_MAX)
3526 is_inf = is_inf_internal = 1;
3528 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3532 if (data_fake.flags & SF_HAS_EVAL)
3533 data->flags |= SF_HAS_EVAL;
3534 data->whilem_c = data_fake.whilem_c;
3536 if (flags & SCF_DO_STCLASS)
3537 cl_or(pRExC_state, &accum, &this_class);
3540 if (flags & SCF_DO_SUBSTR) {
3541 data->pos_min += min1;
3542 data->pos_delta += max1 - min1;
3543 if (max1 != min1 || is_inf)
3544 data->longest = &(data->longest_float);
3547 delta += max1 - min1;
3548 if (flags & SCF_DO_STCLASS_OR) {
3549 cl_or(pRExC_state, data->start_class, &accum);
3551 cl_and(data->start_class, &and_with);
3552 flags &= ~SCF_DO_STCLASS;
3555 else if (flags & SCF_DO_STCLASS_AND) {
3557 cl_and(data->start_class, &accum);
3558 flags &= ~SCF_DO_STCLASS;
3561 /* Switch to OR mode: cache the old value of
3562 * data->start_class */
3563 StructCopy(data->start_class, &and_with,
3564 struct regnode_charclass_class);
3565 flags &= ~SCF_DO_STCLASS_AND;
3566 StructCopy(&accum, data->start_class,
3567 struct regnode_charclass_class);
3568 flags |= SCF_DO_STCLASS_OR;
3569 data->start_class->flags |= ANYOF_EOS;
3576 else if (PL_regkind[OP(scan)] == TRIE) {
3577 reg_trie_data *trie = (reg_trie_data*)RExC_rx->data->data[ ARG(scan) ];
3580 min += trie->minlen;
3581 delta += (trie->maxlen - trie->minlen);
3582 flags &= ~SCF_DO_STCLASS; /* xxx */
3583 if (flags & SCF_DO_SUBSTR) {
3584 scan_commit(pRExC_state,data,minlenp); /* Cannot expect anything... */
3585 data->pos_min += trie->minlen;
3586 data->pos_delta += (trie->maxlen - trie->minlen);
3587 if (trie->maxlen != trie->minlen)
3588 data->longest = &(data->longest_float);
3590 if (trie->jump) /* no more substrings -- for now /grr*/
3591 flags &= ~SCF_DO_SUBSTR;
3593 #endif /* old or new */
3594 #endif /* TRIE_STUDY_OPT */
3595 /* Else: zero-length, ignore. */
3596 scan = regnext(scan);
3601 *deltap = is_inf_internal ? I32_MAX : delta;
3602 if (flags & SCF_DO_SUBSTR && is_inf)
3603 data->pos_delta = I32_MAX - data->pos_min;
3604 if (is_par > (I32)U8_MAX)
3606 if (is_par && pars==1 && data) {
3607 data->flags |= SF_IN_PAR;
3608 data->flags &= ~SF_HAS_PAR;
3610 else if (pars && data) {
3611 data->flags |= SF_HAS_PAR;
3612 data->flags &= ~SF_IN_PAR;
3614 if (flags & SCF_DO_STCLASS_OR)
3615 cl_and(data->start_class, &and_with);
3616 if (flags & SCF_TRIE_RESTUDY)
3617 data->flags |= SCF_TRIE_RESTUDY;
3619 DEBUG_STUDYDATA(data,depth);
3625 S_add_data(RExC_state_t *pRExC_state, I32 n, const char *s)
3627 if (RExC_rx->data) {
3628 Renewc(RExC_rx->data,
3629 sizeof(*RExC_rx->data) + sizeof(void*) * (RExC_rx->data->count + n - 1),
3630 char, struct reg_data);
3631 Renew(RExC_rx->data->what, RExC_rx->data->count + n, U8);
3632 RExC_rx->data->count += n;
3635 Newxc(RExC_rx->data, sizeof(*RExC_rx->data) + sizeof(void*) * (n - 1),
3636 char, struct reg_data);
3637 Newx(RExC_rx->data->what, n, U8);
3638 RExC_rx->data->count = n;
3640 Copy(s, RExC_rx->data->what + RExC_rx->data->count - n, n, U8);
3641 return RExC_rx->data->count - n;
3644 #ifndef PERL_IN_XSUB_RE
3646 Perl_reginitcolors(pTHX)
3649 const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
3651 char *t = savepv(s);
3655 t = strchr(t, '\t');
3661 PL_colors[i] = t = (char *)"";
3666 PL_colors[i++] = (char *)"";
3673 #ifdef TRIE_STUDY_OPT
3674 #define CHECK_RESTUDY_GOTO \
3676 (data.flags & SCF_TRIE_RESTUDY) \
3680 #define CHECK_RESTUDY_GOTO
3684 - pregcomp - compile a regular expression into internal code
3686 * We can't allocate space until we know how big the compiled form will be,
3687 * but we can't compile it (and thus know how big it is) until we've got a
3688 * place to put the code. So we cheat: we compile it twice, once with code
3689 * generation turned off and size counting turned on, and once "for real".
3690 * This also means that we don't allocate space until we are sure that the
3691 * thing really will compile successfully, and we never have to move the
3692 * code and thus invalidate pointers into it. (Note that it has to be in
3693 * one piece because free() must be able to free it all.) [NB: not true in perl]
3695 * Beware that the optimization-preparation code in here knows about some
3696 * of the structure of the compiled regexp. [I'll say.]
3698 #ifndef PERL_IN_XSUB_RE
3699 #define CORE_ONLY_BLOCK(c) {c}{
3700 #define RE_ENGINE_PTR &PL_core_reg_engine
3702 #define CORE_ONLY_BLOCK(c) {
3703 extern const struct regexp_engine my_reg_engine;
3704 #define RE_ENGINE_PTR &my_reg_engine
3709 Perl_pregcomp(pTHX_ char *exp, char *xend, PMOP *pm)
3712 GET_RE_DEBUG_FLAGS_DECL;
3713 DEBUG_r(if (!PL_colorset) reginitcolors());
3715 /* Dispatch a request to compile a regexp to correct
3717 HV * const table = GvHV(PL_hintgv);
3719 SV **ptr= hv_fetchs(table, "regcomp", FALSE);
3720 if (ptr && SvIOK(*ptr)) {
3721 const regexp_engine *eng=INT2PTR(regexp_engine*,SvIV(*ptr));
3723 PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
3726 return CALLREGCOMP_ENG(eng, exp, xend, pm);
3737 RExC_state_t RExC_state;
3738 RExC_state_t * const pRExC_state = &RExC_state;
3739 #ifdef TRIE_STUDY_OPT
3741 RExC_state_t copyRExC_state;
3744 FAIL("NULL regexp argument");
3746 RExC_utf8 = pm->op_pmdynflags & PMdf_CMP_UTF8;
3750 SV *dsv= sv_newmortal();
3751 RE_PV_QUOTED_DECL(s, RExC_utf8,
3752 dsv, RExC_precomp, (xend - exp), 60);
3753 PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
3754 PL_colors[4],PL_colors[5],s);
3756 RExC_flags = pm->op_pmflags;
3760 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
3761 RExC_seen_evals = 0;
3764 /* First pass: determine size, legality. */
3771 RExC_emit = &PL_regdummy;
3772 RExC_whilem_seen = 0;
3773 RExC_charnames = NULL;
3776 #if 0 /* REGC() is (currently) a NOP at the first pass.
3777 * Clever compilers notice this and complain. --jhi */
3778 REGC((U8)REG_MAGIC, (char*)RExC_emit);
3780 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n"));
3781 if (reg(pRExC_state, 0, &flags,1) == NULL) {
3782 RExC_precomp = NULL;
3785 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "Required "));
3786 DEBUG_COMPILE_r(PerlIO_printf(Perl_debug_log, "size %"IVdf" nodes ", (IV)RExC_size));
3787 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "\nStarting second pass (creation)\n"));
3790 RExC_lastparse=NULL;
3794 /* Small enough for pointer-storage convention?
3795 If extralen==0, this means that we will not need long jumps. */
3796 if (RExC_size >= 0x10000L && RExC_extralen)
3797 RExC_size += RExC_extralen;
3800 if (RExC_whilem_seen > 15)
3801 RExC_whilem_seen = 15;
3803 /* Allocate space and zero-initialize. Note, the two step process
3804 of zeroing when in debug mode, thus anything assigned has to
3805 happen after that */
3806 Newxc(r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode),
3809 FAIL("Regexp out of space");
3811 /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
3812 Zero(r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode), char);
3814 /* initialization begins here */
3815 r->engine= RE_ENGINE_PTR;
3817 r->prelen = xend - exp;
3818 r->precomp = savepvn(RExC_precomp, r->prelen);
3820 #ifdef PERL_OLD_COPY_ON_WRITE
3821 r->saved_copy = NULL;
3823 r->reganch = pm->op_pmflags & PMf_COMPILETIME;
3824 r->nparens = RExC_npar - 1; /* set early to validate backrefs */
3825 r->lastparen = 0; /* mg.c reads this. */
3827 r->substrs = 0; /* Useful during FAIL. */
3828 r->startp = 0; /* Useful during FAIL. */
3831 if (RExC_seen & REG_SEEN_RECURSE) {
3832 Newx(RExC_parens, RExC_npar,regnode *);
3833 SAVEFREEPV(RExC_parens);
3836 /* Useful during FAIL. */
3837 Newxz(r->offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
3839 r->offsets[0] = RExC_size;
3841 DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
3842 "%s %"UVuf" bytes for offset annotations.\n",
3843 r->offsets ? "Got" : "Couldn't get",
3844 (UV)((2*RExC_size+1) * sizeof(U32))));
3848 /* Second pass: emit code. */
3849 RExC_flags = pm->op_pmflags; /* don't let top level (?i) bleed */
3854 RExC_emit_start = r->program;
3855 RExC_emit = r->program;
3856 /* Store the count of eval-groups for security checks: */
3857 RExC_emit->next_off = (RExC_seen_evals > (I32)U16_MAX) ? U16_MAX : (U16)RExC_seen_evals;
3858 REGC((U8)REG_MAGIC, (char*) RExC_emit++);
3860 if (reg(pRExC_state, 0, &flags,1) == NULL)
3863 /* XXXX To minimize changes to RE engine we always allocate
3864 3-units-long substrs field. */
3865 Newx(r->substrs, 1, struct reg_substr_data);
3868 r->minlen = minlen = sawplus = sawopen = 0;
3869 Zero(r->substrs, 1, struct reg_substr_data);
3870 StructCopy(&zero_scan_data, &data, scan_data_t);
3872 #ifdef TRIE_STUDY_OPT
3874 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
3875 RExC_state=copyRExC_state;
3876 if (data.last_found) {
3877 SvREFCNT_dec(data.longest_fixed);
3878 SvREFCNT_dec(data.longest_float);
3879 SvREFCNT_dec(data.last_found);
3882 copyRExC_state=RExC_state;
3886 /* Dig out information for optimizations. */
3887 r->reganch = pm->op_pmflags & PMf_COMPILETIME; /* Again? */
3888 pm->op_pmflags = RExC_flags;
3890 r->reganch |= ROPT_UTF8; /* Unicode in it? */
3891 r->regstclass = NULL;
3892 if (RExC_naughty >= 10) /* Probably an expensive pattern. */
3893 r->reganch |= ROPT_NAUGHTY;
3894 scan = r->program + 1; /* First BRANCH. */
3896 /* testing for BRANCH here tells us whether there is "must appear"
3897 data in the pattern. If there is then we can use it for optimisations */
3898 if (OP(scan) != BRANCH) { /* Only one top-level choice. */
3900 STRLEN longest_float_length, longest_fixed_length;
3901 struct regnode_charclass_class ch_class; /* pointed to by data */
3903 I32 last_close = 0; /* pointed to by data */
3906 /* Skip introductions and multiplicators >= 1. */
3907 while ((OP(first) == OPEN && (sawopen = 1)) ||
3908 /* An OR of *one* alternative - should not happen now. */
3909 (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
3910 /* for now we can't handle lookbehind IFMATCH*/
3911 (OP(first) == IFMATCH && !first->flags) ||
3912 (OP(first) == PLUS) ||
3913 (OP(first) == MINMOD) ||
3914 /* An {n,m} with n>0 */
3915 (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) )
3918 if (OP(first) == PLUS)
3921 first += regarglen[OP(first)];
3922 if (OP(first) == IFMATCH) {
3923 first = NEXTOPER(first);
3924 first += EXTRA_STEP_2ARGS;
3925 } else /* XXX possible optimisation for /(?=)/ */
3926 first = NEXTOPER(first);
3929 /* Starting-point info. */
3931 DEBUG_PEEP("first:",first,0);
3932 /* Ignore EXACT as we deal with it later. */
3933 if (PL_regkind[OP(first)] == EXACT) {
3934 if (OP(first) == EXACT)
3935 NOOP; /* Empty, get anchored substr later. */
3936 else if ((OP(first) == EXACTF || OP(first) == EXACTFL))
3937 r->regstclass = first;
3940 else if (PL_regkind[OP(first)] == TRIE &&
3941 ((reg_trie_data *)r->data->data[ ARG(first) ])->minlen>0)
3944 /* this can happen only on restudy */
3945 if ( OP(first) == TRIE ) {
3946 struct regnode_1 *trieop;
3947 Newxz(trieop,1,struct regnode_1);
3948 StructCopy(first,trieop,struct regnode_1);
3949 trie_op=(regnode *)trieop;
3951 struct regnode_charclass *trieop;
3952 Newxz(trieop,1,struct regnode_charclass);
3953 StructCopy(first,trieop,struct regnode_charclass);
3954 trie_op=(regnode *)trieop;
3957 make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
3958 r->regstclass = trie_op;
3961 else if (strchr((const char*)PL_simple,OP(first)))
3962 r->regstclass = first;
3963 else if (PL_regkind[OP(first)] == BOUND ||
3964 PL_regkind[OP(first)] == NBOUND)
3965 r->regstclass = first;
3966 else if (PL_regkind[OP(first)] == BOL) {
3967 r->reganch |= (OP(first) == MBOL
3969 : (OP(first) == SBOL
3972 first = NEXTOPER(first);
3975 else if (OP(first) == GPOS) {
3976 r->reganch |= ROPT_ANCH_GPOS;
3977 first = NEXTOPER(first);
3980 else if (!sawopen && (OP(first) == STAR &&
3981 PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
3982 !(r->reganch & ROPT_ANCH) )
3984 /* turn .* into ^.* with an implied $*=1 */
3986 (OP(NEXTOPER(first)) == REG_ANY)
3989 r->reganch |= type | ROPT_IMPLICIT;
3990 first = NEXTOPER(first);
3993 if (sawplus && (!sawopen || !RExC_sawback)
3994 && !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
3995 /* x+ must match at the 1st pos of run of x's */
3996 r->reganch |= ROPT_SKIP;
3998 /* Scan is after the zeroth branch, first is atomic matcher. */
3999 #ifdef TRIE_STUDY_OPT
4002 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4003 (IV)(first - scan + 1))
4007 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4008 (IV)(first - scan + 1))
4014 * If there's something expensive in the r.e., find the
4015 * longest literal string that must appear and make it the
4016 * regmust. Resolve ties in favor of later strings, since
4017 * the regstart check works with the beginning of the r.e.
4018 * and avoiding duplication strengthens checking. Not a
4019 * strong reason, but sufficient in the absence of others.
4020 * [Now we resolve ties in favor of the earlier string if
4021 * it happens that c_offset_min has been invalidated, since the
4022 * earlier string may buy us something the later one won't.]
4026 data.longest_fixed = newSVpvs("");
4027 data.longest_float = newSVpvs("");
4028 data.last_found = newSVpvs("");
4029 data.longest = &(data.longest_fixed);
4031 if (!r->regstclass) {
4032 cl_init(pRExC_state, &ch_class);
4033 data.start_class = &ch_class;
4034 stclass_flag = SCF_DO_STCLASS_AND;
4035 } else /* XXXX Check for BOUND? */
4037 data.last_closep = &last_close;
4039 minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
4040 &data, SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag,0);
4046 if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
4047 && data.last_start_min == 0 && data.last_end > 0
4048 && !RExC_seen_zerolen
4049 && (!(RExC_seen & REG_SEEN_GPOS) || (r->reganch & ROPT_ANCH_GPOS)))
4050 r->reganch |= ROPT_CHECK_ALL;
4051 scan_commit(pRExC_state, &data,&minlen);
4052 SvREFCNT_dec(data.last_found);
4054 /* Note that code very similar to this but for anchored string
4055 follows immediately below, changes may need to be made to both.
4058 longest_float_length = CHR_SVLEN(data.longest_float);
4059 if (longest_float_length
4060 || (data.flags & SF_FL_BEFORE_EOL
4061 && (!(data.flags & SF_FL_BEFORE_MEOL)
4062 || (RExC_flags & PMf_MULTILINE))))
4066 if (SvCUR(data.longest_fixed) /* ok to leave SvCUR */
4067 && data.offset_fixed == data.offset_float_min
4068 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
4069 goto remove_float; /* As in (a)+. */
4071 /* copy the information about the longest float from the reg_scan_data
4072 over to the program. */
4073 if (SvUTF8(data.longest_float)) {
4074 r->float_utf8 = data.longest_float;
4075 r->float_substr = NULL;
4077 r->float_substr = data.longest_float;
4078 r->float_utf8 = NULL;
4080 /* float_end_shift is how many chars that must be matched that
4081 follow this item. We calculate it ahead of time as once the
4082 lookbehind offset is added in we lose the ability to correctly
4084 ml = data.minlen_float ? *(data.minlen_float)
4085 : (I32)longest_float_length;
4086 r->float_end_shift = ml - data.offset_float_min
4087 - longest_float_length + (SvTAIL(data.longest_float) != 0)
4088 + data.lookbehind_float;
4089 r->float_min_offset = data.offset_float_min - data.lookbehind_float;
4090 r->float_max_offset = data.offset_float_max;
4091 if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
4092 r->float_max_offset -= data.lookbehind_float;
4094 t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
4095 && (!(data.flags & SF_FL_BEFORE_MEOL)
4096 || (RExC_flags & PMf_MULTILINE)));
4097 fbm_compile(data.longest_float, t ? FBMcf_TAIL : 0);
4101 r->float_substr = r->float_utf8 = NULL;
4102 SvREFCNT_dec(data.longest_float);
4103 longest_float_length = 0;
4106 /* Note that code very similar to this but for floating string
4107 is immediately above, changes may need to be made to both.
4110 longest_fixed_length = CHR_SVLEN(data.longest_fixed);
4111 if (longest_fixed_length
4112 || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
4113 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4114 || (RExC_flags & PMf_MULTILINE))))
4118 /* copy the information about the longest fixed
4119 from the reg_scan_data over to the program. */
4120 if (SvUTF8(data.longest_fixed)) {
4121 r->anchored_utf8 = data.longest_fixed;
4122 r->anchored_substr = NULL;
4124 r->anchored_substr = data.longest_fixed;
4125 r->anchored_utf8 = NULL;
4127 /* fixed_end_shift is how many chars that must be matched that
4128 follow this item. We calculate it ahead of time as once the
4129 lookbehind offset is added in we lose the ability to correctly
4131 ml = data.minlen_fixed ? *(data.minlen_fixed)
4132 : (I32)longest_fixed_length;
4133 r->anchored_end_shift = ml - data.offset_fixed
4134 - longest_fixed_length + (SvTAIL(data.longest_fixed) != 0)
4135 + data.lookbehind_fixed;
4136 r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
4138 t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
4139 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4140 || (RExC_flags & PMf_MULTILINE)));
4141 fbm_compile(data.longest_fixed, t ? FBMcf_TAIL : 0);
4144 r->anchored_substr = r->anchored_utf8 = NULL;
4145 SvREFCNT_dec(data.longest_fixed);
4146 longest_fixed_length = 0;
4149 && (OP(r->regstclass) == REG_ANY || OP(r->regstclass) == SANY))
4150 r->regstclass = NULL;
4151 if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
4153 && !(data.start_class->flags & ANYOF_EOS)
4154 && !cl_is_anything(data.start_class))
4156 const I32 n = add_data(pRExC_state, 1, "f");
4158 Newx(RExC_rx->data->data[n], 1,
4159 struct regnode_charclass_class);
4160 StructCopy(data.start_class,
4161 (struct regnode_charclass_class*)RExC_rx->data->data[n],
4162 struct regnode_charclass_class);
4163 r->regstclass = (regnode*)RExC_rx->data->data[n];
4164 r->reganch &= ~ROPT_SKIP; /* Used in find_byclass(). */
4165 DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
4166 regprop(r, sv, (regnode*)data.start_class);
4167 PerlIO_printf(Perl_debug_log,
4168 "synthetic stclass \"%s\".\n",
4169 SvPVX_const(sv));});
4172 /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
4173 if (longest_fixed_length > longest_float_length) {
4174 r->check_end_shift = r->anchored_end_shift;
4175 r->check_substr = r->anchored_substr;
4176 r->check_utf8 = r->anchored_utf8;
4177 r->check_offset_min = r->check_offset_max = r->anchored_offset;
4178 if (r->reganch & ROPT_ANCH_SINGLE)
4179 r->reganch |= ROPT_NOSCAN;
4182 r->check_end_shift = r->float_end_shift;
4183 r->check_substr = r->float_substr;
4184 r->check_utf8 = r->float_utf8;
4185 r->check_offset_min = r->float_min_offset;
4186 r->check_offset_max = r->float_max_offset;
4188 /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
4189 This should be changed ASAP! */
4190 if ((r->check_substr || r->check_utf8) && !(r->reganch & ROPT_ANCH_GPOS)) {
4191 r->reganch |= RE_USE_INTUIT;
4192 if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
4193 r->reganch |= RE_INTUIT_TAIL;
4195 /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
4196 if ( (STRLEN)minlen < longest_float_length )
4197 minlen= longest_float_length;
4198 if ( (STRLEN)minlen < longest_fixed_length )
4199 minlen= longest_fixed_length;
4203 /* Several toplevels. Best we can is to set minlen. */
4205 struct regnode_charclass_class ch_class;
4208 DEBUG_COMPILE_r(PerlIO_printf(Perl_debug_log, "\n"));
4210 scan = r->program + 1;
4211 cl_init(pRExC_state, &ch_class);
4212 data.start_class = &ch_class;
4213 data.last_closep = &last_close;
4215 minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
4216 &data, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS,0);
4220 r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
4221 = r->float_substr = r->float_utf8 = NULL;
4222 if (!(data.start_class->flags & ANYOF_EOS)
4223 && !cl_is_anything(data.start_class))
4225 const I32 n = add_data(pRExC_state, 1, "f");
4227 Newx(RExC_rx->data->data[n], 1,
4228 struct regnode_charclass_class);
4229 StructCopy(data.start_class,
4230 (struct regnode_charclass_class*)RExC_rx->data->data[n],
4231 struct regnode_charclass_class);
4232 r->regstclass = (regnode*)RExC_rx->data->data[n];
4233 r->reganch &= ~ROPT_SKIP; /* Used in find_byclass(). */
4234 DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
4235 regprop(r, sv, (regnode*)data.start_class);
4236 PerlIO_printf(Perl_debug_log,
4237 "synthetic stclass \"%s\".\n",
4238 SvPVX_const(sv));});
4242 /* Guard against an embedded (?=) or (?<=) with a longer minlen than
4243 the "real" pattern. */
4244 if (r->minlen < minlen)
4247 if (RExC_seen & REG_SEEN_GPOS)
4248 r->reganch |= ROPT_GPOS_SEEN;
4249 if (RExC_seen & REG_SEEN_LOOKBEHIND)
4250 r->reganch |= ROPT_LOOKBEHIND_SEEN;
4251 if (RExC_seen & REG_SEEN_EVAL)
4252 r->reganch |= ROPT_EVAL_SEEN;
4253 if (RExC_seen & REG_SEEN_CANY)
4254 r->reganch |= ROPT_CANY_SEEN;
4255 Newxz(r->startp, RExC_npar, I32);
4256 Newxz(r->endp, RExC_npar, I32);
4258 DEBUG_r( RX_DEBUG_on(r) );
4260 PerlIO_printf(Perl_debug_log,"Final program:\n");
4263 DEBUG_OFFSETS_r(if (r->offsets) {
4264 const U32 len = r->offsets[0];
4266 GET_RE_DEBUG_FLAGS_DECL;
4267 PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)r->offsets[0]);
4268 for (i = 1; i <= len; i++) {
4269 if (r->offsets[i*2-1] || r->offsets[i*2])
4270 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
4271 (UV)i, (UV)r->offsets[i*2-1], (UV)r->offsets[i*2]);
4273 PerlIO_printf(Perl_debug_log, "\n");
4279 #undef CORE_ONLY_BLOCK
4281 #undef RE_ENGINE_PTR
4283 #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
4284 int rem=(int)(RExC_end - RExC_parse); \
4293 if (RExC_lastparse!=RExC_parse) \
4294 PerlIO_printf(Perl_debug_log," >%.*s%-*s", \
4297 iscut ? "..." : "<" \
4300 PerlIO_printf(Perl_debug_log,"%16s",""); \
4305 num=REG_NODE_NUM(RExC_emit); \
4306 if (RExC_lastnum!=num) \
4307 PerlIO_printf(Perl_debug_log,"|%4d",num); \
4309 PerlIO_printf(Perl_debug_log,"|%4s",""); \
4310 PerlIO_printf(Perl_debug_log,"|%*s%-4s", \
4311 (int)((depth*2)), "", \
4315 RExC_lastparse=RExC_parse; \
4320 #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
4321 DEBUG_PARSE_MSG((funcname)); \
4322 PerlIO_printf(Perl_debug_log,"%4s","\n"); \
4324 #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({ \
4325 DEBUG_PARSE_MSG((funcname)); \
4326 PerlIO_printf(Perl_debug_log,fmt "\n",args); \
4329 - reg - regular expression, i.e. main body or parenthesized thing
4331 * Caller must absorb opening parenthesis.
4333 * Combining parenthesis handling with the base level of regular expression
4334 * is a trifle forced, but the need to tie the tails of the branches to what
4335 * follows makes it hard to avoid.
4337 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
4339 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
4341 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
4345 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
4346 /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
4349 register regnode *ret; /* Will be the head of the group. */
4350 register regnode *br;
4351 register regnode *lastbr;
4352 register regnode *ender = NULL;
4353 register I32 parno = 0;
4355 const I32 oregflags = RExC_flags;
4356 bool have_branch = 0;
4359 /* for (?g), (?gc), and (?o) warnings; warning
4360 about (?c) will warn about (?g) -- japhy */
4362 #define WASTED_O 0x01
4363 #define WASTED_G 0x02
4364 #define WASTED_C 0x04
4365 #define WASTED_GC (0x02|0x04)
4366 I32 wastedflags = 0x00;
4368 char * parse_start = RExC_parse; /* MJD */
4369 char * const oregcomp_parse = RExC_parse;
4371 GET_RE_DEBUG_FLAGS_DECL;
4372 DEBUG_PARSE("reg ");
4375 *flagp = 0; /* Tentatively. */
4378 /* Make an OPEN node, if parenthesized. */
4380 if (*RExC_parse == '?') { /* (?...) */
4381 U32 posflags = 0, negflags = 0;
4382 U32 *flagsp = &posflags;
4383 bool is_logical = 0;
4384 const char * const seqstart = RExC_parse;
4387 paren = *RExC_parse++;
4388 ret = NULL; /* For look-ahead/behind. */
4390 case '<': /* (?<...) */
4391 RExC_seen |= REG_SEEN_LOOKBEHIND;
4392 if (*RExC_parse == '!')
4394 if (*RExC_parse != '=' && *RExC_parse != '!')
4397 case '=': /* (?=...) */
4398 case '!': /* (?!...) */
4399 RExC_seen_zerolen++;
4400 case ':': /* (?:...) */
4401 case '>': /* (?>...) */
4403 case '$': /* (?$...) */
4404 case '@': /* (?@...) */
4405 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
4407 case '#': /* (?#...) */
4408 while (*RExC_parse && *RExC_parse != ')')
4410 if (*RExC_parse != ')')
4411 FAIL("Sequence (?#... not terminated");
4412 nextchar(pRExC_state);
4416 if (*RExC_parse != ')')
4417 FAIL("Sequence (?R) not terminated");
4418 reg_node(pRExC_state, SRECURSE);
4420 case '1': case '2': case '3': case '4': /* (?1) */
4421 case '5': case '6': case '7': case '8': case '9':
4424 const I32 num = atoi(RExC_parse);
4425 char * const parse_start = RExC_parse - 1; /* MJD */
4426 while (isDIGIT(*RExC_parse))
4428 if (*RExC_parse!=')')
4429 vFAIL("Expecting close bracket");
4430 ret = reganode(pRExC_state, RECURSE, num);
4432 if (num > (I32)RExC_rx->nparens) {
4434 vFAIL("Reference to nonexistent group");
4438 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
4439 "Recurse #%"UVuf" to %"IVdf"\n", ARG(ret), ARG2L(ret)));
4442 RExC_seen|=REG_SEEN_RECURSE;
4444 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
4445 Set_Node_Offset(ret, RExC_parse); /* MJD */
4447 nextchar(pRExC_state);
4450 case 'p': /* (?p...) */
4451 if (SIZE_ONLY && ckWARN2(WARN_DEPRECATED, WARN_REGEXP))
4452 vWARNdep(RExC_parse, "(?p{}) is deprecated - use (??{})");
4454 case '?': /* (??...) */
4456 if (*RExC_parse != '{')
4458 paren = *RExC_parse++;
4460 case '{': /* (?{...}) */
4462 I32 count = 1, n = 0;
4464 char *s = RExC_parse;
4466 RExC_seen_zerolen++;
4467 RExC_seen |= REG_SEEN_EVAL;
4468 while (count && (c = *RExC_parse)) {
4479 if (*RExC_parse != ')') {
4481 vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
4485 OP_4tree *sop, *rop;
4486 SV * const sv = newSVpvn(s, RExC_parse - 1 - s);
4489 Perl_save_re_context(aTHX);
4490 rop = sv_compile_2op(sv, &sop, "re", &pad);
4491 sop->op_private |= OPpREFCOUNTED;
4492 /* re_dup will OpREFCNT_inc */
4493 OpREFCNT_set(sop, 1);
4496 n = add_data(pRExC_state, 3, "nop");
4497 RExC_rx->data->data[n] = (void*)rop;
4498 RExC_rx->data->data[n+1] = (void*)sop;
4499 RExC_rx->data->data[n+2] = (void*)pad;
4502 else { /* First pass */
4503 if (PL_reginterp_cnt < ++RExC_seen_evals
4505 /* No compiled RE interpolated, has runtime
4506 components ===> unsafe. */
4507 FAIL("Eval-group not allowed at runtime, use re 'eval'");
4508 if (PL_tainting && PL_tainted)
4509 FAIL("Eval-group in insecure regular expression");
4510 #if PERL_VERSION > 8
4511 if (IN_PERL_COMPILETIME)
4516 nextchar(pRExC_state);
4518 ret = reg_node(pRExC_state, LOGICAL);
4521 REGTAIL(pRExC_state, ret, reganode(pRExC_state, EVAL, n));
4522 /* deal with the length of this later - MJD */
4525 ret = reganode(pRExC_state, EVAL, n);
4526 Set_Node_Length(ret, RExC_parse - parse_start + 1);
4527 Set_Node_Offset(ret, parse_start);
4530 case '(': /* (?(?{...})...) and (?(?=...)...) */
4532 if (RExC_parse[0] == '?') { /* (?(?...)) */
4533 if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
4534 || RExC_parse[1] == '<'
4535 || RExC_parse[1] == '{') { /* Lookahead or eval. */
4538 ret = reg_node(pRExC_state, LOGICAL);
4541 REGTAIL(pRExC_state, ret, reg(pRExC_state, 1, &flag,depth+1));
4545 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
4548 parno = atoi(RExC_parse++);
4550 while (isDIGIT(*RExC_parse))
4552 ret = reganode(pRExC_state, GROUPP, parno);
4554 if ((c = *nextchar(pRExC_state)) != ')')
4555 vFAIL("Switch condition not recognized");
4557 REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
4558 br = regbranch(pRExC_state, &flags, 1,depth+1);
4560 br = reganode(pRExC_state, LONGJMP, 0);
4562 REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
4563 c = *nextchar(pRExC_state);
4567 lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
4568 regbranch(pRExC_state, &flags, 1,depth+1);
4569 REGTAIL(pRExC_state, ret, lastbr);
4572 c = *nextchar(pRExC_state);
4577 vFAIL("Switch (?(condition)... contains too many branches");
4578 ender = reg_node(pRExC_state, TAIL);
4579 REGTAIL(pRExC_state, br, ender);
4581 REGTAIL(pRExC_state, lastbr, ender);
4582 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
4585 REGTAIL(pRExC_state, ret, ender);
4589 vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
4593 RExC_parse--; /* for vFAIL to print correctly */
4594 vFAIL("Sequence (? incomplete");
4598 parse_flags: /* (?i) */
4599 while (*RExC_parse && strchr("iogcmsx", *RExC_parse)) {
4600 /* (?g), (?gc) and (?o) are useless here
4601 and must be globally applied -- japhy */
4603 if (*RExC_parse == 'o' || *RExC_parse == 'g') {
4604 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
4605 const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
4606 if (! (wastedflags & wflagbit) ) {
4607 wastedflags |= wflagbit;
4610 "Useless (%s%c) - %suse /%c modifier",
4611 flagsp == &negflags ? "?-" : "?",
4613 flagsp == &negflags ? "don't " : "",
4619 else if (*RExC_parse == 'c') {
4620 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
4621 if (! (wastedflags & WASTED_C) ) {
4622 wastedflags |= WASTED_GC;
4625 "Useless (%sc) - %suse /gc modifier",
4626 flagsp == &negflags ? "?-" : "?",
4627 flagsp == &negflags ? "don't " : ""
4632 else { pmflag(flagsp, *RExC_parse); }
4636 if (*RExC_parse == '-') {
4638 wastedflags = 0; /* reset so (?g-c) warns twice */
4642 RExC_flags |= posflags;
4643 RExC_flags &= ~negflags;
4644 if (*RExC_parse == ':') {
4650 if (*RExC_parse != ')') {
4652 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
4654 nextchar(pRExC_state);
4662 ret = reganode(pRExC_state, OPEN, parno);
4663 if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
4664 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
4665 "Setting paren #%"IVdf" to %d\n", parno, REG_NODE_NUM(ret)));
4666 RExC_parens[parno-1]= ret;
4669 Set_Node_Length(ret, 1); /* MJD */
4670 Set_Node_Offset(ret, RExC_parse); /* MJD */
4677 /* Pick up the branches, linking them together. */
4678 parse_start = RExC_parse; /* MJD */
4679 br = regbranch(pRExC_state, &flags, 1,depth+1);
4680 /* branch_len = (paren != 0); */
4684 if (*RExC_parse == '|') {
4685 if (!SIZE_ONLY && RExC_extralen) {
4686 reginsert(pRExC_state, BRANCHJ, br, depth+1);
4689 reginsert(pRExC_state, BRANCH, br, depth+1);
4690 Set_Node_Length(br, paren != 0);
4691 Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
4695 RExC_extralen += 1; /* For BRANCHJ-BRANCH. */
4697 else if (paren == ':') {
4698 *flagp |= flags&SIMPLE;
4700 if (is_open) { /* Starts with OPEN. */
4701 REGTAIL(pRExC_state, ret, br); /* OPEN -> first. */
4703 else if (paren != '?') /* Not Conditional */
4705 *flagp |= flags & (SPSTART | HASWIDTH);
4707 while (*RExC_parse == '|') {
4708 if (!SIZE_ONLY && RExC_extralen) {
4709 ender = reganode(pRExC_state, LONGJMP,0);
4710 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
4713 RExC_extralen += 2; /* Account for LONGJMP. */
4714 nextchar(pRExC_state);
4715 br = regbranch(pRExC_state, &flags, 0, depth+1);
4719 REGTAIL(pRExC_state, lastbr, br); /* BRANCH -> BRANCH. */
4723 *flagp |= flags&SPSTART;
4726 if (have_branch || paren != ':') {
4727 /* Make a closing node, and hook it on the end. */
4730 ender = reg_node(pRExC_state, TAIL);
4733 ender = reganode(pRExC_state, CLOSE, parno);
4734 Set_Node_Offset(ender,RExC_parse+1); /* MJD */
4735 Set_Node_Length(ender,1); /* MJD */
4741 *flagp &= ~HASWIDTH;
4744 ender = reg_node(pRExC_state, SUCCEED);
4747 ender = reg_node(pRExC_state, END);
4750 REGTAIL_STUDY(pRExC_state, lastbr, ender);
4752 if (have_branch && !SIZE_ONLY) {
4753 /* Hook the tails of the branches to the closing node. */
4754 for (br = ret; br; br = regnext(br)) {
4755 const U8 op = PL_regkind[OP(br)];
4757 REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
4759 else if (op == BRANCHJ) {
4760 REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
4768 static const char parens[] = "=!<,>";
4770 if (paren && (p = strchr(parens, paren))) {
4771 U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
4772 int flag = (p - parens) > 1;
4775 node = SUSPEND, flag = 0;
4776 reginsert(pRExC_state, node,ret, depth+1);
4777 Set_Node_Cur_Length(ret);
4778 Set_Node_Offset(ret, parse_start + 1);
4780 REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
4784 /* Check for proper termination. */
4786 RExC_flags = oregflags;
4787 if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
4788 RExC_parse = oregcomp_parse;
4789 vFAIL("Unmatched (");
4792 else if (!paren && RExC_parse < RExC_end) {
4793 if (*RExC_parse == ')') {
4795 vFAIL("Unmatched )");
4798 FAIL("Junk on end of regexp"); /* "Can't happen". */
4806 - regbranch - one alternative of an | operator
4808 * Implements the concatenation operator.
4811 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
4814 register regnode *ret;
4815 register regnode *chain = NULL;
4816 register regnode *latest;
4817 I32 flags = 0, c = 0;
4818 GET_RE_DEBUG_FLAGS_DECL;
4819 DEBUG_PARSE("brnc");
4823 if (!SIZE_ONLY && RExC_extralen)
4824 ret = reganode(pRExC_state, BRANCHJ,0);
4826 ret = reg_node(pRExC_state, BRANCH);
4827 Set_Node_Length(ret, 1);
4831 if (!first && SIZE_ONLY)
4832 RExC_extralen += 1; /* BRANCHJ */
4834 *flagp = WORST; /* Tentatively. */
4837 nextchar(pRExC_state);
4838 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
4840 latest = regpiece(pRExC_state, &flags,depth+1);
4841 if (latest == NULL) {
4842 if (flags & TRYAGAIN)
4846 else if (ret == NULL)
4848 *flagp |= flags&HASWIDTH;
4849 if (chain == NULL) /* First piece. */
4850 *flagp |= flags&SPSTART;
4853 REGTAIL(pRExC_state, chain, latest);
4858 if (chain == NULL) { /* Loop ran zero times. */
4859 chain = reg_node(pRExC_state, NOTHING);
4864 *flagp |= flags&SIMPLE;
4871 - regpiece - something followed by possible [*+?]
4873 * Note that the branching code sequences used for ? and the general cases
4874 * of * and + are somewhat optimized: they use the same NOTHING node as
4875 * both the endmarker for their branch list and the body of the last branch.
4876 * It might seem that this node could be dispensed with entirely, but the
4877 * endmarker role is not redundant.
4880 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
4883 register regnode *ret;
4885 register char *next;
4887 const char * const origparse = RExC_parse;
4889 I32 max = REG_INFTY;
4891 const char *maxpos = NULL;
4892 GET_RE_DEBUG_FLAGS_DECL;
4893 DEBUG_PARSE("piec");
4895 ret = regatom(pRExC_state, &flags,depth+1);
4897 if (flags & TRYAGAIN)
4904 if (op == '{' && regcurly(RExC_parse)) {
4906 parse_start = RExC_parse; /* MJD */
4907 next = RExC_parse + 1;
4908 while (isDIGIT(*next) || *next == ',') {
4917 if (*next == '}') { /* got one */
4921 min = atoi(RExC_parse);
4925 maxpos = RExC_parse;
4927 if (!max && *maxpos != '0')
4928 max = REG_INFTY; /* meaning "infinity" */
4929 else if (max >= REG_INFTY)
4930 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
4932 nextchar(pRExC_state);
4935 if ((flags&SIMPLE)) {
4936 RExC_naughty += 2 + RExC_naughty / 2;
4937 reginsert(pRExC_state, CURLY, ret, depth+1);
4938 Set_Node_Offset(ret, parse_start+1); /* MJD */
4939 Set_Node_Cur_Length(ret);
4942 regnode * const w = reg_node(pRExC_state, WHILEM);
4945 REGTAIL(pRExC_state, ret, w);
4946 if (!SIZE_ONLY && RExC_extralen) {
4947 reginsert(pRExC_state, LONGJMP,ret, depth+1);
4948 reginsert(pRExC_state, NOTHING,ret, depth+1);
4949 NEXT_OFF(ret) = 3; /* Go over LONGJMP. */
4951 reginsert(pRExC_state, CURLYX,ret, depth+1);
4953 Set_Node_Offset(ret, parse_start+1);
4954 Set_Node_Length(ret,
4955 op == '{' ? (RExC_parse - parse_start) : 1);
4957 if (!SIZE_ONLY && RExC_extralen)
4958 NEXT_OFF(ret) = 3; /* Go over NOTHING to LONGJMP. */
4959 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
4961 RExC_whilem_seen++, RExC_extralen += 3;
4962 RExC_naughty += 4 + RExC_naughty; /* compound interest */
4970 if (max && max < min)
4971 vFAIL("Can't do {n,m} with n > m");
4973 ARG1_SET(ret, (U16)min);
4974 ARG2_SET(ret, (U16)max);
4985 /* else if (OP(ret)==RECURSE) {
4987 vFAIL("Illegal quantifier on recursion group");
4990 #if 0 /* Now runtime fix should be reliable. */
4992 /* if this is reinstated, don't forget to put this back into perldiag:
4994 =item Regexp *+ operand could be empty at {#} in regex m/%s/
4996 (F) The part of the regexp subject to either the * or + quantifier
4997 could match an empty string. The {#} shows in the regular
4998 expression about where the problem was discovered.
5002 if (!(flags&HASWIDTH) && op != '?')
5003 vFAIL("Regexp *+ operand could be empty");
5006 parse_start = RExC_parse;
5007 nextchar(pRExC_state);
5009 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
5011 if (op == '*' && (flags&SIMPLE)) {
5012 reginsert(pRExC_state, STAR, ret, depth+1);
5016 else if (op == '*') {
5020 else if (op == '+' && (flags&SIMPLE)) {
5021 reginsert(pRExC_state, PLUS, ret, depth+1);
5025 else if (op == '+') {
5029 else if (op == '?') {
5034 if (!SIZE_ONLY && !(flags&HASWIDTH) && max > REG_INFTY/3 && ckWARN(WARN_REGEXP)) {
5036 "%.*s matches null string many times",
5037 (int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
5041 if (*RExC_parse == '?') {
5042 nextchar(pRExC_state);
5043 reginsert(pRExC_state, MINMOD, ret, depth+1);
5044 REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
5046 if (ISMULT2(RExC_parse)) {
5048 vFAIL("Nested quantifiers");
5055 /* reg_namedseq(pRExC_state,UVp)
5057 This is expected to be called by a parser routine that has
5058 recognized'\N' and needs to handle the rest. RExC_parse is
5059 expected to point at the first char following the N at the time
5062 If valuep is non-null then it is assumed that we are parsing inside
5063 of a charclass definition and the first codepoint in the resolved
5064 string is returned via *valuep and the routine will return NULL.
5065 In this mode if a multichar string is returned from the charnames
5066 handler a warning will be issued, and only the first char in the
5067 sequence will be examined. If the string returned is zero length
5068 then the value of *valuep is undefined and NON-NULL will
5069 be returned to indicate failure. (This will NOT be a valid pointer
5072 If value is null then it is assumed that we are parsing normal text
5073 and inserts a new EXACT node into the program containing the resolved
5074 string and returns a pointer to the new node. If the string is
5075 zerolength a NOTHING node is emitted.
5077 On success RExC_parse is set to the char following the endbrace.
5078 Parsing failures will generate a fatal errorvia vFAIL(...)
5080 NOTE: We cache all results from the charnames handler locally in
5081 the RExC_charnames hash (created on first use) to prevent a charnames
5082 handler from playing silly-buggers and returning a short string and
5083 then a long string for a given pattern. Since the regexp program
5084 size is calculated during an initial parse this would result
5085 in a buffer overrun so we cache to prevent the charname result from
5086 changing during the course of the parse.
5090 S_reg_namedseq(pTHX_ RExC_state_t *pRExC_state, UV *valuep)
5092 char * name; /* start of the content of the name */
5093 char * endbrace; /* endbrace following the name */
5096 STRLEN len; /* this has various purposes throughout the code */
5097 bool cached = 0; /* if this is true then we shouldn't refcount dev sv_str */
5098 regnode *ret = NULL;
5100 if (*RExC_parse != '{') {
5101 vFAIL("Missing braces on \\N{}");
5103 name = RExC_parse+1;
5104 endbrace = strchr(RExC_parse, '}');
5107 vFAIL("Missing right brace on \\N{}");
5109 RExC_parse = endbrace + 1;
5112 /* RExC_parse points at the beginning brace,
5113 endbrace points at the last */
5114 if ( name[0]=='U' && name[1]=='+' ) {
5115 /* its a "unicode hex" notation {U+89AB} */
5116 I32 fl = PERL_SCAN_ALLOW_UNDERSCORES
5117 | PERL_SCAN_DISALLOW_PREFIX
5118 | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
5120 len = (STRLEN)(endbrace - name - 2);
5121 cp = grok_hex(name + 2, &len, &fl, NULL);
5122 if ( len != (STRLEN)(endbrace - name - 2) ) {
5131 sv_str= Perl_newSVpvf_nocontext("%c",(int)cp);
5133 /* fetch the charnames handler for this scope */
5134 HV * const table = GvHV(PL_hintgv);
5136 hv_fetchs(table, "charnames", FALSE) :
5138 SV *cv= cvp ? *cvp : NULL;
5141 /* create an SV with the name as argument */
5142 sv_name = newSVpvn(name, endbrace - name);
5144 if (!table || !(PL_hints & HINT_LOCALIZE_HH)) {
5145 vFAIL2("Constant(\\N{%s}) unknown: "
5146 "(possibly a missing \"use charnames ...\")",
5149 if (!cvp || !SvOK(*cvp)) { /* when $^H{charnames} = undef; */
5150 vFAIL2("Constant(\\N{%s}): "
5151 "$^H{charnames} is not defined",SvPVX(sv_name));
5156 if (!RExC_charnames) {
5157 /* make sure our cache is allocated */
5158 RExC_charnames = newHV();
5159 sv_2mortal((SV*)RExC_charnames);
5161 /* see if we have looked this one up before */
5162 he_str = hv_fetch_ent( RExC_charnames, sv_name, 0, 0 );
5164 sv_str = HeVAL(he_str);
5177 count= call_sv(cv, G_SCALAR);
5179 if (count == 1) { /* XXXX is this right? dmq */
5181 SvREFCNT_inc_simple_void(sv_str);
5189 if ( !sv_str || !SvOK(sv_str) ) {
5190 vFAIL2("Constant(\\N{%s}): Call to &{$^H{charnames}} "
5191 "did not return a defined value",SvPVX(sv_name));
5193 if (hv_store_ent( RExC_charnames, sv_name, sv_str, 0))
5198 char *p = SvPV(sv_str, len);
5201 if ( SvUTF8(sv_str) ) {
5202 *valuep = utf8_to_uvchr((U8*)p, &numlen);
5206 We have to turn on utf8 for high bit chars otherwise
5207 we get failures with
5209 "ss" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
5210 "SS" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
5212 This is different from what \x{} would do with the same
5213 codepoint, where the condition is > 0xFF.
5220 /* warn if we havent used the whole string? */
5222 if (numlen<len && SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5224 "Ignoring excess chars from \\N{%s} in character class",
5228 } else if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5230 "Ignoring zero length \\N{%s} in character class",
5235 SvREFCNT_dec(sv_name);
5237 SvREFCNT_dec(sv_str);
5238 return len ? NULL : (regnode *)&len;
5239 } else if(SvCUR(sv_str)) {
5244 char * parse_start = name-3; /* needed for the offsets */
5245 GET_RE_DEBUG_FLAGS_DECL; /* needed for the offsets */
5247 ret = reg_node(pRExC_state,
5248 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
5251 if ( RExC_utf8 && !SvUTF8(sv_str) ) {
5252 sv_utf8_upgrade(sv_str);
5253 } else if ( !RExC_utf8 && SvUTF8(sv_str) ) {
5257 p = SvPV(sv_str, len);
5259 /* len is the length written, charlen is the size the char read */
5260 for ( len = 0; p < pend; p += charlen ) {
5262 UV uvc = utf8_to_uvchr((U8*)p, &charlen);
5264 STRLEN foldlen,numlen;
5265 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
5266 uvc = toFOLD_uni(uvc, tmpbuf, &foldlen);
5267 /* Emit all the Unicode characters. */
5269 for (foldbuf = tmpbuf;
5273 uvc = utf8_to_uvchr(foldbuf, &numlen);
5275 const STRLEN unilen = reguni(pRExC_state, uvc, s);
5278 /* In EBCDIC the numlen
5279 * and unilen can differ. */
5281 if (numlen >= foldlen)
5285 break; /* "Can't happen." */
5288 const STRLEN unilen = reguni(pRExC_state, uvc, s);
5300 RExC_size += STR_SZ(len);
5303 RExC_emit += STR_SZ(len);
5305 Set_Node_Cur_Length(ret); /* MJD */
5307 nextchar(pRExC_state);
5309 ret = reg_node(pRExC_state,NOTHING);
5312 SvREFCNT_dec(sv_str);
5315 SvREFCNT_dec(sv_name);
5324 - regatom - the lowest level
5326 * Optimization: gobbles an entire sequence of ordinary characters so that
5327 * it can turn them into a single node, which is smaller to store and
5328 * faster to run. Backslashed characters are exceptions, each becoming a
5329 * separate node; the code is simpler that way and it's not worth fixing.
5331 * [Yes, it is worth fixing, some scripts can run twice the speed.]
5332 * [It looks like its ok, as in S_study_chunk we merge adjacent EXACT nodes]
5335 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
5338 register regnode *ret = NULL;
5340 char *parse_start = RExC_parse;
5341 GET_RE_DEBUG_FLAGS_DECL;
5342 DEBUG_PARSE("atom");
5343 *flagp = WORST; /* Tentatively. */
5346 switch (*RExC_parse) {
5348 RExC_seen_zerolen++;
5349 nextchar(pRExC_state);
5350 if (RExC_flags & PMf_MULTILINE)
5351 ret = reg_node(pRExC_state, MBOL);
5352 else if (RExC_flags & PMf_SINGLELINE)
5353 ret = reg_node(pRExC_state, SBOL);
5355 ret = reg_node(pRExC_state, BOL);
5356 Set_Node_Length(ret, 1); /* MJD */
5359 nextchar(pRExC_state);
5361 RExC_seen_zerolen++;
5362 if (RExC_flags & PMf_MULTILINE)
5363 ret = reg_node(pRExC_state, MEOL);
5364 else if (RExC_flags & PMf_SINGLELINE)
5365 ret = reg_node(pRExC_state, SEOL);
5367 ret = reg_node(pRExC_state, EOL);
5368 Set_Node_Length(ret, 1); /* MJD */
5371 nextchar(pRExC_state);
5372 if (RExC_flags & PMf_SINGLELINE)
5373 ret = reg_node(pRExC_state, SANY);
5375 ret = reg_node(pRExC_state, REG_ANY);
5376 *flagp |= HASWIDTH|SIMPLE;
5378 Set_Node_Length(ret, 1); /* MJD */
5382 char * const oregcomp_parse = ++RExC_parse;
5383 ret = regclass(pRExC_state,depth+1);
5384 if (*RExC_parse != ']') {
5385 RExC_parse = oregcomp_parse;
5386 vFAIL("Unmatched [");
5388 nextchar(pRExC_state);
5389 *flagp |= HASWIDTH|SIMPLE;
5390 Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
5394 nextchar(pRExC_state);
5395 ret = reg(pRExC_state, 1, &flags,depth+1);
5397 if (flags & TRYAGAIN) {
5398 if (RExC_parse == RExC_end) {
5399 /* Make parent create an empty node if needed. */
5407 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE);
5411 if (flags & TRYAGAIN) {
5415 vFAIL("Internal urp");
5416 /* Supposed to be caught earlier. */
5419 if (!regcurly(RExC_parse)) {
5428 vFAIL("Quantifier follows nothing");
5431 switch (*++RExC_parse) {
5433 RExC_seen_zerolen++;
5434 ret = reg_node(pRExC_state, SBOL);
5436 nextchar(pRExC_state);
5437 Set_Node_Length(ret, 2); /* MJD */
5440 ret = reg_node(pRExC_state, GPOS);
5441 RExC_seen |= REG_SEEN_GPOS;
5443 nextchar(pRExC_state);
5444 Set_Node_Length(ret, 2); /* MJD */
5447 ret = reg_node(pRExC_state, SEOL);
5449 RExC_seen_zerolen++; /* Do not optimize RE away */
5450 nextchar(pRExC_state);
5453 ret = reg_node(pRExC_state, EOS);
5455 RExC_seen_zerolen++; /* Do not optimize RE away */
5456 nextchar(pRExC_state);
5457 Set_Node_Length(ret, 2); /* MJD */
5460 ret = reg_node(pRExC_state, CANY);
5461 RExC_seen |= REG_SEEN_CANY;
5462 *flagp |= HASWIDTH|SIMPLE;
5463 nextchar(pRExC_state);
5464 Set_Node_Length(ret, 2); /* MJD */
5467 ret = reg_node(pRExC_state, CLUMP);
5469 nextchar(pRExC_state);
5470 Set_Node_Length(ret, 2); /* MJD */
5473 ret = reg_node(pRExC_state, (U8)(LOC ? ALNUML : ALNUM));
5474 *flagp |= HASWIDTH|SIMPLE;
5475 nextchar(pRExC_state);
5476 Set_Node_Length(ret, 2); /* MJD */
5479 ret = reg_node(pRExC_state, (U8)(LOC ? NALNUML : NALNUM));
5480 *flagp |= HASWIDTH|SIMPLE;
5481 nextchar(pRExC_state);
5482 Set_Node_Length(ret, 2); /* MJD */
5485 RExC_seen_zerolen++;
5486 RExC_seen |= REG_SEEN_LOOKBEHIND;
5487 ret = reg_node(pRExC_state, (U8)(LOC ? BOUNDL : BOUND));
5489 nextchar(pRExC_state);
5490 Set_Node_Length(ret, 2); /* MJD */
5493 RExC_seen_zerolen++;
5494 RExC_seen |= REG_SEEN_LOOKBEHIND;
5495 ret = reg_node(pRExC_state, (U8)(LOC ? NBOUNDL : NBOUND));
5497 nextchar(pRExC_state);
5498 Set_Node_Length(ret, 2); /* MJD */
5501 ret = reg_node(pRExC_state, (U8)(LOC ? SPACEL : SPACE));
5502 *flagp |= HASWIDTH|SIMPLE;
5503 nextchar(pRExC_state);
5504 Set_Node_Length(ret, 2); /* MJD */
5507 ret = reg_node(pRExC_state, (U8)(LOC ? NSPACEL : NSPACE));
5508 *flagp |= HASWIDTH|SIMPLE;
5509 nextchar(pRExC_state);
5510 Set_Node_Length(ret, 2); /* MJD */
5513 ret = reg_node(pRExC_state, DIGIT);
5514 *flagp |= HASWIDTH|SIMPLE;
5515 nextchar(pRExC_state);
5516 Set_Node_Length(ret, 2); /* MJD */
5519 ret = reg_node(pRExC_state, NDIGIT);
5520 *flagp |= HASWIDTH|SIMPLE;
5521 nextchar(pRExC_state);
5522 Set_Node_Length(ret, 2); /* MJD */
5527 char* const oldregxend = RExC_end;
5528 char* parse_start = RExC_parse - 2;
5530 if (RExC_parse[1] == '{') {
5531 /* a lovely hack--pretend we saw [\pX] instead */
5532 RExC_end = strchr(RExC_parse, '}');
5534 const U8 c = (U8)*RExC_parse;
5536 RExC_end = oldregxend;
5537 vFAIL2("Missing right brace on \\%c{}", c);
5542 RExC_end = RExC_parse + 2;
5543 if (RExC_end > oldregxend)
5544 RExC_end = oldregxend;
5548 ret = regclass(pRExC_state,depth+1);
5550 RExC_end = oldregxend;
5553 Set_Node_Offset(ret, parse_start + 2);
5554 Set_Node_Cur_Length(ret);
5555 nextchar(pRExC_state);
5556 *flagp |= HASWIDTH|SIMPLE;
5560 /* Handle \N{NAME} here and not below because it can be
5561 multicharacter. join_exact() will join them up later on.
5562 Also this makes sure that things like /\N{BLAH}+/ and
5563 \N{BLAH} being multi char Just Happen. dmq*/
5565 ret= reg_namedseq(pRExC_state, NULL);
5577 case '1': case '2': case '3': case '4':
5578 case '5': case '6': case '7': case '8': case '9':
5580 const I32 num = atoi(RExC_parse);
5582 if (num > 9 && num >= RExC_npar)
5585 char * const parse_start = RExC_parse - 1; /* MJD */
5586 while (isDIGIT(*RExC_parse))
5589 if (!SIZE_ONLY && num > (I32)RExC_rx->nparens)
5590 vFAIL("Reference to nonexistent group");
5592 ret = reganode(pRExC_state,
5593 (U8)(FOLD ? (LOC ? REFFL : REFF) : REF),
5597 /* override incorrect value set in reganode MJD */
5598 Set_Node_Offset(ret, parse_start+1);
5599 Set_Node_Cur_Length(ret); /* MJD */
5601 nextchar(pRExC_state);
5606 if (RExC_parse >= RExC_end)
5607 FAIL("Trailing \\");
5610 /* Do not generate "unrecognized" warnings here, we fall
5611 back into the quick-grab loop below */
5618 if (RExC_flags & PMf_EXTENDED) {
5619 while (RExC_parse < RExC_end && *RExC_parse != '\n')
5621 if (RExC_parse < RExC_end)
5627 register STRLEN len;
5632 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
5634 parse_start = RExC_parse - 1;
5640 ret = reg_node(pRExC_state,
5641 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
5643 for (len = 0, p = RExC_parse - 1;
5644 len < 127 && p < RExC_end;
5647 char * const oldp = p;
5649 if (RExC_flags & PMf_EXTENDED)
5650 p = regwhite(p, RExC_end);
5698 ender = ASCII_TO_NATIVE('\033');
5702 ender = ASCII_TO_NATIVE('\007');
5707 char* const e = strchr(p, '}');
5711 vFAIL("Missing right brace on \\x{}");
5714 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
5715 | PERL_SCAN_DISALLOW_PREFIX;
5716 STRLEN numlen = e - p - 1;
5717 ender = grok_hex(p + 1, &numlen, &flags, NULL);
5724 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
5726 ender = grok_hex(p, &numlen, &flags, NULL);
5732 ender = UCHARAT(p++);
5733 ender = toCTRL(ender);
5735 case '0': case '1': case '2': case '3':case '4':
5736 case '5': case '6': case '7': case '8':case '9':
5738 (isDIGIT(p[1]) && atoi(p) >= RExC_npar) ) {
5741 ender = grok_oct(p, &numlen, &flags, NULL);
5751 FAIL("Trailing \\");
5754 if (!SIZE_ONLY&& isALPHA(*p) && ckWARN(WARN_REGEXP))
5755 vWARN2(p + 1, "Unrecognized escape \\%c passed through", UCHARAT(p));
5756 goto normal_default;
5761 if (UTF8_IS_START(*p) && UTF) {
5763 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
5764 &numlen, UTF8_ALLOW_DEFAULT);
5771 if (RExC_flags & PMf_EXTENDED)
5772 p = regwhite(p, RExC_end);
5774 /* Prime the casefolded buffer. */
5775 ender = toFOLD_uni(ender, tmpbuf, &foldlen);
5777 if (ISMULT2(p)) { /* Back off on ?+*. */
5782 /* Emit all the Unicode characters. */
5784 for (foldbuf = tmpbuf;
5786 foldlen -= numlen) {
5787 ender = utf8_to_uvchr(foldbuf, &numlen);
5789 const STRLEN unilen = reguni(pRExC_state, ender, s);
5792 /* In EBCDIC the numlen
5793 * and unilen can differ. */
5795 if (numlen >= foldlen)
5799 break; /* "Can't happen." */
5803 const STRLEN unilen = reguni(pRExC_state, ender, s);
5812 REGC((char)ender, s++);
5818 /* Emit all the Unicode characters. */
5820 for (foldbuf = tmpbuf;
5822 foldlen -= numlen) {
5823 ender = utf8_to_uvchr(foldbuf, &numlen);
5825 const STRLEN unilen = reguni(pRExC_state, ender, s);
5828 /* In EBCDIC the numlen
5829 * and unilen can differ. */
5831 if (numlen >= foldlen)
5839 const STRLEN unilen = reguni(pRExC_state, ender, s);
5848 REGC((char)ender, s++);
5852 Set_Node_Cur_Length(ret); /* MJD */
5853 nextchar(pRExC_state);
5855 /* len is STRLEN which is unsigned, need to copy to signed */
5858 vFAIL("Internal disaster");
5862 if (len == 1 && UNI_IS_INVARIANT(ender))
5866 RExC_size += STR_SZ(len);
5869 RExC_emit += STR_SZ(len);
5875 /* If the encoding pragma is in effect recode the text of
5876 * any EXACT-kind nodes. */
5877 if (ret && PL_encoding && PL_regkind[OP(ret)] == EXACT) {
5878 const STRLEN oldlen = STR_LEN(ret);
5879 SV * const sv = sv_2mortal(newSVpvn(STRING(ret), oldlen));
5883 if (sv_utf8_downgrade(sv, TRUE)) {
5884 const char * const s = sv_recode_to_utf8(sv, PL_encoding);
5885 const STRLEN newlen = SvCUR(sv);
5890 GET_RE_DEBUG_FLAGS_DECL;
5891 DEBUG_COMPILE_r(PerlIO_printf(Perl_debug_log, "recode %*s to %*s\n",
5892 (int)oldlen, STRING(ret),
5894 Copy(s, STRING(ret), newlen, char);
5895 STR_LEN(ret) += newlen - oldlen;
5896 RExC_emit += STR_SZ(newlen) - STR_SZ(oldlen);
5898 RExC_size += STR_SZ(newlen) - STR_SZ(oldlen);
5906 S_regwhite(char *p, const char *e)
5911 else if (*p == '#') {
5914 } while (p < e && *p != '\n');
5922 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
5923 Character classes ([:foo:]) can also be negated ([:^foo:]).
5924 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
5925 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
5926 but trigger failures because they are currently unimplemented. */
5928 #define POSIXCC_DONE(c) ((c) == ':')
5929 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
5930 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
5933 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
5936 I32 namedclass = OOB_NAMEDCLASS;
5938 if (value == '[' && RExC_parse + 1 < RExC_end &&
5939 /* I smell either [: or [= or [. -- POSIX has been here, right? */
5940 POSIXCC(UCHARAT(RExC_parse))) {
5941 const char c = UCHARAT(RExC_parse);
5942 char* const s = RExC_parse++;
5944 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
5946 if (RExC_parse == RExC_end)
5947 /* Grandfather lone [:, [=, [. */
5950 const char* const t = RExC_parse++; /* skip over the c */
5953 if (UCHARAT(RExC_parse) == ']') {
5954 const char *posixcc = s + 1;
5955 RExC_parse++; /* skip over the ending ] */
5958 const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
5959 const I32 skip = t - posixcc;
5961 /* Initially switch on the length of the name. */
5964 if (memEQ(posixcc, "word", 4)) /* this is not POSIX, this is the Perl \w */
5965 namedclass = complement ? ANYOF_NALNUM : ANYOF_ALNUM;
5968 /* Names all of length 5. */
5969 /* alnum alpha ascii blank cntrl digit graph lower
5970 print punct space upper */
5971 /* Offset 4 gives the best switch position. */
5972 switch (posixcc[4]) {
5974 if (memEQ(posixcc, "alph", 4)) /* alpha */
5975 namedclass = complement ? ANYOF_NALPHA : ANYOF_ALPHA;
5978 if (memEQ(posixcc, "spac", 4)) /* space */
5979 namedclass = complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
5982 if (memEQ(posixcc, "grap", 4)) /* graph */
5983 namedclass = complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
5986 if (memEQ(posixcc, "asci", 4)) /* ascii */
5987 namedclass = complement ? ANYOF_NASCII : ANYOF_ASCII;
5990 if (memEQ(posixcc, "blan", 4)) /* blank */
5991 namedclass = complement ? ANYOF_NBLANK : ANYOF_BLANK;
5994 if (memEQ(posixcc, "cntr", 4)) /* cntrl */
5995 namedclass = complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
5998 if (memEQ(posixcc, "alnu", 4)) /* alnum */
5999 namedclass = complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
6002 if (memEQ(posixcc, "lowe", 4)) /* lower */
6003 namedclass = complement ? ANYOF_NLOWER : ANYOF_LOWER;
6004 else if (memEQ(posixcc, "uppe", 4)) /* upper */
6005 namedclass = complement ? ANYOF_NUPPER : ANYOF_UPPER;
6008 if (memEQ(posixcc, "digi", 4)) /* digit */
6009 namedclass = complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
6010 else if (memEQ(posixcc, "prin", 4)) /* print */
6011 namedclass = complement ? ANYOF_NPRINT : ANYOF_PRINT;
6012 else if (memEQ(posixcc, "punc", 4)) /* punct */
6013 namedclass = complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
6018 if (memEQ(posixcc, "xdigit", 6))
6019 namedclass = complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
6023 if (namedclass == OOB_NAMEDCLASS)
6024 Simple_vFAIL3("POSIX class [:%.*s:] unknown",
6026 assert (posixcc[skip] == ':');
6027 assert (posixcc[skip+1] == ']');
6028 } else if (!SIZE_ONLY) {
6029 /* [[=foo=]] and [[.foo.]] are still future. */
6031 /* adjust RExC_parse so the warning shows after
6033 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
6035 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
6038 /* Maternal grandfather:
6039 * "[:" ending in ":" but not in ":]" */
6049 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
6052 if (POSIXCC(UCHARAT(RExC_parse))) {
6053 const char *s = RExC_parse;
6054 const char c = *s++;
6058 if (*s && c == *s && s[1] == ']') {
6059 if (ckWARN(WARN_REGEXP))
6061 "POSIX syntax [%c %c] belongs inside character classes",
6064 /* [[=foo=]] and [[.foo.]] are still future. */
6065 if (POSIXCC_NOTYET(c)) {
6066 /* adjust RExC_parse so the error shows after
6068 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
6070 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
6078 parse a class specification and produce either an ANYOF node that
6079 matches the pattern. If the pattern matches a single char only and
6080 that char is < 256 then we produce an EXACT node instead.
6083 S_regclass(pTHX_ RExC_state_t *pRExC_state, U32 depth)
6086 register UV value = 0;
6087 register UV nextvalue;
6088 register IV prevvalue = OOB_UNICODE;
6089 register IV range = 0;
6090 register regnode *ret;
6093 char *rangebegin = NULL;
6094 bool need_class = 0;
6097 bool optimize_invert = TRUE;
6098 AV* unicode_alternate = NULL;
6100 UV literal_endpoint = 0;
6102 UV stored = 0; /* number of chars stored in the class */
6104 regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
6105 case we need to change the emitted regop to an EXACT. */
6106 const char * orig_parse = RExC_parse;
6107 GET_RE_DEBUG_FLAGS_DECL;
6109 PERL_UNUSED_ARG(depth);
6112 DEBUG_PARSE("clas");
6114 /* Assume we are going to generate an ANYOF node. */
6115 ret = reganode(pRExC_state, ANYOF, 0);
6118 ANYOF_FLAGS(ret) = 0;
6120 if (UCHARAT(RExC_parse) == '^') { /* Complement of range. */
6124 ANYOF_FLAGS(ret) |= ANYOF_INVERT;
6128 RExC_size += ANYOF_SKIP;
6129 listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
6132 RExC_emit += ANYOF_SKIP;
6134 ANYOF_FLAGS(ret) |= ANYOF_FOLD;
6136 ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
6137 ANYOF_BITMAP_ZERO(ret);
6138 listsv = newSVpvs("# comment\n");
6141 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
6143 if (!SIZE_ONLY && POSIXCC(nextvalue))
6144 checkposixcc(pRExC_state);
6146 /* allow 1st char to be ] (allowing it to be - is dealt with later) */
6147 if (UCHARAT(RExC_parse) == ']')
6151 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
6155 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
6158 rangebegin = RExC_parse;
6160 value = utf8n_to_uvchr((U8*)RExC_parse,
6161 RExC_end - RExC_parse,
6162 &numlen, UTF8_ALLOW_DEFAULT);
6163 RExC_parse += numlen;
6166 value = UCHARAT(RExC_parse++);
6168 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
6169 if (value == '[' && POSIXCC(nextvalue))
6170 namedclass = regpposixcc(pRExC_state, value);
6171 else if (value == '\\') {
6173 value = utf8n_to_uvchr((U8*)RExC_parse,
6174 RExC_end - RExC_parse,
6175 &numlen, UTF8_ALLOW_DEFAULT);
6176 RExC_parse += numlen;
6179 value = UCHARAT(RExC_parse++);
6180 /* Some compilers cannot handle switching on 64-bit integer
6181 * values, therefore value cannot be an UV. Yes, this will
6182 * be a problem later if we want switch on Unicode.
6183 * A similar issue a little bit later when switching on
6184 * namedclass. --jhi */
6185 switch ((I32)value) {
6186 case 'w': namedclass = ANYOF_ALNUM; break;
6187 case 'W': namedclass = ANYOF_NALNUM; break;
6188 case 's': namedclass = ANYOF_SPACE; break;
6189 case 'S': namedclass = ANYOF_NSPACE; break;
6190 case 'd': namedclass = ANYOF_DIGIT; break;
6191 case 'D': namedclass = ANYOF_NDIGIT; break;
6192 case 'N': /* Handle \N{NAME} in class */
6194 /* We only pay attention to the first char of
6195 multichar strings being returned. I kinda wonder
6196 if this makes sense as it does change the behaviour
6197 from earlier versions, OTOH that behaviour was broken
6199 UV v; /* value is register so we cant & it /grrr */
6200 if (reg_namedseq(pRExC_state, &v)) {
6210 if (RExC_parse >= RExC_end)
6211 vFAIL2("Empty \\%c{}", (U8)value);
6212 if (*RExC_parse == '{') {
6213 const U8 c = (U8)value;
6214 e = strchr(RExC_parse++, '}');
6216 vFAIL2("Missing right brace on \\%c{}", c);
6217 while (isSPACE(UCHARAT(RExC_parse)))
6219 if (e == RExC_parse)
6220 vFAIL2("Empty \\%c{}", c);
6222 while (isSPACE(UCHARAT(RExC_parse + n - 1)))
6230 if (UCHARAT(RExC_parse) == '^') {
6233 value = value == 'p' ? 'P' : 'p'; /* toggle */
6234 while (isSPACE(UCHARAT(RExC_parse))) {
6239 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%.*s\n",
6240 (value=='p' ? '+' : '!'), (int)n, RExC_parse);
6243 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
6244 namedclass = ANYOF_MAX; /* no official name, but it's named */
6247 case 'n': value = '\n'; break;
6248 case 'r': value = '\r'; break;
6249 case 't': value = '\t'; break;
6250 case 'f': value = '\f'; break;
6251 case 'b': value = '\b'; break;
6252 case 'e': value = ASCII_TO_NATIVE('\033');break;
6253 case 'a': value = ASCII_TO_NATIVE('\007');break;
6255 if (*RExC_parse == '{') {
6256 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
6257 | PERL_SCAN_DISALLOW_PREFIX;
6258 char * const e = strchr(RExC_parse++, '}');
6260 vFAIL("Missing right brace on \\x{}");
6262 numlen = e - RExC_parse;
6263 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
6267 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
6269 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
6270 RExC_parse += numlen;
6274 value = UCHARAT(RExC_parse++);
6275 value = toCTRL(value);
6277 case '0': case '1': case '2': case '3': case '4':
6278 case '5': case '6': case '7': case '8': case '9':
6282 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
6283 RExC_parse += numlen;
6287 if (!SIZE_ONLY && isALPHA(value) && ckWARN(WARN_REGEXP))
6289 "Unrecognized escape \\%c in character class passed through",
6293 } /* end of \blah */
6299 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
6301 if (!SIZE_ONLY && !need_class)
6302 ANYOF_CLASS_ZERO(ret);
6306 /* a bad range like a-\d, a-[:digit:] ? */
6309 if (ckWARN(WARN_REGEXP)) {
6311 RExC_parse >= rangebegin ?
6312 RExC_parse - rangebegin : 0;
6314 "False [] range \"%*.*s\"",
6317 if (prevvalue < 256) {
6318 ANYOF_BITMAP_SET(ret, prevvalue);
6319 ANYOF_BITMAP_SET(ret, '-');
6322 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
6323 Perl_sv_catpvf(aTHX_ listsv,
6324 "%04"UVxf"\n%04"UVxf"\n", (UV)prevvalue, (UV) '-');
6328 range = 0; /* this was not a true range */
6332 const char *what = NULL;
6335 if (namedclass > OOB_NAMEDCLASS)
6336 optimize_invert = FALSE;
6337 /* Possible truncation here but in some 64-bit environments
6338 * the compiler gets heartburn about switch on 64-bit values.
6339 * A similar issue a little earlier when switching on value.
6341 switch ((I32)namedclass) {
6344 ANYOF_CLASS_SET(ret, ANYOF_ALNUM);
6346 for (value = 0; value < 256; value++)
6348 ANYOF_BITMAP_SET(ret, value);
6355 ANYOF_CLASS_SET(ret, ANYOF_NALNUM);
6357 for (value = 0; value < 256; value++)
6358 if (!isALNUM(value))
6359 ANYOF_BITMAP_SET(ret, value);
6366 ANYOF_CLASS_SET(ret, ANYOF_ALNUMC);
6368 for (value = 0; value < 256; value++)
6369 if (isALNUMC(value))
6370 ANYOF_BITMAP_SET(ret, value);
6377 ANYOF_CLASS_SET(ret, ANYOF_NALNUMC);
6379 for (value = 0; value < 256; value++)
6380 if (!isALNUMC(value))
6381 ANYOF_BITMAP_SET(ret, value);
6388 ANYOF_CLASS_SET(ret, ANYOF_ALPHA);
6390 for (value = 0; value < 256; value++)
6392 ANYOF_BITMAP_SET(ret, value);
6399 ANYOF_CLASS_SET(ret, ANYOF_NALPHA);
6401 for (value = 0; value < 256; value++)
6402 if (!isALPHA(value))
6403 ANYOF_BITMAP_SET(ret, value);
6410 ANYOF_CLASS_SET(ret, ANYOF_ASCII);
6413 for (value = 0; value < 128; value++)
6414 ANYOF_BITMAP_SET(ret, value);
6416 for (value = 0; value < 256; value++) {
6418 ANYOF_BITMAP_SET(ret, value);
6427 ANYOF_CLASS_SET(ret, ANYOF_NASCII);
6430 for (value = 128; value < 256; value++)
6431 ANYOF_BITMAP_SET(ret, value);
6433 for (value = 0; value < 256; value++) {
6434 if (!isASCII(value))
6435 ANYOF_BITMAP_SET(ret, value);
6444 ANYOF_CLASS_SET(ret, ANYOF_BLANK);
6446 for (value = 0; value < 256; value++)
6448 ANYOF_BITMAP_SET(ret, value);
6455 ANYOF_CLASS_SET(ret, ANYOF_NBLANK);
6457 for (value = 0; value < 256; value++)
6458 if (!isBLANK(value))
6459 ANYOF_BITMAP_SET(ret, value);
6466 ANYOF_CLASS_SET(ret, ANYOF_CNTRL);
6468 for (value = 0; value < 256; value++)
6470 ANYOF_BITMAP_SET(ret, value);
6477 ANYOF_CLASS_SET(ret, ANYOF_NCNTRL);
6479 for (value = 0; value < 256; value++)
6480 if (!isCNTRL(value))
6481 ANYOF_BITMAP_SET(ret, value);
6488 ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
6490 /* consecutive digits assumed */
6491 for (value = '0'; value <= '9'; value++)
6492 ANYOF_BITMAP_SET(ret, value);
6499 ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
6501 /* consecutive digits assumed */
6502 for (value = 0; value < '0'; value++)
6503 ANYOF_BITMAP_SET(ret, value);
6504 for (value = '9' + 1; value < 256; value++)
6505 ANYOF_BITMAP_SET(ret, value);
6512 ANYOF_CLASS_SET(ret, ANYOF_GRAPH);
6514 for (value = 0; value < 256; value++)
6516 ANYOF_BITMAP_SET(ret, value);
6523 ANYOF_CLASS_SET(ret, ANYOF_NGRAPH);
6525 for (value = 0; value < 256; value++)
6526 if (!isGRAPH(value))
6527 ANYOF_BITMAP_SET(ret, value);
6534 ANYOF_CLASS_SET(ret, ANYOF_LOWER);
6536 for (value = 0; value < 256; value++)
6538 ANYOF_BITMAP_SET(ret, value);
6545 ANYOF_CLASS_SET(ret, ANYOF_NLOWER);
6547 for (value = 0; value < 256; value++)
6548 if (!isLOWER(value))
6549 ANYOF_BITMAP_SET(ret, value);
6556 ANYOF_CLASS_SET(ret, ANYOF_PRINT);
6558 for (value = 0; value < 256; value++)
6560 ANYOF_BITMAP_SET(ret, value);
6567 ANYOF_CLASS_SET(ret, ANYOF_NPRINT);
6569 for (value = 0; value < 256; value++)
6570 if (!isPRINT(value))
6571 ANYOF_BITMAP_SET(ret, value);
6578 ANYOF_CLASS_SET(ret, ANYOF_PSXSPC);
6580 for (value = 0; value < 256; value++)
6581 if (isPSXSPC(value))
6582 ANYOF_BITMAP_SET(ret, value);
6589 ANYOF_CLASS_SET(ret, ANYOF_NPSXSPC);
6591 for (value = 0; value < 256; value++)
6592 if (!isPSXSPC(value))
6593 ANYOF_BITMAP_SET(ret, value);
6600 ANYOF_CLASS_SET(ret, ANYOF_PUNCT);
6602 for (value = 0; value < 256; value++)
6604 ANYOF_BITMAP_SET(ret, value);
6611 ANYOF_CLASS_SET(ret, ANYOF_NPUNCT);
6613 for (value = 0; value < 256; value++)
6614 if (!isPUNCT(value))
6615 ANYOF_BITMAP_SET(ret, value);
6622 ANYOF_CLASS_SET(ret, ANYOF_SPACE);
6624 for (value = 0; value < 256; value++)
6626 ANYOF_BITMAP_SET(ret, value);
6633 ANYOF_CLASS_SET(ret, ANYOF_NSPACE);
6635 for (value = 0; value < 256; value++)
6636 if (!isSPACE(value))
6637 ANYOF_BITMAP_SET(ret, value);
6644 ANYOF_CLASS_SET(ret, ANYOF_UPPER);
6646 for (value = 0; value < 256; value++)
6648 ANYOF_BITMAP_SET(ret, value);
6655 ANYOF_CLASS_SET(ret, ANYOF_NUPPER);
6657 for (value = 0; value < 256; value++)
6658 if (!isUPPER(value))
6659 ANYOF_BITMAP_SET(ret, value);
6666 ANYOF_CLASS_SET(ret, ANYOF_XDIGIT);
6668 for (value = 0; value < 256; value++)
6669 if (isXDIGIT(value))
6670 ANYOF_BITMAP_SET(ret, value);
6677 ANYOF_CLASS_SET(ret, ANYOF_NXDIGIT);
6679 for (value = 0; value < 256; value++)
6680 if (!isXDIGIT(value))
6681 ANYOF_BITMAP_SET(ret, value);
6687 /* this is to handle \p and \P */
6690 vFAIL("Invalid [::] class");
6694 /* Strings such as "+utf8::isWord\n" */
6695 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::Is%s\n", yesno, what);
6698 ANYOF_FLAGS(ret) |= ANYOF_CLASS;
6701 } /* end of namedclass \blah */
6704 if (prevvalue > (IV)value) /* b-a */ {
6705 const int w = RExC_parse - rangebegin;
6706 Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
6707 range = 0; /* not a valid range */
6711 prevvalue = value; /* save the beginning of the range */
6712 if (*RExC_parse == '-' && RExC_parse+1 < RExC_end &&
6713 RExC_parse[1] != ']') {
6716 /* a bad range like \w-, [:word:]- ? */
6717 if (namedclass > OOB_NAMEDCLASS) {
6718 if (ckWARN(WARN_REGEXP)) {
6720 RExC_parse >= rangebegin ?
6721 RExC_parse - rangebegin : 0;
6723 "False [] range \"%*.*s\"",
6727 ANYOF_BITMAP_SET(ret, '-');
6729 range = 1; /* yeah, it's a range! */
6730 continue; /* but do it the next time */
6734 /* now is the next time */
6735 /*stored += (value - prevvalue + 1);*/
6737 if (prevvalue < 256) {
6738 const IV ceilvalue = value < 256 ? value : 255;
6741 /* In EBCDIC [\x89-\x91] should include
6742 * the \x8e but [i-j] should not. */
6743 if (literal_endpoint == 2 &&
6744 ((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
6745 (isUPPER(prevvalue) && isUPPER(ceilvalue))))
6747 if (isLOWER(prevvalue)) {
6748 for (i = prevvalue; i <= ceilvalue; i++)
6750 ANYOF_BITMAP_SET(ret, i);
6752 for (i = prevvalue; i <= ceilvalue; i++)
6754 ANYOF_BITMAP_SET(ret, i);
6759 for (i = prevvalue; i <= ceilvalue; i++) {
6760 if (!ANYOF_BITMAP_TEST(ret,i)) {
6762 ANYOF_BITMAP_SET(ret, i);
6766 if (value > 255 || UTF) {
6767 const UV prevnatvalue = NATIVE_TO_UNI(prevvalue);
6768 const UV natvalue = NATIVE_TO_UNI(value);
6769 stored+=2; /* can't optimize this class */
6770 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
6771 if (prevnatvalue < natvalue) { /* what about > ? */
6772 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
6773 prevnatvalue, natvalue);
6775 else if (prevnatvalue == natvalue) {
6776 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n", natvalue);
6778 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
6780 const UV f = to_uni_fold(natvalue, foldbuf, &foldlen);
6782 #ifdef EBCDIC /* RD t/uni/fold ff and 6b */
6783 if (RExC_precomp[0] == ':' &&
6784 RExC_precomp[1] == '[' &&
6785 (f == 0xDF || f == 0x92)) {
6786 f = NATIVE_TO_UNI(f);
6789 /* If folding and foldable and a single
6790 * character, insert also the folded version
6791 * to the charclass. */
6793 #ifdef EBCDIC /* RD tunifold ligatures s,t fb05, fb06 */
6794 if ((RExC_precomp[0] == ':' &&
6795 RExC_precomp[1] == '[' &&
6797 (value == 0xFB05 || value == 0xFB06))) ?
6798 foldlen == ((STRLEN)UNISKIP(f) - 1) :
6799 foldlen == (STRLEN)UNISKIP(f) )
6801 if (foldlen == (STRLEN)UNISKIP(f))
6803 Perl_sv_catpvf(aTHX_ listsv,
6806 /* Any multicharacter foldings
6807 * require the following transform:
6808 * [ABCDEF] -> (?:[ABCabcDEFd]|pq|rst)
6809 * where E folds into "pq" and F folds
6810 * into "rst", all other characters
6811 * fold to single characters. We save
6812 * away these multicharacter foldings,
6813 * to be later saved as part of the
6814 * additional "s" data. */
6817 if (!unicode_alternate)
6818 unicode_alternate = newAV();
6819 sv = newSVpvn((char*)foldbuf, foldlen);
6821 av_push(unicode_alternate, sv);
6825 /* If folding and the value is one of the Greek
6826 * sigmas insert a few more sigmas to make the
6827 * folding rules of the sigmas to work right.
6828 * Note that not all the possible combinations
6829 * are handled here: some of them are handled
6830 * by the standard folding rules, and some of
6831 * them (literal or EXACTF cases) are handled
6832 * during runtime in regexec.c:S_find_byclass(). */
6833 if (value == UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA) {
6834 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
6835 (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA);
6836 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
6837 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
6839 else if (value == UNICODE_GREEK_CAPITAL_LETTER_SIGMA)
6840 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
6841 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
6846 literal_endpoint = 0;
6850 range = 0; /* this range (if it was one) is done now */
6854 ANYOF_FLAGS(ret) |= ANYOF_LARGE;
6856 RExC_size += ANYOF_CLASS_ADD_SKIP;
6858 RExC_emit += ANYOF_CLASS_ADD_SKIP;
6864 /****** !SIZE_ONLY AFTER HERE *********/
6866 if( stored == 1 && value < 256
6867 && !( ANYOF_FLAGS(ret) & ( ANYOF_FLAGS_ALL ^ ANYOF_FOLD ) )
6869 /* optimize single char class to an EXACT node
6870 but *only* when its not a UTF/high char */
6871 const char * cur_parse= RExC_parse;
6872 RExC_emit = (regnode *)orig_emit;
6873 RExC_parse = (char *)orig_parse;
6874 ret = reg_node(pRExC_state,
6875 (U8)((ANYOF_FLAGS(ret) & ANYOF_FOLD) ? EXACTF : EXACT));
6876 RExC_parse = (char *)cur_parse;
6877 *STRING(ret)= (char)value;
6879 RExC_emit += STR_SZ(1);
6882 /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
6883 if ( /* If the only flag is folding (plus possibly inversion). */
6884 ((ANYOF_FLAGS(ret) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD)
6886 for (value = 0; value < 256; ++value) {
6887 if (ANYOF_BITMAP_TEST(ret, value)) {
6888 UV fold = PL_fold[value];
6891 ANYOF_BITMAP_SET(ret, fold);
6894 ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
6897 /* optimize inverted simple patterns (e.g. [^a-z]) */
6898 if (optimize_invert &&
6899 /* If the only flag is inversion. */
6900 (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
6901 for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
6902 ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
6903 ANYOF_FLAGS(ret) = ANYOF_UNICODE_ALL;
6906 AV * const av = newAV();
6908 /* The 0th element stores the character class description
6909 * in its textual form: used later (regexec.c:Perl_regclass_swash())
6910 * to initialize the appropriate swash (which gets stored in
6911 * the 1st element), and also useful for dumping the regnode.
6912 * The 2nd element stores the multicharacter foldings,
6913 * used later (regexec.c:S_reginclass()). */
6914 av_store(av, 0, listsv);
6915 av_store(av, 1, NULL);
6916 av_store(av, 2, (SV*)unicode_alternate);
6917 rv = newRV_noinc((SV*)av);
6918 n = add_data(pRExC_state, 1, "s");
6919 RExC_rx->data->data[n] = (void*)rv;
6926 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
6928 char* const retval = RExC_parse++;
6931 if (*RExC_parse == '(' && RExC_parse[1] == '?' &&
6932 RExC_parse[2] == '#') {
6933 while (*RExC_parse != ')') {
6934 if (RExC_parse == RExC_end)
6935 FAIL("Sequence (?#... not terminated");
6941 if (RExC_flags & PMf_EXTENDED) {
6942 if (isSPACE(*RExC_parse)) {
6946 else if (*RExC_parse == '#') {
6947 while (RExC_parse < RExC_end)
6948 if (*RExC_parse++ == '\n') break;
6957 - reg_node - emit a node
6959 STATIC regnode * /* Location. */
6960 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
6963 register regnode *ptr;
6964 regnode * const ret = RExC_emit;
6965 GET_RE_DEBUG_FLAGS_DECL;
6968 SIZE_ALIGN(RExC_size);
6972 NODE_ALIGN_FILL(ret);
6974 FILL_ADVANCE_NODE(ptr, op);
6975 if (RExC_offsets) { /* MJD */
6976 MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n",
6977 "reg_node", __LINE__,
6979 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0]
6980 ? "Overwriting end of array!\n" : "OK",
6981 (UV)(RExC_emit - RExC_emit_start),
6982 (UV)(RExC_parse - RExC_start),
6983 (UV)RExC_offsets[0]));
6984 Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
6993 - reganode - emit a node with an argument
6995 STATIC regnode * /* Location. */
6996 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
6999 register regnode *ptr;
7000 regnode * const ret = RExC_emit;
7001 GET_RE_DEBUG_FLAGS_DECL;
7004 SIZE_ALIGN(RExC_size);
7009 assert(2==regarglen[op]+1);
7011 Anything larger than this has to allocate the extra amount.
7012 If we changed this to be:
7014 RExC_size += (1 + regarglen[op]);
7016 then it wouldn't matter. Its not clear what side effect
7017 might come from that so its not done so far.
7023 NODE_ALIGN_FILL(ret);
7025 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
7026 if (RExC_offsets) { /* MJD */
7027 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
7031 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ?
7032 "Overwriting end of array!\n" : "OK",
7033 (UV)(RExC_emit - RExC_emit_start),
7034 (UV)(RExC_parse - RExC_start),
7035 (UV)RExC_offsets[0]));
7036 Set_Cur_Node_Offset;
7045 - reguni - emit (if appropriate) a Unicode character
7048 S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
7051 return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
7055 - reginsert - insert an operator in front of already-emitted operand
7057 * Means relocating the operand.
7060 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
7063 register regnode *src;
7064 register regnode *dst;
7065 register regnode *place;
7066 const int offset = regarglen[(U8)op];
7067 const int size = NODE_STEP_REGNODE + offset;
7068 GET_RE_DEBUG_FLAGS_DECL;
7069 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
7070 DEBUG_PARSE_FMT("inst"," - %s",reg_name[op]);
7081 for ( paren=0 ; paren < RExC_npar ; paren++ ) {
7082 if ( RExC_parens[paren] >= src )
7083 RExC_parens[paren] += size;
7087 while (src > opnd) {
7088 StructCopy(--src, --dst, regnode);
7089 if (RExC_offsets) { /* MJD 20010112 */
7090 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
7094 (UV)(dst - RExC_emit_start) > RExC_offsets[0]
7095 ? "Overwriting end of array!\n" : "OK",
7096 (UV)(src - RExC_emit_start),
7097 (UV)(dst - RExC_emit_start),
7098 (UV)RExC_offsets[0]));
7099 Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
7100 Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
7105 place = opnd; /* Op node, where operand used to be. */
7106 if (RExC_offsets) { /* MJD */
7107 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
7111 (UV)(place - RExC_emit_start) > RExC_offsets[0]
7112 ? "Overwriting end of array!\n" : "OK",
7113 (UV)(place - RExC_emit_start),
7114 (UV)(RExC_parse - RExC_start),
7115 (UV)RExC_offsets[0]));
7116 Set_Node_Offset(place, RExC_parse);
7117 Set_Node_Length(place, 1);
7119 src = NEXTOPER(place);
7120 FILL_ADVANCE_NODE(place, op);
7121 Zero(src, offset, regnode);
7125 - regtail - set the next-pointer at the end of a node chain of p to val.
7126 - SEE ALSO: regtail_study
7128 /* TODO: All three parms should be const */
7130 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
7133 register regnode *scan;
7134 GET_RE_DEBUG_FLAGS_DECL;
7136 PERL_UNUSED_ARG(depth);
7142 /* Find last node. */
7145 regnode * const temp = regnext(scan);
7147 SV * const mysv=sv_newmortal();
7148 DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
7149 regprop(RExC_rx, mysv, scan);
7150 PerlIO_printf(Perl_debug_log, "~ %s (%d)\n",
7151 SvPV_nolen_const(mysv), REG_NODE_NUM(scan));
7158 if (reg_off_by_arg[OP(scan)]) {
7159 ARG_SET(scan, val - scan);
7162 NEXT_OFF(scan) = val - scan;
7168 - regtail_study - set the next-pointer at the end of a node chain of p to val.
7169 - Look for optimizable sequences at the same time.
7170 - currently only looks for EXACT chains.
7172 This is expermental code. The idea is to use this routine to perform
7173 in place optimizations on branches and groups as they are constructed,
7174 with the long term intention of removing optimization from study_chunk so
7175 that it is purely analytical.
7177 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
7178 to control which is which.
7181 /* TODO: All four parms should be const */
7184 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
7187 register regnode *scan;
7189 #ifdef EXPERIMENTAL_INPLACESCAN
7193 GET_RE_DEBUG_FLAGS_DECL;
7199 /* Find last node. */
7203 regnode * const temp = regnext(scan);
7204 #ifdef EXPERIMENTAL_INPLACESCAN
7205 if (PL_regkind[OP(scan)] == EXACT)
7206 if (join_exact(pRExC_state,scan,&min,1,val,depth+1))
7214 if( exact == PSEUDO )
7216 else if ( exact != OP(scan) )
7225 SV * const mysv=sv_newmortal();
7226 DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
7227 regprop(RExC_rx, mysv, scan);
7228 PerlIO_printf(Perl_debug_log, "~ %s (%s) (%d)\n",
7229 SvPV_nolen_const(mysv),
7231 REG_NODE_NUM(scan));
7238 SV * const mysv_val=sv_newmortal();
7239 DEBUG_PARSE_MSG("");
7240 regprop(RExC_rx, mysv_val, val);
7241 PerlIO_printf(Perl_debug_log, "~ attach to %s (%d) offset to %d\n",
7242 SvPV_nolen_const(mysv_val),
7247 if (reg_off_by_arg[OP(scan)]) {
7248 ARG_SET(scan, val - scan);
7251 NEXT_OFF(scan) = val - scan;
7259 - regcurly - a little FSA that accepts {\d+,?\d*}
7262 S_regcurly(register const char *s)
7281 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
7284 Perl_regdump(pTHX_ const regexp *r)
7288 SV * const sv = sv_newmortal();
7289 SV *dsv= sv_newmortal();
7291 (void)dumpuntil(r, r->program, r->program + 1, NULL, NULL, sv, 0, 0);
7293 /* Header fields of interest. */
7294 if (r->anchored_substr) {
7295 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr),
7296 RE_SV_DUMPLEN(r->anchored_substr), 30);
7297 PerlIO_printf(Perl_debug_log,
7298 "anchored %s%s at %"IVdf" ",
7299 s, RE_SV_TAIL(r->anchored_substr),
7300 (IV)r->anchored_offset);
7301 } else if (r->anchored_utf8) {
7302 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8),
7303 RE_SV_DUMPLEN(r->anchored_utf8), 30);
7304 PerlIO_printf(Perl_debug_log,
7305 "anchored utf8 %s%s at %"IVdf" ",
7306 s, RE_SV_TAIL(r->anchored_utf8),
7307 (IV)r->anchored_offset);
7309 if (r->float_substr) {
7310 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr),
7311 RE_SV_DUMPLEN(r->float_substr), 30);
7312 PerlIO_printf(Perl_debug_log,
7313 "floating %s%s at %"IVdf"..%"UVuf" ",
7314 s, RE_SV_TAIL(r->float_substr),
7315 (IV)r->float_min_offset, (UV)r->float_max_offset);
7316 } else if (r->float_utf8) {
7317 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8),
7318 RE_SV_DUMPLEN(r->float_utf8), 30);
7319 PerlIO_printf(Perl_debug_log,
7320 "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
7321 s, RE_SV_TAIL(r->float_utf8),
7322 (IV)r->float_min_offset, (UV)r->float_max_offset);
7324 if (r->check_substr || r->check_utf8)
7325 PerlIO_printf(Perl_debug_log,
7327 (r->check_substr == r->float_substr
7328 && r->check_utf8 == r->float_utf8
7329 ? "(checking floating" : "(checking anchored"));
7330 if (r->reganch & ROPT_NOSCAN)
7331 PerlIO_printf(Perl_debug_log, " noscan");
7332 if (r->reganch & ROPT_CHECK_ALL)
7333 PerlIO_printf(Perl_debug_log, " isall");
7334 if (r->check_substr || r->check_utf8)
7335 PerlIO_printf(Perl_debug_log, ") ");
7337 if (r->regstclass) {
7338 regprop(r, sv, r->regstclass);
7339 PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
7341 if (r->reganch & ROPT_ANCH) {
7342 PerlIO_printf(Perl_debug_log, "anchored");
7343 if (r->reganch & ROPT_ANCH_BOL)
7344 PerlIO_printf(Perl_debug_log, "(BOL)");
7345 if (r->reganch & ROPT_ANCH_MBOL)
7346 PerlIO_printf(Perl_debug_log, "(MBOL)");
7347 if (r->reganch & ROPT_ANCH_SBOL)
7348 PerlIO_printf(Perl_debug_log, "(SBOL)");
7349 if (r->reganch & ROPT_ANCH_GPOS)
7350 PerlIO_printf(Perl_debug_log, "(GPOS)");
7351 PerlIO_putc(Perl_debug_log, ' ');
7353 if (r->reganch & ROPT_GPOS_SEEN)
7354 PerlIO_printf(Perl_debug_log, "GPOS ");
7355 if (r->reganch & ROPT_SKIP)
7356 PerlIO_printf(Perl_debug_log, "plus ");
7357 if (r->reganch & ROPT_IMPLICIT)
7358 PerlIO_printf(Perl_debug_log, "implicit ");
7359 PerlIO_printf(Perl_debug_log, "minlen %ld ", (long) r->minlen);
7360 if (r->reganch & ROPT_EVAL_SEEN)
7361 PerlIO_printf(Perl_debug_log, "with eval ");
7362 PerlIO_printf(Perl_debug_log, "\n");
7364 PERL_UNUSED_CONTEXT;
7366 #endif /* DEBUGGING */
7370 - regprop - printable representation of opcode
7373 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
7378 GET_RE_DEBUG_FLAGS_DECL;
7380 sv_setpvn(sv, "", 0);
7381 if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */
7382 /* It would be nice to FAIL() here, but this may be called from
7383 regexec.c, and it would be hard to supply pRExC_state. */
7384 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
7385 sv_catpv(sv, reg_name[OP(o)]); /* Take off const! */
7387 k = PL_regkind[OP(o)];
7390 SV * const dsv = sv_2mortal(newSVpvs(""));
7391 /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
7392 * is a crude hack but it may be the best for now since
7393 * we have no flag "this EXACTish node was UTF-8"
7395 const char * const s =
7396 pv_pretty(dsv, STRING(o), STR_LEN(o), 60,
7397 PL_colors[0], PL_colors[1],
7398 PERL_PV_ESCAPE_UNI_DETECT |
7399 PERL_PV_PRETTY_ELIPSES |
7402 Perl_sv_catpvf(aTHX_ sv, " %s", s );
7403 } else if (k == TRIE) {
7404 /* print the details of the trie in dumpuntil instead, as
7405 * prog->data isn't available here */
7406 const char op = OP(o);
7407 const I32 n = ARG(o);
7408 const reg_ac_data * const ac = IS_TRIE_AC(op) ?
7409 (reg_ac_data *)prog->data->data[n] :
7411 const reg_trie_data * const trie = !IS_TRIE_AC(op) ?
7412 (reg_trie_data*)prog->data->data[n] :
7415 Perl_sv_catpvf(aTHX_ sv, "-%s",reg_name[o->flags]);
7416 DEBUG_TRIE_COMPILE_r(
7417 Perl_sv_catpvf(aTHX_ sv,
7418 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
7419 (UV)trie->startstate,
7420 (IV)trie->laststate-1,
7421 (UV)trie->wordcount,
7424 (UV)TRIE_CHARCOUNT(trie),
7425 (UV)trie->uniquecharcount
7428 if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
7430 int rangestart = -1;
7431 U8* bitmap = IS_ANYOF_TRIE(op) ? (U8*)ANYOF_BITMAP(o) : (U8*)TRIE_BITMAP(trie);
7432 Perl_sv_catpvf(aTHX_ sv, "[");
7433 for (i = 0; i <= 256; i++) {
7434 if (i < 256 && BITMAP_TEST(bitmap,i)) {
7435 if (rangestart == -1)
7437 } else if (rangestart != -1) {
7438 if (i <= rangestart + 3)
7439 for (; rangestart < i; rangestart++)
7440 put_byte(sv, rangestart);
7442 put_byte(sv, rangestart);
7444 put_byte(sv, i - 1);
7449 Perl_sv_catpvf(aTHX_ sv, "]");
7452 } else if (k == CURLY) {
7453 if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
7454 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
7455 Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
7457 else if (k == WHILEM && o->flags) /* Ordinal/of */
7458 Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
7459 else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP)
7460 Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o)); /* Parenth number */
7461 else if (k == RECURSE)
7462 Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
7463 else if (k == LOGICAL)
7464 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* 2: embedded, otherwise 1 */
7465 else if (k == ANYOF) {
7466 int i, rangestart = -1;
7467 const U8 flags = ANYOF_FLAGS(o);
7469 /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
7470 static const char * const anyofs[] = {
7503 if (flags & ANYOF_LOCALE)
7504 sv_catpvs(sv, "{loc}");
7505 if (flags & ANYOF_FOLD)
7506 sv_catpvs(sv, "{i}");
7507 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
7508 if (flags & ANYOF_INVERT)
7510 for (i = 0; i <= 256; i++) {
7511 if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
7512 if (rangestart == -1)
7514 } else if (rangestart != -1) {
7515 if (i <= rangestart + 3)
7516 for (; rangestart < i; rangestart++)
7517 put_byte(sv, rangestart);
7519 put_byte(sv, rangestart);
7521 put_byte(sv, i - 1);
7527 if (o->flags & ANYOF_CLASS)
7528 for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++)
7529 if (ANYOF_CLASS_TEST(o,i))
7530 sv_catpv(sv, anyofs[i]);
7532 if (flags & ANYOF_UNICODE)
7533 sv_catpvs(sv, "{unicode}");
7534 else if (flags & ANYOF_UNICODE_ALL)
7535 sv_catpvs(sv, "{unicode_all}");
7539 SV * const sw = regclass_swash(prog, o, FALSE, &lv, 0);
7543 U8 s[UTF8_MAXBYTES_CASE+1];
7545 for (i = 0; i <= 256; i++) { /* just the first 256 */
7546 uvchr_to_utf8(s, i);
7548 if (i < 256 && swash_fetch(sw, s, TRUE)) {
7549 if (rangestart == -1)
7551 } else if (rangestart != -1) {
7552 if (i <= rangestart + 3)
7553 for (; rangestart < i; rangestart++) {
7554 const U8 * const e = uvchr_to_utf8(s,rangestart);
7556 for(p = s; p < e; p++)
7560 const U8 *e = uvchr_to_utf8(s,rangestart);
7562 for (p = s; p < e; p++)
7565 e = uvchr_to_utf8(s, i-1);
7566 for (p = s; p < e; p++)
7573 sv_catpvs(sv, "..."); /* et cetera */
7577 char *s = savesvpv(lv);
7578 char * const origs = s;
7580 while (*s && *s != '\n')
7584 const char * const t = ++s;
7602 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
7604 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
7605 Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
7607 PERL_UNUSED_CONTEXT;
7608 PERL_UNUSED_ARG(sv);
7610 PERL_UNUSED_ARG(prog);
7611 #endif /* DEBUGGING */
7615 Perl_re_intuit_string(pTHX_ regexp *prog)
7616 { /* Assume that RE_INTUIT is set */
7618 GET_RE_DEBUG_FLAGS_DECL;
7619 PERL_UNUSED_CONTEXT;
7623 const char * const s = SvPV_nolen_const(prog->check_substr
7624 ? prog->check_substr : prog->check_utf8);
7626 if (!PL_colorset) reginitcolors();
7627 PerlIO_printf(Perl_debug_log,
7628 "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
7630 prog->check_substr ? "" : "utf8 ",
7631 PL_colors[5],PL_colors[0],
7634 (strlen(s) > 60 ? "..." : ""));
7637 return prog->check_substr ? prog->check_substr : prog->check_utf8;
7641 pregfree - free a regexp
7643 See regdupe below if you change anything here.
7647 Perl_pregfree(pTHX_ struct regexp *r)
7651 GET_RE_DEBUG_FLAGS_DECL;
7653 if (!r || (--r->refcnt > 0))
7659 SV *dsv= sv_newmortal();
7660 RE_PV_QUOTED_DECL(s, (r->reganch & ROPT_UTF8),
7661 dsv, r->precomp, r->prelen, 60);
7662 PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n",
7663 PL_colors[4],PL_colors[5],s);
7667 /* gcov results gave these as non-null 100% of the time, so there's no
7668 optimisation in checking them before calling Safefree */
7669 Safefree(r->precomp);
7670 Safefree(r->offsets); /* 20010421 MJD */
7671 RX_MATCH_COPY_FREE(r);
7672 #ifdef PERL_OLD_COPY_ON_WRITE
7674 SvREFCNT_dec(r->saved_copy);
7677 if (r->anchored_substr)
7678 SvREFCNT_dec(r->anchored_substr);
7679 if (r->anchored_utf8)
7680 SvREFCNT_dec(r->anchored_utf8);
7681 if (r->float_substr)
7682 SvREFCNT_dec(r->float_substr);
7684 SvREFCNT_dec(r->float_utf8);
7685 Safefree(r->substrs);
7688 int n = r->data->count;
7689 PAD* new_comppad = NULL;
7694 /* If you add a ->what type here, update the comment in regcomp.h */
7695 switch (r->data->what[n]) {
7697 SvREFCNT_dec((SV*)r->data->data[n]);
7700 Safefree(r->data->data[n]);
7703 new_comppad = (AV*)r->data->data[n];
7706 if (new_comppad == NULL)
7707 Perl_croak(aTHX_ "panic: pregfree comppad");
7708 PAD_SAVE_LOCAL(old_comppad,
7709 /* Watch out for global destruction's random ordering. */
7710 (SvTYPE(new_comppad) == SVt_PVAV) ? new_comppad : NULL
7713 refcnt = OpREFCNT_dec((OP_4tree*)r->data->data[n]);
7716 op_free((OP_4tree*)r->data->data[n]);
7718 PAD_RESTORE_LOCAL(old_comppad);
7719 SvREFCNT_dec((SV*)new_comppad);
7725 { /* Aho Corasick add-on structure for a trie node.
7726 Used in stclass optimization only */
7728 reg_ac_data *aho=(reg_ac_data*)r->data->data[n];
7730 refcount = --aho->refcount;
7733 Safefree(aho->states);
7734 Safefree(aho->fail);
7735 aho->trie=NULL; /* not necessary to free this as it is
7736 handled by the 't' case */
7737 Safefree(r->data->data[n]); /* do this last!!!! */
7738 Safefree(r->regstclass);
7744 /* trie structure. */
7746 reg_trie_data *trie=(reg_trie_data*)r->data->data[n];
7748 refcount = --trie->refcount;
7751 Safefree(trie->charmap);
7752 if (trie->widecharmap)
7753 SvREFCNT_dec((SV*)trie->widecharmap);
7754 Safefree(trie->states);
7755 Safefree(trie->trans);
7757 Safefree(trie->bitmap);
7759 Safefree(trie->wordlen);
7761 Safefree(trie->jump);
7763 Safefree(trie->nextword);
7767 SvREFCNT_dec((SV*)trie->words);
7768 if (trie->revcharmap)
7769 SvREFCNT_dec((SV*)trie->revcharmap);
7772 Safefree(r->data->data[n]); /* do this last!!!! */
7777 Perl_croak(aTHX_ "panic: regfree data code '%c'", r->data->what[n]);
7780 Safefree(r->data->what);
7783 Safefree(r->startp);
7788 #define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
7789 #define av_dup_inc(s,t) (AV*)SvREFCNT_inc(sv_dup((SV*)s,t))
7790 #define SAVEPVN(p,n) ((p) ? savepvn(p,n) : NULL)
7793 regdupe - duplicate a regexp.
7795 This routine is called by sv.c's re_dup and is expected to clone a
7796 given regexp structure. It is a no-op when not under USE_ITHREADS.
7797 (Originally this *was* re_dup() for change history see sv.c)
7799 See pregfree() above if you change anything here.
7801 #if defined(USE_ITHREADS)
7803 Perl_regdupe(pTHX_ const regexp *r, CLONE_PARAMS *param)
7808 struct reg_substr_datum *s;
7811 return (REGEXP *)NULL;
7813 if ((ret = (REGEXP *)ptr_table_fetch(PL_ptr_table, r)))
7816 len = r->offsets[0];
7817 npar = r->nparens+1;
7819 Newxc(ret, sizeof(regexp) + (len+1)*sizeof(regnode), char, regexp);
7820 Copy(r->program, ret->program, len+1, regnode);
7822 Newx(ret->startp, npar, I32);
7823 Copy(r->startp, ret->startp, npar, I32);
7824 Newx(ret->endp, npar, I32);
7825 Copy(r->startp, ret->startp, npar, I32);
7827 Newx(ret->substrs, 1, struct reg_substr_data);
7828 for (s = ret->substrs->data, i = 0; i < 3; i++, s++) {
7829 s->min_offset = r->substrs->data[i].min_offset;
7830 s->max_offset = r->substrs->data[i].max_offset;
7831 s->end_shift = r->substrs->data[i].end_shift;
7832 s->substr = sv_dup_inc(r->substrs->data[i].substr, param);
7833 s->utf8_substr = sv_dup_inc(r->substrs->data[i].utf8_substr, param);
7836 ret->regstclass = NULL;
7839 const int count = r->data->count;
7842 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
7843 char, struct reg_data);
7844 Newx(d->what, count, U8);
7847 for (i = 0; i < count; i++) {
7848 d->what[i] = r->data->what[i];
7849 switch (d->what[i]) {
7850 /* legal options are one of: sfpont
7851 see also regcomp.h and pregfree() */
7853 d->data[i] = sv_dup_inc((SV *)r->data->data[i], param);
7856 d->data[i] = av_dup_inc((AV *)r->data->data[i], param);
7859 /* This is cheating. */
7860 Newx(d->data[i], 1, struct regnode_charclass_class);
7861 StructCopy(r->data->data[i], d->data[i],
7862 struct regnode_charclass_class);
7863 ret->regstclass = (regnode*)d->data[i];
7866 /* Compiled op trees are readonly, and can thus be
7867 shared without duplication. */
7869 d->data[i] = (void*)OpREFCNT_inc((OP*)r->data->data[i]);
7873 d->data[i] = r->data->data[i];
7876 d->data[i] = r->data->data[i];
7878 ((reg_trie_data*)d->data[i])->refcount++;
7882 d->data[i] = r->data->data[i];
7884 ((reg_ac_data*)d->data[i])->refcount++;
7886 /* Trie stclasses are readonly and can thus be shared
7887 * without duplication. We free the stclass in pregfree
7888 * when the corresponding reg_ac_data struct is freed.
7890 ret->regstclass= r->regstclass;
7893 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", r->data->what[i]);
7902 Newx(ret->offsets, 2*len+1, U32);
7903 Copy(r->offsets, ret->offsets, 2*len+1, U32);
7905 ret->precomp = SAVEPVN(r->precomp, r->prelen);
7906 ret->refcnt = r->refcnt;
7907 ret->minlen = r->minlen;
7908 ret->prelen = r->prelen;
7909 ret->nparens = r->nparens;
7910 ret->lastparen = r->lastparen;
7911 ret->lastcloseparen = r->lastcloseparen;
7912 ret->reganch = r->reganch;
7914 ret->sublen = r->sublen;
7916 ret->engine = r->engine;
7918 if (RX_MATCH_COPIED(ret))
7919 ret->subbeg = SAVEPVN(r->subbeg, r->sublen);
7922 #ifdef PERL_OLD_COPY_ON_WRITE
7923 ret->saved_copy = NULL;
7926 ptr_table_store(PL_ptr_table, r, ret);
7931 #ifndef PERL_IN_XSUB_RE
7933 - regnext - dig the "next" pointer out of a node
7936 Perl_regnext(pTHX_ register regnode *p)
7939 register I32 offset;
7941 if (p == &PL_regdummy)
7944 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
7953 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
7956 STRLEN l1 = strlen(pat1);
7957 STRLEN l2 = strlen(pat2);
7960 const char *message;
7966 Copy(pat1, buf, l1 , char);
7967 Copy(pat2, buf + l1, l2 , char);
7968 buf[l1 + l2] = '\n';
7969 buf[l1 + l2 + 1] = '\0';
7971 /* ANSI variant takes additional second argument */
7972 va_start(args, pat2);
7976 msv = vmess(buf, &args);
7978 message = SvPV_const(msv,l1);
7981 Copy(message, buf, l1 , char);
7982 buf[l1-1] = '\0'; /* Overwrite \n */
7983 Perl_croak(aTHX_ "%s", buf);
7986 /* XXX Here's a total kludge. But we need to re-enter for swash routines. */
7988 #ifndef PERL_IN_XSUB_RE
7990 Perl_save_re_context(pTHX)
7994 struct re_save_state *state;
7996 SAVEVPTR(PL_curcop);
7997 SSGROW(SAVESTACK_ALLOC_FOR_RE_SAVE_STATE + 1);
7999 state = (struct re_save_state *)(PL_savestack + PL_savestack_ix);
8000 PL_savestack_ix += SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
8001 SSPUSHINT(SAVEt_RE_STATE);
8003 Copy(&PL_reg_state, state, 1, struct re_save_state);
8005 PL_reg_start_tmp = 0;
8006 PL_reg_start_tmpl = 0;
8007 PL_reg_oldsaved = NULL;
8008 PL_reg_oldsavedlen = 0;
8010 PL_reg_leftiter = 0;
8011 PL_reg_poscache = NULL;
8012 PL_reg_poscache_size = 0;
8013 #ifdef PERL_OLD_COPY_ON_WRITE
8017 /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
8019 const REGEXP * const rx = PM_GETRE(PL_curpm);
8022 for (i = 1; i <= rx->nparens; i++) {
8023 char digits[TYPE_CHARS(long)];
8024 const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
8025 GV *const *const gvp
8026 = (GV**)hv_fetch(PL_defstash, digits, len, 0);
8029 GV * const gv = *gvp;
8030 if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
8040 clear_re(pTHX_ void *r)
8043 ReREFCNT_dec((regexp *)r);
8049 S_put_byte(pTHX_ SV *sv, int c)
8051 if (isCNTRL(c) || c == 255 || !isPRINT(c))
8052 Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
8053 else if (c == '-' || c == ']' || c == '\\' || c == '^')
8054 Perl_sv_catpvf(aTHX_ sv, "\\%c", c);
8056 Perl_sv_catpvf(aTHX_ sv, "%c", c);
8060 #define CLEAR_OPTSTART \
8061 if (optstart) STMT_START { \
8062 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%d nodes)\n", node - optstart)); \
8066 #define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
8068 STATIC const regnode *
8069 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
8070 const regnode *last, const regnode *plast,
8071 SV* sv, I32 indent, U32 depth)
8074 register U8 op = PSEUDO; /* Arbitrary non-END op. */
8075 register const regnode *next;
8076 const regnode *optstart= NULL;
8077 GET_RE_DEBUG_FLAGS_DECL;
8079 #ifdef DEBUG_DUMPUNTIL
8080 PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
8081 last ? last-start : 0,plast ? plast-start : 0);
8084 if (plast && plast < last)
8087 while (PL_regkind[op] != END && (!last || node < last)) {
8088 /* While that wasn't END last time... */
8094 next = regnext((regnode *)node);
8097 if (OP(node) == OPTIMIZED) {
8098 if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
8105 regprop(r, sv, node);
8106 PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
8107 (int)(2*indent + 1), "", SvPVX_const(sv));
8109 if (OP(node) != OPTIMIZED) {
8110 if (next == NULL) /* Next ptr. */
8111 PerlIO_printf(Perl_debug_log, "(0)");
8112 else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
8113 PerlIO_printf(Perl_debug_log, "(FAIL)");
8115 PerlIO_printf(Perl_debug_log, "(%"IVdf")", (IV)(next - start));
8117 /*if (PL_regkind[(U8)op] != TRIE)*/
8118 (void)PerlIO_putc(Perl_debug_log, '\n');
8122 if (PL_regkind[(U8)op] == BRANCHJ) {
8125 register const regnode *nnode = (OP(next) == LONGJMP
8126 ? regnext((regnode *)next)
8128 if (last && nnode > last)
8130 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
8133 else if (PL_regkind[(U8)op] == BRANCH) {
8135 DUMPUNTIL(NEXTOPER(node), next);
8137 else if ( PL_regkind[(U8)op] == TRIE ) {
8138 const char op = OP(node);
8139 const I32 n = ARG(node);
8140 const reg_ac_data * const ac = op>=AHOCORASICK ?
8141 (reg_ac_data *)r->data->data[n] :
8143 const reg_trie_data * const trie = op<AHOCORASICK ?
8144 (reg_trie_data*)r->data->data[n] :
8146 const regnode *nextbranch= NULL;
8148 sv_setpvn(sv, "", 0);
8149 for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
8150 SV ** const elem_ptr = av_fetch(trie->words,word_idx,0);
8152 PerlIO_printf(Perl_debug_log, "%*s%s ",
8153 (int)(2*(indent+3)), "",
8154 elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
8155 PL_colors[0], PL_colors[1],
8156 (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
8157 PERL_PV_PRETTY_ELIPSES |
8163 U16 dist= trie->jump[word_idx+1];
8164 PerlIO_printf(Perl_debug_log, "(%u)\n",(next - dist) - start);
8167 nextbranch= next - trie->jump[0];
8168 DUMPUNTIL(next - dist, nextbranch);
8170 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
8171 nextbranch= regnext((regnode *)nextbranch);
8173 PerlIO_printf(Perl_debug_log, "\n");
8176 if (last && next > last)
8181 else if ( op == CURLY ) { /* "next" might be very big: optimizer */
8182 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
8183 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
8185 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
8187 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
8189 else if ( op == PLUS || op == STAR) {
8190 DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
8192 else if (op == ANYOF) {
8193 /* arglen 1 + class block */
8194 node += 1 + ((ANYOF_FLAGS(node) & ANYOF_LARGE)
8195 ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
8196 node = NEXTOPER(node);
8198 else if (PL_regkind[(U8)op] == EXACT) {
8199 /* Literal string, where present. */
8200 node += NODE_SZ_STR(node) - 1;
8201 node = NEXTOPER(node);
8204 node = NEXTOPER(node);
8205 node += regarglen[(U8)op];
8207 if (op == CURLYX || op == OPEN)
8209 else if (op == WHILEM)
8213 #ifdef DEBUG_DUMPUNTIL
8214 PerlIO_printf(Perl_debug_log, "--- %d\n",indent);
8219 #endif /* DEBUGGING */
8223 * c-indentation-style: bsd
8225 * indent-tabs-mode: t
8228 * ex: set ts=8 sts=4 sw=4 noet: