5 * 'A fair jaw-cracker dwarf-language must be.' --Samwise Gamgee
7 * [p.285 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
10 /* This file contains functions for compiling a regular expression. See
11 * also regexec.c which funnily enough, contains functions for executing
12 * a regular expression.
14 * This file is also copied at build time to ext/re/re_comp.c, where
15 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
16 * This causes the main functions to be compiled under new names and with
17 * debugging support added, which makes "use re 'debug'" work.
20 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
21 * confused with the original package (see point 3 below). Thanks, Henry!
24 /* Additional note: this code is very heavily munged from Henry's version
25 * in places. In some spots I've traded clarity for efficiency, so don't
26 * blame Henry for some of the lack of readability.
29 /* The names of the functions have been changed from regcomp and
30 * regexec to pregcomp and pregexec in order to avoid conflicts
31 * with the POSIX routines of the same names.
34 #ifdef PERL_EXT_RE_BUILD
39 * pregcomp and pregexec -- regsub and regerror are not used in perl
41 * Copyright (c) 1986 by University of Toronto.
42 * Written by Henry Spencer. Not derived from licensed software.
44 * Permission is granted to anyone to use this software for any
45 * purpose on any computer system, and to redistribute it freely,
46 * subject to the following restrictions:
48 * 1. The author is not responsible for the consequences of use of
49 * this software, no matter how awful, even if they arise
52 * 2. The origin of this software must not be misrepresented, either
53 * by explicit claim or by omission.
55 * 3. Altered versions must be plainly marked as such, and must not
56 * be misrepresented as being the original software.
59 **** Alterations to Henry's code are...
61 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
62 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
63 **** by Larry Wall and others
65 **** You may distribute under the terms of either the GNU General Public
66 **** License or the Artistic License, as specified in the README file.
69 * Beware that some of this code is subtly aware of the way operator
70 * precedence is structured in regular expressions. Serious changes in
71 * regular-expression syntax might require a total rethink.
74 #define PERL_IN_REGCOMP_C
77 #ifndef PERL_IN_XSUB_RE
82 #ifdef PERL_IN_XSUB_RE
84 EXTERN_C const struct regexp_engine my_reg_engine;
89 #include "dquote_inline.h"
90 #include "invlist_inline.h"
91 #include "unicode_constants.h"
93 #define HAS_NONLATIN1_FOLD_CLOSURE(i) \
94 _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
95 #define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
96 _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
97 #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
98 #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
101 #define STATIC static
105 #define MIN(a,b) ((a) < (b) ? (a) : (b))
108 /* this is a chain of data about sub patterns we are processing that
109 need to be handled separately/specially in study_chunk. Its so
110 we can simulate recursion without losing state. */
112 typedef struct scan_frame {
113 regnode *last_regnode; /* last node to process in this frame */
114 regnode *next_regnode; /* next node to process when last is reached */
115 U32 prev_recursed_depth;
116 I32 stopparen; /* what stopparen do we use */
117 U32 is_top_frame; /* what flags do we use? */
119 struct scan_frame *this_prev_frame; /* this previous frame */
120 struct scan_frame *prev_frame; /* previous frame */
121 struct scan_frame *next_frame; /* next frame */
124 /* Certain characters are output as a sequence with the first being a
126 #define isBACKSLASHED_PUNCT(c) \
127 ((c) == '-' || (c) == ']' || (c) == '\\' || (c) == '^')
130 struct RExC_state_t {
131 U32 flags; /* RXf_* are we folding, multilining? */
132 U32 pm_flags; /* PMf_* stuff from the calling PMOP */
133 char *precomp; /* uncompiled string. */
134 char *precomp_end; /* pointer to end of uncompiled string. */
135 REGEXP *rx_sv; /* The SV that is the regexp. */
136 regexp *rx; /* perl core regexp structure */
137 regexp_internal *rxi; /* internal data for regexp object
139 char *start; /* Start of input for compile */
140 char *end; /* End of input for compile */
141 char *parse; /* Input-scan pointer. */
142 char *adjusted_start; /* 'start', adjusted. See code use */
143 STRLEN precomp_adj; /* an offset beyond precomp. See code use */
144 SSize_t whilem_seen; /* number of WHILEM in this expr */
145 regnode *emit_start; /* Start of emitted-code area */
146 regnode *emit_bound; /* First regnode outside of the
148 regnode *emit; /* Code-emit pointer; if = &emit_dummy,
149 implies compiling, so don't emit */
150 regnode_ssc emit_dummy; /* placeholder for emit to point to;
151 large enough for the largest
152 non-EXACTish node, so can use it as
154 I32 naughty; /* How bad is this pattern? */
155 I32 sawback; /* Did we see \1, ...? */
157 SSize_t size; /* Code size. */
158 I32 npar; /* Capture buffer count, (OPEN) plus
159 one. ("par" 0 is the whole
161 I32 nestroot; /* root parens we are in - used by
165 regnode **open_parens; /* pointers to open parens */
166 regnode **close_parens; /* pointers to close parens */
167 regnode *opend; /* END node in program */
168 I32 utf8; /* whether the pattern is utf8 or not */
169 I32 orig_utf8; /* whether the pattern was originally in utf8 */
170 /* XXX use this for future optimisation of case
171 * where pattern must be upgraded to utf8. */
172 I32 uni_semantics; /* If a d charset modifier should use unicode
173 rules, even if the pattern is not in
175 HV *paren_names; /* Paren names */
177 regnode **recurse; /* Recurse regops */
178 I32 recurse_count; /* Number of recurse regops */
179 U8 *study_chunk_recursed; /* bitmap of which subs we have moved
181 U32 study_chunk_recursed_bytes; /* bytes in bitmap */
185 I32 override_recoding;
187 I32 recode_x_to_native;
189 I32 in_multi_char_class;
190 struct reg_code_block *code_blocks; /* positions of literal (?{})
192 int num_code_blocks; /* size of code_blocks[] */
193 int code_index; /* next code_blocks[] slot */
194 SSize_t maxlen; /* mininum possible number of chars in string to match */
195 scan_frame *frame_head;
196 scan_frame *frame_last;
199 #ifdef ADD_TO_REGEXEC
200 char *starttry; /* -Dr: where regtry was called. */
201 #define RExC_starttry (pRExC_state->starttry)
203 SV *runtime_code_qr; /* qr with the runtime code blocks */
205 const char *lastparse;
207 AV *paren_name_list; /* idx -> name */
208 U32 study_chunk_recursed_count;
211 #define RExC_lastparse (pRExC_state->lastparse)
212 #define RExC_lastnum (pRExC_state->lastnum)
213 #define RExC_paren_name_list (pRExC_state->paren_name_list)
214 #define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count)
215 #define RExC_mysv (pRExC_state->mysv1)
216 #define RExC_mysv1 (pRExC_state->mysv1)
217 #define RExC_mysv2 (pRExC_state->mysv2)
220 bool seen_unfolded_sharp_s;
223 #define RExC_flags (pRExC_state->flags)
224 #define RExC_pm_flags (pRExC_state->pm_flags)
225 #define RExC_precomp (pRExC_state->precomp)
226 #define RExC_precomp_adj (pRExC_state->precomp_adj)
227 #define RExC_adjusted_start (pRExC_state->adjusted_start)
228 #define RExC_precomp_end (pRExC_state->precomp_end)
229 #define RExC_rx_sv (pRExC_state->rx_sv)
230 #define RExC_rx (pRExC_state->rx)
231 #define RExC_rxi (pRExC_state->rxi)
232 #define RExC_start (pRExC_state->start)
233 #define RExC_end (pRExC_state->end)
234 #define RExC_parse (pRExC_state->parse)
235 #define RExC_whilem_seen (pRExC_state->whilem_seen)
237 /* Set during the sizing pass when there is a LATIN SMALL LETTER SHARP S in any
238 * EXACTF node, hence was parsed under /di rules. If later in the parse,
239 * something forces the pattern into using /ui rules, the sharp s should be
240 * folded into the sequence 'ss', which takes up more space than previously
241 * calculated. This means that the sizing pass needs to be restarted. (The
242 * node also becomes an EXACTFU_SS.) For all other characters, an EXACTF node
243 * that gets converted to /ui (and EXACTFU) occupies the same amount of space,
244 * so there is no need to resize [perl #125990]. */
245 #define RExC_seen_unfolded_sharp_s (pRExC_state->seen_unfolded_sharp_s)
247 #ifdef RE_TRACK_PATTERN_OFFSETS
248 #define RExC_offsets (pRExC_state->rxi->u.offsets) /* I am not like the
251 #define RExC_emit (pRExC_state->emit)
252 #define RExC_emit_dummy (pRExC_state->emit_dummy)
253 #define RExC_emit_start (pRExC_state->emit_start)
254 #define RExC_emit_bound (pRExC_state->emit_bound)
255 #define RExC_sawback (pRExC_state->sawback)
256 #define RExC_seen (pRExC_state->seen)
257 #define RExC_size (pRExC_state->size)
258 #define RExC_maxlen (pRExC_state->maxlen)
259 #define RExC_npar (pRExC_state->npar)
260 #define RExC_nestroot (pRExC_state->nestroot)
261 #define RExC_extralen (pRExC_state->extralen)
262 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
263 #define RExC_utf8 (pRExC_state->utf8)
264 #define RExC_uni_semantics (pRExC_state->uni_semantics)
265 #define RExC_orig_utf8 (pRExC_state->orig_utf8)
266 #define RExC_open_parens (pRExC_state->open_parens)
267 #define RExC_close_parens (pRExC_state->close_parens)
268 #define RExC_opend (pRExC_state->opend)
269 #define RExC_paren_names (pRExC_state->paren_names)
270 #define RExC_recurse (pRExC_state->recurse)
271 #define RExC_recurse_count (pRExC_state->recurse_count)
272 #define RExC_study_chunk_recursed (pRExC_state->study_chunk_recursed)
273 #define RExC_study_chunk_recursed_bytes \
274 (pRExC_state->study_chunk_recursed_bytes)
275 #define RExC_in_lookbehind (pRExC_state->in_lookbehind)
276 #define RExC_contains_locale (pRExC_state->contains_locale)
277 #define RExC_contains_i (pRExC_state->contains_i)
278 #define RExC_override_recoding (pRExC_state->override_recoding)
280 # define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
282 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
283 #define RExC_frame_head (pRExC_state->frame_head)
284 #define RExC_frame_last (pRExC_state->frame_last)
285 #define RExC_frame_count (pRExC_state->frame_count)
286 #define RExC_strict (pRExC_state->strict)
288 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
289 * a flag to disable back-off on the fixed/floating substrings - if it's
290 * a high complexity pattern we assume the benefit of avoiding a full match
291 * is worth the cost of checking for the substrings even if they rarely help.
293 #define RExC_naughty (pRExC_state->naughty)
294 #define TOO_NAUGHTY (10)
295 #define MARK_NAUGHTY(add) \
296 if (RExC_naughty < TOO_NAUGHTY) \
297 RExC_naughty += (add)
298 #define MARK_NAUGHTY_EXP(exp, add) \
299 if (RExC_naughty < TOO_NAUGHTY) \
300 RExC_naughty += RExC_naughty / (exp) + (add)
302 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
303 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
304 ((*s) == '{' && regcurly(s)))
307 * Flags to be passed up and down.
309 #define WORST 0 /* Worst case. */
310 #define HASWIDTH 0x01 /* Known to match non-null strings. */
312 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
313 * character. (There needs to be a case: in the switch statement in regexec.c
314 * for any node marked SIMPLE.) Note that this is not the same thing as
317 #define SPSTART 0x04 /* Starts with * or + */
318 #define POSTPONED 0x08 /* (?1),(?&name), (??{...}) or similar */
319 #define TRYAGAIN 0x10 /* Weeded out a declaration. */
320 #define RESTART_PASS1 0x20 /* Need to restart sizing pass */
321 #define NEED_UTF8 0x40 /* In conjunction with RESTART_PASS1, need to
322 calcuate sizes as UTF-8 */
324 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
326 /* whether trie related optimizations are enabled */
327 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
328 #define TRIE_STUDY_OPT
329 #define FULL_TRIE_STUDY
335 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
336 #define PBITVAL(paren) (1 << ((paren) & 7))
337 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
338 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
339 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
341 #define REQUIRE_UTF8(flagp) STMT_START { \
344 *flagp = RESTART_PASS1|NEED_UTF8; \
349 /* Change from /d into /u rules, and restart the parse if we've already seen
350 * something whose size would increase as a result, by setting *flagp and
351 * returning 'restart_retval'. RExC_uni_semantics is a flag that indicates
352 * we've change to /u during the parse. */
353 #define REQUIRE_UNI_RULES(flagp, restart_retval) \
355 if (DEPENDS_SEMANTICS) { \
357 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); \
358 RExC_uni_semantics = 1; \
359 if (RExC_seen_unfolded_sharp_s) { \
360 *flagp |= RESTART_PASS1; \
361 return restart_retval; \
366 /* This converts the named class defined in regcomp.h to its equivalent class
367 * number defined in handy.h. */
368 #define namedclass_to_classnum(class) ((int) ((class) / 2))
369 #define classnum_to_namedclass(classnum) ((classnum) * 2)
371 #define _invlist_union_complement_2nd(a, b, output) \
372 _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
373 #define _invlist_intersection_complement_2nd(a, b, output) \
374 _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
376 /* About scan_data_t.
378 During optimisation we recurse through the regexp program performing
379 various inplace (keyhole style) optimisations. In addition study_chunk
380 and scan_commit populate this data structure with information about
381 what strings MUST appear in the pattern. We look for the longest
382 string that must appear at a fixed location, and we look for the
383 longest string that may appear at a floating location. So for instance
388 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
389 strings (because they follow a .* construct). study_chunk will identify
390 both FOO and BAR as being the longest fixed and floating strings respectively.
392 The strings can be composites, for instance
396 will result in a composite fixed substring 'foo'.
398 For each string some basic information is maintained:
400 - offset or min_offset
401 This is the position the string must appear at, or not before.
402 It also implicitly (when combined with minlenp) tells us how many
403 characters must match before the string we are searching for.
404 Likewise when combined with minlenp and the length of the string it
405 tells us how many characters must appear after the string we have
409 Only used for floating strings. This is the rightmost point that
410 the string can appear at. If set to SSize_t_MAX it indicates that the
411 string can occur infinitely far to the right.
414 A pointer to the minimum number of characters of the pattern that the
415 string was found inside. This is important as in the case of positive
416 lookahead or positive lookbehind we can have multiple patterns
421 The minimum length of the pattern overall is 3, the minimum length
422 of the lookahead part is 3, but the minimum length of the part that
423 will actually match is 1. So 'FOO's minimum length is 3, but the
424 minimum length for the F is 1. This is important as the minimum length
425 is used to determine offsets in front of and behind the string being
426 looked for. Since strings can be composites this is the length of the
427 pattern at the time it was committed with a scan_commit. Note that
428 the length is calculated by study_chunk, so that the minimum lengths
429 are not known until the full pattern has been compiled, thus the
430 pointer to the value.
434 In the case of lookbehind the string being searched for can be
435 offset past the start point of the final matching string.
436 If this value was just blithely removed from the min_offset it would
437 invalidate some of the calculations for how many chars must match
438 before or after (as they are derived from min_offset and minlen and
439 the length of the string being searched for).
440 When the final pattern is compiled and the data is moved from the
441 scan_data_t structure into the regexp structure the information
442 about lookbehind is factored in, with the information that would
443 have been lost precalculated in the end_shift field for the
446 The fields pos_min and pos_delta are used to store the minimum offset
447 and the delta to the maximum offset at the current point in the pattern.
451 typedef struct scan_data_t {
452 /*I32 len_min; unused */
453 /*I32 len_delta; unused */
457 SSize_t last_end; /* min value, <0 unless valid. */
458 SSize_t last_start_min;
459 SSize_t last_start_max;
460 SV **longest; /* Either &l_fixed, or &l_float. */
461 SV *longest_fixed; /* longest fixed string found in pattern */
462 SSize_t offset_fixed; /* offset where it starts */
463 SSize_t *minlen_fixed; /* pointer to the minlen relevant to the string */
464 I32 lookbehind_fixed; /* is the position of the string modfied by LB */
465 SV *longest_float; /* longest floating string found in pattern */
466 SSize_t offset_float_min; /* earliest point in string it can appear */
467 SSize_t offset_float_max; /* latest point in string it can appear */
468 SSize_t *minlen_float; /* pointer to the minlen relevant to the string */
469 SSize_t lookbehind_float; /* is the pos of the string modified by LB */
472 SSize_t *last_closep;
473 regnode_ssc *start_class;
477 * Forward declarations for pregcomp()'s friends.
480 static const scan_data_t zero_scan_data =
481 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
483 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
484 #define SF_BEFORE_SEOL 0x0001
485 #define SF_BEFORE_MEOL 0x0002
486 #define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
487 #define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
489 #define SF_FIX_SHIFT_EOL (+2)
490 #define SF_FL_SHIFT_EOL (+4)
492 #define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
493 #define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
495 #define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
496 #define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
497 #define SF_IS_INF 0x0040
498 #define SF_HAS_PAR 0x0080
499 #define SF_IN_PAR 0x0100
500 #define SF_HAS_EVAL 0x0200
501 #define SCF_DO_SUBSTR 0x0400
502 #define SCF_DO_STCLASS_AND 0x0800
503 #define SCF_DO_STCLASS_OR 0x1000
504 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
505 #define SCF_WHILEM_VISITED_POS 0x2000
507 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
508 #define SCF_SEEN_ACCEPT 0x8000
509 #define SCF_TRIE_DOING_RESTUDY 0x10000
510 #define SCF_IN_DEFINE 0x20000
515 #define UTF cBOOL(RExC_utf8)
517 /* The enums for all these are ordered so things work out correctly */
518 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
519 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) \
520 == REGEX_DEPENDS_CHARSET)
521 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
522 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) \
523 >= REGEX_UNICODE_CHARSET)
524 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
525 == REGEX_ASCII_RESTRICTED_CHARSET)
526 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
527 >= REGEX_ASCII_RESTRICTED_CHARSET)
528 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) \
529 == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
531 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
533 /* For programs that want to be strictly Unicode compatible by dying if any
534 * attempt is made to match a non-Unicode code point against a Unicode
536 #define ALWAYS_WARN_SUPER ckDEAD(packWARN(WARN_NON_UNICODE))
538 #define OOB_NAMEDCLASS -1
540 /* There is no code point that is out-of-bounds, so this is problematic. But
541 * its only current use is to initialize a variable that is always set before
543 #define OOB_UNICODE 0xDEADBEEF
545 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
546 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
549 /* length of regex to show in messages that don't mark a position within */
550 #define RegexLengthToShowInErrorMessages 127
553 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
554 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
555 * op/pragma/warn/regcomp.
557 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
558 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
560 #define REPORT_LOCATION " in regex; marked by " MARKER1 \
561 " in m/%"UTF8f MARKER2 "%"UTF8f"/"
563 /* The code in this file in places uses one level of recursion with parsing
564 * rebased to an alternate string constructed by us in memory. This can take
565 * the form of something that is completely different from the input, or
566 * something that uses the input as part of the alternate. In the first case,
567 * there should be no possibility of an error, as we are in complete control of
568 * the alternate string. But in the second case we don't control the input
569 * portion, so there may be errors in that. Here's an example:
571 * is handled specially because \x{df} folds to a sequence of more than one
572 * character, 'ss'. What is done is to create and parse an alternate string,
573 * which looks like this:
574 * /(?:\x{DF}|[abc\x{DF}def])/ui
575 * where it uses the input unchanged in the middle of something it constructs,
576 * which is a branch for the DF outside the character class, and clustering
577 * parens around the whole thing. (It knows enough to skip the DF inside the
578 * class while in this substitute parse.) 'abc' and 'def' may have errors that
579 * need to be reported. The general situation looks like this:
582 * Input: ----------------------------------------------------
583 * Constructed: ---------------------------------------------------
586 * The input string sI..eI is the input pattern. The string sC..EC is the
587 * constructed substitute parse string. The portions sC..tC and eC..EC are
588 * constructed by us. The portion tC..eC is an exact duplicate of the input
589 * pattern tI..eI. In the diagram, these are vertically aligned. Suppose that
590 * while parsing, we find an error at xC. We want to display a message showing
591 * the real input string. Thus we need to find the point xI in it which
592 * corresponds to xC. xC >= tC, since the portion of the string sC..tC has
593 * been constructed by us, and so shouldn't have errors. We get:
595 * xI = sI + (tI - sI) + (xC - tC)
597 * and, the offset into sI is:
599 * (xI - sI) = (tI - sI) + (xC - tC)
601 * When the substitute is constructed, we save (tI -sI) as RExC_precomp_adj,
602 * and we save tC as RExC_adjusted_start.
604 * During normal processing of the input pattern, everything points to that,
605 * with RExC_precomp_adj set to 0, and RExC_adjusted_start set to sI.
608 #define tI_sI RExC_precomp_adj
609 #define tC RExC_adjusted_start
610 #define sC RExC_precomp
611 #define xI_offset(xC) ((IV) (tI_sI + (xC - tC)))
612 #define xI(xC) (sC + xI_offset(xC))
613 #define eC RExC_precomp_end
615 #define REPORT_LOCATION_ARGS(xC) \
617 (xI(xC) > eC) /* Don't run off end */ \
618 ? eC - sC /* Length before the <--HERE */ \
620 sC), /* The input pattern printed up to the <--HERE */ \
622 (xI(xC) > eC) ? 0 : eC - xI(xC), /* Length after <--HERE */ \
623 (xI(xC) > eC) ? eC : xI(xC)) /* pattern after <--HERE */
625 /* Used to point after bad bytes for an error message, but avoid skipping
626 * past a nul byte. */
627 #define SKIP_IF_CHAR(s) (!*(s) ? 0 : UTF ? UTF8SKIP(s) : 1)
630 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
631 * arg. Show regex, up to a maximum length. If it's too long, chop and add
634 #define _FAIL(code) STMT_START { \
635 const char *ellipses = ""; \
636 IV len = RExC_precomp_end - RExC_precomp; \
639 SAVEFREESV(RExC_rx_sv); \
640 if (len > RegexLengthToShowInErrorMessages) { \
641 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
642 len = RegexLengthToShowInErrorMessages - 10; \
648 #define FAIL(msg) _FAIL( \
649 Perl_croak(aTHX_ "%s in regex m/%"UTF8f"%s/", \
650 msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
652 #define FAIL2(msg,arg) _FAIL( \
653 Perl_croak(aTHX_ msg " in regex m/%"UTF8f"%s/", \
654 arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
657 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
659 #define Simple_vFAIL(m) STMT_START { \
660 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
661 m, REPORT_LOCATION_ARGS(RExC_parse)); \
665 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
667 #define vFAIL(m) STMT_START { \
669 SAVEFREESV(RExC_rx_sv); \
674 * Like Simple_vFAIL(), but accepts two arguments.
676 #define Simple_vFAIL2(m,a1) STMT_START { \
677 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
678 REPORT_LOCATION_ARGS(RExC_parse)); \
682 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
684 #define vFAIL2(m,a1) STMT_START { \
686 SAVEFREESV(RExC_rx_sv); \
687 Simple_vFAIL2(m, a1); \
692 * Like Simple_vFAIL(), but accepts three arguments.
694 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
695 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
696 REPORT_LOCATION_ARGS(RExC_parse)); \
700 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
702 #define vFAIL3(m,a1,a2) STMT_START { \
704 SAVEFREESV(RExC_rx_sv); \
705 Simple_vFAIL3(m, a1, a2); \
709 * Like Simple_vFAIL(), but accepts four arguments.
711 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
712 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3, \
713 REPORT_LOCATION_ARGS(RExC_parse)); \
716 #define vFAIL4(m,a1,a2,a3) STMT_START { \
718 SAVEFREESV(RExC_rx_sv); \
719 Simple_vFAIL4(m, a1, a2, a3); \
722 /* A specialized version of vFAIL2 that works with UTF8f */
723 #define vFAIL2utf8f(m, a1) STMT_START { \
725 SAVEFREESV(RExC_rx_sv); \
726 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
727 REPORT_LOCATION_ARGS(RExC_parse)); \
730 #define vFAIL3utf8f(m, a1, a2) STMT_START { \
732 SAVEFREESV(RExC_rx_sv); \
733 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
734 REPORT_LOCATION_ARGS(RExC_parse)); \
737 /* These have asserts in them because of [perl #122671] Many warnings in
738 * regcomp.c can occur twice. If they get output in pass1 and later in that
739 * pass, the pattern has to be converted to UTF-8 and the pass restarted, they
740 * would get output again. So they should be output in pass2, and these
741 * asserts make sure new warnings follow that paradigm. */
743 /* m is not necessarily a "literal string", in this macro */
744 #define reg_warn_non_literal_string(loc, m) STMT_START { \
745 __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
746 "%s" REPORT_LOCATION, \
747 m, REPORT_LOCATION_ARGS(loc)); \
750 #define ckWARNreg(loc,m) STMT_START { \
751 __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
753 REPORT_LOCATION_ARGS(loc)); \
756 #define vWARN(loc, m) STMT_START { \
757 __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
759 REPORT_LOCATION_ARGS(loc)); \
762 #define vWARN_dep(loc, m) STMT_START { \
763 __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), \
765 REPORT_LOCATION_ARGS(loc)); \
768 #define ckWARNdep(loc,m) STMT_START { \
769 __ASSERT_(PASS2) Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
771 REPORT_LOCATION_ARGS(loc)); \
774 #define ckWARNregdep(loc,m) STMT_START { \
775 __ASSERT_(PASS2) Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, \
778 REPORT_LOCATION_ARGS(loc)); \
781 #define ckWARN2reg_d(loc,m, a1) STMT_START { \
782 __ASSERT_(PASS2) Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP), \
784 a1, REPORT_LOCATION_ARGS(loc)); \
787 #define ckWARN2reg(loc, m, a1) STMT_START { \
788 __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
790 a1, REPORT_LOCATION_ARGS(loc)); \
793 #define vWARN3(loc, m, a1, a2) STMT_START { \
794 __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
796 a1, a2, REPORT_LOCATION_ARGS(loc)); \
799 #define ckWARN3reg(loc, m, a1, a2) STMT_START { \
800 __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
803 REPORT_LOCATION_ARGS(loc)); \
806 #define vWARN4(loc, m, a1, a2, a3) STMT_START { \
807 __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
810 REPORT_LOCATION_ARGS(loc)); \
813 #define ckWARN4reg(loc, m, a1, a2, a3) STMT_START { \
814 __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
817 REPORT_LOCATION_ARGS(loc)); \
820 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START { \
821 __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
824 REPORT_LOCATION_ARGS(loc)); \
827 /* Macros for recording node offsets. 20001227 mjd@plover.com
828 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
829 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
830 * Element 0 holds the number n.
831 * Position is 1 indexed.
833 #ifndef RE_TRACK_PATTERN_OFFSETS
834 #define Set_Node_Offset_To_R(node,byte)
835 #define Set_Node_Offset(node,byte)
836 #define Set_Cur_Node_Offset
837 #define Set_Node_Length_To_R(node,len)
838 #define Set_Node_Length(node,len)
839 #define Set_Node_Cur_Length(node,start)
840 #define Node_Offset(n)
841 #define Node_Length(n)
842 #define Set_Node_Offset_Length(node,offset,len)
843 #define ProgLen(ri) ri->u.proglen
844 #define SetProgLen(ri,x) ri->u.proglen = x
846 #define ProgLen(ri) ri->u.offsets[0]
847 #define SetProgLen(ri,x) ri->u.offsets[0] = x
848 #define Set_Node_Offset_To_R(node,byte) STMT_START { \
850 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
851 __LINE__, (int)(node), (int)(byte))); \
853 Perl_croak(aTHX_ "value of node is %d in Offset macro", \
856 RExC_offsets[2*(node)-1] = (byte); \
861 #define Set_Node_Offset(node,byte) \
862 Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
863 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
865 #define Set_Node_Length_To_R(node,len) STMT_START { \
867 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
868 __LINE__, (int)(node), (int)(len))); \
870 Perl_croak(aTHX_ "value of node is %d in Length macro", \
873 RExC_offsets[2*(node)] = (len); \
878 #define Set_Node_Length(node,len) \
879 Set_Node_Length_To_R((node)-RExC_emit_start, len)
880 #define Set_Node_Cur_Length(node, start) \
881 Set_Node_Length(node, RExC_parse - start)
883 /* Get offsets and lengths */
884 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
885 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
887 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
888 Set_Node_Offset_To_R((node)-RExC_emit_start, (offset)); \
889 Set_Node_Length_To_R((node)-RExC_emit_start, (len)); \
893 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
894 #define EXPERIMENTAL_INPLACESCAN
895 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
897 #define DEBUG_RExC_seen() \
898 DEBUG_OPTIMISE_MORE_r({ \
899 PerlIO_printf(Perl_debug_log,"RExC_seen: "); \
901 if (RExC_seen & REG_ZERO_LEN_SEEN) \
902 PerlIO_printf(Perl_debug_log,"REG_ZERO_LEN_SEEN "); \
904 if (RExC_seen & REG_LOOKBEHIND_SEEN) \
905 PerlIO_printf(Perl_debug_log,"REG_LOOKBEHIND_SEEN "); \
907 if (RExC_seen & REG_GPOS_SEEN) \
908 PerlIO_printf(Perl_debug_log,"REG_GPOS_SEEN "); \
910 if (RExC_seen & REG_RECURSE_SEEN) \
911 PerlIO_printf(Perl_debug_log,"REG_RECURSE_SEEN "); \
913 if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN) \
914 PerlIO_printf(Perl_debug_log,"REG_TOP_LEVEL_BRANCHES_SEEN "); \
916 if (RExC_seen & REG_VERBARG_SEEN) \
917 PerlIO_printf(Perl_debug_log,"REG_VERBARG_SEEN "); \
919 if (RExC_seen & REG_CUTGROUP_SEEN) \
920 PerlIO_printf(Perl_debug_log,"REG_CUTGROUP_SEEN "); \
922 if (RExC_seen & REG_RUN_ON_COMMENT_SEEN) \
923 PerlIO_printf(Perl_debug_log,"REG_RUN_ON_COMMENT_SEEN "); \
925 if (RExC_seen & REG_UNFOLDED_MULTI_SEEN) \
926 PerlIO_printf(Perl_debug_log,"REG_UNFOLDED_MULTI_SEEN "); \
928 if (RExC_seen & REG_GOSTART_SEEN) \
929 PerlIO_printf(Perl_debug_log,"REG_GOSTART_SEEN "); \
931 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) \
932 PerlIO_printf(Perl_debug_log,"REG_UNBOUNDED_QUANTIFIER_SEEN "); \
934 PerlIO_printf(Perl_debug_log,"\n"); \
937 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
938 if ((flags) & flag) PerlIO_printf(Perl_debug_log, "%s ", #flag)
940 #define DEBUG_SHOW_STUDY_FLAGS(flags,open_str,close_str) \
942 PerlIO_printf(Perl_debug_log, "%s", open_str); \
943 DEBUG_SHOW_STUDY_FLAG(flags,SF_FL_BEFORE_SEOL); \
944 DEBUG_SHOW_STUDY_FLAG(flags,SF_FL_BEFORE_MEOL); \
945 DEBUG_SHOW_STUDY_FLAG(flags,SF_IS_INF); \
946 DEBUG_SHOW_STUDY_FLAG(flags,SF_HAS_PAR); \
947 DEBUG_SHOW_STUDY_FLAG(flags,SF_IN_PAR); \
948 DEBUG_SHOW_STUDY_FLAG(flags,SF_HAS_EVAL); \
949 DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_SUBSTR); \
950 DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_STCLASS_AND); \
951 DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_STCLASS_OR); \
952 DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_STCLASS); \
953 DEBUG_SHOW_STUDY_FLAG(flags,SCF_WHILEM_VISITED_POS); \
954 DEBUG_SHOW_STUDY_FLAG(flags,SCF_TRIE_RESTUDY); \
955 DEBUG_SHOW_STUDY_FLAG(flags,SCF_SEEN_ACCEPT); \
956 DEBUG_SHOW_STUDY_FLAG(flags,SCF_TRIE_DOING_RESTUDY); \
957 DEBUG_SHOW_STUDY_FLAG(flags,SCF_IN_DEFINE); \
958 PerlIO_printf(Perl_debug_log, "%s", close_str); \
962 #define DEBUG_STUDYDATA(str,data,depth) \
963 DEBUG_OPTIMISE_MORE_r(if(data){ \
964 PerlIO_printf(Perl_debug_log, \
965 "%*s" str "Pos:%"IVdf"/%"IVdf \
967 (int)(depth)*2, "", \
968 (IV)((data)->pos_min), \
969 (IV)((data)->pos_delta), \
970 (UV)((data)->flags) \
972 DEBUG_SHOW_STUDY_FLAGS((data)->flags," [ ","]"); \
973 PerlIO_printf(Perl_debug_log, \
974 " Whilem_c: %"IVdf" Lcp: %"IVdf" %s", \
975 (IV)((data)->whilem_c), \
976 (IV)((data)->last_closep ? *((data)->last_closep) : -1), \
977 is_inf ? "INF " : "" \
979 if ((data)->last_found) \
980 PerlIO_printf(Perl_debug_log, \
981 "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
982 " %sFloat: '%s' @ %"IVdf"/%"IVdf"", \
983 SvPVX_const((data)->last_found), \
984 (IV)((data)->last_end), \
985 (IV)((data)->last_start_min), \
986 (IV)((data)->last_start_max), \
987 ((data)->longest && \
988 (data)->longest==&((data)->longest_fixed)) ? "*" : "", \
989 SvPVX_const((data)->longest_fixed), \
990 (IV)((data)->offset_fixed), \
991 ((data)->longest && \
992 (data)->longest==&((data)->longest_float)) ? "*" : "", \
993 SvPVX_const((data)->longest_float), \
994 (IV)((data)->offset_float_min), \
995 (IV)((data)->offset_float_max) \
997 PerlIO_printf(Perl_debug_log,"\n"); \
1000 /* =========================================================
1001 * BEGIN edit_distance stuff.
1003 * This calculates how many single character changes of any type are needed to
1004 * transform a string into another one. It is taken from version 3.1 of
1006 * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1009 /* Our unsorted dictionary linked list. */
1010 /* Note we use UVs, not chars. */
1015 struct dictionary* next;
1017 typedef struct dictionary item;
1020 PERL_STATIC_INLINE item*
1021 push(UV key,item* curr)
1024 Newxz(head, 1, item);
1032 PERL_STATIC_INLINE item*
1033 find(item* head, UV key)
1035 item* iterator = head;
1037 if (iterator->key == key){
1040 iterator = iterator->next;
1046 PERL_STATIC_INLINE item*
1047 uniquePush(item* head,UV key)
1049 item* iterator = head;
1052 if (iterator->key == key) {
1055 iterator = iterator->next;
1058 return push(key,head);
1061 PERL_STATIC_INLINE void
1062 dict_free(item* head)
1064 item* iterator = head;
1067 item* temp = iterator;
1068 iterator = iterator->next;
1075 /* End of Dictionary Stuff */
1077 /* All calculations/work are done here */
1079 S_edit_distance(const UV* src,
1081 const STRLEN x, /* length of src[] */
1082 const STRLEN y, /* length of tgt[] */
1083 const SSize_t maxDistance
1087 UV swapCount,swapScore,targetCharCount,i,j;
1089 UV score_ceil = x + y;
1091 PERL_ARGS_ASSERT_EDIT_DISTANCE;
1093 /* intialize matrix start values */
1094 Newxz(scores, ( (x + 2) * (y + 2)), UV);
1095 scores[0] = score_ceil;
1096 scores[1 * (y + 2) + 0] = score_ceil;
1097 scores[0 * (y + 2) + 1] = score_ceil;
1098 scores[1 * (y + 2) + 1] = 0;
1099 head = uniquePush(uniquePush(head,src[0]),tgt[0]);
1104 for (i=1;i<=x;i++) {
1106 head = uniquePush(head,src[i]);
1107 scores[(i+1) * (y + 2) + 1] = i;
1108 scores[(i+1) * (y + 2) + 0] = score_ceil;
1111 for (j=1;j<=y;j++) {
1114 head = uniquePush(head,tgt[j]);
1115 scores[1 * (y + 2) + (j + 1)] = j;
1116 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1119 targetCharCount = find(head,tgt[j-1])->value;
1120 swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1122 if (src[i-1] != tgt[j-1]){
1123 scores[(i+1) * (y + 2) + (j + 1)] = MIN(swapScore,(MIN(scores[i * (y + 2) + j], MIN(scores[(i+1) * (y + 2) + j], scores[i * (y + 2) + (j + 1)])) + 1));
1127 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1131 find(head,src[i-1])->value = i;
1135 IV score = scores[(x+1) * (y + 2) + (y + 1)];
1138 return (maxDistance != 0 && maxDistance < score)?(-1):score;
1142 /* END of edit_distance() stuff
1143 * ========================================================= */
1145 /* is c a control character for which we have a mnemonic? */
1146 #define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
1149 S_cntrl_to_mnemonic(const U8 c)
1151 /* Returns the mnemonic string that represents character 'c', if one
1152 * exists; NULL otherwise. The only ones that exist for the purposes of
1153 * this routine are a few control characters */
1156 case '\a': return "\\a";
1157 case '\b': return "\\b";
1158 case ESC_NATIVE: return "\\e";
1159 case '\f': return "\\f";
1160 case '\n': return "\\n";
1161 case '\r': return "\\r";
1162 case '\t': return "\\t";
1168 /* Mark that we cannot extend a found fixed substring at this point.
1169 Update the longest found anchored substring and the longest found
1170 floating substrings if needed. */
1173 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1174 SSize_t *minlenp, int is_inf)
1176 const STRLEN l = CHR_SVLEN(data->last_found);
1177 const STRLEN old_l = CHR_SVLEN(*data->longest);
1178 GET_RE_DEBUG_FLAGS_DECL;
1180 PERL_ARGS_ASSERT_SCAN_COMMIT;
1182 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1183 SvSetMagicSV(*data->longest, data->last_found);
1184 if (*data->longest == data->longest_fixed) {
1185 data->offset_fixed = l ? data->last_start_min : data->pos_min;
1186 if (data->flags & SF_BEFORE_EOL)
1188 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
1190 data->flags &= ~SF_FIX_BEFORE_EOL;
1191 data->minlen_fixed=minlenp;
1192 data->lookbehind_fixed=0;
1194 else { /* *data->longest == data->longest_float */
1195 data->offset_float_min = l ? data->last_start_min : data->pos_min;
1196 data->offset_float_max = (l
1197 ? data->last_start_max
1198 : (data->pos_delta > SSize_t_MAX - data->pos_min
1200 : data->pos_min + data->pos_delta));
1202 || (STRLEN)data->offset_float_max > (STRLEN)SSize_t_MAX)
1203 data->offset_float_max = SSize_t_MAX;
1204 if (data->flags & SF_BEFORE_EOL)
1206 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
1208 data->flags &= ~SF_FL_BEFORE_EOL;
1209 data->minlen_float=minlenp;
1210 data->lookbehind_float=0;
1213 SvCUR_set(data->last_found, 0);
1215 SV * const sv = data->last_found;
1216 if (SvUTF8(sv) && SvMAGICAL(sv)) {
1217 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1222 data->last_end = -1;
1223 data->flags &= ~SF_BEFORE_EOL;
1224 DEBUG_STUDYDATA("commit: ",data,0);
1227 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1228 * list that describes which code points it matches */
1231 S_ssc_anything(pTHX_ regnode_ssc *ssc)
1233 /* Set the SSC 'ssc' to match an empty string or any code point */
1235 PERL_ARGS_ASSERT_SSC_ANYTHING;
1237 assert(is_ANYOF_SYNTHETIC(ssc));
1239 ssc->invlist = sv_2mortal(_new_invlist(2)); /* mortalize so won't leak */
1240 _append_range_to_invlist(ssc->invlist, 0, UV_MAX);
1241 ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING; /* Plus matches empty */
1245 S_ssc_is_anything(const regnode_ssc *ssc)
1247 /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1248 * point; FALSE otherwise. Thus, this is used to see if using 'ssc' buys
1249 * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1250 * in any way, so there's no point in using it */
1255 PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1257 assert(is_ANYOF_SYNTHETIC(ssc));
1259 if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1263 /* See if the list consists solely of the range 0 - Infinity */
1264 invlist_iterinit(ssc->invlist);
1265 ret = invlist_iternext(ssc->invlist, &start, &end)
1269 invlist_iterfinish(ssc->invlist);
1275 /* If e.g., both \w and \W are set, matches everything */
1276 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1278 for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1279 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1289 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1291 /* Initializes the SSC 'ssc'. This includes setting it to match an empty
1292 * string, any code point, or any posix class under locale */
1294 PERL_ARGS_ASSERT_SSC_INIT;
1296 Zero(ssc, 1, regnode_ssc);
1297 set_ANYOF_SYNTHETIC(ssc);
1298 ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1301 /* If any portion of the regex is to operate under locale rules that aren't
1302 * fully known at compile time, initialization includes it. The reason
1303 * this isn't done for all regexes is that the optimizer was written under
1304 * the assumption that locale was all-or-nothing. Given the complexity and
1305 * lack of documentation in the optimizer, and that there are inadequate
1306 * test cases for locale, many parts of it may not work properly, it is
1307 * safest to avoid locale unless necessary. */
1308 if (RExC_contains_locale) {
1309 ANYOF_POSIXL_SETALL(ssc);
1312 ANYOF_POSIXL_ZERO(ssc);
1317 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1318 const regnode_ssc *ssc)
1320 /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1321 * to the list of code points matched, and locale posix classes; hence does
1322 * not check its flags) */
1327 PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1329 assert(is_ANYOF_SYNTHETIC(ssc));
1331 invlist_iterinit(ssc->invlist);
1332 ret = invlist_iternext(ssc->invlist, &start, &end)
1336 invlist_iterfinish(ssc->invlist);
1342 if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1350 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1351 const regnode_charclass* const node)
1353 /* Returns a mortal inversion list defining which code points are matched
1354 * by 'node', which is of type ANYOF. Handles complementing the result if
1355 * appropriate. If some code points aren't knowable at this time, the
1356 * returned list must, and will, contain every code point that is a
1359 SV* invlist = sv_2mortal(_new_invlist(0));
1360 SV* only_utf8_locale_invlist = NULL;
1362 const U32 n = ARG(node);
1363 bool new_node_has_latin1 = FALSE;
1365 PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1367 /* Look at the data structure created by S_set_ANYOF_arg() */
1368 if (n != ANYOF_ONLY_HAS_BITMAP) {
1369 SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1370 AV * const av = MUTABLE_AV(SvRV(rv));
1371 SV **const ary = AvARRAY(av);
1372 assert(RExC_rxi->data->what[n] == 's');
1374 if (ary[1] && ary[1] != &PL_sv_undef) { /* Has compile-time swash */
1375 invlist = sv_2mortal(invlist_clone(_get_swash_invlist(ary[1])));
1377 else if (ary[0] && ary[0] != &PL_sv_undef) {
1379 /* Here, no compile-time swash, and there are things that won't be
1380 * known until runtime -- we have to assume it could be anything */
1381 return _add_range_to_invlist(invlist, 0, UV_MAX);
1383 else if (ary[3] && ary[3] != &PL_sv_undef) {
1385 /* Here no compile-time swash, and no run-time only data. Use the
1386 * node's inversion list */
1387 invlist = sv_2mortal(invlist_clone(ary[3]));
1390 /* Get the code points valid only under UTF-8 locales */
1391 if ((ANYOF_FLAGS(node) & ANYOFL_FOLD)
1392 && ary[2] && ary[2] != &PL_sv_undef)
1394 only_utf8_locale_invlist = ary[2];
1398 /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1399 * code points, and an inversion list for the others, but if there are code
1400 * points that should match only conditionally on the target string being
1401 * UTF-8, those are placed in the inversion list, and not the bitmap.
1402 * Since there are circumstances under which they could match, they are
1403 * included in the SSC. But if the ANYOF node is to be inverted, we have
1404 * to exclude them here, so that when we invert below, the end result
1405 * actually does include them. (Think about "\xe0" =~ /[^\xc0]/di;). We
1406 * have to do this here before we add the unconditionally matched code
1408 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1409 _invlist_intersection_complement_2nd(invlist,
1414 /* Add in the points from the bit map */
1415 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1416 if (ANYOF_BITMAP_TEST(node, i)) {
1417 invlist = add_cp_to_invlist(invlist, i);
1418 new_node_has_latin1 = TRUE;
1422 /* If this can match all upper Latin1 code points, have to add them
1424 if (OP(node) == ANYOFD
1425 && (ANYOF_FLAGS(node) & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1427 _invlist_union(invlist, PL_UpperLatin1, &invlist);
1430 /* Similarly for these */
1431 if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1432 _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1435 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1436 _invlist_invert(invlist);
1438 else if (new_node_has_latin1 && ANYOF_FLAGS(node) & ANYOFL_FOLD) {
1440 /* Under /li, any 0-255 could fold to any other 0-255, depending on the
1441 * locale. We can skip this if there are no 0-255 at all. */
1442 _invlist_union(invlist, PL_Latin1, &invlist);
1445 /* Similarly add the UTF-8 locale possible matches. These have to be
1446 * deferred until after the non-UTF-8 locale ones are taken care of just
1447 * above, or it leads to wrong results under ANYOF_INVERT */
1448 if (only_utf8_locale_invlist) {
1449 _invlist_union_maybe_complement_2nd(invlist,
1450 only_utf8_locale_invlist,
1451 ANYOF_FLAGS(node) & ANYOF_INVERT,
1458 /* These two functions currently do the exact same thing */
1459 #define ssc_init_zero ssc_init
1461 #define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp))
1462 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1464 /* 'AND' a given class with another one. Can create false positives. 'ssc'
1465 * should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1466 * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1469 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1470 const regnode_charclass *and_with)
1472 /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1473 * another SSC or a regular ANYOF class. Can create false positives. */
1478 PERL_ARGS_ASSERT_SSC_AND;
1480 assert(is_ANYOF_SYNTHETIC(ssc));
1482 /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1483 * the code point inversion list and just the relevant flags */
1484 if (is_ANYOF_SYNTHETIC(and_with)) {
1485 anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1486 anded_flags = ANYOF_FLAGS(and_with);
1488 /* XXX This is a kludge around what appears to be deficiencies in the
1489 * optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag,
1490 * there are paths through the optimizer where it doesn't get weeded
1491 * out when it should. And if we don't make some extra provision for
1492 * it like the code just below, it doesn't get added when it should.
1493 * This solution is to add it only when AND'ing, which is here, and
1494 * only when what is being AND'ed is the pristine, original node
1495 * matching anything. Thus it is like adding it to ssc_anything() but
1496 * only when the result is to be AND'ed. Probably the same solution
1497 * could be adopted for the same problem we have with /l matching,
1498 * which is solved differently in S_ssc_init(), and that would lead to
1499 * fewer false positives than that solution has. But if this solution
1500 * creates bugs, the consequences are only that a warning isn't raised
1501 * that should be; while the consequences for having /l bugs is
1502 * incorrect matches */
1503 if (ssc_is_anything((regnode_ssc *)and_with)) {
1504 anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1508 anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1509 if (OP(and_with) == ANYOFD) {
1510 anded_flags = ANYOF_FLAGS(and_with) & ANYOF_COMMON_FLAGS;
1513 anded_flags = ANYOF_FLAGS(and_with)
1514 &( ANYOF_COMMON_FLAGS
1515 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1516 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1517 if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(and_with))) {
1519 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1524 ANYOF_FLAGS(ssc) &= anded_flags;
1526 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1527 * C2 is the list of code points in 'and-with'; P2, its posix classes.
1528 * 'and_with' may be inverted. When not inverted, we have the situation of
1530 * (C1 | P1) & (C2 | P2)
1531 * = (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1532 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1533 * <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2))
1534 * <= ((C1 & C2) | P1 | P2)
1535 * Alternatively, the last few steps could be:
1536 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1537 * <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2))
1538 * <= (C1 | C2 | (P1 & P2))
1539 * We favor the second approach if either P1 or P2 is non-empty. This is
1540 * because these components are a barrier to doing optimizations, as what
1541 * they match cannot be known until the moment of matching as they are
1542 * dependent on the current locale, 'AND"ing them likely will reduce or
1544 * But we can do better if we know that C1,P1 are in their initial state (a
1545 * frequent occurrence), each matching everything:
1546 * (<everything>) & (C2 | P2) = C2 | P2
1547 * Similarly, if C2,P2 are in their initial state (again a frequent
1548 * occurrence), the result is a no-op
1549 * (C1 | P1) & (<everything>) = C1 | P1
1552 * (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2)
1553 * = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1554 * <= (C1 & ~C2) | (P1 & ~P2)
1557 if ((ANYOF_FLAGS(and_with) & ANYOF_INVERT)
1558 && ! is_ANYOF_SYNTHETIC(and_with))
1562 ssc_intersection(ssc,
1564 FALSE /* Has already been inverted */
1567 /* If either P1 or P2 is empty, the intersection will be also; can skip
1569 if (! (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL)) {
1570 ANYOF_POSIXL_ZERO(ssc);
1572 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1574 /* Note that the Posix class component P from 'and_with' actually
1576 * P = Pa | Pb | ... | Pn
1577 * where each component is one posix class, such as in [\w\s].
1579 * ~P = ~(Pa | Pb | ... | Pn)
1580 * = ~Pa & ~Pb & ... & ~Pn
1581 * <= ~Pa | ~Pb | ... | ~Pn
1582 * The last is something we can easily calculate, but unfortunately
1583 * is likely to have many false positives. We could do better
1584 * in some (but certainly not all) instances if two classes in
1585 * P have known relationships. For example
1586 * :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1588 * :lower: & :print: = :lower:
1589 * And similarly for classes that must be disjoint. For example,
1590 * since \s and \w can have no elements in common based on rules in
1591 * the POSIX standard,
1592 * \w & ^\S = nothing
1593 * Unfortunately, some vendor locales do not meet the Posix
1594 * standard, in particular almost everything by Microsoft.
1595 * The loop below just changes e.g., \w into \W and vice versa */
1597 regnode_charclass_posixl temp;
1598 int add = 1; /* To calculate the index of the complement */
1600 ANYOF_POSIXL_ZERO(&temp);
1601 for (i = 0; i < ANYOF_MAX; i++) {
1603 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1604 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1606 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1607 ANYOF_POSIXL_SET(&temp, i + add);
1609 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1611 ANYOF_POSIXL_AND(&temp, ssc);
1613 } /* else ssc already has no posixes */
1614 } /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC
1615 in its initial state */
1616 else if (! is_ANYOF_SYNTHETIC(and_with)
1617 || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1619 /* But if 'ssc' is in its initial state, the result is just 'and_with';
1620 * copy it over 'ssc' */
1621 if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1622 if (is_ANYOF_SYNTHETIC(and_with)) {
1623 StructCopy(and_with, ssc, regnode_ssc);
1626 ssc->invlist = anded_cp_list;
1627 ANYOF_POSIXL_ZERO(ssc);
1628 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1629 ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1633 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1634 || (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL))
1636 /* One or the other of P1, P2 is non-empty. */
1637 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1638 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1640 ssc_union(ssc, anded_cp_list, FALSE);
1642 else { /* P1 = P2 = empty */
1643 ssc_intersection(ssc, anded_cp_list, FALSE);
1649 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1650 const regnode_charclass *or_with)
1652 /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1653 * another SSC or a regular ANYOF class. Can create false positives if
1654 * 'or_with' is to be inverted. */
1659 PERL_ARGS_ASSERT_SSC_OR;
1661 assert(is_ANYOF_SYNTHETIC(ssc));
1663 /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1664 * the code point inversion list and just the relevant flags */
1665 if (is_ANYOF_SYNTHETIC(or_with)) {
1666 ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1667 ored_flags = ANYOF_FLAGS(or_with);
1670 ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
1671 ored_flags = ANYOF_FLAGS(or_with) & ANYOF_COMMON_FLAGS;
1672 if (OP(or_with) != ANYOFD) {
1674 |= ANYOF_FLAGS(or_with)
1675 & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1676 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1677 if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(or_with))) {
1679 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1684 ANYOF_FLAGS(ssc) |= ored_flags;
1686 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1687 * C2 is the list of code points in 'or-with'; P2, its posix classes.
1688 * 'or_with' may be inverted. When not inverted, we have the simple
1689 * situation of computing:
1690 * (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2)
1691 * If P1|P2 yields a situation with both a class and its complement are
1692 * set, like having both \w and \W, this matches all code points, and we
1693 * can delete these from the P component of the ssc going forward. XXX We
1694 * might be able to delete all the P components, but I (khw) am not certain
1695 * about this, and it is better to be safe.
1698 * (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2)
1699 * <= (C1 | P1) | ~C2
1700 * <= (C1 | ~C2) | P1
1701 * (which results in actually simpler code than the non-inverted case)
1704 if ((ANYOF_FLAGS(or_with) & ANYOF_INVERT)
1705 && ! is_ANYOF_SYNTHETIC(or_with))
1707 /* We ignore P2, leaving P1 going forward */
1708 } /* else Not inverted */
1709 else if (ANYOF_FLAGS(or_with) & ANYOF_MATCHES_POSIXL) {
1710 ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
1711 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1713 for (i = 0; i < ANYOF_MAX; i += 2) {
1714 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1716 ssc_match_all_cp(ssc);
1717 ANYOF_POSIXL_CLEAR(ssc, i);
1718 ANYOF_POSIXL_CLEAR(ssc, i+1);
1726 FALSE /* Already has been inverted */
1730 PERL_STATIC_INLINE void
1731 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
1733 PERL_ARGS_ASSERT_SSC_UNION;
1735 assert(is_ANYOF_SYNTHETIC(ssc));
1737 _invlist_union_maybe_complement_2nd(ssc->invlist,
1743 PERL_STATIC_INLINE void
1744 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
1746 const bool invert2nd)
1748 PERL_ARGS_ASSERT_SSC_INTERSECTION;
1750 assert(is_ANYOF_SYNTHETIC(ssc));
1752 _invlist_intersection_maybe_complement_2nd(ssc->invlist,
1758 PERL_STATIC_INLINE void
1759 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
1761 PERL_ARGS_ASSERT_SSC_ADD_RANGE;
1763 assert(is_ANYOF_SYNTHETIC(ssc));
1765 ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
1768 PERL_STATIC_INLINE void
1769 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
1771 /* AND just the single code point 'cp' into the SSC 'ssc' */
1773 SV* cp_list = _new_invlist(2);
1775 PERL_ARGS_ASSERT_SSC_CP_AND;
1777 assert(is_ANYOF_SYNTHETIC(ssc));
1779 cp_list = add_cp_to_invlist(cp_list, cp);
1780 ssc_intersection(ssc, cp_list,
1781 FALSE /* Not inverted */
1783 SvREFCNT_dec_NN(cp_list);
1786 PERL_STATIC_INLINE void
1787 S_ssc_clear_locale(regnode_ssc *ssc)
1789 /* Set the SSC 'ssc' to not match any locale things */
1790 PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
1792 assert(is_ANYOF_SYNTHETIC(ssc));
1794 ANYOF_POSIXL_ZERO(ssc);
1795 ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
1798 #define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
1801 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
1803 /* The synthetic start class is used to hopefully quickly winnow down
1804 * places where a pattern could start a match in the target string. If it
1805 * doesn't really narrow things down that much, there isn't much point to
1806 * having the overhead of using it. This function uses some very crude
1807 * heuristics to decide if to use the ssc or not.
1809 * It returns TRUE if 'ssc' rules out more than half what it considers to
1810 * be the "likely" possible matches, but of course it doesn't know what the
1811 * actual things being matched are going to be; these are only guesses
1813 * For /l matches, it assumes that the only likely matches are going to be
1814 * in the 0-255 range, uniformly distributed, so half of that is 127
1815 * For /a and /d matches, it assumes that the likely matches will be just
1816 * the ASCII range, so half of that is 63
1817 * For /u and there isn't anything matching above the Latin1 range, it
1818 * assumes that that is the only range likely to be matched, and uses
1819 * half that as the cut-off: 127. If anything matches above Latin1,
1820 * it assumes that all of Unicode could match (uniformly), except for
1821 * non-Unicode code points and things in the General Category "Other"
1822 * (unassigned, private use, surrogates, controls and formats). This
1823 * is a much large number. */
1825 const U32 max_match = (LOC)
1829 : (invlist_highest(ssc->invlist) < 256)
1831 : ((NON_OTHER_COUNT + 1) / 2) - 1;
1832 U32 count = 0; /* Running total of number of code points matched by
1834 UV start, end; /* Start and end points of current range in inversion
1837 PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
1839 invlist_iterinit(ssc->invlist);
1840 while (invlist_iternext(ssc->invlist, &start, &end)) {
1842 /* /u is the only thing that we expect to match above 255; so if not /u
1843 * and even if there are matches above 255, ignore them. This catches
1844 * things like \d under /d which does match the digits above 255, but
1845 * since the pattern is /d, it is not likely to be expecting them */
1846 if (! UNI_SEMANTICS) {
1850 end = MIN(end, 255);
1852 count += end - start + 1;
1853 if (count > max_match) {
1854 invlist_iterfinish(ssc->invlist);
1864 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
1866 /* The inversion list in the SSC is marked mortal; now we need a more
1867 * permanent copy, which is stored the same way that is done in a regular
1868 * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
1871 SV* invlist = invlist_clone(ssc->invlist);
1873 PERL_ARGS_ASSERT_SSC_FINALIZE;
1875 assert(is_ANYOF_SYNTHETIC(ssc));
1877 /* The code in this file assumes that all but these flags aren't relevant
1878 * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
1879 * by the time we reach here */
1880 assert(! (ANYOF_FLAGS(ssc)
1881 & ~( ANYOF_COMMON_FLAGS
1882 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1883 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
1885 populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
1887 set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist,
1888 NULL, NULL, NULL, FALSE);
1890 /* Make sure is clone-safe */
1891 ssc->invlist = NULL;
1893 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1894 ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
1897 if (RExC_contains_locale) {
1901 assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
1904 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
1905 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
1906 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
1907 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \
1908 ? (TRIE_LIST_CUR( idx ) - 1) \
1914 dump_trie(trie,widecharmap,revcharmap)
1915 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
1916 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
1918 These routines dump out a trie in a somewhat readable format.
1919 The _interim_ variants are used for debugging the interim
1920 tables that are used to generate the final compressed
1921 representation which is what dump_trie expects.
1923 Part of the reason for their existence is to provide a form
1924 of documentation as to how the different representations function.
1929 Dumps the final compressed table form of the trie to Perl_debug_log.
1930 Used for debugging make_trie().
1934 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
1935 AV *revcharmap, U32 depth)
1938 SV *sv=sv_newmortal();
1939 int colwidth= widecharmap ? 6 : 4;
1941 GET_RE_DEBUG_FLAGS_DECL;
1943 PERL_ARGS_ASSERT_DUMP_TRIE;
1945 PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
1946 (int)depth * 2 + 2,"",
1947 "Match","Base","Ofs" );
1949 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
1950 SV ** const tmp = av_fetch( revcharmap, state, 0);
1952 PerlIO_printf( Perl_debug_log, "%*s",
1954 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
1955 PL_colors[0], PL_colors[1],
1956 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1957 PERL_PV_ESCAPE_FIRSTCHAR
1962 PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
1963 (int)depth * 2 + 2,"");
1965 for( state = 0 ; state < trie->uniquecharcount ; state++ )
1966 PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
1967 PerlIO_printf( Perl_debug_log, "\n");
1969 for( state = 1 ; state < trie->statecount ; state++ ) {
1970 const U32 base = trie->states[ state ].trans.base;
1972 PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|",
1973 (int)depth * 2 + 2,"", (UV)state);
1975 if ( trie->states[ state ].wordnum ) {
1976 PerlIO_printf( Perl_debug_log, " W%4X",
1977 trie->states[ state ].wordnum );
1979 PerlIO_printf( Perl_debug_log, "%6s", "" );
1982 PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
1987 while( ( base + ofs < trie->uniquecharcount ) ||
1988 ( base + ofs - trie->uniquecharcount < trie->lasttrans
1989 && trie->trans[ base + ofs - trie->uniquecharcount ].check
1993 PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
1995 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1996 if ( ( base + ofs >= trie->uniquecharcount )
1997 && ( base + ofs - trie->uniquecharcount
1999 && trie->trans[ base + ofs
2000 - trie->uniquecharcount ].check == state )
2002 PerlIO_printf( Perl_debug_log, "%*"UVXf,
2004 (UV)trie->trans[ base + ofs
2005 - trie->uniquecharcount ].next );
2007 PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
2011 PerlIO_printf( Perl_debug_log, "]");
2014 PerlIO_printf( Perl_debug_log, "\n" );
2016 PerlIO_printf(Perl_debug_log, "%*sword_info N:(prev,len)=",
2018 for (word=1; word <= trie->wordcount; word++) {
2019 PerlIO_printf(Perl_debug_log, " %d:(%d,%d)",
2020 (int)word, (int)(trie->wordinfo[word].prev),
2021 (int)(trie->wordinfo[word].len));
2023 PerlIO_printf(Perl_debug_log, "\n" );
2026 Dumps a fully constructed but uncompressed trie in list form.
2027 List tries normally only are used for construction when the number of
2028 possible chars (trie->uniquecharcount) is very high.
2029 Used for debugging make_trie().
2032 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2033 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2037 SV *sv=sv_newmortal();
2038 int colwidth= widecharmap ? 6 : 4;
2039 GET_RE_DEBUG_FLAGS_DECL;
2041 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2043 /* print out the table precompression. */
2044 PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
2045 (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
2046 "------:-----+-----------------\n" );
2048 for( state=1 ; state < next_alloc ; state ++ ) {
2051 PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
2052 (int)depth * 2 + 2,"", (UV)state );
2053 if ( ! trie->states[ state ].wordnum ) {
2054 PerlIO_printf( Perl_debug_log, "%5s| ","");
2056 PerlIO_printf( Perl_debug_log, "W%4x| ",
2057 trie->states[ state ].wordnum
2060 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2061 SV ** const tmp = av_fetch( revcharmap,
2062 TRIE_LIST_ITEM(state,charid).forid, 0);
2064 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
2066 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2068 PL_colors[0], PL_colors[1],
2069 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2070 | PERL_PV_ESCAPE_FIRSTCHAR
2072 TRIE_LIST_ITEM(state,charid).forid,
2073 (UV)TRIE_LIST_ITEM(state,charid).newstate
2076 PerlIO_printf(Perl_debug_log, "\n%*s| ",
2077 (int)((depth * 2) + 14), "");
2080 PerlIO_printf( Perl_debug_log, "\n");
2085 Dumps a fully constructed but uncompressed trie in table form.
2086 This is the normal DFA style state transition table, with a few
2087 twists to facilitate compression later.
2088 Used for debugging make_trie().
2091 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2092 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2097 SV *sv=sv_newmortal();
2098 int colwidth= widecharmap ? 6 : 4;
2099 GET_RE_DEBUG_FLAGS_DECL;
2101 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2104 print out the table precompression so that we can do a visual check
2105 that they are identical.
2108 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
2110 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2111 SV ** const tmp = av_fetch( revcharmap, charid, 0);
2113 PerlIO_printf( Perl_debug_log, "%*s",
2115 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2116 PL_colors[0], PL_colors[1],
2117 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2118 PERL_PV_ESCAPE_FIRSTCHAR
2124 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
2126 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2127 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
2130 PerlIO_printf( Perl_debug_log, "\n" );
2132 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2134 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
2135 (int)depth * 2 + 2,"",
2136 (UV)TRIE_NODENUM( state ) );
2138 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2139 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2141 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
2143 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
2145 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2146 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n",
2147 (UV)trie->trans[ state ].check );
2149 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n",
2150 (UV)trie->trans[ state ].check,
2151 trie->states[ TRIE_NODENUM( state ) ].wordnum );
2159 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2160 startbranch: the first branch in the whole branch sequence
2161 first : start branch of sequence of branch-exact nodes.
2162 May be the same as startbranch
2163 last : Thing following the last branch.
2164 May be the same as tail.
2165 tail : item following the branch sequence
2166 count : words in the sequence
2167 flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2168 depth : indent depth
2170 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2172 A trie is an N'ary tree where the branches are determined by digital
2173 decomposition of the key. IE, at the root node you look up the 1st character and
2174 follow that branch repeat until you find the end of the branches. Nodes can be
2175 marked as "accepting" meaning they represent a complete word. Eg:
2179 would convert into the following structure. Numbers represent states, letters
2180 following numbers represent valid transitions on the letter from that state, if
2181 the number is in square brackets it represents an accepting state, otherwise it
2182 will be in parenthesis.
2184 +-h->+-e->[3]-+-r->(8)-+-s->[9]
2188 (1) +-i->(6)-+-s->[7]
2190 +-s->(3)-+-h->(4)-+-e->[5]
2192 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2194 This shows that when matching against the string 'hers' we will begin at state 1
2195 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2196 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2197 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2198 single traverse. We store a mapping from accepting to state to which word was
2199 matched, and then when we have multiple possibilities we try to complete the
2200 rest of the regex in the order in which they occurred in the alternation.
2202 The only prior NFA like behaviour that would be changed by the TRIE support is
2203 the silent ignoring of duplicate alternations which are of the form:
2205 / (DUPE|DUPE) X? (?{ ... }) Y /x
2207 Thus EVAL blocks following a trie may be called a different number of times with
2208 and without the optimisation. With the optimisations dupes will be silently
2209 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2210 the following demonstrates:
2212 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2214 which prints out 'word' three times, but
2216 'words'=~/(word|word|word)(?{ print $1 })S/
2218 which doesnt print it out at all. This is due to other optimisations kicking in.
2220 Example of what happens on a structural level:
2222 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2224 1: CURLYM[1] {1,32767}(18)
2235 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2236 and should turn into:
2238 1: CURLYM[1] {1,32767}(18)
2240 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2248 Cases where tail != last would be like /(?foo|bar)baz/:
2258 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2259 and would end up looking like:
2262 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2269 d = uvchr_to_utf8_flags(d, uv, 0);
2271 is the recommended Unicode-aware way of saying
2276 #define TRIE_STORE_REVCHAR(val) \
2279 SV *zlopp = newSV(UTF8_MAXBYTES); \
2280 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
2281 unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
2282 SvCUR_set(zlopp, kapow - flrbbbbb); \
2285 av_push(revcharmap, zlopp); \
2287 char ooooff = (char)val; \
2288 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
2292 /* This gets the next character from the input, folding it if not already
2294 #define TRIE_READ_CHAR STMT_START { \
2297 /* if it is UTF then it is either already folded, or does not need \
2299 uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \
2301 else if (folder == PL_fold_latin1) { \
2302 /* This folder implies Unicode rules, which in the range expressible \
2303 * by not UTF is the lower case, with the two exceptions, one of \
2304 * which should have been taken care of before calling this */ \
2305 assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \
2306 uvc = toLOWER_L1(*uc); \
2307 if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \
2310 /* raw data, will be folded later if needed */ \
2318 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
2319 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
2320 U32 ging = TRIE_LIST_LEN( state ) *= 2; \
2321 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2323 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
2324 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
2325 TRIE_LIST_CUR( state )++; \
2328 #define TRIE_LIST_NEW(state) STMT_START { \
2329 Newxz( trie->states[ state ].trans.list, \
2330 4, reg_trie_trans_le ); \
2331 TRIE_LIST_CUR( state ) = 1; \
2332 TRIE_LIST_LEN( state ) = 4; \
2335 #define TRIE_HANDLE_WORD(state) STMT_START { \
2336 U16 dupe= trie->states[ state ].wordnum; \
2337 regnode * const noper_next = regnext( noper ); \
2340 /* store the word for dumping */ \
2342 if (OP(noper) != NOTHING) \
2343 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
2345 tmp = newSVpvn_utf8( "", 0, UTF ); \
2346 av_push( trie_words, tmp ); \
2350 trie->wordinfo[curword].prev = 0; \
2351 trie->wordinfo[curword].len = wordlen; \
2352 trie->wordinfo[curword].accept = state; \
2354 if ( noper_next < tail ) { \
2356 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2358 trie->jump[curword] = (U16)(noper_next - convert); \
2360 jumper = noper_next; \
2362 nextbranch= regnext(cur); \
2366 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
2367 /* chain, so that when the bits of chain are later */\
2368 /* linked together, the dups appear in the chain */\
2369 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2370 trie->wordinfo[dupe].prev = curword; \
2372 /* we haven't inserted this word yet. */ \
2373 trie->states[ state ].wordnum = curword; \
2378 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
2379 ( ( base + charid >= ucharcount \
2380 && base + charid < ubound \
2381 && state == trie->trans[ base - ucharcount + charid ].check \
2382 && trie->trans[ base - ucharcount + charid ].next ) \
2383 ? trie->trans[ base - ucharcount + charid ].next \
2384 : ( state==1 ? special : 0 ) \
2388 #define MADE_JUMP_TRIE 2
2389 #define MADE_EXACT_TRIE 4
2392 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2393 regnode *first, regnode *last, regnode *tail,
2394 U32 word_count, U32 flags, U32 depth)
2396 /* first pass, loop through and scan words */
2397 reg_trie_data *trie;
2398 HV *widecharmap = NULL;
2399 AV *revcharmap = newAV();
2405 regnode *jumper = NULL;
2406 regnode *nextbranch = NULL;
2407 regnode *convert = NULL;
2408 U32 *prev_states; /* temp array mapping each state to previous one */
2409 /* we just use folder as a flag in utf8 */
2410 const U8 * folder = NULL;
2413 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuuu"));
2414 AV *trie_words = NULL;
2415 /* along with revcharmap, this only used during construction but both are
2416 * useful during debugging so we store them in the struct when debugging.
2419 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2420 STRLEN trie_charcount=0;
2422 SV *re_trie_maxbuff;
2423 GET_RE_DEBUG_FLAGS_DECL;
2425 PERL_ARGS_ASSERT_MAKE_TRIE;
2427 PERL_UNUSED_ARG(depth);
2431 case EXACT: case EXACTL: break;
2435 case EXACTFLU8: folder = PL_fold_latin1; break;
2436 case EXACTF: folder = PL_fold; break;
2437 default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2440 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2442 trie->startstate = 1;
2443 trie->wordcount = word_count;
2444 RExC_rxi->data->data[ data_slot ] = (void*)trie;
2445 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2446 if (flags == EXACT || flags == EXACTL)
2447 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2448 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2449 trie->wordcount+1, sizeof(reg_trie_wordinfo));
2452 trie_words = newAV();
2455 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2456 assert(re_trie_maxbuff);
2457 if (!SvIOK(re_trie_maxbuff)) {
2458 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2460 DEBUG_TRIE_COMPILE_r({
2461 PerlIO_printf( Perl_debug_log,
2462 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2463 (int)depth * 2 + 2, "",
2464 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
2465 REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2468 /* Find the node we are going to overwrite */
2469 if ( first == startbranch && OP( last ) != BRANCH ) {
2470 /* whole branch chain */
2473 /* branch sub-chain */
2474 convert = NEXTOPER( first );
2477 /* -- First loop and Setup --
2479 We first traverse the branches and scan each word to determine if it
2480 contains widechars, and how many unique chars there are, this is
2481 important as we have to build a table with at least as many columns as we
2484 We use an array of integers to represent the character codes 0..255
2485 (trie->charmap) and we use a an HV* to store Unicode characters. We use
2486 the native representation of the character value as the key and IV's for
2489 *TODO* If we keep track of how many times each character is used we can
2490 remap the columns so that the table compression later on is more
2491 efficient in terms of memory by ensuring the most common value is in the
2492 middle and the least common are on the outside. IMO this would be better
2493 than a most to least common mapping as theres a decent chance the most
2494 common letter will share a node with the least common, meaning the node
2495 will not be compressible. With a middle is most common approach the worst
2496 case is when we have the least common nodes twice.
2500 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2501 regnode *noper = NEXTOPER( cur );
2502 const U8 *uc = (U8*)STRING( noper );
2503 const U8 *e = uc + STR_LEN( noper );
2505 U32 wordlen = 0; /* required init */
2506 STRLEN minchars = 0;
2507 STRLEN maxchars = 0;
2508 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2511 if (OP(noper) == NOTHING) {
2512 regnode *noper_next= regnext(noper);
2513 if (noper_next != tail && OP(noper_next) == flags) {
2515 uc= (U8*)STRING(noper);
2516 e= uc + STR_LEN(noper);
2517 trie->minlen= STR_LEN(noper);
2524 if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2525 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2526 regardless of encoding */
2527 if (OP( noper ) == EXACTFU_SS) {
2528 /* false positives are ok, so just set this */
2529 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2532 for ( ; uc < e ; uc += len ) { /* Look at each char in the current
2534 TRIE_CHARCOUNT(trie)++;
2537 /* TRIE_READ_CHAR returns the current character, or its fold if /i
2538 * is in effect. Under /i, this character can match itself, or
2539 * anything that folds to it. If not under /i, it can match just
2540 * itself. Most folds are 1-1, for example k, K, and KELVIN SIGN
2541 * all fold to k, and all are single characters. But some folds
2542 * expand to more than one character, so for example LATIN SMALL
2543 * LIGATURE FFI folds to the three character sequence 'ffi'. If
2544 * the string beginning at 'uc' is 'ffi', it could be matched by
2545 * three characters, or just by the one ligature character. (It
2546 * could also be matched by two characters: LATIN SMALL LIGATURE FF
2547 * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2548 * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2549 * match.) The trie needs to know the minimum and maximum number
2550 * of characters that could match so that it can use size alone to
2551 * quickly reject many match attempts. The max is simple: it is
2552 * the number of folded characters in this branch (since a fold is
2553 * never shorter than what folds to it. */
2557 /* And the min is equal to the max if not under /i (indicated by
2558 * 'folder' being NULL), or there are no multi-character folds. If
2559 * there is a multi-character fold, the min is incremented just
2560 * once, for the character that folds to the sequence. Each
2561 * character in the sequence needs to be added to the list below of
2562 * characters in the trie, but we count only the first towards the
2563 * min number of characters needed. This is done through the
2564 * variable 'foldlen', which is returned by the macros that look
2565 * for these sequences as the number of bytes the sequence
2566 * occupies. Each time through the loop, we decrement 'foldlen' by
2567 * how many bytes the current char occupies. Only when it reaches
2568 * 0 do we increment 'minchars' or look for another multi-character
2570 if (folder == NULL) {
2573 else if (foldlen > 0) {
2574 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2579 /* See if *uc is the beginning of a multi-character fold. If
2580 * so, we decrement the length remaining to look at, to account
2581 * for the current character this iteration. (We can use 'uc'
2582 * instead of the fold returned by TRIE_READ_CHAR because for
2583 * non-UTF, the latin1_safe macro is smart enough to account
2584 * for all the unfolded characters, and because for UTF, the
2585 * string will already have been folded earlier in the
2586 * compilation process */
2588 if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2589 foldlen -= UTF8SKIP(uc);
2592 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2597 /* The current character (and any potential folds) should be added
2598 * to the possible matching characters for this position in this
2602 U8 folded= folder[ (U8) uvc ];
2603 if ( !trie->charmap[ folded ] ) {
2604 trie->charmap[ folded ]=( ++trie->uniquecharcount );
2605 TRIE_STORE_REVCHAR( folded );
2608 if ( !trie->charmap[ uvc ] ) {
2609 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2610 TRIE_STORE_REVCHAR( uvc );
2613 /* store the codepoint in the bitmap, and its folded
2615 TRIE_BITMAP_SET(trie, uvc);
2617 /* store the folded codepoint */
2618 if ( folder ) TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);
2621 /* store first byte of utf8 representation of
2622 variant codepoints */
2623 if (! UVCHR_IS_INVARIANT(uvc)) {
2624 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));
2627 set_bit = 0; /* We've done our bit :-) */
2631 /* XXX We could come up with the list of code points that fold
2632 * to this using PL_utf8_foldclosures, except not for
2633 * multi-char folds, as there may be multiple combinations
2634 * there that could work, which needs to wait until runtime to
2635 * resolve (The comment about LIGATURE FFI above is such an
2640 widecharmap = newHV();
2642 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2645 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
2647 if ( !SvTRUE( *svpp ) ) {
2648 sv_setiv( *svpp, ++trie->uniquecharcount );
2649 TRIE_STORE_REVCHAR(uvc);
2652 } /* end loop through characters in this branch of the trie */
2654 /* We take the min and max for this branch and combine to find the min
2655 * and max for all branches processed so far */
2656 if( cur == first ) {
2657 trie->minlen = minchars;
2658 trie->maxlen = maxchars;
2659 } else if (minchars < trie->minlen) {
2660 trie->minlen = minchars;
2661 } else if (maxchars > trie->maxlen) {
2662 trie->maxlen = maxchars;
2664 } /* end first pass */
2665 DEBUG_TRIE_COMPILE_r(
2666 PerlIO_printf( Perl_debug_log,
2667 "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2668 (int)depth * 2 + 2,"",
2669 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
2670 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2671 (int)trie->minlen, (int)trie->maxlen )
2675 We now know what we are dealing with in terms of unique chars and
2676 string sizes so we can calculate how much memory a naive
2677 representation using a flat table will take. If it's over a reasonable
2678 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
2679 conservative but potentially much slower representation using an array
2682 At the end we convert both representations into the same compressed
2683 form that will be used in regexec.c for matching with. The latter
2684 is a form that cannot be used to construct with but has memory
2685 properties similar to the list form and access properties similar
2686 to the table form making it both suitable for fast searches and
2687 small enough that its feasable to store for the duration of a program.
2689 See the comment in the code where the compressed table is produced
2690 inplace from the flat tabe representation for an explanation of how
2691 the compression works.
2696 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2699 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2700 > SvIV(re_trie_maxbuff) )
2703 Second Pass -- Array Of Lists Representation
2705 Each state will be represented by a list of charid:state records
2706 (reg_trie_trans_le) the first such element holds the CUR and LEN
2707 points of the allocated array. (See defines above).
2709 We build the initial structure using the lists, and then convert
2710 it into the compressed table form which allows faster lookups
2711 (but cant be modified once converted).
2714 STRLEN transcount = 1;
2716 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
2717 "%*sCompiling trie using list compiler\n",
2718 (int)depth * 2 + 2, ""));
2720 trie->states = (reg_trie_state *)
2721 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2722 sizeof(reg_trie_state) );
2726 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2728 regnode *noper = NEXTOPER( cur );
2729 U8 *uc = (U8*)STRING( noper );
2730 const U8 *e = uc + STR_LEN( noper );
2731 U32 state = 1; /* required init */
2732 U16 charid = 0; /* sanity init */
2733 U32 wordlen = 0; /* required init */
2735 if (OP(noper) == NOTHING) {
2736 regnode *noper_next= regnext(noper);
2737 if (noper_next != tail && OP(noper_next) == flags) {
2739 uc= (U8*)STRING(noper);
2740 e= uc + STR_LEN(noper);
2744 if (OP(noper) != NOTHING) {
2745 for ( ; uc < e ; uc += len ) {
2750 charid = trie->charmap[ uvc ];
2752 SV** const svpp = hv_fetch( widecharmap,
2759 charid=(U16)SvIV( *svpp );
2762 /* charid is now 0 if we dont know the char read, or
2763 * nonzero if we do */
2770 if ( !trie->states[ state ].trans.list ) {
2771 TRIE_LIST_NEW( state );
2774 check <= TRIE_LIST_USED( state );
2777 if ( TRIE_LIST_ITEM( state, check ).forid
2780 newstate = TRIE_LIST_ITEM( state, check ).newstate;
2785 newstate = next_alloc++;
2786 prev_states[newstate] = state;
2787 TRIE_LIST_PUSH( state, charid, newstate );
2792 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2796 TRIE_HANDLE_WORD(state);
2798 } /* end second pass */
2800 /* next alloc is the NEXT state to be allocated */
2801 trie->statecount = next_alloc;
2802 trie->states = (reg_trie_state *)
2803 PerlMemShared_realloc( trie->states,
2805 * sizeof(reg_trie_state) );
2807 /* and now dump it out before we compress it */
2808 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
2809 revcharmap, next_alloc,
2813 trie->trans = (reg_trie_trans *)
2814 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
2821 for( state=1 ; state < next_alloc ; state ++ ) {
2825 DEBUG_TRIE_COMPILE_MORE_r(
2826 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
2830 if (trie->states[state].trans.list) {
2831 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
2835 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
2836 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
2837 if ( forid < minid ) {
2839 } else if ( forid > maxid ) {
2843 if ( transcount < tp + maxid - minid + 1) {
2845 trie->trans = (reg_trie_trans *)
2846 PerlMemShared_realloc( trie->trans,
2848 * sizeof(reg_trie_trans) );
2849 Zero( trie->trans + (transcount / 2),
2853 base = trie->uniquecharcount + tp - minid;
2854 if ( maxid == minid ) {
2856 for ( ; zp < tp ; zp++ ) {
2857 if ( ! trie->trans[ zp ].next ) {
2858 base = trie->uniquecharcount + zp - minid;
2859 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
2861 trie->trans[ zp ].check = state;
2867 trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
2869 trie->trans[ tp ].check = state;
2874 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
2875 const U32 tid = base
2876 - trie->uniquecharcount
2877 + TRIE_LIST_ITEM( state, idx ).forid;
2878 trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
2880 trie->trans[ tid ].check = state;
2882 tp += ( maxid - minid + 1 );
2884 Safefree(trie->states[ state ].trans.list);
2887 DEBUG_TRIE_COMPILE_MORE_r(
2888 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
2891 trie->states[ state ].trans.base=base;
2893 trie->lasttrans = tp + 1;
2897 Second Pass -- Flat Table Representation.
2899 we dont use the 0 slot of either trans[] or states[] so we add 1 to
2900 each. We know that we will need Charcount+1 trans at most to store
2901 the data (one row per char at worst case) So we preallocate both
2902 structures assuming worst case.
2904 We then construct the trie using only the .next slots of the entry
2907 We use the .check field of the first entry of the node temporarily
2908 to make compression both faster and easier by keeping track of how
2909 many non zero fields are in the node.
2911 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
2914 There are two terms at use here: state as a TRIE_NODEIDX() which is
2915 a number representing the first entry of the node, and state as a
2916 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
2917 and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
2918 if there are 2 entrys per node. eg:
2926 The table is internally in the right hand, idx form. However as we
2927 also have to deal with the states array which is indexed by nodenum
2928 we have to use TRIE_NODENUM() to convert.
2931 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
2932 "%*sCompiling trie using table compiler\n",
2933 (int)depth * 2 + 2, ""));
2935 trie->trans = (reg_trie_trans *)
2936 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
2937 * trie->uniquecharcount + 1,
2938 sizeof(reg_trie_trans) );
2939 trie->states = (reg_trie_state *)
2940 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2941 sizeof(reg_trie_state) );
2942 next_alloc = trie->uniquecharcount + 1;
2945 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2947 regnode *noper = NEXTOPER( cur );
2948 const U8 *uc = (U8*)STRING( noper );
2949 const U8 *e = uc + STR_LEN( noper );
2951 U32 state = 1; /* required init */
2953 U16 charid = 0; /* sanity init */
2954 U32 accept_state = 0; /* sanity init */
2956 U32 wordlen = 0; /* required init */
2958 if (OP(noper) == NOTHING) {
2959 regnode *noper_next= regnext(noper);
2960 if (noper_next != tail && OP(noper_next) == flags) {
2962 uc= (U8*)STRING(noper);
2963 e= uc + STR_LEN(noper);
2967 if ( OP(noper) != NOTHING ) {
2968 for ( ; uc < e ; uc += len ) {
2973 charid = trie->charmap[ uvc ];
2975 SV* const * const svpp = hv_fetch( widecharmap,
2979 charid = svpp ? (U16)SvIV(*svpp) : 0;
2983 if ( !trie->trans[ state + charid ].next ) {
2984 trie->trans[ state + charid ].next = next_alloc;
2985 trie->trans[ state ].check++;
2986 prev_states[TRIE_NODENUM(next_alloc)]
2987 = TRIE_NODENUM(state);
2988 next_alloc += trie->uniquecharcount;
2990 state = trie->trans[ state + charid ].next;
2992 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2994 /* charid is now 0 if we dont know the char read, or
2995 * nonzero if we do */
2998 accept_state = TRIE_NODENUM( state );
2999 TRIE_HANDLE_WORD(accept_state);
3001 } /* end second pass */
3003 /* and now dump it out before we compress it */
3004 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3006 next_alloc, depth+1));
3010 * Inplace compress the table.*
3012 For sparse data sets the table constructed by the trie algorithm will
3013 be mostly 0/FAIL transitions or to put it another way mostly empty.
3014 (Note that leaf nodes will not contain any transitions.)
3016 This algorithm compresses the tables by eliminating most such
3017 transitions, at the cost of a modest bit of extra work during lookup:
3019 - Each states[] entry contains a .base field which indicates the
3020 index in the state[] array wheres its transition data is stored.
3022 - If .base is 0 there are no valid transitions from that node.
3024 - If .base is nonzero then charid is added to it to find an entry in
3027 -If trans[states[state].base+charid].check!=state then the
3028 transition is taken to be a 0/Fail transition. Thus if there are fail
3029 transitions at the front of the node then the .base offset will point
3030 somewhere inside the previous nodes data (or maybe even into a node
3031 even earlier), but the .check field determines if the transition is
3035 The following process inplace converts the table to the compressed
3036 table: We first do not compress the root node 1,and mark all its
3037 .check pointers as 1 and set its .base pointer as 1 as well. This
3038 allows us to do a DFA construction from the compressed table later,
3039 and ensures that any .base pointers we calculate later are greater
3042 - We set 'pos' to indicate the first entry of the second node.
3044 - We then iterate over the columns of the node, finding the first and
3045 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3046 and set the .check pointers accordingly, and advance pos
3047 appropriately and repreat for the next node. Note that when we copy
3048 the next pointers we have to convert them from the original
3049 NODEIDX form to NODENUM form as the former is not valid post
3052 - If a node has no transitions used we mark its base as 0 and do not
3053 advance the pos pointer.
3055 - If a node only has one transition we use a second pointer into the
3056 structure to fill in allocated fail transitions from other states.
3057 This pointer is independent of the main pointer and scans forward
3058 looking for null transitions that are allocated to a state. When it
3059 finds one it writes the single transition into the "hole". If the
3060 pointer doesnt find one the single transition is appended as normal.
3062 - Once compressed we can Renew/realloc the structures to release the
3065 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3066 specifically Fig 3.47 and the associated pseudocode.
3070 const U32 laststate = TRIE_NODENUM( next_alloc );
3073 trie->statecount = laststate;
3075 for ( state = 1 ; state < laststate ; state++ ) {
3077 const U32 stateidx = TRIE_NODEIDX( state );
3078 const U32 o_used = trie->trans[ stateidx ].check;
3079 U32 used = trie->trans[ stateidx ].check;
3080 trie->trans[ stateidx ].check = 0;
3083 used && charid < trie->uniquecharcount;
3086 if ( flag || trie->trans[ stateidx + charid ].next ) {
3087 if ( trie->trans[ stateidx + charid ].next ) {
3089 for ( ; zp < pos ; zp++ ) {
3090 if ( ! trie->trans[ zp ].next ) {
3094 trie->states[ state ].trans.base
3096 + trie->uniquecharcount
3098 trie->trans[ zp ].next
3099 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3101 trie->trans[ zp ].check = state;
3102 if ( ++zp > pos ) pos = zp;
3109 trie->states[ state ].trans.base
3110 = pos + trie->uniquecharcount - charid ;
3112 trie->trans[ pos ].next
3113 = SAFE_TRIE_NODENUM(
3114 trie->trans[ stateidx + charid ].next );
3115 trie->trans[ pos ].check = state;
3120 trie->lasttrans = pos + 1;
3121 trie->states = (reg_trie_state *)
3122 PerlMemShared_realloc( trie->states, laststate
3123 * sizeof(reg_trie_state) );
3124 DEBUG_TRIE_COMPILE_MORE_r(
3125 PerlIO_printf( Perl_debug_log,
3126 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
3127 (int)depth * 2 + 2,"",
3128 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3132 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3135 } /* end table compress */
3137 DEBUG_TRIE_COMPILE_MORE_r(
3138 PerlIO_printf(Perl_debug_log,
3139 "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
3140 (int)depth * 2 + 2, "",
3141 (UV)trie->statecount,
3142 (UV)trie->lasttrans)
3144 /* resize the trans array to remove unused space */
3145 trie->trans = (reg_trie_trans *)
3146 PerlMemShared_realloc( trie->trans, trie->lasttrans
3147 * sizeof(reg_trie_trans) );
3149 { /* Modify the program and insert the new TRIE node */
3150 U8 nodetype =(U8)(flags & 0xFF);
3154 regnode *optimize = NULL;
3155 #ifdef RE_TRACK_PATTERN_OFFSETS
3158 U32 mjd_nodelen = 0;
3159 #endif /* RE_TRACK_PATTERN_OFFSETS */
3160 #endif /* DEBUGGING */
3162 This means we convert either the first branch or the first Exact,
3163 depending on whether the thing following (in 'last') is a branch
3164 or not and whther first is the startbranch (ie is it a sub part of
3165 the alternation or is it the whole thing.)
3166 Assuming its a sub part we convert the EXACT otherwise we convert
3167 the whole branch sequence, including the first.
3169 /* Find the node we are going to overwrite */
3170 if ( first != startbranch || OP( last ) == BRANCH ) {
3171 /* branch sub-chain */
3172 NEXT_OFF( first ) = (U16)(last - first);
3173 #ifdef RE_TRACK_PATTERN_OFFSETS
3175 mjd_offset= Node_Offset((convert));
3176 mjd_nodelen= Node_Length((convert));
3179 /* whole branch chain */
3181 #ifdef RE_TRACK_PATTERN_OFFSETS
3184 const regnode *nop = NEXTOPER( convert );
3185 mjd_offset= Node_Offset((nop));
3186 mjd_nodelen= Node_Length((nop));
3190 PerlIO_printf(Perl_debug_log,
3191 "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
3192 (int)depth * 2 + 2, "",
3193 (UV)mjd_offset, (UV)mjd_nodelen)
3196 /* But first we check to see if there is a common prefix we can
3197 split out as an EXACT and put in front of the TRIE node. */
3198 trie->startstate= 1;
3199 if ( trie->bitmap && !widecharmap && !trie->jump ) {
3201 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3205 const U32 base = trie->states[ state ].trans.base;
3207 if ( trie->states[state].wordnum )
3210 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3211 if ( ( base + ofs >= trie->uniquecharcount ) &&
3212 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3213 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3215 if ( ++count > 1 ) {
3216 SV **tmp = av_fetch( revcharmap, ofs, 0);
3217 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
3218 if ( state == 1 ) break;
3220 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3222 PerlIO_printf(Perl_debug_log,
3223 "%*sNew Start State=%"UVuf" Class: [",
3224 (int)depth * 2 + 2, "",
3227 SV ** const tmp = av_fetch( revcharmap, idx, 0);
3228 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3230 TRIE_BITMAP_SET(trie,*ch);
3232 TRIE_BITMAP_SET(trie, folder[ *ch ]);
3234 PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
3238 TRIE_BITMAP_SET(trie,*ch);
3240 TRIE_BITMAP_SET(trie,folder[ *ch ]);
3241 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
3247 SV **tmp = av_fetch( revcharmap, idx, 0);
3249 char *ch = SvPV( *tmp, len );
3251 SV *sv=sv_newmortal();
3252 PerlIO_printf( Perl_debug_log,
3253 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
3254 (int)depth * 2 + 2, "",
3256 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3257 PL_colors[0], PL_colors[1],
3258 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3259 PERL_PV_ESCAPE_FIRSTCHAR
3264 OP( convert ) = nodetype;
3265 str=STRING(convert);
3268 STR_LEN(convert) += len;
3274 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
3279 trie->prefixlen = (state-1);
3281 regnode *n = convert+NODE_SZ_STR(convert);
3282 NEXT_OFF(convert) = NODE_SZ_STR(convert);
3283 trie->startstate = state;
3284 trie->minlen -= (state - 1);
3285 trie->maxlen -= (state - 1);
3287 /* At least the UNICOS C compiler choked on this
3288 * being argument to DEBUG_r(), so let's just have
3291 #ifdef PERL_EXT_RE_BUILD
3297 regnode *fix = convert;
3298 U32 word = trie->wordcount;
3300 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3301 while( ++fix < n ) {
3302 Set_Node_Offset_Length(fix, 0, 0);
3305 SV ** const tmp = av_fetch( trie_words, word, 0 );
3307 if ( STR_LEN(convert) <= SvCUR(*tmp) )
3308 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3310 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3318 NEXT_OFF(convert) = (U16)(tail - convert);
3319 DEBUG_r(optimize= n);
3325 if ( trie->maxlen ) {
3326 NEXT_OFF( convert ) = (U16)(tail - convert);
3327 ARG_SET( convert, data_slot );
3328 /* Store the offset to the first unabsorbed branch in
3329 jump[0], which is otherwise unused by the jump logic.
3330 We use this when dumping a trie and during optimisation. */
3332 trie->jump[0] = (U16)(nextbranch - convert);
3334 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3335 * and there is a bitmap
3336 * and the first "jump target" node we found leaves enough room
3337 * then convert the TRIE node into a TRIEC node, with the bitmap
3338 * embedded inline in the opcode - this is hypothetically faster.
3340 if ( !trie->states[trie->startstate].wordnum
3342 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3344 OP( convert ) = TRIEC;
3345 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3346 PerlMemShared_free(trie->bitmap);
3349 OP( convert ) = TRIE;
3351 /* store the type in the flags */
3352 convert->flags = nodetype;
3356 + regarglen[ OP( convert ) ];
3358 /* XXX We really should free up the resource in trie now,
3359 as we won't use them - (which resources?) dmq */
3361 /* needed for dumping*/
3362 DEBUG_r(if (optimize) {
3363 regnode *opt = convert;
3365 while ( ++opt < optimize) {
3366 Set_Node_Offset_Length(opt,0,0);
3369 Try to clean up some of the debris left after the
3372 while( optimize < jumper ) {
3373 mjd_nodelen += Node_Length((optimize));
3374 OP( optimize ) = OPTIMIZED;
3375 Set_Node_Offset_Length(optimize,0,0);
3378 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
3380 } /* end node insert */
3382 /* Finish populating the prev field of the wordinfo array. Walk back
3383 * from each accept state until we find another accept state, and if
3384 * so, point the first word's .prev field at the second word. If the
3385 * second already has a .prev field set, stop now. This will be the
3386 * case either if we've already processed that word's accept state,
3387 * or that state had multiple words, and the overspill words were
3388 * already linked up earlier.
3395 for (word=1; word <= trie->wordcount; word++) {
3397 if (trie->wordinfo[word].prev)
3399 state = trie->wordinfo[word].accept;
3401 state = prev_states[state];
3404 prev = trie->states[state].wordnum;
3408 trie->wordinfo[word].prev = prev;
3410 Safefree(prev_states);
3414 /* and now dump out the compressed format */
3415 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3417 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3419 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3420 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3422 SvREFCNT_dec_NN(revcharmap);
3426 : trie->startstate>1
3432 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3434 /* The Trie is constructed and compressed now so we can build a fail array if
3437 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3439 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3443 We find the fail state for each state in the trie, this state is the longest
3444 proper suffix of the current state's 'word' that is also a proper prefix of
3445 another word in our trie. State 1 represents the word '' and is thus the
3446 default fail state. This allows the DFA not to have to restart after its
3447 tried and failed a word at a given point, it simply continues as though it
3448 had been matching the other word in the first place.
3450 'abcdgu'=~/abcdefg|cdgu/
3451 When we get to 'd' we are still matching the first word, we would encounter
3452 'g' which would fail, which would bring us to the state representing 'd' in
3453 the second word where we would try 'g' and succeed, proceeding to match
3456 /* add a fail transition */
3457 const U32 trie_offset = ARG(source);
3458 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3460 const U32 ucharcount = trie->uniquecharcount;
3461 const U32 numstates = trie->statecount;
3462 const U32 ubound = trie->lasttrans + ucharcount;
3466 U32 base = trie->states[ 1 ].trans.base;
3469 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3471 GET_RE_DEBUG_FLAGS_DECL;
3473 PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3474 PERL_UNUSED_CONTEXT;
3476 PERL_UNUSED_ARG(depth);
3479 if ( OP(source) == TRIE ) {
3480 struct regnode_1 *op = (struct regnode_1 *)
3481 PerlMemShared_calloc(1, sizeof(struct regnode_1));
3482 StructCopy(source,op,struct regnode_1);
3483 stclass = (regnode *)op;
3485 struct regnode_charclass *op = (struct regnode_charclass *)
3486 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3487 StructCopy(source,op,struct regnode_charclass);
3488 stclass = (regnode *)op;
3490 OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3492 ARG_SET( stclass, data_slot );
3493 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3494 RExC_rxi->data->data[ data_slot ] = (void*)aho;
3495 aho->trie=trie_offset;
3496 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3497 Copy( trie->states, aho->states, numstates, reg_trie_state );
3498 Newxz( q, numstates, U32);
3499 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3502 /* initialize fail[0..1] to be 1 so that we always have
3503 a valid final fail state */
3504 fail[ 0 ] = fail[ 1 ] = 1;
3506 for ( charid = 0; charid < ucharcount ; charid++ ) {
3507 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3509 q[ q_write ] = newstate;
3510 /* set to point at the root */
3511 fail[ q[ q_write++ ] ]=1;
3514 while ( q_read < q_write) {
3515 const U32 cur = q[ q_read++ % numstates ];
3516 base = trie->states[ cur ].trans.base;
3518 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3519 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3521 U32 fail_state = cur;
3524 fail_state = fail[ fail_state ];
3525 fail_base = aho->states[ fail_state ].trans.base;
3526 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3528 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3529 fail[ ch_state ] = fail_state;
3530 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3532 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
3534 q[ q_write++ % numstates] = ch_state;
3538 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3539 when we fail in state 1, this allows us to use the
3540 charclass scan to find a valid start char. This is based on the principle
3541 that theres a good chance the string being searched contains lots of stuff
3542 that cant be a start char.
3544 fail[ 0 ] = fail[ 1 ] = 0;
3545 DEBUG_TRIE_COMPILE_r({
3546 PerlIO_printf(Perl_debug_log,
3547 "%*sStclass Failtable (%"UVuf" states): 0",
3548 (int)(depth * 2), "", (UV)numstates
3550 for( q_read=1; q_read<numstates; q_read++ ) {
3551 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
3553 PerlIO_printf(Perl_debug_log, "\n");
3556 /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3561 #define DEBUG_PEEP(str,scan,depth) \
3562 DEBUG_OPTIMISE_r({if (scan){ \
3563 regnode *Next = regnext(scan); \
3564 regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state); \
3565 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)", \
3566 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),\
3567 Next ? (REG_NODE_NUM(Next)) : 0 ); \
3568 DEBUG_SHOW_STUDY_FLAGS(flags," [ ","]");\
3569 PerlIO_printf(Perl_debug_log, "\n"); \
3572 /* The below joins as many adjacent EXACTish nodes as possible into a single
3573 * one. The regop may be changed if the node(s) contain certain sequences that
3574 * require special handling. The joining is only done if:
3575 * 1) there is room in the current conglomerated node to entirely contain the
3577 * 2) they are the exact same node type
3579 * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3580 * these get optimized out
3582 * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3583 * as possible, even if that means splitting an existing node so that its first
3584 * part is moved to the preceeding node. This would maximise the efficiency of
3585 * memEQ during matching. Elsewhere in this file, khw proposes splitting
3586 * EXACTFish nodes into portions that don't change under folding vs those that
3587 * do. Those portions that don't change may be the only things in the pattern that
3588 * could be used to find fixed and floating strings.
3590 * If a node is to match under /i (folded), the number of characters it matches
3591 * can be different than its character length if it contains a multi-character
3592 * fold. *min_subtract is set to the total delta number of characters of the
3595 * And *unfolded_multi_char is set to indicate whether or not the node contains
3596 * an unfolded multi-char fold. This happens when whether the fold is valid or
3597 * not won't be known until runtime; namely for EXACTF nodes that contain LATIN
3598 * SMALL LETTER SHARP S, as only if the target string being matched against
3599 * turns out to be UTF-8 is that fold valid; and also for EXACTFL nodes whose
3600 * folding rules depend on the locale in force at runtime. (Multi-char folds
3601 * whose components are all above the Latin1 range are not run-time locale
3602 * dependent, and have already been folded by the time this function is
3605 * This is as good a place as any to discuss the design of handling these
3606 * multi-character fold sequences. It's been wrong in Perl for a very long
3607 * time. There are three code points in Unicode whose multi-character folds
3608 * were long ago discovered to mess things up. The previous designs for
3609 * dealing with these involved assigning a special node for them. This
3610 * approach doesn't always work, as evidenced by this example:
3611 * "\xDFs" =~ /s\xDF/ui # Used to fail before these patches
3612 * Both sides fold to "sss", but if the pattern is parsed to create a node that
3613 * would match just the \xDF, it won't be able to handle the case where a
3614 * successful match would have to cross the node's boundary. The new approach
3615 * that hopefully generally solves the problem generates an EXACTFU_SS node
3616 * that is "sss" in this case.
3618 * It turns out that there are problems with all multi-character folds, and not
3619 * just these three. Now the code is general, for all such cases. The
3620 * approach taken is:
3621 * 1) This routine examines each EXACTFish node that could contain multi-
3622 * character folded sequences. Since a single character can fold into
3623 * such a sequence, the minimum match length for this node is less than
3624 * the number of characters in the node. This routine returns in
3625 * *min_subtract how many characters to subtract from the the actual
3626 * length of the string to get a real minimum match length; it is 0 if
3627 * there are no multi-char foldeds. This delta is used by the caller to
3628 * adjust the min length of the match, and the delta between min and max,
3629 * so that the optimizer doesn't reject these possibilities based on size
3631 * 2) For the sequence involving the Sharp s (\xDF), the node type EXACTFU_SS
3632 * is used for an EXACTFU node that contains at least one "ss" sequence in
3633 * it. For non-UTF-8 patterns and strings, this is the only case where
3634 * there is a possible fold length change. That means that a regular
3635 * EXACTFU node without UTF-8 involvement doesn't have to concern itself
3636 * with length changes, and so can be processed faster. regexec.c takes
3637 * advantage of this. Generally, an EXACTFish node that is in UTF-8 is
3638 * pre-folded by regcomp.c (except EXACTFL, some of whose folds aren't
3639 * known until runtime). This saves effort in regex matching. However,
3640 * the pre-folding isn't done for non-UTF8 patterns because the fold of
3641 * the MICRO SIGN requires UTF-8, and we don't want to slow things down by
3642 * forcing the pattern into UTF8 unless necessary. Also what EXACTF (and,
3643 * again, EXACTFL) nodes fold to isn't known until runtime. The fold
3644 * possibilities for the non-UTF8 patterns are quite simple, except for
3645 * the sharp s. All the ones that don't involve a UTF-8 target string are
3646 * members of a fold-pair, and arrays are set up for all of them so that
3647 * the other member of the pair can be found quickly. Code elsewhere in
3648 * this file makes sure that in EXACTFU nodes, the sharp s gets folded to
3649 * 'ss', even if the pattern isn't UTF-8. This avoids the issues
3650 * described in the next item.
3651 * 3) A problem remains for unfolded multi-char folds. (These occur when the
3652 * validity of the fold won't be known until runtime, and so must remain
3653 * unfolded for now. This happens for the sharp s in EXACTF and EXACTFA
3654 * nodes when the pattern isn't in UTF-8. (Note, BTW, that there cannot
3655 * be an EXACTF node with a UTF-8 pattern.) They also occur for various
3656 * folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
3657 * The reason this is a problem is that the optimizer part of regexec.c
3658 * (probably unwittingly, in Perl_regexec_flags()) makes an assumption
3659 * that a character in the pattern corresponds to at most a single
3660 * character in the target string. (And I do mean character, and not byte
3661 * here, unlike other parts of the documentation that have never been
3662 * updated to account for multibyte Unicode.) sharp s in EXACTF and
3663 * EXACTFL nodes can match the two character string 'ss'; in EXACTFA nodes
3664 * it can match "\x{17F}\x{17F}". These, along with other ones in EXACTFL
3665 * nodes, violate the assumption, and they are the only instances where it
3666 * is violated. I'm reluctant to try to change the assumption, as the
3667 * code involved is impenetrable to me (khw), so instead the code here
3668 * punts. This routine examines EXACTFL nodes, and (when the pattern
3669 * isn't UTF-8) EXACTF and EXACTFA for such unfolded folds, and returns a
3670 * boolean indicating whether or not the node contains such a fold. When
3671 * it is true, the caller sets a flag that later causes the optimizer in
3672 * this file to not set values for the floating and fixed string lengths,
3673 * and thus avoids the optimizer code in regexec.c that makes the invalid
3674 * assumption. Thus, there is no optimization based on string lengths for
3675 * EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
3676 * EXACTF and EXACTFA nodes that contain the sharp s. (The reason the
3677 * assumption is wrong only in these cases is that all other non-UTF-8
3678 * folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
3679 * their expanded versions. (Again, we can't prefold sharp s to 'ss' in
3680 * EXACTF nodes because we don't know at compile time if it actually
3681 * matches 'ss' or not. For EXACTF nodes it will match iff the target
3682 * string is in UTF-8. This is in contrast to EXACTFU nodes, where it
3683 * always matches; and EXACTFA where it never does. In an EXACTFA node in
3684 * a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
3685 * problem; but in a non-UTF8 pattern, folding it to that above-Latin1
3686 * string would require the pattern to be forced into UTF-8, the overhead
3687 * of which we want to avoid. Similarly the unfolded multi-char folds in
3688 * EXACTFL nodes will match iff the locale at the time of match is a UTF-8
3691 * Similarly, the code that generates tries doesn't currently handle
3692 * not-already-folded multi-char folds, and it looks like a pain to change
3693 * that. Therefore, trie generation of EXACTFA nodes with the sharp s
3694 * doesn't work. Instead, such an EXACTFA is turned into a new regnode,
3695 * EXACTFA_NO_TRIE, which the trie code knows not to handle. Most people
3696 * using /iaa matching will be doing so almost entirely with ASCII
3697 * strings, so this should rarely be encountered in practice */
3699 #define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
3700 if (PL_regkind[OP(scan)] == EXACT) \
3701 join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags),NULL,depth+1)
3704 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
3705 UV *min_subtract, bool *unfolded_multi_char,
3706 U32 flags,regnode *val, U32 depth)
3708 /* Merge several consecutive EXACTish nodes into one. */
3709 regnode *n = regnext(scan);
3711 regnode *next = scan + NODE_SZ_STR(scan);
3715 regnode *stop = scan;
3716 GET_RE_DEBUG_FLAGS_DECL;
3718 PERL_UNUSED_ARG(depth);
3721 PERL_ARGS_ASSERT_JOIN_EXACT;
3722 #ifndef EXPERIMENTAL_INPLACESCAN
3723 PERL_UNUSED_ARG(flags);
3724 PERL_UNUSED_ARG(val);
3726 DEBUG_PEEP("join",scan,depth);
3728 /* Look through the subsequent nodes in the chain. Skip NOTHING, merge
3729 * EXACT ones that are mergeable to the current one. */
3731 && (PL_regkind[OP(n)] == NOTHING
3732 || (stringok && OP(n) == OP(scan)))
3734 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
3737 if (OP(n) == TAIL || n > next)
3739 if (PL_regkind[OP(n)] == NOTHING) {
3740 DEBUG_PEEP("skip:",n,depth);
3741 NEXT_OFF(scan) += NEXT_OFF(n);
3742 next = n + NODE_STEP_REGNODE;
3749 else if (stringok) {
3750 const unsigned int oldl = STR_LEN(scan);
3751 regnode * const nnext = regnext(n);
3753 /* XXX I (khw) kind of doubt that this works on platforms (should
3754 * Perl ever run on one) where U8_MAX is above 255 because of lots
3755 * of other assumptions */
3756 /* Don't join if the sum can't fit into a single node */
3757 if (oldl + STR_LEN(n) > U8_MAX)
3760 DEBUG_PEEP("merg",n,depth);
3763 NEXT_OFF(scan) += NEXT_OFF(n);
3764 STR_LEN(scan) += STR_LEN(n);
3765 next = n + NODE_SZ_STR(n);
3766 /* Now we can overwrite *n : */
3767 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
3775 #ifdef EXPERIMENTAL_INPLACESCAN
3776 if (flags && !NEXT_OFF(n)) {
3777 DEBUG_PEEP("atch", val, depth);
3778 if (reg_off_by_arg[OP(n)]) {
3779 ARG_SET(n, val - n);
3782 NEXT_OFF(n) = val - n;
3790 *unfolded_multi_char = FALSE;
3792 /* Here, all the adjacent mergeable EXACTish nodes have been merged. We
3793 * can now analyze for sequences of problematic code points. (Prior to
3794 * this final joining, sequences could have been split over boundaries, and
3795 * hence missed). The sequences only happen in folding, hence for any
3796 * non-EXACT EXACTish node */
3797 if (OP(scan) != EXACT && OP(scan) != EXACTL) {
3798 U8* s0 = (U8*) STRING(scan);
3800 U8* s_end = s0 + STR_LEN(scan);
3802 int total_count_delta = 0; /* Total delta number of characters that
3803 multi-char folds expand to */
3805 /* One pass is made over the node's string looking for all the
3806 * possibilities. To avoid some tests in the loop, there are two main
3807 * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
3812 if (OP(scan) == EXACTFL) {
3815 /* An EXACTFL node would already have been changed to another
3816 * node type unless there is at least one character in it that
3817 * is problematic; likely a character whose fold definition
3818 * won't be known until runtime, and so has yet to be folded.
3819 * For all but the UTF-8 locale, folds are 1-1 in length, but
3820 * to handle the UTF-8 case, we need to create a temporary
3821 * folded copy using UTF-8 locale rules in order to analyze it.
3822 * This is because our macros that look to see if a sequence is
3823 * a multi-char fold assume everything is folded (otherwise the
3824 * tests in those macros would be too complicated and slow).
3825 * Note that here, the non-problematic folds will have already
3826 * been done, so we can just copy such characters. We actually
3827 * don't completely fold the EXACTFL string. We skip the
3828 * unfolded multi-char folds, as that would just create work
3829 * below to figure out the size they already are */
3831 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
3834 STRLEN s_len = UTF8SKIP(s);
3835 if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
3836 Copy(s, d, s_len, U8);
3839 else if (is_FOLDS_TO_MULTI_utf8(s)) {
3840 *unfolded_multi_char = TRUE;
3841 Copy(s, d, s_len, U8);
3844 else if (isASCII(*s)) {
3845 *(d++) = toFOLD(*s);
3849 _to_utf8_fold_flags(s, d, &len, FOLD_FLAGS_FULL);
3855 /* Point the remainder of the routine to look at our temporary
3859 } /* End of creating folded copy of EXACTFL string */
3861 /* Examine the string for a multi-character fold sequence. UTF-8
3862 * patterns have all characters pre-folded by the time this code is
3864 while (s < s_end - 1) /* Can stop 1 before the end, as minimum
3865 length sequence we are looking for is 2 */
3867 int count = 0; /* How many characters in a multi-char fold */
3868 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
3869 if (! len) { /* Not a multi-char fold: get next char */
3874 /* Nodes with 'ss' require special handling, except for
3875 * EXACTFA-ish for which there is no multi-char fold to this */
3876 if (len == 2 && *s == 's' && *(s+1) == 's'
3877 && OP(scan) != EXACTFA
3878 && OP(scan) != EXACTFA_NO_TRIE)
3881 if (OP(scan) != EXACTFL) {
3882 OP(scan) = EXACTFU_SS;
3886 else { /* Here is a generic multi-char fold. */
3887 U8* multi_end = s + len;
3889 /* Count how many characters are in it. In the case of
3890 * /aa, no folds which contain ASCII code points are
3891 * allowed, so check for those, and skip if found. */
3892 if (OP(scan) != EXACTFA && OP(scan) != EXACTFA_NO_TRIE) {
3893 count = utf8_length(s, multi_end);
3897 while (s < multi_end) {
3900 goto next_iteration;
3910 /* The delta is how long the sequence is minus 1 (1 is how long
3911 * the character that folds to the sequence is) */
3912 total_count_delta += count - 1;
3916 /* We created a temporary folded copy of the string in EXACTFL
3917 * nodes. Therefore we need to be sure it doesn't go below zero,
3918 * as the real string could be shorter */
3919 if (OP(scan) == EXACTFL) {
3920 int total_chars = utf8_length((U8*) STRING(scan),
3921 (U8*) STRING(scan) + STR_LEN(scan));
3922 if (total_count_delta > total_chars) {
3923 total_count_delta = total_chars;
3927 *min_subtract += total_count_delta;
3930 else if (OP(scan) == EXACTFA) {
3932 /* Non-UTF-8 pattern, EXACTFA node. There can't be a multi-char
3933 * fold to the ASCII range (and there are no existing ones in the
3934 * upper latin1 range). But, as outlined in the comments preceding
3935 * this function, we need to flag any occurrences of the sharp s.
3936 * This character forbids trie formation (because of added
3938 #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
3939 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
3940 || UNICODE_DOT_DOT_VERSION > 0)
3942 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
3943 OP(scan) = EXACTFA_NO_TRIE;
3944 *unfolded_multi_char = TRUE;
3952 /* Non-UTF-8 pattern, not EXACTFA node. Look for the multi-char
3953 * folds that are all Latin1. As explained in the comments
3954 * preceding this function, we look also for the sharp s in EXACTF
3955 * and EXACTFL nodes; it can be in the final position. Otherwise
3956 * we can stop looking 1 byte earlier because have to find at least
3957 * two characters for a multi-fold */
3958 const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
3963 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
3964 if (! len) { /* Not a multi-char fold. */
3965 if (*s == LATIN_SMALL_LETTER_SHARP_S
3966 && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
3968 *unfolded_multi_char = TRUE;
3975 && isALPHA_FOLD_EQ(*s, 's')
3976 && isALPHA_FOLD_EQ(*(s+1), 's'))
3979 /* EXACTF nodes need to know that the minimum length
3980 * changed so that a sharp s in the string can match this
3981 * ss in the pattern, but they remain EXACTF nodes, as they
3982 * won't match this unless the target string is is UTF-8,
3983 * which we don't know until runtime. EXACTFL nodes can't
3984 * transform into EXACTFU nodes */
3985 if (OP(scan) != EXACTF && OP(scan) != EXACTFL) {
3986 OP(scan) = EXACTFU_SS;
3990 *min_subtract += len - 1;
3998 /* Allow dumping but overwriting the collection of skipped
3999 * ops and/or strings with fake optimized ops */
4000 n = scan + NODE_SZ_STR(scan);
4008 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
4012 /* REx optimizer. Converts nodes into quicker variants "in place".
4013 Finds fixed substrings. */
4015 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
4016 to the position after last scanned or to NULL. */
4018 #define INIT_AND_WITHP \
4019 assert(!and_withp); \
4020 Newx(and_withp,1, regnode_ssc); \
4021 SAVEFREEPV(and_withp)
4025 S_unwind_scan_frames(pTHX_ const void *p)
4027 scan_frame *f= (scan_frame *)p;
4029 scan_frame *n= f->next_frame;
4037 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
4038 SSize_t *minlenp, SSize_t *deltap,
4043 regnode_ssc *and_withp,
4044 U32 flags, U32 depth)
4045 /* scanp: Start here (read-write). */
4046 /* deltap: Write maxlen-minlen here. */
4047 /* last: Stop before this one. */
4048 /* data: string data about the pattern */
4049 /* stopparen: treat close N as END */
4050 /* recursed: which subroutines have we recursed into */
4051 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
4053 /* There must be at least this number of characters to match */
4056 regnode *scan = *scanp, *next;
4058 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
4059 int is_inf_internal = 0; /* The studied chunk is infinite */
4060 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
4061 scan_data_t data_fake;
4062 SV *re_trie_maxbuff = NULL;
4063 regnode *first_non_open = scan;
4064 SSize_t stopmin = SSize_t_MAX;
4065 scan_frame *frame = NULL;
4066 GET_RE_DEBUG_FLAGS_DECL;
4068 PERL_ARGS_ASSERT_STUDY_CHUNK;
4072 while (first_non_open && OP(first_non_open) == OPEN)
4073 first_non_open=regnext(first_non_open);
4079 RExC_study_chunk_recursed_count++;
4081 DEBUG_OPTIMISE_MORE_r(
4083 PerlIO_printf(Perl_debug_log,
4084 "%*sstudy_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p",
4085 (int)(depth*2), "", (long)stopparen,
4086 (unsigned long)RExC_study_chunk_recursed_count,
4087 (unsigned long)depth, (unsigned long)recursed_depth,
4090 if (recursed_depth) {
4093 for ( j = 0 ; j < recursed_depth ; j++ ) {
4094 for ( i = 0 ; i < (U32)RExC_npar ; i++ ) {
4096 PAREN_TEST(RExC_study_chunk_recursed +
4097 ( j * RExC_study_chunk_recursed_bytes), i )
4100 !PAREN_TEST(RExC_study_chunk_recursed +
4101 (( j - 1 ) * RExC_study_chunk_recursed_bytes), i)
4104 PerlIO_printf(Perl_debug_log," %d",(int)i);
4108 if ( j + 1 < recursed_depth ) {
4109 PerlIO_printf(Perl_debug_log, ",");
4113 PerlIO_printf(Perl_debug_log,"\n");
4116 while ( scan && OP(scan) != END && scan < last ){
4117 UV min_subtract = 0; /* How mmany chars to subtract from the minimum
4118 node length to get a real minimum (because
4119 the folded version may be shorter) */
4120 bool unfolded_multi_char = FALSE;
4121 /* Peephole optimizer: */
4122 DEBUG_STUDYDATA("Peep:", data, depth);
4123 DEBUG_PEEP("Peep", scan, depth);
4126 /* The reason we do this here we need to deal with things like /(?:f)(?:o)(?:o)/
4127 * which cant be dealt with by the normal EXACT parsing code, as each (?:..) is handled
4128 * by a different invocation of reg() -- Yves
4130 JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);
4132 /* Follow the next-chain of the current node and optimize
4133 away all the NOTHINGs from it. */
4134 if (OP(scan) != CURLYX) {
4135 const int max = (reg_off_by_arg[OP(scan)]
4137 /* I32 may be smaller than U16 on CRAYs! */
4138 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
4139 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
4143 /* Skip NOTHING and LONGJMP. */
4144 while ((n = regnext(n))
4145 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
4146 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
4147 && off + noff < max)
4149 if (reg_off_by_arg[OP(scan)])
4152 NEXT_OFF(scan) = off;
4155 /* The principal pseudo-switch. Cannot be a switch, since we
4156 look into several different things. */
4157 if ( OP(scan) == DEFINEP ) {
4159 SSize_t deltanext = 0;
4160 SSize_t fake_last_close = 0;
4161 I32 f = SCF_IN_DEFINE;
4163 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4164 scan = regnext(scan);
4165 assert( OP(scan) == IFTHEN );
4166 DEBUG_PEEP("expect IFTHEN", scan, depth);
4168 data_fake.last_closep= &fake_last_close;
4170 next = regnext(scan);
4171 scan = NEXTOPER(NEXTOPER(scan));
4172 DEBUG_PEEP("scan", scan, depth);
4173 DEBUG_PEEP("next", next, depth);
4175 /* we suppose the run is continuous, last=next...
4176 * NOTE we dont use the return here! */
4177 (void)study_chunk(pRExC_state, &scan, &minlen,
4178 &deltanext, next, &data_fake, stopparen,
4179 recursed_depth, NULL, f, depth+1);
4184 OP(scan) == BRANCH ||
4185 OP(scan) == BRANCHJ ||
4188 next = regnext(scan);
4191 /* The op(next)==code check below is to see if we
4192 * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN"
4193 * IFTHEN is special as it might not appear in pairs.
4194 * Not sure whether BRANCH-BRANCHJ is possible, regardless
4195 * we dont handle it cleanly. */
4196 if (OP(next) == code || code == IFTHEN) {
4197 /* NOTE - There is similar code to this block below for
4198 * handling TRIE nodes on a re-study. If you change stuff here
4199 * check there too. */
4200 SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0;
4202 regnode * const startbranch=scan;
4204 if (flags & SCF_DO_SUBSTR) {
4205 /* Cannot merge strings after this. */
4206 scan_commit(pRExC_state, data, minlenp, is_inf);
4209 if (flags & SCF_DO_STCLASS)
4210 ssc_init_zero(pRExC_state, &accum);
4212 while (OP(scan) == code) {
4213 SSize_t deltanext, minnext, fake;
4215 regnode_ssc this_class;
4217 DEBUG_PEEP("Branch", scan, depth);
4220 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4222 data_fake.whilem_c = data->whilem_c;
4223 data_fake.last_closep = data->last_closep;
4226 data_fake.last_closep = &fake;
4228 data_fake.pos_delta = delta;
4229 next = regnext(scan);
4231 scan = NEXTOPER(scan); /* everything */
4232 if (code != BRANCH) /* everything but BRANCH */
4233 scan = NEXTOPER(scan);
4235 if (flags & SCF_DO_STCLASS) {
4236 ssc_init(pRExC_state, &this_class);
4237 data_fake.start_class = &this_class;
4238 f = SCF_DO_STCLASS_AND;
4240 if (flags & SCF_WHILEM_VISITED_POS)
4241 f |= SCF_WHILEM_VISITED_POS;
4243 /* we suppose the run is continuous, last=next...*/
4244 minnext = study_chunk(pRExC_state, &scan, minlenp,
4245 &deltanext, next, &data_fake, stopparen,
4246 recursed_depth, NULL, f,depth+1);
4250 if (deltanext == SSize_t_MAX) {
4251 is_inf = is_inf_internal = 1;
4253 } else if (max1 < minnext + deltanext)
4254 max1 = minnext + deltanext;
4256 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4258 if (data_fake.flags & SCF_SEEN_ACCEPT) {
4259 if ( stopmin > minnext)
4260 stopmin = min + min1;
4261 flags &= ~SCF_DO_SUBSTR;
4263 data->flags |= SCF_SEEN_ACCEPT;
4266 if (data_fake.flags & SF_HAS_EVAL)
4267 data->flags |= SF_HAS_EVAL;
4268 data->whilem_c = data_fake.whilem_c;
4270 if (flags & SCF_DO_STCLASS)
4271 ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);
4273 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
4275 if (flags & SCF_DO_SUBSTR) {
4276 data->pos_min += min1;
4277 if (data->pos_delta >= SSize_t_MAX - (max1 - min1))
4278 data->pos_delta = SSize_t_MAX;
4280 data->pos_delta += max1 - min1;
4281 if (max1 != min1 || is_inf)
4282 data->longest = &(data->longest_float);
4285 if (delta == SSize_t_MAX
4286 || SSize_t_MAX - delta - (max1 - min1) < 0)
4287 delta = SSize_t_MAX;
4289 delta += max1 - min1;
4290 if (flags & SCF_DO_STCLASS_OR) {
4291 ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);
4293 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4294 flags &= ~SCF_DO_STCLASS;
4297 else if (flags & SCF_DO_STCLASS_AND) {
4299 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
4300 flags &= ~SCF_DO_STCLASS;
4303 /* Switch to OR mode: cache the old value of
4304 * data->start_class */
4306 StructCopy(data->start_class, and_withp, regnode_ssc);
4307 flags &= ~SCF_DO_STCLASS_AND;
4308 StructCopy(&accum, data->start_class, regnode_ssc);
4309 flags |= SCF_DO_STCLASS_OR;
4313 if (PERL_ENABLE_TRIE_OPTIMISATION &&
4314 OP( startbranch ) == BRANCH )
4318 Assuming this was/is a branch we are dealing with: 'scan'
4319 now points at the item that follows the branch sequence,
4320 whatever it is. We now start at the beginning of the
4321 sequence and look for subsequences of
4327 which would be constructed from a pattern like
4330 If we can find such a subsequence we need to turn the first
4331 element into a trie and then add the subsequent branch exact
4332 strings to the trie.
4336 1. patterns where the whole set of branches can be
4339 2. patterns where only a subset can be converted.
4341 In case 1 we can replace the whole set with a single regop
4342 for the trie. In case 2 we need to keep the start and end
4345 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
4346 becomes BRANCH TRIE; BRANCH X;
4348 There is an additional case, that being where there is a
4349 common prefix, which gets split out into an EXACT like node
4350 preceding the TRIE node.
4352 If x(1..n)==tail then we can do a simple trie, if not we make
4353 a "jump" trie, such that when we match the appropriate word
4354 we "jump" to the appropriate tail node. Essentially we turn
4355 a nested if into a case structure of sorts.
4360 if (!re_trie_maxbuff) {
4361 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
4362 if (!SvIOK(re_trie_maxbuff))
4363 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
4365 if ( SvIV(re_trie_maxbuff)>=0 ) {
4367 regnode *first = (regnode *)NULL;
4368 regnode *last = (regnode *)NULL;
4369 regnode *tail = scan;
4373 /* var tail is used because there may be a TAIL
4374 regop in the way. Ie, the exacts will point to the
4375 thing following the TAIL, but the last branch will
4376 point at the TAIL. So we advance tail. If we
4377 have nested (?:) we may have to move through several
4381 while ( OP( tail ) == TAIL ) {
4382 /* this is the TAIL generated by (?:) */
4383 tail = regnext( tail );
4387 DEBUG_TRIE_COMPILE_r({
4388 regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);
4389 PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
4390 (int)depth * 2 + 2, "",
4391 "Looking for TRIE'able sequences. Tail node is: ",
4392 SvPV_nolen_const( RExC_mysv )
4398 Step through the branches
4399 cur represents each branch,
4400 noper is the first thing to be matched as part
4402 noper_next is the regnext() of that node.
4404 We normally handle a case like this
4405 /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also
4406 support building with NOJUMPTRIE, which restricts
4407 the trie logic to structures like /FOO|BAR/.
4409 If noper is a trieable nodetype then the branch is
4410 a possible optimization target. If we are building
4411 under NOJUMPTRIE then we require that noper_next is
4412 the same as scan (our current position in the regex
4415 Once we have two or more consecutive such branches
4416 we can create a trie of the EXACT's contents and
4417 stitch it in place into the program.
4419 If the sequence represents all of the branches in
4420 the alternation we replace the entire thing with a
4423 Otherwise when it is a subsequence we need to
4424 stitch it in place and replace only the relevant
4425 branches. This means the first branch has to remain
4426 as it is used by the alternation logic, and its
4427 next pointer, and needs to be repointed at the item
4428 on the branch chain following the last branch we
4429 have optimized away.
4431 This could be either a BRANCH, in which case the
4432 subsequence is internal, or it could be the item
4433 following the branch sequence in which case the
4434 subsequence is at the end (which does not
4435 necessarily mean the first node is the start of the
4438 TRIE_TYPE(X) is a define which maps the optype to a
4442 ----------------+-----------
4446 EXACTFU_SS | EXACTFU
4449 EXACTFLU8 | EXACTFLU8
4453 #define TRIE_TYPE(X) ( ( NOTHING == (X) ) \
4455 : ( EXACT == (X) ) \
4457 : ( EXACTFU == (X) || EXACTFU_SS == (X) ) \
4459 : ( EXACTFA == (X) ) \
4461 : ( EXACTL == (X) ) \
4463 : ( EXACTFLU8 == (X) ) \
4467 /* dont use tail as the end marker for this traverse */
4468 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
4469 regnode * const noper = NEXTOPER( cur );
4470 U8 noper_type = OP( noper );
4471 U8 noper_trietype = TRIE_TYPE( noper_type );
4472 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
4473 regnode * const noper_next = regnext( noper );
4474 U8 noper_next_type = (noper_next && noper_next != tail) ? OP(noper_next) : 0;
4475 U8 noper_next_trietype = (noper_next && noper_next != tail) ? TRIE_TYPE( noper_next_type ) :0;
4478 DEBUG_TRIE_COMPILE_r({
4479 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4480 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
4481 (int)depth * 2 + 2,"", SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );
4483 regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);
4484 PerlIO_printf( Perl_debug_log, " -> %s",
4485 SvPV_nolen_const(RExC_mysv));
4488 regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);
4489 PerlIO_printf( Perl_debug_log,"\t=> %s\t",
4490 SvPV_nolen_const(RExC_mysv));
4492 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d,tt==%s,nt==%s,nnt==%s)\n",
4493 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
4494 PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]
4498 /* Is noper a trieable nodetype that can be merged
4499 * with the current trie (if there is one)? */
4503 ( noper_trietype == NOTHING)
4504 || ( trietype == NOTHING )
4505 || ( trietype == noper_trietype )
4508 && noper_next == tail
4512 /* Handle mergable triable node Either we are
4513 * the first node in a new trieable sequence,
4514 * in which case we do some bookkeeping,
4515 * otherwise we update the end pointer. */
4518 if ( noper_trietype == NOTHING ) {
4519 #if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
4520 regnode * const noper_next = regnext( noper );
4521 U8 noper_next_type = (noper_next && noper_next!=tail) ? OP(noper_next) : 0;
4522 U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
4525 if ( noper_next_trietype ) {
4526 trietype = noper_next_trietype;
4527 } else if (noper_next_type) {
4528 /* a NOTHING regop is 1 regop wide.
4529 * We need at least two for a trie
4530 * so we can't merge this in */
4534 trietype = noper_trietype;
4537 if ( trietype == NOTHING )
4538 trietype = noper_trietype;
4543 } /* end handle mergable triable node */
4545 /* handle unmergable node -
4546 * noper may either be a triable node which can
4547 * not be tried together with the current trie,
4548 * or a non triable node */
4550 /* If last is set and trietype is not
4551 * NOTHING then we have found at least two
4552 * triable branch sequences in a row of a
4553 * similar trietype so we can turn them
4554 * into a trie. If/when we allow NOTHING to
4555 * start a trie sequence this condition
4556 * will be required, and it isn't expensive
4557 * so we leave it in for now. */
4558 if ( trietype && trietype != NOTHING )
4559 make_trie( pRExC_state,
4560 startbranch, first, cur, tail,
4561 count, trietype, depth+1 );
4562 last = NULL; /* note: we clear/update
4563 first, trietype etc below,
4564 so we dont do it here */
4568 && noper_next == tail
4571 /* noper is triable, so we can start a new
4575 trietype = noper_trietype;
4577 /* if we already saw a first but the
4578 * current node is not triable then we have
4579 * to reset the first information. */
4584 } /* end handle unmergable node */
4585 } /* loop over branches */
4586 DEBUG_TRIE_COMPILE_r({
4587 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4588 PerlIO_printf( Perl_debug_log,
4589 "%*s- %s (%d) <SCAN FINISHED>\n",
4591 "", SvPV_nolen_const( RExC_mysv ),REG_NODE_NUM(cur));
4594 if ( last && trietype ) {
4595 if ( trietype != NOTHING ) {
4596 /* the last branch of the sequence was part of
4597 * a trie, so we have to construct it here
4598 * outside of the loop */
4599 made= make_trie( pRExC_state, startbranch,
4600 first, scan, tail, count,
4601 trietype, depth+1 );
4602 #ifdef TRIE_STUDY_OPT
4603 if ( ((made == MADE_EXACT_TRIE &&
4604 startbranch == first)
4605 || ( first_non_open == first )) &&
4607 flags |= SCF_TRIE_RESTUDY;
4608 if ( startbranch == first
4611 RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;
4616 /* at this point we know whatever we have is a
4617 * NOTHING sequence/branch AND if 'startbranch'
4618 * is 'first' then we can turn the whole thing
4621 if ( startbranch == first ) {
4623 /* the entire thing is a NOTHING sequence,
4624 * something like this: (?:|) So we can
4625 * turn it into a plain NOTHING op. */
4626 DEBUG_TRIE_COMPILE_r({
4627 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4628 PerlIO_printf( Perl_debug_log,
4629 "%*s- %s (%d) <NOTHING BRANCH SEQUENCE>\n", (int)depth * 2 + 2,
4630 "", SvPV_nolen_const( RExC_mysv ),REG_NODE_NUM(cur));
4633 OP(startbranch)= NOTHING;
4634 NEXT_OFF(startbranch)= tail - startbranch;
4635 for ( opt= startbranch + 1; opt < tail ; opt++ )
4639 } /* end if ( last) */
4640 } /* TRIE_MAXBUF is non zero */
4645 else if ( code == BRANCHJ ) { /* single branch is optimized. */
4646 scan = NEXTOPER(NEXTOPER(scan));
4647 } else /* single branch is optimized. */
4648 scan = NEXTOPER(scan);
4650 } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
4652 regnode *start = NULL;
4653 regnode *end = NULL;
4654 U32 my_recursed_depth= recursed_depth;
4657 if (OP(scan) != SUSPEND) { /* GOSUB/GOSTART */
4658 /* Do setup, note this code has side effects beyond
4659 * the rest of this block. Specifically setting
4660 * RExC_recurse[] must happen at least once during
4662 if (OP(scan) == GOSUB) {
4664 RExC_recurse[ARG2L(scan)] = scan;
4665 start = RExC_open_parens[paren-1];
4666 end = RExC_close_parens[paren-1];
4668 start = RExC_rxi->program + 1;
4671 /* NOTE we MUST always execute the above code, even
4672 * if we do nothing with a GOSUB/GOSTART */
4674 ( flags & SCF_IN_DEFINE )
4677 (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))
4679 ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )
4682 /* no need to do anything here if we are in a define. */
4683 /* or we are after some kind of infinite construct
4684 * so we can skip recursing into this item.
4685 * Since it is infinite we will not change the maxlen
4686 * or delta, and if we miss something that might raise
4687 * the minlen it will merely pessimise a little.
4689 * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/
4690 * might result in a minlen of 1 and not of 4,
4691 * but this doesn't make us mismatch, just try a bit
4692 * harder than we should.
4694 scan= regnext(scan);
4701 !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren)
4703 /* it is quite possible that there are more efficient ways
4704 * to do this. We maintain a bitmap per level of recursion
4705 * of which patterns we have entered so we can detect if a
4706 * pattern creates a possible infinite loop. When we
4707 * recurse down a level we copy the previous levels bitmap
4708 * down. When we are at recursion level 0 we zero the top
4709 * level bitmap. It would be nice to implement a different
4710 * more efficient way of doing this. In particular the top
4711 * level bitmap may be unnecessary.
4713 if (!recursed_depth) {
4714 Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);
4716 Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes),
4717 RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes),
4718 RExC_study_chunk_recursed_bytes, U8);
4720 /* we havent recursed into this paren yet, so recurse into it */
4721 DEBUG_STUDYDATA("set:", data,depth);
4722 PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren);
4723 my_recursed_depth= recursed_depth + 1;
4725 DEBUG_STUDYDATA("inf:", data,depth);
4726 /* some form of infinite recursion, assume infinite length
4728 if (flags & SCF_DO_SUBSTR) {
4729 scan_commit(pRExC_state, data, minlenp, is_inf);
4730 data->longest = &(data->longest_float);
4732 is_inf = is_inf_internal = 1;
4733 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
4734 ssc_anything(data->start_class);
4735 flags &= ~SCF_DO_STCLASS;
4737 start= NULL; /* reset start so we dont recurse later on. */
4742 end = regnext(scan);
4745 scan_frame *newframe;
4747 if (!RExC_frame_last) {
4748 Newxz(newframe, 1, scan_frame);
4749 SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);
4750 RExC_frame_head= newframe;
4752 } else if (!RExC_frame_last->next_frame) {
4753 Newxz(newframe,1,scan_frame);
4754 RExC_frame_last->next_frame= newframe;
4755 newframe->prev_frame= RExC_frame_last;
4758 newframe= RExC_frame_last->next_frame;
4760 RExC_frame_last= newframe;
4762 newframe->next_regnode = regnext(scan);
4763 newframe->last_regnode = last;
4764 newframe->stopparen = stopparen;
4765 newframe->prev_recursed_depth = recursed_depth;
4766 newframe->this_prev_frame= frame;
4768 DEBUG_STUDYDATA("frame-new:",data,depth);
4769 DEBUG_PEEP("fnew", scan, depth);
4776 recursed_depth= my_recursed_depth;
4781 else if (OP(scan) == EXACT || OP(scan) == EXACTL) {
4782 SSize_t l = STR_LEN(scan);
4785 const U8 * const s = (U8*)STRING(scan);
4786 uc = utf8_to_uvchr_buf(s, s + l, NULL);
4787 l = utf8_length(s, s + l);
4789 uc = *((U8*)STRING(scan));
4792 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
4793 /* The code below prefers earlier match for fixed
4794 offset, later match for variable offset. */
4795 if (data->last_end == -1) { /* Update the start info. */
4796 data->last_start_min = data->pos_min;
4797 data->last_start_max = is_inf
4798 ? SSize_t_MAX : data->pos_min + data->pos_delta;
4800 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
4802 SvUTF8_on(data->last_found);
4804 SV * const sv = data->last_found;
4805 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
4806 mg_find(sv, PERL_MAGIC_utf8) : NULL;
4807 if (mg && mg->mg_len >= 0)
4808 mg->mg_len += utf8_length((U8*)STRING(scan),
4809 (U8*)STRING(scan)+STR_LEN(scan));
4811 data->last_end = data->pos_min + l;
4812 data->pos_min += l; /* As in the first entry. */
4813 data->flags &= ~SF_BEFORE_EOL;
4816 /* ANDing the code point leaves at most it, and not in locale, and
4817 * can't match null string */
4818 if (flags & SCF_DO_STCLASS_AND) {
4819 ssc_cp_and(data->start_class, uc);
4820 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
4821 ssc_clear_locale(data->start_class);
4823 else if (flags & SCF_DO_STCLASS_OR) {
4824 ssc_add_cp(data->start_class, uc);
4825 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4827 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
4828 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
4830 flags &= ~SCF_DO_STCLASS;
4832 else if (PL_regkind[OP(scan)] == EXACT) {
4833 /* But OP != EXACT!, so is EXACTFish */
4834 SSize_t l = STR_LEN(scan);
4835 const U8 * s = (U8*)STRING(scan);
4837 /* Search for fixed substrings supports EXACT only. */
4838 if (flags & SCF_DO_SUBSTR) {
4840 scan_commit(pRExC_state, data, minlenp, is_inf);
4843 l = utf8_length(s, s + l);
4845 if (unfolded_multi_char) {
4846 RExC_seen |= REG_UNFOLDED_MULTI_SEEN;
4848 min += l - min_subtract;
4850 delta += min_subtract;
4851 if (flags & SCF_DO_SUBSTR) {
4852 data->pos_min += l - min_subtract;
4853 if (data->pos_min < 0) {
4856 data->pos_delta += min_subtract;
4858 data->longest = &(data->longest_float);
4862 if (flags & SCF_DO_STCLASS) {
4863 SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan);
4865 assert(EXACTF_invlist);
4866 if (flags & SCF_DO_STCLASS_AND) {
4867 if (OP(scan) != EXACTFL)
4868 ssc_clear_locale(data->start_class);
4869 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
4870 ANYOF_POSIXL_ZERO(data->start_class);
4871 ssc_intersection(data->start_class, EXACTF_invlist, FALSE);
4873 else { /* SCF_DO_STCLASS_OR */
4874 ssc_union(data->start_class, EXACTF_invlist, FALSE);
4875 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4877 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
4878 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
4880 flags &= ~SCF_DO_STCLASS;
4881 SvREFCNT_dec(EXACTF_invlist);
4884 else if (REGNODE_VARIES(OP(scan))) {
4885 SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;
4886 I32 fl = 0, f = flags;
4887 regnode * const oscan = scan;
4888 regnode_ssc this_class;
4889 regnode_ssc *oclass = NULL;
4890 I32 next_is_eval = 0;
4892 switch (PL_regkind[OP(scan)]) {
4893 case WHILEM: /* End of (?:...)* . */
4894 scan = NEXTOPER(scan);
4897 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
4898 next = NEXTOPER(scan);
4899 if (OP(next) == EXACT
4900 || OP(next) == EXACTL
4901 || (flags & SCF_DO_STCLASS))
4904 maxcount = REG_INFTY;
4905 next = regnext(scan);
4906 scan = NEXTOPER(scan);
4910 if (flags & SCF_DO_SUBSTR)
4915 if (flags & SCF_DO_STCLASS) {
4917 maxcount = REG_INFTY;
4918 next = regnext(scan);
4919 scan = NEXTOPER(scan);
4922 if (flags & SCF_DO_SUBSTR) {
4923 scan_commit(pRExC_state, data, minlenp, is_inf);
4924 /* Cannot extend fixed substrings */
4925 data->longest = &(data->longest_float);
4927 is_inf = is_inf_internal = 1;
4928 scan = regnext(scan);
4929 goto optimize_curly_tail;
4931 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
4932 && (scan->flags == stopparen))
4937 mincount = ARG1(scan);
4938 maxcount = ARG2(scan);
4940 next = regnext(scan);
4941 if (OP(scan) == CURLYX) {
4942 I32 lp = (data ? *(data->last_closep) : 0);
4943 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
4945 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
4946 next_is_eval = (OP(scan) == EVAL);
4948 if (flags & SCF_DO_SUBSTR) {
4950 scan_commit(pRExC_state, data, minlenp, is_inf);
4951 /* Cannot extend fixed substrings */
4952 pos_before = data->pos_min;
4956 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
4958 data->flags |= SF_IS_INF;
4960 if (flags & SCF_DO_STCLASS) {
4961 ssc_init(pRExC_state, &this_class);
4962 oclass = data->start_class;
4963 data->start_class = &this_class;
4964 f |= SCF_DO_STCLASS_AND;
4965 f &= ~SCF_DO_STCLASS_OR;
4967 /* Exclude from super-linear cache processing any {n,m}
4968 regops for which the combination of input pos and regex
4969 pos is not enough information to determine if a match
4972 For example, in the regex /foo(bar\s*){4,8}baz/ with the
4973 regex pos at the \s*, the prospects for a match depend not
4974 only on the input position but also on how many (bar\s*)
4975 repeats into the {4,8} we are. */
4976 if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
4977 f &= ~SCF_WHILEM_VISITED_POS;
4979 /* This will finish on WHILEM, setting scan, or on NULL: */
4980 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
4981 last, data, stopparen, recursed_depth, NULL,
4983 ? (f & ~SCF_DO_SUBSTR)
4987 if (flags & SCF_DO_STCLASS)
4988 data->start_class = oclass;
4989 if (mincount == 0 || minnext == 0) {
4990 if (flags & SCF_DO_STCLASS_OR) {
4991 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
4993 else if (flags & SCF_DO_STCLASS_AND) {
4994 /* Switch to OR mode: cache the old value of
4995 * data->start_class */
4997 StructCopy(data->start_class, and_withp, regnode_ssc);
4998 flags &= ~SCF_DO_STCLASS_AND;
4999 StructCopy(&this_class, data->start_class, regnode_ssc);
5000 flags |= SCF_DO_STCLASS_OR;
5001 ANYOF_FLAGS(data->start_class)
5002 |= SSC_MATCHES_EMPTY_STRING;
5004 } else { /* Non-zero len */
5005 if (flags & SCF_DO_STCLASS_OR) {
5006 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5007 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5009 else if (flags & SCF_DO_STCLASS_AND)
5010 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5011 flags &= ~SCF_DO_STCLASS;
5013 if (!scan) /* It was not CURLYX, but CURLY. */
5015 if (!(flags & SCF_TRIE_DOING_RESTUDY)
5016 /* ? quantifier ok, except for (?{ ... }) */
5017 && (next_is_eval || !(mincount == 0 && maxcount == 1))
5018 && (minnext == 0) && (deltanext == 0)
5019 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
5020 && maxcount <= REG_INFTY/3) /* Complement check for big
5023 /* Fatal warnings may leak the regexp without this: */
5024 SAVEFREESV(RExC_rx_sv);
5025 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
5026 "Quantifier unexpected on zero-length expression "
5027 "in regex m/%"UTF8f"/",
5028 UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,
5030 (void)ReREFCNT_inc(RExC_rx_sv);
5033 min += minnext * mincount;
5034 is_inf_internal |= deltanext == SSize_t_MAX
5035 || (maxcount == REG_INFTY && minnext + deltanext > 0);
5036 is_inf |= is_inf_internal;
5038 delta = SSize_t_MAX;
5040 delta += (minnext + deltanext) * maxcount
5041 - minnext * mincount;
5043 /* Try powerful optimization CURLYX => CURLYN. */
5044 if ( OP(oscan) == CURLYX && data
5045 && data->flags & SF_IN_PAR
5046 && !(data->flags & SF_HAS_EVAL)
5047 && !deltanext && minnext == 1 ) {
5048 /* Try to optimize to CURLYN. */
5049 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
5050 regnode * const nxt1 = nxt;
5057 if (!REGNODE_SIMPLE(OP(nxt))
5058 && !(PL_regkind[OP(nxt)] == EXACT
5059 && STR_LEN(nxt) == 1))
5065 if (OP(nxt) != CLOSE)
5067 if (RExC_open_parens) {
5068 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
5069 RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
5071 /* Now we know that nxt2 is the only contents: */
5072 oscan->flags = (U8)ARG(nxt);
5074 OP(nxt1) = NOTHING; /* was OPEN. */
5077 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5078 NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
5079 NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
5080 OP(nxt) = OPTIMIZED; /* was CLOSE. */
5081 OP(nxt + 1) = OPTIMIZED; /* was count. */
5082 NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
5087 /* Try optimization CURLYX => CURLYM. */
5088 if ( OP(oscan) == CURLYX && data
5089 && !(data->flags & SF_HAS_PAR)
5090 && !(data->flags & SF_HAS_EVAL)
5091 && !deltanext /* atom is fixed width */
5092 && minnext != 0 /* CURLYM can't handle zero width */
5094 /* Nor characters whose fold at run-time may be
5095 * multi-character */
5096 && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)
5098 /* XXXX How to optimize if data == 0? */
5099 /* Optimize to a simpler form. */
5100 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
5104 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
5105 && (OP(nxt2) != WHILEM))
5107 OP(nxt2) = SUCCEED; /* Whas WHILEM */
5108 /* Need to optimize away parenths. */
5109 if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
5110 /* Set the parenth number. */
5111 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
5113 oscan->flags = (U8)ARG(nxt);
5114 if (RExC_open_parens) {
5115 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
5116 RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
5118 OP(nxt1) = OPTIMIZED; /* was OPEN. */
5119 OP(nxt) = OPTIMIZED; /* was CLOSE. */
5122 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5123 OP(nxt + 1) = OPTIMIZED; /* was count. */
5124 NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
5125 NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
5128 while ( nxt1 && (OP(nxt1) != WHILEM)) {
5129 regnode *nnxt = regnext(nxt1);
5131 if (reg_off_by_arg[OP(nxt1)])
5132 ARG_SET(nxt1, nxt2 - nxt1);
5133 else if (nxt2 - nxt1 < U16_MAX)
5134 NEXT_OFF(nxt1) = nxt2 - nxt1;
5136 OP(nxt) = NOTHING; /* Cannot beautify */
5141 /* Optimize again: */
5142 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
5143 NULL, stopparen, recursed_depth, NULL, 0,depth+1);
5148 else if ((OP(oscan) == CURLYX)
5149 && (flags & SCF_WHILEM_VISITED_POS)
5150 /* See the comment on a similar expression above.
5151 However, this time it's not a subexpression
5152 we care about, but the expression itself. */
5153 && (maxcount == REG_INFTY)
5154 && data && ++data->whilem_c < 16) {
5155 /* This stays as CURLYX, we can put the count/of pair. */
5156 /* Find WHILEM (as in regexec.c) */
5157 regnode *nxt = oscan + NEXT_OFF(oscan);
5159 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
5161 PREVOPER(nxt)->flags = (U8)(data->whilem_c
5162 | (RExC_whilem_seen << 4)); /* On WHILEM */
5164 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
5166 if (flags & SCF_DO_SUBSTR) {
5167 SV *last_str = NULL;
5168 STRLEN last_chrs = 0;
5169 int counted = mincount != 0;
5171 if (data->last_end > 0 && mincount != 0) { /* Ends with a
5173 SSize_t b = pos_before >= data->last_start_min
5174 ? pos_before : data->last_start_min;
5176 const char * const s = SvPV_const(data->last_found, l);
5177 SSize_t old = b - data->last_start_min;
5180 old = utf8_hop((U8*)s, old) - (U8*)s;
5182 /* Get the added string: */
5183 last_str = newSVpvn_utf8(s + old, l, UTF);
5184 last_chrs = UTF ? utf8_length((U8*)(s + old),
5185 (U8*)(s + old + l)) : l;
5186 if (deltanext == 0 && pos_before == b) {
5187 /* What was added is a constant string */
5190 SvGROW(last_str, (mincount * l) + 1);
5191 repeatcpy(SvPVX(last_str) + l,
5192 SvPVX_const(last_str), l,
5194 SvCUR_set(last_str, SvCUR(last_str) * mincount);
5195 /* Add additional parts. */
5196 SvCUR_set(data->last_found,
5197 SvCUR(data->last_found) - l);
5198 sv_catsv(data->last_found, last_str);
5200 SV * sv = data->last_found;
5202 SvUTF8(sv) && SvMAGICAL(sv) ?
5203 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5204 if (mg && mg->mg_len >= 0)
5205 mg->mg_len += last_chrs * (mincount-1);
5207 last_chrs *= mincount;
5208 data->last_end += l * (mincount - 1);
5211 /* start offset must point into the last copy */
5212 data->last_start_min += minnext * (mincount - 1);
5213 data->last_start_max =
5216 : data->last_start_max +
5217 (maxcount - 1) * (minnext + data->pos_delta);
5220 /* It is counted once already... */
5221 data->pos_min += minnext * (mincount - counted);
5223 PerlIO_printf(Perl_debug_log, "counted=%"UVuf" deltanext=%"UVuf
5224 " SSize_t_MAX=%"UVuf" minnext=%"UVuf
5225 " maxcount=%"UVuf" mincount=%"UVuf"\n",
5226 (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount,
5228 if (deltanext != SSize_t_MAX)
5229 PerlIO_printf(Perl_debug_log, "LHS=%"UVuf" RHS=%"UVuf"\n",
5230 (UV)(-counted * deltanext + (minnext + deltanext) * maxcount
5231 - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta));
5233 if (deltanext == SSize_t_MAX
5234 || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta)
5235 data->pos_delta = SSize_t_MAX;
5237 data->pos_delta += - counted * deltanext +
5238 (minnext + deltanext) * maxcount - minnext * mincount;
5239 if (mincount != maxcount) {
5240 /* Cannot extend fixed substrings found inside
5242 scan_commit(pRExC_state, data, minlenp, is_inf);
5243 if (mincount && last_str) {
5244 SV * const sv = data->last_found;
5245 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5246 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5250 sv_setsv(sv, last_str);
5251 data->last_end = data->pos_min;
5252 data->last_start_min = data->pos_min - last_chrs;
5253 data->last_start_max = is_inf
5255 : data->pos_min + data->pos_delta - last_chrs;
5257 data->longest = &(data->longest_float);
5259 SvREFCNT_dec(last_str);
5261 if (data && (fl & SF_HAS_EVAL))
5262 data->flags |= SF_HAS_EVAL;
5263 optimize_curly_tail:
5264 if (OP(oscan) != CURLYX) {
5265 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
5267 NEXT_OFF(oscan) += NEXT_OFF(next);
5273 Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d",
5278 if (flags & SCF_DO_SUBSTR) {
5279 /* Cannot expect anything... */
5280 scan_commit(pRExC_state, data, minlenp, is_inf);
5281 data->longest = &(data->longest_float);
5283 is_inf = is_inf_internal = 1;
5284 if (flags & SCF_DO_STCLASS_OR) {
5285 if (OP(scan) == CLUMP) {
5286 /* Actually is any start char, but very few code points
5287 * aren't start characters */
5288 ssc_match_all_cp(data->start_class);
5291 ssc_anything(data->start_class);
5294 flags &= ~SCF_DO_STCLASS;
5298 else if (OP(scan) == LNBREAK) {
5299 if (flags & SCF_DO_STCLASS) {
5300 if (flags & SCF_DO_STCLASS_AND) {
5301 ssc_intersection(data->start_class,
5302 PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);
5303 ssc_clear_locale(data->start_class);
5304 ANYOF_FLAGS(data->start_class)
5305 &= ~SSC_MATCHES_EMPTY_STRING;
5307 else if (flags & SCF_DO_STCLASS_OR) {
5308 ssc_union(data->start_class,
5309 PL_XPosix_ptrs[_CC_VERTSPACE],
5311 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5313 /* See commit msg for
5314 * 749e076fceedeb708a624933726e7989f2302f6a */
5315 ANYOF_FLAGS(data->start_class)
5316 &= ~SSC_MATCHES_EMPTY_STRING;
5318 flags &= ~SCF_DO_STCLASS;
5321 if (delta != SSize_t_MAX)
5322 delta++; /* Because of the 2 char string cr-lf */
5323 if (flags & SCF_DO_SUBSTR) {
5324 /* Cannot expect anything... */
5325 scan_commit(pRExC_state, data, minlenp, is_inf);
5327 data->pos_delta += 1;
5328 data->longest = &(data->longest_float);
5331 else if (REGNODE_SIMPLE(OP(scan))) {
5333 if (flags & SCF_DO_SUBSTR) {
5334 scan_commit(pRExC_state, data, minlenp, is_inf);
5338 if (flags & SCF_DO_STCLASS) {
5340 SV* my_invlist = NULL;
5343 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5344 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5346 /* Some of the logic below assumes that switching
5347 locale on will only add false positives. */
5352 Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d",
5356 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5357 ssc_match_all_cp(data->start_class);
5362 SV* REG_ANY_invlist = _new_invlist(2);
5363 REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,
5365 if (flags & SCF_DO_STCLASS_OR) {
5366 ssc_union(data->start_class,
5368 TRUE /* TRUE => invert, hence all but \n
5372 else if (flags & SCF_DO_STCLASS_AND) {
5373 ssc_intersection(data->start_class,
5375 TRUE /* TRUE => invert */
5377 ssc_clear_locale(data->start_class);
5379 SvREFCNT_dec_NN(REG_ANY_invlist);
5386 if (flags & SCF_DO_STCLASS_AND)
5387 ssc_and(pRExC_state, data->start_class,
5388 (regnode_charclass *) scan);
5390 ssc_or(pRExC_state, data->start_class,
5391 (regnode_charclass *) scan);
5399 namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;
5400 if (flags & SCF_DO_STCLASS_AND) {
5401 bool was_there = cBOOL(
5402 ANYOF_POSIXL_TEST(data->start_class,
5404 ANYOF_POSIXL_ZERO(data->start_class);
5405 if (was_there) { /* Do an AND */
5406 ANYOF_POSIXL_SET(data->start_class, namedclass);
5408 /* No individual code points can now match */
5409 data->start_class->invlist
5410 = sv_2mortal(_new_invlist(0));
5413 int complement = namedclass + ((invert) ? -1 : 1);
5415 assert(flags & SCF_DO_STCLASS_OR);
5417 /* If the complement of this class was already there,
5418 * the result is that they match all code points,
5419 * (\d + \D == everything). Remove the classes from
5420 * future consideration. Locale is not relevant in
5422 if (ANYOF_POSIXL_TEST(data->start_class, complement)) {
5423 ssc_match_all_cp(data->start_class);
5424 ANYOF_POSIXL_CLEAR(data->start_class, namedclass);
5425 ANYOF_POSIXL_CLEAR(data->start_class, complement);
5427 else { /* The usual case; just add this class to the
5429 ANYOF_POSIXL_SET(data->start_class, namedclass);
5434 case NPOSIXA: /* For these, we always know the exact set of
5439 if (FLAGS(scan) == _CC_ASCII) {
5440 my_invlist = invlist_clone(PL_XPosix_ptrs[_CC_ASCII]);
5443 _invlist_intersection(PL_XPosix_ptrs[FLAGS(scan)],
5444 PL_XPosix_ptrs[_CC_ASCII],
5455 my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)]);
5457 /* NPOSIXD matches all upper Latin1 code points unless the
5458 * target string being matched is UTF-8, which is
5459 * unknowable until match time. Since we are going to
5460 * invert, we want to get rid of all of them so that the
5461 * inversion will match all */
5462 if (OP(scan) == NPOSIXD) {
5463 _invlist_subtract(my_invlist, PL_UpperLatin1,
5469 if (flags & SCF_DO_STCLASS_AND) {
5470 ssc_intersection(data->start_class, my_invlist, invert);
5471 ssc_clear_locale(data->start_class);
5474 assert(flags & SCF_DO_STCLASS_OR);
5475 ssc_union(data->start_class, my_invlist, invert);
5477 SvREFCNT_dec(my_invlist);
5479 if (flags & SCF_DO_STCLASS_OR)
5480 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5481 flags &= ~SCF_DO_STCLASS;
5484 else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
5485 data->flags |= (OP(scan) == MEOL
5488 scan_commit(pRExC_state, data, minlenp, is_inf);
5491 else if ( PL_regkind[OP(scan)] == BRANCHJ
5492 /* Lookbehind, or need to calculate parens/evals/stclass: */
5493 && (scan->flags || data || (flags & SCF_DO_STCLASS))
5494 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM))
5496 if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
5497 || OP(scan) == UNLESSM )
5499 /* Negative Lookahead/lookbehind
5500 In this case we can't do fixed string optimisation.
5503 SSize_t deltanext, minnext, fake = 0;
5508 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
5510 data_fake.whilem_c = data->whilem_c;
5511 data_fake.last_closep = data->last_closep;
5514 data_fake.last_closep = &fake;
5515 data_fake.pos_delta = delta;
5516 if ( flags & SCF_DO_STCLASS && !scan->flags
5517 && OP(scan) == IFMATCH ) { /* Lookahead */
5518 ssc_init(pRExC_state, &intrnl);
5519 data_fake.start_class = &intrnl;
5520 f |= SCF_DO_STCLASS_AND;
5522 if (flags & SCF_WHILEM_VISITED_POS)
5523 f |= SCF_WHILEM_VISITED_POS;
5524 next = regnext(scan);
5525 nscan = NEXTOPER(NEXTOPER(scan));
5526 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
5527 last, &data_fake, stopparen,
5528 recursed_depth, NULL, f, depth+1);
5531 FAIL("Variable length lookbehind not implemented");
5533 else if (minnext > (I32)U8_MAX) {
5534 FAIL2("Lookbehind longer than %"UVuf" not implemented",
5537 scan->flags = (U8)minnext;
5540 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
5542 if (data_fake.flags & SF_HAS_EVAL)
5543 data->flags |= SF_HAS_EVAL;
5544 data->whilem_c = data_fake.whilem_c;
5546 if (f & SCF_DO_STCLASS_AND) {
5547 if (flags & SCF_DO_STCLASS_OR) {
5548 /* OR before, AND after: ideally we would recurse with
5549 * data_fake to get the AND applied by study of the
5550 * remainder of the pattern, and then derecurse;
5551 * *** HACK *** for now just treat as "no information".
5552 * See [perl #56690].
5554 ssc_init(pRExC_state, data->start_class);
5556 /* AND before and after: combine and continue. These
5557 * assertions are zero-length, so can match an EMPTY
5559 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
5560 ANYOF_FLAGS(data->start_class)
5561 |= SSC_MATCHES_EMPTY_STRING;
5565 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
5567 /* Positive Lookahead/lookbehind
5568 In this case we can do fixed string optimisation,
5569 but we must be careful about it. Note in the case of
5570 lookbehind the positions will be offset by the minimum
5571 length of the pattern, something we won't know about
5572 until after the recurse.
5574 SSize_t deltanext, fake = 0;
5578 /* We use SAVEFREEPV so that when the full compile
5579 is finished perl will clean up the allocated
5580 minlens when it's all done. This way we don't
5581 have to worry about freeing them when we know
5582 they wont be used, which would be a pain.
5585 Newx( minnextp, 1, SSize_t );
5586 SAVEFREEPV(minnextp);
5589 StructCopy(data, &data_fake, scan_data_t);
5590 if ((flags & SCF_DO_SUBSTR) && data->last_found) {
5593 scan_commit(pRExC_state, &data_fake, minlenp, is_inf);
5594 data_fake.last_found=newSVsv(data->last_found);
5598 data_fake.last_closep = &fake;
5599 data_fake.flags = 0;
5600 data_fake.pos_delta = delta;
5602 data_fake.flags |= SF_IS_INF;
5603 if ( flags & SCF_DO_STCLASS && !scan->flags
5604 && OP(scan) == IFMATCH ) { /* Lookahead */
5605 ssc_init(pRExC_state, &intrnl);
5606 data_fake.start_class = &intrnl;
5607 f |= SCF_DO_STCLASS_AND;
5609 if (flags & SCF_WHILEM_VISITED_POS)
5610 f |= SCF_WHILEM_VISITED_POS;
5611 next = regnext(scan);
5612 nscan = NEXTOPER(NEXTOPER(scan));
5614 *minnextp = study_chunk(pRExC_state, &nscan, minnextp,
5615 &deltanext, last, &data_fake,
5616 stopparen, recursed_depth, NULL,
5620 FAIL("Variable length lookbehind not implemented");
5622 else if (*minnextp > (I32)U8_MAX) {
5623 FAIL2("Lookbehind longer than %"UVuf" not implemented",
5626 scan->flags = (U8)*minnextp;
5631 if (f & SCF_DO_STCLASS_AND) {
5632 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
5633 ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;
5636 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
5638 if (data_fake.flags & SF_HAS_EVAL)
5639 data->flags |= SF_HAS_EVAL;
5640 data->whilem_c = data_fake.whilem_c;
5641 if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
5642 if (RExC_rx->minlen<*minnextp)
5643 RExC_rx->minlen=*minnextp;
5644 scan_commit(pRExC_state, &data_fake, minnextp, is_inf);
5645 SvREFCNT_dec_NN(data_fake.last_found);
5647 if ( data_fake.minlen_fixed != minlenp )
5649 data->offset_fixed= data_fake.offset_fixed;
5650 data->minlen_fixed= data_fake.minlen_fixed;
5651 data->lookbehind_fixed+= scan->flags;
5653 if ( data_fake.minlen_float != minlenp )
5655 data->minlen_float= data_fake.minlen_float;
5656 data->offset_float_min=data_fake.offset_float_min;
5657 data->offset_float_max=data_fake.offset_float_max;
5658 data->lookbehind_float+= scan->flags;
5665 else if (OP(scan) == OPEN) {
5666 if (stopparen != (I32)ARG(scan))
5669 else if (OP(scan) == CLOSE) {
5670 if (stopparen == (I32)ARG(scan)) {
5673 if ((I32)ARG(scan) == is_par) {
5674 next = regnext(scan);
5676 if ( next && (OP(next) != WHILEM) && next < last)
5677 is_par = 0; /* Disable optimization */
5680 *(data->last_closep) = ARG(scan);
5682 else if (OP(scan) == EVAL) {
5684 data->flags |= SF_HAS_EVAL;
5686 else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
5687 if (flags & SCF_DO_SUBSTR) {
5688 scan_commit(pRExC_state, data, minlenp, is_inf);
5689 flags &= ~SCF_DO_SUBSTR;
5691 if (data && OP(scan)==ACCEPT) {
5692 data->flags |= SCF_SEEN_ACCEPT;
5697 else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
5699 if (flags & SCF_DO_SUBSTR) {
5700 scan_commit(pRExC_state, data, minlenp, is_inf);
5701 data->longest = &(data->longest_float);
5703 is_inf = is_inf_internal = 1;
5704 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5705 ssc_anything(data->start_class);
5706 flags &= ~SCF_DO_STCLASS;
5708 else if (OP(scan) == GPOS) {
5709 if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&
5710 !(delta || is_inf || (data && data->pos_delta)))
5712 if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))
5713 RExC_rx->intflags |= PREGf_ANCH_GPOS;
5714 if (RExC_rx->gofs < (STRLEN)min)
5715 RExC_rx->gofs = min;
5717 RExC_rx->intflags |= PREGf_GPOS_FLOAT;
5721 #ifdef TRIE_STUDY_OPT
5722 #ifdef FULL_TRIE_STUDY
5723 else if (PL_regkind[OP(scan)] == TRIE) {
5724 /* NOTE - There is similar code to this block above for handling
5725 BRANCH nodes on the initial study. If you change stuff here
5727 regnode *trie_node= scan;
5728 regnode *tail= regnext(scan);
5729 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
5730 SSize_t max1 = 0, min1 = SSize_t_MAX;
5733 if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */
5734 /* Cannot merge strings after this. */
5735 scan_commit(pRExC_state, data, minlenp, is_inf);
5737 if (flags & SCF_DO_STCLASS)
5738 ssc_init_zero(pRExC_state, &accum);
5744 const regnode *nextbranch= NULL;
5747 for ( word=1 ; word <= trie->wordcount ; word++)
5749 SSize_t deltanext=0, minnext=0, f = 0, fake;
5750 regnode_ssc this_class;
5752 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
5754 data_fake.whilem_c = data->whilem_c;
5755 data_fake.last_closep = data->last_closep;
5758 data_fake.last_closep = &fake;
5759 data_fake.pos_delta = delta;
5760 if (flags & SCF_DO_STCLASS) {
5761 ssc_init(pRExC_state, &this_class);
5762 data_fake.start_class = &this_class;
5763 f = SCF_DO_STCLASS_AND;
5765 if (flags & SCF_WHILEM_VISITED_POS)
5766 f |= SCF_WHILEM_VISITED_POS;
5768 if (trie->jump[word]) {
5770 nextbranch = trie_node + trie->jump[0];
5771 scan= trie_node + trie->jump[word];
5772 /* We go from the jump point to the branch that follows
5773 it. Note this means we need the vestigal unused
5774 branches even though they arent otherwise used. */
5775 minnext = study_chunk(pRExC_state, &scan, minlenp,
5776 &deltanext, (regnode *)nextbranch, &data_fake,
5777 stopparen, recursed_depth, NULL, f,depth+1);
5779 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
5780 nextbranch= regnext((regnode*)nextbranch);
5782 if (min1 > (SSize_t)(minnext + trie->minlen))
5783 min1 = minnext + trie->minlen;
5784 if (deltanext == SSize_t_MAX) {
5785 is_inf = is_inf_internal = 1;
5787 } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))
5788 max1 = minnext + deltanext + trie->maxlen;
5790 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
5792 if (data_fake.flags & SCF_SEEN_ACCEPT) {
5793 if ( stopmin > min + min1)
5794 stopmin = min + min1;
5795 flags &= ~SCF_DO_SUBSTR;
5797 data->flags |= SCF_SEEN_ACCEPT;
5800 if (data_fake.flags & SF_HAS_EVAL)
5801 data->flags |= SF_HAS_EVAL;
5802 data->whilem_c = data_fake.whilem_c;
5804 if (flags & SCF_DO_STCLASS)
5805 ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);
5808 if (flags & SCF_DO_SUBSTR) {
5809 data->pos_min += min1;
5810 data->pos_delta += max1 - min1;
5811 if (max1 != min1 || is_inf)
5812 data->longest = &(data->longest_float);
5815 if (delta != SSize_t_MAX)
5816 delta += max1 - min1;
5817 if (flags & SCF_DO_STCLASS_OR) {
5818 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);
5820 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5821 flags &= ~SCF_DO_STCLASS;
5824 else if (flags & SCF_DO_STCLASS_AND) {
5826 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
5827 flags &= ~SCF_DO_STCLASS;
5830 /* Switch to OR mode: cache the old value of
5831 * data->start_class */
5833 StructCopy(data->start_class, and_withp, regnode_ssc);
5834 flags &= ~SCF_DO_STCLASS_AND;
5835 StructCopy(&accum, data->start_class, regnode_ssc);
5836 flags |= SCF_DO_STCLASS_OR;
5843 else if (PL_regkind[OP(scan)] == TRIE) {
5844 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
5847 min += trie->minlen;
5848 delta += (trie->maxlen - trie->minlen);
5849 flags &= ~SCF_DO_STCLASS; /* xxx */
5850 if (flags & SCF_DO_SUBSTR) {
5851 /* Cannot expect anything... */
5852 scan_commit(pRExC_state, data, minlenp, is_inf);
5853 data->pos_min += trie->minlen;
5854 data->pos_delta += (trie->maxlen - trie->minlen);
5855 if (trie->maxlen != trie->minlen)
5856 data->longest = &(data->longest_float);
5858 if (trie->jump) /* no more substrings -- for now /grr*/
5859 flags &= ~SCF_DO_SUBSTR;
5861 #endif /* old or new */
5862 #endif /* TRIE_STUDY_OPT */
5864 /* Else: zero-length, ignore. */
5865 scan = regnext(scan);
5867 /* If we are exiting a recursion we can unset its recursed bit
5868 * and allow ourselves to enter it again - no danger of an
5869 * infinite loop there.
5870 if (stopparen > -1 && recursed) {
5871 DEBUG_STUDYDATA("unset:", data,depth);
5872 PAREN_UNSET( recursed, stopparen);
5878 DEBUG_STUDYDATA("frame-end:",data,depth);
5879 DEBUG_PEEP("fend", scan, depth);
5881 /* restore previous context */
5882 last = frame->last_regnode;
5883 scan = frame->next_regnode;
5884 stopparen = frame->stopparen;
5885 recursed_depth = frame->prev_recursed_depth;
5887 RExC_frame_last = frame->prev_frame;
5888 frame = frame->this_prev_frame;
5889 goto fake_study_recurse;
5894 DEBUG_STUDYDATA("pre-fin:",data,depth);
5897 *deltap = is_inf_internal ? SSize_t_MAX : delta;
5899 if (flags & SCF_DO_SUBSTR && is_inf)
5900 data->pos_delta = SSize_t_MAX - data->pos_min;
5901 if (is_par > (I32)U8_MAX)
5903 if (is_par && pars==1 && data) {
5904 data->flags |= SF_IN_PAR;
5905 data->flags &= ~SF_HAS_PAR;
5907 else if (pars && data) {
5908 data->flags |= SF_HAS_PAR;
5909 data->flags &= ~SF_IN_PAR;
5911 if (flags & SCF_DO_STCLASS_OR)
5912 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5913 if (flags & SCF_TRIE_RESTUDY)
5914 data->flags |= SCF_TRIE_RESTUDY;
5916 DEBUG_STUDYDATA("post-fin:",data,depth);
5919 SSize_t final_minlen= min < stopmin ? min : stopmin;
5921 if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {
5922 if (final_minlen > SSize_t_MAX - delta)
5923 RExC_maxlen = SSize_t_MAX;
5924 else if (RExC_maxlen < final_minlen + delta)
5925 RExC_maxlen = final_minlen + delta;
5927 return final_minlen;
5929 NOT_REACHED; /* NOTREACHED */
5933 S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n)
5935 U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
5937 PERL_ARGS_ASSERT_ADD_DATA;
5939 Renewc(RExC_rxi->data,
5940 sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
5941 char, struct reg_data);
5943 Renew(RExC_rxi->data->what, count + n, U8);
5945 Newx(RExC_rxi->data->what, n, U8);
5946 RExC_rxi->data->count = count + n;
5947 Copy(s, RExC_rxi->data->what + count, n, U8);
5951 /*XXX: todo make this not included in a non debugging perl, but appears to be
5952 * used anyway there, in 'use re' */
5953 #ifndef PERL_IN_XSUB_RE
5955 Perl_reginitcolors(pTHX)
5957 const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
5959 char *t = savepv(s);
5963 t = strchr(t, '\t');
5969 PL_colors[i] = t = (char *)"";
5974 PL_colors[i++] = (char *)"";
5981 #ifdef TRIE_STUDY_OPT
5982 #define CHECK_RESTUDY_GOTO_butfirst(dOsomething) \
5985 (data.flags & SCF_TRIE_RESTUDY) \
5993 #define CHECK_RESTUDY_GOTO_butfirst
5997 * pregcomp - compile a regular expression into internal code
5999 * Decides which engine's compiler to call based on the hint currently in
6003 #ifndef PERL_IN_XSUB_RE
6005 /* return the currently in-scope regex engine (or the default if none) */
6007 regexp_engine const *
6008 Perl_current_re_engine(pTHX)
6010 if (IN_PERL_COMPILETIME) {
6011 HV * const table = GvHV(PL_hintgv);
6014 if (!table || !(PL_hints & HINT_LOCALIZE_HH))
6015 return &PL_core_reg_engine;
6016 ptr = hv_fetchs(table, "regcomp", FALSE);
6017 if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
6018 return &PL_core_reg_engine;
6019 return INT2PTR(regexp_engine*,SvIV(*ptr));
6023 if (!PL_curcop->cop_hints_hash)
6024 return &PL_core_reg_engine;
6025 ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
6026 if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
6027 return &PL_core_reg_engine;
6028 return INT2PTR(regexp_engine*,SvIV(ptr));
6034 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
6036 regexp_engine const *eng = current_re_engine();
6037 GET_RE_DEBUG_FLAGS_DECL;
6039 PERL_ARGS_ASSERT_PREGCOMP;
6041 /* Dispatch a request to compile a regexp to correct regexp engine. */
6043 PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
6046 return CALLREGCOMP_ENG(eng, pattern, flags);
6050 /* public(ish) entry point for the perl core's own regex compiling code.
6051 * It's actually a wrapper for Perl_re_op_compile that only takes an SV
6052 * pattern rather than a list of OPs, and uses the internal engine rather
6053 * than the current one */
6056 Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
6058 SV *pat = pattern; /* defeat constness! */
6059 PERL_ARGS_ASSERT_RE_COMPILE;
6060 return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
6061 #ifdef PERL_IN_XSUB_RE
6064 &PL_core_reg_engine,
6066 NULL, NULL, rx_flags, 0);
6070 /* upgrade pattern pat_p of length plen_p to UTF8, and if there are code
6071 * blocks, recalculate the indices. Update pat_p and plen_p in-place to
6072 * point to the realloced string and length.
6074 * This is essentially a copy of Perl_bytes_to_utf8() with the code index
6078 S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state,
6079 char **pat_p, STRLEN *plen_p, int num_code_blocks)
6081 U8 *const src = (U8*)*pat_p;
6086 GET_RE_DEBUG_FLAGS_DECL;
6088 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
6089 "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
6091 Newx(dst, *plen_p * 2 + 1, U8);
6094 while (s < *plen_p) {
6095 append_utf8_from_native_byte(src[s], &d);
6096 if (n < num_code_blocks) {
6097 if (!do_end && pRExC_state->code_blocks[n].start == s) {
6098 pRExC_state->code_blocks[n].start = d - dst - 1;
6099 assert(*(d - 1) == '(');
6102 else if (do_end && pRExC_state->code_blocks[n].end == s) {
6103 pRExC_state->code_blocks[n].end = d - dst - 1;
6104 assert(*(d - 1) == ')');
6113 *pat_p = (char*) dst;
6115 RExC_orig_utf8 = RExC_utf8 = 1;
6120 /* S_concat_pat(): concatenate a list of args to the pattern string pat,
6121 * while recording any code block indices, and handling overloading,
6122 * nested qr// objects etc. If pat is null, it will allocate a new
6123 * string, or just return the first arg, if there's only one.
6125 * Returns the malloced/updated pat.
6126 * patternp and pat_count is the array of SVs to be concatted;
6127 * oplist is the optional list of ops that generated the SVs;
6128 * recompile_p is a pointer to a boolean that will be set if
6129 * the regex will need to be recompiled.
6130 * delim, if non-null is an SV that will be inserted between each element
6134 S_concat_pat(pTHX_ RExC_state_t * const pRExC_state,
6135 SV *pat, SV ** const patternp, int pat_count,
6136 OP *oplist, bool *recompile_p, SV *delim)
6140 bool use_delim = FALSE;
6141 bool alloced = FALSE;
6143 /* if we know we have at least two args, create an empty string,
6144 * then concatenate args to that. For no args, return an empty string */
6145 if (!pat && pat_count != 1) {
6151 for (svp = patternp; svp < patternp + pat_count; svp++) {
6154 STRLEN orig_patlen = 0;
6156 SV *msv = use_delim ? delim : *svp;
6157 if (!msv) msv = &PL_sv_undef;
6159 /* if we've got a delimiter, we go round the loop twice for each
6160 * svp slot (except the last), using the delimiter the second
6169 if (SvTYPE(msv) == SVt_PVAV) {
6170 /* we've encountered an interpolated array within
6171 * the pattern, e.g. /...@a..../. Expand the list of elements,
6172 * then recursively append elements.
6173 * The code in this block is based on S_pushav() */
6175 AV *const av = (AV*)msv;
6176 const SSize_t maxarg = AvFILL(av) + 1;
6180 assert(oplist->op_type == OP_PADAV
6181 || oplist->op_type == OP_RV2AV);
6182 oplist = OpSIBLING(oplist);
6185 if (SvRMAGICAL(av)) {
6188 Newx(array, maxarg, SV*);
6190 for (i=0; i < maxarg; i++) {
6191 SV ** const svp = av_fetch(av, i, FALSE);
6192 array[i] = svp ? *svp : &PL_sv_undef;
6196 array = AvARRAY(av);
6198 pat = S_concat_pat(aTHX_ pRExC_state, pat,
6199 array, maxarg, NULL, recompile_p,
6201 GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV))));
6207 /* we make the assumption here that each op in the list of
6208 * op_siblings maps to one SV pushed onto the stack,
6209 * except for code blocks, with have both an OP_NULL and
6211 * This allows us to match up the list of SVs against the
6212 * list of OPs to find the next code block.
6214 * Note that PUSHMARK PADSV PADSV ..
6216 * PADRANGE PADSV PADSV ..
6217 * so the alignment still works. */
6220 if (oplist->op_type == OP_NULL
6221 && (oplist->op_flags & OPf_SPECIAL))
6223 assert(n < pRExC_state->num_code_blocks);
6224 pRExC_state->code_blocks[n].start = pat ? SvCUR(pat) : 0;
6225 pRExC_state->code_blocks[n].block = oplist;
6226 pRExC_state->code_blocks[n].src_regex = NULL;
6229 oplist = OpSIBLING(oplist); /* skip CONST */
6232 oplist = OpSIBLING(oplist);;
6235 /* apply magic and QR overloading to arg */
6238 if (SvROK(msv) && SvAMAGIC(msv)) {
6239 SV *sv = AMG_CALLunary(msv, regexp_amg);
6243 if (SvTYPE(sv) != SVt_REGEXP)
6244 Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
6249 /* try concatenation overload ... */
6250 if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) &&
6251 (sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
6254 /* overloading involved: all bets are off over literal
6255 * code. Pretend we haven't seen it */
6256 pRExC_state->num_code_blocks -= n;
6260 /* ... or failing that, try "" overload */
6261 while (SvAMAGIC(msv)
6262 && (sv = AMG_CALLunary(msv, string_amg))
6266 && SvRV(msv) == SvRV(sv))
6271 if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
6275 /* this is a partially unrolled
6276 * sv_catsv_nomg(pat, msv);
6277 * that allows us to adjust code block indices if
6280 char *dst = SvPV_force_nomg(pat, dlen);
6282 if (SvUTF8(msv) && !SvUTF8(pat)) {
6283 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n);
6284 sv_setpvn(pat, dst, dlen);
6287 sv_catsv_nomg(pat, msv);
6294 pRExC_state->code_blocks[n-1].end = SvCUR(pat)-1;
6297 /* extract any code blocks within any embedded qr//'s */
6298 if (rx && SvTYPE(rx) == SVt_REGEXP
6299 && RX_ENGINE((REGEXP*)rx)->op_comp)
6302 RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
6303 if (ri->num_code_blocks) {
6305 /* the presence of an embedded qr// with code means
6306 * we should always recompile: the text of the
6307 * qr// may not have changed, but it may be a
6308 * different closure than last time */
6310 Renew(pRExC_state->code_blocks,
6311 pRExC_state->num_code_blocks + ri->num_code_blocks,
6312 struct reg_code_block);
6313 pRExC_state->num_code_blocks += ri->num_code_blocks;
6315 for (i=0; i < ri->num_code_blocks; i++) {
6316 struct reg_code_block *src, *dst;
6317 STRLEN offset = orig_patlen
6318 + ReANY((REGEXP *)rx)->pre_prefix;
6319 assert(n < pRExC_state->num_code_blocks);
6320 src = &ri->code_blocks[i];
6321 dst = &pRExC_state->code_blocks[n];
6322 dst->start = src->start + offset;
6323 dst->end = src->end + offset;
6324 dst->block = src->block;
6325 dst->src_regex = (REGEXP*) SvREFCNT_inc( (SV*)
6334 /* avoid calling magic multiple times on a single element e.g. =~ $qr */
6343 /* see if there are any run-time code blocks in the pattern.
6344 * False positives are allowed */
6347 S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
6348 char *pat, STRLEN plen)
6353 PERL_UNUSED_CONTEXT;
6355 for (s = 0; s < plen; s++) {
6356 if (n < pRExC_state->num_code_blocks
6357 && s == pRExC_state->code_blocks[n].start)
6359 s = pRExC_state->code_blocks[n].end;
6363 /* TODO ideally should handle [..], (#..), /#.../x to reduce false
6365 if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' &&
6367 || (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{'))
6374 /* Handle run-time code blocks. We will already have compiled any direct
6375 * or indirect literal code blocks. Now, take the pattern 'pat' and make a
6376 * copy of it, but with any literal code blocks blanked out and
6377 * appropriate chars escaped; then feed it into
6379 * eval "qr'modified_pattern'"
6383 * a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
6387 * qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
6389 * After eval_sv()-ing that, grab any new code blocks from the returned qr
6390 * and merge them with any code blocks of the original regexp.
6392 * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
6393 * instead, just save the qr and return FALSE; this tells our caller that
6394 * the original pattern needs upgrading to utf8.
6398 S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
6399 char *pat, STRLEN plen)
6403 GET_RE_DEBUG_FLAGS_DECL;
6405 if (pRExC_state->runtime_code_qr) {
6406 /* this is the second time we've been called; this should
6407 * only happen if the main pattern got upgraded to utf8
6408 * during compilation; re-use the qr we compiled first time
6409 * round (which should be utf8 too)
6411 qr = pRExC_state->runtime_code_qr;
6412 pRExC_state->runtime_code_qr = NULL;
6413 assert(RExC_utf8 && SvUTF8(qr));
6419 int newlen = plen + 6; /* allow for "qr''x\0" extra chars */
6423 /* determine how many extra chars we need for ' and \ escaping */
6424 for (s = 0; s < plen; s++) {
6425 if (pat[s] == '\'' || pat[s] == '\\')
6429 Newx(newpat, newlen, char);
6431 *p++ = 'q'; *p++ = 'r'; *p++ = '\'';
6433 for (s = 0; s < plen; s++) {
6434 if (n < pRExC_state->num_code_blocks
6435 && s == pRExC_state->code_blocks[n].start)
6437 /* blank out literal code block */
6438 assert(pat[s] == '(');
6439 while (s <= pRExC_state->code_blocks[n].end) {
6447 if (pat[s] == '\'' || pat[s] == '\\')
6452 if (pRExC_state->pm_flags & RXf_PMf_EXTENDED)
6456 PerlIO_printf(Perl_debug_log,
6457 "%sre-parsing pattern for runtime code:%s %s\n",
6458 PL_colors[4],PL_colors[5],newpat);
6461 sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
6467 PUSHSTACKi(PERLSI_REQUIRE);
6468 /* G_RE_REPARSING causes the toker to collapse \\ into \ when
6469 * parsing qr''; normally only q'' does this. It also alters
6471 eval_sv(sv, G_SCALAR|G_RE_REPARSING);
6472 SvREFCNT_dec_NN(sv);
6477 SV * const errsv = ERRSV;
6478 if (SvTRUE_NN(errsv))
6480 Safefree(pRExC_state->code_blocks);
6481 /* use croak_sv ? */
6482 Perl_croak_nocontext("%"SVf, SVfARG(errsv));
6485 assert(SvROK(qr_ref));
6487 assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
6488 /* the leaving below frees the tmp qr_ref.
6489 * Give qr a life of its own */
6497 if (!RExC_utf8 && SvUTF8(qr)) {
6498 /* first time through; the pattern got upgraded; save the
6499 * qr for the next time through */
6500 assert(!pRExC_state->runtime_code_qr);
6501 pRExC_state->runtime_code_qr = qr;
6506 /* extract any code blocks within the returned qr// */
6509 /* merge the main (r1) and run-time (r2) code blocks into one */
6511 RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
6512 struct reg_code_block *new_block, *dst;
6513 RExC_state_t * const r1 = pRExC_state; /* convenient alias */
6516 if (!r2->num_code_blocks) /* we guessed wrong */
6518 SvREFCNT_dec_NN(qr);
6523 r1->num_code_blocks + r2->num_code_blocks,
6524 struct reg_code_block);
6527 while ( i1 < r1->num_code_blocks
6528 || i2 < r2->num_code_blocks)
6530 struct reg_code_block *src;
6533 if (i1 == r1->num_code_blocks) {
6534 src = &r2->code_blocks[i2++];
6537 else if (i2 == r2->num_code_blocks)
6538 src = &r1->code_blocks[i1++];
6539 else if ( r1->code_blocks[i1].start
6540 < r2->code_blocks[i2].start)
6542 src = &r1->code_blocks[i1++];
6543 assert(src->end < r2->code_blocks[i2].start);
6546 assert( r1->code_blocks[i1].start
6547 > r2->code_blocks[i2].start);
6548 src = &r2->code_blocks[i2++];
6550 assert(src->end < r1->code_blocks[i1].start);
6553 assert(pat[src->start] == '(');
6554 assert(pat[src->end] == ')');
6555 dst->start = src->start;
6556 dst->end = src->end;
6557 dst->block = src->block;
6558 dst->src_regex = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
6562 r1->num_code_blocks += r2->num_code_blocks;
6563 Safefree(r1->code_blocks);
6564 r1->code_blocks = new_block;
6567 SvREFCNT_dec_NN(qr);
6573 S_setup_longest(pTHX_ RExC_state_t *pRExC_state, SV* sv_longest,
6574 SV** rx_utf8, SV** rx_substr, SSize_t* rx_end_shift,
6575 SSize_t lookbehind, SSize_t offset, SSize_t *minlen,
6576 STRLEN longest_length, bool eol, bool meol)
6578 /* This is the common code for setting up the floating and fixed length
6579 * string data extracted from Perl_re_op_compile() below. Returns a boolean
6580 * as to whether succeeded or not */
6585 if (! (longest_length
6586 || (eol /* Can't have SEOL and MULTI */
6587 && (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
6589 /* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */
6590 || (RExC_seen & REG_UNFOLDED_MULTI_SEEN))
6595 /* copy the information about the longest from the reg_scan_data
6596 over to the program. */
6597 if (SvUTF8(sv_longest)) {
6598 *rx_utf8 = sv_longest;
6601 *rx_substr = sv_longest;
6604 /* end_shift is how many chars that must be matched that
6605 follow this item. We calculate it ahead of time as once the
6606 lookbehind offset is added in we lose the ability to correctly
6608 ml = minlen ? *(minlen) : (SSize_t)longest_length;
6609 *rx_end_shift = ml - offset
6610 - longest_length + (SvTAIL(sv_longest) != 0)
6613 t = (eol/* Can't have SEOL and MULTI */
6614 && (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
6615 fbm_compile(sv_longest, t ? FBMcf_TAIL : 0);
6621 * Perl_re_op_compile - the perl internal RE engine's function to compile a
6622 * regular expression into internal code.
6623 * The pattern may be passed either as:
6624 * a list of SVs (patternp plus pat_count)
6625 * a list of OPs (expr)
6626 * If both are passed, the SV list is used, but the OP list indicates
6627 * which SVs are actually pre-compiled code blocks
6629 * The SVs in the list have magic and qr overloading applied to them (and
6630 * the list may be modified in-place with replacement SVs in the latter
6633 * If the pattern hasn't changed from old_re, then old_re will be
6636 * eng is the current engine. If that engine has an op_comp method, then
6637 * handle directly (i.e. we assume that op_comp was us); otherwise, just
6638 * do the initial concatenation of arguments and pass on to the external
6641 * If is_bare_re is not null, set it to a boolean indicating whether the
6642 * arg list reduced (after overloading) to a single bare regex which has
6643 * been returned (i.e. /$qr/).
6645 * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
6647 * pm_flags contains the PMf_* flags, typically based on those from the
6648 * pm_flags field of the related PMOP. Currently we're only interested in
6649 * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL.
6651 * We can't allocate space until we know how big the compiled form will be,
6652 * but we can't compile it (and thus know how big it is) until we've got a
6653 * place to put the code. So we cheat: we compile it twice, once with code
6654 * generation turned off and size counting turned on, and once "for real".
6655 * This also means that we don't allocate space until we are sure that the
6656 * thing really will compile successfully, and we never have to move the
6657 * code and thus invalidate pointers into it. (Note that it has to be in
6658 * one piece because free() must be able to free it all.) [NB: not true in perl]
6660 * Beware that the optimization-preparation code in here knows about some
6661 * of the structure of the compiled regexp. [I'll say.]
6665 Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
6666 OP *expr, const regexp_engine* eng, REGEXP *old_re,
6667 bool *is_bare_re, U32 orig_rx_flags, U32 pm_flags)
6671 regexp_internal *ri;
6679 SV *code_blocksv = NULL;
6680 SV** new_patternp = patternp;
6682 /* these are all flags - maybe they should be turned
6683 * into a single int with different bit masks */
6684 I32 sawlookahead = 0;
6689 regex_charset initial_charset = get_regex_charset(orig_rx_flags);
6691 bool runtime_code = 0;
6693 RExC_state_t RExC_state;
6694 RExC_state_t * const pRExC_state = &RExC_state;
6695 #ifdef TRIE_STUDY_OPT
6697 RExC_state_t copyRExC_state;
6699 GET_RE_DEBUG_FLAGS_DECL;
6701 PERL_ARGS_ASSERT_RE_OP_COMPILE;
6703 DEBUG_r(if (!PL_colorset) reginitcolors());
6705 /* Initialize these here instead of as-needed, as is quick and avoids
6706 * having to test them each time otherwise */
6707 if (! PL_AboveLatin1) {
6708 PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
6709 PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
6710 PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist);
6711 PL_utf8_foldable = _new_invlist_C_array(_Perl_Any_Folds_invlist);
6712 PL_HasMultiCharFold =
6713 _new_invlist_C_array(_Perl_Folds_To_Multi_Char_invlist);
6715 /* This is calculated here, because the Perl program that generates the
6716 * static global ones doesn't currently have access to
6717 * NUM_ANYOF_CODE_POINTS */
6718 PL_InBitmap = _new_invlist(2);
6719 PL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0,
6720 NUM_ANYOF_CODE_POINTS - 1);
6723 pRExC_state->code_blocks = NULL;
6724 pRExC_state->num_code_blocks = 0;
6727 *is_bare_re = FALSE;
6729 if (expr && (expr->op_type == OP_LIST ||
6730 (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
6731 /* allocate code_blocks if needed */
6735 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o))
6736 if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
6737 ncode++; /* count of DO blocks */
6739 pRExC_state->num_code_blocks = ncode;
6740 Newx(pRExC_state->code_blocks, ncode, struct reg_code_block);
6745 /* compile-time pattern with just OP_CONSTs and DO blocks */
6750 /* find how many CONSTs there are */
6753 if (expr->op_type == OP_CONST)
6756 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
6757 if (o->op_type == OP_CONST)
6761 /* fake up an SV array */
6763 assert(!new_patternp);
6764 Newx(new_patternp, n, SV*);
6765 SAVEFREEPV(new_patternp);
6769 if (expr->op_type == OP_CONST)
6770 new_patternp[n] = cSVOPx_sv(expr);
6772 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
6773 if (o->op_type == OP_CONST)
6774 new_patternp[n++] = cSVOPo_sv;
6779 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
6780 "Assembling pattern from %d elements%s\n", pat_count,
6781 orig_rx_flags & RXf_SPLIT ? " for split" : ""));
6783 /* set expr to the first arg op */
6785 if (pRExC_state->num_code_blocks
6786 && expr->op_type != OP_CONST)
6788 expr = cLISTOPx(expr)->op_first;
6789 assert( expr->op_type == OP_PUSHMARK
6790 || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)
6791 || expr->op_type == OP_PADRANGE);
6792 expr = OpSIBLING(expr);
6795 pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,
6796 expr, &recompile, NULL);
6798 /* handle bare (possibly after overloading) regex: foo =~ $re */
6803 if (SvTYPE(re) == SVt_REGEXP) {
6807 Safefree(pRExC_state->code_blocks);
6808 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
6809 "Precompiled pattern%s\n",
6810 orig_rx_flags & RXf_SPLIT ? " for split" : ""));
6816 exp = SvPV_nomg(pat, plen);
6818 if (!eng->op_comp) {
6819 if ((SvUTF8(pat) && IN_BYTES)
6820 || SvGMAGICAL(pat) || SvAMAGIC(pat))
6822 /* make a temporary copy; either to convert to bytes,
6823 * or to avoid repeating get-magic / overloaded stringify */
6824 pat = newSVpvn_flags(exp, plen, SVs_TEMP |
6825 (IN_BYTES ? 0 : SvUTF8(pat)));
6827 Safefree(pRExC_state->code_blocks);
6828 return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
6831 /* ignore the utf8ness if the pattern is 0 length */
6832 RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
6834 RExC_uni_semantics = 0;
6835 RExC_seen_unfolded_sharp_s = 0;
6836 RExC_contains_locale = 0;
6837 RExC_contains_i = 0;
6838 RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT);
6839 pRExC_state->runtime_code_qr = NULL;
6840 RExC_frame_head= NULL;
6841 RExC_frame_last= NULL;
6842 RExC_frame_count= 0;
6845 RExC_mysv1= sv_newmortal();
6846 RExC_mysv2= sv_newmortal();
6849 SV *dsv= sv_newmortal();
6850 RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, 60);
6851 PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
6852 PL_colors[4],PL_colors[5],s);
6856 /* we jump here if we have to recompile, e.g., from upgrading the pattern
6859 if ((pm_flags & PMf_USE_RE_EVAL)
6860 /* this second condition covers the non-regex literal case,
6861 * i.e. $foo =~ '(?{})'. */
6862 || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))
6864 runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);
6866 /* return old regex if pattern hasn't changed */
6867 /* XXX: note in the below we have to check the flags as well as the
6870 * Things get a touch tricky as we have to compare the utf8 flag
6871 * independently from the compile flags. */
6875 && !!RX_UTF8(old_re) == !!RExC_utf8
6876 && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )
6877 && RX_PRECOMP(old_re)
6878 && RX_PRELEN(old_re) == plen
6879 && memEQ(RX_PRECOMP(old_re), exp, plen)
6880 && !runtime_code /* with runtime code, always recompile */ )
6882 Safefree(pRExC_state->code_blocks);
6886 rx_flags = orig_rx_flags;
6888 if (rx_flags & PMf_FOLD) {
6889 RExC_contains_i = 1;
6891 if ( initial_charset == REGEX_DEPENDS_CHARSET
6892 && (RExC_utf8 ||RExC_uni_semantics))
6895 /* Set to use unicode semantics if the pattern is in utf8 and has the
6896 * 'depends' charset specified, as it means unicode when utf8 */
6897 set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
6901 RExC_precomp_adj = 0;
6902 RExC_flags = rx_flags;
6903 RExC_pm_flags = pm_flags;
6906 assert(TAINTING_get || !TAINT_get);
6908 Perl_croak(aTHX_ "Eval-group in insecure regular expression");
6910 if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
6911 /* whoops, we have a non-utf8 pattern, whilst run-time code
6912 * got compiled as utf8. Try again with a utf8 pattern */
6913 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
6914 pRExC_state->num_code_blocks);
6915 goto redo_first_pass;
6918 assert(!pRExC_state->runtime_code_qr);
6924 RExC_in_lookbehind = 0;
6925 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
6927 RExC_override_recoding = 0;
6929 RExC_recode_x_to_native = 0;
6931 RExC_in_multi_char_class = 0;
6933 /* First pass: determine size, legality. */
6935 RExC_start = RExC_adjusted_start = exp;
6936 RExC_end = exp + plen;
6937 RExC_precomp_end = RExC_end;
6942 RExC_emit = (regnode *) &RExC_emit_dummy;
6943 RExC_whilem_seen = 0;
6944 RExC_open_parens = NULL;
6945 RExC_close_parens = NULL;
6947 RExC_paren_names = NULL;
6949 RExC_paren_name_list = NULL;
6951 RExC_recurse = NULL;
6952 RExC_study_chunk_recursed = NULL;
6953 RExC_study_chunk_recursed_bytes= 0;
6954 RExC_recurse_count = 0;
6955 pRExC_state->code_index = 0;
6957 /* This NUL is guaranteed because the pattern comes from an SV*, and the sv
6958 * code makes sure the final byte is an uncounted NUL. But should this
6959 * ever not be the case, lots of things could read beyond the end of the
6960 * buffer: loops like
6961 * while(isFOO(*RExC_parse)) RExC_parse++;
6962 * strchr(RExC_parse, "foo");
6963 * etc. So it is worth noting. */
6964 assert(*RExC_end == '\0');
6967 PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n");
6969 RExC_lastparse=NULL;
6971 /* reg may croak on us, not giving us a chance to free
6972 pRExC_state->code_blocks. We cannot SAVEFREEPV it now, as we may
6973 need it to survive as long as the regexp (qr/(?{})/).
6974 We must check that code_blocksv is not already set, because we may
6975 have jumped back to restart the sizing pass. */
6976 if (pRExC_state->code_blocks && !code_blocksv) {
6977 code_blocksv = newSV_type(SVt_PV);
6978 SAVEFREESV(code_blocksv);
6979 SvPV_set(code_blocksv, (char *)pRExC_state->code_blocks);
6980 SvLEN_set(code_blocksv, 1); /*sufficient to make sv_clear free it*/
6982 if (reg(pRExC_state, 0, &flags,1) == NULL) {
6983 /* It's possible to write a regexp in ascii that represents Unicode
6984 codepoints outside of the byte range, such as via \x{100}. If we
6985 detect such a sequence we have to convert the entire pattern to utf8
6986 and then recompile, as our sizing calculation will have been based
6987 on 1 byte == 1 character, but we will need to use utf8 to encode
6988 at least some part of the pattern, and therefore must convert the whole
6991 if (flags & RESTART_PASS1) {
6992 if (flags & NEED_UTF8) {
6993 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
6994 pRExC_state->num_code_blocks);
6997 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
6998 "Need to redo pass 1\n"));
7001 goto redo_first_pass;
7003 Perl_croak(aTHX_ "panic: reg returned NULL to re_op_compile for sizing pass, flags=%#"UVxf"", (UV) flags);
7006 SvLEN_set(code_blocksv,0); /* no you can't have it, sv_clear */
7009 PerlIO_printf(Perl_debug_log,
7010 "Required size %"IVdf" nodes\n"
7011 "Starting second pass (creation)\n",
7014 RExC_lastparse=NULL;
7017 /* The first pass could have found things that force Unicode semantics */
7018 if ((RExC_utf8 || RExC_uni_semantics)
7019 && get_regex_charset(rx_flags) == REGEX_DEPENDS_CHARSET)
7021 set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
7024 /* Small enough for pointer-storage convention?
7025 If extralen==0, this means that we will not need long jumps. */
7026 if (RExC_size >= 0x10000L && RExC_extralen)
7027 RExC_size += RExC_extralen;
7030 if (RExC_whilem_seen > 15)
7031 RExC_whilem_seen = 15;
7033 /* Allocate space and zero-initialize. Note, the two step process
7034 of zeroing when in debug mode, thus anything assigned has to
7035 happen after that */
7036 rx = (REGEXP*) newSV_type(SVt_REGEXP);
7038 Newxc(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
7039 char, regexp_internal);
7040 if ( r == NULL || ri == NULL )
7041 FAIL("Regexp out of space");
7043 /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
7044 Zero(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
7047 /* bulk initialize base fields with 0. */
7048 Zero(ri, sizeof(regexp_internal), char);
7051 /* non-zero initialization begins here */
7054 r->extflags = rx_flags;
7055 RXp_COMPFLAGS(r) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;
7057 if (pm_flags & PMf_IS_QR) {
7058 ri->code_blocks = pRExC_state->code_blocks;
7059 ri->num_code_blocks = pRExC_state->num_code_blocks;
7064 for (n = 0; n < pRExC_state->num_code_blocks; n++)
7065 if (pRExC_state->code_blocks[n].src_regex)
7066 SAVEFREESV(pRExC_state->code_blocks[n].src_regex);
7067 if(pRExC_state->code_blocks)
7068 SAVEFREEPV(pRExC_state->code_blocks); /* often null */
7072 bool has_p = ((r->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
7073 bool has_charset = (get_regex_charset(r->extflags)
7074 != REGEX_DEPENDS_CHARSET);
7076 /* The caret is output if there are any defaults: if not all the STD
7077 * flags are set, or if no character set specifier is needed */
7079 (((r->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
7081 bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN)
7082 == REG_RUN_ON_COMMENT_SEEN);
7083 U8 reganch = (U8)((r->extflags & RXf_PMf_STD_PMMOD)
7084 >> RXf_PMf_STD_PMMOD_SHIFT);
7085 const char *fptr = STD_PAT_MODS; /*"msixn"*/
7088 /* We output all the necessary flags; we never output a minus, as all
7089 * those are defaults, so are
7090 * covered by the caret */
7091 const STRLEN wraplen = plen + has_p + has_runon
7092 + has_default /* If needs a caret */
7093 + PL_bitcount[reganch] /* 1 char for each set standard flag */
7095 /* If needs a character set specifier */
7096 + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
7097 + (sizeof("(?:)") - 1);
7099 /* make sure PL_bitcount bounds not exceeded */
7100 assert(sizeof(STD_PAT_MODS) <= 8);
7102 Newx(p, wraplen + 1, char); /* +1 for the ending NUL */
7103 r->xpv_len_u.xpvlenu_pv = p;
7105 SvFLAGS(rx) |= SVf_UTF8;
7108 /* If a default, cover it using the caret */
7110 *p++= DEFAULT_PAT_MOD;
7114 const char* const name = get_regex_charset_name(r->extflags, &len);
7115 Copy(name, p, len, char);
7119 *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
7122 while((ch = *fptr++)) {
7130 Copy(RExC_precomp, p, plen, char);
7131 assert ((RX_WRAPPED(rx) - p) < 16);
7132 r->pre_prefix = p - RX_WRAPPED(rx);
7138 SvCUR_set(rx, p - RX_WRAPPED(rx));
7142 r->nparens = RExC_npar - 1; /* set early to validate backrefs */
7144 /* setup various meta data about recursion, this all requires
7145 * RExC_npar to be correctly set, and a bit later on we clear it */
7146 if (RExC_seen & REG_RECURSE_SEEN) {
7147 Newxz(RExC_open_parens, RExC_npar,regnode *);
7148 SAVEFREEPV(RExC_open_parens);
7149 Newxz(RExC_close_parens,RExC_npar,regnode *);
7150 SAVEFREEPV(RExC_close_parens);
7152 if (RExC_seen & (REG_RECURSE_SEEN | REG_GOSTART_SEEN)) {
7153 /* Note, RExC_npar is 1 + the number of parens in a pattern.
7154 * So its 1 if there are no parens. */
7155 RExC_study_chunk_recursed_bytes= (RExC_npar >> 3) +
7156 ((RExC_npar & 0x07) != 0);
7157 Newx(RExC_study_chunk_recursed,
7158 RExC_study_chunk_recursed_bytes * RExC_npar, U8);
7159 SAVEFREEPV(RExC_study_chunk_recursed);
7162 /* Useful during FAIL. */
7163 #ifdef RE_TRACK_PATTERN_OFFSETS
7164 Newxz(ri->u.offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
7165 DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
7166 "%s %"UVuf" bytes for offset annotations.\n",
7167 ri->u.offsets ? "Got" : "Couldn't get",
7168 (UV)((2*RExC_size+1) * sizeof(U32))));
7170 SetProgLen(ri,RExC_size);
7175 /* Second pass: emit code. */
7176 RExC_flags = rx_flags; /* don't let top level (?i) bleed */
7177 RExC_pm_flags = pm_flags;
7179 RExC_end = exp + plen;
7182 RExC_emit_start = ri->program;
7183 RExC_emit = ri->program;
7184 RExC_emit_bound = ri->program + RExC_size + 1;
7185 pRExC_state->code_index = 0;
7187 *((char*) RExC_emit++) = (char) REG_MAGIC;
7188 if (reg(pRExC_state, 0, &flags,1) == NULL) {
7190 Perl_croak(aTHX_ "panic: reg returned NULL to re_op_compile for generation pass, flags=%#"UVxf"", (UV) flags);
7192 /* XXXX To minimize changes to RE engine we always allocate
7193 3-units-long substrs field. */
7194 Newx(r->substrs, 1, struct reg_substr_data);
7195 if (RExC_recurse_count) {
7196 Newxz(RExC_recurse,RExC_recurse_count,regnode *);
7197 SAVEFREEPV(RExC_recurse);
7201 r->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;
7203 RExC_study_chunk_recursed_count= 0;
7205 Zero(r->substrs, 1, struct reg_substr_data);
7206 if (RExC_study_chunk_recursed) {
7207 Zero(RExC_study_chunk_recursed,
7208 RExC_study_chunk_recursed_bytes * RExC_npar, U8);
7212 #ifdef TRIE_STUDY_OPT
7214 StructCopy(&zero_scan_data, &data, scan_data_t);
7215 copyRExC_state = RExC_state;
7218 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
7220 RExC_state = copyRExC_state;
7221 if (seen & REG_TOP_LEVEL_BRANCHES_SEEN)
7222 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
7224 RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN;
7225 StructCopy(&zero_scan_data, &data, scan_data_t);
7228 StructCopy(&zero_scan_data, &data, scan_data_t);
7231 /* Dig out information for optimizations. */
7232 r->extflags = RExC_flags; /* was pm_op */
7233 /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
7236 SvUTF8_on(rx); /* Unicode in it? */
7237 ri->regstclass = NULL;
7238 if (RExC_naughty >= TOO_NAUGHTY) /* Probably an expensive pattern. */
7239 r->intflags |= PREGf_NAUGHTY;
7240 scan = ri->program + 1; /* First BRANCH. */
7242 /* testing for BRANCH here tells us whether there is "must appear"
7243 data in the pattern. If there is then we can use it for optimisations */
7244 if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice.
7247 STRLEN longest_float_length, longest_fixed_length;
7248 regnode_ssc ch_class; /* pointed to by data */
7250 SSize_t last_close = 0; /* pointed to by data */
7251 regnode *first= scan;
7252 regnode *first_next= regnext(first);
7254 * Skip introductions and multiplicators >= 1
7255 * so that we can extract the 'meat' of the pattern that must
7256 * match in the large if() sequence following.
7257 * NOTE that EXACT is NOT covered here, as it is normally
7258 * picked up by the optimiser separately.
7260 * This is unfortunate as the optimiser isnt handling lookahead
7261 * properly currently.
7264 while ((OP(first) == OPEN && (sawopen = 1)) ||
7265 /* An OR of *one* alternative - should not happen now. */
7266 (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
7267 /* for now we can't handle lookbehind IFMATCH*/
7268 (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
7269 (OP(first) == PLUS) ||
7270 (OP(first) == MINMOD) ||
7271 /* An {n,m} with n>0 */
7272 (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
7273 (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
7276 * the only op that could be a regnode is PLUS, all the rest
7277 * will be regnode_1 or regnode_2.
7279 * (yves doesn't think this is true)
7281 if (OP(first) == PLUS)
7284 if (OP(first) == MINMOD)
7286 first += regarglen[OP(first)];
7288 first = NEXTOPER(first);
7289 first_next= regnext(first);
7292 /* Starting-point info. */
7294 DEBUG_PEEP("first:",first,0);
7295 /* Ignore EXACT as we deal with it later. */
7296 if (PL_regkind[OP(first)] == EXACT) {
7297 if (OP(first) == EXACT || OP(first) == EXACTL)
7298 NOOP; /* Empty, get anchored substr later. */
7300 ri->regstclass = first;
7303 else if (PL_regkind[OP(first)] == TRIE &&
7304 ((reg_trie_data *)ri->data->data[ ARG(first) ])->minlen>0)
7306 /* this can happen only on restudy */
7307 ri->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0);
7310 else if (REGNODE_SIMPLE(OP(first)))
7311 ri->regstclass = first;
7312 else if (PL_regkind[OP(first)] == BOUND ||
7313 PL_regkind[OP(first)] == NBOUND)
7314 ri->regstclass = first;
7315 else if (PL_regkind[OP(first)] == BOL) {
7316 r->intflags |= (OP(first) == MBOL
7319 first = NEXTOPER(first);
7322 else if (OP(first) == GPOS) {
7323 r->intflags |= PREGf_ANCH_GPOS;
7324 first = NEXTOPER(first);
7327 else if ((!sawopen || !RExC_sawback) &&
7329 (OP(first) == STAR &&
7330 PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
7331 !(r->intflags & PREGf_ANCH) && !pRExC_state->num_code_blocks)
7333 /* turn .* into ^.* with an implied $*=1 */
7335 (OP(NEXTOPER(first)) == REG_ANY)
7338 r->intflags |= (type | PREGf_IMPLICIT);
7339 first = NEXTOPER(first);
7342 if (sawplus && !sawminmod && !sawlookahead
7343 && (!sawopen || !RExC_sawback)
7344 && !pRExC_state->num_code_blocks) /* May examine pos and $& */
7345 /* x+ must match at the 1st pos of run of x's */
7346 r->intflags |= PREGf_SKIP;
7348 /* Scan is after the zeroth branch, first is atomic matcher. */
7349 #ifdef TRIE_STUDY_OPT
7352 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
7353 (IV)(first - scan + 1))
7357 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
7358 (IV)(first - scan + 1))
7364 * If there's something expensive in the r.e., find the
7365 * longest literal string that must appear and make it the
7366 * regmust. Resolve ties in favor of later strings, since
7367 * the regstart check works with the beginning of the r.e.
7368 * and avoiding duplication strengthens checking. Not a
7369 * strong reason, but sufficient in the absence of others.
7370 * [Now we resolve ties in favor of the earlier string if
7371 * it happens that c_offset_min has been invalidated, since the
7372 * earlier string may buy us something the later one won't.]
7375 data.longest_fixed = newSVpvs("");
7376 data.longest_float = newSVpvs("");
7377 data.last_found = newSVpvs("");
7378 data.longest = &(data.longest_fixed);
7379 ENTER_with_name("study_chunk");
7380 SAVEFREESV(data.longest_fixed);
7381 SAVEFREESV(data.longest_float);
7382 SAVEFREESV(data.last_found);
7384 if (!ri->regstclass) {
7385 ssc_init(pRExC_state, &ch_class);
7386 data.start_class = &ch_class;
7387 stclass_flag = SCF_DO_STCLASS_AND;
7388 } else /* XXXX Check for BOUND? */
7390 data.last_closep = &last_close;
7393 minlen = study_chunk(pRExC_state, &first, &minlen, &fake,
7394 scan + RExC_size, /* Up to end */
7396 SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
7397 | (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
7401 CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
7404 if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
7405 && data.last_start_min == 0 && data.last_end > 0
7406 && !RExC_seen_zerolen
7407 && !(RExC_seen & REG_VERBARG_SEEN)
7408 && !(RExC_seen & REG_GPOS_SEEN)
7410 r->extflags |= RXf_CHECK_ALL;
7412 scan_commit(pRExC_state, &data,&minlen,0);
7414 longest_float_length = CHR_SVLEN(data.longest_float);
7416 if (! ((SvCUR(data.longest_fixed) /* ok to leave SvCUR */
7417 && data.offset_fixed == data.offset_float_min
7418 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float)))
7419 && S_setup_longest (aTHX_ pRExC_state,
7423 &(r->float_end_shift),
7424 data.lookbehind_float,
7425 data.offset_float_min,
7427 longest_float_length,
7428 cBOOL(data.flags & SF_FL_BEFORE_EOL),
7429 cBOOL(data.flags & SF_FL_BEFORE_MEOL)))
7431 r->float_min_offset = data.offset_float_min - data.lookbehind_float;
7432 r->float_max_offset = data.offset_float_max;
7433 if (data.offset_float_max < SSize_t_MAX) /* Don't offset infinity */
7434 r->float_max_offset -= data.lookbehind_float;
7435 SvREFCNT_inc_simple_void_NN(data.longest_float);
7438 r->float_substr = r->float_utf8 = NULL;
7439 longest_float_length = 0;
7442 longest_fixed_length = CHR_SVLEN(data.longest_fixed);
7444 if (S_setup_longest (aTHX_ pRExC_state,
7446 &(r->anchored_utf8),
7447 &(r->anchored_substr),
7448 &(r->anchored_end_shift),
7449 data.lookbehind_fixed,
7452 longest_fixed_length,
7453 cBOOL(data.flags & SF_FIX_BEFORE_EOL),
7454 cBOOL(data.flags & SF_FIX_BEFORE_MEOL)))
7456 r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
7457 SvREFCNT_inc_simple_void_NN(data.longest_fixed);
7460 r->anchored_substr = r->anchored_utf8 = NULL;
7461 longest_fixed_length = 0;
7463 LEAVE_with_name("study_chunk");
7466 && (OP(ri->regstclass) == REG_ANY || OP(ri->regstclass) == SANY))
7467 ri->regstclass = NULL;
7469 if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
7471 && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
7472 && is_ssc_worth_it(pRExC_state, data.start_class))
7474 const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
7476 ssc_finalize(pRExC_state, data.start_class);
7478 Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
7479 StructCopy(data.start_class,
7480 (regnode_ssc*)RExC_rxi->data->data[n],
7482 ri->regstclass = (regnode*)RExC_rxi->data->data[n];
7483 r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
7484 DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
7485 regprop(r, sv, (regnode*)data.start_class, NULL, pRExC_state);
7486 PerlIO_printf(Perl_debug_log,
7487 "synthetic stclass \"%s\".\n",
7488 SvPVX_const(sv));});
7489 data.start_class = NULL;
7492 /* A temporary algorithm prefers floated substr to fixed one to dig
7494 if (longest_fixed_length > longest_float_length) {
7495 r->substrs->check_ix = 0;
7496 r->check_end_shift = r->anchored_end_shift;
7497 r->check_substr = r->anchored_substr;
7498 r->check_utf8 = r->anchored_utf8;
7499 r->check_offset_min = r->check_offset_max = r->anchored_offset;
7500 if (r->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS))
7501 r->intflags |= PREGf_NOSCAN;
7504 r->substrs->check_ix = 1;
7505 r->check_end_shift = r->float_end_shift;
7506 r->check_substr = r->float_substr;
7507 r->check_utf8 = r->float_utf8;
7508 r->check_offset_min = r->float_min_offset;
7509 r->check_offset_max = r->float_max_offset;
7511 if ((r->check_substr || r->check_utf8) ) {
7512 r->extflags |= RXf_USE_INTUIT;
7513 if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
7514 r->extflags |= RXf_INTUIT_TAIL;
7516 r->substrs->data[0].max_offset = r->substrs->data[0].min_offset;
7518 /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
7519 if ( (STRLEN)minlen < longest_float_length )
7520 minlen= longest_float_length;
7521 if ( (STRLEN)minlen < longest_fixed_length )
7522 minlen= longest_fixed_length;
7526 /* Several toplevels. Best we can is to set minlen. */
7528 regnode_ssc ch_class;
7529 SSize_t last_close = 0;
7531 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "\nMulti Top Level\n"));
7533 scan = ri->program + 1;
7534 ssc_init(pRExC_state, &ch_class);
7535 data.start_class = &ch_class;
7536 data.last_closep = &last_close;
7539 minlen = study_chunk(pRExC_state,
7540 &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL,
7541 SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied
7542 ? SCF_TRIE_DOING_RESTUDY
7546 CHECK_RESTUDY_GOTO_butfirst(NOOP);
7548 r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
7549 = r->float_substr = r->float_utf8 = NULL;
7551 if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
7552 && is_ssc_worth_it(pRExC_state, data.start_class))
7554 const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
7556 ssc_finalize(pRExC_state, data.start_class);
7558 Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
7559 StructCopy(data.start_class,
7560 (regnode_ssc*)RExC_rxi->data->data[n],
7562 ri->regstclass = (regnode*)RExC_rxi->data->data[n];
7563 r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
7564 DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
7565 regprop(r, sv, (regnode*)data.start_class, NULL, pRExC_state);
7566 PerlIO_printf(Perl_debug_log,
7567 "synthetic stclass \"%s\".\n",
7568 SvPVX_const(sv));});
7569 data.start_class = NULL;
7573 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) {
7574 r->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN;
7575 r->maxlen = REG_INFTY;
7578 r->maxlen = RExC_maxlen;
7581 /* Guard against an embedded (?=) or (?<=) with a longer minlen than
7582 the "real" pattern. */
7584 PerlIO_printf(Perl_debug_log,"minlen: %"IVdf" r->minlen:%"IVdf" maxlen:%"IVdf"\n",
7585 (IV)minlen, (IV)r->minlen, (IV)RExC_maxlen);
7587 r->minlenret = minlen;
7588 if (r->minlen < minlen)
7591 if (RExC_seen & REG_GPOS_SEEN)
7592 r->intflags |= PREGf_GPOS_SEEN;
7593 if (RExC_seen & REG_LOOKBEHIND_SEEN)
7594 r->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the
7596 if (pRExC_state->num_code_blocks)
7597 r->extflags |= RXf_EVAL_SEEN;
7598 if (RExC_seen & REG_VERBARG_SEEN)
7600 r->intflags |= PREGf_VERBARG_SEEN;
7601 r->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */
7603 if (RExC_seen & REG_CUTGROUP_SEEN)
7604 r->intflags |= PREGf_CUTGROUP_SEEN;
7605 if (pm_flags & PMf_USE_RE_EVAL)
7606 r->intflags |= PREGf_USE_RE_EVAL;
7607 if (RExC_paren_names)
7608 RXp_PAREN_NAMES(r) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
7610 RXp_PAREN_NAMES(r) = NULL;
7612 /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED
7613 * so it can be used in pp.c */
7614 if (r->intflags & PREGf_ANCH)
7615 r->extflags |= RXf_IS_ANCHORED;
7619 /* this is used to identify "special" patterns that might result
7620 * in Perl NOT calling the regex engine and instead doing the match "itself",
7621 * particularly special cases in split//. By having the regex compiler
7622 * do this pattern matching at a regop level (instead of by inspecting the pattern)
7623 * we avoid weird issues with equivalent patterns resulting in different behavior,
7624 * AND we allow non Perl engines to get the same optimizations by the setting the
7625 * flags appropriately - Yves */
7626 regnode *first = ri->program + 1;
7628 regnode *next = regnext(first);
7631 if (PL_regkind[fop] == NOTHING && nop == END)
7632 r->extflags |= RXf_NULL;
7633 else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END)
7634 /* when fop is SBOL first->flags will be true only when it was
7635 * produced by parsing /\A/, and not when parsing /^/. This is
7636 * very important for the split code as there we want to
7637 * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m.
7638 * See rt #122761 for more details. -- Yves */
7639 r->extflags |= RXf_START_ONLY;
7640 else if (fop == PLUS
7641 && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE
7643 r->extflags |= RXf_WHITE;
7644 else if ( r->extflags & RXf_SPLIT
7645 && (fop == EXACT || fop == EXACTL)
7646 && STR_LEN(first) == 1
7647 && *(STRING(first)) == ' '
7649 r->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
7653 if (RExC_contains_locale) {
7654 RXp_EXTFLAGS(r) |= RXf_TAINTED;
7658 if (RExC_paren_names) {
7659 ri->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a"));
7660 ri->data->data[ri->name_list_idx]
7661 = (void*)SvREFCNT_inc(RExC_paren_name_list);
7664 ri->name_list_idx = 0;
7666 if (RExC_recurse_count) {
7667 for ( ; RExC_recurse_count ; RExC_recurse_count-- ) {
7668 const regnode *scan = RExC_recurse[RExC_recurse_count-1];
7669 ARG2L_SET( scan, RExC_open_parens[ARG(scan)-1] - scan );
7672 Newxz(r->offs, RExC_npar, regexp_paren_pair);
7673 /* assume we don't need to swap parens around before we match */
7675 PerlIO_printf(Perl_debug_log,"study_chunk_recursed_count: %lu\n",
7676 (unsigned long)RExC_study_chunk_recursed_count);
7680 PerlIO_printf(Perl_debug_log,"Final program:\n");
7683 #ifdef RE_TRACK_PATTERN_OFFSETS
7684 DEBUG_OFFSETS_r(if (ri->u.offsets) {
7685 const STRLEN len = ri->u.offsets[0];
7687 GET_RE_DEBUG_FLAGS_DECL;
7688 PerlIO_printf(Perl_debug_log,
7689 "Offsets: [%"UVuf"]\n\t", (UV)ri->u.offsets[0]);
7690 for (i = 1; i <= len; i++) {
7691 if (ri->u.offsets[i*2-1] || ri->u.offsets[i*2])
7692 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
7693 (UV)i, (UV)ri->u.offsets[i*2-1], (UV)ri->u.offsets[i*2]);
7695 PerlIO_printf(Perl_debug_log, "\n");
7700 /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated
7701 * by setting the regexp SV to readonly-only instead. If the
7702 * pattern's been recompiled, the USEDness should remain. */
7703 if (old_re && SvREADONLY(old_re))
7711 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
7714 PERL_ARGS_ASSERT_REG_NAMED_BUFF;
7716 PERL_UNUSED_ARG(value);
7718 if (flags & RXapif_FETCH) {
7719 return reg_named_buff_fetch(rx, key, flags);
7720 } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
7721 Perl_croak_no_modify();
7723 } else if (flags & RXapif_EXISTS) {
7724 return reg_named_buff_exists(rx, key, flags)
7727 } else if (flags & RXapif_REGNAMES) {
7728 return reg_named_buff_all(rx, flags);
7729 } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
7730 return reg_named_buff_scalar(rx, flags);
7732 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
7738 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
7741 PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
7742 PERL_UNUSED_ARG(lastkey);
7744 if (flags & RXapif_FIRSTKEY)
7745 return reg_named_buff_firstkey(rx, flags);
7746 else if (flags & RXapif_NEXTKEY)
7747 return reg_named_buff_nextkey(rx, flags);
7749 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter",
7756 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
7759 AV *retarray = NULL;
7761 struct regexp *const rx = ReANY(r);
7763 PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
7765 if (flags & RXapif_ALL)
7768 if (rx && RXp_PAREN_NAMES(rx)) {
7769 HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
7772 SV* sv_dat=HeVAL(he_str);
7773 I32 *nums=(I32*)SvPVX(sv_dat);
7774 for ( i=0; i<SvIVX(sv_dat); i++ ) {
7775 if ((I32)(rx->nparens) >= nums[i]
7776 && rx->offs[nums[i]].start != -1
7777 && rx->offs[nums[i]].end != -1)
7780 CALLREG_NUMBUF_FETCH(r,nums[i],ret);
7785 ret = newSVsv(&PL_sv_undef);
7788 av_push(retarray, ret);
7791 return newRV_noinc(MUTABLE_SV(retarray));
7798 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
7801 struct regexp *const rx = ReANY(r);
7803 PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
7805 if (rx && RXp_PAREN_NAMES(rx)) {
7806 if (flags & RXapif_ALL) {
7807 return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
7809 SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
7811 SvREFCNT_dec_NN(sv);
7823 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
7825 struct regexp *const rx = ReANY(r);
7827 PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
7829 if ( rx && RXp_PAREN_NAMES(rx) ) {
7830 (void)hv_iterinit(RXp_PAREN_NAMES(rx));
7832 return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
7839 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
7841 struct regexp *const rx = ReANY(r);
7842 GET_RE_DEBUG_FLAGS_DECL;
7844 PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
7846 if (rx && RXp_PAREN_NAMES(rx)) {
7847 HV *hv = RXp_PAREN_NAMES(rx);
7849 while ( (temphe = hv_iternext_flags(hv,0)) ) {
7852 SV* sv_dat = HeVAL(temphe);
7853 I32 *nums = (I32*)SvPVX(sv_dat);
7854 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
7855 if ((I32)(rx->lastparen) >= nums[i] &&
7856 rx->offs[nums[i]].start != -1 &&
7857 rx->offs[nums[i]].end != -1)
7863 if (parno || flags & RXapif_ALL) {
7864 return newSVhek(HeKEY_hek(temphe));
7872 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
7877 struct regexp *const rx = ReANY(r);
7879 PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
7881 if (rx && RXp_PAREN_NAMES(rx)) {
7882 if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
7883 return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
7884 } else if (flags & RXapif_ONE) {
7885 ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
7886 av = MUTABLE_AV(SvRV(ret));
7887 length = av_tindex(av);
7888 SvREFCNT_dec_NN(ret);
7889 return newSViv(length + 1);
7891 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar",
7896 return &PL_sv_undef;
7900 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
7902 struct regexp *const rx = ReANY(r);
7905 PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
7907 if (rx && RXp_PAREN_NAMES(rx)) {
7908 HV *hv= RXp_PAREN_NAMES(rx);
7910 (void)hv_iterinit(hv);
7911 while ( (temphe = hv_iternext_flags(hv,0)) ) {
7914 SV* sv_dat = HeVAL(temphe);
7915 I32 *nums = (I32*)SvPVX(sv_dat);
7916 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
7917 if ((I32)(rx->lastparen) >= nums[i] &&
7918 rx->offs[nums[i]].start != -1 &&
7919 rx->offs[nums[i]].end != -1)
7925 if (parno || flags & RXapif_ALL) {
7926 av_push(av, newSVhek(HeKEY_hek(temphe)));
7931 return newRV_noinc(MUTABLE_SV(av));
7935 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
7938 struct regexp *const rx = ReANY(r);
7944 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
7946 if ( n == RX_BUFF_IDX_CARET_PREMATCH
7947 || n == RX_BUFF_IDX_CARET_FULLMATCH
7948 || n == RX_BUFF_IDX_CARET_POSTMATCH
7951 bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
7953 /* on something like
7956 * the KEEPCOPY is set on the PMOP rather than the regex */
7957 if (PL_curpm && r == PM_GETRE(PL_curpm))
7958 keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
7967 if (n == RX_BUFF_IDX_CARET_FULLMATCH)
7968 /* no need to distinguish between them any more */
7969 n = RX_BUFF_IDX_FULLMATCH;
7971 if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
7972 && rx->offs[0].start != -1)
7974 /* $`, ${^PREMATCH} */
7975 i = rx->offs[0].start;
7979 if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
7980 && rx->offs[0].end != -1)
7982 /* $', ${^POSTMATCH} */
7983 s = rx->subbeg - rx->suboffset + rx->offs[0].end;
7984 i = rx->sublen + rx->suboffset - rx->offs[0].end;
7987 if ( 0 <= n && n <= (I32)rx->nparens &&
7988 (s1 = rx->offs[n].start) != -1 &&
7989 (t1 = rx->offs[n].end) != -1)
7991 /* $&, ${^MATCH}, $1 ... */
7993 s = rx->subbeg + s1 - rx->suboffset;
7998 assert(s >= rx->subbeg);
7999 assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) );
8001 #ifdef NO_TAINT_SUPPORT
8002 sv_setpvn(sv, s, i);
8004 const int oldtainted = TAINT_get;
8006 sv_setpvn(sv, s, i);
8007 TAINT_set(oldtainted);
8009 if (RXp_MATCH_UTF8(rx))
8014 if (RXp_MATCH_TAINTED(rx)) {
8015 if (SvTYPE(sv) >= SVt_PVMG) {
8016 MAGIC* const mg = SvMAGIC(sv);
8019 SvMAGIC_set(sv, mg->mg_moremagic);
8021 if ((mgt = SvMAGIC(sv))) {
8022 mg->mg_moremagic = mgt;
8023 SvMAGIC_set(sv, mg);
8034 sv_setsv(sv,&PL_sv_undef);
8040 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
8041 SV const * const value)
8043 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
8045 PERL_UNUSED_ARG(rx);
8046 PERL_UNUSED_ARG(paren);
8047 PERL_UNUSED_ARG(value);
8050 Perl_croak_no_modify();
8054 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
8057 struct regexp *const rx = ReANY(r);
8061 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
8063 if ( paren == RX_BUFF_IDX_CARET_PREMATCH
8064 || paren == RX_BUFF_IDX_CARET_FULLMATCH
8065 || paren == RX_BUFF_IDX_CARET_POSTMATCH
8068 bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8070 /* on something like
8073 * the KEEPCOPY is set on the PMOP rather than the regex */
8074 if (PL_curpm && r == PM_GETRE(PL_curpm))
8075 keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8081 /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
8083 case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
8084 case RX_BUFF_IDX_PREMATCH: /* $` */
8085 if (rx->offs[0].start != -1) {
8086 i = rx->offs[0].start;
8095 case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
8096 case RX_BUFF_IDX_POSTMATCH: /* $' */
8097 if (rx->offs[0].end != -1) {
8098 i = rx->sublen - rx->offs[0].end;
8100 s1 = rx->offs[0].end;
8107 default: /* $& / ${^MATCH}, $1, $2, ... */
8108 if (paren <= (I32)rx->nparens &&
8109 (s1 = rx->offs[paren].start) != -1 &&
8110 (t1 = rx->offs[paren].end) != -1)
8116 if (ckWARN(WARN_UNINITIALIZED))
8117 report_uninit((const SV *)sv);
8122 if (i > 0 && RXp_MATCH_UTF8(rx)) {
8123 const char * const s = rx->subbeg - rx->suboffset + s1;
8128 if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
8135 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
8137 PERL_ARGS_ASSERT_REG_QR_PACKAGE;
8138 PERL_UNUSED_ARG(rx);
8142 return newSVpvs("Regexp");
8145 /* Scans the name of a named buffer from the pattern.
8146 * If flags is REG_RSN_RETURN_NULL returns null.
8147 * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
8148 * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
8149 * to the parsed name as looked up in the RExC_paren_names hash.
8150 * If there is an error throws a vFAIL().. type exception.
8153 #define REG_RSN_RETURN_NULL 0
8154 #define REG_RSN_RETURN_NAME 1
8155 #define REG_RSN_RETURN_DATA 2
8158 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
8160 char *name_start = RExC_parse;
8162 PERL_ARGS_ASSERT_REG_SCAN_NAME;
8164 assert (RExC_parse <= RExC_end);
8165 if (RExC_parse == RExC_end) NOOP;
8166 else if (isIDFIRST_lazy_if(RExC_parse, UTF)) {
8167 /* Note that the code here assumes well-formed UTF-8. Skip IDFIRST by
8168 * using do...while */
8171 RExC_parse += UTF8SKIP(RExC_parse);
8172 } while (isWORDCHAR_utf8((U8*)RExC_parse));
8176 } while (isWORDCHAR(*RExC_parse));
8178 RExC_parse++; /* so the <- from the vFAIL is after the offending
8180 vFAIL("Group name must start with a non-digit word character");
8184 = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
8185 SVs_TEMP | (UTF ? SVf_UTF8 : 0));
8186 if ( flags == REG_RSN_RETURN_NAME)
8188 else if (flags==REG_RSN_RETURN_DATA) {
8191 if ( ! sv_name ) /* should not happen*/
8192 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
8193 if (RExC_paren_names)
8194 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
8196 sv_dat = HeVAL(he_str);
8198 vFAIL("Reference to nonexistent named group");
8202 Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
8203 (unsigned long) flags);
8205 NOT_REACHED; /* NOTREACHED */
8210 #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
8212 if (RExC_lastparse!=RExC_parse) { \
8213 PerlIO_printf(Perl_debug_log, "%s", \
8214 Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse, \
8215 RExC_end - RExC_parse, 16, \
8217 PERL_PV_ESCAPE_UNI_DETECT | \
8218 PERL_PV_PRETTY_ELLIPSES | \
8219 PERL_PV_PRETTY_LTGT | \
8220 PERL_PV_ESCAPE_RE | \
8221 PERL_PV_PRETTY_EXACTSIZE \
8225 PerlIO_printf(Perl_debug_log,"%16s",""); \
8228 num = RExC_size + 1; \
8230 num=REG_NODE_NUM(RExC_emit); \
8231 if (RExC_lastnum!=num) \
8232 PerlIO_printf(Perl_debug_log,"|%4d",num); \
8234 PerlIO_printf(Perl_debug_log,"|%4s",""); \
8235 PerlIO_printf(Perl_debug_log,"|%*s%-4s", \
8236 (int)((depth*2)), "", \
8240 RExC_lastparse=RExC_parse; \
8245 #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
8246 DEBUG_PARSE_MSG((funcname)); \
8247 PerlIO_printf(Perl_debug_log,"%4s","\n"); \
8249 #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({ \
8250 DEBUG_PARSE_MSG((funcname)); \
8251 PerlIO_printf(Perl_debug_log,fmt "\n",args); \
8254 /* This section of code defines the inversion list object and its methods. The
8255 * interfaces are highly subject to change, so as much as possible is static to
8256 * this file. An inversion list is here implemented as a malloc'd C UV array
8257 * as an SVt_INVLIST scalar.
8259 * An inversion list for Unicode is an array of code points, sorted by ordinal
8260 * number. The zeroth element is the first code point in the list. The 1th
8261 * element is the first element beyond that not in the list. In other words,
8262 * the first range is
8263 * invlist[0]..(invlist[1]-1)
8264 * The other ranges follow. Thus every element whose index is divisible by two
8265 * marks the beginning of a range that is in the list, and every element not
8266 * divisible by two marks the beginning of a range not in the list. A single
8267 * element inversion list that contains the single code point N generally
8268 * consists of two elements
8271 * (The exception is when N is the highest representable value on the
8272 * machine, in which case the list containing just it would be a single
8273 * element, itself. By extension, if the last range in the list extends to
8274 * infinity, then the first element of that range will be in the inversion list
8275 * at a position that is divisible by two, and is the final element in the
8277 * Taking the complement (inverting) an inversion list is quite simple, if the
8278 * first element is 0, remove it; otherwise add a 0 element at the beginning.
8279 * This implementation reserves an element at the beginning of each inversion
8280 * list to always contain 0; there is an additional flag in the header which
8281 * indicates if the list begins at the 0, or is offset to begin at the next
8284 * More about inversion lists can be found in "Unicode Demystified"
8285 * Chapter 13 by Richard Gillam, published by Addison-Wesley.
8286 * More will be coming when functionality is added later.
8288 * The inversion list data structure is currently implemented as an SV pointing
8289 * to an array of UVs that the SV thinks are bytes. This allows us to have an
8290 * array of UV whose memory management is automatically handled by the existing
8291 * facilities for SV's.
8293 * Some of the methods should always be private to the implementation, and some
8294 * should eventually be made public */
8296 /* The header definitions are in F<invlist_inline.h> */
8298 PERL_STATIC_INLINE UV*
8299 S__invlist_array_init(SV* const invlist, const bool will_have_0)
8301 /* Returns a pointer to the first element in the inversion list's array.
8302 * This is called upon initialization of an inversion list. Where the
8303 * array begins depends on whether the list has the code point U+0000 in it
8304 * or not. The other parameter tells it whether the code that follows this
8305 * call is about to put a 0 in the inversion list or not. The first
8306 * element is either the element reserved for 0, if TRUE, or the element
8307 * after it, if FALSE */
8309 bool* offset = get_invlist_offset_addr(invlist);
8310 UV* zero_addr = (UV *) SvPVX(invlist);
8312 PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
8315 assert(! _invlist_len(invlist));
8319 /* 1^1 = 0; 1^0 = 1 */
8320 *offset = 1 ^ will_have_0;
8321 return zero_addr + *offset;
8324 PERL_STATIC_INLINE void
8325 S_invlist_set_len(pTHX_ SV* const invlist, const UV len, const bool offset)
8327 /* Sets the current number of elements stored in the inversion list.
8328 * Updates SvCUR correspondingly */
8329 PERL_UNUSED_CONTEXT;
8330 PERL_ARGS_ASSERT_INVLIST_SET_LEN;
8332 assert(SvTYPE(invlist) == SVt_INVLIST);
8337 : TO_INTERNAL_SIZE(len + offset));
8338 assert(SvLEN(invlist) == 0 || SvCUR(invlist) <= SvLEN(invlist));
8341 #ifndef PERL_IN_XSUB_RE
8343 PERL_STATIC_INLINE IV*
8344 S_get_invlist_previous_index_addr(SV* invlist)
8346 /* Return the address of the IV that is reserved to hold the cached index
8348 PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
8350 assert(SvTYPE(invlist) == SVt_INVLIST);
8352 return &(((XINVLIST*) SvANY(invlist))->prev_index);
8355 PERL_STATIC_INLINE IV
8356 S_invlist_previous_index(SV* const invlist)
8358 /* Returns cached index of previous search */
8360 PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
8362 return *get_invlist_previous_index_addr(invlist);
8365 PERL_STATIC_INLINE void
8366 S_invlist_set_previous_index(SV* const invlist, const IV index)
8368 /* Caches <index> for later retrieval */
8370 PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
8372 assert(index == 0 || index < (int) _invlist_len(invlist));
8374 *get_invlist_previous_index_addr(invlist) = index;
8377 PERL_STATIC_INLINE void
8378 S_invlist_trim(SV* const invlist)
8380 PERL_ARGS_ASSERT_INVLIST_TRIM;
8382 assert(SvTYPE(invlist) == SVt_INVLIST);
8384 /* Change the length of the inversion list to how many entries it currently
8386 SvPV_shrink_to_cur((SV *) invlist);
8389 PERL_STATIC_INLINE bool
8390 S_invlist_is_iterating(SV* const invlist)
8392 PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
8394 return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX;
8397 #endif /* ifndef PERL_IN_XSUB_RE */
8399 PERL_STATIC_INLINE UV
8400 S_invlist_max(SV* const invlist)
8402 /* Returns the maximum number of elements storable in the inversion list's
8403 * array, without having to realloc() */
8405 PERL_ARGS_ASSERT_INVLIST_MAX;
8407 assert(SvTYPE(invlist) == SVt_INVLIST);
8409 /* Assumes worst case, in which the 0 element is not counted in the
8410 * inversion list, so subtracts 1 for that */
8411 return SvLEN(invlist) == 0 /* This happens under _new_invlist_C_array */
8412 ? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1
8413 : FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1;
8416 #ifndef PERL_IN_XSUB_RE
8418 Perl__new_invlist(pTHX_ IV initial_size)
8421 /* Return a pointer to a newly constructed inversion list, with enough
8422 * space to store 'initial_size' elements. If that number is negative, a
8423 * system default is used instead */
8427 if (initial_size < 0) {
8431 /* Allocate the initial space */
8432 new_list = newSV_type(SVt_INVLIST);
8434 /* First 1 is in case the zero element isn't in the list; second 1 is for
8436 SvGROW(new_list, TO_INTERNAL_SIZE(initial_size + 1) + 1);
8437 invlist_set_len(new_list, 0, 0);
8439 /* Force iterinit() to be used to get iteration to work */
8440 *get_invlist_iter_addr(new_list) = (STRLEN) UV_MAX;
8442 *get_invlist_previous_index_addr(new_list) = 0;
8448 Perl__new_invlist_C_array(pTHX_ const UV* const list)
8450 /* Return a pointer to a newly constructed inversion list, initialized to
8451 * point to <list>, which has to be in the exact correct inversion list
8452 * form, including internal fields. Thus this is a dangerous routine that
8453 * should not be used in the wrong hands. The passed in 'list' contains
8454 * several header fields at the beginning that are not part of the
8455 * inversion list body proper */
8457 const STRLEN length = (STRLEN) list[0];
8458 const UV version_id = list[1];
8459 const bool offset = cBOOL(list[2]);
8460 #define HEADER_LENGTH 3
8461 /* If any of the above changes in any way, you must change HEADER_LENGTH
8462 * (if appropriate) and regenerate INVLIST_VERSION_ID by running
8463 * perl -E 'say int(rand 2**31-1)'
8465 #define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and
8466 data structure type, so that one being
8467 passed in can be validated to be an
8468 inversion list of the correct vintage.
8471 SV* invlist = newSV_type(SVt_INVLIST);
8473 PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
8475 if (version_id != INVLIST_VERSION_ID) {
8476 Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
8479 /* The generated array passed in includes header elements that aren't part
8480 * of the list proper, so start it just after them */
8481 SvPV_set(invlist, (char *) (list + HEADER_LENGTH));
8483 SvLEN_set(invlist, 0); /* Means we own the contents, and the system
8484 shouldn't touch it */
8486 *(get_invlist_offset_addr(invlist)) = offset;
8488 /* The 'length' passed to us is the physical number of elements in the
8489 * inversion list. But if there is an offset the logical number is one
8491 invlist_set_len(invlist, length - offset, offset);
8493 invlist_set_previous_index(invlist, 0);
8495 /* Initialize the iteration pointer. */
8496 invlist_iterfinish(invlist);
8498 SvREADONLY_on(invlist);
8502 #endif /* ifndef PERL_IN_XSUB_RE */
8505 S_invlist_extend(pTHX_ SV* const invlist, const UV new_max)
8507 /* Grow the maximum size of an inversion list */
8509 PERL_ARGS_ASSERT_INVLIST_EXTEND;
8511 assert(SvTYPE(invlist) == SVt_INVLIST);
8513 /* Add one to account for the zero element at the beginning which may not
8514 * be counted by the calling parameters */
8515 SvGROW((SV *)invlist, TO_INTERNAL_SIZE(new_max + 1));
8519 S__append_range_to_invlist(pTHX_ SV* const invlist,
8520 const UV start, const UV end)
8522 /* Subject to change or removal. Append the range from 'start' to 'end' at
8523 * the end of the inversion list. The range must be above any existing
8527 UV max = invlist_max(invlist);
8528 UV len = _invlist_len(invlist);
8531 PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
8533 if (len == 0) { /* Empty lists must be initialized */
8534 offset = start != 0;
8535 array = _invlist_array_init(invlist, ! offset);
8538 /* Here, the existing list is non-empty. The current max entry in the
8539 * list is generally the first value not in the set, except when the
8540 * set extends to the end of permissible values, in which case it is
8541 * the first entry in that final set, and so this call is an attempt to
8542 * append out-of-order */
8544 UV final_element = len - 1;
8545 array = invlist_array(invlist);
8546 if (array[final_element] > start
8547 || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
8549 Perl_croak(aTHX_ "panic: attempting to append to an inversion list, but wasn't at the end of the list, final=%"UVuf", start=%"UVuf", match=%c",
8550 array[final_element], start,
8551 ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
8554 /* Here, it is a legal append. If the new range begins with the first
8555 * value not in the set, it is extending the set, so the new first
8556 * value not in the set is one greater than the newly extended range.
8558 offset = *get_invlist_offset_addr(invlist);
8559 if (array[final_element] == start) {
8560 if (end != UV_MAX) {
8561 array[final_element] = end + 1;
8564 /* But if the end is the maximum representable on the machine,
8565 * just let the range that this would extend to have no end */
8566 invlist_set_len(invlist, len - 1, offset);
8572 /* Here the new range doesn't extend any existing set. Add it */
8574 len += 2; /* Includes an element each for the start and end of range */
8576 /* If wll overflow the existing space, extend, which may cause the array to
8579 invlist_extend(invlist, len);
8581 /* Have to set len here to avoid assert failure in invlist_array() */
8582 invlist_set_len(invlist, len, offset);
8584 array = invlist_array(invlist);
8587 invlist_set_len(invlist, len, offset);
8590 /* The next item on the list starts the range, the one after that is
8591 * one past the new range. */
8592 array[len - 2] = start;
8593 if (end != UV_MAX) {
8594 array[len - 1] = end + 1;
8597 /* But if the end is the maximum representable on the machine, just let
8598 * the range have no end */
8599 invlist_set_len(invlist, len - 1, offset);
8603 #ifndef PERL_IN_XSUB_RE
8606 Perl__invlist_search(SV* const invlist, const UV cp)
8608 /* Searches the inversion list for the entry that contains the input code
8609 * point <cp>. If <cp> is not in the list, -1 is returned. Otherwise, the
8610 * return value is the index into the list's array of the range that
8611 * contains <cp>, that is, 'i' such that
8612 * array[i] <= cp < array[i+1]
8617 IV high = _invlist_len(invlist);
8618 const IV highest_element = high - 1;
8621 PERL_ARGS_ASSERT__INVLIST_SEARCH;
8623 /* If list is empty, return failure. */
8628 /* (We can't get the array unless we know the list is non-empty) */
8629 array = invlist_array(invlist);
8631 mid = invlist_previous_index(invlist);
8633 if (mid > highest_element) {
8634 mid = highest_element;
8637 /* <mid> contains the cache of the result of the previous call to this
8638 * function (0 the first time). See if this call is for the same result,
8639 * or if it is for mid-1. This is under the theory that calls to this
8640 * function will often be for related code points that are near each other.
8641 * And benchmarks show that caching gives better results. We also test
8642 * here if the code point is within the bounds of the list. These tests
8643 * replace others that would have had to be made anyway to make sure that
8644 * the array bounds were not exceeded, and these give us extra information
8645 * at the same time */
8646 if (cp >= array[mid]) {
8647 if (cp >= array[highest_element]) {
8648 return highest_element;
8651 /* Here, array[mid] <= cp < array[highest_element]. This means that
8652 * the final element is not the answer, so can exclude it; it also
8653 * means that <mid> is not the final element, so can refer to 'mid + 1'
8655 if (cp < array[mid + 1]) {
8661 else { /* cp < aray[mid] */
8662 if (cp < array[0]) { /* Fail if outside the array */
8666 if (cp >= array[mid - 1]) {
8671 /* Binary search. What we are looking for is <i> such that
8672 * array[i] <= cp < array[i+1]
8673 * The loop below converges on the i+1. Note that there may not be an
8674 * (i+1)th element in the array, and things work nonetheless */
8675 while (low < high) {
8676 mid = (low + high) / 2;
8677 assert(mid <= highest_element);
8678 if (array[mid] <= cp) { /* cp >= array[mid] */
8681 /* We could do this extra test to exit the loop early.
8682 if (cp < array[low]) {
8687 else { /* cp < array[mid] */
8694 invlist_set_previous_index(invlist, high);
8699 Perl__invlist_populate_swatch(SV* const invlist,
8700 const UV start, const UV end, U8* swatch)
8702 /* populates a swatch of a swash the same way swatch_get() does in utf8.c,
8703 * but is used when the swash has an inversion list. This makes this much
8704 * faster, as it uses a binary search instead of a linear one. This is
8705 * intimately tied to that function, and perhaps should be in utf8.c,
8706 * except it is intimately tied to inversion lists as well. It assumes
8707 * that <swatch> is all 0's on input */
8710 const IV len = _invlist_len(invlist);
8714 PERL_ARGS_ASSERT__INVLIST_POPULATE_SWATCH;
8716 if (len == 0) { /* Empty inversion list */
8720 array = invlist_array(invlist);
8722 /* Find which element it is */
8723 i = _invlist_search(invlist, start);
8725 /* We populate from <start> to <end> */
8726 while (current < end) {
8729 /* The inversion list gives the results for every possible code point
8730 * after the first one in the list. Only those ranges whose index is
8731 * even are ones that the inversion list matches. For the odd ones,
8732 * and if the initial code point is not in the list, we have to skip
8733 * forward to the next element */
8734 if (i == -1 || ! ELEMENT_RANGE_MATCHES_INVLIST(i)) {
8736 if (i >= len) { /* Finished if beyond the end of the array */
8740 if (current >= end) { /* Finished if beyond the end of what we
8742 if (LIKELY(end < UV_MAX)) {
8746 /* We get here when the upper bound is the maximum
8747 * representable on the machine, and we are looking for just
8748 * that code point. Have to special case it */
8750 goto join_end_of_list;
8753 assert(current >= start);
8755 /* The current range ends one below the next one, except don't go past
8758 upper = (i < len && array[i] < end) ? array[i] : end;
8760 /* Here we are in a range that matches. Populate a bit in the 3-bit U8
8761 * for each code point in it */
8762 for (; current < upper; current++) {
8763 const STRLEN offset = (STRLEN)(current - start);
8764 swatch[offset >> 3] |= 1 << (offset & 7);
8769 /* Quit if at the end of the list */
8772 /* But first, have to deal with the highest possible code point on
8773 * the platform. The previous code assumes that <end> is one
8774 * beyond where we want to populate, but that is impossible at the
8775 * platform's infinity, so have to handle it specially */
8776 if (UNLIKELY(end == UV_MAX && ELEMENT_RANGE_MATCHES_INVLIST(len-1)))
8778 const STRLEN offset = (STRLEN)(end - start);
8779 swatch[offset >> 3] |= 1 << (offset & 7);
8784 /* Advance to the next range, which will be for code points not in the
8793 Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
8794 const bool complement_b, SV** output)
8796 /* Take the union of two inversion lists and point <output> to it. *output
8797 * SHOULD BE DEFINED upon input, and if it points to one of the two lists,
8798 * the reference count to that list will be decremented if not already a
8799 * temporary (mortal); otherwise *output will be made correspondingly
8800 * mortal. The first list, <a>, may be NULL, in which case a copy of the
8801 * second list is returned. If <complement_b> is TRUE, the union is taken
8802 * of the complement (inversion) of <b> instead of b itself.
8804 * The basis for this comes from "Unicode Demystified" Chapter 13 by
8805 * Richard Gillam, published by Addison-Wesley, and explained at some
8806 * length there. The preface says to incorporate its examples into your
8807 * code at your own risk.
8809 * The algorithm is like a merge sort.
8811 * XXX A potential performance improvement is to keep track as we go along
8812 * if only one of the inputs contributes to the result, meaning the other
8813 * is a subset of that one. In that case, we can skip the final copy and
8814 * return the larger of the input lists, but then outside code might need
8815 * to keep track of whether to free the input list or not */
8817 const UV* array_a; /* a's array */
8819 UV len_a; /* length of a's array */
8822 SV* u; /* the resulting union */
8826 UV i_a = 0; /* current index into a's array */
8830 /* running count, as explained in the algorithm source book; items are
8831 * stopped accumulating and are output when the count changes to/from 0.
8832 * The count is incremented when we start a range that's in the set, and
8833 * decremented when we start a range that's not in the set. So its range
8834 * is 0 to 2. Only when the count is zero is something not in the set.
8838 PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
8841 /* If either one is empty, the union is the other one */
8842 if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
8843 bool make_temp = FALSE; /* Should we mortalize the result? */
8847 if (! (make_temp = cBOOL(SvTEMP(a)))) {
8853 *output = invlist_clone(b);
8855 _invlist_invert(*output);
8857 } /* else *output already = b; */
8860 sv_2mortal(*output);
8864 else if ((len_b = _invlist_len(b)) == 0) {
8865 bool make_temp = FALSE;
8867 if (! (make_temp = cBOOL(SvTEMP(b)))) {
8872 /* The complement of an empty list is a list that has everything in it,
8873 * so the union with <a> includes everything too */
8876 if (! (make_temp = cBOOL(SvTEMP(a)))) {
8880 *output = _new_invlist(1);
8881 _append_range_to_invlist(*output, 0, UV_MAX);
8883 else if (*output != a) {
8884 *output = invlist_clone(a);
8886 /* else *output already = a; */
8889 sv_2mortal(*output);
8894 /* Here both lists exist and are non-empty */
8895 array_a = invlist_array(a);
8896 array_b = invlist_array(b);
8898 /* If are to take the union of 'a' with the complement of b, set it
8899 * up so are looking at b's complement. */
8902 /* To complement, we invert: if the first element is 0, remove it. To
8903 * do this, we just pretend the array starts one later */
8904 if (array_b[0] == 0) {
8910 /* But if the first element is not zero, we pretend the list starts
8911 * at the 0 that is always stored immediately before the array. */
8917 /* Size the union for the worst case: that the sets are completely
8919 u = _new_invlist(len_a + len_b);
8921 /* Will contain U+0000 if either component does */
8922 array_u = _invlist_array_init(u, (len_a > 0 && array_a[0] == 0)
8923 || (len_b > 0 && array_b[0] == 0));
8925 /* Go through each list item by item, stopping when exhausted one of
8927 while (i_a < len_a && i_b < len_b) {
8928 UV cp; /* The element to potentially add to the union's array */
8929 bool cp_in_set; /* is it in the the input list's set or not */
8931 /* We need to take one or the other of the two inputs for the union.
8932 * Since we are merging two sorted lists, we take the smaller of the
8933 * next items. In case of a tie, we take the one that is in its set
8934 * first. If we took one not in the set first, it would decrement the
8935 * count, possibly to 0 which would cause it to be output as ending the
8936 * range, and the next time through we would take the same number, and
8937 * output it again as beginning the next range. By doing it the
8938 * opposite way, there is no possibility that the count will be
8939 * momentarily decremented to 0, and thus the two adjoining ranges will
8940 * be seamlessly merged. (In a tie and both are in the set or both not
8941 * in the set, it doesn't matter which we take first.) */
8942 if (array_a[i_a] < array_b[i_b]
8943 || (array_a[i_a] == array_b[i_b]
8944 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
8946 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
8950 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
8951 cp = array_b[i_b++];
8954 /* Here, have chosen which of the two inputs to look at. Only output
8955 * if the running count changes to/from 0, which marks the
8956 * beginning/end of a range in that's in the set */
8959 array_u[i_u++] = cp;
8966 array_u[i_u++] = cp;
8971 /* Here, we are finished going through at least one of the lists, which
8972 * means there is something remaining in at most one. We check if the list
8973 * that hasn't been exhausted is positioned such that we are in the middle
8974 * of a range in its set or not. (i_a and i_b point to the element beyond
8975 * the one we care about.) If in the set, we decrement 'count'; if 0, there
8976 * is potentially more to output.
8977 * There are four cases:
8978 * 1) Both weren't in their sets, count is 0, and remains 0. What's left
8979 * in the union is entirely from the non-exhausted set.
8980 * 2) Both were in their sets, count is 2. Nothing further should
8981 * be output, as everything that remains will be in the exhausted
8982 * list's set, hence in the union; decrementing to 1 but not 0 insures
8984 * 3) the exhausted was in its set, non-exhausted isn't, count is 1.
8985 * Nothing further should be output because the union includes
8986 * everything from the exhausted set. Not decrementing ensures that.
8987 * 4) the exhausted wasn't in its set, non-exhausted is, count is 1;
8988 * decrementing to 0 insures that we look at the remainder of the
8989 * non-exhausted set */
8990 if ((i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
8991 || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
8996 /* The final length is what we've output so far, plus what else is about to
8997 * be output. (If 'count' is non-zero, then the input list we exhausted
8998 * has everything remaining up to the machine's limit in its set, and hence
8999 * in the union, so there will be no further output. */
9002 /* At most one of the subexpressions will be non-zero */
9003 len_u += (len_a - i_a) + (len_b - i_b);
9006 /* Set result to final length, which can change the pointer to array_u, so
9008 if (len_u != _invlist_len(u)) {
9009 invlist_set_len(u, len_u, *get_invlist_offset_addr(u));
9011 array_u = invlist_array(u);
9014 /* When 'count' is 0, the list that was exhausted (if one was shorter than
9015 * the other) ended with everything above it not in its set. That means
9016 * that the remaining part of the union is precisely the same as the
9017 * non-exhausted list, so can just copy it unchanged. (If both list were
9018 * exhausted at the same time, then the operations below will be both 0.)
9021 IV copy_count; /* At most one will have a non-zero copy count */
9022 if ((copy_count = len_a - i_a) > 0) {
9023 Copy(array_a + i_a, array_u + i_u, copy_count, UV);
9025 else if ((copy_count = len_b - i_b) > 0) {
9026 Copy(array_b + i_b, array_u + i_u, copy_count, UV);
9030 /* We may be removing a reference to one of the inputs. If so, the output
9031 * is made mortal if the input was. (Mortal SVs shouldn't have their ref
9032 * count decremented) */
9033 if (a == *output || b == *output) {
9034 assert(! invlist_is_iterating(*output));
9035 if ((SvTEMP(*output))) {
9039 SvREFCNT_dec_NN(*output);
9049 Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9050 const bool complement_b, SV** i)
9052 /* Take the intersection of two inversion lists and point <i> to it. *i
9053 * SHOULD BE DEFINED upon input, and if it points to one of the two lists,
9054 * the reference count to that list will be decremented if not already a
9055 * temporary (mortal); otherwise *i will be made correspondingly mortal.
9056 * The first list, <a>, may be NULL, in which case an empty list is
9057 * returned. If <complement_b> is TRUE, the result will be the
9058 * intersection of <a> and the complement (or inversion) of <b> instead of
9061 * The basis for this comes from "Unicode Demystified" Chapter 13 by
9062 * Richard Gillam, published by Addison-Wesley, and explained at some
9063 * length there. The preface says to incorporate its examples into your
9064 * code at your own risk. In fact, it had bugs
9066 * The algorithm is like a merge sort, and is essentially the same as the
9070 const UV* array_a; /* a's array */
9072 UV len_a; /* length of a's array */
9075 SV* r; /* the resulting intersection */
9079 UV i_a = 0; /* current index into a's array */
9083 /* running count, as explained in the algorithm source book; items are
9084 * stopped accumulating and are output when the count changes to/from 2.
9085 * The count is incremented when we start a range that's in the set, and
9086 * decremented when we start a range that's not in the set. So its range
9087 * is 0 to 2. Only when the count is 2 is something in the intersection.
9091 PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
9094 /* Special case if either one is empty */
9095 len_a = (a == NULL) ? 0 : _invlist_len(a);
9096 if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
9097 bool make_temp = FALSE;
9099 if (len_a != 0 && complement_b) {
9101 /* Here, 'a' is not empty, therefore from the above 'if', 'b' must
9102 * be empty. Here, also we are using 'b's complement, which hence
9103 * must be every possible code point. Thus the intersection is
9107 if (! (make_temp = cBOOL(SvTEMP(b)))) {
9112 *i = invlist_clone(a);
9114 /* else *i is already 'a' */
9122 /* Here, 'a' or 'b' is empty and not using the complement of 'b'. The
9123 * intersection must be empty */
9125 if (! (make_temp = cBOOL(SvTEMP(a)))) {
9130 if (! (make_temp = cBOOL(SvTEMP(b)))) {
9134 *i = _new_invlist(0);
9142 /* Here both lists exist and are non-empty */
9143 array_a = invlist_array(a);
9144 array_b = invlist_array(b);
9146 /* If are to take the intersection of 'a' with the complement of b, set it
9147 * up so are looking at b's complement. */
9150 /* To complement, we invert: if the first element is 0, remove it. To
9151 * do this, we just pretend the array starts one later */
9152 if (array_b[0] == 0) {
9158 /* But if the first element is not zero, we pretend the list starts
9159 * at the 0 that is always stored immediately before the array. */
9165 /* Size the intersection for the worst case: that the intersection ends up
9166 * fragmenting everything to be completely disjoint */
9167 r= _new_invlist(len_a + len_b);
9169 /* Will contain U+0000 iff both components do */
9170 array_r = _invlist_array_init(r, len_a > 0 && array_a[0] == 0
9171 && len_b > 0 && array_b[0] == 0);
9173 /* Go through each list item by item, stopping when exhausted one of
9175 while (i_a < len_a && i_b < len_b) {
9176 UV cp; /* The element to potentially add to the intersection's
9178 bool cp_in_set; /* Is it in the input list's set or not */
9180 /* We need to take one or the other of the two inputs for the
9181 * intersection. Since we are merging two sorted lists, we take the
9182 * smaller of the next items. In case of a tie, we take the one that
9183 * is not in its set first (a difference from the union algorithm). If
9184 * we took one in the set first, it would increment the count, possibly
9185 * to 2 which would cause it to be output as starting a range in the
9186 * intersection, and the next time through we would take that same
9187 * number, and output it again as ending the set. By doing it the
9188 * opposite of this, there is no possibility that the count will be
9189 * momentarily incremented to 2. (In a tie and both are in the set or
9190 * both not in the set, it doesn't matter which we take first.) */
9191 if (array_a[i_a] < array_b[i_b]
9192 || (array_a[i_a] == array_b[i_b]
9193 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9195 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9199 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9203 /* Here, have chosen which of the two inputs to look at. Only output
9204 * if the running count changes to/from 2, which marks the
9205 * beginning/end of a range that's in the intersection */
9209 array_r[i_r++] = cp;
9214 array_r[i_r++] = cp;
9220 /* Here, we are finished going through at least one of the lists, which
9221 * means there is something remaining in at most one. We check if the list
9222 * that has been exhausted is positioned such that we are in the middle
9223 * of a range in its set or not. (i_a and i_b point to elements 1 beyond
9224 * the ones we care about.) There are four cases:
9225 * 1) Both weren't in their sets, count is 0, and remains 0. There's
9226 * nothing left in the intersection.
9227 * 2) Both were in their sets, count is 2 and perhaps is incremented to
9228 * above 2. What should be output is exactly that which is in the
9229 * non-exhausted set, as everything it has is also in the intersection
9230 * set, and everything it doesn't have can't be in the intersection
9231 * 3) The exhausted was in its set, non-exhausted isn't, count is 1, and
9232 * gets incremented to 2. Like the previous case, the intersection is
9233 * everything that remains in the non-exhausted set.
9234 * 4) the exhausted wasn't in its set, non-exhausted is, count is 1, and
9235 * remains 1. And the intersection has nothing more. */
9236 if ((i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9237 || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9242 /* The final length is what we've output so far plus what else is in the
9243 * intersection. At most one of the subexpressions below will be non-zero
9247 len_r += (len_a - i_a) + (len_b - i_b);
9250 /* Set result to final length, which can change the pointer to array_r, so
9252 if (len_r != _invlist_len(r)) {
9253 invlist_set_len(r, len_r, *get_invlist_offset_addr(r));
9255 array_r = invlist_array(r);
9258 /* Finish outputting any remaining */
9259 if (count >= 2) { /* At most one will have a non-zero copy count */
9261 if ((copy_count = len_a - i_a) > 0) {
9262 Copy(array_a + i_a, array_r + i_r, copy_count, UV);
9264 else if ((copy_count = len_b - i_b) > 0) {
9265 Copy(array_b + i_b, array_r + i_r, copy_count, UV);
9269 /* We may be removing a reference to one of the inputs. If so, the output
9270 * is made mortal if the input was. (Mortal SVs shouldn't have their ref
9271 * count decremented) */
9272 if (a == *i || b == *i) {
9273 assert(! invlist_is_iterating(*i));
9278 SvREFCNT_dec_NN(*i);
9288 Perl__add_range_to_invlist(pTHX_ SV* invlist, const UV start, const UV end)
9290 /* Add the range from 'start' to 'end' inclusive to the inversion list's
9291 * set. A pointer to the inversion list is returned. This may actually be
9292 * a new list, in which case the passed in one has been destroyed. The
9293 * passed-in inversion list can be NULL, in which case a new one is created
9294 * with just the one range in it */
9299 if (invlist == NULL) {
9300 invlist = _new_invlist(2);
9304 len = _invlist_len(invlist);
9307 /* If comes after the final entry actually in the list, can just append it
9310 || (! ELEMENT_RANGE_MATCHES_INVLIST(len - 1)
9311 && start >= invlist_array(invlist)[len - 1]))
9313 _append_range_to_invlist(invlist, start, end);
9317 /* Here, can't just append things, create and return a new inversion list
9318 * which is the union of this range and the existing inversion list. (If
9319 * the new range is well-behaved wrt to the old one, we could just insert
9320 * it, doing a Move() down on the tail of the old one (potentially growing
9321 * it first). But to determine that means we would have the extra
9322 * (possibly throw-away) work of first finding where the new one goes and
9323 * whether it disrupts (splits) an existing range, so it doesn't appear to
9324 * me (khw) that it's worth it) */
9325 range_invlist = _new_invlist(2);
9326 _append_range_to_invlist(range_invlist, start, end);
9328 _invlist_union(invlist, range_invlist, &invlist);
9330 /* The temporary can be freed */
9331 SvREFCNT_dec_NN(range_invlist);
9337 Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0,
9338 UV** other_elements_ptr)
9340 /* Create and return an inversion list whose contents are to be populated
9341 * by the caller. The caller gives the number of elements (in 'size') and
9342 * the very first element ('element0'). This function will set
9343 * '*other_elements_ptr' to an array of UVs, where the remaining elements
9346 * Obviously there is some trust involved that the caller will properly
9347 * fill in the other elements of the array.
9349 * (The first element needs to be passed in, as the underlying code does
9350 * things differently depending on whether it is zero or non-zero) */
9352 SV* invlist = _new_invlist(size);
9355 PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST;
9357 _append_range_to_invlist(invlist, element0, element0);
9358 offset = *get_invlist_offset_addr(invlist);
9360 invlist_set_len(invlist, size, offset);
9361 *other_elements_ptr = invlist_array(invlist) + 1;
9367 PERL_STATIC_INLINE SV*
9368 S_add_cp_to_invlist(pTHX_ SV* invlist, const UV cp) {
9369 return _add_range_to_invlist(invlist, cp, cp);
9372 #ifndef PERL_IN_XSUB_RE
9374 Perl__invlist_invert(pTHX_ SV* const invlist)
9376 /* Complement the input inversion list. This adds a 0 if the list didn't
9377 * have a zero; removes it otherwise. As described above, the data
9378 * structure is set up so that this is very efficient */
9380 PERL_ARGS_ASSERT__INVLIST_INVERT;
9382 assert(! invlist_is_iterating(invlist));
9384 /* The inverse of matching nothing is matching everything */
9385 if (_invlist_len(invlist) == 0) {
9386 _append_range_to_invlist(invlist, 0, UV_MAX);
9390 *get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist);
9395 PERL_STATIC_INLINE SV*
9396 S_invlist_clone(pTHX_ SV* const invlist)
9399 /* Return a new inversion list that is a copy of the input one, which is
9400 * unchanged. The new list will not be mortal even if the old one was. */
9402 /* Need to allocate extra space to accommodate Perl's addition of a
9403 * trailing NUL to SvPV's, since it thinks they are always strings */
9404 SV* new_invlist = _new_invlist(_invlist_len(invlist) + 1);
9405 STRLEN physical_length = SvCUR(invlist);
9406 bool offset = *(get_invlist_offset_addr(invlist));
9408 PERL_ARGS_ASSERT_INVLIST_CLONE;
9410 *(get_invlist_offset_addr(new_invlist)) = offset;
9411 invlist_set_len(new_invlist, _invlist_len(invlist), offset);
9412 Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char);
9417 PERL_STATIC_INLINE STRLEN*
9418 S_get_invlist_iter_addr(SV* invlist)
9420 /* Return the address of the UV that contains the current iteration
9423 PERL_ARGS_ASSERT_GET_INVLIST_ITER_ADDR;
9425 assert(SvTYPE(invlist) == SVt_INVLIST);
9427 return &(((XINVLIST*) SvANY(invlist))->iterator);
9430 PERL_STATIC_INLINE void
9431 S_invlist_iterinit(SV* invlist) /* Initialize iterator for invlist */
9433 PERL_ARGS_ASSERT_INVLIST_ITERINIT;
9435 *get_invlist_iter_addr(invlist) = 0;
9438 PERL_STATIC_INLINE void
9439 S_invlist_iterfinish(SV* invlist)
9441 /* Terminate iterator for invlist. This is to catch development errors.
9442 * Any iteration that is interrupted before completed should call this
9443 * function. Functions that add code points anywhere else but to the end
9444 * of an inversion list assert that they are not in the middle of an
9445 * iteration. If they were, the addition would make the iteration
9446 * problematical: if the iteration hadn't reached the place where things
9447 * were being added, it would be ok */
9449 PERL_ARGS_ASSERT_INVLIST_ITERFINISH;
9451 *get_invlist_iter_addr(invlist) = (STRLEN) UV_MAX;
9455 S_invlist_iternext(SV* invlist, UV* start, UV* end)
9457 /* An C<invlist_iterinit> call on <invlist> must be used to set this up.
9458 * This call sets in <*start> and <*end>, the next range in <invlist>.
9459 * Returns <TRUE> if successful and the next call will return the next
9460 * range; <FALSE> if was already at the end of the list. If the latter,
9461 * <*start> and <*end> are unchanged, and the next call to this function
9462 * will start over at the beginning of the list */
9464 STRLEN* pos = get_invlist_iter_addr(invlist);
9465 UV len = _invlist_len(invlist);
9468 PERL_ARGS_ASSERT_INVLIST_ITERNEXT;
9471 *pos = (STRLEN) UV_MAX; /* Force iterinit() to be required next time */
9475 array = invlist_array(invlist);
9477 *start = array[(*pos)++];
9483 *end = array[(*pos)++] - 1;
9489 PERL_STATIC_INLINE UV
9490 S_invlist_highest(SV* const invlist)
9492 /* Returns the highest code point that matches an inversion list. This API
9493 * has an ambiguity, as it returns 0 under either the highest is actually
9494 * 0, or if the list is empty. If this distinction matters to you, check
9495 * for emptiness before calling this function */
9497 UV len = _invlist_len(invlist);
9500 PERL_ARGS_ASSERT_INVLIST_HIGHEST;
9506 array = invlist_array(invlist);
9508 /* The last element in the array in the inversion list always starts a
9509 * range that goes to infinity. That range may be for code points that are
9510 * matched in the inversion list, or it may be for ones that aren't
9511 * matched. In the latter case, the highest code point in the set is one
9512 * less than the beginning of this range; otherwise it is the final element
9513 * of this range: infinity */
9514 return (ELEMENT_RANGE_MATCHES_INVLIST(len - 1))
9516 : array[len - 1] - 1;
9519 #ifndef PERL_IN_XSUB_RE
9521 Perl__invlist_contents(pTHX_ SV* const invlist)
9523 /* Get the contents of an inversion list into a string SV so that they can
9524 * be printed out. It uses the format traditionally done for debug tracing
9528 SV* output = newSVpvs("\n");
9530 PERL_ARGS_ASSERT__INVLIST_CONTENTS;
9532 assert(! invlist_is_iterating(invlist));
9534 invlist_iterinit(invlist);
9535 while (invlist_iternext(invlist, &start, &end)) {
9536 if (end == UV_MAX) {
9537 Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\tINFINITY\n", start);
9539 else if (end != start) {
9540 Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\t%04"UVXf"\n",
9544 Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\n", start);
9552 #ifndef PERL_IN_XSUB_RE
9554 Perl__invlist_dump(pTHX_ PerlIO *file, I32 level,
9555 const char * const indent, SV* const invlist)
9557 /* Designed to be called only by do_sv_dump(). Dumps out the ranges of the
9558 * inversion list 'invlist' to 'file' at 'level' Each line is prefixed by
9559 * the string 'indent'. The output looks like this:
9560 [0] 0x000A .. 0x000D
9562 [4] 0x2028 .. 0x2029
9563 [6] 0x3104 .. INFINITY
9564 * This means that the first range of code points matched by the list are
9565 * 0xA through 0xD; the second range contains only the single code point
9566 * 0x85, etc. An inversion list is an array of UVs. Two array elements
9567 * are used to define each range (except if the final range extends to
9568 * infinity, only a single element is needed). The array index of the
9569 * first element for the corresponding range is given in brackets. */
9574 PERL_ARGS_ASSERT__INVLIST_DUMP;
9576 if (invlist_is_iterating(invlist)) {
9577 Perl_dump_indent(aTHX_ level, file,
9578 "%sCan't dump inversion list because is in middle of iterating\n",
9583 invlist_iterinit(invlist);
9584 while (invlist_iternext(invlist, &start, &end)) {
9585 if (end == UV_MAX) {
9586 Perl_dump_indent(aTHX_ level, file,
9587 "%s[%"UVuf"] 0x%04"UVXf" .. INFINITY\n",
9588 indent, (UV)count, start);
9590 else if (end != start) {
9591 Perl_dump_indent(aTHX_ level, file,
9592 "%s[%"UVuf"] 0x%04"UVXf" .. 0x%04"UVXf"\n",
9593 indent, (UV)count, start, end);
9596 Perl_dump_indent(aTHX_ level, file, "%s[%"UVuf"] 0x%04"UVXf"\n",
9597 indent, (UV)count, start);
9604 Perl__load_PL_utf8_foldclosures (pTHX)
9606 assert(! PL_utf8_foldclosures);
9608 /* If the folds haven't been read in, call a fold function
9610 if (! PL_utf8_tofold) {
9611 U8 dummy[UTF8_MAXBYTES_CASE+1];
9613 /* This string is just a short named one above \xff */
9614 to_utf8_fold((U8*) HYPHEN_UTF8, dummy, NULL);
9615 assert(PL_utf8_tofold); /* Verify that worked */
9617 PL_utf8_foldclosures = _swash_inversion_hash(PL_utf8_tofold);
9621 #if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE)
9623 Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b)
9625 /* Return a boolean as to if the two passed in inversion lists are
9626 * identical. The final argument, if TRUE, says to take the complement of
9627 * the second inversion list before doing the comparison */
9629 const UV* array_a = invlist_array(a);
9630 const UV* array_b = invlist_array(b);
9631 UV len_a = _invlist_len(a);
9632 UV len_b = _invlist_len(b);
9634 UV i = 0; /* current index into the arrays */
9635 bool retval = TRUE; /* Assume are identical until proven otherwise */
9637 PERL_ARGS_ASSERT__INVLISTEQ;
9639 /* If are to compare 'a' with the complement of b, set it
9640 * up so are looking at b's complement. */
9643 /* The complement of nothing is everything, so <a> would have to have
9644 * just one element, starting at zero (ending at infinity) */
9646 return (len_a == 1 && array_a[0] == 0);
9648 else if (array_b[0] == 0) {
9650 /* Otherwise, to complement, we invert. Here, the first element is
9651 * 0, just remove it. To do this, we just pretend the array starts
9659 /* But if the first element is not zero, we pretend the list starts
9660 * at the 0 that is always stored immediately before the array. */
9666 /* Make sure that the lengths are the same, as well as the final element
9667 * before looping through the remainder. (Thus we test the length, final,
9668 * and first elements right off the bat) */
9669 if (len_a != len_b || array_a[len_a-1] != array_b[len_a-1]) {
9672 else for (i = 0; i < len_a - 1; i++) {
9673 if (array_a[i] != array_b[i]) {
9684 * As best we can, determine the characters that can match the start of
9685 * the given EXACTF-ish node.
9687 * Returns the invlist as a new SV*; it is the caller's responsibility to
9688 * call SvREFCNT_dec() when done with it.
9691 S__make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node)
9693 const U8 * s = (U8*)STRING(node);
9694 SSize_t bytelen = STR_LEN(node);
9696 /* Start out big enough for 2 separate code points */
9697 SV* invlist = _new_invlist(4);
9699 PERL_ARGS_ASSERT__MAKE_EXACTF_INVLIST;
9704 /* We punt and assume can match anything if the node begins
9705 * with a multi-character fold. Things are complicated. For
9706 * example, /ffi/i could match any of:
9707 * "\N{LATIN SMALL LIGATURE FFI}"
9708 * "\N{LATIN SMALL LIGATURE FF}I"
9709 * "F\N{LATIN SMALL LIGATURE FI}"
9710 * plus several other things; and making sure we have all the
9711 * possibilities is hard. */
9712 if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) {
9713 invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
9716 /* Any Latin1 range character can potentially match any
9717 * other depending on the locale */
9718 if (OP(node) == EXACTFL) {
9719 _invlist_union(invlist, PL_Latin1, &invlist);
9722 /* But otherwise, it matches at least itself. We can
9723 * quickly tell if it has a distinct fold, and if so,
9724 * it matches that as well */
9725 invlist = add_cp_to_invlist(invlist, uc);
9726 if (IS_IN_SOME_FOLD_L1(uc))
9727 invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]);
9730 /* Some characters match above-Latin1 ones under /i. This
9731 * is true of EXACTFL ones when the locale is UTF-8 */
9732 if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc)
9733 && (! isASCII(uc) || (OP(node) != EXACTFA
9734 && OP(node) != EXACTFA_NO_TRIE)))
9736 add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist);
9740 else { /* Pattern is UTF-8 */
9741 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
9742 STRLEN foldlen = UTF8SKIP(s);
9743 const U8* e = s + bytelen;
9746 uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
9748 /* The only code points that aren't folded in a UTF EXACTFish
9749 * node are are the problematic ones in EXACTFL nodes */
9750 if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) {
9751 /* We need to check for the possibility that this EXACTFL
9752 * node begins with a multi-char fold. Therefore we fold
9753 * the first few characters of it so that we can make that
9758 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) {
9760 *(d++) = (U8) toFOLD(*s);
9765 to_utf8_fold(s, d, &len);
9771 /* And set up so the code below that looks in this folded
9772 * buffer instead of the node's string */
9774 foldlen = UTF8SKIP(folded);
9778 /* When we reach here 's' points to the fold of the first
9779 * character(s) of the node; and 'e' points to far enough along
9780 * the folded string to be just past any possible multi-char
9781 * fold. 'foldlen' is the length in bytes of the first
9784 * Unlike the non-UTF-8 case, the macro for determining if a
9785 * string is a multi-char fold requires all the characters to
9786 * already be folded. This is because of all the complications
9787 * if not. Note that they are folded anyway, except in EXACTFL
9788 * nodes. Like the non-UTF case above, we punt if the node
9789 * begins with a multi-char fold */
9791 if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) {
9792 invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
9794 else { /* Single char fold */
9796 /* It matches all the things that fold to it, which are
9797 * found in PL_utf8_foldclosures (including itself) */
9798 invlist = add_cp_to_invlist(invlist, uc);
9799 if (! PL_utf8_foldclosures)
9800 _load_PL_utf8_foldclosures();
9801 if ((listp = hv_fetch(PL_utf8_foldclosures,
9802 (char *) s, foldlen, FALSE)))
9804 AV* list = (AV*) *listp;
9806 for (k = 0; k <= av_tindex(list); k++) {
9807 SV** c_p = av_fetch(list, k, FALSE);
9813 /* /aa doesn't allow folds between ASCII and non- */
9814 if ((OP(node) == EXACTFA || OP(node) == EXACTFA_NO_TRIE)
9815 && isASCII(c) != isASCII(uc))
9820 invlist = add_cp_to_invlist(invlist, c);
9829 #undef HEADER_LENGTH
9830 #undef TO_INTERNAL_SIZE
9831 #undef FROM_INTERNAL_SIZE
9832 #undef INVLIST_VERSION_ID
9834 /* End of inversion list object */
9837 S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state)
9839 /* This parses the flags that are in either the '(?foo)' or '(?foo:bar)'
9840 * constructs, and updates RExC_flags with them. On input, RExC_parse
9841 * should point to the first flag; it is updated on output to point to the
9842 * final ')' or ':'. There needs to be at least one flag, or this will
9845 /* for (?g), (?gc), and (?o) warnings; warning
9846 about (?c) will warn about (?g) -- japhy */
9848 #define WASTED_O 0x01
9849 #define WASTED_G 0x02
9850 #define WASTED_C 0x04
9851 #define WASTED_GC (WASTED_G|WASTED_C)
9852 I32 wastedflags = 0x00;
9853 U32 posflags = 0, negflags = 0;
9854 U32 *flagsp = &posflags;
9855 char has_charset_modifier = '\0';
9857 bool has_use_defaults = FALSE;
9858 const char* const seqstart = RExC_parse - 1; /* Point to the '?' */
9859 int x_mod_count = 0;
9861 PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS;
9863 /* '^' as an initial flag sets certain defaults */
9864 if (UCHARAT(RExC_parse) == '^') {
9866 has_use_defaults = TRUE;
9867 STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
9868 set_regex_charset(&RExC_flags, (RExC_utf8 || RExC_uni_semantics)
9869 ? REGEX_UNICODE_CHARSET
9870 : REGEX_DEPENDS_CHARSET);
9873 cs = get_regex_charset(RExC_flags);
9874 if (cs == REGEX_DEPENDS_CHARSET
9875 && (RExC_utf8 || RExC_uni_semantics))
9877 cs = REGEX_UNICODE_CHARSET;
9880 while (RExC_parse < RExC_end) {
9881 /* && strchr("iogcmsx", *RExC_parse) */
9882 /* (?g), (?gc) and (?o) are useless here
9883 and must be globally applied -- japhy */
9884 switch (*RExC_parse) {
9886 /* Code for the imsxn flags */
9887 CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count);
9889 case LOCALE_PAT_MOD:
9890 if (has_charset_modifier) {
9891 goto excess_modifier;
9893 else if (flagsp == &negflags) {
9896 cs = REGEX_LOCALE_CHARSET;
9897 has_charset_modifier = LOCALE_PAT_MOD;
9899 case UNICODE_PAT_MOD:
9900 if (has_charset_modifier) {
9901 goto excess_modifier;
9903 else if (flagsp == &negflags) {
9906 cs = REGEX_UNICODE_CHARSET;
9907 has_charset_modifier = UNICODE_PAT_MOD;
9909 case ASCII_RESTRICT_PAT_MOD:
9910 if (flagsp == &negflags) {
9913 if (has_charset_modifier) {
9914 if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
9915 goto excess_modifier;
9917 /* Doubled modifier implies more restricted */
9918 cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
9921 cs = REGEX_ASCII_RESTRICTED_CHARSET;
9923 has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
9925 case DEPENDS_PAT_MOD:
9926 if (has_use_defaults) {
9927 goto fail_modifiers;
9929 else if (flagsp == &negflags) {
9932 else if (has_charset_modifier) {
9933 goto excess_modifier;
9936 /* The dual charset means unicode semantics if the
9937 * pattern (or target, not known until runtime) are
9938 * utf8, or something in the pattern indicates unicode
9940 cs = (RExC_utf8 || RExC_uni_semantics)
9941 ? REGEX_UNICODE_CHARSET
9942 : REGEX_DEPENDS_CHARSET;
9943 has_charset_modifier = DEPENDS_PAT_MOD;
9947 if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
9948 vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
9950 else if (has_charset_modifier == *(RExC_parse - 1)) {
9951 vFAIL2("Regexp modifier \"%c\" may not appear twice",
9955 vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
9957 NOT_REACHED; /*NOTREACHED*/
9960 vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"",
9962 NOT_REACHED; /*NOTREACHED*/
9963 case ONCE_PAT_MOD: /* 'o' */
9964 case GLOBAL_PAT_MOD: /* 'g' */
9965 if (PASS2 && ckWARN(WARN_REGEXP)) {
9966 const I32 wflagbit = *RExC_parse == 'o'
9969 if (! (wastedflags & wflagbit) ) {
9970 wastedflags |= wflagbit;
9971 /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
9974 "Useless (%s%c) - %suse /%c modifier",
9975 flagsp == &negflags ? "?-" : "?",
9977 flagsp == &negflags ? "don't " : "",
9984 case CONTINUE_PAT_MOD: /* 'c' */
9985 if (PASS2 && ckWARN(WARN_REGEXP)) {
9986 if (! (wastedflags & WASTED_C) ) {
9987 wastedflags |= WASTED_GC;
9988 /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
9991 "Useless (%sc) - %suse /gc modifier",
9992 flagsp == &negflags ? "?-" : "?",
9993 flagsp == &negflags ? "don't " : ""
9998 case KEEPCOPY_PAT_MOD: /* 'p' */
9999 if (flagsp == &negflags) {
10001 ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
10003 *flagsp |= RXf_PMf_KEEPCOPY;
10007 /* A flag is a default iff it is following a minus, so
10008 * if there is a minus, it means will be trying to
10009 * re-specify a default which is an error */
10010 if (has_use_defaults || flagsp == &negflags) {
10011 goto fail_modifiers;
10013 flagsp = &negflags;
10014 wastedflags = 0; /* reset so (?g-c) warns twice */
10018 RExC_flags |= posflags;
10019 RExC_flags &= ~negflags;
10020 set_regex_charset(&RExC_flags, cs);
10021 if (RExC_flags & RXf_PMf_FOLD) {
10022 RExC_contains_i = 1;
10025 STD_PMMOD_FLAGS_PARSE_X_WARN(x_mod_count);
10031 RExC_parse += SKIP_IF_CHAR(RExC_parse);
10032 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
10033 vFAIL2utf8f("Sequence (%"UTF8f"...) not recognized",
10034 UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
10035 NOT_REACHED; /*NOTREACHED*/
10038 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10041 vFAIL("Sequence (?... not terminated");
10045 - reg - regular expression, i.e. main body or parenthesized thing
10047 * Caller must absorb opening parenthesis.
10049 * Combining parenthesis handling with the base level of regular expression
10050 * is a trifle forced, but the need to tie the tails of the branches to what
10051 * follows makes it hard to avoid.
10053 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
10055 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
10057 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
10060 PERL_STATIC_INLINE regnode *
10061 S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state,
10063 char * parse_start,
10068 char* name_start = RExC_parse;
10070 SV *sv_dat = reg_scan_name(pRExC_state, SIZE_ONLY
10071 ? REG_RSN_RETURN_NULL
10072 : REG_RSN_RETURN_DATA);
10073 GET_RE_DEBUG_FLAGS_DECL;
10075 PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF;
10077 if (RExC_parse == name_start || *RExC_parse != ch) {
10078 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
10079 vFAIL2("Sequence %.3s... not terminated",parse_start);
10083 num = add_data( pRExC_state, STR_WITH_LEN("S"));
10084 RExC_rxi->data->data[num]=(void*)sv_dat;
10085 SvREFCNT_inc_simple_void(sv_dat);
10088 ret = reganode(pRExC_state,
10091 : (ASCII_FOLD_RESTRICTED)
10093 : (AT_LEAST_UNI_SEMANTICS)
10099 *flagp |= HASWIDTH;
10101 Set_Node_Offset(ret, parse_start+1);
10102 Set_Node_Cur_Length(ret, parse_start);
10104 nextchar(pRExC_state);
10108 /* Returns NULL, setting *flagp to TRYAGAIN at the end of (?) that only sets
10109 flags. Returns NULL, setting *flagp to RESTART_PASS1 if the sizing scan
10110 needs to be restarted, or'd with NEED_UTF8 if the pattern needs to be
10111 upgraded to UTF-8. Otherwise would only return NULL if regbranch() returns
10112 NULL, which cannot happen. */
10114 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
10115 /* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter.
10116 * 2 is like 1, but indicates that nextchar() has been called to advance
10117 * RExC_parse beyond the '('. Things like '(?' are indivisible tokens, and
10118 * this flag alerts us to the need to check for that */
10120 regnode *ret; /* Will be the head of the group. */
10123 regnode *ender = NULL;
10126 U32 oregflags = RExC_flags;
10127 bool have_branch = 0;
10129 I32 freeze_paren = 0;
10130 I32 after_freeze = 0;
10131 I32 num; /* numeric backreferences */
10133 char * parse_start = RExC_parse; /* MJD */
10134 char * const oregcomp_parse = RExC_parse;
10136 GET_RE_DEBUG_FLAGS_DECL;
10138 PERL_ARGS_ASSERT_REG;
10139 DEBUG_PARSE("reg ");
10141 *flagp = 0; /* Tentatively. */
10143 /* Having this true makes it feasible to have a lot fewer tests for the
10144 * parse pointer being in scope. For example, we can write
10145 * while(isFOO(*RExC_parse)) RExC_parse++;
10147 * while(RExC_parse < RExC_end && isFOO(*RExC_parse)) RExC_parse++;
10149 assert(*RExC_end == '\0');
10151 /* Make an OPEN node, if parenthesized. */
10154 /* Under /x, space and comments can be gobbled up between the '(' and
10155 * here (if paren ==2). The forms '(*VERB' and '(?...' disallow such
10156 * intervening space, as the sequence is a token, and a token should be
10158 bool has_intervening_patws = paren == 2 && *(RExC_parse - 1) != '(';
10160 assert(RExC_parse < RExC_end);
10162 if ( *RExC_parse == '*') { /* (*VERB:ARG) */
10163 char *start_verb = RExC_parse + 1;
10165 char *start_arg = NULL;
10166 unsigned char op = 0;
10167 int arg_required = 0;
10168 int internal_argval = -1; /* if >-1 we are not allowed an argument*/
10170 if (has_intervening_patws) {
10171 RExC_parse++; /* past the '*' */
10172 vFAIL("In '(*VERB...)', the '(' and '*' must be adjacent");
10174 while (RExC_parse < RExC_end && *RExC_parse != ')' ) {
10175 if ( *RExC_parse == ':' ) {
10176 start_arg = RExC_parse + 1;
10179 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10181 verb_len = RExC_parse - start_verb;
10183 if (RExC_parse >= RExC_end) {
10184 goto unterminated_verb_pattern;
10186 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10187 while ( RExC_parse < RExC_end && *RExC_parse != ')' )
10188 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10189 if ( RExC_parse >= RExC_end || *RExC_parse != ')' )
10190 unterminated_verb_pattern:
10191 vFAIL("Unterminated verb pattern argument");
10192 if ( RExC_parse == start_arg )
10195 if ( RExC_parse >= RExC_end || *RExC_parse != ')' )
10196 vFAIL("Unterminated verb pattern");
10199 /* Here, we know that RExC_parse < RExC_end */
10201 switch ( *start_verb ) {
10202 case 'A': /* (*ACCEPT) */
10203 if ( memEQs(start_verb,verb_len,"ACCEPT") ) {
10205 internal_argval = RExC_nestroot;
10208 case 'C': /* (*COMMIT) */
10209 if ( memEQs(start_verb,verb_len,"COMMIT") )
10212 case 'F': /* (*FAIL) */
10213 if ( verb_len==1 || memEQs(start_verb,verb_len,"FAIL") ) {
10217 case ':': /* (*:NAME) */
10218 case 'M': /* (*MARK:NAME) */
10219 if ( verb_len==0 || memEQs(start_verb,verb_len,"MARK") ) {
10224 case 'P': /* (*PRUNE) */
10225 if ( memEQs(start_verb,verb_len,"PRUNE") )
10228 case 'S': /* (*SKIP) */
10229 if ( memEQs(start_verb,verb_len,"SKIP") )
10232 case 'T': /* (*THEN) */
10233 /* [19:06] <TimToady> :: is then */
10234 if ( memEQs(start_verb,verb_len,"THEN") ) {
10236 RExC_seen |= REG_CUTGROUP_SEEN;
10241 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10243 "Unknown verb pattern '%"UTF8f"'",
10244 UTF8fARG(UTF, verb_len, start_verb));
10246 if ( arg_required && !start_arg ) {
10247 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
10248 verb_len, start_verb);
10250 if (internal_argval == -1) {
10251 ret = reganode(pRExC_state, op, 0);
10253 ret = reg2Lanode(pRExC_state, op, 0, internal_argval);
10255 RExC_seen |= REG_VERBARG_SEEN;
10256 if ( ! SIZE_ONLY ) {
10258 SV *sv = newSVpvn( start_arg,
10259 RExC_parse - start_arg);
10260 ARG(ret) = add_data( pRExC_state,
10261 STR_WITH_LEN("S"));
10262 RExC_rxi->data->data[ARG(ret)]=(void*)sv;
10267 if ( internal_argval != -1 )
10268 ARG2L_SET(ret, internal_argval);
10270 nextchar(pRExC_state);
10273 else if (*RExC_parse == '?') { /* (?...) */
10274 bool is_logical = 0;
10275 const char * const seqstart = RExC_parse;
10276 const char * endptr;
10277 if (has_intervening_patws) {
10279 vFAIL("In '(?...)', the '(' and '?' must be adjacent");
10282 RExC_parse++; /* past the '?' */
10283 paren = *RExC_parse; /* might be a trailing NUL, if not
10285 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10286 if (RExC_parse > RExC_end) {
10289 ret = NULL; /* For look-ahead/behind. */
10292 case 'P': /* (?P...) variants for those used to PCRE/Python */
10293 paren = *RExC_parse;
10294 if ( paren == '<') { /* (?P<...>) named capture */
10296 if (RExC_parse >= RExC_end) {
10297 vFAIL("Sequence (?P<... not terminated");
10299 goto named_capture;
10301 else if (paren == '>') { /* (?P>name) named recursion */
10303 if (RExC_parse >= RExC_end) {
10304 vFAIL("Sequence (?P>... not terminated");
10306 goto named_recursion;
10308 else if (paren == '=') { /* (?P=...) named backref */
10310 return handle_named_backref(pRExC_state, flagp,
10313 RExC_parse += SKIP_IF_CHAR(RExC_parse);
10314 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
10315 vFAIL3("Sequence (%.*s...) not recognized",
10316 RExC_parse-seqstart, seqstart);
10317 NOT_REACHED; /*NOTREACHED*/
10318 case '<': /* (?<...) */
10319 if (*RExC_parse == '!')
10321 else if (*RExC_parse != '=')
10328 case '\'': /* (?'...') */
10329 name_start = RExC_parse;
10330 svname = reg_scan_name(pRExC_state,
10331 SIZE_ONLY /* reverse test from the others */
10332 ? REG_RSN_RETURN_NAME
10333 : REG_RSN_RETURN_NULL);
10334 if ( RExC_parse == name_start
10335 || RExC_parse >= RExC_end
10336 || *RExC_parse != paren)
10338 vFAIL2("Sequence (?%c... not terminated",
10339 paren=='>' ? '<' : paren);
10344 if (!svname) /* shouldn't happen */
10346 "panic: reg_scan_name returned NULL");
10347 if (!RExC_paren_names) {
10348 RExC_paren_names= newHV();
10349 sv_2mortal(MUTABLE_SV(RExC_paren_names));
10351 RExC_paren_name_list= newAV();
10352 sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
10355 he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
10357 sv_dat = HeVAL(he_str);
10359 /* croak baby croak */
10361 "panic: paren_name hash element allocation failed");
10362 } else if ( SvPOK(sv_dat) ) {
10363 /* (?|...) can mean we have dupes so scan to check
10364 its already been stored. Maybe a flag indicating
10365 we are inside such a construct would be useful,
10366 but the arrays are likely to be quite small, so
10367 for now we punt -- dmq */
10368 IV count = SvIV(sv_dat);
10369 I32 *pv = (I32*)SvPVX(sv_dat);
10371 for ( i = 0 ; i < count ; i++ ) {
10372 if ( pv[i] == RExC_npar ) {
10378 pv = (I32*)SvGROW(sv_dat,
10379 SvCUR(sv_dat) + sizeof(I32)+1);
10380 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
10381 pv[count] = RExC_npar;
10382 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
10385 (void)SvUPGRADE(sv_dat,SVt_PVNV);
10386 sv_setpvn(sv_dat, (char *)&(RExC_npar),
10389 SvIV_set(sv_dat, 1);
10392 /* Yes this does cause a memory leak in debugging Perls
10394 if (!av_store(RExC_paren_name_list,
10395 RExC_npar, SvREFCNT_inc(svname)))
10396 SvREFCNT_dec_NN(svname);
10399 /*sv_dump(sv_dat);*/
10401 nextchar(pRExC_state);
10403 goto capturing_parens;
10405 RExC_seen |= REG_LOOKBEHIND_SEEN;
10406 RExC_in_lookbehind++;
10408 assert(RExC_parse < RExC_end);
10410 case '=': /* (?=...) */
10411 RExC_seen_zerolen++;
10413 case '!': /* (?!...) */
10414 RExC_seen_zerolen++;
10415 /* check if we're really just a "FAIL" assertion */
10416 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
10417 FALSE /* Don't force to /x */ );
10418 if (*RExC_parse == ')') {
10419 ret=reganode(pRExC_state, OPFAIL, 0);
10420 nextchar(pRExC_state);
10424 case '|': /* (?|...) */
10425 /* branch reset, behave like a (?:...) except that
10426 buffers in alternations share the same numbers */
10428 after_freeze = freeze_paren = RExC_npar;
10430 case ':': /* (?:...) */
10431 case '>': /* (?>...) */
10433 case '$': /* (?$...) */
10434 case '@': /* (?@...) */
10435 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
10437 case '0' : /* (?0) */
10438 case 'R' : /* (?R) */
10439 if (*RExC_parse != ')')
10440 FAIL("Sequence (?R) not terminated");
10441 ret = reg_node(pRExC_state, GOSTART);
10442 RExC_seen |= REG_GOSTART_SEEN;
10443 *flagp |= POSTPONED;
10444 nextchar(pRExC_state);
10447 /* named and numeric backreferences */
10448 case '&': /* (?&NAME) */
10449 parse_start = RExC_parse - 1;
10452 SV *sv_dat = reg_scan_name(pRExC_state,
10453 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
10454 num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
10456 if (RExC_parse >= RExC_end || *RExC_parse != ')')
10457 vFAIL("Sequence (?&... not terminated");
10458 goto gen_recurse_regop;
10461 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
10463 vFAIL("Illegal pattern");
10465 goto parse_recursion;
10467 case '-': /* (?-1) */
10468 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
10469 RExC_parse--; /* rewind to let it be handled later */
10473 case '1': case '2': case '3': case '4': /* (?1) */
10474 case '5': case '6': case '7': case '8': case '9':
10475 RExC_parse = (char *) seqstart + 1; /* Point to the digit */
10478 bool is_neg = FALSE;
10480 parse_start = RExC_parse - 1; /* MJD */
10481 if (*RExC_parse == '-') {
10485 if (grok_atoUV(RExC_parse, &unum, &endptr)
10489 RExC_parse = (char*)endptr;
10493 /* Some limit for num? */
10497 if (*RExC_parse!=')')
10498 vFAIL("Expecting close bracket");
10501 if ( paren == '-' ) {
10503 Diagram of capture buffer numbering.
10504 Top line is the normal capture buffer numbers
10505 Bottom line is the negative indexing as from
10509 /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
10513 num = RExC_npar + num;
10516 vFAIL("Reference to nonexistent group");
10518 } else if ( paren == '+' ) {
10519 num = RExC_npar + num - 1;
10522 ret = reg2Lanode(pRExC_state, GOSUB, num, RExC_recurse_count);
10524 if (num > (I32)RExC_rx->nparens) {
10526 vFAIL("Reference to nonexistent group");
10528 RExC_recurse_count++;
10529 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
10530 "%*s%*s Recurse #%"UVuf" to %"IVdf"\n",
10531 22, "| |", (int)(depth * 2 + 1), "",
10532 (UV)ARG(ret), (IV)ARG2L(ret)));
10534 RExC_seen |= REG_RECURSE_SEEN;
10535 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
10536 Set_Node_Offset(ret, parse_start); /* MJD */
10538 *flagp |= POSTPONED;
10539 nextchar(pRExC_state);
10544 case '?': /* (??...) */
10546 if (*RExC_parse != '{') {
10547 RExC_parse += SKIP_IF_CHAR(RExC_parse);
10548 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
10550 "Sequence (%"UTF8f"...) not recognized",
10551 UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
10552 NOT_REACHED; /*NOTREACHED*/
10554 *flagp |= POSTPONED;
10558 case '{': /* (?{...}) */
10561 struct reg_code_block *cb;
10563 RExC_seen_zerolen++;
10565 if ( !pRExC_state->num_code_blocks
10566 || pRExC_state->code_index >= pRExC_state->num_code_blocks
10567 || pRExC_state->code_blocks[pRExC_state->code_index].start
10568 != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
10571 if (RExC_pm_flags & PMf_USE_RE_EVAL)
10572 FAIL("panic: Sequence (?{...}): no code block found\n");
10573 FAIL("Eval-group not allowed at runtime, use re 'eval'");
10575 /* this is a pre-compiled code block (?{...}) */
10576 cb = &pRExC_state->code_blocks[pRExC_state->code_index];
10577 RExC_parse = RExC_start + cb->end;
10580 if (cb->src_regex) {
10581 n = add_data(pRExC_state, STR_WITH_LEN("rl"));
10582 RExC_rxi->data->data[n] =
10583 (void*)SvREFCNT_inc((SV*)cb->src_regex);
10584 RExC_rxi->data->data[n+1] = (void*)o;
10587 n = add_data(pRExC_state,
10588 (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l", 1);
10589 RExC_rxi->data->data[n] = (void*)o;
10592 pRExC_state->code_index++;
10593 nextchar(pRExC_state);
10597 ret = reg_node(pRExC_state, LOGICAL);
10599 eval = reg2Lanode(pRExC_state, EVAL,
10602 /* for later propagation into (??{})
10604 RExC_flags & RXf_PMf_COMPILETIME
10609 REGTAIL(pRExC_state, ret, eval);
10610 /* deal with the length of this later - MJD */
10613 ret = reg2Lanode(pRExC_state, EVAL, n, 0);
10614 Set_Node_Length(ret, RExC_parse - parse_start + 1);
10615 Set_Node_Offset(ret, parse_start);
10618 case '(': /* (?(?{...})...) and (?(?=...)...) */
10621 const int DEFINE_len = sizeof("DEFINE") - 1;
10622 if (RExC_parse[0] == '?') { /* (?(?...)) */
10623 if ( RExC_parse < RExC_end - 1
10624 && ( RExC_parse[1] == '='
10625 || RExC_parse[1] == '!'
10626 || RExC_parse[1] == '<'
10627 || RExC_parse[1] == '{')
10628 ) { /* Lookahead or eval. */
10632 ret = reg_node(pRExC_state, LOGICAL);
10636 tail = reg(pRExC_state, 1, &flag, depth+1);
10637 if (flag & (RESTART_PASS1|NEED_UTF8)) {
10638 *flagp = flag & (RESTART_PASS1|NEED_UTF8);
10641 REGTAIL(pRExC_state, ret, tail);
10644 /* Fall through to ‘Unknown switch condition’ at the
10645 end of the if/else chain. */
10647 else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
10648 || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
10650 char ch = RExC_parse[0] == '<' ? '>' : '\'';
10651 char *name_start= RExC_parse++;
10653 SV *sv_dat=reg_scan_name(pRExC_state,
10654 SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
10655 if ( RExC_parse == name_start
10656 || RExC_parse >= RExC_end
10657 || *RExC_parse != ch)
10659 vFAIL2("Sequence (?(%c... not terminated",
10660 (ch == '>' ? '<' : ch));
10664 num = add_data( pRExC_state, STR_WITH_LEN("S"));
10665 RExC_rxi->data->data[num]=(void*)sv_dat;
10666 SvREFCNT_inc_simple_void(sv_dat);
10668 ret = reganode(pRExC_state,NGROUPP,num);
10669 goto insert_if_check_paren;
10671 else if (RExC_end - RExC_parse >= DEFINE_len
10672 && strnEQ(RExC_parse, "DEFINE", DEFINE_len))
10674 ret = reganode(pRExC_state,DEFINEP,0);
10675 RExC_parse += DEFINE_len;
10677 goto insert_if_check_paren;
10679 else if (RExC_parse[0] == 'R') {
10682 if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
10684 if (grok_atoUV(RExC_parse, &uv, &endptr)
10688 RExC_parse = (char*)endptr;
10690 /* else "Switch condition not recognized" below */
10691 } else if (RExC_parse[0] == '&') {
10694 sv_dat = reg_scan_name(pRExC_state,
10696 ? REG_RSN_RETURN_NULL
10697 : REG_RSN_RETURN_DATA);
10698 parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
10700 ret = reganode(pRExC_state,INSUBP,parno);
10701 goto insert_if_check_paren;
10703 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
10707 if (grok_atoUV(RExC_parse, &uv, &endptr)
10711 RExC_parse = (char*)endptr;
10714 vFAIL("panic: grok_atoUV returned FALSE");
10716 ret = reganode(pRExC_state, GROUPP, parno);
10718 insert_if_check_paren:
10719 if (UCHARAT(RExC_parse) != ')') {
10720 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10721 vFAIL("Switch condition not recognized");
10723 nextchar(pRExC_state);
10725 REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
10726 br = regbranch(pRExC_state, &flags, 1,depth+1);
10728 if (flags & (RESTART_PASS1|NEED_UTF8)) {
10729 *flagp = flags & (RESTART_PASS1|NEED_UTF8);
10732 FAIL2("panic: regbranch returned NULL, flags=%#"UVxf"",
10735 REGTAIL(pRExC_state, br, reganode(pRExC_state,
10737 c = UCHARAT(RExC_parse);
10738 nextchar(pRExC_state);
10739 if (flags&HASWIDTH)
10740 *flagp |= HASWIDTH;
10743 vFAIL("(?(DEFINE)....) does not allow branches");
10745 /* Fake one for optimizer. */
10746 lastbr = reganode(pRExC_state, IFTHEN, 0);
10748 if (!regbranch(pRExC_state, &flags, 1,depth+1)) {
10749 if (flags & (RESTART_PASS1|NEED_UTF8)) {
10750 *flagp = flags & (RESTART_PASS1|NEED_UTF8);
10753 FAIL2("panic: regbranch returned NULL, flags=%#"UVxf"",
10756 REGTAIL(pRExC_state, ret, lastbr);
10757 if (flags&HASWIDTH)
10758 *flagp |= HASWIDTH;
10759 c = UCHARAT(RExC_parse);
10760 nextchar(pRExC_state);
10765 if (RExC_parse >= RExC_end)
10766 vFAIL("Switch (?(condition)... not terminated");
10768 vFAIL("Switch (?(condition)... contains too many branches");
10770 ender = reg_node(pRExC_state, TAIL);
10771 REGTAIL(pRExC_state, br, ender);
10773 REGTAIL(pRExC_state, lastbr, ender);
10774 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
10777 REGTAIL(pRExC_state, ret, ender);
10778 RExC_size++; /* XXX WHY do we need this?!!
10779 For large programs it seems to be required
10780 but I can't figure out why. -- dmq*/
10783 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10784 vFAIL("Unknown switch condition (?(...))");
10786 case '[': /* (?[ ... ]) */
10787 return handle_regex_sets(pRExC_state, NULL, flagp, depth,
10789 case 0: /* A NUL */
10790 RExC_parse--; /* for vFAIL to print correctly */
10791 vFAIL("Sequence (? incomplete");
10793 default: /* e.g., (?i) */
10794 RExC_parse = (char *) seqstart + 1;
10796 parse_lparen_question_flags(pRExC_state);
10797 if (UCHARAT(RExC_parse) != ':') {
10798 if (RExC_parse < RExC_end)
10799 nextchar(pRExC_state);
10804 nextchar(pRExC_state);
10809 else if (!(RExC_flags & RXf_PMf_NOCAPTURE)) { /* (...) */
10814 ret = reganode(pRExC_state, OPEN, parno);
10816 if (!RExC_nestroot)
10817 RExC_nestroot = parno;
10818 if (RExC_seen & REG_RECURSE_SEEN
10819 && !RExC_open_parens[parno-1])
10821 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
10822 "%*s%*s Setting open paren #%"IVdf" to %d\n",
10823 22, "| |", (int)(depth * 2 + 1), "",
10824 (IV)parno, REG_NODE_NUM(ret)));
10825 RExC_open_parens[parno-1]= ret;
10828 Set_Node_Length(ret, 1); /* MJD */
10829 Set_Node_Offset(ret, RExC_parse); /* MJD */
10832 /* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */
10841 /* Pick up the branches, linking them together. */
10842 parse_start = RExC_parse; /* MJD */
10843 br = regbranch(pRExC_state, &flags, 1,depth+1);
10845 /* branch_len = (paren != 0); */
10848 if (flags & (RESTART_PASS1|NEED_UTF8)) {
10849 *flagp = flags & (RESTART_PASS1|NEED_UTF8);
10852 FAIL2("panic: regbranch returned NULL, flags=%#"UVxf"", (UV) flags);
10854 if (*RExC_parse == '|') {
10855 if (!SIZE_ONLY && RExC_extralen) {
10856 reginsert(pRExC_state, BRANCHJ, br, depth+1);
10859 reginsert(pRExC_state, BRANCH, br, depth+1);
10860 Set_Node_Length(br, paren != 0);
10861 Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
10865 RExC_extralen += 1; /* For BRANCHJ-BRANCH. */
10867 else if (paren == ':') {
10868 *flagp |= flags&SIMPLE;
10870 if (is_open) { /* Starts with OPEN. */
10871 REGTAIL(pRExC_state, ret, br); /* OPEN -> first. */
10873 else if (paren != '?') /* Not Conditional */
10875 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
10877 while (*RExC_parse == '|') {
10878 if (!SIZE_ONLY && RExC_extralen) {
10879 ender = reganode(pRExC_state, LONGJMP,0);
10881 /* Append to the previous. */
10882 REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
10885 RExC_extralen += 2; /* Account for LONGJMP. */
10886 nextchar(pRExC_state);
10887 if (freeze_paren) {
10888 if (RExC_npar > after_freeze)
10889 after_freeze = RExC_npar;
10890 RExC_npar = freeze_paren;
10892 br = regbranch(pRExC_state, &flags, 0, depth+1);
10895 if (flags & (RESTART_PASS1|NEED_UTF8)) {
10896 *flagp = flags & (RESTART_PASS1|NEED_UTF8);
10899 FAIL2("panic: regbranch returned NULL, flags=%#"UVxf"", (UV) flags);
10901 REGTAIL(pRExC_state, lastbr, br); /* BRANCH -> BRANCH. */
10903 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
10906 if (have_branch || paren != ':') {
10907 /* Make a closing node, and hook it on the end. */
10910 ender = reg_node(pRExC_state, TAIL);
10913 ender = reganode(pRExC_state, CLOSE, parno);
10914 if (!SIZE_ONLY && RExC_seen & REG_RECURSE_SEEN) {
10915 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
10916 "%*s%*s Setting close paren #%"IVdf" to %d\n",
10917 22, "| |", (int)(depth * 2 + 1), "", (IV)parno, REG_NODE_NUM(ender)));
10918 RExC_close_parens[parno-1]= ender;
10919 if (RExC_nestroot == parno)
10922 Set_Node_Offset(ender,RExC_parse+1); /* MJD */
10923 Set_Node_Length(ender,1); /* MJD */
10929 *flagp &= ~HASWIDTH;
10932 ender = reg_node(pRExC_state, SUCCEED);
10935 ender = reg_node(pRExC_state, END);
10937 assert(!RExC_opend); /* there can only be one! */
10938 RExC_opend = ender;
10942 DEBUG_PARSE_r(if (!SIZE_ONLY) {
10943 DEBUG_PARSE_MSG("lsbr");
10944 regprop(RExC_rx, RExC_mysv1, lastbr, NULL, pRExC_state);
10945 regprop(RExC_rx, RExC_mysv2, ender, NULL, pRExC_state);
10946 PerlIO_printf(Perl_debug_log, "~ tying lastbr %s (%"IVdf") to ender %s (%"IVdf") offset %"IVdf"\n",
10947 SvPV_nolen_const(RExC_mysv1),
10948 (IV)REG_NODE_NUM(lastbr),
10949 SvPV_nolen_const(RExC_mysv2),
10950 (IV)REG_NODE_NUM(ender),
10951 (IV)(ender - lastbr)
10954 REGTAIL(pRExC_state, lastbr, ender);
10956 if (have_branch && !SIZE_ONLY) {
10957 char is_nothing= 1;
10959 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
10961 /* Hook the tails of the branches to the closing node. */
10962 for (br = ret; br; br = regnext(br)) {
10963 const U8 op = PL_regkind[OP(br)];
10964 if (op == BRANCH) {
10965 REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
10966 if ( OP(NEXTOPER(br)) != NOTHING
10967 || regnext(NEXTOPER(br)) != ender)
10970 else if (op == BRANCHJ) {
10971 REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
10972 /* for now we always disable this optimisation * /
10973 if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING
10974 || regnext(NEXTOPER(NEXTOPER(br))) != ender)
10980 br= PL_regkind[OP(ret)] != BRANCH ? regnext(ret) : ret;
10981 DEBUG_PARSE_r(if (!SIZE_ONLY) {
10982 DEBUG_PARSE_MSG("NADA");
10983 regprop(RExC_rx, RExC_mysv1, ret, NULL, pRExC_state);
10984 regprop(RExC_rx, RExC_mysv2, ender, NULL, pRExC_state);
10985 PerlIO_printf(Perl_debug_log, "~ converting ret %s (%"IVdf") to ender %s (%"IVdf") offset %"IVdf"\n",
10986 SvPV_nolen_const(RExC_mysv1),
10987 (IV)REG_NODE_NUM(ret),
10988 SvPV_nolen_const(RExC_mysv2),
10989 (IV)REG_NODE_NUM(ender),
10994 if (OP(ender) == TAIL) {
10999 for ( opt= br + 1; opt < ender ; opt++ )
11000 OP(opt)= OPTIMIZED;
11001 NEXT_OFF(br)= ender - br;
11009 static const char parens[] = "=!<,>";
11011 if (paren && (p = strchr(parens, paren))) {
11012 U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
11013 int flag = (p - parens) > 1;
11016 node = SUSPEND, flag = 0;
11017 reginsert(pRExC_state, node,ret, depth+1);
11018 Set_Node_Cur_Length(ret, parse_start);
11019 Set_Node_Offset(ret, parse_start + 1);
11021 REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
11025 /* Check for proper termination. */
11027 /* restore original flags, but keep (?p) and, if we've changed from /d
11028 * rules to /u, keep the /u */
11029 RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY);
11030 if (DEPENDS_SEMANTICS && RExC_uni_semantics) {
11031 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
11033 if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') {
11034 RExC_parse = oregcomp_parse;
11035 vFAIL("Unmatched (");
11037 nextchar(pRExC_state);
11039 else if (!paren && RExC_parse < RExC_end) {
11040 if (*RExC_parse == ')') {
11042 vFAIL("Unmatched )");
11045 FAIL("Junk on end of regexp"); /* "Can't happen". */
11046 NOT_REACHED; /* NOTREACHED */
11049 if (RExC_in_lookbehind) {
11050 RExC_in_lookbehind--;
11052 if (after_freeze > RExC_npar)
11053 RExC_npar = after_freeze;
11058 - regbranch - one alternative of an | operator
11060 * Implements the concatenation operator.
11062 * Returns NULL, setting *flagp to RESTART_PASS1 if the sizing scan needs to be
11063 * restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
11066 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
11069 regnode *chain = NULL;
11071 I32 flags = 0, c = 0;
11072 GET_RE_DEBUG_FLAGS_DECL;
11074 PERL_ARGS_ASSERT_REGBRANCH;
11076 DEBUG_PARSE("brnc");
11081 if (!SIZE_ONLY && RExC_extralen)
11082 ret = reganode(pRExC_state, BRANCHJ,0);
11084 ret = reg_node(pRExC_state, BRANCH);
11085 Set_Node_Length(ret, 1);
11089 if (!first && SIZE_ONLY)
11090 RExC_extralen += 1; /* BRANCHJ */
11092 *flagp = WORST; /* Tentatively. */
11094 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
11095 FALSE /* Don't force to /x */ );
11096 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
11097 flags &= ~TRYAGAIN;
11098 latest = regpiece(pRExC_state, &flags,depth+1);
11099 if (latest == NULL) {
11100 if (flags & TRYAGAIN)
11102 if (flags & (RESTART_PASS1|NEED_UTF8)) {
11103 *flagp = flags & (RESTART_PASS1|NEED_UTF8);
11106 FAIL2("panic: regpiece returned NULL, flags=%#"UVxf"", (UV) flags);
11108 else if (ret == NULL)
11110 *flagp |= flags&(HASWIDTH|POSTPONED);
11111 if (chain == NULL) /* First piece. */
11112 *flagp |= flags&SPSTART;
11114 /* FIXME adding one for every branch after the first is probably
11115 * excessive now we have TRIE support. (hv) */
11117 REGTAIL(pRExC_state, chain, latest);
11122 if (chain == NULL) { /* Loop ran zero times. */
11123 chain = reg_node(pRExC_state, NOTHING);
11128 *flagp |= flags&SIMPLE;
11135 - regpiece - something followed by possible [*+?]
11137 * Note that the branching code sequences used for ? and the general cases
11138 * of * and + are somewhat optimized: they use the same NOTHING node as
11139 * both the endmarker for their branch list and the body of the last branch.
11140 * It might seem that this node could be dispensed with entirely, but the
11141 * endmarker role is not redundant.
11143 * Returns NULL, setting *flagp to TRYAGAIN if regatom() returns NULL with
11145 * Returns NULL, setting *flagp to RESTART_PASS1 if the sizing scan needs to be
11146 * restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
11149 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
11155 const char * const origparse = RExC_parse;
11157 I32 max = REG_INFTY;
11158 #ifdef RE_TRACK_PATTERN_OFFSETS
11161 const char *maxpos = NULL;
11164 /* Save the original in case we change the emitted regop to a FAIL. */
11165 regnode * const orig_emit = RExC_emit;
11167 GET_RE_DEBUG_FLAGS_DECL;
11169 PERL_ARGS_ASSERT_REGPIECE;
11171 DEBUG_PARSE("piec");
11173 ret = regatom(pRExC_state, &flags,depth+1);
11175 if (flags & (TRYAGAIN|RESTART_PASS1|NEED_UTF8))
11176 *flagp |= flags & (TRYAGAIN|RESTART_PASS1|NEED_UTF8);
11178 FAIL2("panic: regatom returned NULL, flags=%#"UVxf"", (UV) flags);
11184 if (op == '{' && regcurly(RExC_parse)) {
11186 #ifdef RE_TRACK_PATTERN_OFFSETS
11187 parse_start = RExC_parse; /* MJD */
11189 next = RExC_parse + 1;
11190 while (isDIGIT(*next) || *next == ',') {
11191 if (*next == ',') {
11199 if (*next == '}') { /* got one */
11200 const char* endptr;
11204 if (isDIGIT(*RExC_parse)) {
11205 if (!grok_atoUV(RExC_parse, &uv, &endptr))
11206 vFAIL("Invalid quantifier in {,}");
11207 if (uv >= REG_INFTY)
11208 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
11213 if (*maxpos == ',')
11216 maxpos = RExC_parse;
11217 if (isDIGIT(*maxpos)) {
11218 if (!grok_atoUV(maxpos, &uv, &endptr))
11219 vFAIL("Invalid quantifier in {,}");
11220 if (uv >= REG_INFTY)
11221 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
11224 max = REG_INFTY; /* meaning "infinity" */
11227 nextchar(pRExC_state);
11228 if (max < min) { /* If can't match, warn and optimize to fail
11232 /* We can't back off the size because we have to reserve
11233 * enough space for all the things we are about to throw
11234 * away, but we can shrink it by the amount we are about
11235 * to re-use here */
11236 RExC_size += PREVOPER(RExC_size) - regarglen[(U8)OPFAIL];
11239 ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
11240 RExC_emit = orig_emit;
11242 ret = reganode(pRExC_state, OPFAIL, 0);
11245 else if (min == max && *RExC_parse == '?')
11248 ckWARN2reg(RExC_parse + 1,
11249 "Useless use of greediness modifier '%c'",
11255 if ((flags&SIMPLE)) {
11256 if (min == 0 && max == REG_INFTY) {
11257 reginsert(pRExC_state, STAR, ret, depth+1);
11260 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
11263 if (min == 1 && max == REG_INFTY) {
11264 reginsert(pRExC_state, PLUS, ret, depth+1);
11267 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
11270 MARK_NAUGHTY_EXP(2, 2);
11271 reginsert(pRExC_state, CURLY, ret, depth+1);
11272 Set_Node_Offset(ret, parse_start+1); /* MJD */
11273 Set_Node_Cur_Length(ret, parse_start);
11276 regnode * const w = reg_node(pRExC_state, WHILEM);
11279 REGTAIL(pRExC_state, ret, w);
11280 if (!SIZE_ONLY && RExC_extralen) {
11281 reginsert(pRExC_state, LONGJMP,ret, depth+1);
11282 reginsert(pRExC_state, NOTHING,ret, depth+1);
11283 NEXT_OFF(ret) = 3; /* Go over LONGJMP. */
11285 reginsert(pRExC_state, CURLYX,ret, depth+1);
11287 Set_Node_Offset(ret, parse_start+1);
11288 Set_Node_Length(ret,
11289 op == '{' ? (RExC_parse - parse_start) : 1);
11291 if (!SIZE_ONLY && RExC_extralen)
11292 NEXT_OFF(ret) = 3; /* Go over NOTHING to LONGJMP. */
11293 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
11295 RExC_whilem_seen++, RExC_extralen += 3;
11296 MARK_NAUGHTY_EXP(1, 4); /* compound interest */
11303 *flagp |= HASWIDTH;
11305 ARG1_SET(ret, (U16)min);
11306 ARG2_SET(ret, (U16)max);
11308 if (max == REG_INFTY)
11309 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
11315 if (!ISMULT1(op)) {
11320 #if 0 /* Now runtime fix should be reliable. */
11322 /* if this is reinstated, don't forget to put this back into perldiag:
11324 =item Regexp *+ operand could be empty at {#} in regex m/%s/
11326 (F) The part of the regexp subject to either the * or + quantifier
11327 could match an empty string. The {#} shows in the regular
11328 expression about where the problem was discovered.
11332 if (!(flags&HASWIDTH) && op != '?')
11333 vFAIL("Regexp *+ operand could be empty");
11336 #ifdef RE_TRACK_PATTERN_OFFSETS
11337 parse_start = RExC_parse;
11339 nextchar(pRExC_state);
11341 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
11347 else if (op == '+') {
11351 else if (op == '?') {
11356 if (!SIZE_ONLY && !(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
11357 SAVEFREESV(RExC_rx_sv); /* in case of fatal warnings */
11358 ckWARN2reg(RExC_parse,
11359 "%"UTF8f" matches null string many times",
11360 UTF8fARG(UTF, (RExC_parse >= origparse
11361 ? RExC_parse - origparse
11364 (void)ReREFCNT_inc(RExC_rx_sv);
11367 if (*RExC_parse == '?') {
11368 nextchar(pRExC_state);
11369 reginsert(pRExC_state, MINMOD, ret, depth+1);
11370 REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
11372 else if (*RExC_parse == '+') {
11374 nextchar(pRExC_state);
11375 ender = reg_node(pRExC_state, SUCCEED);
11376 REGTAIL(pRExC_state, ret, ender);
11377 reginsert(pRExC_state, SUSPEND, ret, depth+1);
11379 ender = reg_node(pRExC_state, TAIL);
11380 REGTAIL(pRExC_state, ret, ender);
11383 if (ISMULT2(RExC_parse)) {
11385 vFAIL("Nested quantifiers");
11392 S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state,
11400 /* This routine teases apart the various meanings of \N and returns
11401 * accordingly. The input parameters constrain which meaning(s) is/are valid
11402 * in the current context.
11404 * Exactly one of <node_p> and <code_point_p> must be non-NULL.
11406 * If <code_point_p> is not NULL, the context is expecting the result to be a
11407 * single code point. If this \N instance turns out to a single code point,
11408 * the function returns TRUE and sets *code_point_p to that code point.
11410 * If <node_p> is not NULL, the context is expecting the result to be one of
11411 * the things representable by a regnode. If this \N instance turns out to be
11412 * one such, the function generates the regnode, returns TRUE and sets *node_p
11413 * to point to that regnode.
11415 * If this instance of \N isn't legal in any context, this function will
11416 * generate a fatal error and not return.
11418 * On input, RExC_parse should point to the first char following the \N at the
11419 * time of the call. On successful return, RExC_parse will have been updated
11420 * to point to just after the sequence identified by this routine. Also
11421 * *flagp has been updated as needed.
11423 * When there is some problem with the current context and this \N instance,
11424 * the function returns FALSE, without advancing RExC_parse, nor setting
11425 * *node_p, nor *code_point_p, nor *flagp.
11427 * If <cp_count> is not NULL, the caller wants to know the length (in code
11428 * points) that this \N sequence matches. This is set even if the function
11429 * returns FALSE, as detailed below.
11431 * There are 5 possibilities here, as detailed in the next 5 paragraphs.
11433 * Probably the most common case is for the \N to specify a single code point.
11434 * *cp_count will be set to 1, and *code_point_p will be set to that code
11437 * Another possibility is for the input to be an empty \N{}, which for
11438 * backwards compatibility we accept. *cp_count will be set to 0. *node_p
11439 * will be set to a generated NOTHING node.
11441 * Still another possibility is for the \N to mean [^\n]. *cp_count will be
11442 * set to 0. *node_p will be set to a generated REG_ANY node.
11444 * The fourth possibility is that \N resolves to a sequence of more than one
11445 * code points. *cp_count will be set to the number of code points in the
11446 * sequence. *node_p * will be set to a generated node returned by this
11447 * function calling S_reg().
11449 * The final possibility is that it is premature to be calling this function;
11450 * that pass1 needs to be restarted. This can happen when this changes from
11451 * /d to /u rules, or when the pattern needs to be upgraded to UTF-8. The
11452 * latter occurs only when the fourth possibility would otherwise be in
11453 * effect, and is because one of those code points requires the pattern to be
11454 * recompiled as UTF-8. The function returns FALSE, and sets the
11455 * RESTART_PASS1 and NEED_UTF8 flags in *flagp, as appropriate. When this
11456 * happens, the caller needs to desist from continuing parsing, and return
11457 * this information to its caller. This is not set for when there is only one
11458 * code point, as this can be called as part of an ANYOF node, and they can
11459 * store above-Latin1 code points without the pattern having to be in UTF-8.
11461 * For non-single-quoted regexes, the tokenizer has resolved character and
11462 * sequence names inside \N{...} into their Unicode values, normalizing the
11463 * result into what we should see here: '\N{U+c1.c2...}', where c1... are the
11464 * hex-represented code points in the sequence. This is done there because
11465 * the names can vary based on what charnames pragma is in scope at the time,
11466 * so we need a way to take a snapshot of what they resolve to at the time of
11467 * the original parse. [perl #56444].
11469 * That parsing is skipped for single-quoted regexes, so we may here get
11470 * '\N{NAME}'. This is a fatal error. These names have to be resolved by the
11471 * parser. But if the single-quoted regex is something like '\N{U+41}', that
11472 * is legal and handled here. The code point is Unicode, and has to be
11473 * translated into the native character set for non-ASCII platforms.
11476 char * endbrace; /* points to '}' following the name */
11477 char *endchar; /* Points to '.' or '}' ending cur char in the input
11479 char* p = RExC_parse; /* Temporary */
11481 GET_RE_DEBUG_FLAGS_DECL;
11483 PERL_ARGS_ASSERT_GROK_BSLASH_N;
11485 GET_RE_DEBUG_FLAGS;
11487 assert(cBOOL(node_p) ^ cBOOL(code_point_p)); /* Exactly one should be set */
11488 assert(! (node_p && cp_count)); /* At most 1 should be set */
11490 if (cp_count) { /* Initialize return for the most common case */
11494 /* The [^\n] meaning of \N ignores spaces and comments under the /x
11495 * modifier. The other meanings do not, so use a temporary until we find
11496 * out which we are being called with */
11497 skip_to_be_ignored_text(pRExC_state, &p,
11498 FALSE /* Don't force to /x */ );
11500 /* Disambiguate between \N meaning a named character versus \N meaning
11501 * [^\n]. The latter is assumed when the {...} following the \N is a legal
11502 * quantifier, or there is no '{' at all */
11503 if (*p != '{' || regcurly(p)) {
11513 *node_p = reg_node(pRExC_state, REG_ANY);
11514 *flagp |= HASWIDTH|SIMPLE;
11516 Set_Node_Length(*node_p, 1); /* MJD */
11520 /* Here, we have decided it should be a named character or sequence */
11522 /* The test above made sure that the next real character is a '{', but
11523 * under the /x modifier, it could be separated by space (or a comment and
11524 * \n) and this is not allowed (for consistency with \x{...} and the
11525 * tokenizer handling of \N{NAME}). */
11526 if (*RExC_parse != '{') {
11527 vFAIL("Missing braces on \\N{}");
11530 RExC_parse++; /* Skip past the '{' */
11532 if (! (endbrace = strchr(RExC_parse, '}')) /* no trailing brace */
11533 || ! (endbrace == RExC_parse /* nothing between the {} */
11534 || (endbrace - RExC_parse >= 2 /* U+ (bad hex is checked... */
11535 && strnEQ(RExC_parse, "U+", 2)))) /* ... below for a better
11538 if (endbrace) RExC_parse = endbrace; /* position msg's '<--HERE' */
11539 vFAIL("\\N{NAME} must be resolved by the lexer");
11542 REQUIRE_UNI_RULES(flagp, FALSE); /* Unicode named chars imply Unicode
11545 if (endbrace == RExC_parse) { /* empty: \N{} */
11549 nextchar(pRExC_state);
11554 *node_p = reg_node(pRExC_state,NOTHING);
11558 RExC_parse += 2; /* Skip past the 'U+' */
11560 /* Because toke.c has generated a special construct for us guaranteed not
11561 * to have NULs, we can use a str function */
11562 endchar = RExC_parse + strcspn(RExC_parse, ".}");
11564 /* Code points are separated by dots. If none, there is only one code
11565 * point, and is terminated by the brace */
11567 if (endchar >= endbrace) {
11568 STRLEN length_of_hex;
11569 I32 grok_hex_flags;
11571 /* Here, exactly one code point. If that isn't what is wanted, fail */
11572 if (! code_point_p) {
11577 /* Convert code point from hex */
11578 length_of_hex = (STRLEN)(endchar - RExC_parse);
11579 grok_hex_flags = PERL_SCAN_ALLOW_UNDERSCORES
11580 | PERL_SCAN_DISALLOW_PREFIX
11582 /* No errors in the first pass (See [perl
11583 * #122671].) We let the code below find the
11584 * errors when there are multiple chars. */
11586 ? PERL_SCAN_SILENT_ILLDIGIT
11589 /* This routine is the one place where both single- and double-quotish
11590 * \N{U+xxxx} are evaluated. The value is a Unicode code point which
11591 * must be converted to native. */
11592 *code_point_p = UNI_TO_NATIVE(grok_hex(RExC_parse,
11597 /* The tokenizer should have guaranteed validity, but it's possible to
11598 * bypass it by using single quoting, so check. Don't do the check
11599 * here when there are multiple chars; we do it below anyway. */
11600 if (length_of_hex == 0
11601 || length_of_hex != (STRLEN)(endchar - RExC_parse) )
11603 RExC_parse += length_of_hex; /* Includes all the valid */
11604 RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */
11605 ? UTF8SKIP(RExC_parse)
11607 /* Guard against malformed utf8 */
11608 if (RExC_parse >= endchar) {
11609 RExC_parse = endchar;
11611 vFAIL("Invalid hexadecimal number in \\N{U+...}");
11614 RExC_parse = endbrace + 1;
11617 else { /* Is a multiple character sequence */
11618 SV * substitute_parse;
11620 char *orig_end = RExC_end;
11621 char *save_start = RExC_start;
11624 /* Count the code points, if desired, in the sequence */
11627 while (RExC_parse < endbrace) {
11628 /* Point to the beginning of the next character in the sequence. */
11629 RExC_parse = endchar + 1;
11630 endchar = RExC_parse + strcspn(RExC_parse, ".}");
11635 /* Fail if caller doesn't want to handle a multi-code-point sequence.
11636 * But don't backup up the pointer if the caller want to know how many
11637 * code points there are (they can then handle things) */
11645 /* What is done here is to convert this to a sub-pattern of the form
11646 * \x{char1}\x{char2}... and then call reg recursively to parse it
11647 * (enclosing in "(?: ... )" ). That way, it retains its atomicness,
11648 * while not having to worry about special handling that some code
11649 * points may have. */
11651 substitute_parse = newSVpvs("?:");
11653 while (RExC_parse < endbrace) {
11655 /* Convert to notation the rest of the code understands */
11656 sv_catpv(substitute_parse, "\\x{");
11657 sv_catpvn(substitute_parse, RExC_parse, endchar - RExC_parse);
11658 sv_catpv(substitute_parse, "}");
11660 /* Point to the beginning of the next character in the sequence. */
11661 RExC_parse = endchar + 1;
11662 endchar = RExC_parse + strcspn(RExC_parse, ".}");
11665 sv_catpv(substitute_parse, ")");
11667 RExC_parse = RExC_start = RExC_adjusted_start = SvPV(substitute_parse,
11670 /* Don't allow empty number */
11671 if (len < (STRLEN) 8) {
11672 RExC_parse = endbrace;
11673 vFAIL("Invalid hexadecimal number in \\N{U+...}");
11675 RExC_end = RExC_parse + len;
11677 /* The values are Unicode, and therefore not subject to recoding, but
11678 * have to be converted to native on a non-Unicode (meaning non-ASCII)
11680 RExC_override_recoding = 1;
11682 RExC_recode_x_to_native = 1;
11686 if (!(*node_p = reg(pRExC_state, 1, &flags, depth+1))) {
11687 if (flags & (RESTART_PASS1|NEED_UTF8)) {
11688 *flagp = flags & (RESTART_PASS1|NEED_UTF8);
11691 FAIL2("panic: reg returned NULL to grok_bslash_N, flags=%#"UVxf"",
11694 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
11697 /* Restore the saved values */
11698 RExC_start = RExC_adjusted_start = save_start;
11699 RExC_parse = endbrace;
11700 RExC_end = orig_end;
11701 RExC_override_recoding = 0;
11703 RExC_recode_x_to_native = 0;
11706 SvREFCNT_dec_NN(substitute_parse);
11707 nextchar(pRExC_state);
11717 * It returns the code point in utf8 for the value in *encp.
11718 * value: a code value in the source encoding
11719 * encp: a pointer to an Encode object
11721 * If the result from Encode is not a single character,
11722 * it returns U+FFFD (Replacement character) and sets *encp to NULL.
11725 S_reg_recode(pTHX_ const U8 value, SV **encp)
11728 SV * const sv = newSVpvn_flags((const char *) &value, numlen, SVs_TEMP);
11729 const char * const s = *encp ? sv_recode_to_utf8(sv, *encp) : SvPVX(sv);
11730 const STRLEN newlen = SvCUR(sv);
11731 UV uv = UNICODE_REPLACEMENT;
11733 PERL_ARGS_ASSERT_REG_RECODE;
11737 ? utf8n_to_uvchr((U8*)s, newlen, &numlen, UTF8_ALLOW_DEFAULT)
11740 if (!newlen || numlen != newlen) {
11741 uv = UNICODE_REPLACEMENT;
11747 PERL_STATIC_INLINE U8
11748 S_compute_EXACTish(RExC_state_t *pRExC_state)
11752 PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
11760 op = get_regex_charset(RExC_flags);
11761 if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
11762 op--; /* /a is same as /u, and map /aa's offset to what /a's would have
11763 been, so there is no hole */
11766 return op + EXACTF;
11769 PERL_STATIC_INLINE void
11770 S_alloc_maybe_populate_EXACT(pTHX_ RExC_state_t *pRExC_state,
11771 regnode *node, I32* flagp, STRLEN len, UV code_point,
11774 /* This knows the details about sizing an EXACTish node, setting flags for
11775 * it (by setting <*flagp>, and potentially populating it with a single
11778 * If <len> (the length in bytes) is non-zero, this function assumes that
11779 * the node has already been populated, and just does the sizing. In this
11780 * case <code_point> should be the final code point that has already been
11781 * placed into the node. This value will be ignored except that under some
11782 * circumstances <*flagp> is set based on it.
11784 * If <len> is zero, the function assumes that the node is to contain only
11785 * the single character given by <code_point> and calculates what <len>
11786 * should be. In pass 1, it sizes the node appropriately. In pass 2, it
11787 * additionally will populate the node's STRING with <code_point> or its
11790 * In both cases <*flagp> is appropriately set
11792 * It knows that under FOLD, the Latin Sharp S and UTF characters above
11793 * 255, must be folded (the former only when the rules indicate it can
11796 * When it does the populating, it looks at the flag 'downgradable'. If
11797 * true with a node that folds, it checks if the single code point
11798 * participates in a fold, and if not downgrades the node to an EXACT.
11799 * This helps the optimizer */
11801 bool len_passed_in = cBOOL(len != 0);
11802 U8 character[UTF8_MAXBYTES_CASE+1];
11804 PERL_ARGS_ASSERT_ALLOC_MAYBE_POPULATE_EXACT;
11806 /* Don't bother to check for downgrading in PASS1, as it doesn't make any
11807 * sizing difference, and is extra work that is thrown away */
11808 if (downgradable && ! PASS2) {
11809 downgradable = FALSE;
11812 if (! len_passed_in) {
11814 if (UVCHR_IS_INVARIANT(code_point)) {
11815 if (LOC || ! FOLD) { /* /l defers folding until runtime */
11816 *character = (U8) code_point;
11818 else { /* Here is /i and not /l. (toFOLD() is defined on just
11819 ASCII, which isn't the same thing as INVARIANT on
11820 EBCDIC, but it works there, as the extra invariants
11821 fold to themselves) */
11822 *character = toFOLD((U8) code_point);
11824 /* We can downgrade to an EXACT node if this character
11825 * isn't a folding one. Note that this assumes that
11826 * nothing above Latin1 folds to some other invariant than
11827 * one of these alphabetics; otherwise we would also have
11829 * && (! HAS_NONLATIN1_FOLD_CLOSURE(code_point)
11830 * || ASCII_FOLD_RESTRICTED))
11832 if (downgradable && PL_fold[code_point] == code_point) {
11838 else if (FOLD && (! LOC
11839 || ! is_PROBLEMATIC_LOCALE_FOLD_cp(code_point)))
11840 { /* Folding, and ok to do so now */
11841 UV folded = _to_uni_fold_flags(
11845 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
11846 ? FOLD_FLAGS_NOMIX_ASCII
11849 && folded == code_point /* This quickly rules out many
11850 cases, avoiding the
11851 _invlist_contains_cp() overhead
11853 && ! _invlist_contains_cp(PL_utf8_foldable, code_point))
11860 else if (code_point <= MAX_UTF8_TWO_BYTE) {
11862 /* Not folding this cp, and can output it directly */
11863 *character = UTF8_TWO_BYTE_HI(code_point);
11864 *(character + 1) = UTF8_TWO_BYTE_LO(code_point);
11868 uvchr_to_utf8( character, code_point);
11869 len = UTF8SKIP(character);
11871 } /* Else pattern isn't UTF8. */
11873 *character = (U8) code_point;
11875 } /* Else is folded non-UTF8 */
11876 #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
11877 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
11878 || UNICODE_DOT_DOT_VERSION > 0)
11879 else if (LIKELY(code_point != LATIN_SMALL_LETTER_SHARP_S)) {
11883 /* We don't fold any non-UTF8 except possibly the Sharp s (see
11884 * comments at join_exact()); */
11885 *character = (U8) code_point;
11888 /* Can turn into an EXACT node if we know the fold at compile time,
11889 * and it folds to itself and doesn't particpate in other folds */
11892 && PL_fold_latin1[code_point] == code_point
11893 && (! HAS_NONLATIN1_FOLD_CLOSURE(code_point)
11894 || (isASCII(code_point) && ASCII_FOLD_RESTRICTED)))
11898 } /* else is Sharp s. May need to fold it */
11899 else if (AT_LEAST_UNI_SEMANTICS && ! ASCII_FOLD_RESTRICTED) {
11901 *(character + 1) = 's';
11905 *character = LATIN_SMALL_LETTER_SHARP_S;
11911 RExC_size += STR_SZ(len);
11914 RExC_emit += STR_SZ(len);
11915 STR_LEN(node) = len;
11916 if (! len_passed_in) {
11917 Copy((char *) character, STRING(node), len, char);
11921 *flagp |= HASWIDTH;
11923 /* A single character node is SIMPLE, except for the special-cased SHARP S
11925 if ((len == 1 || (UTF && len == UVCHR_SKIP(code_point)))
11926 #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
11927 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
11928 || UNICODE_DOT_DOT_VERSION > 0)
11929 && ( code_point != LATIN_SMALL_LETTER_SHARP_S
11930 || ! FOLD || ! DEPENDS_SEMANTICS)
11936 /* The OP may not be well defined in PASS1 */
11937 if (PASS2 && OP(node) == EXACTFL) {
11938 RExC_contains_locale = 1;
11943 /* Parse backref decimal value, unless it's too big to sensibly be a backref,
11944 * in which case return I32_MAX (rather than possibly 32-bit wrapping) */
11947 S_backref_value(char *p)
11949 const char* endptr;
11951 if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX)
11958 - regatom - the lowest level
11960 Try to identify anything special at the start of the pattern. If there
11961 is, then handle it as required. This may involve generating a single regop,
11962 such as for an assertion; or it may involve recursing, such as to
11963 handle a () structure.
11965 If the string doesn't start with something special then we gobble up
11966 as much literal text as we can.
11968 Once we have been able to handle whatever type of thing started the
11969 sequence, we return.
11971 Note: we have to be careful with escapes, as they can be both literal
11972 and special, and in the case of \10 and friends, context determines which.
11974 A summary of the code structure is:
11976 switch (first_byte) {
11977 cases for each special:
11978 handle this special;
11981 switch (2nd byte) {
11982 cases for each unambiguous special:
11983 handle this special;
11985 cases for each ambigous special/literal:
11987 if (special) handle here
11989 default: // unambiguously literal:
11992 default: // is a literal char
11995 create EXACTish node for literal;
11996 while (more input and node isn't full) {
11997 switch (input_byte) {
11998 cases for each special;
11999 make sure parse pointer is set so that the next call to
12000 regatom will see this special first
12001 goto loopdone; // EXACTish node terminated by prev. char
12003 append char to EXACTISH node;
12005 get next input byte;
12009 return the generated node;
12011 Specifically there are two separate switches for handling
12012 escape sequences, with the one for handling literal escapes requiring
12013 a dummy entry for all of the special escapes that are actually handled
12016 Returns NULL, setting *flagp to TRYAGAIN if reg() returns NULL with
12018 Returns NULL, setting *flagp to RESTART_PASS1 if the sizing scan needs to be
12019 restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
12020 Otherwise does not return NULL.
12024 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
12026 regnode *ret = NULL;
12033 GET_RE_DEBUG_FLAGS_DECL;
12035 *flagp = WORST; /* Tentatively. */
12037 DEBUG_PARSE("atom");
12039 PERL_ARGS_ASSERT_REGATOM;
12042 parse_start = RExC_parse;
12043 assert(RExC_parse < RExC_end);
12044 switch ((U8)*RExC_parse) {
12046 RExC_seen_zerolen++;
12047 nextchar(pRExC_state);
12048 if (RExC_flags & RXf_PMf_MULTILINE)
12049 ret = reg_node(pRExC_state, MBOL);
12051 ret = reg_node(pRExC_state, SBOL);
12052 Set_Node_Length(ret, 1); /* MJD */
12055 nextchar(pRExC_state);
12057 RExC_seen_zerolen++;
12058 if (RExC_flags & RXf_PMf_MULTILINE)
12059 ret = reg_node(pRExC_state, MEOL);
12061 ret = reg_node(pRExC_state, SEOL);
12062 Set_Node_Length(ret, 1); /* MJD */
12065 nextchar(pRExC_state);
12066 if (RExC_flags & RXf_PMf_SINGLELINE)
12067 ret = reg_node(pRExC_state, SANY);
12069 ret = reg_node(pRExC_state, REG_ANY);
12070 *flagp |= HASWIDTH|SIMPLE;
12072 Set_Node_Length(ret, 1); /* MJD */
12076 char * const oregcomp_parse = ++RExC_parse;
12077 ret = regclass(pRExC_state, flagp,depth+1,
12078 FALSE, /* means parse the whole char class */
12079 TRUE, /* allow multi-char folds */
12080 FALSE, /* don't silence non-portable warnings. */
12081 (bool) RExC_strict,
12082 TRUE, /* Allow an optimized regnode result */
12086 if (*flagp & (RESTART_PASS1|NEED_UTF8))
12088 FAIL2("panic: regclass returned NULL to regatom, flags=%#"UVxf"",
12091 if (*RExC_parse != ']') {
12092 RExC_parse = oregcomp_parse;
12093 vFAIL("Unmatched [");
12095 nextchar(pRExC_state);
12096 Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
12100 nextchar(pRExC_state);
12101 ret = reg(pRExC_state, 2, &flags,depth+1);
12103 if (flags & TRYAGAIN) {
12104 if (RExC_parse >= RExC_end) {
12105 /* Make parent create an empty node if needed. */
12106 *flagp |= TRYAGAIN;
12111 if (flags & (RESTART_PASS1|NEED_UTF8)) {
12112 *flagp = flags & (RESTART_PASS1|NEED_UTF8);
12115 FAIL2("panic: reg returned NULL to regatom, flags=%#"UVxf"",
12118 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
12122 if (flags & TRYAGAIN) {
12123 *flagp |= TRYAGAIN;
12126 vFAIL("Internal urp");
12127 /* Supposed to be caught earlier. */
12133 vFAIL("Quantifier follows nothing");
12138 This switch handles escape sequences that resolve to some kind
12139 of special regop and not to literal text. Escape sequnces that
12140 resolve to literal text are handled below in the switch marked
12143 Every entry in this switch *must* have a corresponding entry
12144 in the literal escape switch. However, the opposite is not
12145 required, as the default for this switch is to jump to the
12146 literal text handling code.
12149 switch ((U8)*RExC_parse) {
12150 /* Special Escapes */
12152 RExC_seen_zerolen++;
12153 ret = reg_node(pRExC_state, SBOL);
12154 /* SBOL is shared with /^/ so we set the flags so we can tell
12155 * /\A/ from /^/ in split. We check ret because first pass we
12156 * have no regop struct to set the flags on. */
12160 goto finish_meta_pat;
12162 ret = reg_node(pRExC_state, GPOS);
12163 RExC_seen |= REG_GPOS_SEEN;
12165 goto finish_meta_pat;
12167 RExC_seen_zerolen++;
12168 ret = reg_node(pRExC_state, KEEPS);
12170 /* XXX:dmq : disabling in-place substitution seems to
12171 * be necessary here to avoid cases of memory corruption, as
12172 * with: C<$_="x" x 80; s/x\K/y/> -- rgs
12174 RExC_seen |= REG_LOOKBEHIND_SEEN;
12175 goto finish_meta_pat;
12177 ret = reg_node(pRExC_state, SEOL);
12179 RExC_seen_zerolen++; /* Do not optimize RE away */
12180 goto finish_meta_pat;
12182 ret = reg_node(pRExC_state, EOS);
12184 RExC_seen_zerolen++; /* Do not optimize RE away */
12185 goto finish_meta_pat;
12187 vFAIL("\\C no longer supported");
12189 ret = reg_node(pRExC_state, CLUMP);
12190 *flagp |= HASWIDTH;
12191 goto finish_meta_pat;
12197 arg = ANYOF_WORDCHAR;
12205 regex_charset charset = get_regex_charset(RExC_flags);
12207 RExC_seen_zerolen++;
12208 RExC_seen |= REG_LOOKBEHIND_SEEN;
12209 op = BOUND + charset;
12211 if (op == BOUNDL) {
12212 RExC_contains_locale = 1;
12215 ret = reg_node(pRExC_state, op);
12217 if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') {
12218 FLAGS(ret) = TRADITIONAL_BOUND;
12219 if (PASS2 && op > BOUNDA) { /* /aa is same as /a */
12225 char name = *RExC_parse;
12228 endbrace = strchr(RExC_parse, '}');
12231 vFAIL2("Missing right brace on \\%c{}", name);
12233 /* XXX Need to decide whether to take spaces or not. Should be
12234 * consistent with \p{}, but that currently is SPACE, which
12235 * means vertical too, which seems wrong
12236 * while (isBLANK(*RExC_parse)) {
12239 if (endbrace == RExC_parse) {
12240 RExC_parse++; /* After the '}' */
12241 vFAIL2("Empty \\%c{}", name);
12243 length = endbrace - RExC_parse;
12244 /*while (isBLANK(*(RExC_parse + length - 1))) {
12247 switch (*RExC_parse) {
12250 && (length != 3 || strnNE(RExC_parse + 1, "cb", 2)))
12252 goto bad_bound_type;
12254 FLAGS(ret) = GCB_BOUND;
12257 if (length != 2 || *(RExC_parse + 1) != 'b') {
12258 goto bad_bound_type;
12260 FLAGS(ret) = LB_BOUND;
12263 if (length != 2 || *(RExC_parse + 1) != 'b') {
12264 goto bad_bound_type;
12266 FLAGS(ret) = SB_BOUND;
12269 if (length != 2 || *(RExC_parse + 1) != 'b') {
12270 goto bad_bound_type;
12272 FLAGS(ret) = WB_BOUND;
12276 RExC_parse = endbrace;
12278 "'%"UTF8f"' is an unknown bound type",
12279 UTF8fARG(UTF, length, endbrace - length));
12280 NOT_REACHED; /*NOTREACHED*/
12282 RExC_parse = endbrace;
12283 REQUIRE_UNI_RULES(flagp, NULL);
12285 if (PASS2 && op >= BOUNDA) { /* /aa is same as /a */
12289 /* Don't have to worry about UTF-8, in this message because
12290 * to get here the contents of the \b must be ASCII */
12291 ckWARN4reg(RExC_parse + 1, /* Include the '}' in msg */
12292 "Using /u for '%.*s' instead of /%s",
12294 endbrace - length + 1,
12295 (charset == REGEX_ASCII_RESTRICTED_CHARSET)
12296 ? ASCII_RESTRICT_PAT_MODS
12297 : ASCII_MORE_RESTRICT_PAT_MODS);
12301 if (PASS2 && invert) {
12302 OP(ret) += NBOUND - BOUND;
12304 goto finish_meta_pat;
12312 if (! DEPENDS_SEMANTICS) {
12316 /* \d doesn't have any matches in the upper Latin1 range, hence /d
12317 * is equivalent to /u. Changing to /u saves some branches at
12320 goto join_posix_op_known;
12323 ret = reg_node(pRExC_state, LNBREAK);
12324 *flagp |= HASWIDTH|SIMPLE;
12325 goto finish_meta_pat;
12333 goto join_posix_op_known;
12339 arg = ANYOF_VERTWS;
12341 goto join_posix_op_known;
12351 op = POSIXD + get_regex_charset(RExC_flags);
12352 if (op > POSIXA) { /* /aa is same as /a */
12355 else if (op == POSIXL) {
12356 RExC_contains_locale = 1;
12359 join_posix_op_known:
12362 op += NPOSIXD - POSIXD;
12365 ret = reg_node(pRExC_state, op);
12367 FLAGS(ret) = namedclass_to_classnum(arg);
12370 *flagp |= HASWIDTH|SIMPLE;
12374 nextchar(pRExC_state);
12375 Set_Node_Length(ret, 2); /* MJD */
12381 ret = regclass(pRExC_state, flagp,depth+1,
12382 TRUE, /* means just parse this element */
12383 FALSE, /* don't allow multi-char folds */
12384 FALSE, /* don't silence non-portable warnings. It
12385 would be a bug if these returned
12387 (bool) RExC_strict,
12388 TRUE, /* Allow an optimized regnode result */
12391 if (*flagp & RESTART_PASS1)
12393 /* regclass() can only return RESTART_PASS1 and NEED_UTF8 if
12394 * multi-char folds are allowed. */
12396 FAIL2("panic: regclass returned NULL to regatom, flags=%#"UVxf"",
12401 Set_Node_Offset(ret, parse_start);
12402 Set_Node_Cur_Length(ret, parse_start - 2);
12403 nextchar(pRExC_state);
12406 /* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the
12407 * \N{...} evaluates to a sequence of more than one code points).
12408 * The function call below returns a regnode, which is our result.
12409 * The parameters cause it to fail if the \N{} evaluates to a
12410 * single code point; we handle those like any other literal. The
12411 * reason that the multicharacter case is handled here and not as
12412 * part of the EXACtish code is because of quantifiers. In
12413 * /\N{BLAH}+/, the '+' applies to the whole thing, and doing it
12414 * this way makes that Just Happen. dmq.
12415 * join_exact() will join this up with adjacent EXACTish nodes
12416 * later on, if appropriate. */
12418 if (grok_bslash_N(pRExC_state,
12419 &ret, /* Want a regnode returned */
12420 NULL, /* Fail if evaluates to a single code
12422 NULL, /* Don't need a count of how many code
12430 if (*flagp & RESTART_PASS1)
12433 /* Here, evaluates to a single code point. Go get that */
12434 RExC_parse = parse_start;
12437 case 'k': /* Handle \k<NAME> and \k'NAME' */
12441 if ( RExC_parse >= RExC_end - 1
12442 || (( ch = RExC_parse[1]) != '<'
12447 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
12448 vFAIL2("Sequence %.2s... not terminated",parse_start);
12451 ret = handle_named_backref(pRExC_state,
12463 case '1': case '2': case '3': case '4':
12464 case '5': case '6': case '7': case '8': case '9':
12469 if (*RExC_parse == 'g') {
12473 if (*RExC_parse == '{') {
12477 if (*RExC_parse == '-') {
12481 if (hasbrace && !isDIGIT(*RExC_parse)) {
12482 if (isrel) RExC_parse--;
12484 goto parse_named_seq;
12487 if (RExC_parse >= RExC_end) {
12488 goto unterminated_g;
12490 num = S_backref_value(RExC_parse);
12492 vFAIL("Reference to invalid group 0");
12493 else if (num == I32_MAX) {
12494 if (isDIGIT(*RExC_parse))
12495 vFAIL("Reference to nonexistent group");
12498 vFAIL("Unterminated \\g... pattern");
12502 num = RExC_npar - num;
12504 vFAIL("Reference to nonexistent or unclosed group");
12508 num = S_backref_value(RExC_parse);
12509 /* bare \NNN might be backref or octal - if it is larger
12510 * than or equal RExC_npar then it is assumed to be an
12511 * octal escape. Note RExC_npar is +1 from the actual
12512 * number of parens. */
12513 /* Note we do NOT check if num == I32_MAX here, as that is
12514 * handled by the RExC_npar check */
12517 /* any numeric escape < 10 is always a backref */
12519 /* any numeric escape < RExC_npar is a backref */
12520 && num >= RExC_npar
12521 /* cannot be an octal escape if it starts with 8 */
12522 && *RExC_parse != '8'
12523 /* cannot be an octal escape it it starts with 9 */
12524 && *RExC_parse != '9'
12527 /* Probably not a backref, instead likely to be an
12528 * octal character escape, e.g. \35 or \777.
12529 * The above logic should make it obvious why using
12530 * octal escapes in patterns is problematic. - Yves */
12531 RExC_parse = parse_start;
12536 /* At this point RExC_parse points at a numeric escape like
12537 * \12 or \88 or something similar, which we should NOT treat
12538 * as an octal escape. It may or may not be a valid backref
12539 * escape. For instance \88888888 is unlikely to be a valid
12541 while (isDIGIT(*RExC_parse))
12544 if (*RExC_parse != '}')
12545 vFAIL("Unterminated \\g{...} pattern");
12549 if (num > (I32)RExC_rx->nparens)
12550 vFAIL("Reference to nonexistent group");
12553 ret = reganode(pRExC_state,
12556 : (ASCII_FOLD_RESTRICTED)
12558 : (AT_LEAST_UNI_SEMANTICS)
12564 *flagp |= HASWIDTH;
12566 /* override incorrect value set in reganode MJD */
12567 Set_Node_Offset(ret, parse_start);
12568 Set_Node_Cur_Length(ret, parse_start-1);
12569 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
12570 FALSE /* Don't force to /x */ );
12574 if (RExC_parse >= RExC_end)
12575 FAIL("Trailing \\");
12578 /* Do not generate "unrecognized" warnings here, we fall
12579 back into the quick-grab loop below */
12580 RExC_parse = parse_start;
12582 } /* end of switch on a \foo sequence */
12587 /* '#' comments should have been spaced over before this function was
12589 assert((RExC_flags & RXf_PMf_EXTENDED) == 0);
12591 if (RExC_flags & RXf_PMf_EXTENDED) {
12592 RExC_parse = reg_skipcomment( pRExC_state, RExC_parse );
12593 if (RExC_parse < RExC_end)
12603 /* Here, we have determined that the next thing is probably a
12604 * literal character. RExC_parse points to the first byte of its
12605 * definition. (It still may be an escape sequence that evaluates
12606 * to a single character) */
12612 #define MAX_NODE_STRING_SIZE 127
12613 char foldbuf[MAX_NODE_STRING_SIZE+UTF8_MAXBYTES_CASE];
12615 U8 upper_parse = MAX_NODE_STRING_SIZE;
12616 U8 node_type = compute_EXACTish(pRExC_state);
12617 bool next_is_quantifier;
12618 char * oldp = NULL;
12620 /* We can convert EXACTF nodes to EXACTFU if they contain only
12621 * characters that match identically regardless of the target
12622 * string's UTF8ness. The reason to do this is that EXACTF is not
12623 * trie-able, EXACTFU is.
12625 * Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they
12626 * contain only above-Latin1 characters (hence must be in UTF8),
12627 * which don't participate in folds with Latin1-range characters,
12628 * as the latter's folds aren't known until runtime. (We don't
12629 * need to figure this out until pass 2) */
12630 bool maybe_exactfu = PASS2
12631 && (node_type == EXACTF || node_type == EXACTFL);
12633 /* If a folding node contains only code points that don't
12634 * participate in folds, it can be changed into an EXACT node,
12635 * which allows the optimizer more things to look for */
12638 ret = reg_node(pRExC_state, node_type);
12640 /* In pass1, folded, we use a temporary buffer instead of the
12641 * actual node, as the node doesn't exist yet */
12642 s = (SIZE_ONLY && FOLD) ? foldbuf : STRING(ret);
12648 /* We look for the EXACTFish to EXACT node optimizaton only if
12649 * folding. (And we don't need to figure this out until pass 2).
12650 * XXX It might actually make sense to split the node into portions
12651 * that are exact and ones that aren't, so that we could later use
12652 * the exact ones to find the longest fixed and floating strings.
12653 * One would want to join them back into a larger node. One could
12654 * use a pseudo regnode like 'EXACT_ORIG_FOLD' */
12655 maybe_exact = FOLD && PASS2;
12657 /* XXX The node can hold up to 255 bytes, yet this only goes to
12658 * 127. I (khw) do not know why. Keeping it somewhat less than
12659 * 255 allows us to not have to worry about overflow due to
12660 * converting to utf8 and fold expansion, but that value is
12661 * 255-UTF8_MAXBYTES_CASE. join_exact() may join adjacent nodes
12662 * split up by this limit into a single one using the real max of
12663 * 255. Even at 127, this breaks under rare circumstances. If
12664 * folding, we do not want to split a node at a character that is a
12665 * non-final in a multi-char fold, as an input string could just
12666 * happen to want to match across the node boundary. The join
12667 * would solve that problem if the join actually happens. But a
12668 * series of more than two nodes in a row each of 127 would cause
12669 * the first join to succeed to get to 254, but then there wouldn't
12670 * be room for the next one, which could at be one of those split
12671 * multi-char folds. I don't know of any fool-proof solution. One
12672 * could back off to end with only a code point that isn't such a
12673 * non-final, but it is possible for there not to be any in the
12676 assert( ! UTF /* Is at the beginning of a character */
12677 || UTF8_IS_INVARIANT(UCHARAT(RExC_parse))
12678 || UTF8_IS_START(UCHARAT(RExC_parse)));
12680 for (p = RExC_parse;
12681 len < upper_parse && p < RExC_end;
12686 /* White space has already been ignored */
12687 assert( (RExC_flags & RXf_PMf_EXTENDED) == 0
12688 || ! is_PATWS_safe((p), RExC_end, UTF));
12700 /* Literal Escapes Switch
12702 This switch is meant to handle escape sequences that
12703 resolve to a literal character.
12705 Every escape sequence that represents something
12706 else, like an assertion or a char class, is handled
12707 in the switch marked 'Special Escapes' above in this
12708 routine, but also has an entry here as anything that
12709 isn't explicitly mentioned here will be treated as
12710 an unescaped equivalent literal.
12713 switch ((U8)*++p) {
12714 /* These are all the special escapes. */
12715 case 'A': /* Start assertion */
12716 case 'b': case 'B': /* Word-boundary assertion*/
12717 case 'C': /* Single char !DANGEROUS! */
12718 case 'd': case 'D': /* digit class */
12719 case 'g': case 'G': /* generic-backref, pos assertion */
12720 case 'h': case 'H': /* HORIZWS */
12721 case 'k': case 'K': /* named backref, keep marker */
12722 case 'p': case 'P': /* Unicode property */
12723 case 'R': /* LNBREAK */
12724 case 's': case 'S': /* space class */
12725 case 'v': case 'V': /* VERTWS */
12726 case 'w': case 'W': /* word class */
12727 case 'X': /* eXtended Unicode "combining
12728 character sequence" */
12729 case 'z': case 'Z': /* End of line/string assertion */
12733 /* Anything after here is an escape that resolves to a
12734 literal. (Except digits, which may or may not)
12740 case 'N': /* Handle a single-code point named character. */
12741 RExC_parse = p + 1;
12742 if (! grok_bslash_N(pRExC_state,
12743 NULL, /* Fail if evaluates to
12744 anything other than a
12745 single code point */
12746 &ender, /* The returned single code
12748 NULL, /* Don't need a count of
12749 how many code points */
12753 if (*flagp & NEED_UTF8)
12754 FAIL("panic: grok_bslash_N set NEED_UTF8");
12755 if (*flagp & RESTART_PASS1)
12758 /* Here, it wasn't a single code point. Go close
12759 * up this EXACTish node. The switch() prior to
12760 * this switch handles the other cases */
12761 RExC_parse = p = oldp;
12765 if (ender > 0xff) {
12766 REQUIRE_UTF8(flagp);
12782 ender = ESC_NATIVE;
12792 const char* error_msg;
12794 bool valid = grok_bslash_o(&p,
12797 PASS2, /* out warnings */
12798 (bool) RExC_strict,
12799 TRUE, /* Output warnings
12804 RExC_parse = p; /* going to die anyway; point
12805 to exact spot of failure */
12809 if (IN_ENCODING && ender < 0x100) {
12810 goto recode_encoding;
12812 if (ender > 0xff) {
12813 REQUIRE_UTF8(flagp);
12819 UV result = UV_MAX; /* initialize to erroneous
12821 const char* error_msg;
12823 bool valid = grok_bslash_x(&p,
12826 PASS2, /* out warnings */
12827 (bool) RExC_strict,
12828 TRUE, /* Silence warnings
12833 RExC_parse = p; /* going to die anyway; point
12834 to exact spot of failure */
12839 if (ender < 0x100) {
12841 if (RExC_recode_x_to_native) {
12842 ender = LATIN1_TO_NATIVE(ender);
12847 goto recode_encoding;
12851 REQUIRE_UTF8(flagp);
12857 ender = grok_bslash_c(*p++, PASS2);
12859 case '8': case '9': /* must be a backreference */
12861 /* we have an escape like \8 which cannot be an octal escape
12862 * so we exit the loop, and let the outer loop handle this
12863 * escape which may or may not be a legitimate backref. */
12865 case '1': case '2': case '3':case '4':
12866 case '5': case '6': case '7':
12867 /* When we parse backslash escapes there is ambiguity
12868 * between backreferences and octal escapes. Any escape
12869 * from \1 - \9 is a backreference, any multi-digit
12870 * escape which does not start with 0 and which when
12871 * evaluated as decimal could refer to an already
12872 * parsed capture buffer is a back reference. Anything
12875 * Note this implies that \118 could be interpreted as
12876 * 118 OR as "\11" . "8" depending on whether there
12877 * were 118 capture buffers defined already in the
12880 /* NOTE, RExC_npar is 1 more than the actual number of
12881 * parens we have seen so far, hence the < RExC_npar below. */
12883 if ( !isDIGIT(p[1]) || S_backref_value(p) < RExC_npar)
12884 { /* Not to be treated as an octal constant, go
12892 I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
12894 ender = grok_oct(p, &numlen, &flags, NULL);
12895 if (ender > 0xff) {
12896 REQUIRE_UTF8(flagp);
12899 if (PASS2 /* like \08, \178 */
12901 && isDIGIT(*p) && ckWARN(WARN_REGEXP))
12903 reg_warn_non_literal_string(
12905 form_short_octal_warning(p, numlen));
12908 if (IN_ENCODING && ender < 0x100)
12909 goto recode_encoding;
12912 if (! RExC_override_recoding) {
12913 SV* enc = _get_encoding();
12914 ender = reg_recode((U8)ender, &enc);
12916 ckWARNreg(p, "Invalid escape in the specified encoding");
12917 REQUIRE_UTF8(flagp);
12922 FAIL("Trailing \\");
12925 if (!SIZE_ONLY&& isALPHANUMERIC(*p)) {
12926 /* Include any left brace following the alpha to emphasize
12927 * that it could be part of an escape at some point
12929 int len = (isALPHA(*p) && *(p + 1) == '{') ? 2 : 1;
12930 ckWARN3reg(p + len, "Unrecognized escape \\%.*s passed through", len, p);
12932 goto normal_default;
12933 } /* End of switch on '\' */
12936 /* Currently we don't warn when the lbrace is at the start
12937 * of a construct. This catches it in the middle of a
12938 * literal string, or when it's the first thing after
12939 * something like "\b" */
12941 && (len || (p > RExC_start && isALPHA_A(*(p -1)))))
12943 ckWARNregdep(p + 1, "Unescaped left brace in regex is deprecated, passed through");
12946 default: /* A literal character */
12948 if (! UTF8_IS_INVARIANT(*p) && UTF) {
12950 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
12951 &numlen, UTF8_ALLOW_DEFAULT);
12957 } /* End of switch on the literal */
12959 /* Here, have looked at the literal character and <ender>
12960 * contains its ordinal, <p> points to the character after it.
12961 * We need to check if the next non-ignored thing is a
12962 * quantifier. Move <p> to after anything that should be
12963 * ignored, which, as a side effect, positions <p> for the next
12964 * loop iteration */
12965 skip_to_be_ignored_text(pRExC_state, &p,
12966 FALSE /* Don't force to /x */ );
12968 /* If the next thing is a quantifier, it applies to this
12969 * character only, which means that this character has to be in
12970 * its own node and can't just be appended to the string in an
12971 * existing node, so if there are already other characters in
12972 * the node, close the node with just them, and set up to do
12973 * this character again next time through, when it will be the
12974 * only thing in its new node */
12975 if ((next_is_quantifier = ( LIKELY(p < RExC_end)
12976 && UNLIKELY(ISMULT2(p))))
12983 /* Ready to add 'ender' to the node */
12985 if (! FOLD) { /* The simple case, just append the literal */
12987 /* In the sizing pass, we need only the size of the
12988 * character we are appending, hence we can delay getting
12989 * its representation until PASS2. */
12992 const STRLEN unilen = UVCHR_SKIP(ender);
12995 /* We have to subtract 1 just below (and again in
12996 * the corresponding PASS2 code) because the loop
12997 * increments <len> each time, as all but this path
12998 * (and one other) through it add a single byte to
12999 * the EXACTish node. But these paths would change
13000 * len to be the correct final value, so cancel out
13001 * the increment that follows */
13007 } else { /* PASS2 */
13010 U8 * new_s = uvchr_to_utf8((U8*)s, ender);
13011 len += (char *) new_s - s - 1;
13012 s = (char *) new_s;
13015 *(s++) = (char) ender;
13019 else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) {
13021 /* Here are folding under /l, and the code point is
13022 * problematic. First, we know we can't simplify things */
13023 maybe_exact = FALSE;
13024 maybe_exactfu = FALSE;
13026 /* A problematic code point in this context means that its
13027 * fold isn't known until runtime, so we can't fold it now.
13028 * (The non-problematic code points are the above-Latin1
13029 * ones that fold to also all above-Latin1. Their folds
13030 * don't vary no matter what the locale is.) But here we
13031 * have characters whose fold depends on the locale.
13032 * Unlike the non-folding case above, we have to keep track
13033 * of these in the sizing pass, so that we can make sure we
13034 * don't split too-long nodes in the middle of a potential
13035 * multi-char fold. And unlike the regular fold case
13036 * handled in the else clauses below, we don't actually
13037 * fold and don't have special cases to consider. What we
13038 * do for both passes is the PASS2 code for non-folding */
13039 goto not_fold_common;
13041 else /* A regular FOLD code point */
13043 #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
13044 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
13045 || UNICODE_DOT_DOT_VERSION > 0)
13046 /* See comments for join_exact() as to why we fold
13047 * this non-UTF at compile time */
13048 || ( node_type == EXACTFU
13049 && ender == LATIN_SMALL_LETTER_SHARP_S)
13052 /* Here, are folding and are not UTF-8 encoded; therefore
13053 * the character must be in the range 0-255, and is not /l
13054 * (Not /l because we already handled these under /l in
13055 * is_PROBLEMATIC_LOCALE_FOLD_cp) */
13056 if (IS_IN_SOME_FOLD_L1(ender)) {
13057 maybe_exact = FALSE;
13059 /* See if the character's fold differs between /d and
13060 * /u. This includes the multi-char fold SHARP S to
13062 if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) {
13063 RExC_seen_unfolded_sharp_s = 1;
13064 maybe_exactfu = FALSE;
13066 else if (maybe_exactfu
13067 && (PL_fold[ender] != PL_fold_latin1[ender]
13068 #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
13069 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
13070 || UNICODE_DOT_DOT_VERSION > 0)
13072 && isALPHA_FOLD_EQ(ender, 's')
13073 && isALPHA_FOLD_EQ(*(s-1), 's'))
13076 maybe_exactfu = FALSE;
13080 /* Even when folding, we store just the input character, as
13081 * we have an array that finds its fold quickly */
13082 *(s++) = (char) ender;
13084 else { /* FOLD, and UTF (or sharp s) */
13085 /* Unlike the non-fold case, we do actually have to
13086 * calculate the results here in pass 1. This is for two
13087 * reasons, the folded length may be longer than the
13088 * unfolded, and we have to calculate how many EXACTish
13089 * nodes it will take; and we may run out of room in a node
13090 * in the middle of a potential multi-char fold, and have
13091 * to back off accordingly. */
13094 if (isASCII_uni(ender)) {
13095 folded = toFOLD(ender);
13096 *(s)++ = (U8) folded;
13101 folded = _to_uni_fold_flags(
13105 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
13106 ? FOLD_FLAGS_NOMIX_ASCII
13110 /* The loop increments <len> each time, as all but this
13111 * path (and one other) through it add a single byte to
13112 * the EXACTish node. But this one has changed len to
13113 * be the correct final value, so subtract one to
13114 * cancel out the increment that follows */
13115 len += foldlen - 1;
13117 /* If this node only contains non-folding code points so
13118 * far, see if this new one is also non-folding */
13120 if (folded != ender) {
13121 maybe_exact = FALSE;
13124 /* Here the fold is the original; we have to check
13125 * further to see if anything folds to it */
13126 if (_invlist_contains_cp(PL_utf8_foldable,
13129 maybe_exact = FALSE;
13136 if (next_is_quantifier) {
13138 /* Here, the next input is a quantifier, and to get here,
13139 * the current character is the only one in the node.
13140 * Also, here <len> doesn't include the final byte for this
13146 } /* End of loop through literal characters */
13148 /* Here we have either exhausted the input or ran out of room in
13149 * the node. (If we encountered a character that can't be in the
13150 * node, transfer is made directly to <loopdone>, and so we
13151 * wouldn't have fallen off the end of the loop.) In the latter
13152 * case, we artificially have to split the node into two, because
13153 * we just don't have enough space to hold everything. This
13154 * creates a problem if the final character participates in a
13155 * multi-character fold in the non-final position, as a match that
13156 * should have occurred won't, due to the way nodes are matched,
13157 * and our artificial boundary. So back off until we find a non-
13158 * problematic character -- one that isn't at the beginning or
13159 * middle of such a fold. (Either it doesn't participate in any
13160 * folds, or appears only in the final position of all the folds it
13161 * does participate in.) A better solution with far fewer false
13162 * positives, and that would fill the nodes more completely, would
13163 * be to actually have available all the multi-character folds to
13164 * test against, and to back-off only far enough to be sure that
13165 * this node isn't ending with a partial one. <upper_parse> is set
13166 * further below (if we need to reparse the node) to include just
13167 * up through that final non-problematic character that this code
13168 * identifies, so when it is set to less than the full node, we can
13169 * skip the rest of this */
13170 if (FOLD && p < RExC_end && upper_parse == MAX_NODE_STRING_SIZE) {
13172 const STRLEN full_len = len;
13174 assert(len >= MAX_NODE_STRING_SIZE);
13176 /* Here, <s> points to the final byte of the final character.
13177 * Look backwards through the string until find a non-
13178 * problematic character */
13182 /* This has no multi-char folds to non-UTF characters */
13183 if (ASCII_FOLD_RESTRICTED) {
13187 while (--s >= s0 && IS_NON_FINAL_FOLD(*s)) { }
13191 if (! PL_NonL1NonFinalFold) {
13192 PL_NonL1NonFinalFold = _new_invlist_C_array(
13193 NonL1_Perl_Non_Final_Folds_invlist);
13196 /* Point to the first byte of the final character */
13197 s = (char *) utf8_hop((U8 *) s, -1);
13199 while (s >= s0) { /* Search backwards until find
13200 non-problematic char */
13201 if (UTF8_IS_INVARIANT(*s)) {
13203 /* There are no ascii characters that participate
13204 * in multi-char folds under /aa. In EBCDIC, the
13205 * non-ascii invariants are all control characters,
13206 * so don't ever participate in any folds. */
13207 if (ASCII_FOLD_RESTRICTED
13208 || ! IS_NON_FINAL_FOLD(*s))
13213 else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
13214 if (! IS_NON_FINAL_FOLD(EIGHT_BIT_UTF8_TO_NATIVE(
13220 else if (! _invlist_contains_cp(
13221 PL_NonL1NonFinalFold,
13222 valid_utf8_to_uvchr((U8 *) s, NULL)))
13227 /* Here, the current character is problematic in that
13228 * it does occur in the non-final position of some
13229 * fold, so try the character before it, but have to
13230 * special case the very first byte in the string, so
13231 * we don't read outside the string */
13232 s = (s == s0) ? s -1 : (char *) utf8_hop((U8 *) s, -1);
13233 } /* End of loop backwards through the string */
13235 /* If there were only problematic characters in the string,
13236 * <s> will point to before s0, in which case the length
13237 * should be 0, otherwise include the length of the
13238 * non-problematic character just found */
13239 len = (s < s0) ? 0 : s - s0 + UTF8SKIP(s);
13242 /* Here, have found the final character, if any, that is
13243 * non-problematic as far as ending the node without splitting
13244 * it across a potential multi-char fold. <len> contains the
13245 * number of bytes in the node up-to and including that
13246 * character, or is 0 if there is no such character, meaning
13247 * the whole node contains only problematic characters. In
13248 * this case, give up and just take the node as-is. We can't
13253 /* If the node ends in an 's' we make sure it stays EXACTF,
13254 * as if it turns into an EXACTFU, it could later get
13255 * joined with another 's' that would then wrongly match
13257 if (maybe_exactfu && isALPHA_FOLD_EQ(ender, 's'))
13259 maybe_exactfu = FALSE;
13263 /* Here, the node does contain some characters that aren't
13264 * problematic. If one such is the final character in the
13265 * node, we are done */
13266 if (len == full_len) {
13269 else if (len + ((UTF) ? UTF8SKIP(s) : 1) == full_len) {
13271 /* If the final character is problematic, but the
13272 * penultimate is not, back-off that last character to
13273 * later start a new node with it */
13278 /* Here, the final non-problematic character is earlier
13279 * in the input than the penultimate character. What we do
13280 * is reparse from the beginning, going up only as far as
13281 * this final ok one, thus guaranteeing that the node ends
13282 * in an acceptable character. The reason we reparse is
13283 * that we know how far in the character is, but we don't
13284 * know how to correlate its position with the input parse.
13285 * An alternate implementation would be to build that
13286 * correlation as we go along during the original parse,
13287 * but that would entail extra work for every node, whereas
13288 * this code gets executed only when the string is too
13289 * large for the node, and the final two characters are
13290 * problematic, an infrequent occurrence. Yet another
13291 * possible strategy would be to save the tail of the
13292 * string, and the next time regatom is called, initialize
13293 * with that. The problem with this is that unless you
13294 * back off one more character, you won't be guaranteed
13295 * regatom will get called again, unless regbranch,
13296 * regpiece ... are also changed. If you do back off that
13297 * extra character, so that there is input guaranteed to
13298 * force calling regatom, you can't handle the case where
13299 * just the first character in the node is acceptable. I
13300 * (khw) decided to try this method which doesn't have that
13301 * pitfall; if performance issues are found, we can do a
13302 * combination of the current approach plus that one */
13308 } /* End of verifying node ends with an appropriate char */
13310 loopdone: /* Jumped to when encounters something that shouldn't be
13313 /* I (khw) don't know if you can get here with zero length, but the
13314 * old code handled this situation by creating a zero-length EXACT
13315 * node. Might as well be NOTHING instead */
13321 /* If 'maybe_exact' is still set here, means there are no
13322 * code points in the node that participate in folds;
13323 * similarly for 'maybe_exactfu' and code points that match
13324 * differently depending on UTF8ness of the target string
13325 * (for /u), or depending on locale for /l */
13331 else if (maybe_exactfu) {
13337 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, len, ender,
13338 FALSE /* Don't look to see if could
13339 be turned into an EXACT
13340 node, as we have already
13345 RExC_parse = p - 1;
13346 Set_Node_Cur_Length(ret, parse_start);
13348 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
13349 FALSE /* Don't force to /x */ );
13351 /* len is STRLEN which is unsigned, need to copy to signed */
13354 vFAIL("Internal disaster");
13357 } /* End of label 'defchar:' */
13359 } /* End of giant switch on input character */
13366 S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr)
13368 /* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'. It
13369 * sets up the bitmap and any flags, removing those code points from the
13370 * inversion list, setting it to NULL should it become completely empty */
13372 PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST;
13373 assert(PL_regkind[OP(node)] == ANYOF);
13375 ANYOF_BITMAP_ZERO(node);
13376 if (*invlist_ptr) {
13378 /* This gets set if we actually need to modify things */
13379 bool change_invlist = FALSE;
13383 /* Start looking through *invlist_ptr */
13384 invlist_iterinit(*invlist_ptr);
13385 while (invlist_iternext(*invlist_ptr, &start, &end)) {
13389 if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) {
13390 ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP;
13393 /* Quit if are above what we should change */
13394 if (start >= NUM_ANYOF_CODE_POINTS) {
13398 change_invlist = TRUE;
13400 /* Set all the bits in the range, up to the max that we are doing */
13401 high = (end < NUM_ANYOF_CODE_POINTS - 1)
13403 : NUM_ANYOF_CODE_POINTS - 1;
13404 for (i = start; i <= (int) high; i++) {
13405 if (! ANYOF_BITMAP_TEST(node, i)) {
13406 ANYOF_BITMAP_SET(node, i);
13410 invlist_iterfinish(*invlist_ptr);
13412 /* Done with loop; remove any code points that are in the bitmap from
13413 * *invlist_ptr; similarly for code points above the bitmap if we have
13414 * a flag to match all of them anyways */
13415 if (change_invlist) {
13416 _invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr);
13418 if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
13419 _invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr);
13422 /* If have completely emptied it, remove it completely */
13423 if (_invlist_len(*invlist_ptr) == 0) {
13424 SvREFCNT_dec_NN(*invlist_ptr);
13425 *invlist_ptr = NULL;
13430 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
13431 Character classes ([:foo:]) can also be negated ([:^foo:]).
13432 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
13433 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
13434 but trigger failures because they are currently unimplemented. */
13436 #define POSIXCC_DONE(c) ((c) == ':')
13437 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
13438 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
13439 #define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';')
13441 #define WARNING_PREFIX "Assuming NOT a POSIX class since "
13442 #define NO_BLANKS_POSIX_WARNING "no blanks are allowed in one"
13443 #define SEMI_COLON_POSIX_WARNING "a semi-colon was found instead of a colon"
13445 #define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1)
13447 /* 'posix_warnings' and 'warn_text' are names of variables in the following
13449 #define ADD_POSIX_WARNING(p, text) STMT_START { \
13450 if (posix_warnings && ( posix_warnings != (AV **) -1 \
13451 || (PASS2 && ckWARN(WARN_REGEXP)))) \
13453 if (! warn_text) warn_text = newAV(); \
13454 av_push(warn_text, Perl_newSVpvf(aTHX_ \
13458 REPORT_LOCATION_ARGS(p))); \
13463 S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state,
13465 const char * const s, /* Where the putative posix class begins.
13466 Normally, this is one past the '['. This
13467 parameter exists so it can be somewhere
13468 besides RExC_parse. */
13469 char ** updated_parse_ptr, /* Where to set the updated parse pointer, or
13471 AV ** posix_warnings /* Where to place any generated warnings, or -1
13472 if to output them, or NULL */
13475 /* This parses what the caller thinks may be one of the three POSIX
13477 * 1) a character class, like [:blank:]
13478 * 2) a collating symbol, like [. .]
13479 * 3) an equivalence class, like [= =]
13480 * In the latter two cases, it croaks if it finds a syntactically legal
13481 * one, as these are not handled by Perl.
13483 * The main purpose is to look for a POSIX character class. It returns:
13484 * a) the class number
13485 * if it is a completely syntactically and semantically legal class.
13486 * 'updated_parse_ptr', if not NULL, is set to point to just after the
13487 * closing ']' of the class
13488 * b) OOB_NAMEDCLASS
13489 * if it appears that one of the three POSIX constructs was meant, but
13490 * its specification was somehow defective. 'updated_parse_ptr', if
13491 * not NULL, is set to point to the character just after the end
13492 * character of the class. See below for handling of warnings.
13493 * c) NOT_MEANT_TO_BE_A_POSIX_CLASS
13494 * if it doesn't appear that a POSIX construct was intended.
13495 * 'updated_parse_ptr' is not changed. No warnings nor errors are
13498 * In b) there may be warnings and even errors generated. What to do about
13499 * these is determined by the 'posix_warnings' parameter. If it is NULL,
13500 * this call is treated as a check-only, scouting-out-the-territory call,
13501 * and no warnings nor errors are generated at all. Otherwise, any errors
13502 * are raised if found. If 'posix_warnings' is -1 (appropriately cast),
13503 * warnings are generated and displayed (in pass 2), just as they would be
13504 * for any other message of the same type from this file. If it isn't NULL
13505 * and not -1, warnings aren't displayed, but instead an AV is generated
13506 * with all the warning messages (that aren't to be ignored) stored into
13507 * it, so that the caller can output them if it wants. This is done in all
13508 * passes. The reason for this is that the rest of the parsing is heavily
13509 * dependent on whether this routine found a valid posix class or not. If
13510 * it did, the closing ']' is absorbed as part of the class. If no class
13511 * or an invalid one is found, any ']' will be considered the terminator of
13512 * the outer bracketed character class, leading to very different results.
13513 * In particular, a '(?[ ])' construct will likely have a syntax error if
13514 * the class is parsed other than intended, and this will happen in pass1,
13515 * before the warnings would normally be output. This mechanism allows the
13516 * caller to output those warnings in pass1 just before dieing, giving a
13517 * much better clue as to what is wrong.
13519 * The reason for this function, and its complexity is that a bracketed
13520 * character class can contain just about anything. But it's easy to
13521 * mistype the very specific posix class syntax but yielding a valid
13522 * regular bracketed class, so it silently gets compiled into something
13523 * quite unintended.
13525 * The solution adopted here maintains backward compatibility except that
13526 * it adds a warning if it looks like a posix class was intended but
13527 * improperly specified. The warning is not raised unless what is input
13528 * very closely resembles one of the 14 legal posix classes. To do this,
13529 * it uses fuzzy parsing. It calculates how many single-character edits it
13530 * would take to transform what was input into a legal posix class. Only
13531 * if that number is quite small does it think that the intention was a
13532 * posix class. Obviously these are heuristics, and there will be cases
13533 * where it errs on one side or another, and they can be tweaked as
13534 * experience informs.
13536 * The syntax for a legal posix class is:
13538 * qr/(?xa: \[ : \^? [:lower:]{4,6} : \] )/
13540 * What this routine considers syntactically to be an intended posix class
13541 * is this (the comments indicate some restrictions that the pattern
13544 * qr/(?x: \[? # The left bracket, possibly
13546 * \h* # possibly followed by blanks
13547 * (?: \^ \h* )? # possibly a misplaced caret
13548 * [:;]? # The opening class character,
13549 * # possibly omitted. A typo
13550 * # semi-colon can also be used.
13552 * \^? # possibly a correctly placed
13553 * # caret, but not if there was also
13554 * # a misplaced one
13556 * .{3,15} # The class name. If there are
13557 * # deviations from the legal syntax,
13558 * # its edit distance must be close
13559 * # to a real class name in order
13560 * # for it to be considered to be
13561 * # an intended posix class.
13563 * [:punct:]? # The closing class character,
13564 * # possibly omitted. If not a colon
13565 * # nor semi colon, the class name
13566 * # must be even closer to a valid
13569 * \]? # The right bracket, possibly
13573 * In the above, \h must be ASCII-only.
13575 * These are heuristics, and can be tweaked as field experience dictates.
13576 * There will be cases when someone didn't intend to specify a posix class
13577 * that this warns as being so. The goal is to minimize these, while
13578 * maximizing the catching of things intended to be a posix class that
13579 * aren't parsed as such.
13583 const char * const e = RExC_end;
13584 unsigned complement = 0; /* If to complement the class */
13585 bool found_problem = FALSE; /* Assume OK until proven otherwise */
13586 bool has_opening_bracket = FALSE;
13587 bool has_opening_colon = FALSE;
13588 int class_number = OOB_NAMEDCLASS; /* Out-of-bounds until find
13590 AV* warn_text = NULL; /* any warning messages */
13591 const char * possible_end = NULL; /* used for a 2nd parse pass */
13592 const char* name_start; /* ptr to class name first char */
13594 /* If the number of single-character typos the input name is away from a
13595 * legal name is no more than this number, it is considered to have meant
13596 * the legal name */
13597 int max_distance = 2;
13599 /* to store the name. The size determines the maximum length before we
13600 * decide that no posix class was intended. Should be at least
13601 * sizeof("alphanumeric") */
13604 PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX;
13607 return NOT_MEANT_TO_BE_A_POSIX_CLASS;
13610 if (*(p - 1) != '[') {
13611 ADD_POSIX_WARNING(p, "it doesn't start with a '['");
13612 found_problem = TRUE;
13615 has_opening_bracket = TRUE;
13618 /* They could be confused and think you can put spaces between the
13621 found_problem = TRUE;
13625 } while (p < e && isBLANK(*p));
13627 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
13630 /* For [. .] and [= =]. These are quite different internally from [: :],
13631 * so they are handled separately. */
13632 if (POSIXCC_NOTYET(*p)) {
13633 const char open_char = *p;
13634 const char * temp_ptr = p + 1;
13635 unsigned int len = 0;
13637 /* These two constructs are not handled by perl, and if we find a
13638 * syntactically valid one, we croak. It looks like just about any
13639 * byte can be in them, but they are likely very short, like [.ch.] to
13640 * denote a ligature 'ch' single character. If we find something that
13641 * started out to look like one of these constructs, but isn't, we
13642 * break so that it can be checked for being a class name with a typo
13643 * of '.' or '=' instead of a colon */
13644 while (temp_ptr < e) {
13647 /* qr/[[.].]]/, for example, is valid. But otherwise we quit on an
13648 * unexpected ']'. It is possible, it appears, for such a ']' to
13649 * be not in the final position, but that's so unlikely that that
13650 * case is not handled. */
13651 if (*temp_ptr == ']' && temp_ptr[1] != open_char) {
13655 /* XXX this could be cut down, but this value is certainly large
13661 if (*temp_ptr == open_char) {
13663 if (*temp_ptr == ']') {
13665 if (! found_problem && posix_warnings) {
13666 RExC_parse = (char *) temp_ptr;
13667 vFAIL3("POSIX syntax [%c %c] is reserved for future "
13668 "extensions", open_char, open_char);
13671 /* Here, the syntax wasn't completely valid, or else the
13672 * call is to check-only */
13673 if (updated_parse_ptr) {
13674 *updated_parse_ptr = (char *) temp_ptr;
13677 return OOB_NAMEDCLASS;
13680 else if (*temp_ptr == '\\') {
13682 /* A backslash is treate as like any other character, unless it
13683 * precedes a comment starter. XXX multiple backslashes in a
13684 * row are not handled specially here, nor would they ever
13685 * likely to be handled specially in one of these constructs */
13686 if (temp_ptr[1] == '#' && (RExC_flags & RXf_PMf_EXTENDED)) {
13691 else if (*temp_ptr == '#' && (RExC_flags & RXf_PMf_EXTENDED)) {
13692 break; /* Under no circumstances can we look at the interior
13695 else if (*temp_ptr == '\n') { /* And we don't allow newlines
13696 either as it's extremely
13697 unlikely that one could be in an
13701 else if (UTF && ! UTF8_IS_INVARIANT(*temp_ptr)) {
13702 /* XXX Since perl will never handle multi-byte locales, except
13703 * for UTF-8, we could break if we found a byte above latin1,
13704 * but perhaps the person intended to use one. */
13705 temp_ptr += UTF8SKIP(temp_ptr);
13713 /* Here, we think there is a possibility that a [: :] class was meant, and
13714 * we have the first real character. It could be they think the '^' comes
13717 found_problem = TRUE;
13718 ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon");
13723 found_problem = TRUE;
13727 } while (p < e && isBLANK(*p));
13729 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
13733 /* But the first character should be a colon, which they could have easily
13734 * mistyped on a qwerty keyboard as a semi-colon (and which may be hard to
13735 * distinguish from a colon, so treat that as a colon). */
13738 has_opening_colon = TRUE;
13740 else if (*p == ';') {
13741 found_problem = TRUE;
13743 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
13744 has_opening_colon = TRUE;
13747 found_problem = TRUE;
13748 ADD_POSIX_WARNING(p, "there must be a starting ':'");
13750 /* Consider an initial punctuation (not one of the recognized ones) to
13751 * be a left terminator */
13752 if (*p != '^' && *p != ']' && isPUNCT(*p)) {
13757 /* They may think that you can put spaces between the components */
13759 found_problem = TRUE;
13763 } while (p < e && isBLANK(*p));
13765 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
13770 /* We consider something like [^:^alnum:]] to not have been intended to
13771 * be a posix class, but XXX maybe we should */
13773 return NOT_MEANT_TO_BE_A_POSIX_CLASS;
13780 /* Again, they may think that you can put spaces between the components */
13782 found_problem = TRUE;
13786 } while (p < e && isBLANK(*p));
13788 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
13793 /* XXX This ']' may be a typo, and something else was meant. But
13794 * treating it as such creates enough complications, that that
13795 * possibility isn't currently considered here. So we assume that the
13796 * ']' is what is intended, and if we've already found an initial '[',
13797 * this leaves this construct looking like [:] or [:^], which almost
13798 * certainly weren't intended to be posix classes */
13799 if (has_opening_bracket) {
13800 return NOT_MEANT_TO_BE_A_POSIX_CLASS;
13803 /* But this function can be called when we parse the colon for
13804 * something like qr/[alpha:]]/, so we back up to look for the
13809 found_problem = TRUE;
13810 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
13812 else if (*p != ':') {
13814 /* XXX We are currently very restrictive here, so this code doesn't
13815 * consider the possibility that, say, /[alpha.]]/ was intended to
13816 * be a posix class. */
13817 return NOT_MEANT_TO_BE_A_POSIX_CLASS;
13820 /* Here we have something like 'foo:]'. There was no initial colon,
13821 * and we back up over 'foo. XXX Unlike the going forward case, we
13822 * don't handle typos of non-word chars in the middle */
13823 has_opening_colon = FALSE;
13826 while (p > RExC_start && isWORDCHAR(*p)) {
13831 /* Here, we have positioned ourselves to where we think the first
13832 * character in the potential class is */
13835 /* Now the interior really starts. There are certain key characters that
13836 * can end the interior, or these could just be typos. To catch both
13837 * cases, we may have to do two passes. In the first pass, we keep on
13838 * going unless we come to a sequence that matches
13839 * qr/ [[:punct:]] [[:blank:]]* \] /xa
13840 * This means it takes a sequence to end the pass, so two typos in a row if
13841 * that wasn't what was intended. If the class is perfectly formed, just
13842 * this one pass is needed. We also stop if there are too many characters
13843 * being accumulated, but this number is deliberately set higher than any
13844 * real class. It is set high enough so that someone who thinks that
13845 * 'alphanumeric' is a correct name would get warned that it wasn't.
13846 * While doing the pass, we keep track of where the key characters were in
13847 * it. If we don't find an end to the class, and one of the key characters
13848 * was found, we redo the pass, but stop when we get to that character.
13849 * Thus the key character was considered a typo in the first pass, but a
13850 * terminator in the second. If two key characters are found, we stop at
13851 * the second one in the first pass. Again this can miss two typos, but
13852 * catches a single one
13854 * In the first pass, 'possible_end' starts as NULL, and then gets set to
13855 * point to the first key character. For the second pass, it starts as -1.
13861 bool has_blank = FALSE;
13862 bool has_upper = FALSE;
13863 bool has_terminating_colon = FALSE;
13864 bool has_terminating_bracket = FALSE;
13865 bool has_semi_colon = FALSE;
13866 unsigned int name_len = 0;
13867 int punct_count = 0;
13871 /* Squeeze out blanks when looking up the class name below */
13872 if (isBLANK(*p) ) {
13874 found_problem = TRUE;
13879 /* The name will end with a punctuation */
13881 const char * peek = p + 1;
13883 /* Treat any non-']' punctuation followed by a ']' (possibly
13884 * with intervening blanks) as trying to terminate the class.
13885 * ']]' is very likely to mean a class was intended (but
13886 * missing the colon), but the warning message that gets
13887 * generated shows the error position better if we exit the
13888 * loop at the bottom (eventually), so skip it here. */
13890 if (peek < e && isBLANK(*peek)) {
13892 found_problem = TRUE;
13895 } while (peek < e && isBLANK(*peek));
13898 if (peek < e && *peek == ']') {
13899 has_terminating_bracket = TRUE;
13901 has_terminating_colon = TRUE;
13903 else if (*p == ';') {
13904 has_semi_colon = TRUE;
13905 has_terminating_colon = TRUE;
13908 found_problem = TRUE;
13915 /* Here we have punctuation we thought didn't end the class.
13916 * Keep track of the position of the key characters that are
13917 * more likely to have been class-enders */
13918 if (*p == ']' || *p == '[' || *p == ':' || *p == ';') {
13920 /* Allow just one such possible class-ender not actually
13921 * ending the class. */
13922 if (possible_end) {
13928 /* If we have too many punctuation characters, no use in
13930 if (++punct_count > max_distance) {
13934 /* Treat the punctuation as a typo. */
13935 input_text[name_len++] = *p;
13938 else if (isUPPER(*p)) { /* Use lowercase for lookup */
13939 input_text[name_len++] = toLOWER(*p);
13941 found_problem = TRUE;
13943 } else if (! UTF || UTF8_IS_INVARIANT(*p)) {
13944 input_text[name_len++] = *p;
13948 input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL);
13952 /* The declaration of 'input_text' is how long we allow a potential
13953 * class name to be, before saying they didn't mean a class name at
13955 if (name_len >= C_ARRAY_LENGTH(input_text)) {
13960 /* We get to here when the possible class name hasn't been properly
13961 * terminated before:
13962 * 1) we ran off the end of the pattern; or
13963 * 2) found two characters, each of which might have been intended to
13964 * be the name's terminator
13965 * 3) found so many punctuation characters in the purported name,
13966 * that the edit distance to a valid one is exceeded
13967 * 4) we decided it was more characters than anyone could have
13968 * intended to be one. */
13970 found_problem = TRUE;
13972 /* In the final two cases, we know that looking up what we've
13973 * accumulated won't lead to a match, even a fuzzy one. */
13974 if ( name_len >= C_ARRAY_LENGTH(input_text)
13975 || punct_count > max_distance)
13977 /* If there was an intermediate key character that could have been
13978 * an intended end, redo the parse, but stop there */
13979 if (possible_end && possible_end != (char *) -1) {
13980 possible_end = (char *) -1; /* Special signal value to say
13981 we've done a first pass */
13986 /* Otherwise, it can't have meant to have been a class */
13987 return NOT_MEANT_TO_BE_A_POSIX_CLASS;
13990 /* If we ran off the end, and the final character was a punctuation
13991 * one, back up one, to look at that final one just below. Later, we
13992 * will restore the parse pointer if appropriate */
13993 if (name_len && p == e && isPUNCT(*(p-1))) {
13998 if (p < e && isPUNCT(*p)) {
14000 has_terminating_bracket = TRUE;
14002 /* If this is a 2nd ']', and the first one is just below this
14003 * one, consider that to be the real terminator. This gives a
14004 * uniform and better positioning for the warning message */
14006 && possible_end != (char *) -1
14007 && *possible_end == ']'
14008 && name_len && input_text[name_len - 1] == ']')
14013 /* And this is actually equivalent to having done the 2nd
14014 * pass now, so set it to not try again */
14015 possible_end = (char *) -1;
14020 has_terminating_colon = TRUE;
14022 else if (*p == ';') {
14023 has_semi_colon = TRUE;
14024 has_terminating_colon = TRUE;
14032 /* Here, we have a class name to look up. We can short circuit the
14033 * stuff below for short names that can't possibly be meant to be a
14034 * class name. (We can do this on the first pass, as any second pass
14035 * will yield an even shorter name) */
14036 if (name_len < 3) {
14037 return NOT_MEANT_TO_BE_A_POSIX_CLASS;
14040 /* Find which class it is. Initially switch on the length of the name.
14042 switch (name_len) {
14044 if (memEQ(name_start, "word", 4)) {
14045 /* this is not POSIX, this is the Perl \w */
14046 class_number = ANYOF_WORDCHAR;
14050 /* Names all of length 5: alnum alpha ascii blank cntrl digit
14051 * graph lower print punct space upper
14052 * Offset 4 gives the best switch position. */
14053 switch (name_start[4]) {
14055 if (memEQ(name_start, "alph", 4)) /* alpha */
14056 class_number = ANYOF_ALPHA;
14059 if (memEQ(name_start, "spac", 4)) /* space */
14060 class_number = ANYOF_SPACE;
14063 if (memEQ(name_start, "grap", 4)) /* graph */
14064 class_number = ANYOF_GRAPH;
14067 if (memEQ(name_start, "asci", 4)) /* ascii */
14068 class_number = ANYOF_ASCII;
14071 if (memEQ(name_start, "blan", 4)) /* blank */
14072 class_number = ANYOF_BLANK;
14075 if (memEQ(name_start, "cntr", 4)) /* cntrl */
14076 class_number = ANYOF_CNTRL;
14079 if (memEQ(name_start, "alnu", 4)) /* alnum */
14080 class_number = ANYOF_ALPHANUMERIC;
14083 if (memEQ(name_start, "lowe", 4)) /* lower */
14084 class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER;
14085 else if (memEQ(name_start, "uppe", 4)) /* upper */
14086 class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER;
14089 if (memEQ(name_start, "digi", 4)) /* digit */
14090 class_number = ANYOF_DIGIT;
14091 else if (memEQ(name_start, "prin", 4)) /* print */
14092 class_number = ANYOF_PRINT;
14093 else if (memEQ(name_start, "punc", 4)) /* punct */
14094 class_number = ANYOF_PUNCT;
14099 if (memEQ(name_start, "xdigit", 6))
14100 class_number = ANYOF_XDIGIT;
14104 /* If the name exactly matches a posix class name the class number will
14105 * here be set to it, and the input almost certainly was meant to be a
14106 * posix class, so we can skip further checking. If instead the syntax
14107 * is exactly correct, but the name isn't one of the legal ones, we
14108 * will return that as an error below. But if neither of these apply,
14109 * it could be that no posix class was intended at all, or that one
14110 * was, but there was a typo. We tease these apart by doing fuzzy
14111 * matching on the name */
14112 if (class_number == OOB_NAMEDCLASS && found_problem) {
14113 const UV posix_names[][6] = {
14114 { 'a', 'l', 'n', 'u', 'm' },
14115 { 'a', 'l', 'p', 'h', 'a' },
14116 { 'a', 's', 'c', 'i', 'i' },
14117 { 'b', 'l', 'a', 'n', 'k' },
14118 { 'c', 'n', 't', 'r', 'l' },
14119 { 'd', 'i', 'g', 'i', 't' },
14120 { 'g', 'r', 'a', 'p', 'h' },
14121 { 'l', 'o', 'w', 'e', 'r' },
14122 { 'p', 'r', 'i', 'n', 't' },
14123 { 'p', 'u', 'n', 'c', 't' },
14124 { 's', 'p', 'a', 'c', 'e' },
14125 { 'u', 'p', 'p', 'e', 'r' },
14126 { 'w', 'o', 'r', 'd' },
14127 { 'x', 'd', 'i', 'g', 'i', 't' }
14129 /* The names of the above all have added NULs to make them the same
14130 * size, so we need to also have the real lengths */
14131 const UV posix_name_lengths[] = {
14132 sizeof("alnum") - 1,
14133 sizeof("alpha") - 1,
14134 sizeof("ascii") - 1,
14135 sizeof("blank") - 1,
14136 sizeof("cntrl") - 1,
14137 sizeof("digit") - 1,
14138 sizeof("graph") - 1,
14139 sizeof("lower") - 1,
14140 sizeof("print") - 1,
14141 sizeof("punct") - 1,
14142 sizeof("space") - 1,
14143 sizeof("upper") - 1,
14144 sizeof("word") - 1,
14145 sizeof("xdigit")- 1
14148 int temp_max = max_distance; /* Use a temporary, so if we
14149 reparse, we haven't changed the
14152 /* Use a smaller max edit distance if we are missing one of the
14154 if ( has_opening_bracket + has_opening_colon < 2
14155 || has_terminating_bracket + has_terminating_colon < 2)
14160 /* See if the input name is close to a legal one */
14161 for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) {
14163 /* Short circuit call if the lengths are too far apart to be
14165 if (abs( (int) (name_len - posix_name_lengths[i]))
14171 if (edit_distance(input_text,
14174 posix_name_lengths[i],
14178 { /* If it is close, it probably was intended to be a class */
14179 goto probably_meant_to_be;
14183 /* Here the input name is not close enough to a valid class name
14184 * for us to consider it to be intended to be a posix class. If
14185 * we haven't already done so, and the parse found a character that
14186 * could have been terminators for the name, but which we absorbed
14187 * as typos during the first pass, repeat the parse, signalling it
14188 * to stop at that character */
14189 if (possible_end && possible_end != (char *) -1) {
14190 possible_end = (char *) -1;
14195 /* Here neither pass found a close-enough class name */
14196 return NOT_MEANT_TO_BE_A_POSIX_CLASS;
14199 probably_meant_to_be:
14201 /* Here we think that a posix specification was intended. Update any
14203 if (updated_parse_ptr) {
14204 *updated_parse_ptr = (char *) p;
14207 /* If a posix class name was intended but incorrectly specified, we
14208 * output or return the warnings */
14209 if (found_problem) {
14211 /* We set flags for these issues in the parse loop above instead of
14212 * adding them to the list of warnings, because we can parse it
14213 * twice, and we only want one warning instance */
14215 ADD_POSIX_WARNING(p, "the name must be all lowercase letters");
14218 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14220 if (has_semi_colon) {
14221 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
14223 else if (! has_terminating_colon) {
14224 ADD_POSIX_WARNING(p, "there is no terminating ':'");
14226 if (! has_terminating_bracket) {
14227 ADD_POSIX_WARNING(p, "there is no terminating ']'");
14231 if (posix_warnings != (AV **) -1) {
14232 *posix_warnings = warn_text;
14236 while ((msg = av_shift(warn_text)) != &PL_sv_undef) {
14237 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
14239 SvREFCNT_dec_NN(msg);
14241 SvREFCNT_dec_NN(warn_text);
14245 else if (class_number != OOB_NAMEDCLASS) {
14246 /* If it is a known class, return the class. The class number
14247 * #defines are structured so each complement is +1 to the normal
14249 return class_number + complement;
14251 else if (posix_warnings) {
14253 /* Here, it is an unrecognized class. This is an error (unless the
14254 * call is to check only, which we've already handled above) */
14255 const char * const complement_string = (complement)
14258 RExC_parse = (char *) p;
14259 vFAIL3utf8f("POSIX class [:%s%"UTF8f":] unknown",
14261 UTF8fARG(UTF, RExC_parse - name_start - 2, name_start));
14265 return OOB_NAMEDCLASS;
14267 #undef ADD_POSIX_WARNING
14269 STATIC unsigned int
14270 S_regex_set_precedence(const U8 my_operator) {
14272 /* Returns the precedence in the (?[...]) construct of the input operator,
14273 * specified by its character representation. The precedence follows
14274 * general Perl rules, but it extends this so that ')' and ']' have (low)
14275 * precedence even though they aren't really operators */
14277 switch (my_operator) {
14293 NOT_REACHED; /* NOTREACHED */
14294 return 0; /* Silence compiler warning */
14298 S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist,
14299 I32 *flagp, U32 depth,
14300 char * const oregcomp_parse)
14302 /* Handle the (?[...]) construct to do set operations */
14304 U8 curchar; /* Current character being parsed */
14305 UV start, end; /* End points of code point ranges */
14306 SV* final = NULL; /* The end result inversion list */
14307 SV* result_string; /* 'final' stringified */
14308 AV* stack; /* stack of operators and operands not yet
14310 AV* fence_stack = NULL; /* A stack containing the positions in
14311 'stack' of where the undealt-with left
14312 parens would be if they were actually
14314 IV fence = 0; /* Position of where most recent undealt-
14315 with left paren in stack is; -1 if none.
14317 STRLEN len; /* Temporary */
14318 regnode* node; /* Temporary, and final regnode returned by
14320 const bool save_fold = FOLD; /* Temporary */
14321 char *save_end, *save_parse; /* Temporaries */
14322 const bool in_locale = LOC; /* we turn off /l during processing */
14323 AV* posix_warnings = NULL;
14325 GET_RE_DEBUG_FLAGS_DECL;
14327 PERL_ARGS_ASSERT_HANDLE_REGEX_SETS;
14330 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
14333 REQUIRE_UNI_RULES(flagp, NULL); /* The use of this operator implies /u.
14334 This is required so that the compile
14335 time values are valid in all runtime
14338 /* This will return only an ANYOF regnode, or (unlikely) something smaller
14339 * (such as EXACT). Thus we can skip most everything if just sizing. We
14340 * call regclass to handle '[]' so as to not have to reinvent its parsing
14341 * rules here (throwing away the size it computes each time). And, we exit
14342 * upon an unescaped ']' that isn't one ending a regclass. To do both
14343 * these things, we need to realize that something preceded by a backslash
14344 * is escaped, so we have to keep track of backslashes */
14346 UV depth = 0; /* how many nested (?[...]) constructs */
14348 while (RExC_parse < RExC_end) {
14349 SV* current = NULL;
14351 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
14352 TRUE /* Force /x */ );
14354 switch (*RExC_parse) {
14356 if (RExC_parse[1] == '[') depth++, RExC_parse++;
14361 /* Skip past this, so the next character gets skipped, after
14364 if (*RExC_parse == 'c') {
14365 /* Skip the \cX notation for control characters */
14366 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
14372 /* See if this is a [:posix:] class. */
14373 bool is_posix_class = (OOB_NAMEDCLASS
14374 < handle_possible_posix(pRExC_state,
14378 /* If it is a posix class, leave the parse pointer at the
14379 * '[' to fool regclass() into thinking it is part of a
14380 * '[[:posix:]]'. */
14381 if (! is_posix_class) {
14385 /* regclass() can only return RESTART_PASS1 and NEED_UTF8
14386 * if multi-char folds are allowed. */
14387 if (!regclass(pRExC_state, flagp,depth+1,
14388 is_posix_class, /* parse the whole char
14389 class only if not a
14391 FALSE, /* don't allow multi-char folds */
14392 TRUE, /* silence non-portable warnings. */
14394 FALSE, /* Require return to be an ANYOF */
14398 FAIL2("panic: regclass returned NULL to handle_sets, "
14399 "flags=%#"UVxf"", (UV) *flagp);
14401 /* function call leaves parse pointing to the ']', except
14402 * if we faked it */
14403 if (is_posix_class) {
14407 SvREFCNT_dec(current); /* In case it returned something */
14412 if (depth--) break;
14414 if (*RExC_parse == ')') {
14415 node = reganode(pRExC_state, ANYOF, 0);
14416 RExC_size += ANYOF_SKIP;
14417 nextchar(pRExC_state);
14418 Set_Node_Length(node,
14419 RExC_parse - oregcomp_parse + 1); /* MJD */
14421 set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
14429 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
14433 /* We output the messages even if warnings are off, because we'll fail
14434 * the very next thing, and these give a likely diagnosis for that */
14435 if (posix_warnings) {
14437 while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) {
14438 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg));
14439 SvREFCNT_dec_NN(msg);
14441 SvREFCNT_dec_NN(posix_warnings);
14444 FAIL("Syntax error in (?[...])");
14447 /* Pass 2 only after this. */
14448 Perl_ck_warner_d(aTHX_
14449 packWARN(WARN_EXPERIMENTAL__REGEX_SETS),
14450 "The regex_sets feature is experimental" REPORT_LOCATION,
14451 REPORT_LOCATION_ARGS(RExC_parse));
14453 /* Everything in this construct is a metacharacter. Operands begin with
14454 * either a '\' (for an escape sequence), or a '[' for a bracketed
14455 * character class. Any other character should be an operator, or
14456 * parenthesis for grouping. Both types of operands are handled by calling
14457 * regclass() to parse them. It is called with a parameter to indicate to
14458 * return the computed inversion list. The parsing here is implemented via
14459 * a stack. Each entry on the stack is a single character representing one
14460 * of the operators; or else a pointer to an operand inversion list. */
14462 #define IS_OPERATOR(a) SvIOK(a)
14463 #define IS_OPERAND(a) (! IS_OPERATOR(a))
14465 /* The stack is kept in Łukasiewicz order. (That's pronounced similar
14466 * to luke-a-shave-itch (or -itz), but people who didn't want to bother
14467 * with pronouncing it called it Reverse Polish instead, but now that YOU
14468 * know how to pronounce it you can use the correct term, thus giving due
14469 * credit to the person who invented it, and impressing your geek friends.
14470 * Wikipedia says that the pronounciation of "Ł" has been changing so that
14471 * it is now more like an English initial W (as in wonk) than an L.)
14473 * This means that, for example, 'a | b & c' is stored on the stack as
14481 * where the numbers in brackets give the stack [array] element number.
14482 * In this implementation, parentheses are not stored on the stack.
14483 * Instead a '(' creates a "fence" so that the part of the stack below the
14484 * fence is invisible except to the corresponding ')' (this allows us to
14485 * replace testing for parens, by using instead subtraction of the fence
14486 * position). As new operands are processed they are pushed onto the stack
14487 * (except as noted in the next paragraph). New operators of higher
14488 * precedence than the current final one are inserted on the stack before
14489 * the lhs operand (so that when the rhs is pushed next, everything will be
14490 * in the correct positions shown above. When an operator of equal or
14491 * lower precedence is encountered in parsing, all the stacked operations
14492 * of equal or higher precedence are evaluated, leaving the result as the
14493 * top entry on the stack. This makes higher precedence operations
14494 * evaluate before lower precedence ones, and causes operations of equal
14495 * precedence to left associate.
14497 * The only unary operator '!' is immediately pushed onto the stack when
14498 * encountered. When an operand is encountered, if the top of the stack is
14499 * a '!", the complement is immediately performed, and the '!' popped. The
14500 * resulting value is treated as a new operand, and the logic in the
14501 * previous paragraph is executed. Thus in the expression
14503 * the stack looks like
14509 * as 'b' gets parsed, the latter gets evaluated to '!b', and the stack
14516 * A ')' is treated as an operator with lower precedence than all the
14517 * aforementioned ones, which causes all operations on the stack above the
14518 * corresponding '(' to be evaluated down to a single resultant operand.
14519 * Then the fence for the '(' is removed, and the operand goes through the
14520 * algorithm above, without the fence.
14522 * A separate stack is kept of the fence positions, so that the position of
14523 * the latest so-far unbalanced '(' is at the top of it.
14525 * The ']' ending the construct is treated as the lowest operator of all,
14526 * so that everything gets evaluated down to a single operand, which is the
14529 sv_2mortal((SV *)(stack = newAV()));
14530 sv_2mortal((SV *)(fence_stack = newAV()));
14532 while (RExC_parse < RExC_end) {
14533 I32 top_index; /* Index of top-most element in 'stack' */
14534 SV** top_ptr; /* Pointer to top 'stack' element */
14535 SV* current = NULL; /* To contain the current inversion list
14537 SV* only_to_avoid_leaks;
14539 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
14540 TRUE /* Force /x */ );
14541 if (RExC_parse >= RExC_end) {
14542 Perl_croak(aTHX_ "panic: Read past end of '(?[ ])'");
14545 curchar = UCHARAT(RExC_parse);
14549 top_index = av_tindex(stack);
14552 SV** stacked_ptr; /* Ptr to something already on 'stack' */
14553 char stacked_operator; /* The topmost operator on the 'stack'. */
14554 SV* lhs; /* Operand to the left of the operator */
14555 SV* rhs; /* Operand to the right of the operator */
14556 SV* fence_ptr; /* Pointer to top element of the fence
14561 if ( RExC_parse < RExC_end - 1
14562 && (UCHARAT(RExC_parse + 1) == '?'))
14564 /* If is a '(?', could be an embedded '(?flags:(?[...])'.
14565 * This happens when we have some thing like
14567 * my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
14569 * qr/(?[ \p{Digit} & $thai_or_lao ])/;
14571 * Here we would be handling the interpolated
14572 * '$thai_or_lao'. We handle this by a recursive call to
14573 * ourselves which returns the inversion list the
14574 * interpolated expression evaluates to. We use the flags
14575 * from the interpolated pattern. */
14576 U32 save_flags = RExC_flags;
14577 const char * save_parse;
14579 RExC_parse += 2; /* Skip past the '(?' */
14580 save_parse = RExC_parse;
14582 /* Parse any flags for the '(?' */
14583 parse_lparen_question_flags(pRExC_state);
14585 if (RExC_parse == save_parse /* Makes sure there was at
14586 least one flag (or else
14587 this embedding wasn't
14589 || RExC_parse >= RExC_end - 4
14590 || UCHARAT(RExC_parse) != ':'
14591 || UCHARAT(++RExC_parse) != '('
14592 || UCHARAT(++RExC_parse) != '?'
14593 || UCHARAT(++RExC_parse) != '[')
14596 /* In combination with the above, this moves the
14597 * pointer to the point just after the first erroneous
14598 * character (or if there are no flags, to where they
14599 * should have been) */
14600 if (RExC_parse >= RExC_end - 4) {
14601 RExC_parse = RExC_end;
14603 else if (RExC_parse != save_parse) {
14604 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
14606 vFAIL("Expecting '(?flags:(?[...'");
14609 /* Recurse, with the meat of the embedded expression */
14611 (void) handle_regex_sets(pRExC_state, ¤t, flagp,
14612 depth+1, oregcomp_parse);
14614 /* Here, 'current' contains the embedded expression's
14615 * inversion list, and RExC_parse points to the trailing
14616 * ']'; the next character should be the ')' */
14618 assert(UCHARAT(RExC_parse) == ')');
14620 /* Then the ')' matching the original '(' handled by this
14621 * case: statement */
14623 assert(UCHARAT(RExC_parse) == ')');
14626 RExC_flags = save_flags;
14627 goto handle_operand;
14630 /* A regular '('. Look behind for illegal syntax */
14631 if (top_index - fence >= 0) {
14632 /* If the top entry on the stack is an operator, it had
14633 * better be a '!', otherwise the entry below the top
14634 * operand should be an operator */
14635 if ( ! (top_ptr = av_fetch(stack, top_index, FALSE))
14636 || (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!')
14637 || ( IS_OPERAND(*top_ptr)
14638 && ( top_index - fence < 1
14639 || ! (stacked_ptr = av_fetch(stack,
14642 || ! IS_OPERATOR(*stacked_ptr))))
14645 vFAIL("Unexpected '(' with no preceding operator");
14649 /* Stack the position of this undealt-with left paren */
14650 fence = top_index + 1;
14651 av_push(fence_stack, newSViv(fence));
14655 /* regclass() can only return RESTART_PASS1 and NEED_UTF8 if
14656 * multi-char folds are allowed. */
14657 if (!regclass(pRExC_state, flagp,depth+1,
14658 TRUE, /* means parse just the next thing */
14659 FALSE, /* don't allow multi-char folds */
14660 FALSE, /* don't silence non-portable warnings. */
14662 FALSE, /* Require return to be an ANYOF */
14666 FAIL2("panic: regclass returned NULL to handle_sets, "
14667 "flags=%#"UVxf"", (UV) *flagp);
14670 /* regclass() will return with parsing just the \ sequence,
14671 * leaving the parse pointer at the next thing to parse */
14673 goto handle_operand;
14675 case '[': /* Is a bracketed character class */
14677 /* See if this is a [:posix:] class. */
14678 bool is_posix_class = (OOB_NAMEDCLASS
14679 < handle_possible_posix(pRExC_state,
14683 /* If it is a posix class, leave the parse pointer at the '['
14684 * to fool regclass() into thinking it is part of a
14685 * '[[:posix:]]'. */
14686 if (! is_posix_class) {
14690 /* regclass() can only return RESTART_PASS1 and NEED_UTF8 if
14691 * multi-char folds are allowed. */
14692 if (!regclass(pRExC_state, flagp,depth+1,
14693 is_posix_class, /* parse the whole char
14694 class only if not a
14696 FALSE, /* don't allow multi-char folds */
14697 TRUE, /* silence non-portable warnings. */
14699 FALSE, /* Require return to be an ANYOF */
14704 FAIL2("panic: regclass returned NULL to handle_sets, "
14705 "flags=%#"UVxf"", (UV) *flagp);
14708 /* function call leaves parse pointing to the ']', except if we
14710 if (is_posix_class) {
14714 goto handle_operand;
14718 if (top_index >= 1) {
14719 goto join_operators;
14722 /* Only a single operand on the stack: are done */
14726 if (av_tindex(fence_stack) < 0) {
14728 vFAIL("Unexpected ')'");
14731 /* If at least two thing on the stack, treat this as an
14733 if (top_index - fence >= 1) {
14734 goto join_operators;
14737 /* Here only a single thing on the fenced stack, and there is a
14738 * fence. Get rid of it */
14739 fence_ptr = av_pop(fence_stack);
14741 fence = SvIV(fence_ptr) - 1;
14742 SvREFCNT_dec_NN(fence_ptr);
14749 /* Having gotten rid of the fence, we pop the operand at the
14750 * stack top and process it as a newly encountered operand */
14751 current = av_pop(stack);
14752 if (IS_OPERAND(current)) {
14753 goto handle_operand;
14765 /* These binary operators should have a left operand already
14767 if ( top_index - fence < 0
14768 || top_index - fence == 1
14769 || ( ! (top_ptr = av_fetch(stack, top_index, FALSE)))
14770 || ! IS_OPERAND(*top_ptr))
14772 goto unexpected_binary;
14775 /* If only the one operand is on the part of the stack visible
14776 * to us, we just place this operator in the proper position */
14777 if (top_index - fence < 2) {
14779 /* Place the operator before the operand */
14781 SV* lhs = av_pop(stack);
14782 av_push(stack, newSVuv(curchar));
14783 av_push(stack, lhs);
14787 /* But if there is something else on the stack, we need to
14788 * process it before this new operator if and only if the
14789 * stacked operation has equal or higher precedence than the
14794 /* The operator on the stack is supposed to be below both its
14796 if ( ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE))
14797 || IS_OPERAND(*stacked_ptr))
14799 /* But if not, it's legal and indicates we are completely
14800 * done if and only if we're currently processing a ']',
14801 * which should be the final thing in the expression */
14802 if (curchar == ']') {
14808 vFAIL2("Unexpected binary operator '%c' with no "
14809 "preceding operand", curchar);
14811 stacked_operator = (char) SvUV(*stacked_ptr);
14813 if (regex_set_precedence(curchar)
14814 > regex_set_precedence(stacked_operator))
14816 /* Here, the new operator has higher precedence than the
14817 * stacked one. This means we need to add the new one to
14818 * the stack to await its rhs operand (and maybe more
14819 * stuff). We put it before the lhs operand, leaving
14820 * untouched the stacked operator and everything below it
14822 lhs = av_pop(stack);
14823 assert(IS_OPERAND(lhs));
14825 av_push(stack, newSVuv(curchar));
14826 av_push(stack, lhs);
14830 /* Here, the new operator has equal or lower precedence than
14831 * what's already there. This means the operation already
14832 * there should be performed now, before the new one. */
14834 rhs = av_pop(stack);
14835 if (! IS_OPERAND(rhs)) {
14837 /* This can happen when a ! is not followed by an operand,
14838 * like in /(?[\t &!])/ */
14842 lhs = av_pop(stack);
14844 if (! IS_OPERAND(lhs)) {
14846 /* This can happen when there is an empty (), like in
14847 * /(?[[0]+()+])/ */
14851 switch (stacked_operator) {
14853 _invlist_intersection(lhs, rhs, &rhs);
14858 _invlist_union(lhs, rhs, &rhs);
14862 _invlist_subtract(lhs, rhs, &rhs);
14865 case '^': /* The union minus the intersection */
14871 _invlist_union(lhs, rhs, &u);
14872 _invlist_intersection(lhs, rhs, &i);
14873 /* _invlist_subtract will overwrite rhs
14874 without freeing what it already contains */
14876 _invlist_subtract(u, i, &rhs);
14877 SvREFCNT_dec_NN(i);
14878 SvREFCNT_dec_NN(u);
14879 SvREFCNT_dec_NN(element);
14885 /* Here, the higher precedence operation has been done, and the
14886 * result is in 'rhs'. We overwrite the stacked operator with
14887 * the result. Then we redo this code to either push the new
14888 * operator onto the stack or perform any higher precedence
14889 * stacked operation */
14890 only_to_avoid_leaks = av_pop(stack);
14891 SvREFCNT_dec(only_to_avoid_leaks);
14892 av_push(stack, rhs);
14895 case '!': /* Highest priority, right associative */
14897 /* If what's already at the top of the stack is another '!",
14898 * they just cancel each other out */
14899 if ( (top_ptr = av_fetch(stack, top_index, FALSE))
14900 && (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!'))
14902 only_to_avoid_leaks = av_pop(stack);
14903 SvREFCNT_dec(only_to_avoid_leaks);
14905 else { /* Otherwise, since it's right associative, just push
14907 av_push(stack, newSVuv(curchar));
14912 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
14913 vFAIL("Unexpected character");
14917 /* Here 'current' is the operand. If something is already on the
14918 * stack, we have to check if it is a !. */
14919 top_index = av_tindex(stack); /* Code above may have altered the
14920 * stack in the time since we
14921 * earlier set 'top_index'. */
14922 if (top_index - fence >= 0) {
14923 /* If the top entry on the stack is an operator, it had better
14924 * be a '!', otherwise the entry below the top operand should
14925 * be an operator */
14926 top_ptr = av_fetch(stack, top_index, FALSE);
14928 if (IS_OPERATOR(*top_ptr)) {
14930 /* The only permissible operator at the top of the stack is
14931 * '!', which is applied immediately to this operand. */
14932 curchar = (char) SvUV(*top_ptr);
14933 if (curchar != '!') {
14934 SvREFCNT_dec(current);
14935 vFAIL2("Unexpected binary operator '%c' with no "
14936 "preceding operand", curchar);
14939 _invlist_invert(current);
14941 only_to_avoid_leaks = av_pop(stack);
14942 SvREFCNT_dec(only_to_avoid_leaks);
14943 top_index = av_tindex(stack);
14945 /* And we redo with the inverted operand. This allows
14946 * handling multiple ! in a row */
14947 goto handle_operand;
14949 /* Single operand is ok only for the non-binary ')'
14951 else if ((top_index - fence == 0 && curchar != ')')
14952 || (top_index - fence > 0
14953 && (! (stacked_ptr = av_fetch(stack,
14956 || IS_OPERAND(*stacked_ptr))))
14958 SvREFCNT_dec(current);
14959 vFAIL("Operand with no preceding operator");
14963 /* Here there was nothing on the stack or the top element was
14964 * another operand. Just add this new one */
14965 av_push(stack, current);
14967 } /* End of switch on next parse token */
14969 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
14970 } /* End of loop parsing through the construct */
14973 if (av_tindex(fence_stack) >= 0) {
14974 vFAIL("Unmatched (");
14977 if (av_tindex(stack) < 0 /* Was empty */
14978 || ((final = av_pop(stack)) == NULL)
14979 || ! IS_OPERAND(final)
14980 || SvTYPE(final) != SVt_INVLIST
14981 || av_tindex(stack) >= 0) /* More left on stack */
14984 SvREFCNT_dec(final);
14985 vFAIL("Incomplete expression within '(?[ ])'");
14988 /* Here, 'final' is the resultant inversion list from evaluating the
14989 * expression. Return it if so requested */
14990 if (return_invlist) {
14991 *return_invlist = final;
14995 /* Otherwise generate a resultant node, based on 'final'. regclass() is
14996 * expecting a string of ranges and individual code points */
14997 invlist_iterinit(final);
14998 result_string = newSVpvs("");
14999 while (invlist_iternext(final, &start, &end)) {
15000 if (start == end) {
15001 Perl_sv_catpvf(aTHX_ result_string, "\\x{%"UVXf"}", start);
15004 Perl_sv_catpvf(aTHX_ result_string, "\\x{%"UVXf"}-\\x{%"UVXf"}",
15009 /* About to generate an ANYOF (or similar) node from the inversion list we
15010 * have calculated */
15011 save_parse = RExC_parse;
15012 RExC_parse = SvPV(result_string, len);
15013 save_end = RExC_end;
15014 RExC_end = RExC_parse + len;
15016 /* We turn off folding around the call, as the class we have constructed
15017 * already has all folding taken into consideration, and we don't want
15018 * regclass() to add to that */
15019 RExC_flags &= ~RXf_PMf_FOLD;
15020 /* regclass() can only return RESTART_PASS1 and NEED_UTF8 if multi-char
15021 * folds are allowed. */
15022 node = regclass(pRExC_state, flagp,depth+1,
15023 FALSE, /* means parse the whole char class */
15024 FALSE, /* don't allow multi-char folds */
15025 TRUE, /* silence non-portable warnings. The above may very
15026 well have generated non-portable code points, but
15027 they're valid on this machine */
15028 FALSE, /* similarly, no need for strict */
15029 FALSE, /* Require return to be an ANYOF */
15034 FAIL2("panic: regclass returned NULL to handle_sets, flags=%#"UVxf,
15037 /* Fix up the node type if we are in locale. (We have pretended we are
15038 * under /u for the purposes of regclass(), as this construct will only
15039 * work under UTF-8 locales. But now we change the opcode to be ANYOFL (so
15040 * as to cause any warnings about bad locales to be output in regexec.c),
15041 * and add the flag that indicates to check if not in a UTF-8 locale. The
15042 * reason we above forbid optimization into something other than an ANYOF
15043 * node is simply to minimize the number of code changes in regexec.c.
15044 * Otherwise we would have to create new EXACTish node types and deal with
15045 * them. This decision could be revisited should this construct become
15048 * (One might think we could look at the resulting ANYOF node and suppress
15049 * the flag if everything is above 255, as those would be UTF-8 only,
15050 * but this isn't true, as the components that led to that result could
15051 * have been locale-affected, and just happen to cancel each other out
15052 * under UTF-8 locales.) */
15054 set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
15056 assert(OP(node) == ANYOF);
15060 |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
15064 RExC_flags |= RXf_PMf_FOLD;
15067 RExC_parse = save_parse + 1;
15068 RExC_end = save_end;
15069 SvREFCNT_dec_NN(final);
15070 SvREFCNT_dec_NN(result_string);
15072 nextchar(pRExC_state);
15073 Set_Node_Length(node, RExC_parse - oregcomp_parse + 1); /* MJD */
15080 S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist)
15082 /* This hard-codes the Latin1/above-Latin1 folding rules, so that an
15083 * innocent-looking character class, like /[ks]/i won't have to go out to
15084 * disk to find the possible matches.
15086 * This should be called only for a Latin1-range code points, cp, which is
15087 * known to be involved in a simple fold with other code points above
15088 * Latin1. It would give false results if /aa has been specified.
15089 * Multi-char folds are outside the scope of this, and must be handled
15092 * XXX It would be better to generate these via regen, in case a new
15093 * version of the Unicode standard adds new mappings, though that is not
15094 * really likely, and may be caught by the default: case of the switch
15097 PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS;
15099 assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp));
15105 add_cp_to_invlist(*invlist, KELVIN_SIGN);
15109 *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S);
15112 *invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU);
15113 *invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU);
15115 case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
15116 case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
15117 *invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN);
15119 case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
15120 *invlist = add_cp_to_invlist(*invlist,
15121 LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
15124 #ifdef LATIN_CAPITAL_LETTER_SHARP_S /* not defined in early Unicode releases */
15126 case LATIN_SMALL_LETTER_SHARP_S:
15127 *invlist = add_cp_to_invlist(*invlist, LATIN_CAPITAL_LETTER_SHARP_S);
15132 #if UNICODE_MAJOR_VERSION < 3 \
15133 || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0)
15135 /* In 3.0 and earlier, U+0130 folded simply to 'i'; and in 3.0.1 so did
15140 add_cp_to_invlist(*invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
15141 # if UNICODE_DOT_DOT_VERSION == 1
15142 *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_DOTLESS_I);
15148 /* Use deprecated warning to increase the chances of this being
15151 ckWARN2reg_d(RExC_parse, "Perl folding rules are not up-to-date for 0x%02X; please use the perlbug utility to report;", cp);
15158 S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count)
15160 /* This adds the string scalar <multi_string> to the array
15161 * <multi_char_matches>. <multi_string> is known to have exactly
15162 * <cp_count> code points in it. This is used when constructing a
15163 * bracketed character class and we find something that needs to match more
15164 * than a single character.
15166 * <multi_char_matches> is actually an array of arrays. Each top-level
15167 * element is an array that contains all the strings known so far that are
15168 * the same length. And that length (in number of code points) is the same
15169 * as the index of the top-level array. Hence, the [2] element is an
15170 * array, each element thereof is a string containing TWO code points;
15171 * while element [3] is for strings of THREE characters, and so on. Since
15172 * this is for multi-char strings there can never be a [0] nor [1] element.
15174 * When we rewrite the character class below, we will do so such that the
15175 * longest strings are written first, so that it prefers the longest
15176 * matching strings first. This is done even if it turns out that any
15177 * quantifier is non-greedy, out of this programmer's (khw) laziness. Tom
15178 * Christiansen has agreed that this is ok. This makes the test for the
15179 * ligature 'ffi' come before the test for 'ff', for example */
15182 AV** this_array_ptr;
15184 PERL_ARGS_ASSERT_ADD_MULTI_MATCH;
15186 if (! multi_char_matches) {
15187 multi_char_matches = newAV();
15190 if (av_exists(multi_char_matches, cp_count)) {
15191 this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE);
15192 this_array = *this_array_ptr;
15195 this_array = newAV();
15196 av_store(multi_char_matches, cp_count,
15199 av_push(this_array, multi_string);
15201 return multi_char_matches;
15204 /* The names of properties whose definitions are not known at compile time are
15205 * stored in this SV, after a constant heading. So if the length has been
15206 * changed since initialization, then there is a run-time definition. */
15207 #define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION \
15208 (SvCUR(listsv) != initial_listsv_len)
15210 /* There is a restricted set of white space characters that are legal when
15211 * ignoring white space in a bracketed character class. This generates the
15212 * code to skip them.
15214 * There is a line below that uses the same white space criteria but is outside
15215 * this macro. Both here and there must use the same definition */
15216 #define SKIP_BRACKETED_WHITE_SPACE(do_skip, p) \
15219 while (isBLANK_A(UCHARAT(p))) \
15227 S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth,
15228 const bool stop_at_1, /* Just parse the next thing, don't
15229 look for a full character class */
15230 bool allow_multi_folds,
15231 const bool silence_non_portable, /* Don't output warnings
15235 bool optimizable, /* ? Allow a non-ANYOF return
15237 SV** ret_invlist, /* Return an inversion list, not a node */
15238 AV** posix_warnings
15241 /* parse a bracketed class specification. Most of these will produce an
15242 * ANYOF node; but something like [a] will produce an EXACT node; [aA], an
15243 * EXACTFish node; [[:ascii:]], a POSIXA node; etc. It is more complex
15244 * under /i with multi-character folds: it will be rewritten following the
15245 * paradigm of this example, where the <multi-fold>s are characters which
15246 * fold to multiple character sequences:
15247 * /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
15248 * gets effectively rewritten as:
15249 * /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
15250 * reg() gets called (recursively) on the rewritten version, and this
15251 * function will return what it constructs. (Actually the <multi-fold>s
15252 * aren't physically removed from the [abcdefghi], it's just that they are
15253 * ignored in the recursion by means of a flag:
15254 * <RExC_in_multi_char_class>.)
15256 * ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS
15257 * characters, with the corresponding bit set if that character is in the
15258 * list. For characters above this, a range list or swash is used. There
15259 * are extra bits for \w, etc. in locale ANYOFs, as what these match is not
15260 * determinable at compile time
15262 * Returns NULL, setting *flagp to RESTART_PASS1 if the sizing scan needs
15263 * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded
15264 * to UTF-8. This can only happen if ret_invlist is non-NULL.
15267 UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
15269 UV value = OOB_UNICODE, save_value = OOB_UNICODE;
15272 int namedclass = OOB_NAMEDCLASS;
15273 char *rangebegin = NULL;
15274 bool need_class = 0;
15276 STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
15277 than just initialized. */
15278 SV* properties = NULL; /* Code points that match \p{} \P{} */
15279 SV* posixes = NULL; /* Code points that match classes like [:word:],
15280 extended beyond the Latin1 range. These have to
15281 be kept separate from other code points for much
15282 of this function because their handling is
15283 different under /i, and for most classes under
15285 SV* nposixes = NULL; /* Similarly for [:^word:]. These are kept
15286 separate for a while from the non-complemented
15287 versions because of complications with /d
15289 SV* simple_posixes = NULL; /* But under some conditions, the classes can be
15290 treated more simply than the general case,
15291 leading to less compilation and execution
15293 UV element_count = 0; /* Number of distinct elements in the class.
15294 Optimizations may be possible if this is tiny */
15295 AV * multi_char_matches = NULL; /* Code points that fold to more than one
15296 character; used under /i */
15298 char * stop_ptr = RExC_end; /* where to stop parsing */
15299 const bool skip_white = cBOOL(ret_invlist); /* ignore unescaped white
15302 /* Unicode properties are stored in a swash; this holds the current one
15303 * being parsed. If this swash is the only above-latin1 component of the
15304 * character class, an optimization is to pass it directly on to the
15305 * execution engine. Otherwise, it is set to NULL to indicate that there
15306 * are other things in the class that have to be dealt with at execution
15308 SV* swash = NULL; /* Code points that match \p{} \P{} */
15310 /* Set if a component of this character class is user-defined; just passed
15311 * on to the engine */
15312 bool has_user_defined_property = FALSE;
15314 /* inversion list of code points this node matches only when the target
15315 * string is in UTF-8. These are all non-ASCII, < 256. (Because is under
15317 SV* has_upper_latin1_only_utf8_matches = NULL;
15319 /* Inversion list of code points this node matches regardless of things
15320 * like locale, folding, utf8ness of the target string */
15321 SV* cp_list = NULL;
15323 /* Like cp_list, but code points on this list need to be checked for things
15324 * that fold to/from them under /i */
15325 SV* cp_foldable_list = NULL;
15327 /* Like cp_list, but code points on this list are valid only when the
15328 * runtime locale is UTF-8 */
15329 SV* only_utf8_locale_list = NULL;
15331 /* In a range, if one of the endpoints is non-character-set portable,
15332 * meaning that it hard-codes a code point that may mean a different
15333 * charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a
15334 * mnemonic '\t' which each mean the same character no matter which
15335 * character set the platform is on. */
15336 unsigned int non_portable_endpoint = 0;
15338 /* Is the range unicode? which means on a platform that isn't 1-1 native
15339 * to Unicode (i.e. non-ASCII), each code point in it should be considered
15340 * to be a Unicode value. */
15341 bool unicode_range = FALSE;
15342 bool invert = FALSE; /* Is this class to be complemented */
15344 bool warn_super = ALWAYS_WARN_SUPER;
15346 regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
15347 case we need to change the emitted regop to an EXACT. */
15348 const char * orig_parse = RExC_parse;
15349 const SSize_t orig_size = RExC_size;
15350 bool posixl_matches_all = FALSE; /* Does /l class have both e.g. \W,\w ? */
15352 /* This variable is used to mark where in the input something that looks
15353 * like a POSIX construct ends. During the parse, when something looks
15354 * like it could be such a construct is encountered, it is checked for
15355 * being one, but not if we've already checked this area of the input.
15356 * Only after this position is reached do we check again */
15357 char *dont_check_for_posix_end = RExC_parse - 1;
15359 GET_RE_DEBUG_FLAGS_DECL;
15361 PERL_ARGS_ASSERT_REGCLASS;
15363 PERL_UNUSED_ARG(depth);
15366 DEBUG_PARSE("clas");
15368 #if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */ \
15369 || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0 \
15370 && UNICODE_DOT_DOT_VERSION == 0)
15371 allow_multi_folds = FALSE;
15374 if (posix_warnings == NULL) {
15375 posix_warnings = (AV **) -1;
15378 /* Assume we are going to generate an ANYOF node. */
15379 ret = reganode(pRExC_state,
15386 RExC_size += ANYOF_SKIP;
15387 listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
15390 ANYOF_FLAGS(ret) = 0;
15392 RExC_emit += ANYOF_SKIP;
15393 listsv = newSVpvs_flags("# comment\n", SVs_TEMP);
15394 initial_listsv_len = SvCUR(listsv);
15395 SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated. */
15398 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
15400 assert(RExC_parse <= RExC_end);
15402 if (UCHARAT(RExC_parse) == '^') { /* Complement the class */
15405 allow_multi_folds = FALSE;
15407 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
15410 /* Check that they didn't say [:posix:] instead of [[:posix:]] */
15411 if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) {
15413 int maybe_class = handle_possible_posix(pRExC_state, RExC_parse,
15415 if (maybe_class >= OOB_NAMEDCLASS) {
15416 dont_check_for_posix_end = class_end;
15417 if (PASS2 && posix_warnings == (AV **) -1) {
15418 SAVEFREESV(RExC_rx_sv);
15419 ckWARN4reg(class_end,
15420 "POSIX syntax [%c %c] belongs inside character classes%s",
15421 *RExC_parse, *RExC_parse,
15422 (maybe_class == OOB_NAMEDCLASS)
15423 ? ((POSIXCC_NOTYET(*RExC_parse))
15424 ? " (but this one isn't implemented)"
15425 : " (but this one isn't fully valid)")
15428 (void)ReREFCNT_inc(RExC_rx_sv);
15433 /* If the caller wants us to just parse a single element, accomplish this
15434 * by faking the loop ending condition */
15435 if (stop_at_1 && RExC_end > RExC_parse) {
15436 stop_ptr = RExC_parse + 1;
15439 /* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */
15440 if (UCHARAT(RExC_parse) == ']')
15441 goto charclassloop;
15444 if (RExC_parse >= stop_ptr) {
15448 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
15450 if (UCHARAT(RExC_parse) == ']') {
15456 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
15457 save_value = value;
15458 save_prevvalue = prevvalue;
15461 rangebegin = RExC_parse;
15463 non_portable_endpoint = 0;
15465 if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) {
15466 value = utf8n_to_uvchr((U8*)RExC_parse,
15467 RExC_end - RExC_parse,
15468 &numlen, UTF8_ALLOW_DEFAULT);
15469 RExC_parse += numlen;
15472 value = UCHARAT(RExC_parse++);
15474 if (value == '[') {
15475 namedclass = handle_possible_posix(pRExC_state, RExC_parse, &dont_check_for_posix_end, posix_warnings);
15476 if (namedclass > OOB_NAMEDCLASS) {
15477 RExC_parse = dont_check_for_posix_end;
15480 namedclass = OOB_NAMEDCLASS;
15483 else if ( RExC_parse - 1 > dont_check_for_posix_end
15484 && MAYBE_POSIXCC(value))
15486 (void) handle_possible_posix(pRExC_state, RExC_parse - 1, /* -1 because parse has already been advanced */
15487 &dont_check_for_posix_end, posix_warnings);
15489 else if (value == '\\') {
15490 /* Is a backslash; get the code point of the char after it */
15491 if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) {
15492 value = utf8n_to_uvchr((U8*)RExC_parse,
15493 RExC_end - RExC_parse,
15494 &numlen, UTF8_ALLOW_DEFAULT);
15495 RExC_parse += numlen;
15498 value = UCHARAT(RExC_parse++);
15500 /* Some compilers cannot handle switching on 64-bit integer
15501 * values, therefore value cannot be an UV. Yes, this will
15502 * be a problem later if we want switch on Unicode.
15503 * A similar issue a little bit later when switching on
15504 * namedclass. --jhi */
15506 /* If the \ is escaping white space when white space is being
15507 * skipped, it means that that white space is wanted literally, and
15508 * is already in 'value'. Otherwise, need to translate the escape
15509 * into what it signifies. */
15510 if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) {
15512 case 'w': namedclass = ANYOF_WORDCHAR; break;
15513 case 'W': namedclass = ANYOF_NWORDCHAR; break;
15514 case 's': namedclass = ANYOF_SPACE; break;
15515 case 'S': namedclass = ANYOF_NSPACE; break;
15516 case 'd': namedclass = ANYOF_DIGIT; break;
15517 case 'D': namedclass = ANYOF_NDIGIT; break;
15518 case 'v': namedclass = ANYOF_VERTWS; break;
15519 case 'V': namedclass = ANYOF_NVERTWS; break;
15520 case 'h': namedclass = ANYOF_HORIZWS; break;
15521 case 'H': namedclass = ANYOF_NHORIZWS; break;
15522 case 'N': /* Handle \N{NAME} in class */
15524 const char * const backslash_N_beg = RExC_parse - 2;
15527 if (! grok_bslash_N(pRExC_state,
15528 NULL, /* No regnode */
15529 &value, /* Yes single value */
15530 &cp_count, /* Multiple code pt count */
15535 if (*flagp & NEED_UTF8)
15536 FAIL("panic: grok_bslash_N set NEED_UTF8");
15537 if (*flagp & RESTART_PASS1)
15540 if (cp_count < 0) {
15541 vFAIL("\\N in a character class must be a named character: \\N{...}");
15543 else if (cp_count == 0) {
15545 RExC_parse++; /* Position after the "}" */
15546 vFAIL("Zero length \\N{}");
15549 ckWARNreg(RExC_parse,
15550 "Ignoring zero length \\N{} in character class");
15553 else { /* cp_count > 1 */
15554 if (! RExC_in_multi_char_class) {
15555 if (invert || range || *RExC_parse == '-') {
15558 vFAIL("\\N{} in inverted character class or as a range end-point is restricted to one character");
15561 ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class");
15563 break; /* <value> contains the first code
15564 point. Drop out of the switch to
15568 SV * multi_char_N = newSVpvn(backslash_N_beg,
15569 RExC_parse - backslash_N_beg);
15571 = add_multi_match(multi_char_matches,
15576 } /* End of cp_count != 1 */
15578 /* This element should not be processed further in this
15581 value = save_value;
15582 prevvalue = save_prevvalue;
15583 continue; /* Back to top of loop to get next char */
15586 /* Here, is a single code point, and <value> contains it */
15587 unicode_range = TRUE; /* \N{} are Unicode */
15595 /* We will handle any undefined properties ourselves */
15596 U8 swash_init_flags = _CORE_SWASH_INIT_RETURN_IF_UNDEF
15597 /* And we actually would prefer to get
15598 * the straight inversion list of the
15599 * swash, since we will be accessing it
15600 * anyway, to save a little time */
15601 |_CORE_SWASH_INIT_ACCEPT_INVLIST;
15603 if (RExC_parse >= RExC_end)
15604 vFAIL2("Empty \\%c", (U8)value);
15605 if (*RExC_parse == '{') {
15606 const U8 c = (U8)value;
15607 e = strchr(RExC_parse, '}');
15610 vFAIL2("Missing right brace on \\%c{}", c);
15614 while (isSPACE(*RExC_parse)) {
15618 if (UCHARAT(RExC_parse) == '^') {
15620 /* toggle. (The rhs xor gets the single bit that
15621 * differs between P and p; the other xor inverts just
15623 value ^= 'P' ^ 'p';
15626 while (isSPACE(*RExC_parse)) {
15631 if (e == RExC_parse)
15632 vFAIL2("Empty \\%c{}", c);
15634 n = e - RExC_parse;
15635 while (isSPACE(*(RExC_parse + n - 1)))
15637 } /* The \p isn't immediately followed by a '{' */
15638 else if (! isALPHA(*RExC_parse)) {
15639 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
15640 vFAIL2("Character following \\%c must be '{' or a "
15641 "single-character Unicode property name",
15651 char* base_name; /* name after any packages are stripped */
15652 const char * const colon_colon = "::";
15654 /* Try to get the definition of the property into
15655 * <invlist>. If /i is in effect, the effective property
15656 * will have its name be <__NAME_i>. The design is
15657 * discussed in commit
15658 * 2f833f5208e26b208886e51e09e2c072b5eabb46 */
15659 name = savepv(Perl_form(aTHX_
15661 (FOLD) ? "__" : "",
15667 /* Look up the property name, and get its swash and
15668 * inversion list, if the property is found */
15669 if (swash) { /* Return any left-overs */
15670 SvREFCNT_dec_NN(swash);
15672 swash = _core_swash_init("utf8", name, &PL_sv_undef,
15675 NULL, /* No inversion list */
15678 if (! swash || ! (invlist = _get_swash_invlist(swash))) {
15679 HV* curpkg = (IN_PERL_COMPILETIME)
15681 : CopSTASH(PL_curcop);
15685 if (swash) { /* Got a swash but no inversion list.
15686 Something is likely wrong that will
15687 be sorted-out later */
15688 SvREFCNT_dec_NN(swash);
15692 /* Here didn't find it. It could be a an error (like a
15693 * typo) in specifying a Unicode property, or it could
15694 * be a user-defined property that will be available at
15695 * run-time. The names of these must begin with 'In'
15696 * or 'Is' (after any packages are stripped off). So
15697 * if not one of those, or if we accept only
15698 * compile-time properties, is an error; otherwise add
15699 * it to the list for run-time look up. */
15700 if ((base_name = rninstr(name, name + n,
15701 colon_colon, colon_colon + 2)))
15702 { /* Has ::. We know this must be a user-defined
15705 final_n -= base_name - name;
15714 || base_name[0] != 'I'
15715 || (base_name[1] != 's' && base_name[1] != 'n')
15718 const char * const msg
15720 ? "Illegal user-defined property name"
15721 : "Can't find Unicode property definition";
15722 RExC_parse = e + 1;
15724 /* diag_listed_as: Can't find Unicode property definition "%s" */
15725 vFAIL3utf8f("%s \"%"UTF8f"\"",
15726 msg, UTF8fARG(UTF, n, name));
15729 /* If the property name doesn't already have a package
15730 * name, add the current one to it so that it can be
15731 * referred to outside it. [perl #121777] */
15732 if (! has_pkg && curpkg) {
15733 char* pkgname = HvNAME(curpkg);
15734 if (strNE(pkgname, "main")) {
15735 char* full_name = Perl_form(aTHX_
15739 n = strlen(full_name);
15741 name = savepvn(full_name, n);
15744 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%"UTF8f"\n",
15745 (value == 'p' ? '+' : '!'),
15746 UTF8fARG(UTF, n, name));
15747 has_user_defined_property = TRUE;
15748 optimizable = FALSE; /* Will have to leave this an
15751 /* We don't know yet what this matches, so have to flag
15753 ANYOF_FLAGS(ret) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
15757 /* Here, did get the swash and its inversion list. If
15758 * the swash is from a user-defined property, then this
15759 * whole character class should be regarded as such */
15760 if (swash_init_flags
15761 & _CORE_SWASH_INIT_USER_DEFINED_PROPERTY)
15763 has_user_defined_property = TRUE;
15766 /* We warn on matching an above-Unicode code point
15767 * if the match would return true, except don't
15768 * warn for \p{All}, which has exactly one element
15770 (_invlist_contains_cp(invlist, 0x110000)
15771 && (! (_invlist_len(invlist) == 1
15772 && *invlist_array(invlist) == 0)))
15778 /* Invert if asking for the complement */
15779 if (value == 'P') {
15780 _invlist_union_complement_2nd(properties,
15784 /* The swash can't be used as-is, because we've
15785 * inverted things; delay removing it to here after
15786 * have copied its invlist above */
15787 SvREFCNT_dec_NN(swash);
15791 _invlist_union(properties, invlist, &properties);
15796 RExC_parse = e + 1;
15797 namedclass = ANYOF_UNIPROP; /* no official name, but it's
15800 /* \p means they want Unicode semantics */
15801 REQUIRE_UNI_RULES(flagp, NULL);
15804 case 'n': value = '\n'; break;
15805 case 'r': value = '\r'; break;
15806 case 't': value = '\t'; break;
15807 case 'f': value = '\f'; break;
15808 case 'b': value = '\b'; break;
15809 case 'e': value = ESC_NATIVE; break;
15810 case 'a': value = '\a'; break;
15812 RExC_parse--; /* function expects to be pointed at the 'o' */
15814 const char* error_msg;
15815 bool valid = grok_bslash_o(&RExC_parse,
15818 PASS2, /* warnings only in
15821 silence_non_portable,
15827 non_portable_endpoint++;
15828 if (IN_ENCODING && value < 0x100) {
15829 goto recode_encoding;
15833 RExC_parse--; /* function expects to be pointed at the 'x' */
15835 const char* error_msg;
15836 bool valid = grok_bslash_x(&RExC_parse,
15839 PASS2, /* Output warnings */
15841 silence_non_portable,
15847 non_portable_endpoint++;
15848 if (IN_ENCODING && value < 0x100)
15849 goto recode_encoding;
15852 value = grok_bslash_c(*RExC_parse++, PASS2);
15853 non_portable_endpoint++;
15855 case '0': case '1': case '2': case '3': case '4':
15856 case '5': case '6': case '7':
15858 /* Take 1-3 octal digits */
15859 I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
15860 numlen = (strict) ? 4 : 3;
15861 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
15862 RExC_parse += numlen;
15865 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
15866 vFAIL("Need exactly 3 octal digits");
15868 else if (! SIZE_ONLY /* like \08, \178 */
15870 && RExC_parse < RExC_end
15871 && isDIGIT(*RExC_parse)
15872 && ckWARN(WARN_REGEXP))
15874 SAVEFREESV(RExC_rx_sv);
15875 reg_warn_non_literal_string(
15877 form_short_octal_warning(RExC_parse, numlen));
15878 (void)ReREFCNT_inc(RExC_rx_sv);
15881 non_portable_endpoint++;
15882 if (IN_ENCODING && value < 0x100)
15883 goto recode_encoding;
15887 if (! RExC_override_recoding) {
15888 SV* enc = _get_encoding();
15889 value = reg_recode((U8)value, &enc);
15892 vFAIL("Invalid escape in the specified encoding");
15895 ckWARNreg(RExC_parse,
15896 "Invalid escape in the specified encoding");
15902 /* Allow \_ to not give an error */
15903 if (!SIZE_ONLY && isWORDCHAR(value) && value != '_') {
15905 vFAIL2("Unrecognized escape \\%c in character class",
15909 SAVEFREESV(RExC_rx_sv);
15910 ckWARN2reg(RExC_parse,
15911 "Unrecognized escape \\%c in character class passed through",
15913 (void)ReREFCNT_inc(RExC_rx_sv);
15917 } /* End of switch on char following backslash */
15918 } /* end of handling backslash escape sequences */
15920 /* Here, we have the current token in 'value' */
15922 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
15925 /* a bad range like a-\d, a-[:digit:]. The '-' is taken as a
15926 * literal, as is the character that began the false range, i.e.
15927 * the 'a' in the examples */
15930 const int w = (RExC_parse >= rangebegin)
15931 ? RExC_parse - rangebegin
15935 "False [] range \"%"UTF8f"\"",
15936 UTF8fARG(UTF, w, rangebegin));
15939 SAVEFREESV(RExC_rx_sv); /* in case of fatal warnings */
15940 ckWARN2reg(RExC_parse,
15941 "False [] range \"%"UTF8f"\"",
15942 UTF8fARG(UTF, w, rangebegin));
15943 (void)ReREFCNT_inc(RExC_rx_sv);
15944 cp_list = add_cp_to_invlist(cp_list, '-');
15945 cp_foldable_list = add_cp_to_invlist(cp_foldable_list,
15950 range = 0; /* this was not a true range */
15951 element_count += 2; /* So counts for three values */
15954 classnum = namedclass_to_classnum(namedclass);
15956 if (LOC && namedclass < ANYOF_POSIXL_MAX
15957 #ifndef HAS_ISASCII
15958 && classnum != _CC_ASCII
15961 /* What the Posix classes (like \w, [:space:]) match in locale
15962 * isn't knowable under locale until actual match time. Room
15963 * must be reserved (one time per outer bracketed class) to
15964 * store such classes. The space will contain a bit for each
15965 * named class that is to be matched against. This isn't
15966 * needed for \p{} and pseudo-classes, as they are not affected
15967 * by locale, and hence are dealt with separately */
15968 if (! need_class) {
15971 RExC_size += ANYOF_POSIXL_SKIP - ANYOF_SKIP;
15974 RExC_emit += ANYOF_POSIXL_SKIP - ANYOF_SKIP;
15976 ANYOF_FLAGS(ret) |= ANYOF_MATCHES_POSIXL;
15977 ANYOF_POSIXL_ZERO(ret);
15979 /* We can't change this into some other type of node
15980 * (unless this is the only element, in which case there
15981 * are nodes that mean exactly this) as has runtime
15983 optimizable = FALSE;
15986 /* Coverity thinks it is possible for this to be negative; both
15987 * jhi and khw think it's not, but be safer */
15988 assert(! (ANYOF_FLAGS(ret) & ANYOF_MATCHES_POSIXL)
15989 || (namedclass + ((namedclass % 2) ? -1 : 1)) >= 0);
15991 /* See if it already matches the complement of this POSIX
15993 if ((ANYOF_FLAGS(ret) & ANYOF_MATCHES_POSIXL)
15994 && ANYOF_POSIXL_TEST(ret, namedclass + ((namedclass % 2)
15998 posixl_matches_all = TRUE;
15999 break; /* No need to continue. Since it matches both
16000 e.g., \w and \W, it matches everything, and the
16001 bracketed class can be optimized into qr/./s */
16004 /* Add this class to those that should be checked at runtime */
16005 ANYOF_POSIXL_SET(ret, namedclass);
16007 /* The above-Latin1 characters are not subject to locale rules.
16008 * Just add them, in the second pass, to the
16009 * unconditionally-matched list */
16011 SV* scratch_list = NULL;
16013 /* Get the list of the above-Latin1 code points this
16015 _invlist_intersection_maybe_complement_2nd(PL_AboveLatin1,
16016 PL_XPosix_ptrs[classnum],
16018 /* Odd numbers are complements, like
16019 * NDIGIT, NASCII, ... */
16020 namedclass % 2 != 0,
16022 /* Checking if 'cp_list' is NULL first saves an extra
16023 * clone. Its reference count will be decremented at the
16024 * next union, etc, or if this is the only instance, at the
16025 * end of the routine */
16027 cp_list = scratch_list;
16030 _invlist_union(cp_list, scratch_list, &cp_list);
16031 SvREFCNT_dec_NN(scratch_list);
16033 continue; /* Go get next character */
16036 else if (! SIZE_ONLY) {
16038 /* Here, not in pass1 (in that pass we skip calculating the
16039 * contents of this class), and is /l, or is a POSIX class for
16040 * which /l doesn't matter (or is a Unicode property, which is
16041 * skipped here). */
16042 if (namedclass >= ANYOF_POSIXL_MAX) { /* If a special class */
16043 if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */
16045 /* Here, should be \h, \H, \v, or \V. None of /d, /i
16046 * nor /l make a difference in what these match,
16047 * therefore we just add what they match to cp_list. */
16048 if (classnum != _CC_VERTSPACE) {
16049 assert( namedclass == ANYOF_HORIZWS
16050 || namedclass == ANYOF_NHORIZWS);
16052 /* It turns out that \h is just a synonym for
16054 classnum = _CC_BLANK;
16057 _invlist_union_maybe_complement_2nd(
16059 PL_XPosix_ptrs[classnum],
16060 namedclass % 2 != 0, /* Complement if odd
16061 (NHORIZWS, NVERTWS)
16066 else if (UNI_SEMANTICS
16067 || classnum == _CC_ASCII
16068 || (DEPENDS_SEMANTICS && (classnum == _CC_DIGIT
16069 || classnum == _CC_XDIGIT)))
16071 /* We usually have to worry about /d and /a affecting what
16072 * POSIX classes match, with special code needed for /d
16073 * because we won't know until runtime what all matches.
16074 * But there is no extra work needed under /u, and
16075 * [:ascii:] is unaffected by /a and /d; and :digit: and
16076 * :xdigit: don't have runtime differences under /d. So we
16077 * can special case these, and avoid some extra work below,
16078 * and at runtime. */
16079 _invlist_union_maybe_complement_2nd(
16081 PL_XPosix_ptrs[classnum],
16082 namedclass % 2 != 0,
16085 else { /* Garden variety class. If is NUPPER, NALPHA, ...
16086 complement and use nposixes */
16087 SV** posixes_ptr = namedclass % 2 == 0
16090 _invlist_union_maybe_complement_2nd(
16092 PL_XPosix_ptrs[classnum],
16093 namedclass % 2 != 0,
16097 } /* end of namedclass \blah */
16099 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
16101 /* If 'range' is set, 'value' is the ending of a range--check its
16102 * validity. (If value isn't a single code point in the case of a
16103 * range, we should have figured that out above in the code that
16104 * catches false ranges). Later, we will handle each individual code
16105 * point in the range. If 'range' isn't set, this could be the
16106 * beginning of a range, so check for that by looking ahead to see if
16107 * the next real character to be processed is the range indicator--the
16112 /* For unicode ranges, we have to test that the Unicode as opposed
16113 * to the native values are not decreasing. (Above 255, there is
16114 * no difference between native and Unicode) */
16115 if (unicode_range && prevvalue < 255 && value < 255) {
16116 if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) {
16117 goto backwards_range;
16122 if (prevvalue > value) /* b-a */ {
16127 w = RExC_parse - rangebegin;
16129 "Invalid [] range \"%"UTF8f"\"",
16130 UTF8fARG(UTF, w, rangebegin));
16131 NOT_REACHED; /* NOTREACHED */
16135 prevvalue = value; /* save the beginning of the potential range */
16136 if (! stop_at_1 /* Can't be a range if parsing just one thing */
16137 && *RExC_parse == '-')
16139 char* next_char_ptr = RExC_parse + 1;
16141 /* Get the next real char after the '-' */
16142 SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr);
16144 /* If the '-' is at the end of the class (just before the ']',
16145 * it is a literal minus; otherwise it is a range */
16146 if (next_char_ptr < RExC_end && *next_char_ptr != ']') {
16147 RExC_parse = next_char_ptr;
16149 /* a bad range like \w-, [:word:]- ? */
16150 if (namedclass > OOB_NAMEDCLASS) {
16151 if (strict || (PASS2 && ckWARN(WARN_REGEXP))) {
16152 const int w = RExC_parse >= rangebegin
16153 ? RExC_parse - rangebegin
16156 vFAIL4("False [] range \"%*.*s\"",
16161 "False [] range \"%*.*s\"",
16166 cp_list = add_cp_to_invlist(cp_list, '-');
16170 range = 1; /* yeah, it's a range! */
16171 continue; /* but do it the next time */
16176 if (namedclass > OOB_NAMEDCLASS) {
16180 /* Here, we have a single value this time through the loop, and
16181 * <prevvalue> is the beginning of the range, if any; or <value> if
16184 /* non-Latin1 code point implies unicode semantics. Must be set in
16185 * pass1 so is there for the whole of pass 2 */
16187 REQUIRE_UNI_RULES(flagp, NULL);
16190 /* Ready to process either the single value, or the completed range.
16191 * For single-valued non-inverted ranges, we consider the possibility
16192 * of multi-char folds. (We made a conscious decision to not do this
16193 * for the other cases because it can often lead to non-intuitive
16194 * results. For example, you have the peculiar case that:
16195 * "s s" =~ /^[^\xDF]+$/i => Y
16196 * "ss" =~ /^[^\xDF]+$/i => N
16198 * See [perl #89750] */
16199 if (FOLD && allow_multi_folds && value == prevvalue) {
16200 if (value == LATIN_SMALL_LETTER_SHARP_S
16201 || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
16204 /* Here <value> is indeed a multi-char fold. Get what it is */
16206 U8 foldbuf[UTF8_MAXBYTES_CASE];
16209 UV folded = _to_uni_fold_flags(
16213 FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED
16214 ? FOLD_FLAGS_NOMIX_ASCII
16218 /* Here, <folded> should be the first character of the
16219 * multi-char fold of <value>, with <foldbuf> containing the
16220 * whole thing. But, if this fold is not allowed (because of
16221 * the flags), <fold> will be the same as <value>, and should
16222 * be processed like any other character, so skip the special
16224 if (folded != value) {
16226 /* Skip if we are recursed, currently parsing the class
16227 * again. Otherwise add this character to the list of
16228 * multi-char folds. */
16229 if (! RExC_in_multi_char_class) {
16230 STRLEN cp_count = utf8_length(foldbuf,
16231 foldbuf + foldlen);
16232 SV* multi_fold = sv_2mortal(newSVpvs(""));
16234 Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%"UVXf"}", value);
16237 = add_multi_match(multi_char_matches,
16243 /* This element should not be processed further in this
16246 value = save_value;
16247 prevvalue = save_prevvalue;
16253 if (strict && PASS2 && ckWARN(WARN_REGEXP)) {
16256 /* If the range starts above 255, everything is portable and
16257 * likely to be so for any forseeable character set, so don't
16259 if (unicode_range && non_portable_endpoint && prevvalue < 256) {
16260 vWARN(RExC_parse, "Both or neither range ends should be Unicode");
16262 else if (prevvalue != value) {
16264 /* Under strict, ranges that stop and/or end in an ASCII
16265 * printable should have each end point be a portable value
16266 * for it (preferably like 'A', but we don't warn if it is
16267 * a (portable) Unicode name or code point), and the range
16268 * must be be all digits or all letters of the same case.
16269 * Otherwise, the range is non-portable and unclear as to
16270 * what it contains */
16271 if ((isPRINT_A(prevvalue) || isPRINT_A(value))
16272 && (non_portable_endpoint
16273 || ! ((isDIGIT_A(prevvalue) && isDIGIT_A(value))
16274 || (isLOWER_A(prevvalue) && isLOWER_A(value))
16275 || (isUPPER_A(prevvalue) && isUPPER_A(value)))))
16277 vWARN(RExC_parse, "Ranges of ASCII printables should be some subset of \"0-9\", \"A-Z\", or \"a-z\"");
16279 else if (prevvalue >= 0x660) { /* ARABIC_INDIC_DIGIT_ZERO */
16281 /* But the nature of Unicode and languages mean we
16282 * can't do the same checks for above-ASCII ranges,
16283 * except in the case of digit ones. These should
16284 * contain only digits from the same group of 10. The
16285 * ASCII case is handled just above. 0x660 is the
16286 * first digit character beyond ASCII. Hence here, the
16287 * range could be a range of digits. Find out. */
16288 IV index_start = _invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
16290 IV index_final = _invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
16293 /* If the range start and final points are in the same
16294 * inversion list element, it means that either both
16295 * are not digits, or both are digits in a consecutive
16296 * sequence of digits. (So far, Unicode has kept all
16297 * such sequences as distinct groups of 10, but assert
16298 * to make sure). If the end points are not in the
16299 * same element, neither should be a digit. */
16300 if (index_start == index_final) {
16301 assert(! ELEMENT_RANGE_MATCHES_INVLIST(index_start)
16302 || (invlist_array(PL_XPosix_ptrs[_CC_DIGIT])[index_start+1]
16303 - invlist_array(PL_XPosix_ptrs[_CC_DIGIT])[index_start]
16305 /* But actually Unicode did have one group of 11
16306 * 'digits' in 5.2, so in case we are operating
16307 * on that version, let that pass */
16308 || (invlist_array(PL_XPosix_ptrs[_CC_DIGIT])[index_start+1]
16309 - invlist_array(PL_XPosix_ptrs[_CC_DIGIT])[index_start]
16311 && invlist_array(PL_XPosix_ptrs[_CC_DIGIT])[index_start]
16315 else if ((index_start >= 0
16316 && ELEMENT_RANGE_MATCHES_INVLIST(index_start))
16317 || (index_final >= 0
16318 && ELEMENT_RANGE_MATCHES_INVLIST(index_final)))
16320 vWARN(RExC_parse, "Ranges of digits should be from the same group of 10");
16325 if ((! range || prevvalue == value) && non_portable_endpoint) {
16326 if (isPRINT_A(value)) {
16329 if (isBACKSLASHED_PUNCT(value)) {
16330 literal[d++] = '\\';
16332 literal[d++] = (char) value;
16333 literal[d++] = '\0';
16336 "\"%.*s\" is more clearly written simply as \"%s\"",
16337 (int) (RExC_parse - rangebegin),
16342 else if isMNEMONIC_CNTRL(value) {
16344 "\"%.*s\" is more clearly written simply as \"%s\"",
16345 (int) (RExC_parse - rangebegin),
16347 cntrl_to_mnemonic((char) value)
16353 /* Deal with this element of the class */
16357 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
16360 /* On non-ASCII platforms, for ranges that span all of 0..255, and
16361 * ones that don't require special handling, we can just add the
16362 * range like we do for ASCII platforms */
16363 if ((UNLIKELY(prevvalue == 0) && value >= 255)
16364 || ! (prevvalue < 256
16366 || (! non_portable_endpoint
16367 && ((isLOWER_A(prevvalue) && isLOWER_A(value))
16368 || (isUPPER_A(prevvalue)
16369 && isUPPER_A(value)))))))
16371 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
16375 /* Here, requires special handling. This can be because it is
16376 * a range whose code points are considered to be Unicode, and
16377 * so must be individually translated into native, or because
16378 * its a subrange of 'A-Z' or 'a-z' which each aren't
16379 * contiguous in EBCDIC, but we have defined them to include
16380 * only the "expected" upper or lower case ASCII alphabetics.
16381 * Subranges above 255 are the same in native and Unicode, so
16382 * can be added as a range */
16383 U8 start = NATIVE_TO_LATIN1(prevvalue);
16385 U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255;
16386 for (j = start; j <= end; j++) {
16387 cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j));
16390 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
16397 range = 0; /* this range (if it was one) is done now */
16398 } /* End of loop through all the text within the brackets */
16400 /* If anything in the class expands to more than one character, we have to
16401 * deal with them by building up a substitute parse string, and recursively
16402 * calling reg() on it, instead of proceeding */
16403 if (multi_char_matches) {
16404 SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
16407 char *save_end = RExC_end;
16408 char *save_parse = RExC_parse;
16409 char *save_start = RExC_start;
16410 STRLEN prefix_end = 0; /* We copy the character class after a
16411 prefix supplied here. This is the size
16412 + 1 of that prefix */
16413 bool first_time = TRUE; /* First multi-char occurrence doesn't get
16418 assert(RExC_precomp_adj == 0); /* Only one level of recursion allowed */
16420 #if 0 /* Have decided not to deal with multi-char folds in inverted classes,
16421 because too confusing */
16423 sv_catpv(substitute_parse, "(?:");
16427 /* Look at the longest folds first */
16428 for (cp_count = av_tindex(multi_char_matches); cp_count > 0; cp_count--) {
16430 if (av_exists(multi_char_matches, cp_count)) {
16431 AV** this_array_ptr;
16434 this_array_ptr = (AV**) av_fetch(multi_char_matches,
16436 while ((this_sequence = av_pop(*this_array_ptr)) !=
16439 if (! first_time) {
16440 sv_catpv(substitute_parse, "|");
16442 first_time = FALSE;
16444 sv_catpv(substitute_parse, SvPVX(this_sequence));
16449 /* If the character class contains anything else besides these
16450 * multi-character folds, have to include it in recursive parsing */
16451 if (element_count) {
16452 sv_catpv(substitute_parse, "|[");
16453 prefix_end = SvCUR(substitute_parse);
16454 sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
16456 /* Put in a closing ']' only if not going off the end, as otherwise
16457 * we are adding something that really isn't there */
16458 if (RExC_parse < RExC_end) {
16459 sv_catpv(substitute_parse, "]");
16463 sv_catpv(substitute_parse, ")");
16466 /* This is a way to get the parse to skip forward a whole named
16467 * sequence instead of matching the 2nd character when it fails the
16469 sv_catpv(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
16473 /* Set up the data structure so that any errors will be properly
16474 * reported. See the comments at the definition of
16475 * REPORT_LOCATION_ARGS for details */
16476 RExC_precomp_adj = orig_parse - RExC_precomp;
16477 RExC_start = RExC_parse = SvPV(substitute_parse, len);
16478 RExC_adjusted_start = RExC_start + prefix_end;
16479 RExC_end = RExC_parse + len;
16480 RExC_in_multi_char_class = 1;
16481 RExC_override_recoding = 1;
16482 RExC_emit = (regnode *)orig_emit;
16484 ret = reg(pRExC_state, 1, ®_flags, depth+1);
16486 *flagp |= reg_flags&(HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PASS1|NEED_UTF8);
16488 /* And restore so can parse the rest of the pattern */
16489 RExC_parse = save_parse;
16490 RExC_start = RExC_adjusted_start = save_start;
16491 RExC_precomp_adj = 0;
16492 RExC_end = save_end;
16493 RExC_in_multi_char_class = 0;
16494 RExC_override_recoding = 0;
16495 SvREFCNT_dec_NN(multi_char_matches);
16499 /* Here, we've gone through the entire class and dealt with multi-char
16500 * folds. We are now in a position that we can do some checks to see if we
16501 * can optimize this ANYOF node into a simpler one, even in Pass 1.
16502 * Currently we only do two checks:
16503 * 1) is in the unlikely event that the user has specified both, eg. \w and
16504 * \W under /l, then the class matches everything. (This optimization
16505 * is done only to make the optimizer code run later work.)
16506 * 2) if the character class contains only a single element (including a
16507 * single range), we see if there is an equivalent node for it.
16508 * Other checks are possible */
16510 && ! ret_invlist /* Can't optimize if returning the constructed
16512 && (UNLIKELY(posixl_matches_all) || element_count == 1))
16517 if (UNLIKELY(posixl_matches_all)) {
16520 else if (namedclass > OOB_NAMEDCLASS) { /* this is a single named
16521 class, like \w or [:digit:]
16524 /* All named classes are mapped into POSIXish nodes, with its FLAG
16525 * argument giving which class it is */
16526 switch ((I32)namedclass) {
16527 case ANYOF_UNIPROP:
16530 /* These don't depend on the charset modifiers. They always
16531 * match under /u rules */
16532 case ANYOF_NHORIZWS:
16533 case ANYOF_HORIZWS:
16534 namedclass = ANYOF_BLANK + namedclass - ANYOF_HORIZWS;
16537 case ANYOF_NVERTWS:
16542 /* The actual POSIXish node for all the rest depends on the
16543 * charset modifier. The ones in the first set depend only on
16544 * ASCII or, if available on this platform, also locale */
16548 op = (LOC) ? POSIXL : POSIXA;
16554 /* The following don't have any matches in the upper Latin1
16555 * range, hence /d is equivalent to /u for them. Making it /u
16556 * saves some branches at runtime */
16560 case ANYOF_NXDIGIT:
16561 if (! DEPENDS_SEMANTICS) {
16562 goto treat_as_default;
16568 /* The following change to CASED under /i */
16574 namedclass = ANYOF_CASED + (namedclass % 2);
16578 /* The rest have more possibilities depending on the charset.
16579 * We take advantage of the enum ordering of the charset
16580 * modifiers to get the exact node type, */
16583 op = POSIXD + get_regex_charset(RExC_flags);
16584 if (op > POSIXA) { /* /aa is same as /a */
16589 /* The odd numbered ones are the complements of the
16590 * next-lower even number one */
16591 if (namedclass % 2 == 1) {
16595 arg = namedclass_to_classnum(namedclass);
16599 else if (value == prevvalue) {
16601 /* Here, the class consists of just a single code point */
16604 if (! LOC && value == '\n') {
16605 op = REG_ANY; /* Optimize [^\n] */
16606 *flagp |= HASWIDTH|SIMPLE;
16610 else if (value < 256 || UTF) {
16612 /* Optimize a single value into an EXACTish node, but not if it
16613 * would require converting the pattern to UTF-8. */
16614 op = compute_EXACTish(pRExC_state);
16616 } /* Otherwise is a range */
16617 else if (! LOC) { /* locale could vary these */
16618 if (prevvalue == '0') {
16619 if (value == '9') {
16624 else if (! FOLD || ASCII_FOLD_RESTRICTED) {
16625 /* We can optimize A-Z or a-z, but not if they could match
16626 * something like the KELVIN SIGN under /i. */
16627 if (prevvalue == 'A') {
16630 && ! non_portable_endpoint
16633 arg = (FOLD) ? _CC_ALPHA : _CC_UPPER;
16637 else if (prevvalue == 'a') {
16640 && ! non_portable_endpoint
16643 arg = (FOLD) ? _CC_ALPHA : _CC_LOWER;
16650 /* Here, we have changed <op> away from its initial value iff we found
16651 * an optimization */
16654 /* Throw away this ANYOF regnode, and emit the calculated one,
16655 * which should correspond to the beginning, not current, state of
16657 const char * cur_parse = RExC_parse;
16658 RExC_parse = (char *)orig_parse;
16662 /* To get locale nodes to not use the full ANYOF size would
16663 * require moving the code above that writes the portions
16664 * of it that aren't in other nodes to after this point.
16665 * e.g. ANYOF_POSIXL_SET */
16666 RExC_size = orig_size;
16670 RExC_emit = (regnode *)orig_emit;
16671 if (PL_regkind[op] == POSIXD) {
16672 if (op == POSIXL) {
16673 RExC_contains_locale = 1;
16676 op += NPOSIXD - POSIXD;
16681 ret = reg_node(pRExC_state, op);
16683 if (PL_regkind[op] == POSIXD || PL_regkind[op] == NPOSIXD) {
16687 *flagp |= HASWIDTH|SIMPLE;
16689 else if (PL_regkind[op] == EXACT) {
16690 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, 0, value,
16691 TRUE /* downgradable to EXACT */
16695 RExC_parse = (char *) cur_parse;
16697 SvREFCNT_dec(posixes);
16698 SvREFCNT_dec(nposixes);
16699 SvREFCNT_dec(simple_posixes);
16700 SvREFCNT_dec(cp_list);
16701 SvREFCNT_dec(cp_foldable_list);
16708 /****** !SIZE_ONLY (Pass 2) AFTER HERE *********/
16710 /* If folding, we calculate all characters that could fold to or from the
16711 * ones already on the list */
16712 if (cp_foldable_list) {
16714 UV start, end; /* End points of code point ranges */
16716 SV* fold_intersection = NULL;
16719 /* Our calculated list will be for Unicode rules. For locale
16720 * matching, we have to keep a separate list that is consulted at
16721 * runtime only when the locale indicates Unicode rules. For
16722 * non-locale, we just use the general list */
16724 use_list = &only_utf8_locale_list;
16727 use_list = &cp_list;
16730 /* Only the characters in this class that participate in folds need
16731 * be checked. Get the intersection of this class and all the
16732 * possible characters that are foldable. This can quickly narrow
16733 * down a large class */
16734 _invlist_intersection(PL_utf8_foldable, cp_foldable_list,
16735 &fold_intersection);
16737 /* The folds for all the Latin1 characters are hard-coded into this
16738 * program, but we have to go out to disk to get the others. */
16739 if (invlist_highest(cp_foldable_list) >= 256) {
16741 /* This is a hash that for a particular fold gives all
16742 * characters that are involved in it */
16743 if (! PL_utf8_foldclosures) {
16744 _load_PL_utf8_foldclosures();
16748 /* Now look at the foldable characters in this class individually */
16749 invlist_iterinit(fold_intersection);
16750 while (invlist_iternext(fold_intersection, &start, &end)) {
16753 /* Look at every character in the range */
16754 for (j = start; j <= end; j++) {
16755 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
16761 if (IS_IN_SOME_FOLD_L1(j)) {
16763 /* ASCII is always matched; non-ASCII is matched
16764 * only under Unicode rules (which could happen
16765 * under /l if the locale is a UTF-8 one */
16766 if (isASCII(j) || ! DEPENDS_SEMANTICS) {
16767 *use_list = add_cp_to_invlist(*use_list,
16768 PL_fold_latin1[j]);
16771 has_upper_latin1_only_utf8_matches
16772 = add_cp_to_invlist(
16773 has_upper_latin1_only_utf8_matches,
16774 PL_fold_latin1[j]);
16778 if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j)
16779 && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
16781 add_above_Latin1_folds(pRExC_state,
16788 /* Here is an above Latin1 character. We don't have the
16789 * rules hard-coded for it. First, get its fold. This is
16790 * the simple fold, as the multi-character folds have been
16791 * handled earlier and separated out */
16792 _to_uni_fold_flags(j, foldbuf, &foldlen,
16793 (ASCII_FOLD_RESTRICTED)
16794 ? FOLD_FLAGS_NOMIX_ASCII
16797 /* Single character fold of above Latin1. Add everything in
16798 * its fold closure to the list that this node should match.
16799 * The fold closures data structure is a hash with the keys
16800 * being the UTF-8 of every character that is folded to, like
16801 * 'k', and the values each an array of all code points that
16802 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
16803 * Multi-character folds are not included */
16804 if ((listp = hv_fetch(PL_utf8_foldclosures,
16805 (char *) foldbuf, foldlen, FALSE)))
16807 AV* list = (AV*) *listp;
16809 for (k = 0; k <= av_tindex(list); k++) {
16810 SV** c_p = av_fetch(list, k, FALSE);
16816 /* /aa doesn't allow folds between ASCII and non- */
16817 if ((ASCII_FOLD_RESTRICTED
16818 && (isASCII(c) != isASCII(j))))
16823 /* Folds under /l which cross the 255/256 boundary
16824 * are added to a separate list. (These are valid
16825 * only when the locale is UTF-8.) */
16826 if (c < 256 && LOC) {
16827 *use_list = add_cp_to_invlist(*use_list, c);
16831 if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
16833 cp_list = add_cp_to_invlist(cp_list, c);
16836 /* Similarly folds involving non-ascii Latin1
16837 * characters under /d are added to their list */
16838 has_upper_latin1_only_utf8_matches
16839 = add_cp_to_invlist(
16840 has_upper_latin1_only_utf8_matches,
16847 SvREFCNT_dec_NN(fold_intersection);
16850 /* Now that we have finished adding all the folds, there is no reason
16851 * to keep the foldable list separate */
16852 _invlist_union(cp_list, cp_foldable_list, &cp_list);
16853 SvREFCNT_dec_NN(cp_foldable_list);
16856 /* And combine the result (if any) with any inversion list from posix
16857 * classes. The lists are kept separate up to now because we don't want to
16858 * fold the classes (folding of those is automatically handled by the swash
16859 * fetching code) */
16860 if (simple_posixes) {
16861 _invlist_union(cp_list, simple_posixes, &cp_list);
16862 SvREFCNT_dec_NN(simple_posixes);
16864 if (posixes || nposixes) {
16865 if (posixes && AT_LEAST_ASCII_RESTRICTED) {
16866 /* Under /a and /aa, nothing above ASCII matches these */
16867 _invlist_intersection(posixes,
16868 PL_XPosix_ptrs[_CC_ASCII],
16872 if (DEPENDS_SEMANTICS) {
16873 /* Under /d, everything in the upper half of the Latin1 range
16874 * matches these complements */
16875 ANYOF_FLAGS(ret) |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
16877 else if (AT_LEAST_ASCII_RESTRICTED) {
16878 /* Under /a and /aa, everything above ASCII matches these
16880 _invlist_union_complement_2nd(nposixes,
16881 PL_XPosix_ptrs[_CC_ASCII],
16885 _invlist_union(posixes, nposixes, &posixes);
16886 SvREFCNT_dec_NN(nposixes);
16889 posixes = nposixes;
16892 if (! DEPENDS_SEMANTICS) {
16894 _invlist_union(cp_list, posixes, &cp_list);
16895 SvREFCNT_dec_NN(posixes);
16902 /* Under /d, we put into a separate list the Latin1 things that
16903 * match only when the target string is utf8 */
16904 SV* nonascii_but_latin1_properties = NULL;
16905 _invlist_intersection(posixes, PL_UpperLatin1,
16906 &nonascii_but_latin1_properties);
16907 _invlist_subtract(posixes, nonascii_but_latin1_properties,
16910 _invlist_union(cp_list, posixes, &cp_list);
16911 SvREFCNT_dec_NN(posixes);
16917 if (has_upper_latin1_only_utf8_matches) {
16918 _invlist_union(has_upper_latin1_only_utf8_matches,
16919 nonascii_but_latin1_properties,
16920 &has_upper_latin1_only_utf8_matches);
16921 SvREFCNT_dec_NN(nonascii_but_latin1_properties);
16924 has_upper_latin1_only_utf8_matches
16925 = nonascii_but_latin1_properties;
16930 /* And combine the result (if any) with any inversion list from properties.
16931 * The lists are kept separate up to now so that we can distinguish the two
16932 * in regards to matching above-Unicode. A run-time warning is generated
16933 * if a Unicode property is matched against a non-Unicode code point. But,
16934 * we allow user-defined properties to match anything, without any warning,
16935 * and we also suppress the warning if there is a portion of the character
16936 * class that isn't a Unicode property, and which matches above Unicode, \W
16937 * or [\x{110000}] for example.
16938 * (Note that in this case, unlike the Posix one above, there is no
16939 * <has_upper_latin1_only_utf8_matches>, because having a Unicode property
16940 * forces Unicode semantics */
16944 /* If it matters to the final outcome, see if a non-property
16945 * component of the class matches above Unicode. If so, the
16946 * warning gets suppressed. This is true even if just a single
16947 * such code point is specified, as, though not strictly correct if
16948 * another such code point is matched against, the fact that they
16949 * are using above-Unicode code points indicates they should know
16950 * the issues involved */
16952 warn_super = ! (invert
16953 ^ (invlist_highest(cp_list) > PERL_UNICODE_MAX));
16956 _invlist_union(properties, cp_list, &cp_list);
16957 SvREFCNT_dec_NN(properties);
16960 cp_list = properties;
16965 |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
16967 /* Because an ANYOF node is the only one that warns, this node
16968 * can't be optimized into something else */
16969 optimizable = FALSE;
16973 /* Here, we have calculated what code points should be in the character
16976 * Now we can see about various optimizations. Fold calculation (which we
16977 * did above) needs to take place before inversion. Otherwise /[^k]/i
16978 * would invert to include K, which under /i would match k, which it
16979 * shouldn't. Therefore we can't invert folded locale now, as it won't be
16980 * folded until runtime */
16982 /* If we didn't do folding, it's because some information isn't available
16983 * until runtime; set the run-time fold flag for these. (We don't have to
16984 * worry about properties folding, as that is taken care of by the swash
16985 * fetching). We know to set the flag if we have a non-NULL list for UTF-8
16986 * locales, or the class matches at least one 0-255 range code point */
16988 if (only_utf8_locale_list) {
16991 |ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
16993 else if (cp_list) { /* Look to see if a 0-255 code point is in list */
16995 invlist_iterinit(cp_list);
16996 if (invlist_iternext(cp_list, &start, &end) && start < 256) {
16997 ANYOF_FLAGS(ret) |= ANYOFL_FOLD;
16999 invlist_iterfinish(cp_list);
17003 #define MATCHES_ALL_NON_UTF8_NON_ASCII(ret) \
17004 ( DEPENDS_SEMANTICS \
17005 && (ANYOF_FLAGS(ret) \
17006 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
17008 /* See if we can simplify things under /d */
17009 if ( has_upper_latin1_only_utf8_matches
17010 || MATCHES_ALL_NON_UTF8_NON_ASCII(ret))
17012 if (has_upper_latin1_only_utf8_matches) {
17013 if (MATCHES_ALL_NON_UTF8_NON_ASCII(ret)) {
17015 /* Here, we have both the flag and inversion list. Any character in
17016 * 'has_upper_latin1_only_utf8_matches' matches when UTF-8 is
17017 * in effect, but it also matches when UTF-8 is not in effect
17018 * because of MATCHES_ALL_NON_UTF8_NON_ASCII. Therefore it
17019 * matches unconditionally, so can be added to the regular
17020 * list, and 'has_upper_latin1_only_utf8_matches' cleared */
17021 _invlist_union(cp_list,
17022 has_upper_latin1_only_utf8_matches,
17024 SvREFCNT_dec_NN(has_upper_latin1_only_utf8_matches);
17025 has_upper_latin1_only_utf8_matches = NULL;
17027 else if (cp_list) {
17029 /* Here, 'cp_list' gives chars that always match, and
17030 * 'has_upper_latin1_only_utf8_matches' gives chars that were
17031 * specified to match only if the target string is in UTF-8.
17032 * It may be that these overlap, so we can subtract the
17033 * unconditionally matching from the conditional ones, to make
17034 * the conditional list as small as possible, perhaps even
17035 * clearing it, in which case more optimizations are possible
17037 _invlist_subtract(has_upper_latin1_only_utf8_matches,
17039 &has_upper_latin1_only_utf8_matches);
17040 if (_invlist_len(has_upper_latin1_only_utf8_matches) == 0) {
17041 SvREFCNT_dec_NN(has_upper_latin1_only_utf8_matches);
17042 has_upper_latin1_only_utf8_matches = NULL;
17047 /* Similarly, if the unconditional matches include every upper latin1
17048 * character, we can clear that flag to permit later optimizations */
17049 if (cp_list && MATCHES_ALL_NON_UTF8_NON_ASCII(ret)) {
17050 SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1);
17051 _invlist_subtract(only_non_utf8_list, cp_list, &only_non_utf8_list);
17052 if (_invlist_len(only_non_utf8_list) == 0) {
17053 ANYOF_FLAGS(ret) &= ~ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
17055 SvREFCNT_dec_NN(only_non_utf8_list);
17056 only_non_utf8_list = NULL;;
17059 /* If we haven't gotten rid of all conditional matching, we change the
17060 * regnode type to indicate that */
17061 if ( has_upper_latin1_only_utf8_matches
17062 || MATCHES_ALL_NON_UTF8_NON_ASCII(ret))
17065 optimizable = FALSE;
17068 #undef MATCHES_ALL_NON_UTF8_NON_ASCII
17070 /* Optimize inverted simple patterns (e.g. [^a-z]) when everything is known
17071 * at compile time. Besides not inverting folded locale now, we can't
17072 * invert if there are things such as \w, which aren't known until runtime
17076 && OP(ret) != ANYOFD
17077 && ! (ANYOF_FLAGS(ret) & (ANYOF_LOCALE_FLAGS))
17078 && ! HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
17080 _invlist_invert(cp_list);
17082 /* Any swash can't be used as-is, because we've inverted things */
17084 SvREFCNT_dec_NN(swash);
17088 /* Clear the invert flag since have just done it here */
17095 *ret_invlist = cp_list;
17096 SvREFCNT_dec(swash);
17098 /* Discard the generated node */
17100 RExC_size = orig_size;
17103 RExC_emit = orig_emit;
17108 /* Some character classes are equivalent to other nodes. Such nodes take
17109 * up less room and generally fewer operations to execute than ANYOF nodes.
17110 * Above, we checked for and optimized into some such equivalents for
17111 * certain common classes that are easy to test. Getting to this point in
17112 * the code means that the class didn't get optimized there. Since this
17113 * code is only executed in Pass 2, it is too late to save space--it has
17114 * been allocated in Pass 1, and currently isn't given back. But turning
17115 * things into an EXACTish node can allow the optimizer to join it to any
17116 * adjacent such nodes. And if the class is equivalent to things like /./,
17117 * expensive run-time swashes can be avoided. Now that we have more
17118 * complete information, we can find things necessarily missed by the
17119 * earlier code. Another possible "optimization" that isn't done is that
17120 * something like [Ee] could be changed into an EXACTFU. khw tried this
17121 * and found that the ANYOF is faster, including for code points not in the
17122 * bitmap. This still might make sense to do, provided it got joined with
17123 * an adjacent node(s) to create a longer EXACTFU one. This could be
17124 * accomplished by creating a pseudo ANYOF_EXACTFU node type that the join
17125 * routine would know is joinable. If that didn't happen, the node type
17126 * could then be made a straight ANYOF */
17128 if (optimizable && cp_list && ! invert) {
17130 U8 op = END; /* The optimzation node-type */
17131 int posix_class = -1; /* Illegal value */
17132 const char * cur_parse= RExC_parse;
17134 invlist_iterinit(cp_list);
17135 if (! invlist_iternext(cp_list, &start, &end)) {
17137 /* Here, the list is empty. This happens, for example, when a
17138 * Unicode property that doesn't match anything is the only element
17139 * in the character class (perluniprops.pod notes such properties).
17142 *flagp |= HASWIDTH|SIMPLE;
17144 else if (start == end) { /* The range is a single code point */
17145 if (! invlist_iternext(cp_list, &start, &end)
17147 /* Don't do this optimization if it would require changing
17148 * the pattern to UTF-8 */
17149 && (start < 256 || UTF))
17151 /* Here, the list contains a single code point. Can optimize
17152 * into an EXACTish node */
17163 /* A locale node under folding with one code point can be
17164 * an EXACTFL, as its fold won't be calculated until
17170 /* Here, we are generally folding, but there is only one
17171 * code point to match. If we have to, we use an EXACT
17172 * node, but it would be better for joining with adjacent
17173 * nodes in the optimization pass if we used the same
17174 * EXACTFish node that any such are likely to be. We can
17175 * do this iff the code point doesn't participate in any
17176 * folds. For example, an EXACTF of a colon is the same as
17177 * an EXACT one, since nothing folds to or from a colon. */
17179 if (IS_IN_SOME_FOLD_L1(value)) {
17184 if (_invlist_contains_cp(PL_utf8_foldable, value)) {
17189 /* If we haven't found the node type, above, it means we
17190 * can use the prevailing one */
17192 op = compute_EXACTish(pRExC_state);
17196 } /* End of first range contains just a single code point */
17197 else if (start == 0) {
17198 if (end == UV_MAX) {
17200 *flagp |= HASWIDTH|SIMPLE;
17203 else if (end == '\n' - 1
17204 && invlist_iternext(cp_list, &start, &end)
17205 && start == '\n' + 1 && end == UV_MAX)
17208 *flagp |= HASWIDTH|SIMPLE;
17212 invlist_iterfinish(cp_list);
17215 const UV cp_list_len = _invlist_len(cp_list);
17216 const UV* cp_list_array = invlist_array(cp_list);
17218 /* Here, didn't find an optimization. See if this matches any of
17219 * the POSIX classes. These run slightly faster for above-Unicode
17220 * code points, so don't bother with POSIXA ones nor the 2 that
17221 * have no above-Unicode matches. We can avoid these checks unless
17222 * the ANYOF matches at least as high as the lowest POSIX one
17223 * (which was manually found to be \v. The actual code point may
17224 * increase in later Unicode releases, if a higher code point is
17225 * assigned to be \v, but this code will never break. It would
17226 * just mean we could execute the checks for posix optimizations
17227 * unnecessarily) */
17229 if (cp_list_array[cp_list_len-1] > 0x2029) {
17230 for (posix_class = 0;
17231 posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC;
17235 if (posix_class == _CC_ASCII || posix_class == _CC_CNTRL) {
17238 for (try_inverted = 0; try_inverted < 2; try_inverted++) {
17240 /* Check if matches normal or inverted */
17241 if (_invlistEQ(cp_list,
17242 PL_XPosix_ptrs[posix_class],
17245 op = (try_inverted)
17248 *flagp |= HASWIDTH|SIMPLE;
17258 RExC_parse = (char *)orig_parse;
17259 RExC_emit = (regnode *)orig_emit;
17261 if (regarglen[op]) {
17262 ret = reganode(pRExC_state, op, 0);
17264 ret = reg_node(pRExC_state, op);
17267 RExC_parse = (char *)cur_parse;
17269 if (PL_regkind[op] == EXACT) {
17270 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, 0, value,
17271 TRUE /* downgradable to EXACT */
17274 else if (PL_regkind[op] == POSIXD || PL_regkind[op] == NPOSIXD) {
17275 FLAGS(ret) = posix_class;
17278 SvREFCNT_dec_NN(cp_list);
17283 /* Here, <cp_list> contains all the code points we can determine at
17284 * compile time that match under all conditions. Go through it, and
17285 * for things that belong in the bitmap, put them there, and delete from
17286 * <cp_list>. While we are at it, see if everything above 255 is in the
17287 * list, and if so, set a flag to speed up execution */
17289 populate_ANYOF_from_invlist(ret, &cp_list);
17292 ANYOF_FLAGS(ret) |= ANYOF_INVERT;
17295 /* Here, the bitmap has been populated with all the Latin1 code points that
17296 * always match. Can now add to the overall list those that match only
17297 * when the target string is UTF-8 (<has_upper_latin1_only_utf8_matches>).
17299 if (has_upper_latin1_only_utf8_matches) {
17301 _invlist_union(cp_list,
17302 has_upper_latin1_only_utf8_matches,
17304 SvREFCNT_dec_NN(has_upper_latin1_only_utf8_matches);
17307 cp_list = has_upper_latin1_only_utf8_matches;
17309 ANYOF_FLAGS(ret) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
17312 /* If there is a swash and more than one element, we can't use the swash in
17313 * the optimization below. */
17314 if (swash && element_count > 1) {
17315 SvREFCNT_dec_NN(swash);
17319 /* Note that the optimization of using 'swash' if it is the only thing in
17320 * the class doesn't have us change swash at all, so it can include things
17321 * that are also in the bitmap; otherwise we have purposely deleted that
17322 * duplicate information */
17323 set_ANYOF_arg(pRExC_state, ret, cp_list,
17324 (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
17326 only_utf8_locale_list,
17327 swash, has_user_defined_property);
17329 *flagp |= HASWIDTH|SIMPLE;
17331 if (ANYOF_FLAGS(ret) & ANYOF_LOCALE_FLAGS) {
17332 RExC_contains_locale = 1;
17338 #undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
17341 S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state,
17342 regnode* const node,
17344 SV* const runtime_defns,
17345 SV* const only_utf8_locale_list,
17347 const bool has_user_defined_property)
17349 /* Sets the arg field of an ANYOF-type node 'node', using information about
17350 * the node passed-in. If there is nothing outside the node's bitmap, the
17351 * arg is set to ANYOF_ONLY_HAS_BITMAP. Otherwise, it sets the argument to
17352 * the count returned by add_data(), having allocated and stored an array,
17353 * av, that that count references, as follows:
17354 * av[0] stores the character class description in its textual form.
17355 * This is used later (regexec.c:Perl_regclass_swash()) to
17356 * initialize the appropriate swash, and is also useful for dumping
17357 * the regnode. This is set to &PL_sv_undef if the textual
17358 * description is not needed at run-time (as happens if the other
17359 * elements completely define the class)
17360 * av[1] if &PL_sv_undef, is a placeholder to later contain the swash
17361 * computed from av[0]. But if no further computation need be done,
17362 * the swash is stored here now (and av[0] is &PL_sv_undef).
17363 * av[2] stores the inversion list of code points that match only if the
17364 * current locale is UTF-8
17365 * av[3] stores the cp_list inversion list for use in addition or instead
17366 * of av[0]; used only if cp_list exists and av[1] is &PL_sv_undef.
17367 * (Otherwise everything needed is already in av[0] and av[1])
17368 * av[4] is set if any component of the class is from a user-defined
17369 * property; used only if av[3] exists */
17373 PERL_ARGS_ASSERT_SET_ANYOF_ARG;
17375 if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) {
17376 assert(! (ANYOF_FLAGS(node)
17377 & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP));
17378 ARG_SET(node, ANYOF_ONLY_HAS_BITMAP);
17381 AV * const av = newAV();
17384 av_store(av, 0, (runtime_defns)
17385 ? SvREFCNT_inc(runtime_defns) : &PL_sv_undef);
17388 av_store(av, 1, swash);
17389 SvREFCNT_dec_NN(cp_list);
17392 av_store(av, 1, &PL_sv_undef);
17394 av_store(av, 3, cp_list);
17395 av_store(av, 4, newSVuv(has_user_defined_property));
17399 if (only_utf8_locale_list) {
17400 av_store(av, 2, only_utf8_locale_list);
17403 av_store(av, 2, &PL_sv_undef);
17406 rv = newRV_noinc(MUTABLE_SV(av));
17407 n = add_data(pRExC_state, STR_WITH_LEN("s"));
17408 RExC_rxi->data->data[n] = (void*)rv;
17413 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
17415 Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog,
17416 const regnode* node,
17419 SV** only_utf8_locale_ptr,
17423 /* For internal core use only.
17424 * Returns the swash for the input 'node' in the regex 'prog'.
17425 * If <doinit> is 'true', will attempt to create the swash if not already
17427 * If <listsvp> is non-null, will return the printable contents of the
17428 * swash. This can be used to get debugging information even before the
17429 * swash exists, by calling this function with 'doinit' set to false, in
17430 * which case the components that will be used to eventually create the
17431 * swash are returned (in a printable form).
17432 * If <exclude_list> is not NULL, it is an inversion list of things to
17433 * exclude from what's returned in <listsvp>.
17434 * Tied intimately to how S_set_ANYOF_arg sets up the data structure. Note
17435 * that, in spite of this function's name, the swash it returns may include
17436 * the bitmap data as well */
17439 SV *si = NULL; /* Input swash initialization string */
17440 SV* invlist = NULL;
17442 RXi_GET_DECL(prog,progi);
17443 const struct reg_data * const data = prog ? progi->data : NULL;
17445 PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA;
17447 if (data && data->count) {
17448 const U32 n = ARG(node);
17450 if (data->what[n] == 's') {
17451 SV * const rv = MUTABLE_SV(data->data[n]);
17452 AV * const av = MUTABLE_AV(SvRV(rv));
17453 SV **const ary = AvARRAY(av);
17454 U8 swash_init_flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
17456 si = *ary; /* ary[0] = the string to initialize the swash with */
17458 if (av_tindex(av) >= 2) {
17459 if (only_utf8_locale_ptr
17461 && ary[2] != &PL_sv_undef)
17463 *only_utf8_locale_ptr = ary[2];
17466 assert(only_utf8_locale_ptr);
17467 *only_utf8_locale_ptr = NULL;
17470 /* Elements 3 and 4 are either both present or both absent. [3]
17471 * is any inversion list generated at compile time; [4]
17472 * indicates if that inversion list has any user-defined
17473 * properties in it. */
17474 if (av_tindex(av) >= 3) {
17476 if (SvUV(ary[4])) {
17477 swash_init_flags |= _CORE_SWASH_INIT_USER_DEFINED_PROPERTY;
17485 /* Element [1] is reserved for the set-up swash. If already there,
17486 * return it; if not, create it and store it there */
17487 if (ary[1] && SvROK(ary[1])) {
17490 else if (doinit && ((si && si != &PL_sv_undef)
17491 || (invlist && invlist != &PL_sv_undef))) {
17493 sw = _core_swash_init("utf8", /* the utf8 package */
17497 0, /* not from tr/// */
17499 &swash_init_flags);
17500 (void)av_store(av, 1, sw);
17505 /* If requested, return a printable version of what this swash matches */
17507 SV* matches_string = newSVpvs("");
17509 /* The swash should be used, if possible, to get the data, as it
17510 * contains the resolved data. But this function can be called at
17511 * compile-time, before everything gets resolved, in which case we
17512 * return the currently best available information, which is the string
17513 * that will eventually be used to do that resolving, 'si' */
17514 if ((! sw || (invlist = _get_swash_invlist(sw)) == NULL)
17515 && (si && si != &PL_sv_undef))
17517 sv_catsv(matches_string, si);
17520 /* Add the inversion list to whatever we have. This may have come from
17521 * the swash, or from an input parameter */
17523 if (exclude_list) {
17524 SV* clone = invlist_clone(invlist);
17525 _invlist_subtract(clone, exclude_list, &clone);
17526 sv_catsv(matches_string, _invlist_contents(clone));
17527 SvREFCNT_dec_NN(clone);
17530 sv_catsv(matches_string, _invlist_contents(invlist));
17533 *listsvp = matches_string;
17538 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
17540 /* reg_skipcomment()
17542 Absorbs an /x style # comment from the input stream,
17543 returning a pointer to the first character beyond the comment, or if the
17544 comment terminates the pattern without anything following it, this returns
17545 one past the final character of the pattern (in other words, RExC_end) and
17546 sets the REG_RUN_ON_COMMENT_SEEN flag.
17548 Note it's the callers responsibility to ensure that we are
17549 actually in /x mode
17553 PERL_STATIC_INLINE char*
17554 S_reg_skipcomment(RExC_state_t *pRExC_state, char* p)
17556 PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
17560 while (p < RExC_end) {
17561 if (*(++p) == '\n') {
17566 /* we ran off the end of the pattern without ending the comment, so we have
17567 * to add an \n when wrapping */
17568 RExC_seen |= REG_RUN_ON_COMMENT_SEEN;
17573 S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state,
17575 const bool force_to_xmod
17578 /* If the text at the current parse position '*p' is a '(?#...)' comment,
17579 * or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p'
17580 * is /x whitespace, advance '*p' so that on exit it points to the first
17581 * byte past all such white space and comments */
17583 const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED);
17585 PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT;
17587 assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p));
17590 if (RExC_end - (*p) >= 3
17592 && *(*p + 1) == '?'
17593 && *(*p + 2) == '#')
17595 while (*(*p) != ')') {
17596 if ((*p) == RExC_end)
17597 FAIL("Sequence (?#... not terminated");
17605 const char * save_p = *p;
17606 while ((*p) < RExC_end) {
17608 if ((len = is_PATWS_safe((*p), RExC_end, UTF))) {
17611 else if (*(*p) == '#') {
17612 (*p) = reg_skipcomment(pRExC_state, (*p));
17618 if (*p != save_p) {
17631 Advances the parse position by one byte, unless that byte is the beginning
17632 of a '(?#...)' style comment, or is /x whitespace and /x is in effect. In
17633 those two cases, the parse position is advanced beyond all such comments and
17636 This is the UTF, (?#...), and /x friendly way of saying RExC_parse++.
17640 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
17642 PERL_ARGS_ASSERT_NEXTCHAR;
17644 if (RExC_parse < RExC_end) {
17646 || UTF8_IS_INVARIANT(*RExC_parse)
17647 || UTF8_IS_START(*RExC_parse));
17649 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
17651 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
17652 FALSE /* Don't assume /x */ );
17657 S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name)
17659 /* Allocate a regnode for 'op' and returns it, with 'extra_size' extra
17660 * space. In pass1, it aligns and increments RExC_size; in pass2,
17663 regnode * const ret = RExC_emit;
17664 GET_RE_DEBUG_FLAGS_DECL;
17666 PERL_ARGS_ASSERT_REGNODE_GUTS;
17668 assert(extra_size >= regarglen[op]);
17671 SIZE_ALIGN(RExC_size);
17672 RExC_size += 1 + extra_size;
17675 if (RExC_emit >= RExC_emit_bound)
17676 Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d, %p>=%p",
17677 op, (void*)RExC_emit, (void*)RExC_emit_bound);
17679 NODE_ALIGN_FILL(ret);
17680 #ifndef RE_TRACK_PATTERN_OFFSETS
17681 PERL_UNUSED_ARG(name);
17683 if (RExC_offsets) { /* MJD */
17685 ("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n",
17688 (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0]
17689 ? "Overwriting end of array!\n" : "OK",
17690 (UV)(RExC_emit - RExC_emit_start),
17691 (UV)(RExC_parse - RExC_start),
17692 (UV)RExC_offsets[0]));
17693 Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
17700 - reg_node - emit a node
17702 STATIC regnode * /* Location. */
17703 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
17705 regnode * const ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node");
17707 PERL_ARGS_ASSERT_REG_NODE;
17709 assert(regarglen[op] == 0);
17712 regnode *ptr = ret;
17713 FILL_ADVANCE_NODE(ptr, op);
17720 - reganode - emit a node with an argument
17722 STATIC regnode * /* Location. */
17723 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
17725 regnode * const ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode");
17727 PERL_ARGS_ASSERT_REGANODE;
17729 assert(regarglen[op] == 1);
17732 regnode *ptr = ret;
17733 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
17740 S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2)
17742 /* emit a node with U32 and I32 arguments */
17744 regnode * const ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode");
17746 PERL_ARGS_ASSERT_REG2LANODE;
17748 assert(regarglen[op] == 2);
17751 regnode *ptr = ret;
17752 FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2);
17759 - reginsert - insert an operator in front of already-emitted operand
17761 * Means relocating the operand.
17764 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
17769 const int offset = regarglen[(U8)op];
17770 const int size = NODE_STEP_REGNODE + offset;
17771 GET_RE_DEBUG_FLAGS_DECL;
17773 PERL_ARGS_ASSERT_REGINSERT;
17774 PERL_UNUSED_CONTEXT;
17775 PERL_UNUSED_ARG(depth);
17776 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
17777 DEBUG_PARSE_FMT("inst"," - %s",PL_reg_name[op]);
17786 if (RExC_open_parens) {
17788 /*DEBUG_PARSE_FMT("inst"," - %"IVdf, (IV)RExC_npar);*/
17789 for ( paren=0 ; paren < RExC_npar ; paren++ ) {
17790 if ( RExC_open_parens[paren] >= opnd ) {
17791 /*DEBUG_PARSE_FMT("open"," - %d",size);*/
17792 RExC_open_parens[paren] += size;
17794 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
17796 if ( RExC_close_parens[paren] >= opnd ) {
17797 /*DEBUG_PARSE_FMT("close"," - %d",size);*/
17798 RExC_close_parens[paren] += size;
17800 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
17805 while (src > opnd) {
17806 StructCopy(--src, --dst, regnode);
17807 #ifdef RE_TRACK_PATTERN_OFFSETS
17808 if (RExC_offsets) { /* MJD 20010112 */
17810 ("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
17814 (UV)(dst - RExC_emit_start) > RExC_offsets[0]
17815 ? "Overwriting end of array!\n" : "OK",
17816 (UV)(src - RExC_emit_start),
17817 (UV)(dst - RExC_emit_start),
17818 (UV)RExC_offsets[0]));
17819 Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
17820 Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
17826 place = opnd; /* Op node, where operand used to be. */
17827 #ifdef RE_TRACK_PATTERN_OFFSETS
17828 if (RExC_offsets) { /* MJD */
17830 ("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
17834 (UV)(place - RExC_emit_start) > RExC_offsets[0]
17835 ? "Overwriting end of array!\n" : "OK",
17836 (UV)(place - RExC_emit_start),
17837 (UV)(RExC_parse - RExC_start),
17838 (UV)RExC_offsets[0]));
17839 Set_Node_Offset(place, RExC_parse);
17840 Set_Node_Length(place, 1);
17843 src = NEXTOPER(place);
17844 FILL_ADVANCE_NODE(place, op);
17845 Zero(src, offset, regnode);
17849 - regtail - set the next-pointer at the end of a node chain of p to val.
17850 - SEE ALSO: regtail_study
17853 S_regtail(pTHX_ RExC_state_t * pRExC_state,
17854 const regnode * const p,
17855 const regnode * const val,
17859 GET_RE_DEBUG_FLAGS_DECL;
17861 PERL_ARGS_ASSERT_REGTAIL;
17863 PERL_UNUSED_ARG(depth);
17869 /* Find last node. */
17870 scan = (regnode *) p;
17872 regnode * const temp = regnext(scan);
17874 DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
17875 regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
17876 PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
17877 SvPV_nolen_const(RExC_mysv), REG_NODE_NUM(scan),
17878 (temp == NULL ? "->" : ""),
17879 (temp == NULL ? PL_reg_name[OP(val)] : "")
17887 if (reg_off_by_arg[OP(scan)]) {
17888 ARG_SET(scan, val - scan);
17891 NEXT_OFF(scan) = val - scan;
17897 - regtail_study - set the next-pointer at the end of a node chain of p to val.
17898 - Look for optimizable sequences at the same time.
17899 - currently only looks for EXACT chains.
17901 This is experimental code. The idea is to use this routine to perform
17902 in place optimizations on branches and groups as they are constructed,
17903 with the long term intention of removing optimization from study_chunk so
17904 that it is purely analytical.
17906 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
17907 to control which is which.
17910 /* TODO: All four parms should be const */
17913 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p,
17914 const regnode *val,U32 depth)
17918 #ifdef EXPERIMENTAL_INPLACESCAN
17921 GET_RE_DEBUG_FLAGS_DECL;
17923 PERL_ARGS_ASSERT_REGTAIL_STUDY;
17929 /* Find last node. */
17933 regnode * const temp = regnext(scan);
17934 #ifdef EXPERIMENTAL_INPLACESCAN
17935 if (PL_regkind[OP(scan)] == EXACT) {
17936 bool unfolded_multi_char; /* Unexamined in this routine */
17937 if (join_exact(pRExC_state, scan, &min,
17938 &unfolded_multi_char, 1, val, depth+1))
17943 switch (OP(scan)) {
17947 case EXACTFA_NO_TRIE:
17953 if( exact == PSEUDO )
17955 else if ( exact != OP(scan) )
17964 DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
17965 regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
17966 PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
17967 SvPV_nolen_const(RExC_mysv),
17968 REG_NODE_NUM(scan),
17969 PL_reg_name[exact]);
17976 DEBUG_PARSE_MSG("");
17977 regprop(RExC_rx, RExC_mysv, val, NULL, pRExC_state);
17978 PerlIO_printf(Perl_debug_log,
17979 "~ attach to %s (%"IVdf") offset to %"IVdf"\n",
17980 SvPV_nolen_const(RExC_mysv),
17981 (IV)REG_NODE_NUM(val),
17985 if (reg_off_by_arg[OP(scan)]) {
17986 ARG_SET(scan, val - scan);
17989 NEXT_OFF(scan) = val - scan;
17997 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
18002 S_regdump_intflags(pTHX_ const char *lead, const U32 flags)
18007 ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8);
18009 for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) {
18010 if (flags & (1<<bit)) {
18011 if (!set++ && lead)
18012 PerlIO_printf(Perl_debug_log, "%s",lead);
18013 PerlIO_printf(Perl_debug_log, "%s ",PL_reg_intflags_name[bit]);
18018 PerlIO_printf(Perl_debug_log, "\n");
18020 PerlIO_printf(Perl_debug_log, "%s[none-set]\n",lead);
18025 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
18031 ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8);
18033 for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) {
18034 if (flags & (1<<bit)) {
18035 if ((1<<bit) & RXf_PMf_CHARSET) { /* Output separately, below */
18038 if (!set++ && lead)
18039 PerlIO_printf(Perl_debug_log, "%s",lead);
18040 PerlIO_printf(Perl_debug_log, "%s ",PL_reg_extflags_name[bit]);
18043 if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
18044 if (!set++ && lead) {
18045 PerlIO_printf(Perl_debug_log, "%s",lead);
18048 case REGEX_UNICODE_CHARSET:
18049 PerlIO_printf(Perl_debug_log, "UNICODE");
18051 case REGEX_LOCALE_CHARSET:
18052 PerlIO_printf(Perl_debug_log, "LOCALE");
18054 case REGEX_ASCII_RESTRICTED_CHARSET:
18055 PerlIO_printf(Perl_debug_log, "ASCII-RESTRICTED");
18057 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
18058 PerlIO_printf(Perl_debug_log, "ASCII-MORE_RESTRICTED");
18061 PerlIO_printf(Perl_debug_log, "UNKNOWN CHARACTER SET");
18067 PerlIO_printf(Perl_debug_log, "\n");
18069 PerlIO_printf(Perl_debug_log, "%s[none-set]\n",lead);
18075 Perl_regdump(pTHX_ const regexp *r)
18078 SV * const sv = sv_newmortal();
18079 SV *dsv= sv_newmortal();
18080 RXi_GET_DECL(r,ri);
18081 GET_RE_DEBUG_FLAGS_DECL;
18083 PERL_ARGS_ASSERT_REGDUMP;
18085 (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
18087 /* Header fields of interest. */
18088 if (r->anchored_substr) {
18089 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr),
18090 RE_SV_DUMPLEN(r->anchored_substr), 30);
18091 PerlIO_printf(Perl_debug_log,
18092 "anchored %s%s at %"IVdf" ",
18093 s, RE_SV_TAIL(r->anchored_substr),
18094 (IV)r->anchored_offset);
18095 } else if (r->anchored_utf8) {
18096 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8),
18097 RE_SV_DUMPLEN(r->anchored_utf8), 30);
18098 PerlIO_printf(Perl_debug_log,
18099 "anchored utf8 %s%s at %"IVdf" ",
18100 s, RE_SV_TAIL(r->anchored_utf8),
18101 (IV)r->anchored_offset);
18103 if (r->float_substr) {
18104 RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr),
18105 RE_SV_DUMPLEN(r->float_substr), 30);
18106 PerlIO_printf(Perl_debug_log,
18107 "floating %s%s at %"IVdf"..%"UVuf" ",
18108 s, RE_SV_TAIL(r->float_substr),
18109 (IV)r->float_min_offset, (UV)r->float_max_offset);
18110 } else if (r->float_utf8) {
18111 RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8),
18112 RE_SV_DUMPLEN(r->float_utf8), 30);
18113 PerlIO_printf(Perl_debug_log,
18114 "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
18115 s, RE_SV_TAIL(r->float_utf8),
18116 (IV)r->float_min_offset, (UV)r->float_max_offset);
18118 if (r->check_substr || r->check_utf8)
18119 PerlIO_printf(Perl_debug_log,
18121 (r->check_substr == r->float_substr
18122 && r->check_utf8 == r->float_utf8
18123 ? "(checking floating" : "(checking anchored"));
18124 if (r->intflags & PREGf_NOSCAN)
18125 PerlIO_printf(Perl_debug_log, " noscan");
18126 if (r->extflags & RXf_CHECK_ALL)
18127 PerlIO_printf(Perl_debug_log, " isall");
18128 if (r->check_substr || r->check_utf8)
18129 PerlIO_printf(Perl_debug_log, ") ");
18131 if (ri->regstclass) {
18132 regprop(r, sv, ri->regstclass, NULL, NULL);
18133 PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
18135 if (r->intflags & PREGf_ANCH) {
18136 PerlIO_printf(Perl_debug_log, "anchored");
18137 if (r->intflags & PREGf_ANCH_MBOL)
18138 PerlIO_printf(Perl_debug_log, "(MBOL)");
18139 if (r->intflags & PREGf_ANCH_SBOL)
18140 PerlIO_printf(Perl_debug_log, "(SBOL)");
18141 if (r->intflags & PREGf_ANCH_GPOS)
18142 PerlIO_printf(Perl_debug_log, "(GPOS)");
18143 (void)PerlIO_putc(Perl_debug_log, ' ');
18145 if (r->intflags & PREGf_GPOS_SEEN)
18146 PerlIO_printf(Perl_debug_log, "GPOS:%"UVuf" ", (UV)r->gofs);
18147 if (r->intflags & PREGf_SKIP)
18148 PerlIO_printf(Perl_debug_log, "plus ");
18149 if (r->intflags & PREGf_IMPLICIT)
18150 PerlIO_printf(Perl_debug_log, "implicit ");
18151 PerlIO_printf(Perl_debug_log, "minlen %"IVdf" ", (IV)r->minlen);
18152 if (r->extflags & RXf_EVAL_SEEN)
18153 PerlIO_printf(Perl_debug_log, "with eval ");
18154 PerlIO_printf(Perl_debug_log, "\n");
18156 regdump_extflags("r->extflags: ",r->extflags);
18157 regdump_intflags("r->intflags: ",r->intflags);
18160 PERL_ARGS_ASSERT_REGDUMP;
18161 PERL_UNUSED_CONTEXT;
18162 PERL_UNUSED_ARG(r);
18163 #endif /* DEBUGGING */
18167 - regprop - printable representation of opcode, with run time support
18171 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state)
18176 /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
18177 static const char * const anyofs[] = {
18178 #if _CC_WORDCHAR != 0 || _CC_DIGIT != 1 || _CC_ALPHA != 2 || _CC_LOWER != 3 \
18179 || _CC_UPPER != 4 || _CC_PUNCT != 5 || _CC_PRINT != 6 \
18180 || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8 || _CC_CASED != 9 \
18181 || _CC_SPACE != 10 || _CC_BLANK != 11 || _CC_XDIGIT != 12 \
18182 || _CC_CNTRL != 13 || _CC_ASCII != 14 || _CC_VERTSPACE != 15
18183 #error Need to adjust order of anyofs[]
18218 RXi_GET_DECL(prog,progi);
18219 GET_RE_DEBUG_FLAGS_DECL;
18221 PERL_ARGS_ASSERT_REGPROP;
18223 sv_setpvn(sv, "", 0);
18225 if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */
18226 /* It would be nice to FAIL() here, but this may be called from
18227 regexec.c, and it would be hard to supply pRExC_state. */
18228 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
18229 (int)OP(o), (int)REGNODE_MAX);
18230 sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
18232 k = PL_regkind[OP(o)];
18235 sv_catpvs(sv, " ");
18236 /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
18237 * is a crude hack but it may be the best for now since
18238 * we have no flag "this EXACTish node was UTF-8"
18240 pv_pretty(sv, STRING(o), STR_LEN(o), 60, PL_colors[0], PL_colors[1],
18241 PERL_PV_ESCAPE_UNI_DETECT |
18242 PERL_PV_ESCAPE_NONASCII |
18243 PERL_PV_PRETTY_ELLIPSES |
18244 PERL_PV_PRETTY_LTGT |
18245 PERL_PV_PRETTY_NOCLEAR
18247 } else if (k == TRIE) {
18248 /* print the details of the trie in dumpuntil instead, as
18249 * progi->data isn't available here */
18250 const char op = OP(o);
18251 const U32 n = ARG(o);
18252 const reg_ac_data * const ac = IS_TRIE_AC(op) ?
18253 (reg_ac_data *)progi->data->data[n] :
18255 const reg_trie_data * const trie
18256 = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
18258 Perl_sv_catpvf(aTHX_ sv, "-%s",PL_reg_name[o->flags]);
18259 DEBUG_TRIE_COMPILE_r(
18260 Perl_sv_catpvf(aTHX_ sv,
18261 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
18262 (UV)trie->startstate,
18263 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
18264 (UV)trie->wordcount,
18267 (UV)TRIE_CHARCOUNT(trie),
18268 (UV)trie->uniquecharcount
18271 if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
18272 sv_catpvs(sv, "[");
18273 (void) put_charclass_bitmap_innards(sv,
18274 (IS_ANYOF_TRIE(op))
18276 : TRIE_BITMAP(trie),
18278 sv_catpvs(sv, "]");
18281 } else if (k == CURLY) {
18282 U32 lo = ARG1(o), hi = ARG2(o);
18283 if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
18284 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
18285 Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo);
18286 if (hi == REG_INFTY)
18287 sv_catpvs(sv, "INFTY");
18289 Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi);
18290 sv_catpvs(sv, "}");
18292 else if (k == WHILEM && o->flags) /* Ordinal/of */
18293 Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
18294 else if (k == REF || k == OPEN || k == CLOSE
18295 || k == GROUPP || OP(o)==ACCEPT)
18297 AV *name_list= NULL;
18298 U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o);
18299 Perl_sv_catpvf(aTHX_ sv, "%"UVuf, (UV)parno); /* Parenth number */
18300 if ( RXp_PAREN_NAMES(prog) ) {
18301 name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
18302 } else if ( pRExC_state ) {
18303 name_list= RExC_paren_name_list;
18306 if ( k != REF || (OP(o) < NREF)) {
18307 SV **name= av_fetch(name_list, parno, 0 );
18309 Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
18312 SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]);
18313 I32 *nums=(I32*)SvPVX(sv_dat);
18314 SV **name= av_fetch(name_list, nums[0], 0 );
18317 for ( n=0; n<SvIVX(sv_dat); n++ ) {
18318 Perl_sv_catpvf(aTHX_ sv, "%s%"IVdf,
18319 (n ? "," : ""), (IV)nums[n]);
18321 Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
18325 if ( k == REF && reginfo) {
18326 U32 n = ARG(o); /* which paren pair */
18327 I32 ln = prog->offs[n].start;
18328 if (prog->lastparen < n || ln == -1)
18329 Perl_sv_catpvf(aTHX_ sv, ": FAIL");
18330 else if (ln == prog->offs[n].end)
18331 Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING");
18333 const char *s = reginfo->strbeg + ln;
18334 Perl_sv_catpvf(aTHX_ sv, ": ");
18335 Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0,
18336 PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE );
18339 } else if (k == GOSUB) {
18340 AV *name_list= NULL;
18341 if ( RXp_PAREN_NAMES(prog) ) {
18342 name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
18343 } else if ( pRExC_state ) {
18344 name_list= RExC_paren_name_list;
18347 /* Paren and offset */
18348 Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o));
18350 SV **name= av_fetch(name_list, ARG(o), 0 );
18352 Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
18355 else if (k == LOGICAL)
18356 /* 2: embedded, otherwise 1 */
18357 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);
18358 else if (k == ANYOF) {
18359 const U8 flags = ANYOF_FLAGS(o);
18361 SV* bitmap_invlist = NULL; /* Will hold what the bit map contains */
18364 if (OP(o) == ANYOFL) {
18365 if (ANYOFL_UTF8_LOCALE_REQD(flags)) {
18366 sv_catpvs(sv, "{utf8-loc}");
18369 sv_catpvs(sv, "{loc}");
18372 if (flags & ANYOFL_FOLD)
18373 sv_catpvs(sv, "{i}");
18374 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
18375 if (flags & ANYOF_INVERT)
18376 sv_catpvs(sv, "^");
18378 /* output what the standard cp 0-NUM_ANYOF_CODE_POINTS-1 bitmap matches
18380 do_sep = put_charclass_bitmap_innards(sv, ANYOF_BITMAP(o),
18383 /* output any special charclass tests (used entirely under use
18385 if (ANYOF_POSIXL_TEST_ANY_SET(o)) {
18387 for (i = 0; i < ANYOF_POSIXL_MAX; i++) {
18388 if (ANYOF_POSIXL_TEST(o,i)) {
18389 sv_catpv(sv, anyofs[i]);
18395 if ( ARG(o) != ANYOF_ONLY_HAS_BITMAP
18397 & ( ANYOF_MATCHES_ALL_ABOVE_BITMAP
18398 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP
18402 Perl_sv_catpvf(aTHX_ sv,"%s][%s",PL_colors[1],PL_colors[0]);
18403 if (flags & ANYOF_INVERT)
18404 /*make sure the invert info is in each */
18405 sv_catpvs(sv, "^");
18408 if (OP(o) == ANYOFD
18409 && (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
18411 sv_catpvs(sv, "{non-utf8-latin1-all}");
18414 if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP)
18415 sv_catpvs(sv, "{above_bitmap_all}");
18417 if (ARG(o) != ANYOF_ONLY_HAS_BITMAP) {
18418 SV *lv; /* Set if there is something outside the bit map. */
18419 bool byte_output = FALSE; /* If something has been output */
18420 SV *only_utf8_locale;
18422 /* Get the stuff that wasn't in the bitmap. 'bitmap_invlist'
18423 * is used to guarantee that nothing in the bitmap gets
18425 (void) _get_regclass_nonbitmap_data(prog, o, FALSE,
18426 &lv, &only_utf8_locale,
18428 if (lv && lv != &PL_sv_undef) {
18429 char *s = savesvpv(lv);
18430 char * const origs = s;
18432 while (*s && *s != '\n')
18436 const char * const t = ++s;
18438 if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP) {
18439 if (OP(o) == ANYOFD) {
18440 sv_catpvs(sv, "{utf8}");
18443 sv_catpvs(sv, "{outside bitmap}");
18448 sv_catpvs(sv, " ");
18454 /* Truncate very long output */
18455 if (s - origs > 256) {
18456 Perl_sv_catpvf(aTHX_ sv,
18458 (int) (s - origs - 1),
18464 else if (*s == '\t') {
18478 SvREFCNT_dec_NN(lv);
18481 if ((flags & ANYOFL_FOLD)
18482 && only_utf8_locale
18483 && only_utf8_locale != &PL_sv_undef)
18486 int max_entries = 256;
18488 sv_catpvs(sv, "{utf8 locale}");
18489 invlist_iterinit(only_utf8_locale);
18490 while (invlist_iternext(only_utf8_locale,
18492 put_range(sv, start, end, FALSE);
18494 if (max_entries < 0) {
18495 sv_catpvs(sv, "...");
18499 invlist_iterfinish(only_utf8_locale);
18503 SvREFCNT_dec(bitmap_invlist);
18506 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
18508 else if (k == POSIXD || k == NPOSIXD) {
18509 U8 index = FLAGS(o) * 2;
18510 if (index < C_ARRAY_LENGTH(anyofs)) {
18511 if (*anyofs[index] != '[') {
18514 sv_catpv(sv, anyofs[index]);
18515 if (*anyofs[index] != '[') {
18520 Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
18523 else if (k == BOUND || k == NBOUND) {
18524 /* Must be synced with order of 'bound_type' in regcomp.h */
18525 const char * const bounds[] = {
18526 "", /* Traditional */
18532 assert(FLAGS(o) < C_ARRAY_LENGTH(bounds));
18533 sv_catpv(sv, bounds[FLAGS(o)]);
18535 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
18536 Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
18537 else if (OP(o) == SBOL)
18538 Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^");
18540 /* add on the verb argument if there is one */
18541 if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) {
18542 Perl_sv_catpvf(aTHX_ sv, ":%"SVf,
18543 SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
18546 PERL_UNUSED_CONTEXT;
18547 PERL_UNUSED_ARG(sv);
18548 PERL_UNUSED_ARG(o);
18549 PERL_UNUSED_ARG(prog);
18550 PERL_UNUSED_ARG(reginfo);
18551 PERL_UNUSED_ARG(pRExC_state);
18552 #endif /* DEBUGGING */
18558 Perl_re_intuit_string(pTHX_ REGEXP * const r)
18559 { /* Assume that RE_INTUIT is set */
18560 struct regexp *const prog = ReANY(r);
18561 GET_RE_DEBUG_FLAGS_DECL;
18563 PERL_ARGS_ASSERT_RE_INTUIT_STRING;
18564 PERL_UNUSED_CONTEXT;
18568 const char * const s = SvPV_nolen_const(RX_UTF8(r)
18569 ? prog->check_utf8 : prog->check_substr);
18571 if (!PL_colorset) reginitcolors();
18572 PerlIO_printf(Perl_debug_log,
18573 "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
18575 RX_UTF8(r) ? "utf8 " : "",
18576 PL_colors[5],PL_colors[0],
18579 (strlen(s) > 60 ? "..." : ""));
18582 /* use UTF8 check substring if regexp pattern itself is in UTF8 */
18583 return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr;
18589 handles refcounting and freeing the perl core regexp structure. When
18590 it is necessary to actually free the structure the first thing it
18591 does is call the 'free' method of the regexp_engine associated to
18592 the regexp, allowing the handling of the void *pprivate; member
18593 first. (This routine is not overridable by extensions, which is why
18594 the extensions free is called first.)
18596 See regdupe and regdupe_internal if you change anything here.
18598 #ifndef PERL_IN_XSUB_RE
18600 Perl_pregfree(pTHX_ REGEXP *r)
18606 Perl_pregfree2(pTHX_ REGEXP *rx)
18608 struct regexp *const r = ReANY(rx);
18609 GET_RE_DEBUG_FLAGS_DECL;
18611 PERL_ARGS_ASSERT_PREGFREE2;
18613 if (r->mother_re) {
18614 ReREFCNT_dec(r->mother_re);
18616 CALLREGFREE_PVT(rx); /* free the private data */
18617 SvREFCNT_dec(RXp_PAREN_NAMES(r));
18618 Safefree(r->xpv_len_u.xpvlenu_pv);
18621 SvREFCNT_dec(r->anchored_substr);
18622 SvREFCNT_dec(r->anchored_utf8);
18623 SvREFCNT_dec(r->float_substr);
18624 SvREFCNT_dec(r->float_utf8);
18625 Safefree(r->substrs);
18627 RX_MATCH_COPY_FREE(rx);
18628 #ifdef PERL_ANY_COW
18629 SvREFCNT_dec(r->saved_copy);
18632 SvREFCNT_dec(r->qr_anoncv);
18633 rx->sv_u.svu_rx = 0;
18638 This is a hacky workaround to the structural issue of match results
18639 being stored in the regexp structure which is in turn stored in
18640 PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
18641 could be PL_curpm in multiple contexts, and could require multiple
18642 result sets being associated with the pattern simultaneously, such
18643 as when doing a recursive match with (??{$qr})
18645 The solution is to make a lightweight copy of the regexp structure
18646 when a qr// is returned from the code executed by (??{$qr}) this
18647 lightweight copy doesn't actually own any of its data except for
18648 the starp/end and the actual regexp structure itself.
18654 Perl_reg_temp_copy (pTHX_ REGEXP *ret_x, REGEXP *rx)
18656 struct regexp *ret;
18657 struct regexp *const r = ReANY(rx);
18658 const bool islv = ret_x && SvTYPE(ret_x) == SVt_PVLV;
18660 PERL_ARGS_ASSERT_REG_TEMP_COPY;
18663 ret_x = (REGEXP*) newSV_type(SVt_REGEXP);
18665 SvOK_off((SV *)ret_x);
18667 /* For PVLVs, SvANY points to the xpvlv body while sv_u points
18668 to the regexp. (For SVt_REGEXPs, sv_upgrade has already
18669 made both spots point to the same regexp body.) */
18670 REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
18671 assert(!SvPVX(ret_x));
18672 ret_x->sv_u.svu_rx = temp->sv_any;
18673 temp->sv_any = NULL;
18674 SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
18675 SvREFCNT_dec_NN(temp);
18676 /* SvCUR still resides in the xpvlv struct, so the regexp copy-
18677 ing below will not set it. */
18678 SvCUR_set(ret_x, SvCUR(rx));
18681 /* This ensures that SvTHINKFIRST(sv) is true, and hence that
18682 sv_force_normal(sv) is called. */
18684 ret = ReANY(ret_x);
18686 SvFLAGS(ret_x) |= SvUTF8(rx);
18687 /* We share the same string buffer as the original regexp, on which we
18688 hold a reference count, incremented when mother_re is set below.
18689 The string pointer is copied here, being part of the regexp struct.
18691 memcpy(&(ret->xpv_cur), &(r->xpv_cur),
18692 sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
18694 const I32 npar = r->nparens+1;
18695 Newx(ret->offs, npar, regexp_paren_pair);
18696 Copy(r->offs, ret->offs, npar, regexp_paren_pair);
18699 Newx(ret->substrs, 1, struct reg_substr_data);
18700 StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
18702 SvREFCNT_inc_void(ret->anchored_substr);
18703 SvREFCNT_inc_void(ret->anchored_utf8);
18704 SvREFCNT_inc_void(ret->float_substr);
18705 SvREFCNT_inc_void(ret->float_utf8);
18707 /* check_substr and check_utf8, if non-NULL, point to either their
18708 anchored or float namesakes, and don't hold a second reference. */
18710 RX_MATCH_COPIED_off(ret_x);
18711 #ifdef PERL_ANY_COW
18712 ret->saved_copy = NULL;
18714 ret->mother_re = ReREFCNT_inc(r->mother_re ? r->mother_re : rx);
18715 SvREFCNT_inc_void(ret->qr_anoncv);
18721 /* regfree_internal()
18723 Free the private data in a regexp. This is overloadable by
18724 extensions. Perl takes care of the regexp structure in pregfree(),
18725 this covers the *pprivate pointer which technically perl doesn't
18726 know about, however of course we have to handle the
18727 regexp_internal structure when no extension is in use.
18729 Note this is called before freeing anything in the regexp
18734 Perl_regfree_internal(pTHX_ REGEXP * const rx)
18736 struct regexp *const r = ReANY(rx);
18737 RXi_GET_DECL(r,ri);
18738 GET_RE_DEBUG_FLAGS_DECL;
18740 PERL_ARGS_ASSERT_REGFREE_INTERNAL;
18746 SV *dsv= sv_newmortal();
18747 RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
18748 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), 60);
18749 PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n",
18750 PL_colors[4],PL_colors[5],s);
18753 #ifdef RE_TRACK_PATTERN_OFFSETS
18755 Safefree(ri->u.offsets); /* 20010421 MJD */
18757 if (ri->code_blocks) {
18759 for (n = 0; n < ri->num_code_blocks; n++)
18760 SvREFCNT_dec(ri->code_blocks[n].src_regex);
18761 Safefree(ri->code_blocks);
18765 int n = ri->data->count;
18768 /* If you add a ->what type here, update the comment in regcomp.h */
18769 switch (ri->data->what[n]) {
18775 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
18778 Safefree(ri->data->data[n]);
18784 { /* Aho Corasick add-on structure for a trie node.
18785 Used in stclass optimization only */
18787 reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
18788 #ifdef USE_ITHREADS
18792 refcount = --aho->refcount;
18795 PerlMemShared_free(aho->states);
18796 PerlMemShared_free(aho->fail);
18797 /* do this last!!!! */
18798 PerlMemShared_free(ri->data->data[n]);
18799 /* we should only ever get called once, so
18800 * assert as much, and also guard the free
18801 * which /might/ happen twice. At the least
18802 * it will make code anlyzers happy and it
18803 * doesn't cost much. - Yves */
18804 assert(ri->regstclass);
18805 if (ri->regstclass) {
18806 PerlMemShared_free(ri->regstclass);
18807 ri->regstclass = 0;
18814 /* trie structure. */
18816 reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
18817 #ifdef USE_ITHREADS
18821 refcount = --trie->refcount;
18824 PerlMemShared_free(trie->charmap);
18825 PerlMemShared_free(trie->states);
18826 PerlMemShared_free(trie->trans);
18828 PerlMemShared_free(trie->bitmap);
18830 PerlMemShared_free(trie->jump);
18831 PerlMemShared_free(trie->wordinfo);
18832 /* do this last!!!! */
18833 PerlMemShared_free(ri->data->data[n]);
18838 Perl_croak(aTHX_ "panic: regfree data code '%c'",
18839 ri->data->what[n]);
18842 Safefree(ri->data->what);
18843 Safefree(ri->data);
18849 #define av_dup_inc(s,t) MUTABLE_AV(sv_dup_inc((const SV *)s,t))
18850 #define hv_dup_inc(s,t) MUTABLE_HV(sv_dup_inc((const SV *)s,t))
18851 #define SAVEPVN(p,n) ((p) ? savepvn(p,n) : NULL)
18854 re_dup - duplicate a regexp.
18856 This routine is expected to clone a given regexp structure. It is only
18857 compiled under USE_ITHREADS.
18859 After all of the core data stored in struct regexp is duplicated
18860 the regexp_engine.dupe method is used to copy any private data
18861 stored in the *pprivate pointer. This allows extensions to handle
18862 any duplication it needs to do.
18864 See pregfree() and regfree_internal() if you change anything here.
18866 #if defined(USE_ITHREADS)
18867 #ifndef PERL_IN_XSUB_RE
18869 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
18873 const struct regexp *r = ReANY(sstr);
18874 struct regexp *ret = ReANY(dstr);
18876 PERL_ARGS_ASSERT_RE_DUP_GUTS;
18878 npar = r->nparens+1;
18879 Newx(ret->offs, npar, regexp_paren_pair);
18880 Copy(r->offs, ret->offs, npar, regexp_paren_pair);
18882 if (ret->substrs) {
18883 /* Do it this way to avoid reading from *r after the StructCopy().
18884 That way, if any of the sv_dup_inc()s dislodge *r from the L1
18885 cache, it doesn't matter. */
18886 const bool anchored = r->check_substr
18887 ? r->check_substr == r->anchored_substr
18888 : r->check_utf8 == r->anchored_utf8;
18889 Newx(ret->substrs, 1, struct reg_substr_data);
18890 StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
18892 ret->anchored_substr = sv_dup_inc(ret->anchored_substr, param);
18893 ret->anchored_utf8 = sv_dup_inc(ret->anchored_utf8, param);
18894 ret->float_substr = sv_dup_inc(ret->float_substr, param);
18895 ret->float_utf8 = sv_dup_inc(ret->float_utf8, param);
18897 /* check_substr and check_utf8, if non-NULL, point to either their
18898 anchored or float namesakes, and don't hold a second reference. */
18900 if (ret->check_substr) {
18902 assert(r->check_utf8 == r->anchored_utf8);
18903 ret->check_substr = ret->anchored_substr;
18904 ret->check_utf8 = ret->anchored_utf8;
18906 assert(r->check_substr == r->float_substr);
18907 assert(r->check_utf8 == r->float_utf8);
18908 ret->check_substr = ret->float_substr;
18909 ret->check_utf8 = ret->float_utf8;
18911 } else if (ret->check_utf8) {
18913 ret->check_utf8 = ret->anchored_utf8;
18915 ret->check_utf8 = ret->float_utf8;
18920 RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
18921 ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
18924 RXi_SET(ret,CALLREGDUPE_PVT(dstr,param));
18926 if (RX_MATCH_COPIED(dstr))
18927 ret->subbeg = SAVEPVN(ret->subbeg, ret->sublen);
18929 ret->subbeg = NULL;
18930 #ifdef PERL_ANY_COW
18931 ret->saved_copy = NULL;
18934 /* Whether mother_re be set or no, we need to copy the string. We
18935 cannot refrain from copying it when the storage points directly to
18936 our mother regexp, because that's
18937 1: a buffer in a different thread
18938 2: something we no longer hold a reference on
18939 so we need to copy it locally. */
18940 RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED(sstr), SvCUR(sstr)+1);
18941 ret->mother_re = NULL;
18943 #endif /* PERL_IN_XSUB_RE */
18948 This is the internal complement to regdupe() which is used to copy
18949 the structure pointed to by the *pprivate pointer in the regexp.
18950 This is the core version of the extension overridable cloning hook.
18951 The regexp structure being duplicated will be copied by perl prior
18952 to this and will be provided as the regexp *r argument, however
18953 with the /old/ structures pprivate pointer value. Thus this routine
18954 may override any copying normally done by perl.
18956 It returns a pointer to the new regexp_internal structure.
18960 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
18963 struct regexp *const r = ReANY(rx);
18964 regexp_internal *reti;
18966 RXi_GET_DECL(r,ri);
18968 PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
18972 Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode),
18973 char, regexp_internal);
18974 Copy(ri->program, reti->program, len+1, regnode);
18976 reti->num_code_blocks = ri->num_code_blocks;
18977 if (ri->code_blocks) {
18979 Newxc(reti->code_blocks, ri->num_code_blocks, struct reg_code_block,
18980 struct reg_code_block);
18981 Copy(ri->code_blocks, reti->code_blocks, ri->num_code_blocks,
18982 struct reg_code_block);
18983 for (n = 0; n < ri->num_code_blocks; n++)
18984 reti->code_blocks[n].src_regex = (REGEXP*)
18985 sv_dup_inc((SV*)(ri->code_blocks[n].src_regex), param);
18988 reti->code_blocks = NULL;
18990 reti->regstclass = NULL;
18993 struct reg_data *d;
18994 const int count = ri->data->count;
18997 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
18998 char, struct reg_data);
18999 Newx(d->what, count, U8);
19002 for (i = 0; i < count; i++) {
19003 d->what[i] = ri->data->what[i];
19004 switch (d->what[i]) {
19005 /* see also regcomp.h and regfree_internal() */
19006 case 'a': /* actually an AV, but the dup function is identical. */
19010 case 'u': /* actually an HV, but the dup function is identical. */
19011 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
19014 /* This is cheating. */
19015 Newx(d->data[i], 1, regnode_ssc);
19016 StructCopy(ri->data->data[i], d->data[i], regnode_ssc);
19017 reti->regstclass = (regnode*)d->data[i];
19020 /* Trie stclasses are readonly and can thus be shared
19021 * without duplication. We free the stclass in pregfree
19022 * when the corresponding reg_ac_data struct is freed.
19024 reti->regstclass= ri->regstclass;
19028 ((reg_trie_data*)ri->data->data[i])->refcount++;
19033 d->data[i] = ri->data->data[i];
19036 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'",
19037 ri->data->what[i]);
19046 reti->name_list_idx = ri->name_list_idx;
19048 #ifdef RE_TRACK_PATTERN_OFFSETS
19049 if (ri->u.offsets) {
19050 Newx(reti->u.offsets, 2*len+1, U32);
19051 Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
19054 SetProgLen(reti,len);
19057 return (void*)reti;
19060 #endif /* USE_ITHREADS */
19062 #ifndef PERL_IN_XSUB_RE
19065 - regnext - dig the "next" pointer out of a node
19068 Perl_regnext(pTHX_ regnode *p)
19075 if (OP(p) > REGNODE_MAX) { /* regnode.type is unsigned */
19076 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
19077 (int)OP(p), (int)REGNODE_MAX);
19080 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
19089 S_re_croak2(pTHX_ bool utf8, const char* pat1,const char* pat2,...)
19092 STRLEN l1 = strlen(pat1);
19093 STRLEN l2 = strlen(pat2);
19096 const char *message;
19098 PERL_ARGS_ASSERT_RE_CROAK2;
19104 Copy(pat1, buf, l1 , char);
19105 Copy(pat2, buf + l1, l2 , char);
19106 buf[l1 + l2] = '\n';
19107 buf[l1 + l2 + 1] = '\0';
19108 va_start(args, pat2);
19109 msv = vmess(buf, &args);
19111 message = SvPV_const(msv,l1);
19114 Copy(message, buf, l1 , char);
19115 /* l1-1 to avoid \n */
19116 Perl_croak(aTHX_ "%"UTF8f, UTF8fARG(utf8, l1-1, buf));
19119 /* XXX Here's a total kludge. But we need to re-enter for swash routines. */
19121 #ifndef PERL_IN_XSUB_RE
19123 Perl_save_re_context(pTHX)
19128 /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
19131 const REGEXP * const rx = PM_GETRE(PL_curpm);
19133 nparens = RX_NPARENS(rx);
19136 /* RT #124109. This is a complete hack; in the SWASHNEW case we know
19137 * that PL_curpm will be null, but that utf8.pm and the modules it
19138 * loads will only use $1..$3.
19139 * The t/porting/re_context.t test file checks this assumption.
19144 for (i = 1; i <= nparens; i++) {
19145 char digits[TYPE_CHARS(long)];
19146 const STRLEN len = my_snprintf(digits, sizeof(digits),
19148 GV *const *const gvp
19149 = (GV**)hv_fetch(PL_defstash, digits, len, 0);
19152 GV * const gv = *gvp;
19153 if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
19163 S_put_code_point(pTHX_ SV *sv, UV c)
19165 PERL_ARGS_ASSERT_PUT_CODE_POINT;
19168 Perl_sv_catpvf(aTHX_ sv, "\\x{%04"UVXf"}", c);
19170 else if (isPRINT(c)) {
19171 const char string = (char) c;
19172 if (isBACKSLASHED_PUNCT(c))
19173 sv_catpvs(sv, "\\");
19174 sv_catpvn(sv, &string, 1);
19177 const char * const mnemonic = cntrl_to_mnemonic((char) c);
19179 Perl_sv_catpvf(aTHX_ sv, "%s", mnemonic);
19182 Perl_sv_catpvf(aTHX_ sv, "\\x{%02X}", (U8) c);
19187 #define MAX_PRINT_A MAX_PRINT_A_FOR_USE_ONLY_BY_REGCOMP_DOT_C
19190 S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals)
19192 /* Appends to 'sv' a displayable version of the range of code points from
19193 * 'start' to 'end'. It assumes that only ASCII printables are displayable
19194 * as-is (though some of these will be escaped by put_code_point()). */
19196 const unsigned int min_range_count = 3;
19198 assert(start <= end);
19200 PERL_ARGS_ASSERT_PUT_RANGE;
19202 while (start <= end) {
19204 const char * format;
19206 if (end - start < min_range_count) {
19208 /* Individual chars in short ranges */
19209 for (; start <= end; start++) {
19210 put_code_point(sv, start);
19215 /* If permitted by the input options, and there is a possibility that
19216 * this range contains a printable literal, look to see if there is
19218 if (allow_literals && start <= MAX_PRINT_A) {
19220 /* If the range begin isn't an ASCII printable, effectively split
19221 * the range into two parts:
19222 * 1) the portion before the first such printable,
19224 * and output them separately. */
19225 if (! isPRINT_A(start)) {
19226 UV temp_end = start + 1;
19228 /* There is no point looking beyond the final possible
19229 * printable, in MAX_PRINT_A */
19230 UV max = MIN(end, MAX_PRINT_A);
19232 while (temp_end <= max && ! isPRINT_A(temp_end)) {
19236 /* Here, temp_end points to one beyond the first printable if
19237 * found, or to one beyond 'max' if not. If none found, make
19238 * sure that we use the entire range */
19239 if (temp_end > MAX_PRINT_A) {
19240 temp_end = end + 1;
19243 /* Output the first part of the split range, the part that
19244 * doesn't have printables, with no looking for literals
19245 * (otherwise we would infinitely recurse) */
19246 put_range(sv, start, temp_end - 1, FALSE);
19248 /* The 2nd part of the range (if any) starts here. */
19251 /* We continue instead of dropping down because even if the 2nd
19252 * part is non-empty, it could be so short that we want to
19253 * output it specially, as tested for at the top of this loop.
19258 /* Here, 'start' is a printable ASCII. If it is an alphanumeric,
19259 * output a sub-range of just the digits or letters, then process
19260 * the remaining portion as usual. */
19261 if (isALPHANUMERIC_A(start)) {
19262 UV mask = (isDIGIT_A(start))
19267 UV temp_end = start + 1;
19269 /* Find the end of the sub-range that includes just the
19270 * characters in the same class as the first character in it */
19271 while (temp_end <= end && _generic_isCC_A(temp_end, mask)) {
19276 /* For short ranges, don't duplicate the code above to output
19277 * them; just call recursively */
19278 if (temp_end - start < min_range_count) {
19279 put_range(sv, start, temp_end, FALSE);
19281 else { /* Output as a range */
19282 put_code_point(sv, start);
19283 sv_catpvs(sv, "-");
19284 put_code_point(sv, temp_end);
19286 start = temp_end + 1;
19290 /* We output any other printables as individual characters */
19291 if (isPUNCT_A(start) || isSPACE_A(start)) {
19292 while (start <= end && (isPUNCT_A(start)
19293 || isSPACE_A(start)))
19295 put_code_point(sv, start);
19300 } /* End of looking for literals */
19302 /* Here is not to output as a literal. Some control characters have
19303 * mnemonic names. Split off any of those at the beginning and end of
19304 * the range to print mnemonically. It isn't possible for many of
19305 * these to be in a row, so this won't overwhelm with output */
19306 while (isMNEMONIC_CNTRL(start) && start <= end) {
19307 put_code_point(sv, start);
19310 if (start < end && isMNEMONIC_CNTRL(end)) {
19312 /* Here, the final character in the range has a mnemonic name.
19313 * Work backwards from the end to find the final non-mnemonic */
19314 UV temp_end = end - 1;
19315 while (isMNEMONIC_CNTRL(temp_end)) {
19319 /* And separately output the range that doesn't have mnemonics */
19320 put_range(sv, start, temp_end, FALSE);
19322 /* Then output the mnemonic trailing controls */
19323 start = temp_end + 1;
19324 while (start <= end) {
19325 put_code_point(sv, start);
19331 /* As a final resort, output the range or subrange as hex. */
19333 this_end = (end < NUM_ANYOF_CODE_POINTS)
19335 : NUM_ANYOF_CODE_POINTS - 1;
19336 #if NUM_ANYOF_CODE_POINTS > 256
19337 format = (this_end < 256)
19338 ? "\\x{%02"UVXf"}-\\x{%02"UVXf"}"
19339 : "\\x{%04"UVXf"}-\\x{%04"UVXf"}";
19341 format = "\\x{%02"UVXf"}-\\x{%02"UVXf"}";
19343 GCC_DIAG_IGNORE(-Wformat-nonliteral);
19344 Perl_sv_catpvf(aTHX_ sv, format, start, this_end);
19351 S_put_charclass_bitmap_innards(pTHX_ SV *sv, char *bitmap, SV** bitmap_invlist)
19353 /* Appends to 'sv' a displayable version of the innards of the bracketed
19354 * character class whose bitmap is 'bitmap'; Returns 'TRUE' if it actually
19355 * output anything, and bitmap_invlist, if not NULL, will point to an
19356 * inversion list of what is in the bit map */
19360 unsigned int punct_count = 0;
19362 bool allow_literals = TRUE;
19363 bool inverted_for_output = FALSE;
19365 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS;
19367 /* Worst case is exactly every-other code point is in the list */
19368 invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2);
19370 /* Convert the bit map to an inversion list, keeping track of how many
19371 * ASCII puncts are set, including an extra amount for the backslashed
19373 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
19374 if (BITMAP_TEST(bitmap, i)) {
19375 invlist = add_cp_to_invlist(invlist, i);
19376 if (isPUNCT_A(i)) {
19378 if isBACKSLASHED_PUNCT(i) {
19385 /* Nothing to output */
19386 if (_invlist_len(invlist) == 0) {
19387 SvREFCNT_dec_NN(invlist);
19391 /* Generally, it is more readable if printable characters are output as
19392 * literals, but if a range (nearly) spans all of them, it's best to output
19393 * it as a single range. This code will use a single range if all but 2
19394 * printables are in it */
19395 invlist_iterinit(invlist);
19396 while (invlist_iternext(invlist, &start, &end)) {
19398 /* If range starts beyond final printable, it doesn't have any in it */
19399 if (start > MAX_PRINT_A) {
19403 /* In both ASCII and EBCDIC, a SPACE is the lowest printable. To span
19404 * all but two, the range must start and end no later than 2 from
19406 if (start < ' ' + 2 && end > MAX_PRINT_A - 2) {
19407 if (end > MAX_PRINT_A) {
19413 if (end - start >= MAX_PRINT_A - ' ' - 2) {
19414 allow_literals = FALSE;
19419 invlist_iterfinish(invlist);
19421 /* The legibility of the output depends mostly on how many punctuation
19422 * characters are output. There are 32 possible ASCII ones, and some have
19423 * an additional backslash, bringing it to currently 36, so if any more
19424 * than 18 are to be output, we can instead output it as its complement,
19425 * yielding fewer puncts, and making it more legible. But give some weight
19426 * to the fact that outputting it as a complement is less legible than a
19427 * straight output, so don't complement unless we are somewhat over the 18
19429 if (allow_literals && punct_count > 22) {
19430 sv_catpvs(sv, "^");
19432 /* Add everything remaining to the list, so when we invert it just
19433 * below, it will be excluded */
19434 _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
19435 _invlist_invert(invlist);
19436 inverted_for_output = TRUE;
19439 /* Here we have figured things out. Output each range */
19440 invlist_iterinit(invlist);
19441 while (invlist_iternext(invlist, &start, &end)) {
19442 if (start >= NUM_ANYOF_CODE_POINTS) {
19445 put_range(sv, start, end, allow_literals);
19447 invlist_iterfinish(invlist);
19449 if (bitmap_invlist) {
19451 /* Here, wants the inversion list returned. If we inverted it, we have
19452 * to restore it to the original */
19453 if (inverted_for_output) {
19454 _invlist_invert(invlist);
19455 _invlist_intersection(invlist, PL_InBitmap, &invlist);
19458 *bitmap_invlist = invlist;
19461 SvREFCNT_dec_NN(invlist);
19467 #define CLEAR_OPTSTART \
19468 if (optstart) STMT_START { \
19469 DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, \
19470 " (%"IVdf" nodes)\n", (IV)(node - optstart))); \
19474 #define DUMPUNTIL(b,e) \
19476 node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
19478 STATIC const regnode *
19479 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
19480 const regnode *last, const regnode *plast,
19481 SV* sv, I32 indent, U32 depth)
19483 U8 op = PSEUDO; /* Arbitrary non-END op. */
19484 const regnode *next;
19485 const regnode *optstart= NULL;
19487 RXi_GET_DECL(r,ri);
19488 GET_RE_DEBUG_FLAGS_DECL;
19490 PERL_ARGS_ASSERT_DUMPUNTIL;
19492 #ifdef DEBUG_DUMPUNTIL
19493 PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
19494 last ? last-start : 0,plast ? plast-start : 0);
19497 if (plast && plast < last)
19500 while (PL_regkind[op] != END && (!last || node < last)) {
19502 /* While that wasn't END last time... */
19505 if (op == CLOSE || op == WHILEM)
19507 next = regnext((regnode *)node);
19510 if (OP(node) == OPTIMIZED) {
19511 if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
19518 regprop(r, sv, node, NULL, NULL);
19519 PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
19520 (int)(2*indent + 1), "", SvPVX_const(sv));
19522 if (OP(node) != OPTIMIZED) {
19523 if (next == NULL) /* Next ptr. */
19524 PerlIO_printf(Perl_debug_log, " (0)");
19525 else if (PL_regkind[(U8)op] == BRANCH
19526 && PL_regkind[OP(next)] != BRANCH )
19527 PerlIO_printf(Perl_debug_log, " (FAIL)");
19529 PerlIO_printf(Perl_debug_log, " (%"IVdf")", (IV)(next - start));
19530 (void)PerlIO_putc(Perl_debug_log, '\n');
19534 if (PL_regkind[(U8)op] == BRANCHJ) {
19537 const regnode *nnode = (OP(next) == LONGJMP
19538 ? regnext((regnode *)next)
19540 if (last && nnode > last)
19542 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
19545 else if (PL_regkind[(U8)op] == BRANCH) {
19547 DUMPUNTIL(NEXTOPER(node), next);
19549 else if ( PL_regkind[(U8)op] == TRIE ) {
19550 const regnode *this_trie = node;
19551 const char op = OP(node);
19552 const U32 n = ARG(node);
19553 const reg_ac_data * const ac = op>=AHOCORASICK ?
19554 (reg_ac_data *)ri->data->data[n] :
19556 const reg_trie_data * const trie =
19557 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
19559 AV *const trie_words
19560 = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
19562 const regnode *nextbranch= NULL;
19565 for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
19566 SV ** const elem_ptr = av_fetch(trie_words,word_idx,0);
19568 PerlIO_printf(Perl_debug_log, "%*s%s ",
19569 (int)(2*(indent+3)), "",
19571 ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr),
19572 SvCUR(*elem_ptr), 60,
19573 PL_colors[0], PL_colors[1],
19575 ? PERL_PV_ESCAPE_UNI
19577 | PERL_PV_PRETTY_ELLIPSES
19578 | PERL_PV_PRETTY_LTGT
19583 U16 dist= trie->jump[word_idx+1];
19584 PerlIO_printf(Perl_debug_log, "(%"UVuf")\n",
19585 (UV)((dist ? this_trie + dist : next) - start));
19588 nextbranch= this_trie + trie->jump[0];
19589 DUMPUNTIL(this_trie + dist, nextbranch);
19591 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
19592 nextbranch= regnext((regnode *)nextbranch);
19594 PerlIO_printf(Perl_debug_log, "\n");
19597 if (last && next > last)
19602 else if ( op == CURLY ) { /* "next" might be very big: optimizer */
19603 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
19604 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
19606 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
19608 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
19610 else if ( op == PLUS || op == STAR) {
19611 DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
19613 else if (PL_regkind[(U8)op] == ANYOF) {
19614 /* arglen 1 + class block */
19615 node += 1 + ((ANYOF_FLAGS(node) & ANYOF_MATCHES_POSIXL)
19616 ? ANYOF_POSIXL_SKIP
19618 node = NEXTOPER(node);
19620 else if (PL_regkind[(U8)op] == EXACT) {
19621 /* Literal string, where present. */
19622 node += NODE_SZ_STR(node) - 1;
19623 node = NEXTOPER(node);
19626 node = NEXTOPER(node);
19627 node += regarglen[(U8)op];
19629 if (op == CURLYX || op == OPEN)
19633 #ifdef DEBUG_DUMPUNTIL
19634 PerlIO_printf(Perl_debug_log, "--- %d\n", (int)indent);
19639 #endif /* DEBUGGING */
19642 * ex: set ts=8 sts=4 sw=4 et: