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; /* Capture buffer count, (OPEN). */
117 I32 cpar; /* Capture buffer count, (CLOSE). */
118 I32 nestroot; /* root parens we are in - used by accept */
122 regnode **open_parens; /* pointers to open parens */
123 regnode **close_parens; /* pointers to close parens */
124 regnode *opend; /* END node in program */
126 HV *charnames; /* cache of named sequences */
127 HV *paren_names; /* Paren names */
128 regnode **recurse; /* Recurse regops */
129 I32 recurse_count; /* Number of recurse regops */
131 char *starttry; /* -Dr: where regtry was called. */
132 #define RExC_starttry (pRExC_state->starttry)
135 const char *lastparse;
137 #define RExC_lastparse (pRExC_state->lastparse)
138 #define RExC_lastnum (pRExC_state->lastnum)
142 #define RExC_flags (pRExC_state->flags)
143 #define RExC_precomp (pRExC_state->precomp)
144 #define RExC_rx (pRExC_state->rx)
145 #define RExC_start (pRExC_state->start)
146 #define RExC_end (pRExC_state->end)
147 #define RExC_parse (pRExC_state->parse)
148 #define RExC_whilem_seen (pRExC_state->whilem_seen)
149 #define RExC_offsets (pRExC_state->rx->offsets) /* I am not like the others */
150 #define RExC_emit (pRExC_state->emit)
151 #define RExC_emit_start (pRExC_state->emit_start)
152 #define RExC_naughty (pRExC_state->naughty)
153 #define RExC_sawback (pRExC_state->sawback)
154 #define RExC_seen (pRExC_state->seen)
155 #define RExC_size (pRExC_state->size)
156 #define RExC_npar (pRExC_state->npar)
157 #define RExC_cpar (pRExC_state->cpar)
158 #define RExC_nestroot (pRExC_state->nestroot)
159 #define RExC_extralen (pRExC_state->extralen)
160 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
161 #define RExC_seen_evals (pRExC_state->seen_evals)
162 #define RExC_utf8 (pRExC_state->utf8)
163 #define RExC_charnames (pRExC_state->charnames)
164 #define RExC_open_parens (pRExC_state->open_parens)
165 #define RExC_close_parens (pRExC_state->close_parens)
166 #define RExC_opend (pRExC_state->opend)
167 #define RExC_paren_names (pRExC_state->paren_names)
168 #define RExC_recurse (pRExC_state->recurse)
169 #define RExC_recurse_count (pRExC_state->recurse_count)
171 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
172 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
173 ((*s) == '{' && regcurly(s)))
176 #undef SPSTART /* dratted cpp namespace... */
179 * Flags to be passed up and down.
181 #define WORST 0 /* Worst case. */
182 #define HASWIDTH 0x1 /* Known to match non-null strings. */
183 #define SIMPLE 0x2 /* Simple enough to be STAR/PLUS operand. */
184 #define SPSTART 0x4 /* Starts with * or +. */
185 #define TRYAGAIN 0x8 /* Weeded out a declaration. */
187 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
189 /* whether trie related optimizations are enabled */
190 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
191 #define TRIE_STUDY_OPT
192 #define FULL_TRIE_STUDY
198 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
199 #define PBITVAL(paren) (1 << ((paren) & 7))
200 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
201 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
202 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
205 /* About scan_data_t.
207 During optimisation we recurse through the regexp program performing
208 various inplace (keyhole style) optimisations. In addition study_chunk
209 and scan_commit populate this data structure with information about
210 what strings MUST appear in the pattern. We look for the longest
211 string that must appear for at a fixed location, and we look for the
212 longest string that may appear at a floating location. So for instance
217 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
218 strings (because they follow a .* construct). study_chunk will identify
219 both FOO and BAR as being the longest fixed and floating strings respectively.
221 The strings can be composites, for instance
225 will result in a composite fixed substring 'foo'.
227 For each string some basic information is maintained:
229 - offset or min_offset
230 This is the position the string must appear at, or not before.
231 It also implicitly (when combined with minlenp) tells us how many
232 character must match before the string we are searching.
233 Likewise when combined with minlenp and the length of the string
234 tells us how many characters must appear after the string we have
238 Only used for floating strings. This is the rightmost point that
239 the string can appear at. Ifset to I32 max it indicates that the
240 string can occur infinitely far to the right.
243 A pointer to the minimum length of the pattern that the string
244 was found inside. This is important as in the case of positive
245 lookahead or positive lookbehind we can have multiple patterns
250 The minimum length of the pattern overall is 3, the minimum length
251 of the lookahead part is 3, but the minimum length of the part that
252 will actually match is 1. So 'FOO's minimum length is 3, but the
253 minimum length for the F is 1. This is important as the minimum length
254 is used to determine offsets in front of and behind the string being
255 looked for. Since strings can be composites this is the length of the
256 pattern at the time it was commited with a scan_commit. Note that
257 the length is calculated by study_chunk, so that the minimum lengths
258 are not known until the full pattern has been compiled, thus the
259 pointer to the value.
263 In the case of lookbehind the string being searched for can be
264 offset past the start point of the final matching string.
265 If this value was just blithely removed from the min_offset it would
266 invalidate some of the calculations for how many chars must match
267 before or after (as they are derived from min_offset and minlen and
268 the length of the string being searched for).
269 When the final pattern is compiled and the data is moved from the
270 scan_data_t structure into the regexp structure the information
271 about lookbehind is factored in, with the information that would
272 have been lost precalculated in the end_shift field for the
275 The fields pos_min and pos_delta are used to store the minimum offset
276 and the delta to the maximum offset at the current point in the pattern.
280 typedef struct scan_data_t {
281 /*I32 len_min; unused */
282 /*I32 len_delta; unused */
286 I32 last_end; /* min value, <0 unless valid. */
289 SV **longest; /* Either &l_fixed, or &l_float. */
290 SV *longest_fixed; /* longest fixed string found in pattern */
291 I32 offset_fixed; /* offset where it starts */
292 I32 *minlen_fixed; /* pointer to the minlen relevent to the string */
293 I32 lookbehind_fixed; /* is the position of the string modfied by LB */
294 SV *longest_float; /* longest floating string found in pattern */
295 I32 offset_float_min; /* earliest point in string it can appear */
296 I32 offset_float_max; /* latest point in string it can appear */
297 I32 *minlen_float; /* pointer to the minlen relevent to the string */
298 I32 lookbehind_float; /* is the position of the string modified by LB */
302 struct regnode_charclass_class *start_class;
306 * Forward declarations for pregcomp()'s friends.
309 static const scan_data_t zero_scan_data =
310 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
312 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
313 #define SF_BEFORE_SEOL 0x0001
314 #define SF_BEFORE_MEOL 0x0002
315 #define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
316 #define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
319 # define SF_FIX_SHIFT_EOL (0+2)
320 # define SF_FL_SHIFT_EOL (0+4)
322 # define SF_FIX_SHIFT_EOL (+2)
323 # define SF_FL_SHIFT_EOL (+4)
326 #define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
327 #define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
329 #define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
330 #define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
331 #define SF_IS_INF 0x0040
332 #define SF_HAS_PAR 0x0080
333 #define SF_IN_PAR 0x0100
334 #define SF_HAS_EVAL 0x0200
335 #define SCF_DO_SUBSTR 0x0400
336 #define SCF_DO_STCLASS_AND 0x0800
337 #define SCF_DO_STCLASS_OR 0x1000
338 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
339 #define SCF_WHILEM_VISITED_POS 0x2000
341 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
342 #define SCF_SEEN_ACCEPT 0x8000
344 #define UTF (RExC_utf8 != 0)
345 #define LOC ((RExC_flags & PMf_LOCALE) != 0)
346 #define FOLD ((RExC_flags & PMf_FOLD) != 0)
348 #define OOB_UNICODE 12345678
349 #define OOB_NAMEDCLASS -1
351 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
352 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
355 /* length of regex to show in messages that don't mark a position within */
356 #define RegexLengthToShowInErrorMessages 127
359 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
360 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
361 * op/pragma/warn/regcomp.
363 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
364 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
366 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
369 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
370 * arg. Show regex, up to a maximum length. If it's too long, chop and add
373 #define FAIL(msg) STMT_START { \
374 const char *ellipses = ""; \
375 IV len = RExC_end - RExC_precomp; \
378 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
379 if (len > RegexLengthToShowInErrorMessages) { \
380 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
381 len = RegexLengthToShowInErrorMessages - 10; \
384 Perl_croak(aTHX_ "%s in regex m/%.*s%s/", \
385 msg, (int)len, RExC_precomp, ellipses); \
389 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
391 #define Simple_vFAIL(m) STMT_START { \
392 const IV offset = RExC_parse - RExC_precomp; \
393 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
394 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
398 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
400 #define vFAIL(m) STMT_START { \
402 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
407 * Like Simple_vFAIL(), but accepts two arguments.
409 #define Simple_vFAIL2(m,a1) STMT_START { \
410 const IV offset = RExC_parse - RExC_precomp; \
411 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, \
412 (int)offset, RExC_precomp, RExC_precomp + offset); \
416 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
418 #define vFAIL2(m,a1) STMT_START { \
420 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
421 Simple_vFAIL2(m, a1); \
426 * Like Simple_vFAIL(), but accepts three arguments.
428 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
429 const IV offset = RExC_parse - RExC_precomp; \
430 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, \
431 (int)offset, RExC_precomp, RExC_precomp + offset); \
435 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
437 #define vFAIL3(m,a1,a2) STMT_START { \
439 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
440 Simple_vFAIL3(m, a1, a2); \
444 * Like Simple_vFAIL(), but accepts four arguments.
446 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
447 const IV offset = RExC_parse - RExC_precomp; \
448 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, \
449 (int)offset, RExC_precomp, RExC_precomp + offset); \
452 #define vWARN(loc,m) STMT_START { \
453 const IV offset = loc - RExC_precomp; \
454 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s" REPORT_LOCATION, \
455 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
458 #define vWARNdep(loc,m) STMT_START { \
459 const IV offset = loc - RExC_precomp; \
460 Perl_warner(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
461 "%s" REPORT_LOCATION, \
462 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
466 #define vWARN2(loc, m, a1) STMT_START { \
467 const IV offset = loc - RExC_precomp; \
468 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
469 a1, (int)offset, RExC_precomp, RExC_precomp + offset); \
472 #define vWARN3(loc, m, a1, a2) STMT_START { \
473 const IV offset = loc - RExC_precomp; \
474 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
475 a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
478 #define vWARN4(loc, m, a1, a2, a3) STMT_START { \
479 const IV offset = loc - RExC_precomp; \
480 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
481 a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
484 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START { \
485 const IV offset = loc - RExC_precomp; \
486 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
487 a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
491 /* Allow for side effects in s */
492 #define REGC(c,s) STMT_START { \
493 if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
496 /* Macros for recording node offsets. 20001227 mjd@plover.com
497 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
498 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
499 * Element 0 holds the number n.
500 * Position is 1 indexed.
503 #define Set_Node_Offset_To_R(node,byte) STMT_START { \
505 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
506 __LINE__, (int)(node), (int)(byte))); \
508 Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
510 RExC_offsets[2*(node)-1] = (byte); \
515 #define Set_Node_Offset(node,byte) \
516 Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
517 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
519 #define Set_Node_Length_To_R(node,len) STMT_START { \
521 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
522 __LINE__, (int)(node), (int)(len))); \
524 Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
526 RExC_offsets[2*(node)] = (len); \
531 #define Set_Node_Length(node,len) \
532 Set_Node_Length_To_R((node)-RExC_emit_start, len)
533 #define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
534 #define Set_Node_Cur_Length(node) \
535 Set_Node_Length(node, RExC_parse - parse_start)
537 /* Get offsets and lengths */
538 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
539 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
541 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
542 Set_Node_Offset_To_R((node)-RExC_emit_start, (offset)); \
543 Set_Node_Length_To_R((node)-RExC_emit_start, (len)); \
547 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
548 #define EXPERIMENTAL_INPLACESCAN
551 #define DEBUG_STUDYDATA(data,depth) \
552 DEBUG_OPTIMISE_MORE_r(if(data){ \
553 PerlIO_printf(Perl_debug_log, \
554 "%*s"/* Len:%"IVdf"/%"IVdf" */"Pos:%"IVdf"/%"IVdf \
555 " Flags: %"IVdf" Whilem_c: %"IVdf" Lcp: %"IVdf" ", \
556 (int)(depth)*2, "", \
557 (IV)((data)->pos_min), \
558 (IV)((data)->pos_delta), \
559 (IV)((data)->flags), \
560 (IV)((data)->whilem_c), \
561 (IV)((data)->last_closep ? *((data)->last_closep) : -1) \
563 if ((data)->last_found) \
564 PerlIO_printf(Perl_debug_log, \
565 "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
566 " %sFloat: '%s' @ %"IVdf"/%"IVdf"", \
567 SvPVX_const((data)->last_found), \
568 (IV)((data)->last_end), \
569 (IV)((data)->last_start_min), \
570 (IV)((data)->last_start_max), \
571 ((data)->longest && \
572 (data)->longest==&((data)->longest_fixed)) ? "*" : "", \
573 SvPVX_const((data)->longest_fixed), \
574 (IV)((data)->offset_fixed), \
575 ((data)->longest && \
576 (data)->longest==&((data)->longest_float)) ? "*" : "", \
577 SvPVX_const((data)->longest_float), \
578 (IV)((data)->offset_float_min), \
579 (IV)((data)->offset_float_max) \
581 PerlIO_printf(Perl_debug_log,"\n"); \
584 static void clear_re(pTHX_ void *r);
586 /* Mark that we cannot extend a found fixed substring at this point.
587 Update the longest found anchored substring and the longest found
588 floating substrings if needed. */
591 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp)
593 const STRLEN l = CHR_SVLEN(data->last_found);
594 const STRLEN old_l = CHR_SVLEN(*data->longest);
595 GET_RE_DEBUG_FLAGS_DECL;
597 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
598 SvSetMagicSV(*data->longest, data->last_found);
599 if (*data->longest == data->longest_fixed) {
600 data->offset_fixed = l ? data->last_start_min : data->pos_min;
601 if (data->flags & SF_BEFORE_EOL)
603 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
605 data->flags &= ~SF_FIX_BEFORE_EOL;
606 data->minlen_fixed=minlenp;
607 data->lookbehind_fixed=0;
610 data->offset_float_min = l ? data->last_start_min : data->pos_min;
611 data->offset_float_max = (l
612 ? data->last_start_max
613 : data->pos_min + data->pos_delta);
614 if ((U32)data->offset_float_max > (U32)I32_MAX)
615 data->offset_float_max = I32_MAX;
616 if (data->flags & SF_BEFORE_EOL)
618 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
620 data->flags &= ~SF_FL_BEFORE_EOL;
621 data->minlen_float=minlenp;
622 data->lookbehind_float=0;
625 SvCUR_set(data->last_found, 0);
627 SV * const sv = data->last_found;
628 if (SvUTF8(sv) && SvMAGICAL(sv)) {
629 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
635 data->flags &= ~SF_BEFORE_EOL;
636 DEBUG_STUDYDATA(data,0);
639 /* Can match anything (initialization) */
641 S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
643 ANYOF_CLASS_ZERO(cl);
644 ANYOF_BITMAP_SETALL(cl);
645 cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL;
647 cl->flags |= ANYOF_LOCALE;
650 /* Can match anything (initialization) */
652 S_cl_is_anything(const struct regnode_charclass_class *cl)
656 for (value = 0; value <= ANYOF_MAX; value += 2)
657 if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
659 if (!(cl->flags & ANYOF_UNICODE_ALL))
661 if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
666 /* Can match anything (initialization) */
668 S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
670 Zero(cl, 1, struct regnode_charclass_class);
672 cl_anything(pRExC_state, cl);
676 S_cl_init_zero(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
678 Zero(cl, 1, struct regnode_charclass_class);
680 cl_anything(pRExC_state, cl);
682 cl->flags |= ANYOF_LOCALE;
685 /* 'And' a given class with another one. Can create false positives */
686 /* We assume that cl is not inverted */
688 S_cl_and(struct regnode_charclass_class *cl,
689 const struct regnode_charclass_class *and_with)
692 assert(and_with->type == ANYOF);
693 if (!(and_with->flags & ANYOF_CLASS)
694 && !(cl->flags & ANYOF_CLASS)
695 && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
696 && !(and_with->flags & ANYOF_FOLD)
697 && !(cl->flags & ANYOF_FOLD)) {
700 if (and_with->flags & ANYOF_INVERT)
701 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
702 cl->bitmap[i] &= ~and_with->bitmap[i];
704 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
705 cl->bitmap[i] &= and_with->bitmap[i];
706 } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
707 if (!(and_with->flags & ANYOF_EOS))
708 cl->flags &= ~ANYOF_EOS;
710 if (cl->flags & ANYOF_UNICODE_ALL && and_with->flags & ANYOF_UNICODE &&
711 !(and_with->flags & ANYOF_INVERT)) {
712 cl->flags &= ~ANYOF_UNICODE_ALL;
713 cl->flags |= ANYOF_UNICODE;
714 ARG_SET(cl, ARG(and_with));
716 if (!(and_with->flags & ANYOF_UNICODE_ALL) &&
717 !(and_with->flags & ANYOF_INVERT))
718 cl->flags &= ~ANYOF_UNICODE_ALL;
719 if (!(and_with->flags & (ANYOF_UNICODE|ANYOF_UNICODE_ALL)) &&
720 !(and_with->flags & ANYOF_INVERT))
721 cl->flags &= ~ANYOF_UNICODE;
724 /* 'OR' a given class with another one. Can create false positives */
725 /* We assume that cl is not inverted */
727 S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
729 if (or_with->flags & ANYOF_INVERT) {
731 * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
732 * <= (B1 | !B2) | (CL1 | !CL2)
733 * which is wasteful if CL2 is small, but we ignore CL2:
734 * (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
735 * XXXX Can we handle case-fold? Unclear:
736 * (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
737 * (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
739 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
740 && !(or_with->flags & ANYOF_FOLD)
741 && !(cl->flags & ANYOF_FOLD) ) {
744 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
745 cl->bitmap[i] |= ~or_with->bitmap[i];
746 } /* XXXX: logic is complicated otherwise */
748 cl_anything(pRExC_state, cl);
751 /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
752 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
753 && (!(or_with->flags & ANYOF_FOLD)
754 || (cl->flags & ANYOF_FOLD)) ) {
757 /* OR char bitmap and class bitmap separately */
758 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
759 cl->bitmap[i] |= or_with->bitmap[i];
760 if (or_with->flags & ANYOF_CLASS) {
761 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
762 cl->classflags[i] |= or_with->classflags[i];
763 cl->flags |= ANYOF_CLASS;
766 else { /* XXXX: logic is complicated, leave it along for a moment. */
767 cl_anything(pRExC_state, cl);
770 if (or_with->flags & ANYOF_EOS)
771 cl->flags |= ANYOF_EOS;
773 if (cl->flags & ANYOF_UNICODE && or_with->flags & ANYOF_UNICODE &&
774 ARG(cl) != ARG(or_with)) {
775 cl->flags |= ANYOF_UNICODE_ALL;
776 cl->flags &= ~ANYOF_UNICODE;
778 if (or_with->flags & ANYOF_UNICODE_ALL) {
779 cl->flags |= ANYOF_UNICODE_ALL;
780 cl->flags &= ~ANYOF_UNICODE;
784 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
785 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
786 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
787 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
793 dump_trie_interim_list(trie,next_alloc)
794 dump_trie_interim_table(trie,next_alloc)
796 These routines dump out a trie in a somewhat readable format.
797 The _interim_ variants are used for debugging the interim
798 tables that are used to generate the final compressed
799 representation which is what dump_trie expects.
801 Part of the reason for their existance is to provide a form
802 of documentation as to how the different representations function.
808 Dumps the final compressed table form of the trie to Perl_debug_log.
809 Used for debugging make_trie().
813 S_dump_trie(pTHX_ const struct _reg_trie_data *trie,U32 depth)
816 SV *sv=sv_newmortal();
817 int colwidth= trie->widecharmap ? 6 : 4;
818 GET_RE_DEBUG_FLAGS_DECL;
821 PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
822 (int)depth * 2 + 2,"",
823 "Match","Base","Ofs" );
825 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
826 SV ** const tmp = av_fetch( trie->revcharmap, state, 0);
828 PerlIO_printf( Perl_debug_log, "%*s",
830 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
831 PL_colors[0], PL_colors[1],
832 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
833 PERL_PV_ESCAPE_FIRSTCHAR
838 PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
839 (int)depth * 2 + 2,"");
841 for( state = 0 ; state < trie->uniquecharcount ; state++ )
842 PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
843 PerlIO_printf( Perl_debug_log, "\n");
845 for( state = 1 ; state < trie->statecount ; state++ ) {
846 const U32 base = trie->states[ state ].trans.base;
848 PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
850 if ( trie->states[ state ].wordnum ) {
851 PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
853 PerlIO_printf( Perl_debug_log, "%6s", "" );
856 PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
861 while( ( base + ofs < trie->uniquecharcount ) ||
862 ( base + ofs - trie->uniquecharcount < trie->lasttrans
863 && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
866 PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
868 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
869 if ( ( base + ofs >= trie->uniquecharcount ) &&
870 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
871 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
873 PerlIO_printf( Perl_debug_log, "%*"UVXf,
875 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
877 PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
881 PerlIO_printf( Perl_debug_log, "]");
884 PerlIO_printf( Perl_debug_log, "\n" );
888 dump_trie_interim_list(trie,next_alloc)
889 Dumps a fully constructed but uncompressed trie in list form.
890 List tries normally only are used for construction when the number of
891 possible chars (trie->uniquecharcount) is very high.
892 Used for debugging make_trie().
895 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie, U32 next_alloc,U32 depth)
898 SV *sv=sv_newmortal();
899 int colwidth= trie->widecharmap ? 6 : 4;
900 GET_RE_DEBUG_FLAGS_DECL;
901 /* print out the table precompression. */
902 PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
903 (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
904 "------:-----+-----------------\n" );
906 for( state=1 ; state < next_alloc ; state ++ ) {
909 PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
910 (int)depth * 2 + 2,"", (UV)state );
911 if ( ! trie->states[ state ].wordnum ) {
912 PerlIO_printf( Perl_debug_log, "%5s| ","");
914 PerlIO_printf( Perl_debug_log, "W%4x| ",
915 trie->states[ state ].wordnum
918 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
919 SV ** const tmp = av_fetch( trie->revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
921 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
923 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
924 PL_colors[0], PL_colors[1],
925 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
926 PERL_PV_ESCAPE_FIRSTCHAR
928 TRIE_LIST_ITEM(state,charid).forid,
929 (UV)TRIE_LIST_ITEM(state,charid).newstate
932 PerlIO_printf(Perl_debug_log, "\n%*s| ",
933 (int)((depth * 2) + 14), "");
936 PerlIO_printf( Perl_debug_log, "\n");
941 dump_trie_interim_table(trie,next_alloc)
942 Dumps a fully constructed but uncompressed trie in table form.
943 This is the normal DFA style state transition table, with a few
944 twists to facilitate compression later.
945 Used for debugging make_trie().
948 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie, U32 next_alloc, U32 depth)
952 SV *sv=sv_newmortal();
953 int colwidth= trie->widecharmap ? 6 : 4;
954 GET_RE_DEBUG_FLAGS_DECL;
957 print out the table precompression so that we can do a visual check
958 that they are identical.
961 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
963 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
964 SV ** const tmp = av_fetch( trie->revcharmap, charid, 0);
966 PerlIO_printf( Perl_debug_log, "%*s",
968 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
969 PL_colors[0], PL_colors[1],
970 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
971 PERL_PV_ESCAPE_FIRSTCHAR
977 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
979 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
980 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
983 PerlIO_printf( Perl_debug_log, "\n" );
985 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
987 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
988 (int)depth * 2 + 2,"",
989 (UV)TRIE_NODENUM( state ) );
991 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
992 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
994 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
996 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
998 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
999 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
1001 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
1002 trie->states[ TRIE_NODENUM( state ) ].wordnum );
1009 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1010 startbranch: the first branch in the whole branch sequence
1011 first : start branch of sequence of branch-exact nodes.
1012 May be the same as startbranch
1013 last : Thing following the last branch.
1014 May be the same as tail.
1015 tail : item following the branch sequence
1016 count : words in the sequence
1017 flags : currently the OP() type we will be building one of /EXACT(|F|Fl)/
1018 depth : indent depth
1020 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
1022 A trie is an N'ary tree where the branches are determined by digital
1023 decomposition of the key. IE, at the root node you look up the 1st character and
1024 follow that branch repeat until you find the end of the branches. Nodes can be
1025 marked as "accepting" meaning they represent a complete word. Eg:
1029 would convert into the following structure. Numbers represent states, letters
1030 following numbers represent valid transitions on the letter from that state, if
1031 the number is in square brackets it represents an accepting state, otherwise it
1032 will be in parenthesis.
1034 +-h->+-e->[3]-+-r->(8)-+-s->[9]
1038 (1) +-i->(6)-+-s->[7]
1040 +-s->(3)-+-h->(4)-+-e->[5]
1042 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1044 This shows that when matching against the string 'hers' we will begin at state 1
1045 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1046 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1047 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1048 single traverse. We store a mapping from accepting to state to which word was
1049 matched, and then when we have multiple possibilities we try to complete the
1050 rest of the regex in the order in which they occured in the alternation.
1052 The only prior NFA like behaviour that would be changed by the TRIE support is
1053 the silent ignoring of duplicate alternations which are of the form:
1055 / (DUPE|DUPE) X? (?{ ... }) Y /x
1057 Thus EVAL blocks follwing a trie may be called a different number of times with
1058 and without the optimisation. With the optimisations dupes will be silently
1059 ignored. This inconsistant behaviour of EVAL type nodes is well established as
1060 the following demonstrates:
1062 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1064 which prints out 'word' three times, but
1066 'words'=~/(word|word|word)(?{ print $1 })S/
1068 which doesnt print it out at all. This is due to other optimisations kicking in.
1070 Example of what happens on a structural level:
1072 The regexp /(ac|ad|ab)+/ will produce the folowing debug output:
1074 1: CURLYM[1] {1,32767}(18)
1085 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1086 and should turn into:
1088 1: CURLYM[1] {1,32767}(18)
1090 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1098 Cases where tail != last would be like /(?foo|bar)baz/:
1108 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1109 and would end up looking like:
1112 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1119 d = uvuni_to_utf8_flags(d, uv, 0);
1121 is the recommended Unicode-aware way of saying
1126 #define TRIE_STORE_REVCHAR \
1128 SV *tmp = newSVpvs(""); \
1129 if (UTF) SvUTF8_on(tmp); \
1130 Perl_sv_catpvf( aTHX_ tmp, "%c", (int)uvc ); \
1131 av_push( TRIE_REVCHARMAP(trie), tmp ); \
1134 #define TRIE_READ_CHAR STMT_START { \
1138 if ( foldlen > 0 ) { \
1139 uvc = utf8n_to_uvuni( scan, UTF8_MAXLEN, &len, uniflags ); \
1144 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1145 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1146 foldlen -= UNISKIP( uvc ); \
1147 scan = foldbuf + UNISKIP( uvc ); \
1150 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1160 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
1161 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
1162 U32 ging = TRIE_LIST_LEN( state ) *= 2; \
1163 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
1165 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
1166 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
1167 TRIE_LIST_CUR( state )++; \
1170 #define TRIE_LIST_NEW(state) STMT_START { \
1171 Newxz( trie->states[ state ].trans.list, \
1172 4, reg_trie_trans_le ); \
1173 TRIE_LIST_CUR( state ) = 1; \
1174 TRIE_LIST_LEN( state ) = 4; \
1177 #define TRIE_HANDLE_WORD(state) STMT_START { \
1178 U16 dupe= trie->states[ state ].wordnum; \
1179 regnode * const noper_next = regnext( noper ); \
1181 if (trie->wordlen) \
1182 trie->wordlen[ curword ] = wordlen; \
1184 /* store the word for dumping */ \
1186 if (OP(noper) != NOTHING) \
1187 tmp = newSVpvn(STRING(noper), STR_LEN(noper)); \
1189 tmp = newSVpvn( "", 0 ); \
1190 if ( UTF ) SvUTF8_on( tmp ); \
1191 av_push( trie->words, tmp ); \
1196 if ( noper_next < tail ) { \
1198 Newxz( trie->jump, word_count + 1, U16); \
1199 trie->jump[curword] = (U16)(noper_next - convert); \
1201 jumper = noper_next; \
1203 nextbranch= regnext(cur); \
1207 /* So it's a dupe. This means we need to maintain a */\
1208 /* linked-list from the first to the next. */\
1209 /* we only allocate the nextword buffer when there */\
1210 /* a dupe, so first time we have to do the allocation */\
1211 if (!trie->nextword) \
1212 Newxz( trie->nextword, word_count + 1, U16); \
1213 while ( trie->nextword[dupe] ) \
1214 dupe= trie->nextword[dupe]; \
1215 trie->nextword[dupe]= curword; \
1217 /* we haven't inserted this word yet. */ \
1218 trie->states[ state ].wordnum = curword; \
1223 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
1224 ( ( base + charid >= ucharcount \
1225 && base + charid < ubound \
1226 && state == trie->trans[ base - ucharcount + charid ].check \
1227 && trie->trans[ base - ucharcount + charid ].next ) \
1228 ? trie->trans[ base - ucharcount + charid ].next \
1229 : ( state==1 ? special : 0 ) \
1233 #define MADE_JUMP_TRIE 2
1234 #define MADE_EXACT_TRIE 4
1237 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
1240 /* first pass, loop through and scan words */
1241 reg_trie_data *trie;
1243 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1248 regnode *jumper = NULL;
1249 regnode *nextbranch = NULL;
1250 regnode *convert = NULL;
1251 /* we just use folder as a flag in utf8 */
1252 const U8 * const folder = ( flags == EXACTF
1254 : ( flags == EXACTFL
1260 const U32 data_slot = add_data( pRExC_state, 1, "t" );
1261 SV *re_trie_maxbuff;
1263 /* these are only used during construction but are useful during
1264 * debugging so we store them in the struct when debugging.
1266 STRLEN trie_charcount=0;
1267 AV *trie_revcharmap;
1269 GET_RE_DEBUG_FLAGS_DECL;
1271 PERL_UNUSED_ARG(depth);
1274 Newxz( trie, 1, reg_trie_data );
1276 trie->startstate = 1;
1277 trie->wordcount = word_count;
1278 RExC_rx->data->data[ data_slot ] = (void*)trie;
1279 Newxz( trie->charmap, 256, U16 );
1280 if (!(UTF && folder))
1281 Newxz( trie->bitmap, ANYOF_BITMAP_SIZE, char );
1283 trie->words = newAV();
1285 TRIE_REVCHARMAP(trie) = newAV();
1287 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
1288 if (!SvIOK(re_trie_maxbuff)) {
1289 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
1292 PerlIO_printf( Perl_debug_log,
1293 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
1294 (int)depth * 2 + 2, "",
1295 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
1296 REG_NODE_NUM(last), REG_NODE_NUM(tail),
1300 /* Find the node we are going to overwrite */
1301 if ( first == startbranch && OP( last ) != BRANCH ) {
1302 /* whole branch chain */
1305 /* branch sub-chain */
1306 convert = NEXTOPER( first );
1309 /* -- First loop and Setup --
1311 We first traverse the branches and scan each word to determine if it
1312 contains widechars, and how many unique chars there are, this is
1313 important as we have to build a table with at least as many columns as we
1316 We use an array of integers to represent the character codes 0..255
1317 (trie->charmap) and we use a an HV* to store unicode characters. We use the
1318 native representation of the character value as the key and IV's for the
1321 *TODO* If we keep track of how many times each character is used we can
1322 remap the columns so that the table compression later on is more
1323 efficient in terms of memory by ensuring most common value is in the
1324 middle and the least common are on the outside. IMO this would be better
1325 than a most to least common mapping as theres a decent chance the most
1326 common letter will share a node with the least common, meaning the node
1327 will not be compressable. With a middle is most common approach the worst
1328 case is when we have the least common nodes twice.
1332 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1333 regnode * const noper = NEXTOPER( cur );
1334 const U8 *uc = (U8*)STRING( noper );
1335 const U8 * const e = uc + STR_LEN( noper );
1337 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1338 const U8 *scan = (U8*)NULL;
1339 U32 wordlen = 0; /* required init */
1342 if (OP(noper) == NOTHING) {
1347 TRIE_BITMAP_SET(trie,*uc);
1348 if ( folder ) TRIE_BITMAP_SET(trie,folder[ *uc ]);
1350 for ( ; uc < e ; uc += len ) {
1351 TRIE_CHARCOUNT(trie)++;
1355 if ( !trie->charmap[ uvc ] ) {
1356 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1358 trie->charmap[ folder[ uvc ] ] = trie->charmap[ uvc ];
1363 if ( !trie->widecharmap )
1364 trie->widecharmap = newHV();
1366 svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 1 );
1369 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
1371 if ( !SvTRUE( *svpp ) ) {
1372 sv_setiv( *svpp, ++trie->uniquecharcount );
1377 if( cur == first ) {
1380 } else if (chars < trie->minlen) {
1382 } else if (chars > trie->maxlen) {
1386 } /* end first pass */
1387 DEBUG_TRIE_COMPILE_r(
1388 PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1389 (int)depth * 2 + 2,"",
1390 ( trie->widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
1391 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1392 (int)trie->minlen, (int)trie->maxlen )
1394 Newxz( trie->wordlen, word_count, U32 );
1397 We now know what we are dealing with in terms of unique chars and
1398 string sizes so we can calculate how much memory a naive
1399 representation using a flat table will take. If it's over a reasonable
1400 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
1401 conservative but potentially much slower representation using an array
1404 At the end we convert both representations into the same compressed
1405 form that will be used in regexec.c for matching with. The latter
1406 is a form that cannot be used to construct with but has memory
1407 properties similar to the list form and access properties similar
1408 to the table form making it both suitable for fast searches and
1409 small enough that its feasable to store for the duration of a program.
1411 See the comment in the code where the compressed table is produced
1412 inplace from the flat tabe representation for an explanation of how
1413 the compression works.
1418 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
1420 Second Pass -- Array Of Lists Representation
1422 Each state will be represented by a list of charid:state records
1423 (reg_trie_trans_le) the first such element holds the CUR and LEN
1424 points of the allocated array. (See defines above).
1426 We build the initial structure using the lists, and then convert
1427 it into the compressed table form which allows faster lookups
1428 (but cant be modified once converted).
1431 STRLEN transcount = 1;
1433 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1434 "%*sCompiling trie using list compiler\n",
1435 (int)depth * 2 + 2, ""));
1437 Newxz( trie->states, TRIE_CHARCOUNT(trie) + 2, reg_trie_state );
1441 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1443 regnode * const noper = NEXTOPER( cur );
1444 U8 *uc = (U8*)STRING( noper );
1445 const U8 * const e = uc + STR_LEN( noper );
1446 U32 state = 1; /* required init */
1447 U16 charid = 0; /* sanity init */
1448 U8 *scan = (U8*)NULL; /* sanity init */
1449 STRLEN foldlen = 0; /* required init */
1450 U32 wordlen = 0; /* required init */
1451 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1453 if (OP(noper) != NOTHING) {
1454 for ( ; uc < e ; uc += len ) {
1459 charid = trie->charmap[ uvc ];
1461 SV** const svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 0);
1465 charid=(U16)SvIV( *svpp );
1468 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1475 if ( !trie->states[ state ].trans.list ) {
1476 TRIE_LIST_NEW( state );
1478 for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1479 if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1480 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1485 newstate = next_alloc++;
1486 TRIE_LIST_PUSH( state, charid, newstate );
1491 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1495 TRIE_HANDLE_WORD(state);
1497 } /* end second pass */
1499 /* next alloc is the NEXT state to be allocated */
1500 trie->statecount = next_alloc;
1501 Renew( trie->states, next_alloc, reg_trie_state );
1503 /* and now dump it out before we compress it */
1504 DEBUG_TRIE_COMPILE_MORE_r(
1505 dump_trie_interim_list(trie,next_alloc,depth+1)
1508 Newxz( trie->trans, transcount ,reg_trie_trans );
1515 for( state=1 ; state < next_alloc ; state ++ ) {
1519 DEBUG_TRIE_COMPILE_MORE_r(
1520 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1524 if (trie->states[state].trans.list) {
1525 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1529 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1530 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1531 if ( forid < minid ) {
1533 } else if ( forid > maxid ) {
1537 if ( transcount < tp + maxid - minid + 1) {
1539 Renew( trie->trans, transcount, reg_trie_trans );
1540 Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1542 base = trie->uniquecharcount + tp - minid;
1543 if ( maxid == minid ) {
1545 for ( ; zp < tp ; zp++ ) {
1546 if ( ! trie->trans[ zp ].next ) {
1547 base = trie->uniquecharcount + zp - minid;
1548 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1549 trie->trans[ zp ].check = state;
1555 trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1556 trie->trans[ tp ].check = state;
1561 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1562 const U32 tid = base - trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
1563 trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1564 trie->trans[ tid ].check = state;
1566 tp += ( maxid - minid + 1 );
1568 Safefree(trie->states[ state ].trans.list);
1571 DEBUG_TRIE_COMPILE_MORE_r(
1572 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1575 trie->states[ state ].trans.base=base;
1577 trie->lasttrans = tp + 1;
1581 Second Pass -- Flat Table Representation.
1583 we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1584 We know that we will need Charcount+1 trans at most to store the data
1585 (one row per char at worst case) So we preallocate both structures
1586 assuming worst case.
1588 We then construct the trie using only the .next slots of the entry
1591 We use the .check field of the first entry of the node temporarily to
1592 make compression both faster and easier by keeping track of how many non
1593 zero fields are in the node.
1595 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1598 There are two terms at use here: state as a TRIE_NODEIDX() which is a
1599 number representing the first entry of the node, and state as a
1600 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1601 TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1602 are 2 entrys per node. eg:
1610 The table is internally in the right hand, idx form. However as we also
1611 have to deal with the states array which is indexed by nodenum we have to
1612 use TRIE_NODENUM() to convert.
1615 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1616 "%*sCompiling trie using table compiler\n",
1617 (int)depth * 2 + 2, ""));
1619 Newxz( trie->trans, ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1,
1621 Newxz( trie->states, TRIE_CHARCOUNT(trie) + 2, reg_trie_state );
1622 next_alloc = trie->uniquecharcount + 1;
1625 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1627 regnode * const noper = NEXTOPER( cur );
1628 const U8 *uc = (U8*)STRING( noper );
1629 const U8 * const e = uc + STR_LEN( noper );
1631 U32 state = 1; /* required init */
1633 U16 charid = 0; /* sanity init */
1634 U32 accept_state = 0; /* sanity init */
1635 U8 *scan = (U8*)NULL; /* sanity init */
1637 STRLEN foldlen = 0; /* required init */
1638 U32 wordlen = 0; /* required init */
1639 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1641 if ( OP(noper) != NOTHING ) {
1642 for ( ; uc < e ; uc += len ) {
1647 charid = trie->charmap[ uvc ];
1649 SV* const * const svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 0);
1650 charid = svpp ? (U16)SvIV(*svpp) : 0;
1654 if ( !trie->trans[ state + charid ].next ) {
1655 trie->trans[ state + charid ].next = next_alloc;
1656 trie->trans[ state ].check++;
1657 next_alloc += trie->uniquecharcount;
1659 state = trie->trans[ state + charid ].next;
1661 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1663 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1666 accept_state = TRIE_NODENUM( state );
1667 TRIE_HANDLE_WORD(accept_state);
1669 } /* end second pass */
1671 /* and now dump it out before we compress it */
1672 DEBUG_TRIE_COMPILE_MORE_r(
1673 dump_trie_interim_table(trie,next_alloc,depth+1)
1678 * Inplace compress the table.*
1680 For sparse data sets the table constructed by the trie algorithm will
1681 be mostly 0/FAIL transitions or to put it another way mostly empty.
1682 (Note that leaf nodes will not contain any transitions.)
1684 This algorithm compresses the tables by eliminating most such
1685 transitions, at the cost of a modest bit of extra work during lookup:
1687 - Each states[] entry contains a .base field which indicates the
1688 index in the state[] array wheres its transition data is stored.
1690 - If .base is 0 there are no valid transitions from that node.
1692 - If .base is nonzero then charid is added to it to find an entry in
1695 -If trans[states[state].base+charid].check!=state then the
1696 transition is taken to be a 0/Fail transition. Thus if there are fail
1697 transitions at the front of the node then the .base offset will point
1698 somewhere inside the previous nodes data (or maybe even into a node
1699 even earlier), but the .check field determines if the transition is
1703 The following process inplace converts the table to the compressed
1704 table: We first do not compress the root node 1,and mark its all its
1705 .check pointers as 1 and set its .base pointer as 1 as well. This
1706 allows to do a DFA construction from the compressed table later, and
1707 ensures that any .base pointers we calculate later are greater than
1710 - We set 'pos' to indicate the first entry of the second node.
1712 - We then iterate over the columns of the node, finding the first and
1713 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
1714 and set the .check pointers accordingly, and advance pos
1715 appropriately and repreat for the next node. Note that when we copy
1716 the next pointers we have to convert them from the original
1717 NODEIDX form to NODENUM form as the former is not valid post
1720 - If a node has no transitions used we mark its base as 0 and do not
1721 advance the pos pointer.
1723 - If a node only has one transition we use a second pointer into the
1724 structure to fill in allocated fail transitions from other states.
1725 This pointer is independent of the main pointer and scans forward
1726 looking for null transitions that are allocated to a state. When it
1727 finds one it writes the single transition into the "hole". If the
1728 pointer doesnt find one the single transition is appended as normal.
1730 - Once compressed we can Renew/realloc the structures to release the
1733 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
1734 specifically Fig 3.47 and the associated pseudocode.
1738 const U32 laststate = TRIE_NODENUM( next_alloc );
1741 trie->statecount = laststate;
1743 for ( state = 1 ; state < laststate ; state++ ) {
1745 const U32 stateidx = TRIE_NODEIDX( state );
1746 const U32 o_used = trie->trans[ stateidx ].check;
1747 U32 used = trie->trans[ stateidx ].check;
1748 trie->trans[ stateidx ].check = 0;
1750 for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
1751 if ( flag || trie->trans[ stateidx + charid ].next ) {
1752 if ( trie->trans[ stateidx + charid ].next ) {
1754 for ( ; zp < pos ; zp++ ) {
1755 if ( ! trie->trans[ zp ].next ) {
1759 trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
1760 trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1761 trie->trans[ zp ].check = state;
1762 if ( ++zp > pos ) pos = zp;
1769 trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
1771 trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1772 trie->trans[ pos ].check = state;
1777 trie->lasttrans = pos + 1;
1778 Renew( trie->states, laststate, reg_trie_state);
1779 DEBUG_TRIE_COMPILE_MORE_r(
1780 PerlIO_printf( Perl_debug_log,
1781 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
1782 (int)depth * 2 + 2,"",
1783 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
1786 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
1789 } /* end table compress */
1791 DEBUG_TRIE_COMPILE_MORE_r(
1792 PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
1793 (int)depth * 2 + 2, "",
1794 (UV)trie->statecount,
1795 (UV)trie->lasttrans)
1797 /* resize the trans array to remove unused space */
1798 Renew( trie->trans, trie->lasttrans, reg_trie_trans);
1800 /* and now dump out the compressed format */
1801 DEBUG_TRIE_COMPILE_r(
1802 dump_trie(trie,depth+1)
1805 { /* Modify the program and insert the new TRIE node*/
1806 U8 nodetype =(U8)(flags & 0xFF);
1810 regnode *optimize = NULL;
1812 U32 mjd_nodelen = 0;
1815 This means we convert either the first branch or the first Exact,
1816 depending on whether the thing following (in 'last') is a branch
1817 or not and whther first is the startbranch (ie is it a sub part of
1818 the alternation or is it the whole thing.)
1819 Assuming its a sub part we conver the EXACT otherwise we convert
1820 the whole branch sequence, including the first.
1822 /* Find the node we are going to overwrite */
1823 if ( first != startbranch || OP( last ) == BRANCH ) {
1824 /* branch sub-chain */
1825 NEXT_OFF( first ) = (U16)(last - first);
1827 mjd_offset= Node_Offset((convert));
1828 mjd_nodelen= Node_Length((convert));
1830 /* whole branch chain */
1833 const regnode *nop = NEXTOPER( convert );
1834 mjd_offset= Node_Offset((nop));
1835 mjd_nodelen= Node_Length((nop));
1840 PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
1841 (int)depth * 2 + 2, "",
1842 (UV)mjd_offset, (UV)mjd_nodelen)
1845 /* But first we check to see if there is a common prefix we can
1846 split out as an EXACT and put in front of the TRIE node. */
1847 trie->startstate= 1;
1848 if ( trie->bitmap && !trie->widecharmap && !trie->jump ) {
1850 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
1854 const U32 base = trie->states[ state ].trans.base;
1856 if ( trie->states[state].wordnum )
1859 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1860 if ( ( base + ofs >= trie->uniquecharcount ) &&
1861 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
1862 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
1864 if ( ++count > 1 ) {
1865 SV **tmp = av_fetch( TRIE_REVCHARMAP(trie), ofs, 0);
1866 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
1867 if ( state == 1 ) break;
1869 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
1871 PerlIO_printf(Perl_debug_log,
1872 "%*sNew Start State=%"UVuf" Class: [",
1873 (int)depth * 2 + 2, "",
1876 SV ** const tmp = av_fetch( TRIE_REVCHARMAP(trie), idx, 0);
1877 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
1879 TRIE_BITMAP_SET(trie,*ch);
1881 TRIE_BITMAP_SET(trie, folder[ *ch ]);
1883 PerlIO_printf(Perl_debug_log, (char*)ch)
1887 TRIE_BITMAP_SET(trie,*ch);
1889 TRIE_BITMAP_SET(trie,folder[ *ch ]);
1890 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
1896 SV **tmp = av_fetch( TRIE_REVCHARMAP(trie), idx, 0);
1897 char *ch = SvPV_nolen( *tmp );
1899 SV *sv=sv_newmortal();
1900 PerlIO_printf( Perl_debug_log,
1901 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
1902 (int)depth * 2 + 2, "",
1904 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
1905 PL_colors[0], PL_colors[1],
1906 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1907 PERL_PV_ESCAPE_FIRSTCHAR
1912 OP( convert ) = nodetype;
1913 str=STRING(convert);
1924 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
1930 regnode *n = convert+NODE_SZ_STR(convert);
1931 NEXT_OFF(convert) = NODE_SZ_STR(convert);
1932 trie->startstate = state;
1933 trie->minlen -= (state - 1);
1934 trie->maxlen -= (state - 1);
1936 regnode *fix = convert;
1937 U32 word = trie->wordcount;
1939 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
1940 while( ++fix < n ) {
1941 Set_Node_Offset_Length(fix, 0, 0);
1944 SV ** const tmp = av_fetch( trie->words, word, 0 );
1946 if ( STR_LEN(convert) <= SvCUR(*tmp) )
1947 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
1949 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
1956 NEXT_OFF(convert) = (U16)(tail - convert);
1957 DEBUG_r(optimize= n);
1963 if ( trie->maxlen ) {
1964 NEXT_OFF( convert ) = (U16)(tail - convert);
1965 ARG_SET( convert, data_slot );
1966 /* Store the offset to the first unabsorbed branch in
1967 jump[0], which is otherwise unused by the jump logic.
1968 We use this when dumping a trie and during optimisation. */
1970 trie->jump[0] = (U16)(nextbranch - convert);
1973 if ( !trie->states[trie->startstate].wordnum && trie->bitmap &&
1974 ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
1976 OP( convert ) = TRIEC;
1977 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
1978 Safefree(trie->bitmap);
1981 OP( convert ) = TRIE;
1983 /* store the type in the flags */
1984 convert->flags = nodetype;
1988 + regarglen[ OP( convert ) ];
1990 /* XXX We really should free up the resource in trie now,
1991 as we won't use them - (which resources?) dmq */
1993 /* needed for dumping*/
1994 DEBUG_r(if (optimize) {
1995 regnode *opt = convert;
1996 while ( ++opt < optimize) {
1997 Set_Node_Offset_Length(opt,0,0);
2000 Try to clean up some of the debris left after the
2003 while( optimize < jumper ) {
2004 mjd_nodelen += Node_Length((optimize));
2005 OP( optimize ) = OPTIMIZED;
2006 Set_Node_Offset_Length(optimize,0,0);
2009 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
2011 } /* end node insert */
2013 SvREFCNT_dec(TRIE_REVCHARMAP(trie));
2017 : trie->startstate>1
2023 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source, regnode *stclass, U32 depth)
2025 /* The Trie is constructed and compressed now so we can build a fail array now if its needed
2027 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
2028 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
2031 We find the fail state for each state in the trie, this state is the longest proper
2032 suffix of the current states 'word' that is also a proper prefix of another word in our
2033 trie. State 1 represents the word '' and is the thus the default fail state. This allows
2034 the DFA not to have to restart after its tried and failed a word at a given point, it
2035 simply continues as though it had been matching the other word in the first place.
2037 'abcdgu'=~/abcdefg|cdgu/
2038 When we get to 'd' we are still matching the first word, we would encounter 'g' which would
2039 fail, which would bring use to the state representing 'd' in the second word where we would
2040 try 'g' and succeed, prodceding to match 'cdgu'.
2042 /* add a fail transition */
2043 reg_trie_data *trie=(reg_trie_data *)RExC_rx->data->data[ARG(source)];
2045 const U32 ucharcount = trie->uniquecharcount;
2046 const U32 numstates = trie->statecount;
2047 const U32 ubound = trie->lasttrans + ucharcount;
2051 U32 base = trie->states[ 1 ].trans.base;
2054 const U32 data_slot = add_data( pRExC_state, 1, "T" );
2055 GET_RE_DEBUG_FLAGS_DECL;
2057 PERL_UNUSED_ARG(depth);
2061 ARG_SET( stclass, data_slot );
2062 Newxz( aho, 1, reg_ac_data );
2063 RExC_rx->data->data[ data_slot ] = (void*)aho;
2065 aho->states=(reg_trie_state *)savepvn((const char*)trie->states,
2066 numstates * sizeof(reg_trie_state));
2067 Newxz( q, numstates, U32);
2068 Newxz( aho->fail, numstates, U32 );
2071 /* initialize fail[0..1] to be 1 so that we always have
2072 a valid final fail state */
2073 fail[ 0 ] = fail[ 1 ] = 1;
2075 for ( charid = 0; charid < ucharcount ; charid++ ) {
2076 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2078 q[ q_write ] = newstate;
2079 /* set to point at the root */
2080 fail[ q[ q_write++ ] ]=1;
2083 while ( q_read < q_write) {
2084 const U32 cur = q[ q_read++ % numstates ];
2085 base = trie->states[ cur ].trans.base;
2087 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2088 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2090 U32 fail_state = cur;
2093 fail_state = fail[ fail_state ];
2094 fail_base = aho->states[ fail_state ].trans.base;
2095 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2097 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2098 fail[ ch_state ] = fail_state;
2099 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2101 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
2103 q[ q_write++ % numstates] = ch_state;
2107 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2108 when we fail in state 1, this allows us to use the
2109 charclass scan to find a valid start char. This is based on the principle
2110 that theres a good chance the string being searched contains lots of stuff
2111 that cant be a start char.
2113 fail[ 0 ] = fail[ 1 ] = 0;
2114 DEBUG_TRIE_COMPILE_r({
2115 PerlIO_printf(Perl_debug_log,
2116 "%*sStclass Failtable (%"UVuf" states): 0",
2117 (int)(depth * 2), "", (UV)numstates
2119 for( q_read=1; q_read<numstates; q_read++ ) {
2120 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2122 PerlIO_printf(Perl_debug_log, "\n");
2125 /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2130 * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2131 * These need to be revisited when a newer toolchain becomes available.
2133 #if defined(__sparc64__) && defined(__GNUC__)
2134 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2135 # undef SPARC64_GCC_WORKAROUND
2136 # define SPARC64_GCC_WORKAROUND 1
2140 #define DEBUG_PEEP(str,scan,depth) \
2141 DEBUG_OPTIMISE_r({if (scan){ \
2142 SV * const mysv=sv_newmortal(); \
2143 regnode *Next = regnext(scan); \
2144 regprop(RExC_rx, mysv, scan); \
2145 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
2146 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2147 Next ? (REG_NODE_NUM(Next)) : 0 ); \
2154 #define JOIN_EXACT(scan,min,flags) \
2155 if (PL_regkind[OP(scan)] == EXACT) \
2156 join_exact(pRExC_state,(scan),(min),(flags),NULL,depth+1)
2159 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, I32 *min, U32 flags,regnode *val, U32 depth) {
2160 /* Merge several consecutive EXACTish nodes into one. */
2161 regnode *n = regnext(scan);
2163 regnode *next = scan + NODE_SZ_STR(scan);
2167 regnode *stop = scan;
2168 GET_RE_DEBUG_FLAGS_DECL;
2170 PERL_UNUSED_ARG(depth);
2172 #ifndef EXPERIMENTAL_INPLACESCAN
2173 PERL_UNUSED_ARG(flags);
2174 PERL_UNUSED_ARG(val);
2176 DEBUG_PEEP("join",scan,depth);
2178 /* Skip NOTHING, merge EXACT*. */
2180 ( PL_regkind[OP(n)] == NOTHING ||
2181 (stringok && (OP(n) == OP(scan))))
2183 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
2185 if (OP(n) == TAIL || n > next)
2187 if (PL_regkind[OP(n)] == NOTHING) {
2188 DEBUG_PEEP("skip:",n,depth);
2189 NEXT_OFF(scan) += NEXT_OFF(n);
2190 next = n + NODE_STEP_REGNODE;
2197 else if (stringok) {
2198 const unsigned int oldl = STR_LEN(scan);
2199 regnode * const nnext = regnext(n);
2201 DEBUG_PEEP("merg",n,depth);
2204 if (oldl + STR_LEN(n) > U8_MAX)
2206 NEXT_OFF(scan) += NEXT_OFF(n);
2207 STR_LEN(scan) += STR_LEN(n);
2208 next = n + NODE_SZ_STR(n);
2209 /* Now we can overwrite *n : */
2210 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2218 #ifdef EXPERIMENTAL_INPLACESCAN
2219 if (flags && !NEXT_OFF(n)) {
2220 DEBUG_PEEP("atch", val, depth);
2221 if (reg_off_by_arg[OP(n)]) {
2222 ARG_SET(n, val - n);
2225 NEXT_OFF(n) = val - n;
2232 if (UTF && ( OP(scan) == EXACTF ) && ( STR_LEN(scan) >= 6 ) ) {
2234 Two problematic code points in Unicode casefolding of EXACT nodes:
2236 U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2237 U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2243 U+03B9 U+0308 U+0301 0xCE 0xB9 0xCC 0x88 0xCC 0x81
2244 U+03C5 U+0308 U+0301 0xCF 0x85 0xCC 0x88 0xCC 0x81
2246 This means that in case-insensitive matching (or "loose matching",
2247 as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte
2248 length of the above casefolded versions) can match a target string
2249 of length two (the byte length of UTF-8 encoded U+0390 or U+03B0).
2250 This would rather mess up the minimum length computation.
2252 What we'll do is to look for the tail four bytes, and then peek
2253 at the preceding two bytes to see whether we need to decrease
2254 the minimum length by four (six minus two).
2256 Thanks to the design of UTF-8, there cannot be false matches:
2257 A sequence of valid UTF-8 bytes cannot be a subsequence of
2258 another valid sequence of UTF-8 bytes.
2261 char * const s0 = STRING(scan), *s, *t;
2262 char * const s1 = s0 + STR_LEN(scan) - 1;
2263 char * const s2 = s1 - 4;
2264 #ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2265 const char t0[] = "\xaf\x49\xaf\x42";
2267 const char t0[] = "\xcc\x88\xcc\x81";
2269 const char * const t1 = t0 + 3;
2272 s < s2 && (t = ninstr(s, s1, t0, t1));
2275 if (((U8)t[-1] == 0x68 && (U8)t[-2] == 0xB4) ||
2276 ((U8)t[-1] == 0x46 && (U8)t[-2] == 0xB5))
2278 if (((U8)t[-1] == 0xB9 && (U8)t[-2] == 0xCE) ||
2279 ((U8)t[-1] == 0x85 && (U8)t[-2] == 0xCF))
2287 n = scan + NODE_SZ_STR(scan);
2289 if (PL_regkind[OP(n)] != NOTHING || OP(n) == NOTHING) {
2296 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2300 /* REx optimizer. Converts nodes into quickier variants "in place".
2301 Finds fixed substrings. */
2303 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
2304 to the position after last scanned or to NULL. */
2306 #define INIT_AND_WITHP \
2307 assert(!and_withp); \
2308 Newx(and_withp,1,struct regnode_charclass_class); \
2309 SAVEFREEPV(and_withp)
2311 /* this is a chain of data about sub patterns we are processing that
2312 need to be handled seperately/specially in study_chunk. Its so
2313 we can simulate recursion without losing state. */
2315 typedef struct scan_frame {
2316 regnode *last; /* last node to process in this frame */
2317 regnode *next; /* next node to process when last is reached */
2318 struct scan_frame *prev; /*previous frame*/
2319 I32 stop; /* what stopparen do we use */
2323 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
2324 I32 *minlenp, I32 *deltap,
2329 struct regnode_charclass_class *and_withp,
2330 U32 flags, U32 depth)
2331 /* scanp: Start here (read-write). */
2332 /* deltap: Write maxlen-minlen here. */
2333 /* last: Stop before this one. */
2334 /* data: string data about the pattern */
2335 /* stopparen: treat close N as END */
2336 /* recursed: which subroutines have we recursed into */
2337 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
2340 I32 min = 0, pars = 0, code;
2341 regnode *scan = *scanp, *next;
2343 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
2344 int is_inf_internal = 0; /* The studied chunk is infinite */
2345 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2346 scan_data_t data_fake;
2347 SV *re_trie_maxbuff = NULL;
2348 regnode *first_non_open = scan;
2349 I32 stopmin = I32_MAX;
2350 scan_frame *frame = NULL;
2352 GET_RE_DEBUG_FLAGS_DECL;
2355 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
2359 while (first_non_open && OP(first_non_open) == OPEN)
2360 first_non_open=regnext(first_non_open);
2365 while ( scan && OP(scan) != END && scan < last ){
2366 /* Peephole optimizer: */
2367 DEBUG_STUDYDATA(data,depth);
2368 DEBUG_PEEP("Peep",scan,depth);
2369 JOIN_EXACT(scan,&min,0);
2371 /* Follow the next-chain of the current node and optimize
2372 away all the NOTHINGs from it. */
2373 if (OP(scan) != CURLYX) {
2374 const int max = (reg_off_by_arg[OP(scan)]
2376 /* I32 may be smaller than U16 on CRAYs! */
2377 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
2378 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
2382 /* Skip NOTHING and LONGJMP. */
2383 while ((n = regnext(n))
2384 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
2385 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
2386 && off + noff < max)
2388 if (reg_off_by_arg[OP(scan)])
2391 NEXT_OFF(scan) = off;
2396 /* The principal pseudo-switch. Cannot be a switch, since we
2397 look into several different things. */
2398 if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
2399 || OP(scan) == IFTHEN) {
2400 next = regnext(scan);
2402 /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
2404 if (OP(next) == code || code == IFTHEN) {
2405 /* NOTE - There is similar code to this block below for handling
2406 TRIE nodes on a re-study. If you change stuff here check there
2408 I32 max1 = 0, min1 = I32_MAX, num = 0;
2409 struct regnode_charclass_class accum;
2410 regnode * const startbranch=scan;
2412 if (flags & SCF_DO_SUBSTR)
2413 scan_commit(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
2414 if (flags & SCF_DO_STCLASS)
2415 cl_init_zero(pRExC_state, &accum);
2417 while (OP(scan) == code) {
2418 I32 deltanext, minnext, f = 0, fake;
2419 struct regnode_charclass_class this_class;
2422 data_fake.flags = 0;
2424 data_fake.whilem_c = data->whilem_c;
2425 data_fake.last_closep = data->last_closep;
2428 data_fake.last_closep = &fake;
2429 next = regnext(scan);
2430 scan = NEXTOPER(scan);
2432 scan = NEXTOPER(scan);
2433 if (flags & SCF_DO_STCLASS) {
2434 cl_init(pRExC_state, &this_class);
2435 data_fake.start_class = &this_class;
2436 f = SCF_DO_STCLASS_AND;
2438 if (flags & SCF_WHILEM_VISITED_POS)
2439 f |= SCF_WHILEM_VISITED_POS;
2441 /* we suppose the run is continuous, last=next...*/
2442 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2444 stopparen, recursed, NULL, f,depth+1);
2447 if (max1 < minnext + deltanext)
2448 max1 = minnext + deltanext;
2449 if (deltanext == I32_MAX)
2450 is_inf = is_inf_internal = 1;
2452 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
2454 if (data_fake.flags & SCF_SEEN_ACCEPT) {
2455 if ( stopmin > minnext)
2456 stopmin = min + min1;
2457 flags &= ~SCF_DO_SUBSTR;
2459 data->flags |= SCF_SEEN_ACCEPT;
2462 if (data_fake.flags & SF_HAS_EVAL)
2463 data->flags |= SF_HAS_EVAL;
2464 data->whilem_c = data_fake.whilem_c;
2466 if (flags & SCF_DO_STCLASS)
2467 cl_or(pRExC_state, &accum, &this_class);
2469 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
2471 if (flags & SCF_DO_SUBSTR) {
2472 data->pos_min += min1;
2473 data->pos_delta += max1 - min1;
2474 if (max1 != min1 || is_inf)
2475 data->longest = &(data->longest_float);
2478 delta += max1 - min1;
2479 if (flags & SCF_DO_STCLASS_OR) {
2480 cl_or(pRExC_state, data->start_class, &accum);
2482 cl_and(data->start_class, and_withp);
2483 flags &= ~SCF_DO_STCLASS;
2486 else if (flags & SCF_DO_STCLASS_AND) {
2488 cl_and(data->start_class, &accum);
2489 flags &= ~SCF_DO_STCLASS;
2492 /* Switch to OR mode: cache the old value of
2493 * data->start_class */
2495 StructCopy(data->start_class, and_withp,
2496 struct regnode_charclass_class);
2497 flags &= ~SCF_DO_STCLASS_AND;
2498 StructCopy(&accum, data->start_class,
2499 struct regnode_charclass_class);
2500 flags |= SCF_DO_STCLASS_OR;
2501 data->start_class->flags |= ANYOF_EOS;
2505 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
2508 Assuming this was/is a branch we are dealing with: 'scan' now
2509 points at the item that follows the branch sequence, whatever
2510 it is. We now start at the beginning of the sequence and look
2517 which would be constructed from a pattern like /A|LIST|OF|WORDS/
2519 If we can find such a subseqence we need to turn the first
2520 element into a trie and then add the subsequent branch exact
2521 strings to the trie.
2525 1. patterns where the whole set of branch can be converted.
2527 2. patterns where only a subset can be converted.
2529 In case 1 we can replace the whole set with a single regop
2530 for the trie. In case 2 we need to keep the start and end
2533 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
2534 becomes BRANCH TRIE; BRANCH X;
2536 There is an additional case, that being where there is a
2537 common prefix, which gets split out into an EXACT like node
2538 preceding the TRIE node.
2540 If x(1..n)==tail then we can do a simple trie, if not we make
2541 a "jump" trie, such that when we match the appropriate word
2542 we "jump" to the appopriate tail node. Essentailly we turn
2543 a nested if into a case structure of sorts.
2548 if (!re_trie_maxbuff) {
2549 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2550 if (!SvIOK(re_trie_maxbuff))
2551 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2553 if ( SvIV(re_trie_maxbuff)>=0 ) {
2555 regnode *first = (regnode *)NULL;
2556 regnode *last = (regnode *)NULL;
2557 regnode *tail = scan;
2562 SV * const mysv = sv_newmortal(); /* for dumping */
2564 /* var tail is used because there may be a TAIL
2565 regop in the way. Ie, the exacts will point to the
2566 thing following the TAIL, but the last branch will
2567 point at the TAIL. So we advance tail. If we
2568 have nested (?:) we may have to move through several
2572 while ( OP( tail ) == TAIL ) {
2573 /* this is the TAIL generated by (?:) */
2574 tail = regnext( tail );
2579 regprop(RExC_rx, mysv, tail );
2580 PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
2581 (int)depth * 2 + 2, "",
2582 "Looking for TRIE'able sequences. Tail node is: ",
2583 SvPV_nolen_const( mysv )
2589 step through the branches, cur represents each
2590 branch, noper is the first thing to be matched
2591 as part of that branch and noper_next is the
2592 regnext() of that node. if noper is an EXACT
2593 and noper_next is the same as scan (our current
2594 position in the regex) then the EXACT branch is
2595 a possible optimization target. Once we have
2596 two or more consequetive such branches we can
2597 create a trie of the EXACT's contents and stich
2598 it in place. If the sequence represents all of
2599 the branches we eliminate the whole thing and
2600 replace it with a single TRIE. If it is a
2601 subsequence then we need to stitch it in. This
2602 means the first branch has to remain, and needs
2603 to be repointed at the item on the branch chain
2604 following the last branch optimized. This could
2605 be either a BRANCH, in which case the
2606 subsequence is internal, or it could be the
2607 item following the branch sequence in which
2608 case the subsequence is at the end.
2612 /* dont use tail as the end marker for this traverse */
2613 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
2614 regnode * const noper = NEXTOPER( cur );
2615 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
2616 regnode * const noper_next = regnext( noper );
2620 regprop(RExC_rx, mysv, cur);
2621 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
2622 (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
2624 regprop(RExC_rx, mysv, noper);
2625 PerlIO_printf( Perl_debug_log, " -> %s",
2626 SvPV_nolen_const(mysv));
2629 regprop(RExC_rx, mysv, noper_next );
2630 PerlIO_printf( Perl_debug_log,"\t=> %s\t",
2631 SvPV_nolen_const(mysv));
2633 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
2634 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
2636 if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
2637 : PL_regkind[ OP( noper ) ] == EXACT )
2638 || OP(noper) == NOTHING )
2640 && noper_next == tail
2645 if ( !first || optype == NOTHING ) {
2646 if (!first) first = cur;
2647 optype = OP( noper );
2653 make_trie( pRExC_state,
2654 startbranch, first, cur, tail, count,
2657 if ( PL_regkind[ OP( noper ) ] == EXACT
2659 && noper_next == tail
2664 optype = OP( noper );
2674 regprop(RExC_rx, mysv, cur);
2675 PerlIO_printf( Perl_debug_log,
2676 "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
2677 "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
2681 made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
2682 #ifdef TRIE_STUDY_OPT
2683 if ( ((made == MADE_EXACT_TRIE &&
2684 startbranch == first)
2685 || ( first_non_open == first )) &&
2687 flags |= SCF_TRIE_RESTUDY;
2688 if ( startbranch == first
2691 RExC_seen &=~REG_TOP_LEVEL_BRANCHES;
2701 else if ( code == BRANCHJ ) { /* single branch is optimized. */
2702 scan = NEXTOPER(NEXTOPER(scan));
2703 } else /* single branch is optimized. */
2704 scan = NEXTOPER(scan);
2706 } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
2707 scan_frame *newframe = NULL;
2712 if (OP(scan) != SUSPEND) {
2713 /* set the pointer */
2714 if (OP(scan) == GOSUB) {
2716 RExC_recurse[ARG2L(scan)] = scan;
2717 start = RExC_open_parens[paren-1];
2718 end = RExC_close_parens[paren-1];
2721 start = RExC_rx->program + 1;
2725 Newxz(recursed, (((RExC_npar)>>3) +1), U8);
2726 SAVEFREEPV(recursed);
2728 if (!PAREN_TEST(recursed,paren+1)) {
2729 PAREN_SET(recursed,paren+1);
2730 Newx(newframe,1,scan_frame);
2732 if (flags & SCF_DO_SUBSTR) {
2733 scan_commit(pRExC_state,data,minlenp);
2734 data->longest = &(data->longest_float);
2736 is_inf = is_inf_internal = 1;
2737 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
2738 cl_anything(pRExC_state, data->start_class);
2739 flags &= ~SCF_DO_STCLASS;
2742 Newx(newframe,1,scan_frame);
2745 end = regnext(scan);
2750 SAVEFREEPV(newframe);
2751 newframe->next = regnext(scan);
2752 newframe->last = last;
2753 newframe->stop = stopparen;
2754 newframe->prev = frame;
2764 else if (OP(scan) == EXACT) {
2765 I32 l = STR_LEN(scan);
2768 const U8 * const s = (U8*)STRING(scan);
2769 l = utf8_length(s, s + l);
2770 uc = utf8_to_uvchr(s, NULL);
2772 uc = *((U8*)STRING(scan));
2775 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
2776 /* The code below prefers earlier match for fixed
2777 offset, later match for variable offset. */
2778 if (data->last_end == -1) { /* Update the start info. */
2779 data->last_start_min = data->pos_min;
2780 data->last_start_max = is_inf
2781 ? I32_MAX : data->pos_min + data->pos_delta;
2783 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
2785 SvUTF8_on(data->last_found);
2787 SV * const sv = data->last_found;
2788 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
2789 mg_find(sv, PERL_MAGIC_utf8) : NULL;
2790 if (mg && mg->mg_len >= 0)
2791 mg->mg_len += utf8_length((U8*)STRING(scan),
2792 (U8*)STRING(scan)+STR_LEN(scan));
2794 data->last_end = data->pos_min + l;
2795 data->pos_min += l; /* As in the first entry. */
2796 data->flags &= ~SF_BEFORE_EOL;
2798 if (flags & SCF_DO_STCLASS_AND) {
2799 /* Check whether it is compatible with what we know already! */
2803 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2804 && !ANYOF_BITMAP_TEST(data->start_class, uc)
2805 && (!(data->start_class->flags & ANYOF_FOLD)
2806 || !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2809 ANYOF_CLASS_ZERO(data->start_class);
2810 ANYOF_BITMAP_ZERO(data->start_class);
2812 ANYOF_BITMAP_SET(data->start_class, uc);
2813 data->start_class->flags &= ~ANYOF_EOS;
2815 data->start_class->flags &= ~ANYOF_UNICODE_ALL;
2817 else if (flags & SCF_DO_STCLASS_OR) {
2818 /* false positive possible if the class is case-folded */
2820 ANYOF_BITMAP_SET(data->start_class, uc);
2822 data->start_class->flags |= ANYOF_UNICODE_ALL;
2823 data->start_class->flags &= ~ANYOF_EOS;
2824 cl_and(data->start_class, and_withp);
2826 flags &= ~SCF_DO_STCLASS;
2828 else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
2829 I32 l = STR_LEN(scan);
2830 UV uc = *((U8*)STRING(scan));
2832 /* Search for fixed substrings supports EXACT only. */
2833 if (flags & SCF_DO_SUBSTR) {
2835 scan_commit(pRExC_state, data, minlenp);
2838 const U8 * const s = (U8 *)STRING(scan);
2839 l = utf8_length(s, s + l);
2840 uc = utf8_to_uvchr(s, NULL);
2843 if (flags & SCF_DO_SUBSTR)
2845 if (flags & SCF_DO_STCLASS_AND) {
2846 /* Check whether it is compatible with what we know already! */
2850 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2851 && !ANYOF_BITMAP_TEST(data->start_class, uc)
2852 && !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2854 ANYOF_CLASS_ZERO(data->start_class);
2855 ANYOF_BITMAP_ZERO(data->start_class);
2857 ANYOF_BITMAP_SET(data->start_class, uc);
2858 data->start_class->flags &= ~ANYOF_EOS;
2859 data->start_class->flags |= ANYOF_FOLD;
2860 if (OP(scan) == EXACTFL)
2861 data->start_class->flags |= ANYOF_LOCALE;
2864 else if (flags & SCF_DO_STCLASS_OR) {
2865 if (data->start_class->flags & ANYOF_FOLD) {
2866 /* false positive possible if the class is case-folded.
2867 Assume that the locale settings are the same... */
2869 ANYOF_BITMAP_SET(data->start_class, uc);
2870 data->start_class->flags &= ~ANYOF_EOS;
2872 cl_and(data->start_class, and_withp);
2874 flags &= ~SCF_DO_STCLASS;
2876 else if (strchr((const char*)PL_varies,OP(scan))) {
2877 I32 mincount, maxcount, minnext, deltanext, fl = 0;
2878 I32 f = flags, pos_before = 0;
2879 regnode * const oscan = scan;
2880 struct regnode_charclass_class this_class;
2881 struct regnode_charclass_class *oclass = NULL;
2882 I32 next_is_eval = 0;
2884 switch (PL_regkind[OP(scan)]) {
2885 case WHILEM: /* End of (?:...)* . */
2886 scan = NEXTOPER(scan);
2889 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
2890 next = NEXTOPER(scan);
2891 if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
2893 maxcount = REG_INFTY;
2894 next = regnext(scan);
2895 scan = NEXTOPER(scan);
2899 if (flags & SCF_DO_SUBSTR)
2904 if (flags & SCF_DO_STCLASS) {
2906 maxcount = REG_INFTY;
2907 next = regnext(scan);
2908 scan = NEXTOPER(scan);
2911 is_inf = is_inf_internal = 1;
2912 scan = regnext(scan);
2913 if (flags & SCF_DO_SUBSTR) {
2914 scan_commit(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
2915 data->longest = &(data->longest_float);
2917 goto optimize_curly_tail;
2919 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
2920 && (scan->flags == stopparen))
2925 mincount = ARG1(scan);
2926 maxcount = ARG2(scan);
2928 next = regnext(scan);
2929 if (OP(scan) == CURLYX) {
2930 I32 lp = (data ? *(data->last_closep) : 0);
2931 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
2933 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
2934 next_is_eval = (OP(scan) == EVAL);
2936 if (flags & SCF_DO_SUBSTR) {
2937 if (mincount == 0) scan_commit(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
2938 pos_before = data->pos_min;
2942 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
2944 data->flags |= SF_IS_INF;
2946 if (flags & SCF_DO_STCLASS) {
2947 cl_init(pRExC_state, &this_class);
2948 oclass = data->start_class;
2949 data->start_class = &this_class;
2950 f |= SCF_DO_STCLASS_AND;
2951 f &= ~SCF_DO_STCLASS_OR;
2953 /* These are the cases when once a subexpression
2954 fails at a particular position, it cannot succeed
2955 even after backtracking at the enclosing scope.
2957 XXXX what if minimal match and we are at the
2958 initial run of {n,m}? */
2959 if ((mincount != maxcount - 1) && (maxcount != REG_INFTY))
2960 f &= ~SCF_WHILEM_VISITED_POS;
2962 /* This will finish on WHILEM, setting scan, or on NULL: */
2963 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2964 last, data, stopparen, recursed, NULL,
2966 ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
2968 if (flags & SCF_DO_STCLASS)
2969 data->start_class = oclass;
2970 if (mincount == 0 || minnext == 0) {
2971 if (flags & SCF_DO_STCLASS_OR) {
2972 cl_or(pRExC_state, data->start_class, &this_class);
2974 else if (flags & SCF_DO_STCLASS_AND) {
2975 /* Switch to OR mode: cache the old value of
2976 * data->start_class */
2978 StructCopy(data->start_class, and_withp,
2979 struct regnode_charclass_class);
2980 flags &= ~SCF_DO_STCLASS_AND;
2981 StructCopy(&this_class, data->start_class,
2982 struct regnode_charclass_class);
2983 flags |= SCF_DO_STCLASS_OR;
2984 data->start_class->flags |= ANYOF_EOS;
2986 } else { /* Non-zero len */
2987 if (flags & SCF_DO_STCLASS_OR) {
2988 cl_or(pRExC_state, data->start_class, &this_class);
2989 cl_and(data->start_class, and_withp);
2991 else if (flags & SCF_DO_STCLASS_AND)
2992 cl_and(data->start_class, &this_class);
2993 flags &= ~SCF_DO_STCLASS;
2995 if (!scan) /* It was not CURLYX, but CURLY. */
2997 if ( /* ? quantifier ok, except for (?{ ... }) */
2998 (next_is_eval || !(mincount == 0 && maxcount == 1))
2999 && (minnext == 0) && (deltanext == 0)
3000 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
3001 && maxcount <= REG_INFTY/3 /* Complement check for big count */
3002 && ckWARN(WARN_REGEXP))
3005 "Quantifier unexpected on zero-length expression");
3008 min += minnext * mincount;
3009 is_inf_internal |= ((maxcount == REG_INFTY
3010 && (minnext + deltanext) > 0)
3011 || deltanext == I32_MAX);
3012 is_inf |= is_inf_internal;
3013 delta += (minnext + deltanext) * maxcount - minnext * mincount;
3015 /* Try powerful optimization CURLYX => CURLYN. */
3016 if ( OP(oscan) == CURLYX && data
3017 && data->flags & SF_IN_PAR
3018 && !(data->flags & SF_HAS_EVAL)
3019 && !deltanext && minnext == 1 ) {
3020 /* Try to optimize to CURLYN. */
3021 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
3022 regnode * const nxt1 = nxt;
3029 if (!strchr((const char*)PL_simple,OP(nxt))
3030 && !(PL_regkind[OP(nxt)] == EXACT
3031 && STR_LEN(nxt) == 1))
3037 if (OP(nxt) != CLOSE)
3039 if (RExC_open_parens) {
3040 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3041 RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
3043 /* Now we know that nxt2 is the only contents: */
3044 oscan->flags = (U8)ARG(nxt);
3046 OP(nxt1) = NOTHING; /* was OPEN. */
3049 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3050 NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
3051 NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
3052 OP(nxt) = OPTIMIZED; /* was CLOSE. */
3053 OP(nxt + 1) = OPTIMIZED; /* was count. */
3054 NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
3059 /* Try optimization CURLYX => CURLYM. */
3060 if ( OP(oscan) == CURLYX && data
3061 && !(data->flags & SF_HAS_PAR)
3062 && !(data->flags & SF_HAS_EVAL)
3063 && !deltanext /* atom is fixed width */
3064 && minnext != 0 /* CURLYM can't handle zero width */
3066 /* XXXX How to optimize if data == 0? */
3067 /* Optimize to a simpler form. */
3068 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
3072 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
3073 && (OP(nxt2) != WHILEM))
3075 OP(nxt2) = SUCCEED; /* Whas WHILEM */
3076 /* Need to optimize away parenths. */
3077 if (data->flags & SF_IN_PAR) {
3078 /* Set the parenth number. */
3079 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
3081 if (OP(nxt) != CLOSE)
3082 FAIL("Panic opt close");
3083 oscan->flags = (U8)ARG(nxt);
3084 if (RExC_open_parens) {
3085 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3086 RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
3088 OP(nxt1) = OPTIMIZED; /* was OPEN. */
3089 OP(nxt) = OPTIMIZED; /* was CLOSE. */
3092 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3093 OP(nxt + 1) = OPTIMIZED; /* was count. */
3094 NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
3095 NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
3098 while ( nxt1 && (OP(nxt1) != WHILEM)) {
3099 regnode *nnxt = regnext(nxt1);
3102 if (reg_off_by_arg[OP(nxt1)])
3103 ARG_SET(nxt1, nxt2 - nxt1);
3104 else if (nxt2 - nxt1 < U16_MAX)
3105 NEXT_OFF(nxt1) = nxt2 - nxt1;
3107 OP(nxt) = NOTHING; /* Cannot beautify */
3112 /* Optimize again: */
3113 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
3114 NULL, stopparen, recursed, NULL, 0,depth+1);
3119 else if ((OP(oscan) == CURLYX)
3120 && (flags & SCF_WHILEM_VISITED_POS)
3121 /* See the comment on a similar expression above.
3122 However, this time it not a subexpression
3123 we care about, but the expression itself. */
3124 && (maxcount == REG_INFTY)
3125 && data && ++data->whilem_c < 16) {
3126 /* This stays as CURLYX, we can put the count/of pair. */
3127 /* Find WHILEM (as in regexec.c) */
3128 regnode *nxt = oscan + NEXT_OFF(oscan);
3130 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
3132 PREVOPER(nxt)->flags = (U8)(data->whilem_c
3133 | (RExC_whilem_seen << 4)); /* On WHILEM */
3135 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
3137 if (flags & SCF_DO_SUBSTR) {
3138 SV *last_str = NULL;
3139 int counted = mincount != 0;
3141 if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
3142 #if defined(SPARC64_GCC_WORKAROUND)
3145 const char *s = NULL;
3148 if (pos_before >= data->last_start_min)
3151 b = data->last_start_min;
3154 s = SvPV_const(data->last_found, l);
3155 old = b - data->last_start_min;
3158 I32 b = pos_before >= data->last_start_min
3159 ? pos_before : data->last_start_min;
3161 const char * const s = SvPV_const(data->last_found, l);
3162 I32 old = b - data->last_start_min;
3166 old = utf8_hop((U8*)s, old) - (U8*)s;
3169 /* Get the added string: */
3170 last_str = newSVpvn(s + old, l);
3172 SvUTF8_on(last_str);
3173 if (deltanext == 0 && pos_before == b) {
3174 /* What was added is a constant string */
3176 SvGROW(last_str, (mincount * l) + 1);
3177 repeatcpy(SvPVX(last_str) + l,
3178 SvPVX_const(last_str), l, mincount - 1);
3179 SvCUR_set(last_str, SvCUR(last_str) * mincount);
3180 /* Add additional parts. */
3181 SvCUR_set(data->last_found,
3182 SvCUR(data->last_found) - l);
3183 sv_catsv(data->last_found, last_str);
3185 SV * sv = data->last_found;
3187 SvUTF8(sv) && SvMAGICAL(sv) ?
3188 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3189 if (mg && mg->mg_len >= 0)
3190 mg->mg_len += CHR_SVLEN(last_str);
3192 data->last_end += l * (mincount - 1);
3195 /* start offset must point into the last copy */
3196 data->last_start_min += minnext * (mincount - 1);
3197 data->last_start_max += is_inf ? I32_MAX
3198 : (maxcount - 1) * (minnext + data->pos_delta);
3201 /* It is counted once already... */
3202 data->pos_min += minnext * (mincount - counted);
3203 data->pos_delta += - counted * deltanext +
3204 (minnext + deltanext) * maxcount - minnext * mincount;
3205 if (mincount != maxcount) {
3206 /* Cannot extend fixed substrings found inside
3208 scan_commit(pRExC_state,data,minlenp);
3209 if (mincount && last_str) {
3210 SV * const sv = data->last_found;
3211 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3212 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3216 sv_setsv(sv, last_str);
3217 data->last_end = data->pos_min;
3218 data->last_start_min =
3219 data->pos_min - CHR_SVLEN(last_str);
3220 data->last_start_max = is_inf
3222 : data->pos_min + data->pos_delta
3223 - CHR_SVLEN(last_str);
3225 data->longest = &(data->longest_float);
3227 SvREFCNT_dec(last_str);
3229 if (data && (fl & SF_HAS_EVAL))
3230 data->flags |= SF_HAS_EVAL;
3231 optimize_curly_tail:
3232 if (OP(oscan) != CURLYX) {
3233 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
3235 NEXT_OFF(oscan) += NEXT_OFF(next);
3238 default: /* REF and CLUMP only? */
3239 if (flags & SCF_DO_SUBSTR) {
3240 scan_commit(pRExC_state,data,minlenp); /* Cannot expect anything... */
3241 data->longest = &(data->longest_float);
3243 is_inf = is_inf_internal = 1;
3244 if (flags & SCF_DO_STCLASS_OR)
3245 cl_anything(pRExC_state, data->start_class);
3246 flags &= ~SCF_DO_STCLASS;
3250 else if (strchr((const char*)PL_simple,OP(scan))) {
3253 if (flags & SCF_DO_SUBSTR) {
3254 scan_commit(pRExC_state,data,minlenp);
3258 if (flags & SCF_DO_STCLASS) {
3259 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3261 /* Some of the logic below assumes that switching
3262 locale on will only add false positives. */
3263 switch (PL_regkind[OP(scan)]) {
3267 /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
3268 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3269 cl_anything(pRExC_state, data->start_class);
3272 if (OP(scan) == SANY)
3274 if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
3275 value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
3276 || (data->start_class->flags & ANYOF_CLASS));
3277 cl_anything(pRExC_state, data->start_class);
3279 if (flags & SCF_DO_STCLASS_AND || !value)
3280 ANYOF_BITMAP_CLEAR(data->start_class,'\n');
3283 if (flags & SCF_DO_STCLASS_AND)
3284 cl_and(data->start_class,
3285 (struct regnode_charclass_class*)scan);
3287 cl_or(pRExC_state, data->start_class,
3288 (struct regnode_charclass_class*)scan);
3291 if (flags & SCF_DO_STCLASS_AND) {
3292 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3293 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3294 for (value = 0; value < 256; value++)
3295 if (!isALNUM(value))
3296 ANYOF_BITMAP_CLEAR(data->start_class, value);
3300 if (data->start_class->flags & ANYOF_LOCALE)
3301 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3303 for (value = 0; value < 256; value++)
3305 ANYOF_BITMAP_SET(data->start_class, value);
3310 if (flags & SCF_DO_STCLASS_AND) {
3311 if (data->start_class->flags & ANYOF_LOCALE)
3312 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3315 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3316 data->start_class->flags |= ANYOF_LOCALE;
3320 if (flags & SCF_DO_STCLASS_AND) {
3321 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3322 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3323 for (value = 0; value < 256; value++)
3325 ANYOF_BITMAP_CLEAR(data->start_class, value);
3329 if (data->start_class->flags & ANYOF_LOCALE)
3330 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3332 for (value = 0; value < 256; value++)
3333 if (!isALNUM(value))
3334 ANYOF_BITMAP_SET(data->start_class, value);
3339 if (flags & SCF_DO_STCLASS_AND) {
3340 if (data->start_class->flags & ANYOF_LOCALE)
3341 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3344 data->start_class->flags |= ANYOF_LOCALE;
3345 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3349 if (flags & SCF_DO_STCLASS_AND) {
3350 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3351 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3352 for (value = 0; value < 256; value++)
3353 if (!isSPACE(value))
3354 ANYOF_BITMAP_CLEAR(data->start_class, value);
3358 if (data->start_class->flags & ANYOF_LOCALE)
3359 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3361 for (value = 0; value < 256; value++)
3363 ANYOF_BITMAP_SET(data->start_class, value);
3368 if (flags & SCF_DO_STCLASS_AND) {
3369 if (data->start_class->flags & ANYOF_LOCALE)
3370 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3373 data->start_class->flags |= ANYOF_LOCALE;
3374 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3378 if (flags & SCF_DO_STCLASS_AND) {
3379 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3380 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3381 for (value = 0; value < 256; value++)
3383 ANYOF_BITMAP_CLEAR(data->start_class, value);
3387 if (data->start_class->flags & ANYOF_LOCALE)
3388 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3390 for (value = 0; value < 256; value++)
3391 if (!isSPACE(value))
3392 ANYOF_BITMAP_SET(data->start_class, value);
3397 if (flags & SCF_DO_STCLASS_AND) {
3398 if (data->start_class->flags & ANYOF_LOCALE) {
3399 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3400 for (value = 0; value < 256; value++)
3401 if (!isSPACE(value))
3402 ANYOF_BITMAP_CLEAR(data->start_class, value);
3406 data->start_class->flags |= ANYOF_LOCALE;
3407 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3411 if (flags & SCF_DO_STCLASS_AND) {
3412 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
3413 for (value = 0; value < 256; value++)
3414 if (!isDIGIT(value))
3415 ANYOF_BITMAP_CLEAR(data->start_class, value);
3418 if (data->start_class->flags & ANYOF_LOCALE)
3419 ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
3421 for (value = 0; value < 256; value++)
3423 ANYOF_BITMAP_SET(data->start_class, value);
3428 if (flags & SCF_DO_STCLASS_AND) {
3429 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
3430 for (value = 0; value < 256; value++)
3432 ANYOF_BITMAP_CLEAR(data->start_class, value);
3435 if (data->start_class->flags & ANYOF_LOCALE)
3436 ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
3438 for (value = 0; value < 256; value++)
3439 if (!isDIGIT(value))
3440 ANYOF_BITMAP_SET(data->start_class, value);
3445 if (flags & SCF_DO_STCLASS_OR)
3446 cl_and(data->start_class, and_withp);
3447 flags &= ~SCF_DO_STCLASS;
3450 else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
3451 data->flags |= (OP(scan) == MEOL
3455 else if ( PL_regkind[OP(scan)] == BRANCHJ
3456 /* Lookbehind, or need to calculate parens/evals/stclass: */
3457 && (scan->flags || data || (flags & SCF_DO_STCLASS))
3458 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
3459 if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3460 || OP(scan) == UNLESSM )
3462 /* Negative Lookahead/lookbehind
3463 In this case we can't do fixed string optimisation.
3466 I32 deltanext, minnext, fake = 0;
3468 struct regnode_charclass_class intrnl;
3471 data_fake.flags = 0;
3473 data_fake.whilem_c = data->whilem_c;
3474 data_fake.last_closep = data->last_closep;
3477 data_fake.last_closep = &fake;
3478 if ( flags & SCF_DO_STCLASS && !scan->flags
3479 && OP(scan) == IFMATCH ) { /* Lookahead */
3480 cl_init(pRExC_state, &intrnl);
3481 data_fake.start_class = &intrnl;
3482 f |= SCF_DO_STCLASS_AND;
3484 if (flags & SCF_WHILEM_VISITED_POS)
3485 f |= SCF_WHILEM_VISITED_POS;
3486 next = regnext(scan);
3487 nscan = NEXTOPER(NEXTOPER(scan));
3488 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
3489 last, &data_fake, stopparen, recursed, NULL, f, depth+1);
3492 vFAIL("Variable length lookbehind not implemented");
3494 else if (minnext > (I32)U8_MAX) {
3495 vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3497 scan->flags = (U8)minnext;
3500 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3502 if (data_fake.flags & SF_HAS_EVAL)
3503 data->flags |= SF_HAS_EVAL;
3504 data->whilem_c = data_fake.whilem_c;
3506 if (f & SCF_DO_STCLASS_AND) {
3507 const int was = (data->start_class->flags & ANYOF_EOS);
3509 cl_and(data->start_class, &intrnl);
3511 data->start_class->flags |= ANYOF_EOS;
3514 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3516 /* Positive Lookahead/lookbehind
3517 In this case we can do fixed string optimisation,
3518 but we must be careful about it. Note in the case of
3519 lookbehind the positions will be offset by the minimum
3520 length of the pattern, something we won't know about
3521 until after the recurse.
3523 I32 deltanext, fake = 0;
3525 struct regnode_charclass_class intrnl;
3527 /* We use SAVEFREEPV so that when the full compile
3528 is finished perl will clean up the allocated
3529 minlens when its all done. This was we don't
3530 have to worry about freeing them when we know
3531 they wont be used, which would be a pain.
3534 Newx( minnextp, 1, I32 );
3535 SAVEFREEPV(minnextp);
3538 StructCopy(data, &data_fake, scan_data_t);
3539 if ((flags & SCF_DO_SUBSTR) && data->last_found) {
3542 scan_commit(pRExC_state, &data_fake,minlenp);
3543 data_fake.last_found=newSVsv(data->last_found);
3547 data_fake.last_closep = &fake;
3548 data_fake.flags = 0;
3550 data_fake.flags |= SF_IS_INF;
3551 if ( flags & SCF_DO_STCLASS && !scan->flags
3552 && OP(scan) == IFMATCH ) { /* Lookahead */
3553 cl_init(pRExC_state, &intrnl);
3554 data_fake.start_class = &intrnl;
3555 f |= SCF_DO_STCLASS_AND;
3557 if (flags & SCF_WHILEM_VISITED_POS)
3558 f |= SCF_WHILEM_VISITED_POS;
3559 next = regnext(scan);
3560 nscan = NEXTOPER(NEXTOPER(scan));
3562 *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext,
3563 last, &data_fake, stopparen, recursed, NULL, f,depth+1);
3566 vFAIL("Variable length lookbehind not implemented");
3568 else if (*minnextp > (I32)U8_MAX) {
3569 vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3571 scan->flags = (U8)*minnextp;
3576 if (f & SCF_DO_STCLASS_AND) {
3577 const int was = (data->start_class->flags & ANYOF_EOS);
3579 cl_and(data->start_class, &intrnl);
3581 data->start_class->flags |= ANYOF_EOS;
3584 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3586 if (data_fake.flags & SF_HAS_EVAL)
3587 data->flags |= SF_HAS_EVAL;
3588 data->whilem_c = data_fake.whilem_c;
3589 if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
3590 if (RExC_rx->minlen<*minnextp)
3591 RExC_rx->minlen=*minnextp;
3592 scan_commit(pRExC_state, &data_fake, minnextp);
3593 SvREFCNT_dec(data_fake.last_found);
3595 if ( data_fake.minlen_fixed != minlenp )
3597 data->offset_fixed= data_fake.offset_fixed;
3598 data->minlen_fixed= data_fake.minlen_fixed;
3599 data->lookbehind_fixed+= scan->flags;
3601 if ( data_fake.minlen_float != minlenp )
3603 data->minlen_float= data_fake.minlen_float;
3604 data->offset_float_min=data_fake.offset_float_min;
3605 data->offset_float_max=data_fake.offset_float_max;
3606 data->lookbehind_float+= scan->flags;
3615 else if (OP(scan) == OPEN) {
3616 if (stopparen != (I32)ARG(scan))
3619 else if (OP(scan) == CLOSE) {
3620 if (stopparen == (I32)ARG(scan)) {
3623 if ((I32)ARG(scan) == is_par) {
3624 next = regnext(scan);
3626 if ( next && (OP(next) != WHILEM) && next < last)
3627 is_par = 0; /* Disable optimization */
3630 *(data->last_closep) = ARG(scan);
3632 else if (OP(scan) == EVAL) {
3634 data->flags |= SF_HAS_EVAL;
3636 else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
3637 if (flags & SCF_DO_SUBSTR) {
3638 scan_commit(pRExC_state,data,minlenp);
3639 flags &= ~SCF_DO_SUBSTR;
3641 if (data && OP(scan)==ACCEPT) {
3642 data->flags |= SCF_SEEN_ACCEPT;
3647 else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
3649 if (flags & SCF_DO_SUBSTR) {
3650 scan_commit(pRExC_state,data,minlenp);
3651 data->longest = &(data->longest_float);
3653 is_inf = is_inf_internal = 1;
3654 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3655 cl_anything(pRExC_state, data->start_class);
3656 flags &= ~SCF_DO_STCLASS;
3658 #ifdef TRIE_STUDY_OPT
3659 #ifdef FULL_TRIE_STUDY
3660 else if (PL_regkind[OP(scan)] == TRIE) {
3661 /* NOTE - There is similar code to this block above for handling
3662 BRANCH nodes on the initial study. If you change stuff here
3664 regnode *trie_node= scan;
3665 regnode *tail= regnext(scan);
3666 reg_trie_data *trie = (reg_trie_data*)RExC_rx->data->data[ ARG(scan) ];
3667 I32 max1 = 0, min1 = I32_MAX;
3668 struct regnode_charclass_class accum;
3670 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
3671 scan_commit(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
3672 if (flags & SCF_DO_STCLASS)
3673 cl_init_zero(pRExC_state, &accum);
3679 const regnode *nextbranch= NULL;
3682 for ( word=1 ; word <= trie->wordcount ; word++)
3684 I32 deltanext=0, minnext=0, f = 0, fake;
3685 struct regnode_charclass_class this_class;
3687 data_fake.flags = 0;
3689 data_fake.whilem_c = data->whilem_c;
3690 data_fake.last_closep = data->last_closep;
3693 data_fake.last_closep = &fake;
3695 if (flags & SCF_DO_STCLASS) {
3696 cl_init(pRExC_state, &this_class);
3697 data_fake.start_class = &this_class;
3698 f = SCF_DO_STCLASS_AND;
3700 if (flags & SCF_WHILEM_VISITED_POS)
3701 f |= SCF_WHILEM_VISITED_POS;
3703 if (trie->jump[word]) {
3705 nextbranch = trie_node + trie->jump[0];
3706 scan= trie_node + trie->jump[word];
3707 /* We go from the jump point to the branch that follows
3708 it. Note this means we need the vestigal unused branches
3709 even though they arent otherwise used.
3711 minnext = study_chunk(pRExC_state, &scan, minlenp,
3712 &deltanext, (regnode *)nextbranch, &data_fake,
3713 stopparen, recursed, NULL, f,depth+1);
3715 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
3716 nextbranch= regnext((regnode*)nextbranch);
3718 if (min1 > (I32)(minnext + trie->minlen))
3719 min1 = minnext + trie->minlen;
3720 if (max1 < (I32)(minnext + deltanext + trie->maxlen))
3721 max1 = minnext + deltanext + trie->maxlen;
3722 if (deltanext == I32_MAX)
3723 is_inf = is_inf_internal = 1;
3725 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3727 if (data_fake.flags & SCF_SEEN_ACCEPT) {
3728 if ( stopmin > min + min1)
3729 stopmin = min + min1;
3730 flags &= ~SCF_DO_SUBSTR;
3732 data->flags |= SCF_SEEN_ACCEPT;
3735 if (data_fake.flags & SF_HAS_EVAL)
3736 data->flags |= SF_HAS_EVAL;
3737 data->whilem_c = data_fake.whilem_c;
3739 if (flags & SCF_DO_STCLASS)
3740 cl_or(pRExC_state, &accum, &this_class);
3743 if (flags & SCF_DO_SUBSTR) {
3744 data->pos_min += min1;
3745 data->pos_delta += max1 - min1;
3746 if (max1 != min1 || is_inf)
3747 data->longest = &(data->longest_float);
3750 delta += max1 - min1;
3751 if (flags & SCF_DO_STCLASS_OR) {
3752 cl_or(pRExC_state, data->start_class, &accum);
3754 cl_and(data->start_class, and_withp);
3755 flags &= ~SCF_DO_STCLASS;
3758 else if (flags & SCF_DO_STCLASS_AND) {
3760 cl_and(data->start_class, &accum);
3761 flags &= ~SCF_DO_STCLASS;
3764 /* Switch to OR mode: cache the old value of
3765 * data->start_class */
3767 StructCopy(data->start_class, and_withp,
3768 struct regnode_charclass_class);
3769 flags &= ~SCF_DO_STCLASS_AND;
3770 StructCopy(&accum, data->start_class,
3771 struct regnode_charclass_class);
3772 flags |= SCF_DO_STCLASS_OR;
3773 data->start_class->flags |= ANYOF_EOS;
3780 else if (PL_regkind[OP(scan)] == TRIE) {
3781 reg_trie_data *trie = (reg_trie_data*)RExC_rx->data->data[ ARG(scan) ];
3784 min += trie->minlen;
3785 delta += (trie->maxlen - trie->minlen);
3786 flags &= ~SCF_DO_STCLASS; /* xxx */
3787 if (flags & SCF_DO_SUBSTR) {
3788 scan_commit(pRExC_state,data,minlenp); /* Cannot expect anything... */
3789 data->pos_min += trie->minlen;
3790 data->pos_delta += (trie->maxlen - trie->minlen);
3791 if (trie->maxlen != trie->minlen)
3792 data->longest = &(data->longest_float);
3794 if (trie->jump) /* no more substrings -- for now /grr*/
3795 flags &= ~SCF_DO_SUBSTR;
3797 #endif /* old or new */
3798 #endif /* TRIE_STUDY_OPT */
3799 /* Else: zero-length, ignore. */
3800 scan = regnext(scan);
3805 stopparen = frame->stop;
3806 frame = frame->prev;
3807 goto fake_study_recurse;
3814 *deltap = is_inf_internal ? I32_MAX : delta;
3815 if (flags & SCF_DO_SUBSTR && is_inf)
3816 data->pos_delta = I32_MAX - data->pos_min;
3817 if (is_par > (I32)U8_MAX)
3819 if (is_par && pars==1 && data) {
3820 data->flags |= SF_IN_PAR;
3821 data->flags &= ~SF_HAS_PAR;
3823 else if (pars && data) {
3824 data->flags |= SF_HAS_PAR;
3825 data->flags &= ~SF_IN_PAR;
3827 if (flags & SCF_DO_STCLASS_OR)
3828 cl_and(data->start_class, and_withp);
3829 if (flags & SCF_TRIE_RESTUDY)
3830 data->flags |= SCF_TRIE_RESTUDY;
3832 DEBUG_STUDYDATA(data,depth);
3834 return min < stopmin ? min : stopmin;
3838 S_add_data(RExC_state_t *pRExC_state, I32 n, const char *s)
3840 if (RExC_rx->data) {
3841 const U32 count = RExC_rx->data->count;
3842 Renewc(RExC_rx->data,
3843 sizeof(*RExC_rx->data) + sizeof(void*) * (count + n - 1),
3844 char, struct reg_data);
3845 Renew(RExC_rx->data->what, count + n, U8);
3846 RExC_rx->data->count += n;
3849 Newxc(RExC_rx->data, sizeof(*RExC_rx->data) + sizeof(void*) * (n - 1),
3850 char, struct reg_data);
3851 Newx(RExC_rx->data->what, n, U8);
3852 RExC_rx->data->count = n;
3854 Copy(s, RExC_rx->data->what + RExC_rx->data->count - n, n, U8);
3855 return RExC_rx->data->count - n;
3858 #ifndef PERL_IN_XSUB_RE
3860 Perl_reginitcolors(pTHX)
3863 const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
3865 char *t = savepv(s);
3869 t = strchr(t, '\t');
3875 PL_colors[i] = t = (char *)"";
3880 PL_colors[i++] = (char *)"";
3887 #ifdef TRIE_STUDY_OPT
3888 #define CHECK_RESTUDY_GOTO \
3890 (data.flags & SCF_TRIE_RESTUDY) \
3894 #define CHECK_RESTUDY_GOTO
3898 - pregcomp - compile a regular expression into internal code
3900 * We can't allocate space until we know how big the compiled form will be,
3901 * but we can't compile it (and thus know how big it is) until we've got a
3902 * place to put the code. So we cheat: we compile it twice, once with code
3903 * generation turned off and size counting turned on, and once "for real".
3904 * This also means that we don't allocate space until we are sure that the
3905 * thing really will compile successfully, and we never have to move the
3906 * code and thus invalidate pointers into it. (Note that it has to be in
3907 * one piece because free() must be able to free it all.) [NB: not true in perl]
3909 * Beware that the optimization-preparation code in here knows about some
3910 * of the structure of the compiled regexp. [I'll say.]
3915 #ifndef PERL_IN_XSUB_RE
3916 #define RE_ENGINE_PTR &PL_core_reg_engine
3918 extern const struct regexp_engine my_reg_engine;
3919 #define RE_ENGINE_PTR &my_reg_engine
3921 /* these make a few things look better, to avoid indentation */
3922 #define BEGIN_BLOCK {
3926 Perl_pregcomp(pTHX_ char *exp, char *xend, PMOP *pm)
3929 GET_RE_DEBUG_FLAGS_DECL;
3930 DEBUG_r(if (!PL_colorset) reginitcolors());
3931 #ifndef PERL_IN_XSUB_RE
3933 /* Dispatch a request to compile a regexp to correct
3935 HV * const table = GvHV(PL_hintgv);
3937 SV **ptr= hv_fetchs(table, "regcomp", FALSE);
3938 if (ptr && SvIOK(*ptr) && SvIV(*ptr)) {
3939 const regexp_engine *eng=INT2PTR(regexp_engine*,SvIV(*ptr));
3941 PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
3944 return CALLREGCOMP_ENG(eng, exp, xend, pm);
3958 RExC_state_t RExC_state;
3959 RExC_state_t * const pRExC_state = &RExC_state;
3960 #ifdef TRIE_STUDY_OPT
3962 RExC_state_t copyRExC_state;
3965 FAIL("NULL regexp argument");
3967 RExC_utf8 = pm->op_pmdynflags & PMdf_CMP_UTF8;
3971 SV *dsv= sv_newmortal();
3972 RE_PV_QUOTED_DECL(s, RExC_utf8,
3973 dsv, RExC_precomp, (xend - exp), 60);
3974 PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
3975 PL_colors[4],PL_colors[5],s);
3977 RExC_flags = pm->op_pmflags;
3981 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
3982 RExC_seen_evals = 0;
3985 /* First pass: determine size, legality. */
3994 RExC_emit = &PL_regdummy;
3995 RExC_whilem_seen = 0;
3996 RExC_charnames = NULL;
3997 RExC_open_parens = NULL;
3998 RExC_close_parens = NULL;
4000 RExC_paren_names = NULL;
4001 RExC_recurse = NULL;
4002 RExC_recurse_count = 0;
4004 #if 0 /* REGC() is (currently) a NOP at the first pass.
4005 * Clever compilers notice this and complain. --jhi */
4006 REGC((U8)REG_MAGIC, (char*)RExC_emit);
4008 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n"));
4009 if (reg(pRExC_state, 0, &flags,1) == NULL) {
4010 RExC_precomp = NULL;
4014 PerlIO_printf(Perl_debug_log,
4015 "Required size %"IVdf" nodes\n"
4016 "Starting second pass (creation)\n",
4019 RExC_lastparse=NULL;
4021 /* Small enough for pointer-storage convention?
4022 If extralen==0, this means that we will not need long jumps. */
4023 if (RExC_size >= 0x10000L && RExC_extralen)
4024 RExC_size += RExC_extralen;
4027 if (RExC_whilem_seen > 15)
4028 RExC_whilem_seen = 15;
4031 /* Make room for a sentinel value at the end of the program */
4035 /* Allocate space and zero-initialize. Note, the two step process
4036 of zeroing when in debug mode, thus anything assigned has to
4037 happen after that */
4038 Newxc(r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode),
4041 FAIL("Regexp out of space");
4043 /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
4044 Zero(r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode), char);
4046 /* initialization begins here */
4047 r->engine= RE_ENGINE_PTR;
4049 r->prelen = xend - exp;
4050 r->precomp = savepvn(RExC_precomp, r->prelen);
4052 #ifdef PERL_OLD_COPY_ON_WRITE
4053 r->saved_copy = NULL;
4055 r->reganch = pm->op_pmflags & PMf_COMPILETIME;
4056 r->nparens = RExC_npar - 1; /* set early to validate backrefs */
4057 r->lastparen = 0; /* mg.c reads this. */
4059 r->substrs = 0; /* Useful during FAIL. */
4060 r->startp = 0; /* Useful during FAIL. */
4065 if (RExC_seen & REG_SEEN_RECURSE) {
4066 Newxz(RExC_open_parens, RExC_npar,regnode *);
4067 SAVEFREEPV(RExC_open_parens);
4068 Newxz(RExC_close_parens,RExC_npar,regnode *);
4069 SAVEFREEPV(RExC_close_parens);
4072 /* Useful during FAIL. */
4073 Newxz(r->offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
4075 r->offsets[0] = RExC_size;
4077 DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
4078 "%s %"UVuf" bytes for offset annotations.\n",
4079 r->offsets ? "Got" : "Couldn't get",
4080 (UV)((2*RExC_size+1) * sizeof(U32))));
4084 /* Second pass: emit code. */
4085 RExC_flags = pm->op_pmflags; /* don't let top level (?i) bleed */
4091 RExC_emit_start = r->program;
4092 RExC_emit = r->program;
4094 /* put a sentinal on the end of the program so we can check for
4096 r->program[RExC_size].type = 255;
4098 /* Store the count of eval-groups for security checks: */
4099 RExC_emit->next_off = (RExC_seen_evals > (I32)U16_MAX) ? U16_MAX : (U16)RExC_seen_evals;
4100 REGC((U8)REG_MAGIC, (char*) RExC_emit++);
4102 if (reg(pRExC_state, 0, &flags,1) == NULL)
4105 /* XXXX To minimize changes to RE engine we always allocate
4106 3-units-long substrs field. */
4107 Newx(r->substrs, 1, struct reg_substr_data);
4108 if (RExC_recurse_count) {
4109 Newxz(RExC_recurse,RExC_recurse_count,regnode *);
4110 SAVEFREEPV(RExC_recurse);
4114 r->minlen = minlen = sawplus = sawopen = 0;
4115 Zero(r->substrs, 1, struct reg_substr_data);
4117 #ifdef TRIE_STUDY_OPT
4120 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
4122 RExC_state = copyRExC_state;
4123 if (seen & REG_TOP_LEVEL_BRANCHES)
4124 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
4126 RExC_seen &= ~REG_TOP_LEVEL_BRANCHES;
4127 if (data.last_found) {
4128 SvREFCNT_dec(data.longest_fixed);
4129 SvREFCNT_dec(data.longest_float);
4130 SvREFCNT_dec(data.last_found);
4132 StructCopy(&zero_scan_data, &data, scan_data_t);
4134 StructCopy(&zero_scan_data, &data, scan_data_t);
4135 copyRExC_state = RExC_state;
4138 StructCopy(&zero_scan_data, &data, scan_data_t);
4141 /* Dig out information for optimizations. */
4142 r->reganch = pm->op_pmflags & PMf_COMPILETIME; /* Again? */
4143 pm->op_pmflags = RExC_flags;
4145 r->reganch |= ROPT_UTF8; /* Unicode in it? */
4146 r->regstclass = NULL;
4147 if (RExC_naughty >= 10) /* Probably an expensive pattern. */
4148 r->reganch |= ROPT_NAUGHTY;
4149 scan = r->program + 1; /* First BRANCH. */
4151 /* testing for BRANCH here tells us whether there is "must appear"
4152 data in the pattern. If there is then we can use it for optimisations */
4153 if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES)) { /* Only one top-level choice. */
4155 STRLEN longest_float_length, longest_fixed_length;
4156 struct regnode_charclass_class ch_class; /* pointed to by data */
4158 I32 last_close = 0; /* pointed to by data */
4161 /* Skip introductions and multiplicators >= 1. */
4162 while ((OP(first) == OPEN && (sawopen = 1)) ||
4163 /* An OR of *one* alternative - should not happen now. */
4164 (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
4165 /* for now we can't handle lookbehind IFMATCH*/
4166 (OP(first) == IFMATCH && !first->flags) ||
4167 (OP(first) == PLUS) ||
4168 (OP(first) == MINMOD) ||
4169 /* An {n,m} with n>0 */
4170 (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) )
4173 if (OP(first) == PLUS)
4176 first += regarglen[OP(first)];
4177 if (OP(first) == IFMATCH) {
4178 first = NEXTOPER(first);
4179 first += EXTRA_STEP_2ARGS;
4180 } else /* XXX possible optimisation for /(?=)/ */
4181 first = NEXTOPER(first);
4184 /* Starting-point info. */
4186 DEBUG_PEEP("first:",first,0);
4187 /* Ignore EXACT as we deal with it later. */
4188 if (PL_regkind[OP(first)] == EXACT) {
4189 if (OP(first) == EXACT)
4190 NOOP; /* Empty, get anchored substr later. */
4191 else if ((OP(first) == EXACTF || OP(first) == EXACTFL))
4192 r->regstclass = first;
4195 else if (PL_regkind[OP(first)] == TRIE &&
4196 ((reg_trie_data *)r->data->data[ ARG(first) ])->minlen>0)
4199 /* this can happen only on restudy */
4200 if ( OP(first) == TRIE ) {
4201 struct regnode_1 *trieop;
4202 Newxz(trieop,1,struct regnode_1);
4203 StructCopy(first,trieop,struct regnode_1);
4204 trie_op=(regnode *)trieop;
4206 struct regnode_charclass *trieop;
4207 Newxz(trieop,1,struct regnode_charclass);
4208 StructCopy(first,trieop,struct regnode_charclass);
4209 trie_op=(regnode *)trieop;
4212 make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
4213 r->regstclass = trie_op;
4216 else if (strchr((const char*)PL_simple,OP(first)))
4217 r->regstclass = first;
4218 else if (PL_regkind[OP(first)] == BOUND ||
4219 PL_regkind[OP(first)] == NBOUND)
4220 r->regstclass = first;
4221 else if (PL_regkind[OP(first)] == BOL) {
4222 r->reganch |= (OP(first) == MBOL
4224 : (OP(first) == SBOL
4227 first = NEXTOPER(first);
4230 else if (OP(first) == GPOS) {
4231 r->reganch |= ROPT_ANCH_GPOS;
4232 first = NEXTOPER(first);
4235 else if ((!sawopen || !RExC_sawback) &&
4236 (OP(first) == STAR &&
4237 PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
4238 !(r->reganch & ROPT_ANCH) )
4240 /* turn .* into ^.* with an implied $*=1 */
4242 (OP(NEXTOPER(first)) == REG_ANY)
4245 r->reganch |= type | ROPT_IMPLICIT;
4246 first = NEXTOPER(first);
4249 if (sawplus && (!sawopen || !RExC_sawback)
4250 && !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
4251 /* x+ must match at the 1st pos of run of x's */
4252 r->reganch |= ROPT_SKIP;
4254 /* Scan is after the zeroth branch, first is atomic matcher. */
4255 #ifdef TRIE_STUDY_OPT
4258 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4259 (IV)(first - scan + 1))
4263 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4264 (IV)(first - scan + 1))
4270 * If there's something expensive in the r.e., find the
4271 * longest literal string that must appear and make it the
4272 * regmust. Resolve ties in favor of later strings, since
4273 * the regstart check works with the beginning of the r.e.
4274 * and avoiding duplication strengthens checking. Not a
4275 * strong reason, but sufficient in the absence of others.
4276 * [Now we resolve ties in favor of the earlier string if
4277 * it happens that c_offset_min has been invalidated, since the
4278 * earlier string may buy us something the later one won't.]
4281 data.longest_fixed = newSVpvs("");
4282 data.longest_float = newSVpvs("");
4283 data.last_found = newSVpvs("");
4284 data.longest = &(data.longest_fixed);
4286 if (!r->regstclass) {
4287 cl_init(pRExC_state, &ch_class);
4288 data.start_class = &ch_class;
4289 stclass_flag = SCF_DO_STCLASS_AND;
4290 } else /* XXXX Check for BOUND? */
4292 data.last_closep = &last_close;
4294 minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
4295 &data, -1, NULL, NULL,
4296 SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag,0);
4302 if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
4303 && data.last_start_min == 0 && data.last_end > 0
4304 && !RExC_seen_zerolen
4305 && (!(RExC_seen & REG_SEEN_GPOS) || (r->reganch & ROPT_ANCH_GPOS)))
4306 r->reganch |= ROPT_CHECK_ALL;
4307 scan_commit(pRExC_state, &data,&minlen);
4308 SvREFCNT_dec(data.last_found);
4310 /* Note that code very similar to this but for anchored string
4311 follows immediately below, changes may need to be made to both.
4314 longest_float_length = CHR_SVLEN(data.longest_float);
4315 if (longest_float_length
4316 || (data.flags & SF_FL_BEFORE_EOL
4317 && (!(data.flags & SF_FL_BEFORE_MEOL)
4318 || (RExC_flags & PMf_MULTILINE))))
4322 if (SvCUR(data.longest_fixed) /* ok to leave SvCUR */
4323 && data.offset_fixed == data.offset_float_min
4324 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
4325 goto remove_float; /* As in (a)+. */
4327 /* copy the information about the longest float from the reg_scan_data
4328 over to the program. */
4329 if (SvUTF8(data.longest_float)) {
4330 r->float_utf8 = data.longest_float;
4331 r->float_substr = NULL;
4333 r->float_substr = data.longest_float;
4334 r->float_utf8 = NULL;
4336 /* float_end_shift is how many chars that must be matched that
4337 follow this item. We calculate it ahead of time as once the
4338 lookbehind offset is added in we lose the ability to correctly
4340 ml = data.minlen_float ? *(data.minlen_float)
4341 : (I32)longest_float_length;
4342 r->float_end_shift = ml - data.offset_float_min
4343 - longest_float_length + (SvTAIL(data.longest_float) != 0)
4344 + data.lookbehind_float;
4345 r->float_min_offset = data.offset_float_min - data.lookbehind_float;
4346 r->float_max_offset = data.offset_float_max;
4347 if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
4348 r->float_max_offset -= data.lookbehind_float;
4350 t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
4351 && (!(data.flags & SF_FL_BEFORE_MEOL)
4352 || (RExC_flags & PMf_MULTILINE)));
4353 fbm_compile(data.longest_float, t ? FBMcf_TAIL : 0);
4357 r->float_substr = r->float_utf8 = NULL;
4358 SvREFCNT_dec(data.longest_float);
4359 longest_float_length = 0;
4362 /* Note that code very similar to this but for floating string
4363 is immediately above, changes may need to be made to both.
4366 longest_fixed_length = CHR_SVLEN(data.longest_fixed);
4367 if (longest_fixed_length
4368 || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
4369 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4370 || (RExC_flags & PMf_MULTILINE))))
4374 /* copy the information about the longest fixed
4375 from the reg_scan_data over to the program. */
4376 if (SvUTF8(data.longest_fixed)) {
4377 r->anchored_utf8 = data.longest_fixed;
4378 r->anchored_substr = NULL;
4380 r->anchored_substr = data.longest_fixed;
4381 r->anchored_utf8 = NULL;
4383 /* fixed_end_shift is how many chars that must be matched that
4384 follow this item. We calculate it ahead of time as once the
4385 lookbehind offset is added in we lose the ability to correctly
4387 ml = data.minlen_fixed ? *(data.minlen_fixed)
4388 : (I32)longest_fixed_length;
4389 r->anchored_end_shift = ml - data.offset_fixed
4390 - longest_fixed_length + (SvTAIL(data.longest_fixed) != 0)
4391 + data.lookbehind_fixed;
4392 r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
4394 t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
4395 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4396 || (RExC_flags & PMf_MULTILINE)));
4397 fbm_compile(data.longest_fixed, t ? FBMcf_TAIL : 0);
4400 r->anchored_substr = r->anchored_utf8 = NULL;
4401 SvREFCNT_dec(data.longest_fixed);
4402 longest_fixed_length = 0;
4405 && (OP(r->regstclass) == REG_ANY || OP(r->regstclass) == SANY))
4406 r->regstclass = NULL;
4407 if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
4409 && !(data.start_class->flags & ANYOF_EOS)
4410 && !cl_is_anything(data.start_class))
4412 const I32 n = add_data(pRExC_state, 1, "f");
4414 Newx(RExC_rx->data->data[n], 1,
4415 struct regnode_charclass_class);
4416 StructCopy(data.start_class,
4417 (struct regnode_charclass_class*)RExC_rx->data->data[n],
4418 struct regnode_charclass_class);
4419 r->regstclass = (regnode*)RExC_rx->data->data[n];
4420 r->reganch &= ~ROPT_SKIP; /* Used in find_byclass(). */
4421 DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
4422 regprop(r, sv, (regnode*)data.start_class);
4423 PerlIO_printf(Perl_debug_log,
4424 "synthetic stclass \"%s\".\n",
4425 SvPVX_const(sv));});
4428 /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
4429 if (longest_fixed_length > longest_float_length) {
4430 r->check_end_shift = r->anchored_end_shift;
4431 r->check_substr = r->anchored_substr;
4432 r->check_utf8 = r->anchored_utf8;
4433 r->check_offset_min = r->check_offset_max = r->anchored_offset;
4434 if (r->reganch & ROPT_ANCH_SINGLE)
4435 r->reganch |= ROPT_NOSCAN;
4438 r->check_end_shift = r->float_end_shift;
4439 r->check_substr = r->float_substr;
4440 r->check_utf8 = r->float_utf8;
4441 r->check_offset_min = r->float_min_offset;
4442 r->check_offset_max = r->float_max_offset;
4444 /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
4445 This should be changed ASAP! */
4446 if ((r->check_substr || r->check_utf8) && !(r->reganch & ROPT_ANCH_GPOS)) {
4447 r->reganch |= RE_USE_INTUIT;
4448 if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
4449 r->reganch |= RE_INTUIT_TAIL;
4451 /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
4452 if ( (STRLEN)minlen < longest_float_length )
4453 minlen= longest_float_length;
4454 if ( (STRLEN)minlen < longest_fixed_length )
4455 minlen= longest_fixed_length;
4459 /* Several toplevels. Best we can is to set minlen. */
4461 struct regnode_charclass_class ch_class;
4464 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "\nMulti Top Level\n"));
4466 scan = r->program + 1;
4467 cl_init(pRExC_state, &ch_class);
4468 data.start_class = &ch_class;
4469 data.last_closep = &last_close;
4472 minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
4473 &data, -1, NULL, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS,0);
4477 r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
4478 = r->float_substr = r->float_utf8 = NULL;
4479 if (!(data.start_class->flags & ANYOF_EOS)
4480 && !cl_is_anything(data.start_class))
4482 const I32 n = add_data(pRExC_state, 1, "f");
4484 Newx(RExC_rx->data->data[n], 1,
4485 struct regnode_charclass_class);
4486 StructCopy(data.start_class,
4487 (struct regnode_charclass_class*)RExC_rx->data->data[n],
4488 struct regnode_charclass_class);
4489 r->regstclass = (regnode*)RExC_rx->data->data[n];
4490 r->reganch &= ~ROPT_SKIP; /* Used in find_byclass(). */
4491 DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
4492 regprop(r, sv, (regnode*)data.start_class);
4493 PerlIO_printf(Perl_debug_log,
4494 "synthetic stclass \"%s\".\n",
4495 SvPVX_const(sv));});
4499 /* Guard against an embedded (?=) or (?<=) with a longer minlen than
4500 the "real" pattern. */
4502 PerlIO_printf(Perl_debug_log,"minlen: %"IVdf" r->minlen:%"IVdf"\n",
4505 r->minlenret = minlen;
4506 if (r->minlen < minlen)
4509 if (RExC_seen & REG_SEEN_GPOS)
4510 r->reganch |= ROPT_GPOS_SEEN;
4511 if (RExC_seen & REG_SEEN_LOOKBEHIND)
4512 r->reganch |= ROPT_LOOKBEHIND_SEEN;
4513 if (RExC_seen & REG_SEEN_EVAL)
4514 r->reganch |= ROPT_EVAL_SEEN;
4515 if (RExC_seen & REG_SEEN_CANY)
4516 r->reganch |= ROPT_CANY_SEEN;
4517 if (RExC_seen & REG_SEEN_VERBARG)
4518 r->reganch |= ROPT_VERBARG_SEEN;
4519 if (RExC_seen & REG_SEEN_CUTGROUP)
4520 r->reganch |= ROPT_CUTGROUP_SEEN;
4521 if (RExC_paren_names)
4522 r->paren_names = (HV*)SvREFCNT_inc(RExC_paren_names);
4524 r->paren_names = NULL;
4526 if (RExC_recurse_count) {
4527 for ( ; RExC_recurse_count ; RExC_recurse_count-- ) {
4528 const regnode *scan = RExC_recurse[RExC_recurse_count-1];
4529 ARG2L_SET( scan, RExC_open_parens[ARG(scan)-1] - scan );
4532 Newxz(r->startp, RExC_npar, I32);
4533 Newxz(r->endp, RExC_npar, I32);
4534 /* assume we don't need to swap parens around before we match */
4537 PerlIO_printf(Perl_debug_log,"Final program:\n");
4540 DEBUG_OFFSETS_r(if (r->offsets) {
4541 const U32 len = r->offsets[0];
4543 GET_RE_DEBUG_FLAGS_DECL;
4544 PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)r->offsets[0]);
4545 for (i = 1; i <= len; i++) {
4546 if (r->offsets[i*2-1] || r->offsets[i*2])
4547 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
4548 (UV)i, (UV)r->offsets[i*2-1], (UV)r->offsets[i*2]);
4550 PerlIO_printf(Perl_debug_log, "\n");
4556 #undef CORE_ONLY_BLOCK
4558 #undef RE_ENGINE_PTR
4560 #ifndef PERL_IN_XSUB_RE
4562 Perl_reg_named_buff_sv(pTHX_ SV* namesv)
4564 I32 parno = 0; /* no match */
4566 const REGEXP * const rx = PM_GETRE(PL_curpm);
4567 if (rx && rx->paren_names) {
4568 HE *he_str = hv_fetch_ent( rx->paren_names, namesv, 0, 0 );
4571 SV* sv_dat=HeVAL(he_str);
4572 I32 *nums=(I32*)SvPVX(sv_dat);
4573 for ( i=0; i<SvIVX(sv_dat); i++ ) {
4574 if ((I32)(rx->lastparen) >= nums[i] &&
4575 rx->endp[nums[i]] != -1)
4588 SV *sv= sv_newmortal();
4589 Perl_sv_setpvf(aTHX_ sv, "%"IVdf,(IV)parno);
4590 gv_paren= Perl_gv_fetchsv(aTHX_ sv, GV_ADD, SVt_PVGV);
4591 return GvSVn(gv_paren);
4596 /* Scans the name of a named buffer from the pattern.
4597 * If flags is REG_RSN_RETURN_NULL returns null.
4598 * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
4599 * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
4600 * to the parsed name as looked up in the RExC_paren_names hash.
4601 * If there is an error throws a vFAIL().. type exception.
4604 #define REG_RSN_RETURN_NULL 0
4605 #define REG_RSN_RETURN_NAME 1
4606 #define REG_RSN_RETURN_DATA 2
4609 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags) {
4610 char *name_start = RExC_parse;
4613 while( isIDFIRST_uni(utf8n_to_uvchr((U8*)RExC_parse,
4614 RExC_end - RExC_parse, &numlen, UTF8_ALLOW_DEFAULT)))
4616 RExC_parse += numlen;
4619 while( isIDFIRST(*RExC_parse) )
4623 SV* sv_name = sv_2mortal(Perl_newSVpvn(aTHX_ name_start,
4624 (int)(RExC_parse - name_start)));
4627 if ( flags == REG_RSN_RETURN_NAME)
4629 else if (flags==REG_RSN_RETURN_DATA) {
4632 if ( ! sv_name ) /* should not happen*/
4633 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
4634 if (RExC_paren_names)
4635 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
4637 sv_dat = HeVAL(he_str);
4639 vFAIL("Reference to nonexistent named group");
4643 Perl_croak(aTHX_ "panic: bad flag in reg_scan_name");
4650 #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
4651 int rem=(int)(RExC_end - RExC_parse); \
4660 if (RExC_lastparse!=RExC_parse) \
4661 PerlIO_printf(Perl_debug_log," >%.*s%-*s", \
4664 iscut ? "..." : "<" \
4667 PerlIO_printf(Perl_debug_log,"%16s",""); \
4672 num=REG_NODE_NUM(RExC_emit); \
4673 if (RExC_lastnum!=num) \
4674 PerlIO_printf(Perl_debug_log,"|%4d",num); \
4676 PerlIO_printf(Perl_debug_log,"|%4s",""); \
4677 PerlIO_printf(Perl_debug_log,"|%*s%-4s", \
4678 (int)((depth*2)), "", \
4682 RExC_lastparse=RExC_parse; \
4687 #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
4688 DEBUG_PARSE_MSG((funcname)); \
4689 PerlIO_printf(Perl_debug_log,"%4s","\n"); \
4691 #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({ \
4692 DEBUG_PARSE_MSG((funcname)); \
4693 PerlIO_printf(Perl_debug_log,fmt "\n",args); \
4696 - reg - regular expression, i.e. main body or parenthesized thing
4698 * Caller must absorb opening parenthesis.
4700 * Combining parenthesis handling with the base level of regular expression
4701 * is a trifle forced, but the need to tie the tails of the branches to what
4702 * follows makes it hard to avoid.
4704 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
4706 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
4708 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
4711 /* this idea is borrowed from STR_WITH_LEN in handy.h */
4712 #define CHECK_WORD(s,v,l) \
4713 (((sizeof(s)-1)==(l)) && (strnEQ(start_verb, (s ""), (sizeof(s)-1))))
4716 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
4717 /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
4720 register regnode *ret; /* Will be the head of the group. */
4721 register regnode *br;
4722 register regnode *lastbr;
4723 register regnode *ender = NULL;
4724 register I32 parno = 0;
4726 const I32 oregflags = RExC_flags;
4727 bool have_branch = 0;
4730 /* for (?g), (?gc), and (?o) warnings; warning
4731 about (?c) will warn about (?g) -- japhy */
4733 #define WASTED_O 0x01
4734 #define WASTED_G 0x02
4735 #define WASTED_C 0x04
4736 #define WASTED_GC (0x02|0x04)
4737 I32 wastedflags = 0x00;
4739 char * parse_start = RExC_parse; /* MJD */
4740 char * const oregcomp_parse = RExC_parse;
4742 GET_RE_DEBUG_FLAGS_DECL;
4743 DEBUG_PARSE("reg ");
4746 *flagp = 0; /* Tentatively. */
4749 /* Make an OPEN node, if parenthesized. */
4751 if ( *RExC_parse == '*') { /* (*VERB:ARG) */
4752 char *start_verb = RExC_parse;
4753 STRLEN verb_len = 0;
4754 char *start_arg = NULL;
4755 unsigned char op = 0;
4757 int internal_argval = 0; /* internal_argval is only useful if !argok */
4758 while ( *RExC_parse && *RExC_parse != ')' ) {
4759 if ( *RExC_parse == ':' ) {
4760 start_arg = RExC_parse + 1;
4766 verb_len = RExC_parse - start_verb;
4769 while ( *RExC_parse && *RExC_parse != ')' )
4771 if ( *RExC_parse != ')' )
4772 vFAIL("Unterminated verb pattern argument");
4773 if ( RExC_parse == start_arg )
4776 if ( *RExC_parse != ')' )
4777 vFAIL("Unterminated verb pattern");
4780 switch ( *start_verb ) {
4781 case 'A': /* (*ACCEPT) */
4782 if ( CHECK_WORD("ACCEPT",start_verb,verb_len) ) {
4784 internal_argval = RExC_nestroot;
4787 case 'C': /* (*COMMIT) */
4788 if ( CHECK_WORD("COMMIT",start_verb,verb_len) )
4791 case 'F': /* (*FAIL) */
4792 if ( verb_len==1 || CHECK_WORD("FAIL",start_verb,verb_len) ) {
4797 case ':': /* (*:NAME) */
4798 case 'M': /* (*MARK:NAME) */
4799 if ( verb_len==0 || CHECK_WORD("MARK",start_verb,verb_len) ) {
4804 case 'P': /* (*PRUNE) */
4805 if ( CHECK_WORD("PRUNE",start_verb,verb_len) )
4808 case 'S': /* (*SKIP) */
4809 if ( CHECK_WORD("SKIP",start_verb,verb_len) )
4812 case 'T': /* (*THEN) */
4813 /* [19:06] <TimToady> :: is then */
4814 if ( CHECK_WORD("THEN",start_verb,verb_len) ) {
4816 RExC_seen |= REG_SEEN_CUTGROUP;
4822 vFAIL3("Unknown verb pattern '%.*s'",
4823 verb_len, start_verb);
4826 if ( start_arg && internal_argval ) {
4827 vFAIL3("Verb pattern '%.*s' may not have an argument",
4828 verb_len, start_verb);
4829 } else if ( argok < 0 && !start_arg ) {
4830 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
4831 verb_len, start_verb);
4833 ret = reganode(pRExC_state, op, internal_argval);
4834 if ( ! internal_argval && ! SIZE_ONLY ) {
4836 SV *sv = newSVpvn( start_arg, RExC_parse - start_arg);
4837 ARG(ret) = add_data( pRExC_state, 1, "S" );
4838 RExC_rx->data->data[ARG(ret)]=(void*)sv;
4845 if (!internal_argval)
4846 RExC_seen |= REG_SEEN_VERBARG;
4847 } else if ( start_arg ) {
4848 vFAIL3("Verb pattern '%.*s' may not have an argument",
4849 verb_len, start_verb);
4851 ret = reg_node(pRExC_state, op);
4853 nextchar(pRExC_state);
4856 if (*RExC_parse == '?') { /* (?...) */
4857 U32 posflags = 0, negflags = 0;
4858 U32 *flagsp = &posflags;
4859 bool is_logical = 0;
4860 const char * const seqstart = RExC_parse;
4863 paren = *RExC_parse++;
4864 ret = NULL; /* For look-ahead/behind. */
4867 case '<': /* (?<...) */
4868 if (*RExC_parse == '!')
4870 else if (*RExC_parse != '=')
4875 case '\'': /* (?'...') */
4876 name_start= RExC_parse;
4877 svname = reg_scan_name(pRExC_state,
4878 SIZE_ONLY ? /* reverse test from the others */
4879 REG_RSN_RETURN_NAME :
4880 REG_RSN_RETURN_NULL);
4881 if (RExC_parse == name_start)
4883 if (*RExC_parse != paren)
4884 vFAIL2("Sequence (?%c... not terminated",
4885 paren=='>' ? '<' : paren);
4889 if (!svname) /* shouldnt happen */
4891 "panic: reg_scan_name returned NULL");
4892 if (!RExC_paren_names) {
4893 RExC_paren_names= newHV();
4894 sv_2mortal((SV*)RExC_paren_names);
4896 he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
4898 sv_dat = HeVAL(he_str);
4900 /* croak baby croak */
4902 "panic: paren_name hash element allocation failed");
4903 } else if ( SvPOK(sv_dat) ) {
4904 IV count=SvIV(sv_dat);
4905 I32 *pv=(I32*)SvGROW(sv_dat,SvCUR(sv_dat)+sizeof(I32)+1);
4906 SvCUR_set(sv_dat,SvCUR(sv_dat)+sizeof(I32));
4907 pv[count]=RExC_npar;
4910 (void)SvUPGRADE(sv_dat,SVt_PVNV);
4911 sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32));
4916 /*sv_dump(sv_dat);*/
4918 nextchar(pRExC_state);
4920 goto capturing_parens;
4922 RExC_seen |= REG_SEEN_LOOKBEHIND;
4924 case '=': /* (?=...) */
4925 case '!': /* (?!...) */
4926 RExC_seen_zerolen++;
4927 if (*RExC_parse == ')') {
4928 ret=reg_node(pRExC_state, OPFAIL);
4929 nextchar(pRExC_state);
4932 case ':': /* (?:...) */
4933 case '>': /* (?>...) */
4935 case '$': /* (?$...) */
4936 case '@': /* (?@...) */
4937 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
4939 case '#': /* (?#...) */
4940 while (*RExC_parse && *RExC_parse != ')')
4942 if (*RExC_parse != ')')
4943 FAIL("Sequence (?#... not terminated");
4944 nextchar(pRExC_state);
4947 case '0' : /* (?0) */
4948 case 'R' : /* (?R) */
4949 if (*RExC_parse != ')')
4950 FAIL("Sequence (?R) not terminated");
4951 ret = reg_node(pRExC_state, GOSTART);
4952 nextchar(pRExC_state);
4955 { /* named and numeric backreferences */
4958 case '&': /* (?&NAME) */
4959 parse_start = RExC_parse - 1;
4961 SV *sv_dat = reg_scan_name(pRExC_state,
4962 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
4963 num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
4965 goto gen_recurse_regop;
4968 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
4970 vFAIL("Illegal pattern");
4972 goto parse_recursion;
4974 case '-': /* (?-1) */
4975 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
4976 RExC_parse--; /* rewind to let it be handled later */
4980 case '1': case '2': case '3': case '4': /* (?1) */
4981 case '5': case '6': case '7': case '8': case '9':
4984 num = atoi(RExC_parse);
4985 parse_start = RExC_parse - 1; /* MJD */
4986 if (*RExC_parse == '-')
4988 while (isDIGIT(*RExC_parse))
4990 if (*RExC_parse!=')')
4991 vFAIL("Expecting close bracket");
4994 if ( paren == '-' ) {
4996 Diagram of capture buffer numbering.
4997 Top line is the normal capture buffer numbers
4998 Botton line is the negative indexing as from
5002 /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
5006 num = RExC_npar + num;
5009 vFAIL("Reference to nonexistent group");
5011 } else if ( paren == '+' ) {
5012 num = RExC_npar + num - 1;
5015 ret = reganode(pRExC_state, GOSUB, num);
5017 if (num > (I32)RExC_rx->nparens) {
5019 vFAIL("Reference to nonexistent group");
5021 ARG2L_SET( ret, RExC_recurse_count++);
5023 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5024 "Recurse #%"UVuf" to %"IVdf"\n", (UV)ARG(ret), (IV)ARG2L(ret)));
5028 RExC_seen |= REG_SEEN_RECURSE;
5029 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
5030 Set_Node_Offset(ret, parse_start); /* MJD */
5032 nextchar(pRExC_state);
5034 } /* named and numeric backreferences */
5037 case 'p': /* (?p...) */
5038 if (SIZE_ONLY && ckWARN2(WARN_DEPRECATED, WARN_REGEXP))
5039 vWARNdep(RExC_parse, "(?p{}) is deprecated - use (??{})");
5041 case '?': /* (??...) */
5043 if (*RExC_parse != '{')
5045 paren = *RExC_parse++;
5047 case '{': /* (?{...}) */
5049 I32 count = 1, n = 0;
5051 char *s = RExC_parse;
5053 RExC_seen_zerolen++;
5054 RExC_seen |= REG_SEEN_EVAL;
5055 while (count && (c = *RExC_parse)) {
5066 if (*RExC_parse != ')') {
5068 vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
5072 OP_4tree *sop, *rop;
5073 SV * const sv = newSVpvn(s, RExC_parse - 1 - s);
5076 Perl_save_re_context(aTHX);
5077 rop = sv_compile_2op(sv, &sop, "re", &pad);
5078 sop->op_private |= OPpREFCOUNTED;
5079 /* re_dup will OpREFCNT_inc */
5080 OpREFCNT_set(sop, 1);
5083 n = add_data(pRExC_state, 3, "nop");
5084 RExC_rx->data->data[n] = (void*)rop;
5085 RExC_rx->data->data[n+1] = (void*)sop;
5086 RExC_rx->data->data[n+2] = (void*)pad;
5089 else { /* First pass */
5090 if (PL_reginterp_cnt < ++RExC_seen_evals
5092 /* No compiled RE interpolated, has runtime
5093 components ===> unsafe. */
5094 FAIL("Eval-group not allowed at runtime, use re 'eval'");
5095 if (PL_tainting && PL_tainted)
5096 FAIL("Eval-group in insecure regular expression");
5097 #if PERL_VERSION > 8
5098 if (IN_PERL_COMPILETIME)
5103 nextchar(pRExC_state);
5105 ret = reg_node(pRExC_state, LOGICAL);
5108 REGTAIL(pRExC_state, ret, reganode(pRExC_state, EVAL, n));
5109 /* deal with the length of this later - MJD */
5112 ret = reganode(pRExC_state, EVAL, n);
5113 Set_Node_Length(ret, RExC_parse - parse_start + 1);
5114 Set_Node_Offset(ret, parse_start);
5117 case '(': /* (?(?{...})...) and (?(?=...)...) */
5120 if (RExC_parse[0] == '?') { /* (?(?...)) */
5121 if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
5122 || RExC_parse[1] == '<'
5123 || RExC_parse[1] == '{') { /* Lookahead or eval. */
5126 ret = reg_node(pRExC_state, LOGICAL);
5129 REGTAIL(pRExC_state, ret, reg(pRExC_state, 1, &flag,depth+1));
5133 else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
5134 || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
5136 char ch = RExC_parse[0] == '<' ? '>' : '\'';
5137 char *name_start= RExC_parse++;
5139 SV *sv_dat=reg_scan_name(pRExC_state,
5140 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5141 if (RExC_parse == name_start || *RExC_parse != ch)
5142 vFAIL2("Sequence (?(%c... not terminated",
5143 (ch == '>' ? '<' : ch));
5146 num = add_data( pRExC_state, 1, "S" );
5147 RExC_rx->data->data[num]=(void*)sv_dat;
5148 SvREFCNT_inc(sv_dat);
5150 ret = reganode(pRExC_state,NGROUPP,num);
5151 goto insert_if_check_paren;
5153 else if (RExC_parse[0] == 'D' &&
5154 RExC_parse[1] == 'E' &&
5155 RExC_parse[2] == 'F' &&
5156 RExC_parse[3] == 'I' &&
5157 RExC_parse[4] == 'N' &&
5158 RExC_parse[5] == 'E')
5160 ret = reganode(pRExC_state,DEFINEP,0);
5163 goto insert_if_check_paren;
5165 else if (RExC_parse[0] == 'R') {
5168 if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
5169 parno = atoi(RExC_parse++);
5170 while (isDIGIT(*RExC_parse))
5172 } else if (RExC_parse[0] == '&') {
5175 sv_dat = reg_scan_name(pRExC_state,
5176 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5177 parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
5179 ret = reganode(pRExC_state,INSUBP,parno);
5180 goto insert_if_check_paren;
5182 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
5185 parno = atoi(RExC_parse++);
5187 while (isDIGIT(*RExC_parse))
5189 ret = reganode(pRExC_state, GROUPP, parno);
5191 insert_if_check_paren:
5192 if ((c = *nextchar(pRExC_state)) != ')')
5193 vFAIL("Switch condition not recognized");
5195 REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
5196 br = regbranch(pRExC_state, &flags, 1,depth+1);
5198 br = reganode(pRExC_state, LONGJMP, 0);
5200 REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
5201 c = *nextchar(pRExC_state);
5206 vFAIL("(?(DEFINE)....) does not allow branches");
5207 lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
5208 regbranch(pRExC_state, &flags, 1,depth+1);
5209 REGTAIL(pRExC_state, ret, lastbr);
5212 c = *nextchar(pRExC_state);
5217 vFAIL("Switch (?(condition)... contains too many branches");
5218 ender = reg_node(pRExC_state, TAIL);
5219 REGTAIL(pRExC_state, br, ender);
5221 REGTAIL(pRExC_state, lastbr, ender);
5222 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
5225 REGTAIL(pRExC_state, ret, ender);
5229 vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
5233 RExC_parse--; /* for vFAIL to print correctly */
5234 vFAIL("Sequence (? incomplete");
5238 parse_flags: /* (?i) */
5239 while (*RExC_parse && strchr("iogcmsx", *RExC_parse)) {
5240 /* (?g), (?gc) and (?o) are useless here
5241 and must be globally applied -- japhy */
5243 if (*RExC_parse == 'o' || *RExC_parse == 'g') {
5244 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5245 const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
5246 if (! (wastedflags & wflagbit) ) {
5247 wastedflags |= wflagbit;
5250 "Useless (%s%c) - %suse /%c modifier",
5251 flagsp == &negflags ? "?-" : "?",
5253 flagsp == &negflags ? "don't " : "",
5259 else if (*RExC_parse == 'c') {
5260 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5261 if (! (wastedflags & WASTED_C) ) {
5262 wastedflags |= WASTED_GC;
5265 "Useless (%sc) - %suse /gc modifier",
5266 flagsp == &negflags ? "?-" : "?",
5267 flagsp == &negflags ? "don't " : ""
5272 else { pmflag(flagsp, *RExC_parse); }
5276 if (*RExC_parse == '-') {
5278 wastedflags = 0; /* reset so (?g-c) warns twice */
5282 RExC_flags |= posflags;
5283 RExC_flags &= ~negflags;
5284 if (*RExC_parse == ':') {
5290 if (*RExC_parse != ')') {
5292 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5294 nextchar(pRExC_state);
5304 ret = reganode(pRExC_state, OPEN, parno);
5307 RExC_nestroot = parno;
5308 if (RExC_seen & REG_SEEN_RECURSE) {
5309 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5310 "Setting open paren #%"IVdf" to %d\n",
5311 (IV)parno, REG_NODE_NUM(ret)));
5312 RExC_open_parens[parno-1]= ret;
5315 Set_Node_Length(ret, 1); /* MJD */
5316 Set_Node_Offset(ret, RExC_parse); /* MJD */
5323 /* Pick up the branches, linking them together. */
5324 parse_start = RExC_parse; /* MJD */
5325 br = regbranch(pRExC_state, &flags, 1,depth+1);
5326 /* branch_len = (paren != 0); */
5330 if (*RExC_parse == '|') {
5331 if (!SIZE_ONLY && RExC_extralen) {
5332 reginsert(pRExC_state, BRANCHJ, br, depth+1);
5335 reginsert(pRExC_state, BRANCH, br, depth+1);
5336 Set_Node_Length(br, paren != 0);
5337 Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
5341 RExC_extralen += 1; /* For BRANCHJ-BRANCH. */
5343 else if (paren == ':') {
5344 *flagp |= flags&SIMPLE;
5346 if (is_open) { /* Starts with OPEN. */
5347 REGTAIL(pRExC_state, ret, br); /* OPEN -> first. */
5349 else if (paren != '?') /* Not Conditional */
5351 *flagp |= flags & (SPSTART | HASWIDTH);
5353 while (*RExC_parse == '|') {
5354 if (!SIZE_ONLY && RExC_extralen) {
5355 ender = reganode(pRExC_state, LONGJMP,0);
5356 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
5359 RExC_extralen += 2; /* Account for LONGJMP. */
5360 nextchar(pRExC_state);
5361 br = regbranch(pRExC_state, &flags, 0, depth+1);
5365 REGTAIL(pRExC_state, lastbr, br); /* BRANCH -> BRANCH. */
5369 *flagp |= flags&SPSTART;
5372 if (have_branch || paren != ':') {
5373 /* Make a closing node, and hook it on the end. */
5376 ender = reg_node(pRExC_state, TAIL);
5380 ender = reganode(pRExC_state, CLOSE, parno);
5381 if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
5382 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5383 "Setting close paren #%"IVdf" to %d\n",
5384 (IV)parno, REG_NODE_NUM(ender)));
5385 RExC_close_parens[parno-1]= ender;
5386 if (RExC_nestroot == parno)
5389 Set_Node_Offset(ender,RExC_parse+1); /* MJD */
5390 Set_Node_Length(ender,1); /* MJD */
5396 *flagp &= ~HASWIDTH;
5399 ender = reg_node(pRExC_state, SUCCEED);
5402 ender = reg_node(pRExC_state, END);
5404 assert(!RExC_opend); /* there can only be one! */
5409 REGTAIL(pRExC_state, lastbr, ender);
5411 if (have_branch && !SIZE_ONLY) {
5413 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
5415 /* Hook the tails of the branches to the closing node. */
5416 for (br = ret; br; br = regnext(br)) {
5417 const U8 op = PL_regkind[OP(br)];
5419 REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
5421 else if (op == BRANCHJ) {
5422 REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
5430 static const char parens[] = "=!<,>";
5432 if (paren && (p = strchr(parens, paren))) {
5433 U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
5434 int flag = (p - parens) > 1;
5437 node = SUSPEND, flag = 0;
5438 reginsert(pRExC_state, node,ret, depth+1);
5439 Set_Node_Cur_Length(ret);
5440 Set_Node_Offset(ret, parse_start + 1);
5442 REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
5446 /* Check for proper termination. */
5448 RExC_flags = oregflags;
5449 if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
5450 RExC_parse = oregcomp_parse;
5451 vFAIL("Unmatched (");
5454 else if (!paren && RExC_parse < RExC_end) {
5455 if (*RExC_parse == ')') {
5457 vFAIL("Unmatched )");
5460 FAIL("Junk on end of regexp"); /* "Can't happen". */
5468 - regbranch - one alternative of an | operator
5470 * Implements the concatenation operator.
5473 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
5476 register regnode *ret;
5477 register regnode *chain = NULL;
5478 register regnode *latest;
5479 I32 flags = 0, c = 0;
5480 GET_RE_DEBUG_FLAGS_DECL;
5481 DEBUG_PARSE("brnc");
5485 if (!SIZE_ONLY && RExC_extralen)
5486 ret = reganode(pRExC_state, BRANCHJ,0);
5488 ret = reg_node(pRExC_state, BRANCH);
5489 Set_Node_Length(ret, 1);
5493 if (!first && SIZE_ONLY)
5494 RExC_extralen += 1; /* BRANCHJ */
5496 *flagp = WORST; /* Tentatively. */
5499 nextchar(pRExC_state);
5500 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
5502 latest = regpiece(pRExC_state, &flags,depth+1);
5503 if (latest == NULL) {
5504 if (flags & TRYAGAIN)
5508 else if (ret == NULL)
5510 *flagp |= flags&HASWIDTH;
5511 if (chain == NULL) /* First piece. */
5512 *flagp |= flags&SPSTART;
5515 REGTAIL(pRExC_state, chain, latest);
5520 if (chain == NULL) { /* Loop ran zero times. */
5521 chain = reg_node(pRExC_state, NOTHING);
5526 *flagp |= flags&SIMPLE;
5533 - regpiece - something followed by possible [*+?]
5535 * Note that the branching code sequences used for ? and the general cases
5536 * of * and + are somewhat optimized: they use the same NOTHING node as
5537 * both the endmarker for their branch list and the body of the last branch.
5538 * It might seem that this node could be dispensed with entirely, but the
5539 * endmarker role is not redundant.
5542 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
5545 register regnode *ret;
5547 register char *next;
5549 const char * const origparse = RExC_parse;
5551 I32 max = REG_INFTY;
5553 const char *maxpos = NULL;
5554 GET_RE_DEBUG_FLAGS_DECL;
5555 DEBUG_PARSE("piec");
5557 ret = regatom(pRExC_state, &flags,depth+1);
5559 if (flags & TRYAGAIN)
5566 if (op == '{' && regcurly(RExC_parse)) {
5568 parse_start = RExC_parse; /* MJD */
5569 next = RExC_parse + 1;
5570 while (isDIGIT(*next) || *next == ',') {
5579 if (*next == '}') { /* got one */
5583 min = atoi(RExC_parse);
5587 maxpos = RExC_parse;
5589 if (!max && *maxpos != '0')
5590 max = REG_INFTY; /* meaning "infinity" */
5591 else if (max >= REG_INFTY)
5592 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
5594 nextchar(pRExC_state);
5597 if ((flags&SIMPLE)) {
5598 RExC_naughty += 2 + RExC_naughty / 2;
5599 reginsert(pRExC_state, CURLY, ret, depth+1);
5600 Set_Node_Offset(ret, parse_start+1); /* MJD */
5601 Set_Node_Cur_Length(ret);
5604 regnode * const w = reg_node(pRExC_state, WHILEM);
5607 REGTAIL(pRExC_state, ret, w);
5608 if (!SIZE_ONLY && RExC_extralen) {
5609 reginsert(pRExC_state, LONGJMP,ret, depth+1);
5610 reginsert(pRExC_state, NOTHING,ret, depth+1);
5611 NEXT_OFF(ret) = 3; /* Go over LONGJMP. */
5613 reginsert(pRExC_state, CURLYX,ret, depth+1);
5615 Set_Node_Offset(ret, parse_start+1);
5616 Set_Node_Length(ret,
5617 op == '{' ? (RExC_parse - parse_start) : 1);
5619 if (!SIZE_ONLY && RExC_extralen)
5620 NEXT_OFF(ret) = 3; /* Go over NOTHING to LONGJMP. */
5621 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
5623 RExC_whilem_seen++, RExC_extralen += 3;
5624 RExC_naughty += 4 + RExC_naughty; /* compound interest */
5632 if (max && max < min)
5633 vFAIL("Can't do {n,m} with n > m");
5635 ARG1_SET(ret, (U16)min);
5636 ARG2_SET(ret, (U16)max);
5648 #if 0 /* Now runtime fix should be reliable. */
5650 /* if this is reinstated, don't forget to put this back into perldiag:
5652 =item Regexp *+ operand could be empty at {#} in regex m/%s/
5654 (F) The part of the regexp subject to either the * or + quantifier
5655 could match an empty string. The {#} shows in the regular
5656 expression about where the problem was discovered.
5660 if (!(flags&HASWIDTH) && op != '?')
5661 vFAIL("Regexp *+ operand could be empty");
5664 parse_start = RExC_parse;
5665 nextchar(pRExC_state);
5667 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
5669 if (op == '*' && (flags&SIMPLE)) {
5670 reginsert(pRExC_state, STAR, ret, depth+1);
5674 else if (op == '*') {
5678 else if (op == '+' && (flags&SIMPLE)) {
5679 reginsert(pRExC_state, PLUS, ret, depth+1);
5683 else if (op == '+') {
5687 else if (op == '?') {
5692 if (!SIZE_ONLY && !(flags&HASWIDTH) && max > REG_INFTY/3 && ckWARN(WARN_REGEXP)) {
5694 "%.*s matches null string many times",
5695 (int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
5699 if (RExC_parse < RExC_end && *RExC_parse == '?') {
5700 nextchar(pRExC_state);
5701 reginsert(pRExC_state, MINMOD, ret, depth+1);
5702 REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
5704 #ifndef REG_ALLOW_MINMOD_SUSPEND
5707 if (RExC_parse < RExC_end && *RExC_parse == '+') {
5709 nextchar(pRExC_state);
5710 ender = reg_node(pRExC_state, SUCCEED);
5711 REGTAIL(pRExC_state, ret, ender);
5712 reginsert(pRExC_state, SUSPEND, ret, depth+1);
5714 ender = reg_node(pRExC_state, TAIL);
5715 REGTAIL(pRExC_state, ret, ender);
5719 if (RExC_parse < RExC_end && ISMULT2(RExC_parse)) {
5721 vFAIL("Nested quantifiers");
5728 /* reg_namedseq(pRExC_state,UVp)
5730 This is expected to be called by a parser routine that has
5731 recognized'\N' and needs to handle the rest. RExC_parse is
5732 expected to point at the first char following the N at the time
5735 If valuep is non-null then it is assumed that we are parsing inside
5736 of a charclass definition and the first codepoint in the resolved
5737 string is returned via *valuep and the routine will return NULL.
5738 In this mode if a multichar string is returned from the charnames
5739 handler a warning will be issued, and only the first char in the
5740 sequence will be examined. If the string returned is zero length
5741 then the value of *valuep is undefined and NON-NULL will
5742 be returned to indicate failure. (This will NOT be a valid pointer
5745 If value is null then it is assumed that we are parsing normal text
5746 and inserts a new EXACT node into the program containing the resolved
5747 string and returns a pointer to the new node. If the string is
5748 zerolength a NOTHING node is emitted.
5750 On success RExC_parse is set to the char following the endbrace.
5751 Parsing failures will generate a fatal errorvia vFAIL(...)
5753 NOTE: We cache all results from the charnames handler locally in
5754 the RExC_charnames hash (created on first use) to prevent a charnames
5755 handler from playing silly-buggers and returning a short string and
5756 then a long string for a given pattern. Since the regexp program
5757 size is calculated during an initial parse this would result
5758 in a buffer overrun so we cache to prevent the charname result from
5759 changing during the course of the parse.
5763 S_reg_namedseq(pTHX_ RExC_state_t *pRExC_state, UV *valuep)
5765 char * name; /* start of the content of the name */
5766 char * endbrace; /* endbrace following the name */
5769 STRLEN len; /* this has various purposes throughout the code */
5770 bool cached = 0; /* if this is true then we shouldn't refcount dev sv_str */
5771 regnode *ret = NULL;
5773 if (*RExC_parse != '{') {
5774 vFAIL("Missing braces on \\N{}");
5776 name = RExC_parse+1;
5777 endbrace = strchr(RExC_parse, '}');
5780 vFAIL("Missing right brace on \\N{}");
5782 RExC_parse = endbrace + 1;
5785 /* RExC_parse points at the beginning brace,
5786 endbrace points at the last */
5787 if ( name[0]=='U' && name[1]=='+' ) {
5788 /* its a "unicode hex" notation {U+89AB} */
5789 I32 fl = PERL_SCAN_ALLOW_UNDERSCORES
5790 | PERL_SCAN_DISALLOW_PREFIX
5791 | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
5793 len = (STRLEN)(endbrace - name - 2);
5794 cp = grok_hex(name + 2, &len, &fl, NULL);
5795 if ( len != (STRLEN)(endbrace - name - 2) ) {
5804 sv_str= Perl_newSVpvf_nocontext("%c",(int)cp);
5806 /* fetch the charnames handler for this scope */
5807 HV * const table = GvHV(PL_hintgv);
5809 hv_fetchs(table, "charnames", FALSE) :
5811 SV *cv= cvp ? *cvp : NULL;
5814 /* create an SV with the name as argument */
5815 sv_name = newSVpvn(name, endbrace - name);
5817 if (!table || !(PL_hints & HINT_LOCALIZE_HH)) {
5818 vFAIL2("Constant(\\N{%s}) unknown: "
5819 "(possibly a missing \"use charnames ...\")",
5822 if (!cvp || !SvOK(*cvp)) { /* when $^H{charnames} = undef; */
5823 vFAIL2("Constant(\\N{%s}): "
5824 "$^H{charnames} is not defined",SvPVX(sv_name));
5829 if (!RExC_charnames) {
5830 /* make sure our cache is allocated */
5831 RExC_charnames = newHV();
5832 sv_2mortal((SV*)RExC_charnames);
5834 /* see if we have looked this one up before */
5835 he_str = hv_fetch_ent( RExC_charnames, sv_name, 0, 0 );
5837 sv_str = HeVAL(he_str);
5850 count= call_sv(cv, G_SCALAR);
5852 if (count == 1) { /* XXXX is this right? dmq */
5854 SvREFCNT_inc_simple_void(sv_str);
5862 if ( !sv_str || !SvOK(sv_str) ) {
5863 vFAIL2("Constant(\\N{%s}): Call to &{$^H{charnames}} "
5864 "did not return a defined value",SvPVX(sv_name));
5866 if (hv_store_ent( RExC_charnames, sv_name, sv_str, 0))
5871 char *p = SvPV(sv_str, len);
5874 if ( SvUTF8(sv_str) ) {
5875 *valuep = utf8_to_uvchr((U8*)p, &numlen);
5879 We have to turn on utf8 for high bit chars otherwise
5880 we get failures with
5882 "ss" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
5883 "SS" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
5885 This is different from what \x{} would do with the same
5886 codepoint, where the condition is > 0xFF.
5893 /* warn if we havent used the whole string? */
5895 if (numlen<len && SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5897 "Ignoring excess chars from \\N{%s} in character class",
5901 } else if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5903 "Ignoring zero length \\N{%s} in character class",
5908 SvREFCNT_dec(sv_name);
5910 SvREFCNT_dec(sv_str);
5911 return len ? NULL : (regnode *)&len;
5912 } else if(SvCUR(sv_str)) {
5917 char * parse_start = name-3; /* needed for the offsets */
5918 GET_RE_DEBUG_FLAGS_DECL; /* needed for the offsets */
5920 ret = reg_node(pRExC_state,
5921 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
5924 if ( RExC_utf8 && !SvUTF8(sv_str) ) {
5925 sv_utf8_upgrade(sv_str);
5926 } else if ( !RExC_utf8 && SvUTF8(sv_str) ) {
5930 p = SvPV(sv_str, len);
5932 /* len is the length written, charlen is the size the char read */
5933 for ( len = 0; p < pend; p += charlen ) {
5935 UV uvc = utf8_to_uvchr((U8*)p, &charlen);
5937 STRLEN foldlen,numlen;
5938 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
5939 uvc = toFOLD_uni(uvc, tmpbuf, &foldlen);
5940 /* Emit all the Unicode characters. */
5942 for (foldbuf = tmpbuf;
5946 uvc = utf8_to_uvchr(foldbuf, &numlen);
5948 const STRLEN unilen = reguni(pRExC_state, uvc, s);
5951 /* In EBCDIC the numlen
5952 * and unilen can differ. */
5954 if (numlen >= foldlen)
5958 break; /* "Can't happen." */
5961 const STRLEN unilen = reguni(pRExC_state, uvc, s);
5973 RExC_size += STR_SZ(len);
5976 RExC_emit += STR_SZ(len);
5978 Set_Node_Cur_Length(ret); /* MJD */
5980 nextchar(pRExC_state);
5982 ret = reg_node(pRExC_state,NOTHING);
5985 SvREFCNT_dec(sv_str);
5988 SvREFCNT_dec(sv_name);
5998 * It returns the code point in utf8 for the value in *encp.
5999 * value: a code value in the source encoding
6000 * encp: a pointer to an Encode object
6002 * If the result from Encode is not a single character,
6003 * it returns U+FFFD (Replacement character) and sets *encp to NULL.
6006 S_reg_recode(pTHX_ const char value, SV **encp)
6009 SV * const sv = sv_2mortal(newSVpvn(&value, numlen));
6010 const char * const s = encp && *encp ? sv_recode_to_utf8(sv, *encp)
6012 const STRLEN newlen = SvCUR(sv);
6013 UV uv = UNICODE_REPLACEMENT;
6017 ? utf8n_to_uvchr((U8*)s, newlen, &numlen, UTF8_ALLOW_DEFAULT)
6020 if (!newlen || numlen != newlen) {
6021 uv = UNICODE_REPLACEMENT;
6030 - regatom - the lowest level
6032 * Optimization: gobbles an entire sequence of ordinary characters so that
6033 * it can turn them into a single node, which is smaller to store and
6034 * faster to run. Backslashed characters are exceptions, each becoming a
6035 * separate node; the code is simpler that way and it's not worth fixing.
6037 * [Yes, it is worth fixing, some scripts can run twice the speed.]
6038 * [It looks like its ok, as in S_study_chunk we merge adjacent EXACT nodes]
6041 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
6044 register regnode *ret = NULL;
6046 char *parse_start = RExC_parse;
6047 GET_RE_DEBUG_FLAGS_DECL;
6048 DEBUG_PARSE("atom");
6049 *flagp = WORST; /* Tentatively. */
6052 switch (*RExC_parse) {
6054 RExC_seen_zerolen++;
6055 nextchar(pRExC_state);
6056 if (RExC_flags & PMf_MULTILINE)
6057 ret = reg_node(pRExC_state, MBOL);
6058 else if (RExC_flags & PMf_SINGLELINE)
6059 ret = reg_node(pRExC_state, SBOL);
6061 ret = reg_node(pRExC_state, BOL);
6062 Set_Node_Length(ret, 1); /* MJD */
6065 nextchar(pRExC_state);
6067 RExC_seen_zerolen++;
6068 if (RExC_flags & PMf_MULTILINE)
6069 ret = reg_node(pRExC_state, MEOL);
6070 else if (RExC_flags & PMf_SINGLELINE)
6071 ret = reg_node(pRExC_state, SEOL);
6073 ret = reg_node(pRExC_state, EOL);
6074 Set_Node_Length(ret, 1); /* MJD */
6077 nextchar(pRExC_state);
6078 if (RExC_flags & PMf_SINGLELINE)
6079 ret = reg_node(pRExC_state, SANY);
6081 ret = reg_node(pRExC_state, REG_ANY);
6082 *flagp |= HASWIDTH|SIMPLE;
6084 Set_Node_Length(ret, 1); /* MJD */
6088 char * const oregcomp_parse = ++RExC_parse;
6089 ret = regclass(pRExC_state,depth+1);
6090 if (*RExC_parse != ']') {
6091 RExC_parse = oregcomp_parse;
6092 vFAIL("Unmatched [");
6094 nextchar(pRExC_state);
6095 *flagp |= HASWIDTH|SIMPLE;
6096 Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
6100 nextchar(pRExC_state);
6101 ret = reg(pRExC_state, 1, &flags,depth+1);
6103 if (flags & TRYAGAIN) {
6104 if (RExC_parse == RExC_end) {
6105 /* Make parent create an empty node if needed. */
6113 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE);
6117 if (flags & TRYAGAIN) {
6121 vFAIL("Internal urp");
6122 /* Supposed to be caught earlier. */
6125 if (!regcurly(RExC_parse)) {
6134 vFAIL("Quantifier follows nothing");
6137 switch (*++RExC_parse) {
6139 RExC_seen_zerolen++;
6140 ret = reg_node(pRExC_state, SBOL);
6142 nextchar(pRExC_state);
6143 Set_Node_Length(ret, 2); /* MJD */
6146 ret = reg_node(pRExC_state, GPOS);
6147 RExC_seen |= REG_SEEN_GPOS;
6149 nextchar(pRExC_state);
6150 Set_Node_Length(ret, 2); /* MJD */
6153 ret = reg_node(pRExC_state, SEOL);
6155 RExC_seen_zerolen++; /* Do not optimize RE away */
6156 nextchar(pRExC_state);
6159 ret = reg_node(pRExC_state, EOS);
6161 RExC_seen_zerolen++; /* Do not optimize RE away */
6162 nextchar(pRExC_state);
6163 Set_Node_Length(ret, 2); /* MJD */
6166 ret = reg_node(pRExC_state, CANY);
6167 RExC_seen |= REG_SEEN_CANY;
6168 *flagp |= HASWIDTH|SIMPLE;
6169 nextchar(pRExC_state);
6170 Set_Node_Length(ret, 2); /* MJD */
6173 ret = reg_node(pRExC_state, CLUMP);
6175 nextchar(pRExC_state);
6176 Set_Node_Length(ret, 2); /* MJD */
6179 ret = reg_node(pRExC_state, (U8)(LOC ? ALNUML : ALNUM));
6180 *flagp |= HASWIDTH|SIMPLE;
6181 nextchar(pRExC_state);
6182 Set_Node_Length(ret, 2); /* MJD */
6185 ret = reg_node(pRExC_state, (U8)(LOC ? NALNUML : NALNUM));
6186 *flagp |= HASWIDTH|SIMPLE;
6187 nextchar(pRExC_state);
6188 Set_Node_Length(ret, 2); /* MJD */
6191 RExC_seen_zerolen++;
6192 RExC_seen |= REG_SEEN_LOOKBEHIND;
6193 ret = reg_node(pRExC_state, (U8)(LOC ? BOUNDL : BOUND));
6195 nextchar(pRExC_state);
6196 Set_Node_Length(ret, 2); /* MJD */
6199 RExC_seen_zerolen++;
6200 RExC_seen |= REG_SEEN_LOOKBEHIND;
6201 ret = reg_node(pRExC_state, (U8)(LOC ? NBOUNDL : NBOUND));
6203 nextchar(pRExC_state);
6204 Set_Node_Length(ret, 2); /* MJD */
6207 ret = reg_node(pRExC_state, (U8)(LOC ? SPACEL : SPACE));
6208 *flagp |= HASWIDTH|SIMPLE;
6209 nextchar(pRExC_state);
6210 Set_Node_Length(ret, 2); /* MJD */
6213 ret = reg_node(pRExC_state, (U8)(LOC ? NSPACEL : NSPACE));
6214 *flagp |= HASWIDTH|SIMPLE;
6215 nextchar(pRExC_state);
6216 Set_Node_Length(ret, 2); /* MJD */
6219 ret = reg_node(pRExC_state, DIGIT);
6220 *flagp |= HASWIDTH|SIMPLE;
6221 nextchar(pRExC_state);
6222 Set_Node_Length(ret, 2); /* MJD */
6225 ret = reg_node(pRExC_state, NDIGIT);
6226 *flagp |= HASWIDTH|SIMPLE;
6227 nextchar(pRExC_state);
6228 Set_Node_Length(ret, 2); /* MJD */
6233 char* const oldregxend = RExC_end;
6234 char* parse_start = RExC_parse - 2;
6236 if (RExC_parse[1] == '{') {
6237 /* a lovely hack--pretend we saw [\pX] instead */
6238 RExC_end = strchr(RExC_parse, '}');
6240 const U8 c = (U8)*RExC_parse;
6242 RExC_end = oldregxend;
6243 vFAIL2("Missing right brace on \\%c{}", c);
6248 RExC_end = RExC_parse + 2;
6249 if (RExC_end > oldregxend)
6250 RExC_end = oldregxend;
6254 ret = regclass(pRExC_state,depth+1);
6256 RExC_end = oldregxend;
6259 Set_Node_Offset(ret, parse_start + 2);
6260 Set_Node_Cur_Length(ret);
6261 nextchar(pRExC_state);
6262 *flagp |= HASWIDTH|SIMPLE;
6266 /* Handle \N{NAME} here and not below because it can be
6267 multicharacter. join_exact() will join them up later on.
6268 Also this makes sure that things like /\N{BLAH}+/ and
6269 \N{BLAH} being multi char Just Happen. dmq*/
6271 ret= reg_namedseq(pRExC_state, NULL);
6273 case 'k': /* Handle \k<NAME> and \k'NAME' */
6275 char ch= RExC_parse[1];
6276 if (ch != '<' && ch != '\'') {
6278 vWARN( RExC_parse + 1,
6279 "Possible broken named back reference treated as literal k");
6283 char* name_start = (RExC_parse += 2);
6285 SV *sv_dat = reg_scan_name(pRExC_state,
6286 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
6287 ch= (ch == '<') ? '>' : '\'';
6289 if (RExC_parse == name_start || *RExC_parse != ch)
6290 vFAIL2("Sequence \\k%c... not terminated",
6291 (ch == '>' ? '<' : ch));
6294 ret = reganode(pRExC_state,
6295 (U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
6301 num = add_data( pRExC_state, 1, "S" );
6303 RExC_rx->data->data[num]=(void*)sv_dat;
6304 SvREFCNT_inc(sv_dat);
6306 /* override incorrect value set in reganode MJD */
6307 Set_Node_Offset(ret, parse_start+1);
6308 Set_Node_Cur_Length(ret); /* MJD */
6309 nextchar(pRExC_state);
6325 case '1': case '2': case '3': case '4':
6326 case '5': case '6': case '7': case '8': case '9':
6329 bool isrel=(*RExC_parse=='R');
6332 num = atoi(RExC_parse);
6334 num = RExC_cpar - num;
6336 vFAIL("Reference to nonexistent or unclosed group");
6338 if (num > 9 && num >= RExC_npar)
6341 char * const parse_start = RExC_parse - 1; /* MJD */
6342 while (isDIGIT(*RExC_parse))
6346 if (num > (I32)RExC_rx->nparens)
6347 vFAIL("Reference to nonexistent group");
6348 /* People make this error all the time apparently.
6349 So we cant fail on it, even though we should
6351 else if (num >= RExC_cpar)
6352 vFAIL("Reference to unclosed group will always match");
6356 ret = reganode(pRExC_state,
6357 (U8)(FOLD ? (LOC ? REFFL : REFF) : REF),
6361 /* override incorrect value set in reganode MJD */
6362 Set_Node_Offset(ret, parse_start+1);
6363 Set_Node_Cur_Length(ret); /* MJD */
6365 nextchar(pRExC_state);
6370 if (RExC_parse >= RExC_end)
6371 FAIL("Trailing \\");
6374 /* Do not generate "unrecognized" warnings here, we fall
6375 back into the quick-grab loop below */
6382 if (RExC_flags & PMf_EXTENDED) {
6383 while (RExC_parse < RExC_end && *RExC_parse != '\n')
6385 if (RExC_parse < RExC_end)
6391 register STRLEN len;
6396 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
6398 parse_start = RExC_parse - 1;
6404 ret = reg_node(pRExC_state,
6405 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
6407 for (len = 0, p = RExC_parse - 1;
6408 len < 127 && p < RExC_end;
6411 char * const oldp = p;
6413 if (RExC_flags & PMf_EXTENDED)
6414 p = regwhite(p, RExC_end);
6463 ender = ASCII_TO_NATIVE('\033');
6467 ender = ASCII_TO_NATIVE('\007');
6472 char* const e = strchr(p, '}');
6476 vFAIL("Missing right brace on \\x{}");
6479 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
6480 | PERL_SCAN_DISALLOW_PREFIX;
6481 STRLEN numlen = e - p - 1;
6482 ender = grok_hex(p + 1, &numlen, &flags, NULL);
6489 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
6491 ender = grok_hex(p, &numlen, &flags, NULL);
6494 if (PL_encoding && ender < 0x100)
6495 goto recode_encoding;
6499 ender = UCHARAT(p++);
6500 ender = toCTRL(ender);
6502 case '0': case '1': case '2': case '3':case '4':
6503 case '5': case '6': case '7': case '8':case '9':
6505 (isDIGIT(p[1]) && atoi(p) >= RExC_npar) ) {
6508 ender = grok_oct(p, &numlen, &flags, NULL);
6515 if (PL_encoding && ender < 0x100)
6516 goto recode_encoding;
6520 SV* enc = PL_encoding;
6521 ender = reg_recode((const char)(U8)ender, &enc);
6522 if (!enc && SIZE_ONLY && ckWARN(WARN_REGEXP))
6523 vWARN(p, "Invalid escape in the specified encoding");
6529 FAIL("Trailing \\");
6532 if (!SIZE_ONLY&& isALPHA(*p) && ckWARN(WARN_REGEXP))
6533 vWARN2(p + 1, "Unrecognized escape \\%c passed through", UCHARAT(p));
6534 goto normal_default;
6539 if (UTF8_IS_START(*p) && UTF) {
6541 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
6542 &numlen, UTF8_ALLOW_DEFAULT);
6549 if (RExC_flags & PMf_EXTENDED)
6550 p = regwhite(p, RExC_end);
6552 /* Prime the casefolded buffer. */
6553 ender = toFOLD_uni(ender, tmpbuf, &foldlen);
6555 if (ISMULT2(p)) { /* Back off on ?+*. */
6560 /* Emit all the Unicode characters. */
6562 for (foldbuf = tmpbuf;
6564 foldlen -= numlen) {
6565 ender = utf8_to_uvchr(foldbuf, &numlen);
6567 const STRLEN unilen = reguni(pRExC_state, ender, s);
6570 /* In EBCDIC the numlen
6571 * and unilen can differ. */
6573 if (numlen >= foldlen)
6577 break; /* "Can't happen." */
6581 const STRLEN unilen = reguni(pRExC_state, ender, s);
6590 REGC((char)ender, s++);
6596 /* Emit all the Unicode characters. */
6598 for (foldbuf = tmpbuf;
6600 foldlen -= numlen) {
6601 ender = utf8_to_uvchr(foldbuf, &numlen);
6603 const STRLEN unilen = reguni(pRExC_state, ender, s);
6606 /* In EBCDIC the numlen
6607 * and unilen can differ. */
6609 if (numlen >= foldlen)
6617 const STRLEN unilen = reguni(pRExC_state, ender, s);
6626 REGC((char)ender, s++);
6630 Set_Node_Cur_Length(ret); /* MJD */
6631 nextchar(pRExC_state);
6633 /* len is STRLEN which is unsigned, need to copy to signed */
6636 vFAIL("Internal disaster");
6640 if (len == 1 && UNI_IS_INVARIANT(ender))
6644 RExC_size += STR_SZ(len);
6647 RExC_emit += STR_SZ(len);
6657 S_regwhite(char *p, const char *e)
6662 else if (*p == '#') {
6665 } while (p < e && *p != '\n');
6673 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
6674 Character classes ([:foo:]) can also be negated ([:^foo:]).
6675 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
6676 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
6677 but trigger failures because they are currently unimplemented. */
6679 #define POSIXCC_DONE(c) ((c) == ':')
6680 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
6681 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
6684 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
6687 I32 namedclass = OOB_NAMEDCLASS;
6689 if (value == '[' && RExC_parse + 1 < RExC_end &&
6690 /* I smell either [: or [= or [. -- POSIX has been here, right? */
6691 POSIXCC(UCHARAT(RExC_parse))) {
6692 const char c = UCHARAT(RExC_parse);
6693 char* const s = RExC_parse++;
6695 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
6697 if (RExC_parse == RExC_end)
6698 /* Grandfather lone [:, [=, [. */
6701 const char* const t = RExC_parse++; /* skip over the c */
6704 if (UCHARAT(RExC_parse) == ']') {
6705 const char *posixcc = s + 1;
6706 RExC_parse++; /* skip over the ending ] */
6709 const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
6710 const I32 skip = t - posixcc;
6712 /* Initially switch on the length of the name. */
6715 if (memEQ(posixcc, "word", 4)) /* this is not POSIX, this is the Perl \w */
6716 namedclass = complement ? ANYOF_NALNUM : ANYOF_ALNUM;
6719 /* Names all of length 5. */
6720 /* alnum alpha ascii blank cntrl digit graph lower
6721 print punct space upper */
6722 /* Offset 4 gives the best switch position. */
6723 switch (posixcc[4]) {
6725 if (memEQ(posixcc, "alph", 4)) /* alpha */
6726 namedclass = complement ? ANYOF_NALPHA : ANYOF_ALPHA;
6729 if (memEQ(posixcc, "spac", 4)) /* space */
6730 namedclass = complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
6733 if (memEQ(posixcc, "grap", 4)) /* graph */
6734 namedclass = complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
6737 if (memEQ(posixcc, "asci", 4)) /* ascii */
6738 namedclass = complement ? ANYOF_NASCII : ANYOF_ASCII;
6741 if (memEQ(posixcc, "blan", 4)) /* blank */
6742 namedclass = complement ? ANYOF_NBLANK : ANYOF_BLANK;
6745 if (memEQ(posixcc, "cntr", 4)) /* cntrl */
6746 namedclass = complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
6749 if (memEQ(posixcc, "alnu", 4)) /* alnum */
6750 namedclass = complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
6753 if (memEQ(posixcc, "lowe", 4)) /* lower */
6754 namedclass = complement ? ANYOF_NLOWER : ANYOF_LOWER;
6755 else if (memEQ(posixcc, "uppe", 4)) /* upper */
6756 namedclass = complement ? ANYOF_NUPPER : ANYOF_UPPER;
6759 if (memEQ(posixcc, "digi", 4)) /* digit */
6760 namedclass = complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
6761 else if (memEQ(posixcc, "prin", 4)) /* print */
6762 namedclass = complement ? ANYOF_NPRINT : ANYOF_PRINT;
6763 else if (memEQ(posixcc, "punc", 4)) /* punct */
6764 namedclass = complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
6769 if (memEQ(posixcc, "xdigit", 6))
6770 namedclass = complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
6774 if (namedclass == OOB_NAMEDCLASS)
6775 Simple_vFAIL3("POSIX class [:%.*s:] unknown",
6777 assert (posixcc[skip] == ':');
6778 assert (posixcc[skip+1] == ']');
6779 } else if (!SIZE_ONLY) {
6780 /* [[=foo=]] and [[.foo.]] are still future. */
6782 /* adjust RExC_parse so the warning shows after
6784 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
6786 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
6789 /* Maternal grandfather:
6790 * "[:" ending in ":" but not in ":]" */
6800 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
6803 if (POSIXCC(UCHARAT(RExC_parse))) {
6804 const char *s = RExC_parse;
6805 const char c = *s++;
6809 if (*s && c == *s && s[1] == ']') {
6810 if (ckWARN(WARN_REGEXP))
6812 "POSIX syntax [%c %c] belongs inside character classes",
6815 /* [[=foo=]] and [[.foo.]] are still future. */
6816 if (POSIXCC_NOTYET(c)) {
6817 /* adjust RExC_parse so the error shows after
6819 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
6821 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
6829 parse a class specification and produce either an ANYOF node that
6830 matches the pattern. If the pattern matches a single char only and
6831 that char is < 256 then we produce an EXACT node instead.
6834 S_regclass(pTHX_ RExC_state_t *pRExC_state, U32 depth)
6837 register UV value = 0;
6838 register UV nextvalue;
6839 register IV prevvalue = OOB_UNICODE;
6840 register IV range = 0;
6841 register regnode *ret;
6844 char *rangebegin = NULL;
6845 bool need_class = 0;
6848 bool optimize_invert = TRUE;
6849 AV* unicode_alternate = NULL;
6851 UV literal_endpoint = 0;
6853 UV stored = 0; /* number of chars stored in the class */
6855 regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
6856 case we need to change the emitted regop to an EXACT. */
6857 const char * orig_parse = RExC_parse;
6858 GET_RE_DEBUG_FLAGS_DECL;
6860 PERL_UNUSED_ARG(depth);
6863 DEBUG_PARSE("clas");
6865 /* Assume we are going to generate an ANYOF node. */
6866 ret = reganode(pRExC_state, ANYOF, 0);
6869 ANYOF_FLAGS(ret) = 0;
6871 if (UCHARAT(RExC_parse) == '^') { /* Complement of range. */
6875 ANYOF_FLAGS(ret) |= ANYOF_INVERT;
6879 RExC_size += ANYOF_SKIP;
6880 listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
6883 RExC_emit += ANYOF_SKIP;
6885 ANYOF_FLAGS(ret) |= ANYOF_FOLD;
6887 ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
6888 ANYOF_BITMAP_ZERO(ret);
6889 listsv = newSVpvs("# comment\n");
6892 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
6894 if (!SIZE_ONLY && POSIXCC(nextvalue))
6895 checkposixcc(pRExC_state);
6897 /* allow 1st char to be ] (allowing it to be - is dealt with later) */
6898 if (UCHARAT(RExC_parse) == ']')
6902 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
6906 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
6909 rangebegin = RExC_parse;
6911 value = utf8n_to_uvchr((U8*)RExC_parse,
6912 RExC_end - RExC_parse,
6913 &numlen, UTF8_ALLOW_DEFAULT);
6914 RExC_parse += numlen;
6917 value = UCHARAT(RExC_parse++);
6919 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
6920 if (value == '[' && POSIXCC(nextvalue))
6921 namedclass = regpposixcc(pRExC_state, value);
6922 else if (value == '\\') {
6924 value = utf8n_to_uvchr((U8*)RExC_parse,
6925 RExC_end - RExC_parse,
6926 &numlen, UTF8_ALLOW_DEFAULT);
6927 RExC_parse += numlen;
6930 value = UCHARAT(RExC_parse++);
6931 /* Some compilers cannot handle switching on 64-bit integer
6932 * values, therefore value cannot be an UV. Yes, this will
6933 * be a problem later if we want switch on Unicode.
6934 * A similar issue a little bit later when switching on
6935 * namedclass. --jhi */
6936 switch ((I32)value) {
6937 case 'w': namedclass = ANYOF_ALNUM; break;
6938 case 'W': namedclass = ANYOF_NALNUM; break;
6939 case 's': namedclass = ANYOF_SPACE; break;
6940 case 'S': namedclass = ANYOF_NSPACE; break;
6941 case 'd': namedclass = ANYOF_DIGIT; break;
6942 case 'D': namedclass = ANYOF_NDIGIT; break;
6943 case 'N': /* Handle \N{NAME} in class */
6945 /* We only pay attention to the first char of
6946 multichar strings being returned. I kinda wonder
6947 if this makes sense as it does change the behaviour
6948 from earlier versions, OTOH that behaviour was broken
6950 UV v; /* value is register so we cant & it /grrr */
6951 if (reg_namedseq(pRExC_state, &v)) {
6961 if (RExC_parse >= RExC_end)
6962 vFAIL2("Empty \\%c{}", (U8)value);
6963 if (*RExC_parse == '{') {
6964 const U8 c = (U8)value;
6965 e = strchr(RExC_parse++, '}');
6967 vFAIL2("Missing right brace on \\%c{}", c);
6968 while (isSPACE(UCHARAT(RExC_parse)))
6970 if (e == RExC_parse)
6971 vFAIL2("Empty \\%c{}", c);
6973 while (isSPACE(UCHARAT(RExC_parse + n - 1)))
6981 if (UCHARAT(RExC_parse) == '^') {
6984 value = value == 'p' ? 'P' : 'p'; /* toggle */
6985 while (isSPACE(UCHARAT(RExC_parse))) {
6990 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%.*s\n",
6991 (value=='p' ? '+' : '!'), (int)n, RExC_parse);
6994 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
6995 namedclass = ANYOF_MAX; /* no official name, but it's named */
6998 case 'n': value = '\n'; break;
6999 case 'r': value = '\r'; break;
7000 case 't': value = '\t'; break;
7001 case 'f': value = '\f'; break;
7002 case 'b': value = '\b'; break;
7003 case 'e': value = ASCII_TO_NATIVE('\033');break;
7004 case 'a': value = ASCII_TO_NATIVE('\007');break;
7006 if (*RExC_parse == '{') {
7007 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
7008 | PERL_SCAN_DISALLOW_PREFIX;
7009 char * const e = strchr(RExC_parse++, '}');
7011 vFAIL("Missing right brace on \\x{}");
7013 numlen = e - RExC_parse;
7014 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
7018 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
7020 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
7021 RExC_parse += numlen;
7023 if (PL_encoding && value < 0x100)
7024 goto recode_encoding;
7027 value = UCHARAT(RExC_parse++);
7028 value = toCTRL(value);
7030 case '0': case '1': case '2': case '3': case '4':
7031 case '5': case '6': case '7': case '8': case '9':
7035 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
7036 RExC_parse += numlen;
7037 if (PL_encoding && value < 0x100)
7038 goto recode_encoding;
7043 SV* enc = PL_encoding;
7044 value = reg_recode((const char)(U8)value, &enc);
7045 if (!enc && SIZE_ONLY && ckWARN(WARN_REGEXP))
7047 "Invalid escape in the specified encoding");
7051 if (!SIZE_ONLY && isALPHA(value) && ckWARN(WARN_REGEXP))
7053 "Unrecognized escape \\%c in character class passed through",
7057 } /* end of \blah */
7063 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
7065 if (!SIZE_ONLY && !need_class)
7066 ANYOF_CLASS_ZERO(ret);
7070 /* a bad range like a-\d, a-[:digit:] ? */
7073 if (ckWARN(WARN_REGEXP)) {
7075 RExC_parse >= rangebegin ?
7076 RExC_parse - rangebegin : 0;
7078 "False [] range \"%*.*s\"",
7081 if (prevvalue < 256) {
7082 ANYOF_BITMAP_SET(ret, prevvalue);
7083 ANYOF_BITMAP_SET(ret, '-');
7086 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
7087 Perl_sv_catpvf(aTHX_ listsv,
7088 "%04"UVxf"\n%04"UVxf"\n", (UV)prevvalue, (UV) '-');
7092 range = 0; /* this was not a true range */
7096 const char *what = NULL;
7099 if (namedclass > OOB_NAMEDCLASS)
7100 optimize_invert = FALSE;
7101 /* Possible truncation here but in some 64-bit environments
7102 * the compiler gets heartburn about switch on 64-bit values.
7103 * A similar issue a little earlier when switching on value.
7105 switch ((I32)namedclass) {
7108 ANYOF_CLASS_SET(ret, ANYOF_ALNUM);
7110 for (value = 0; value < 256; value++)
7112 ANYOF_BITMAP_SET(ret, value);
7119 ANYOF_CLASS_SET(ret, ANYOF_NALNUM);
7121 for (value = 0; value < 256; value++)
7122 if (!isALNUM(value))
7123 ANYOF_BITMAP_SET(ret, value);
7130 ANYOF_CLASS_SET(ret, ANYOF_ALNUMC);
7132 for (value = 0; value < 256; value++)
7133 if (isALNUMC(value))
7134 ANYOF_BITMAP_SET(ret, value);
7141 ANYOF_CLASS_SET(ret, ANYOF_NALNUMC);
7143 for (value = 0; value < 256; value++)
7144 if (!isALNUMC(value))
7145 ANYOF_BITMAP_SET(ret, value);
7152 ANYOF_CLASS_SET(ret, ANYOF_ALPHA);
7154 for (value = 0; value < 256; value++)
7156 ANYOF_BITMAP_SET(ret, value);
7163 ANYOF_CLASS_SET(ret, ANYOF_NALPHA);
7165 for (value = 0; value < 256; value++)
7166 if (!isALPHA(value))
7167 ANYOF_BITMAP_SET(ret, value);
7174 ANYOF_CLASS_SET(ret, ANYOF_ASCII);
7177 for (value = 0; value < 128; value++)
7178 ANYOF_BITMAP_SET(ret, value);
7180 for (value = 0; value < 256; value++) {
7182 ANYOF_BITMAP_SET(ret, value);
7191 ANYOF_CLASS_SET(ret, ANYOF_NASCII);
7194 for (value = 128; value < 256; value++)
7195 ANYOF_BITMAP_SET(ret, value);
7197 for (value = 0; value < 256; value++) {
7198 if (!isASCII(value))
7199 ANYOF_BITMAP_SET(ret, value);
7208 ANYOF_CLASS_SET(ret, ANYOF_BLANK);
7210 for (value = 0; value < 256; value++)
7212 ANYOF_BITMAP_SET(ret, value);
7219 ANYOF_CLASS_SET(ret, ANYOF_NBLANK);
7221 for (value = 0; value < 256; value++)
7222 if (!isBLANK(value))
7223 ANYOF_BITMAP_SET(ret, value);
7230 ANYOF_CLASS_SET(ret, ANYOF_CNTRL);
7232 for (value = 0; value < 256; value++)
7234 ANYOF_BITMAP_SET(ret, value);
7241 ANYOF_CLASS_SET(ret, ANYOF_NCNTRL);
7243 for (value = 0; value < 256; value++)
7244 if (!isCNTRL(value))
7245 ANYOF_BITMAP_SET(ret, value);
7252 ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
7254 /* consecutive digits assumed */
7255 for (value = '0'; value <= '9'; value++)
7256 ANYOF_BITMAP_SET(ret, value);
7263 ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
7265 /* consecutive digits assumed */
7266 for (value = 0; value < '0'; value++)
7267 ANYOF_BITMAP_SET(ret, value);
7268 for (value = '9' + 1; value < 256; value++)
7269 ANYOF_BITMAP_SET(ret, value);
7276 ANYOF_CLASS_SET(ret, ANYOF_GRAPH);
7278 for (value = 0; value < 256; value++)
7280 ANYOF_BITMAP_SET(ret, value);
7287 ANYOF_CLASS_SET(ret, ANYOF_NGRAPH);
7289 for (value = 0; value < 256; value++)
7290 if (!isGRAPH(value))
7291 ANYOF_BITMAP_SET(ret, value);
7298 ANYOF_CLASS_SET(ret, ANYOF_LOWER);
7300 for (value = 0; value < 256; value++)
7302 ANYOF_BITMAP_SET(ret, value);
7309 ANYOF_CLASS_SET(ret, ANYOF_NLOWER);
7311 for (value = 0; value < 256; value++)
7312 if (!isLOWER(value))
7313 ANYOF_BITMAP_SET(ret, value);
7320 ANYOF_CLASS_SET(ret, ANYOF_PRINT);
7322 for (value = 0; value < 256; value++)
7324 ANYOF_BITMAP_SET(ret, value);
7331 ANYOF_CLASS_SET(ret, ANYOF_NPRINT);
7333 for (value = 0; value < 256; value++)
7334 if (!isPRINT(value))
7335 ANYOF_BITMAP_SET(ret, value);
7342 ANYOF_CLASS_SET(ret, ANYOF_PSXSPC);
7344 for (value = 0; value < 256; value++)
7345 if (isPSXSPC(value))
7346 ANYOF_BITMAP_SET(ret, value);
7353 ANYOF_CLASS_SET(ret, ANYOF_NPSXSPC);
7355 for (value = 0; value < 256; value++)
7356 if (!isPSXSPC(value))
7357 ANYOF_BITMAP_SET(ret, value);
7364 ANYOF_CLASS_SET(ret, ANYOF_PUNCT);
7366 for (value = 0; value < 256; value++)
7368 ANYOF_BITMAP_SET(ret, value);
7375 ANYOF_CLASS_SET(ret, ANYOF_NPUNCT);
7377 for (value = 0; value < 256; value++)
7378 if (!isPUNCT(value))
7379 ANYOF_BITMAP_SET(ret, value);
7386 ANYOF_CLASS_SET(ret, ANYOF_SPACE);
7388 for (value = 0; value < 256; value++)
7390 ANYOF_BITMAP_SET(ret, value);
7397 ANYOF_CLASS_SET(ret, ANYOF_NSPACE);
7399 for (value = 0; value < 256; value++)
7400 if (!isSPACE(value))
7401 ANYOF_BITMAP_SET(ret, value);
7408 ANYOF_CLASS_SET(ret, ANYOF_UPPER);
7410 for (value = 0; value < 256; value++)
7412 ANYOF_BITMAP_SET(ret, value);
7419 ANYOF_CLASS_SET(ret, ANYOF_NUPPER);
7421 for (value = 0; value < 256; value++)
7422 if (!isUPPER(value))
7423 ANYOF_BITMAP_SET(ret, value);
7430 ANYOF_CLASS_SET(ret, ANYOF_XDIGIT);
7432 for (value = 0; value < 256; value++)
7433 if (isXDIGIT(value))
7434 ANYOF_BITMAP_SET(ret, value);
7441 ANYOF_CLASS_SET(ret, ANYOF_NXDIGIT);
7443 for (value = 0; value < 256; value++)
7444 if (!isXDIGIT(value))
7445 ANYOF_BITMAP_SET(ret, value);
7451 /* this is to handle \p and \P */
7454 vFAIL("Invalid [::] class");
7458 /* Strings such as "+utf8::isWord\n" */
7459 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::Is%s\n", yesno, what);
7462 ANYOF_FLAGS(ret) |= ANYOF_CLASS;
7465 } /* end of namedclass \blah */
7468 if (prevvalue > (IV)value) /* b-a */ {
7469 const int w = RExC_parse - rangebegin;
7470 Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
7471 range = 0; /* not a valid range */
7475 prevvalue = value; /* save the beginning of the range */
7476 if (*RExC_parse == '-' && RExC_parse+1 < RExC_end &&
7477 RExC_parse[1] != ']') {
7480 /* a bad range like \w-, [:word:]- ? */
7481 if (namedclass > OOB_NAMEDCLASS) {
7482 if (ckWARN(WARN_REGEXP)) {
7484 RExC_parse >= rangebegin ?
7485 RExC_parse - rangebegin : 0;
7487 "False [] range \"%*.*s\"",
7491 ANYOF_BITMAP_SET(ret, '-');
7493 range = 1; /* yeah, it's a range! */
7494 continue; /* but do it the next time */
7498 /* now is the next time */
7499 /*stored += (value - prevvalue + 1);*/
7501 if (prevvalue < 256) {
7502 const IV ceilvalue = value < 256 ? value : 255;
7505 /* In EBCDIC [\x89-\x91] should include
7506 * the \x8e but [i-j] should not. */
7507 if (literal_endpoint == 2 &&
7508 ((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
7509 (isUPPER(prevvalue) && isUPPER(ceilvalue))))
7511 if (isLOWER(prevvalue)) {
7512 for (i = prevvalue; i <= ceilvalue; i++)
7514 ANYOF_BITMAP_SET(ret, i);
7516 for (i = prevvalue; i <= ceilvalue; i++)
7518 ANYOF_BITMAP_SET(ret, i);
7523 for (i = prevvalue; i <= ceilvalue; i++) {
7524 if (!ANYOF_BITMAP_TEST(ret,i)) {
7526 ANYOF_BITMAP_SET(ret, i);
7530 if (value > 255 || UTF) {
7531 const UV prevnatvalue = NATIVE_TO_UNI(prevvalue);
7532 const UV natvalue = NATIVE_TO_UNI(value);
7533 stored+=2; /* can't optimize this class */
7534 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
7535 if (prevnatvalue < natvalue) { /* what about > ? */
7536 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
7537 prevnatvalue, natvalue);
7539 else if (prevnatvalue == natvalue) {
7540 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n", natvalue);
7542 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
7544 const UV f = to_uni_fold(natvalue, foldbuf, &foldlen);
7546 #ifdef EBCDIC /* RD t/uni/fold ff and 6b */
7547 if (RExC_precomp[0] == ':' &&
7548 RExC_precomp[1] == '[' &&
7549 (f == 0xDF || f == 0x92)) {
7550 f = NATIVE_TO_UNI(f);
7553 /* If folding and foldable and a single
7554 * character, insert also the folded version
7555 * to the charclass. */
7557 #ifdef EBCDIC /* RD tunifold ligatures s,t fb05, fb06 */
7558 if ((RExC_precomp[0] == ':' &&
7559 RExC_precomp[1] == '[' &&
7561 (value == 0xFB05 || value == 0xFB06))) ?
7562 foldlen == ((STRLEN)UNISKIP(f) - 1) :
7563 foldlen == (STRLEN)UNISKIP(f) )
7565 if (foldlen == (STRLEN)UNISKIP(f))
7567 Perl_sv_catpvf(aTHX_ listsv,
7570 /* Any multicharacter foldings
7571 * require the following transform:
7572 * [ABCDEF] -> (?:[ABCabcDEFd]|pq|rst)
7573 * where E folds into "pq" and F folds
7574 * into "rst", all other characters
7575 * fold to single characters. We save
7576 * away these multicharacter foldings,
7577 * to be later saved as part of the
7578 * additional "s" data. */
7581 if (!unicode_alternate)
7582 unicode_alternate = newAV();
7583 sv = newSVpvn((char*)foldbuf, foldlen);
7585 av_push(unicode_alternate, sv);
7589 /* If folding and the value is one of the Greek
7590 * sigmas insert a few more sigmas to make the
7591 * folding rules of the sigmas to work right.
7592 * Note that not all the possible combinations
7593 * are handled here: some of them are handled
7594 * by the standard folding rules, and some of
7595 * them (literal or EXACTF cases) are handled
7596 * during runtime in regexec.c:S_find_byclass(). */
7597 if (value == UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA) {
7598 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7599 (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA);
7600 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7601 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
7603 else if (value == UNICODE_GREEK_CAPITAL_LETTER_SIGMA)
7604 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7605 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
7610 literal_endpoint = 0;
7614 range = 0; /* this range (if it was one) is done now */
7618 ANYOF_FLAGS(ret) |= ANYOF_LARGE;
7620 RExC_size += ANYOF_CLASS_ADD_SKIP;
7622 RExC_emit += ANYOF_CLASS_ADD_SKIP;
7628 /****** !SIZE_ONLY AFTER HERE *********/
7630 if( stored == 1 && value < 256
7631 && !( ANYOF_FLAGS(ret) & ( ANYOF_FLAGS_ALL ^ ANYOF_FOLD ) )
7633 /* optimize single char class to an EXACT node
7634 but *only* when its not a UTF/high char */
7635 const char * cur_parse= RExC_parse;
7636 RExC_emit = (regnode *)orig_emit;
7637 RExC_parse = (char *)orig_parse;
7638 ret = reg_node(pRExC_state,
7639 (U8)((ANYOF_FLAGS(ret) & ANYOF_FOLD) ? EXACTF : EXACT));
7640 RExC_parse = (char *)cur_parse;
7641 *STRING(ret)= (char)value;
7643 RExC_emit += STR_SZ(1);
7646 /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
7647 if ( /* If the only flag is folding (plus possibly inversion). */
7648 ((ANYOF_FLAGS(ret) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD)
7650 for (value = 0; value < 256; ++value) {
7651 if (ANYOF_BITMAP_TEST(ret, value)) {
7652 UV fold = PL_fold[value];
7655 ANYOF_BITMAP_SET(ret, fold);
7658 ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
7661 /* optimize inverted simple patterns (e.g. [^a-z]) */
7662 if (optimize_invert &&
7663 /* If the only flag is inversion. */
7664 (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
7665 for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
7666 ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
7667 ANYOF_FLAGS(ret) = ANYOF_UNICODE_ALL;
7670 AV * const av = newAV();
7672 /* The 0th element stores the character class description
7673 * in its textual form: used later (regexec.c:Perl_regclass_swash())
7674 * to initialize the appropriate swash (which gets stored in
7675 * the 1st element), and also useful for dumping the regnode.
7676 * The 2nd element stores the multicharacter foldings,
7677 * used later (regexec.c:S_reginclass()). */
7678 av_store(av, 0, listsv);
7679 av_store(av, 1, NULL);
7680 av_store(av, 2, (SV*)unicode_alternate);
7681 rv = newRV_noinc((SV*)av);
7682 n = add_data(pRExC_state, 1, "s");
7683 RExC_rx->data->data[n] = (void*)rv;
7690 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
7692 char* const retval = RExC_parse++;
7695 if (*RExC_parse == '(' && RExC_parse[1] == '?' &&
7696 RExC_parse[2] == '#') {
7697 while (*RExC_parse != ')') {
7698 if (RExC_parse == RExC_end)
7699 FAIL("Sequence (?#... not terminated");
7705 if (RExC_flags & PMf_EXTENDED) {
7706 if (isSPACE(*RExC_parse)) {
7710 else if (*RExC_parse == '#') {
7711 while (RExC_parse < RExC_end)
7712 if (*RExC_parse++ == '\n') break;
7721 - reg_node - emit a node
7723 STATIC regnode * /* Location. */
7724 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
7727 register regnode *ptr;
7728 regnode * const ret = RExC_emit;
7729 GET_RE_DEBUG_FLAGS_DECL;
7732 SIZE_ALIGN(RExC_size);
7737 if (OP(RExC_emit) == 255)
7738 Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %s: %d ",
7739 reg_name[op], OP(RExC_emit));
7741 NODE_ALIGN_FILL(ret);
7743 FILL_ADVANCE_NODE(ptr, op);
7744 if (RExC_offsets) { /* MJD */
7745 MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n",
7746 "reg_node", __LINE__,
7748 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0]
7749 ? "Overwriting end of array!\n" : "OK",
7750 (UV)(RExC_emit - RExC_emit_start),
7751 (UV)(RExC_parse - RExC_start),
7752 (UV)RExC_offsets[0]));
7753 Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
7761 - reganode - emit a node with an argument
7763 STATIC regnode * /* Location. */
7764 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
7767 register regnode *ptr;
7768 regnode * const ret = RExC_emit;
7769 GET_RE_DEBUG_FLAGS_DECL;
7772 SIZE_ALIGN(RExC_size);
7777 assert(2==regarglen[op]+1);
7779 Anything larger than this has to allocate the extra amount.
7780 If we changed this to be:
7782 RExC_size += (1 + regarglen[op]);
7784 then it wouldn't matter. Its not clear what side effect
7785 might come from that so its not done so far.
7791 if (OP(RExC_emit) == 255)
7792 Perl_croak(aTHX_ "panic: reganode overwriting end of allocated program space");
7794 NODE_ALIGN_FILL(ret);
7796 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
7797 if (RExC_offsets) { /* MJD */
7798 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
7802 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ?
7803 "Overwriting end of array!\n" : "OK",
7804 (UV)(RExC_emit - RExC_emit_start),
7805 (UV)(RExC_parse - RExC_start),
7806 (UV)RExC_offsets[0]));
7807 Set_Cur_Node_Offset;
7815 - reguni - emit (if appropriate) a Unicode character
7818 S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
7821 return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
7825 - reginsert - insert an operator in front of already-emitted operand
7827 * Means relocating the operand.
7830 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
7833 register regnode *src;
7834 register regnode *dst;
7835 register regnode *place;
7836 const int offset = regarglen[(U8)op];
7837 const int size = NODE_STEP_REGNODE + offset;
7838 GET_RE_DEBUG_FLAGS_DECL;
7839 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
7840 DEBUG_PARSE_FMT("inst"," - %s",reg_name[op]);
7849 if (RExC_open_parens) {
7851 DEBUG_PARSE_FMT("inst"," - %"IVdf, (IV)RExC_npar);
7852 for ( paren=0 ; paren < RExC_npar ; paren++ ) {
7853 if ( RExC_open_parens[paren] >= opnd ) {
7854 DEBUG_PARSE_FMT("open"," - %d",size);
7855 RExC_open_parens[paren] += size;
7857 DEBUG_PARSE_FMT("open"," - %s","ok");
7859 if ( RExC_close_parens[paren] >= opnd ) {
7860 DEBUG_PARSE_FMT("close"," - %d",size);
7861 RExC_close_parens[paren] += size;
7863 DEBUG_PARSE_FMT("close"," - %s","ok");
7868 while (src > opnd) {
7869 StructCopy(--src, --dst, regnode);
7870 if (RExC_offsets) { /* MJD 20010112 */
7871 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
7875 (UV)(dst - RExC_emit_start) > RExC_offsets[0]
7876 ? "Overwriting end of array!\n" : "OK",
7877 (UV)(src - RExC_emit_start),
7878 (UV)(dst - RExC_emit_start),
7879 (UV)RExC_offsets[0]));
7880 Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
7881 Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
7886 place = opnd; /* Op node, where operand used to be. */
7887 if (RExC_offsets) { /* MJD */
7888 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
7892 (UV)(place - RExC_emit_start) > RExC_offsets[0]
7893 ? "Overwriting end of array!\n" : "OK",
7894 (UV)(place - RExC_emit_start),
7895 (UV)(RExC_parse - RExC_start),
7896 (UV)RExC_offsets[0]));
7897 Set_Node_Offset(place, RExC_parse);
7898 Set_Node_Length(place, 1);
7900 src = NEXTOPER(place);
7901 FILL_ADVANCE_NODE(place, op);
7902 Zero(src, offset, regnode);
7906 - regtail - set the next-pointer at the end of a node chain of p to val.
7907 - SEE ALSO: regtail_study
7909 /* TODO: All three parms should be const */
7911 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
7914 register regnode *scan;
7915 GET_RE_DEBUG_FLAGS_DECL;
7917 PERL_UNUSED_ARG(depth);
7923 /* Find last node. */
7926 regnode * const temp = regnext(scan);
7928 SV * const mysv=sv_newmortal();
7929 DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
7930 regprop(RExC_rx, mysv, scan);
7931 PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
7932 SvPV_nolen_const(mysv), REG_NODE_NUM(scan),
7933 (temp == NULL ? "->" : ""),
7934 (temp == NULL ? reg_name[OP(val)] : "")
7942 if (reg_off_by_arg[OP(scan)]) {
7943 ARG_SET(scan, val - scan);
7946 NEXT_OFF(scan) = val - scan;
7952 - regtail_study - set the next-pointer at the end of a node chain of p to val.
7953 - Look for optimizable sequences at the same time.
7954 - currently only looks for EXACT chains.
7956 This is expermental code. The idea is to use this routine to perform
7957 in place optimizations on branches and groups as they are constructed,
7958 with the long term intention of removing optimization from study_chunk so
7959 that it is purely analytical.
7961 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
7962 to control which is which.
7965 /* TODO: All four parms should be const */
7968 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
7971 register regnode *scan;
7973 #ifdef EXPERIMENTAL_INPLACESCAN
7977 GET_RE_DEBUG_FLAGS_DECL;
7983 /* Find last node. */
7987 regnode * const temp = regnext(scan);
7988 #ifdef EXPERIMENTAL_INPLACESCAN
7989 if (PL_regkind[OP(scan)] == EXACT)
7990 if (join_exact(pRExC_state,scan,&min,1,val,depth+1))
7998 if( exact == PSEUDO )
8000 else if ( exact != OP(scan) )
8009 SV * const mysv=sv_newmortal();
8010 DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
8011 regprop(RExC_rx, mysv, scan);
8012 PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
8013 SvPV_nolen_const(mysv),
8022 SV * const mysv_val=sv_newmortal();
8023 DEBUG_PARSE_MSG("");
8024 regprop(RExC_rx, mysv_val, val);
8025 PerlIO_printf(Perl_debug_log, "~ attach to %s (%d) offset to %d\n",
8026 SvPV_nolen_const(mysv_val),
8031 if (reg_off_by_arg[OP(scan)]) {
8032 ARG_SET(scan, val - scan);
8035 NEXT_OFF(scan) = val - scan;
8043 - regcurly - a little FSA that accepts {\d+,?\d*}
8046 S_regcurly(register const char *s)
8065 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
8068 Perl_regdump(pTHX_ const regexp *r)
8072 SV * const sv = sv_newmortal();
8073 SV *dsv= sv_newmortal();
8075 (void)dumpuntil(r, r->program, r->program + 1, NULL, NULL, sv, 0, 0);
8077 /* Header fields of interest. */
8078 if (r->anchored_substr) {
8079 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr),
8080 RE_SV_DUMPLEN(r->anchored_substr), 30);
8081 PerlIO_printf(Perl_debug_log,
8082 "anchored %s%s at %"IVdf" ",
8083 s, RE_SV_TAIL(r->anchored_substr),
8084 (IV)r->anchored_offset);
8085 } else if (r->anchored_utf8) {
8086 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8),
8087 RE_SV_DUMPLEN(r->anchored_utf8), 30);
8088 PerlIO_printf(Perl_debug_log,
8089 "anchored utf8 %s%s at %"IVdf" ",
8090 s, RE_SV_TAIL(r->anchored_utf8),
8091 (IV)r->anchored_offset);
8093 if (r->float_substr) {
8094 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr),
8095 RE_SV_DUMPLEN(r->float_substr), 30);
8096 PerlIO_printf(Perl_debug_log,
8097 "floating %s%s at %"IVdf"..%"UVuf" ",
8098 s, RE_SV_TAIL(r->float_substr),
8099 (IV)r->float_min_offset, (UV)r->float_max_offset);
8100 } else if (r->float_utf8) {
8101 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8),
8102 RE_SV_DUMPLEN(r->float_utf8), 30);
8103 PerlIO_printf(Perl_debug_log,
8104 "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
8105 s, RE_SV_TAIL(r->float_utf8),
8106 (IV)r->float_min_offset, (UV)r->float_max_offset);
8108 if (r->check_substr || r->check_utf8)
8109 PerlIO_printf(Perl_debug_log,
8111 (r->check_substr == r->float_substr
8112 && r->check_utf8 == r->float_utf8
8113 ? "(checking floating" : "(checking anchored"));
8114 if (r->reganch & ROPT_NOSCAN)
8115 PerlIO_printf(Perl_debug_log, " noscan");
8116 if (r->reganch & ROPT_CHECK_ALL)
8117 PerlIO_printf(Perl_debug_log, " isall");
8118 if (r->check_substr || r->check_utf8)
8119 PerlIO_printf(Perl_debug_log, ") ");
8121 if (r->regstclass) {
8122 regprop(r, sv, r->regstclass);
8123 PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
8125 if (r->reganch & ROPT_ANCH) {
8126 PerlIO_printf(Perl_debug_log, "anchored");
8127 if (r->reganch & ROPT_ANCH_BOL)
8128 PerlIO_printf(Perl_debug_log, "(BOL)");
8129 if (r->reganch & ROPT_ANCH_MBOL)
8130 PerlIO_printf(Perl_debug_log, "(MBOL)");
8131 if (r->reganch & ROPT_ANCH_SBOL)
8132 PerlIO_printf(Perl_debug_log, "(SBOL)");
8133 if (r->reganch & ROPT_ANCH_GPOS)
8134 PerlIO_printf(Perl_debug_log, "(GPOS)");
8135 PerlIO_putc(Perl_debug_log, ' ');
8137 if (r->reganch & ROPT_GPOS_SEEN)
8138 PerlIO_printf(Perl_debug_log, "GPOS ");
8139 if (r->reganch & ROPT_SKIP)
8140 PerlIO_printf(Perl_debug_log, "plus ");
8141 if (r->reganch & ROPT_IMPLICIT)
8142 PerlIO_printf(Perl_debug_log, "implicit ");
8143 PerlIO_printf(Perl_debug_log, "minlen %ld ", (long) r->minlen);
8144 if (r->reganch & ROPT_EVAL_SEEN)
8145 PerlIO_printf(Perl_debug_log, "with eval ");
8146 PerlIO_printf(Perl_debug_log, "\n");
8148 PERL_UNUSED_CONTEXT;
8150 #endif /* DEBUGGING */
8154 - regprop - printable representation of opcode
8157 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
8162 GET_RE_DEBUG_FLAGS_DECL;
8164 sv_setpvn(sv, "", 0);
8166 if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */
8167 /* It would be nice to FAIL() here, but this may be called from
8168 regexec.c, and it would be hard to supply pRExC_state. */
8169 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
8170 sv_catpv(sv, reg_name[OP(o)]); /* Take off const! */
8172 k = PL_regkind[OP(o)];
8175 SV * const dsv = sv_2mortal(newSVpvs(""));
8176 /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
8177 * is a crude hack but it may be the best for now since
8178 * we have no flag "this EXACTish node was UTF-8"
8180 const char * const s =
8181 pv_pretty(dsv, STRING(o), STR_LEN(o), 60,
8182 PL_colors[0], PL_colors[1],
8183 PERL_PV_ESCAPE_UNI_DETECT |
8184 PERL_PV_PRETTY_ELIPSES |
8187 Perl_sv_catpvf(aTHX_ sv, " %s", s );
8188 } else if (k == TRIE) {
8189 /* print the details of the trie in dumpuntil instead, as
8190 * prog->data isn't available here */
8191 const char op = OP(o);
8192 const I32 n = ARG(o);
8193 const reg_ac_data * const ac = IS_TRIE_AC(op) ?
8194 (reg_ac_data *)prog->data->data[n] :
8196 const reg_trie_data * const trie = !IS_TRIE_AC(op) ?
8197 (reg_trie_data*)prog->data->data[n] :
8200 Perl_sv_catpvf(aTHX_ sv, "-%s",reg_name[o->flags]);
8201 DEBUG_TRIE_COMPILE_r(
8202 Perl_sv_catpvf(aTHX_ sv,
8203 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
8204 (UV)trie->startstate,
8205 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
8206 (UV)trie->wordcount,
8209 (UV)TRIE_CHARCOUNT(trie),
8210 (UV)trie->uniquecharcount
8213 if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
8215 int rangestart = -1;
8216 U8* bitmap = IS_ANYOF_TRIE(op) ? (U8*)ANYOF_BITMAP(o) : (U8*)TRIE_BITMAP(trie);
8217 Perl_sv_catpvf(aTHX_ sv, "[");
8218 for (i = 0; i <= 256; i++) {
8219 if (i < 256 && BITMAP_TEST(bitmap,i)) {
8220 if (rangestart == -1)
8222 } else if (rangestart != -1) {
8223 if (i <= rangestart + 3)
8224 for (; rangestart < i; rangestart++)
8225 put_byte(sv, rangestart);
8227 put_byte(sv, rangestart);
8229 put_byte(sv, i - 1);
8234 Perl_sv_catpvf(aTHX_ sv, "]");
8237 } else if (k == CURLY) {
8238 if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
8239 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
8240 Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
8242 else if (k == WHILEM && o->flags) /* Ordinal/of */
8243 Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
8244 else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP || OP(o)==ACCEPT)
8245 Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o)); /* Parenth number */
8246 else if (k == GOSUB)
8247 Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
8248 else if (k == VERB) {
8250 Perl_sv_catpvf(aTHX_ sv, ":%"SVf,
8251 (SV*)prog->data->data[ ARG( o ) ]);
8252 } else if (k == LOGICAL)
8253 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* 2: embedded, otherwise 1 */
8254 else if (k == ANYOF) {
8255 int i, rangestart = -1;
8256 const U8 flags = ANYOF_FLAGS(o);
8258 /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
8259 static const char * const anyofs[] = {
8292 if (flags & ANYOF_LOCALE)
8293 sv_catpvs(sv, "{loc}");
8294 if (flags & ANYOF_FOLD)
8295 sv_catpvs(sv, "{i}");
8296 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
8297 if (flags & ANYOF_INVERT)
8299 for (i = 0; i <= 256; i++) {
8300 if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
8301 if (rangestart == -1)
8303 } else if (rangestart != -1) {
8304 if (i <= rangestart + 3)
8305 for (; rangestart < i; rangestart++)
8306 put_byte(sv, rangestart);
8308 put_byte(sv, rangestart);
8310 put_byte(sv, i - 1);
8316 if (o->flags & ANYOF_CLASS)
8317 for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++)
8318 if (ANYOF_CLASS_TEST(o,i))
8319 sv_catpv(sv, anyofs[i]);
8321 if (flags & ANYOF_UNICODE)
8322 sv_catpvs(sv, "{unicode}");
8323 else if (flags & ANYOF_UNICODE_ALL)
8324 sv_catpvs(sv, "{unicode_all}");
8328 SV * const sw = regclass_swash(prog, o, FALSE, &lv, 0);
8332 U8 s[UTF8_MAXBYTES_CASE+1];
8334 for (i = 0; i <= 256; i++) { /* just the first 256 */
8335 uvchr_to_utf8(s, i);
8337 if (i < 256 && swash_fetch(sw, s, TRUE)) {
8338 if (rangestart == -1)
8340 } else if (rangestart != -1) {
8341 if (i <= rangestart + 3)
8342 for (; rangestart < i; rangestart++) {
8343 const U8 * const e = uvchr_to_utf8(s,rangestart);
8345 for(p = s; p < e; p++)
8349 const U8 *e = uvchr_to_utf8(s,rangestart);
8351 for (p = s; p < e; p++)
8354 e = uvchr_to_utf8(s, i-1);
8355 for (p = s; p < e; p++)
8362 sv_catpvs(sv, "..."); /* et cetera */
8366 char *s = savesvpv(lv);
8367 char * const origs = s;
8369 while (*s && *s != '\n')
8373 const char * const t = ++s;
8391 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
8393 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
8394 Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
8396 PERL_UNUSED_CONTEXT;
8397 PERL_UNUSED_ARG(sv);
8399 PERL_UNUSED_ARG(prog);
8400 #endif /* DEBUGGING */
8404 Perl_re_intuit_string(pTHX_ regexp *prog)
8405 { /* Assume that RE_INTUIT is set */
8407 GET_RE_DEBUG_FLAGS_DECL;
8408 PERL_UNUSED_CONTEXT;
8412 const char * const s = SvPV_nolen_const(prog->check_substr
8413 ? prog->check_substr : prog->check_utf8);
8415 if (!PL_colorset) reginitcolors();
8416 PerlIO_printf(Perl_debug_log,
8417 "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
8419 prog->check_substr ? "" : "utf8 ",
8420 PL_colors[5],PL_colors[0],
8423 (strlen(s) > 60 ? "..." : ""));
8426 return prog->check_substr ? prog->check_substr : prog->check_utf8;
8430 pregfree - free a regexp
8432 See regdupe below if you change anything here.
8436 Perl_pregfree(pTHX_ struct regexp *r)
8440 GET_RE_DEBUG_FLAGS_DECL;
8442 if (!r || (--r->refcnt > 0))
8448 SV *dsv= sv_newmortal();
8449 RE_PV_QUOTED_DECL(s, (r->reganch & ROPT_UTF8),
8450 dsv, r->precomp, r->prelen, 60);
8451 PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n",
8452 PL_colors[4],PL_colors[5],s);
8456 /* gcov results gave these as non-null 100% of the time, so there's no
8457 optimisation in checking them before calling Safefree */
8458 Safefree(r->precomp);
8459 Safefree(r->offsets); /* 20010421 MJD */
8460 RX_MATCH_COPY_FREE(r);
8461 #ifdef PERL_OLD_COPY_ON_WRITE
8463 SvREFCNT_dec(r->saved_copy);
8466 if (r->anchored_substr)
8467 SvREFCNT_dec(r->anchored_substr);
8468 if (r->anchored_utf8)
8469 SvREFCNT_dec(r->anchored_utf8);
8470 if (r->float_substr)
8471 SvREFCNT_dec(r->float_substr);
8473 SvREFCNT_dec(r->float_utf8);
8474 Safefree(r->substrs);
8477 SvREFCNT_dec(r->paren_names);
8479 int n = r->data->count;
8480 PAD* new_comppad = NULL;
8485 /* If you add a ->what type here, update the comment in regcomp.h */
8486 switch (r->data->what[n]) {
8489 SvREFCNT_dec((SV*)r->data->data[n]);
8492 Safefree(r->data->data[n]);
8495 new_comppad = (AV*)r->data->data[n];
8498 if (new_comppad == NULL)
8499 Perl_croak(aTHX_ "panic: pregfree comppad");
8500 PAD_SAVE_LOCAL(old_comppad,
8501 /* Watch out for global destruction's random ordering. */
8502 (SvTYPE(new_comppad) == SVt_PVAV) ? new_comppad : NULL
8505 refcnt = OpREFCNT_dec((OP_4tree*)r->data->data[n]);
8508 op_free((OP_4tree*)r->data->data[n]);
8510 PAD_RESTORE_LOCAL(old_comppad);
8511 SvREFCNT_dec((SV*)new_comppad);
8517 { /* Aho Corasick add-on structure for a trie node.
8518 Used in stclass optimization only */
8520 reg_ac_data *aho=(reg_ac_data*)r->data->data[n];
8522 refcount = --aho->refcount;
8525 Safefree(aho->states);
8526 Safefree(aho->fail);
8527 aho->trie=NULL; /* not necessary to free this as it is
8528 handled by the 't' case */
8529 Safefree(r->data->data[n]); /* do this last!!!! */
8530 Safefree(r->regstclass);
8536 /* trie structure. */
8538 reg_trie_data *trie=(reg_trie_data*)r->data->data[n];
8540 refcount = --trie->refcount;
8543 Safefree(trie->charmap);
8544 if (trie->widecharmap)
8545 SvREFCNT_dec((SV*)trie->widecharmap);
8546 Safefree(trie->states);
8547 Safefree(trie->trans);
8549 Safefree(trie->bitmap);
8551 Safefree(trie->wordlen);
8553 Safefree(trie->jump);
8555 Safefree(trie->nextword);
8558 SvREFCNT_dec((SV*)trie->words);
8559 if (trie->revcharmap)
8560 SvREFCNT_dec((SV*)trie->revcharmap);
8562 Safefree(r->data->data[n]); /* do this last!!!! */
8567 Perl_croak(aTHX_ "panic: regfree data code '%c'", r->data->what[n]);
8570 Safefree(r->data->what);
8573 Safefree(r->startp);
8576 Safefree(r->swap->startp);
8577 Safefree(r->swap->endp);
8583 #define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
8584 #define av_dup_inc(s,t) (AV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8585 #define hv_dup_inc(s,t) (HV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8586 #define SAVEPVN(p,n) ((p) ? savepvn(p,n) : NULL)
8589 regdupe - duplicate a regexp.
8591 This routine is called by sv.c's re_dup and is expected to clone a
8592 given regexp structure. It is a no-op when not under USE_ITHREADS.
8593 (Originally this *was* re_dup() for change history see sv.c)
8595 See pregfree() above if you change anything here.
8597 #if defined(USE_ITHREADS)
8599 Perl_regdupe(pTHX_ const regexp *r, CLONE_PARAMS *param)
8604 struct reg_substr_datum *s;
8607 return (REGEXP *)NULL;
8609 if ((ret = (REGEXP *)ptr_table_fetch(PL_ptr_table, r)))
8612 len = r->offsets[0];
8613 npar = r->nparens+1;
8615 Newxc(ret, sizeof(regexp) + (len+1)*sizeof(regnode), char, regexp);
8616 Copy(r->program, ret->program, len+1, regnode);
8618 Newx(ret->startp, npar, I32);
8619 Copy(r->startp, ret->startp, npar, I32);
8620 Newx(ret->endp, npar, I32);
8621 Copy(r->startp, ret->startp, npar, I32);
8623 Newx(ret->swap, 1, regexp_paren_ofs);
8624 /* no need to copy these */
8625 Newx(ret->swap->startp, npar, I32);
8626 Newx(ret->swap->endp, npar, I32);
8631 Newx(ret->substrs, 1, struct reg_substr_data);
8632 for (s = ret->substrs->data, i = 0; i < 3; i++, s++) {
8633 s->min_offset = r->substrs->data[i].min_offset;
8634 s->max_offset = r->substrs->data[i].max_offset;
8635 s->end_shift = r->substrs->data[i].end_shift;
8636 s->substr = sv_dup_inc(r->substrs->data[i].substr, param);
8637 s->utf8_substr = sv_dup_inc(r->substrs->data[i].utf8_substr, param);
8640 ret->regstclass = NULL;
8643 const int count = r->data->count;
8646 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
8647 char, struct reg_data);
8648 Newx(d->what, count, U8);
8651 for (i = 0; i < count; i++) {
8652 d->what[i] = r->data->what[i];
8653 switch (d->what[i]) {
8654 /* legal options are one of: sSfpont
8655 see also regcomp.h and pregfree() */
8658 d->data[i] = sv_dup_inc((SV *)r->data->data[i], param);
8661 d->data[i] = av_dup_inc((AV *)r->data->data[i], param);
8664 /* This is cheating. */
8665 Newx(d->data[i], 1, struct regnode_charclass_class);
8666 StructCopy(r->data->data[i], d->data[i],
8667 struct regnode_charclass_class);
8668 ret->regstclass = (regnode*)d->data[i];
8671 /* Compiled op trees are readonly, and can thus be
8672 shared without duplication. */
8674 d->data[i] = (void*)OpREFCNT_inc((OP*)r->data->data[i]);
8678 d->data[i] = r->data->data[i];
8681 d->data[i] = r->data->data[i];
8683 ((reg_trie_data*)d->data[i])->refcount++;
8687 d->data[i] = r->data->data[i];
8689 ((reg_ac_data*)d->data[i])->refcount++;
8691 /* Trie stclasses are readonly and can thus be shared
8692 * without duplication. We free the stclass in pregfree
8693 * when the corresponding reg_ac_data struct is freed.
8695 ret->regstclass= r->regstclass;
8698 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", r->data->what[i]);
8707 Newx(ret->offsets, 2*len+1, U32);
8708 Copy(r->offsets, ret->offsets, 2*len+1, U32);
8710 ret->precomp = SAVEPVN(r->precomp, r->prelen);
8711 ret->refcnt = r->refcnt;
8712 ret->minlen = r->minlen;
8713 ret->minlenret = r->minlenret;
8714 ret->prelen = r->prelen;
8715 ret->nparens = r->nparens;
8716 ret->lastparen = r->lastparen;
8717 ret->lastcloseparen = r->lastcloseparen;
8718 ret->reganch = r->reganch;
8720 ret->sublen = r->sublen;
8722 ret->engine = r->engine;
8724 ret->paren_names = hv_dup_inc(r->paren_names, param);
8726 if (RX_MATCH_COPIED(ret))
8727 ret->subbeg = SAVEPVN(r->subbeg, r->sublen);
8730 #ifdef PERL_OLD_COPY_ON_WRITE
8731 ret->saved_copy = NULL;
8734 ptr_table_store(PL_ptr_table, r, ret);
8742 converts a regexp embedded in a MAGIC struct to its stringified form,
8743 caching the converted form in the struct and returns the cached
8746 If lp is nonnull then it is used to return the length of the
8749 If flags is nonnull and the returned string contains UTF8 then
8750 (flags & 1) will be true.
8752 If haseval is nonnull then it is used to return whether the pattern
8755 Normally called via macro:
8757 CALLREG_STRINGIFY(mg,0,0);
8761 CALLREG_AS_STR(mg,lp,flags,haseval)
8763 See sv_2pv_flags() in sv.c for an example of internal usage.
8768 Perl_reg_stringify(pTHX_ MAGIC *mg, STRLEN *lp, U32 *flags, I32 *haseval ) {
8770 const regexp * const re = (regexp *)mg->mg_obj;
8773 const char *fptr = "msix";
8778 bool need_newline = 0;
8779 U16 reganch = (U16)((re->reganch & PMf_COMPILETIME) >> 12);
8781 while((ch = *fptr++)) {
8783 reflags[left++] = ch;
8786 reflags[right--] = ch;
8791 reflags[left] = '-';
8795 mg->mg_len = re->prelen + 4 + left;
8797 * If /x was used, we have to worry about a regex ending with a
8798 * comment later being embedded within another regex. If so, we don't
8799 * want this regex's "commentization" to leak out to the right part of
8800 * the enclosing regex, we must cap it with a newline.
8802 * So, if /x was used, we scan backwards from the end of the regex. If
8803 * we find a '#' before we find a newline, we need to add a newline
8804 * ourself. If we find a '\n' first (or if we don't find '#' or '\n'),
8805 * we don't need to add anything. -jfriedl
8807 if (PMf_EXTENDED & re->reganch) {
8808 const char *endptr = re->precomp + re->prelen;
8809 while (endptr >= re->precomp) {
8810 const char c = *(endptr--);
8812 break; /* don't need another */
8814 /* we end while in a comment, so we need a newline */
8815 mg->mg_len++; /* save space for it */
8816 need_newline = 1; /* note to add it */
8822 Newx(mg->mg_ptr, mg->mg_len + 1 + left, char);
8823 mg->mg_ptr[0] = '(';
8824 mg->mg_ptr[1] = '?';
8825 Copy(reflags, mg->mg_ptr+2, left, char);
8826 *(mg->mg_ptr+left+2) = ':';
8827 Copy(re->precomp, mg->mg_ptr+3+left, re->prelen, char);
8829 mg->mg_ptr[mg->mg_len - 2] = '\n';
8830 mg->mg_ptr[mg->mg_len - 1] = ')';
8831 mg->mg_ptr[mg->mg_len] = 0;
8834 *haseval = re->program[0].next_off;
8836 *flags = ((re->reganch & ROPT_UTF8) ? 1 : 0);
8844 #ifndef PERL_IN_XSUB_RE
8846 - regnext - dig the "next" pointer out of a node
8849 Perl_regnext(pTHX_ register regnode *p)
8852 register I32 offset;
8854 if (p == &PL_regdummy)
8857 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
8866 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
8869 STRLEN l1 = strlen(pat1);
8870 STRLEN l2 = strlen(pat2);
8873 const char *message;
8879 Copy(pat1, buf, l1 , char);
8880 Copy(pat2, buf + l1, l2 , char);
8881 buf[l1 + l2] = '\n';
8882 buf[l1 + l2 + 1] = '\0';
8884 /* ANSI variant takes additional second argument */
8885 va_start(args, pat2);
8889 msv = vmess(buf, &args);
8891 message = SvPV_const(msv,l1);
8894 Copy(message, buf, l1 , char);
8895 buf[l1-1] = '\0'; /* Overwrite \n */
8896 Perl_croak(aTHX_ "%s", buf);
8899 /* XXX Here's a total kludge. But we need to re-enter for swash routines. */
8901 #ifndef PERL_IN_XSUB_RE
8903 Perl_save_re_context(pTHX)
8907 struct re_save_state *state;
8909 SAVEVPTR(PL_curcop);
8910 SSGROW(SAVESTACK_ALLOC_FOR_RE_SAVE_STATE + 1);
8912 state = (struct re_save_state *)(PL_savestack + PL_savestack_ix);
8913 PL_savestack_ix += SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
8914 SSPUSHINT(SAVEt_RE_STATE);
8916 Copy(&PL_reg_state, state, 1, struct re_save_state);
8918 PL_reg_start_tmp = 0;
8919 PL_reg_start_tmpl = 0;
8920 PL_reg_oldsaved = NULL;
8921 PL_reg_oldsavedlen = 0;
8923 PL_reg_leftiter = 0;
8924 PL_reg_poscache = NULL;
8925 PL_reg_poscache_size = 0;
8926 #ifdef PERL_OLD_COPY_ON_WRITE
8930 /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
8932 const REGEXP * const rx = PM_GETRE(PL_curpm);
8935 for (i = 1; i <= rx->nparens; i++) {
8936 char digits[TYPE_CHARS(long)];
8937 const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
8938 GV *const *const gvp
8939 = (GV**)hv_fetch(PL_defstash, digits, len, 0);
8942 GV * const gv = *gvp;
8943 if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
8953 clear_re(pTHX_ void *r)
8956 ReREFCNT_dec((regexp *)r);
8962 S_put_byte(pTHX_ SV *sv, int c)
8964 if (isCNTRL(c) || c == 255 || !isPRINT(c))
8965 Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
8966 else if (c == '-' || c == ']' || c == '\\' || c == '^')
8967 Perl_sv_catpvf(aTHX_ sv, "\\%c", c);
8969 Perl_sv_catpvf(aTHX_ sv, "%c", c);
8973 #define CLEAR_OPTSTART \
8974 if (optstart) STMT_START { \
8975 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%d nodes)\n", node - optstart)); \
8979 #define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
8981 STATIC const regnode *
8982 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
8983 const regnode *last, const regnode *plast,
8984 SV* sv, I32 indent, U32 depth)
8987 register U8 op = PSEUDO; /* Arbitrary non-END op. */
8988 register const regnode *next;
8989 const regnode *optstart= NULL;
8990 GET_RE_DEBUG_FLAGS_DECL;
8992 #ifdef DEBUG_DUMPUNTIL
8993 PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
8994 last ? last-start : 0,plast ? plast-start : 0);
8997 if (plast && plast < last)
9000 while (PL_regkind[op] != END && (!last || node < last)) {
9001 /* While that wasn't END last time... */
9005 if (op == CLOSE || op == WHILEM)
9007 next = regnext((regnode *)node);
9010 if (OP(node) == OPTIMIZED) {
9011 if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
9018 regprop(r, sv, node);
9019 PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
9020 (int)(2*indent + 1), "", SvPVX_const(sv));
9022 if (OP(node) != OPTIMIZED) {
9023 if (next == NULL) /* Next ptr. */
9024 PerlIO_printf(Perl_debug_log, "(0)");
9025 else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
9026 PerlIO_printf(Perl_debug_log, "(FAIL)");
9028 PerlIO_printf(Perl_debug_log, "(%"IVdf")", (IV)(next - start));
9030 /*if (PL_regkind[(U8)op] != TRIE)*/
9031 (void)PerlIO_putc(Perl_debug_log, '\n');
9035 if (PL_regkind[(U8)op] == BRANCHJ) {
9038 register const regnode *nnode = (OP(next) == LONGJMP
9039 ? regnext((regnode *)next)
9041 if (last && nnode > last)
9043 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
9046 else if (PL_regkind[(U8)op] == BRANCH) {
9048 DUMPUNTIL(NEXTOPER(node), next);
9050 else if ( PL_regkind[(U8)op] == TRIE ) {
9051 const regnode *this_trie = node;
9052 const char op = OP(node);
9053 const I32 n = ARG(node);
9054 const reg_ac_data * const ac = op>=AHOCORASICK ?
9055 (reg_ac_data *)r->data->data[n] :
9057 const reg_trie_data * const trie = op<AHOCORASICK ?
9058 (reg_trie_data*)r->data->data[n] :
9060 const regnode *nextbranch= NULL;
9062 sv_setpvn(sv, "", 0);
9063 for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
9064 SV ** const elem_ptr = av_fetch(trie->words,word_idx,0);
9066 PerlIO_printf(Perl_debug_log, "%*s%s ",
9067 (int)(2*(indent+3)), "",
9068 elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
9069 PL_colors[0], PL_colors[1],
9070 (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
9071 PERL_PV_PRETTY_ELIPSES |
9077 U16 dist= trie->jump[word_idx+1];
9078 PerlIO_printf(Perl_debug_log, "(%u)\n",
9079 (dist ? this_trie + dist : next) - start);
9082 nextbranch= this_trie + trie->jump[0];
9083 DUMPUNTIL(this_trie + dist, nextbranch);
9085 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
9086 nextbranch= regnext((regnode *)nextbranch);
9088 PerlIO_printf(Perl_debug_log, "\n");
9091 if (last && next > last)
9096 else if ( op == CURLY ) { /* "next" might be very big: optimizer */
9097 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
9098 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
9100 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
9102 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
9104 else if ( op == PLUS || op == STAR) {
9105 DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
9107 else if (op == ANYOF) {
9108 /* arglen 1 + class block */
9109 node += 1 + ((ANYOF_FLAGS(node) & ANYOF_LARGE)
9110 ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
9111 node = NEXTOPER(node);
9113 else if (PL_regkind[(U8)op] == EXACT) {
9114 /* Literal string, where present. */
9115 node += NODE_SZ_STR(node) - 1;
9116 node = NEXTOPER(node);
9119 node = NEXTOPER(node);
9120 node += regarglen[(U8)op];
9122 if (op == CURLYX || op == OPEN)
9126 #ifdef DEBUG_DUMPUNTIL
9127 PerlIO_printf(Perl_debug_log, "--- %d\n",indent);
9132 #endif /* DEBUGGING */
9136 * c-indentation-style: bsd
9138 * indent-tabs-mode: t
9141 * ex: set ts=8 sts=4 sw=4 noet: