5 * "A fair jaw-cracker dwarf-language must be." --Samwise Gamgee
8 /* This file contains functions for compiling a regular expression. See
9 * also regexec.c which funnily enough, contains functions for executing
10 * a regular expression.
12 * This file is also copied at build time to ext/re/re_comp.c, where
13 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
14 * This causes the main functions to be compiled under new names and with
15 * debugging support added, which makes "use re 'debug'" work.
18 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
19 * confused with the original package (see point 3 below). Thanks, Henry!
22 /* Additional note: this code is very heavily munged from Henry's version
23 * in places. In some spots I've traded clarity for efficiency, so don't
24 * blame Henry for some of the lack of readability.
27 /* The names of the functions have been changed from regcomp and
28 * regexec to pregcomp and pregexec in order to avoid conflicts
29 * with the POSIX routines of the same names.
32 #ifdef PERL_EXT_RE_BUILD
37 * pregcomp and pregexec -- regsub and regerror are not used in perl
39 * Copyright (c) 1986 by University of Toronto.
40 * Written by Henry Spencer. Not derived from licensed software.
42 * Permission is granted to anyone to use this software for any
43 * purpose on any computer system, and to redistribute it freely,
44 * subject to the following restrictions:
46 * 1. The author is not responsible for the consequences of use of
47 * this software, no matter how awful, even if they arise
50 * 2. The origin of this software must not be misrepresented, either
51 * by explicit claim or by omission.
53 * 3. Altered versions must be plainly marked as such, and must not
54 * be misrepresented as being the original software.
57 **** Alterations to Henry's code are...
59 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
60 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, by Larry Wall and others
62 **** You may distribute under the terms of either the GNU General Public
63 **** License or the Artistic License, as specified in the README file.
66 * Beware that some of this code is subtly aware of the way operator
67 * precedence is structured in regular expressions. Serious changes in
68 * regular-expression syntax might require a total rethink.
71 #define PERL_IN_REGCOMP_C
74 #ifndef PERL_IN_XSUB_RE
79 #ifdef PERL_IN_XSUB_RE
90 # if defined(BUGGY_MSC6)
91 /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
92 # pragma optimize("a",off)
93 /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
94 # pragma optimize("w",on )
95 # endif /* BUGGY_MSC6 */
102 typedef struct RExC_state_t {
103 U32 flags; /* are we folding, multilining? */
104 char *precomp; /* uncompiled string. */
106 char *start; /* Start of input for compile */
107 char *end; /* End of input for compile */
108 char *parse; /* Input-scan pointer. */
109 I32 whilem_seen; /* number of WHILEM in this expr */
110 regnode *emit_start; /* Start of emitted-code area */
111 regnode *emit; /* Code-emit pointer; ®dummy = don't = compiling */
112 I32 naughty; /* How bad is this pattern? */
113 I32 sawback; /* Did we see \1, ...? */
115 I32 size; /* Code size. */
116 I32 npar; /* () count. */
120 regnode **open_parens; /* pointers to open parens */
121 regnode **close_parens; /* pointers to close parens */
122 regnode *opend; /* END node in program */
124 HV *charnames; /* cache of named sequences */
125 HV *paren_names; /* Paren names */
126 regnode **recurse; /* Recurse regops */
127 I32 recurse_count; /* Number of recurse regops */
129 char *starttry; /* -Dr: where regtry was called. */
130 #define RExC_starttry (pRExC_state->starttry)
133 const char *lastparse;
135 #define RExC_lastparse (pRExC_state->lastparse)
136 #define RExC_lastnum (pRExC_state->lastnum)
140 #define RExC_flags (pRExC_state->flags)
141 #define RExC_precomp (pRExC_state->precomp)
142 #define RExC_rx (pRExC_state->rx)
143 #define RExC_start (pRExC_state->start)
144 #define RExC_end (pRExC_state->end)
145 #define RExC_parse (pRExC_state->parse)
146 #define RExC_whilem_seen (pRExC_state->whilem_seen)
147 #define RExC_offsets (pRExC_state->rx->offsets) /* I am not like the others */
148 #define RExC_emit (pRExC_state->emit)
149 #define RExC_emit_start (pRExC_state->emit_start)
150 #define RExC_naughty (pRExC_state->naughty)
151 #define RExC_sawback (pRExC_state->sawback)
152 #define RExC_seen (pRExC_state->seen)
153 #define RExC_size (pRExC_state->size)
154 #define RExC_npar (pRExC_state->npar)
155 #define RExC_extralen (pRExC_state->extralen)
156 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
157 #define RExC_seen_evals (pRExC_state->seen_evals)
158 #define RExC_utf8 (pRExC_state->utf8)
159 #define RExC_charnames (pRExC_state->charnames)
160 #define RExC_open_parens (pRExC_state->open_parens)
161 #define RExC_close_parens (pRExC_state->close_parens)
162 #define RExC_opend (pRExC_state->opend)
163 #define RExC_paren_names (pRExC_state->paren_names)
164 #define RExC_recurse (pRExC_state->recurse)
165 #define RExC_recurse_count (pRExC_state->recurse_count)
167 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
168 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
169 ((*s) == '{' && regcurly(s)))
172 #undef SPSTART /* dratted cpp namespace... */
175 * Flags to be passed up and down.
177 #define WORST 0 /* Worst case. */
178 #define HASWIDTH 0x1 /* Known to match non-null strings. */
179 #define SIMPLE 0x2 /* Simple enough to be STAR/PLUS operand. */
180 #define SPSTART 0x4 /* Starts with * or +. */
181 #define TRYAGAIN 0x8 /* Weeded out a declaration. */
183 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
185 /* whether trie related optimizations are enabled */
186 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
187 #define TRIE_STUDY_OPT
188 #define FULL_TRIE_STUDY
194 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
195 #define PBITVAL(paren) (1 << ((paren) & 7))
196 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
197 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
198 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
201 /* About scan_data_t.
203 During optimisation we recurse through the regexp program performing
204 various inplace (keyhole style) optimisations. In addition study_chunk
205 and scan_commit populate this data structure with information about
206 what strings MUST appear in the pattern. We look for the longest
207 string that must appear for at a fixed location, and we look for the
208 longest string that may appear at a floating location. So for instance
213 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
214 strings (because they follow a .* construct). study_chunk will identify
215 both FOO and BAR as being the longest fixed and floating strings respectively.
217 The strings can be composites, for instance
221 will result in a composite fixed substring 'foo'.
223 For each string some basic information is maintained:
225 - offset or min_offset
226 This is the position the string must appear at, or not before.
227 It also implicitly (when combined with minlenp) tells us how many
228 character must match before the string we are searching.
229 Likewise when combined with minlenp and the length of the string
230 tells us how many characters must appear after the string we have
234 Only used for floating strings. This is the rightmost point that
235 the string can appear at. Ifset to I32 max it indicates that the
236 string can occur infinitely far to the right.
239 A pointer to the minimum length of the pattern that the string
240 was found inside. This is important as in the case of positive
241 lookahead or positive lookbehind we can have multiple patterns
246 The minimum length of the pattern overall is 3, the minimum length
247 of the lookahead part is 3, but the minimum length of the part that
248 will actually match is 1. So 'FOO's minimum length is 3, but the
249 minimum length for the F is 1. This is important as the minimum length
250 is used to determine offsets in front of and behind the string being
251 looked for. Since strings can be composites this is the length of the
252 pattern at the time it was commited with a scan_commit. Note that
253 the length is calculated by study_chunk, so that the minimum lengths
254 are not known until the full pattern has been compiled, thus the
255 pointer to the value.
259 In the case of lookbehind the string being searched for can be
260 offset past the start point of the final matching string.
261 If this value was just blithely removed from the min_offset it would
262 invalidate some of the calculations for how many chars must match
263 before or after (as they are derived from min_offset and minlen and
264 the length of the string being searched for).
265 When the final pattern is compiled and the data is moved from the
266 scan_data_t structure into the regexp structure the information
267 about lookbehind is factored in, with the information that would
268 have been lost precalculated in the end_shift field for the
271 The fields pos_min and pos_delta are used to store the minimum offset
272 and the delta to the maximum offset at the current point in the pattern.
276 typedef struct scan_data_t {
277 /*I32 len_min; unused */
278 /*I32 len_delta; unused */
282 I32 last_end; /* min value, <0 unless valid. */
285 SV **longest; /* Either &l_fixed, or &l_float. */
286 SV *longest_fixed; /* longest fixed string found in pattern */
287 I32 offset_fixed; /* offset where it starts */
288 I32 *minlen_fixed; /* pointer to the minlen relevent to the string */
289 I32 lookbehind_fixed; /* is the position of the string modfied by LB */
290 SV *longest_float; /* longest floating string found in pattern */
291 I32 offset_float_min; /* earliest point in string it can appear */
292 I32 offset_float_max; /* latest point in string it can appear */
293 I32 *minlen_float; /* pointer to the minlen relevent to the string */
294 I32 lookbehind_float; /* is the position of the string modified by LB */
298 struct regnode_charclass_class *start_class;
302 * Forward declarations for pregcomp()'s friends.
305 static const scan_data_t zero_scan_data =
306 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
308 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
309 #define SF_BEFORE_SEOL 0x0001
310 #define SF_BEFORE_MEOL 0x0002
311 #define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
312 #define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
315 # define SF_FIX_SHIFT_EOL (0+2)
316 # define SF_FL_SHIFT_EOL (0+4)
318 # define SF_FIX_SHIFT_EOL (+2)
319 # define SF_FL_SHIFT_EOL (+4)
322 #define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
323 #define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
325 #define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
326 #define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
327 #define SF_IS_INF 0x0040
328 #define SF_HAS_PAR 0x0080
329 #define SF_IN_PAR 0x0100
330 #define SF_HAS_EVAL 0x0200
331 #define SCF_DO_SUBSTR 0x0400
332 #define SCF_DO_STCLASS_AND 0x0800
333 #define SCF_DO_STCLASS_OR 0x1000
334 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
335 #define SCF_WHILEM_VISITED_POS 0x2000
337 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
340 #define UTF (RExC_utf8 != 0)
341 #define LOC ((RExC_flags & PMf_LOCALE) != 0)
342 #define FOLD ((RExC_flags & PMf_FOLD) != 0)
344 #define OOB_UNICODE 12345678
345 #define OOB_NAMEDCLASS -1
347 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
348 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
351 /* length of regex to show in messages that don't mark a position within */
352 #define RegexLengthToShowInErrorMessages 127
355 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
356 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
357 * op/pragma/warn/regcomp.
359 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
360 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
362 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
365 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
366 * arg. Show regex, up to a maximum length. If it's too long, chop and add
369 #define FAIL(msg) STMT_START { \
370 const char *ellipses = ""; \
371 IV len = RExC_end - RExC_precomp; \
374 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
375 if (len > RegexLengthToShowInErrorMessages) { \
376 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
377 len = RegexLengthToShowInErrorMessages - 10; \
380 Perl_croak(aTHX_ "%s in regex m/%.*s%s/", \
381 msg, (int)len, RExC_precomp, ellipses); \
385 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
387 #define Simple_vFAIL(m) STMT_START { \
388 const IV offset = RExC_parse - RExC_precomp; \
389 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
390 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
394 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
396 #define vFAIL(m) STMT_START { \
398 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
403 * Like Simple_vFAIL(), but accepts two arguments.
405 #define Simple_vFAIL2(m,a1) STMT_START { \
406 const IV offset = RExC_parse - RExC_precomp; \
407 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, \
408 (int)offset, RExC_precomp, RExC_precomp + offset); \
412 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
414 #define vFAIL2(m,a1) STMT_START { \
416 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
417 Simple_vFAIL2(m, a1); \
422 * Like Simple_vFAIL(), but accepts three arguments.
424 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
425 const IV offset = RExC_parse - RExC_precomp; \
426 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, \
427 (int)offset, RExC_precomp, RExC_precomp + offset); \
431 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
433 #define vFAIL3(m,a1,a2) STMT_START { \
435 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
436 Simple_vFAIL3(m, a1, a2); \
440 * Like Simple_vFAIL(), but accepts four arguments.
442 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
443 const IV offset = RExC_parse - RExC_precomp; \
444 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, \
445 (int)offset, RExC_precomp, RExC_precomp + offset); \
448 #define vWARN(loc,m) STMT_START { \
449 const IV offset = loc - RExC_precomp; \
450 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s" REPORT_LOCATION, \
451 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
454 #define vWARNdep(loc,m) STMT_START { \
455 const IV offset = loc - RExC_precomp; \
456 Perl_warner(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
457 "%s" REPORT_LOCATION, \
458 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
462 #define vWARN2(loc, m, a1) STMT_START { \
463 const IV offset = loc - RExC_precomp; \
464 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
465 a1, (int)offset, RExC_precomp, RExC_precomp + offset); \
468 #define vWARN3(loc, m, a1, a2) STMT_START { \
469 const IV offset = loc - RExC_precomp; \
470 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
471 a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
474 #define vWARN4(loc, m, a1, a2, a3) STMT_START { \
475 const IV offset = loc - RExC_precomp; \
476 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
477 a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
480 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START { \
481 const IV offset = loc - RExC_precomp; \
482 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
483 a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
487 /* Allow for side effects in s */
488 #define REGC(c,s) STMT_START { \
489 if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
492 /* Macros for recording node offsets. 20001227 mjd@plover.com
493 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
494 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
495 * Element 0 holds the number n.
496 * Position is 1 indexed.
499 #define Set_Node_Offset_To_R(node,byte) STMT_START { \
501 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
502 __LINE__, (node), (int)(byte))); \
504 Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
506 RExC_offsets[2*(node)-1] = (byte); \
511 #define Set_Node_Offset(node,byte) \
512 Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
513 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
515 #define Set_Node_Length_To_R(node,len) STMT_START { \
517 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
518 __LINE__, (int)(node), (int)(len))); \
520 Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
522 RExC_offsets[2*(node)] = (len); \
527 #define Set_Node_Length(node,len) \
528 Set_Node_Length_To_R((node)-RExC_emit_start, len)
529 #define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
530 #define Set_Node_Cur_Length(node) \
531 Set_Node_Length(node, RExC_parse - parse_start)
533 /* Get offsets and lengths */
534 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
535 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
537 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
538 Set_Node_Offset_To_R((node)-RExC_emit_start, (offset)); \
539 Set_Node_Length_To_R((node)-RExC_emit_start, (len)); \
543 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
544 #define EXPERIMENTAL_INPLACESCAN
547 #define DEBUG_STUDYDATA(data,depth) \
548 DEBUG_OPTIMISE_MORE_r(if(data){ \
549 PerlIO_printf(Perl_debug_log, \
550 "%*s"/* Len:%"IVdf"/%"IVdf" */" Pos:%"IVdf"/%"IVdf \
551 " Flags: %"IVdf" Whilem_c: %"IVdf" Lcp: %"IVdf" ", \
552 (int)(depth)*2, "", \
553 (IV)((data)->pos_min), \
554 (IV)((data)->pos_delta), \
555 (IV)((data)->flags), \
556 (IV)((data)->whilem_c), \
557 (IV)((data)->last_closep ? *((data)->last_closep) : -1) \
559 if ((data)->last_found) \
560 PerlIO_printf(Perl_debug_log, \
561 "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
562 " %sFloat: '%s' @ %"IVdf"/%"IVdf"", \
563 SvPVX_const((data)->last_found), \
564 (IV)((data)->last_end), \
565 (IV)((data)->last_start_min), \
566 (IV)((data)->last_start_max), \
567 ((data)->longest && \
568 (data)->longest==&((data)->longest_fixed)) ? "*" : "", \
569 SvPVX_const((data)->longest_fixed), \
570 (IV)((data)->offset_fixed), \
571 ((data)->longest && \
572 (data)->longest==&((data)->longest_float)) ? "*" : "", \
573 SvPVX_const((data)->longest_float), \
574 (IV)((data)->offset_float_min), \
575 (IV)((data)->offset_float_max) \
577 PerlIO_printf(Perl_debug_log,"\n"); \
580 static void clear_re(pTHX_ void *r);
582 /* Mark that we cannot extend a found fixed substring at this point.
583 Update the longest found anchored substring and the longest found
584 floating substrings if needed. */
587 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp)
589 const STRLEN l = CHR_SVLEN(data->last_found);
590 const STRLEN old_l = CHR_SVLEN(*data->longest);
591 GET_RE_DEBUG_FLAGS_DECL;
593 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
594 SvSetMagicSV(*data->longest, data->last_found);
595 if (*data->longest == data->longest_fixed) {
596 data->offset_fixed = l ? data->last_start_min : data->pos_min;
597 if (data->flags & SF_BEFORE_EOL)
599 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
601 data->flags &= ~SF_FIX_BEFORE_EOL;
602 data->minlen_fixed=minlenp;
603 data->lookbehind_fixed=0;
606 data->offset_float_min = l ? data->last_start_min : data->pos_min;
607 data->offset_float_max = (l
608 ? data->last_start_max
609 : data->pos_min + data->pos_delta);
610 if ((U32)data->offset_float_max > (U32)I32_MAX)
611 data->offset_float_max = I32_MAX;
612 if (data->flags & SF_BEFORE_EOL)
614 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
616 data->flags &= ~SF_FL_BEFORE_EOL;
617 data->minlen_float=minlenp;
618 data->lookbehind_float=0;
621 SvCUR_set(data->last_found, 0);
623 SV * const sv = data->last_found;
624 if (SvUTF8(sv) && SvMAGICAL(sv)) {
625 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
631 data->flags &= ~SF_BEFORE_EOL;
632 DEBUG_STUDYDATA(data,0);
635 /* Can match anything (initialization) */
637 S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
639 ANYOF_CLASS_ZERO(cl);
640 ANYOF_BITMAP_SETALL(cl);
641 cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL;
643 cl->flags |= ANYOF_LOCALE;
646 /* Can match anything (initialization) */
648 S_cl_is_anything(const struct regnode_charclass_class *cl)
652 for (value = 0; value <= ANYOF_MAX; value += 2)
653 if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
655 if (!(cl->flags & ANYOF_UNICODE_ALL))
657 if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
662 /* Can match anything (initialization) */
664 S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
666 Zero(cl, 1, struct regnode_charclass_class);
668 cl_anything(pRExC_state, cl);
672 S_cl_init_zero(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
674 Zero(cl, 1, struct regnode_charclass_class);
676 cl_anything(pRExC_state, cl);
678 cl->flags |= ANYOF_LOCALE;
681 /* 'And' a given class with another one. Can create false positives */
682 /* We assume that cl is not inverted */
684 S_cl_and(struct regnode_charclass_class *cl,
685 const struct regnode_charclass_class *and_with)
688 assert(and_with->type == ANYOF);
689 if (!(and_with->flags & ANYOF_CLASS)
690 && !(cl->flags & ANYOF_CLASS)
691 && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
692 && !(and_with->flags & ANYOF_FOLD)
693 && !(cl->flags & ANYOF_FOLD)) {
696 if (and_with->flags & ANYOF_INVERT)
697 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
698 cl->bitmap[i] &= ~and_with->bitmap[i];
700 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
701 cl->bitmap[i] &= and_with->bitmap[i];
702 } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
703 if (!(and_with->flags & ANYOF_EOS))
704 cl->flags &= ~ANYOF_EOS;
706 if (cl->flags & ANYOF_UNICODE_ALL && and_with->flags & ANYOF_UNICODE &&
707 !(and_with->flags & ANYOF_INVERT)) {
708 cl->flags &= ~ANYOF_UNICODE_ALL;
709 cl->flags |= ANYOF_UNICODE;
710 ARG_SET(cl, ARG(and_with));
712 if (!(and_with->flags & ANYOF_UNICODE_ALL) &&
713 !(and_with->flags & ANYOF_INVERT))
714 cl->flags &= ~ANYOF_UNICODE_ALL;
715 if (!(and_with->flags & (ANYOF_UNICODE|ANYOF_UNICODE_ALL)) &&
716 !(and_with->flags & ANYOF_INVERT))
717 cl->flags &= ~ANYOF_UNICODE;
720 /* 'OR' a given class with another one. Can create false positives */
721 /* We assume that cl is not inverted */
723 S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
725 if (or_with->flags & ANYOF_INVERT) {
727 * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
728 * <= (B1 | !B2) | (CL1 | !CL2)
729 * which is wasteful if CL2 is small, but we ignore CL2:
730 * (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
731 * XXXX Can we handle case-fold? Unclear:
732 * (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
733 * (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
735 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
736 && !(or_with->flags & ANYOF_FOLD)
737 && !(cl->flags & ANYOF_FOLD) ) {
740 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
741 cl->bitmap[i] |= ~or_with->bitmap[i];
742 } /* XXXX: logic is complicated otherwise */
744 cl_anything(pRExC_state, cl);
747 /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
748 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
749 && (!(or_with->flags & ANYOF_FOLD)
750 || (cl->flags & ANYOF_FOLD)) ) {
753 /* OR char bitmap and class bitmap separately */
754 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
755 cl->bitmap[i] |= or_with->bitmap[i];
756 if (or_with->flags & ANYOF_CLASS) {
757 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
758 cl->classflags[i] |= or_with->classflags[i];
759 cl->flags |= ANYOF_CLASS;
762 else { /* XXXX: logic is complicated, leave it along for a moment. */
763 cl_anything(pRExC_state, cl);
766 if (or_with->flags & ANYOF_EOS)
767 cl->flags |= ANYOF_EOS;
769 if (cl->flags & ANYOF_UNICODE && or_with->flags & ANYOF_UNICODE &&
770 ARG(cl) != ARG(or_with)) {
771 cl->flags |= ANYOF_UNICODE_ALL;
772 cl->flags &= ~ANYOF_UNICODE;
774 if (or_with->flags & ANYOF_UNICODE_ALL) {
775 cl->flags |= ANYOF_UNICODE_ALL;
776 cl->flags &= ~ANYOF_UNICODE;
780 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
781 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
782 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
783 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
789 dump_trie_interim_list(trie,next_alloc)
790 dump_trie_interim_table(trie,next_alloc)
792 These routines dump out a trie in a somewhat readable format.
793 The _interim_ variants are used for debugging the interim
794 tables that are used to generate the final compressed
795 representation which is what dump_trie expects.
797 Part of the reason for their existance is to provide a form
798 of documentation as to how the different representations function.
804 Dumps the final compressed table form of the trie to Perl_debug_log.
805 Used for debugging make_trie().
809 S_dump_trie(pTHX_ const struct _reg_trie_data *trie,U32 depth)
812 SV *sv=sv_newmortal();
813 int colwidth= trie->widecharmap ? 6 : 4;
814 GET_RE_DEBUG_FLAGS_DECL;
817 PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
818 (int)depth * 2 + 2,"",
819 "Match","Base","Ofs" );
821 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
822 SV ** const tmp = av_fetch( trie->revcharmap, state, 0);
824 PerlIO_printf( Perl_debug_log, "%*s",
826 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
827 PL_colors[0], PL_colors[1],
828 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
829 PERL_PV_ESCAPE_FIRSTCHAR
834 PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
835 (int)depth * 2 + 2,"");
837 for( state = 0 ; state < trie->uniquecharcount ; state++ )
838 PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
839 PerlIO_printf( Perl_debug_log, "\n");
841 for( state = 1 ; state < trie->statecount ; state++ ) {
842 const U32 base = trie->states[ state ].trans.base;
844 PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
846 if ( trie->states[ state ].wordnum ) {
847 PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
849 PerlIO_printf( Perl_debug_log, "%6s", "" );
852 PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
857 while( ( base + ofs < trie->uniquecharcount ) ||
858 ( base + ofs - trie->uniquecharcount < trie->lasttrans
859 && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
862 PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
864 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
865 if ( ( base + ofs >= trie->uniquecharcount ) &&
866 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
867 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
869 PerlIO_printf( Perl_debug_log, "%*"UVXf,
871 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
873 PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
877 PerlIO_printf( Perl_debug_log, "]");
880 PerlIO_printf( Perl_debug_log, "\n" );
884 dump_trie_interim_list(trie,next_alloc)
885 Dumps a fully constructed but uncompressed trie in list form.
886 List tries normally only are used for construction when the number of
887 possible chars (trie->uniquecharcount) is very high.
888 Used for debugging make_trie().
891 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie, U32 next_alloc,U32 depth)
894 SV *sv=sv_newmortal();
895 int colwidth= trie->widecharmap ? 6 : 4;
896 GET_RE_DEBUG_FLAGS_DECL;
897 /* print out the table precompression. */
898 PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
899 (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
900 "------:-----+-----------------\n" );
902 for( state=1 ; state < next_alloc ; state ++ ) {
905 PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
906 (int)depth * 2 + 2,"", (UV)state );
907 if ( ! trie->states[ state ].wordnum ) {
908 PerlIO_printf( Perl_debug_log, "%5s| ","");
910 PerlIO_printf( Perl_debug_log, "W%4x| ",
911 trie->states[ state ].wordnum
914 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
915 SV ** const tmp = av_fetch( trie->revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
917 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
919 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
920 PL_colors[0], PL_colors[1],
921 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
922 PERL_PV_ESCAPE_FIRSTCHAR
924 TRIE_LIST_ITEM(state,charid).forid,
925 (UV)TRIE_LIST_ITEM(state,charid).newstate
928 PerlIO_printf(Perl_debug_log, "\n%*s| ",
929 (int)((depth * 2) + 14), "");
932 PerlIO_printf( Perl_debug_log, "\n");
937 dump_trie_interim_table(trie,next_alloc)
938 Dumps a fully constructed but uncompressed trie in table form.
939 This is the normal DFA style state transition table, with a few
940 twists to facilitate compression later.
941 Used for debugging make_trie().
944 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie, U32 next_alloc, U32 depth)
948 SV *sv=sv_newmortal();
949 int colwidth= trie->widecharmap ? 6 : 4;
950 GET_RE_DEBUG_FLAGS_DECL;
953 print out the table precompression so that we can do a visual check
954 that they are identical.
957 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
959 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
960 SV ** const tmp = av_fetch( trie->revcharmap, charid, 0);
962 PerlIO_printf( Perl_debug_log, "%*s",
964 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
965 PL_colors[0], PL_colors[1],
966 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
967 PERL_PV_ESCAPE_FIRSTCHAR
973 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
975 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
976 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
979 PerlIO_printf( Perl_debug_log, "\n" );
981 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
983 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
984 (int)depth * 2 + 2,"",
985 (UV)TRIE_NODENUM( state ) );
987 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
988 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
990 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
992 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
994 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
995 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
997 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
998 trie->states[ TRIE_NODENUM( state ) ].wordnum );
1005 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1006 startbranch: the first branch in the whole branch sequence
1007 first : start branch of sequence of branch-exact nodes.
1008 May be the same as startbranch
1009 last : Thing following the last branch.
1010 May be the same as tail.
1011 tail : item following the branch sequence
1012 count : words in the sequence
1013 flags : currently the OP() type we will be building one of /EXACT(|F|Fl)/
1014 depth : indent depth
1016 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
1018 A trie is an N'ary tree where the branches are determined by digital
1019 decomposition of the key. IE, at the root node you look up the 1st character and
1020 follow that branch repeat until you find the end of the branches. Nodes can be
1021 marked as "accepting" meaning they represent a complete word. Eg:
1025 would convert into the following structure. Numbers represent states, letters
1026 following numbers represent valid transitions on the letter from that state, if
1027 the number is in square brackets it represents an accepting state, otherwise it
1028 will be in parenthesis.
1030 +-h->+-e->[3]-+-r->(8)-+-s->[9]
1034 (1) +-i->(6)-+-s->[7]
1036 +-s->(3)-+-h->(4)-+-e->[5]
1038 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1040 This shows that when matching against the string 'hers' we will begin at state 1
1041 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1042 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1043 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1044 single traverse. We store a mapping from accepting to state to which word was
1045 matched, and then when we have multiple possibilities we try to complete the
1046 rest of the regex in the order in which they occured in the alternation.
1048 The only prior NFA like behaviour that would be changed by the TRIE support is
1049 the silent ignoring of duplicate alternations which are of the form:
1051 / (DUPE|DUPE) X? (?{ ... }) Y /x
1053 Thus EVAL blocks follwing a trie may be called a different number of times with
1054 and without the optimisation. With the optimisations dupes will be silently
1055 ignored. This inconsistant behaviour of EVAL type nodes is well established as
1056 the following demonstrates:
1058 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1060 which prints out 'word' three times, but
1062 'words'=~/(word|word|word)(?{ print $1 })S/
1064 which doesnt print it out at all. This is due to other optimisations kicking in.
1066 Example of what happens on a structural level:
1068 The regexp /(ac|ad|ab)+/ will produce the folowing debug output:
1070 1: CURLYM[1] {1,32767}(18)
1081 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1082 and should turn into:
1084 1: CURLYM[1] {1,32767}(18)
1086 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1094 Cases where tail != last would be like /(?foo|bar)baz/:
1104 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1105 and would end up looking like:
1108 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1115 d = uvuni_to_utf8_flags(d, uv, 0);
1117 is the recommended Unicode-aware way of saying
1122 #define TRIE_STORE_REVCHAR \
1124 SV *tmp = newSVpvs(""); \
1125 if (UTF) SvUTF8_on(tmp); \
1126 Perl_sv_catpvf( aTHX_ tmp, "%c", (int)uvc ); \
1127 av_push( TRIE_REVCHARMAP(trie), tmp ); \
1130 #define TRIE_READ_CHAR STMT_START { \
1134 if ( foldlen > 0 ) { \
1135 uvc = utf8n_to_uvuni( scan, UTF8_MAXLEN, &len, uniflags ); \
1140 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1141 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1142 foldlen -= UNISKIP( uvc ); \
1143 scan = foldbuf + UNISKIP( uvc ); \
1146 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1156 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
1157 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
1158 U32 ging = TRIE_LIST_LEN( state ) *= 2; \
1159 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
1161 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
1162 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
1163 TRIE_LIST_CUR( state )++; \
1166 #define TRIE_LIST_NEW(state) STMT_START { \
1167 Newxz( trie->states[ state ].trans.list, \
1168 4, reg_trie_trans_le ); \
1169 TRIE_LIST_CUR( state ) = 1; \
1170 TRIE_LIST_LEN( state ) = 4; \
1173 #define TRIE_HANDLE_WORD(state) STMT_START { \
1174 U16 dupe= trie->states[ state ].wordnum; \
1175 regnode * const noper_next = regnext( noper ); \
1177 if (trie->wordlen) \
1178 trie->wordlen[ curword ] = wordlen; \
1180 /* store the word for dumping */ \
1182 if (OP(noper) != NOTHING) \
1183 tmp = newSVpvn(STRING(noper), STR_LEN(noper)); \
1185 tmp = newSVpvn( "", 0 ); \
1186 if ( UTF ) SvUTF8_on( tmp ); \
1187 av_push( trie->words, tmp ); \
1192 if ( noper_next < tail ) { \
1194 Newxz( trie->jump, word_count + 1, U16); \
1195 trie->jump[curword] = (U16)(noper_next - convert); \
1197 jumper = noper_next; \
1199 nextbranch= regnext(cur); \
1203 /* So it's a dupe. This means we need to maintain a */\
1204 /* linked-list from the first to the next. */\
1205 /* we only allocate the nextword buffer when there */\
1206 /* a dupe, so first time we have to do the allocation */\
1207 if (!trie->nextword) \
1208 Newxz( trie->nextword, word_count + 1, U16); \
1209 while ( trie->nextword[dupe] ) \
1210 dupe= trie->nextword[dupe]; \
1211 trie->nextword[dupe]= curword; \
1213 /* we haven't inserted this word yet. */ \
1214 trie->states[ state ].wordnum = curword; \
1219 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
1220 ( ( base + charid >= ucharcount \
1221 && base + charid < ubound \
1222 && state == trie->trans[ base - ucharcount + charid ].check \
1223 && trie->trans[ base - ucharcount + charid ].next ) \
1224 ? trie->trans[ base - ucharcount + charid ].next \
1225 : ( state==1 ? special : 0 ) \
1229 #define MADE_JUMP_TRIE 2
1230 #define MADE_EXACT_TRIE 4
1233 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
1236 /* first pass, loop through and scan words */
1237 reg_trie_data *trie;
1239 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1244 regnode *jumper = NULL;
1245 regnode *nextbranch = NULL;
1246 regnode *convert = NULL;
1247 /* we just use folder as a flag in utf8 */
1248 const U8 * const folder = ( flags == EXACTF
1250 : ( flags == EXACTFL
1256 const U32 data_slot = add_data( pRExC_state, 1, "t" );
1257 SV *re_trie_maxbuff;
1259 /* these are only used during construction but are useful during
1260 * debugging so we store them in the struct when debugging.
1262 STRLEN trie_charcount=0;
1263 AV *trie_revcharmap;
1265 GET_RE_DEBUG_FLAGS_DECL;
1267 PERL_UNUSED_ARG(depth);
1270 Newxz( trie, 1, reg_trie_data );
1272 trie->startstate = 1;
1273 trie->wordcount = word_count;
1274 RExC_rx->data->data[ data_slot ] = (void*)trie;
1275 Newxz( trie->charmap, 256, U16 );
1276 if (!(UTF && folder))
1277 Newxz( trie->bitmap, ANYOF_BITMAP_SIZE, char );
1279 trie->words = newAV();
1281 TRIE_REVCHARMAP(trie) = newAV();
1283 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
1284 if (!SvIOK(re_trie_maxbuff)) {
1285 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
1288 PerlIO_printf( Perl_debug_log,
1289 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
1290 (int)depth * 2 + 2, "",
1291 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
1292 REG_NODE_NUM(last), REG_NODE_NUM(tail),
1296 /* Find the node we are going to overwrite */
1297 if ( first == startbranch && OP( last ) != BRANCH ) {
1298 /* whole branch chain */
1301 /* branch sub-chain */
1302 convert = NEXTOPER( first );
1305 /* -- First loop and Setup --
1307 We first traverse the branches and scan each word to determine if it
1308 contains widechars, and how many unique chars there are, this is
1309 important as we have to build a table with at least as many columns as we
1312 We use an array of integers to represent the character codes 0..255
1313 (trie->charmap) and we use a an HV* to store unicode characters. We use the
1314 native representation of the character value as the key and IV's for the
1317 *TODO* If we keep track of how many times each character is used we can
1318 remap the columns so that the table compression later on is more
1319 efficient in terms of memory by ensuring most common value is in the
1320 middle and the least common are on the outside. IMO this would be better
1321 than a most to least common mapping as theres a decent chance the most
1322 common letter will share a node with the least common, meaning the node
1323 will not be compressable. With a middle is most common approach the worst
1324 case is when we have the least common nodes twice.
1328 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1329 regnode * const noper = NEXTOPER( cur );
1330 const U8 *uc = (U8*)STRING( noper );
1331 const U8 * const e = uc + STR_LEN( noper );
1333 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1334 const U8 *scan = (U8*)NULL;
1335 U32 wordlen = 0; /* required init */
1338 if (OP(noper) == NOTHING) {
1343 TRIE_BITMAP_SET(trie,*uc);
1344 if ( folder ) TRIE_BITMAP_SET(trie,folder[ *uc ]);
1346 for ( ; uc < e ; uc += len ) {
1347 TRIE_CHARCOUNT(trie)++;
1351 if ( !trie->charmap[ uvc ] ) {
1352 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1354 trie->charmap[ folder[ uvc ] ] = trie->charmap[ uvc ];
1359 if ( !trie->widecharmap )
1360 trie->widecharmap = newHV();
1362 svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 1 );
1365 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
1367 if ( !SvTRUE( *svpp ) ) {
1368 sv_setiv( *svpp, ++trie->uniquecharcount );
1373 if( cur == first ) {
1376 } else if (chars < trie->minlen) {
1378 } else if (chars > trie->maxlen) {
1382 } /* end first pass */
1383 DEBUG_TRIE_COMPILE_r(
1384 PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1385 (int)depth * 2 + 2,"",
1386 ( trie->widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
1387 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1388 (int)trie->minlen, (int)trie->maxlen )
1390 Newxz( trie->wordlen, word_count, U32 );
1393 We now know what we are dealing with in terms of unique chars and
1394 string sizes so we can calculate how much memory a naive
1395 representation using a flat table will take. If it's over a reasonable
1396 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
1397 conservative but potentially much slower representation using an array
1400 At the end we convert both representations into the same compressed
1401 form that will be used in regexec.c for matching with. The latter
1402 is a form that cannot be used to construct with but has memory
1403 properties similar to the list form and access properties similar
1404 to the table form making it both suitable for fast searches and
1405 small enough that its feasable to store for the duration of a program.
1407 See the comment in the code where the compressed table is produced
1408 inplace from the flat tabe representation for an explanation of how
1409 the compression works.
1414 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
1416 Second Pass -- Array Of Lists Representation
1418 Each state will be represented by a list of charid:state records
1419 (reg_trie_trans_le) the first such element holds the CUR and LEN
1420 points of the allocated array. (See defines above).
1422 We build the initial structure using the lists, and then convert
1423 it into the compressed table form which allows faster lookups
1424 (but cant be modified once converted).
1427 STRLEN transcount = 1;
1429 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1430 "%*sCompiling trie using list compiler\n",
1431 (int)depth * 2 + 2, ""));
1433 Newxz( trie->states, TRIE_CHARCOUNT(trie) + 2, reg_trie_state );
1437 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1439 regnode * const noper = NEXTOPER( cur );
1440 U8 *uc = (U8*)STRING( noper );
1441 const U8 * const e = uc + STR_LEN( noper );
1442 U32 state = 1; /* required init */
1443 U16 charid = 0; /* sanity init */
1444 U8 *scan = (U8*)NULL; /* sanity init */
1445 STRLEN foldlen = 0; /* required init */
1446 U32 wordlen = 0; /* required init */
1447 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1449 if (OP(noper) != NOTHING) {
1450 for ( ; uc < e ; uc += len ) {
1455 charid = trie->charmap[ uvc ];
1457 SV** const svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 0);
1461 charid=(U16)SvIV( *svpp );
1464 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1471 if ( !trie->states[ state ].trans.list ) {
1472 TRIE_LIST_NEW( state );
1474 for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1475 if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1476 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1481 newstate = next_alloc++;
1482 TRIE_LIST_PUSH( state, charid, newstate );
1487 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1491 TRIE_HANDLE_WORD(state);
1493 } /* end second pass */
1495 /* next alloc is the NEXT state to be allocated */
1496 trie->statecount = next_alloc;
1497 Renew( trie->states, next_alloc, reg_trie_state );
1499 /* and now dump it out before we compress it */
1500 DEBUG_TRIE_COMPILE_MORE_r(
1501 dump_trie_interim_list(trie,next_alloc,depth+1)
1504 Newxz( trie->trans, transcount ,reg_trie_trans );
1511 for( state=1 ; state < next_alloc ; state ++ ) {
1515 DEBUG_TRIE_COMPILE_MORE_r(
1516 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1520 if (trie->states[state].trans.list) {
1521 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1525 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1526 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1527 if ( forid < minid ) {
1529 } else if ( forid > maxid ) {
1533 if ( transcount < tp + maxid - minid + 1) {
1535 Renew( trie->trans, transcount, reg_trie_trans );
1536 Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1538 base = trie->uniquecharcount + tp - minid;
1539 if ( maxid == minid ) {
1541 for ( ; zp < tp ; zp++ ) {
1542 if ( ! trie->trans[ zp ].next ) {
1543 base = trie->uniquecharcount + zp - minid;
1544 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1545 trie->trans[ zp ].check = state;
1551 trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1552 trie->trans[ tp ].check = state;
1557 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1558 const U32 tid = base - trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
1559 trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1560 trie->trans[ tid ].check = state;
1562 tp += ( maxid - minid + 1 );
1564 Safefree(trie->states[ state ].trans.list);
1567 DEBUG_TRIE_COMPILE_MORE_r(
1568 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1571 trie->states[ state ].trans.base=base;
1573 trie->lasttrans = tp + 1;
1577 Second Pass -- Flat Table Representation.
1579 we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1580 We know that we will need Charcount+1 trans at most to store the data
1581 (one row per char at worst case) So we preallocate both structures
1582 assuming worst case.
1584 We then construct the trie using only the .next slots of the entry
1587 We use the .check field of the first entry of the node temporarily to
1588 make compression both faster and easier by keeping track of how many non
1589 zero fields are in the node.
1591 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1594 There are two terms at use here: state as a TRIE_NODEIDX() which is a
1595 number representing the first entry of the node, and state as a
1596 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1597 TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1598 are 2 entrys per node. eg:
1606 The table is internally in the right hand, idx form. However as we also
1607 have to deal with the states array which is indexed by nodenum we have to
1608 use TRIE_NODENUM() to convert.
1611 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1612 "%*sCompiling trie using table compiler\n",
1613 (int)depth * 2 + 2, ""));
1615 Newxz( trie->trans, ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1,
1617 Newxz( trie->states, TRIE_CHARCOUNT(trie) + 2, reg_trie_state );
1618 next_alloc = trie->uniquecharcount + 1;
1621 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1623 regnode * const noper = NEXTOPER( cur );
1624 const U8 *uc = (U8*)STRING( noper );
1625 const U8 * const e = uc + STR_LEN( noper );
1627 U32 state = 1; /* required init */
1629 U16 charid = 0; /* sanity init */
1630 U32 accept_state = 0; /* sanity init */
1631 U8 *scan = (U8*)NULL; /* sanity init */
1633 STRLEN foldlen = 0; /* required init */
1634 U32 wordlen = 0; /* required init */
1635 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1637 if ( OP(noper) != NOTHING ) {
1638 for ( ; uc < e ; uc += len ) {
1643 charid = trie->charmap[ uvc ];
1645 SV* const * const svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 0);
1646 charid = svpp ? (U16)SvIV(*svpp) : 0;
1650 if ( !trie->trans[ state + charid ].next ) {
1651 trie->trans[ state + charid ].next = next_alloc;
1652 trie->trans[ state ].check++;
1653 next_alloc += trie->uniquecharcount;
1655 state = trie->trans[ state + charid ].next;
1657 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1659 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1662 accept_state = TRIE_NODENUM( state );
1663 TRIE_HANDLE_WORD(accept_state);
1665 } /* end second pass */
1667 /* and now dump it out before we compress it */
1668 DEBUG_TRIE_COMPILE_MORE_r(
1669 dump_trie_interim_table(trie,next_alloc,depth+1)
1674 * Inplace compress the table.*
1676 For sparse data sets the table constructed by the trie algorithm will
1677 be mostly 0/FAIL transitions or to put it another way mostly empty.
1678 (Note that leaf nodes will not contain any transitions.)
1680 This algorithm compresses the tables by eliminating most such
1681 transitions, at the cost of a modest bit of extra work during lookup:
1683 - Each states[] entry contains a .base field which indicates the
1684 index in the state[] array wheres its transition data is stored.
1686 - If .base is 0 there are no valid transitions from that node.
1688 - If .base is nonzero then charid is added to it to find an entry in
1691 -If trans[states[state].base+charid].check!=state then the
1692 transition is taken to be a 0/Fail transition. Thus if there are fail
1693 transitions at the front of the node then the .base offset will point
1694 somewhere inside the previous nodes data (or maybe even into a node
1695 even earlier), but the .check field determines if the transition is
1699 The following process inplace converts the table to the compressed
1700 table: We first do not compress the root node 1,and mark its all its
1701 .check pointers as 1 and set its .base pointer as 1 as well. This
1702 allows to do a DFA construction from the compressed table later, and
1703 ensures that any .base pointers we calculate later are greater than
1706 - We set 'pos' to indicate the first entry of the second node.
1708 - We then iterate over the columns of the node, finding the first and
1709 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
1710 and set the .check pointers accordingly, and advance pos
1711 appropriately and repreat for the next node. Note that when we copy
1712 the next pointers we have to convert them from the original
1713 NODEIDX form to NODENUM form as the former is not valid post
1716 - If a node has no transitions used we mark its base as 0 and do not
1717 advance the pos pointer.
1719 - If a node only has one transition we use a second pointer into the
1720 structure to fill in allocated fail transitions from other states.
1721 This pointer is independent of the main pointer and scans forward
1722 looking for null transitions that are allocated to a state. When it
1723 finds one it writes the single transition into the "hole". If the
1724 pointer doesnt find one the single transition is appended as normal.
1726 - Once compressed we can Renew/realloc the structures to release the
1729 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
1730 specifically Fig 3.47 and the associated pseudocode.
1734 const U32 laststate = TRIE_NODENUM( next_alloc );
1737 trie->statecount = laststate;
1739 for ( state = 1 ; state < laststate ; state++ ) {
1741 const U32 stateidx = TRIE_NODEIDX( state );
1742 const U32 o_used = trie->trans[ stateidx ].check;
1743 U32 used = trie->trans[ stateidx ].check;
1744 trie->trans[ stateidx ].check = 0;
1746 for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
1747 if ( flag || trie->trans[ stateidx + charid ].next ) {
1748 if ( trie->trans[ stateidx + charid ].next ) {
1750 for ( ; zp < pos ; zp++ ) {
1751 if ( ! trie->trans[ zp ].next ) {
1755 trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
1756 trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1757 trie->trans[ zp ].check = state;
1758 if ( ++zp > pos ) pos = zp;
1765 trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
1767 trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1768 trie->trans[ pos ].check = state;
1773 trie->lasttrans = pos + 1;
1774 Renew( trie->states, laststate, reg_trie_state);
1775 DEBUG_TRIE_COMPILE_MORE_r(
1776 PerlIO_printf( Perl_debug_log,
1777 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
1778 (int)depth * 2 + 2,"",
1779 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
1782 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
1785 } /* end table compress */
1787 DEBUG_TRIE_COMPILE_MORE_r(
1788 PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
1789 (int)depth * 2 + 2, "",
1790 (UV)trie->statecount,
1791 (UV)trie->lasttrans)
1793 /* resize the trans array to remove unused space */
1794 Renew( trie->trans, trie->lasttrans, reg_trie_trans);
1796 /* and now dump out the compressed format */
1797 DEBUG_TRIE_COMPILE_r(
1798 dump_trie(trie,depth+1)
1801 { /* Modify the program and insert the new TRIE node*/
1802 U8 nodetype =(U8)(flags & 0xFF);
1806 regnode *optimize = NULL;
1808 U32 mjd_nodelen = 0;
1811 This means we convert either the first branch or the first Exact,
1812 depending on whether the thing following (in 'last') is a branch
1813 or not and whther first is the startbranch (ie is it a sub part of
1814 the alternation or is it the whole thing.)
1815 Assuming its a sub part we conver the EXACT otherwise we convert
1816 the whole branch sequence, including the first.
1818 /* Find the node we are going to overwrite */
1819 if ( first != startbranch || OP( last ) == BRANCH ) {
1820 /* branch sub-chain */
1821 NEXT_OFF( first ) = (U16)(last - first);
1823 mjd_offset= Node_Offset((convert));
1824 mjd_nodelen= Node_Length((convert));
1826 /* whole branch chain */
1829 const regnode *nop = NEXTOPER( convert );
1830 mjd_offset= Node_Offset((nop));
1831 mjd_nodelen= Node_Length((nop));
1836 PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
1837 (int)depth * 2 + 2, "",
1838 (UV)mjd_offset, (UV)mjd_nodelen)
1841 /* But first we check to see if there is a common prefix we can
1842 split out as an EXACT and put in front of the TRIE node. */
1843 trie->startstate= 1;
1844 if ( trie->bitmap && !trie->widecharmap && !trie->jump ) {
1846 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
1850 const U32 base = trie->states[ state ].trans.base;
1852 if ( trie->states[state].wordnum )
1855 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1856 if ( ( base + ofs >= trie->uniquecharcount ) &&
1857 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
1858 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
1860 if ( ++count > 1 ) {
1861 SV **tmp = av_fetch( TRIE_REVCHARMAP(trie), ofs, 0);
1862 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
1863 if ( state == 1 ) break;
1865 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
1867 PerlIO_printf(Perl_debug_log,
1868 "%*sNew Start State=%"UVuf" Class: [",
1869 (int)depth * 2 + 2, "",
1872 SV ** const tmp = av_fetch( TRIE_REVCHARMAP(trie), idx, 0);
1873 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
1875 TRIE_BITMAP_SET(trie,*ch);
1877 TRIE_BITMAP_SET(trie, folder[ *ch ]);
1879 PerlIO_printf(Perl_debug_log, (char*)ch)
1883 TRIE_BITMAP_SET(trie,*ch);
1885 TRIE_BITMAP_SET(trie,folder[ *ch ]);
1886 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
1892 SV **tmp = av_fetch( TRIE_REVCHARMAP(trie), idx, 0);
1893 const char *ch = SvPV_nolen_const( *tmp );
1895 PerlIO_printf( Perl_debug_log,
1896 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
1897 (int)depth * 2 + 2, "",
1898 (UV)state, (UV)idx, ch)
1901 OP( convert ) = nodetype;
1902 str=STRING(convert);
1911 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
1917 regnode *n = convert+NODE_SZ_STR(convert);
1918 NEXT_OFF(convert) = NODE_SZ_STR(convert);
1919 trie->startstate = state;
1920 trie->minlen -= (state - 1);
1921 trie->maxlen -= (state - 1);
1923 regnode *fix = convert;
1925 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
1926 while( ++fix < n ) {
1927 Set_Node_Offset_Length(fix, 0, 0);
1933 NEXT_OFF(convert) = (U16)(tail - convert);
1934 DEBUG_r(optimize= n);
1940 if ( trie->maxlen ) {
1941 NEXT_OFF( convert ) = (U16)(tail - convert);
1942 ARG_SET( convert, data_slot );
1943 /* Store the offset to the first unabsorbed branch in
1944 jump[0], which is otherwise unused by the jump logic.
1945 We use this when dumping a trie and during optimisation. */
1947 trie->jump[0] = (U16)(nextbranch - convert);
1950 if ( !trie->states[trie->startstate].wordnum && trie->bitmap &&
1951 ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
1953 OP( convert ) = TRIEC;
1954 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
1955 Safefree(trie->bitmap);
1958 OP( convert ) = TRIE;
1960 /* store the type in the flags */
1961 convert->flags = nodetype;
1965 + regarglen[ OP( convert ) ];
1967 /* XXX We really should free up the resource in trie now,
1968 as we won't use them - (which resources?) dmq */
1970 /* needed for dumping*/
1971 DEBUG_r(if (optimize) {
1972 regnode *opt = convert;
1973 while ( ++opt < optimize) {
1974 Set_Node_Offset_Length(opt,0,0);
1977 Try to clean up some of the debris left after the
1980 while( optimize < jumper ) {
1981 mjd_nodelen += Node_Length((optimize));
1982 OP( optimize ) = OPTIMIZED;
1983 Set_Node_Offset_Length(optimize,0,0);
1986 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
1988 } /* end node insert */
1990 SvREFCNT_dec(TRIE_REVCHARMAP(trie));
1994 : trie->startstate>1
2000 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source, regnode *stclass, U32 depth)
2002 /* The Trie is constructed and compressed now so we can build a fail array now if its needed
2004 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
2005 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
2008 We find the fail state for each state in the trie, this state is the longest proper
2009 suffix of the current states 'word' that is also a proper prefix of another word in our
2010 trie. State 1 represents the word '' and is the thus the default fail state. This allows
2011 the DFA not to have to restart after its tried and failed a word at a given point, it
2012 simply continues as though it had been matching the other word in the first place.
2014 'abcdgu'=~/abcdefg|cdgu/
2015 When we get to 'd' we are still matching the first word, we would encounter 'g' which would
2016 fail, which would bring use to the state representing 'd' in the second word where we would
2017 try 'g' and succeed, prodceding to match 'cdgu'.
2019 /* add a fail transition */
2020 reg_trie_data *trie=(reg_trie_data *)RExC_rx->data->data[ARG(source)];
2022 const U32 ucharcount = trie->uniquecharcount;
2023 const U32 numstates = trie->statecount;
2024 const U32 ubound = trie->lasttrans + ucharcount;
2028 U32 base = trie->states[ 1 ].trans.base;
2031 const U32 data_slot = add_data( pRExC_state, 1, "T" );
2032 GET_RE_DEBUG_FLAGS_DECL;
2034 PERL_UNUSED_ARG(depth);
2038 ARG_SET( stclass, data_slot );
2039 Newxz( aho, 1, reg_ac_data );
2040 RExC_rx->data->data[ data_slot ] = (void*)aho;
2042 aho->states=(reg_trie_state *)savepvn((const char*)trie->states,
2043 numstates * sizeof(reg_trie_state));
2044 Newxz( q, numstates, U32);
2045 Newxz( aho->fail, numstates, U32 );
2048 /* initialize fail[0..1] to be 1 so that we always have
2049 a valid final fail state */
2050 fail[ 0 ] = fail[ 1 ] = 1;
2052 for ( charid = 0; charid < ucharcount ; charid++ ) {
2053 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2055 q[ q_write ] = newstate;
2056 /* set to point at the root */
2057 fail[ q[ q_write++ ] ]=1;
2060 while ( q_read < q_write) {
2061 const U32 cur = q[ q_read++ % numstates ];
2062 base = trie->states[ cur ].trans.base;
2064 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2065 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2067 U32 fail_state = cur;
2070 fail_state = fail[ fail_state ];
2071 fail_base = aho->states[ fail_state ].trans.base;
2072 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2074 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2075 fail[ ch_state ] = fail_state;
2076 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2078 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
2080 q[ q_write++ % numstates] = ch_state;
2084 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2085 when we fail in state 1, this allows us to use the
2086 charclass scan to find a valid start char. This is based on the principle
2087 that theres a good chance the string being searched contains lots of stuff
2088 that cant be a start char.
2090 fail[ 0 ] = fail[ 1 ] = 0;
2091 DEBUG_TRIE_COMPILE_r({
2092 PerlIO_printf(Perl_debug_log, "%*sStclass Failtable (%"UVuf" states): 0",
2093 (int)(depth * 2), "", numstates
2095 for( q_read=1; q_read<numstates; q_read++ ) {
2096 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2098 PerlIO_printf(Perl_debug_log, "\n");
2101 /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2106 * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2107 * These need to be revisited when a newer toolchain becomes available.
2109 #if defined(__sparc64__) && defined(__GNUC__)
2110 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2111 # undef SPARC64_GCC_WORKAROUND
2112 # define SPARC64_GCC_WORKAROUND 1
2116 #define DEBUG_PEEP(str,scan,depth) \
2117 DEBUG_OPTIMISE_r({ \
2118 SV * const mysv=sv_newmortal(); \
2119 regnode *Next = regnext(scan); \
2120 regprop(RExC_rx, mysv, scan); \
2121 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
2122 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2123 Next ? (REG_NODE_NUM(Next)) : 0 ); \
2130 #define JOIN_EXACT(scan,min,flags) \
2131 if (PL_regkind[OP(scan)] == EXACT) \
2132 join_exact(pRExC_state,(scan),(min),(flags),NULL,depth+1)
2135 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, I32 *min, U32 flags,regnode *val, U32 depth) {
2136 /* Merge several consecutive EXACTish nodes into one. */
2137 regnode *n = regnext(scan);
2139 regnode *next = scan + NODE_SZ_STR(scan);
2143 regnode *stop = scan;
2144 GET_RE_DEBUG_FLAGS_DECL;
2146 PERL_UNUSED_ARG(depth);
2148 #ifndef EXPERIMENTAL_INPLACESCAN
2149 PERL_UNUSED_ARG(flags);
2150 PERL_UNUSED_ARG(val);
2152 DEBUG_PEEP("join",scan,depth);
2154 /* Skip NOTHING, merge EXACT*. */
2156 ( PL_regkind[OP(n)] == NOTHING ||
2157 (stringok && (OP(n) == OP(scan))))
2159 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
2161 if (OP(n) == TAIL || n > next)
2163 if (PL_regkind[OP(n)] == NOTHING) {
2164 DEBUG_PEEP("skip:",n,depth);
2165 NEXT_OFF(scan) += NEXT_OFF(n);
2166 next = n + NODE_STEP_REGNODE;
2173 else if (stringok) {
2174 const unsigned int oldl = STR_LEN(scan);
2175 regnode * const nnext = regnext(n);
2177 DEBUG_PEEP("merg",n,depth);
2180 if (oldl + STR_LEN(n) > U8_MAX)
2182 NEXT_OFF(scan) += NEXT_OFF(n);
2183 STR_LEN(scan) += STR_LEN(n);
2184 next = n + NODE_SZ_STR(n);
2185 /* Now we can overwrite *n : */
2186 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2194 #ifdef EXPERIMENTAL_INPLACESCAN
2195 if (flags && !NEXT_OFF(n)) {
2196 DEBUG_PEEP("atch", val, depth);
2197 if (reg_off_by_arg[OP(n)]) {
2198 ARG_SET(n, val - n);
2201 NEXT_OFF(n) = val - n;
2208 if (UTF && ( OP(scan) == EXACTF ) && ( STR_LEN(scan) >= 6 ) ) {
2210 Two problematic code points in Unicode casefolding of EXACT nodes:
2212 U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2213 U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2219 U+03B9 U+0308 U+0301 0xCE 0xB9 0xCC 0x88 0xCC 0x81
2220 U+03C5 U+0308 U+0301 0xCF 0x85 0xCC 0x88 0xCC 0x81
2222 This means that in case-insensitive matching (or "loose matching",
2223 as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte
2224 length of the above casefolded versions) can match a target string
2225 of length two (the byte length of UTF-8 encoded U+0390 or U+03B0).
2226 This would rather mess up the minimum length computation.
2228 What we'll do is to look for the tail four bytes, and then peek
2229 at the preceding two bytes to see whether we need to decrease
2230 the minimum length by four (six minus two).
2232 Thanks to the design of UTF-8, there cannot be false matches:
2233 A sequence of valid UTF-8 bytes cannot be a subsequence of
2234 another valid sequence of UTF-8 bytes.
2237 char * const s0 = STRING(scan), *s, *t;
2238 char * const s1 = s0 + STR_LEN(scan) - 1;
2239 char * const s2 = s1 - 4;
2240 #ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2241 const char t0[] = "\xaf\x49\xaf\x42";
2243 const char t0[] = "\xcc\x88\xcc\x81";
2245 const char * const t1 = t0 + 3;
2248 s < s2 && (t = ninstr(s, s1, t0, t1));
2251 if (((U8)t[-1] == 0x68 && (U8)t[-2] == 0xB4) ||
2252 ((U8)t[-1] == 0x46 && (U8)t[-2] == 0xB5))
2254 if (((U8)t[-1] == 0xB9 && (U8)t[-2] == 0xCE) ||
2255 ((U8)t[-1] == 0x85 && (U8)t[-2] == 0xCF))
2263 n = scan + NODE_SZ_STR(scan);
2265 if (PL_regkind[OP(n)] != NOTHING || OP(n) == NOTHING) {
2272 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2276 /* REx optimizer. Converts nodes into quickier variants "in place".
2277 Finds fixed substrings. */
2279 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
2280 to the position after last scanned or to NULL. */
2282 #define INIT_AND_WITHP \
2283 assert(!and_withp); \
2284 Newx(and_withp,1,struct regnode_charclass_class); \
2285 SAVEFREEPV(and_withp)
2288 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
2289 I32 *minlenp, I32 *deltap,
2294 struct regnode_charclass_class *and_withp,
2295 U32 flags, U32 depth)
2296 /* scanp: Start here (read-write). */
2297 /* deltap: Write maxlen-minlen here. */
2298 /* last: Stop before this one. */
2299 /* data: string data about the pattern */
2300 /* stopparen: treat close N as END */
2301 /* recursed: which subroutines have we recursed into */
2302 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
2305 I32 min = 0, pars = 0, code;
2306 regnode *scan = *scanp, *next;
2308 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
2309 int is_inf_internal = 0; /* The studied chunk is infinite */
2310 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2311 scan_data_t data_fake;
2312 SV *re_trie_maxbuff = NULL;
2313 regnode *first_non_open = scan;
2314 GET_RE_DEBUG_FLAGS_DECL;
2316 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
2320 while (first_non_open && OP(first_non_open) == OPEN)
2321 first_non_open=regnext(first_non_open);
2325 while (scan && OP(scan) != END && scan < last) {
2326 /* Peephole optimizer: */
2327 DEBUG_STUDYDATA(data,depth);
2328 DEBUG_PEEP("Peep",scan,depth);
2329 JOIN_EXACT(scan,&min,0);
2331 /* Follow the next-chain of the current node and optimize
2332 away all the NOTHINGs from it. */
2333 if (OP(scan) != CURLYX) {
2334 const int max = (reg_off_by_arg[OP(scan)]
2336 /* I32 may be smaller than U16 on CRAYs! */
2337 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
2338 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
2342 /* Skip NOTHING and LONGJMP. */
2343 while ((n = regnext(n))
2344 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
2345 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
2346 && off + noff < max)
2348 if (reg_off_by_arg[OP(scan)])
2351 NEXT_OFF(scan) = off;
2356 /* The principal pseudo-switch. Cannot be a switch, since we
2357 look into several different things. */
2358 if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
2359 || OP(scan) == IFTHEN || OP(scan) == SUSPEND) {
2360 next = regnext(scan);
2362 /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
2364 if (OP(next) == code || code == IFTHEN || code == SUSPEND) {
2365 /* NOTE - There is similar code to this block below for handling
2366 TRIE nodes on a re-study. If you change stuff here check there
2368 I32 max1 = 0, min1 = I32_MAX, num = 0;
2369 struct regnode_charclass_class accum;
2370 regnode * const startbranch=scan;
2372 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
2373 scan_commit(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
2374 if (flags & SCF_DO_STCLASS)
2375 cl_init_zero(pRExC_state, &accum);
2377 while (OP(scan) == code) {
2378 I32 deltanext, minnext, f = 0, fake;
2379 struct regnode_charclass_class this_class;
2382 data_fake.flags = 0;
2384 data_fake.whilem_c = data->whilem_c;
2385 data_fake.last_closep = data->last_closep;
2388 data_fake.last_closep = &fake;
2389 next = regnext(scan);
2390 scan = NEXTOPER(scan);
2392 scan = NEXTOPER(scan);
2393 if (flags & SCF_DO_STCLASS) {
2394 cl_init(pRExC_state, &this_class);
2395 data_fake.start_class = &this_class;
2396 f = SCF_DO_STCLASS_AND;
2398 if (flags & SCF_WHILEM_VISITED_POS)
2399 f |= SCF_WHILEM_VISITED_POS;
2401 /* we suppose the run is continuous, last=next...*/
2402 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2404 stopparen, recursed, NULL, f,depth+1);
2407 if (max1 < minnext + deltanext)
2408 max1 = minnext + deltanext;
2409 if (deltanext == I32_MAX)
2410 is_inf = is_inf_internal = 1;
2412 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
2415 if (data_fake.flags & SF_HAS_EVAL)
2416 data->flags |= SF_HAS_EVAL;
2417 data->whilem_c = data_fake.whilem_c;
2419 if (flags & SCF_DO_STCLASS)
2420 cl_or(pRExC_state, &accum, &this_class);
2421 if (code == SUSPEND)
2424 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
2426 if (flags & SCF_DO_SUBSTR) {
2427 data->pos_min += min1;
2428 data->pos_delta += max1 - min1;
2429 if (max1 != min1 || is_inf)
2430 data->longest = &(data->longest_float);
2433 delta += max1 - min1;
2434 if (flags & SCF_DO_STCLASS_OR) {
2435 cl_or(pRExC_state, data->start_class, &accum);
2437 cl_and(data->start_class, and_withp);
2438 flags &= ~SCF_DO_STCLASS;
2441 else if (flags & SCF_DO_STCLASS_AND) {
2443 cl_and(data->start_class, &accum);
2444 flags &= ~SCF_DO_STCLASS;
2447 /* Switch to OR mode: cache the old value of
2448 * data->start_class */
2450 StructCopy(data->start_class, and_withp,
2451 struct regnode_charclass_class);
2452 flags &= ~SCF_DO_STCLASS_AND;
2453 StructCopy(&accum, data->start_class,
2454 struct regnode_charclass_class);
2455 flags |= SCF_DO_STCLASS_OR;
2456 data->start_class->flags |= ANYOF_EOS;
2460 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
2463 Assuming this was/is a branch we are dealing with: 'scan' now
2464 points at the item that follows the branch sequence, whatever
2465 it is. We now start at the beginning of the sequence and look
2472 which would be constructed from a pattern like /A|LIST|OF|WORDS/
2474 If we can find such a subseqence we need to turn the first
2475 element into a trie and then add the subsequent branch exact
2476 strings to the trie.
2480 1. patterns where the whole set of branch can be converted.
2482 2. patterns where only a subset can be converted.
2484 In case 1 we can replace the whole set with a single regop
2485 for the trie. In case 2 we need to keep the start and end
2488 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
2489 becomes BRANCH TRIE; BRANCH X;
2491 There is an additional case, that being where there is a
2492 common prefix, which gets split out into an EXACT like node
2493 preceding the TRIE node.
2495 If x(1..n)==tail then we can do a simple trie, if not we make
2496 a "jump" trie, such that when we match the appropriate word
2497 we "jump" to the appopriate tail node. Essentailly we turn
2498 a nested if into a case structure of sorts.
2503 if (!re_trie_maxbuff) {
2504 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2505 if (!SvIOK(re_trie_maxbuff))
2506 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2508 if ( SvIV(re_trie_maxbuff)>=0 ) {
2510 regnode *first = (regnode *)NULL;
2511 regnode *last = (regnode *)NULL;
2512 regnode *tail = scan;
2517 SV * const mysv = sv_newmortal(); /* for dumping */
2519 /* var tail is used because there may be a TAIL
2520 regop in the way. Ie, the exacts will point to the
2521 thing following the TAIL, but the last branch will
2522 point at the TAIL. So we advance tail. If we
2523 have nested (?:) we may have to move through several
2527 while ( OP( tail ) == TAIL ) {
2528 /* this is the TAIL generated by (?:) */
2529 tail = regnext( tail );
2534 regprop(RExC_rx, mysv, tail );
2535 PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
2536 (int)depth * 2 + 2, "",
2537 "Looking for TRIE'able sequences. Tail node is: ",
2538 SvPV_nolen_const( mysv )
2544 step through the branches, cur represents each
2545 branch, noper is the first thing to be matched
2546 as part of that branch and noper_next is the
2547 regnext() of that node. if noper is an EXACT
2548 and noper_next is the same as scan (our current
2549 position in the regex) then the EXACT branch is
2550 a possible optimization target. Once we have
2551 two or more consequetive such branches we can
2552 create a trie of the EXACT's contents and stich
2553 it in place. If the sequence represents all of
2554 the branches we eliminate the whole thing and
2555 replace it with a single TRIE. If it is a
2556 subsequence then we need to stitch it in. This
2557 means the first branch has to remain, and needs
2558 to be repointed at the item on the branch chain
2559 following the last branch optimized. This could
2560 be either a BRANCH, in which case the
2561 subsequence is internal, or it could be the
2562 item following the branch sequence in which
2563 case the subsequence is at the end.
2567 /* dont use tail as the end marker for this traverse */
2568 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
2569 regnode * const noper = NEXTOPER( cur );
2570 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
2571 regnode * const noper_next = regnext( noper );
2575 regprop(RExC_rx, mysv, cur);
2576 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
2577 (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
2579 regprop(RExC_rx, mysv, noper);
2580 PerlIO_printf( Perl_debug_log, " -> %s",
2581 SvPV_nolen_const(mysv));
2584 regprop(RExC_rx, mysv, noper_next );
2585 PerlIO_printf( Perl_debug_log,"\t=> %s\t",
2586 SvPV_nolen_const(mysv));
2588 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
2589 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
2591 if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
2592 : PL_regkind[ OP( noper ) ] == EXACT )
2593 || OP(noper) == NOTHING )
2595 && noper_next == tail
2600 if ( !first || optype == NOTHING ) {
2601 if (!first) first = cur;
2602 optype = OP( noper );
2608 make_trie( pRExC_state,
2609 startbranch, first, cur, tail, count,
2612 if ( PL_regkind[ OP( noper ) ] == EXACT
2614 && noper_next == tail
2619 optype = OP( noper );
2629 regprop(RExC_rx, mysv, cur);
2630 PerlIO_printf( Perl_debug_log,
2631 "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
2632 "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
2636 made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
2637 #ifdef TRIE_STUDY_OPT
2638 if ( ((made == MADE_EXACT_TRIE &&
2639 startbranch == first)
2640 || ( first_non_open == first )) &&
2642 flags |= SCF_TRIE_RESTUDY;
2650 else if ( code == BRANCHJ ) { /* single branch is optimized. */
2651 scan = NEXTOPER(NEXTOPER(scan));
2652 } else /* single branch is optimized. */
2653 scan = NEXTOPER(scan);
2656 else if (OP(scan) == EXACT) {
2657 I32 l = STR_LEN(scan);
2660 const U8 * const s = (U8*)STRING(scan);
2661 l = utf8_length(s, s + l);
2662 uc = utf8_to_uvchr(s, NULL);
2664 uc = *((U8*)STRING(scan));
2667 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
2668 /* The code below prefers earlier match for fixed
2669 offset, later match for variable offset. */
2670 if (data->last_end == -1) { /* Update the start info. */
2671 data->last_start_min = data->pos_min;
2672 data->last_start_max = is_inf
2673 ? I32_MAX : data->pos_min + data->pos_delta;
2675 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
2677 SvUTF8_on(data->last_found);
2679 SV * const sv = data->last_found;
2680 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
2681 mg_find(sv, PERL_MAGIC_utf8) : NULL;
2682 if (mg && mg->mg_len >= 0)
2683 mg->mg_len += utf8_length((U8*)STRING(scan),
2684 (U8*)STRING(scan)+STR_LEN(scan));
2686 data->last_end = data->pos_min + l;
2687 data->pos_min += l; /* As in the first entry. */
2688 data->flags &= ~SF_BEFORE_EOL;
2690 if (flags & SCF_DO_STCLASS_AND) {
2691 /* Check whether it is compatible with what we know already! */
2695 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2696 && !ANYOF_BITMAP_TEST(data->start_class, uc)
2697 && (!(data->start_class->flags & ANYOF_FOLD)
2698 || !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2701 ANYOF_CLASS_ZERO(data->start_class);
2702 ANYOF_BITMAP_ZERO(data->start_class);
2704 ANYOF_BITMAP_SET(data->start_class, uc);
2705 data->start_class->flags &= ~ANYOF_EOS;
2707 data->start_class->flags &= ~ANYOF_UNICODE_ALL;
2709 else if (flags & SCF_DO_STCLASS_OR) {
2710 /* false positive possible if the class is case-folded */
2712 ANYOF_BITMAP_SET(data->start_class, uc);
2714 data->start_class->flags |= ANYOF_UNICODE_ALL;
2715 data->start_class->flags &= ~ANYOF_EOS;
2716 cl_and(data->start_class, and_withp);
2718 flags &= ~SCF_DO_STCLASS;
2720 else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
2721 I32 l = STR_LEN(scan);
2722 UV uc = *((U8*)STRING(scan));
2724 /* Search for fixed substrings supports EXACT only. */
2725 if (flags & SCF_DO_SUBSTR) {
2727 scan_commit(pRExC_state, data, minlenp);
2730 const U8 * const s = (U8 *)STRING(scan);
2731 l = utf8_length(s, s + l);
2732 uc = utf8_to_uvchr(s, NULL);
2735 if (flags & SCF_DO_SUBSTR)
2737 if (flags & SCF_DO_STCLASS_AND) {
2738 /* Check whether it is compatible with what we know already! */
2742 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2743 && !ANYOF_BITMAP_TEST(data->start_class, uc)
2744 && !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2746 ANYOF_CLASS_ZERO(data->start_class);
2747 ANYOF_BITMAP_ZERO(data->start_class);
2749 ANYOF_BITMAP_SET(data->start_class, uc);
2750 data->start_class->flags &= ~ANYOF_EOS;
2751 data->start_class->flags |= ANYOF_FOLD;
2752 if (OP(scan) == EXACTFL)
2753 data->start_class->flags |= ANYOF_LOCALE;
2756 else if (flags & SCF_DO_STCLASS_OR) {
2757 if (data->start_class->flags & ANYOF_FOLD) {
2758 /* false positive possible if the class is case-folded.
2759 Assume that the locale settings are the same... */
2761 ANYOF_BITMAP_SET(data->start_class, uc);
2762 data->start_class->flags &= ~ANYOF_EOS;
2764 cl_and(data->start_class, and_withp);
2766 flags &= ~SCF_DO_STCLASS;
2768 else if (strchr((const char*)PL_varies,OP(scan))) {
2769 I32 mincount, maxcount, minnext, deltanext, fl = 0;
2770 I32 f = flags, pos_before = 0;
2771 regnode * const oscan = scan;
2772 struct regnode_charclass_class this_class;
2773 struct regnode_charclass_class *oclass = NULL;
2774 I32 next_is_eval = 0;
2776 switch (PL_regkind[OP(scan)]) {
2777 case WHILEM: /* End of (?:...)* . */
2778 scan = NEXTOPER(scan);
2781 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
2782 next = NEXTOPER(scan);
2783 if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
2785 maxcount = REG_INFTY;
2786 next = regnext(scan);
2787 scan = NEXTOPER(scan);
2791 if (flags & SCF_DO_SUBSTR)
2796 if (flags & SCF_DO_STCLASS) {
2798 maxcount = REG_INFTY;
2799 next = regnext(scan);
2800 scan = NEXTOPER(scan);
2803 is_inf = is_inf_internal = 1;
2804 scan = regnext(scan);
2805 if (flags & SCF_DO_SUBSTR) {
2806 scan_commit(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
2807 data->longest = &(data->longest_float);
2809 goto optimize_curly_tail;
2811 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
2812 && (scan->flags == stopparen))
2817 mincount = ARG1(scan);
2818 maxcount = ARG2(scan);
2820 next = regnext(scan);
2821 if (OP(scan) == CURLYX) {
2822 I32 lp = (data ? *(data->last_closep) : 0);
2823 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
2825 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
2826 next_is_eval = (OP(scan) == EVAL);
2828 if (flags & SCF_DO_SUBSTR) {
2829 if (mincount == 0) scan_commit(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
2830 pos_before = data->pos_min;
2834 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
2836 data->flags |= SF_IS_INF;
2838 if (flags & SCF_DO_STCLASS) {
2839 cl_init(pRExC_state, &this_class);
2840 oclass = data->start_class;
2841 data->start_class = &this_class;
2842 f |= SCF_DO_STCLASS_AND;
2843 f &= ~SCF_DO_STCLASS_OR;
2845 /* These are the cases when once a subexpression
2846 fails at a particular position, it cannot succeed
2847 even after backtracking at the enclosing scope.
2849 XXXX what if minimal match and we are at the
2850 initial run of {n,m}? */
2851 if ((mincount != maxcount - 1) && (maxcount != REG_INFTY))
2852 f &= ~SCF_WHILEM_VISITED_POS;
2854 /* This will finish on WHILEM, setting scan, or on NULL: */
2855 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2856 last, data, stopparen, recursed, NULL,
2858 ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
2860 if (flags & SCF_DO_STCLASS)
2861 data->start_class = oclass;
2862 if (mincount == 0 || minnext == 0) {
2863 if (flags & SCF_DO_STCLASS_OR) {
2864 cl_or(pRExC_state, data->start_class, &this_class);
2866 else if (flags & SCF_DO_STCLASS_AND) {
2867 /* Switch to OR mode: cache the old value of
2868 * data->start_class */
2870 StructCopy(data->start_class, and_withp,
2871 struct regnode_charclass_class);
2872 flags &= ~SCF_DO_STCLASS_AND;
2873 StructCopy(&this_class, data->start_class,
2874 struct regnode_charclass_class);
2875 flags |= SCF_DO_STCLASS_OR;
2876 data->start_class->flags |= ANYOF_EOS;
2878 } else { /* Non-zero len */
2879 if (flags & SCF_DO_STCLASS_OR) {
2880 cl_or(pRExC_state, data->start_class, &this_class);
2881 cl_and(data->start_class, and_withp);
2883 else if (flags & SCF_DO_STCLASS_AND)
2884 cl_and(data->start_class, &this_class);
2885 flags &= ~SCF_DO_STCLASS;
2887 if (!scan) /* It was not CURLYX, but CURLY. */
2889 if ( /* ? quantifier ok, except for (?{ ... }) */
2890 (next_is_eval || !(mincount == 0 && maxcount == 1))
2891 && (minnext == 0) && (deltanext == 0)
2892 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
2893 && maxcount <= REG_INFTY/3 /* Complement check for big count */
2894 && ckWARN(WARN_REGEXP))
2897 "Quantifier unexpected on zero-length expression");
2900 min += minnext * mincount;
2901 is_inf_internal |= ((maxcount == REG_INFTY
2902 && (minnext + deltanext) > 0)
2903 || deltanext == I32_MAX);
2904 is_inf |= is_inf_internal;
2905 delta += (minnext + deltanext) * maxcount - minnext * mincount;
2907 /* Try powerful optimization CURLYX => CURLYN. */
2908 if ( OP(oscan) == CURLYX && data
2909 && data->flags & SF_IN_PAR
2910 && !(data->flags & SF_HAS_EVAL)
2911 && !deltanext && minnext == 1 ) {
2912 /* Try to optimize to CURLYN. */
2913 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
2914 regnode * const nxt1 = nxt;
2921 if (!strchr((const char*)PL_simple,OP(nxt))
2922 && !(PL_regkind[OP(nxt)] == EXACT
2923 && STR_LEN(nxt) == 1))
2929 if (OP(nxt) != CLOSE)
2931 if (RExC_open_parens) {
2932 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
2933 RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
2935 /* Now we know that nxt2 is the only contents: */
2936 oscan->flags = (U8)ARG(nxt);
2938 OP(nxt1) = NOTHING; /* was OPEN. */
2941 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
2942 NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
2943 NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
2944 OP(nxt) = OPTIMIZED; /* was CLOSE. */
2945 OP(nxt + 1) = OPTIMIZED; /* was count. */
2946 NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
2951 /* Try optimization CURLYX => CURLYM. */
2952 if ( OP(oscan) == CURLYX && data
2953 && !(data->flags & SF_HAS_PAR)
2954 && !(data->flags & SF_HAS_EVAL)
2955 && !deltanext /* atom is fixed width */
2956 && minnext != 0 /* CURLYM can't handle zero width */
2958 /* XXXX How to optimize if data == 0? */
2959 /* Optimize to a simpler form. */
2960 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
2964 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
2965 && (OP(nxt2) != WHILEM))
2967 OP(nxt2) = SUCCEED; /* Whas WHILEM */
2968 /* Need to optimize away parenths. */
2969 if (data->flags & SF_IN_PAR) {
2970 /* Set the parenth number. */
2971 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
2973 if (OP(nxt) != CLOSE)
2974 FAIL("Panic opt close");
2975 oscan->flags = (U8)ARG(nxt);
2976 if (RExC_open_parens) {
2977 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
2978 RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
2980 OP(nxt1) = OPTIMIZED; /* was OPEN. */
2981 OP(nxt) = OPTIMIZED; /* was CLOSE. */
2984 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
2985 OP(nxt + 1) = OPTIMIZED; /* was count. */
2986 NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
2987 NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
2990 while ( nxt1 && (OP(nxt1) != WHILEM)) {
2991 regnode *nnxt = regnext(nxt1);
2994 if (reg_off_by_arg[OP(nxt1)])
2995 ARG_SET(nxt1, nxt2 - nxt1);
2996 else if (nxt2 - nxt1 < U16_MAX)
2997 NEXT_OFF(nxt1) = nxt2 - nxt1;
2999 OP(nxt) = NOTHING; /* Cannot beautify */
3004 /* Optimize again: */
3005 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
3006 NULL, stopparen, recursed, NULL, 0,depth+1);
3011 else if ((OP(oscan) == CURLYX)
3012 && (flags & SCF_WHILEM_VISITED_POS)
3013 /* See the comment on a similar expression above.
3014 However, this time it not a subexpression
3015 we care about, but the expression itself. */
3016 && (maxcount == REG_INFTY)
3017 && data && ++data->whilem_c < 16) {
3018 /* This stays as CURLYX, we can put the count/of pair. */
3019 /* Find WHILEM (as in regexec.c) */
3020 regnode *nxt = oscan + NEXT_OFF(oscan);
3022 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
3024 PREVOPER(nxt)->flags = (U8)(data->whilem_c
3025 | (RExC_whilem_seen << 4)); /* On WHILEM */
3027 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
3029 if (flags & SCF_DO_SUBSTR) {
3030 SV *last_str = NULL;
3031 int counted = mincount != 0;
3033 if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
3034 #if defined(SPARC64_GCC_WORKAROUND)
3037 const char *s = NULL;
3040 if (pos_before >= data->last_start_min)
3043 b = data->last_start_min;
3046 s = SvPV_const(data->last_found, l);
3047 old = b - data->last_start_min;
3050 I32 b = pos_before >= data->last_start_min
3051 ? pos_before : data->last_start_min;
3053 const char * const s = SvPV_const(data->last_found, l);
3054 I32 old = b - data->last_start_min;
3058 old = utf8_hop((U8*)s, old) - (U8*)s;
3061 /* Get the added string: */
3062 last_str = newSVpvn(s + old, l);
3064 SvUTF8_on(last_str);
3065 if (deltanext == 0 && pos_before == b) {
3066 /* What was added is a constant string */
3068 SvGROW(last_str, (mincount * l) + 1);
3069 repeatcpy(SvPVX(last_str) + l,
3070 SvPVX_const(last_str), l, mincount - 1);
3071 SvCUR_set(last_str, SvCUR(last_str) * mincount);
3072 /* Add additional parts. */
3073 SvCUR_set(data->last_found,
3074 SvCUR(data->last_found) - l);
3075 sv_catsv(data->last_found, last_str);
3077 SV * sv = data->last_found;
3079 SvUTF8(sv) && SvMAGICAL(sv) ?
3080 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3081 if (mg && mg->mg_len >= 0)
3082 mg->mg_len += CHR_SVLEN(last_str);
3084 data->last_end += l * (mincount - 1);
3087 /* start offset must point into the last copy */
3088 data->last_start_min += minnext * (mincount - 1);
3089 data->last_start_max += is_inf ? I32_MAX
3090 : (maxcount - 1) * (minnext + data->pos_delta);
3093 /* It is counted once already... */
3094 data->pos_min += minnext * (mincount - counted);
3095 data->pos_delta += - counted * deltanext +
3096 (minnext + deltanext) * maxcount - minnext * mincount;
3097 if (mincount != maxcount) {
3098 /* Cannot extend fixed substrings found inside
3100 scan_commit(pRExC_state,data,minlenp);
3101 if (mincount && last_str) {
3102 SV * const sv = data->last_found;
3103 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3104 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3108 sv_setsv(sv, last_str);
3109 data->last_end = data->pos_min;
3110 data->last_start_min =
3111 data->pos_min - CHR_SVLEN(last_str);
3112 data->last_start_max = is_inf
3114 : data->pos_min + data->pos_delta
3115 - CHR_SVLEN(last_str);
3117 data->longest = &(data->longest_float);
3119 SvREFCNT_dec(last_str);
3121 if (data && (fl & SF_HAS_EVAL))
3122 data->flags |= SF_HAS_EVAL;
3123 optimize_curly_tail:
3124 if (OP(oscan) != CURLYX) {
3125 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
3127 NEXT_OFF(oscan) += NEXT_OFF(next);
3130 default: /* REF and CLUMP only? */
3131 if (flags & SCF_DO_SUBSTR) {
3132 scan_commit(pRExC_state,data,minlenp); /* Cannot expect anything... */
3133 data->longest = &(data->longest_float);
3135 is_inf = is_inf_internal = 1;
3136 if (flags & SCF_DO_STCLASS_OR)
3137 cl_anything(pRExC_state, data->start_class);
3138 flags &= ~SCF_DO_STCLASS;
3142 else if (strchr((const char*)PL_simple,OP(scan))) {
3145 if (flags & SCF_DO_SUBSTR) {
3146 scan_commit(pRExC_state,data,minlenp);
3150 if (flags & SCF_DO_STCLASS) {
3151 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3153 /* Some of the logic below assumes that switching
3154 locale on will only add false positives. */
3155 switch (PL_regkind[OP(scan)]) {
3159 /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
3160 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3161 cl_anything(pRExC_state, data->start_class);
3164 if (OP(scan) == SANY)
3166 if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
3167 value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
3168 || (data->start_class->flags & ANYOF_CLASS));
3169 cl_anything(pRExC_state, data->start_class);
3171 if (flags & SCF_DO_STCLASS_AND || !value)
3172 ANYOF_BITMAP_CLEAR(data->start_class,'\n');
3175 if (flags & SCF_DO_STCLASS_AND)
3176 cl_and(data->start_class,
3177 (struct regnode_charclass_class*)scan);
3179 cl_or(pRExC_state, data->start_class,
3180 (struct regnode_charclass_class*)scan);
3183 if (flags & SCF_DO_STCLASS_AND) {
3184 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3185 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3186 for (value = 0; value < 256; value++)
3187 if (!isALNUM(value))
3188 ANYOF_BITMAP_CLEAR(data->start_class, value);
3192 if (data->start_class->flags & ANYOF_LOCALE)
3193 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3195 for (value = 0; value < 256; value++)
3197 ANYOF_BITMAP_SET(data->start_class, value);
3202 if (flags & SCF_DO_STCLASS_AND) {
3203 if (data->start_class->flags & ANYOF_LOCALE)
3204 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3207 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3208 data->start_class->flags |= ANYOF_LOCALE;
3212 if (flags & SCF_DO_STCLASS_AND) {
3213 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3214 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3215 for (value = 0; value < 256; value++)
3217 ANYOF_BITMAP_CLEAR(data->start_class, value);
3221 if (data->start_class->flags & ANYOF_LOCALE)
3222 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3224 for (value = 0; value < 256; value++)
3225 if (!isALNUM(value))
3226 ANYOF_BITMAP_SET(data->start_class, value);
3231 if (flags & SCF_DO_STCLASS_AND) {
3232 if (data->start_class->flags & ANYOF_LOCALE)
3233 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3236 data->start_class->flags |= ANYOF_LOCALE;
3237 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3241 if (flags & SCF_DO_STCLASS_AND) {
3242 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3243 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3244 for (value = 0; value < 256; value++)
3245 if (!isSPACE(value))
3246 ANYOF_BITMAP_CLEAR(data->start_class, value);
3250 if (data->start_class->flags & ANYOF_LOCALE)
3251 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3253 for (value = 0; value < 256; value++)
3255 ANYOF_BITMAP_SET(data->start_class, value);
3260 if (flags & SCF_DO_STCLASS_AND) {
3261 if (data->start_class->flags & ANYOF_LOCALE)
3262 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3265 data->start_class->flags |= ANYOF_LOCALE;
3266 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3270 if (flags & SCF_DO_STCLASS_AND) {
3271 if (!(data->start_class->flags & ANYOF_LOCALE)) {
3272 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3273 for (value = 0; value < 256; value++)
3275 ANYOF_BITMAP_CLEAR(data->start_class, value);
3279 if (data->start_class->flags & ANYOF_LOCALE)
3280 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3282 for (value = 0; value < 256; value++)
3283 if (!isSPACE(value))
3284 ANYOF_BITMAP_SET(data->start_class, value);
3289 if (flags & SCF_DO_STCLASS_AND) {
3290 if (data->start_class->flags & ANYOF_LOCALE) {
3291 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3292 for (value = 0; value < 256; value++)
3293 if (!isSPACE(value))
3294 ANYOF_BITMAP_CLEAR(data->start_class, value);
3298 data->start_class->flags |= ANYOF_LOCALE;
3299 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3303 if (flags & SCF_DO_STCLASS_AND) {
3304 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
3305 for (value = 0; value < 256; value++)
3306 if (!isDIGIT(value))
3307 ANYOF_BITMAP_CLEAR(data->start_class, value);
3310 if (data->start_class->flags & ANYOF_LOCALE)
3311 ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
3313 for (value = 0; value < 256; value++)
3315 ANYOF_BITMAP_SET(data->start_class, value);
3320 if (flags & SCF_DO_STCLASS_AND) {
3321 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
3322 for (value = 0; value < 256; value++)
3324 ANYOF_BITMAP_CLEAR(data->start_class, value);
3327 if (data->start_class->flags & ANYOF_LOCALE)
3328 ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
3330 for (value = 0; value < 256; value++)
3331 if (!isDIGIT(value))
3332 ANYOF_BITMAP_SET(data->start_class, value);
3337 if (flags & SCF_DO_STCLASS_OR)
3338 cl_and(data->start_class, and_withp);
3339 flags &= ~SCF_DO_STCLASS;
3342 else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
3343 data->flags |= (OP(scan) == MEOL
3347 else if ( PL_regkind[OP(scan)] == BRANCHJ
3348 /* Lookbehind, or need to calculate parens/evals/stclass: */
3349 && (scan->flags || data || (flags & SCF_DO_STCLASS))
3350 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
3351 if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3352 || OP(scan) == UNLESSM )
3354 /* Negative Lookahead/lookbehind
3355 In this case we can't do fixed string optimisation.
3358 I32 deltanext, minnext, fake = 0;
3360 struct regnode_charclass_class intrnl;
3363 data_fake.flags = 0;
3365 data_fake.whilem_c = data->whilem_c;
3366 data_fake.last_closep = data->last_closep;
3369 data_fake.last_closep = &fake;
3370 if ( flags & SCF_DO_STCLASS && !scan->flags
3371 && OP(scan) == IFMATCH ) { /* Lookahead */
3372 cl_init(pRExC_state, &intrnl);
3373 data_fake.start_class = &intrnl;
3374 f |= SCF_DO_STCLASS_AND;
3376 if (flags & SCF_WHILEM_VISITED_POS)
3377 f |= SCF_WHILEM_VISITED_POS;
3378 next = regnext(scan);
3379 nscan = NEXTOPER(NEXTOPER(scan));
3380 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
3381 last, &data_fake, stopparen, recursed, NULL, f, depth+1);
3384 vFAIL("Variable length lookbehind not implemented");
3386 else if (minnext > (I32)U8_MAX) {
3387 vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3389 scan->flags = (U8)minnext;
3392 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3394 if (data_fake.flags & SF_HAS_EVAL)
3395 data->flags |= SF_HAS_EVAL;
3396 data->whilem_c = data_fake.whilem_c;
3398 if (f & SCF_DO_STCLASS_AND) {
3399 const int was = (data->start_class->flags & ANYOF_EOS);
3401 cl_and(data->start_class, &intrnl);
3403 data->start_class->flags |= ANYOF_EOS;
3406 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3408 /* Positive Lookahead/lookbehind
3409 In this case we can do fixed string optimisation,
3410 but we must be careful about it. Note in the case of
3411 lookbehind the positions will be offset by the minimum
3412 length of the pattern, something we won't know about
3413 until after the recurse.
3415 I32 deltanext, fake = 0;
3417 struct regnode_charclass_class intrnl;
3419 /* We use SAVEFREEPV so that when the full compile
3420 is finished perl will clean up the allocated
3421 minlens when its all done. This was we don't
3422 have to worry about freeing them when we know
3423 they wont be used, which would be a pain.
3426 Newx( minnextp, 1, I32 );
3427 SAVEFREEPV(minnextp);
3430 StructCopy(data, &data_fake, scan_data_t);
3431 if ((flags & SCF_DO_SUBSTR) && data->last_found) {
3434 scan_commit(pRExC_state, &data_fake,minlenp);
3435 data_fake.last_found=newSVsv(data->last_found);
3439 data_fake.last_closep = &fake;
3440 data_fake.flags = 0;
3442 data_fake.flags |= SF_IS_INF;
3443 if ( flags & SCF_DO_STCLASS && !scan->flags
3444 && OP(scan) == IFMATCH ) { /* Lookahead */
3445 cl_init(pRExC_state, &intrnl);
3446 data_fake.start_class = &intrnl;
3447 f |= SCF_DO_STCLASS_AND;
3449 if (flags & SCF_WHILEM_VISITED_POS)
3450 f |= SCF_WHILEM_VISITED_POS;
3451 next = regnext(scan);
3452 nscan = NEXTOPER(NEXTOPER(scan));
3454 *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext,
3455 last, &data_fake, stopparen, recursed, NULL, f,depth+1);
3458 vFAIL("Variable length lookbehind not implemented");
3460 else if (*minnextp > (I32)U8_MAX) {
3461 vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3463 scan->flags = (U8)*minnextp;
3468 if (f & SCF_DO_STCLASS_AND) {
3469 const int was = (data->start_class->flags & ANYOF_EOS);
3471 cl_and(data->start_class, &intrnl);
3473 data->start_class->flags |= ANYOF_EOS;
3476 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3478 if (data_fake.flags & SF_HAS_EVAL)
3479 data->flags |= SF_HAS_EVAL;
3480 data->whilem_c = data_fake.whilem_c;
3481 if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
3482 if (RExC_rx->minlen<*minnextp)
3483 RExC_rx->minlen=*minnextp;
3484 scan_commit(pRExC_state, &data_fake, minnextp);
3485 SvREFCNT_dec(data_fake.last_found);
3487 if ( data_fake.minlen_fixed != minlenp )
3489 data->offset_fixed= data_fake.offset_fixed;
3490 data->minlen_fixed= data_fake.minlen_fixed;
3491 data->lookbehind_fixed+= scan->flags;
3493 if ( data_fake.minlen_float != minlenp )
3495 data->minlen_float= data_fake.minlen_float;
3496 data->offset_float_min=data_fake.offset_float_min;
3497 data->offset_float_max=data_fake.offset_float_max;
3498 data->lookbehind_float+= scan->flags;
3507 else if (OP(scan) == OPEN) {
3508 if (stopparen != (I32)ARG(scan))
3511 else if (OP(scan) == CLOSE) {
3512 if (stopparen == (I32)ARG(scan)) {
3515 if ((I32)ARG(scan) == is_par) {
3516 next = regnext(scan);
3518 if ( next && (OP(next) != WHILEM) && next < last)
3519 is_par = 0; /* Disable optimization */
3522 *(data->last_closep) = ARG(scan);
3524 else if (OP(scan) == RECURSE || OP(scan) == SRECURSE) {
3525 /* set the pointer */
3529 if (OP(scan) == RECURSE) {
3531 RExC_recurse[ARG2L(scan)] = scan;
3532 start = RExC_open_parens[paren-1];
3533 end = RExC_close_parens[paren-1];
3536 start = RExC_rx->program + 1;
3542 Newxz(recursed, (((RExC_npar)>>3) +1), U8);
3543 SAVEFREEPV(recursed);
3545 if (!PAREN_TEST(recursed,paren+1)) {
3547 PAREN_SET(recursed,paren+1);
3549 DEBUG_PEEP("goto",start,depth);
3562 if (deltanext == I32_MAX) {
3563 is_inf = is_inf_internal = 1;
3566 DEBUG_PEEP("rtrn",end,depth);
3567 PAREN_UNSET(recursed,paren+1);
3569 if (flags & SCF_DO_SUBSTR) {
3570 scan_commit(pRExC_state,data,minlenp);
3571 data->longest = &(data->longest_float);
3573 is_inf = is_inf_internal = 1;
3574 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3575 cl_anything(pRExC_state, data->start_class);
3576 flags &= ~SCF_DO_STCLASS;
3579 else if (OP(scan) == EVAL) {
3581 data->flags |= SF_HAS_EVAL;
3583 else if ( OP(scan)==OPFAIL ) {
3584 if (flags & SCF_DO_SUBSTR) {
3585 scan_commit(pRExC_state,data,minlenp);
3586 flags &= ~SCF_DO_SUBSTR;
3589 else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
3591 if (flags & SCF_DO_SUBSTR) {
3592 scan_commit(pRExC_state,data,minlenp);
3593 data->longest = &(data->longest_float);
3595 is_inf = is_inf_internal = 1;
3596 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3597 cl_anything(pRExC_state, data->start_class);
3598 flags &= ~SCF_DO_STCLASS;
3600 #ifdef TRIE_STUDY_OPT
3601 #ifdef FULL_TRIE_STUDY
3602 else if (PL_regkind[OP(scan)] == TRIE) {
3603 /* NOTE - There is similar code to this block above for handling
3604 BRANCH nodes on the initial study. If you change stuff here
3606 regnode *trie_node= scan;
3607 regnode *tail= regnext(scan);
3608 reg_trie_data *trie = (reg_trie_data*)RExC_rx->data->data[ ARG(scan) ];
3609 I32 max1 = 0, min1 = I32_MAX;
3610 struct regnode_charclass_class accum;
3612 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
3613 scan_commit(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
3614 if (flags & SCF_DO_STCLASS)
3615 cl_init_zero(pRExC_state, &accum);
3621 const regnode *nextbranch= NULL;
3624 for ( word=1 ; word <= trie->wordcount ; word++)
3626 I32 deltanext=0, minnext=0, f = 0, fake;
3627 struct regnode_charclass_class this_class;
3629 data_fake.flags = 0;
3631 data_fake.whilem_c = data->whilem_c;
3632 data_fake.last_closep = data->last_closep;
3635 data_fake.last_closep = &fake;
3637 if (flags & SCF_DO_STCLASS) {
3638 cl_init(pRExC_state, &this_class);
3639 data_fake.start_class = &this_class;
3640 f = SCF_DO_STCLASS_AND;
3642 if (flags & SCF_WHILEM_VISITED_POS)
3643 f |= SCF_WHILEM_VISITED_POS;
3645 if (trie->jump[word]) {
3647 nextbranch = trie_node + trie->jump[0];
3648 scan= trie_node + trie->jump[word];
3649 /* We go from the jump point to the branch that follows
3650 it. Note this means we need the vestigal unused branches
3651 even though they arent otherwise used.
3653 minnext = study_chunk(pRExC_state, &scan, minlenp,
3654 &deltanext, (regnode *)nextbranch, &data_fake,
3655 stopparen, recursed, NULL, f,depth+1);
3657 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
3658 nextbranch= regnext((regnode*)nextbranch);
3660 if (min1 > (I32)(minnext + trie->minlen))
3661 min1 = minnext + trie->minlen;
3662 if (max1 < (I32)(minnext + deltanext + trie->maxlen))
3663 max1 = minnext + deltanext + trie->maxlen;
3664 if (deltanext == I32_MAX)
3665 is_inf = is_inf_internal = 1;
3667 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3671 if (data_fake.flags & SF_HAS_EVAL)
3672 data->flags |= SF_HAS_EVAL;
3673 data->whilem_c = data_fake.whilem_c;
3675 if (flags & SCF_DO_STCLASS)
3676 cl_or(pRExC_state, &accum, &this_class);
3679 if (flags & SCF_DO_SUBSTR) {
3680 data->pos_min += min1;
3681 data->pos_delta += max1 - min1;
3682 if (max1 != min1 || is_inf)
3683 data->longest = &(data->longest_float);
3686 delta += max1 - min1;
3687 if (flags & SCF_DO_STCLASS_OR) {
3688 cl_or(pRExC_state, data->start_class, &accum);
3690 cl_and(data->start_class, and_withp);
3691 flags &= ~SCF_DO_STCLASS;
3694 else if (flags & SCF_DO_STCLASS_AND) {
3696 cl_and(data->start_class, &accum);
3697 flags &= ~SCF_DO_STCLASS;
3700 /* Switch to OR mode: cache the old value of
3701 * data->start_class */
3703 StructCopy(data->start_class, and_withp,
3704 struct regnode_charclass_class);
3705 flags &= ~SCF_DO_STCLASS_AND;
3706 StructCopy(&accum, data->start_class,
3707 struct regnode_charclass_class);
3708 flags |= SCF_DO_STCLASS_OR;
3709 data->start_class->flags |= ANYOF_EOS;
3716 else if (PL_regkind[OP(scan)] == TRIE) {
3717 reg_trie_data *trie = (reg_trie_data*)RExC_rx->data->data[ ARG(scan) ];
3720 min += trie->minlen;
3721 delta += (trie->maxlen - trie->minlen);
3722 flags &= ~SCF_DO_STCLASS; /* xxx */
3723 if (flags & SCF_DO_SUBSTR) {
3724 scan_commit(pRExC_state,data,minlenp); /* Cannot expect anything... */
3725 data->pos_min += trie->minlen;
3726 data->pos_delta += (trie->maxlen - trie->minlen);
3727 if (trie->maxlen != trie->minlen)
3728 data->longest = &(data->longest_float);
3730 if (trie->jump) /* no more substrings -- for now /grr*/
3731 flags &= ~SCF_DO_SUBSTR;
3733 #endif /* old or new */
3734 #endif /* TRIE_STUDY_OPT */
3735 /* Else: zero-length, ignore. */
3736 scan = regnext(scan);
3741 *deltap = is_inf_internal ? I32_MAX : delta;
3742 if (flags & SCF_DO_SUBSTR && is_inf)
3743 data->pos_delta = I32_MAX - data->pos_min;
3744 if (is_par > (I32)U8_MAX)
3746 if (is_par && pars==1 && data) {
3747 data->flags |= SF_IN_PAR;
3748 data->flags &= ~SF_HAS_PAR;
3750 else if (pars && data) {
3751 data->flags |= SF_HAS_PAR;
3752 data->flags &= ~SF_IN_PAR;
3754 if (flags & SCF_DO_STCLASS_OR)
3755 cl_and(data->start_class, and_withp);
3756 if (flags & SCF_TRIE_RESTUDY)
3757 data->flags |= SCF_TRIE_RESTUDY;
3759 DEBUG_STUDYDATA(data,depth);
3765 S_add_data(RExC_state_t *pRExC_state, I32 n, const char *s)
3767 if (RExC_rx->data) {
3768 const U32 count = RExC_rx->data->count;
3769 Renewc(RExC_rx->data,
3770 sizeof(*RExC_rx->data) + sizeof(void*) * (count + n - 1),
3771 char, struct reg_data);
3772 Renew(RExC_rx->data->what, count + n, U8);
3773 RExC_rx->data->count += n;
3776 Newxc(RExC_rx->data, sizeof(*RExC_rx->data) + sizeof(void*) * (n - 1),
3777 char, struct reg_data);
3778 Newx(RExC_rx->data->what, n, U8);
3779 RExC_rx->data->count = n;
3781 Copy(s, RExC_rx->data->what + RExC_rx->data->count - n, n, U8);
3782 return RExC_rx->data->count - n;
3785 #ifndef PERL_IN_XSUB_RE
3787 Perl_reginitcolors(pTHX)
3790 const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
3792 char *t = savepv(s);
3796 t = strchr(t, '\t');
3802 PL_colors[i] = t = (char *)"";
3807 PL_colors[i++] = (char *)"";
3814 #ifdef TRIE_STUDY_OPT
3815 #define CHECK_RESTUDY_GOTO \
3817 (data.flags & SCF_TRIE_RESTUDY) \
3821 #define CHECK_RESTUDY_GOTO
3825 - pregcomp - compile a regular expression into internal code
3827 * We can't allocate space until we know how big the compiled form will be,
3828 * but we can't compile it (and thus know how big it is) until we've got a
3829 * place to put the code. So we cheat: we compile it twice, once with code
3830 * generation turned off and size counting turned on, and once "for real".
3831 * This also means that we don't allocate space until we are sure that the
3832 * thing really will compile successfully, and we never have to move the
3833 * code and thus invalidate pointers into it. (Note that it has to be in
3834 * one piece because free() must be able to free it all.) [NB: not true in perl]
3836 * Beware that the optimization-preparation code in here knows about some
3837 * of the structure of the compiled regexp. [I'll say.]
3842 #ifndef PERL_IN_XSUB_RE
3843 #define RE_ENGINE_PTR &PL_core_reg_engine
3845 extern const struct regexp_engine my_reg_engine;
3846 #define RE_ENGINE_PTR &my_reg_engine
3848 /* these make a few things look better, to avoid indentation */
3849 #define BEGIN_BLOCK {
3853 Perl_pregcomp(pTHX_ char *exp, char *xend, PMOP *pm)
3856 GET_RE_DEBUG_FLAGS_DECL;
3857 DEBUG_r(if (!PL_colorset) reginitcolors());
3858 #ifndef PERL_IN_XSUB_RE
3860 /* Dispatch a request to compile a regexp to correct
3862 HV * const table = GvHV(PL_hintgv);
3864 SV **ptr= hv_fetchs(table, "regcomp", FALSE);
3865 if (ptr && SvIOK(*ptr) && SvIV(*ptr)) {
3866 const regexp_engine *eng=INT2PTR(regexp_engine*,SvIV(*ptr));
3868 PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
3871 return CALLREGCOMP_ENG(eng, exp, xend, pm);
3885 RExC_state_t RExC_state;
3886 RExC_state_t * const pRExC_state = &RExC_state;
3887 #ifdef TRIE_STUDY_OPT
3889 RExC_state_t copyRExC_state;
3892 FAIL("NULL regexp argument");
3894 RExC_utf8 = pm->op_pmdynflags & PMdf_CMP_UTF8;
3898 SV *dsv= sv_newmortal();
3899 RE_PV_QUOTED_DECL(s, RExC_utf8,
3900 dsv, RExC_precomp, (xend - exp), 60);
3901 PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
3902 PL_colors[4],PL_colors[5],s);
3904 RExC_flags = pm->op_pmflags;
3908 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
3909 RExC_seen_evals = 0;
3912 /* First pass: determine size, legality. */
3919 RExC_emit = &PL_regdummy;
3920 RExC_whilem_seen = 0;
3921 RExC_charnames = NULL;
3922 RExC_open_parens = NULL;
3923 RExC_close_parens = NULL;
3925 RExC_paren_names = NULL;
3926 RExC_recurse = NULL;
3927 RExC_recurse_count = 0;
3929 #if 0 /* REGC() is (currently) a NOP at the first pass.
3930 * Clever compilers notice this and complain. --jhi */
3931 REGC((U8)REG_MAGIC, (char*)RExC_emit);
3933 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n"));
3934 if (reg(pRExC_state, 0, &flags,1) == NULL) {
3935 RExC_precomp = NULL;
3939 PerlIO_printf(Perl_debug_log,
3940 "Required size %"IVdf" nodes\n"
3941 "Starting second pass (creation)\n",
3944 RExC_lastparse=NULL;
3946 /* Small enough for pointer-storage convention?
3947 If extralen==0, this means that we will not need long jumps. */
3948 if (RExC_size >= 0x10000L && RExC_extralen)
3949 RExC_size += RExC_extralen;
3952 if (RExC_whilem_seen > 15)
3953 RExC_whilem_seen = 15;
3955 /* Allocate space and zero-initialize. Note, the two step process
3956 of zeroing when in debug mode, thus anything assigned has to
3957 happen after that */
3958 Newxc(r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode),
3961 FAIL("Regexp out of space");
3963 /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
3964 Zero(r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode), char);
3966 /* initialization begins here */
3967 r->engine= RE_ENGINE_PTR;
3969 r->prelen = xend - exp;
3970 r->precomp = savepvn(RExC_precomp, r->prelen);
3972 #ifdef PERL_OLD_COPY_ON_WRITE
3973 r->saved_copy = NULL;
3975 r->reganch = pm->op_pmflags & PMf_COMPILETIME;
3976 r->nparens = RExC_npar - 1; /* set early to validate backrefs */
3977 r->lastparen = 0; /* mg.c reads this. */
3979 r->substrs = 0; /* Useful during FAIL. */
3980 r->startp = 0; /* Useful during FAIL. */
3984 if (RExC_seen & REG_SEEN_RECURSE) {
3985 Newxz(RExC_open_parens, RExC_npar,regnode *);
3986 SAVEFREEPV(RExC_open_parens);
3987 Newxz(RExC_close_parens,RExC_npar,regnode *);
3988 SAVEFREEPV(RExC_close_parens);
3991 /* Useful during FAIL. */
3992 Newxz(r->offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
3994 r->offsets[0] = RExC_size;
3996 DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
3997 "%s %"UVuf" bytes for offset annotations.\n",
3998 r->offsets ? "Got" : "Couldn't get",
3999 (UV)((2*RExC_size+1) * sizeof(U32))));
4003 /* Second pass: emit code. */
4004 RExC_flags = pm->op_pmflags; /* don't let top level (?i) bleed */
4009 RExC_emit_start = r->program;
4010 RExC_emit = r->program;
4011 /* Store the count of eval-groups for security checks: */
4012 RExC_emit->next_off = (RExC_seen_evals > (I32)U16_MAX) ? U16_MAX : (U16)RExC_seen_evals;
4013 REGC((U8)REG_MAGIC, (char*) RExC_emit++);
4015 if (reg(pRExC_state, 0, &flags,1) == NULL)
4018 /* XXXX To minimize changes to RE engine we always allocate
4019 3-units-long substrs field. */
4020 Newx(r->substrs, 1, struct reg_substr_data);
4021 if (RExC_recurse_count) {
4022 Newxz(RExC_recurse,RExC_recurse_count,regnode *);
4023 SAVEFREEPV(RExC_recurse);
4027 r->minlen = minlen = sawplus = sawopen = 0;
4028 Zero(r->substrs, 1, struct reg_substr_data);
4030 #ifdef TRIE_STUDY_OPT
4032 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
4033 RExC_state=copyRExC_state;
4034 if (data.last_found) {
4035 SvREFCNT_dec(data.longest_fixed);
4036 SvREFCNT_dec(data.longest_float);
4037 SvREFCNT_dec(data.last_found);
4039 StructCopy(&zero_scan_data, &data, scan_data_t);
4041 StructCopy(&zero_scan_data, &data, scan_data_t);
4042 copyRExC_state=RExC_state;
4045 StructCopy(&zero_scan_data, &data, scan_data_t);
4048 /* Dig out information for optimizations. */
4049 r->reganch = pm->op_pmflags & PMf_COMPILETIME; /* Again? */
4050 pm->op_pmflags = RExC_flags;
4052 r->reganch |= ROPT_UTF8; /* Unicode in it? */
4053 r->regstclass = NULL;
4054 if (RExC_naughty >= 10) /* Probably an expensive pattern. */
4055 r->reganch |= ROPT_NAUGHTY;
4056 scan = r->program + 1; /* First BRANCH. */
4058 /* testing for BRANCH here tells us whether there is "must appear"
4059 data in the pattern. If there is then we can use it for optimisations */
4060 if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES)) { /* Only one top-level choice. */
4062 STRLEN longest_float_length, longest_fixed_length;
4063 struct regnode_charclass_class ch_class; /* pointed to by data */
4065 I32 last_close = 0; /* pointed to by data */
4068 /* Skip introductions and multiplicators >= 1. */
4069 while ((OP(first) == OPEN && (sawopen = 1)) ||
4070 /* An OR of *one* alternative - should not happen now. */
4071 (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
4072 /* for now we can't handle lookbehind IFMATCH*/
4073 (OP(first) == IFMATCH && !first->flags) ||
4074 (OP(first) == PLUS) ||
4075 (OP(first) == MINMOD) ||
4076 /* An {n,m} with n>0 */
4077 (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) )
4080 if (OP(first) == PLUS)
4083 first += regarglen[OP(first)];
4084 if (OP(first) == IFMATCH) {
4085 first = NEXTOPER(first);
4086 first += EXTRA_STEP_2ARGS;
4087 } else /* XXX possible optimisation for /(?=)/ */
4088 first = NEXTOPER(first);
4091 /* Starting-point info. */
4093 DEBUG_PEEP("first:",first,0);
4094 /* Ignore EXACT as we deal with it later. */
4095 if (PL_regkind[OP(first)] == EXACT) {
4096 if (OP(first) == EXACT)
4097 NOOP; /* Empty, get anchored substr later. */
4098 else if ((OP(first) == EXACTF || OP(first) == EXACTFL))
4099 r->regstclass = first;
4102 else if (PL_regkind[OP(first)] == TRIE &&
4103 ((reg_trie_data *)r->data->data[ ARG(first) ])->minlen>0)
4106 /* this can happen only on restudy */
4107 if ( OP(first) == TRIE ) {
4108 struct regnode_1 *trieop;
4109 Newxz(trieop,1,struct regnode_1);
4110 StructCopy(first,trieop,struct regnode_1);
4111 trie_op=(regnode *)trieop;
4113 struct regnode_charclass *trieop;
4114 Newxz(trieop,1,struct regnode_charclass);
4115 StructCopy(first,trieop,struct regnode_charclass);
4116 trie_op=(regnode *)trieop;
4119 make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
4120 r->regstclass = trie_op;
4123 else if (strchr((const char*)PL_simple,OP(first)))
4124 r->regstclass = first;
4125 else if (PL_regkind[OP(first)] == BOUND ||
4126 PL_regkind[OP(first)] == NBOUND)
4127 r->regstclass = first;
4128 else if (PL_regkind[OP(first)] == BOL) {
4129 r->reganch |= (OP(first) == MBOL
4131 : (OP(first) == SBOL
4134 first = NEXTOPER(first);
4137 else if (OP(first) == GPOS) {
4138 r->reganch |= ROPT_ANCH_GPOS;
4139 first = NEXTOPER(first);
4142 else if (!sawopen && (OP(first) == STAR &&
4143 PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
4144 !(r->reganch & ROPT_ANCH) )
4146 /* turn .* into ^.* with an implied $*=1 */
4148 (OP(NEXTOPER(first)) == REG_ANY)
4151 r->reganch |= type | ROPT_IMPLICIT;
4152 first = NEXTOPER(first);
4155 if (sawplus && (!sawopen || !RExC_sawback)
4156 && !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
4157 /* x+ must match at the 1st pos of run of x's */
4158 r->reganch |= ROPT_SKIP;
4160 /* Scan is after the zeroth branch, first is atomic matcher. */
4161 #ifdef TRIE_STUDY_OPT
4164 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4165 (IV)(first - scan + 1))
4169 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4170 (IV)(first - scan + 1))
4176 * If there's something expensive in the r.e., find the
4177 * longest literal string that must appear and make it the
4178 * regmust. Resolve ties in favor of later strings, since
4179 * the regstart check works with the beginning of the r.e.
4180 * and avoiding duplication strengthens checking. Not a
4181 * strong reason, but sufficient in the absence of others.
4182 * [Now we resolve ties in favor of the earlier string if
4183 * it happens that c_offset_min has been invalidated, since the
4184 * earlier string may buy us something the later one won't.]
4188 data.longest_fixed = newSVpvs("");
4189 data.longest_float = newSVpvs("");
4190 data.last_found = newSVpvs("");
4191 data.longest = &(data.longest_fixed);
4193 if (!r->regstclass) {
4194 cl_init(pRExC_state, &ch_class);
4195 data.start_class = &ch_class;
4196 stclass_flag = SCF_DO_STCLASS_AND;
4197 } else /* XXXX Check for BOUND? */
4199 data.last_closep = &last_close;
4201 minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
4202 &data, -1, NULL, NULL,
4203 SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag,0);
4209 if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
4210 && data.last_start_min == 0 && data.last_end > 0
4211 && !RExC_seen_zerolen
4212 && (!(RExC_seen & REG_SEEN_GPOS) || (r->reganch & ROPT_ANCH_GPOS)))
4213 r->reganch |= ROPT_CHECK_ALL;
4214 scan_commit(pRExC_state, &data,&minlen);
4215 SvREFCNT_dec(data.last_found);
4217 /* Note that code very similar to this but for anchored string
4218 follows immediately below, changes may need to be made to both.
4221 longest_float_length = CHR_SVLEN(data.longest_float);
4222 if (longest_float_length
4223 || (data.flags & SF_FL_BEFORE_EOL
4224 && (!(data.flags & SF_FL_BEFORE_MEOL)
4225 || (RExC_flags & PMf_MULTILINE))))
4229 if (SvCUR(data.longest_fixed) /* ok to leave SvCUR */
4230 && data.offset_fixed == data.offset_float_min
4231 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
4232 goto remove_float; /* As in (a)+. */
4234 /* copy the information about the longest float from the reg_scan_data
4235 over to the program. */
4236 if (SvUTF8(data.longest_float)) {
4237 r->float_utf8 = data.longest_float;
4238 r->float_substr = NULL;
4240 r->float_substr = data.longest_float;
4241 r->float_utf8 = NULL;
4243 /* float_end_shift is how many chars that must be matched that
4244 follow this item. We calculate it ahead of time as once the
4245 lookbehind offset is added in we lose the ability to correctly
4247 ml = data.minlen_float ? *(data.minlen_float)
4248 : (I32)longest_float_length;
4249 r->float_end_shift = ml - data.offset_float_min
4250 - longest_float_length + (SvTAIL(data.longest_float) != 0)
4251 + data.lookbehind_float;
4252 r->float_min_offset = data.offset_float_min - data.lookbehind_float;
4253 r->float_max_offset = data.offset_float_max;
4254 if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
4255 r->float_max_offset -= data.lookbehind_float;
4257 t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
4258 && (!(data.flags & SF_FL_BEFORE_MEOL)
4259 || (RExC_flags & PMf_MULTILINE)));
4260 fbm_compile(data.longest_float, t ? FBMcf_TAIL : 0);
4264 r->float_substr = r->float_utf8 = NULL;
4265 SvREFCNT_dec(data.longest_float);
4266 longest_float_length = 0;
4269 /* Note that code very similar to this but for floating string
4270 is immediately above, changes may need to be made to both.
4273 longest_fixed_length = CHR_SVLEN(data.longest_fixed);
4274 if (longest_fixed_length
4275 || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
4276 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4277 || (RExC_flags & PMf_MULTILINE))))
4281 /* copy the information about the longest fixed
4282 from the reg_scan_data over to the program. */
4283 if (SvUTF8(data.longest_fixed)) {
4284 r->anchored_utf8 = data.longest_fixed;
4285 r->anchored_substr = NULL;
4287 r->anchored_substr = data.longest_fixed;
4288 r->anchored_utf8 = NULL;
4290 /* fixed_end_shift is how many chars that must be matched that
4291 follow this item. We calculate it ahead of time as once the
4292 lookbehind offset is added in we lose the ability to correctly
4294 ml = data.minlen_fixed ? *(data.minlen_fixed)
4295 : (I32)longest_fixed_length;
4296 r->anchored_end_shift = ml - data.offset_fixed
4297 - longest_fixed_length + (SvTAIL(data.longest_fixed) != 0)
4298 + data.lookbehind_fixed;
4299 r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
4301 t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
4302 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4303 || (RExC_flags & PMf_MULTILINE)));
4304 fbm_compile(data.longest_fixed, t ? FBMcf_TAIL : 0);
4307 r->anchored_substr = r->anchored_utf8 = NULL;
4308 SvREFCNT_dec(data.longest_fixed);
4309 longest_fixed_length = 0;
4312 && (OP(r->regstclass) == REG_ANY || OP(r->regstclass) == SANY))
4313 r->regstclass = NULL;
4314 if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
4316 && !(data.start_class->flags & ANYOF_EOS)
4317 && !cl_is_anything(data.start_class))
4319 const I32 n = add_data(pRExC_state, 1, "f");
4321 Newx(RExC_rx->data->data[n], 1,
4322 struct regnode_charclass_class);
4323 StructCopy(data.start_class,
4324 (struct regnode_charclass_class*)RExC_rx->data->data[n],
4325 struct regnode_charclass_class);
4326 r->regstclass = (regnode*)RExC_rx->data->data[n];
4327 r->reganch &= ~ROPT_SKIP; /* Used in find_byclass(). */
4328 DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
4329 regprop(r, sv, (regnode*)data.start_class);
4330 PerlIO_printf(Perl_debug_log,
4331 "synthetic stclass \"%s\".\n",
4332 SvPVX_const(sv));});
4335 /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
4336 if (longest_fixed_length > longest_float_length) {
4337 r->check_end_shift = r->anchored_end_shift;
4338 r->check_substr = r->anchored_substr;
4339 r->check_utf8 = r->anchored_utf8;
4340 r->check_offset_min = r->check_offset_max = r->anchored_offset;
4341 if (r->reganch & ROPT_ANCH_SINGLE)
4342 r->reganch |= ROPT_NOSCAN;
4345 r->check_end_shift = r->float_end_shift;
4346 r->check_substr = r->float_substr;
4347 r->check_utf8 = r->float_utf8;
4348 r->check_offset_min = r->float_min_offset;
4349 r->check_offset_max = r->float_max_offset;
4351 /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
4352 This should be changed ASAP! */
4353 if ((r->check_substr || r->check_utf8) && !(r->reganch & ROPT_ANCH_GPOS)) {
4354 r->reganch |= RE_USE_INTUIT;
4355 if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
4356 r->reganch |= RE_INTUIT_TAIL;
4358 /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
4359 if ( (STRLEN)minlen < longest_float_length )
4360 minlen= longest_float_length;
4361 if ( (STRLEN)minlen < longest_fixed_length )
4362 minlen= longest_fixed_length;
4366 /* Several toplevels. Best we can is to set minlen. */
4368 struct regnode_charclass_class ch_class;
4371 DEBUG_COMPILE_r(PerlIO_printf(Perl_debug_log, "\n"));
4373 scan = r->program + 1;
4374 cl_init(pRExC_state, &ch_class);
4375 data.start_class = &ch_class;
4376 data.last_closep = &last_close;
4378 minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
4379 &data, -1, NULL, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS,0);
4383 r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
4384 = r->float_substr = r->float_utf8 = NULL;
4385 if (!(data.start_class->flags & ANYOF_EOS)
4386 && !cl_is_anything(data.start_class))
4388 const I32 n = add_data(pRExC_state, 1, "f");
4390 Newx(RExC_rx->data->data[n], 1,
4391 struct regnode_charclass_class);
4392 StructCopy(data.start_class,
4393 (struct regnode_charclass_class*)RExC_rx->data->data[n],
4394 struct regnode_charclass_class);
4395 r->regstclass = (regnode*)RExC_rx->data->data[n];
4396 r->reganch &= ~ROPT_SKIP; /* Used in find_byclass(). */
4397 DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
4398 regprop(r, sv, (regnode*)data.start_class);
4399 PerlIO_printf(Perl_debug_log,
4400 "synthetic stclass \"%s\".\n",
4401 SvPVX_const(sv));});
4405 /* Guard against an embedded (?=) or (?<=) with a longer minlen than
4406 the "real" pattern. */
4407 if (r->minlen < minlen)
4410 if (RExC_seen & REG_SEEN_GPOS)
4411 r->reganch |= ROPT_GPOS_SEEN;
4412 if (RExC_seen & REG_SEEN_LOOKBEHIND)
4413 r->reganch |= ROPT_LOOKBEHIND_SEEN;
4414 if (RExC_seen & REG_SEEN_EVAL)
4415 r->reganch |= ROPT_EVAL_SEEN;
4416 if (RExC_seen & REG_SEEN_CANY)
4417 r->reganch |= ROPT_CANY_SEEN;
4418 if (RExC_paren_names)
4419 r->paren_names = (HV*)SvREFCNT_inc(RExC_paren_names);
4421 r->paren_names = NULL;
4423 if (RExC_recurse_count) {
4424 for ( ; RExC_recurse_count ; RExC_recurse_count-- ) {
4425 const regnode *scan = RExC_recurse[RExC_recurse_count-1];
4426 ARG2L_SET( scan, RExC_open_parens[ARG(scan)-1] - scan );
4429 Newxz(r->startp, RExC_npar, I32);
4430 Newxz(r->endp, RExC_npar, I32);
4432 DEBUG_r( RX_DEBUG_on(r) );
4434 PerlIO_printf(Perl_debug_log,"Final program:\n");
4437 DEBUG_OFFSETS_r(if (r->offsets) {
4438 const U32 len = r->offsets[0];
4440 GET_RE_DEBUG_FLAGS_DECL;
4441 PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)r->offsets[0]);
4442 for (i = 1; i <= len; i++) {
4443 if (r->offsets[i*2-1] || r->offsets[i*2])
4444 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
4445 (UV)i, (UV)r->offsets[i*2-1], (UV)r->offsets[i*2]);
4447 PerlIO_printf(Perl_debug_log, "\n");
4453 #undef CORE_ONLY_BLOCK
4455 #undef RE_ENGINE_PTR
4457 #ifndef PERL_IN_XSUB_RE
4459 Perl_reg_named_buff_sv(pTHX_ SV* namesv)
4461 I32 parno = 0; /* no match */
4463 const REGEXP * const rx = PM_GETRE(PL_curpm);
4464 if (rx && rx->paren_names) {
4465 HE *he_str = hv_fetch_ent( rx->paren_names, namesv, 0, 0 );
4468 SV* sv_dat=HeVAL(he_str);
4469 I32 *nums=(I32*)SvPVX(sv_dat);
4470 for ( i=0; i<SvIVX(sv_dat); i++ ) {
4471 if ((I32)(rx->lastparen) >= nums[i] &&
4472 rx->endp[nums[i]] != -1)
4485 SV *sv= sv_newmortal();
4486 Perl_sv_setpvf(aTHX_ sv, "%"IVdf,(IV)parno);
4487 gv_paren= Perl_gv_fetchsv(aTHX_ sv, GV_ADD, SVt_PVGV);
4488 return GvSVn(gv_paren);
4493 /* Scans the name of a named buffer from the pattern.
4494 * If flags is REG_RSN_RETURN_NULL returns null.
4495 * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
4496 * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
4497 * to the parsed name as looked up in the RExC_paren_names hash.
4498 * If there is an error throws a vFAIL().. type exception.
4501 #define REG_RSN_RETURN_NULL 0
4502 #define REG_RSN_RETURN_NAME 1
4503 #define REG_RSN_RETURN_DATA 2
4506 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags) {
4507 char *name_start = RExC_parse;
4510 while( isIDFIRST_uni(utf8n_to_uvchr((U8*)RExC_parse,
4511 RExC_end - RExC_parse, &numlen, UTF8_ALLOW_DEFAULT)))
4513 RExC_parse += numlen;
4516 while( isIDFIRST(*RExC_parse) )
4520 SV* sv_name = sv_2mortal(Perl_newSVpvn(aTHX_ name_start,
4521 (int)(RExC_parse - name_start)));
4524 if ( flags == REG_RSN_RETURN_NAME)
4526 else if (flags==REG_RSN_RETURN_DATA) {
4529 if ( ! sv_name ) /* should not happen*/
4530 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
4531 if (RExC_paren_names)
4532 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
4534 sv_dat = HeVAL(he_str);
4536 vFAIL("Reference to nonexistent named group");
4540 Perl_croak(aTHX_ "panic: bad flag in reg_scan_name");
4547 #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
4548 int rem=(int)(RExC_end - RExC_parse); \
4557 if (RExC_lastparse!=RExC_parse) \
4558 PerlIO_printf(Perl_debug_log," >%.*s%-*s", \
4561 iscut ? "..." : "<" \
4564 PerlIO_printf(Perl_debug_log,"%16s",""); \
4569 num=REG_NODE_NUM(RExC_emit); \
4570 if (RExC_lastnum!=num) \
4571 PerlIO_printf(Perl_debug_log,"|%4d",num); \
4573 PerlIO_printf(Perl_debug_log,"|%4s",""); \
4574 PerlIO_printf(Perl_debug_log,"|%*s%-4s", \
4575 (int)((depth*2)), "", \
4579 RExC_lastparse=RExC_parse; \
4584 #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
4585 DEBUG_PARSE_MSG((funcname)); \
4586 PerlIO_printf(Perl_debug_log,"%4s","\n"); \
4588 #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({ \
4589 DEBUG_PARSE_MSG((funcname)); \
4590 PerlIO_printf(Perl_debug_log,fmt "\n",args); \
4593 - reg - regular expression, i.e. main body or parenthesized thing
4595 * Caller must absorb opening parenthesis.
4597 * Combining parenthesis handling with the base level of regular expression
4598 * is a trifle forced, but the need to tie the tails of the branches to what
4599 * follows makes it hard to avoid.
4601 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
4603 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
4605 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
4609 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
4610 /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
4613 register regnode *ret; /* Will be the head of the group. */
4614 register regnode *br;
4615 register regnode *lastbr;
4616 register regnode *ender = NULL;
4617 register I32 parno = 0;
4619 const I32 oregflags = RExC_flags;
4620 bool have_branch = 0;
4623 /* for (?g), (?gc), and (?o) warnings; warning
4624 about (?c) will warn about (?g) -- japhy */
4626 #define WASTED_O 0x01
4627 #define WASTED_G 0x02
4628 #define WASTED_C 0x04
4629 #define WASTED_GC (0x02|0x04)
4630 I32 wastedflags = 0x00;
4632 char * parse_start = RExC_parse; /* MJD */
4633 char * const oregcomp_parse = RExC_parse;
4635 GET_RE_DEBUG_FLAGS_DECL;
4636 DEBUG_PARSE("reg ");
4639 *flagp = 0; /* Tentatively. */
4642 /* Make an OPEN node, if parenthesized. */
4644 if (*RExC_parse == '?') { /* (?...) */
4645 U32 posflags = 0, negflags = 0;
4646 U32 *flagsp = &posflags;
4647 bool is_logical = 0;
4648 const char * const seqstart = RExC_parse;
4651 paren = *RExC_parse++;
4652 ret = NULL; /* For look-ahead/behind. */
4655 case '<': /* (?<...) */
4656 if (*RExC_parse == '!')
4658 else if (*RExC_parse != '=')
4663 case '\'': /* (?'...') */
4664 name_start= RExC_parse;
4665 svname = reg_scan_name(pRExC_state,
4666 SIZE_ONLY ? /* reverse test from the others */
4667 REG_RSN_RETURN_NAME :
4668 REG_RSN_RETURN_NULL);
4669 if (RExC_parse == name_start)
4671 if (*RExC_parse != paren)
4672 vFAIL2("Sequence (?%c... not terminated",
4673 paren=='>' ? '<' : paren);
4677 if (!svname) /* shouldnt happen */
4679 "panic: reg_scan_name returned NULL");
4680 if (!RExC_paren_names) {
4681 RExC_paren_names= newHV();
4682 sv_2mortal((SV*)RExC_paren_names);
4684 he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
4686 sv_dat = HeVAL(he_str);
4688 /* croak baby croak */
4690 "panic: paren_name hash element allocation failed");
4691 } else if ( SvPOK(sv_dat) ) {
4692 IV count=SvIV(sv_dat);
4693 I32 *pv=(I32*)SvGROW(sv_dat,SvCUR(sv_dat)+sizeof(I32)+1);
4694 SvCUR_set(sv_dat,SvCUR(sv_dat)+sizeof(I32));
4695 pv[count]=RExC_npar;
4698 (void)SvUPGRADE(sv_dat,SVt_PVNV);
4699 sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32));
4704 /*sv_dump(sv_dat);*/
4706 nextchar(pRExC_state);
4708 goto capturing_parens;
4710 RExC_seen |= REG_SEEN_LOOKBEHIND;
4712 case '=': /* (?=...) */
4713 case '!': /* (?!...) */
4714 if (*RExC_parse == ')')
4716 RExC_seen_zerolen++;
4717 case ':': /* (?:...) */
4718 case '>': /* (?>...) */
4721 if (RExC_parse[0] == 'A' &&
4722 RExC_parse[1] == 'I' &&
4723 RExC_parse[2] == 'L')
4725 if (*RExC_parse != ')')
4726 vFAIL("Sequence (?FAIL) or (?F) not terminated");
4728 ret = reg_node(pRExC_state, OPFAIL);
4729 nextchar(pRExC_state);
4732 case '$': /* (?$...) */
4733 case '@': /* (?@...) */
4734 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
4736 case '#': /* (?#...) */
4737 while (*RExC_parse && *RExC_parse != ')')
4739 if (*RExC_parse != ')')
4740 FAIL("Sequence (?#... not terminated");
4741 nextchar(pRExC_state);
4744 case '0' : /* (?0) */
4745 case 'R' : /* (?R) */
4746 if (*RExC_parse != ')')
4747 FAIL("Sequence (?R) not terminated");
4748 ret = reg_node(pRExC_state, SRECURSE);
4749 nextchar(pRExC_state);
4752 { /* named and numeric backreferences */
4755 case '&': /* (?&NAME) */
4756 parse_start = RExC_parse - 1;
4758 SV *sv_dat = reg_scan_name(pRExC_state,
4759 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
4760 num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
4762 goto gen_recurse_regop;
4764 case '1': case '2': case '3': case '4': /* (?1) */
4765 case '5': case '6': case '7': case '8': case '9':
4767 num = atoi(RExC_parse);
4768 parse_start = RExC_parse - 1; /* MJD */
4769 while (isDIGIT(*RExC_parse))
4771 if (*RExC_parse!=')')
4772 vFAIL("Expecting close bracket");
4775 ret = reganode(pRExC_state, RECURSE, num);
4777 if (num > (I32)RExC_rx->nparens) {
4779 vFAIL("Reference to nonexistent group");
4781 ARG2L_SET( ret, RExC_recurse_count++);
4783 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
4784 "Recurse #%"UVuf" to %"IVdf"\n", (UV)ARG(ret), (IV)ARG2L(ret)));
4788 RExC_seen |= REG_SEEN_RECURSE;
4789 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
4790 Set_Node_Offset(ret, parse_start); /* MJD */
4792 nextchar(pRExC_state);
4794 } /* named and numeric backreferences */
4797 case 'p': /* (?p...) */
4798 if (SIZE_ONLY && ckWARN2(WARN_DEPRECATED, WARN_REGEXP))
4799 vWARNdep(RExC_parse, "(?p{}) is deprecated - use (??{})");
4801 case '?': /* (??...) */
4803 if (*RExC_parse != '{')
4805 paren = *RExC_parse++;
4807 case '{': /* (?{...}) */
4809 I32 count = 1, n = 0;
4811 char *s = RExC_parse;
4813 RExC_seen_zerolen++;
4814 RExC_seen |= REG_SEEN_EVAL;
4815 while (count && (c = *RExC_parse)) {
4826 if (*RExC_parse != ')') {
4828 vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
4832 OP_4tree *sop, *rop;
4833 SV * const sv = newSVpvn(s, RExC_parse - 1 - s);
4836 Perl_save_re_context(aTHX);
4837 rop = sv_compile_2op(sv, &sop, "re", &pad);
4838 sop->op_private |= OPpREFCOUNTED;
4839 /* re_dup will OpREFCNT_inc */
4840 OpREFCNT_set(sop, 1);
4843 n = add_data(pRExC_state, 3, "nop");
4844 RExC_rx->data->data[n] = (void*)rop;
4845 RExC_rx->data->data[n+1] = (void*)sop;
4846 RExC_rx->data->data[n+2] = (void*)pad;
4849 else { /* First pass */
4850 if (PL_reginterp_cnt < ++RExC_seen_evals
4852 /* No compiled RE interpolated, has runtime
4853 components ===> unsafe. */
4854 FAIL("Eval-group not allowed at runtime, use re 'eval'");
4855 if (PL_tainting && PL_tainted)
4856 FAIL("Eval-group in insecure regular expression");
4857 #if PERL_VERSION > 8
4858 if (IN_PERL_COMPILETIME)
4863 nextchar(pRExC_state);
4865 ret = reg_node(pRExC_state, LOGICAL);
4868 REGTAIL(pRExC_state, ret, reganode(pRExC_state, EVAL, n));
4869 /* deal with the length of this later - MJD */
4872 ret = reganode(pRExC_state, EVAL, n);
4873 Set_Node_Length(ret, RExC_parse - parse_start + 1);
4874 Set_Node_Offset(ret, parse_start);
4877 case '(': /* (?(?{...})...) and (?(?=...)...) */
4880 if (RExC_parse[0] == '?') { /* (?(?...)) */
4881 if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
4882 || RExC_parse[1] == '<'
4883 || RExC_parse[1] == '{') { /* Lookahead or eval. */
4886 ret = reg_node(pRExC_state, LOGICAL);
4889 REGTAIL(pRExC_state, ret, reg(pRExC_state, 1, &flag,depth+1));
4893 else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
4894 || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
4896 char ch = RExC_parse[0] == '<' ? '>' : '\'';
4897 char *name_start= RExC_parse++;
4899 SV *sv_dat=reg_scan_name(pRExC_state,
4900 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
4901 if (RExC_parse == name_start || *RExC_parse != ch)
4902 vFAIL2("Sequence (?(%c... not terminated",
4903 (ch == '>' ? '<' : ch));
4906 num = add_data( pRExC_state, 1, "S" );
4907 RExC_rx->data->data[num]=(void*)sv_dat;
4908 SvREFCNT_inc(sv_dat);
4910 ret = reganode(pRExC_state,NGROUPP,num);
4911 goto insert_if_check_paren;
4913 else if (RExC_parse[0] == 'D' &&
4914 RExC_parse[1] == 'E' &&
4915 RExC_parse[2] == 'F' &&
4916 RExC_parse[3] == 'I' &&
4917 RExC_parse[4] == 'N' &&
4918 RExC_parse[5] == 'E')
4920 ret = reganode(pRExC_state,DEFINEP,0);
4923 goto insert_if_check_paren;
4925 else if (RExC_parse[0] == 'R') {
4928 if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
4929 parno = atoi(RExC_parse++);
4930 while (isDIGIT(*RExC_parse))
4932 } else if (RExC_parse[0] == '&') {
4935 sv_dat = reg_scan_name(pRExC_state,
4936 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
4937 parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
4939 ret = reganode(pRExC_state,RECURSEP,parno);
4940 goto insert_if_check_paren;
4942 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
4945 parno = atoi(RExC_parse++);
4947 while (isDIGIT(*RExC_parse))
4949 ret = reganode(pRExC_state, GROUPP, parno);
4951 insert_if_check_paren:
4952 if ((c = *nextchar(pRExC_state)) != ')')
4953 vFAIL("Switch condition not recognized");
4955 REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
4956 br = regbranch(pRExC_state, &flags, 1,depth+1);
4958 br = reganode(pRExC_state, LONGJMP, 0);
4960 REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
4961 c = *nextchar(pRExC_state);
4966 vFAIL("(?(DEFINE)....) does not allow branches");
4967 lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
4968 regbranch(pRExC_state, &flags, 1,depth+1);
4969 REGTAIL(pRExC_state, ret, lastbr);
4972 c = *nextchar(pRExC_state);
4977 vFAIL("Switch (?(condition)... contains too many branches");
4978 ender = reg_node(pRExC_state, TAIL);
4979 REGTAIL(pRExC_state, br, ender);
4981 REGTAIL(pRExC_state, lastbr, ender);
4982 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
4985 REGTAIL(pRExC_state, ret, ender);
4989 vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
4993 RExC_parse--; /* for vFAIL to print correctly */
4994 vFAIL("Sequence (? incomplete");
4998 parse_flags: /* (?i) */
4999 while (*RExC_parse && strchr("iogcmsx", *RExC_parse)) {
5000 /* (?g), (?gc) and (?o) are useless here
5001 and must be globally applied -- japhy */
5003 if (*RExC_parse == 'o' || *RExC_parse == 'g') {
5004 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5005 const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
5006 if (! (wastedflags & wflagbit) ) {
5007 wastedflags |= wflagbit;
5010 "Useless (%s%c) - %suse /%c modifier",
5011 flagsp == &negflags ? "?-" : "?",
5013 flagsp == &negflags ? "don't " : "",
5019 else if (*RExC_parse == 'c') {
5020 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5021 if (! (wastedflags & WASTED_C) ) {
5022 wastedflags |= WASTED_GC;
5025 "Useless (%sc) - %suse /gc modifier",
5026 flagsp == &negflags ? "?-" : "?",
5027 flagsp == &negflags ? "don't " : ""
5032 else { pmflag(flagsp, *RExC_parse); }
5036 if (*RExC_parse == '-') {
5038 wastedflags = 0; /* reset so (?g-c) warns twice */
5042 RExC_flags |= posflags;
5043 RExC_flags &= ~negflags;
5044 if (*RExC_parse == ':') {
5050 if (*RExC_parse != ')') {
5052 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5054 nextchar(pRExC_state);
5063 ret = reganode(pRExC_state, OPEN, parno);
5064 if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
5065 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5066 "Setting open paren #%"IVdf" to %d\n",
5067 (IV)parno, REG_NODE_NUM(ret)));
5068 RExC_open_parens[parno-1]= ret;
5070 Set_Node_Length(ret, 1); /* MJD */
5071 Set_Node_Offset(ret, RExC_parse); /* MJD */
5078 /* Pick up the branches, linking them together. */
5079 parse_start = RExC_parse; /* MJD */
5080 br = regbranch(pRExC_state, &flags, 1,depth+1);
5081 /* branch_len = (paren != 0); */
5085 if (*RExC_parse == '|') {
5086 if (!SIZE_ONLY && RExC_extralen) {
5087 reginsert(pRExC_state, BRANCHJ, br, depth+1);
5090 reginsert(pRExC_state, BRANCH, br, depth+1);
5091 Set_Node_Length(br, paren != 0);
5092 Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
5096 RExC_extralen += 1; /* For BRANCHJ-BRANCH. */
5098 else if (paren == ':') {
5099 *flagp |= flags&SIMPLE;
5101 if (is_open) { /* Starts with OPEN. */
5102 REGTAIL(pRExC_state, ret, br); /* OPEN -> first. */
5104 else if (paren != '?') /* Not Conditional */
5106 *flagp |= flags & (SPSTART | HASWIDTH);
5108 while (*RExC_parse == '|') {
5109 if (!SIZE_ONLY && RExC_extralen) {
5110 ender = reganode(pRExC_state, LONGJMP,0);
5111 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
5114 RExC_extralen += 2; /* Account for LONGJMP. */
5115 nextchar(pRExC_state);
5116 br = regbranch(pRExC_state, &flags, 0, depth+1);
5120 REGTAIL(pRExC_state, lastbr, br); /* BRANCH -> BRANCH. */
5124 *flagp |= flags&SPSTART;
5127 if (have_branch || paren != ':') {
5128 /* Make a closing node, and hook it on the end. */
5131 ender = reg_node(pRExC_state, TAIL);
5134 ender = reganode(pRExC_state, CLOSE, parno);
5135 if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
5136 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5137 "Setting close paren #%"IVdf" to %d\n",
5138 (IV)parno, REG_NODE_NUM(ender)));
5139 RExC_close_parens[parno-1]= ender;
5141 Set_Node_Offset(ender,RExC_parse+1); /* MJD */
5142 Set_Node_Length(ender,1); /* MJD */
5148 *flagp &= ~HASWIDTH;
5151 ender = reg_node(pRExC_state, SUCCEED);
5154 ender = reg_node(pRExC_state, END);
5156 assert(!RExC_opend); /* there can only be one! */
5161 REGTAIL(pRExC_state, lastbr, ender);
5163 if (have_branch && !SIZE_ONLY) {
5165 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
5167 /* Hook the tails of the branches to the closing node. */
5168 for (br = ret; br; br = regnext(br)) {
5169 const U8 op = PL_regkind[OP(br)];
5171 REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
5173 else if (op == BRANCHJ) {
5174 REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
5182 static const char parens[] = "=!<,>";
5184 if (paren && (p = strchr(parens, paren))) {
5185 U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
5186 int flag = (p - parens) > 1;
5189 node = SUSPEND, flag = 0;
5190 reginsert(pRExC_state, node,ret, depth+1);
5191 Set_Node_Cur_Length(ret);
5192 Set_Node_Offset(ret, parse_start + 1);
5194 REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
5198 /* Check for proper termination. */
5200 RExC_flags = oregflags;
5201 if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
5202 RExC_parse = oregcomp_parse;
5203 vFAIL("Unmatched (");
5206 else if (!paren && RExC_parse < RExC_end) {
5207 if (*RExC_parse == ')') {
5209 vFAIL("Unmatched )");
5212 FAIL("Junk on end of regexp"); /* "Can't happen". */
5220 - regbranch - one alternative of an | operator
5222 * Implements the concatenation operator.
5225 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
5228 register regnode *ret;
5229 register regnode *chain = NULL;
5230 register regnode *latest;
5231 I32 flags = 0, c = 0;
5232 GET_RE_DEBUG_FLAGS_DECL;
5233 DEBUG_PARSE("brnc");
5237 if (!SIZE_ONLY && RExC_extralen)
5238 ret = reganode(pRExC_state, BRANCHJ,0);
5240 ret = reg_node(pRExC_state, BRANCH);
5241 Set_Node_Length(ret, 1);
5245 if (!first && SIZE_ONLY)
5246 RExC_extralen += 1; /* BRANCHJ */
5248 *flagp = WORST; /* Tentatively. */
5251 nextchar(pRExC_state);
5252 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
5254 latest = regpiece(pRExC_state, &flags,depth+1);
5255 if (latest == NULL) {
5256 if (flags & TRYAGAIN)
5260 else if (ret == NULL)
5262 *flagp |= flags&HASWIDTH;
5263 if (chain == NULL) /* First piece. */
5264 *flagp |= flags&SPSTART;
5267 REGTAIL(pRExC_state, chain, latest);
5272 if (chain == NULL) { /* Loop ran zero times. */
5273 chain = reg_node(pRExC_state, NOTHING);
5278 *flagp |= flags&SIMPLE;
5285 - regpiece - something followed by possible [*+?]
5287 * Note that the branching code sequences used for ? and the general cases
5288 * of * and + are somewhat optimized: they use the same NOTHING node as
5289 * both the endmarker for their branch list and the body of the last branch.
5290 * It might seem that this node could be dispensed with entirely, but the
5291 * endmarker role is not redundant.
5294 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
5297 register regnode *ret;
5299 register char *next;
5301 const char * const origparse = RExC_parse;
5303 I32 max = REG_INFTY;
5305 const char *maxpos = NULL;
5306 GET_RE_DEBUG_FLAGS_DECL;
5307 DEBUG_PARSE("piec");
5309 ret = regatom(pRExC_state, &flags,depth+1);
5311 if (flags & TRYAGAIN)
5318 if (op == '{' && regcurly(RExC_parse)) {
5320 parse_start = RExC_parse; /* MJD */
5321 next = RExC_parse + 1;
5322 while (isDIGIT(*next) || *next == ',') {
5331 if (*next == '}') { /* got one */
5335 min = atoi(RExC_parse);
5339 maxpos = RExC_parse;
5341 if (!max && *maxpos != '0')
5342 max = REG_INFTY; /* meaning "infinity" */
5343 else if (max >= REG_INFTY)
5344 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
5346 nextchar(pRExC_state);
5349 if ((flags&SIMPLE)) {
5350 RExC_naughty += 2 + RExC_naughty / 2;
5351 reginsert(pRExC_state, CURLY, ret, depth+1);
5352 Set_Node_Offset(ret, parse_start+1); /* MJD */
5353 Set_Node_Cur_Length(ret);
5356 regnode * const w = reg_node(pRExC_state, WHILEM);
5359 REGTAIL(pRExC_state, ret, w);
5360 if (!SIZE_ONLY && RExC_extralen) {
5361 reginsert(pRExC_state, LONGJMP,ret, depth+1);
5362 reginsert(pRExC_state, NOTHING,ret, depth+1);
5363 NEXT_OFF(ret) = 3; /* Go over LONGJMP. */
5365 reginsert(pRExC_state, CURLYX,ret, depth+1);
5367 Set_Node_Offset(ret, parse_start+1);
5368 Set_Node_Length(ret,
5369 op == '{' ? (RExC_parse - parse_start) : 1);
5371 if (!SIZE_ONLY && RExC_extralen)
5372 NEXT_OFF(ret) = 3; /* Go over NOTHING to LONGJMP. */
5373 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
5375 RExC_whilem_seen++, RExC_extralen += 3;
5376 RExC_naughty += 4 + RExC_naughty; /* compound interest */
5384 if (max && max < min)
5385 vFAIL("Can't do {n,m} with n > m");
5387 ARG1_SET(ret, (U16)min);
5388 ARG2_SET(ret, (U16)max);
5400 #if 0 /* Now runtime fix should be reliable. */
5402 /* if this is reinstated, don't forget to put this back into perldiag:
5404 =item Regexp *+ operand could be empty at {#} in regex m/%s/
5406 (F) The part of the regexp subject to either the * or + quantifier
5407 could match an empty string. The {#} shows in the regular
5408 expression about where the problem was discovered.
5412 if (!(flags&HASWIDTH) && op != '?')
5413 vFAIL("Regexp *+ operand could be empty");
5416 parse_start = RExC_parse;
5417 nextchar(pRExC_state);
5419 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
5421 if (op == '*' && (flags&SIMPLE)) {
5422 reginsert(pRExC_state, STAR, ret, depth+1);
5426 else if (op == '*') {
5430 else if (op == '+' && (flags&SIMPLE)) {
5431 reginsert(pRExC_state, PLUS, ret, depth+1);
5435 else if (op == '+') {
5439 else if (op == '?') {
5444 if (!SIZE_ONLY && !(flags&HASWIDTH) && max > REG_INFTY/3 && ckWARN(WARN_REGEXP)) {
5446 "%.*s matches null string many times",
5447 (int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
5451 if (RExC_parse < RExC_end && *RExC_parse == '?') {
5452 nextchar(pRExC_state);
5453 reginsert(pRExC_state, MINMOD, ret, depth+1);
5454 REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
5456 #ifndef REG_ALLOW_MINMOD_SUSPEND
5459 if (RExC_parse < RExC_end && *RExC_parse == '+') {
5461 nextchar(pRExC_state);
5462 ender = reg_node(pRExC_state, SUCCEED);
5463 REGTAIL(pRExC_state, ret, ender);
5464 reginsert(pRExC_state, SUSPEND, ret, depth+1);
5466 ender = reg_node(pRExC_state, TAIL);
5467 REGTAIL(pRExC_state, ret, ender);
5471 if (RExC_parse < RExC_end && ISMULT2(RExC_parse)) {
5473 vFAIL("Nested quantifiers");
5480 /* reg_namedseq(pRExC_state,UVp)
5482 This is expected to be called by a parser routine that has
5483 recognized'\N' and needs to handle the rest. RExC_parse is
5484 expected to point at the first char following the N at the time
5487 If valuep is non-null then it is assumed that we are parsing inside
5488 of a charclass definition and the first codepoint in the resolved
5489 string is returned via *valuep and the routine will return NULL.
5490 In this mode if a multichar string is returned from the charnames
5491 handler a warning will be issued, and only the first char in the
5492 sequence will be examined. If the string returned is zero length
5493 then the value of *valuep is undefined and NON-NULL will
5494 be returned to indicate failure. (This will NOT be a valid pointer
5497 If value is null then it is assumed that we are parsing normal text
5498 and inserts a new EXACT node into the program containing the resolved
5499 string and returns a pointer to the new node. If the string is
5500 zerolength a NOTHING node is emitted.
5502 On success RExC_parse is set to the char following the endbrace.
5503 Parsing failures will generate a fatal errorvia vFAIL(...)
5505 NOTE: We cache all results from the charnames handler locally in
5506 the RExC_charnames hash (created on first use) to prevent a charnames
5507 handler from playing silly-buggers and returning a short string and
5508 then a long string for a given pattern. Since the regexp program
5509 size is calculated during an initial parse this would result
5510 in a buffer overrun so we cache to prevent the charname result from
5511 changing during the course of the parse.
5515 S_reg_namedseq(pTHX_ RExC_state_t *pRExC_state, UV *valuep)
5517 char * name; /* start of the content of the name */
5518 char * endbrace; /* endbrace following the name */
5521 STRLEN len; /* this has various purposes throughout the code */
5522 bool cached = 0; /* if this is true then we shouldn't refcount dev sv_str */
5523 regnode *ret = NULL;
5525 if (*RExC_parse != '{') {
5526 vFAIL("Missing braces on \\N{}");
5528 name = RExC_parse+1;
5529 endbrace = strchr(RExC_parse, '}');
5532 vFAIL("Missing right brace on \\N{}");
5534 RExC_parse = endbrace + 1;
5537 /* RExC_parse points at the beginning brace,
5538 endbrace points at the last */
5539 if ( name[0]=='U' && name[1]=='+' ) {
5540 /* its a "unicode hex" notation {U+89AB} */
5541 I32 fl = PERL_SCAN_ALLOW_UNDERSCORES
5542 | PERL_SCAN_DISALLOW_PREFIX
5543 | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
5545 len = (STRLEN)(endbrace - name - 2);
5546 cp = grok_hex(name + 2, &len, &fl, NULL);
5547 if ( len != (STRLEN)(endbrace - name - 2) ) {
5556 sv_str= Perl_newSVpvf_nocontext("%c",(int)cp);
5558 /* fetch the charnames handler for this scope */
5559 HV * const table = GvHV(PL_hintgv);
5561 hv_fetchs(table, "charnames", FALSE) :
5563 SV *cv= cvp ? *cvp : NULL;
5566 /* create an SV with the name as argument */
5567 sv_name = newSVpvn(name, endbrace - name);
5569 if (!table || !(PL_hints & HINT_LOCALIZE_HH)) {
5570 vFAIL2("Constant(\\N{%s}) unknown: "
5571 "(possibly a missing \"use charnames ...\")",
5574 if (!cvp || !SvOK(*cvp)) { /* when $^H{charnames} = undef; */
5575 vFAIL2("Constant(\\N{%s}): "
5576 "$^H{charnames} is not defined",SvPVX(sv_name));
5581 if (!RExC_charnames) {
5582 /* make sure our cache is allocated */
5583 RExC_charnames = newHV();
5584 sv_2mortal((SV*)RExC_charnames);
5586 /* see if we have looked this one up before */
5587 he_str = hv_fetch_ent( RExC_charnames, sv_name, 0, 0 );
5589 sv_str = HeVAL(he_str);
5602 count= call_sv(cv, G_SCALAR);
5604 if (count == 1) { /* XXXX is this right? dmq */
5606 SvREFCNT_inc_simple_void(sv_str);
5614 if ( !sv_str || !SvOK(sv_str) ) {
5615 vFAIL2("Constant(\\N{%s}): Call to &{$^H{charnames}} "
5616 "did not return a defined value",SvPVX(sv_name));
5618 if (hv_store_ent( RExC_charnames, sv_name, sv_str, 0))
5623 char *p = SvPV(sv_str, len);
5626 if ( SvUTF8(sv_str) ) {
5627 *valuep = utf8_to_uvchr((U8*)p, &numlen);
5631 We have to turn on utf8 for high bit chars otherwise
5632 we get failures with
5634 "ss" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
5635 "SS" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
5637 This is different from what \x{} would do with the same
5638 codepoint, where the condition is > 0xFF.
5645 /* warn if we havent used the whole string? */
5647 if (numlen<len && SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5649 "Ignoring excess chars from \\N{%s} in character class",
5653 } else if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5655 "Ignoring zero length \\N{%s} in character class",
5660 SvREFCNT_dec(sv_name);
5662 SvREFCNT_dec(sv_str);
5663 return len ? NULL : (regnode *)&len;
5664 } else if(SvCUR(sv_str)) {
5669 char * parse_start = name-3; /* needed for the offsets */
5670 GET_RE_DEBUG_FLAGS_DECL; /* needed for the offsets */
5672 ret = reg_node(pRExC_state,
5673 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
5676 if ( RExC_utf8 && !SvUTF8(sv_str) ) {
5677 sv_utf8_upgrade(sv_str);
5678 } else if ( !RExC_utf8 && SvUTF8(sv_str) ) {
5682 p = SvPV(sv_str, len);
5684 /* len is the length written, charlen is the size the char read */
5685 for ( len = 0; p < pend; p += charlen ) {
5687 UV uvc = utf8_to_uvchr((U8*)p, &charlen);
5689 STRLEN foldlen,numlen;
5690 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
5691 uvc = toFOLD_uni(uvc, tmpbuf, &foldlen);
5692 /* Emit all the Unicode characters. */
5694 for (foldbuf = tmpbuf;
5698 uvc = utf8_to_uvchr(foldbuf, &numlen);
5700 const STRLEN unilen = reguni(pRExC_state, uvc, s);
5703 /* In EBCDIC the numlen
5704 * and unilen can differ. */
5706 if (numlen >= foldlen)
5710 break; /* "Can't happen." */
5713 const STRLEN unilen = reguni(pRExC_state, uvc, s);
5725 RExC_size += STR_SZ(len);
5728 RExC_emit += STR_SZ(len);
5730 Set_Node_Cur_Length(ret); /* MJD */
5732 nextchar(pRExC_state);
5734 ret = reg_node(pRExC_state,NOTHING);
5737 SvREFCNT_dec(sv_str);
5740 SvREFCNT_dec(sv_name);
5749 - regatom - the lowest level
5751 * Optimization: gobbles an entire sequence of ordinary characters so that
5752 * it can turn them into a single node, which is smaller to store and
5753 * faster to run. Backslashed characters are exceptions, each becoming a
5754 * separate node; the code is simpler that way and it's not worth fixing.
5756 * [Yes, it is worth fixing, some scripts can run twice the speed.]
5757 * [It looks like its ok, as in S_study_chunk we merge adjacent EXACT nodes]
5760 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
5763 register regnode *ret = NULL;
5765 char *parse_start = RExC_parse;
5766 GET_RE_DEBUG_FLAGS_DECL;
5767 DEBUG_PARSE("atom");
5768 *flagp = WORST; /* Tentatively. */
5771 switch (*RExC_parse) {
5773 RExC_seen_zerolen++;
5774 nextchar(pRExC_state);
5775 if (RExC_flags & PMf_MULTILINE)
5776 ret = reg_node(pRExC_state, MBOL);
5777 else if (RExC_flags & PMf_SINGLELINE)
5778 ret = reg_node(pRExC_state, SBOL);
5780 ret = reg_node(pRExC_state, BOL);
5781 Set_Node_Length(ret, 1); /* MJD */
5784 nextchar(pRExC_state);
5786 RExC_seen_zerolen++;
5787 if (RExC_flags & PMf_MULTILINE)
5788 ret = reg_node(pRExC_state, MEOL);
5789 else if (RExC_flags & PMf_SINGLELINE)
5790 ret = reg_node(pRExC_state, SEOL);
5792 ret = reg_node(pRExC_state, EOL);
5793 Set_Node_Length(ret, 1); /* MJD */
5796 nextchar(pRExC_state);
5797 if (RExC_flags & PMf_SINGLELINE)
5798 ret = reg_node(pRExC_state, SANY);
5800 ret = reg_node(pRExC_state, REG_ANY);
5801 *flagp |= HASWIDTH|SIMPLE;
5803 Set_Node_Length(ret, 1); /* MJD */
5807 char * const oregcomp_parse = ++RExC_parse;
5808 ret = regclass(pRExC_state,depth+1);
5809 if (*RExC_parse != ']') {
5810 RExC_parse = oregcomp_parse;
5811 vFAIL("Unmatched [");
5813 nextchar(pRExC_state);
5814 *flagp |= HASWIDTH|SIMPLE;
5815 Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
5819 nextchar(pRExC_state);
5820 ret = reg(pRExC_state, 1, &flags,depth+1);
5822 if (flags & TRYAGAIN) {
5823 if (RExC_parse == RExC_end) {
5824 /* Make parent create an empty node if needed. */
5832 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE);
5836 if (flags & TRYAGAIN) {
5840 vFAIL("Internal urp");
5841 /* Supposed to be caught earlier. */
5844 if (!regcurly(RExC_parse)) {
5853 vFAIL("Quantifier follows nothing");
5856 switch (*++RExC_parse) {
5858 RExC_seen_zerolen++;
5859 ret = reg_node(pRExC_state, SBOL);
5861 nextchar(pRExC_state);
5862 Set_Node_Length(ret, 2); /* MJD */
5865 ret = reg_node(pRExC_state, GPOS);
5866 RExC_seen |= REG_SEEN_GPOS;
5868 nextchar(pRExC_state);
5869 Set_Node_Length(ret, 2); /* MJD */
5872 ret = reg_node(pRExC_state, SEOL);
5874 RExC_seen_zerolen++; /* Do not optimize RE away */
5875 nextchar(pRExC_state);
5878 ret = reg_node(pRExC_state, EOS);
5880 RExC_seen_zerolen++; /* Do not optimize RE away */
5881 nextchar(pRExC_state);
5882 Set_Node_Length(ret, 2); /* MJD */
5885 ret = reg_node(pRExC_state, CANY);
5886 RExC_seen |= REG_SEEN_CANY;
5887 *flagp |= HASWIDTH|SIMPLE;
5888 nextchar(pRExC_state);
5889 Set_Node_Length(ret, 2); /* MJD */
5892 ret = reg_node(pRExC_state, CLUMP);
5894 nextchar(pRExC_state);
5895 Set_Node_Length(ret, 2); /* MJD */
5898 ret = reg_node(pRExC_state, (U8)(LOC ? ALNUML : ALNUM));
5899 *flagp |= HASWIDTH|SIMPLE;
5900 nextchar(pRExC_state);
5901 Set_Node_Length(ret, 2); /* MJD */
5904 ret = reg_node(pRExC_state, (U8)(LOC ? NALNUML : NALNUM));
5905 *flagp |= HASWIDTH|SIMPLE;
5906 nextchar(pRExC_state);
5907 Set_Node_Length(ret, 2); /* MJD */
5910 RExC_seen_zerolen++;
5911 RExC_seen |= REG_SEEN_LOOKBEHIND;
5912 ret = reg_node(pRExC_state, (U8)(LOC ? BOUNDL : BOUND));
5914 nextchar(pRExC_state);
5915 Set_Node_Length(ret, 2); /* MJD */
5918 RExC_seen_zerolen++;
5919 RExC_seen |= REG_SEEN_LOOKBEHIND;
5920 ret = reg_node(pRExC_state, (U8)(LOC ? NBOUNDL : NBOUND));
5922 nextchar(pRExC_state);
5923 Set_Node_Length(ret, 2); /* MJD */
5926 ret = reg_node(pRExC_state, (U8)(LOC ? SPACEL : SPACE));
5927 *flagp |= HASWIDTH|SIMPLE;
5928 nextchar(pRExC_state);
5929 Set_Node_Length(ret, 2); /* MJD */
5932 ret = reg_node(pRExC_state, (U8)(LOC ? NSPACEL : NSPACE));
5933 *flagp |= HASWIDTH|SIMPLE;
5934 nextchar(pRExC_state);
5935 Set_Node_Length(ret, 2); /* MJD */
5938 ret = reg_node(pRExC_state, DIGIT);
5939 *flagp |= HASWIDTH|SIMPLE;
5940 nextchar(pRExC_state);
5941 Set_Node_Length(ret, 2); /* MJD */
5944 ret = reg_node(pRExC_state, NDIGIT);
5945 *flagp |= HASWIDTH|SIMPLE;
5946 nextchar(pRExC_state);
5947 Set_Node_Length(ret, 2); /* MJD */
5952 char* const oldregxend = RExC_end;
5953 char* parse_start = RExC_parse - 2;
5955 if (RExC_parse[1] == '{') {
5956 /* a lovely hack--pretend we saw [\pX] instead */
5957 RExC_end = strchr(RExC_parse, '}');
5959 const U8 c = (U8)*RExC_parse;
5961 RExC_end = oldregxend;
5962 vFAIL2("Missing right brace on \\%c{}", c);
5967 RExC_end = RExC_parse + 2;
5968 if (RExC_end > oldregxend)
5969 RExC_end = oldregxend;
5973 ret = regclass(pRExC_state,depth+1);
5975 RExC_end = oldregxend;
5978 Set_Node_Offset(ret, parse_start + 2);
5979 Set_Node_Cur_Length(ret);
5980 nextchar(pRExC_state);
5981 *flagp |= HASWIDTH|SIMPLE;
5985 /* Handle \N{NAME} here and not below because it can be
5986 multicharacter. join_exact() will join them up later on.
5987 Also this makes sure that things like /\N{BLAH}+/ and
5988 \N{BLAH} being multi char Just Happen. dmq*/
5990 ret= reg_namedseq(pRExC_state, NULL);
5992 case 'k': /* Handle \k<NAME> and \k'NAME' */
5994 char ch= RExC_parse[1];
5995 if (ch != '<' && ch != '\'') {
5997 vWARN( RExC_parse + 1,
5998 "Possible broken named back reference treated as literal k");
6002 char* name_start = (RExC_parse += 2);
6004 SV *sv_dat = reg_scan_name(pRExC_state,
6005 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
6006 ch= (ch == '<') ? '>' : '\'';
6008 if (RExC_parse == name_start || *RExC_parse != ch)
6009 vFAIL2("Sequence \\k%c... not terminated",
6010 (ch == '>' ? '<' : ch));
6013 ret = reganode(pRExC_state,
6014 (U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
6020 num = add_data( pRExC_state, 1, "S" );
6022 RExC_rx->data->data[num]=(void*)sv_dat;
6023 SvREFCNT_inc(sv_dat);
6025 /* override incorrect value set in reganode MJD */
6026 Set_Node_Offset(ret, parse_start+1);
6027 Set_Node_Cur_Length(ret); /* MJD */
6028 nextchar(pRExC_state);
6043 case '1': case '2': case '3': case '4':
6044 case '5': case '6': case '7': case '8': case '9':
6046 const I32 num = atoi(RExC_parse);
6048 if (num > 9 && num >= RExC_npar)
6051 char * const parse_start = RExC_parse - 1; /* MJD */
6052 while (isDIGIT(*RExC_parse))
6055 if (!SIZE_ONLY && num > (I32)RExC_rx->nparens)
6056 vFAIL("Reference to nonexistent group");
6058 ret = reganode(pRExC_state,
6059 (U8)(FOLD ? (LOC ? REFFL : REFF) : REF),
6063 /* override incorrect value set in reganode MJD */
6064 Set_Node_Offset(ret, parse_start+1);
6065 Set_Node_Cur_Length(ret); /* MJD */
6067 nextchar(pRExC_state);
6072 if (RExC_parse >= RExC_end)
6073 FAIL("Trailing \\");
6076 /* Do not generate "unrecognized" warnings here, we fall
6077 back into the quick-grab loop below */
6084 if (RExC_flags & PMf_EXTENDED) {
6085 while (RExC_parse < RExC_end && *RExC_parse != '\n')
6087 if (RExC_parse < RExC_end)
6093 register STRLEN len;
6098 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
6100 parse_start = RExC_parse - 1;
6106 ret = reg_node(pRExC_state,
6107 (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
6109 for (len = 0, p = RExC_parse - 1;
6110 len < 127 && p < RExC_end;
6113 char * const oldp = p;
6115 if (RExC_flags & PMf_EXTENDED)
6116 p = regwhite(p, RExC_end);
6164 ender = ASCII_TO_NATIVE('\033');
6168 ender = ASCII_TO_NATIVE('\007');
6173 char* const e = strchr(p, '}');
6177 vFAIL("Missing right brace on \\x{}");
6180 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
6181 | PERL_SCAN_DISALLOW_PREFIX;
6182 STRLEN numlen = e - p - 1;
6183 ender = grok_hex(p + 1, &numlen, &flags, NULL);
6190 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
6192 ender = grok_hex(p, &numlen, &flags, NULL);
6198 ender = UCHARAT(p++);
6199 ender = toCTRL(ender);
6201 case '0': case '1': case '2': case '3':case '4':
6202 case '5': case '6': case '7': case '8':case '9':
6204 (isDIGIT(p[1]) && atoi(p) >= RExC_npar) ) {
6207 ender = grok_oct(p, &numlen, &flags, NULL);
6217 FAIL("Trailing \\");
6220 if (!SIZE_ONLY&& isALPHA(*p) && ckWARN(WARN_REGEXP))
6221 vWARN2(p + 1, "Unrecognized escape \\%c passed through", UCHARAT(p));
6222 goto normal_default;
6227 if (UTF8_IS_START(*p) && UTF) {
6229 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
6230 &numlen, UTF8_ALLOW_DEFAULT);
6237 if (RExC_flags & PMf_EXTENDED)
6238 p = regwhite(p, RExC_end);
6240 /* Prime the casefolded buffer. */
6241 ender = toFOLD_uni(ender, tmpbuf, &foldlen);
6243 if (ISMULT2(p)) { /* Back off on ?+*. */
6248 /* Emit all the Unicode characters. */
6250 for (foldbuf = tmpbuf;
6252 foldlen -= numlen) {
6253 ender = utf8_to_uvchr(foldbuf, &numlen);
6255 const STRLEN unilen = reguni(pRExC_state, ender, s);
6258 /* In EBCDIC the numlen
6259 * and unilen can differ. */
6261 if (numlen >= foldlen)
6265 break; /* "Can't happen." */
6269 const STRLEN unilen = reguni(pRExC_state, ender, s);
6278 REGC((char)ender, s++);
6284 /* Emit all the Unicode characters. */
6286 for (foldbuf = tmpbuf;
6288 foldlen -= numlen) {
6289 ender = utf8_to_uvchr(foldbuf, &numlen);
6291 const STRLEN unilen = reguni(pRExC_state, ender, s);
6294 /* In EBCDIC the numlen
6295 * and unilen can differ. */
6297 if (numlen >= foldlen)
6305 const STRLEN unilen = reguni(pRExC_state, ender, s);
6314 REGC((char)ender, s++);
6318 Set_Node_Cur_Length(ret); /* MJD */
6319 nextchar(pRExC_state);
6321 /* len is STRLEN which is unsigned, need to copy to signed */
6324 vFAIL("Internal disaster");
6328 if (len == 1 && UNI_IS_INVARIANT(ender))
6332 RExC_size += STR_SZ(len);
6335 RExC_emit += STR_SZ(len);
6341 /* If the encoding pragma is in effect recode the text of
6342 * any EXACT-kind nodes. */
6343 if (ret && PL_encoding && PL_regkind[OP(ret)] == EXACT) {
6344 const STRLEN oldlen = STR_LEN(ret);
6345 SV * const sv = sv_2mortal(newSVpvn(STRING(ret), oldlen));
6349 if (sv_utf8_downgrade(sv, TRUE)) {
6350 const char * const s = sv_recode_to_utf8(sv, PL_encoding);
6351 const STRLEN newlen = SvCUR(sv);
6356 GET_RE_DEBUG_FLAGS_DECL;
6357 DEBUG_COMPILE_r(PerlIO_printf(Perl_debug_log, "recode %*s to %*s\n",
6358 (int)oldlen, STRING(ret),
6360 Copy(s, STRING(ret), newlen, char);
6361 STR_LEN(ret) += newlen - oldlen;
6362 RExC_emit += STR_SZ(newlen) - STR_SZ(oldlen);
6364 RExC_size += STR_SZ(newlen) - STR_SZ(oldlen);
6372 S_regwhite(char *p, const char *e)
6377 else if (*p == '#') {
6380 } while (p < e && *p != '\n');
6388 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
6389 Character classes ([:foo:]) can also be negated ([:^foo:]).
6390 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
6391 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
6392 but trigger failures because they are currently unimplemented. */
6394 #define POSIXCC_DONE(c) ((c) == ':')
6395 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
6396 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
6399 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
6402 I32 namedclass = OOB_NAMEDCLASS;
6404 if (value == '[' && RExC_parse + 1 < RExC_end &&
6405 /* I smell either [: or [= or [. -- POSIX has been here, right? */
6406 POSIXCC(UCHARAT(RExC_parse))) {
6407 const char c = UCHARAT(RExC_parse);
6408 char* const s = RExC_parse++;
6410 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
6412 if (RExC_parse == RExC_end)
6413 /* Grandfather lone [:, [=, [. */
6416 const char* const t = RExC_parse++; /* skip over the c */
6419 if (UCHARAT(RExC_parse) == ']') {
6420 const char *posixcc = s + 1;
6421 RExC_parse++; /* skip over the ending ] */
6424 const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
6425 const I32 skip = t - posixcc;
6427 /* Initially switch on the length of the name. */
6430 if (memEQ(posixcc, "word", 4)) /* this is not POSIX, this is the Perl \w */
6431 namedclass = complement ? ANYOF_NALNUM : ANYOF_ALNUM;
6434 /* Names all of length 5. */
6435 /* alnum alpha ascii blank cntrl digit graph lower
6436 print punct space upper */
6437 /* Offset 4 gives the best switch position. */
6438 switch (posixcc[4]) {
6440 if (memEQ(posixcc, "alph", 4)) /* alpha */
6441 namedclass = complement ? ANYOF_NALPHA : ANYOF_ALPHA;
6444 if (memEQ(posixcc, "spac", 4)) /* space */
6445 namedclass = complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
6448 if (memEQ(posixcc, "grap", 4)) /* graph */
6449 namedclass = complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
6452 if (memEQ(posixcc, "asci", 4)) /* ascii */
6453 namedclass = complement ? ANYOF_NASCII : ANYOF_ASCII;
6456 if (memEQ(posixcc, "blan", 4)) /* blank */
6457 namedclass = complement ? ANYOF_NBLANK : ANYOF_BLANK;
6460 if (memEQ(posixcc, "cntr", 4)) /* cntrl */
6461 namedclass = complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
6464 if (memEQ(posixcc, "alnu", 4)) /* alnum */
6465 namedclass = complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
6468 if (memEQ(posixcc, "lowe", 4)) /* lower */
6469 namedclass = complement ? ANYOF_NLOWER : ANYOF_LOWER;
6470 else if (memEQ(posixcc, "uppe", 4)) /* upper */
6471 namedclass = complement ? ANYOF_NUPPER : ANYOF_UPPER;
6474 if (memEQ(posixcc, "digi", 4)) /* digit */
6475 namedclass = complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
6476 else if (memEQ(posixcc, "prin", 4)) /* print */
6477 namedclass = complement ? ANYOF_NPRINT : ANYOF_PRINT;
6478 else if (memEQ(posixcc, "punc", 4)) /* punct */
6479 namedclass = complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
6484 if (memEQ(posixcc, "xdigit", 6))
6485 namedclass = complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
6489 if (namedclass == OOB_NAMEDCLASS)
6490 Simple_vFAIL3("POSIX class [:%.*s:] unknown",
6492 assert (posixcc[skip] == ':');
6493 assert (posixcc[skip+1] == ']');
6494 } else if (!SIZE_ONLY) {
6495 /* [[=foo=]] and [[.foo.]] are still future. */
6497 /* adjust RExC_parse so the warning shows after
6499 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
6501 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
6504 /* Maternal grandfather:
6505 * "[:" ending in ":" but not in ":]" */
6515 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
6518 if (POSIXCC(UCHARAT(RExC_parse))) {
6519 const char *s = RExC_parse;
6520 const char c = *s++;
6524 if (*s && c == *s && s[1] == ']') {
6525 if (ckWARN(WARN_REGEXP))
6527 "POSIX syntax [%c %c] belongs inside character classes",
6530 /* [[=foo=]] and [[.foo.]] are still future. */
6531 if (POSIXCC_NOTYET(c)) {
6532 /* adjust RExC_parse so the error shows after
6534 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
6536 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
6544 parse a class specification and produce either an ANYOF node that
6545 matches the pattern. If the pattern matches a single char only and
6546 that char is < 256 then we produce an EXACT node instead.
6549 S_regclass(pTHX_ RExC_state_t *pRExC_state, U32 depth)
6552 register UV value = 0;
6553 register UV nextvalue;
6554 register IV prevvalue = OOB_UNICODE;
6555 register IV range = 0;
6556 register regnode *ret;
6559 char *rangebegin = NULL;
6560 bool need_class = 0;
6563 bool optimize_invert = TRUE;
6564 AV* unicode_alternate = NULL;
6566 UV literal_endpoint = 0;
6568 UV stored = 0; /* number of chars stored in the class */
6570 regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
6571 case we need to change the emitted regop to an EXACT. */
6572 const char * orig_parse = RExC_parse;
6573 GET_RE_DEBUG_FLAGS_DECL;
6575 PERL_UNUSED_ARG(depth);
6578 DEBUG_PARSE("clas");
6580 /* Assume we are going to generate an ANYOF node. */
6581 ret = reganode(pRExC_state, ANYOF, 0);
6584 ANYOF_FLAGS(ret) = 0;
6586 if (UCHARAT(RExC_parse) == '^') { /* Complement of range. */
6590 ANYOF_FLAGS(ret) |= ANYOF_INVERT;
6594 RExC_size += ANYOF_SKIP;
6595 listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
6598 RExC_emit += ANYOF_SKIP;
6600 ANYOF_FLAGS(ret) |= ANYOF_FOLD;
6602 ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
6603 ANYOF_BITMAP_ZERO(ret);
6604 listsv = newSVpvs("# comment\n");
6607 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
6609 if (!SIZE_ONLY && POSIXCC(nextvalue))
6610 checkposixcc(pRExC_state);
6612 /* allow 1st char to be ] (allowing it to be - is dealt with later) */
6613 if (UCHARAT(RExC_parse) == ']')
6617 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
6621 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
6624 rangebegin = RExC_parse;
6626 value = utf8n_to_uvchr((U8*)RExC_parse,
6627 RExC_end - RExC_parse,
6628 &numlen, UTF8_ALLOW_DEFAULT);
6629 RExC_parse += numlen;
6632 value = UCHARAT(RExC_parse++);
6634 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
6635 if (value == '[' && POSIXCC(nextvalue))
6636 namedclass = regpposixcc(pRExC_state, value);
6637 else if (value == '\\') {
6639 value = utf8n_to_uvchr((U8*)RExC_parse,
6640 RExC_end - RExC_parse,
6641 &numlen, UTF8_ALLOW_DEFAULT);
6642 RExC_parse += numlen;
6645 value = UCHARAT(RExC_parse++);
6646 /* Some compilers cannot handle switching on 64-bit integer
6647 * values, therefore value cannot be an UV. Yes, this will
6648 * be a problem later if we want switch on Unicode.
6649 * A similar issue a little bit later when switching on
6650 * namedclass. --jhi */
6651 switch ((I32)value) {
6652 case 'w': namedclass = ANYOF_ALNUM; break;
6653 case 'W': namedclass = ANYOF_NALNUM; break;
6654 case 's': namedclass = ANYOF_SPACE; break;
6655 case 'S': namedclass = ANYOF_NSPACE; break;
6656 case 'd': namedclass = ANYOF_DIGIT; break;
6657 case 'D': namedclass = ANYOF_NDIGIT; break;
6658 case 'N': /* Handle \N{NAME} in class */
6660 /* We only pay attention to the first char of
6661 multichar strings being returned. I kinda wonder
6662 if this makes sense as it does change the behaviour
6663 from earlier versions, OTOH that behaviour was broken
6665 UV v; /* value is register so we cant & it /grrr */
6666 if (reg_namedseq(pRExC_state, &v)) {
6676 if (RExC_parse >= RExC_end)
6677 vFAIL2("Empty \\%c{}", (U8)value);
6678 if (*RExC_parse == '{') {
6679 const U8 c = (U8)value;
6680 e = strchr(RExC_parse++, '}');
6682 vFAIL2("Missing right brace on \\%c{}", c);
6683 while (isSPACE(UCHARAT(RExC_parse)))
6685 if (e == RExC_parse)
6686 vFAIL2("Empty \\%c{}", c);
6688 while (isSPACE(UCHARAT(RExC_parse + n - 1)))
6696 if (UCHARAT(RExC_parse) == '^') {
6699 value = value == 'p' ? 'P' : 'p'; /* toggle */
6700 while (isSPACE(UCHARAT(RExC_parse))) {
6705 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%.*s\n",
6706 (value=='p' ? '+' : '!'), (int)n, RExC_parse);
6709 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
6710 namedclass = ANYOF_MAX; /* no official name, but it's named */
6713 case 'n': value = '\n'; break;
6714 case 'r': value = '\r'; break;
6715 case 't': value = '\t'; break;
6716 case 'f': value = '\f'; break;
6717 case 'b': value = '\b'; break;
6718 case 'e': value = ASCII_TO_NATIVE('\033');break;
6719 case 'a': value = ASCII_TO_NATIVE('\007');break;
6721 if (*RExC_parse == '{') {
6722 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
6723 | PERL_SCAN_DISALLOW_PREFIX;
6724 char * const e = strchr(RExC_parse++, '}');
6726 vFAIL("Missing right brace on \\x{}");
6728 numlen = e - RExC_parse;
6729 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
6733 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
6735 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
6736 RExC_parse += numlen;
6740 value = UCHARAT(RExC_parse++);
6741 value = toCTRL(value);
6743 case '0': case '1': case '2': case '3': case '4':
6744 case '5': case '6': case '7': case '8': case '9':
6748 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
6749 RExC_parse += numlen;
6753 if (!SIZE_ONLY && isALPHA(value) && ckWARN(WARN_REGEXP))
6755 "Unrecognized escape \\%c in character class passed through",
6759 } /* end of \blah */
6765 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
6767 if (!SIZE_ONLY && !need_class)
6768 ANYOF_CLASS_ZERO(ret);
6772 /* a bad range like a-\d, a-[:digit:] ? */
6775 if (ckWARN(WARN_REGEXP)) {
6777 RExC_parse >= rangebegin ?
6778 RExC_parse - rangebegin : 0;
6780 "False [] range \"%*.*s\"",
6783 if (prevvalue < 256) {
6784 ANYOF_BITMAP_SET(ret, prevvalue);
6785 ANYOF_BITMAP_SET(ret, '-');
6788 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
6789 Perl_sv_catpvf(aTHX_ listsv,
6790 "%04"UVxf"\n%04"UVxf"\n", (UV)prevvalue, (UV) '-');
6794 range = 0; /* this was not a true range */
6798 const char *what = NULL;
6801 if (namedclass > OOB_NAMEDCLASS)
6802 optimize_invert = FALSE;
6803 /* Possible truncation here but in some 64-bit environments
6804 * the compiler gets heartburn about switch on 64-bit values.
6805 * A similar issue a little earlier when switching on value.
6807 switch ((I32)namedclass) {
6810 ANYOF_CLASS_SET(ret, ANYOF_ALNUM);
6812 for (value = 0; value < 256; value++)
6814 ANYOF_BITMAP_SET(ret, value);
6821 ANYOF_CLASS_SET(ret, ANYOF_NALNUM);
6823 for (value = 0; value < 256; value++)
6824 if (!isALNUM(value))
6825 ANYOF_BITMAP_SET(ret, value);
6832 ANYOF_CLASS_SET(ret, ANYOF_ALNUMC);
6834 for (value = 0; value < 256; value++)
6835 if (isALNUMC(value))
6836 ANYOF_BITMAP_SET(ret, value);
6843 ANYOF_CLASS_SET(ret, ANYOF_NALNUMC);
6845 for (value = 0; value < 256; value++)
6846 if (!isALNUMC(value))
6847 ANYOF_BITMAP_SET(ret, value);
6854 ANYOF_CLASS_SET(ret, ANYOF_ALPHA);
6856 for (value = 0; value < 256; value++)
6858 ANYOF_BITMAP_SET(ret, value);
6865 ANYOF_CLASS_SET(ret, ANYOF_NALPHA);
6867 for (value = 0; value < 256; value++)
6868 if (!isALPHA(value))
6869 ANYOF_BITMAP_SET(ret, value);
6876 ANYOF_CLASS_SET(ret, ANYOF_ASCII);
6879 for (value = 0; value < 128; value++)
6880 ANYOF_BITMAP_SET(ret, value);
6882 for (value = 0; value < 256; value++) {
6884 ANYOF_BITMAP_SET(ret, value);
6893 ANYOF_CLASS_SET(ret, ANYOF_NASCII);
6896 for (value = 128; value < 256; value++)
6897 ANYOF_BITMAP_SET(ret, value);
6899 for (value = 0; value < 256; value++) {
6900 if (!isASCII(value))
6901 ANYOF_BITMAP_SET(ret, value);
6910 ANYOF_CLASS_SET(ret, ANYOF_BLANK);
6912 for (value = 0; value < 256; value++)
6914 ANYOF_BITMAP_SET(ret, value);
6921 ANYOF_CLASS_SET(ret, ANYOF_NBLANK);
6923 for (value = 0; value < 256; value++)
6924 if (!isBLANK(value))
6925 ANYOF_BITMAP_SET(ret, value);
6932 ANYOF_CLASS_SET(ret, ANYOF_CNTRL);
6934 for (value = 0; value < 256; value++)
6936 ANYOF_BITMAP_SET(ret, value);
6943 ANYOF_CLASS_SET(ret, ANYOF_NCNTRL);
6945 for (value = 0; value < 256; value++)
6946 if (!isCNTRL(value))
6947 ANYOF_BITMAP_SET(ret, value);
6954 ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
6956 /* consecutive digits assumed */
6957 for (value = '0'; value <= '9'; value++)
6958 ANYOF_BITMAP_SET(ret, value);
6965 ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
6967 /* consecutive digits assumed */
6968 for (value = 0; value < '0'; value++)
6969 ANYOF_BITMAP_SET(ret, value);
6970 for (value = '9' + 1; value < 256; value++)
6971 ANYOF_BITMAP_SET(ret, value);
6978 ANYOF_CLASS_SET(ret, ANYOF_GRAPH);
6980 for (value = 0; value < 256; value++)
6982 ANYOF_BITMAP_SET(ret, value);
6989 ANYOF_CLASS_SET(ret, ANYOF_NGRAPH);
6991 for (value = 0; value < 256; value++)
6992 if (!isGRAPH(value))
6993 ANYOF_BITMAP_SET(ret, value);
7000 ANYOF_CLASS_SET(ret, ANYOF_LOWER);
7002 for (value = 0; value < 256; value++)
7004 ANYOF_BITMAP_SET(ret, value);
7011 ANYOF_CLASS_SET(ret, ANYOF_NLOWER);
7013 for (value = 0; value < 256; value++)
7014 if (!isLOWER(value))
7015 ANYOF_BITMAP_SET(ret, value);
7022 ANYOF_CLASS_SET(ret, ANYOF_PRINT);
7024 for (value = 0; value < 256; value++)
7026 ANYOF_BITMAP_SET(ret, value);
7033 ANYOF_CLASS_SET(ret, ANYOF_NPRINT);
7035 for (value = 0; value < 256; value++)
7036 if (!isPRINT(value))
7037 ANYOF_BITMAP_SET(ret, value);
7044 ANYOF_CLASS_SET(ret, ANYOF_PSXSPC);
7046 for (value = 0; value < 256; value++)
7047 if (isPSXSPC(value))
7048 ANYOF_BITMAP_SET(ret, value);
7055 ANYOF_CLASS_SET(ret, ANYOF_NPSXSPC);
7057 for (value = 0; value < 256; value++)
7058 if (!isPSXSPC(value))
7059 ANYOF_BITMAP_SET(ret, value);
7066 ANYOF_CLASS_SET(ret, ANYOF_PUNCT);
7068 for (value = 0; value < 256; value++)
7070 ANYOF_BITMAP_SET(ret, value);
7077 ANYOF_CLASS_SET(ret, ANYOF_NPUNCT);
7079 for (value = 0; value < 256; value++)
7080 if (!isPUNCT(value))
7081 ANYOF_BITMAP_SET(ret, value);
7088 ANYOF_CLASS_SET(ret, ANYOF_SPACE);
7090 for (value = 0; value < 256; value++)
7092 ANYOF_BITMAP_SET(ret, value);
7099 ANYOF_CLASS_SET(ret, ANYOF_NSPACE);
7101 for (value = 0; value < 256; value++)
7102 if (!isSPACE(value))
7103 ANYOF_BITMAP_SET(ret, value);
7110 ANYOF_CLASS_SET(ret, ANYOF_UPPER);
7112 for (value = 0; value < 256; value++)
7114 ANYOF_BITMAP_SET(ret, value);
7121 ANYOF_CLASS_SET(ret, ANYOF_NUPPER);
7123 for (value = 0; value < 256; value++)
7124 if (!isUPPER(value))
7125 ANYOF_BITMAP_SET(ret, value);
7132 ANYOF_CLASS_SET(ret, ANYOF_XDIGIT);
7134 for (value = 0; value < 256; value++)
7135 if (isXDIGIT(value))
7136 ANYOF_BITMAP_SET(ret, value);
7143 ANYOF_CLASS_SET(ret, ANYOF_NXDIGIT);
7145 for (value = 0; value < 256; value++)
7146 if (!isXDIGIT(value))
7147 ANYOF_BITMAP_SET(ret, value);
7153 /* this is to handle \p and \P */
7156 vFAIL("Invalid [::] class");
7160 /* Strings such as "+utf8::isWord\n" */
7161 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::Is%s\n", yesno, what);
7164 ANYOF_FLAGS(ret) |= ANYOF_CLASS;
7167 } /* end of namedclass \blah */
7170 if (prevvalue > (IV)value) /* b-a */ {
7171 const int w = RExC_parse - rangebegin;
7172 Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
7173 range = 0; /* not a valid range */
7177 prevvalue = value; /* save the beginning of the range */
7178 if (*RExC_parse == '-' && RExC_parse+1 < RExC_end &&
7179 RExC_parse[1] != ']') {
7182 /* a bad range like \w-, [:word:]- ? */
7183 if (namedclass > OOB_NAMEDCLASS) {
7184 if (ckWARN(WARN_REGEXP)) {
7186 RExC_parse >= rangebegin ?
7187 RExC_parse - rangebegin : 0;
7189 "False [] range \"%*.*s\"",
7193 ANYOF_BITMAP_SET(ret, '-');
7195 range = 1; /* yeah, it's a range! */
7196 continue; /* but do it the next time */
7200 /* now is the next time */
7201 /*stored += (value - prevvalue + 1);*/
7203 if (prevvalue < 256) {
7204 const IV ceilvalue = value < 256 ? value : 255;
7207 /* In EBCDIC [\x89-\x91] should include
7208 * the \x8e but [i-j] should not. */
7209 if (literal_endpoint == 2 &&
7210 ((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
7211 (isUPPER(prevvalue) && isUPPER(ceilvalue))))
7213 if (isLOWER(prevvalue)) {
7214 for (i = prevvalue; i <= ceilvalue; i++)
7216 ANYOF_BITMAP_SET(ret, i);
7218 for (i = prevvalue; i <= ceilvalue; i++)
7220 ANYOF_BITMAP_SET(ret, i);
7225 for (i = prevvalue; i <= ceilvalue; i++) {
7226 if (!ANYOF_BITMAP_TEST(ret,i)) {
7228 ANYOF_BITMAP_SET(ret, i);
7232 if (value > 255 || UTF) {
7233 const UV prevnatvalue = NATIVE_TO_UNI(prevvalue);
7234 const UV natvalue = NATIVE_TO_UNI(value);
7235 stored+=2; /* can't optimize this class */
7236 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
7237 if (prevnatvalue < natvalue) { /* what about > ? */
7238 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
7239 prevnatvalue, natvalue);
7241 else if (prevnatvalue == natvalue) {
7242 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n", natvalue);
7244 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
7246 const UV f = to_uni_fold(natvalue, foldbuf, &foldlen);
7248 #ifdef EBCDIC /* RD t/uni/fold ff and 6b */
7249 if (RExC_precomp[0] == ':' &&
7250 RExC_precomp[1] == '[' &&
7251 (f == 0xDF || f == 0x92)) {
7252 f = NATIVE_TO_UNI(f);
7255 /* If folding and foldable and a single
7256 * character, insert also the folded version
7257 * to the charclass. */
7259 #ifdef EBCDIC /* RD tunifold ligatures s,t fb05, fb06 */
7260 if ((RExC_precomp[0] == ':' &&
7261 RExC_precomp[1] == '[' &&
7263 (value == 0xFB05 || value == 0xFB06))) ?
7264 foldlen == ((STRLEN)UNISKIP(f) - 1) :
7265 foldlen == (STRLEN)UNISKIP(f) )
7267 if (foldlen == (STRLEN)UNISKIP(f))
7269 Perl_sv_catpvf(aTHX_ listsv,
7272 /* Any multicharacter foldings
7273 * require the following transform:
7274 * [ABCDEF] -> (?:[ABCabcDEFd]|pq|rst)
7275 * where E folds into "pq" and F folds
7276 * into "rst", all other characters
7277 * fold to single characters. We save
7278 * away these multicharacter foldings,
7279 * to be later saved as part of the
7280 * additional "s" data. */
7283 if (!unicode_alternate)
7284 unicode_alternate = newAV();
7285 sv = newSVpvn((char*)foldbuf, foldlen);
7287 av_push(unicode_alternate, sv);
7291 /* If folding and the value is one of the Greek
7292 * sigmas insert a few more sigmas to make the
7293 * folding rules of the sigmas to work right.
7294 * Note that not all the possible combinations
7295 * are handled here: some of them are handled
7296 * by the standard folding rules, and some of
7297 * them (literal or EXACTF cases) are handled
7298 * during runtime in regexec.c:S_find_byclass(). */
7299 if (value == UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA) {
7300 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7301 (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA);
7302 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7303 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
7305 else if (value == UNICODE_GREEK_CAPITAL_LETTER_SIGMA)
7306 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7307 (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
7312 literal_endpoint = 0;
7316 range = 0; /* this range (if it was one) is done now */
7320 ANYOF_FLAGS(ret) |= ANYOF_LARGE;
7322 RExC_size += ANYOF_CLASS_ADD_SKIP;
7324 RExC_emit += ANYOF_CLASS_ADD_SKIP;
7330 /****** !SIZE_ONLY AFTER HERE *********/
7332 if( stored == 1 && value < 256
7333 && !( ANYOF_FLAGS(ret) & ( ANYOF_FLAGS_ALL ^ ANYOF_FOLD ) )
7335 /* optimize single char class to an EXACT node
7336 but *only* when its not a UTF/high char */
7337 const char * cur_parse= RExC_parse;
7338 RExC_emit = (regnode *)orig_emit;
7339 RExC_parse = (char *)orig_parse;
7340 ret = reg_node(pRExC_state,
7341 (U8)((ANYOF_FLAGS(ret) & ANYOF_FOLD) ? EXACTF : EXACT));
7342 RExC_parse = (char *)cur_parse;
7343 *STRING(ret)= (char)value;
7345 RExC_emit += STR_SZ(1);
7348 /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
7349 if ( /* If the only flag is folding (plus possibly inversion). */
7350 ((ANYOF_FLAGS(ret) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD)
7352 for (value = 0; value < 256; ++value) {
7353 if (ANYOF_BITMAP_TEST(ret, value)) {
7354 UV fold = PL_fold[value];
7357 ANYOF_BITMAP_SET(ret, fold);
7360 ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
7363 /* optimize inverted simple patterns (e.g. [^a-z]) */
7364 if (optimize_invert &&
7365 /* If the only flag is inversion. */
7366 (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
7367 for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
7368 ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
7369 ANYOF_FLAGS(ret) = ANYOF_UNICODE_ALL;
7372 AV * const av = newAV();
7374 /* The 0th element stores the character class description
7375 * in its textual form: used later (regexec.c:Perl_regclass_swash())
7376 * to initialize the appropriate swash (which gets stored in
7377 * the 1st element), and also useful for dumping the regnode.
7378 * The 2nd element stores the multicharacter foldings,
7379 * used later (regexec.c:S_reginclass()). */
7380 av_store(av, 0, listsv);
7381 av_store(av, 1, NULL);
7382 av_store(av, 2, (SV*)unicode_alternate);
7383 rv = newRV_noinc((SV*)av);
7384 n = add_data(pRExC_state, 1, "s");
7385 RExC_rx->data->data[n] = (void*)rv;
7392 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
7394 char* const retval = RExC_parse++;
7397 if (*RExC_parse == '(' && RExC_parse[1] == '?' &&
7398 RExC_parse[2] == '#') {
7399 while (*RExC_parse != ')') {
7400 if (RExC_parse == RExC_end)
7401 FAIL("Sequence (?#... not terminated");
7407 if (RExC_flags & PMf_EXTENDED) {
7408 if (isSPACE(*RExC_parse)) {
7412 else if (*RExC_parse == '#') {
7413 while (RExC_parse < RExC_end)
7414 if (*RExC_parse++ == '\n') break;
7423 - reg_node - emit a node
7425 STATIC regnode * /* Location. */
7426 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
7429 register regnode *ptr;
7430 regnode * const ret = RExC_emit;
7431 GET_RE_DEBUG_FLAGS_DECL;
7434 SIZE_ALIGN(RExC_size);
7438 NODE_ALIGN_FILL(ret);
7440 FILL_ADVANCE_NODE(ptr, op);
7441 if (RExC_offsets) { /* MJD */
7442 MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n",
7443 "reg_node", __LINE__,
7445 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0]
7446 ? "Overwriting end of array!\n" : "OK",
7447 (UV)(RExC_emit - RExC_emit_start),
7448 (UV)(RExC_parse - RExC_start),
7449 (UV)RExC_offsets[0]));
7450 Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
7459 - reganode - emit a node with an argument
7461 STATIC regnode * /* Location. */
7462 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
7465 register regnode *ptr;
7466 regnode * const ret = RExC_emit;
7467 GET_RE_DEBUG_FLAGS_DECL;
7470 SIZE_ALIGN(RExC_size);
7475 assert(2==regarglen[op]+1);
7477 Anything larger than this has to allocate the extra amount.
7478 If we changed this to be:
7480 RExC_size += (1 + regarglen[op]);
7482 then it wouldn't matter. Its not clear what side effect
7483 might come from that so its not done so far.
7489 NODE_ALIGN_FILL(ret);
7491 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
7492 if (RExC_offsets) { /* MJD */
7493 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
7497 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ?
7498 "Overwriting end of array!\n" : "OK",
7499 (UV)(RExC_emit - RExC_emit_start),
7500 (UV)(RExC_parse - RExC_start),
7501 (UV)RExC_offsets[0]));
7502 Set_Cur_Node_Offset;
7511 - reguni - emit (if appropriate) a Unicode character
7514 S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
7517 return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
7521 - reginsert - insert an operator in front of already-emitted operand
7523 * Means relocating the operand.
7526 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
7529 register regnode *src;
7530 register regnode *dst;
7531 register regnode *place;
7532 const int offset = regarglen[(U8)op];
7533 const int size = NODE_STEP_REGNODE + offset;
7534 GET_RE_DEBUG_FLAGS_DECL;
7535 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
7536 DEBUG_PARSE_FMT("inst"," - %s",reg_name[op]);
7545 if (RExC_open_parens) {
7547 DEBUG_PARSE_FMT("inst"," - %d",RExC_npar);
7548 for ( paren=0 ; paren < RExC_npar ; paren++ ) {
7549 if ( RExC_open_parens[paren] >= opnd ) {
7550 DEBUG_PARSE_FMT("open"," - %d",size);
7551 RExC_open_parens[paren] += size;
7553 DEBUG_PARSE_FMT("open"," - %s","ok");
7555 if ( RExC_close_parens[paren] >= opnd ) {
7556 DEBUG_PARSE_FMT("close"," - %d",size);
7557 RExC_close_parens[paren] += size;
7559 DEBUG_PARSE_FMT("close"," - %s","ok");
7564 while (src > opnd) {
7565 StructCopy(--src, --dst, regnode);
7566 if (RExC_offsets) { /* MJD 20010112 */
7567 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
7571 (UV)(dst - RExC_emit_start) > RExC_offsets[0]
7572 ? "Overwriting end of array!\n" : "OK",
7573 (UV)(src - RExC_emit_start),
7574 (UV)(dst - RExC_emit_start),
7575 (UV)RExC_offsets[0]));
7576 Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
7577 Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
7582 place = opnd; /* Op node, where operand used to be. */
7583 if (RExC_offsets) { /* MJD */
7584 MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
7588 (UV)(place - RExC_emit_start) > RExC_offsets[0]
7589 ? "Overwriting end of array!\n" : "OK",
7590 (UV)(place - RExC_emit_start),
7591 (UV)(RExC_parse - RExC_start),
7592 (UV)RExC_offsets[0]));
7593 Set_Node_Offset(place, RExC_parse);
7594 Set_Node_Length(place, 1);
7596 src = NEXTOPER(place);
7597 FILL_ADVANCE_NODE(place, op);
7598 Zero(src, offset, regnode);
7602 - regtail - set the next-pointer at the end of a node chain of p to val.
7603 - SEE ALSO: regtail_study
7605 /* TODO: All three parms should be const */
7607 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
7610 register regnode *scan;
7611 GET_RE_DEBUG_FLAGS_DECL;
7613 PERL_UNUSED_ARG(depth);
7619 /* Find last node. */
7622 regnode * const temp = regnext(scan);
7624 SV * const mysv=sv_newmortal();
7625 DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
7626 regprop(RExC_rx, mysv, scan);
7627 PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
7628 SvPV_nolen_const(mysv), REG_NODE_NUM(scan),
7629 (temp == NULL ? "->" : ""),
7630 (temp == NULL ? reg_name[OP(val)] : "")
7638 if (reg_off_by_arg[OP(scan)]) {
7639 ARG_SET(scan, val - scan);
7642 NEXT_OFF(scan) = val - scan;
7648 - regtail_study - set the next-pointer at the end of a node chain of p to val.
7649 - Look for optimizable sequences at the same time.
7650 - currently only looks for EXACT chains.
7652 This is expermental code. The idea is to use this routine to perform
7653 in place optimizations on branches and groups as they are constructed,
7654 with the long term intention of removing optimization from study_chunk so
7655 that it is purely analytical.
7657 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
7658 to control which is which.
7661 /* TODO: All four parms should be const */
7664 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
7667 register regnode *scan;
7669 #ifdef EXPERIMENTAL_INPLACESCAN
7673 GET_RE_DEBUG_FLAGS_DECL;
7679 /* Find last node. */
7683 regnode * const temp = regnext(scan);
7684 #ifdef EXPERIMENTAL_INPLACESCAN
7685 if (PL_regkind[OP(scan)] == EXACT)
7686 if (join_exact(pRExC_state,scan,&min,1,val,depth+1))
7694 if( exact == PSEUDO )
7696 else if ( exact != OP(scan) )
7705 SV * const mysv=sv_newmortal();
7706 DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
7707 regprop(RExC_rx, mysv, scan);
7708 PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
7709 SvPV_nolen_const(mysv),
7718 SV * const mysv_val=sv_newmortal();
7719 DEBUG_PARSE_MSG("");
7720 regprop(RExC_rx, mysv_val, val);
7721 PerlIO_printf(Perl_debug_log, "~ attach to %s (%d) offset to %d\n",
7722 SvPV_nolen_const(mysv_val),
7727 if (reg_off_by_arg[OP(scan)]) {
7728 ARG_SET(scan, val - scan);
7731 NEXT_OFF(scan) = val - scan;
7739 - regcurly - a little FSA that accepts {\d+,?\d*}
7742 S_regcurly(register const char *s)
7761 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
7764 Perl_regdump(pTHX_ const regexp *r)
7768 SV * const sv = sv_newmortal();
7769 SV *dsv= sv_newmortal();
7771 (void)dumpuntil(r, r->program, r->program + 1, NULL, NULL, sv, 0, 0);
7773 /* Header fields of interest. */
7774 if (r->anchored_substr) {
7775 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr),
7776 RE_SV_DUMPLEN(r->anchored_substr), 30);
7777 PerlIO_printf(Perl_debug_log,
7778 "anchored %s%s at %"IVdf" ",
7779 s, RE_SV_TAIL(r->anchored_substr),
7780 (IV)r->anchored_offset);
7781 } else if (r->anchored_utf8) {
7782 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8),
7783 RE_SV_DUMPLEN(r->anchored_utf8), 30);
7784 PerlIO_printf(Perl_debug_log,
7785 "anchored utf8 %s%s at %"IVdf" ",
7786 s, RE_SV_TAIL(r->anchored_utf8),
7787 (IV)r->anchored_offset);
7789 if (r->float_substr) {
7790 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr),
7791 RE_SV_DUMPLEN(r->float_substr), 30);
7792 PerlIO_printf(Perl_debug_log,
7793 "floating %s%s at %"IVdf"..%"UVuf" ",
7794 s, RE_SV_TAIL(r->float_substr),
7795 (IV)r->float_min_offset, (UV)r->float_max_offset);
7796 } else if (r->float_utf8) {
7797 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8),
7798 RE_SV_DUMPLEN(r->float_utf8), 30);
7799 PerlIO_printf(Perl_debug_log,
7800 "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
7801 s, RE_SV_TAIL(r->float_utf8),
7802 (IV)r->float_min_offset, (UV)r->float_max_offset);
7804 if (r->check_substr || r->check_utf8)
7805 PerlIO_printf(Perl_debug_log,
7807 (r->check_substr == r->float_substr
7808 && r->check_utf8 == r->float_utf8
7809 ? "(checking floating" : "(checking anchored"));
7810 if (r->reganch & ROPT_NOSCAN)
7811 PerlIO_printf(Perl_debug_log, " noscan");
7812 if (r->reganch & ROPT_CHECK_ALL)
7813 PerlIO_printf(Perl_debug_log, " isall");
7814 if (r->check_substr || r->check_utf8)
7815 PerlIO_printf(Perl_debug_log, ") ");
7817 if (r->regstclass) {
7818 regprop(r, sv, r->regstclass);
7819 PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
7821 if (r->reganch & ROPT_ANCH) {
7822 PerlIO_printf(Perl_debug_log, "anchored");
7823 if (r->reganch & ROPT_ANCH_BOL)
7824 PerlIO_printf(Perl_debug_log, "(BOL)");
7825 if (r->reganch & ROPT_ANCH_MBOL)
7826 PerlIO_printf(Perl_debug_log, "(MBOL)");
7827 if (r->reganch & ROPT_ANCH_SBOL)
7828 PerlIO_printf(Perl_debug_log, "(SBOL)");
7829 if (r->reganch & ROPT_ANCH_GPOS)
7830 PerlIO_printf(Perl_debug_log, "(GPOS)");
7831 PerlIO_putc(Perl_debug_log, ' ');
7833 if (r->reganch & ROPT_GPOS_SEEN)
7834 PerlIO_printf(Perl_debug_log, "GPOS ");
7835 if (r->reganch & ROPT_SKIP)
7836 PerlIO_printf(Perl_debug_log, "plus ");
7837 if (r->reganch & ROPT_IMPLICIT)
7838 PerlIO_printf(Perl_debug_log, "implicit ");
7839 PerlIO_printf(Perl_debug_log, "minlen %ld ", (long) r->minlen);
7840 if (r->reganch & ROPT_EVAL_SEEN)
7841 PerlIO_printf(Perl_debug_log, "with eval ");
7842 PerlIO_printf(Perl_debug_log, "\n");
7844 PERL_UNUSED_CONTEXT;
7846 #endif /* DEBUGGING */
7850 - regprop - printable representation of opcode
7853 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
7858 GET_RE_DEBUG_FLAGS_DECL;
7860 sv_setpvn(sv, "", 0);
7861 if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */
7862 /* It would be nice to FAIL() here, but this may be called from
7863 regexec.c, and it would be hard to supply pRExC_state. */
7864 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
7865 sv_catpv(sv, reg_name[OP(o)]); /* Take off const! */
7867 k = PL_regkind[OP(o)];
7870 SV * const dsv = sv_2mortal(newSVpvs(""));
7871 /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
7872 * is a crude hack but it may be the best for now since
7873 * we have no flag "this EXACTish node was UTF-8"
7875 const char * const s =
7876 pv_pretty(dsv, STRING(o), STR_LEN(o), 60,
7877 PL_colors[0], PL_colors[1],
7878 PERL_PV_ESCAPE_UNI_DETECT |
7879 PERL_PV_PRETTY_ELIPSES |
7882 Perl_sv_catpvf(aTHX_ sv, " %s", s );
7883 } else if (k == TRIE) {
7884 /* print the details of the trie in dumpuntil instead, as
7885 * prog->data isn't available here */
7886 const char op = OP(o);
7887 const I32 n = ARG(o);
7888 const reg_ac_data * const ac = IS_TRIE_AC(op) ?
7889 (reg_ac_data *)prog->data->data[n] :
7891 const reg_trie_data * const trie = !IS_TRIE_AC(op) ?
7892 (reg_trie_data*)prog->data->data[n] :
7895 Perl_sv_catpvf(aTHX_ sv, "-%s",reg_name[o->flags]);
7896 DEBUG_TRIE_COMPILE_r(
7897 Perl_sv_catpvf(aTHX_ sv,
7898 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
7899 (UV)trie->startstate,
7900 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
7901 (UV)trie->wordcount,
7904 (UV)TRIE_CHARCOUNT(trie),
7905 (UV)trie->uniquecharcount
7908 if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
7910 int rangestart = -1;
7911 U8* bitmap = IS_ANYOF_TRIE(op) ? (U8*)ANYOF_BITMAP(o) : (U8*)TRIE_BITMAP(trie);
7912 Perl_sv_catpvf(aTHX_ sv, "[");
7913 for (i = 0; i <= 256; i++) {
7914 if (i < 256 && BITMAP_TEST(bitmap,i)) {
7915 if (rangestart == -1)
7917 } else if (rangestart != -1) {
7918 if (i <= rangestart + 3)
7919 for (; rangestart < i; rangestart++)
7920 put_byte(sv, rangestart);
7922 put_byte(sv, rangestart);
7924 put_byte(sv, i - 1);
7929 Perl_sv_catpvf(aTHX_ sv, "]");
7932 } else if (k == CURLY) {
7933 if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
7934 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
7935 Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
7937 else if (k == WHILEM && o->flags) /* Ordinal/of */
7938 Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
7939 else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP)
7940 Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o)); /* Parenth number */
7941 else if (k == RECURSE)
7942 Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
7943 else if (k == LOGICAL)
7944 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* 2: embedded, otherwise 1 */
7945 else if (k == ANYOF) {
7946 int i, rangestart = -1;
7947 const U8 flags = ANYOF_FLAGS(o);
7949 /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
7950 static const char * const anyofs[] = {
7983 if (flags & ANYOF_LOCALE)
7984 sv_catpvs(sv, "{loc}");
7985 if (flags & ANYOF_FOLD)
7986 sv_catpvs(sv, "{i}");
7987 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
7988 if (flags & ANYOF_INVERT)
7990 for (i = 0; i <= 256; i++) {
7991 if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
7992 if (rangestart == -1)
7994 } else if (rangestart != -1) {
7995 if (i <= rangestart + 3)
7996 for (; rangestart < i; rangestart++)
7997 put_byte(sv, rangestart);
7999 put_byte(sv, rangestart);
8001 put_byte(sv, i - 1);
8007 if (o->flags & ANYOF_CLASS)
8008 for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++)
8009 if (ANYOF_CLASS_TEST(o,i))
8010 sv_catpv(sv, anyofs[i]);
8012 if (flags & ANYOF_UNICODE)
8013 sv_catpvs(sv, "{unicode}");
8014 else if (flags & ANYOF_UNICODE_ALL)
8015 sv_catpvs(sv, "{unicode_all}");
8019 SV * const sw = regclass_swash(prog, o, FALSE, &lv, 0);
8023 U8 s[UTF8_MAXBYTES_CASE+1];
8025 for (i = 0; i <= 256; i++) { /* just the first 256 */
8026 uvchr_to_utf8(s, i);
8028 if (i < 256 && swash_fetch(sw, s, TRUE)) {
8029 if (rangestart == -1)
8031 } else if (rangestart != -1) {
8032 if (i <= rangestart + 3)
8033 for (; rangestart < i; rangestart++) {
8034 const U8 * const e = uvchr_to_utf8(s,rangestart);
8036 for(p = s; p < e; p++)
8040 const U8 *e = uvchr_to_utf8(s,rangestart);
8042 for (p = s; p < e; p++)
8045 e = uvchr_to_utf8(s, i-1);
8046 for (p = s; p < e; p++)
8053 sv_catpvs(sv, "..."); /* et cetera */
8057 char *s = savesvpv(lv);
8058 char * const origs = s;
8060 while (*s && *s != '\n')
8064 const char * const t = ++s;
8082 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
8084 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
8085 Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
8087 PERL_UNUSED_CONTEXT;
8088 PERL_UNUSED_ARG(sv);
8090 PERL_UNUSED_ARG(prog);
8091 #endif /* DEBUGGING */
8095 Perl_re_intuit_string(pTHX_ regexp *prog)
8096 { /* Assume that RE_INTUIT is set */
8098 GET_RE_DEBUG_FLAGS_DECL;
8099 PERL_UNUSED_CONTEXT;
8103 const char * const s = SvPV_nolen_const(prog->check_substr
8104 ? prog->check_substr : prog->check_utf8);
8106 if (!PL_colorset) reginitcolors();
8107 PerlIO_printf(Perl_debug_log,
8108 "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
8110 prog->check_substr ? "" : "utf8 ",
8111 PL_colors[5],PL_colors[0],
8114 (strlen(s) > 60 ? "..." : ""));
8117 return prog->check_substr ? prog->check_substr : prog->check_utf8;
8121 pregfree - free a regexp
8123 See regdupe below if you change anything here.
8127 Perl_pregfree(pTHX_ struct regexp *r)
8131 GET_RE_DEBUG_FLAGS_DECL;
8133 if (!r || (--r->refcnt > 0))
8139 SV *dsv= sv_newmortal();
8140 RE_PV_QUOTED_DECL(s, (r->reganch & ROPT_UTF8),
8141 dsv, r->precomp, r->prelen, 60);
8142 PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n",
8143 PL_colors[4],PL_colors[5],s);
8147 /* gcov results gave these as non-null 100% of the time, so there's no
8148 optimisation in checking them before calling Safefree */
8149 Safefree(r->precomp);
8150 Safefree(r->offsets); /* 20010421 MJD */
8151 RX_MATCH_COPY_FREE(r);
8152 #ifdef PERL_OLD_COPY_ON_WRITE
8154 SvREFCNT_dec(r->saved_copy);
8157 if (r->anchored_substr)
8158 SvREFCNT_dec(r->anchored_substr);
8159 if (r->anchored_utf8)
8160 SvREFCNT_dec(r->anchored_utf8);
8161 if (r->float_substr)
8162 SvREFCNT_dec(r->float_substr);
8164 SvREFCNT_dec(r->float_utf8);
8165 Safefree(r->substrs);
8168 SvREFCNT_dec(r->paren_names);
8170 int n = r->data->count;
8171 PAD* new_comppad = NULL;
8176 /* If you add a ->what type here, update the comment in regcomp.h */
8177 switch (r->data->what[n]) {
8180 SvREFCNT_dec((SV*)r->data->data[n]);
8183 Safefree(r->data->data[n]);
8186 new_comppad = (AV*)r->data->data[n];
8189 if (new_comppad == NULL)
8190 Perl_croak(aTHX_ "panic: pregfree comppad");
8191 PAD_SAVE_LOCAL(old_comppad,
8192 /* Watch out for global destruction's random ordering. */
8193 (SvTYPE(new_comppad) == SVt_PVAV) ? new_comppad : NULL
8196 refcnt = OpREFCNT_dec((OP_4tree*)r->data->data[n]);
8199 op_free((OP_4tree*)r->data->data[n]);
8201 PAD_RESTORE_LOCAL(old_comppad);
8202 SvREFCNT_dec((SV*)new_comppad);
8208 { /* Aho Corasick add-on structure for a trie node.
8209 Used in stclass optimization only */
8211 reg_ac_data *aho=(reg_ac_data*)r->data->data[n];
8213 refcount = --aho->refcount;
8216 Safefree(aho->states);
8217 Safefree(aho->fail);
8218 aho->trie=NULL; /* not necessary to free this as it is
8219 handled by the 't' case */
8220 Safefree(r->data->data[n]); /* do this last!!!! */
8221 Safefree(r->regstclass);
8227 /* trie structure. */
8229 reg_trie_data *trie=(reg_trie_data*)r->data->data[n];
8231 refcount = --trie->refcount;
8234 Safefree(trie->charmap);
8235 if (trie->widecharmap)
8236 SvREFCNT_dec((SV*)trie->widecharmap);
8237 Safefree(trie->states);
8238 Safefree(trie->trans);
8240 Safefree(trie->bitmap);
8242 Safefree(trie->wordlen);
8244 Safefree(trie->jump);
8246 Safefree(trie->nextword);
8250 SvREFCNT_dec((SV*)trie->words);
8251 if (trie->revcharmap)
8252 SvREFCNT_dec((SV*)trie->revcharmap);
8255 Safefree(r->data->data[n]); /* do this last!!!! */
8260 Perl_croak(aTHX_ "panic: regfree data code '%c'", r->data->what[n]);
8263 Safefree(r->data->what);
8266 Safefree(r->startp);
8271 #define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
8272 #define av_dup_inc(s,t) (AV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8273 #define hv_dup_inc(s,t) (HV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8274 #define SAVEPVN(p,n) ((p) ? savepvn(p,n) : NULL)
8277 regdupe - duplicate a regexp.
8279 This routine is called by sv.c's re_dup and is expected to clone a
8280 given regexp structure. It is a no-op when not under USE_ITHREADS.
8281 (Originally this *was* re_dup() for change history see sv.c)
8283 See pregfree() above if you change anything here.
8285 #if defined(USE_ITHREADS)
8287 Perl_regdupe(pTHX_ const regexp *r, CLONE_PARAMS *param)
8292 struct reg_substr_datum *s;
8295 return (REGEXP *)NULL;
8297 if ((ret = (REGEXP *)ptr_table_fetch(PL_ptr_table, r)))
8300 len = r->offsets[0];
8301 npar = r->nparens+1;
8303 Newxc(ret, sizeof(regexp) + (len+1)*sizeof(regnode), char, regexp);
8304 Copy(r->program, ret->program, len+1, regnode);
8306 Newx(ret->startp, npar, I32);
8307 Copy(r->startp, ret->startp, npar, I32);
8308 Newx(ret->endp, npar, I32);
8309 Copy(r->startp, ret->startp, npar, I32);
8311 Newx(ret->substrs, 1, struct reg_substr_data);
8312 for (s = ret->substrs->data, i = 0; i < 3; i++, s++) {
8313 s->min_offset = r->substrs->data[i].min_offset;
8314 s->max_offset = r->substrs->data[i].max_offset;
8315 s->end_shift = r->substrs->data[i].end_shift;
8316 s->substr = sv_dup_inc(r->substrs->data[i].substr, param);
8317 s->utf8_substr = sv_dup_inc(r->substrs->data[i].utf8_substr, param);
8320 ret->regstclass = NULL;
8323 const int count = r->data->count;
8326 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
8327 char, struct reg_data);
8328 Newx(d->what, count, U8);
8331 for (i = 0; i < count; i++) {
8332 d->what[i] = r->data->what[i];
8333 switch (d->what[i]) {
8334 /* legal options are one of: sfpont
8335 see also regcomp.h and pregfree() */
8338 d->data[i] = sv_dup_inc((SV *)r->data->data[i], param);
8341 d->data[i] = av_dup_inc((AV *)r->data->data[i], param);
8344 /* This is cheating. */
8345 Newx(d->data[i], 1, struct regnode_charclass_class);
8346 StructCopy(r->data->data[i], d->data[i],
8347 struct regnode_charclass_class);
8348 ret->regstclass = (regnode*)d->data[i];
8351 /* Compiled op trees are readonly, and can thus be
8352 shared without duplication. */
8354 d->data[i] = (void*)OpREFCNT_inc((OP*)r->data->data[i]);
8358 d->data[i] = r->data->data[i];
8361 d->data[i] = r->data->data[i];
8363 ((reg_trie_data*)d->data[i])->refcount++;
8367 d->data[i] = r->data->data[i];
8369 ((reg_ac_data*)d->data[i])->refcount++;
8371 /* Trie stclasses are readonly and can thus be shared
8372 * without duplication. We free the stclass in pregfree
8373 * when the corresponding reg_ac_data struct is freed.
8375 ret->regstclass= r->regstclass;
8378 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", r->data->what[i]);
8387 Newx(ret->offsets, 2*len+1, U32);
8388 Copy(r->offsets, ret->offsets, 2*len+1, U32);
8390 ret->precomp = SAVEPVN(r->precomp, r->prelen);
8391 ret->refcnt = r->refcnt;
8392 ret->minlen = r->minlen;
8393 ret->prelen = r->prelen;
8394 ret->nparens = r->nparens;
8395 ret->lastparen = r->lastparen;
8396 ret->lastcloseparen = r->lastcloseparen;
8397 ret->reganch = r->reganch;
8399 ret->sublen = r->sublen;
8401 ret->engine = r->engine;
8403 ret->paren_names = hv_dup_inc(r->paren_names, param);
8405 if (RX_MATCH_COPIED(ret))
8406 ret->subbeg = SAVEPVN(r->subbeg, r->sublen);
8409 #ifdef PERL_OLD_COPY_ON_WRITE
8410 ret->saved_copy = NULL;
8413 ptr_table_store(PL_ptr_table, r, ret);
8418 #ifndef PERL_IN_XSUB_RE
8420 - regnext - dig the "next" pointer out of a node
8423 Perl_regnext(pTHX_ register regnode *p)
8426 register I32 offset;
8428 if (p == &PL_regdummy)
8431 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
8440 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
8443 STRLEN l1 = strlen(pat1);
8444 STRLEN l2 = strlen(pat2);
8447 const char *message;
8453 Copy(pat1, buf, l1 , char);
8454 Copy(pat2, buf + l1, l2 , char);
8455 buf[l1 + l2] = '\n';
8456 buf[l1 + l2 + 1] = '\0';
8458 /* ANSI variant takes additional second argument */
8459 va_start(args, pat2);
8463 msv = vmess(buf, &args);
8465 message = SvPV_const(msv,l1);
8468 Copy(message, buf, l1 , char);
8469 buf[l1-1] = '\0'; /* Overwrite \n */
8470 Perl_croak(aTHX_ "%s", buf);
8473 /* XXX Here's a total kludge. But we need to re-enter for swash routines. */
8475 #ifndef PERL_IN_XSUB_RE
8477 Perl_save_re_context(pTHX)
8481 struct re_save_state *state;
8483 SAVEVPTR(PL_curcop);
8484 SSGROW(SAVESTACK_ALLOC_FOR_RE_SAVE_STATE + 1);
8486 state = (struct re_save_state *)(PL_savestack + PL_savestack_ix);
8487 PL_savestack_ix += SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
8488 SSPUSHINT(SAVEt_RE_STATE);
8490 Copy(&PL_reg_state, state, 1, struct re_save_state);
8492 PL_reg_start_tmp = 0;
8493 PL_reg_start_tmpl = 0;
8494 PL_reg_oldsaved = NULL;
8495 PL_reg_oldsavedlen = 0;
8497 PL_reg_leftiter = 0;
8498 PL_reg_poscache = NULL;
8499 PL_reg_poscache_size = 0;
8500 #ifdef PERL_OLD_COPY_ON_WRITE
8504 /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
8506 const REGEXP * const rx = PM_GETRE(PL_curpm);
8509 for (i = 1; i <= rx->nparens; i++) {
8510 char digits[TYPE_CHARS(long)];
8511 const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
8512 GV *const *const gvp
8513 = (GV**)hv_fetch(PL_defstash, digits, len, 0);
8516 GV * const gv = *gvp;
8517 if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
8527 clear_re(pTHX_ void *r)
8530 ReREFCNT_dec((regexp *)r);
8536 S_put_byte(pTHX_ SV *sv, int c)
8538 if (isCNTRL(c) || c == 255 || !isPRINT(c))
8539 Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
8540 else if (c == '-' || c == ']' || c == '\\' || c == '^')
8541 Perl_sv_catpvf(aTHX_ sv, "\\%c", c);
8543 Perl_sv_catpvf(aTHX_ sv, "%c", c);
8547 #define CLEAR_OPTSTART \
8548 if (optstart) STMT_START { \
8549 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%d nodes)\n", node - optstart)); \
8553 #define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
8555 STATIC const regnode *
8556 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
8557 const regnode *last, const regnode *plast,
8558 SV* sv, I32 indent, U32 depth)
8561 register U8 op = PSEUDO; /* Arbitrary non-END op. */
8562 register const regnode *next;
8563 const regnode *optstart= NULL;
8564 GET_RE_DEBUG_FLAGS_DECL;
8566 #ifdef DEBUG_DUMPUNTIL
8567 PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
8568 last ? last-start : 0,plast ? plast-start : 0);
8571 if (plast && plast < last)
8574 while (PL_regkind[op] != END && (!last || node < last)) {
8575 /* While that wasn't END last time... */
8581 next = regnext((regnode *)node);
8584 if (OP(node) == OPTIMIZED) {
8585 if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
8592 regprop(r, sv, node);
8593 PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
8594 (int)(2*indent + 1), "", SvPVX_const(sv));
8596 if (OP(node) != OPTIMIZED) {
8597 if (next == NULL) /* Next ptr. */
8598 PerlIO_printf(Perl_debug_log, "(0)");
8599 else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
8600 PerlIO_printf(Perl_debug_log, "(FAIL)");
8602 PerlIO_printf(Perl_debug_log, "(%"IVdf")", (IV)(next - start));
8604 /*if (PL_regkind[(U8)op] != TRIE)*/
8605 (void)PerlIO_putc(Perl_debug_log, '\n');
8609 if (PL_regkind[(U8)op] == BRANCHJ) {
8612 register const regnode *nnode = (OP(next) == LONGJMP
8613 ? regnext((regnode *)next)
8615 if (last && nnode > last)
8617 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
8620 else if (PL_regkind[(U8)op] == BRANCH) {
8622 DUMPUNTIL(NEXTOPER(node), next);
8624 else if ( PL_regkind[(U8)op] == TRIE ) {
8625 const regnode *this_trie = node;
8626 const char op = OP(node);
8627 const I32 n = ARG(node);
8628 const reg_ac_data * const ac = op>=AHOCORASICK ?
8629 (reg_ac_data *)r->data->data[n] :
8631 const reg_trie_data * const trie = op<AHOCORASICK ?
8632 (reg_trie_data*)r->data->data[n] :
8634 const regnode *nextbranch= NULL;
8636 sv_setpvn(sv, "", 0);
8637 for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
8638 SV ** const elem_ptr = av_fetch(trie->words,word_idx,0);
8640 PerlIO_printf(Perl_debug_log, "%*s%s ",
8641 (int)(2*(indent+3)), "",
8642 elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
8643 PL_colors[0], PL_colors[1],
8644 (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
8645 PERL_PV_PRETTY_ELIPSES |
8651 U16 dist= trie->jump[word_idx+1];
8652 PerlIO_printf(Perl_debug_log, "(%u)\n",
8653 (dist ? this_trie + dist : next) - start);
8656 nextbranch = this_trie + trie->jump[0];
8657 DUMPUNTIL(this_trie + dist, nextbranch);
8659 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
8660 nextbranch= regnext((regnode *)nextbranch);
8662 PerlIO_printf(Perl_debug_log, "\n");
8665 if (last && next > last)
8670 else if ( op == CURLY ) { /* "next" might be very big: optimizer */
8671 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
8672 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
8674 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
8676 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
8678 else if ( op == PLUS || op == STAR) {
8679 DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
8681 else if (op == ANYOF) {
8682 /* arglen 1 + class block */
8683 node += 1 + ((ANYOF_FLAGS(node) & ANYOF_LARGE)
8684 ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
8685 node = NEXTOPER(node);
8687 else if (PL_regkind[(U8)op] == EXACT) {
8688 /* Literal string, where present. */
8689 node += NODE_SZ_STR(node) - 1;
8690 node = NEXTOPER(node);
8693 node = NEXTOPER(node);
8694 node += regarglen[(U8)op];
8696 if (op == CURLYX || op == OPEN)
8698 else if (op == WHILEM)
8702 #ifdef DEBUG_DUMPUNTIL
8703 PerlIO_printf(Perl_debug_log, "--- %d\n",indent);
8708 #endif /* DEBUGGING */
8712 * c-indentation-style: bsd
8714 * indent-tabs-mode: t
8717 * ex: set ts=8 sts=4 sw=4 noet: