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
78 #ifdef PERL_IN_XSUB_RE
80 EXTERN_C const struct regexp_engine my_reg_engine;
85 #include "dquote_inline.h"
86 #include "invlist_inline.h"
87 #include "unicode_constants.h"
89 #define HAS_NONLATIN1_FOLD_CLOSURE(i) \
90 _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
91 #define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
92 _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
93 #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
94 #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
100 /* this is a chain of data about sub patterns we are processing that
101 need to be handled separately/specially in study_chunk. Its so
102 we can simulate recursion without losing state. */
104 typedef struct scan_frame {
105 regnode *last_regnode; /* last node to process in this frame */
106 regnode *next_regnode; /* next node to process when last is reached */
107 U32 prev_recursed_depth;
108 I32 stopparen; /* what stopparen do we use */
110 struct scan_frame *this_prev_frame; /* this previous frame */
111 struct scan_frame *prev_frame; /* previous frame */
112 struct scan_frame *next_frame; /* next frame */
115 /* Certain characters are output as a sequence with the first being a
117 #define isBACKSLASHED_PUNCT(c) strchr("-[]\\^", c)
120 struct RExC_state_t {
121 U32 flags; /* RXf_* are we folding, multilining? */
122 U32 pm_flags; /* PMf_* stuff from the calling PMOP */
123 char *precomp; /* uncompiled string. */
124 char *precomp_end; /* pointer to end of uncompiled string. */
125 REGEXP *rx_sv; /* The SV that is the regexp. */
126 regexp *rx; /* perl core regexp structure */
127 regexp_internal *rxi; /* internal data for regexp object
129 char *start; /* Start of input for compile */
130 char *end; /* End of input for compile */
131 char *parse; /* Input-scan pointer. */
132 char *copy_start; /* start of copy of input within
133 constructed parse string */
134 char *copy_start_in_input; /* Position in input string
135 corresponding to copy_start */
136 SSize_t whilem_seen; /* number of WHILEM in this expr */
137 regnode *emit_start; /* Start of emitted-code area */
138 regnode_offset emit; /* Code-emit pointer */
139 I32 naughty; /* How bad is this pattern? */
140 I32 sawback; /* Did we see \1, ...? */
142 SSize_t size; /* Number of regnode equivalents in
145 /* position beyond 'precomp' of the warning message furthest away from
146 * 'precomp'. During the parse, no warnings are raised for any problems
147 * earlier in the parse than this position. This works if warnings are
148 * raised the first time a given spot is parsed, and if only one
149 * independent warning is raised for any given spot */
150 Size_t latest_warn_offset;
152 I32 npar; /* Capture buffer count so far in the
153 parse, (OPEN) plus one. ("par" 0 is
155 I32 total_par; /* During initial parse, is either 0,
156 or -1; the latter indicating a
157 reparse is needed. After that pass,
158 it is what 'npar' became after the
159 pass. Hence, it being > 0 indicates
160 we are in a reparse situation */
161 I32 nestroot; /* root parens we are in - used by
164 regnode_offset *open_parens; /* offsets to open parens */
165 regnode_offset *close_parens; /* offsets to close parens */
166 regnode *end_op; /* END node in program */
167 I32 utf8; /* whether the pattern is utf8 or not */
168 I32 orig_utf8; /* whether the pattern was originally in utf8 */
169 /* XXX use this for future optimisation of case
170 * where pattern must be upgraded to utf8. */
171 I32 uni_semantics; /* If a d charset modifier should use unicode
172 rules, even if the pattern is not in
174 HV *paren_names; /* Paren names */
176 regnode **recurse; /* Recurse regops */
177 I32 recurse_count; /* Number of recurse regops we have generated */
178 U8 *study_chunk_recursed; /* bitmap of which subs we have moved
180 U32 study_chunk_recursed_bytes; /* bytes in bitmap */
183 I32 override_recoding;
185 I32 recode_x_to_native;
187 I32 in_multi_char_class;
188 struct reg_code_blocks *code_blocks;/* positions of literal (?{})
190 int code_index; /* next code_blocks[] slot */
191 SSize_t maxlen; /* mininum possible number of chars in string to match */
192 scan_frame *frame_head;
193 scan_frame *frame_last;
196 #ifdef ADD_TO_REGEXEC
197 char *starttry; /* -Dr: where regtry was called. */
198 #define RExC_starttry (pRExC_state->starttry)
200 SV *runtime_code_qr; /* qr with the runtime code blocks */
202 const char *lastparse;
204 AV *paren_name_list; /* idx -> name */
205 U32 study_chunk_recursed_count;
209 #define RExC_lastparse (pRExC_state->lastparse)
210 #define RExC_lastnum (pRExC_state->lastnum)
211 #define RExC_paren_name_list (pRExC_state->paren_name_list)
212 #define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count)
213 #define RExC_mysv (pRExC_state->mysv1)
214 #define RExC_mysv1 (pRExC_state->mysv1)
215 #define RExC_mysv2 (pRExC_state->mysv2)
225 #define RExC_flags (pRExC_state->flags)
226 #define RExC_pm_flags (pRExC_state->pm_flags)
227 #define RExC_precomp (pRExC_state->precomp)
228 #define RExC_copy_start_in_input (pRExC_state->copy_start_in_input)
229 #define RExC_copy_start_in_constructed (pRExC_state->copy_start)
230 #define RExC_precomp_end (pRExC_state->precomp_end)
231 #define RExC_rx_sv (pRExC_state->rx_sv)
232 #define RExC_rx (pRExC_state->rx)
233 #define RExC_rxi (pRExC_state->rxi)
234 #define RExC_start (pRExC_state->start)
235 #define RExC_end (pRExC_state->end)
236 #define RExC_parse (pRExC_state->parse)
237 #define RExC_latest_warn_offset (pRExC_state->latest_warn_offset )
238 #define RExC_whilem_seen (pRExC_state->whilem_seen)
239 #define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs
240 under /d from /u ? */
243 #ifdef RE_TRACK_PATTERN_OFFSETS
244 # define RExC_offsets (RExC_rxi->u.offsets) /* I am not like the
247 #define RExC_emit (pRExC_state->emit)
248 #define RExC_emit_start (pRExC_state->emit_start)
249 #define RExC_sawback (pRExC_state->sawback)
250 #define RExC_seen (pRExC_state->seen)
251 #define RExC_size (pRExC_state->size)
252 #define RExC_maxlen (pRExC_state->maxlen)
253 #define RExC_npar (pRExC_state->npar)
254 #define RExC_total_parens (pRExC_state->total_par)
255 #define RExC_nestroot (pRExC_state->nestroot)
256 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
257 #define RExC_utf8 (pRExC_state->utf8)
258 #define RExC_uni_semantics (pRExC_state->uni_semantics)
259 #define RExC_orig_utf8 (pRExC_state->orig_utf8)
260 #define RExC_open_parens (pRExC_state->open_parens)
261 #define RExC_close_parens (pRExC_state->close_parens)
262 #define RExC_end_op (pRExC_state->end_op)
263 #define RExC_paren_names (pRExC_state->paren_names)
264 #define RExC_recurse (pRExC_state->recurse)
265 #define RExC_recurse_count (pRExC_state->recurse_count)
266 #define RExC_study_chunk_recursed (pRExC_state->study_chunk_recursed)
267 #define RExC_study_chunk_recursed_bytes \
268 (pRExC_state->study_chunk_recursed_bytes)
269 #define RExC_in_lookbehind (pRExC_state->in_lookbehind)
270 #define RExC_contains_locale (pRExC_state->contains_locale)
272 # define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
274 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
275 #define RExC_frame_head (pRExC_state->frame_head)
276 #define RExC_frame_last (pRExC_state->frame_last)
277 #define RExC_frame_count (pRExC_state->frame_count)
278 #define RExC_strict (pRExC_state->strict)
279 #define RExC_study_started (pRExC_state->study_started)
280 #define RExC_warn_text (pRExC_state->warn_text)
281 #define RExC_in_script_run (pRExC_state->in_script_run)
282 #define RExC_use_BRANCHJ (pRExC_state->use_BRANCHJ)
284 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
285 * a flag to disable back-off on the fixed/floating substrings - if it's
286 * a high complexity pattern we assume the benefit of avoiding a full match
287 * is worth the cost of checking for the substrings even if they rarely help.
289 #define RExC_naughty (pRExC_state->naughty)
290 #define TOO_NAUGHTY (10)
291 #define MARK_NAUGHTY(add) \
292 if (RExC_naughty < TOO_NAUGHTY) \
293 RExC_naughty += (add)
294 #define MARK_NAUGHTY_EXP(exp, add) \
295 if (RExC_naughty < TOO_NAUGHTY) \
296 RExC_naughty += RExC_naughty / (exp) + (add)
298 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
299 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
300 ((*s) == '{' && regcurly(s)))
303 * Flags to be passed up and down.
305 #define WORST 0 /* Worst case. */
306 #define HASWIDTH 0x01 /* Known to not match null strings, could match
309 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
310 * character. (There needs to be a case: in the switch statement in regexec.c
311 * for any node marked SIMPLE.) Note that this is not the same thing as
314 #define SPSTART 0x04 /* Starts with * or + */
315 #define POSTPONED 0x08 /* (?1),(?&name), (??{...}) or similar */
316 #define TRYAGAIN 0x10 /* Weeded out a declaration. */
317 #define RESTART_PARSE 0x20 /* Need to redo the parse */
318 #define NEED_UTF8 0x40 /* In conjunction with RESTART_PARSE, need to
319 calcuate sizes as UTF-8 */
321 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
323 /* whether trie related optimizations are enabled */
324 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
325 #define TRIE_STUDY_OPT
326 #define FULL_TRIE_STUDY
332 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
333 #define PBITVAL(paren) (1 << ((paren) & 7))
334 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
335 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
336 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
338 #define REQUIRE_UTF8(flagp) STMT_START { \
340 *flagp = RESTART_PARSE|NEED_UTF8; \
345 /* Change from /d into /u rules, and restart the parse. RExC_uni_semantics is
346 * a flag that indicates we need to override /d with /u as a result of
347 * something in the pattern. It should only be used in regards to calling
348 * set_regex_charset() or get_regex_charse() */
349 #define REQUIRE_UNI_RULES(flagp, restart_retval) \
351 if (DEPENDS_SEMANTICS) { \
352 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); \
353 RExC_uni_semantics = 1; \
354 if (RExC_seen_d_op && LIKELY(RExC_total_parens >= 0)) { \
355 /* No need to restart the parse if we haven't seen \
356 * anything that differs between /u and /d, and no need \
357 * to restart immediately if we're going to reparse \
358 * anyway to count parens */ \
359 *flagp |= RESTART_PARSE; \
360 return restart_retval; \
365 #define BRANCH_MAX_OFFSET U16_MAX
366 #define REQUIRE_BRANCHJ(flagp, restart_retval) \
368 RExC_use_BRANCHJ = 1; \
369 if (LIKELY(RExC_total_parens >= 0)) { \
370 /* No need to restart the parse immediately if we're \
371 * going to reparse anyway to count parens */ \
372 *flagp |= RESTART_PARSE; \
373 return restart_retval; \
377 #define REQUIRE_PARENS_PASS \
379 if (RExC_total_parens == 0) RExC_total_parens = -1; \
382 /* This is used to return failure (zero) early from the calling function if
383 * various flags in 'flags' are set. Two flags always cause a return:
384 * 'RESTART_PARSE' and 'NEED_UTF8'. 'extra' can be used to specify any
385 * additional flags that should cause a return; 0 if none. If the return will
386 * be done, '*flagp' is first set to be all of the flags that caused the
388 #define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra) \
390 if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) { \
391 *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra)); \
396 #define MUST_RESTART(flags) ((flags) & (RESTART_PARSE))
398 #define RETURN_FAIL_ON_RESTART(flags,flagp) \
399 RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0)
400 #define RETURN_FAIL_ON_RESTART_FLAGP(flagp) \
401 if (MUST_RESTART(*(flagp))) return 0
403 /* This converts the named class defined in regcomp.h to its equivalent class
404 * number defined in handy.h. */
405 #define namedclass_to_classnum(class) ((int) ((class) / 2))
406 #define classnum_to_namedclass(classnum) ((classnum) * 2)
408 #define _invlist_union_complement_2nd(a, b, output) \
409 _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
410 #define _invlist_intersection_complement_2nd(a, b, output) \
411 _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
413 /* About scan_data_t.
415 During optimisation we recurse through the regexp program performing
416 various inplace (keyhole style) optimisations. In addition study_chunk
417 and scan_commit populate this data structure with information about
418 what strings MUST appear in the pattern. We look for the longest
419 string that must appear at a fixed location, and we look for the
420 longest string that may appear at a floating location. So for instance
425 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
426 strings (because they follow a .* construct). study_chunk will identify
427 both FOO and BAR as being the longest fixed and floating strings respectively.
429 The strings can be composites, for instance
433 will result in a composite fixed substring 'foo'.
435 For each string some basic information is maintained:
438 This is the position the string must appear at, or not before.
439 It also implicitly (when combined with minlenp) tells us how many
440 characters must match before the string we are searching for.
441 Likewise when combined with minlenp and the length of the string it
442 tells us how many characters must appear after the string we have
446 Only used for floating strings. This is the rightmost point that
447 the string can appear at. If set to SSize_t_MAX it indicates that the
448 string can occur infinitely far to the right.
449 For fixed strings, it is equal to min_offset.
452 A pointer to the minimum number of characters of the pattern that the
453 string was found inside. This is important as in the case of positive
454 lookahead or positive lookbehind we can have multiple patterns
459 The minimum length of the pattern overall is 3, the minimum length
460 of the lookahead part is 3, but the minimum length of the part that
461 will actually match is 1. So 'FOO's minimum length is 3, but the
462 minimum length for the F is 1. This is important as the minimum length
463 is used to determine offsets in front of and behind the string being
464 looked for. Since strings can be composites this is the length of the
465 pattern at the time it was committed with a scan_commit. Note that
466 the length is calculated by study_chunk, so that the minimum lengths
467 are not known until the full pattern has been compiled, thus the
468 pointer to the value.
472 In the case of lookbehind the string being searched for can be
473 offset past the start point of the final matching string.
474 If this value was just blithely removed from the min_offset it would
475 invalidate some of the calculations for how many chars must match
476 before or after (as they are derived from min_offset and minlen and
477 the length of the string being searched for).
478 When the final pattern is compiled and the data is moved from the
479 scan_data_t structure into the regexp structure the information
480 about lookbehind is factored in, with the information that would
481 have been lost precalculated in the end_shift field for the
484 The fields pos_min and pos_delta are used to store the minimum offset
485 and the delta to the maximum offset at the current point in the pattern.
489 struct scan_data_substrs {
490 SV *str; /* longest substring found in pattern */
491 SSize_t min_offset; /* earliest point in string it can appear */
492 SSize_t max_offset; /* latest point in string it can appear */
493 SSize_t *minlenp; /* pointer to the minlen relevant to the string */
494 SSize_t lookbehind; /* is the pos of the string modified by LB */
495 I32 flags; /* per substring SF_* and SCF_* flags */
498 typedef struct scan_data_t {
499 /*I32 len_min; unused */
500 /*I32 len_delta; unused */
504 SSize_t last_end; /* min value, <0 unless valid. */
505 SSize_t last_start_min;
506 SSize_t last_start_max;
507 U8 cur_is_floating; /* whether the last_* values should be set as
508 * the next fixed (0) or floating (1)
511 /* [0] is longest fixed substring so far, [1] is longest float so far */
512 struct scan_data_substrs substrs[2];
514 I32 flags; /* common SF_* and SCF_* flags */
516 SSize_t *last_closep;
517 regnode_ssc *start_class;
521 * Forward declarations for pregcomp()'s friends.
524 static const scan_data_t zero_scan_data = {
525 0, 0, NULL, 0, 0, 0, 0,
527 { NULL, 0, 0, 0, 0, 0 },
528 { NULL, 0, 0, 0, 0, 0 },
535 #define SF_BEFORE_SEOL 0x0001
536 #define SF_BEFORE_MEOL 0x0002
537 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
539 #define SF_IS_INF 0x0040
540 #define SF_HAS_PAR 0x0080
541 #define SF_IN_PAR 0x0100
542 #define SF_HAS_EVAL 0x0200
545 /* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
546 * longest substring in the pattern. When it is not set the optimiser keeps
547 * track of position, but does not keep track of the actual strings seen,
549 * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
552 * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
553 * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
554 * turned off because of the alternation (BRANCH). */
555 #define SCF_DO_SUBSTR 0x0400
557 #define SCF_DO_STCLASS_AND 0x0800
558 #define SCF_DO_STCLASS_OR 0x1000
559 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
560 #define SCF_WHILEM_VISITED_POS 0x2000
562 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
563 #define SCF_SEEN_ACCEPT 0x8000
564 #define SCF_TRIE_DOING_RESTUDY 0x10000
565 #define SCF_IN_DEFINE 0x20000
570 #define UTF cBOOL(RExC_utf8)
572 /* The enums for all these are ordered so things work out correctly */
573 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
574 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) \
575 == REGEX_DEPENDS_CHARSET)
576 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
577 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) \
578 >= REGEX_UNICODE_CHARSET)
579 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
580 == REGEX_ASCII_RESTRICTED_CHARSET)
581 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
582 >= REGEX_ASCII_RESTRICTED_CHARSET)
583 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) \
584 == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
586 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
588 /* For programs that want to be strictly Unicode compatible by dying if any
589 * attempt is made to match a non-Unicode code point against a Unicode
591 #define ALWAYS_WARN_SUPER ckDEAD(packWARN(WARN_NON_UNICODE))
593 #define OOB_NAMEDCLASS -1
595 /* There is no code point that is out-of-bounds, so this is problematic. But
596 * its only current use is to initialize a variable that is always set before
598 #define OOB_UNICODE 0xDEADBEEF
600 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
603 /* length of regex to show in messages that don't mark a position within */
604 #define RegexLengthToShowInErrorMessages 127
607 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
608 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
609 * op/pragma/warn/regcomp.
611 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
612 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
614 #define REPORT_LOCATION " in regex; marked by " MARKER1 \
615 " in m/%" UTF8f MARKER2 "%" UTF8f "/"
617 /* The code in this file in places uses one level of recursion with parsing
618 * rebased to an alternate string constructed by us in memory. This can take
619 * the form of something that is completely different from the input, or
620 * something that uses the input as part of the alternate. In the first case,
621 * there should be no possibility of an error, as we are in complete control of
622 * the alternate string. But in the second case we don't completely control
623 * the input portion, so there may be errors in that. Here's an example:
625 * is handled specially because \x{df} folds to a sequence of more than one
626 * character: 'ss'. What is done is to create and parse an alternate string,
627 * which looks like this:
628 * /(?:\x{DF}|[abc\x{DF}def])/ui
629 * where it uses the input unchanged in the middle of something it constructs,
630 * which is a branch for the DF outside the character class, and clustering
631 * parens around the whole thing. (It knows enough to skip the DF inside the
632 * class while in this substitute parse.) 'abc' and 'def' may have errors that
633 * need to be reported. The general situation looks like this:
635 * |<------- identical ------>|
637 * Input: ---------------------------------------------------------------
638 * Constructed: ---------------------------------------------------
640 * |<------- identical ------>|
642 * sI..eI is the portion of the input pattern we are concerned with here.
643 * sC..EC is the constructed substitute parse string.
644 * sC..tC is constructed by us
645 * tC..eC is an exact duplicate of the portion of the input pattern tI..eI.
646 * In the diagram, these are vertically aligned.
647 * eC..EC is also constructed by us.
648 * xC is the position in the substitute parse string where we found a
650 * xI is the position in the original pattern corresponding to xC.
652 * We want to display a message showing the real input string. Thus we need to
653 * translate from xC to xI. We know that xC >= tC, since the portion of the
654 * string sC..tC has been constructed by us, and so shouldn't have errors. We
656 * xI = tI + (xC - tC)
658 * When the substitute parse is constructed, the code needs to set:
661 * RExC_copy_start_in_input (tI)
662 * RExC_copy_start_in_constructed (tC)
663 * and restore them when done.
665 * During normal processing of the input pattern, both
666 * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to
667 * sI, so that xC equals xI.
670 #define sI RExC_precomp
671 #define eI RExC_precomp_end
672 #define sC RExC_start
674 #define tI RExC_copy_start_in_input
675 #define tC RExC_copy_start_in_constructed
676 #define xI(xC) (tI + (xC - tC))
677 #define xI_offset(xC) (xI(xC) - sI)
679 #define REPORT_LOCATION_ARGS(xC) \
681 (xI(xC) > eI) /* Don't run off end */ \
682 ? eI - sI /* Length before the <--HERE */ \
683 : ((xI_offset(xC) >= 0) \
685 : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %" \
686 IVdf " trying to output message for " \
688 __FILE__, __LINE__, (IV) xI_offset(xC), \
689 ((int) (eC - sC)), sC), 0)), \
690 sI), /* The input pattern printed up to the <--HERE */ \
692 (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */ \
693 (xI(xC) > eI) ? eI : xI(xC)) /* pattern after <--HERE */
695 /* Used to point after bad bytes for an error message, but avoid skipping
696 * past a nul byte. */
697 #define SKIP_IF_CHAR(s) (!*(s) ? 0 : UTF ? UTF8SKIP(s) : 1)
699 /* Set up to clean up after our imminent demise */
700 #define PREPARE_TO_DIE \
703 SAVEFREESV(RExC_rx_sv); \
704 if (RExC_open_parens) \
705 SAVEFREEPV(RExC_open_parens); \
706 if (RExC_close_parens) \
707 SAVEFREEPV(RExC_close_parens); \
711 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
712 * arg. Show regex, up to a maximum length. If it's too long, chop and add
715 #define _FAIL(code) STMT_START { \
716 const char *ellipses = ""; \
717 IV len = RExC_precomp_end - RExC_precomp; \
720 if (len > RegexLengthToShowInErrorMessages) { \
721 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
722 len = RegexLengthToShowInErrorMessages - 10; \
728 #define FAIL(msg) _FAIL( \
729 Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/", \
730 msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
732 #define FAIL2(msg,arg) _FAIL( \
733 Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \
734 arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
737 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
739 #define Simple_vFAIL(m) STMT_START { \
740 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
741 m, REPORT_LOCATION_ARGS(RExC_parse)); \
745 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
747 #define vFAIL(m) STMT_START { \
753 * Like Simple_vFAIL(), but accepts two arguments.
755 #define Simple_vFAIL2(m,a1) STMT_START { \
756 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
757 REPORT_LOCATION_ARGS(RExC_parse)); \
761 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
763 #define vFAIL2(m,a1) STMT_START { \
765 Simple_vFAIL2(m, a1); \
770 * Like Simple_vFAIL(), but accepts three arguments.
772 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
773 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
774 REPORT_LOCATION_ARGS(RExC_parse)); \
778 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
780 #define vFAIL3(m,a1,a2) STMT_START { \
782 Simple_vFAIL3(m, a1, a2); \
786 * Like Simple_vFAIL(), but accepts four arguments.
788 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
789 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3, \
790 REPORT_LOCATION_ARGS(RExC_parse)); \
793 #define vFAIL4(m,a1,a2,a3) STMT_START { \
795 Simple_vFAIL4(m, a1, a2, a3); \
798 /* A specialized version of vFAIL2 that works with UTF8f */
799 #define vFAIL2utf8f(m, a1) STMT_START { \
801 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
802 REPORT_LOCATION_ARGS(RExC_parse)); \
805 #define vFAIL3utf8f(m, a1, a2) STMT_START { \
807 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
808 REPORT_LOCATION_ARGS(RExC_parse)); \
811 /* Setting this to NULL is a signal to not output warnings */
812 #define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE RExC_copy_start_in_constructed = NULL
813 #define RESTORE_WARNINGS RExC_copy_start_in_constructed = RExC_precomp
815 /* Since a warning can be generated multiple times as the input is reparsed, we
816 * output it the first time we come to that point in the parse, but suppress it
817 * otherwise. 'RExC_copy_start_in_constructed' being NULL is a flag to not
818 * generate any warnings */
819 #define TO_OUTPUT_WARNINGS(loc) \
820 ( RExC_copy_start_in_constructed \
821 && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset)
823 /* After we've emitted a warning, we save the position in the input so we don't
825 #define UPDATE_WARNINGS_LOC(loc) \
827 if (TO_OUTPUT_WARNINGS(loc)) { \
828 RExC_latest_warn_offset = (xI(loc)) - RExC_precomp; \
832 /* 'warns' is the output of the packWARNx macro used in 'code' */
833 #define _WARN_HELPER(loc, warns, code) \
835 if (! RExC_copy_start_in_constructed) { \
836 Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none" \
837 " expected at '%s'", \
838 __FILE__, __LINE__, loc); \
840 if (TO_OUTPUT_WARNINGS(loc)) { \
844 UPDATE_WARNINGS_LOC(loc); \
848 /* m is not necessarily a "literal string", in this macro */
849 #define reg_warn_non_literal_string(loc, m) \
850 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
851 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
852 "%s" REPORT_LOCATION, \
853 m, REPORT_LOCATION_ARGS(loc)))
855 #define ckWARNreg(loc,m) \
856 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
857 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
859 REPORT_LOCATION_ARGS(loc)))
861 #define vWARN(loc, m) \
862 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
863 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
865 REPORT_LOCATION_ARGS(loc))) \
867 #define vWARN_dep(loc, m) \
868 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
869 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), \
871 REPORT_LOCATION_ARGS(loc)))
873 #define ckWARNdep(loc,m) \
874 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
875 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
877 REPORT_LOCATION_ARGS(loc)))
879 #define ckWARNregdep(loc,m) \
880 _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
881 Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, \
884 REPORT_LOCATION_ARGS(loc)))
886 #define ckWARN2reg_d(loc,m, a1) \
887 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
888 Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP), \
890 a1, REPORT_LOCATION_ARGS(loc)))
892 #define ckWARN2reg(loc, m, a1) \
893 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
894 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
896 a1, REPORT_LOCATION_ARGS(loc)))
898 #define vWARN3(loc, m, a1, a2) \
899 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
900 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
902 a1, a2, REPORT_LOCATION_ARGS(loc)))
904 #define ckWARN3reg(loc, m, a1, a2) \
905 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
906 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
909 REPORT_LOCATION_ARGS(loc)))
911 #define vWARN4(loc, m, a1, a2, a3) \
912 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
913 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
916 REPORT_LOCATION_ARGS(loc)))
918 #define ckWARN4reg(loc, m, a1, a2, a3) \
919 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
920 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
923 REPORT_LOCATION_ARGS(loc)))
925 #define vWARN5(loc, m, a1, a2, a3, a4) \
926 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
927 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
930 REPORT_LOCATION_ARGS(loc)))
932 #define ckWARNexperimental(loc, class, m) \
933 _WARN_HELPER(loc, packWARN(class), \
934 Perl_ck_warner_d(aTHX_ packWARN(class), \
936 REPORT_LOCATION_ARGS(loc)))
938 /* Convert between a pointer to a node and its offset from the beginning of the
940 #define REGNODE_p(offset) (RExC_emit_start + (offset))
941 #define REGNODE_OFFSET(node) ((node) - RExC_emit_start)
943 /* Macros for recording node offsets. 20001227 mjd@plover.com
944 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
945 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
946 * Element 0 holds the number n.
947 * Position is 1 indexed.
949 #ifndef RE_TRACK_PATTERN_OFFSETS
950 #define Set_Node_Offset_To_R(offset,byte)
951 #define Set_Node_Offset(node,byte)
952 #define Set_Cur_Node_Offset
953 #define Set_Node_Length_To_R(node,len)
954 #define Set_Node_Length(node,len)
955 #define Set_Node_Cur_Length(node,start)
956 #define Node_Offset(n)
957 #define Node_Length(n)
958 #define Set_Node_Offset_Length(node,offset,len)
959 #define ProgLen(ri) ri->u.proglen
960 #define SetProgLen(ri,x) ri->u.proglen = x
961 #define Track_Code(code)
963 #define ProgLen(ri) ri->u.offsets[0]
964 #define SetProgLen(ri,x) ri->u.offsets[0] = x
965 #define Set_Node_Offset_To_R(offset,byte) STMT_START { \
966 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
967 __LINE__, (int)(offset), (int)(byte))); \
969 Perl_croak(aTHX_ "value of node is %d in Offset macro", \
972 RExC_offsets[2*(offset)-1] = (byte); \
976 #define Set_Node_Offset(node,byte) \
977 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start)
978 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
980 #define Set_Node_Length_To_R(node,len) STMT_START { \
981 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
982 __LINE__, (int)(node), (int)(len))); \
984 Perl_croak(aTHX_ "value of node is %d in Length macro", \
987 RExC_offsets[2*(node)] = (len); \
991 #define Set_Node_Length(node,len) \
992 Set_Node_Length_To_R(REGNODE_OFFSET(node), len)
993 #define Set_Node_Cur_Length(node, start) \
994 Set_Node_Length(node, RExC_parse - start)
996 /* Get offsets and lengths */
997 #define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1])
998 #define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))])
1000 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
1001 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset)); \
1002 Set_Node_Length_To_R(REGNODE_OFFSET(node), (len)); \
1005 #define Track_Code(code) STMT_START { code } STMT_END
1008 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
1009 #define EXPERIMENTAL_INPLACESCAN
1010 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
1014 Perl_re_printf(pTHX_ const char *fmt, ...)
1018 PerlIO *f= Perl_debug_log;
1019 PERL_ARGS_ASSERT_RE_PRINTF;
1021 result = PerlIO_vprintf(f, fmt, ap);
1027 Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
1031 PerlIO *f= Perl_debug_log;
1032 PERL_ARGS_ASSERT_RE_INDENTF;
1033 va_start(ap, depth);
1034 PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
1035 result = PerlIO_vprintf(f, fmt, ap);
1039 #endif /* DEBUGGING */
1041 #define DEBUG_RExC_seen() \
1042 DEBUG_OPTIMISE_MORE_r({ \
1043 Perl_re_printf( aTHX_ "RExC_seen: "); \
1045 if (RExC_seen & REG_ZERO_LEN_SEEN) \
1046 Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN "); \
1048 if (RExC_seen & REG_LOOKBEHIND_SEEN) \
1049 Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN "); \
1051 if (RExC_seen & REG_GPOS_SEEN) \
1052 Perl_re_printf( aTHX_ "REG_GPOS_SEEN "); \
1054 if (RExC_seen & REG_RECURSE_SEEN) \
1055 Perl_re_printf( aTHX_ "REG_RECURSE_SEEN "); \
1057 if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN) \
1058 Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN "); \
1060 if (RExC_seen & REG_VERBARG_SEEN) \
1061 Perl_re_printf( aTHX_ "REG_VERBARG_SEEN "); \
1063 if (RExC_seen & REG_CUTGROUP_SEEN) \
1064 Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN "); \
1066 if (RExC_seen & REG_RUN_ON_COMMENT_SEEN) \
1067 Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN "); \
1069 if (RExC_seen & REG_UNFOLDED_MULTI_SEEN) \
1070 Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN "); \
1072 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) \
1073 Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN "); \
1075 Perl_re_printf( aTHX_ "\n"); \
1078 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
1079 if ((flags) & flag) Perl_re_printf( aTHX_ "%s ", #flag)
1084 S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
1085 const char *close_str)
1090 Perl_re_printf( aTHX_ "%s", open_str);
1091 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
1092 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
1093 DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
1094 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
1095 DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
1096 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
1097 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
1098 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
1099 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
1100 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
1101 DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
1102 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
1103 DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
1104 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
1105 DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
1106 Perl_re_printf( aTHX_ "%s", close_str);
1111 S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
1112 U32 depth, int is_inf)
1114 GET_RE_DEBUG_FLAGS_DECL;
1116 DEBUG_OPTIMISE_MORE_r({
1119 Perl_re_indentf(aTHX_ "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
1123 (IV)data->pos_delta,
1127 S_debug_show_study_flags(aTHX_ data->flags," [","]");
1129 Perl_re_printf( aTHX_
1130 " Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
1132 (IV)(data->last_closep ? *((data)->last_closep) : -1),
1133 is_inf ? "INF " : ""
1136 if (data->last_found) {
1138 Perl_re_printf(aTHX_
1139 "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
1140 SvPVX_const(data->last_found),
1142 (IV)data->last_start_min,
1143 (IV)data->last_start_max
1146 for (i = 0; i < 2; i++) {
1147 Perl_re_printf(aTHX_
1148 " %s%s: '%s' @ %" IVdf "/%" IVdf,
1149 data->cur_is_floating == i ? "*" : "",
1150 i ? "Float" : "Fixed",
1151 SvPVX_const(data->substrs[i].str),
1152 (IV)data->substrs[i].min_offset,
1153 (IV)data->substrs[i].max_offset
1155 S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
1159 Perl_re_printf( aTHX_ "\n");
1165 S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
1166 regnode *scan, U32 depth, U32 flags)
1168 GET_RE_DEBUG_FLAGS_DECL;
1175 Next = regnext(scan);
1176 regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
1177 Perl_re_indentf( aTHX_ "%s>%3d: %s (%d)",
1180 REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
1181 Next ? (REG_NODE_NUM(Next)) : 0 );
1182 S_debug_show_study_flags(aTHX_ flags," [ ","]");
1183 Perl_re_printf( aTHX_ "\n");
1188 # define DEBUG_STUDYDATA(where, data, depth, is_inf) \
1189 S_debug_studydata(aTHX_ where, data, depth, is_inf)
1191 # define DEBUG_PEEP(str, scan, depth, flags) \
1192 S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
1195 # define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
1196 # define DEBUG_PEEP(str, scan, depth, flags) NOOP
1200 /* =========================================================
1201 * BEGIN edit_distance stuff.
1203 * This calculates how many single character changes of any type are needed to
1204 * transform a string into another one. It is taken from version 3.1 of
1206 * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1209 /* Our unsorted dictionary linked list. */
1210 /* Note we use UVs, not chars. */
1215 struct dictionary* next;
1217 typedef struct dictionary item;
1220 PERL_STATIC_INLINE item*
1221 push(UV key, item* curr)
1224 Newx(head, 1, item);
1232 PERL_STATIC_INLINE item*
1233 find(item* head, UV key)
1235 item* iterator = head;
1237 if (iterator->key == key){
1240 iterator = iterator->next;
1246 PERL_STATIC_INLINE item*
1247 uniquePush(item* head, UV key)
1249 item* iterator = head;
1252 if (iterator->key == key) {
1255 iterator = iterator->next;
1258 return push(key, head);
1261 PERL_STATIC_INLINE void
1262 dict_free(item* head)
1264 item* iterator = head;
1267 item* temp = iterator;
1268 iterator = iterator->next;
1275 /* End of Dictionary Stuff */
1277 /* All calculations/work are done here */
1279 S_edit_distance(const UV* src,
1281 const STRLEN x, /* length of src[] */
1282 const STRLEN y, /* length of tgt[] */
1283 const SSize_t maxDistance
1287 UV swapCount, swapScore, targetCharCount, i, j;
1289 UV score_ceil = x + y;
1291 PERL_ARGS_ASSERT_EDIT_DISTANCE;
1293 /* intialize matrix start values */
1294 Newx(scores, ( (x + 2) * (y + 2)), UV);
1295 scores[0] = score_ceil;
1296 scores[1 * (y + 2) + 0] = score_ceil;
1297 scores[0 * (y + 2) + 1] = score_ceil;
1298 scores[1 * (y + 2) + 1] = 0;
1299 head = uniquePush(uniquePush(head, src[0]), tgt[0]);
1304 for (i=1;i<=x;i++) {
1306 head = uniquePush(head, src[i]);
1307 scores[(i+1) * (y + 2) + 1] = i;
1308 scores[(i+1) * (y + 2) + 0] = score_ceil;
1311 for (j=1;j<=y;j++) {
1314 head = uniquePush(head, tgt[j]);
1315 scores[1 * (y + 2) + (j + 1)] = j;
1316 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1319 targetCharCount = find(head, tgt[j-1])->value;
1320 swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1322 if (src[i-1] != tgt[j-1]){
1323 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));
1327 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1331 find(head, src[i-1])->value = i;
1335 IV score = scores[(x+1) * (y + 2) + (y + 1)];
1338 return (maxDistance != 0 && maxDistance < score)?(-1):score;
1342 /* END of edit_distance() stuff
1343 * ========================================================= */
1345 /* is c a control character for which we have a mnemonic? */
1346 #define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
1349 S_cntrl_to_mnemonic(const U8 c)
1351 /* Returns the mnemonic string that represents character 'c', if one
1352 * exists; NULL otherwise. The only ones that exist for the purposes of
1353 * this routine are a few control characters */
1356 case '\a': return "\\a";
1357 case '\b': return "\\b";
1358 case ESC_NATIVE: return "\\e";
1359 case '\f': return "\\f";
1360 case '\n': return "\\n";
1361 case '\r': return "\\r";
1362 case '\t': return "\\t";
1368 /* Mark that we cannot extend a found fixed substring at this point.
1369 Update the longest found anchored substring or the longest found
1370 floating substrings if needed. */
1373 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1374 SSize_t *minlenp, int is_inf)
1376 const STRLEN l = CHR_SVLEN(data->last_found);
1377 SV * const longest_sv = data->substrs[data->cur_is_floating].str;
1378 const STRLEN old_l = CHR_SVLEN(longest_sv);
1379 GET_RE_DEBUG_FLAGS_DECL;
1381 PERL_ARGS_ASSERT_SCAN_COMMIT;
1383 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1384 const U8 i = data->cur_is_floating;
1385 SvSetMagicSV(longest_sv, data->last_found);
1386 data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
1389 data->substrs[0].max_offset = data->substrs[0].min_offset;
1391 data->substrs[1].max_offset = (l
1392 ? data->last_start_max
1393 : (data->pos_delta > SSize_t_MAX - data->pos_min
1395 : data->pos_min + data->pos_delta));
1397 || (STRLEN)data->substrs[1].max_offset > (STRLEN)SSize_t_MAX)
1398 data->substrs[1].max_offset = SSize_t_MAX;
1401 if (data->flags & SF_BEFORE_EOL)
1402 data->substrs[i].flags |= (data->flags & SF_BEFORE_EOL);
1404 data->substrs[i].flags &= ~SF_BEFORE_EOL;
1405 data->substrs[i].minlenp = minlenp;
1406 data->substrs[i].lookbehind = 0;
1409 SvCUR_set(data->last_found, 0);
1411 SV * const sv = data->last_found;
1412 if (SvUTF8(sv) && SvMAGICAL(sv)) {
1413 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1418 data->last_end = -1;
1419 data->flags &= ~SF_BEFORE_EOL;
1420 DEBUG_STUDYDATA("commit", data, 0, is_inf);
1423 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1424 * list that describes which code points it matches */
1427 S_ssc_anything(pTHX_ regnode_ssc *ssc)
1429 /* Set the SSC 'ssc' to match an empty string or any code point */
1431 PERL_ARGS_ASSERT_SSC_ANYTHING;
1433 assert(is_ANYOF_SYNTHETIC(ssc));
1435 /* mortalize so won't leak */
1436 ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
1437 ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING; /* Plus matches empty */
1441 S_ssc_is_anything(const regnode_ssc *ssc)
1443 /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1444 * point; FALSE otherwise. Thus, this is used to see if using 'ssc' buys
1445 * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1446 * in any way, so there's no point in using it */
1451 PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1453 assert(is_ANYOF_SYNTHETIC(ssc));
1455 if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1459 /* See if the list consists solely of the range 0 - Infinity */
1460 invlist_iterinit(ssc->invlist);
1461 ret = invlist_iternext(ssc->invlist, &start, &end)
1465 invlist_iterfinish(ssc->invlist);
1471 /* If e.g., both \w and \W are set, matches everything */
1472 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1474 for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1475 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1485 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1487 /* Initializes the SSC 'ssc'. This includes setting it to match an empty
1488 * string, any code point, or any posix class under locale */
1490 PERL_ARGS_ASSERT_SSC_INIT;
1492 Zero(ssc, 1, regnode_ssc);
1493 set_ANYOF_SYNTHETIC(ssc);
1494 ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1497 /* If any portion of the regex is to operate under locale rules that aren't
1498 * fully known at compile time, initialization includes it. The reason
1499 * this isn't done for all regexes is that the optimizer was written under
1500 * the assumption that locale was all-or-nothing. Given the complexity and
1501 * lack of documentation in the optimizer, and that there are inadequate
1502 * test cases for locale, many parts of it may not work properly, it is
1503 * safest to avoid locale unless necessary. */
1504 if (RExC_contains_locale) {
1505 ANYOF_POSIXL_SETALL(ssc);
1508 ANYOF_POSIXL_ZERO(ssc);
1513 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1514 const regnode_ssc *ssc)
1516 /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1517 * to the list of code points matched, and locale posix classes; hence does
1518 * not check its flags) */
1523 PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1525 assert(is_ANYOF_SYNTHETIC(ssc));
1527 invlist_iterinit(ssc->invlist);
1528 ret = invlist_iternext(ssc->invlist, &start, &end)
1532 invlist_iterfinish(ssc->invlist);
1538 if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1545 #define INVLIST_INDEX 0
1546 #define ONLY_LOCALE_MATCHES_INDEX 1
1547 #define DEFERRED_USER_DEFINED_INDEX 2
1550 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1551 const regnode_charclass* const node)
1553 /* Returns a mortal inversion list defining which code points are matched
1554 * by 'node', which is of type ANYOF. Handles complementing the result if
1555 * appropriate. If some code points aren't knowable at this time, the
1556 * returned list must, and will, contain every code point that is a
1561 SV* only_utf8_locale_invlist = NULL;
1563 const U32 n = ARG(node);
1564 bool new_node_has_latin1 = FALSE;
1566 PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1568 /* Look at the data structure created by S_set_ANYOF_arg() */
1569 if (n != ANYOF_ONLY_HAS_BITMAP) {
1570 SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1571 AV * const av = MUTABLE_AV(SvRV(rv));
1572 SV **const ary = AvARRAY(av);
1573 assert(RExC_rxi->data->what[n] == 's');
1575 if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
1577 /* Here there are things that won't be known until runtime -- we
1578 * have to assume it could be anything */
1579 invlist = sv_2mortal(_new_invlist(1));
1580 return _add_range_to_invlist(invlist, 0, UV_MAX);
1582 else if (ary[INVLIST_INDEX]) {
1584 /* Use the node's inversion list */
1585 invlist = sv_2mortal(invlist_clone(ary[INVLIST_INDEX], NULL));
1588 /* Get the code points valid only under UTF-8 locales */
1589 if ( (ANYOF_FLAGS(node) & ANYOFL_FOLD)
1590 && av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX)
1592 only_utf8_locale_invlist = ary[ONLY_LOCALE_MATCHES_INDEX];
1597 invlist = sv_2mortal(_new_invlist(0));
1600 /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1601 * code points, and an inversion list for the others, but if there are code
1602 * points that should match only conditionally on the target string being
1603 * UTF-8, those are placed in the inversion list, and not the bitmap.
1604 * Since there are circumstances under which they could match, they are
1605 * included in the SSC. But if the ANYOF node is to be inverted, we have
1606 * to exclude them here, so that when we invert below, the end result
1607 * actually does include them. (Think about "\xe0" =~ /[^\xc0]/di;). We
1608 * have to do this here before we add the unconditionally matched code
1610 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1611 _invlist_intersection_complement_2nd(invlist,
1616 /* Add in the points from the bit map */
1617 if (OP(node) != ANYOFH) {
1618 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1619 if (ANYOF_BITMAP_TEST(node, i)) {
1620 unsigned int start = i++;
1622 for (; i < NUM_ANYOF_CODE_POINTS
1623 && ANYOF_BITMAP_TEST(node, i); ++i)
1627 invlist = _add_range_to_invlist(invlist, start, i-1);
1628 new_node_has_latin1 = TRUE;
1633 /* If this can match all upper Latin1 code points, have to add them
1634 * as well. But don't add them if inverting, as when that gets done below,
1635 * it would exclude all these characters, including the ones it shouldn't
1636 * that were added just above */
1637 if (! (ANYOF_FLAGS(node) & ANYOF_INVERT) && OP(node) == ANYOFD
1638 && (ANYOF_FLAGS(node) & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1640 _invlist_union(invlist, PL_UpperLatin1, &invlist);
1643 /* Similarly for these */
1644 if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1645 _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1648 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1649 _invlist_invert(invlist);
1651 else if (ANYOF_FLAGS(node) & ANYOFL_FOLD) {
1652 if (new_node_has_latin1) {
1654 /* Under /li, any 0-255 could fold to any other 0-255, depending on
1655 * the locale. We can skip this if there are no 0-255 at all. */
1656 _invlist_union(invlist, PL_Latin1, &invlist);
1658 invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I);
1659 invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
1662 if (_invlist_contains_cp(invlist, LATIN_SMALL_LETTER_DOTLESS_I)) {
1663 invlist = add_cp_to_invlist(invlist, 'I');
1665 if (_invlist_contains_cp(invlist,
1666 LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE))
1668 invlist = add_cp_to_invlist(invlist, 'i');
1673 /* Similarly add the UTF-8 locale possible matches. These have to be
1674 * deferred until after the non-UTF-8 locale ones are taken care of just
1675 * above, or it leads to wrong results under ANYOF_INVERT */
1676 if (only_utf8_locale_invlist) {
1677 _invlist_union_maybe_complement_2nd(invlist,
1678 only_utf8_locale_invlist,
1679 ANYOF_FLAGS(node) & ANYOF_INVERT,
1686 /* These two functions currently do the exact same thing */
1687 #define ssc_init_zero ssc_init
1689 #define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp))
1690 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1692 /* 'AND' a given class with another one. Can create false positives. 'ssc'
1693 * should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1694 * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1697 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1698 const regnode_charclass *and_with)
1700 /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1701 * another SSC or a regular ANYOF class. Can create false positives. */
1706 PERL_ARGS_ASSERT_SSC_AND;
1708 assert(is_ANYOF_SYNTHETIC(ssc));
1710 /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1711 * the code point inversion list and just the relevant flags */
1712 if (is_ANYOF_SYNTHETIC(and_with)) {
1713 anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1714 anded_flags = ANYOF_FLAGS(and_with);
1716 /* XXX This is a kludge around what appears to be deficiencies in the
1717 * optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag,
1718 * there are paths through the optimizer where it doesn't get weeded
1719 * out when it should. And if we don't make some extra provision for
1720 * it like the code just below, it doesn't get added when it should.
1721 * This solution is to add it only when AND'ing, which is here, and
1722 * only when what is being AND'ed is the pristine, original node
1723 * matching anything. Thus it is like adding it to ssc_anything() but
1724 * only when the result is to be AND'ed. Probably the same solution
1725 * could be adopted for the same problem we have with /l matching,
1726 * which is solved differently in S_ssc_init(), and that would lead to
1727 * fewer false positives than that solution has. But if this solution
1728 * creates bugs, the consequences are only that a warning isn't raised
1729 * that should be; while the consequences for having /l bugs is
1730 * incorrect matches */
1731 if (ssc_is_anything((regnode_ssc *)and_with)) {
1732 anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1736 anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1737 if (OP(and_with) == ANYOFD) {
1738 anded_flags = ANYOF_FLAGS(and_with) & ANYOF_COMMON_FLAGS;
1741 anded_flags = ANYOF_FLAGS(and_with)
1742 &( ANYOF_COMMON_FLAGS
1743 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1744 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1745 if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(and_with))) {
1747 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1752 ANYOF_FLAGS(ssc) &= anded_flags;
1754 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1755 * C2 is the list of code points in 'and-with'; P2, its posix classes.
1756 * 'and_with' may be inverted. When not inverted, we have the situation of
1758 * (C1 | P1) & (C2 | P2)
1759 * = (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1760 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1761 * <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2))
1762 * <= ((C1 & C2) | P1 | P2)
1763 * Alternatively, the last few steps could be:
1764 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1765 * <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2))
1766 * <= (C1 | C2 | (P1 & P2))
1767 * We favor the second approach if either P1 or P2 is non-empty. This is
1768 * because these components are a barrier to doing optimizations, as what
1769 * they match cannot be known until the moment of matching as they are
1770 * dependent on the current locale, 'AND"ing them likely will reduce or
1772 * But we can do better if we know that C1,P1 are in their initial state (a
1773 * frequent occurrence), each matching everything:
1774 * (<everything>) & (C2 | P2) = C2 | P2
1775 * Similarly, if C2,P2 are in their initial state (again a frequent
1776 * occurrence), the result is a no-op
1777 * (C1 | P1) & (<everything>) = C1 | P1
1780 * (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2)
1781 * = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1782 * <= (C1 & ~C2) | (P1 & ~P2)
1785 if ((ANYOF_FLAGS(and_with) & ANYOF_INVERT)
1786 && ! is_ANYOF_SYNTHETIC(and_with))
1790 ssc_intersection(ssc,
1792 FALSE /* Has already been inverted */
1795 /* If either P1 or P2 is empty, the intersection will be also; can skip
1797 if (! (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL)) {
1798 ANYOF_POSIXL_ZERO(ssc);
1800 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1802 /* Note that the Posix class component P from 'and_with' actually
1804 * P = Pa | Pb | ... | Pn
1805 * where each component is one posix class, such as in [\w\s].
1807 * ~P = ~(Pa | Pb | ... | Pn)
1808 * = ~Pa & ~Pb & ... & ~Pn
1809 * <= ~Pa | ~Pb | ... | ~Pn
1810 * The last is something we can easily calculate, but unfortunately
1811 * is likely to have many false positives. We could do better
1812 * in some (but certainly not all) instances if two classes in
1813 * P have known relationships. For example
1814 * :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1816 * :lower: & :print: = :lower:
1817 * And similarly for classes that must be disjoint. For example,
1818 * since \s and \w can have no elements in common based on rules in
1819 * the POSIX standard,
1820 * \w & ^\S = nothing
1821 * Unfortunately, some vendor locales do not meet the Posix
1822 * standard, in particular almost everything by Microsoft.
1823 * The loop below just changes e.g., \w into \W and vice versa */
1825 regnode_charclass_posixl temp;
1826 int add = 1; /* To calculate the index of the complement */
1828 Zero(&temp, 1, regnode_charclass_posixl);
1829 ANYOF_POSIXL_ZERO(&temp);
1830 for (i = 0; i < ANYOF_MAX; i++) {
1832 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1833 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1835 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1836 ANYOF_POSIXL_SET(&temp, i + add);
1838 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1840 ANYOF_POSIXL_AND(&temp, ssc);
1842 } /* else ssc already has no posixes */
1843 } /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC
1844 in its initial state */
1845 else if (! is_ANYOF_SYNTHETIC(and_with)
1846 || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1848 /* But if 'ssc' is in its initial state, the result is just 'and_with';
1849 * copy it over 'ssc' */
1850 if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1851 if (is_ANYOF_SYNTHETIC(and_with)) {
1852 StructCopy(and_with, ssc, regnode_ssc);
1855 ssc->invlist = anded_cp_list;
1856 ANYOF_POSIXL_ZERO(ssc);
1857 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1858 ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1862 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1863 || (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL))
1865 /* One or the other of P1, P2 is non-empty. */
1866 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1867 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1869 ssc_union(ssc, anded_cp_list, FALSE);
1871 else { /* P1 = P2 = empty */
1872 ssc_intersection(ssc, anded_cp_list, FALSE);
1878 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1879 const regnode_charclass *or_with)
1881 /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1882 * another SSC or a regular ANYOF class. Can create false positives if
1883 * 'or_with' is to be inverted. */
1888 PERL_ARGS_ASSERT_SSC_OR;
1890 assert(is_ANYOF_SYNTHETIC(ssc));
1892 /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1893 * the code point inversion list and just the relevant flags */
1894 if (is_ANYOF_SYNTHETIC(or_with)) {
1895 ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1896 ored_flags = ANYOF_FLAGS(or_with);
1899 ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
1900 ored_flags = ANYOF_FLAGS(or_with) & ANYOF_COMMON_FLAGS;
1901 if (OP(or_with) != ANYOFD) {
1903 |= ANYOF_FLAGS(or_with)
1904 & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1905 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1906 if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(or_with))) {
1908 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1913 ANYOF_FLAGS(ssc) |= ored_flags;
1915 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1916 * C2 is the list of code points in 'or-with'; P2, its posix classes.
1917 * 'or_with' may be inverted. When not inverted, we have the simple
1918 * situation of computing:
1919 * (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2)
1920 * If P1|P2 yields a situation with both a class and its complement are
1921 * set, like having both \w and \W, this matches all code points, and we
1922 * can delete these from the P component of the ssc going forward. XXX We
1923 * might be able to delete all the P components, but I (khw) am not certain
1924 * about this, and it is better to be safe.
1927 * (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2)
1928 * <= (C1 | P1) | ~C2
1929 * <= (C1 | ~C2) | P1
1930 * (which results in actually simpler code than the non-inverted case)
1933 if ((ANYOF_FLAGS(or_with) & ANYOF_INVERT)
1934 && ! is_ANYOF_SYNTHETIC(or_with))
1936 /* We ignore P2, leaving P1 going forward */
1937 } /* else Not inverted */
1938 else if (ANYOF_FLAGS(or_with) & ANYOF_MATCHES_POSIXL) {
1939 ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
1940 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1942 for (i = 0; i < ANYOF_MAX; i += 2) {
1943 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1945 ssc_match_all_cp(ssc);
1946 ANYOF_POSIXL_CLEAR(ssc, i);
1947 ANYOF_POSIXL_CLEAR(ssc, i+1);
1955 FALSE /* Already has been inverted */
1959 PERL_STATIC_INLINE void
1960 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
1962 PERL_ARGS_ASSERT_SSC_UNION;
1964 assert(is_ANYOF_SYNTHETIC(ssc));
1966 _invlist_union_maybe_complement_2nd(ssc->invlist,
1972 PERL_STATIC_INLINE void
1973 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
1975 const bool invert2nd)
1977 PERL_ARGS_ASSERT_SSC_INTERSECTION;
1979 assert(is_ANYOF_SYNTHETIC(ssc));
1981 _invlist_intersection_maybe_complement_2nd(ssc->invlist,
1987 PERL_STATIC_INLINE void
1988 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
1990 PERL_ARGS_ASSERT_SSC_ADD_RANGE;
1992 assert(is_ANYOF_SYNTHETIC(ssc));
1994 ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
1997 PERL_STATIC_INLINE void
1998 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
2000 /* AND just the single code point 'cp' into the SSC 'ssc' */
2002 SV* cp_list = _new_invlist(2);
2004 PERL_ARGS_ASSERT_SSC_CP_AND;
2006 assert(is_ANYOF_SYNTHETIC(ssc));
2008 cp_list = add_cp_to_invlist(cp_list, cp);
2009 ssc_intersection(ssc, cp_list,
2010 FALSE /* Not inverted */
2012 SvREFCNT_dec_NN(cp_list);
2015 PERL_STATIC_INLINE void
2016 S_ssc_clear_locale(regnode_ssc *ssc)
2018 /* Set the SSC 'ssc' to not match any locale things */
2019 PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
2021 assert(is_ANYOF_SYNTHETIC(ssc));
2023 ANYOF_POSIXL_ZERO(ssc);
2024 ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
2027 #define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
2030 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
2032 /* The synthetic start class is used to hopefully quickly winnow down
2033 * places where a pattern could start a match in the target string. If it
2034 * doesn't really narrow things down that much, there isn't much point to
2035 * having the overhead of using it. This function uses some very crude
2036 * heuristics to decide if to use the ssc or not.
2038 * It returns TRUE if 'ssc' rules out more than half what it considers to
2039 * be the "likely" possible matches, but of course it doesn't know what the
2040 * actual things being matched are going to be; these are only guesses
2042 * For /l matches, it assumes that the only likely matches are going to be
2043 * in the 0-255 range, uniformly distributed, so half of that is 127
2044 * For /a and /d matches, it assumes that the likely matches will be just
2045 * the ASCII range, so half of that is 63
2046 * For /u and there isn't anything matching above the Latin1 range, it
2047 * assumes that that is the only range likely to be matched, and uses
2048 * half that as the cut-off: 127. If anything matches above Latin1,
2049 * it assumes that all of Unicode could match (uniformly), except for
2050 * non-Unicode code points and things in the General Category "Other"
2051 * (unassigned, private use, surrogates, controls and formats). This
2052 * is a much large number. */
2054 U32 count = 0; /* Running total of number of code points matched by
2056 UV start, end; /* Start and end points of current range in inversion
2057 XXX outdated. UTF-8 locales are common, what about invert? list */
2058 const U32 max_code_points = (LOC)
2060 : (( ! UNI_SEMANTICS
2061 || invlist_highest(ssc->invlist) < 256)
2064 const U32 max_match = max_code_points / 2;
2066 PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
2068 invlist_iterinit(ssc->invlist);
2069 while (invlist_iternext(ssc->invlist, &start, &end)) {
2070 if (start >= max_code_points) {
2073 end = MIN(end, max_code_points - 1);
2074 count += end - start + 1;
2075 if (count >= max_match) {
2076 invlist_iterfinish(ssc->invlist);
2086 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
2088 /* The inversion list in the SSC is marked mortal; now we need a more
2089 * permanent copy, which is stored the same way that is done in a regular
2090 * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
2093 SV* invlist = invlist_clone(ssc->invlist, NULL);
2095 PERL_ARGS_ASSERT_SSC_FINALIZE;
2097 assert(is_ANYOF_SYNTHETIC(ssc));
2099 /* The code in this file assumes that all but these flags aren't relevant
2100 * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
2101 * by the time we reach here */
2102 assert(! (ANYOF_FLAGS(ssc)
2103 & ~( ANYOF_COMMON_FLAGS
2104 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2105 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
2107 populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
2109 set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist, NULL, NULL);
2111 /* Make sure is clone-safe */
2112 ssc->invlist = NULL;
2114 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2115 ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
2116 OP(ssc) = ANYOFPOSIXL;
2118 else if (RExC_contains_locale) {
2122 assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
2125 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
2126 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
2127 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
2128 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \
2129 ? (TRIE_LIST_CUR( idx ) - 1) \
2135 dump_trie(trie,widecharmap,revcharmap)
2136 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
2137 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
2139 These routines dump out a trie in a somewhat readable format.
2140 The _interim_ variants are used for debugging the interim
2141 tables that are used to generate the final compressed
2142 representation which is what dump_trie expects.
2144 Part of the reason for their existence is to provide a form
2145 of documentation as to how the different representations function.
2150 Dumps the final compressed table form of the trie to Perl_debug_log.
2151 Used for debugging make_trie().
2155 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
2156 AV *revcharmap, U32 depth)
2159 SV *sv=sv_newmortal();
2160 int colwidth= widecharmap ? 6 : 4;
2162 GET_RE_DEBUG_FLAGS_DECL;
2164 PERL_ARGS_ASSERT_DUMP_TRIE;
2166 Perl_re_indentf( aTHX_ "Char : %-6s%-6s%-4s ",
2167 depth+1, "Match","Base","Ofs" );
2169 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2170 SV ** const tmp = av_fetch( revcharmap, state, 0);
2172 Perl_re_printf( aTHX_ "%*s",
2174 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2175 PL_colors[0], PL_colors[1],
2176 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2177 PERL_PV_ESCAPE_FIRSTCHAR
2182 Perl_re_printf( aTHX_ "\n");
2183 Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
2185 for( state = 0 ; state < trie->uniquecharcount ; state++ )
2186 Perl_re_printf( aTHX_ "%.*s", colwidth, "--------");
2187 Perl_re_printf( aTHX_ "\n");
2189 for( state = 1 ; state < trie->statecount ; state++ ) {
2190 const U32 base = trie->states[ state ].trans.base;
2192 Perl_re_indentf( aTHX_ "#%4" UVXf "|", depth+1, (UV)state);
2194 if ( trie->states[ state ].wordnum ) {
2195 Perl_re_printf( aTHX_ " W%4X", trie->states[ state ].wordnum );
2197 Perl_re_printf( aTHX_ "%6s", "" );
2200 Perl_re_printf( aTHX_ " @%4" UVXf " ", (UV)base );
2205 while( ( base + ofs < trie->uniquecharcount ) ||
2206 ( base + ofs - trie->uniquecharcount < trie->lasttrans
2207 && trie->trans[ base + ofs - trie->uniquecharcount ].check
2211 Perl_re_printf( aTHX_ "+%2" UVXf "[ ", (UV)ofs);
2213 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2214 if ( ( base + ofs >= trie->uniquecharcount )
2215 && ( base + ofs - trie->uniquecharcount
2217 && trie->trans[ base + ofs
2218 - trie->uniquecharcount ].check == state )
2220 Perl_re_printf( aTHX_ "%*" UVXf, colwidth,
2221 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
2224 Perl_re_printf( aTHX_ "%*s", colwidth," ." );
2228 Perl_re_printf( aTHX_ "]");
2231 Perl_re_printf( aTHX_ "\n" );
2233 Perl_re_indentf( aTHX_ "word_info N:(prev,len)=",
2235 for (word=1; word <= trie->wordcount; word++) {
2236 Perl_re_printf( aTHX_ " %d:(%d,%d)",
2237 (int)word, (int)(trie->wordinfo[word].prev),
2238 (int)(trie->wordinfo[word].len));
2240 Perl_re_printf( aTHX_ "\n" );
2243 Dumps a fully constructed but uncompressed trie in list form.
2244 List tries normally only are used for construction when the number of
2245 possible chars (trie->uniquecharcount) is very high.
2246 Used for debugging make_trie().
2249 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2250 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2254 SV *sv=sv_newmortal();
2255 int colwidth= widecharmap ? 6 : 4;
2256 GET_RE_DEBUG_FLAGS_DECL;
2258 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2260 /* print out the table precompression. */
2261 Perl_re_indentf( aTHX_ "State :Word | Transition Data\n",
2263 Perl_re_indentf( aTHX_ "%s",
2264 depth+1, "------:-----+-----------------\n" );
2266 for( state=1 ; state < next_alloc ; state ++ ) {
2269 Perl_re_indentf( aTHX_ " %4" UVXf " :",
2270 depth+1, (UV)state );
2271 if ( ! trie->states[ state ].wordnum ) {
2272 Perl_re_printf( aTHX_ "%5s| ","");
2274 Perl_re_printf( aTHX_ "W%4x| ",
2275 trie->states[ state ].wordnum
2278 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2279 SV ** const tmp = av_fetch( revcharmap,
2280 TRIE_LIST_ITEM(state, charid).forid, 0);
2282 Perl_re_printf( aTHX_ "%*s:%3X=%4" UVXf " | ",
2284 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2286 PL_colors[0], PL_colors[1],
2287 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2288 | PERL_PV_ESCAPE_FIRSTCHAR
2290 TRIE_LIST_ITEM(state, charid).forid,
2291 (UV)TRIE_LIST_ITEM(state, charid).newstate
2294 Perl_re_printf( aTHX_ "\n%*s| ",
2295 (int)((depth * 2) + 14), "");
2298 Perl_re_printf( aTHX_ "\n");
2303 Dumps a fully constructed but uncompressed trie in table form.
2304 This is the normal DFA style state transition table, with a few
2305 twists to facilitate compression later.
2306 Used for debugging make_trie().
2309 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2310 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2315 SV *sv=sv_newmortal();
2316 int colwidth= widecharmap ? 6 : 4;
2317 GET_RE_DEBUG_FLAGS_DECL;
2319 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2322 print out the table precompression so that we can do a visual check
2323 that they are identical.
2326 Perl_re_indentf( aTHX_ "Char : ", depth+1 );
2328 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2329 SV ** const tmp = av_fetch( revcharmap, charid, 0);
2331 Perl_re_printf( aTHX_ "%*s",
2333 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2334 PL_colors[0], PL_colors[1],
2335 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2336 PERL_PV_ESCAPE_FIRSTCHAR
2342 Perl_re_printf( aTHX_ "\n");
2343 Perl_re_indentf( aTHX_ "State+-", depth+1 );
2345 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2346 Perl_re_printf( aTHX_ "%.*s", colwidth,"--------");
2349 Perl_re_printf( aTHX_ "\n" );
2351 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2353 Perl_re_indentf( aTHX_ "%4" UVXf " : ",
2355 (UV)TRIE_NODENUM( state ) );
2357 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2358 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2360 Perl_re_printf( aTHX_ "%*" UVXf, colwidth, v );
2362 Perl_re_printf( aTHX_ "%*s", colwidth, "." );
2364 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2365 Perl_re_printf( aTHX_ " (%4" UVXf ")\n",
2366 (UV)trie->trans[ state ].check );
2368 Perl_re_printf( aTHX_ " (%4" UVXf ") W%4X\n",
2369 (UV)trie->trans[ state ].check,
2370 trie->states[ TRIE_NODENUM( state ) ].wordnum );
2378 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2379 startbranch: the first branch in the whole branch sequence
2380 first : start branch of sequence of branch-exact nodes.
2381 May be the same as startbranch
2382 last : Thing following the last branch.
2383 May be the same as tail.
2384 tail : item following the branch sequence
2385 count : words in the sequence
2386 flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2387 depth : indent depth
2389 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2391 A trie is an N'ary tree where the branches are determined by digital
2392 decomposition of the key. IE, at the root node you look up the 1st character and
2393 follow that branch repeat until you find the end of the branches. Nodes can be
2394 marked as "accepting" meaning they represent a complete word. Eg:
2398 would convert into the following structure. Numbers represent states, letters
2399 following numbers represent valid transitions on the letter from that state, if
2400 the number is in square brackets it represents an accepting state, otherwise it
2401 will be in parenthesis.
2403 +-h->+-e->[3]-+-r->(8)-+-s->[9]
2407 (1) +-i->(6)-+-s->[7]
2409 +-s->(3)-+-h->(4)-+-e->[5]
2411 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2413 This shows that when matching against the string 'hers' we will begin at state 1
2414 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2415 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2416 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2417 single traverse. We store a mapping from accepting to state to which word was
2418 matched, and then when we have multiple possibilities we try to complete the
2419 rest of the regex in the order in which they occurred in the alternation.
2421 The only prior NFA like behaviour that would be changed by the TRIE support is
2422 the silent ignoring of duplicate alternations which are of the form:
2424 / (DUPE|DUPE) X? (?{ ... }) Y /x
2426 Thus EVAL blocks following a trie may be called a different number of times with
2427 and without the optimisation. With the optimisations dupes will be silently
2428 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2429 the following demonstrates:
2431 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2433 which prints out 'word' three times, but
2435 'words'=~/(word|word|word)(?{ print $1 })S/
2437 which doesnt print it out at all. This is due to other optimisations kicking in.
2439 Example of what happens on a structural level:
2441 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2443 1: CURLYM[1] {1,32767}(18)
2454 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2455 and should turn into:
2457 1: CURLYM[1] {1,32767}(18)
2459 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2467 Cases where tail != last would be like /(?foo|bar)baz/:
2477 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2478 and would end up looking like:
2481 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2488 d = uvchr_to_utf8_flags(d, uv, 0);
2490 is the recommended Unicode-aware way of saying
2495 #define TRIE_STORE_REVCHAR(val) \
2498 SV *zlopp = newSV(UTF8_MAXBYTES); \
2499 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
2500 unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
2501 SvCUR_set(zlopp, kapow - flrbbbbb); \
2504 av_push(revcharmap, zlopp); \
2506 char ooooff = (char)val; \
2507 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
2511 /* This gets the next character from the input, folding it if not already
2513 #define TRIE_READ_CHAR STMT_START { \
2516 /* if it is UTF then it is either already folded, or does not need \
2518 uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \
2520 else if (folder == PL_fold_latin1) { \
2521 /* This folder implies Unicode rules, which in the range expressible \
2522 * by not UTF is the lower case, with the two exceptions, one of \
2523 * which should have been taken care of before calling this */ \
2524 assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \
2525 uvc = toLOWER_L1(*uc); \
2526 if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \
2529 /* raw data, will be folded later if needed */ \
2537 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
2538 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
2539 U32 ging = TRIE_LIST_LEN( state ) * 2; \
2540 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2541 TRIE_LIST_LEN( state ) = ging; \
2543 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
2544 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
2545 TRIE_LIST_CUR( state )++; \
2548 #define TRIE_LIST_NEW(state) STMT_START { \
2549 Newx( trie->states[ state ].trans.list, \
2550 4, reg_trie_trans_le ); \
2551 TRIE_LIST_CUR( state ) = 1; \
2552 TRIE_LIST_LEN( state ) = 4; \
2555 #define TRIE_HANDLE_WORD(state) STMT_START { \
2556 U16 dupe= trie->states[ state ].wordnum; \
2557 regnode * const noper_next = regnext( noper ); \
2560 /* store the word for dumping */ \
2562 if (OP(noper) != NOTHING) \
2563 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
2565 tmp = newSVpvn_utf8( "", 0, UTF ); \
2566 av_push( trie_words, tmp ); \
2570 trie->wordinfo[curword].prev = 0; \
2571 trie->wordinfo[curword].len = wordlen; \
2572 trie->wordinfo[curword].accept = state; \
2574 if ( noper_next < tail ) { \
2576 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2578 trie->jump[curword] = (U16)(noper_next - convert); \
2580 jumper = noper_next; \
2582 nextbranch= regnext(cur); \
2586 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
2587 /* chain, so that when the bits of chain are later */\
2588 /* linked together, the dups appear in the chain */\
2589 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2590 trie->wordinfo[dupe].prev = curword; \
2592 /* we haven't inserted this word yet. */ \
2593 trie->states[ state ].wordnum = curword; \
2598 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
2599 ( ( base + charid >= ucharcount \
2600 && base + charid < ubound \
2601 && state == trie->trans[ base - ucharcount + charid ].check \
2602 && trie->trans[ base - ucharcount + charid ].next ) \
2603 ? trie->trans[ base - ucharcount + charid ].next \
2604 : ( state==1 ? special : 0 ) \
2607 #define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder) \
2609 TRIE_BITMAP_SET(trie, uvc); \
2610 /* store the folded codepoint */ \
2612 TRIE_BITMAP_SET(trie, folder[(U8) uvc ]); \
2615 /* store first byte of utf8 representation of */ \
2616 /* variant codepoints */ \
2617 if (! UVCHR_IS_INVARIANT(uvc)) { \
2618 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc)); \
2623 #define MADE_JUMP_TRIE 2
2624 #define MADE_EXACT_TRIE 4
2627 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2628 regnode *first, regnode *last, regnode *tail,
2629 U32 word_count, U32 flags, U32 depth)
2631 /* first pass, loop through and scan words */
2632 reg_trie_data *trie;
2633 HV *widecharmap = NULL;
2634 AV *revcharmap = newAV();
2640 regnode *jumper = NULL;
2641 regnode *nextbranch = NULL;
2642 regnode *convert = NULL;
2643 U32 *prev_states; /* temp array mapping each state to previous one */
2644 /* we just use folder as a flag in utf8 */
2645 const U8 * folder = NULL;
2647 /* in the below add_data call we are storing either 'tu' or 'tuaa'
2648 * which stands for one trie structure, one hash, optionally followed
2651 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
2652 AV *trie_words = NULL;
2653 /* along with revcharmap, this only used during construction but both are
2654 * useful during debugging so we store them in the struct when debugging.
2657 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2658 STRLEN trie_charcount=0;
2660 SV *re_trie_maxbuff;
2661 GET_RE_DEBUG_FLAGS_DECL;
2663 PERL_ARGS_ASSERT_MAKE_TRIE;
2665 PERL_UNUSED_ARG(depth);
2669 case EXACT: case EXACT_ONLY8: case EXACTL: break;
2673 case EXACTFLU8: folder = PL_fold_latin1; break;
2674 case EXACTF: folder = PL_fold; break;
2675 default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2678 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2680 trie->startstate = 1;
2681 trie->wordcount = word_count;
2682 RExC_rxi->data->data[ data_slot ] = (void*)trie;
2683 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2684 if (flags == EXACT || flags == EXACT_ONLY8 || flags == EXACTL)
2685 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2686 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2687 trie->wordcount+1, sizeof(reg_trie_wordinfo));
2690 trie_words = newAV();
2693 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2694 assert(re_trie_maxbuff);
2695 if (!SvIOK(re_trie_maxbuff)) {
2696 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2698 DEBUG_TRIE_COMPILE_r({
2699 Perl_re_indentf( aTHX_
2700 "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2702 REG_NODE_NUM(startbranch), REG_NODE_NUM(first),
2703 REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2706 /* Find the node we are going to overwrite */
2707 if ( first == startbranch && OP( last ) != BRANCH ) {
2708 /* whole branch chain */
2711 /* branch sub-chain */
2712 convert = NEXTOPER( first );
2715 /* -- First loop and Setup --
2717 We first traverse the branches and scan each word to determine if it
2718 contains widechars, and how many unique chars there are, this is
2719 important as we have to build a table with at least as many columns as we
2722 We use an array of integers to represent the character codes 0..255
2723 (trie->charmap) and we use a an HV* to store Unicode characters. We use
2724 the native representation of the character value as the key and IV's for
2727 *TODO* If we keep track of how many times each character is used we can
2728 remap the columns so that the table compression later on is more
2729 efficient in terms of memory by ensuring the most common value is in the
2730 middle and the least common are on the outside. IMO this would be better
2731 than a most to least common mapping as theres a decent chance the most
2732 common letter will share a node with the least common, meaning the node
2733 will not be compressible. With a middle is most common approach the worst
2734 case is when we have the least common nodes twice.
2738 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2739 regnode *noper = NEXTOPER( cur );
2743 U32 wordlen = 0; /* required init */
2744 STRLEN minchars = 0;
2745 STRLEN maxchars = 0;
2746 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2749 if (OP(noper) == NOTHING) {
2750 /* skip past a NOTHING at the start of an alternation
2751 * eg, /(?:)a|(?:b)/ should be the same as /a|b/
2753 regnode *noper_next= regnext(noper);
2754 if (noper_next < tail)
2759 && ( OP(noper) == flags
2760 || (flags == EXACT && OP(noper) == EXACT_ONLY8)
2761 || (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8
2762 || OP(noper) == EXACTFUP))))
2764 uc= (U8*)STRING(noper);
2765 e= uc + STR_LEN(noper);
2772 if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2773 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2774 regardless of encoding */
2775 if (OP( noper ) == EXACTFUP) {
2776 /* false positives are ok, so just set this */
2777 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2781 for ( ; uc < e ; uc += len ) { /* Look at each char in the current
2783 TRIE_CHARCOUNT(trie)++;
2786 /* TRIE_READ_CHAR returns the current character, or its fold if /i
2787 * is in effect. Under /i, this character can match itself, or
2788 * anything that folds to it. If not under /i, it can match just
2789 * itself. Most folds are 1-1, for example k, K, and KELVIN SIGN
2790 * all fold to k, and all are single characters. But some folds
2791 * expand to more than one character, so for example LATIN SMALL
2792 * LIGATURE FFI folds to the three character sequence 'ffi'. If
2793 * the string beginning at 'uc' is 'ffi', it could be matched by
2794 * three characters, or just by the one ligature character. (It
2795 * could also be matched by two characters: LATIN SMALL LIGATURE FF
2796 * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2797 * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2798 * match.) The trie needs to know the minimum and maximum number
2799 * of characters that could match so that it can use size alone to
2800 * quickly reject many match attempts. The max is simple: it is
2801 * the number of folded characters in this branch (since a fold is
2802 * never shorter than what folds to it. */
2806 /* And the min is equal to the max if not under /i (indicated by
2807 * 'folder' being NULL), or there are no multi-character folds. If
2808 * there is a multi-character fold, the min is incremented just
2809 * once, for the character that folds to the sequence. Each
2810 * character in the sequence needs to be added to the list below of
2811 * characters in the trie, but we count only the first towards the
2812 * min number of characters needed. This is done through the
2813 * variable 'foldlen', which is returned by the macros that look
2814 * for these sequences as the number of bytes the sequence
2815 * occupies. Each time through the loop, we decrement 'foldlen' by
2816 * how many bytes the current char occupies. Only when it reaches
2817 * 0 do we increment 'minchars' or look for another multi-character
2819 if (folder == NULL) {
2822 else if (foldlen > 0) {
2823 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2828 /* See if *uc is the beginning of a multi-character fold. If
2829 * so, we decrement the length remaining to look at, to account
2830 * for the current character this iteration. (We can use 'uc'
2831 * instead of the fold returned by TRIE_READ_CHAR because for
2832 * non-UTF, the latin1_safe macro is smart enough to account
2833 * for all the unfolded characters, and because for UTF, the
2834 * string will already have been folded earlier in the
2835 * compilation process */
2837 if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2838 foldlen -= UTF8SKIP(uc);
2841 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2846 /* The current character (and any potential folds) should be added
2847 * to the possible matching characters for this position in this
2851 U8 folded= folder[ (U8) uvc ];
2852 if ( !trie->charmap[ folded ] ) {
2853 trie->charmap[ folded ]=( ++trie->uniquecharcount );
2854 TRIE_STORE_REVCHAR( folded );
2857 if ( !trie->charmap[ uvc ] ) {
2858 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2859 TRIE_STORE_REVCHAR( uvc );
2862 /* store the codepoint in the bitmap, and its folded
2864 TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
2865 set_bit = 0; /* We've done our bit :-) */
2869 /* XXX We could come up with the list of code points that fold
2870 * to this using PL_utf8_foldclosures, except not for
2871 * multi-char folds, as there may be multiple combinations
2872 * there that could work, which needs to wait until runtime to
2873 * resolve (The comment about LIGATURE FFI above is such an
2878 widecharmap = newHV();
2880 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2883 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
2885 if ( !SvTRUE( *svpp ) ) {
2886 sv_setiv( *svpp, ++trie->uniquecharcount );
2887 TRIE_STORE_REVCHAR(uvc);
2890 } /* end loop through characters in this branch of the trie */
2892 /* We take the min and max for this branch and combine to find the min
2893 * and max for all branches processed so far */
2894 if( cur == first ) {
2895 trie->minlen = minchars;
2896 trie->maxlen = maxchars;
2897 } else if (minchars < trie->minlen) {
2898 trie->minlen = minchars;
2899 } else if (maxchars > trie->maxlen) {
2900 trie->maxlen = maxchars;
2902 } /* end first pass */
2903 DEBUG_TRIE_COMPILE_r(
2904 Perl_re_indentf( aTHX_
2905 "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2907 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
2908 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2909 (int)trie->minlen, (int)trie->maxlen )
2913 We now know what we are dealing with in terms of unique chars and
2914 string sizes so we can calculate how much memory a naive
2915 representation using a flat table will take. If it's over a reasonable
2916 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
2917 conservative but potentially much slower representation using an array
2920 At the end we convert both representations into the same compressed
2921 form that will be used in regexec.c for matching with. The latter
2922 is a form that cannot be used to construct with but has memory
2923 properties similar to the list form and access properties similar
2924 to the table form making it both suitable for fast searches and
2925 small enough that its feasable to store for the duration of a program.
2927 See the comment in the code where the compressed table is produced
2928 inplace from the flat tabe representation for an explanation of how
2929 the compression works.
2934 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2937 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2938 > SvIV(re_trie_maxbuff) )
2941 Second Pass -- Array Of Lists Representation
2943 Each state will be represented by a list of charid:state records
2944 (reg_trie_trans_le) the first such element holds the CUR and LEN
2945 points of the allocated array. (See defines above).
2947 We build the initial structure using the lists, and then convert
2948 it into the compressed table form which allows faster lookups
2949 (but cant be modified once converted).
2952 STRLEN transcount = 1;
2954 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using list compiler\n",
2957 trie->states = (reg_trie_state *)
2958 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2959 sizeof(reg_trie_state) );
2963 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2965 regnode *noper = NEXTOPER( cur );
2966 U32 state = 1; /* required init */
2967 U16 charid = 0; /* sanity init */
2968 U32 wordlen = 0; /* required init */
2970 if (OP(noper) == NOTHING) {
2971 regnode *noper_next= regnext(noper);
2972 if (noper_next < tail)
2977 && ( OP(noper) == flags
2978 || (flags == EXACT && OP(noper) == EXACT_ONLY8)
2979 || (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8
2980 || OP(noper) == EXACTFUP))))
2982 const U8 *uc= (U8*)STRING(noper);
2983 const U8 *e= uc + STR_LEN(noper);
2985 for ( ; uc < e ; uc += len ) {
2990 charid = trie->charmap[ uvc ];
2992 SV** const svpp = hv_fetch( widecharmap,
2999 charid=(U16)SvIV( *svpp );
3002 /* charid is now 0 if we dont know the char read, or
3003 * nonzero if we do */
3010 if ( !trie->states[ state ].trans.list ) {
3011 TRIE_LIST_NEW( state );
3014 check <= TRIE_LIST_USED( state );
3017 if ( TRIE_LIST_ITEM( state, check ).forid
3020 newstate = TRIE_LIST_ITEM( state, check ).newstate;
3025 newstate = next_alloc++;
3026 prev_states[newstate] = state;
3027 TRIE_LIST_PUSH( state, charid, newstate );
3032 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3036 TRIE_HANDLE_WORD(state);
3038 } /* end second pass */
3040 /* next alloc is the NEXT state to be allocated */
3041 trie->statecount = next_alloc;
3042 trie->states = (reg_trie_state *)
3043 PerlMemShared_realloc( trie->states,
3045 * sizeof(reg_trie_state) );
3047 /* and now dump it out before we compress it */
3048 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
3049 revcharmap, next_alloc,
3053 trie->trans = (reg_trie_trans *)
3054 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
3061 for( state=1 ; state < next_alloc ; state ++ ) {
3065 DEBUG_TRIE_COMPILE_MORE_r(
3066 Perl_re_printf( aTHX_ "tp: %d zp: %d ",tp,zp)
3070 if (trie->states[state].trans.list) {
3071 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
3075 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3076 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
3077 if ( forid < minid ) {
3079 } else if ( forid > maxid ) {
3083 if ( transcount < tp + maxid - minid + 1) {
3085 trie->trans = (reg_trie_trans *)
3086 PerlMemShared_realloc( trie->trans,
3088 * sizeof(reg_trie_trans) );
3089 Zero( trie->trans + (transcount / 2),
3093 base = trie->uniquecharcount + tp - minid;
3094 if ( maxid == minid ) {
3096 for ( ; zp < tp ; zp++ ) {
3097 if ( ! trie->trans[ zp ].next ) {
3098 base = trie->uniquecharcount + zp - minid;
3099 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
3101 trie->trans[ zp ].check = state;
3107 trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
3109 trie->trans[ tp ].check = state;
3114 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3115 const U32 tid = base
3116 - trie->uniquecharcount
3117 + TRIE_LIST_ITEM( state, idx ).forid;
3118 trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
3120 trie->trans[ tid ].check = state;
3122 tp += ( maxid - minid + 1 );
3124 Safefree(trie->states[ state ].trans.list);
3127 DEBUG_TRIE_COMPILE_MORE_r(
3128 Perl_re_printf( aTHX_ " base: %d\n",base);
3131 trie->states[ state ].trans.base=base;
3133 trie->lasttrans = tp + 1;
3137 Second Pass -- Flat Table Representation.
3139 we dont use the 0 slot of either trans[] or states[] so we add 1 to
3140 each. We know that we will need Charcount+1 trans at most to store
3141 the data (one row per char at worst case) So we preallocate both
3142 structures assuming worst case.
3144 We then construct the trie using only the .next slots of the entry
3147 We use the .check field of the first entry of the node temporarily
3148 to make compression both faster and easier by keeping track of how
3149 many non zero fields are in the node.
3151 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
3154 There are two terms at use here: state as a TRIE_NODEIDX() which is
3155 a number representing the first entry of the node, and state as a
3156 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
3157 and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
3158 if there are 2 entrys per node. eg:
3166 The table is internally in the right hand, idx form. However as we
3167 also have to deal with the states array which is indexed by nodenum
3168 we have to use TRIE_NODENUM() to convert.
3171 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using table compiler\n",
3174 trie->trans = (reg_trie_trans *)
3175 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
3176 * trie->uniquecharcount + 1,
3177 sizeof(reg_trie_trans) );
3178 trie->states = (reg_trie_state *)
3179 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3180 sizeof(reg_trie_state) );
3181 next_alloc = trie->uniquecharcount + 1;
3184 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3186 regnode *noper = NEXTOPER( cur );
3188 U32 state = 1; /* required init */
3190 U16 charid = 0; /* sanity init */
3191 U32 accept_state = 0; /* sanity init */
3193 U32 wordlen = 0; /* required init */
3195 if (OP(noper) == NOTHING) {
3196 regnode *noper_next= regnext(noper);
3197 if (noper_next < tail)
3202 && ( OP(noper) == flags
3203 || (flags == EXACT && OP(noper) == EXACT_ONLY8)
3204 || (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8
3205 || OP(noper) == EXACTFUP))))
3207 const U8 *uc= (U8*)STRING(noper);
3208 const U8 *e= uc + STR_LEN(noper);
3210 for ( ; uc < e ; uc += len ) {
3215 charid = trie->charmap[ uvc ];
3217 SV* const * const svpp = hv_fetch( widecharmap,
3221 charid = svpp ? (U16)SvIV(*svpp) : 0;
3225 if ( !trie->trans[ state + charid ].next ) {
3226 trie->trans[ state + charid ].next = next_alloc;
3227 trie->trans[ state ].check++;
3228 prev_states[TRIE_NODENUM(next_alloc)]
3229 = TRIE_NODENUM(state);
3230 next_alloc += trie->uniquecharcount;
3232 state = trie->trans[ state + charid ].next;
3234 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3236 /* charid is now 0 if we dont know the char read, or
3237 * nonzero if we do */
3240 accept_state = TRIE_NODENUM( state );
3241 TRIE_HANDLE_WORD(accept_state);
3243 } /* end second pass */
3245 /* and now dump it out before we compress it */
3246 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3248 next_alloc, depth+1));
3252 * Inplace compress the table.*
3254 For sparse data sets the table constructed by the trie algorithm will
3255 be mostly 0/FAIL transitions or to put it another way mostly empty.
3256 (Note that leaf nodes will not contain any transitions.)
3258 This algorithm compresses the tables by eliminating most such
3259 transitions, at the cost of a modest bit of extra work during lookup:
3261 - Each states[] entry contains a .base field which indicates the
3262 index in the state[] array wheres its transition data is stored.
3264 - If .base is 0 there are no valid transitions from that node.
3266 - If .base is nonzero then charid is added to it to find an entry in
3269 -If trans[states[state].base+charid].check!=state then the
3270 transition is taken to be a 0/Fail transition. Thus if there are fail
3271 transitions at the front of the node then the .base offset will point
3272 somewhere inside the previous nodes data (or maybe even into a node
3273 even earlier), but the .check field determines if the transition is
3277 The following process inplace converts the table to the compressed
3278 table: We first do not compress the root node 1,and mark all its
3279 .check pointers as 1 and set its .base pointer as 1 as well. This
3280 allows us to do a DFA construction from the compressed table later,
3281 and ensures that any .base pointers we calculate later are greater
3284 - We set 'pos' to indicate the first entry of the second node.
3286 - We then iterate over the columns of the node, finding the first and
3287 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3288 and set the .check pointers accordingly, and advance pos
3289 appropriately and repreat for the next node. Note that when we copy
3290 the next pointers we have to convert them from the original
3291 NODEIDX form to NODENUM form as the former is not valid post
3294 - If a node has no transitions used we mark its base as 0 and do not
3295 advance the pos pointer.
3297 - If a node only has one transition we use a second pointer into the
3298 structure to fill in allocated fail transitions from other states.
3299 This pointer is independent of the main pointer and scans forward
3300 looking for null transitions that are allocated to a state. When it
3301 finds one it writes the single transition into the "hole". If the
3302 pointer doesnt find one the single transition is appended as normal.
3304 - Once compressed we can Renew/realloc the structures to release the
3307 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3308 specifically Fig 3.47 and the associated pseudocode.
3312 const U32 laststate = TRIE_NODENUM( next_alloc );
3315 trie->statecount = laststate;
3317 for ( state = 1 ; state < laststate ; state++ ) {
3319 const U32 stateidx = TRIE_NODEIDX( state );
3320 const U32 o_used = trie->trans[ stateidx ].check;
3321 U32 used = trie->trans[ stateidx ].check;
3322 trie->trans[ stateidx ].check = 0;
3325 used && charid < trie->uniquecharcount;
3328 if ( flag || trie->trans[ stateidx + charid ].next ) {
3329 if ( trie->trans[ stateidx + charid ].next ) {
3331 for ( ; zp < pos ; zp++ ) {
3332 if ( ! trie->trans[ zp ].next ) {
3336 trie->states[ state ].trans.base
3338 + trie->uniquecharcount
3340 trie->trans[ zp ].next
3341 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3343 trie->trans[ zp ].check = state;
3344 if ( ++zp > pos ) pos = zp;
3351 trie->states[ state ].trans.base
3352 = pos + trie->uniquecharcount - charid ;
3354 trie->trans[ pos ].next
3355 = SAFE_TRIE_NODENUM(
3356 trie->trans[ stateidx + charid ].next );
3357 trie->trans[ pos ].check = state;
3362 trie->lasttrans = pos + 1;
3363 trie->states = (reg_trie_state *)
3364 PerlMemShared_realloc( trie->states, laststate
3365 * sizeof(reg_trie_state) );
3366 DEBUG_TRIE_COMPILE_MORE_r(
3367 Perl_re_indentf( aTHX_ "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
3369 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3373 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3376 } /* end table compress */
3378 DEBUG_TRIE_COMPILE_MORE_r(
3379 Perl_re_indentf( aTHX_ "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
3381 (UV)trie->statecount,
3382 (UV)trie->lasttrans)
3384 /* resize the trans array to remove unused space */
3385 trie->trans = (reg_trie_trans *)
3386 PerlMemShared_realloc( trie->trans, trie->lasttrans
3387 * sizeof(reg_trie_trans) );
3389 { /* Modify the program and insert the new TRIE node */
3390 U8 nodetype =(U8)(flags & 0xFF);
3394 regnode *optimize = NULL;
3395 #ifdef RE_TRACK_PATTERN_OFFSETS
3398 U32 mjd_nodelen = 0;
3399 #endif /* RE_TRACK_PATTERN_OFFSETS */
3400 #endif /* DEBUGGING */
3402 This means we convert either the first branch or the first Exact,
3403 depending on whether the thing following (in 'last') is a branch
3404 or not and whther first is the startbranch (ie is it a sub part of
3405 the alternation or is it the whole thing.)
3406 Assuming its a sub part we convert the EXACT otherwise we convert
3407 the whole branch sequence, including the first.
3409 /* Find the node we are going to overwrite */
3410 if ( first != startbranch || OP( last ) == BRANCH ) {
3411 /* branch sub-chain */
3412 NEXT_OFF( first ) = (U16)(last - first);
3413 #ifdef RE_TRACK_PATTERN_OFFSETS
3415 mjd_offset= Node_Offset((convert));
3416 mjd_nodelen= Node_Length((convert));
3419 /* whole branch chain */
3421 #ifdef RE_TRACK_PATTERN_OFFSETS
3424 const regnode *nop = NEXTOPER( convert );
3425 mjd_offset= Node_Offset((nop));
3426 mjd_nodelen= Node_Length((nop));
3430 Perl_re_indentf( aTHX_ "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
3432 (UV)mjd_offset, (UV)mjd_nodelen)
3435 /* But first we check to see if there is a common prefix we can
3436 split out as an EXACT and put in front of the TRIE node. */
3437 trie->startstate= 1;
3438 if ( trie->bitmap && !widecharmap && !trie->jump ) {
3439 /* we want to find the first state that has more than
3440 * one transition, if that state is not the first state
3441 * then we have a common prefix which we can remove.
3444 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3446 I32 first_ofs = -1; /* keeps track of the ofs of the first
3447 transition, -1 means none */
3449 const U32 base = trie->states[ state ].trans.base;
3451 /* does this state terminate an alternation? */
3452 if ( trie->states[state].wordnum )
3455 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3456 if ( ( base + ofs >= trie->uniquecharcount ) &&
3457 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3458 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3460 if ( ++count > 1 ) {
3461 /* we have more than one transition */
3464 /* if this is the first state there is no common prefix
3465 * to extract, so we can exit */
3466 if ( state == 1 ) break;
3467 tmp = av_fetch( revcharmap, ofs, 0);
3468 ch = (U8*)SvPV_nolen_const( *tmp );
3470 /* if we are on count 2 then we need to initialize the
3471 * bitmap, and store the previous char if there was one
3474 /* clear the bitmap */
3475 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3477 Perl_re_indentf( aTHX_ "New Start State=%" UVuf " Class: [",
3480 if (first_ofs >= 0) {
3481 SV ** const tmp = av_fetch( revcharmap, first_ofs, 0);
3482 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3484 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3486 Perl_re_printf( aTHX_ "%s", (char*)ch)
3490 /* store the current firstchar in the bitmap */
3491 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3492 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch));
3498 /* This state has only one transition, its transition is part
3499 * of a common prefix - we need to concatenate the char it
3500 * represents to what we have so far. */
3501 SV **tmp = av_fetch( revcharmap, first_ofs, 0);
3503 char *ch = SvPV( *tmp, len );
3505 SV *sv=sv_newmortal();
3506 Perl_re_indentf( aTHX_ "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n",
3508 (UV)state, (UV)first_ofs,
3509 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3510 PL_colors[0], PL_colors[1],
3511 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3512 PERL_PV_ESCAPE_FIRSTCHAR
3517 OP( convert ) = nodetype;
3518 str=STRING(convert);
3521 STR_LEN(convert) += len;
3527 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n"));
3532 trie->prefixlen = (state-1);
3534 regnode *n = convert+NODE_SZ_STR(convert);
3535 NEXT_OFF(convert) = NODE_SZ_STR(convert);
3536 trie->startstate = state;
3537 trie->minlen -= (state - 1);
3538 trie->maxlen -= (state - 1);
3540 /* At least the UNICOS C compiler choked on this
3541 * being argument to DEBUG_r(), so let's just have
3544 #ifdef PERL_EXT_RE_BUILD
3550 regnode *fix = convert;
3551 U32 word = trie->wordcount;
3552 #ifdef RE_TRACK_PATTERN_OFFSETS
3555 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3556 while( ++fix < n ) {
3557 Set_Node_Offset_Length(fix, 0, 0);
3560 SV ** const tmp = av_fetch( trie_words, word, 0 );
3562 if ( STR_LEN(convert) <= SvCUR(*tmp) )
3563 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3565 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3573 NEXT_OFF(convert) = (U16)(tail - convert);
3574 DEBUG_r(optimize= n);
3580 if ( trie->maxlen ) {
3581 NEXT_OFF( convert ) = (U16)(tail - convert);
3582 ARG_SET( convert, data_slot );
3583 /* Store the offset to the first unabsorbed branch in
3584 jump[0], which is otherwise unused by the jump logic.
3585 We use this when dumping a trie and during optimisation. */
3587 trie->jump[0] = (U16)(nextbranch - convert);
3589 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3590 * and there is a bitmap
3591 * and the first "jump target" node we found leaves enough room
3592 * then convert the TRIE node into a TRIEC node, with the bitmap
3593 * embedded inline in the opcode - this is hypothetically faster.
3595 if ( !trie->states[trie->startstate].wordnum
3597 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3599 OP( convert ) = TRIEC;
3600 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3601 PerlMemShared_free(trie->bitmap);
3604 OP( convert ) = TRIE;
3606 /* store the type in the flags */
3607 convert->flags = nodetype;
3611 + regarglen[ OP( convert ) ];
3613 /* XXX We really should free up the resource in trie now,
3614 as we won't use them - (which resources?) dmq */
3616 /* needed for dumping*/
3617 DEBUG_r(if (optimize) {
3618 regnode *opt = convert;
3620 while ( ++opt < optimize) {
3621 Set_Node_Offset_Length(opt, 0, 0);
3624 Try to clean up some of the debris left after the
3627 while( optimize < jumper ) {
3628 Track_Code( mjd_nodelen += Node_Length((optimize)); );
3629 OP( optimize ) = OPTIMIZED;
3630 Set_Node_Offset_Length(optimize, 0, 0);
3633 Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen);
3635 } /* end node insert */
3637 /* Finish populating the prev field of the wordinfo array. Walk back
3638 * from each accept state until we find another accept state, and if
3639 * so, point the first word's .prev field at the second word. If the
3640 * second already has a .prev field set, stop now. This will be the
3641 * case either if we've already processed that word's accept state,
3642 * or that state had multiple words, and the overspill words were
3643 * already linked up earlier.
3650 for (word=1; word <= trie->wordcount; word++) {
3652 if (trie->wordinfo[word].prev)
3654 state = trie->wordinfo[word].accept;
3656 state = prev_states[state];
3659 prev = trie->states[state].wordnum;
3663 trie->wordinfo[word].prev = prev;
3665 Safefree(prev_states);
3669 /* and now dump out the compressed format */
3670 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3672 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3674 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3675 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3677 SvREFCNT_dec_NN(revcharmap);
3681 : trie->startstate>1
3687 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3689 /* The Trie is constructed and compressed now so we can build a fail array if
3692 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3694 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3698 We find the fail state for each state in the trie, this state is the longest
3699 proper suffix of the current state's 'word' that is also a proper prefix of
3700 another word in our trie. State 1 represents the word '' and is thus the
3701 default fail state. This allows the DFA not to have to restart after its
3702 tried and failed a word at a given point, it simply continues as though it
3703 had been matching the other word in the first place.
3705 'abcdgu'=~/abcdefg|cdgu/
3706 When we get to 'd' we are still matching the first word, we would encounter
3707 'g' which would fail, which would bring us to the state representing 'd' in
3708 the second word where we would try 'g' and succeed, proceeding to match
3711 /* add a fail transition */
3712 const U32 trie_offset = ARG(source);
3713 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3715 const U32 ucharcount = trie->uniquecharcount;
3716 const U32 numstates = trie->statecount;
3717 const U32 ubound = trie->lasttrans + ucharcount;
3721 U32 base = trie->states[ 1 ].trans.base;
3724 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3726 GET_RE_DEBUG_FLAGS_DECL;
3728 PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3729 PERL_UNUSED_CONTEXT;
3731 PERL_UNUSED_ARG(depth);
3734 if ( OP(source) == TRIE ) {
3735 struct regnode_1 *op = (struct regnode_1 *)
3736 PerlMemShared_calloc(1, sizeof(struct regnode_1));
3737 StructCopy(source, op, struct regnode_1);
3738 stclass = (regnode *)op;
3740 struct regnode_charclass *op = (struct regnode_charclass *)
3741 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3742 StructCopy(source, op, struct regnode_charclass);
3743 stclass = (regnode *)op;
3745 OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3747 ARG_SET( stclass, data_slot );
3748 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3749 RExC_rxi->data->data[ data_slot ] = (void*)aho;
3750 aho->trie=trie_offset;
3751 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3752 Copy( trie->states, aho->states, numstates, reg_trie_state );
3753 Newx( q, numstates, U32);
3754 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3757 /* initialize fail[0..1] to be 1 so that we always have
3758 a valid final fail state */
3759 fail[ 0 ] = fail[ 1 ] = 1;
3761 for ( charid = 0; charid < ucharcount ; charid++ ) {
3762 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3764 q[ q_write ] = newstate;
3765 /* set to point at the root */
3766 fail[ q[ q_write++ ] ]=1;
3769 while ( q_read < q_write) {
3770 const U32 cur = q[ q_read++ % numstates ];
3771 base = trie->states[ cur ].trans.base;
3773 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3774 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3776 U32 fail_state = cur;
3779 fail_state = fail[ fail_state ];
3780 fail_base = aho->states[ fail_state ].trans.base;
3781 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3783 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3784 fail[ ch_state ] = fail_state;
3785 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3787 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
3789 q[ q_write++ % numstates] = ch_state;
3793 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3794 when we fail in state 1, this allows us to use the
3795 charclass scan to find a valid start char. This is based on the principle
3796 that theres a good chance the string being searched contains lots of stuff
3797 that cant be a start char.
3799 fail[ 0 ] = fail[ 1 ] = 0;
3800 DEBUG_TRIE_COMPILE_r({
3801 Perl_re_indentf( aTHX_ "Stclass Failtable (%" UVuf " states): 0",
3802 depth, (UV)numstates
3804 for( q_read=1; q_read<numstates; q_read++ ) {
3805 Perl_re_printf( aTHX_ ", %" UVuf, (UV)fail[q_read]);
3807 Perl_re_printf( aTHX_ "\n");
3810 /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3815 /* The below joins as many adjacent EXACTish nodes as possible into a single
3816 * one. The regop may be changed if the node(s) contain certain sequences that
3817 * require special handling. The joining is only done if:
3818 * 1) there is room in the current conglomerated node to entirely contain the
3820 * 2) they are compatible node types
3822 * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3823 * these get optimized out
3825 * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3826 * as possible, even if that means splitting an existing node so that its first
3827 * part is moved to the preceeding node. This would maximise the efficiency of
3828 * memEQ during matching.
3830 * If a node is to match under /i (folded), the number of characters it matches
3831 * can be different than its character length if it contains a multi-character
3832 * fold. *min_subtract is set to the total delta number of characters of the
3835 * And *unfolded_multi_char is set to indicate whether or not the node contains
3836 * an unfolded multi-char fold. This happens when it won't be known until
3837 * runtime whether the fold is valid or not; namely
3838 * 1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the
3839 * target string being matched against turns out to be UTF-8 is that fold
3841 * 2) for EXACTFL nodes whose folding rules depend on the locale in force at
3843 * (Multi-char folds whose components are all above the Latin1 range are not
3844 * run-time locale dependent, and have already been folded by the time this
3845 * function is called.)
3847 * This is as good a place as any to discuss the design of handling these
3848 * multi-character fold sequences. It's been wrong in Perl for a very long
3849 * time. There are three code points in Unicode whose multi-character folds
3850 * were long ago discovered to mess things up. The previous designs for
3851 * dealing with these involved assigning a special node for them. This
3852 * approach doesn't always work, as evidenced by this example:
3853 * "\xDFs" =~ /s\xDF/ui # Used to fail before these patches
3854 * Both sides fold to "sss", but if the pattern is parsed to create a node that
3855 * would match just the \xDF, it won't be able to handle the case where a
3856 * successful match would have to cross the node's boundary. The new approach
3857 * that hopefully generally solves the problem generates an EXACTFUP node
3858 * that is "sss" in this case.
3860 * It turns out that there are problems with all multi-character folds, and not
3861 * just these three. Now the code is general, for all such cases. The
3862 * approach taken is:
3863 * 1) This routine examines each EXACTFish node that could contain multi-
3864 * character folded sequences. Since a single character can fold into
3865 * such a sequence, the minimum match length for this node is less than
3866 * the number of characters in the node. This routine returns in
3867 * *min_subtract how many characters to subtract from the the actual
3868 * length of the string to get a real minimum match length; it is 0 if
3869 * there are no multi-char foldeds. This delta is used by the caller to
3870 * adjust the min length of the match, and the delta between min and max,
3871 * so that the optimizer doesn't reject these possibilities based on size
3874 * 2) For the sequence involving the LATIN SMALL LETTER SHARP S (U+00DF)
3875 * under /u, we fold it to 'ss' in regatom(), and in this routine, after
3876 * joining, we scan for occurrences of the sequence 'ss' in non-UTF-8
3877 * EXACTFU nodes. The node type of such nodes is then changed to
3878 * EXACTFUP, indicating it is problematic, and needs careful handling.
3879 * (The procedures in step 1) above are sufficient to handle this case in
3880 * UTF-8 encoded nodes.) The reason this is problematic is that this is
3881 * the only case where there is a possible fold length change in non-UTF-8
3882 * patterns. By reserving a special node type for problematic cases, the
3883 * far more common regular EXACTFU nodes can be processed faster.
3884 * regexec.c takes advantage of this.
3886 * EXACTFUP has been created as a grab-bag for (hopefully uncommon)
3887 * problematic cases. These all only occur when the pattern is not
3888 * UTF-8. In addition to the 'ss' sequence where there is a possible fold
3889 * length change, it handles the situation where the string cannot be
3890 * entirely folded. The strings in an EXACTFish node are folded as much
3891 * as possible during compilation in regcomp.c. This saves effort in
3892 * regex matching. By using an EXACTFUP node when it is not possible to
3893 * fully fold at compile time, regexec.c can know that everything in an
3894 * EXACTFU node is folded, so folding can be skipped at runtime. The only
3895 * case where folding in EXACTFU nodes can't be done at compile time is
3896 * the presumably uncommon MICRO SIGN, when the pattern isn't UTF-8. This
3897 * is because its fold requires UTF-8 to represent. Thus EXACTFUP nodes
3898 * handle two very different cases. Alternatively, there could have been
3899 * a node type where there are length changes, one for unfolded, and one
3900 * for both. If yet another special case needed to be created, the number
3901 * of required node types would have to go to 7. khw figures that even
3902 * though there are plenty of node types to spare, that the maintenance
3903 * cost wasn't worth the small speedup of doing it that way, especially
3904 * since he thinks the MICRO SIGN is rarely encountered in practice.
3906 * There are other cases where folding isn't done at compile time, but
3907 * none of them are under /u, and hence not for EXACTFU nodes. The folds
3908 * in EXACTFL nodes aren't known until runtime, and vary as the locale
3909 * changes. Some folds in EXACTF depend on if the runtime target string
3910 * is UTF-8 or not. (regatom() will create an EXACTFU node even under /di
3911 * when no fold in it depends on the UTF-8ness of the target string.)
3913 * 3) A problem remains for unfolded multi-char folds. (These occur when the
3914 * validity of the fold won't be known until runtime, and so must remain
3915 * unfolded for now. This happens for the sharp s in EXACTF and EXACTFAA
3916 * nodes when the pattern isn't in UTF-8. (Note, BTW, that there cannot
3917 * be an EXACTF node with a UTF-8 pattern.) They also occur for various
3918 * folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
3919 * The reason this is a problem is that the optimizer part of regexec.c
3920 * (probably unwittingly, in Perl_regexec_flags()) makes an assumption
3921 * that a character in the pattern corresponds to at most a single
3922 * character in the target string. (And I do mean character, and not byte
3923 * here, unlike other parts of the documentation that have never been
3924 * updated to account for multibyte Unicode.) Sharp s in EXACTF and
3925 * EXACTFL nodes can match the two character string 'ss'; in EXACTFAA
3926 * nodes it can match "\x{17F}\x{17F}". These, along with other ones in
3927 * EXACTFL nodes, violate the assumption, and they are the only instances
3928 * where it is violated. I'm reluctant to try to change the assumption,
3929 * as the code involved is impenetrable to me (khw), so instead the code
3930 * here punts. This routine examines EXACTFL nodes, and (when the pattern
3931 * isn't UTF-8) EXACTF and EXACTFAA for such unfolded folds, and returns a
3932 * boolean indicating whether or not the node contains such a fold. When
3933 * it is true, the caller sets a flag that later causes the optimizer in
3934 * this file to not set values for the floating and fixed string lengths,
3935 * and thus avoids the optimizer code in regexec.c that makes the invalid
3936 * assumption. Thus, there is no optimization based on string lengths for
3937 * EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
3938 * EXACTF and EXACTFAA nodes that contain the sharp s. (The reason the
3939 * assumption is wrong only in these cases is that all other non-UTF-8
3940 * folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
3941 * their expanded versions. (Again, we can't prefold sharp s to 'ss' in
3942 * EXACTF nodes because we don't know at compile time if it actually
3943 * matches 'ss' or not. For EXACTF nodes it will match iff the target
3944 * string is in UTF-8. This is in contrast to EXACTFU nodes, where it
3945 * always matches; and EXACTFAA where it never does. In an EXACTFAA node
3946 * in a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
3947 * problem; but in a non-UTF8 pattern, folding it to that above-Latin1
3948 * string would require the pattern to be forced into UTF-8, the overhead
3949 * of which we want to avoid. Similarly the unfolded multi-char folds in
3950 * EXACTFL nodes will match iff the locale at the time of match is a UTF-8
3953 * Similarly, the code that generates tries doesn't currently handle
3954 * not-already-folded multi-char folds, and it looks like a pain to change
3955 * that. Therefore, trie generation of EXACTFAA nodes with the sharp s
3956 * doesn't work. Instead, such an EXACTFAA is turned into a new regnode,
3957 * EXACTFAA_NO_TRIE, which the trie code knows not to handle. Most people
3958 * using /iaa matching will be doing so almost entirely with ASCII
3959 * strings, so this should rarely be encountered in practice */
3961 #define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
3962 if (PL_regkind[OP(scan)] == EXACT) \
3963 join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags), NULL, depth+1)
3966 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
3967 UV *min_subtract, bool *unfolded_multi_char,
3968 U32 flags, regnode *val, U32 depth)
3970 /* Merge several consecutive EXACTish nodes into one. */
3972 regnode *n = regnext(scan);
3974 regnode *next = scan + NODE_SZ_STR(scan);
3978 regnode *stop = scan;
3979 GET_RE_DEBUG_FLAGS_DECL;
3981 PERL_UNUSED_ARG(depth);
3984 PERL_ARGS_ASSERT_JOIN_EXACT;
3985 #ifndef EXPERIMENTAL_INPLACESCAN
3986 PERL_UNUSED_ARG(flags);
3987 PERL_UNUSED_ARG(val);
3989 DEBUG_PEEP("join", scan, depth, 0);
3991 assert(PL_regkind[OP(scan)] == EXACT);
3993 /* Look through the subsequent nodes in the chain. Skip NOTHING, merge
3994 * EXACT ones that are mergeable to the current one. */
3996 && ( PL_regkind[OP(n)] == NOTHING
3997 || (stringok && PL_regkind[OP(n)] == EXACT))
3999 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
4002 if (OP(n) == TAIL || n > next)
4004 if (PL_regkind[OP(n)] == NOTHING) {
4005 DEBUG_PEEP("skip:", n, depth, 0);
4006 NEXT_OFF(scan) += NEXT_OFF(n);
4007 next = n + NODE_STEP_REGNODE;
4014 else if (stringok) {
4015 const unsigned int oldl = STR_LEN(scan);
4016 regnode * const nnext = regnext(n);
4018 /* XXX I (khw) kind of doubt that this works on platforms (should
4019 * Perl ever run on one) where U8_MAX is above 255 because of lots
4020 * of other assumptions */
4021 /* Don't join if the sum can't fit into a single node */
4022 if (oldl + STR_LEN(n) > U8_MAX)
4025 /* Joining something that requires UTF-8 with something that
4026 * doesn't, means the result requires UTF-8. */
4027 if (OP(scan) == EXACT && (OP(n) == EXACT_ONLY8)) {
4028 OP(scan) = EXACT_ONLY8;
4030 else if (OP(scan) == EXACT_ONLY8 && (OP(n) == EXACT)) {
4031 ; /* join is compatible, no need to change OP */
4033 else if ((OP(scan) == EXACTFU) && (OP(n) == EXACTFU_ONLY8)) {
4034 OP(scan) = EXACTFU_ONLY8;
4036 else if ((OP(scan) == EXACTFU_ONLY8) && (OP(n) == EXACTFU)) {
4037 ; /* join is compatible, no need to change OP */
4039 else if (OP(scan) == EXACTFU && OP(n) == EXACTFU) {
4040 ; /* join is compatible, no need to change OP */
4042 else if (OP(scan) == EXACTFU && OP(n) == EXACTFU_S_EDGE) {
4044 /* Under /di, temporary EXACTFU_S_EDGE nodes are generated,
4045 * which can join with EXACTFU ones. We check for this case
4046 * here. These need to be resolved to either EXACTFU or
4047 * EXACTF at joining time. They have nothing in them that
4048 * would forbid them from being the more desirable EXACTFU
4049 * nodes except that they begin and/or end with a single [Ss].
4050 * The reason this is problematic is because they could be
4051 * joined in this loop with an adjacent node that ends and/or
4052 * begins with [Ss] which would then form the sequence 'ss',
4053 * which matches differently under /di than /ui, in which case
4054 * EXACTFU can't be used. If the 'ss' sequence doesn't get
4055 * formed, the nodes get absorbed into any adjacent EXACTFU
4056 * node. And if the only adjacent node is EXACTF, they get
4057 * absorbed into that, under the theory that a longer node is
4058 * better than two shorter ones, even if one is EXACTFU. Note
4059 * that EXACTFU_ONLY8 is generated only for UTF-8 patterns,
4060 * and the EXACTFU_S_EDGE ones only for non-UTF-8. */
4062 if (STRING(n)[STR_LEN(n)-1] == 's') {
4064 /* Here the joined node would end with 's'. If the node
4065 * following the combination is an EXACTF one, it's better to
4066 * join this trailing edge 's' node with that one, leaving the
4067 * current one in 'scan' be the more desirable EXACTFU */
4068 if (OP(nnext) == EXACTF) {
4072 OP(scan) = EXACTFU_S_EDGE;
4074 } /* Otherwise, the beginning 's' of the 2nd node just
4075 becomes an interior 's' in 'scan' */
4077 else if (OP(scan) == EXACTF && OP(n) == EXACTF) {
4078 ; /* join is compatible, no need to change OP */
4080 else if (OP(scan) == EXACTF && OP(n) == EXACTFU_S_EDGE) {
4082 /* EXACTF nodes are compatible for joining with EXACTFU_S_EDGE
4083 * nodes. But the latter nodes can be also joined with EXACTFU
4084 * ones, and that is a better outcome, so if the node following
4085 * 'n' is EXACTFU, quit now so that those two can be joined
4087 if (OP(nnext) == EXACTFU) {
4091 /* The join is compatible, and the combined node will be
4092 * EXACTF. (These don't care if they begin or end with 's' */
4094 else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU_S_EDGE) {
4095 if ( STRING(scan)[STR_LEN(scan)-1] == 's'
4096 && STRING(n)[0] == 's')
4098 /* When combined, we have the sequence 'ss', which means we
4099 * have to remain /di */
4103 else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU) {
4104 if (STRING(n)[0] == 's') {
4105 ; /* Here the join is compatible and the combined node
4106 starts with 's', no need to change OP */
4108 else { /* Now the trailing 's' is in the interior */
4112 else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTF) {
4114 /* The join is compatible, and the combined node will be
4115 * EXACTF. (These don't care if they begin or end with 's' */
4118 else if (OP(scan) != OP(n)) {
4120 /* The only other compatible joinings are the same node type */
4124 DEBUG_PEEP("merg", n, depth, 0);
4127 NEXT_OFF(scan) += NEXT_OFF(n);
4128 STR_LEN(scan) += STR_LEN(n);
4129 next = n + NODE_SZ_STR(n);
4130 /* Now we can overwrite *n : */
4131 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
4139 #ifdef EXPERIMENTAL_INPLACESCAN
4140 if (flags && !NEXT_OFF(n)) {
4141 DEBUG_PEEP("atch", val, depth, 0);
4142 if (reg_off_by_arg[OP(n)]) {
4143 ARG_SET(n, val - n);
4146 NEXT_OFF(n) = val - n;
4153 /* This temporary node can now be turned into EXACTFU, and must, as
4154 * regexec.c doesn't handle it */
4155 if (OP(scan) == EXACTFU_S_EDGE) {
4160 *unfolded_multi_char = FALSE;
4162 /* Here, all the adjacent mergeable EXACTish nodes have been merged. We
4163 * can now analyze for sequences of problematic code points. (Prior to
4164 * this final joining, sequences could have been split over boundaries, and
4165 * hence missed). The sequences only happen in folding, hence for any
4166 * non-EXACT EXACTish node */
4167 if (OP(scan) != EXACT && OP(scan) != EXACT_ONLY8 && OP(scan) != EXACTL) {
4168 U8* s0 = (U8*) STRING(scan);
4170 U8* s_end = s0 + STR_LEN(scan);
4172 int total_count_delta = 0; /* Total delta number of characters that
4173 multi-char folds expand to */
4175 /* One pass is made over the node's string looking for all the
4176 * possibilities. To avoid some tests in the loop, there are two main
4177 * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
4182 if (OP(scan) == EXACTFL) {
4185 /* An EXACTFL node would already have been changed to another
4186 * node type unless there is at least one character in it that
4187 * is problematic; likely a character whose fold definition
4188 * won't be known until runtime, and so has yet to be folded.
4189 * For all but the UTF-8 locale, folds are 1-1 in length, but
4190 * to handle the UTF-8 case, we need to create a temporary
4191 * folded copy using UTF-8 locale rules in order to analyze it.
4192 * This is because our macros that look to see if a sequence is
4193 * a multi-char fold assume everything is folded (otherwise the
4194 * tests in those macros would be too complicated and slow).
4195 * Note that here, the non-problematic folds will have already
4196 * been done, so we can just copy such characters. We actually
4197 * don't completely fold the EXACTFL string. We skip the
4198 * unfolded multi-char folds, as that would just create work
4199 * below to figure out the size they already are */
4201 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
4204 STRLEN s_len = UTF8SKIP(s);
4205 if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
4206 Copy(s, d, s_len, U8);
4209 else if (is_FOLDS_TO_MULTI_utf8(s)) {
4210 *unfolded_multi_char = TRUE;
4211 Copy(s, d, s_len, U8);
4214 else if (isASCII(*s)) {
4215 *(d++) = toFOLD(*s);
4219 _toFOLD_utf8_flags(s, s_end, d, &len, FOLD_FLAGS_FULL);
4225 /* Point the remainder of the routine to look at our temporary
4229 } /* End of creating folded copy of EXACTFL string */
4231 /* Examine the string for a multi-character fold sequence. UTF-8
4232 * patterns have all characters pre-folded by the time this code is
4234 while (s < s_end - 1) /* Can stop 1 before the end, as minimum
4235 length sequence we are looking for is 2 */
4237 int count = 0; /* How many characters in a multi-char fold */
4238 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
4239 if (! len) { /* Not a multi-char fold: get next char */
4244 { /* Here is a generic multi-char fold. */
4245 U8* multi_end = s + len;
4247 /* Count how many characters are in it. In the case of
4248 * /aa, no folds which contain ASCII code points are
4249 * allowed, so check for those, and skip if found. */
4250 if (OP(scan) != EXACTFAA && OP(scan) != EXACTFAA_NO_TRIE) {
4251 count = utf8_length(s, multi_end);
4255 while (s < multi_end) {
4258 goto next_iteration;
4268 /* The delta is how long the sequence is minus 1 (1 is how long
4269 * the character that folds to the sequence is) */
4270 total_count_delta += count - 1;
4274 /* We created a temporary folded copy of the string in EXACTFL
4275 * nodes. Therefore we need to be sure it doesn't go below zero,
4276 * as the real string could be shorter */
4277 if (OP(scan) == EXACTFL) {
4278 int total_chars = utf8_length((U8*) STRING(scan),
4279 (U8*) STRING(scan) + STR_LEN(scan));
4280 if (total_count_delta > total_chars) {
4281 total_count_delta = total_chars;
4285 *min_subtract += total_count_delta;
4288 else if (OP(scan) == EXACTFAA) {
4290 /* Non-UTF-8 pattern, EXACTFAA node. There can't be a multi-char
4291 * fold to the ASCII range (and there are no existing ones in the
4292 * upper latin1 range). But, as outlined in the comments preceding
4293 * this function, we need to flag any occurrences of the sharp s.
4294 * This character forbids trie formation (because of added
4296 #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
4297 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
4298 || UNICODE_DOT_DOT_VERSION > 0)
4300 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
4301 OP(scan) = EXACTFAA_NO_TRIE;
4302 *unfolded_multi_char = TRUE;
4310 /* Non-UTF-8 pattern, not EXACTFAA node. Look for the multi-char
4311 * folds that are all Latin1. As explained in the comments
4312 * preceding this function, we look also for the sharp s in EXACTF
4313 * and EXACTFL nodes; it can be in the final position. Otherwise
4314 * we can stop looking 1 byte earlier because have to find at least
4315 * two characters for a multi-fold */
4316 const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
4321 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
4322 if (! len) { /* Not a multi-char fold. */
4323 if (*s == LATIN_SMALL_LETTER_SHARP_S
4324 && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
4326 *unfolded_multi_char = TRUE;
4333 && isALPHA_FOLD_EQ(*s, 's')
4334 && isALPHA_FOLD_EQ(*(s+1), 's'))
4337 /* EXACTF nodes need to know that the minimum length
4338 * changed so that a sharp s in the string can match this
4339 * ss in the pattern, but they remain EXACTF nodes, as they
4340 * won't match this unless the target string is is UTF-8,
4341 * which we don't know until runtime. EXACTFL nodes can't
4342 * transform into EXACTFU nodes */
4343 if (OP(scan) != EXACTF && OP(scan) != EXACTFL) {
4344 OP(scan) = EXACTFUP;
4348 *min_subtract += len - 1;
4354 if ( STR_LEN(scan) == 1
4355 && isALPHA_A(* STRING(scan))
4356 && ( OP(scan) == EXACTFAA
4357 || ( OP(scan) == EXACTFU
4358 && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(scan)))))
4360 U8 mask = ~ ('A' ^ 'a'); /* These differ in just one bit */
4362 /* Replace a length 1 ASCII fold pair node with an ANYOFM node,
4363 * with the mask set to the complement of the bit that differs
4364 * between upper and lower case, and the lowest code point of the
4365 * pair (which the '&' forces) */
4367 ARG_SET(scan, *STRING(scan) & mask);
4373 /* Allow dumping but overwriting the collection of skipped
4374 * ops and/or strings with fake optimized ops */
4375 n = scan + NODE_SZ_STR(scan);
4383 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl", scan, depth, 0);});
4387 /* REx optimizer. Converts nodes into quicker variants "in place".
4388 Finds fixed substrings. */
4390 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
4391 to the position after last scanned or to NULL. */
4393 #define INIT_AND_WITHP \
4394 assert(!and_withp); \
4395 Newx(and_withp, 1, regnode_ssc); \
4396 SAVEFREEPV(and_withp)
4400 S_unwind_scan_frames(pTHX_ const void *p)
4402 scan_frame *f= (scan_frame *)p;
4404 scan_frame *n= f->next_frame;
4410 /* the return from this sub is the minimum length that could possibly match */
4412 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
4413 SSize_t *minlenp, SSize_t *deltap,
4418 regnode_ssc *and_withp,
4419 U32 flags, U32 depth)
4420 /* scanp: Start here (read-write). */
4421 /* deltap: Write maxlen-minlen here. */
4422 /* last: Stop before this one. */
4423 /* data: string data about the pattern */
4424 /* stopparen: treat close N as END */
4425 /* recursed: which subroutines have we recursed into */
4426 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
4429 /* There must be at least this number of characters to match */
4432 regnode *scan = *scanp, *next;
4434 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
4435 int is_inf_internal = 0; /* The studied chunk is infinite */
4436 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
4437 scan_data_t data_fake;
4438 SV *re_trie_maxbuff = NULL;
4439 regnode *first_non_open = scan;
4440 SSize_t stopmin = SSize_t_MAX;
4441 scan_frame *frame = NULL;
4442 GET_RE_DEBUG_FLAGS_DECL;
4444 PERL_ARGS_ASSERT_STUDY_CHUNK;
4445 RExC_study_started= 1;
4447 Zero(&data_fake, 1, scan_data_t);
4450 while (first_non_open && OP(first_non_open) == OPEN)
4451 first_non_open=regnext(first_non_open);
4457 RExC_study_chunk_recursed_count++;
4459 DEBUG_OPTIMISE_MORE_r(
4461 Perl_re_indentf( aTHX_ "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p",
4462 depth, (long)stopparen,
4463 (unsigned long)RExC_study_chunk_recursed_count,
4464 (unsigned long)depth, (unsigned long)recursed_depth,
4467 if (recursed_depth) {
4470 for ( j = 0 ; j < recursed_depth ; j++ ) {
4471 for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) {
4473 PAREN_TEST(RExC_study_chunk_recursed +
4474 ( j * RExC_study_chunk_recursed_bytes), i )
4477 !PAREN_TEST(RExC_study_chunk_recursed +
4478 (( j - 1 ) * RExC_study_chunk_recursed_bytes), i)
4481 Perl_re_printf( aTHX_ " %d",(int)i);
4485 if ( j + 1 < recursed_depth ) {
4486 Perl_re_printf( aTHX_ ",");
4490 Perl_re_printf( aTHX_ "\n");
4493 while ( scan && OP(scan) != END && scan < last ){
4494 UV min_subtract = 0; /* How mmany chars to subtract from the minimum
4495 node length to get a real minimum (because
4496 the folded version may be shorter) */
4497 bool unfolded_multi_char = FALSE;
4498 /* Peephole optimizer: */
4499 DEBUG_STUDYDATA("Peep", data, depth, is_inf);
4500 DEBUG_PEEP("Peep", scan, depth, flags);
4503 /* The reason we do this here is that we need to deal with things like
4504 * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT
4505 * parsing code, as each (?:..) is handled by a different invocation of
4508 JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);
4510 /* Follow the next-chain of the current node and optimize
4511 away all the NOTHINGs from it. */
4512 if (OP(scan) != CURLYX) {
4513 const int max = (reg_off_by_arg[OP(scan)]
4515 /* I32 may be smaller than U16 on CRAYs! */
4516 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
4517 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
4521 /* Skip NOTHING and LONGJMP. */
4522 while ((n = regnext(n))
4523 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
4524 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
4525 && off + noff < max)
4527 if (reg_off_by_arg[OP(scan)])
4530 NEXT_OFF(scan) = off;
4533 /* The principal pseudo-switch. Cannot be a switch, since we
4534 look into several different things. */
4535 if ( OP(scan) == DEFINEP ) {
4537 SSize_t deltanext = 0;
4538 SSize_t fake_last_close = 0;
4539 I32 f = SCF_IN_DEFINE;
4541 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4542 scan = regnext(scan);
4543 assert( OP(scan) == IFTHEN );
4544 DEBUG_PEEP("expect IFTHEN", scan, depth, flags);
4546 data_fake.last_closep= &fake_last_close;
4548 next = regnext(scan);
4549 scan = NEXTOPER(NEXTOPER(scan));
4550 DEBUG_PEEP("scan", scan, depth, flags);
4551 DEBUG_PEEP("next", next, depth, flags);
4553 /* we suppose the run is continuous, last=next...
4554 * NOTE we dont use the return here! */
4555 /* DEFINEP study_chunk() recursion */
4556 (void)study_chunk(pRExC_state, &scan, &minlen,
4557 &deltanext, next, &data_fake, stopparen,
4558 recursed_depth, NULL, f, depth+1);
4563 OP(scan) == BRANCH ||
4564 OP(scan) == BRANCHJ ||
4567 next = regnext(scan);
4570 /* The op(next)==code check below is to see if we
4571 * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN"
4572 * IFTHEN is special as it might not appear in pairs.
4573 * Not sure whether BRANCH-BRANCHJ is possible, regardless
4574 * we dont handle it cleanly. */
4575 if (OP(next) == code || code == IFTHEN) {
4576 /* NOTE - There is similar code to this block below for
4577 * handling TRIE nodes on a re-study. If you change stuff here
4578 * check there too. */
4579 SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0;
4581 regnode * const startbranch=scan;
4583 if (flags & SCF_DO_SUBSTR) {
4584 /* Cannot merge strings after this. */
4585 scan_commit(pRExC_state, data, minlenp, is_inf);
4588 if (flags & SCF_DO_STCLASS)
4589 ssc_init_zero(pRExC_state, &accum);
4591 while (OP(scan) == code) {
4592 SSize_t deltanext, minnext, fake;
4594 regnode_ssc this_class;
4596 DEBUG_PEEP("Branch", scan, depth, flags);
4599 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4601 data_fake.whilem_c = data->whilem_c;
4602 data_fake.last_closep = data->last_closep;
4605 data_fake.last_closep = &fake;
4607 data_fake.pos_delta = delta;
4608 next = regnext(scan);
4610 scan = NEXTOPER(scan); /* everything */
4611 if (code != BRANCH) /* everything but BRANCH */
4612 scan = NEXTOPER(scan);
4614 if (flags & SCF_DO_STCLASS) {
4615 ssc_init(pRExC_state, &this_class);
4616 data_fake.start_class = &this_class;
4617 f = SCF_DO_STCLASS_AND;
4619 if (flags & SCF_WHILEM_VISITED_POS)
4620 f |= SCF_WHILEM_VISITED_POS;
4622 /* we suppose the run is continuous, last=next...*/
4623 /* recurse study_chunk() for each BRANCH in an alternation */
4624 minnext = study_chunk(pRExC_state, &scan, minlenp,
4625 &deltanext, next, &data_fake, stopparen,
4626 recursed_depth, NULL, f, depth+1);
4630 if (deltanext == SSize_t_MAX) {
4631 is_inf = is_inf_internal = 1;
4633 } else if (max1 < minnext + deltanext)
4634 max1 = minnext + deltanext;
4636 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4638 if (data_fake.flags & SCF_SEEN_ACCEPT) {
4639 if ( stopmin > minnext)
4640 stopmin = min + min1;
4641 flags &= ~SCF_DO_SUBSTR;
4643 data->flags |= SCF_SEEN_ACCEPT;
4646 if (data_fake.flags & SF_HAS_EVAL)
4647 data->flags |= SF_HAS_EVAL;
4648 data->whilem_c = data_fake.whilem_c;
4650 if (flags & SCF_DO_STCLASS)
4651 ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);
4653 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
4655 if (flags & SCF_DO_SUBSTR) {
4656 data->pos_min += min1;
4657 if (data->pos_delta >= SSize_t_MAX - (max1 - min1))
4658 data->pos_delta = SSize_t_MAX;
4660 data->pos_delta += max1 - min1;
4661 if (max1 != min1 || is_inf)
4662 data->cur_is_floating = 1;
4665 if (delta == SSize_t_MAX
4666 || SSize_t_MAX - delta - (max1 - min1) < 0)
4667 delta = SSize_t_MAX;
4669 delta += max1 - min1;
4670 if (flags & SCF_DO_STCLASS_OR) {
4671 ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);
4673 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4674 flags &= ~SCF_DO_STCLASS;
4677 else if (flags & SCF_DO_STCLASS_AND) {
4679 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
4680 flags &= ~SCF_DO_STCLASS;
4683 /* Switch to OR mode: cache the old value of
4684 * data->start_class */
4686 StructCopy(data->start_class, and_withp, regnode_ssc);
4687 flags &= ~SCF_DO_STCLASS_AND;
4688 StructCopy(&accum, data->start_class, regnode_ssc);
4689 flags |= SCF_DO_STCLASS_OR;
4693 if (PERL_ENABLE_TRIE_OPTIMISATION &&
4694 OP( startbranch ) == BRANCH )
4698 Assuming this was/is a branch we are dealing with: 'scan'
4699 now points at the item that follows the branch sequence,
4700 whatever it is. We now start at the beginning of the
4701 sequence and look for subsequences of
4707 which would be constructed from a pattern like
4710 If we can find such a subsequence we need to turn the first
4711 element into a trie and then add the subsequent branch exact
4712 strings to the trie.
4716 1. patterns where the whole set of branches can be
4719 2. patterns where only a subset can be converted.
4721 In case 1 we can replace the whole set with a single regop
4722 for the trie. In case 2 we need to keep the start and end
4725 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
4726 becomes BRANCH TRIE; BRANCH X;
4728 There is an additional case, that being where there is a
4729 common prefix, which gets split out into an EXACT like node
4730 preceding the TRIE node.
4732 If x(1..n)==tail then we can do a simple trie, if not we make
4733 a "jump" trie, such that when we match the appropriate word
4734 we "jump" to the appropriate tail node. Essentially we turn
4735 a nested if into a case structure of sorts.
4740 if (!re_trie_maxbuff) {
4741 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
4742 if (!SvIOK(re_trie_maxbuff))
4743 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
4745 if ( SvIV(re_trie_maxbuff)>=0 ) {
4747 regnode *first = (regnode *)NULL;
4748 regnode *last = (regnode *)NULL;
4749 regnode *tail = scan;
4753 /* var tail is used because there may be a TAIL
4754 regop in the way. Ie, the exacts will point to the
4755 thing following the TAIL, but the last branch will
4756 point at the TAIL. So we advance tail. If we
4757 have nested (?:) we may have to move through several
4761 while ( OP( tail ) == TAIL ) {
4762 /* this is the TAIL generated by (?:) */
4763 tail = regnext( tail );
4767 DEBUG_TRIE_COMPILE_r({
4768 regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);
4769 Perl_re_indentf( aTHX_ "%s %" UVuf ":%s\n",
4771 "Looking for TRIE'able sequences. Tail node is ",
4772 (UV) REGNODE_OFFSET(tail),
4773 SvPV_nolen_const( RExC_mysv )
4779 Step through the branches
4780 cur represents each branch,
4781 noper is the first thing to be matched as part
4783 noper_next is the regnext() of that node.
4785 We normally handle a case like this
4786 /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also
4787 support building with NOJUMPTRIE, which restricts
4788 the trie logic to structures like /FOO|BAR/.
4790 If noper is a trieable nodetype then the branch is
4791 a possible optimization target. If we are building
4792 under NOJUMPTRIE then we require that noper_next is
4793 the same as scan (our current position in the regex
4796 Once we have two or more consecutive such branches
4797 we can create a trie of the EXACT's contents and
4798 stitch it in place into the program.
4800 If the sequence represents all of the branches in
4801 the alternation we replace the entire thing with a
4804 Otherwise when it is a subsequence we need to
4805 stitch it in place and replace only the relevant
4806 branches. This means the first branch has to remain
4807 as it is used by the alternation logic, and its
4808 next pointer, and needs to be repointed at the item
4809 on the branch chain following the last branch we
4810 have optimized away.
4812 This could be either a BRANCH, in which case the
4813 subsequence is internal, or it could be the item
4814 following the branch sequence in which case the
4815 subsequence is at the end (which does not
4816 necessarily mean the first node is the start of the
4819 TRIE_TYPE(X) is a define which maps the optype to a
4823 ----------------+-----------
4828 EXACTFU_ONLY8 | EXACTFU
4832 EXACTFLU8 | EXACTFLU8
4836 #define TRIE_TYPE(X) ( ( NOTHING == (X) ) \
4838 : ( EXACT == (X) || EXACT_ONLY8 == (X) ) \
4840 : ( EXACTFU == (X) \
4841 || EXACTFU_ONLY8 == (X) \
4842 || EXACTFUP == (X) ) \
4844 : ( EXACTFAA == (X) ) \
4846 : ( EXACTL == (X) ) \
4848 : ( EXACTFLU8 == (X) ) \
4852 /* dont use tail as the end marker for this traverse */
4853 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
4854 regnode * const noper = NEXTOPER( cur );
4855 U8 noper_type = OP( noper );
4856 U8 noper_trietype = TRIE_TYPE( noper_type );
4857 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
4858 regnode * const noper_next = regnext( noper );
4859 U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
4860 U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0;
4863 DEBUG_TRIE_COMPILE_r({
4864 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4865 Perl_re_indentf( aTHX_ "- %d:%s (%d)",
4867 REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );
4869 regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);
4870 Perl_re_printf( aTHX_ " -> %d:%s",
4871 REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv));
4874 regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);
4875 Perl_re_printf( aTHX_ "\t=> %d:%s\t",
4876 REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv));
4878 Perl_re_printf( aTHX_ "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n",
4879 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
4880 PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]
4884 /* Is noper a trieable nodetype that can be merged
4885 * with the current trie (if there is one)? */
4889 ( noper_trietype == NOTHING )
4890 || ( trietype == NOTHING )
4891 || ( trietype == noper_trietype )
4894 && noper_next >= tail
4898 /* Handle mergable triable node Either we are
4899 * the first node in a new trieable sequence,
4900 * in which case we do some bookkeeping,
4901 * otherwise we update the end pointer. */
4904 if ( noper_trietype == NOTHING ) {
4905 #if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
4906 regnode * const noper_next = regnext( noper );
4907 U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
4908 U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
4911 if ( noper_next_trietype ) {
4912 trietype = noper_next_trietype;
4913 } else if (noper_next_type) {
4914 /* a NOTHING regop is 1 regop wide.
4915 * We need at least two for a trie
4916 * so we can't merge this in */
4920 trietype = noper_trietype;
4923 if ( trietype == NOTHING )
4924 trietype = noper_trietype;
4929 } /* end handle mergable triable node */
4931 /* handle unmergable node -
4932 * noper may either be a triable node which can
4933 * not be tried together with the current trie,
4934 * or a non triable node */
4936 /* If last is set and trietype is not
4937 * NOTHING then we have found at least two
4938 * triable branch sequences in a row of a
4939 * similar trietype so we can turn them
4940 * into a trie. If/when we allow NOTHING to
4941 * start a trie sequence this condition
4942 * will be required, and it isn't expensive
4943 * so we leave it in for now. */
4944 if ( trietype && trietype != NOTHING )
4945 make_trie( pRExC_state,
4946 startbranch, first, cur, tail,
4947 count, trietype, depth+1 );
4948 last = NULL; /* note: we clear/update
4949 first, trietype etc below,
4950 so we dont do it here */
4954 && noper_next >= tail
4957 /* noper is triable, so we can start a new
4961 trietype = noper_trietype;
4963 /* if we already saw a first but the
4964 * current node is not triable then we have
4965 * to reset the first information. */
4970 } /* end handle unmergable node */
4971 } /* loop over branches */
4972 DEBUG_TRIE_COMPILE_r({
4973 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4974 Perl_re_indentf( aTHX_ "- %s (%d) <SCAN FINISHED> ",
4975 depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
4976 Perl_re_printf( aTHX_ "(First==%d, Last==%d, Cur==%d, tt==%s)\n",
4977 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
4978 PL_reg_name[trietype]
4982 if ( last && trietype ) {
4983 if ( trietype != NOTHING ) {
4984 /* the last branch of the sequence was part of
4985 * a trie, so we have to construct it here
4986 * outside of the loop */
4987 made= make_trie( pRExC_state, startbranch,
4988 first, scan, tail, count,
4989 trietype, depth+1 );
4990 #ifdef TRIE_STUDY_OPT
4991 if ( ((made == MADE_EXACT_TRIE &&
4992 startbranch == first)
4993 || ( first_non_open == first )) &&
4995 flags |= SCF_TRIE_RESTUDY;
4996 if ( startbranch == first
4999 RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;
5004 /* at this point we know whatever we have is a
5005 * NOTHING sequence/branch AND if 'startbranch'
5006 * is 'first' then we can turn the whole thing
5009 if ( startbranch == first ) {
5011 /* the entire thing is a NOTHING sequence,
5012 * something like this: (?:|) So we can
5013 * turn it into a plain NOTHING op. */
5014 DEBUG_TRIE_COMPILE_r({
5015 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5016 Perl_re_indentf( aTHX_ "- %s (%d) <NOTHING BRANCH SEQUENCE>\n",
5018 SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
5021 OP(startbranch)= NOTHING;
5022 NEXT_OFF(startbranch)= tail - startbranch;
5023 for ( opt= startbranch + 1; opt < tail ; opt++ )
5027 } /* end if ( last) */
5028 } /* TRIE_MAXBUF is non zero */
5033 else if ( code == BRANCHJ ) { /* single branch is optimized. */
5034 scan = NEXTOPER(NEXTOPER(scan));
5035 } else /* single branch is optimized. */
5036 scan = NEXTOPER(scan);
5038 } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) {
5040 regnode *start = NULL;
5041 regnode *end = NULL;
5042 U32 my_recursed_depth= recursed_depth;
5044 if (OP(scan) != SUSPEND) { /* GOSUB */
5045 /* Do setup, note this code has side effects beyond
5046 * the rest of this block. Specifically setting
5047 * RExC_recurse[] must happen at least once during
5050 RExC_recurse[ARG2L(scan)] = scan;
5051 start = REGNODE_p(RExC_open_parens[paren]);
5052 end = REGNODE_p(RExC_close_parens[paren]);
5054 /* NOTE we MUST always execute the above code, even
5055 * if we do nothing with a GOSUB */
5057 ( flags & SCF_IN_DEFINE )
5060 (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))
5062 ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )
5065 /* no need to do anything here if we are in a define. */
5066 /* or we are after some kind of infinite construct
5067 * so we can skip recursing into this item.
5068 * Since it is infinite we will not change the maxlen
5069 * or delta, and if we miss something that might raise
5070 * the minlen it will merely pessimise a little.
5072 * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/
5073 * might result in a minlen of 1 and not of 4,
5074 * but this doesn't make us mismatch, just try a bit
5075 * harder than we should.
5077 scan= regnext(scan);
5084 !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren)
5086 /* it is quite possible that there are more efficient ways
5087 * to do this. We maintain a bitmap per level of recursion
5088 * of which patterns we have entered so we can detect if a
5089 * pattern creates a possible infinite loop. When we
5090 * recurse down a level we copy the previous levels bitmap
5091 * down. When we are at recursion level 0 we zero the top
5092 * level bitmap. It would be nice to implement a different
5093 * more efficient way of doing this. In particular the top
5094 * level bitmap may be unnecessary.
5096 if (!recursed_depth) {
5097 Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);
5099 Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes),
5100 RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes),
5101 RExC_study_chunk_recursed_bytes, U8);
5103 /* we havent recursed into this paren yet, so recurse into it */
5104 DEBUG_STUDYDATA("gosub-set", data, depth, is_inf);
5105 PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren);
5106 my_recursed_depth= recursed_depth + 1;
5108 DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf);
5109 /* some form of infinite recursion, assume infinite length
5111 if (flags & SCF_DO_SUBSTR) {
5112 scan_commit(pRExC_state, data, minlenp, is_inf);
5113 data->cur_is_floating = 1;
5115 is_inf = is_inf_internal = 1;
5116 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5117 ssc_anything(data->start_class);
5118 flags &= ~SCF_DO_STCLASS;
5120 start= NULL; /* reset start so we dont recurse later on. */
5125 end = regnext(scan);
5128 scan_frame *newframe;
5130 if (!RExC_frame_last) {
5131 Newxz(newframe, 1, scan_frame);
5132 SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);
5133 RExC_frame_head= newframe;
5135 } else if (!RExC_frame_last->next_frame) {
5136 Newxz(newframe, 1, scan_frame);
5137 RExC_frame_last->next_frame= newframe;
5138 newframe->prev_frame= RExC_frame_last;
5141 newframe= RExC_frame_last->next_frame;
5143 RExC_frame_last= newframe;
5145 newframe->next_regnode = regnext(scan);
5146 newframe->last_regnode = last;
5147 newframe->stopparen = stopparen;
5148 newframe->prev_recursed_depth = recursed_depth;
5149 newframe->this_prev_frame= frame;
5151 DEBUG_STUDYDATA("frame-new", data, depth, is_inf);
5152 DEBUG_PEEP("fnew", scan, depth, flags);
5159 recursed_depth= my_recursed_depth;
5164 else if ( OP(scan) == EXACT
5165 || OP(scan) == EXACT_ONLY8
5166 || OP(scan) == EXACTL)
5168 SSize_t l = STR_LEN(scan);
5172 const U8 * const s = (U8*)STRING(scan);
5173 uc = utf8_to_uvchr_buf(s, s + l, NULL);
5174 l = utf8_length(s, s + l);
5176 uc = *((U8*)STRING(scan));
5179 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
5180 /* The code below prefers earlier match for fixed
5181 offset, later match for variable offset. */
5182 if (data->last_end == -1) { /* Update the start info. */
5183 data->last_start_min = data->pos_min;
5184 data->last_start_max = is_inf
5185 ? SSize_t_MAX : data->pos_min + data->pos_delta;
5187 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
5189 SvUTF8_on(data->last_found);
5191 SV * const sv = data->last_found;
5192 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5193 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5194 if (mg && mg->mg_len >= 0)
5195 mg->mg_len += utf8_length((U8*)STRING(scan),
5196 (U8*)STRING(scan)+STR_LEN(scan));
5198 data->last_end = data->pos_min + l;
5199 data->pos_min += l; /* As in the first entry. */
5200 data->flags &= ~SF_BEFORE_EOL;
5203 /* ANDing the code point leaves at most it, and not in locale, and
5204 * can't match null string */
5205 if (flags & SCF_DO_STCLASS_AND) {
5206 ssc_cp_and(data->start_class, uc);
5207 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5208 ssc_clear_locale(data->start_class);
5210 else if (flags & SCF_DO_STCLASS_OR) {
5211 ssc_add_cp(data->start_class, uc);
5212 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5214 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5215 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5217 flags &= ~SCF_DO_STCLASS;
5219 else if (PL_regkind[OP(scan)] == EXACT) {
5220 /* But OP != EXACT!, so is EXACTFish */
5221 SSize_t l = STR_LEN(scan);
5222 const U8 * s = (U8*)STRING(scan);
5224 /* Search for fixed substrings supports EXACT only. */
5225 if (flags & SCF_DO_SUBSTR) {
5227 scan_commit(pRExC_state, data, minlenp, is_inf);
5230 l = utf8_length(s, s + l);
5232 if (unfolded_multi_char) {
5233 RExC_seen |= REG_UNFOLDED_MULTI_SEEN;
5235 min += l - min_subtract;
5237 delta += min_subtract;
5238 if (flags & SCF_DO_SUBSTR) {
5239 data->pos_min += l - min_subtract;
5240 if (data->pos_min < 0) {
5243 data->pos_delta += min_subtract;
5245 data->cur_is_floating = 1; /* float */
5249 if (flags & SCF_DO_STCLASS) {
5250 SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan);
5252 assert(EXACTF_invlist);
5253 if (flags & SCF_DO_STCLASS_AND) {
5254 if (OP(scan) != EXACTFL)
5255 ssc_clear_locale(data->start_class);
5256 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5257 ANYOF_POSIXL_ZERO(data->start_class);
5258 ssc_intersection(data->start_class, EXACTF_invlist, FALSE);
5260 else { /* SCF_DO_STCLASS_OR */
5261 ssc_union(data->start_class, EXACTF_invlist, FALSE);
5262 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5264 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5265 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5267 flags &= ~SCF_DO_STCLASS;
5268 SvREFCNT_dec(EXACTF_invlist);
5271 else if (REGNODE_VARIES(OP(scan))) {
5272 SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;
5273 I32 fl = 0, f = flags;
5274 regnode * const oscan = scan;
5275 regnode_ssc this_class;
5276 regnode_ssc *oclass = NULL;
5277 I32 next_is_eval = 0;
5279 switch (PL_regkind[OP(scan)]) {
5280 case WHILEM: /* End of (?:...)* . */
5281 scan = NEXTOPER(scan);
5284 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
5285 next = NEXTOPER(scan);
5286 if ( OP(next) == EXACT
5287 || OP(next) == EXACT_ONLY8
5288 || OP(next) == EXACTL
5289 || (flags & SCF_DO_STCLASS))
5292 maxcount = REG_INFTY;
5293 next = regnext(scan);
5294 scan = NEXTOPER(scan);
5298 if (flags & SCF_DO_SUBSTR)
5303 next = NEXTOPER(scan);
5305 /* This temporary node can now be turned into EXACTFU, and
5306 * must, as regexec.c doesn't handle it */
5307 if (OP(next) == EXACTFU_S_EDGE) {
5311 if ( STR_LEN(next) == 1
5312 && isALPHA_A(* STRING(next))
5313 && ( OP(next) == EXACTFAA
5314 || ( OP(next) == EXACTFU
5315 && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next)))))
5317 /* These differ in just one bit */
5318 U8 mask = ~ ('A' ^ 'a');
5320 assert(isALPHA_A(* STRING(next)));
5322 /* Then replace it by an ANYOFM node, with
5323 * the mask set to the complement of the
5324 * bit that differs between upper and lower
5325 * case, and the lowest code point of the
5326 * pair (which the '&' forces) */
5328 ARG_SET(next, *STRING(next) & mask);
5332 if (flags & SCF_DO_STCLASS) {
5334 maxcount = REG_INFTY;
5335 next = regnext(scan);
5336 scan = NEXTOPER(scan);
5339 if (flags & SCF_DO_SUBSTR) {
5340 scan_commit(pRExC_state, data, minlenp, is_inf);
5341 /* Cannot extend fixed substrings */
5342 data->cur_is_floating = 1; /* float */
5344 is_inf = is_inf_internal = 1;
5345 scan = regnext(scan);
5346 goto optimize_curly_tail;
5348 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
5349 && (scan->flags == stopparen))
5354 mincount = ARG1(scan);
5355 maxcount = ARG2(scan);
5357 next = regnext(scan);
5358 if (OP(scan) == CURLYX) {
5359 I32 lp = (data ? *(data->last_closep) : 0);
5360 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
5362 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
5363 next_is_eval = (OP(scan) == EVAL);
5365 if (flags & SCF_DO_SUBSTR) {
5367 scan_commit(pRExC_state, data, minlenp, is_inf);
5368 /* Cannot extend fixed substrings */
5369 pos_before = data->pos_min;
5373 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
5375 data->flags |= SF_IS_INF;
5377 if (flags & SCF_DO_STCLASS) {
5378 ssc_init(pRExC_state, &this_class);
5379 oclass = data->start_class;
5380 data->start_class = &this_class;
5381 f |= SCF_DO_STCLASS_AND;
5382 f &= ~SCF_DO_STCLASS_OR;
5384 /* Exclude from super-linear cache processing any {n,m}
5385 regops for which the combination of input pos and regex
5386 pos is not enough information to determine if a match
5389 For example, in the regex /foo(bar\s*){4,8}baz/ with the
5390 regex pos at the \s*, the prospects for a match depend not
5391 only on the input position but also on how many (bar\s*)
5392 repeats into the {4,8} we are. */
5393 if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
5394 f &= ~SCF_WHILEM_VISITED_POS;
5396 /* This will finish on WHILEM, setting scan, or on NULL: */
5397 /* recurse study_chunk() on loop bodies */
5398 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
5399 last, data, stopparen, recursed_depth, NULL,
5401 ? (f & ~SCF_DO_SUBSTR)
5405 if (flags & SCF_DO_STCLASS)
5406 data->start_class = oclass;
5407 if (mincount == 0 || minnext == 0) {
5408 if (flags & SCF_DO_STCLASS_OR) {
5409 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5411 else if (flags & SCF_DO_STCLASS_AND) {
5412 /* Switch to OR mode: cache the old value of
5413 * data->start_class */
5415 StructCopy(data->start_class, and_withp, regnode_ssc);
5416 flags &= ~SCF_DO_STCLASS_AND;
5417 StructCopy(&this_class, data->start_class, regnode_ssc);
5418 flags |= SCF_DO_STCLASS_OR;
5419 ANYOF_FLAGS(data->start_class)
5420 |= SSC_MATCHES_EMPTY_STRING;
5422 } else { /* Non-zero len */
5423 if (flags & SCF_DO_STCLASS_OR) {
5424 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5425 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5427 else if (flags & SCF_DO_STCLASS_AND)
5428 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5429 flags &= ~SCF_DO_STCLASS;
5431 if (!scan) /* It was not CURLYX, but CURLY. */
5433 if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR)
5434 /* ? quantifier ok, except for (?{ ... }) */
5435 && (next_is_eval || !(mincount == 0 && maxcount == 1))
5436 && (minnext == 0) && (deltanext == 0)
5437 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
5438 && maxcount <= REG_INFTY/3) /* Complement check for big
5441 _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP),
5442 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
5443 "Quantifier unexpected on zero-length expression "
5444 "in regex m/%" UTF8f "/",
5445 UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,
5449 min += minnext * mincount;
5450 is_inf_internal |= deltanext == SSize_t_MAX
5451 || (maxcount == REG_INFTY && minnext + deltanext > 0);
5452 is_inf |= is_inf_internal;
5454 delta = SSize_t_MAX;
5456 delta += (minnext + deltanext) * maxcount
5457 - minnext * mincount;
5459 /* Try powerful optimization CURLYX => CURLYN. */
5460 if ( OP(oscan) == CURLYX && data
5461 && data->flags & SF_IN_PAR
5462 && !(data->flags & SF_HAS_EVAL)
5463 && !deltanext && minnext == 1 ) {
5464 /* Try to optimize to CURLYN. */
5465 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
5466 regnode * const nxt1 = nxt;
5473 if (!REGNODE_SIMPLE(OP(nxt))
5474 && !(PL_regkind[OP(nxt)] == EXACT
5475 && STR_LEN(nxt) == 1))
5481 if (OP(nxt) != CLOSE)
5483 if (RExC_open_parens) {
5486 RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5489 RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2;
5491 /* Now we know that nxt2 is the only contents: */
5492 oscan->flags = (U8)ARG(nxt);
5494 OP(nxt1) = NOTHING; /* was OPEN. */
5497 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5498 NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
5499 NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
5500 OP(nxt) = OPTIMIZED; /* was CLOSE. */
5501 OP(nxt + 1) = OPTIMIZED; /* was count. */
5502 NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
5507 /* Try optimization CURLYX => CURLYM. */
5508 if ( OP(oscan) == CURLYX && data
5509 && !(data->flags & SF_HAS_PAR)
5510 && !(data->flags & SF_HAS_EVAL)
5511 && !deltanext /* atom is fixed width */
5512 && minnext != 0 /* CURLYM can't handle zero width */
5514 /* Nor characters whose fold at run-time may be
5515 * multi-character */
5516 && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)
5518 /* XXXX How to optimize if data == 0? */
5519 /* Optimize to a simpler form. */
5520 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
5524 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
5525 && (OP(nxt2) != WHILEM))
5527 OP(nxt2) = SUCCEED; /* Whas WHILEM */
5528 /* Need to optimize away parenths. */
5529 if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
5530 /* Set the parenth number. */
5531 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
5533 oscan->flags = (U8)ARG(nxt);
5534 if (RExC_open_parens) {
5536 RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5539 RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2)
5542 OP(nxt1) = OPTIMIZED; /* was OPEN. */
5543 OP(nxt) = OPTIMIZED; /* was CLOSE. */
5546 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5547 OP(nxt + 1) = OPTIMIZED; /* was count. */
5548 NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
5549 NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
5552 while ( nxt1 && (OP(nxt1) != WHILEM)) {
5553 regnode *nnxt = regnext(nxt1);
5555 if (reg_off_by_arg[OP(nxt1)])
5556 ARG_SET(nxt1, nxt2 - nxt1);
5557 else if (nxt2 - nxt1 < U16_MAX)
5558 NEXT_OFF(nxt1) = nxt2 - nxt1;
5560 OP(nxt) = NOTHING; /* Cannot beautify */
5565 /* Optimize again: */
5566 /* recurse study_chunk() on optimised CURLYX => CURLYM */
5567 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
5568 NULL, stopparen, recursed_depth, NULL, 0,
5574 else if ((OP(oscan) == CURLYX)
5575 && (flags & SCF_WHILEM_VISITED_POS)
5576 /* See the comment on a similar expression above.
5577 However, this time it's not a subexpression
5578 we care about, but the expression itself. */
5579 && (maxcount == REG_INFTY)
5581 /* This stays as CURLYX, we can put the count/of pair. */
5582 /* Find WHILEM (as in regexec.c) */
5583 regnode *nxt = oscan + NEXT_OFF(oscan);
5585 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
5587 nxt = PREVOPER(nxt);
5588 if (nxt->flags & 0xf) {
5589 /* we've already set whilem count on this node */
5590 } else if (++data->whilem_c < 16) {
5591 assert(data->whilem_c <= RExC_whilem_seen);
5592 nxt->flags = (U8)(data->whilem_c
5593 | (RExC_whilem_seen << 4)); /* On WHILEM */
5596 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
5598 if (flags & SCF_DO_SUBSTR) {
5599 SV *last_str = NULL;
5600 STRLEN last_chrs = 0;
5601 int counted = mincount != 0;
5603 if (data->last_end > 0 && mincount != 0) { /* Ends with a
5605 SSize_t b = pos_before >= data->last_start_min
5606 ? pos_before : data->last_start_min;
5608 const char * const s = SvPV_const(data->last_found, l);
5609 SSize_t old = b - data->last_start_min;
5612 old = utf8_hop((U8*)s, old) - (U8*)s;
5614 /* Get the added string: */
5615 last_str = newSVpvn_utf8(s + old, l, UTF);
5616 last_chrs = UTF ? utf8_length((U8*)(s + old),
5617 (U8*)(s + old + l)) : l;
5618 if (deltanext == 0 && pos_before == b) {
5619 /* What was added is a constant string */
5622 SvGROW(last_str, (mincount * l) + 1);
5623 repeatcpy(SvPVX(last_str) + l,
5624 SvPVX_const(last_str), l,
5626 SvCUR_set(last_str, SvCUR(last_str) * mincount);
5627 /* Add additional parts. */
5628 SvCUR_set(data->last_found,
5629 SvCUR(data->last_found) - l);
5630 sv_catsv(data->last_found, last_str);
5632 SV * sv = data->last_found;
5634 SvUTF8(sv) && SvMAGICAL(sv) ?
5635 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5636 if (mg && mg->mg_len >= 0)
5637 mg->mg_len += last_chrs * (mincount-1);
5639 last_chrs *= mincount;
5640 data->last_end += l * (mincount - 1);
5643 /* start offset must point into the last copy */
5644 data->last_start_min += minnext * (mincount - 1);
5645 data->last_start_max =
5648 : data->last_start_max +
5649 (maxcount - 1) * (minnext + data->pos_delta);
5652 /* It is counted once already... */
5653 data->pos_min += minnext * (mincount - counted);
5655 Perl_re_printf( aTHX_ "counted=%" UVuf " deltanext=%" UVuf
5656 " SSize_t_MAX=%" UVuf " minnext=%" UVuf
5657 " maxcount=%" UVuf " mincount=%" UVuf "\n",
5658 (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount,
5660 if (deltanext != SSize_t_MAX)
5661 Perl_re_printf( aTHX_ "LHS=%" UVuf " RHS=%" UVuf "\n",
5662 (UV)(-counted * deltanext + (minnext + deltanext) * maxcount
5663 - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta));
5665 if (deltanext == SSize_t_MAX
5666 || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta)
5667 data->pos_delta = SSize_t_MAX;
5669 data->pos_delta += - counted * deltanext +
5670 (minnext + deltanext) * maxcount - minnext * mincount;
5671 if (mincount != maxcount) {
5672 /* Cannot extend fixed substrings found inside
5674 scan_commit(pRExC_state, data, minlenp, is_inf);
5675 if (mincount && last_str) {
5676 SV * const sv = data->last_found;
5677 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5678 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5682 sv_setsv(sv, last_str);
5683 data->last_end = data->pos_min;
5684 data->last_start_min = data->pos_min - last_chrs;
5685 data->last_start_max = is_inf
5687 : data->pos_min + data->pos_delta - last_chrs;
5689 data->cur_is_floating = 1; /* float */
5691 SvREFCNT_dec(last_str);
5693 if (data && (fl & SF_HAS_EVAL))
5694 data->flags |= SF_HAS_EVAL;
5695 optimize_curly_tail:
5696 if (OP(oscan) != CURLYX) {
5697 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
5699 NEXT_OFF(oscan) += NEXT_OFF(next);
5705 Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d",
5710 if (flags & SCF_DO_SUBSTR) {
5711 /* Cannot expect anything... */
5712 scan_commit(pRExC_state, data, minlenp, is_inf);
5713 data->cur_is_floating = 1; /* float */
5715 is_inf = is_inf_internal = 1;
5716 if (flags & SCF_DO_STCLASS_OR) {
5717 if (OP(scan) == CLUMP) {
5718 /* Actually is any start char, but very few code points
5719 * aren't start characters */
5720 ssc_match_all_cp(data->start_class);
5723 ssc_anything(data->start_class);
5726 flags &= ~SCF_DO_STCLASS;
5730 else if (OP(scan) == LNBREAK) {
5731 if (flags & SCF_DO_STCLASS) {
5732 if (flags & SCF_DO_STCLASS_AND) {
5733 ssc_intersection(data->start_class,
5734 PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);
5735 ssc_clear_locale(data->start_class);
5736 ANYOF_FLAGS(data->start_class)
5737 &= ~SSC_MATCHES_EMPTY_STRING;
5739 else if (flags & SCF_DO_STCLASS_OR) {
5740 ssc_union(data->start_class,
5741 PL_XPosix_ptrs[_CC_VERTSPACE],
5743 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5745 /* See commit msg for
5746 * 749e076fceedeb708a624933726e7989f2302f6a */
5747 ANYOF_FLAGS(data->start_class)
5748 &= ~SSC_MATCHES_EMPTY_STRING;
5750 flags &= ~SCF_DO_STCLASS;
5753 if (delta != SSize_t_MAX)
5754 delta++; /* Because of the 2 char string cr-lf */
5755 if (flags & SCF_DO_SUBSTR) {
5756 /* Cannot expect anything... */
5757 scan_commit(pRExC_state, data, minlenp, is_inf);
5759 if (data->pos_delta != SSize_t_MAX) {
5760 data->pos_delta += 1;
5762 data->cur_is_floating = 1; /* float */
5765 else if (REGNODE_SIMPLE(OP(scan))) {
5767 if (flags & SCF_DO_SUBSTR) {
5768 scan_commit(pRExC_state, data, minlenp, is_inf);
5772 if (flags & SCF_DO_STCLASS) {
5774 SV* my_invlist = NULL;
5777 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5778 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5780 /* Some of the logic below assumes that switching
5781 locale on will only add false positives. */
5786 Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d",
5790 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5791 ssc_match_all_cp(data->start_class);
5796 SV* REG_ANY_invlist = _new_invlist(2);
5797 REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,
5799 if (flags & SCF_DO_STCLASS_OR) {
5800 ssc_union(data->start_class,
5802 TRUE /* TRUE => invert, hence all but \n
5806 else if (flags & SCF_DO_STCLASS_AND) {
5807 ssc_intersection(data->start_class,
5809 TRUE /* TRUE => invert */
5811 ssc_clear_locale(data->start_class);
5813 SvREFCNT_dec_NN(REG_ANY_invlist);
5822 if (flags & SCF_DO_STCLASS_AND)
5823 ssc_and(pRExC_state, data->start_class,
5824 (regnode_charclass *) scan);
5826 ssc_or(pRExC_state, data->start_class,
5827 (regnode_charclass *) scan);
5833 SV* cp_list = get_ANYOFM_contents(scan);
5835 if (flags & SCF_DO_STCLASS_OR) {
5836 ssc_union(data->start_class, cp_list, invert);
5838 else if (flags & SCF_DO_STCLASS_AND) {
5839 ssc_intersection(data->start_class, cp_list, invert);
5842 SvREFCNT_dec_NN(cp_list);
5851 namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;
5852 if (flags & SCF_DO_STCLASS_AND) {
5853 bool was_there = cBOOL(
5854 ANYOF_POSIXL_TEST(data->start_class,
5856 ANYOF_POSIXL_ZERO(data->start_class);
5857 if (was_there) { /* Do an AND */
5858 ANYOF_POSIXL_SET(data->start_class, namedclass);
5860 /* No individual code points can now match */
5861 data->start_class->invlist
5862 = sv_2mortal(_new_invlist(0));
5865 int complement = namedclass + ((invert) ? -1 : 1);
5867 assert(flags & SCF_DO_STCLASS_OR);
5869 /* If the complement of this class was already there,
5870 * the result is that they match all code points,
5871 * (\d + \D == everything). Remove the classes from
5872 * future consideration. Locale is not relevant in
5874 if (ANYOF_POSIXL_TEST(data->start_class, complement)) {
5875 ssc_match_all_cp(data->start_class);
5876 ANYOF_POSIXL_CLEAR(data->start_class, namedclass);
5877 ANYOF_POSIXL_CLEAR(data->start_class, complement);
5879 else { /* The usual case; just add this class to the
5881 ANYOF_POSIXL_SET(data->start_class, namedclass);
5886 case NPOSIXA: /* For these, we always know the exact set of
5891 my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL);
5892 goto join_posix_and_ascii;
5900 my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL);
5902 /* NPOSIXD matches all upper Latin1 code points unless the
5903 * target string being matched is UTF-8, which is
5904 * unknowable until match time. Since we are going to
5905 * invert, we want to get rid of all of them so that the
5906 * inversion will match all */
5907 if (OP(scan) == NPOSIXD) {
5908 _invlist_subtract(my_invlist, PL_UpperLatin1,
5912 join_posix_and_ascii:
5914 if (flags & SCF_DO_STCLASS_AND) {
5915 ssc_intersection(data->start_class, my_invlist, invert);
5916 ssc_clear_locale(data->start_class);
5919 assert(flags & SCF_DO_STCLASS_OR);
5920 ssc_union(data->start_class, my_invlist, invert);
5922 SvREFCNT_dec(my_invlist);
5924 if (flags & SCF_DO_STCLASS_OR)
5925 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5926 flags &= ~SCF_DO_STCLASS;
5929 else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
5930 data->flags |= (OP(scan) == MEOL
5933 scan_commit(pRExC_state, data, minlenp, is_inf);
5936 else if ( PL_regkind[OP(scan)] == BRANCHJ
5937 /* Lookbehind, or need to calculate parens/evals/stclass: */
5938 && (scan->flags || data || (flags & SCF_DO_STCLASS))
5939 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM))
5941 if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
5942 || OP(scan) == UNLESSM )
5944 /* Negative Lookahead/lookbehind
5945 In this case we can't do fixed string optimisation.
5948 SSize_t deltanext, minnext, fake = 0;
5953 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
5955 data_fake.whilem_c = data->whilem_c;
5956 data_fake.last_closep = data->last_closep;
5959 data_fake.last_closep = &fake;
5960 data_fake.pos_delta = delta;
5961 if ( flags & SCF_DO_STCLASS && !scan->flags
5962 && OP(scan) == IFMATCH ) { /* Lookahead */
5963 ssc_init(pRExC_state, &intrnl);
5964 data_fake.start_class = &intrnl;
5965 f |= SCF_DO_STCLASS_AND;
5967 if (flags & SCF_WHILEM_VISITED_POS)
5968 f |= SCF_WHILEM_VISITED_POS;
5969 next = regnext(scan);
5970 nscan = NEXTOPER(NEXTOPER(scan));
5972 /* recurse study_chunk() for lookahead body */
5973 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
5974 last, &data_fake, stopparen,
5975 recursed_depth, NULL, f, depth+1);
5978 FAIL("Variable length lookbehind not implemented");
5980 else if (minnext > (I32)U8_MAX) {
5981 FAIL2("Lookbehind longer than %" UVuf " not implemented",
5984 scan->flags = (U8)minnext;
5987 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
5989 if (data_fake.flags & SF_HAS_EVAL)
5990 data->flags |= SF_HAS_EVAL;
5991 data->whilem_c = data_fake.whilem_c;
5993 if (f & SCF_DO_STCLASS_AND) {
5994 if (flags & SCF_DO_STCLASS_OR) {
5995 /* OR before, AND after: ideally we would recurse with
5996 * data_fake to get the AND applied by study of the
5997 * remainder of the pattern, and then derecurse;
5998 * *** HACK *** for now just treat as "no information".
5999 * See [perl #56690].
6001 ssc_init(pRExC_state, data->start_class);
6003 /* AND before and after: combine and continue. These
6004 * assertions are zero-length, so can match an EMPTY
6006 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6007 ANYOF_FLAGS(data->start_class)
6008 |= SSC_MATCHES_EMPTY_STRING;
6012 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
6014 /* Positive Lookahead/lookbehind
6015 In this case we can do fixed string optimisation,
6016 but we must be careful about it. Note in the case of
6017 lookbehind the positions will be offset by the minimum
6018 length of the pattern, something we won't know about
6019 until after the recurse.
6021 SSize_t deltanext, fake = 0;
6025 /* We use SAVEFREEPV so that when the full compile
6026 is finished perl will clean up the allocated
6027 minlens when it's all done. This way we don't
6028 have to worry about freeing them when we know
6029 they wont be used, which would be a pain.
6032 Newx( minnextp, 1, SSize_t );
6033 SAVEFREEPV(minnextp);
6036 StructCopy(data, &data_fake, scan_data_t);
6037 if ((flags & SCF_DO_SUBSTR) && data->last_found) {
6040 scan_commit(pRExC_state, &data_fake, minlenp, is_inf);
6041 data_fake.last_found=newSVsv(data->last_found);
6045 data_fake.last_closep = &fake;
6046 data_fake.flags = 0;
6047 data_fake.substrs[0].flags = 0;
6048 data_fake.substrs[1].flags = 0;
6049 data_fake.pos_delta = delta;
6051 data_fake.flags |= SF_IS_INF;
6052 if ( flags & SCF_DO_STCLASS && !scan->flags
6053 && OP(scan) == IFMATCH ) { /* Lookahead */
6054 ssc_init(pRExC_state, &intrnl);
6055 data_fake.start_class = &intrnl;
6056 f |= SCF_DO_STCLASS_AND;
6058 if (flags & SCF_WHILEM_VISITED_POS)
6059 f |= SCF_WHILEM_VISITED_POS;
6060 next = regnext(scan);
6061 nscan = NEXTOPER(NEXTOPER(scan));
6063 /* positive lookahead study_chunk() recursion */
6064 *minnextp = study_chunk(pRExC_state, &nscan, minnextp,
6065 &deltanext, last, &data_fake,
6066 stopparen, recursed_depth, NULL,
6070 FAIL("Variable length lookbehind not implemented");
6072 else if (*minnextp > (I32)U8_MAX) {
6073 FAIL2("Lookbehind longer than %" UVuf " not implemented",
6076 scan->flags = (U8)*minnextp;
6081 if (f & SCF_DO_STCLASS_AND) {
6082 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6083 ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;
6086 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6088 if (data_fake.flags & SF_HAS_EVAL)
6089 data->flags |= SF_HAS_EVAL;
6090 data->whilem_c = data_fake.whilem_c;
6091 if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
6093 if (RExC_rx->minlen<*minnextp)
6094 RExC_rx->minlen=*minnextp;
6095 scan_commit(pRExC_state, &data_fake, minnextp, is_inf);
6096 SvREFCNT_dec_NN(data_fake.last_found);
6098 for (i = 0; i < 2; i++) {
6099 if (data_fake.substrs[i].minlenp != minlenp) {
6100 data->substrs[i].min_offset =
6101 data_fake.substrs[i].min_offset;
6102 data->substrs[i].max_offset =
6103 data_fake.substrs[i].max_offset;
6104 data->substrs[i].minlenp =
6105 data_fake.substrs[i].minlenp;
6106 data->substrs[i].lookbehind += scan->flags;
6115 else if (OP(scan) == OPEN) {
6116 if (stopparen != (I32)ARG(scan))
6119 else if (OP(scan) == CLOSE) {
6120 if (stopparen == (I32)ARG(scan)) {
6123 if ((I32)ARG(scan) == is_par) {
6124 next = regnext(scan);
6126 if ( next && (OP(next) != WHILEM) && next < last)
6127 is_par = 0; /* Disable optimization */
6130 *(data->last_closep) = ARG(scan);
6132 else if (OP(scan) == EVAL) {
6134 data->flags |= SF_HAS_EVAL;
6136 else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
6137 if (flags & SCF_DO_SUBSTR) {
6138 scan_commit(pRExC_state, data, minlenp, is_inf);
6139 flags &= ~SCF_DO_SUBSTR;
6141 if (data && OP(scan)==ACCEPT) {
6142 data->flags |= SCF_SEEN_ACCEPT;
6147 else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
6149 if (flags & SCF_DO_SUBSTR) {
6150 scan_commit(pRExC_state, data, minlenp, is_inf);
6151 data->cur_is_floating = 1; /* float */
6153 is_inf = is_inf_internal = 1;
6154 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
6155 ssc_anything(data->start_class);
6156 flags &= ~SCF_DO_STCLASS;
6158 else if (OP(scan) == GPOS) {
6159 if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&
6160 !(delta || is_inf || (data && data->pos_delta)))
6162 if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))
6163 RExC_rx->intflags |= PREGf_ANCH_GPOS;
6164 if (RExC_rx->gofs < (STRLEN)min)
6165 RExC_rx->gofs = min;
6167 RExC_rx->intflags |= PREGf_GPOS_FLOAT;
6171 #ifdef TRIE_STUDY_OPT
6172 #ifdef FULL_TRIE_STUDY
6173 else if (PL_regkind[OP(scan)] == TRIE) {
6174 /* NOTE - There is similar code to this block above for handling
6175 BRANCH nodes on the initial study. If you change stuff here
6177 regnode *trie_node= scan;
6178 regnode *tail= regnext(scan);
6179 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6180 SSize_t max1 = 0, min1 = SSize_t_MAX;
6183 if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */
6184 /* Cannot merge strings after this. */
6185 scan_commit(pRExC_state, data, minlenp, is_inf);
6187 if (flags & SCF_DO_STCLASS)
6188 ssc_init_zero(pRExC_state, &accum);
6194 const regnode *nextbranch= NULL;
6197 for ( word=1 ; word <= trie->wordcount ; word++)
6199 SSize_t deltanext=0, minnext=0, f = 0, fake;
6200 regnode_ssc this_class;
6202 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6204 data_fake.whilem_c = data->whilem_c;
6205 data_fake.last_closep = data->last_closep;
6208 data_fake.last_closep = &fake;
6209 data_fake.pos_delta = delta;
6210 if (flags & SCF_DO_STCLASS) {
6211 ssc_init(pRExC_state, &this_class);
6212 data_fake.start_class = &this_class;
6213 f = SCF_DO_STCLASS_AND;
6215 if (flags & SCF_WHILEM_VISITED_POS)
6216 f |= SCF_WHILEM_VISITED_POS;
6218 if (trie->jump[word]) {
6220 nextbranch = trie_node + trie->jump[0];
6221 scan= trie_node + trie->jump[word];
6222 /* We go from the jump point to the branch that follows
6223 it. Note this means we need the vestigal unused
6224 branches even though they arent otherwise used. */
6225 /* optimise study_chunk() for TRIE */
6226 minnext = study_chunk(pRExC_state, &scan, minlenp,
6227 &deltanext, (regnode *)nextbranch, &data_fake,
6228 stopparen, recursed_depth, NULL, f, depth+1);
6230 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
6231 nextbranch= regnext((regnode*)nextbranch);
6233 if (min1 > (SSize_t)(minnext + trie->minlen))
6234 min1 = minnext + trie->minlen;
6235 if (deltanext == SSize_t_MAX) {
6236 is_inf = is_inf_internal = 1;
6238 } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))
6239 max1 = minnext + deltanext + trie->maxlen;
6241 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6243 if (data_fake.flags & SCF_SEEN_ACCEPT) {
6244 if ( stopmin > min + min1)
6245 stopmin = min + min1;
6246 flags &= ~SCF_DO_SUBSTR;
6248 data->flags |= SCF_SEEN_ACCEPT;
6251 if (data_fake.flags & SF_HAS_EVAL)
6252 data->flags |= SF_HAS_EVAL;
6253 data->whilem_c = data_fake.whilem_c;
6255 if (flags & SCF_DO_STCLASS)
6256 ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);
6259 if (flags & SCF_DO_SUBSTR) {
6260 data->pos_min += min1;
6261 data->pos_delta += max1 - min1;
6262 if (max1 != min1 || is_inf)
6263 data->cur_is_floating = 1; /* float */
6266 if (delta != SSize_t_MAX) {
6267 if (SSize_t_MAX - (max1 - min1) >= delta)
6268 delta += max1 - min1;
6270 delta = SSize_t_MAX;
6272 if (flags & SCF_DO_STCLASS_OR) {
6273 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6275 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6276 flags &= ~SCF_DO_STCLASS;
6279 else if (flags & SCF_DO_STCLASS_AND) {
6281 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6282 flags &= ~SCF_DO_STCLASS;
6285 /* Switch to OR mode: cache the old value of
6286 * data->start_class */
6288 StructCopy(data->start_class, and_withp, regnode_ssc);
6289 flags &= ~SCF_DO_STCLASS_AND;
6290 StructCopy(&accum, data->start_class, regnode_ssc);
6291 flags |= SCF_DO_STCLASS_OR;
6298 else if (PL_regkind[OP(scan)] == TRIE) {
6299 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6302 min += trie->minlen;
6303 delta += (trie->maxlen - trie->minlen);
6304 flags &= ~SCF_DO_STCLASS; /* xxx */
6305 if (flags & SCF_DO_SUBSTR) {
6306 /* Cannot expect anything... */
6307 scan_commit(pRExC_state, data, minlenp, is_inf);
6308 data->pos_min += trie->minlen;
6309 data->pos_delta += (trie->maxlen - trie->minlen);
6310 if (trie->maxlen != trie->minlen)
6311 data->cur_is_floating = 1; /* float */
6313 if (trie->jump) /* no more substrings -- for now /grr*/
6314 flags &= ~SCF_DO_SUBSTR;
6316 #endif /* old or new */
6317 #endif /* TRIE_STUDY_OPT */
6319 /* Else: zero-length, ignore. */
6320 scan = regnext(scan);
6325 /* we need to unwind recursion. */
6328 DEBUG_STUDYDATA("frame-end", data, depth, is_inf);
6329 DEBUG_PEEP("fend", scan, depth, flags);
6331 /* restore previous context */
6332 last = frame->last_regnode;
6333 scan = frame->next_regnode;
6334 stopparen = frame->stopparen;
6335 recursed_depth = frame->prev_recursed_depth;
6337 RExC_frame_last = frame->prev_frame;
6338 frame = frame->this_prev_frame;
6339 goto fake_study_recurse;
6343 DEBUG_STUDYDATA("pre-fin", data, depth, is_inf);
6346 *deltap = is_inf_internal ? SSize_t_MAX : delta;
6348 if (flags & SCF_DO_SUBSTR && is_inf)
6349 data->pos_delta = SSize_t_MAX - data->pos_min;
6350 if (is_par > (I32)U8_MAX)
6352 if (is_par && pars==1 && data) {
6353 data->flags |= SF_IN_PAR;
6354 data->flags &= ~SF_HAS_PAR;
6356 else if (pars && data) {
6357 data->flags |= SF_HAS_PAR;
6358 data->flags &= ~SF_IN_PAR;
6360 if (flags & SCF_DO_STCLASS_OR)
6361 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6362 if (flags & SCF_TRIE_RESTUDY)
6363 data->flags |= SCF_TRIE_RESTUDY;
6365 DEBUG_STUDYDATA("post-fin", data, depth, is_inf);
6368 SSize_t final_minlen= min < stopmin ? min : stopmin;
6370 if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {
6371 if (final_minlen > SSize_t_MAX - delta)
6372 RExC_maxlen = SSize_t_MAX;
6373 else if (RExC_maxlen < final_minlen + delta)
6374 RExC_maxlen = final_minlen + delta;
6376 return final_minlen;
6378 NOT_REACHED; /* NOTREACHED */
6382 S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n)
6384 U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
6386 PERL_ARGS_ASSERT_ADD_DATA;
6388 Renewc(RExC_rxi->data,
6389 sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
6390 char, struct reg_data);
6392 Renew(RExC_rxi->data->what, count + n, U8);
6394 Newx(RExC_rxi->data->what, n, U8);
6395 RExC_rxi->data->count = count + n;
6396 Copy(s, RExC_rxi->data->what + count, n, U8);
6400 /*XXX: todo make this not included in a non debugging perl, but appears to be
6401 * used anyway there, in 'use re' */
6402 #ifndef PERL_IN_XSUB_RE
6404 Perl_reginitcolors(pTHX)
6406 const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
6408 char *t = savepv(s);
6412 t = strchr(t, '\t');
6418 PL_colors[i] = t = (char *)"";
6423 PL_colors[i++] = (char *)"";
6430 #ifdef TRIE_STUDY_OPT
6431 #define CHECK_RESTUDY_GOTO_butfirst(dOsomething) \
6434 (data.flags & SCF_TRIE_RESTUDY) \
6442 #define CHECK_RESTUDY_GOTO_butfirst
6446 * pregcomp - compile a regular expression into internal code
6448 * Decides which engine's compiler to call based on the hint currently in
6452 #ifndef PERL_IN_XSUB_RE
6454 /* return the currently in-scope regex engine (or the default if none) */
6456 regexp_engine const *
6457 Perl_current_re_engine(pTHX)
6459 if (IN_PERL_COMPILETIME) {
6460 HV * const table = GvHV(PL_hintgv);
6463 if (!table || !(PL_hints & HINT_LOCALIZE_HH))
6464 return &PL_core_reg_engine;
6465 ptr = hv_fetchs(table, "regcomp", FALSE);
6466 if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
6467 return &PL_core_reg_engine;
6468 return INT2PTR(regexp_engine*, SvIV(*ptr));
6472 if (!PL_curcop->cop_hints_hash)
6473 return &PL_core_reg_engine;
6474 ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
6475 if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
6476 return &PL_core_reg_engine;
6477 return INT2PTR(regexp_engine*, SvIV(ptr));
6483 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
6485 regexp_engine const *eng = current_re_engine();
6486 GET_RE_DEBUG_FLAGS_DECL;
6488 PERL_ARGS_ASSERT_PREGCOMP;
6490 /* Dispatch a request to compile a regexp to correct regexp engine. */
6492 Perl_re_printf( aTHX_ "Using engine %" UVxf "\n",
6495 return CALLREGCOMP_ENG(eng, pattern, flags);
6499 /* public(ish) entry point for the perl core's own regex compiling code.
6500 * It's actually a wrapper for Perl_re_op_compile that only takes an SV
6501 * pattern rather than a list of OPs, and uses the internal engine rather
6502 * than the current one */
6505 Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
6507 SV *pat = pattern; /* defeat constness! */
6508 PERL_ARGS_ASSERT_RE_COMPILE;
6509 return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
6510 #ifdef PERL_IN_XSUB_RE
6513 &PL_core_reg_engine,
6515 NULL, NULL, rx_flags, 0);
6520 S_free_codeblocks(pTHX_ struct reg_code_blocks *cbs)
6524 if (--cbs->refcnt > 0)
6526 for (n = 0; n < cbs->count; n++) {
6527 REGEXP *rx = cbs->cb[n].src_regex;
6529 cbs->cb[n].src_regex = NULL;
6530 SvREFCNT_dec_NN(rx);
6538 static struct reg_code_blocks *
6539 S_alloc_code_blocks(pTHX_ int ncode)
6541 struct reg_code_blocks *cbs;
6542 Newx(cbs, 1, struct reg_code_blocks);
6545 SAVEDESTRUCTOR_X(S_free_codeblocks, cbs);
6547 Newx(cbs->cb, ncode, struct reg_code_block);
6554 /* upgrade pattern pat_p of length plen_p to UTF8, and if there are code
6555 * blocks, recalculate the indices. Update pat_p and plen_p in-place to
6556 * point to the realloced string and length.
6558 * This is essentially a copy of Perl_bytes_to_utf8() with the code index
6562 S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state,
6563 char **pat_p, STRLEN *plen_p, int num_code_blocks)
6565 U8 *const src = (U8*)*pat_p;
6570 GET_RE_DEBUG_FLAGS_DECL;
6572 DEBUG_PARSE_r(Perl_re_printf( aTHX_
6573 "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
6575 /* 1 for each byte + 1 for each byte that expands to two, + trailing NUL */
6576 Newx(dst, *plen_p + variant_under_utf8_count(src, src + *plen_p) + 1, U8);
6579 while (s < *plen_p) {
6580 append_utf8_from_native_byte(src[s], &d);
6582 if (n < num_code_blocks) {
6583 assert(pRExC_state->code_blocks);
6584 if (!do_end && pRExC_state->code_blocks->cb[n].start == s) {
6585 pRExC_state->code_blocks->cb[n].start = d - dst - 1;
6586 assert(*(d - 1) == '(');
6589 else if (do_end && pRExC_state->code_blocks->cb[n].end == s) {
6590 pRExC_state->code_blocks->cb[n].end = d - dst - 1;
6591 assert(*(d - 1) == ')');
6600 *pat_p = (char*) dst;
6602 RExC_orig_utf8 = RExC_utf8 = 1;
6607 /* S_concat_pat(): concatenate a list of args to the pattern string pat,
6608 * while recording any code block indices, and handling overloading,
6609 * nested qr// objects etc. If pat is null, it will allocate a new
6610 * string, or just return the first arg, if there's only one.
6612 * Returns the malloced/updated pat.
6613 * patternp and pat_count is the array of SVs to be concatted;
6614 * oplist is the optional list of ops that generated the SVs;
6615 * recompile_p is a pointer to a boolean that will be set if
6616 * the regex will need to be recompiled.
6617 * delim, if non-null is an SV that will be inserted between each element
6621 S_concat_pat(pTHX_ RExC_state_t * const pRExC_state,
6622 SV *pat, SV ** const patternp, int pat_count,
6623 OP *oplist, bool *recompile_p, SV *delim)
6627 bool use_delim = FALSE;
6628 bool alloced = FALSE;
6630 /* if we know we have at least two args, create an empty string,
6631 * then concatenate args to that. For no args, return an empty string */
6632 if (!pat && pat_count != 1) {
6638 for (svp = patternp; svp < patternp + pat_count; svp++) {
6641 STRLEN orig_patlen = 0;
6643 SV *msv = use_delim ? delim : *svp;
6644 if (!msv) msv = &PL_sv_undef;
6646 /* if we've got a delimiter, we go round the loop twice for each
6647 * svp slot (except the last), using the delimiter the second
6656 if (SvTYPE(msv) == SVt_PVAV) {
6657 /* we've encountered an interpolated array within
6658 * the pattern, e.g. /...@a..../. Expand the list of elements,
6659 * then recursively append elements.
6660 * The code in this block is based on S_pushav() */
6662 AV *const av = (AV*)msv;
6663 const SSize_t maxarg = AvFILL(av) + 1;
6667 assert(oplist->op_type == OP_PADAV
6668 || oplist->op_type == OP_RV2AV);
6669 oplist = OpSIBLING(oplist);
6672 if (SvRMAGICAL(av)) {
6675 Newx(array, maxarg, SV*);
6677 for (i=0; i < maxarg; i++) {
6678 SV ** const svp = av_fetch(av, i, FALSE);
6679 array[i] = svp ? *svp : &PL_sv_undef;
6683 array = AvARRAY(av);
6685 pat = S_concat_pat(aTHX_ pRExC_state, pat,
6686 array, maxarg, NULL, recompile_p,
6688 GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV))));
6694 /* we make the assumption here that each op in the list of
6695 * op_siblings maps to one SV pushed onto the stack,
6696 * except for code blocks, with have both an OP_NULL and
6698 * This allows us to match up the list of SVs against the
6699 * list of OPs to find the next code block.
6701 * Note that PUSHMARK PADSV PADSV ..
6703 * PADRANGE PADSV PADSV ..
6704 * so the alignment still works. */
6707 if (oplist->op_type == OP_NULL
6708 && (oplist->op_flags & OPf_SPECIAL))
6710 assert(n < pRExC_state->code_blocks->count);
6711 pRExC_state->code_blocks->cb[n].start = pat ? SvCUR(pat) : 0;
6712 pRExC_state->code_blocks->cb[n].block = oplist;
6713 pRExC_state->code_blocks->cb[n].src_regex = NULL;
6716 oplist = OpSIBLING(oplist); /* skip CONST */
6719 oplist = OpSIBLING(oplist);;
6722 /* apply magic and QR overloading to arg */
6725 if (SvROK(msv) && SvAMAGIC(msv)) {
6726 SV *sv = AMG_CALLunary(msv, regexp_amg);
6730 if (SvTYPE(sv) != SVt_REGEXP)
6731 Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
6736 /* try concatenation overload ... */
6737 if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) &&
6738 (sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
6741 /* overloading involved: all bets are off over literal
6742 * code. Pretend we haven't seen it */
6744 pRExC_state->code_blocks->count -= n;
6748 /* ... or failing that, try "" overload */
6749 while (SvAMAGIC(msv)
6750 && (sv = AMG_CALLunary(msv, string_amg))
6754 && SvRV(msv) == SvRV(sv))
6759 if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
6763 /* this is a partially unrolled
6764 * sv_catsv_nomg(pat, msv);
6765 * that allows us to adjust code block indices if
6768 char *dst = SvPV_force_nomg(pat, dlen);
6770 if (SvUTF8(msv) && !SvUTF8(pat)) {
6771 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n);
6772 sv_setpvn(pat, dst, dlen);
6775 sv_catsv_nomg(pat, msv);
6779 /* We have only one SV to process, but we need to verify
6780 * it is properly null terminated or we will fail asserts
6781 * later. In theory we probably shouldn't get such SV's,
6782 * but if we do we should handle it gracefully. */
6783 if ( SvTYPE(msv) != SVt_PV || (SvLEN(msv) > SvCUR(msv) && *(SvEND(msv)) == 0) || SvIsCOW_shared_hash(msv) ) {
6784 /* not a string, or a string with a trailing null */
6787 /* a string with no trailing null, we need to copy it
6788 * so it has a trailing null */
6789 pat = sv_2mortal(newSVsv(msv));
6794 pRExC_state->code_blocks->cb[n-1].end = SvCUR(pat)-1;
6797 /* extract any code blocks within any embedded qr//'s */
6798 if (rx && SvTYPE(rx) == SVt_REGEXP
6799 && RX_ENGINE((REGEXP*)rx)->op_comp)
6802 RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
6803 if (ri->code_blocks && ri->code_blocks->count) {
6805 /* the presence of an embedded qr// with code means
6806 * we should always recompile: the text of the
6807 * qr// may not have changed, but it may be a
6808 * different closure than last time */
6810 if (pRExC_state->code_blocks) {
6811 int new_count = pRExC_state->code_blocks->count
6812 + ri->code_blocks->count;
6813 Renew(pRExC_state->code_blocks->cb,
6814 new_count, struct reg_code_block);
6815 pRExC_state->code_blocks->count = new_count;
6818 pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_
6819 ri->code_blocks->count);
6821 for (i=0; i < ri->code_blocks->count; i++) {
6822 struct reg_code_block *src, *dst;
6823 STRLEN offset = orig_patlen
6824 + ReANY((REGEXP *)rx)->pre_prefix;
6825 assert(n < pRExC_state->code_blocks->count);
6826 src = &ri->code_blocks->cb[i];
6827 dst = &pRExC_state->code_blocks->cb[n];
6828 dst->start = src->start + offset;
6829 dst->end = src->end + offset;
6830 dst->block = src->block;
6831 dst->src_regex = (REGEXP*) SvREFCNT_inc( (SV*)
6840 /* avoid calling magic multiple times on a single element e.g. =~ $qr */
6849 /* see if there are any run-time code blocks in the pattern.
6850 * False positives are allowed */
6853 S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
6854 char *pat, STRLEN plen)
6859 PERL_UNUSED_CONTEXT;
6861 for (s = 0; s < plen; s++) {
6862 if ( pRExC_state->code_blocks
6863 && n < pRExC_state->code_blocks->count
6864 && s == pRExC_state->code_blocks->cb[n].start)
6866 s = pRExC_state->code_blocks->cb[n].end;
6870 /* TODO ideally should handle [..], (#..), /#.../x to reduce false
6872 if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' &&
6874 || (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{'))
6881 /* Handle run-time code blocks. We will already have compiled any direct
6882 * or indirect literal code blocks. Now, take the pattern 'pat' and make a
6883 * copy of it, but with any literal code blocks blanked out and
6884 * appropriate chars escaped; then feed it into
6886 * eval "qr'modified_pattern'"
6890 * a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
6894 * qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
6896 * After eval_sv()-ing that, grab any new code blocks from the returned qr
6897 * and merge them with any code blocks of the original regexp.
6899 * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
6900 * instead, just save the qr and return FALSE; this tells our caller that
6901 * the original pattern needs upgrading to utf8.
6905 S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
6906 char *pat, STRLEN plen)
6910 GET_RE_DEBUG_FLAGS_DECL;
6912 if (pRExC_state->runtime_code_qr) {
6913 /* this is the second time we've been called; this should
6914 * only happen if the main pattern got upgraded to utf8
6915 * during compilation; re-use the qr we compiled first time
6916 * round (which should be utf8 too)
6918 qr = pRExC_state->runtime_code_qr;
6919 pRExC_state->runtime_code_qr = NULL;
6920 assert(RExC_utf8 && SvUTF8(qr));
6926 int newlen = plen + 7; /* allow for "qr''xx\0" extra chars */
6930 /* determine how many extra chars we need for ' and \ escaping */
6931 for (s = 0; s < plen; s++) {
6932 if (pat[s] == '\'' || pat[s] == '\\')
6936 Newx(newpat, newlen, char);
6938 *p++ = 'q'; *p++ = 'r'; *p++ = '\'';
6940 for (s = 0; s < plen; s++) {
6941 if ( pRExC_state->code_blocks
6942 && n < pRExC_state->code_blocks->count
6943 && s == pRExC_state->code_blocks->cb[n].start)
6945 /* blank out literal code block so that they aren't
6946 * recompiled: eg change from/to:
6956 assert(pat[s] == '(');
6957 assert(pat[s+1] == '?');
6961 while (s < pRExC_state->code_blocks->cb[n].end) {
6969 if (pat[s] == '\'' || pat[s] == '\\')
6974 if (pRExC_state->pm_flags & RXf_PMf_EXTENDED) {
6976 if (pRExC_state->pm_flags & RXf_PMf_EXTENDED_MORE) {
6982 Perl_re_printf( aTHX_
6983 "%sre-parsing pattern for runtime code:%s %s\n",
6984 PL_colors[4], PL_colors[5], newpat);
6987 sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
6993 PUSHSTACKi(PERLSI_REQUIRE);
6994 /* G_RE_REPARSING causes the toker to collapse \\ into \ when
6995 * parsing qr''; normally only q'' does this. It also alters
6997 eval_sv(sv, G_SCALAR|G_RE_REPARSING);
6998 SvREFCNT_dec_NN(sv);
7003 SV * const errsv = ERRSV;
7004 if (SvTRUE_NN(errsv))
7005 /* use croak_sv ? */
7006 Perl_croak_nocontext("%" SVf, SVfARG(errsv));
7008 assert(SvROK(qr_ref));
7010 assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
7011 /* the leaving below frees the tmp qr_ref.
7012 * Give qr a life of its own */
7020 if (!RExC_utf8 && SvUTF8(qr)) {
7021 /* first time through; the pattern got upgraded; save the
7022 * qr for the next time through */
7023 assert(!pRExC_state->runtime_code_qr);
7024 pRExC_state->runtime_code_qr = qr;
7029 /* extract any code blocks within the returned qr// */
7032 /* merge the main (r1) and run-time (r2) code blocks into one */
7034 RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
7035 struct reg_code_block *new_block, *dst;
7036 RExC_state_t * const r1 = pRExC_state; /* convenient alias */
7040 if (!r2->code_blocks || !r2->code_blocks->count) /* we guessed wrong */
7042 SvREFCNT_dec_NN(qr);
7046 if (!r1->code_blocks)
7047 r1->code_blocks = S_alloc_code_blocks(aTHX_ 0);
7049 r1c = r1->code_blocks->count;
7050 r2c = r2->code_blocks->count;
7052 Newx(new_block, r1c + r2c, struct reg_code_block);
7056 while (i1 < r1c || i2 < r2c) {
7057 struct reg_code_block *src;
7061 src = &r2->code_blocks->cb[i2++];
7065 src = &r1->code_blocks->cb[i1++];
7066 else if ( r1->code_blocks->cb[i1].start
7067 < r2->code_blocks->cb[i2].start)
7069 src = &r1->code_blocks->cb[i1++];
7070 assert(src->end < r2->code_blocks->cb[i2].start);
7073 assert( r1->code_blocks->cb[i1].start
7074 > r2->code_blocks->cb[i2].start);
7075 src = &r2->code_blocks->cb[i2++];
7077 assert(src->end < r1->code_blocks->cb[i1].start);
7080 assert(pat[src->start] == '(');
7081 assert(pat[src->end] == ')');
7082 dst->start = src->start;
7083 dst->end = src->end;
7084 dst->block = src->block;
7085 dst->src_regex = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
7089 r1->code_blocks->count += r2c;
7090 Safefree(r1->code_blocks->cb);
7091 r1->code_blocks->cb = new_block;
7094 SvREFCNT_dec_NN(qr);
7100 S_setup_longest(pTHX_ RExC_state_t *pRExC_state,
7101 struct reg_substr_datum *rsd,
7102 struct scan_data_substrs *sub,
7103 STRLEN longest_length)
7105 /* This is the common code for setting up the floating and fixed length
7106 * string data extracted from Perl_re_op_compile() below. Returns a boolean
7107 * as to whether succeeded or not */
7111 bool eol = cBOOL(sub->flags & SF_BEFORE_EOL);
7112 bool meol = cBOOL(sub->flags & SF_BEFORE_MEOL);
7114 if (! (longest_length
7115 || (eol /* Can't have SEOL and MULTI */
7116 && (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
7118 /* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */
7119 || (RExC_seen & REG_UNFOLDED_MULTI_SEEN))
7124 /* copy the information about the longest from the reg_scan_data
7125 over to the program. */
7126 if (SvUTF8(sub->str)) {
7128 rsd->utf8_substr = sub->str;
7130 rsd->substr = sub->str;
7131 rsd->utf8_substr = NULL;
7133 /* end_shift is how many chars that must be matched that
7134 follow this item. We calculate it ahead of time as once the
7135 lookbehind offset is added in we lose the ability to correctly
7137 ml = sub->minlenp ? *(sub->minlenp) : (SSize_t)longest_length;
7138 rsd->end_shift = ml - sub->min_offset
7140 /* XXX SvTAIL is always false here - did you mean FBMcf_TAIL
7142 + (SvTAIL(sub->str) != 0)
7146 t = (eol/* Can't have SEOL and MULTI */
7147 && (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
7148 fbm_compile(sub->str, t ? FBMcf_TAIL : 0);
7154 S_set_regex_pv(pTHX_ RExC_state_t *pRExC_state, REGEXP *Rx)
7156 /* Calculates and sets in the compiled pattern 'Rx' the string to compile,
7157 * properly wrapped with the right modifiers */
7159 bool has_p = ((RExC_rx->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
7160 bool has_charset = RExC_utf8 || (get_regex_charset(RExC_rx->extflags)
7161 != REGEX_DEPENDS_CHARSET);
7163 /* The caret is output if there are any defaults: if not all the STD
7164 * flags are set, or if no character set specifier is needed */
7166 (((RExC_rx->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
7168 bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN)
7169 == REG_RUN_ON_COMMENT_SEEN);
7170 U8 reganch = (U8)((RExC_rx->extflags & RXf_PMf_STD_PMMOD)
7171 >> RXf_PMf_STD_PMMOD_SHIFT);
7172 const char *fptr = STD_PAT_MODS; /*"msixxn"*/
7174 STRLEN pat_len = RExC_precomp_end - RExC_precomp;
7176 /* We output all the necessary flags; we never output a minus, as all
7177 * those are defaults, so are
7178 * covered by the caret */
7179 const STRLEN wraplen = pat_len + has_p + has_runon
7180 + has_default /* If needs a caret */
7181 + PL_bitcount[reganch] /* 1 char for each set standard flag */
7183 /* If needs a character set specifier */
7184 + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
7185 + (sizeof("(?:)") - 1);
7187 PERL_ARGS_ASSERT_SET_REGEX_PV;
7189 /* make sure PL_bitcount bounds not exceeded */
7190 assert(sizeof(STD_PAT_MODS) <= 8);
7192 p = sv_grow(MUTABLE_SV(Rx), wraplen + 1); /* +1 for the ending NUL */
7195 SvFLAGS(Rx) |= SVf_UTF8;
7198 /* If a default, cover it using the caret */
7200 *p++= DEFAULT_PAT_MOD;
7206 name = get_regex_charset_name(RExC_rx->extflags, &len);
7207 if strEQ(name, DEPENDS_PAT_MODS) { /* /d under UTF-8 => /u */
7209 name = UNICODE_PAT_MODS;
7210 len = sizeof(UNICODE_PAT_MODS) - 1;
7212 Copy(name, p, len, char);
7216 *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
7219 while((ch = *fptr++)) {
7227 Copy(RExC_precomp, p, pat_len, char);
7228 assert ((RX_WRAPPED(Rx) - p) < 16);
7229 RExC_rx->pre_prefix = p - RX_WRAPPED(Rx);
7232 /* Adding a trailing \n causes this to compile properly:
7233 my $R = qr / A B C # D E/x; /($R)/
7234 Otherwise the parens are considered part of the comment */
7239 SvCUR_set(Rx, p - RX_WRAPPED(Rx));
7243 * Perl_re_op_compile - the perl internal RE engine's function to compile a
7244 * regular expression into internal code.
7245 * The pattern may be passed either as:
7246 * a list of SVs (patternp plus pat_count)
7247 * a list of OPs (expr)
7248 * If both are passed, the SV list is used, but the OP list indicates
7249 * which SVs are actually pre-compiled code blocks
7251 * The SVs in the list have magic and qr overloading applied to them (and
7252 * the list may be modified in-place with replacement SVs in the latter
7255 * If the pattern hasn't changed from old_re, then old_re will be
7258 * eng is the current engine. If that engine has an op_comp method, then
7259 * handle directly (i.e. we assume that op_comp was us); otherwise, just
7260 * do the initial concatenation of arguments and pass on to the external
7263 * If is_bare_re is not null, set it to a boolean indicating whether the
7264 * arg list reduced (after overloading) to a single bare regex which has
7265 * been returned (i.e. /$qr/).
7267 * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
7269 * pm_flags contains the PMf_* flags, typically based on those from the
7270 * pm_flags field of the related PMOP. Currently we're only interested in
7271 * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL.
7273 * For many years this code had an initial sizing pass that calculated
7274 * (sometimes incorrectly, leading to security holes) the size needed for the
7275 * compiled pattern. That was changed by commit
7276 * 7c932d07cab18751bfc7515b4320436273a459e2 in 5.29, which reallocs the size, a
7277 * node at a time, as parsing goes along. Patches welcome to fix any obsolete
7278 * references to this sizing pass.
7280 * Now, an initial crude guess as to the size needed is made, based on the
7281 * length of the pattern. Patches welcome to improve that guess. That amount
7282 * of space is malloc'd and then immediately freed, and then clawed back node
7283 * by node. This design is to minimze, to the extent possible, memory churn
7284 * when doing the the reallocs.
7286 * A separate parentheses counting pass may be needed in some cases.
7287 * (Previously the sizing pass did this.) Patches welcome to reduce the number
7290 * The existence of a sizing pass necessitated design decisions that are no
7291 * longer needed. There are potential areas of simplification.
7293 * Beware that the optimization-preparation code in here knows about some
7294 * of the structure of the compiled regexp. [I'll say.]
7298 Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
7299 OP *expr, const regexp_engine* eng, REGEXP *old_re,
7300 bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags)
7303 REGEXP *Rx; /* Capital 'R' means points to a REGEXP */
7311 SV** new_patternp = patternp;
7313 /* these are all flags - maybe they should be turned
7314 * into a single int with different bit masks */
7315 I32 sawlookahead = 0;
7320 regex_charset initial_charset = get_regex_charset(orig_rx_flags);
7322 bool runtime_code = 0;
7324 RExC_state_t RExC_state;
7325 RExC_state_t * const pRExC_state = &RExC_state;
7326 #ifdef TRIE_STUDY_OPT
7328 RExC_state_t copyRExC_state;
7330 GET_RE_DEBUG_FLAGS_DECL;
7332 PERL_ARGS_ASSERT_RE_OP_COMPILE;
7334 DEBUG_r(if (!PL_colorset) reginitcolors());
7336 /* Initialize these here instead of as-needed, as is quick and avoids
7337 * having to test them each time otherwise */
7338 if (! PL_InBitmap) {
7340 char * dump_len_string;
7343 /* This is calculated here, because the Perl program that generates the
7344 * static global ones doesn't currently have access to
7345 * NUM_ANYOF_CODE_POINTS */
7346 PL_InBitmap = _new_invlist(2);
7347 PL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0,
7348 NUM_ANYOF_CODE_POINTS - 1);
7350 dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN");
7351 if ( ! dump_len_string
7352 || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL))
7354 PL_dump_re_max_len = 60; /* A reasonable default */
7359 pRExC_state->warn_text = NULL;
7360 pRExC_state->code_blocks = NULL;
7363 *is_bare_re = FALSE;
7365 if (expr && (expr->op_type == OP_LIST ||
7366 (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
7367 /* allocate code_blocks if needed */
7371 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o))
7372 if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
7373 ncode++; /* count of DO blocks */
7376 pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode);
7380 /* compile-time pattern with just OP_CONSTs and DO blocks */
7385 /* find how many CONSTs there are */
7388 if (expr->op_type == OP_CONST)
7391 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7392 if (o->op_type == OP_CONST)
7396 /* fake up an SV array */
7398 assert(!new_patternp);
7399 Newx(new_patternp, n, SV*);
7400 SAVEFREEPV(new_patternp);
7404 if (expr->op_type == OP_CONST)
7405 new_patternp[n] = cSVOPx_sv(expr);
7407 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7408 if (o->op_type == OP_CONST)
7409 new_patternp[n++] = cSVOPo_sv;
7414 DEBUG_PARSE_r(Perl_re_printf( aTHX_
7415 "Assembling pattern from %d elements%s\n", pat_count,
7416 orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7418 /* set expr to the first arg op */
7420 if (pRExC_state->code_blocks && pRExC_state->code_blocks->count
7421 && expr->op_type != OP_CONST)
7423 expr = cLISTOPx(expr)->op_first;
7424 assert( expr->op_type == OP_PUSHMARK
7425 || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)
7426 || expr->op_type == OP_PADRANGE);
7427 expr = OpSIBLING(expr);
7430 pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,
7431 expr, &recompile, NULL);
7433 /* handle bare (possibly after overloading) regex: foo =~ $re */
7438 if (SvTYPE(re) == SVt_REGEXP) {
7442 DEBUG_PARSE_r(Perl_re_printf( aTHX_
7443 "Precompiled pattern%s\n",
7444 orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7450 exp = SvPV_nomg(pat, plen);
7452 if (!eng->op_comp) {
7453 if ((SvUTF8(pat) && IN_BYTES)
7454 || SvGMAGICAL(pat) || SvAMAGIC(pat))
7456 /* make a temporary copy; either to convert to bytes,
7457 * or to avoid repeating get-magic / overloaded stringify */
7458 pat = newSVpvn_flags(exp, plen, SVs_TEMP |
7459 (IN_BYTES ? 0 : SvUTF8(pat)));
7461 return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
7464 /* ignore the utf8ness if the pattern is 0 length */
7465 RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
7466 RExC_uni_semantics = 0;
7467 RExC_contains_locale = 0;
7468 RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT);
7469 RExC_in_script_run = 0;
7470 RExC_study_started = 0;
7471 pRExC_state->runtime_code_qr = NULL;
7472 RExC_frame_head= NULL;
7473 RExC_frame_last= NULL;
7474 RExC_frame_count= 0;
7475 RExC_latest_warn_offset = 0;
7476 RExC_use_BRANCHJ = 0;
7477 RExC_total_parens = 0;
7478 RExC_open_parens = NULL;
7479 RExC_close_parens = NULL;
7480 RExC_paren_names = NULL;
7482 RExC_seen_d_op = FALSE;
7484 RExC_paren_name_list = NULL;
7488 RExC_mysv1= sv_newmortal();
7489 RExC_mysv2= sv_newmortal();
7493 SV *dsv= sv_newmortal();
7494 RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7495 Perl_re_printf( aTHX_ "%sCompiling REx%s %s\n",
7496 PL_colors[4], PL_colors[5], s);
7499 /* we jump here if we have to recompile, e.g., from upgrading the pattern
7502 if ((pm_flags & PMf_USE_RE_EVAL)
7503 /* this second condition covers the non-regex literal case,
7504 * i.e. $foo =~ '(?{})'. */
7505 || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))
7507 runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);
7510 /* return old regex if pattern hasn't changed */
7511 /* XXX: note in the below we have to check the flags as well as the
7514 * Things get a touch tricky as we have to compare the utf8 flag
7515 * independently from the compile flags. */
7519 && !!RX_UTF8(old_re) == !!RExC_utf8
7520 && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )
7521 && RX_PRECOMP(old_re)
7522 && RX_PRELEN(old_re) == plen
7523 && memEQ(RX_PRECOMP(old_re), exp, plen)
7524 && !runtime_code /* with runtime code, always recompile */ )
7529 /* Allocate the pattern's SV */
7530 RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP);
7531 RExC_rx = ReANY(Rx);
7532 if ( RExC_rx == NULL )
7533 FAIL("Regexp out of space");
7535 rx_flags = orig_rx_flags;
7537 if ( (UTF || RExC_uni_semantics)
7538 && initial_charset == REGEX_DEPENDS_CHARSET)
7541 /* Set to use unicode semantics if the pattern is in utf8 and has the
7542 * 'depends' charset specified, as it means unicode when utf8 */
7543 set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
7544 RExC_uni_semantics = 1;
7547 RExC_pm_flags = pm_flags;
7550 assert(TAINTING_get || !TAINT_get);
7552 Perl_croak(aTHX_ "Eval-group in insecure regular expression");
7554 if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
7555 /* whoops, we have a non-utf8 pattern, whilst run-time code
7556 * got compiled as utf8. Try again with a utf8 pattern */
7557 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7558 pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7562 assert(!pRExC_state->runtime_code_qr);
7568 RExC_in_lookbehind = 0;
7569 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
7571 RExC_recode_x_to_native = 0;
7573 RExC_in_multi_char_class = 0;
7575 RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp;
7576 RExC_precomp_end = RExC_end = exp + plen;
7578 RExC_whilem_seen = 0;
7580 RExC_recurse = NULL;
7581 RExC_study_chunk_recursed = NULL;
7582 RExC_study_chunk_recursed_bytes= 0;
7583 RExC_recurse_count = 0;
7584 pRExC_state->code_index = 0;
7586 /* Initialize the string in the compiled pattern. This is so that there is
7587 * something to output if necessary */
7588 set_regex_pv(pRExC_state, Rx);
7591 Perl_re_printf( aTHX_
7592 "Starting parse and generation\n");
7594 RExC_lastparse=NULL;
7597 /* Allocate space and zero-initialize. Note, the two step process
7598 of zeroing when in debug mode, thus anything assigned has to
7599 happen after that */
7602 /* On the first pass of the parse, we guess how big this will be. Then
7603 * we grow in one operation to that amount and then give it back. As
7604 * we go along, we re-allocate what we need.
7606 * XXX Currently the guess is essentially that the pattern will be an
7607 * EXACT node with one byte input, one byte output. This is crude, and
7608 * better heuristics are welcome.
7610 * On any subsequent passes, we guess what we actually computed in the
7611 * latest earlier pass. Such a pass probably didn't complete so is
7612 * missing stuff. We could improve those guesses by knowing where the
7613 * parse stopped, and use the length so far plus apply the above
7614 * assumption to what's left. */
7615 RExC_size = STR_SZ(RExC_end - RExC_start);
7618 Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal);
7619 if ( RExC_rxi == NULL )
7620 FAIL("Regexp out of space");
7622 Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char);
7623 RXi_SET( RExC_rx, RExC_rxi );
7625 /* We start from 0 (over from 0 in the case this is a reparse. The first
7626 * node parsed will give back any excess memory we have allocated so far).
7630 /* non-zero initialization begins here */
7631 RExC_rx->engine= eng;
7632 RExC_rx->extflags = rx_flags;
7633 RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;
7635 if (pm_flags & PMf_IS_QR) {
7636 RExC_rxi->code_blocks = pRExC_state->code_blocks;
7637 if (RExC_rxi->code_blocks) {
7638 RExC_rxi->code_blocks->refcnt++;
7642 RExC_rx->intflags = 0;
7644 RExC_flags = rx_flags; /* don't let top level (?i) bleed */
7647 /* This NUL is guaranteed because the pattern comes from an SV*, and the sv
7648 * code makes sure the final byte is an uncounted NUL. But should this
7649 * ever not be the case, lots of things could read beyond the end of the
7650 * buffer: loops like
7651 * while(isFOO(*RExC_parse)) RExC_parse++;
7652 * strchr(RExC_parse, "foo");
7653 * etc. So it is worth noting. */
7654 assert(*RExC_end == '\0');
7658 RExC_emit_start = RExC_rxi->program;
7659 pRExC_state->code_index = 0;
7661 *((char*) RExC_emit_start) = (char) REG_MAGIC;
7665 if (reg(pRExC_state, 0, &flags, 1)) {
7667 /* Success!, But if RExC_total_parens < 0, we need to redo the parse
7668 * knowing how many parens there actually are */
7669 if (RExC_total_parens < 0) {
7670 flags |= RESTART_PARSE;
7673 /* We have that number in RExC_npar */
7674 RExC_total_parens = RExC_npar;
7676 else if (! MUST_RESTART(flags)) {
7678 Perl_croak(aTHX_ "panic: reg returned failure to re_op_compile, flags=%#" UVxf, (UV) flags);
7681 /* Here, we either have success, or we have to redo the parse for some reason */
7682 if (MUST_RESTART(flags)) {
7684 /* It's possible to write a regexp in ascii that represents Unicode
7685 codepoints outside of the byte range, such as via \x{100}. If we
7686 detect such a sequence we have to convert the entire pattern to utf8
7687 and then recompile, as our sizing calculation will have been based
7688 on 1 byte == 1 character, but we will need to use utf8 to encode
7689 at least some part of the pattern, and therefore must convert the whole
7692 if (flags & NEED_UTF8) {
7694 /* We have stored the offset of the final warning output so far.
7695 * That must be adjusted. Any variant characters between the start
7696 * of the pattern and this warning count for 2 bytes in the final,
7697 * so just add them again */
7698 if (UNLIKELY(RExC_latest_warn_offset > 0)) {
7699 RExC_latest_warn_offset +=
7700 variant_under_utf8_count((U8 *) exp, (U8 *) exp
7701 + RExC_latest_warn_offset);
7703 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7704 pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7705 DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse after upgrade\n"));
7708 DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse\n"));
7711 if (RExC_total_parens > 0) {
7712 /* Make enough room for all the known parens, and zero it */
7713 Renew(RExC_open_parens, RExC_total_parens, regnode_offset);
7714 Zero(RExC_open_parens, RExC_total_parens, regnode_offset);
7715 RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */
7717 Renew(RExC_close_parens, RExC_total_parens, regnode_offset);
7718 Zero(RExC_close_parens, RExC_total_parens, regnode_offset);
7720 else { /* Parse did not complete. Reinitialize the parentheses
7722 RExC_total_parens = 0;
7723 if (RExC_open_parens) {
7724 Safefree(RExC_open_parens);
7725 RExC_open_parens = NULL;
7727 if (RExC_close_parens) {
7728 Safefree(RExC_close_parens);
7729 RExC_close_parens = NULL;
7733 /* Clean up what we did in this parse */
7734 SvREFCNT_dec_NN(RExC_rx_sv);
7739 /* Here, we have successfully parsed and generated the pattern's program
7740 * for the regex engine. We are ready to finish things up and look for
7743 /* Update the string to compile, with correct modifiers, etc */
7744 set_regex_pv(pRExC_state, Rx);
7746 RExC_rx->nparens = RExC_total_parens - 1;
7748 /* Uses the upper 4 bits of the FLAGS field, so keep within that size */
7749 if (RExC_whilem_seen > 15)
7750 RExC_whilem_seen = 15;
7753 Perl_re_printf( aTHX_
7754 "Required size %" IVdf " nodes\n", (IV)RExC_size);
7756 RExC_lastparse=NULL;
7759 #ifdef RE_TRACK_PATTERN_OFFSETS
7760 DEBUG_OFFSETS_r(Perl_re_printf( aTHX_
7761 "%s %" UVuf " bytes for offset annotations.\n",
7762 RExC_offsets ? "Got" : "Couldn't get",
7763 (UV)((RExC_offsets[0] * 2 + 1))));
7764 DEBUG_OFFSETS_r(if (RExC_offsets) {
7765 const STRLEN len = RExC_offsets[0];
7767 GET_RE_DEBUG_FLAGS_DECL;
7768 Perl_re_printf( aTHX_
7769 "Offsets: [%" UVuf "]\n\t", (UV)RExC_offsets[0]);
7770 for (i = 1; i <= len; i++) {
7771 if (RExC_offsets[i*2-1] || RExC_offsets[i*2])
7772 Perl_re_printf( aTHX_ "%" UVuf ":%" UVuf "[%" UVuf "] ",
7773 (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]);
7775 Perl_re_printf( aTHX_ "\n");
7779 SetProgLen(RExC_rxi,RExC_size);
7783 Perl_re_printf( aTHX_ "Starting post parse optimization\n");
7786 /* XXXX To minimize changes to RE engine we always allocate
7787 3-units-long substrs field. */
7788 Newx(RExC_rx->substrs, 1, struct reg_substr_data);
7789 if (RExC_recurse_count) {
7790 Newx(RExC_recurse, RExC_recurse_count, regnode *);
7791 SAVEFREEPV(RExC_recurse);
7794 if (RExC_seen & REG_RECURSE_SEEN) {
7795 /* Note, RExC_total_parens is 1 + the number of parens in a pattern.
7796 * So its 1 if there are no parens. */
7797 RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) +
7798 ((RExC_total_parens & 0x07) != 0);
7799 Newx(RExC_study_chunk_recursed,
7800 RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
7801 SAVEFREEPV(RExC_study_chunk_recursed);
7805 RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;
7807 RExC_study_chunk_recursed_count= 0;
7809 Zero(RExC_rx->substrs, 1, struct reg_substr_data);
7810 if (RExC_study_chunk_recursed) {
7811 Zero(RExC_study_chunk_recursed,
7812 RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
7816 #ifdef TRIE_STUDY_OPT
7818 StructCopy(&zero_scan_data, &data, scan_data_t);
7819 copyRExC_state = RExC_state;
7822 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n"));
7824 RExC_state = copyRExC_state;
7825 if (seen & REG_TOP_LEVEL_BRANCHES_SEEN)
7826 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
7828 RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN;
7829 StructCopy(&zero_scan_data, &data, scan_data_t);
7832 StructCopy(&zero_scan_data, &data, scan_data_t);
7835 /* Dig out information for optimizations. */
7836 RExC_rx->extflags = RExC_flags; /* was pm_op */
7837 /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
7840 SvUTF8_on(Rx); /* Unicode in it? */
7841 RExC_rxi->regstclass = NULL;
7842 if (RExC_naughty >= TOO_NAUGHTY) /* Probably an expensive pattern. */
7843 RExC_rx->intflags |= PREGf_NAUGHTY;
7844 scan = RExC_rxi->program + 1; /* First BRANCH. */
7846 /* testing for BRANCH here tells us whether there is "must appear"
7847 data in the pattern. If there is then we can use it for optimisations */
7848 if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice.
7851 STRLEN longest_length[2];
7852 regnode_ssc ch_class; /* pointed to by data */
7854 SSize_t last_close = 0; /* pointed to by data */
7855 regnode *first= scan;
7856 regnode *first_next= regnext(first);
7860 * Skip introductions and multiplicators >= 1
7861 * so that we can extract the 'meat' of the pattern that must
7862 * match in the large if() sequence following.
7863 * NOTE that EXACT is NOT covered here, as it is normally
7864 * picked up by the optimiser separately.
7866 * This is unfortunate as the optimiser isnt handling lookahead
7867 * properly currently.
7870 while ((OP(first) == OPEN && (sawopen = 1)) ||
7871 /* An OR of *one* alternative - should not happen now. */
7872 (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
7873 /* for now we can't handle lookbehind IFMATCH*/
7874 (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
7875 (OP(first) == PLUS) ||
7876 (OP(first) == MINMOD) ||
7877 /* An {n,m} with n>0 */
7878 (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
7879 (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
7882 * the only op that could be a regnode is PLUS, all the rest
7883 * will be regnode_1 or regnode_2.
7885 * (yves doesn't think this is true)
7887 if (OP(first) == PLUS)
7890 if (OP(first) == MINMOD)
7892 first += regarglen[OP(first)];
7894 first = NEXTOPER(first);
7895 first_next= regnext(first);
7898 /* Starting-point info. */
7900 DEBUG_PEEP("first:", first, 0, 0);
7901 /* Ignore EXACT as we deal with it later. */
7902 if (PL_regkind[OP(first)] == EXACT) {
7903 if ( OP(first) == EXACT
7904 || OP(first) == EXACT_ONLY8
7905 || OP(first) == EXACTL)
7907 NOOP; /* Empty, get anchored substr later. */
7910 RExC_rxi->regstclass = first;
7913 else if (PL_regkind[OP(first)] == TRIE &&
7914 ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0)
7916 /* this can happen only on restudy */
7917 RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0);
7920 else if (REGNODE_SIMPLE(OP(first)))
7921 RExC_rxi->regstclass = first;
7922 else if (PL_regkind[OP(first)] == BOUND ||
7923 PL_regkind[OP(first)] == NBOUND)
7924 RExC_rxi->regstclass = first;
7925 else if (PL_regkind[OP(first)] == BOL) {
7926 RExC_rx->intflags |= (OP(first) == MBOL
7929 first = NEXTOPER(first);
7932 else if (OP(first) == GPOS) {
7933 RExC_rx->intflags |= PREGf_ANCH_GPOS;
7934 first = NEXTOPER(first);
7937 else if ((!sawopen || !RExC_sawback) &&
7939 (OP(first) == STAR &&
7940 PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
7941 !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks)
7943 /* turn .* into ^.* with an implied $*=1 */
7945 (OP(NEXTOPER(first)) == REG_ANY)
7948 RExC_rx->intflags |= (type | PREGf_IMPLICIT);
7949 first = NEXTOPER(first);
7952 if (sawplus && !sawminmod && !sawlookahead
7953 && (!sawopen || !RExC_sawback)
7954 && !pRExC_state->code_blocks) /* May examine pos and $& */
7955 /* x+ must match at the 1st pos of run of x's */
7956 RExC_rx->intflags |= PREGf_SKIP;
7958 /* Scan is after the zeroth branch, first is atomic matcher. */
7959 #ifdef TRIE_STUDY_OPT
7962 Perl_re_printf( aTHX_ "first at %" IVdf "\n",
7963 (IV)(first - scan + 1))
7967 Perl_re_printf( aTHX_ "first at %" IVdf "\n",
7968 (IV)(first - scan + 1))
7974 * If there's something expensive in the r.e., find the
7975 * longest literal string that must appear and make it the
7976 * regmust. Resolve ties in favor of later strings, since
7977 * the regstart check works with the beginning of the r.e.
7978 * and avoiding duplication strengthens checking. Not a
7979 * strong reason, but sufficient in the absence of others.
7980 * [Now we resolve ties in favor of the earlier string if
7981 * it happens that c_offset_min has been invalidated, since the
7982 * earlier string may buy us something the later one won't.]
7985 data.substrs[0].str = newSVpvs("");
7986 data.substrs[1].str = newSVpvs("");
7987 data.last_found = newSVpvs("");
7988 data.cur_is_floating = 0; /* initially any found substring is fixed */
7989 ENTER_with_name("study_chunk");
7990 SAVEFREESV(data.substrs[0].str);
7991 SAVEFREESV(data.substrs[1].str);
7992 SAVEFREESV(data.last_found);
7994 if (!RExC_rxi->regstclass) {
7995 ssc_init(pRExC_state, &ch_class);
7996 data.start_class = &ch_class;
7997 stclass_flag = SCF_DO_STCLASS_AND;
7998 } else /* XXXX Check for BOUND? */
8000 data.last_closep = &last_close;
8004 * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/
8005 * (NO top level branches)
8007 minlen = study_chunk(pRExC_state, &first, &minlen, &fake,
8008 scan + RExC_size, /* Up to end */
8010 SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
8011 | (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
8015 CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
8018 if ( RExC_total_parens == 1 && !data.cur_is_floating
8019 && data.last_start_min == 0 && data.last_end > 0
8020 && !RExC_seen_zerolen
8021 && !(RExC_seen & REG_VERBARG_SEEN)
8022 && !(RExC_seen & REG_GPOS_SEEN)
8024 RExC_rx->extflags |= RXf_CHECK_ALL;
8026 scan_commit(pRExC_state, &data,&minlen, 0);
8029 /* XXX this is done in reverse order because that's the way the
8030 * code was before it was parameterised. Don't know whether it
8031 * actually needs doing in reverse order. DAPM */
8032 for (i = 1; i >= 0; i--) {
8033 longest_length[i] = CHR_SVLEN(data.substrs[i].str);
8036 && SvCUR(data.substrs[0].str) /* ok to leave SvCUR */
8037 && data.substrs[0].min_offset
8038 == data.substrs[1].min_offset
8039 && SvCUR(data.substrs[0].str)
8040 == SvCUR(data.substrs[1].str)
8042 && S_setup_longest (aTHX_ pRExC_state,
8043 &(RExC_rx->substrs->data[i]),
8047 RExC_rx->substrs->data[i].min_offset =
8048 data.substrs[i].min_offset - data.substrs[i].lookbehind;
8050 RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset;
8051 /* Don't offset infinity */
8052 if (data.substrs[i].max_offset < SSize_t_MAX)
8053 RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind;
8054 SvREFCNT_inc_simple_void_NN(data.substrs[i].str);
8057 RExC_rx->substrs->data[i].substr = NULL;
8058 RExC_rx->substrs->data[i].utf8_substr = NULL;
8059 longest_length[i] = 0;
8063 LEAVE_with_name("study_chunk");
8065 if (RExC_rxi->regstclass
8066 && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY))
8067 RExC_rxi->regstclass = NULL;
8069 if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr)
8070 || RExC_rx->substrs->data[0].min_offset)
8072 && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8073 && is_ssc_worth_it(pRExC_state, data.start_class))
8075 const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8077 ssc_finalize(pRExC_state, data.start_class);
8079 Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8080 StructCopy(data.start_class,
8081 (regnode_ssc*)RExC_rxi->data->data[n],
8083 RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8084 RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
8085 DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
8086 regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8087 Perl_re_printf( aTHX_
8088 "synthetic stclass \"%s\".\n",
8089 SvPVX_const(sv));});
8090 data.start_class = NULL;
8093 /* A temporary algorithm prefers floated substr to fixed one of
8094 * same length to dig more info. */
8095 i = (longest_length[0] <= longest_length[1]);
8096 RExC_rx->substrs->check_ix = i;
8097 RExC_rx->check_end_shift = RExC_rx->substrs->data[i].end_shift;
8098 RExC_rx->check_substr = RExC_rx->substrs->data[i].substr;
8099 RExC_rx->check_utf8 = RExC_rx->substrs->data[i].utf8_substr;
8100 RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset;
8101 RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset;
8102 if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS)))
8103 RExC_rx->intflags |= PREGf_NOSCAN;
8105 if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) {
8106 RExC_rx->extflags |= RXf_USE_INTUIT;
8107 if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8))
8108 RExC_rx->extflags |= RXf_INTUIT_TAIL;
8111 /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
8112 if ( (STRLEN)minlen < longest_length[1] )
8113 minlen= longest_length[1];
8114 if ( (STRLEN)minlen < longest_length[0] )
8115 minlen= longest_length[0];
8119 /* Several toplevels. Best we can is to set minlen. */
8121 regnode_ssc ch_class;
8122 SSize_t last_close = 0;
8124 DEBUG_PARSE_r(Perl_re_printf( aTHX_ "\nMulti Top Level\n"));
8126 scan = RExC_rxi->program + 1;
8127 ssc_init(pRExC_state, &ch_class);
8128 data.start_class = &ch_class;
8129 data.last_closep = &last_close;
8133 * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../
8134 * (patterns WITH top level branches)
8136 minlen = study_chunk(pRExC_state,
8137 &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL,
8138 SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied
8139 ? SCF_TRIE_DOING_RESTUDY
8143 CHECK_RESTUDY_GOTO_butfirst(NOOP);
8145 RExC_rx->check_substr = NULL;
8146 RExC_rx->check_utf8 = NULL;
8147 RExC_rx->substrs->data[0].substr = NULL;
8148 RExC_rx->substrs->data[0].utf8_substr = NULL;
8149 RExC_rx->substrs->data[1].substr = NULL;
8150 RExC_rx->substrs->data[1].utf8_substr = NULL;
8152 if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8153 && is_ssc_worth_it(pRExC_state, data.start_class))
8155 const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8157 ssc_finalize(pRExC_state, data.start_class);
8159 Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8160 StructCopy(data.start_class,
8161 (regnode_ssc*)RExC_rxi->data->data[n],
8163 RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8164 RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
8165 DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
8166 regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8167 Perl_re_printf( aTHX_
8168 "synthetic stclass \"%s\".\n",
8169 SvPVX_const(sv));});
8170 data.start_class = NULL;
8174 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) {
8175 RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN;
8176 RExC_rx->maxlen = REG_INFTY;
8179 RExC_rx->maxlen = RExC_maxlen;
8182 /* Guard against an embedded (?=) or (?<=) with a longer minlen than
8183 the "real" pattern. */
8185 Perl_re_printf( aTHX_ "minlen: %" IVdf " RExC_rx->minlen:%" IVdf " maxlen:%" IVdf "\n",
8186 (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen);
8188 RExC_rx->minlenret = minlen;
8189 if (RExC_rx->minlen < minlen)
8190 RExC_rx->minlen = minlen;
8192 if (RExC_seen & REG_RECURSE_SEEN ) {
8193 RExC_rx->intflags |= PREGf_RECURSE_SEEN;
8194 Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *);
8196 if (RExC_seen & REG_GPOS_SEEN)
8197 RExC_rx->intflags |= PREGf_GPOS_SEEN;
8198 if (RExC_seen & REG_LOOKBEHIND_SEEN)
8199 RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the
8201 if (pRExC_state->code_blocks)
8202 RExC_rx->extflags |= RXf_EVAL_SEEN;
8203 if (RExC_seen & REG_VERBARG_SEEN)
8205 RExC_rx->intflags |= PREGf_VERBARG_SEEN;
8206 RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */
8208 if (RExC_seen & REG_CUTGROUP_SEEN)
8209 RExC_rx->intflags |= PREGf_CUTGROUP_SEEN;
8210 if (pm_flags & PMf_USE_RE_EVAL)
8211 RExC_rx->intflags |= PREGf_USE_RE_EVAL;
8212 if (RExC_paren_names)
8213 RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
8215 RXp_PAREN_NAMES(RExC_rx) = NULL;
8217 /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED
8218 * so it can be used in pp.c */
8219 if (RExC_rx->intflags & PREGf_ANCH)
8220 RExC_rx->extflags |= RXf_IS_ANCHORED;
8224 /* this is used to identify "special" patterns that might result
8225 * in Perl NOT calling the regex engine and instead doing the match "itself",
8226 * particularly special cases in split//. By having the regex compiler
8227 * do this pattern matching at a regop level (instead of by inspecting the pattern)
8228 * we avoid weird issues with equivalent patterns resulting in different behavior,
8229 * AND we allow non Perl engines to get the same optimizations by the setting the
8230 * flags appropriately - Yves */
8231 regnode *first = RExC_rxi->program + 1;
8233 regnode *next = regnext(first);
8236 if (PL_regkind[fop] == NOTHING && nop == END)
8237 RExC_rx->extflags |= RXf_NULL;
8238 else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END)
8239 /* when fop is SBOL first->flags will be true only when it was
8240 * produced by parsing /\A/, and not when parsing /^/. This is
8241 * very important for the split code as there we want to
8242 * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m.
8243 * See rt #122761 for more details. -- Yves */
8244 RExC_rx->extflags |= RXf_START_ONLY;
8245 else if (fop == PLUS
8246 && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE
8248 RExC_rx->extflags |= RXf_WHITE;
8249 else if ( RExC_rx->extflags & RXf_SPLIT
8250 && (fop == EXACT || fop == EXACT_ONLY8 || fop == EXACTL)
8251 && STR_LEN(first) == 1
8252 && *(STRING(first)) == ' '
8254 RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
8258 if (RExC_contains_locale) {
8259 RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED;
8263 if (RExC_paren_names) {
8264 RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a"));
8265 RExC_rxi->data->data[RExC_rxi->name_list_idx]
8266 = (void*)SvREFCNT_inc(RExC_paren_name_list);
8269 RExC_rxi->name_list_idx = 0;
8271 while ( RExC_recurse_count > 0 ) {
8272 const regnode *scan = RExC_recurse[ --RExC_recurse_count ];
8274 * This data structure is set up in study_chunk() and is used
8275 * to calculate the distance between a GOSUB regopcode and
8276 * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's)
8279 * If for some reason someone writes code that optimises
8280 * away a GOSUB opcode then the assert should be changed to
8281 * an if(scan) to guard the ARG2L_SET() - Yves
8284 assert(scan && OP(scan) == GOSUB);
8285 ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan));
8288 Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair);
8289 /* assume we don't need to swap parens around before we match */
8291 Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n",
8292 (unsigned long)RExC_study_chunk_recursed_count);
8296 Perl_re_printf( aTHX_ "Final program:\n");
8300 if (RExC_open_parens) {
8301 Safefree(RExC_open_parens);
8302 RExC_open_parens = NULL;
8304 if (RExC_close_parens) {
8305 Safefree(RExC_close_parens);
8306 RExC_close_parens = NULL;
8310 /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated
8311 * by setting the regexp SV to readonly-only instead. If the
8312 * pattern's been recompiled, the USEDness should remain. */
8313 if (old_re && SvREADONLY(old_re))
8321 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
8324 PERL_ARGS_ASSERT_REG_NAMED_BUFF;
8326 PERL_UNUSED_ARG(value);
8328 if (flags & RXapif_FETCH) {
8329 return reg_named_buff_fetch(rx, key, flags);
8330 } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
8331 Perl_croak_no_modify();
8333 } else if (flags & RXapif_EXISTS) {
8334 return reg_named_buff_exists(rx, key, flags)
8337 } else if (flags & RXapif_REGNAMES) {
8338 return reg_named_buff_all(rx, flags);
8339 } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
8340 return reg_named_buff_scalar(rx, flags);
8342 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
8348 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
8351 PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
8352 PERL_UNUSED_ARG(lastkey);
8354 if (flags & RXapif_FIRSTKEY)
8355 return reg_named_buff_firstkey(rx, flags);
8356 else if (flags & RXapif_NEXTKEY)
8357 return reg_named_buff_nextkey(rx, flags);
8359 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter",
8366 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
8370 struct regexp *const rx = ReANY(r);
8372 PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
8374 if (rx && RXp_PAREN_NAMES(rx)) {
8375 HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
8378 SV* sv_dat=HeVAL(he_str);
8379 I32 *nums=(I32*)SvPVX(sv_dat);
8380 AV * const retarray = (flags & RXapif_ALL) ? newAV() : NULL;
8381 for ( i=0; i<SvIVX(sv_dat); i++ ) {
8382 if ((I32)(rx->nparens) >= nums[i]
8383 && rx->offs[nums[i]].start != -1
8384 && rx->offs[nums[i]].end != -1)
8387 CALLREG_NUMBUF_FETCH(r, nums[i], ret);
8392 ret = newSVsv(&PL_sv_undef);
8395 av_push(retarray, ret);
8398 return newRV_noinc(MUTABLE_SV(retarray));
8405 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
8408 struct regexp *const rx = ReANY(r);
8410 PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
8412 if (rx && RXp_PAREN_NAMES(rx)) {
8413 if (flags & RXapif_ALL) {
8414 return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
8416 SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
8418 SvREFCNT_dec_NN(sv);
8430 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
8432 struct regexp *const rx = ReANY(r);
8434 PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
8436 if ( rx && RXp_PAREN_NAMES(rx) ) {
8437 (void)hv_iterinit(RXp_PAREN_NAMES(rx));
8439 return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
8446 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
8448 struct regexp *const rx = ReANY(r);
8449 GET_RE_DEBUG_FLAGS_DECL;
8451 PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
8453 if (rx && RXp_PAREN_NAMES(rx)) {
8454 HV *hv = RXp_PAREN_NAMES(rx);
8456 while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8459 SV* sv_dat = HeVAL(temphe);
8460 I32 *nums = (I32*)SvPVX(sv_dat);
8461 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8462 if ((I32)(rx->lastparen) >= nums[i] &&
8463 rx->offs[nums[i]].start != -1 &&
8464 rx->offs[nums[i]].end != -1)
8470 if (parno || flags & RXapif_ALL) {
8471 return newSVhek(HeKEY_hek(temphe));
8479 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
8484 struct regexp *const rx = ReANY(r);
8486 PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
8488 if (rx && RXp_PAREN_NAMES(rx)) {
8489 if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
8490 return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
8491 } else if (flags & RXapif_ONE) {
8492 ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
8493 av = MUTABLE_AV(SvRV(ret));
8494 length = av_tindex(av);
8495 SvREFCNT_dec_NN(ret);
8496 return newSViv(length + 1);
8498 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar",
8503 return &PL_sv_undef;
8507 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
8509 struct regexp *const rx = ReANY(r);
8512 PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
8514 if (rx && RXp_PAREN_NAMES(rx)) {
8515 HV *hv= RXp_PAREN_NAMES(rx);
8517 (void)hv_iterinit(hv);
8518 while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8521 SV* sv_dat = HeVAL(temphe);
8522 I32 *nums = (I32*)SvPVX(sv_dat);
8523 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8524 if ((I32)(rx->lastparen) >= nums[i] &&
8525 rx->offs[nums[i]].start != -1 &&
8526 rx->offs[nums[i]].end != -1)
8532 if (parno || flags & RXapif_ALL) {
8533 av_push(av, newSVhek(HeKEY_hek(temphe)));
8538 return newRV_noinc(MUTABLE_SV(av));
8542 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
8545 struct regexp *const rx = ReANY(r);
8551 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
8553 if ( n == RX_BUFF_IDX_CARET_PREMATCH
8554 || n == RX_BUFF_IDX_CARET_FULLMATCH
8555 || n == RX_BUFF_IDX_CARET_POSTMATCH
8558 bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8560 /* on something like
8563 * the KEEPCOPY is set on the PMOP rather than the regex */
8564 if (PL_curpm && r == PM_GETRE(PL_curpm))
8565 keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8574 if (n == RX_BUFF_IDX_CARET_FULLMATCH)
8575 /* no need to distinguish between them any more */
8576 n = RX_BUFF_IDX_FULLMATCH;
8578 if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
8579 && rx->offs[0].start != -1)
8581 /* $`, ${^PREMATCH} */
8582 i = rx->offs[0].start;
8586 if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
8587 && rx->offs[0].end != -1)
8589 /* $', ${^POSTMATCH} */
8590 s = rx->subbeg - rx->suboffset + rx->offs[0].end;
8591 i = rx->sublen + rx->suboffset - rx->offs[0].end;
8594 if ( 0 <= n && n <= (I32)rx->nparens &&
8595 (s1 = rx->offs[n].start) != -1 &&
8596 (t1 = rx->offs[n].end) != -1)
8598 /* $&, ${^MATCH}, $1 ... */
8600 s = rx->subbeg + s1 - rx->suboffset;
8605 assert(s >= rx->subbeg);
8606 assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) );
8608 #ifdef NO_TAINT_SUPPORT
8609 sv_setpvn(sv, s, i);
8611 const int oldtainted = TAINT_get;
8613 sv_setpvn(sv, s, i);
8614 TAINT_set(oldtainted);
8616 if (RXp_MATCH_UTF8(rx))
8621 if (RXp_MATCH_TAINTED(rx)) {
8622 if (SvTYPE(sv) >= SVt_PVMG) {
8623 MAGIC* const mg = SvMAGIC(sv);
8626 SvMAGIC_set(sv, mg->mg_moremagic);
8628 if ((mgt = SvMAGIC(sv))) {
8629 mg->mg_moremagic = mgt;
8630 SvMAGIC_set(sv, mg);
8647 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
8648 SV const * const value)
8650 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
8652 PERL_UNUSED_ARG(rx);
8653 PERL_UNUSED_ARG(paren);
8654 PERL_UNUSED_ARG(value);
8657 Perl_croak_no_modify();
8661 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
8664 struct regexp *const rx = ReANY(r);
8668 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
8670 if ( paren == RX_BUFF_IDX_CARET_PREMATCH
8671 || paren == RX_BUFF_IDX_CARET_FULLMATCH
8672 || paren == RX_BUFF_IDX_CARET_POSTMATCH
8675 bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8677 /* on something like
8680 * the KEEPCOPY is set on the PMOP rather than the regex */
8681 if (PL_curpm && r == PM_GETRE(PL_curpm))
8682 keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8688 /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
8690 case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
8691 case RX_BUFF_IDX_PREMATCH: /* $` */
8692 if (rx->offs[0].start != -1) {
8693 i = rx->offs[0].start;
8702 case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
8703 case RX_BUFF_IDX_POSTMATCH: /* $' */
8704 if (rx->offs[0].end != -1) {
8705 i = rx->sublen - rx->offs[0].end;
8707 s1 = rx->offs[0].end;
8714 default: /* $& / ${^MATCH}, $1, $2, ... */
8715 if (paren <= (I32)rx->nparens &&
8716 (s1 = rx->offs[paren].start) != -1 &&
8717 (t1 = rx->offs[paren].end) != -1)
8723 if (ckWARN(WARN_UNINITIALIZED))
8724 report_uninit((const SV *)sv);
8729 if (i > 0 && RXp_MATCH_UTF8(rx)) {
8730 const char * const s = rx->subbeg - rx->suboffset + s1;
8735 if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
8742 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
8744 PERL_ARGS_ASSERT_REG_QR_PACKAGE;
8745 PERL_UNUSED_ARG(rx);
8749 return newSVpvs("Regexp");
8752 /* Scans the name of a named buffer from the pattern.
8753 * If flags is REG_RSN_RETURN_NULL returns null.
8754 * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
8755 * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
8756 * to the parsed name as looked up in the RExC_paren_names hash.
8757 * If there is an error throws a vFAIL().. type exception.
8760 #define REG_RSN_RETURN_NULL 0
8761 #define REG_RSN_RETURN_NAME 1
8762 #define REG_RSN_RETURN_DATA 2
8765 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
8767 char *name_start = RExC_parse;
8770 PERL_ARGS_ASSERT_REG_SCAN_NAME;
8772 assert (RExC_parse <= RExC_end);
8773 if (RExC_parse == RExC_end) NOOP;
8774 else if (isIDFIRST_lazy_if_safe(RExC_parse, RExC_end, UTF)) {
8775 /* Note that the code here assumes well-formed UTF-8. Skip IDFIRST by
8776 * using do...while */
8779 RExC_parse += UTF8SKIP(RExC_parse);
8780 } while ( RExC_parse < RExC_end
8781 && isWORDCHAR_utf8_safe((U8*)RExC_parse, (U8*) RExC_end));
8785 } while (RExC_parse < RExC_end && isWORDCHAR(*RExC_parse));
8787 RExC_parse++; /* so the <- from the vFAIL is after the offending
8789 vFAIL("Group name must start with a non-digit word character");
8791 sv_name = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
8792 SVs_TEMP | (UTF ? SVf_UTF8 : 0));
8793 if ( flags == REG_RSN_RETURN_NAME)
8795 else if (flags==REG_RSN_RETURN_DATA) {
8798 if ( ! sv_name ) /* should not happen*/
8799 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
8800 if (RExC_paren_names)
8801 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
8803 sv_dat = HeVAL(he_str);
8804 if ( ! sv_dat ) { /* Didn't find group */
8806 /* It might be a forward reference; we can't fail until we
8807 * know, by completing the parse to get all the groups, and
8809 if (RExC_total_parens > 0) {
8810 vFAIL("Reference to nonexistent named group");
8813 REQUIRE_PARENS_PASS;
8819 Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
8820 (unsigned long) flags);
8823 #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
8824 if (RExC_lastparse!=RExC_parse) { \
8825 Perl_re_printf( aTHX_ "%s", \
8826 Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse, \
8827 RExC_end - RExC_parse, 16, \
8829 PERL_PV_ESCAPE_UNI_DETECT | \
8830 PERL_PV_PRETTY_ELLIPSES | \
8831 PERL_PV_PRETTY_LTGT | \
8832 PERL_PV_ESCAPE_RE | \
8833 PERL_PV_PRETTY_EXACTSIZE \
8837 Perl_re_printf( aTHX_ "%16s",""); \
8839 if (RExC_lastnum!=RExC_emit) \
8840 Perl_re_printf( aTHX_ "|%4d", RExC_emit); \
8842 Perl_re_printf( aTHX_ "|%4s",""); \
8843 Perl_re_printf( aTHX_ "|%*s%-4s", \
8844 (int)((depth*2)), "", \
8847 RExC_lastnum=RExC_emit; \
8848 RExC_lastparse=RExC_parse; \
8853 #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
8854 DEBUG_PARSE_MSG((funcname)); \
8855 Perl_re_printf( aTHX_ "%4s","\n"); \
8857 #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({\
8858 DEBUG_PARSE_MSG((funcname)); \
8859 Perl_re_printf( aTHX_ fmt "\n",args); \
8862 /* This section of code defines the inversion list object and its methods. The
8863 * interfaces are highly subject to change, so as much as possible is static to
8864 * this file. An inversion list is here implemented as a malloc'd C UV array
8865 * as an SVt_INVLIST scalar.
8867 * An inversion list for Unicode is an array of code points, sorted by ordinal
8868 * number. Each element gives the code point that begins a range that extends
8869 * up-to but not including the code point given by the next element. The final
8870 * element gives the first code point of a range that extends to the platform's
8871 * infinity. The even-numbered elements (invlist[0], invlist[2], invlist[4],
8872 * ...) give ranges whose code points are all in the inversion list. We say
8873 * that those ranges are in the set. The odd-numbered elements give ranges
8874 * whose code points are not in the inversion list, and hence not in the set.
8875 * Thus, element [0] is the first code point in the list. Element [1]
8876 * is the first code point beyond that not in the list; and element [2] is the
8877 * first code point beyond that that is in the list. In other words, the first
8878 * range is invlist[0]..(invlist[1]-1), and all code points in that range are
8879 * in the inversion list. The second range is invlist[1]..(invlist[2]-1), and
8880 * all code points in that range are not in the inversion list. The third
8881 * range invlist[2]..(invlist[3]-1) gives code points that are in the inversion
8882 * list, and so forth. Thus every element whose index is divisible by two
8883 * gives the beginning of a range that is in the list, and every element whose
8884 * index is not divisible by two gives the beginning of a range not in the
8885 * list. If the final element's index is divisible by two, the inversion list
8886 * extends to the platform's infinity; otherwise the highest code point in the
8887 * inversion list is the contents of that element minus 1.
8889 * A range that contains just a single code point N will look like
8891 * invlist[i+1] == N+1
8893 * If N is UV_MAX (the highest representable code point on the machine), N+1 is
8894 * impossible to represent, so element [i+1] is omitted. The single element
8896 * invlist[0] == UV_MAX
8897 * contains just UV_MAX, but is interpreted as matching to infinity.
8899 * Taking the complement (inverting) an inversion list is quite simple, if the
8900 * first element is 0, remove it; otherwise add a 0 element at the beginning.
8901 * This implementation reserves an element at the beginning of each inversion
8902 * list to always contain 0; there is an additional flag in the header which
8903 * indicates if the list begins at the 0, or is offset to begin at the next
8904 * element. This means that the inversion list can be inverted without any
8905 * copying; just flip the flag.
8907 * More about inversion lists can be found in "Unicode Demystified"
8908 * Chapter 13 by Richard Gillam, published by Addison-Wesley.
8910 * The inversion list data structure is currently implemented as an SV pointing
8911 * to an array of UVs that the SV thinks are bytes. This allows us to have an
8912 * array of UV whose memory management is automatically handled by the existing
8913 * facilities for SV's.
8915 * Some of the methods should always be private to the implementation, and some
8916 * should eventually be made public */
8918 /* The header definitions are in F<invlist_inline.h> */
8920 #ifndef PERL_IN_XSUB_RE
8922 PERL_STATIC_INLINE UV*
8923 S__invlist_array_init(SV* const invlist, const bool will_have_0)
8925 /* Returns a pointer to the first element in the inversion list's array.
8926 * This is called upon initialization of an inversion list. Where the
8927 * array begins depends on whether the list has the code point U+0000 in it
8928 * or not. The other parameter tells it whether the code that follows this
8929 * call is about to put a 0 in the inversion list or not. The first
8930 * element is either the element reserved for 0, if TRUE, or the element
8931 * after it, if FALSE */
8933 bool* offset = get_invlist_offset_addr(invlist);
8934 UV* zero_addr = (UV *) SvPVX(invlist);
8936 PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
8939 assert(! _invlist_len(invlist));
8943 /* 1^1 = 0; 1^0 = 1 */
8944 *offset = 1 ^ will_have_0;
8945 return zero_addr + *offset;
8948 PERL_STATIC_INLINE void
8949 S_invlist_set_len(pTHX_ SV* const invlist, const UV len, const bool offset)
8951 /* Sets the current number of elements stored in the inversion list.
8952 * Updates SvCUR correspondingly */
8953 PERL_UNUSED_CONTEXT;
8954 PERL_ARGS_ASSERT_INVLIST_SET_LEN;
8956 assert(is_invlist(invlist));
8961 : TO_INTERNAL_SIZE(len + offset));
8962 assert(SvLEN(invlist) == 0 || SvCUR(invlist) <= SvLEN(invlist));
8966 S_invlist_replace_list_destroys_src(pTHX_ SV * dest, SV * src)
8968 /* Replaces the inversion list in 'dest' with the one from 'src'. It
8969 * steals the list from 'src', so 'src' is made to have a NULL list. This
8970 * is similar to what SvSetMagicSV() would do, if it were implemented on
8971 * inversion lists, though this routine avoids a copy */
8973 const UV src_len = _invlist_len(src);
8974 const bool src_offset = *get_invlist_offset_addr(src);
8975 const STRLEN src_byte_len = SvLEN(src);
8976 char * array = SvPVX(src);
8978 const int oldtainted = TAINT_get;
8980 PERL_ARGS_ASSERT_INVLIST_REPLACE_LIST_DESTROYS_SRC;
8982 assert(is_invlist(src));
8983 assert(is_invlist(dest));
8984 assert(! invlist_is_iterating(src));
8985 assert(SvCUR(src) == 0 || SvCUR(src) < SvLEN(src));
8987 /* Make sure it ends in the right place with a NUL, as our inversion list
8988 * manipulations aren't careful to keep this true, but sv_usepvn_flags()
8990 array[src_byte_len - 1] = '\0';
8992 TAINT_NOT; /* Otherwise it breaks */
8993 sv_usepvn_flags(dest,
8997 /* This flag is documented to cause a copy to be avoided */
8998 SV_HAS_TRAILING_NUL);
8999 TAINT_set(oldtainted);
9004 /* Finish up copying over the other fields in an inversion list */
9005 *get_invlist_offset_addr(dest) = src_offset;
9006 invlist_set_len(dest, src_len, src_offset);
9007 *get_invlist_previous_index_addr(dest) = 0;
9008 invlist_iterfinish(dest);
9011 PERL_STATIC_INLINE IV*
9012 S_get_invlist_previous_index_addr(SV* invlist)
9014 /* Return the address of the IV that is reserved to hold the cached index
9016 PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
9018 assert(is_invlist(invlist));
9020 return &(((XINVLIST*) SvANY(invlist))->prev_index);
9023 PERL_STATIC_INLINE IV
9024 S_invlist_previous_index(SV* const invlist)
9026 /* Returns cached index of previous search */
9028 PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
9030 return *get_invlist_previous_index_addr(invlist);
9033 PERL_STATIC_INLINE void
9034 S_invlist_set_previous_index(SV* const invlist, const IV index)
9036 /* Caches <index> for later retrieval */
9038 PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
9040 assert(index == 0 || index < (int) _invlist_len(invlist));
9042 *get_invlist_previous_index_addr(invlist) = index;
9045 PERL_STATIC_INLINE void
9046 S_invlist_trim(SV* invlist)
9048 /* Free the not currently-being-used space in an inversion list */
9050 /* But don't free up the space needed for the 0 UV that is always at the
9051 * beginning of the list, nor the trailing NUL */
9052 const UV min_size = TO_INTERNAL_SIZE(1) + 1;
9054 PERL_ARGS_ASSERT_INVLIST_TRIM;
9056 assert(is_invlist(invlist));
9058 SvPV_renew(invlist, MAX(min_size, SvCUR(invlist) + 1));
9061 PERL_STATIC_INLINE void
9062 S_invlist_clear(pTHX_ SV* invlist) /* Empty the inversion list */
9064 PERL_ARGS_ASSERT_INVLIST_CLEAR;
9066 assert(is_invlist(invlist));
9068 invlist_set_len(invlist, 0, 0);
9069 invlist_trim(invlist);
9072 #endif /* ifndef PERL_IN_XSUB_RE */
9074 PERL_STATIC_INLINE bool
9075 S_invlist_is_iterating(SV* const invlist)
9077 PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
9079 return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX;
9082 #ifndef PERL_IN_XSUB_RE
9084 PERL_STATIC_INLINE UV
9085 S_invlist_max(SV* const invlist)
9087 /* Returns the maximum number of elements storable in the inversion list's
9088 * array, without having to realloc() */
9090 PERL_ARGS_ASSERT_INVLIST_MAX;
9092 assert(is_invlist(invlist));
9094 /* Assumes worst case, in which the 0 element is not counted in the
9095 * inversion list, so subtracts 1 for that */
9096 return SvLEN(invlist) == 0 /* This happens under _new_invlist_C_array */
9097 ? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1
9098 : FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1;
9102 S_initialize_invlist_guts(pTHX_ SV* invlist, const Size_t initial_size)
9104 PERL_ARGS_ASSERT_INITIALIZE_INVLIST_GUTS;
9106 /* First 1 is in case the zero element isn't in the list; second 1 is for
9108 SvGROW(invlist, TO_INTERNAL_SIZE(initial_size + 1) + 1);
9109 invlist_set_len(invlist, 0, 0);
9111 /* Force iterinit() to be used to get iteration to work */
9112 invlist_iterfinish(invlist);
9114 *get_invlist_previous_index_addr(invlist) = 0;
9118 Perl__new_invlist(pTHX_ IV initial_size)
9121 /* Return a pointer to a newly constructed inversion list, with enough
9122 * space to store 'initial_size' elements. If that number is negative, a
9123 * system default is used instead */
9127 if (initial_size < 0) {
9131 new_list = newSV_type(SVt_INVLIST);
9132 initialize_invlist_guts(new_list, initial_size);
9138 Perl__new_invlist_C_array(pTHX_ const UV* const list)
9140 /* Return a pointer to a newly constructed inversion list, initialized to
9141 * point to <list>, which has to be in the exact correct inversion list
9142 * form, including internal fields. Thus this is a dangerous routine that
9143 * should not be used in the wrong hands. The passed in 'list' contains
9144 * several header fields at the beginning that are not part of the
9145 * inversion list body proper */
9147 const STRLEN length = (STRLEN) list[0];
9148 const UV version_id = list[1];
9149 const bool offset = cBOOL(list[2]);
9150 #define HEADER_LENGTH 3
9151 /* If any of the above changes in any way, you must change HEADER_LENGTH
9152 * (if appropriate) and regenerate INVLIST_VERSION_ID by running
9153 * perl -E 'say int(rand 2**31-1)'
9155 #define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and
9156 data structure type, so that one being
9157 passed in can be validated to be an
9158 inversion list of the correct vintage.
9161 SV* invlist = newSV_type(SVt_INVLIST);
9163 PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
9165 if (version_id != INVLIST_VERSION_ID) {
9166 Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
9169 /* The generated array passed in includes header elements that aren't part
9170 * of the list proper, so start it just after them */
9171 SvPV_set(invlist, (char *) (list + HEADER_LENGTH));
9173 SvLEN_set(invlist, 0); /* Means we own the contents, and the system
9174 shouldn't touch it */
9176 *(get_invlist_offset_addr(invlist)) = offset;
9178 /* The 'length' passed to us is the physical number of elements in the
9179 * inversion list. But if there is an offset the logical number is one
9181 invlist_set_len(invlist, length - offset, offset);
9183 invlist_set_previous_index(invlist, 0);
9185 /* Initialize the iteration pointer. */
9186 invlist_iterfinish(invlist);
9188 SvREADONLY_on(invlist);
9194 S_invlist_extend(pTHX_ SV* const invlist, const UV new_max)
9196 /* Grow the maximum size of an inversion list */
9198 PERL_ARGS_ASSERT_INVLIST_EXTEND;
9200 assert(is_invlist(invlist));
9202 /* Add one to account for the zero element at the beginning which may not
9203 * be counted by the calling parameters */
9204 SvGROW((SV *)invlist, TO_INTERNAL_SIZE(new_max + 1));
9208 S__append_range_to_invlist(pTHX_ SV* const invlist,
9209 const UV start, const UV end)
9211 /* Subject to change or removal. Append the range from 'start' to 'end' at
9212 * the end of the inversion list. The range must be above any existing
9216 UV max = invlist_max(invlist);
9217 UV len = _invlist_len(invlist);
9220 PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
9222 if (len == 0) { /* Empty lists must be initialized */
9223 offset = start != 0;
9224 array = _invlist_array_init(invlist, ! offset);
9227 /* Here, the existing list is non-empty. The current max entry in the
9228 * list is generally the first value not in the set, except when the
9229 * set extends to the end of permissible values, in which case it is
9230 * the first entry in that final set, and so this call is an attempt to
9231 * append out-of-order */
9233 UV final_element = len - 1;
9234 array = invlist_array(invlist);
9235 if ( array[final_element] > start
9236 || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
9238 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",
9239 array[final_element], start,
9240 ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
9243 /* Here, it is a legal append. If the new range begins 1 above the end
9244 * of the range below it, it is extending the range below it, so the
9245 * new first value not in the set is one greater than the newly
9246 * extended range. */
9247 offset = *get_invlist_offset_addr(invlist);
9248 if (array[final_element] == start) {
9249 if (end != UV_MAX) {
9250 array[final_element] = end + 1;
9253 /* But if the end is the maximum representable on the machine,
9254 * assume that infinity was actually what was meant. Just let
9255 * the range that this would extend to have no end */
9256 invlist_set_len(invlist, len - 1, offset);
9262 /* Here the new range doesn't extend any existing set. Add it */
9264 len += 2; /* Includes an element each for the start and end of range */
9266 /* If wll overflow the existing space, extend, which may cause the array to
9269 invlist_extend(invlist, len);
9271 /* Have to set len here to avoid assert failure in invlist_array() */
9272 invlist_set_len(invlist, len, offset);
9274 array = invlist_array(invlist);
9277 invlist_set_len(invlist, len, offset);
9280 /* The next item on the list starts the range, the one after that is
9281 * one past the new range. */
9282 array[len - 2] = start;
9283 if (end != UV_MAX) {
9284 array[len - 1] = end + 1;
9287 /* But if the end is the maximum representable on the machine, just let
9288 * the range have no end */
9289 invlist_set_len(invlist, len - 1, offset);
9294 Perl__invlist_search(SV* const invlist, const UV cp)
9296 /* Searches the inversion list for the entry that contains the input code
9297 * point <cp>. If <cp> is not in the list, -1 is returned. Otherwise, the
9298 * return value is the index into the list's array of the range that
9299 * contains <cp>, that is, 'i' such that
9300 * array[i] <= cp < array[i+1]
9305 IV high = _invlist_len(invlist);
9306 const IV highest_element = high - 1;
9309 PERL_ARGS_ASSERT__INVLIST_SEARCH;
9311 /* If list is empty, return failure. */
9316 /* (We can't get the array unless we know the list is non-empty) */
9317 array = invlist_array(invlist);
9319 mid = invlist_previous_index(invlist);
9321 if (mid > highest_element) {
9322 mid = highest_element;
9325 /* <mid> contains the cache of the result of the previous call to this
9326 * function (0 the first time). See if this call is for the same result,
9327 * or if it is for mid-1. This is under the theory that calls to this
9328 * function will often be for related code points that are near each other.
9329 * And benchmarks show that caching gives better results. We also test
9330 * here if the code point is within the bounds of the list. These tests
9331 * replace others that would have had to be made anyway to make sure that
9332 * the array bounds were not exceeded, and these give us extra information
9333 * at the same time */
9334 if (cp >= array[mid]) {
9335 if (cp >= array[highest_element]) {
9336 return highest_element;
9339 /* Here, array[mid] <= cp < array[highest_element]. This means that
9340 * the final element is not the answer, so can exclude it; it also
9341 * means that <mid> is not the final element, so can refer to 'mid + 1'
9343 if (cp < array[mid + 1]) {
9349 else { /* cp < aray[mid] */
9350 if (cp < array[0]) { /* Fail if outside the array */
9354 if (cp >= array[mid - 1]) {
9359 /* Binary search. What we are looking for is <i> such that
9360 * array[i] <= cp < array[i+1]
9361 * The loop below converges on the i+1. Note that there may not be an
9362 * (i+1)th element in the array, and things work nonetheless */
9363 while (low < high) {
9364 mid = (low + high) / 2;
9365 assert(mid <= highest_element);
9366 if (array[mid] <= cp) { /* cp >= array[mid] */
9369 /* We could do this extra test to exit the loop early.
9370 if (cp < array[low]) {
9375 else { /* cp < array[mid] */
9382 invlist_set_previous_index(invlist, high);
9387 Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9388 const bool complement_b, SV** output)
9390 /* Take the union of two inversion lists and point '*output' to it. On
9391 * input, '*output' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9392 * even 'a' or 'b'). If to an inversion list, the contents of the original
9393 * list will be replaced by the union. The first list, 'a', may be
9394 * NULL, in which case a copy of the second list is placed in '*output'.
9395 * If 'complement_b' is TRUE, the union is taken of the complement
9396 * (inversion) of 'b' instead of b itself.
9398 * The basis for this comes from "Unicode Demystified" Chapter 13 by
9399 * Richard Gillam, published by Addison-Wesley, and explained at some
9400 * length there. The preface says to incorporate its examples into your
9401 * code at your own risk.
9403 * The algorithm is like a merge sort. */
9405 const UV* array_a; /* a's array */
9407 UV len_a; /* length of a's array */
9410 SV* u; /* the resulting union */
9414 UV i_a = 0; /* current index into a's array */
9418 /* running count, as explained in the algorithm source book; items are
9419 * stopped accumulating and are output when the count changes to/from 0.
9420 * The count is incremented when we start a range that's in an input's set,
9421 * and decremented when we start a range that's not in a set. So this
9422 * variable can be 0, 1, or 2. When it is 0 neither input is in their set,
9423 * and hence nothing goes into the union; 1, just one of the inputs is in
9424 * its set (and its current range gets added to the union); and 2 when both
9425 * inputs are in their sets. */
9428 PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
9430 assert(*output == NULL || is_invlist(*output));
9432 len_b = _invlist_len(b);
9435 /* Here, 'b' is empty, hence it's complement is all possible code
9436 * points. So if the union includes the complement of 'b', it includes
9437 * everything, and we need not even look at 'a'. It's easiest to
9438 * create a new inversion list that matches everything. */
9440 SV* everything = _add_range_to_invlist(NULL, 0, UV_MAX);
9442 if (*output == NULL) { /* If the output didn't exist, just point it
9444 *output = everything;
9446 else { /* Otherwise, replace its contents with the new list */
9447 invlist_replace_list_destroys_src(*output, everything);
9448 SvREFCNT_dec_NN(everything);
9454 /* Here, we don't want the complement of 'b', and since 'b' is empty,
9455 * the union will come entirely from 'a'. If 'a' is NULL or empty, the
9456 * output will be empty */
9458 if (a == NULL || _invlist_len(a) == 0) {
9459 if (*output == NULL) {
9460 *output = _new_invlist(0);
9463 invlist_clear(*output);
9468 /* Here, 'a' is not empty, but 'b' is, so 'a' entirely determines the
9469 * union. We can just return a copy of 'a' if '*output' doesn't point
9470 * to an existing list */
9471 if (*output == NULL) {
9472 *output = invlist_clone(a, NULL);
9476 /* If the output is to overwrite 'a', we have a no-op, as it's
9482 /* Here, '*output' is to be overwritten by 'a' */
9483 u = invlist_clone(a, NULL);
9484 invlist_replace_list_destroys_src(*output, u);
9490 /* Here 'b' is not empty. See about 'a' */
9492 if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
9494 /* Here, 'a' is empty (and b is not). That means the union will come
9495 * entirely from 'b'. If '*output' is NULL, we can directly return a
9496 * clone of 'b'. Otherwise, we replace the contents of '*output' with
9499 SV ** dest = (*output == NULL) ? output : &u;
9500 *dest = invlist_clone(b, NULL);
9502 _invlist_invert(*dest);
9506 invlist_replace_list_destroys_src(*output, u);
9513 /* Here both lists exist and are non-empty */
9514 array_a = invlist_array(a);
9515 array_b = invlist_array(b);
9517 /* If are to take the union of 'a' with the complement of b, set it
9518 * up so are looking at b's complement. */
9521 /* To complement, we invert: if the first element is 0, remove it. To
9522 * do this, we just pretend the array starts one later */
9523 if (array_b[0] == 0) {
9529 /* But if the first element is not zero, we pretend the list starts
9530 * at the 0 that is always stored immediately before the array. */
9536 /* Size the union for the worst case: that the sets are completely
9538 u = _new_invlist(len_a + len_b);
9540 /* Will contain U+0000 if either component does */
9541 array_u = _invlist_array_init(u, ( len_a > 0 && array_a[0] == 0)
9542 || (len_b > 0 && array_b[0] == 0));
9544 /* Go through each input list item by item, stopping when have exhausted
9546 while (i_a < len_a && i_b < len_b) {
9547 UV cp; /* The element to potentially add to the union's array */
9548 bool cp_in_set; /* is it in the the input list's set or not */
9550 /* We need to take one or the other of the two inputs for the union.
9551 * Since we are merging two sorted lists, we take the smaller of the
9552 * next items. In case of a tie, we take first the one that is in its
9553 * set. If we first took the one not in its set, it would decrement
9554 * the count, possibly to 0 which would cause it to be output as ending
9555 * the range, and the next time through we would take the same number,
9556 * and output it again as beginning the next range. By doing it the
9557 * opposite way, there is no possibility that the count will be
9558 * momentarily decremented to 0, and thus the two adjoining ranges will
9559 * be seamlessly merged. (In a tie and both are in the set or both not
9560 * in the set, it doesn't matter which we take first.) */
9561 if ( array_a[i_a] < array_b[i_b]
9562 || ( array_a[i_a] == array_b[i_b]
9563 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9565 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9566 cp = array_a[i_a++];
9569 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9570 cp = array_b[i_b++];
9573 /* Here, have chosen which of the two inputs to look at. Only output
9574 * if the running count changes to/from 0, which marks the
9575 * beginning/end of a range that's in the set */
9578 array_u[i_u++] = cp;
9585 array_u[i_u++] = cp;
9591 /* The loop above increments the index into exactly one of the input lists
9592 * each iteration, and ends when either index gets to its list end. That
9593 * means the other index is lower than its end, and so something is
9594 * remaining in that one. We decrement 'count', as explained below, if
9595 * that list is in its set. (i_a and i_b each currently index the element
9596 * beyond the one we care about.) */
9597 if ( (i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9598 || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9603 /* Above we decremented 'count' if the list that had unexamined elements in
9604 * it was in its set. This has made it so that 'count' being non-zero
9605 * means there isn't anything left to output; and 'count' equal to 0 means
9606 * that what is left to output is precisely that which is left in the
9607 * non-exhausted input list.
9609 * To see why, note first that the exhausted input obviously has nothing
9610 * left to add to the union. If it was in its set at its end, that means
9611 * the set extends from here to the platform's infinity, and hence so does
9612 * the union and the non-exhausted set is irrelevant. The exhausted set
9613 * also contributed 1 to 'count'. If 'count' was 2, it got decremented to
9614 * 1, but if it was 1, the non-exhausted set wasn't in its set, and so
9615 * 'count' remains at 1. This is consistent with the decremented 'count'
9616 * != 0 meaning there's nothing left to add to the union.
9618 * But if the exhausted input wasn't in its set, it contributed 0 to
9619 * 'count', and the rest of the union will be whatever the other input is.
9620 * If 'count' was 0, neither list was in its set, and 'count' remains 0;
9621 * otherwise it gets decremented to 0. This is consistent with 'count'
9622 * == 0 meaning the remainder of the union is whatever is left in the
9623 * non-exhausted list. */
9628 IV copy_count = len_a - i_a;
9629 if (copy_count > 0) { /* The non-exhausted input is 'a' */
9630 Copy(array_a + i_a, array_u + i_u, copy_count, UV);
9632 else { /* The non-exhausted input is b */
9633 copy_count = len_b - i_b;
9634 Copy(array_b + i_b, array_u + i_u, copy_count, UV);
9636 len_u = i_u + copy_count;
9639 /* Set the result to the final length, which can change the pointer to
9640 * array_u, so re-find it. (Note that it is unlikely that this will
9641 * change, as we are shrinking the space, not enlarging it) */
9642 if (len_u != _invlist_len(u)) {
9643 invlist_set_len(u, len_u, *get_invlist_offset_addr(u));
9645 array_u = invlist_array(u);
9648 if (*output == NULL) { /* Simply return the new inversion list */
9652 /* Otherwise, overwrite the inversion list that was in '*output'. We
9653 * could instead free '*output', and then set it to 'u', but experience
9654 * has shown [perl #127392] that if the input is a mortal, we can get a
9655 * huge build-up of these during regex compilation before they get
9657 invlist_replace_list_destroys_src(*output, u);
9665 Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9666 const bool complement_b, SV** i)
9668 /* Take the intersection of two inversion lists and point '*i' to it. On
9669 * input, '*i' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9670 * even 'a' or 'b'). If to an inversion list, the contents of the original
9671 * list will be replaced by the intersection. The first list, 'a', may be
9672 * NULL, in which case '*i' will be an empty list. If 'complement_b' is
9673 * TRUE, the result will be the intersection of 'a' and the complement (or
9674 * inversion) of 'b' instead of 'b' directly.
9676 * The basis for this comes from "Unicode Demystified" Chapter 13 by
9677 * Richard Gillam, published by Addison-Wesley, and explained at some
9678 * length there. The preface says to incorporate its examples into your
9679 * code at your own risk. In fact, it had bugs
9681 * The algorithm is like a merge sort, and is essentially the same as the
9685 const UV* array_a; /* a's array */
9687 UV len_a; /* length of a's array */
9690 SV* r; /* the resulting intersection */
9694 UV i_a = 0; /* current index into a's array */
9698 /* running count of how many of the two inputs are postitioned at ranges
9699 * that are in their sets. As explained in the algorithm source book,
9700 * items are stopped accumulating and are output when the count changes
9701 * to/from 2. The count is incremented when we start a range that's in an
9702 * input's set, and decremented when we start a range that's not in a set.
9703 * Only when it is 2 are we in the intersection. */
9706 PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
9708 assert(*i == NULL || is_invlist(*i));
9710 /* Special case if either one is empty */
9711 len_a = (a == NULL) ? 0 : _invlist_len(a);
9712 if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
9713 if (len_a != 0 && complement_b) {
9715 /* Here, 'a' is not empty, therefore from the enclosing 'if', 'b'
9716 * must be empty. Here, also we are using 'b's complement, which
9717 * hence must be every possible code point. Thus the intersection
9720 if (*i == a) { /* No-op */
9725 *i = invlist_clone(a, NULL);
9729 r = invlist_clone(a, NULL);
9730 invlist_replace_list_destroys_src(*i, r);
9735 /* Here, 'a' or 'b' is empty and not using the complement of 'b'. The
9736 * intersection must be empty */
9738 *i = _new_invlist(0);
9746 /* Here both lists exist and are non-empty */
9747 array_a = invlist_array(a);
9748 array_b = invlist_array(b);
9750 /* If are to take the intersection of 'a' with the complement of b, set it
9751 * up so are looking at b's complement. */
9754 /* To complement, we invert: if the first element is 0, remove it. To
9755 * do this, we just pretend the array starts one later */
9756 if (array_b[0] == 0) {
9762 /* But if the first element is not zero, we pretend the list starts
9763 * at the 0 that is always stored immediately before the array. */
9769 /* Size the intersection for the worst case: that the intersection ends up
9770 * fragmenting everything to be completely disjoint */
9771 r= _new_invlist(len_a + len_b);
9773 /* Will contain U+0000 iff both components do */
9774 array_r = _invlist_array_init(r, len_a > 0 && array_a[0] == 0
9775 && len_b > 0 && array_b[0] == 0);
9777 /* Go through each list item by item, stopping when have exhausted one of
9779 while (i_a < len_a && i_b < len_b) {
9780 UV cp; /* The element to potentially add to the intersection's
9782 bool cp_in_set; /* Is it in the input list's set or not */
9784 /* We need to take one or the other of the two inputs for the
9785 * intersection. Since we are merging two sorted lists, we take the
9786 * smaller of the next items. In case of a tie, we take first the one
9787 * that is not in its set (a difference from the union algorithm). If
9788 * we first took the one in its set, it would increment the count,
9789 * possibly to 2 which would cause it to be output as starting a range
9790 * in the intersection, and the next time through we would take that
9791 * same number, and output it again as ending the set. By doing the
9792 * opposite of this, there is no possibility that the count will be
9793 * momentarily incremented to 2. (In a tie and both are in the set or
9794 * both not in the set, it doesn't matter which we take first.) */
9795 if ( array_a[i_a] < array_b[i_b]
9796 || ( array_a[i_a] == array_b[i_b]
9797 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9799 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9800 cp = array_a[i_a++];
9803 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9807 /* Here, have chosen which of the two inputs to look at. Only output
9808 * if the running count changes to/from 2, which marks the
9809 * beginning/end of a range that's in the intersection */
9813 array_r[i_r++] = cp;
9818 array_r[i_r++] = cp;
9825 /* The loop above increments the index into exactly one of the input lists
9826 * each iteration, and ends when either index gets to its list end. That
9827 * means the other index is lower than its end, and so something is
9828 * remaining in that one. We increment 'count', as explained below, if the
9829 * exhausted list was in its set. (i_a and i_b each currently index the
9830 * element beyond the one we care about.) */
9831 if ( (i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9832 || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9837 /* Above we incremented 'count' if the exhausted list was in its set. This
9838 * has made it so that 'count' being below 2 means there is nothing left to
9839 * output; otheriwse what's left to add to the intersection is precisely
9840 * that which is left in the non-exhausted input list.
9842 * To see why, note first that the exhausted input obviously has nothing
9843 * left to affect the intersection. If it was in its set at its end, that
9844 * means the set extends from here to the platform's infinity, and hence
9845 * anything in the non-exhausted's list will be in the intersection, and
9846 * anything not in it won't be. Hence, the rest of the intersection is
9847 * precisely what's in the non-exhausted list The exhausted set also
9848 * contributed 1 to 'count', meaning 'count' was at least 1. Incrementing
9849 * it means 'count' is now at least 2. This is consistent with the
9850 * incremented 'count' being >= 2 means to add the non-exhausted list to
9853 * But if the exhausted input wasn't in its set, it contributed 0 to
9854 * 'count', and the intersection can't include anything further; the
9855 * non-exhausted set is irrelevant. 'count' was at most 1, and doesn't get
9856 * incremented. This is consistent with 'count' being < 2 meaning nothing
9857 * further to add to the intersection. */
9858 if (count < 2) { /* Nothing left to put in the intersection. */
9861 else { /* copy the non-exhausted list, unchanged. */
9862 IV copy_count = len_a - i_a;
9863 if (copy_count > 0) { /* a is the one with stuff left */
9864 Copy(array_a + i_a, array_r + i_r, copy_count, UV);
9866 else { /* b is the one with stuff left */
9867 copy_count = len_b - i_b;
9868 Copy(array_b + i_b, array_r + i_r, copy_count, UV);
9870 len_r = i_r + copy_count;
9873 /* Set the result to the final length, which can change the pointer to
9874 * array_r, so re-find it. (Note that it is unlikely that this will
9875 * change, as we are shrinking the space, not enlarging it) */
9876 if (len_r != _invlist_len(r)) {
9877 invlist_set_len(r, len_r, *get_invlist_offset_addr(r));
9879 array_r = invlist_array(r);
9882 if (*i == NULL) { /* Simply return the calculated intersection */
9885 else { /* Otherwise, replace the existing inversion list in '*i'. We could
9886 instead free '*i', and then set it to 'r', but experience has
9887 shown [perl #127392] that if the input is a mortal, we can get a
9888 huge build-up of these during regex compilation before they get
9891 invlist_replace_list_destroys_src(*i, r);
9903 Perl__add_range_to_invlist(pTHX_ SV* invlist, UV start, UV end)
9905 /* Add the range from 'start' to 'end' inclusive to the inversion list's
9906 * set. A pointer to the inversion list is returned. This may actually be
9907 * a new list, in which case the passed in one has been destroyed. The
9908 * passed-in inversion list can be NULL, in which case a new one is created
9909 * with just the one range in it. The new list is not necessarily
9910 * NUL-terminated. Space is not freed if the inversion list shrinks as a
9911 * result of this function. The gain would not be large, and in many
9912 * cases, this is called multiple times on a single inversion list, so
9913 * anything freed may almost immediately be needed again.
9915 * This used to mostly call the 'union' routine, but that is much more
9916 * heavyweight than really needed for a single range addition */
9918 UV* array; /* The array implementing the inversion list */
9919 UV len; /* How many elements in 'array' */
9920 SSize_t i_s; /* index into the invlist array where 'start'
9922 SSize_t i_e = 0; /* And the index where 'end' should go */
9923 UV cur_highest; /* The highest code point in the inversion list
9924 upon entry to this function */
9926 /* This range becomes the whole inversion list if none already existed */
9927 if (invlist == NULL) {
9928 invlist = _new_invlist(2);
9929 _append_range_to_invlist(invlist, start, end);
9933 /* Likewise, if the inversion list is currently empty */
9934 len = _invlist_len(invlist);
9936 _append_range_to_invlist(invlist, start, end);
9940 /* Starting here, we have to know the internals of the list */
9941 array = invlist_array(invlist);
9943 /* If the new range ends higher than the current highest ... */
9944 cur_highest = invlist_highest(invlist);
9945 if (end > cur_highest) {
9947 /* If the whole range is higher, we can just append it */
9948 if (start > cur_highest) {
9949 _append_range_to_invlist(invlist, start, end);
9953 /* Otherwise, add the portion that is higher ... */
9954 _append_range_to_invlist(invlist, cur_highest + 1, end);
9956 /* ... and continue on below to handle the rest. As a result of the
9957 * above append, we know that the index of the end of the range is the
9958 * final even numbered one of the array. Recall that the final element
9959 * always starts a range that extends to infinity. If that range is in
9960 * the set (meaning the set goes from here to infinity), it will be an
9961 * even index, but if it isn't in the set, it's odd, and the final
9962 * range in the set is one less, which is even. */
9963 if (end == UV_MAX) {
9971 /* We have dealt with appending, now see about prepending. If the new
9972 * range starts lower than the current lowest ... */
9973 if (start < array[0]) {
9975 /* Adding something which has 0 in it is somewhat tricky, and uncommon.
9976 * Let the union code handle it, rather than having to know the
9977 * trickiness in two code places. */
9978 if (UNLIKELY(start == 0)) {
9981 range_invlist = _new_invlist(2);
9982 _append_range_to_invlist(range_invlist, start, end);
9984 _invlist_union(invlist, range_invlist, &invlist);
9986 SvREFCNT_dec_NN(range_invlist);
9991 /* If the whole new range comes before the first entry, and doesn't
9992 * extend it, we have to insert it as an additional range */
9993 if (end < array[0] - 1) {
9995 goto splice_in_new_range;
9998 /* Here the new range adjoins the existing first range, extending it
10002 /* And continue on below to handle the rest. We know that the index of
10003 * the beginning of the range is the first one of the array */
10006 else { /* Not prepending any part of the new range to the existing list.
10007 * Find where in the list it should go. This finds i_s, such that:
10008 * invlist[i_s] <= start < array[i_s+1]
10010 i_s = _invlist_search(invlist, start);
10013 /* At this point, any extending before the beginning of the inversion list
10014 * and/or after the end has been done. This has made it so that, in the
10015 * code below, each endpoint of the new range is either in a range that is
10016 * in the set, or is in a gap between two ranges that are. This means we
10017 * don't have to worry about exceeding the array bounds.
10019 * Find where in the list the new range ends (but we can skip this if we
10020 * have already determined what it is, or if it will be the same as i_s,
10021 * which we already have computed) */
10023 i_e = (start == end)
10025 : _invlist_search(invlist, end);
10028 /* Here generally invlist[i_e] <= end < array[i_e+1]. But if invlist[i_e]
10029 * is a range that goes to infinity there is no element at invlist[i_e+1],
10030 * so only the first relation holds. */
10032 if ( ! ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10034 /* Here, the ranges on either side of the beginning of the new range
10035 * are in the set, and this range starts in the gap between them.
10037 * The new range extends the range above it downwards if the new range
10038 * ends at or above that range's start */
10039 const bool extends_the_range_above = ( end == UV_MAX
10040 || end + 1 >= array[i_s+1]);
10042 /* The new range extends the range below it upwards if it begins just
10043 * after where that range ends */
10044 if (start == array[i_s]) {
10046 /* If the new range fills the entire gap between the other ranges,
10047 * they will get merged together. Other ranges may also get
10048 * merged, depending on how many of them the new range spans. In
10049 * the general case, we do the merge later, just once, after we
10050 * figure out how many to merge. But in the case where the new
10051 * range exactly spans just this one gap (possibly extending into
10052 * the one above), we do the merge here, and an early exit. This
10053 * is done here to avoid having to special case later. */
10054 if (i_e - i_s <= 1) {
10056 /* If i_e - i_s == 1, it means that the new range terminates
10057 * within the range above, and hence 'extends_the_range_above'
10058 * must be true. (If the range above it extends to infinity,
10059 * 'i_s+2' will be above the array's limit, but 'len-i_s-2'
10060 * will be 0, so no harm done.) */
10061 if (extends_the_range_above) {
10062 Move(array + i_s + 2, array + i_s, len - i_s - 2, UV);
10063 invlist_set_len(invlist,
10065 *(get_invlist_offset_addr(invlist)));
10069 /* Here, i_e must == i_s. We keep them in sync, as they apply
10070 * to the same range, and below we are about to decrement i_s
10075 /* Here, the new range is adjacent to the one below. (It may also
10076 * span beyond the range above, but that will get resolved later.)
10077 * Extend the range below to include this one. */
10078 array[i_s] = (end == UV_MAX) ? UV_MAX : end + 1;
10080 start = array[i_s];
10082 else if (extends_the_range_above) {
10084 /* Here the new range only extends the range above it, but not the
10085 * one below. It merges with the one above. Again, we keep i_e
10086 * and i_s in sync if they point to the same range */
10091 array[i_s] = start;
10095 /* Here, we've dealt with the new range start extending any adjoining
10098 * If the new range extends to infinity, it is now the final one,
10099 * regardless of what was there before */
10100 if (UNLIKELY(end == UV_MAX)) {
10101 invlist_set_len(invlist, i_s + 1, *(get_invlist_offset_addr(invlist)));
10105 /* If i_e started as == i_s, it has also been dealt with,
10106 * and been updated to the new i_s, which will fail the following if */
10107 if (! ELEMENT_RANGE_MATCHES_INVLIST(i_e)) {
10109 /* Here, the ranges on either side of the end of the new range are in
10110 * the set, and this range ends in the gap between them.
10112 * If this range is adjacent to (hence extends) the range above it, it
10113 * becomes part of that range; likewise if it extends the range below,
10114 * it becomes part of that range */
10115 if (end + 1 == array[i_e+1]) {
10117 array[i_e] = start;
10119 else if (start <= array[i_e]) {
10120 array[i_e] = end + 1;
10127 /* If the range fits entirely in an existing range (as possibly already
10128 * extended above), it doesn't add anything new */
10129 if (ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10133 /* Here, no part of the range is in the list. Must add it. It will
10134 * occupy 2 more slots */
10135 splice_in_new_range:
10137 invlist_extend(invlist, len + 2);
10138 array = invlist_array(invlist);
10139 /* Move the rest of the array down two slots. Don't include any
10141 Move(array + i_e + 1, array + i_e + 3, len - i_e - 1, UV);
10143 /* Do the actual splice */
10144 array[i_e+1] = start;
10145 array[i_e+2] = end + 1;
10146 invlist_set_len(invlist, len + 2, *(get_invlist_offset_addr(invlist)));
10150 /* Here the new range crossed the boundaries of a pre-existing range. The
10151 * code above has adjusted things so that both ends are in ranges that are
10152 * in the set. This means everything in between must also be in the set.
10153 * Just squash things together */
10154 Move(array + i_e + 1, array + i_s + 1, len - i_e - 1, UV);
10155 invlist_set_len(invlist,
10157 *(get_invlist_offset_addr(invlist)));
10163 Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0,
10164 UV** other_elements_ptr)
10166 /* Create and return an inversion list whose contents are to be populated
10167 * by the caller. The caller gives the number of elements (in 'size') and
10168 * the very first element ('element0'). This function will set
10169 * '*other_elements_ptr' to an array of UVs, where the remaining elements
10170 * are to be placed.
10172 * Obviously there is some trust involved that the caller will properly
10173 * fill in the other elements of the array.
10175 * (The first element needs to be passed in, as the underlying code does
10176 * things differently depending on whether it is zero or non-zero) */
10178 SV* invlist = _new_invlist(size);
10181 PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST;
10183 invlist = add_cp_to_invlist(invlist, element0);
10184 offset = *get_invlist_offset_addr(invlist);
10186 invlist_set_len(invlist, size, offset);
10187 *other_elements_ptr = invlist_array(invlist) + 1;
10193 PERL_STATIC_INLINE SV*
10194 S_add_cp_to_invlist(pTHX_ SV* invlist, const UV cp) {
10195 return _add_range_to_invlist(invlist, cp, cp);
10198 #ifndef PERL_IN_XSUB_RE
10200 Perl__invlist_invert(pTHX_ SV* const invlist)
10202 /* Complement the input inversion list. This adds a 0 if the list didn't
10203 * have a zero; removes it otherwise. As described above, the data
10204 * structure is set up so that this is very efficient */
10206 PERL_ARGS_ASSERT__INVLIST_INVERT;
10208 assert(! invlist_is_iterating(invlist));
10210 /* The inverse of matching nothing is matching everything */
10211 if (_invlist_len(invlist) == 0) {
10212 _append_range_to_invlist(invlist, 0, UV_MAX);
10216 *get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist);
10220 Perl_invlist_clone(pTHX_ SV* const invlist, SV* new_invlist)
10222 /* Return a new inversion list that is a copy of the input one, which is
10223 * unchanged. The new list will not be mortal even if the old one was. */
10225 const STRLEN nominal_length = _invlist_len(invlist);
10226 const STRLEN physical_length = SvCUR(invlist);
10227 const bool offset = *(get_invlist_offset_addr(invlist));
10229 PERL_ARGS_ASSERT_INVLIST_CLONE;
10231 if (new_invlist == NULL) {
10232 new_invlist = _new_invlist(nominal_length);
10235 sv_upgrade(new_invlist, SVt_INVLIST);
10236 initialize_invlist_guts(new_invlist, nominal_length);
10239 *(get_invlist_offset_addr(new_invlist)) = offset;
10240 invlist_set_len(new_invlist, nominal_length, offset);
10241 Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char);
10243 return new_invlist;
10248 PERL_STATIC_INLINE STRLEN*
10249 S_get_invlist_iter_addr(SV* invlist)
10251 /* Return the address of the UV that contains the current iteration
10254 PERL_ARGS_ASSERT_GET_INVLIST_ITER_ADDR;
10256 assert(is_invlist(invlist));
10258 return &(((XINVLIST*) SvANY(invlist))->iterator);
10261 PERL_STATIC_INLINE void
10262 S_invlist_iterinit(SV* invlist) /* Initialize iterator for invlist */
10264 PERL_ARGS_ASSERT_INVLIST_ITERINIT;
10266 *get_invlist_iter_addr(invlist) = 0;
10269 PERL_STATIC_INLINE void
10270 S_invlist_iterfinish(SV* invlist)
10272 /* Terminate iterator for invlist. This is to catch development errors.
10273 * Any iteration that is interrupted before completed should call this
10274 * function. Functions that add code points anywhere else but to the end
10275 * of an inversion list assert that they are not in the middle of an
10276 * iteration. If they were, the addition would make the iteration
10277 * problematical: if the iteration hadn't reached the place where things
10278 * were being added, it would be ok */
10280 PERL_ARGS_ASSERT_INVLIST_ITERFINISH;
10282 *get_invlist_iter_addr(invlist) = (STRLEN) UV_MAX;
10286 S_invlist_iternext(SV* invlist, UV* start, UV* end)
10288 /* An C<invlist_iterinit> call on <invlist> must be used to set this up.
10289 * This call sets in <*start> and <*end>, the next range in <invlist>.
10290 * Returns <TRUE> if successful and the next call will return the next
10291 * range; <FALSE> if was already at the end of the list. If the latter,
10292 * <*start> and <*end> are unchanged, and the next call to this function
10293 * will start over at the beginning of the list */
10295 STRLEN* pos = get_invlist_iter_addr(invlist);
10296 UV len = _invlist_len(invlist);
10299 PERL_ARGS_ASSERT_INVLIST_ITERNEXT;
10302 *pos = (STRLEN) UV_MAX; /* Force iterinit() to be required next time */
10306 array = invlist_array(invlist);
10308 *start = array[(*pos)++];
10314 *end = array[(*pos)++] - 1;
10320 PERL_STATIC_INLINE UV
10321 S_invlist_highest(SV* const invlist)
10323 /* Returns the highest code point that matches an inversion list. This API
10324 * has an ambiguity, as it returns 0 under either the highest is actually
10325 * 0, or if the list is empty. If this distinction matters to you, check
10326 * for emptiness before calling this function */
10328 UV len = _invlist_len(invlist);
10331 PERL_ARGS_ASSERT_INVLIST_HIGHEST;
10337 array = invlist_array(invlist);
10339 /* The last element in the array in the inversion list always starts a
10340 * range that goes to infinity. That range may be for code points that are
10341 * matched in the inversion list, or it may be for ones that aren't
10342 * matched. In the latter case, the highest code point in the set is one
10343 * less than the beginning of this range; otherwise it is the final element
10344 * of this range: infinity */
10345 return (ELEMENT_RANGE_MATCHES_INVLIST(len - 1))
10347 : array[len - 1] - 1;
10351 S_invlist_contents(pTHX_ SV* const invlist, const bool traditional_style)
10353 /* Get the contents of an inversion list into a string SV so that they can
10354 * be printed out. If 'traditional_style' is TRUE, it uses the format
10355 * traditionally done for debug tracing; otherwise it uses a format
10356 * suitable for just copying to the output, with blanks between ranges and
10357 * a dash between range components */
10361 const char intra_range_delimiter = (traditional_style ? '\t' : '-');
10362 const char inter_range_delimiter = (traditional_style ? '\n' : ' ');
10364 if (traditional_style) {
10365 output = newSVpvs("\n");
10368 output = newSVpvs("");
10371 PERL_ARGS_ASSERT_INVLIST_CONTENTS;
10373 assert(! invlist_is_iterating(invlist));
10375 invlist_iterinit(invlist);
10376 while (invlist_iternext(invlist, &start, &end)) {
10377 if (end == UV_MAX) {
10378 Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%cINFTY%c",
10379 start, intra_range_delimiter,
10380 inter_range_delimiter);
10382 else if (end != start) {
10383 Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c%04" UVXf "%c",
10385 intra_range_delimiter,
10386 end, inter_range_delimiter);
10389 Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c",
10390 start, inter_range_delimiter);
10394 if (SvCUR(output) && ! traditional_style) {/* Get rid of trailing blank */
10395 SvCUR_set(output, SvCUR(output) - 1);
10401 #ifndef PERL_IN_XSUB_RE
10403 Perl__invlist_dump(pTHX_ PerlIO *file, I32 level,
10404 const char * const indent, SV* const invlist)
10406 /* Designed to be called only by do_sv_dump(). Dumps out the ranges of the
10407 * inversion list 'invlist' to 'file' at 'level' Each line is prefixed by
10408 * the string 'indent'. The output looks like this:
10409 [0] 0x000A .. 0x000D
10411 [4] 0x2028 .. 0x2029
10412 [6] 0x3104 .. INFTY
10413 * This means that the first range of code points matched by the list are
10414 * 0xA through 0xD; the second range contains only the single code point
10415 * 0x85, etc. An inversion list is an array of UVs. Two array elements
10416 * are used to define each range (except if the final range extends to
10417 * infinity, only a single element is needed). The array index of the
10418 * first element for the corresponding range is given in brackets. */
10423 PERL_ARGS_ASSERT__INVLIST_DUMP;
10425 if (invlist_is_iterating(invlist)) {
10426 Perl_dump_indent(aTHX_ level, file,
10427 "%sCan't dump inversion list because is in middle of iterating\n",
10432 invlist_iterinit(invlist);
10433 while (invlist_iternext(invlist, &start, &end)) {
10434 if (end == UV_MAX) {
10435 Perl_dump_indent(aTHX_ level, file,
10436 "%s[%" UVuf "] 0x%04" UVXf " .. INFTY\n",
10437 indent, (UV)count, start);
10439 else if (end != start) {
10440 Perl_dump_indent(aTHX_ level, file,
10441 "%s[%" UVuf "] 0x%04" UVXf " .. 0x%04" UVXf "\n",
10442 indent, (UV)count, start, end);
10445 Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf "\n",
10446 indent, (UV)count, start);
10454 #if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE)
10456 Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b)
10458 /* Return a boolean as to if the two passed in inversion lists are
10459 * identical. The final argument, if TRUE, says to take the complement of
10460 * the second inversion list before doing the comparison */
10462 const UV len_a = _invlist_len(a);
10463 UV len_b = _invlist_len(b);
10465 const UV* array_a = NULL;
10466 const UV* array_b = NULL;
10468 PERL_ARGS_ASSERT__INVLISTEQ;
10470 /* This code avoids accessing the arrays unless it knows the length is
10475 return ! complement_b;
10479 array_a = invlist_array(a);
10483 array_b = invlist_array(b);
10486 /* If are to compare 'a' with the complement of b, set it
10487 * up so are looking at b's complement. */
10488 if (complement_b) {
10490 /* The complement of nothing is everything, so <a> would have to have
10491 * just one element, starting at zero (ending at infinity) */
10493 return (len_a == 1 && array_a[0] == 0);
10495 if (array_b[0] == 0) {
10497 /* Otherwise, to complement, we invert. Here, the first element is
10498 * 0, just remove it. To do this, we just pretend the array starts
10506 /* But if the first element is not zero, we pretend the list starts
10507 * at the 0 that is always stored immediately before the array. */
10513 return len_a == len_b
10514 && memEQ(array_a, array_b, len_a * sizeof(array_a[0]));
10520 * As best we can, determine the characters that can match the start of
10521 * the given EXACTF-ish node. This is for use in creating ssc nodes, so there
10522 * can be false positive matches
10524 * Returns the invlist as a new SV*; it is the caller's responsibility to
10525 * call SvREFCNT_dec() when done with it.
10528 S__make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node)
10531 const U8 * s = (U8*)STRING(node);
10532 SSize_t bytelen = STR_LEN(node);
10534 /* Start out big enough for 2 separate code points */
10535 SV* invlist = _new_invlist(4);
10537 PERL_ARGS_ASSERT__MAKE_EXACTF_INVLIST;
10542 /* We punt and assume can match anything if the node begins
10543 * with a multi-character fold. Things are complicated. For
10544 * example, /ffi/i could match any of:
10545 * "\N{LATIN SMALL LIGATURE FFI}"
10546 * "\N{LATIN SMALL LIGATURE FF}I"
10547 * "F\N{LATIN SMALL LIGATURE FI}"
10548 * plus several other things; and making sure we have all the
10549 * possibilities is hard. */
10550 if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) {
10551 invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10554 /* Any Latin1 range character can potentially match any
10555 * other depending on the locale, and in Turkic locales, U+130 and
10557 if (OP(node) == EXACTFL) {
10558 _invlist_union(invlist, PL_Latin1, &invlist);
10559 invlist = add_cp_to_invlist(invlist,
10560 LATIN_SMALL_LETTER_DOTLESS_I);
10561 invlist = add_cp_to_invlist(invlist,
10562 LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10565 /* But otherwise, it matches at least itself. We can
10566 * quickly tell if it has a distinct fold, and if so,
10567 * it matches that as well */
10568 invlist = add_cp_to_invlist(invlist, uc);
10569 if (IS_IN_SOME_FOLD_L1(uc))
10570 invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]);
10573 /* Some characters match above-Latin1 ones under /i. This
10574 * is true of EXACTFL ones when the locale is UTF-8 */
10575 if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc)
10576 && (! isASCII(uc) || (OP(node) != EXACTFAA
10577 && OP(node) != EXACTFAA_NO_TRIE)))
10579 add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist);
10583 else { /* Pattern is UTF-8 */
10584 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
10585 const U8* e = s + bytelen;
10588 fc = uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
10590 /* The only code points that aren't folded in a UTF EXACTFish
10591 * node are are the problematic ones in EXACTFL nodes */
10592 if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) {
10593 /* We need to check for the possibility that this EXACTFL
10594 * node begins with a multi-char fold. Therefore we fold
10595 * the first few characters of it so that we can make that
10601 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) {
10603 *(d++) = (U8) toFOLD(*s);
10604 if (fc < 0) { /* Save the first fold */
10611 UV fold = toFOLD_utf8_safe(s, e, d, &len);
10612 if (fc < 0) { /* Save the first fold */
10620 /* And set up so the code below that looks in this folded
10621 * buffer instead of the node's string */
10626 /* When we reach here 's' points to the fold of the first
10627 * character(s) of the node; and 'e' points to far enough along
10628 * the folded string to be just past any possible multi-char
10631 * Unlike the non-UTF-8 case, the macro for determining if a
10632 * string is a multi-char fold requires all the characters to
10633 * already be folded. This is because of all the complications
10634 * if not. Note that they are folded anyway, except in EXACTFL
10635 * nodes. Like the non-UTF case above, we punt if the node
10636 * begins with a multi-char fold */
10638 if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) {
10639 invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10641 else { /* Single char fold */
10643 unsigned int first_fold;
10644 const unsigned int * remaining_folds;
10645 Size_t folds_count;
10647 /* It matches itself */
10648 invlist = add_cp_to_invlist(invlist, fc);
10650 /* ... plus all the things that fold to it, which are found in
10651 * PL_utf8_foldclosures */
10652 folds_count = _inverse_folds(fc, &first_fold,
10654 for (k = 0; k < folds_count; k++) {
10655 UV c = (k == 0) ? first_fold : remaining_folds[k-1];
10657 /* /aa doesn't allow folds between ASCII and non- */
10658 if ( (OP(node) == EXACTFAA || OP(node) == EXACTFAA_NO_TRIE)
10659 && isASCII(c) != isASCII(fc))
10664 invlist = add_cp_to_invlist(invlist, c);
10667 if (OP(node) == EXACTFL) {
10669 /* If either [iI] are present in an EXACTFL node the above code
10670 * should have added its normal case pair, but under a Turkish
10671 * locale they could match instead the case pairs from it. Add
10672 * those as potential matches as well */
10673 if (isALPHA_FOLD_EQ(fc, 'I')) {
10674 invlist = add_cp_to_invlist(invlist,
10675 LATIN_SMALL_LETTER_DOTLESS_I);
10676 invlist = add_cp_to_invlist(invlist,
10677 LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10679 else if (fc == LATIN_SMALL_LETTER_DOTLESS_I) {
10680 invlist = add_cp_to_invlist(invlist, 'I');
10682 else if (fc == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) {
10683 invlist = add_cp_to_invlist(invlist, 'i');
10692 #undef HEADER_LENGTH
10693 #undef TO_INTERNAL_SIZE
10694 #undef FROM_INTERNAL_SIZE
10695 #undef INVLIST_VERSION_ID
10697 /* End of inversion list object */
10700 S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state)
10702 /* This parses the flags that are in either the '(?foo)' or '(?foo:bar)'
10703 * constructs, and updates RExC_flags with them. On input, RExC_parse
10704 * should point to the first flag; it is updated on output to point to the
10705 * final ')' or ':'. There needs to be at least one flag, or this will
10708 /* for (?g), (?gc), and (?o) warnings; warning
10709 about (?c) will warn about (?g) -- japhy */
10711 #define WASTED_O 0x01
10712 #define WASTED_G 0x02
10713 #define WASTED_C 0x04
10714 #define WASTED_GC (WASTED_G|WASTED_C)
10715 I32 wastedflags = 0x00;
10716 U32 posflags = 0, negflags = 0;
10717 U32 *flagsp = &posflags;
10718 char has_charset_modifier = '\0';
10720 bool has_use_defaults = FALSE;
10721 const char* const seqstart = RExC_parse - 1; /* Point to the '?' */
10722 int x_mod_count = 0;
10724 PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS;
10726 /* '^' as an initial flag sets certain defaults */
10727 if (UCHARAT(RExC_parse) == '^') {
10729 has_use_defaults = TRUE;
10730 STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
10731 cs = (RExC_uni_semantics)
10732 ? REGEX_UNICODE_CHARSET
10733 : REGEX_DEPENDS_CHARSET;
10734 set_regex_charset(&RExC_flags, cs);
10737 cs = get_regex_charset(RExC_flags);
10738 if ( cs == REGEX_DEPENDS_CHARSET
10739 && RExC_uni_semantics)
10741 cs = REGEX_UNICODE_CHARSET;
10745 while (RExC_parse < RExC_end) {
10746 /* && strchr("iogcmsx", *RExC_parse) */
10747 /* (?g), (?gc) and (?o) are useless here
10748 and must be globally applied -- japhy */
10749 switch (*RExC_parse) {
10751 /* Code for the imsxn flags */
10752 CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count);
10754 case LOCALE_PAT_MOD:
10755 if (has_charset_modifier) {
10756 goto excess_modifier;
10758 else if (flagsp == &negflags) {
10761 cs = REGEX_LOCALE_CHARSET;
10762 has_charset_modifier = LOCALE_PAT_MOD;
10764 case UNICODE_PAT_MOD:
10765 if (has_charset_modifier) {
10766 goto excess_modifier;
10768 else if (flagsp == &negflags) {
10771 cs = REGEX_UNICODE_CHARSET;
10772 has_charset_modifier = UNICODE_PAT_MOD;
10774 case ASCII_RESTRICT_PAT_MOD:
10775 if (flagsp == &negflags) {
10778 if (has_charset_modifier) {
10779 if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
10780 goto excess_modifier;
10782 /* Doubled modifier implies more restricted */
10783 cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
10786 cs = REGEX_ASCII_RESTRICTED_CHARSET;
10788 has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
10790 case DEPENDS_PAT_MOD:
10791 if (has_use_defaults) {
10792 goto fail_modifiers;
10794 else if (flagsp == &negflags) {
10797 else if (has_charset_modifier) {
10798 goto excess_modifier;
10801 /* The dual charset means unicode semantics if the
10802 * pattern (or target, not known until runtime) are
10803 * utf8, or something in the pattern indicates unicode
10805 cs = (RExC_uni_semantics)
10806 ? REGEX_UNICODE_CHARSET
10807 : REGEX_DEPENDS_CHARSET;
10808 has_charset_modifier = DEPENDS_PAT_MOD;
10812 if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
10813 vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
10815 else if (has_charset_modifier == *(RExC_parse - 1)) {
10816 vFAIL2("Regexp modifier \"%c\" may not appear twice",
10817 *(RExC_parse - 1));
10820 vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
10822 NOT_REACHED; /*NOTREACHED*/
10825 vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"",
10826 *(RExC_parse - 1));
10827 NOT_REACHED; /*NOTREACHED*/
10828 case ONCE_PAT_MOD: /* 'o' */
10829 case GLOBAL_PAT_MOD: /* 'g' */
10830 if (ckWARN(WARN_REGEXP)) {
10831 const I32 wflagbit = *RExC_parse == 'o'
10834 if (! (wastedflags & wflagbit) ) {
10835 wastedflags |= wflagbit;
10836 /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10839 "Useless (%s%c) - %suse /%c modifier",
10840 flagsp == &negflags ? "?-" : "?",
10842 flagsp == &negflags ? "don't " : "",
10849 case CONTINUE_PAT_MOD: /* 'c' */
10850 if (ckWARN(WARN_REGEXP)) {
10851 if (! (wastedflags & WASTED_C) ) {
10852 wastedflags |= WASTED_GC;
10853 /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10856 "Useless (%sc) - %suse /gc modifier",
10857 flagsp == &negflags ? "?-" : "?",
10858 flagsp == &negflags ? "don't " : ""
10863 case KEEPCOPY_PAT_MOD: /* 'p' */
10864 if (flagsp == &negflags) {
10865 ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
10867 *flagsp |= RXf_PMf_KEEPCOPY;
10871 /* A flag is a default iff it is following a minus, so
10872 * if there is a minus, it means will be trying to
10873 * re-specify a default which is an error */
10874 if (has_use_defaults || flagsp == &negflags) {
10875 goto fail_modifiers;
10877 flagsp = &negflags;
10878 wastedflags = 0; /* reset so (?g-c) warns twice */
10884 if ((posflags & (RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE)) == RXf_PMf_EXTENDED) {
10885 negflags |= RXf_PMf_EXTENDED_MORE;
10887 RExC_flags |= posflags;
10889 if (negflags & RXf_PMf_EXTENDED) {
10890 negflags |= RXf_PMf_EXTENDED_MORE;
10892 RExC_flags &= ~negflags;
10893 set_regex_charset(&RExC_flags, cs);
10898 RExC_parse += SKIP_IF_CHAR(RExC_parse);
10899 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
10900 vFAIL2utf8f("Sequence (%" UTF8f "...) not recognized",
10901 UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
10902 NOT_REACHED; /*NOTREACHED*/
10905 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10908 vFAIL("Sequence (?... not terminated");
10912 - reg - regular expression, i.e. main body or parenthesized thing
10914 * Caller must absorb opening parenthesis.
10916 * Combining parenthesis handling with the base level of regular expression
10917 * is a trifle forced, but the need to tie the tails of the branches to what
10918 * follows makes it hard to avoid.
10920 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
10922 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
10924 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
10927 PERL_STATIC_INLINE regnode_offset
10928 S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state,
10930 char * parse_start,
10934 regnode_offset ret;
10935 char* name_start = RExC_parse;
10937 SV *sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
10938 GET_RE_DEBUG_FLAGS_DECL;
10940 PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF;
10942 if (RExC_parse == name_start || *RExC_parse != ch) {
10943 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
10944 vFAIL2("Sequence %.3s... not terminated", parse_start);
10948 num = add_data( pRExC_state, STR_WITH_LEN("S"));
10949 RExC_rxi->data->data[num]=(void*)sv_dat;
10950 SvREFCNT_inc_simple_void_NN(sv_dat);
10953 ret = reganode(pRExC_state,
10956 : (ASCII_FOLD_RESTRICTED)
10958 : (AT_LEAST_UNI_SEMANTICS)
10964 *flagp |= HASWIDTH;
10966 Set_Node_Offset(REGNODE_p(ret), parse_start+1);
10967 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
10969 nextchar(pRExC_state);
10973 /* On success, returns the offset at which any next node should be placed into
10974 * the regex engine program being compiled.
10976 * Returns 0 otherwise, with *flagp set to indicate why:
10977 * TRYAGAIN at the end of (?) that only sets flags.
10978 * RESTART_PARSE if the parse needs to be restarted, or'd with
10979 * NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
10980 * Otherwise would only return 0 if regbranch() returns 0, which cannot
10982 STATIC regnode_offset
10983 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp, U32 depth)
10984 /* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter.
10985 * 2 is like 1, but indicates that nextchar() has been called to advance
10986 * RExC_parse beyond the '('. Things like '(?' are indivisible tokens, and
10987 * this flag alerts us to the need to check for that */
10989 regnode_offset ret = 0; /* Will be the head of the group. */
10991 regnode_offset lastbr;
10992 regnode_offset ender = 0;
10995 U32 oregflags = RExC_flags;
10996 bool have_branch = 0;
10998 I32 freeze_paren = 0;
10999 I32 after_freeze = 0;
11000 I32 num; /* numeric backreferences */
11002 char * parse_start = RExC_parse; /* MJD */
11003 char * const oregcomp_parse = RExC_parse;
11005 GET_RE_DEBUG_FLAGS_DECL;
11007 PERL_ARGS_ASSERT_REG;
11008 DEBUG_PARSE("reg ");
11010 *flagp = 0; /* Tentatively. */
11012 /* Having this true makes it feasible to have a lot fewer tests for the
11013 * parse pointer being in scope. For example, we can write
11014 * while(isFOO(*RExC_parse)) RExC_parse++;
11016 * while(RExC_parse < RExC_end && isFOO(*RExC_parse)) RExC_parse++;
11018 assert(*RExC_end == '\0');
11020 /* Make an OPEN node, if parenthesized. */
11023 /* Under /x, space and comments can be gobbled up between the '(' and
11024 * here (if paren ==2). The forms '(*VERB' and '(?...' disallow such
11025 * intervening space, as the sequence is a token, and a token should be
11027 bool has_intervening_patws = (paren == 2)
11028 && *(RExC_parse - 1) != '(';
11030 if (RExC_parse >= RExC_end) {
11031 vFAIL("Unmatched (");
11034 if (paren == 'r') { /* Atomic script run */
11038 else if ( *RExC_parse == '*') { /* (*VERB:ARG), (*construct:...) */
11039 char *start_verb = RExC_parse + 1;
11041 char *start_arg = NULL;
11042 unsigned char op = 0;
11043 int arg_required = 0;
11044 int internal_argval = -1; /* if >-1 we are not allowed an argument*/
11045 bool has_upper = FALSE;
11047 if (has_intervening_patws) {
11048 RExC_parse++; /* past the '*' */
11050 /* For strict backwards compatibility, don't change the message
11051 * now that we also have lowercase operands */
11052 if (isUPPER(*RExC_parse)) {
11053 vFAIL("In '(*VERB...)', the '(' and '*' must be adjacent");
11056 vFAIL("In '(*...)', the '(' and '*' must be adjacent");
11059 while (RExC_parse < RExC_end && *RExC_parse != ')' ) {
11060 if ( *RExC_parse == ':' ) {
11061 start_arg = RExC_parse + 1;
11065 if (isUPPER(*RExC_parse)) {
11071 RExC_parse += UTF8SKIP(RExC_parse);
11074 verb_len = RExC_parse - start_verb;
11076 if (RExC_parse >= RExC_end) {
11077 goto unterminated_verb_pattern;
11080 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11081 while ( RExC_parse < RExC_end && *RExC_parse != ')' ) {
11082 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11084 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
11085 unterminated_verb_pattern:
11087 vFAIL("Unterminated verb pattern argument");
11090 vFAIL("Unterminated '(*...' argument");
11094 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
11096 vFAIL("Unterminated verb pattern");
11099 vFAIL("Unterminated '(*...' construct");
11104 /* Here, we know that RExC_parse < RExC_end */
11106 switch ( *start_verb ) {
11107 case 'A': /* (*ACCEPT) */
11108 if ( memEQs(start_verb, verb_len,"ACCEPT") ) {
11110 internal_argval = RExC_nestroot;
11113 case 'C': /* (*COMMIT) */
11114 if ( memEQs(start_verb, verb_len,"COMMIT") )
11117 case 'F': /* (*FAIL) */
11118 if ( verb_len==1 || memEQs(start_verb, verb_len,"FAIL") ) {
11122 case ':': /* (*:NAME) */
11123 case 'M': /* (*MARK:NAME) */
11124 if ( verb_len==0 || memEQs(start_verb, verb_len,"MARK") ) {
11129 case 'P': /* (*PRUNE) */
11130 if ( memEQs(start_verb, verb_len,"PRUNE") )
11133 case 'S': /* (*SKIP) */
11134 if ( memEQs(start_verb, verb_len,"SKIP") )
11137 case 'T': /* (*THEN) */
11138 /* [19:06] <TimToady> :: is then */
11139 if ( memEQs(start_verb, verb_len,"THEN") ) {
11141 RExC_seen |= REG_CUTGROUP_SEEN;
11145 if ( memEQs(start_verb, verb_len, "asr")
11146 || memEQs(start_verb, verb_len, "atomic_script_run"))
11148 paren = 'r'; /* Mnemonic: recursed run */
11151 else if (memEQs(start_verb, verb_len, "atomic")) {
11152 paren = 't'; /* AtOMIC */
11153 goto alpha_assertions;
11157 if ( memEQs(start_verb, verb_len, "plb")
11158 || memEQs(start_verb, verb_len, "positive_lookbehind"))
11161 goto lookbehind_alpha_assertions;
11163 else if ( memEQs(start_verb, verb_len, "pla")
11164 || memEQs(start_verb, verb_len, "positive_lookahead"))
11167 goto alpha_assertions;
11171 if ( memEQs(start_verb, verb_len, "nlb")
11172 || memEQs(start_verb, verb_len, "negative_lookbehind"))
11175 goto lookbehind_alpha_assertions;
11177 else if ( memEQs(start_verb, verb_len, "nla")
11178 || memEQs(start_verb, verb_len, "negative_lookahead"))
11181 goto alpha_assertions;
11185 if ( memEQs(start_verb, verb_len, "sr")
11186 || memEQs(start_verb, verb_len, "script_run"))
11188 regnode_offset atomic;
11194 /* This indicates Unicode rules. */
11195 REQUIRE_UNI_RULES(flagp, 0);
11201 RExC_parse = start_arg;
11203 if (RExC_in_script_run) {
11205 /* Nested script runs are treated as no-ops, because
11206 * if the nested one fails, the outer one must as
11207 * well. It could fail sooner, and avoid (??{} with
11208 * side effects, but that is explicitly documented as
11209 * undefined behavior. */
11213 if (paren == 's') {
11218 /* But, the atomic part of a nested atomic script run
11219 * isn't a no-op, but can be treated just like a '(?>'
11225 /* By doing this here, we avoid extra warnings for nested
11227 ckWARNexperimental(RExC_parse,
11228 WARN_EXPERIMENTAL__SCRIPT_RUN,
11229 "The script_run feature is experimental");
11231 if (paren == 's') {
11232 /* Here, we're starting a new regular script run */
11233 ret = reg_node(pRExC_state, SROPEN);
11234 RExC_in_script_run = 1;
11239 /* Here, we are starting an atomic script run. This is
11240 * handled by recursing to deal with the atomic portion
11241 * separately, enclosed in SROPEN ... SRCLOSE nodes */
11243 ret = reg_node(pRExC_state, SROPEN);
11245 RExC_in_script_run = 1;
11247 atomic = reg(pRExC_state, 'r', &flags, depth);
11248 if (flags & (RESTART_PARSE|NEED_UTF8)) {
11249 *flagp = flags & (RESTART_PARSE|NEED_UTF8);
11253 REGTAIL(pRExC_state, ret, atomic);
11255 REGTAIL(pRExC_state, atomic,
11256 reg_node(pRExC_state, SRCLOSE));
11258 RExC_in_script_run = 0;
11264 lookbehind_alpha_assertions:
11265 RExC_seen |= REG_LOOKBEHIND_SEEN;
11266 RExC_in_lookbehind++;
11270 ckWARNexperimental(RExC_parse,
11271 WARN_EXPERIMENTAL__ALPHA_ASSERTIONS,
11272 "The alpha_assertions feature is experimental");
11274 RExC_seen_zerolen++;
11280 /* An empty negative lookahead assertion simply is failure */
11281 if (paren == 'A' && RExC_parse == start_arg) {
11282 ret=reganode(pRExC_state, OPFAIL, 0);
11283 nextchar(pRExC_state);
11287 RExC_parse = start_arg;
11292 "'(*%" UTF8f "' requires a terminating ':'",
11293 UTF8fARG(UTF, verb_len, start_verb));
11294 NOT_REACHED; /*NOTREACHED*/
11296 } /* End of switch */
11298 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11299 if (has_upper || verb_len == 0) {
11301 "Unknown verb pattern '%" UTF8f "'",
11302 UTF8fARG(UTF, verb_len, start_verb));
11306 "Unknown '(*...)' construct '%" UTF8f "'",
11307 UTF8fARG(UTF, verb_len, start_verb));
11310 if ( RExC_parse == start_arg ) {
11313 if ( arg_required && !start_arg ) {
11314 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
11315 verb_len, start_verb);
11317 if (internal_argval == -1) {
11318 ret = reganode(pRExC_state, op, 0);
11320 ret = reg2Lanode(pRExC_state, op, 0, internal_argval);
11322 RExC_seen |= REG_VERBARG_SEEN;
11324 SV *sv = newSVpvn( start_arg,
11325 RExC_parse - start_arg);
11326 ARG(REGNODE_p(ret)) = add_data( pRExC_state,
11327 STR_WITH_LEN("S"));
11328 RExC_rxi->data->data[ARG(REGNODE_p(ret))]=(void*)sv;
11329 FLAGS(REGNODE_p(ret)) = 1;
11331 FLAGS(REGNODE_p(ret)) = 0;
11333 if ( internal_argval != -1 )
11334 ARG2L_SET(REGNODE_p(ret), internal_argval);
11335 nextchar(pRExC_state);
11338 else if (*RExC_parse == '?') { /* (?...) */
11339 bool is_logical = 0;
11340 const char * const seqstart = RExC_parse;
11341 const char * endptr;
11342 if (has_intervening_patws) {
11344 vFAIL("In '(?...)', the '(' and '?' must be adjacent");
11347 RExC_parse++; /* past the '?' */
11348 paren = *RExC_parse; /* might be a trailing NUL, if not
11350 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11351 if (RExC_parse > RExC_end) {
11354 ret = 0; /* For look-ahead/behind. */
11357 case 'P': /* (?P...) variants for those used to PCRE/Python */
11358 paren = *RExC_parse;
11359 if ( paren == '<') { /* (?P<...>) named capture */
11361 if (RExC_parse >= RExC_end) {
11362 vFAIL("Sequence (?P<... not terminated");
11364 goto named_capture;
11366 else if (paren == '>') { /* (?P>name) named recursion */
11368 if (RExC_parse >= RExC_end) {
11369 vFAIL("Sequence (?P>... not terminated");
11371 goto named_recursion;
11373 else if (paren == '=') { /* (?P=...) named backref */
11375 return handle_named_backref(pRExC_state, flagp,
11378 RExC_parse += SKIP_IF_CHAR(RExC_parse);
11379 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11380 vFAIL3("Sequence (%.*s...) not recognized",
11381 RExC_parse-seqstart, seqstart);
11382 NOT_REACHED; /*NOTREACHED*/
11383 case '<': /* (?<...) */
11384 if (*RExC_parse == '!')
11386 else if (*RExC_parse != '=')
11393 case '\'': /* (?'...') */
11394 name_start = RExC_parse;
11395 svname = reg_scan_name(pRExC_state, REG_RSN_RETURN_NAME);
11396 if ( RExC_parse == name_start
11397 || RExC_parse >= RExC_end
11398 || *RExC_parse != paren)
11400 vFAIL2("Sequence (?%c... not terminated",
11401 paren=='>' ? '<' : paren);
11406 if (!svname) /* shouldn't happen */
11408 "panic: reg_scan_name returned NULL");
11409 if (!RExC_paren_names) {
11410 RExC_paren_names= newHV();
11411 sv_2mortal(MUTABLE_SV(RExC_paren_names));
11413 RExC_paren_name_list= newAV();
11414 sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
11417 he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
11419 sv_dat = HeVAL(he_str);
11421 /* croak baby croak */
11423 "panic: paren_name hash element allocation failed");
11424 } else if ( SvPOK(sv_dat) ) {
11425 /* (?|...) can mean we have dupes so scan to check
11426 its already been stored. Maybe a flag indicating
11427 we are inside such a construct would be useful,
11428 but the arrays are likely to be quite small, so
11429 for now we punt -- dmq */
11430 IV count = SvIV(sv_dat);
11431 I32 *pv = (I32*)SvPVX(sv_dat);
11433 for ( i = 0 ; i < count ; i++ ) {
11434 if ( pv[i] == RExC_npar ) {
11440 pv = (I32*)SvGROW(sv_dat,
11441 SvCUR(sv_dat) + sizeof(I32)+1);
11442 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
11443 pv[count] = RExC_npar;
11444 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
11447 (void)SvUPGRADE(sv_dat, SVt_PVNV);
11448 sv_setpvn(sv_dat, (char *)&(RExC_npar),
11451 SvIV_set(sv_dat, 1);
11454 /* Yes this does cause a memory leak in debugging Perls
11456 if (!av_store(RExC_paren_name_list,
11457 RExC_npar, SvREFCNT_inc_NN(svname)))
11458 SvREFCNT_dec_NN(svname);
11461 /*sv_dump(sv_dat);*/
11463 nextchar(pRExC_state);
11465 goto capturing_parens;
11468 RExC_seen |= REG_LOOKBEHIND_SEEN;
11469 RExC_in_lookbehind++;
11471 if (RExC_parse >= RExC_end) {
11472 vFAIL("Sequence (?... not terminated");
11476 case '=': /* (?=...) */
11477 RExC_seen_zerolen++;
11479 case '!': /* (?!...) */
11480 RExC_seen_zerolen++;
11481 /* check if we're really just a "FAIL" assertion */
11482 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
11483 FALSE /* Don't force to /x */ );
11484 if (*RExC_parse == ')') {
11485 ret=reganode(pRExC_state, OPFAIL, 0);
11486 nextchar(pRExC_state);
11490 case '|': /* (?|...) */
11491 /* branch reset, behave like a (?:...) except that
11492 buffers in alternations share the same numbers */
11494 after_freeze = freeze_paren = RExC_npar;
11496 /* XXX This construct currently requires an extra pass.
11497 * Investigation would be required to see if that could be
11499 REQUIRE_PARENS_PASS;
11501 case ':': /* (?:...) */
11502 case '>': /* (?>...) */
11504 case '$': /* (?$...) */
11505 case '@': /* (?@...) */
11506 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
11508 case '0' : /* (?0) */
11509 case 'R' : /* (?R) */
11510 if (RExC_parse == RExC_end || *RExC_parse != ')')
11511 FAIL("Sequence (?R) not terminated");
11513 RExC_seen |= REG_RECURSE_SEEN;
11515 /* XXX These constructs currently require an extra pass.
11516 * It probably could be changed */
11517 REQUIRE_PARENS_PASS;
11519 *flagp |= POSTPONED;
11520 goto gen_recurse_regop;
11522 /* named and numeric backreferences */
11523 case '&': /* (?&NAME) */
11524 parse_start = RExC_parse - 1;
11527 SV *sv_dat = reg_scan_name(pRExC_state,
11528 REG_RSN_RETURN_DATA);
11529 num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
11531 if (RExC_parse >= RExC_end || *RExC_parse != ')')
11532 vFAIL("Sequence (?&... not terminated");
11533 goto gen_recurse_regop;
11536 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
11538 vFAIL("Illegal pattern");
11540 goto parse_recursion;
11542 case '-': /* (?-1) */
11543 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
11544 RExC_parse--; /* rewind to let it be handled later */
11548 case '1': case '2': case '3': case '4': /* (?1) */
11549 case '5': case '6': case '7': case '8': case '9':
11550 RExC_parse = (char *) seqstart + 1; /* Point to the digit */
11553 bool is_neg = FALSE;
11555 parse_start = RExC_parse - 1; /* MJD */
11556 if (*RExC_parse == '-') {
11561 if (grok_atoUV(RExC_parse, &unum, &endptr)
11565 RExC_parse = (char*)endptr;
11569 /* Some limit for num? */
11573 if (*RExC_parse!=')')
11574 vFAIL("Expecting close bracket");
11577 if ( paren == '-' ) {
11579 Diagram of capture buffer numbering.
11580 Top line is the normal capture buffer numbers
11581 Bottom line is the negative indexing as from
11585 /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
11589 num = RExC_npar + num;
11592 /* It might be a forward reference; we can't fail until
11593 * we know, by completing the parse to get all the
11594 * groups, and then reparsing */
11595 if (RExC_total_parens > 0) {
11597 vFAIL("Reference to nonexistent group");
11600 REQUIRE_PARENS_PASS;
11603 } else if ( paren == '+' ) {
11604 num = RExC_npar + num - 1;
11606 /* We keep track how many GOSUB items we have produced.
11607 To start off the ARG2L() of the GOSUB holds its "id",
11608 which is used later in conjunction with RExC_recurse
11609 to calculate the offset we need to jump for the GOSUB,
11610 which it will store in the final representation.
11611 We have to defer the actual calculation until much later
11612 as the regop may move.
11615 ret = reg2Lanode(pRExC_state, GOSUB, num, RExC_recurse_count);
11616 if (num >= RExC_npar) {
11618 /* It might be a forward reference; we can't fail until we
11619 * know, by completing the parse to get all the groups, and
11620 * then reparsing */
11621 if (RExC_total_parens > 0) {
11622 if (num >= RExC_total_parens) {
11624 vFAIL("Reference to nonexistent group");
11628 REQUIRE_PARENS_PASS;
11631 RExC_recurse_count++;
11632 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11633 "%*s%*s Recurse #%" UVuf " to %" IVdf "\n",
11634 22, "| |", (int)(depth * 2 + 1), "",
11635 (UV)ARG(REGNODE_p(ret)),
11636 (IV)ARG2L(REGNODE_p(ret))));
11637 RExC_seen |= REG_RECURSE_SEEN;
11639 Set_Node_Length(REGNODE_p(ret),
11640 1 + regarglen[OP(REGNODE_p(ret))]); /* MJD */
11641 Set_Node_Offset(REGNODE_p(ret), parse_start); /* MJD */
11643 *flagp |= POSTPONED;
11644 assert(*RExC_parse == ')');
11645 nextchar(pRExC_state);
11650 case '?': /* (??...) */
11652 if (*RExC_parse != '{') {
11653 RExC_parse += SKIP_IF_CHAR(RExC_parse);
11654 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11656 "Sequence (%" UTF8f "...) not recognized",
11657 UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
11658 NOT_REACHED; /*NOTREACHED*/
11660 *flagp |= POSTPONED;
11664 case '{': /* (?{...}) */
11667 struct reg_code_block *cb;
11670 RExC_seen_zerolen++;
11672 if ( !pRExC_state->code_blocks
11673 || pRExC_state->code_index
11674 >= pRExC_state->code_blocks->count
11675 || pRExC_state->code_blocks->cb[pRExC_state->code_index].start
11676 != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
11679 if (RExC_pm_flags & PMf_USE_RE_EVAL)
11680 FAIL("panic: Sequence (?{...}): no code block found\n");
11681 FAIL("Eval-group not allowed at runtime, use re 'eval'");
11683 /* this is a pre-compiled code block (?{...}) */
11684 cb = &pRExC_state->code_blocks->cb[pRExC_state->code_index];
11685 RExC_parse = RExC_start + cb->end;
11687 if (cb->src_regex) {
11688 n = add_data(pRExC_state, STR_WITH_LEN("rl"));
11689 RExC_rxi->data->data[n] =
11690 (void*)SvREFCNT_inc((SV*)cb->src_regex);
11691 RExC_rxi->data->data[n+1] = (void*)o;
11694 n = add_data(pRExC_state,
11695 (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l", 1);
11696 RExC_rxi->data->data[n] = (void*)o;
11698 pRExC_state->code_index++;
11699 nextchar(pRExC_state);
11702 regnode_offset eval;
11703 ret = reg_node(pRExC_state, LOGICAL);
11705 eval = reg2Lanode(pRExC_state, EVAL,
11708 /* for later propagation into (??{})
11710 RExC_flags & RXf_PMf_COMPILETIME
11712 FLAGS(REGNODE_p(ret)) = 2;
11713 REGTAIL(pRExC_state, ret, eval);
11714 /* deal with the length of this later - MJD */
11717 ret = reg2Lanode(pRExC_state, EVAL, n, 0);
11718 Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1);
11719 Set_Node_Offset(REGNODE_p(ret), parse_start);
11722 case '(': /* (?(?{...})...) and (?(?=...)...) */
11725 const int DEFINE_len = sizeof("DEFINE") - 1;
11726 if ( RExC_parse < RExC_end - 1
11727 && ( ( RExC_parse[0] == '?' /* (?(?...)) */
11728 && ( RExC_parse[1] == '='
11729 || RExC_parse[1] == '!'
11730 || RExC_parse[1] == '<'
11731 || RExC_parse[1] == '{'))
11732 || ( RExC_parse[0] == '*' /* (?(*...)) */
11733 && ( memBEGINs(RExC_parse + 1,
11734 (Size_t) (RExC_end - (RExC_parse + 1)),
11736 || memBEGINs(RExC_parse + 1,
11737 (Size_t) (RExC_end - (RExC_parse + 1)),
11739 || memBEGINs(RExC_parse + 1,
11740 (Size_t) (RExC_end - (RExC_parse + 1)),
11742 || memBEGINs(RExC_parse + 1,
11743 (Size_t) (RExC_end - (RExC_parse + 1)),
11745 || memBEGINs(RExC_parse + 1,
11746 (Size_t) (RExC_end - (RExC_parse + 1)),
11747 "positive_lookahead:")
11748 || memBEGINs(RExC_parse + 1,
11749 (Size_t) (RExC_end - (RExC_parse + 1)),
11750 "positive_lookbehind:")
11751 || memBEGINs(RExC_parse + 1,
11752 (Size_t) (RExC_end - (RExC_parse + 1)),
11753 "negative_lookahead:")
11754 || memBEGINs(RExC_parse + 1,
11755 (Size_t) (RExC_end - (RExC_parse + 1)),
11756 "negative_lookbehind:"))))
11757 ) { /* Lookahead or eval. */
11759 regnode_offset tail;
11761 ret = reg_node(pRExC_state, LOGICAL);
11762 FLAGS(REGNODE_p(ret)) = 1;
11764 tail = reg(pRExC_state, 1, &flag, depth+1);
11765 RETURN_FAIL_ON_RESTART(flag, flagp);
11766 REGTAIL(pRExC_state, ret, tail);
11769 else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
11770 || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
11772 char ch = RExC_parse[0] == '<' ? '>' : '\'';
11773 char *name_start= RExC_parse++;
11775 SV *sv_dat=reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
11776 if ( RExC_parse == name_start
11777 || RExC_parse >= RExC_end
11778 || *RExC_parse != ch)
11780 vFAIL2("Sequence (?(%c... not terminated",
11781 (ch == '>' ? '<' : ch));
11785 num = add_data( pRExC_state, STR_WITH_LEN("S"));
11786 RExC_rxi->data->data[num]=(void*)sv_dat;
11787 SvREFCNT_inc_simple_void_NN(sv_dat);
11789 ret = reganode(pRExC_state, NGROUPP, num);
11790 goto insert_if_check_paren;
11792 else if (memBEGINs(RExC_parse,
11793 (STRLEN) (RExC_end - RExC_parse),
11796 ret = reganode(pRExC_state, DEFINEP, 0);
11797 RExC_parse += DEFINE_len;
11799 goto insert_if_check_paren;
11801 else if (RExC_parse[0] == 'R') {
11803 /* parno == 0 => /(?(R)YES|NO)/ "in any form of recursion OR eval"
11804 * parno == 1 => /(?(R0)YES|NO)/ "in GOSUB (?0) / (?R)"
11805 * parno == 2 => /(?(R1)YES|NO)/ "in GOSUB (?1) (parno-1)"
11808 if (RExC_parse[0] == '0') {
11812 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
11815 if (grok_atoUV(RExC_parse, &uv, &endptr)
11818 parno = (I32)uv + 1;
11819 RExC_parse = (char*)endptr;
11821 /* else "Switch condition not recognized" below */
11822 } else if (RExC_parse[0] == '&') {
11825 sv_dat = reg_scan_name(pRExC_state,
11826 REG_RSN_RETURN_DATA);
11828 parno = 1 + *((I32 *)SvPVX(sv_dat));
11830 ret = reganode(pRExC_state, INSUBP, parno);
11831 goto insert_if_check_paren;
11833 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
11838 if (grok_atoUV(RExC_parse, &uv, &endptr)
11842 RExC_parse = (char*)endptr;
11845 vFAIL("panic: grok_atoUV returned FALSE");
11847 ret = reganode(pRExC_state, GROUPP, parno);
11849 insert_if_check_paren:
11850 if (UCHARAT(RExC_parse) != ')') {
11851 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11852 vFAIL("Switch condition not recognized");
11854 nextchar(pRExC_state);
11856 REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
11857 br = regbranch(pRExC_state, &flags, 1, depth+1);
11859 RETURN_FAIL_ON_RESTART(flags,flagp);
11860 FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
11863 REGTAIL(pRExC_state, br, reganode(pRExC_state,
11865 c = UCHARAT(RExC_parse);
11866 nextchar(pRExC_state);
11867 if (flags&HASWIDTH)
11868 *flagp |= HASWIDTH;
11871 vFAIL("(?(DEFINE)....) does not allow branches");
11873 /* Fake one for optimizer. */
11874 lastbr = reganode(pRExC_state, IFTHEN, 0);
11876 if (!regbranch(pRExC_state, &flags, 1, depth+1)) {
11877 RETURN_FAIL_ON_RESTART(flags, flagp);
11878 FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
11881 REGTAIL(pRExC_state, ret, lastbr);
11882 if (flags&HASWIDTH)
11883 *flagp |= HASWIDTH;
11884 c = UCHARAT(RExC_parse);
11885 nextchar(pRExC_state);
11890 if (RExC_parse >= RExC_end)
11891 vFAIL("Switch (?(condition)... not terminated");
11893 vFAIL("Switch (?(condition)... contains too many branches");
11895 ender = reg_node(pRExC_state, TAIL);
11896 REGTAIL(pRExC_state, br, ender);
11898 REGTAIL(pRExC_state, lastbr, ender);
11899 REGTAIL(pRExC_state, REGNODE_OFFSET(
11901 NEXTOPER(REGNODE_p(lastbr)))),
11905 REGTAIL(pRExC_state, ret, ender);
11906 #if 0 /* Removing this doesn't cause failures in the test suite -- khw */
11907 RExC_size++; /* XXX WHY do we need this?!!
11908 For large programs it seems to be required
11909 but I can't figure out why. -- dmq*/
11913 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11914 vFAIL("Unknown switch condition (?(...))");
11916 case '[': /* (?[ ... ]) */
11917 return handle_regex_sets(pRExC_state, NULL, flagp, depth+1,
11919 case 0: /* A NUL */
11920 RExC_parse--; /* for vFAIL to print correctly */
11921 vFAIL("Sequence (? incomplete");
11923 default: /* e.g., (?i) */
11924 RExC_parse = (char *) seqstart + 1;
11926 parse_lparen_question_flags(pRExC_state);
11927 if (UCHARAT(RExC_parse) != ':') {
11928 if (RExC_parse < RExC_end)
11929 nextchar(pRExC_state);
11934 nextchar(pRExC_state);
11940 if (*RExC_parse == '{') {
11941 ckWARNregdep(RExC_parse + 1,
11942 "Unescaped left brace in regex is "
11943 "deprecated here (and will be fatal "
11944 "in Perl 5.32), passed through");
11946 /* Not bothering to indent here, as the above 'else' is temporary
11948 if (!(RExC_flags & RXf_PMf_NOCAPTURE)) { /* (...) */
11952 if (RExC_total_parens <= 0) {
11953 /* If we are in our first pass through (and maybe only pass),
11954 * we need to allocate memory for the capturing parentheses
11955 * data structures. Since we start at npar=1, when it reaches
11956 * 2, for the first time it has something to put in it. Above
11957 * 2 means we extend what we already have */
11958 if (RExC_npar == 2) {
11959 /* setup RExC_open_parens, which holds the address of each
11960 * OPEN tag, and to make things simpler for the 0 index the
11961 * start of the program - this is used later for offsets */
11962 Newxz(RExC_open_parens, RExC_npar, regnode_offset);
11963 RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */
11965 /* setup RExC_close_parens, which holds the address of each
11966 * CLOSE tag, and to make things simpler for the 0 index
11967 * the end of the program - this is used later for offsets
11969 Newxz(RExC_close_parens, RExC_npar, regnode_offset);
11970 /* we dont know where end op starts yet, so we dont need to
11971 * set RExC_close_parens[0] like we do RExC_open_parens[0]
11975 Renew(RExC_open_parens, RExC_npar, regnode_offset);
11976 Zero(RExC_open_parens + RExC_npar - 1, 1, regnode_offset);
11978 Renew(RExC_close_parens, RExC_npar, regnode_offset);
11979 Zero(RExC_close_parens + RExC_npar - 1, 1, regnode_offset);
11983 ret = reganode(pRExC_state, OPEN, parno);
11984 if (!RExC_nestroot)
11985 RExC_nestroot = parno;
11986 if (RExC_open_parens && !RExC_open_parens[parno])
11988 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11989 "%*s%*s Setting open paren #%" IVdf " to %d\n",
11990 22, "| |", (int)(depth * 2 + 1), "",
11992 RExC_open_parens[parno]= ret;
11995 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
11996 Set_Node_Offset(REGNODE_p(ret), RExC_parse); /* MJD */
11999 /* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */
12009 /* Pick up the branches, linking them together. */
12010 parse_start = RExC_parse; /* MJD */
12011 br = regbranch(pRExC_state, &flags, 1, depth+1);
12013 /* branch_len = (paren != 0); */
12016 RETURN_FAIL_ON_RESTART(flags, flagp);
12017 FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12019 if (*RExC_parse == '|') {
12020 if (RExC_use_BRANCHJ) {
12021 reginsert(pRExC_state, BRANCHJ, br, depth+1);
12024 reginsert(pRExC_state, BRANCH, br, depth+1);
12025 Set_Node_Length(REGNODE_p(br), paren != 0);
12026 Set_Node_Offset_To_R(br, parse_start-RExC_start);
12030 else if (paren == ':') {
12031 *flagp |= flags&SIMPLE;
12033 if (is_open) { /* Starts with OPEN. */
12034 REGTAIL(pRExC_state, ret, br); /* OPEN -> first. */
12036 else if (paren != '?') /* Not Conditional */
12038 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
12040 while (*RExC_parse == '|') {
12041 if (RExC_use_BRANCHJ) {
12042 ender = reganode(pRExC_state, LONGJMP, 0);
12044 /* Append to the previous. */
12045 REGTAIL(pRExC_state,
12046 REGNODE_OFFSET(NEXTOPER(NEXTOPER(REGNODE_p(lastbr)))),
12049 nextchar(pRExC_state);
12050 if (freeze_paren) {
12051 if (RExC_npar > after_freeze)
12052 after_freeze = RExC_npar;
12053 RExC_npar = freeze_paren;
12055 br = regbranch(pRExC_state, &flags, 0, depth+1);
12058 RETURN_FAIL_ON_RESTART(flags, flagp);
12059 FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12061 REGTAIL(pRExC_state, lastbr, br); /* BRANCH -> BRANCH. */
12063 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
12066 if (have_branch || paren != ':') {
12069 /* Make a closing node, and hook it on the end. */
12072 ender = reg_node(pRExC_state, TAIL);
12075 ender = reganode(pRExC_state, CLOSE, parno);
12076 if ( RExC_close_parens ) {
12077 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12078 "%*s%*s Setting close paren #%" IVdf " to %d\n",
12079 22, "| |", (int)(depth * 2 + 1), "",
12080 (IV)parno, ender));
12081 RExC_close_parens[parno]= ender;
12082 if (RExC_nestroot == parno)
12085 Set_Node_Offset(REGNODE_p(ender), RExC_parse+1); /* MJD */
12086 Set_Node_Length(REGNODE_p(ender), 1); /* MJD */
12089 ender = reg_node(pRExC_state, SRCLOSE);
12090 RExC_in_script_run = 0;
12100 *flagp &= ~HASWIDTH;
12102 case 't': /* aTomic */
12104 ender = reg_node(pRExC_state, SUCCEED);
12107 ender = reg_node(pRExC_state, END);
12108 assert(!RExC_end_op); /* there can only be one! */
12109 RExC_end_op = REGNODE_p(ender);
12110 if (RExC_close_parens) {
12111 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12112 "%*s%*s Setting close paren #0 (END) to %d\n",
12113 22, "| |", (int)(depth * 2 + 1), "",
12116 RExC_close_parens[0]= ender;
12121 DEBUG_PARSE_MSG("lsbr");
12122 regprop(RExC_rx, RExC_mysv1, REGNODE_p(lastbr), NULL, pRExC_state);
12123 regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender), NULL, pRExC_state);
12124 Perl_re_printf( aTHX_ "~ tying lastbr %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12125 SvPV_nolen_const(RExC_mysv1),
12127 SvPV_nolen_const(RExC_mysv2),
12129 (IV)(ender - lastbr)
12132 REGTAIL(pRExC_state, lastbr, ender);
12135 char is_nothing= 1;
12137 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
12139 /* Hook the tails of the branches to the closing node. */
12140 for (br = REGNODE_p(ret); br; br = regnext(br)) {
12141 const U8 op = PL_regkind[OP(br)];
12142 if (op == BRANCH) {
12143 REGTAIL_STUDY(pRExC_state,
12144 REGNODE_OFFSET(NEXTOPER(br)),
12146 if ( OP(NEXTOPER(br)) != NOTHING
12147 || regnext(NEXTOPER(br)) != REGNODE_p(ender))
12150 else if (op == BRANCHJ) {
12151 REGTAIL_STUDY(pRExC_state,
12152 REGNODE_OFFSET(NEXTOPER(NEXTOPER(br))),
12154 /* for now we always disable this optimisation * /
12155 if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING
12156 || regnext(NEXTOPER(NEXTOPER(br))) != REGNODE_p(ender))
12162 regnode * ret_as_regnode = REGNODE_p(ret);
12163 br= PL_regkind[OP(ret_as_regnode)] != BRANCH
12164 ? regnext(ret_as_regnode)
12167 DEBUG_PARSE_MSG("NADA");
12168 regprop(RExC_rx, RExC_mysv1, ret_as_regnode,
12169 NULL, pRExC_state);
12170 regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender),
12171 NULL, pRExC_state);
12172 Perl_re_printf( aTHX_ "~ converting ret %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12173 SvPV_nolen_const(RExC_mysv1),
12174 (IV)REG_NODE_NUM(ret_as_regnode),
12175 SvPV_nolen_const(RExC_mysv2),
12181 if (OP(REGNODE_p(ender)) == TAIL) {
12183 RExC_emit= REGNODE_OFFSET(br) + 1;
12186 for ( opt= br + 1; opt < REGNODE_p(ender) ; opt++ )
12187 OP(opt)= OPTIMIZED;
12188 NEXT_OFF(br)= REGNODE_p(ender) - br;
12196 /* Even/odd or x=don't care: 010101x10x */
12197 static const char parens[] = "=!aA<,>Bbt";
12198 /* flag below is set to 0 up through 'A'; 1 for larger */
12200 if (paren && (p = strchr(parens, paren))) {
12201 U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
12202 int flag = (p - parens) > 3;
12204 if (paren == '>' || paren == 't') {
12205 node = SUSPEND, flag = 0;
12208 reginsert(pRExC_state, node, ret, depth+1);
12209 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12210 Set_Node_Offset(REGNODE_p(ret), parse_start + 1);
12211 FLAGS(REGNODE_p(ret)) = flag;
12212 REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
12216 /* Check for proper termination. */
12218 /* restore original flags, but keep (?p) and, if we've encountered
12219 * something in the parse that changes /d rules into /u, keep the /u */
12220 RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY);
12221 if (DEPENDS_SEMANTICS && RExC_uni_semantics) {
12222 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
12224 if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') {
12225 RExC_parse = oregcomp_parse;
12226 vFAIL("Unmatched (");
12228 nextchar(pRExC_state);
12230 else if (!paren && RExC_parse < RExC_end) {
12231 if (*RExC_parse == ')') {
12233 vFAIL("Unmatched )");
12236 FAIL("Junk on end of regexp"); /* "Can't happen". */
12237 NOT_REACHED; /* NOTREACHED */
12240 if (RExC_in_lookbehind) {
12241 RExC_in_lookbehind--;
12243 if (after_freeze > RExC_npar)
12244 RExC_npar = after_freeze;
12249 - regbranch - one alternative of an | operator
12251 * Implements the concatenation operator.
12253 * On success, returns the offset at which any next node should be placed into
12254 * the regex engine program being compiled.
12256 * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
12257 * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
12260 STATIC regnode_offset
12261 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
12263 regnode_offset ret;
12264 regnode_offset chain = 0;
12265 regnode_offset latest;
12266 I32 flags = 0, c = 0;
12267 GET_RE_DEBUG_FLAGS_DECL;
12269 PERL_ARGS_ASSERT_REGBRANCH;
12271 DEBUG_PARSE("brnc");
12276 if (RExC_use_BRANCHJ)
12277 ret = reganode(pRExC_state, BRANCHJ, 0);
12279 ret = reg_node(pRExC_state, BRANCH);
12280 Set_Node_Length(REGNODE_p(ret), 1);
12284 *flagp = WORST; /* Tentatively. */
12286 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
12287 FALSE /* Don't force to /x */ );
12288 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
12289 flags &= ~TRYAGAIN;
12290 latest = regpiece(pRExC_state, &flags, depth+1);
12292 if (flags & TRYAGAIN)
12294 RETURN_FAIL_ON_RESTART(flags, flagp);
12295 FAIL2("panic: regpiece returned failure, flags=%#" UVxf, (UV) flags);
12299 *flagp |= flags&(HASWIDTH|POSTPONED);
12300 if (chain == 0) /* First piece. */
12301 *flagp |= flags&SPSTART;
12303 /* FIXME adding one for every branch after the first is probably
12304 * excessive now we have TRIE support. (hv) */
12306 if ( chain > (SSize_t) BRANCH_MAX_OFFSET
12307 && ! RExC_use_BRANCHJ)
12309 /* XXX We could just redo this branch, but figuring out what
12310 * bookkeeping needs to be reset is a pain */
12311 REQUIRE_BRANCHJ(flagp, 0);
12313 REGTAIL(pRExC_state, chain, latest);
12318 if (chain == 0) { /* Loop ran zero times. */
12319 chain = reg_node(pRExC_state, NOTHING);
12324 *flagp |= flags&SIMPLE;
12331 - regpiece - something followed by possible quantifier * + ? {n,m}
12333 * Note that the branching code sequences used for ? and the general cases
12334 * of * and + are somewhat optimized: they use the same NOTHING node as
12335 * both the endmarker for their branch list and the body of the last branch.
12336 * It might seem that this node could be dispensed with entirely, but the
12337 * endmarker role is not redundant.
12339 * On success, returns the offset at which any next node should be placed into
12340 * the regex engine program being compiled.
12342 * Returns 0 otherwise, with *flagp set to indicate why:
12343 * TRYAGAIN if regatom() returns 0 with TRYAGAIN.
12344 * RESTART_PARSE if the parse needs to be restarted, or'd with
12345 * NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
12347 STATIC regnode_offset
12348 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
12350 regnode_offset ret;
12354 const char * const origparse = RExC_parse;
12356 I32 max = REG_INFTY;
12357 #ifdef RE_TRACK_PATTERN_OFFSETS
12360 const char *maxpos = NULL;
12363 /* Save the original in case we change the emitted regop to a FAIL. */
12364 const regnode_offset orig_emit = RExC_emit;
12366 GET_RE_DEBUG_FLAGS_DECL;
12368 PERL_ARGS_ASSERT_REGPIECE;
12370 DEBUG_PARSE("piec");
12372 ret = regatom(pRExC_state, &flags, depth+1);
12374 RETURN_FAIL_ON_RESTART_OR_FLAGS(flags, flagp, TRYAGAIN);
12375 FAIL2("panic: regatom returned failure, flags=%#" UVxf, (UV) flags);
12380 if (op == '{' && regcurly(RExC_parse)) {
12382 #ifdef RE_TRACK_PATTERN_OFFSETS
12383 parse_start = RExC_parse; /* MJD */
12385 next = RExC_parse + 1;
12386 while (isDIGIT(*next) || *next == ',') {
12387 if (*next == ',') {
12395 if (*next == '}') { /* got one */
12396 const char* endptr;
12400 if (isDIGIT(*RExC_parse)) {
12402 if (!grok_atoUV(RExC_parse, &uv, &endptr))
12403 vFAIL("Invalid quantifier in {,}");
12404 if (uv >= REG_INFTY)
12405 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12410 if (*maxpos == ',')
12413 maxpos = RExC_parse;
12414 if (isDIGIT(*maxpos)) {
12416 if (!grok_atoUV(maxpos, &uv, &endptr))
12417 vFAIL("Invalid quantifier in {,}");
12418 if (uv >= REG_INFTY)
12419 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12422 max = REG_INFTY; /* meaning "infinity" */
12425 nextchar(pRExC_state);
12426 if (max < min) { /* If can't match, warn and optimize to fail
12428 reginsert(pRExC_state, OPFAIL, orig_emit, depth+1);
12429 ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
12430 NEXT_OFF(REGNODE_p(orig_emit)) =
12431 regarglen[OPFAIL] + NODE_STEP_REGNODE;
12434 else if (min == max && *RExC_parse == '?')
12436 ckWARN2reg(RExC_parse + 1,
12437 "Useless use of greediness modifier '%c'",
12442 if ((flags&SIMPLE)) {
12443 if (min == 0 && max == REG_INFTY) {
12444 reginsert(pRExC_state, STAR, ret, depth+1);
12446 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12449 if (min == 1 && max == REG_INFTY) {
12450 reginsert(pRExC_state, PLUS, ret, depth+1);
12452 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12455 MARK_NAUGHTY_EXP(2, 2);
12456 reginsert(pRExC_state, CURLY, ret, depth+1);
12457 Set_Node_Offset(REGNODE_p(ret), parse_start+1); /* MJD */
12458 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12461 const regnode_offset w = reg_node(pRExC_state, WHILEM);
12463 FLAGS(REGNODE_p(w)) = 0;
12464 REGTAIL(pRExC_state, ret, w);
12465 if (RExC_use_BRANCHJ) {
12466 reginsert(pRExC_state, LONGJMP, ret, depth+1);
12467 reginsert(pRExC_state, NOTHING, ret, depth+1);
12468 NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over LONGJMP. */
12470 reginsert(pRExC_state, CURLYX, ret, depth+1);
12472 Set_Node_Offset(REGNODE_p(ret), parse_start+1);
12473 Set_Node_Length(REGNODE_p(ret),
12474 op == '{' ? (RExC_parse - parse_start) : 1);
12476 if (RExC_use_BRANCHJ)
12477 NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over NOTHING to
12479 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
12480 RExC_whilem_seen++;
12481 MARK_NAUGHTY_EXP(1, 4); /* compound interest */
12483 FLAGS(REGNODE_p(ret)) = 0;
12488 *flagp |= HASWIDTH;
12489 ARG1_SET(REGNODE_p(ret), (U16)min);
12490 ARG2_SET(REGNODE_p(ret), (U16)max);
12491 if (max == REG_INFTY)
12492 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12498 if (!ISMULT1(op)) {
12503 #if 0 /* Now runtime fix should be reliable. */
12505 /* if this is reinstated, don't forget to put this back into perldiag:
12507 =item Regexp *+ operand could be empty at {#} in regex m/%s/
12509 (F) The part of the regexp subject to either the * or + quantifier
12510 could match an empty string. The {#} shows in the regular
12511 expression about where the problem was discovered.
12515 if (!(flags&HASWIDTH) && op != '?')
12516 vFAIL("Regexp *+ operand could be empty");
12519 #ifdef RE_TRACK_PATTERN_OFFSETS
12520 parse_start = RExC_parse;
12522 nextchar(pRExC_state);
12524 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
12530 else if (op == '+') {
12534 else if (op == '?') {
12539 if (!(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
12540 ckWARN2reg(RExC_parse,
12541 "%" UTF8f " matches null string many times",
12542 UTF8fARG(UTF, (RExC_parse >= origparse
12543 ? RExC_parse - origparse
12548 if (*RExC_parse == '?') {
12549 nextchar(pRExC_state);
12550 reginsert(pRExC_state, MINMOD, ret, depth+1);
12551 REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
12553 else if (*RExC_parse == '+') {
12554 regnode_offset ender;
12555 nextchar(pRExC_state);
12556 ender = reg_node(pRExC_state, SUCCEED);
12557 REGTAIL(pRExC_state, ret, ender);
12558 reginsert(pRExC_state, SUSPEND, ret, depth+1);
12559 ender = reg_node(pRExC_state, TAIL);
12560 REGTAIL(pRExC_state, ret, ender);
12563 if (ISMULT2(RExC_parse)) {
12565 vFAIL("Nested quantifiers");
12572 S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state,
12573 regnode_offset * node_p,
12581 /* This routine teases apart the various meanings of \N and returns
12582 * accordingly. The input parameters constrain which meaning(s) is/are valid
12583 * in the current context.
12585 * Exactly one of <node_p> and <code_point_p> must be non-NULL.
12587 * If <code_point_p> is not NULL, the context is expecting the result to be a
12588 * single code point. If this \N instance turns out to a single code point,
12589 * the function returns TRUE and sets *code_point_p to that code point.
12591 * If <node_p> is not NULL, the context is expecting the result to be one of
12592 * the things representable by a regnode. If this \N instance turns out to be
12593 * one such, the function generates the regnode, returns TRUE and sets *node_p
12594 * to point to the offset of that regnode into the regex engine program being
12597 * If this instance of \N isn't legal in any context, this function will
12598 * generate a fatal error and not return.
12600 * On input, RExC_parse should point to the first char following the \N at the
12601 * time of the call. On successful return, RExC_parse will have been updated
12602 * to point to just after the sequence identified by this routine. Also
12603 * *flagp has been updated as needed.
12605 * When there is some problem with the current context and this \N instance,
12606 * the function returns FALSE, without advancing RExC_parse, nor setting
12607 * *node_p, nor *code_point_p, nor *flagp.
12609 * If <cp_count> is not NULL, the caller wants to know the length (in code
12610 * points) that this \N sequence matches. This is set, and the input is
12611 * parsed for errors, even if the function returns FALSE, as detailed below.
12613 * There are 5 possibilities here, as detailed in the next 5 paragraphs.
12615 * Probably the most common case is for the \N to specify a single code point.
12616 * *cp_count will be set to 1, and *code_point_p will be set to that code
12619 * Another possibility is for the input to be an empty \N{}, which for
12620 * backwards compatibility we accept. *cp_count will be set to 0. *node_p
12621 * will be set to a generated NOTHING node.
12623 * Still another possibility is for the \N to mean [^\n]. *cp_count will be
12624 * set to 0. *node_p will be set to a generated REG_ANY node.
12626 * The fourth possibility is that \N resolves to a sequence of more than one
12627 * code points. *cp_count will be set to the number of code points in the
12628 * sequence. *node_p will be set to a generated node returned by this
12629 * function calling S_reg().
12631 * The final possibility is that it is premature to be calling this function;
12632 * the parse needs to be restarted. This can happen when this changes from
12633 * /d to /u rules, or when the pattern needs to be upgraded to UTF-8. The
12634 * latter occurs only when the fourth possibility would otherwise be in
12635 * effect, and is because one of those code points requires the pattern to be
12636 * recompiled as UTF-8. The function returns FALSE, and sets the
12637 * RESTART_PARSE and NEED_UTF8 flags in *flagp, as appropriate. When this
12638 * happens, the caller needs to desist from continuing parsing, and return
12639 * this information to its caller. This is not set for when there is only one
12640 * code point, as this can be called as part of an ANYOF node, and they can
12641 * store above-Latin1 code points without the pattern having to be in UTF-8.
12643 * For non-single-quoted regexes, the tokenizer has resolved character and
12644 * sequence names inside \N{...} into their Unicode values, normalizing the
12645 * result into what we should see here: '\N{U+c1.c2...}', where c1... are the
12646 * hex-represented code points in the sequence. This is done there because
12647 * the names can vary based on what charnames pragma is in scope at the time,
12648 * so we need a way to take a snapshot of what they resolve to at the time of
12649 * the original parse. [perl #56444].
12651 * That parsing is skipped for single-quoted regexes, so we may here get
12652 * '\N{NAME}'. This is a fatal error. These names have to be resolved by the
12653 * parser. But if the single-quoted regex is something like '\N{U+41}', that
12654 * is legal and handled here. The code point is Unicode, and has to be
12655 * translated into the native character set for non-ASCII platforms.
12658 char * endbrace; /* points to '}' following the name */
12659 char* p = RExC_parse; /* Temporary */
12661 SV * substitute_parse = NULL;
12665 Size_t count = 0; /* code point count kept internally by this function */
12667 GET_RE_DEBUG_FLAGS_DECL;
12669 PERL_ARGS_ASSERT_GROK_BSLASH_N;
12671 GET_RE_DEBUG_FLAGS;
12673 assert(cBOOL(node_p) ^ cBOOL(code_point_p)); /* Exactly one should be set */
12674 assert(! (node_p && cp_count)); /* At most 1 should be set */
12676 if (cp_count) { /* Initialize return for the most common case */
12680 /* The [^\n] meaning of \N ignores spaces and comments under the /x
12681 * modifier. The other meanings do not, so use a temporary until we find
12682 * out which we are being called with */
12683 skip_to_be_ignored_text(pRExC_state, &p,
12684 FALSE /* Don't force to /x */ );
12686 /* Disambiguate between \N meaning a named character versus \N meaning
12687 * [^\n]. The latter is assumed when the {...} following the \N is a legal
12688 * quantifier, or there is no '{' at all */
12689 if (*p != '{' || regcurly(p)) {
12699 *node_p = reg_node(pRExC_state, REG_ANY);
12700 *flagp |= HASWIDTH|SIMPLE;
12702 Set_Node_Length(REGNODE_p(*(node_p)), 1); /* MJD */
12706 /* The test above made sure that the next real character is a '{', but
12707 * under the /x modifier, it could be separated by space (or a comment and
12708 * \n) and this is not allowed (for consistency with \x{...} and the
12709 * tokenizer handling of \N{NAME}). */
12710 if (*RExC_parse != '{') {
12711 vFAIL("Missing braces on \\N{}");
12714 RExC_parse++; /* Skip past the '{' */
12716 endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
12717 if (! endbrace) { /* no trailing brace */
12718 vFAIL2("Missing right brace on \\%c{}", 'N');
12721 /* Here, we have decided it should be a named character or sequence */
12722 REQUIRE_UNI_RULES(flagp, FALSE); /* Unicode named chars imply Unicode
12725 if (endbrace == RExC_parse) { /* empty: \N{} */
12727 RExC_parse++; /* Position after the "}" */
12728 vFAIL("Zero length \\N{}");
12733 nextchar(pRExC_state);
12738 *node_p = reg_node(pRExC_state, NOTHING);
12742 /* If we haven't got something that begins with 'U+', then it didn't get lexed. */
12743 if ( endbrace - RExC_parse < 2
12744 || strnNE(RExC_parse, "U+", 2))
12746 RExC_parse = endbrace; /* position msg's '<--HERE' */
12747 vFAIL("\\N{NAME} must be resolved by the lexer");
12750 /* This code purposely indented below because of future changes coming */
12752 /* We can get to here when the input is \N{U+...} or when toke.c has
12753 * converted a name to the \N{U+...} form. This include changing a
12754 * name that evaluates to multiple code points to \N{U+c1.c2.c3 ...} */
12756 RExC_parse += 2; /* Skip past the 'U+' */
12758 /* Code points are separated by dots. The '}' terminates the whole
12761 do { /* Loop until the ending brace */
12763 char * start_digit; /* The first of the current code point */
12764 if (! isXDIGIT(*RExC_parse)) {
12766 vFAIL("Invalid hexadecimal number in \\N{U+...}");
12769 start_digit = RExC_parse;
12772 /* Loop through the hex digits of the current code point */
12774 /* Adding this digit will shift the result 4 bits. If that
12775 * result would be above the legal max, it's overflow */
12776 if (cp > MAX_LEGAL_CP >> 4) {
12778 /* Find the end of the code point */
12781 } while (isXDIGIT(*RExC_parse) || *RExC_parse == '_');
12783 /* Be sure to synchronize this message with the similar one
12785 vFAIL4("Use of code point 0x%.*s is not allowed; the"
12786 " permissible max is 0x%" UVxf,
12787 (int) (RExC_parse - start_digit), start_digit,
12791 /* Accumulate this (valid) digit into the running total */
12792 cp = (cp << 4) + READ_XDIGIT(RExC_parse);
12794 /* READ_XDIGIT advanced the input pointer. Ignore a single
12795 * underscore separator */
12796 if (*RExC_parse == '_' && isXDIGIT(RExC_parse[1])) {
12799 } while (isXDIGIT(*RExC_parse));
12801 /* Here, have accumulated the next code point */
12802 if (RExC_parse >= endbrace) { /* If done ... */
12807 /* Here, is a single code point; fail if doesn't want that */
12808 if (! code_point_p) {
12813 /* A single code point is easy to handle; just return it */
12814 *code_point_p = UNI_TO_NATIVE(cp);
12815 RExC_parse = endbrace;
12816 nextchar(pRExC_state);
12820 /* Here, the only legal thing would be a multiple character
12821 * sequence (of the form "\N{U+c1.c2. ... }". So the next
12822 * character must be a dot (and the one after that can't be the
12823 * endbrace, or we'd have something like \N{U+100.} ) */
12824 if (*RExC_parse != '.' || RExC_parse + 1 >= endbrace) {
12825 RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */
12826 ? UTF8SKIP(RExC_parse)
12828 if (RExC_parse >= endbrace) { /* Guard against malformed utf8 */
12829 RExC_parse = endbrace;
12831 vFAIL("Invalid hexadecimal number in \\N{U+...}");
12834 /* Here, looks like its really a multiple character sequence. Fail
12835 * if that's not what the caller wants. But continue with counting
12836 * and error checking if they still want a count */
12837 if (! node_p && ! cp_count) {
12841 /* What is done here is to convert this to a sub-pattern of the
12842 * form \x{char1}\x{char2}... and then call reg recursively to
12843 * parse it (enclosing in "(?: ... )" ). That way, it retains its
12844 * atomicness, while not having to worry about special handling
12845 * that some code points may have. We don't create a subpattern,
12846 * but go through the motions of code point counting and error
12847 * checking, if the caller doesn't want a node returned. */
12849 if (node_p && count == 1) {
12850 substitute_parse = newSVpvs("?:");
12856 /* Convert to notation the rest of the code understands */
12857 sv_catpvs(substitute_parse, "\\x{");
12858 sv_catpvn(substitute_parse, start_digit,
12859 RExC_parse - start_digit);
12860 sv_catpvs(substitute_parse, "}");
12863 /* Move to after the dot (or ending brace the final time through.)
12868 } while (RExC_parse < endbrace);
12870 if (! node_p) { /* Doesn't want the node */
12877 sv_catpvs(substitute_parse, ")");
12880 /* The values are Unicode, and therefore have to be converted to native
12881 * on a non-Unicode (meaning non-ASCII) platform. */
12882 RExC_recode_x_to_native = 1;
12885 /* Here, we have the string the name evaluates to, ready to be parsed,
12886 * stored in 'substitute_parse' as a series of valid "\x{...}\x{...}"
12887 * constructs. This can be called from within a substitute parse already.
12888 * The error reporting mechanism doesn't work for 2 levels of this, but the
12889 * code above has validated this new construct, so there should be no
12890 * errors generated by the below. And this isn' an exact copy, so the
12891 * mechanism to seamlessly deal with this won't work, so turn off warnings
12893 save_start = RExC_start;
12894 orig_end = RExC_end;
12896 RExC_parse = RExC_start = SvPVX(substitute_parse);
12897 RExC_end = RExC_parse + SvCUR(substitute_parse);
12898 TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
12900 *node_p = reg(pRExC_state, 1, &flags, depth+1);
12902 /* Restore the saved values */
12904 RExC_start = save_start;
12905 RExC_parse = endbrace;
12906 RExC_end = orig_end;
12908 RExC_recode_x_to_native = 0;
12911 SvREFCNT_dec_NN(substitute_parse);
12914 RETURN_FAIL_ON_RESTART(flags, flagp);
12915 FAIL2("panic: reg returned failure to grok_bslash_N, flags=%#" UVxf,
12918 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
12920 nextchar(pRExC_state);
12926 PERL_STATIC_INLINE U8
12927 S_compute_EXACTish(RExC_state_t *pRExC_state)
12931 PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
12939 op = get_regex_charset(RExC_flags);
12940 if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
12941 op--; /* /a is same as /u, and map /aa's offset to what /a's would have
12942 been, so there is no hole */
12945 return op + EXACTF;
12949 S_new_regcurly(const char *s, const char *e)
12951 /* This is a temporary function designed to match the most lenient form of
12952 * a {m,n} quantifier we ever envision, with either number omitted, and
12953 * spaces anywhere between/before/after them.
12955 * If this function fails, then the string it matches is very unlikely to
12956 * ever be considered a valid quantifier, so we can allow the '{' that
12957 * begins it to be considered as a literal */
12959 bool has_min = FALSE;
12960 bool has_max = FALSE;
12962 PERL_ARGS_ASSERT_NEW_REGCURLY;
12964 if (s >= e || *s++ != '{')
12967 while (s < e && isSPACE(*s)) {
12970 while (s < e && isDIGIT(*s)) {
12974 while (s < e && isSPACE(*s)) {
12980 while (s < e && isSPACE(*s)) {
12983 while (s < e && isDIGIT(*s)) {
12987 while (s < e && isSPACE(*s)) {
12992 return s < e && *s == '}' && (has_min || has_max);
12995 /* Parse backref decimal value, unless it's too big to sensibly be a backref,
12996 * in which case return I32_MAX (rather than possibly 32-bit wrapping) */
12999 S_backref_value(char *p, char *e)
13001 const char* endptr = e;
13003 if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX)
13010 - regatom - the lowest level
13012 Try to identify anything special at the start of the current parse position.
13013 If there is, then handle it as required. This may involve generating a
13014 single regop, such as for an assertion; or it may involve recursing, such as
13015 to handle a () structure.
13017 If the string doesn't start with something special then we gobble up
13018 as much literal text as we can. If we encounter a quantifier, we have to
13019 back off the final literal character, as that quantifier applies to just it
13020 and not to the whole string of literals.
13022 Once we have been able to handle whatever type of thing started the
13023 sequence, we return the offset into the regex engine program being compiled
13024 at which any next regnode should be placed.
13026 Returns 0, setting *flagp to TRYAGAIN if reg() returns 0 with TRYAGAIN.
13027 Returns 0, setting *flagp to RESTART_PARSE if the parse needs to be
13028 restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
13029 Otherwise does not return 0.
13031 Note: we have to be careful with escapes, as they can be both literal
13032 and special, and in the case of \10 and friends, context determines which.
13034 A summary of the code structure is:
13036 switch (first_byte) {
13037 cases for each special:
13038 handle this special;
13041 switch (2nd byte) {
13042 cases for each unambiguous special:
13043 handle this special;
13045 cases for each ambigous special/literal:
13047 if (special) handle here
13049 default: // unambiguously literal:
13052 default: // is a literal char
13055 create EXACTish node for literal;
13056 while (more input and node isn't full) {
13057 switch (input_byte) {
13058 cases for each special;
13059 make sure parse pointer is set so that the next call to
13060 regatom will see this special first
13061 goto loopdone; // EXACTish node terminated by prev. char
13063 append char to EXACTISH node;
13065 get next input byte;
13069 return the generated node;
13071 Specifically there are two separate switches for handling
13072 escape sequences, with the one for handling literal escapes requiring
13073 a dummy entry for all of the special escapes that are actually handled
13078 STATIC regnode_offset
13079 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
13082 regnode_offset ret = 0;
13089 GET_RE_DEBUG_FLAGS_DECL;
13091 *flagp = WORST; /* Tentatively. */
13093 DEBUG_PARSE("atom");
13095 PERL_ARGS_ASSERT_REGATOM;
13098 parse_start = RExC_parse;
13099 assert(RExC_parse < RExC_end);
13100 switch ((U8)*RExC_parse) {
13102 RExC_seen_zerolen++;
13103 nextchar(pRExC_state);
13104 if (RExC_flags & RXf_PMf_MULTILINE)
13105 ret = reg_node(pRExC_state, MBOL);
13107 ret = reg_node(pRExC_state, SBOL);
13108 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13111 nextchar(pRExC_state);
13113 RExC_seen_zerolen++;
13114 if (RExC_flags & RXf_PMf_MULTILINE)
13115 ret = reg_node(pRExC_state, MEOL);
13117 ret = reg_node(pRExC_state, SEOL);
13118 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13121 nextchar(pRExC_state);
13122 if (RExC_flags & RXf_PMf_SINGLELINE)
13123 ret = reg_node(pRExC_state, SANY);
13125 ret = reg_node(pRExC_state, REG_ANY);
13126 *flagp |= HASWIDTH|SIMPLE;
13128 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13132 char * const oregcomp_parse = ++RExC_parse;
13133 ret = regclass(pRExC_state, flagp, depth+1,
13134 FALSE, /* means parse the whole char class */
13135 TRUE, /* allow multi-char folds */
13136 FALSE, /* don't silence non-portable warnings. */
13137 (bool) RExC_strict,
13138 TRUE, /* Allow an optimized regnode result */
13141 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13142 FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13145 if (*RExC_parse != ']') {
13146 RExC_parse = oregcomp_parse;
13147 vFAIL("Unmatched [");
13149 nextchar(pRExC_state);
13150 Set_Node_Length(REGNODE_p(ret), RExC_parse - oregcomp_parse + 1); /* MJD */
13154 nextchar(pRExC_state);
13155 ret = reg(pRExC_state, 2, &flags, depth+1);
13157 if (flags & TRYAGAIN) {
13158 if (RExC_parse >= RExC_end) {
13159 /* Make parent create an empty node if needed. */
13160 *flagp |= TRYAGAIN;
13165 RETURN_FAIL_ON_RESTART(flags, flagp);
13166 FAIL2("panic: reg returned failure to regatom, flags=%#" UVxf,
13169 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
13173 if (flags & TRYAGAIN) {
13174 *flagp |= TRYAGAIN;
13177 vFAIL("Internal urp");
13178 /* Supposed to be caught earlier. */
13184 vFAIL("Quantifier follows nothing");
13189 This switch handles escape sequences that resolve to some kind
13190 of special regop and not to literal text. Escape sequences that
13191 resolve to literal text are handled below in the switch marked
13194 Every entry in this switch *must* have a corresponding entry
13195 in the literal escape switch. However, the opposite is not
13196 required, as the default for this switch is to jump to the
13197 literal text handling code.
13200 switch ((U8)*RExC_parse) {
13201 /* Special Escapes */
13203 RExC_seen_zerolen++;
13204 ret = reg_node(pRExC_state, SBOL);
13205 /* SBOL is shared with /^/ so we set the flags so we can tell
13206 * /\A/ from /^/ in split. */
13207 FLAGS(REGNODE_p(ret)) = 1;
13209 goto finish_meta_pat;
13211 ret = reg_node(pRExC_state, GPOS);
13212 RExC_seen |= REG_GPOS_SEEN;
13214 goto finish_meta_pat;
13216 RExC_seen_zerolen++;
13217 ret = reg_node(pRExC_state, KEEPS);
13219 /* XXX:dmq : disabling in-place substitution seems to
13220 * be necessary here to avoid cases of memory corruption, as
13221 * with: C<$_="x" x 80; s/x\K/y/> -- rgs
13223 RExC_seen |= REG_LOOKBEHIND_SEEN;
13224 goto finish_meta_pat;
13226 ret = reg_node(pRExC_state, SEOL);
13228 RExC_seen_zerolen++; /* Do not optimize RE away */
13229 goto finish_meta_pat;
13231 ret = reg_node(pRExC_state, EOS);
13233 RExC_seen_zerolen++; /* Do not optimize RE away */
13234 goto finish_meta_pat;
13236 vFAIL("\\C no longer supported");
13238 ret = reg_node(pRExC_state, CLUMP);
13239 *flagp |= HASWIDTH;
13240 goto finish_meta_pat;
13246 arg = ANYOF_WORDCHAR;
13255 regex_charset charset = get_regex_charset(RExC_flags);
13257 RExC_seen_zerolen++;
13258 RExC_seen |= REG_LOOKBEHIND_SEEN;
13259 op = BOUND + charset;
13261 if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') {
13262 flags = TRADITIONAL_BOUND;
13263 if (op > BOUNDA) { /* /aa is same as /a */
13269 char name = *RExC_parse;
13270 char * endbrace = NULL;
13272 if (RExC_parse < RExC_end) {
13273 endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
13277 vFAIL2("Missing right brace on \\%c{}", name);
13279 /* XXX Need to decide whether to take spaces or not. Should be
13280 * consistent with \p{}, but that currently is SPACE, which
13281 * means vertical too, which seems wrong
13282 * while (isBLANK(*RExC_parse)) {
13285 if (endbrace == RExC_parse) {
13286 RExC_parse++; /* After the '}' */
13287 vFAIL2("Empty \\%c{}", name);
13289 length = endbrace - RExC_parse;
13290 /*while (isBLANK(*(RExC_parse + length - 1))) {
13293 switch (*RExC_parse) {
13296 && (memNEs(RExC_parse + 1, length - 1, "cb")))
13298 goto bad_bound_type;
13303 if (length != 2 || *(RExC_parse + 1) != 'b') {
13304 goto bad_bound_type;
13309 if (length != 2 || *(RExC_parse + 1) != 'b') {
13310 goto bad_bound_type;
13315 if (length != 2 || *(RExC_parse + 1) != 'b') {
13316 goto bad_bound_type;
13322 RExC_parse = endbrace;
13324 "'%" UTF8f "' is an unknown bound type",
13325 UTF8fARG(UTF, length, endbrace - length));
13326 NOT_REACHED; /*NOTREACHED*/
13328 RExC_parse = endbrace;
13329 REQUIRE_UNI_RULES(flagp, 0);
13334 else if (op >= BOUNDA) { /* /aa is same as /a */
13338 /* Don't have to worry about UTF-8, in this message because
13339 * to get here the contents of the \b must be ASCII */
13340 ckWARN4reg(RExC_parse + 1, /* Include the '}' in msg */
13341 "Using /u for '%.*s' instead of /%s",
13343 endbrace - length + 1,
13344 (charset == REGEX_ASCII_RESTRICTED_CHARSET)
13345 ? ASCII_RESTRICT_PAT_MODS
13346 : ASCII_MORE_RESTRICT_PAT_MODS);
13351 RExC_seen_d_op = TRUE;
13353 else if (op == BOUNDL) {
13354 RExC_contains_locale = 1;
13358 op += NBOUND - BOUND;
13361 ret = reg_node(pRExC_state, op);
13362 FLAGS(REGNODE_p(ret)) = flags;
13366 goto finish_meta_pat;
13374 if (! DEPENDS_SEMANTICS) {
13378 /* \d doesn't have any matches in the upper Latin1 range, hence /d
13379 * is equivalent to /u. Changing to /u saves some branches at
13382 goto join_posix_op_known;
13385 ret = reg_node(pRExC_state, LNBREAK);
13386 *flagp |= HASWIDTH|SIMPLE;
13387 goto finish_meta_pat;
13395 goto join_posix_op_known;
13401 arg = ANYOF_VERTWS;
13403 goto join_posix_op_known;
13413 op = POSIXD + get_regex_charset(RExC_flags);
13414 if (op > POSIXA) { /* /aa is same as /a */
13417 else if (op == POSIXL) {
13418 RExC_contains_locale = 1;
13420 else if (op == POSIXD) {
13421 RExC_seen_d_op = TRUE;
13424 join_posix_op_known:
13427 op += NPOSIXD - POSIXD;
13430 ret = reg_node(pRExC_state, op);
13431 FLAGS(REGNODE_p(ret)) = namedclass_to_classnum(arg);
13433 *flagp |= HASWIDTH|SIMPLE;
13437 if ( UCHARAT(RExC_parse + 1) == '{'
13438 && UNLIKELY(! new_regcurly(RExC_parse + 1, RExC_end)))
13441 vFAIL("Unescaped left brace in regex is illegal here");
13443 nextchar(pRExC_state);
13444 Set_Node_Length(REGNODE_p(ret), 2); /* MJD */
13450 ret = regclass(pRExC_state, flagp, depth+1,
13451 TRUE, /* means just parse this element */
13452 FALSE, /* don't allow multi-char folds */
13453 FALSE, /* don't silence non-portable warnings. It
13454 would be a bug if these returned
13456 (bool) RExC_strict,
13457 TRUE, /* Allow an optimized regnode result */
13459 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13460 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
13461 * multi-char folds are allowed. */
13463 FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13468 Set_Node_Offset(REGNODE_p(ret), parse_start);
13469 Set_Node_Cur_Length(REGNODE_p(ret), parse_start - 2);
13470 nextchar(pRExC_state);
13473 /* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the
13474 * \N{...} evaluates to a sequence of more than one code points).
13475 * The function call below returns a regnode, which is our result.
13476 * The parameters cause it to fail if the \N{} evaluates to a
13477 * single code point; we handle those like any other literal. The
13478 * reason that the multicharacter case is handled here and not as
13479 * part of the EXACtish code is because of quantifiers. In
13480 * /\N{BLAH}+/, the '+' applies to the whole thing, and doing it
13481 * this way makes that Just Happen. dmq.
13482 * join_exact() will join this up with adjacent EXACTish nodes
13483 * later on, if appropriate. */
13485 if (grok_bslash_N(pRExC_state,
13486 &ret, /* Want a regnode returned */
13487 NULL, /* Fail if evaluates to a single code
13489 NULL, /* Don't need a count of how many code
13498 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13500 /* Here, evaluates to a single code point. Go get that */
13501 RExC_parse = parse_start;
13504 case 'k': /* Handle \k<NAME> and \k'NAME' */
13508 if ( RExC_parse >= RExC_end - 1
13509 || (( ch = RExC_parse[1]) != '<'
13514 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
13515 vFAIL2("Sequence %.2s... not terminated", parse_start);
13518 ret = handle_named_backref(pRExC_state,
13530 case '1': case '2': case '3': case '4':
13531 case '5': case '6': case '7': case '8': case '9':
13536 if (*RExC_parse == 'g') {
13540 if (*RExC_parse == '{') {
13544 if (*RExC_parse == '-') {
13548 if (hasbrace && !isDIGIT(*RExC_parse)) {
13549 if (isrel) RExC_parse--;
13551 goto parse_named_seq;
13554 if (RExC_parse >= RExC_end) {
13555 goto unterminated_g;
13557 num = S_backref_value(RExC_parse, RExC_end);
13559 vFAIL("Reference to invalid group 0");
13560 else if (num == I32_MAX) {
13561 if (isDIGIT(*RExC_parse))
13562 vFAIL("Reference to nonexistent group");
13565 vFAIL("Unterminated \\g... pattern");
13569 num = RExC_npar - num;
13571 vFAIL("Reference to nonexistent or unclosed group");
13575 num = S_backref_value(RExC_parse, RExC_end);
13576 /* bare \NNN might be backref or octal - if it is larger
13577 * than or equal RExC_npar then it is assumed to be an
13578 * octal escape. Note RExC_npar is +1 from the actual
13579 * number of parens. */
13580 /* Note we do NOT check if num == I32_MAX here, as that is
13581 * handled by the RExC_npar check */
13584 /* any numeric escape < 10 is always a backref */
13586 /* any numeric escape < RExC_npar is a backref */
13587 && num >= RExC_npar
13588 /* cannot be an octal escape if it starts with 8 */
13589 && *RExC_parse != '8'
13590 /* cannot be an octal escape it it starts with 9 */
13591 && *RExC_parse != '9'
13593 /* Probably not meant to be a backref, instead likely
13594 * to be an octal character escape, e.g. \35 or \777.
13595 * The above logic should make it obvious why using
13596 * octal escapes in patterns is problematic. - Yves */
13597 RExC_parse = parse_start;
13602 /* At this point RExC_parse points at a numeric escape like
13603 * \12 or \88 or something similar, which we should NOT treat
13604 * as an octal escape. It may or may not be a valid backref
13605 * escape. For instance \88888888 is unlikely to be a valid
13607 while (isDIGIT(*RExC_parse))
13610 if (*RExC_parse != '}')
13611 vFAIL("Unterminated \\g{...} pattern");
13614 if (num >= (I32)RExC_npar) {
13616 /* It might be a forward reference; we can't fail until we
13617 * know, by completing the parse to get all the groups, and
13618 * then reparsing */
13619 if (RExC_total_parens > 0) {
13620 if (num >= RExC_total_parens) {
13621 vFAIL("Reference to nonexistent group");
13625 REQUIRE_PARENS_PASS;
13629 ret = reganode(pRExC_state,
13632 : (ASCII_FOLD_RESTRICTED)
13634 : (AT_LEAST_UNI_SEMANTICS)
13640 if (OP(REGNODE_p(ret)) == REFF) {
13641 RExC_seen_d_op = TRUE;
13643 *flagp |= HASWIDTH;
13645 /* override incorrect value set in reganode MJD */
13646 Set_Node_Offset(REGNODE_p(ret), parse_start);
13647 Set_Node_Cur_Length(REGNODE_p(ret), parse_start-1);
13648 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
13649 FALSE /* Don't force to /x */ );
13653 if (RExC_parse >= RExC_end)
13654 FAIL("Trailing \\");
13657 /* Do not generate "unrecognized" warnings here, we fall
13658 back into the quick-grab loop below */
13659 RExC_parse = parse_start;
13661 } /* end of switch on a \foo sequence */
13666 /* '#' comments should have been spaced over before this function was
13668 assert((RExC_flags & RXf_PMf_EXTENDED) == 0);
13670 if (RExC_flags & RXf_PMf_EXTENDED) {
13671 RExC_parse = reg_skipcomment( pRExC_state, RExC_parse );
13672 if (RExC_parse < RExC_end)
13682 /* Here, we have determined that the next thing is probably a
13683 * literal character. RExC_parse points to the first byte of its
13684 * definition. (It still may be an escape sequence that evaluates
13685 * to a single character) */
13692 /* This allows us to fill a node with just enough spare so that if the final
13693 * character folds, its expansion is guaranteed to fit */
13694 #define MAX_NODE_STRING_SIZE (255-UTF8_MAXBYTES_CASE)
13697 U8 upper_parse = MAX_NODE_STRING_SIZE;
13699 /* We start out as an EXACT node, even if under /i, until we find a
13700 * character which is in a fold. The algorithm now segregates into
13701 * separate nodes, characters that fold from those that don't under
13702 * /i. (This hopefully will create nodes that are fixed strings
13703 * even under /i, giving the optimizer something to grab on to.)
13704 * So, if a node has something in it and the next character is in
13705 * the opposite category, that node is closed up, and the function
13706 * returns. Then regatom is called again, and a new node is
13707 * created for the new category. */
13708 U8 node_type = EXACT;
13710 /* Assume the node will be fully used; the excess is given back at
13711 * the end. We can't make any other length assumptions, as a byte
13712 * input sequence could shrink down. */
13713 Ptrdiff_t initial_size = STR_SZ(256);
13715 bool next_is_quantifier;
13716 char * oldp = NULL;
13718 /* We can convert EXACTF nodes to EXACTFU if they contain only
13719 * characters that match identically regardless of the target
13720 * string's UTF8ness. The reason to do this is that EXACTF is not
13721 * trie-able, EXACTFU is, and EXACTFU requires fewer operations at
13724 * Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they
13725 * contain only above-Latin1 characters (hence must be in UTF8),
13726 * which don't participate in folds with Latin1-range characters,
13727 * as the latter's folds aren't known until runtime. */
13728 bool maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC);
13730 /* Single-character EXACTish nodes are almost always SIMPLE. This
13731 * allows us to override this as encountered */
13732 U8 maybe_SIMPLE = SIMPLE;
13734 /* Does this node contain something that can't match unless the
13735 * target string is (also) in UTF-8 */
13736 bool requires_utf8_target = FALSE;
13738 /* The sequence 'ss' is problematic in non-UTF-8 patterns. */
13739 bool has_ss = FALSE;
13741 /* So is the MICRO SIGN */
13742 bool has_micro_sign = FALSE;
13744 /* Allocate an EXACT node. The node_type may change below to
13745 * another EXACTish node, but since the size of the node doesn't
13746 * change, it works */
13747 ret = regnode_guts(pRExC_state, node_type, initial_size, "exact");
13748 FILL_NODE(ret, node_type);
13751 s = STRING(REGNODE_p(ret));
13757 /* This breaks under rare circumstances. If folding, we do not
13758 * want to split a node at a character that is a non-final in a
13759 * multi-char fold, as an input string could just happen to want to
13760 * match across the node boundary. The code at the end of the loop
13761 * looks for this, and backs off until it finds not such a
13762 * character, but it is possible (though extremely, extremely
13763 * unlikely) for all characters in the node to be non-final fold
13764 * ones, in which case we just leave the node fully filled, and
13765 * hope that it doesn't match the string in just the wrong place */
13767 assert( ! UTF /* Is at the beginning of a character */
13768 || UTF8_IS_INVARIANT(UCHARAT(RExC_parse))
13769 || UTF8_IS_START(UCHARAT(RExC_parse)));
13772 /* Here, we have a literal character. Find the maximal string of
13773 * them in the input that we can fit into a single EXACTish node.
13774 * We quit at the first non-literal or when the node gets full, or
13775 * under /i the categorization of folding/non-folding character
13777 for (p = RExC_parse; len < upper_parse && p < RExC_end; ) {
13779 /* In most cases each iteration adds one byte to the output.
13780 * The exceptions override this */
13781 Size_t added_len = 1;
13785 /* White space has already been ignored */
13786 assert( (RExC_flags & RXf_PMf_EXTENDED) == 0
13787 || ! is_PATWS_safe((p), RExC_end, UTF));
13799 /* Literal Escapes Switch
13801 This switch is meant to handle escape sequences that
13802 resolve to a literal character.
13804 Every escape sequence that represents something
13805 else, like an assertion or a char class, is handled
13806 in the switch marked 'Special Escapes' above in this
13807 routine, but also has an entry here as anything that
13808 isn't explicitly mentioned here will be treated as
13809 an unescaped equivalent literal.
13812 switch ((U8)*++p) {
13814 /* These are all the special escapes. */
13815 case 'A': /* Start assertion */
13816 case 'b': case 'B': /* Word-boundary assertion*/
13817 case 'C': /* Single char !DANGEROUS! */
13818 case 'd': case 'D': /* digit class */
13819 case 'g': case 'G': /* generic-backref, pos assertion */
13820 case 'h': case 'H': /* HORIZWS */
13821 case 'k': case 'K': /* named backref, keep marker */
13822 case 'p': case 'P': /* Unicode property */
13823 case 'R': /* LNBREAK */
13824 case 's': case 'S': /* space class */
13825 case 'v': case 'V': /* VERTWS */
13826 case 'w': case 'W': /* word class */
13827 case 'X': /* eXtended Unicode "combining
13828 character sequence" */
13829 case 'z': case 'Z': /* End of line/string assertion */
13833 /* Anything after here is an escape that resolves to a
13834 literal. (Except digits, which may or may not)
13840 case 'N': /* Handle a single-code point named character. */
13841 RExC_parse = p + 1;
13842 if (! grok_bslash_N(pRExC_state,
13843 NULL, /* Fail if evaluates to
13844 anything other than a
13845 single code point */
13846 &ender, /* The returned single code
13848 NULL, /* Don't need a count of
13849 how many code points */
13854 if (*flagp & NEED_UTF8)
13855 FAIL("panic: grok_bslash_N set NEED_UTF8");
13856 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13858 /* Here, it wasn't a single code point. Go close
13859 * up this EXACTish node. The switch() prior to
13860 * this switch handles the other cases */
13861 RExC_parse = p = oldp;
13865 RExC_parse = parse_start;
13867 /* The \N{} means the pattern, if previously /d,
13868 * becomes /u. That means it can't be an EXACTF node,
13869 * but an EXACTFU */
13870 if (node_type == EXACTF) {
13871 node_type = EXACTFU;
13873 /* If the node already contains something that
13874 * differs between EXACTF and EXACTFU, reparse it
13876 if (! maybe_exactfu) {
13897 ender = ESC_NATIVE;
13907 const char* error_msg;
13909 bool valid = grok_bslash_o(&p,
13913 TO_OUTPUT_WARNINGS(p),
13914 (bool) RExC_strict,
13915 TRUE, /* Output warnings
13920 RExC_parse = p; /* going to die anyway; point
13921 to exact spot of failure */
13924 UPDATE_WARNINGS_LOC(p - 1);
13930 UV result = UV_MAX; /* initialize to erroneous
13932 const char* error_msg;
13934 bool valid = grok_bslash_x(&p,
13938 TO_OUTPUT_WARNINGS(p),
13939 (bool) RExC_strict,
13940 TRUE, /* Silence warnings
13945 RExC_parse = p; /* going to die anyway; point
13946 to exact spot of failure */
13949 UPDATE_WARNINGS_LOC(p - 1);
13952 if (ender < 0x100) {
13954 if (RExC_recode_x_to_native) {
13955 ender = LATIN1_TO_NATIVE(ender);
13963 ender = grok_bslash_c(*p, TO_OUTPUT_WARNINGS(p));
13964 UPDATE_WARNINGS_LOC(p);
13967 case '8': case '9': /* must be a backreference */
13969 /* we have an escape like \8 which cannot be an octal escape
13970 * so we exit the loop, and let the outer loop handle this
13971 * escape which may or may not be a legitimate backref. */
13973 case '1': case '2': case '3':case '4':
13974 case '5': case '6': case '7':
13975 /* When we parse backslash escapes there is ambiguity
13976 * between backreferences and octal escapes. Any escape
13977 * from \1 - \9 is a backreference, any multi-digit
13978 * escape which does not start with 0 and which when
13979 * evaluated as decimal could refer to an already
13980 * parsed capture buffer is a back reference. Anything
13983 * Note this implies that \118 could be interpreted as
13984 * 118 OR as "\11" . "8" depending on whether there
13985 * were 118 capture buffers defined already in the
13988 /* NOTE, RExC_npar is 1 more than the actual number of
13989 * parens we have seen so far, hence the "<" as opposed
13991 if ( !isDIGIT(p[1]) || S_backref_value(p, RExC_end) < RExC_npar)
13992 { /* Not to be treated as an octal constant, go
14000 I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
14002 ender = grok_oct(p, &numlen, &flags, NULL);
14004 if ( isDIGIT(*p) /* like \08, \178 */
14005 && ckWARN(WARN_REGEXP)
14008 reg_warn_non_literal_string(
14010 form_short_octal_warning(p, numlen));
14016 FAIL("Trailing \\");
14019 if (isALPHANUMERIC(*p)) {
14020 /* An alpha followed by '{' is going to fail next
14021 * iteration, so don't output this warning in that
14023 if (! isALPHA(*p) || *(p + 1) != '{') {
14024 ckWARN2reg(p + 1, "Unrecognized escape \\%.1s"
14025 " passed through", p);
14028 goto normal_default;
14029 } /* End of switch on '\' */
14032 /* Trying to gain new uses for '{' without breaking too
14033 * much existing code is hard. The solution currently
14035 * 1) If there is no ambiguity that a '{' should always
14036 * be taken literally, at the start of a construct, we
14038 * 2) If the literal '{' conflicts with our desired use
14039 * of it as a metacharacter, we die. The deprecation
14040 * cycles for this have come and gone.
14041 * 3) If there is ambiguity, we raise a simple warning.
14042 * This could happen, for example, if the user
14043 * intended it to introduce a quantifier, but slightly
14044 * misspelled the quantifier. Without this warning,
14045 * the quantifier would silently be taken as a literal
14046 * string of characters instead of a meta construct */
14047 if (len || (p > RExC_start && isALPHA_A(*(p - 1)))) {
14049 || ( p > parse_start + 1
14050 && isALPHA_A(*(p - 1))
14051 && *(p - 2) == '\\')
14052 || new_regcurly(p, RExC_end))
14054 RExC_parse = p + 1;
14055 vFAIL("Unescaped left brace in regex is "
14058 ckWARNreg(p + 1, "Unescaped left brace in regex is"
14059 " passed through");
14061 goto normal_default;
14064 if (p > RExC_parse && RExC_strict) {
14065 ckWARN2reg(p + 1, "Unescaped literal '%c'", *p);
14068 default: /* A literal character */
14070 if (! UTF8_IS_INVARIANT(*p) && UTF) {
14072 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
14073 &numlen, UTF8_ALLOW_DEFAULT);
14079 } /* End of switch on the literal */
14081 /* Here, have looked at the literal character, and <ender>
14082 * contains its ordinal; <p> points to the character after it.
14086 REQUIRE_UTF8(flagp);
14089 /* We need to check if the next non-ignored thing is a
14090 * quantifier. Move <p> to after anything that should be
14091 * ignored, which, as a side effect, positions <p> for the next
14092 * loop iteration */
14093 skip_to_be_ignored_text(pRExC_state, &p,
14094 FALSE /* Don't force to /x */ );
14096 /* If the next thing is a quantifier, it applies to this
14097 * character only, which means that this character has to be in
14098 * its own node and can't just be appended to the string in an
14099 * existing node, so if there are already other characters in
14100 * the node, close the node with just them, and set up to do
14101 * this character again next time through, when it will be the
14102 * only thing in its new node */
14104 next_is_quantifier = LIKELY(p < RExC_end)
14105 && UNLIKELY(ISMULT2(p));
14107 if (next_is_quantifier && LIKELY(len)) {
14112 /* Ready to add 'ender' to the node */
14114 if (! FOLD) { /* The simple case, just append the literal */
14117 if (UVCHR_IS_INVARIANT(ender) || ! UTF) {
14118 *(s++) = (char) ender;
14121 U8 * new_s = uvchr_to_utf8((U8*)s, ender);
14122 added_len = (char *) new_s - s;
14123 s = (char *) new_s;
14126 requires_utf8_target = TRUE;
14130 else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) {
14132 /* Here are folding under /l, and the code point is
14133 * problematic. If this is the first character in the
14134 * node, change the node type to folding. Otherwise, if
14135 * this is the first problematic character, close up the
14136 * existing node, so can start a new node with this one */
14138 node_type = EXACTFL;
14139 RExC_contains_locale = 1;
14141 else if (node_type == EXACT) {
14146 /* This problematic code point means we can't simplify
14148 maybe_exactfu = FALSE;
14150 /* Here, we are adding a problematic fold character.
14151 * "Problematic" in this context means that its fold isn't
14152 * known until runtime. (The non-problematic code points
14153 * are the above-Latin1 ones that fold to also all
14154 * above-Latin1. Their folds don't vary no matter what the
14155 * locale is.) But here we have characters whose fold
14156 * depends on the locale. We just add in the unfolded
14157 * character, and wait until runtime to fold it */
14158 goto not_fold_common;
14160 else /* regular fold; see if actually is in a fold */
14161 if ( (ender < 256 && ! IS_IN_SOME_FOLD_L1(ender))
14163 && ! _invlist_contains_cp(PL_in_some_fold, ender)))
14165 /* Here, folding, but the character isn't in a fold.
14167 * Start a new node if previous characters in the node were
14169 if (len && node_type != EXACT) {
14174 /* Here, continuing a node with non-folded characters. Add
14176 goto not_fold_common;
14178 else { /* Here, does participate in some fold */
14180 /* If this is the first character in the node, change its
14181 * type to folding. Otherwise, if this is the first
14182 * folding character in the node, close up the existing
14183 * node, so can start a new node with this one. */
14185 node_type = compute_EXACTish(pRExC_state);
14187 else if (node_type == EXACT) {
14192 if (UTF) { /* Use the folded value */
14193 if (UVCHR_IS_INVARIANT(ender)) {
14194 *(s)++ = (U8) toFOLD(ender);
14197 ender = _to_uni_fold_flags(
14201 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
14202 ? FOLD_FLAGS_NOMIX_ASCII
14207 && LIKELY(ender != GREEK_SMALL_LETTER_MU))
14209 /* U+B5 folds to the MU, so its possible for a
14210 * non-UTF-8 target to match it */
14211 requires_utf8_target = TRUE;
14217 /* Here is non-UTF8. First, see if the character's
14218 * fold differs between /d and /u. */
14219 if (PL_fold[ender] != PL_fold_latin1[ender]) {
14220 maybe_exactfu = FALSE;
14223 #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
14224 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
14225 || UNICODE_DOT_DOT_VERSION > 0)
14227 /* On non-ancient Unicode versions, this includes the
14228 * multi-char fold SHARP S to 'ss' */
14230 if ( UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)
14231 || ( isALPHA_FOLD_EQ(ender, 's')
14233 && isALPHA_FOLD_EQ(*(s-1), 's')))
14235 /* Here, we have one of the following:
14236 * a) a SHARP S. This folds to 'ss' only under
14237 * /u rules. If we are in that situation,
14238 * fold the SHARP S to 'ss'. See the comments
14239 * for join_exact() as to why we fold this
14240 * non-UTF at compile time, and no others.
14241 * b) 'ss'. When under /u, there's nothing
14242 * special needed to be done here. The
14243 * previous iteration handled the first 's',
14244 * and this iteration will handle the second.
14245 * If, on the otherhand it's not /u, we have
14246 * to exclude the possibility of moving to /u,
14247 * so that we won't generate an unwanted
14248 * match, unless, at runtime, the target
14249 * string is in UTF-8.
14253 maybe_exactfu = FALSE; /* Can't generate an
14254 EXACTFU node (unless we
14255 already are in one) */
14256 if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) {
14258 if (node_type == EXACTFU) {
14261 /* Let the code below add in the extra 's' */
14269 else if (UNLIKELY(ender == MICRO_SIGN)) {
14270 has_micro_sign = TRUE;
14273 *(s++) = (char) (DEPENDS_SEMANTICS)
14276 /* Under /u, the fold of any
14277 * character in the 0-255 range
14278 * happens to be its lowercase
14279 * equivalent, except for LATIN SMALL
14280 * LETTER SHARP S, which was handled
14281 * above, and the MICRO SIGN, whose
14282 * fold requires UTF-8 to represent.
14284 : toLOWER_L1(ender);
14286 } /* End of adding current character to the node */
14290 if (next_is_quantifier) {
14292 /* Here, the next input is a quantifier, and to get here,
14293 * the current character is the only one in the node. */
14297 } /* End of loop through literal characters */
14299 /* Here we have either exhausted the input or ran out of room in
14300 * the node. (If we encountered a character that can't be in the
14301 * node, transfer is made directly to <loopdone>, and so we
14302 * wouldn't have fallen off the end of the loop.) In the latter
14303 * case, we artificially have to split the node into two, because
14304 * we just don't have enough space to hold everything. This
14305 * creates a problem if the final character participates in a
14306 * multi-character fold in the non-final position, as a match that
14307 * should have occurred won't, due to the way nodes are matched,
14308 * and our artificial boundary. So back off until we find a non-
14309 * problematic character -- one that isn't at the beginning or
14310 * middle of such a fold. (Either it doesn't participate in any
14311 * folds, or appears only in the final position of all the folds it
14312 * does participate in.) A better solution with far fewer false
14313 * positives, and that would fill the nodes more completely, would
14314 * be to actually have available all the multi-character folds to
14315 * test against, and to back-off only far enough to be sure that
14316 * this node isn't ending with a partial one. <upper_parse> is set
14317 * further below (if we need to reparse the node) to include just
14318 * up through that final non-problematic character that this code
14319 * identifies, so when it is set to less than the full node, we can
14320 * skip the rest of this */
14321 if (FOLD && p < RExC_end && upper_parse == MAX_NODE_STRING_SIZE) {
14322 PERL_UINT_FAST8_T backup_count = 0;
14324 const STRLEN full_len = len;
14326 assert(len >= MAX_NODE_STRING_SIZE);
14328 /* Here, <s> points to just beyond where we have output the
14329 * final character of the node. Look backwards through the
14330 * string until find a non- problematic character */
14334 /* This has no multi-char folds to non-UTF characters */
14335 if (ASCII_FOLD_RESTRICTED) {
14339 while (--s >= s0 && IS_NON_FINAL_FOLD(*s)) {
14346 /* Point to the first byte of the final character */
14347 s = (char *) utf8_hop((U8 *) s, -1);
14349 while (s >= s0) { /* Search backwards until find
14350 a non-problematic char */
14351 if (UTF8_IS_INVARIANT(*s)) {
14353 /* There are no ascii characters that participate
14354 * in multi-char folds under /aa. In EBCDIC, the
14355 * non-ascii invariants are all control characters,
14356 * so don't ever participate in any folds. */
14357 if (ASCII_FOLD_RESTRICTED
14358 || ! IS_NON_FINAL_FOLD(*s))
14363 else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
14364 if (! IS_NON_FINAL_FOLD(EIGHT_BIT_UTF8_TO_NATIVE(
14370 else if (! _invlist_contains_cp(
14372 valid_utf8_to_uvchr((U8 *) s, NULL)))
14377 /* Here, the current character is problematic in that
14378 * it does occur in the non-final position of some
14379 * fold, so try the character before it, but have to
14380 * special case the very first byte in the string, so
14381 * we don't read outside the string */
14382 s = (s == s0) ? s -1 : (char *) utf8_hop((U8 *) s, -1);
14384 } /* End of loop backwards through the string */
14386 /* If there were only problematic characters in the string,
14387 * <s> will point to before s0, in which case the length
14388 * should be 0, otherwise include the length of the
14389 * non-problematic character just found */
14390 len = (s < s0) ? 0 : s - s0 + UTF8SKIP(s);
14393 /* Here, have found the final character, if any, that is
14394 * non-problematic as far as ending the node without splitting
14395 * it across a potential multi-char fold. <len> contains the
14396 * number of bytes in the node up-to and including that
14397 * character, or is 0 if there is no such character, meaning
14398 * the whole node contains only problematic characters. In
14399 * this case, give up and just take the node as-is. We can't
14406 /* Here, the node does contain some characters that aren't
14407 * problematic. If we didn't have to backup any, then the
14408 * final character in the node is non-problematic, and we
14409 * can take the node as-is */
14410 if (backup_count == 0) {
14413 else if (backup_count == 1) {
14415 /* If the final character is problematic, but the
14416 * penultimate is not, back-off that last character to
14417 * later start a new node with it */
14422 /* Here, the final non-problematic character is earlier
14423 * in the input than the penultimate character. What we do
14424 * is reparse from the beginning, going up only as far as
14425 * this final ok one, thus guaranteeing that the node ends
14426 * in an acceptable character. The reason we reparse is
14427 * that we know how far in the character is, but we don't
14428 * know how to correlate its position with the input parse.
14429 * An alternate implementation would be to build that
14430 * correlation as we go along during the original parse,
14431 * but that would entail extra work for every node, whereas
14432 * this code gets executed only when the string is too
14433 * large for the node, and the final two characters are
14434 * problematic, an infrequent occurrence. Yet another
14435 * possible strategy would be to save the tail of the
14436 * string, and the next time regatom is called, initialize
14437 * with that. The problem with this is that unless you
14438 * back off one more character, you won't be guaranteed
14439 * regatom will get called again, unless regbranch,
14440 * regpiece ... are also changed. If you do back off that
14441 * extra character, so that there is input guaranteed to
14442 * force calling regatom, you can't handle the case where
14443 * just the first character in the node is acceptable. I
14444 * (khw) decided to try this method which doesn't have that
14445 * pitfall; if performance issues are found, we can do a
14446 * combination of the current approach plus that one */
14452 } /* End of verifying node ends with an appropriate char */
14454 loopdone: /* Jumped to when encounters something that shouldn't be
14457 /* Free up any over-allocated space */
14458 change_engine_size(pRExC_state, - (initial_size - STR_SZ(len)));
14460 /* I (khw) don't know if you can get here with zero length, but the
14461 * old code handled this situation by creating a zero-length EXACT
14462 * node. Might as well be NOTHING instead */
14464 OP(REGNODE_p(ret)) = NOTHING;
14468 /* If the node type is EXACT here, check to see if it
14469 * should be EXACTL, or EXACT_ONLY8. */
14470 if (node_type == EXACT) {
14472 node_type = EXACTL;
14474 else if (requires_utf8_target) {
14475 node_type = EXACT_ONLY8;
14478 if ( UNLIKELY(has_micro_sign || has_ss)
14479 && (node_type == EXACTFU || ( node_type == EXACTF
14480 && maybe_exactfu)))
14481 { /* These two conditions are problematic in non-UTF-8
14484 node_type = EXACTFUP;
14486 else if (node_type == EXACTFL) {
14488 /* 'maybe_exactfu' is deliberately set above to
14489 * indicate this node type, where all code points in it
14491 if (maybe_exactfu) {
14492 node_type = EXACTFLU8;
14495 else if (node_type == EXACTF) { /* Means is /di */
14497 /* If 'maybe_exactfu' is clear, then we need to stay
14498 * /di. If it is set, it means there are no code
14499 * points that match differently depending on UTF8ness
14500 * of the target string, so it can become an EXACTFU
14502 if (! maybe_exactfu) {
14503 RExC_seen_d_op = TRUE;
14505 else if ( isALPHA_FOLD_EQ(* STRING(REGNODE_p(ret)), 's')
14506 || isALPHA_FOLD_EQ(ender, 's'))
14508 /* But, if the node begins or ends in an 's' we
14509 * have to defer changing it into an EXACTFU, as
14510 * the node could later get joined with another one
14511 * that ends or begins with 's' creating an 'ss'
14512 * sequence which would then wrongly match the
14513 * sharp s without the target being UTF-8. We
14514 * create a special node that we resolve later when
14515 * we join nodes together */
14517 node_type = EXACTFU_S_EDGE;
14520 node_type = EXACTFU;
14524 if (requires_utf8_target && node_type == EXACTFU) {
14525 node_type = EXACTFU_ONLY8;
14529 OP(REGNODE_p(ret)) = node_type;
14530 STR_LEN(REGNODE_p(ret)) = len;
14531 RExC_emit += STR_SZ(len);
14533 /* If the node isn't a single character, it can't be SIMPLE */
14534 if (len > ((UTF) ? UVCHR_SKIP(ender) : 1)) {
14538 *flagp |= HASWIDTH | maybe_SIMPLE;
14541 Set_Node_Length(REGNODE_p(ret), p - parse_start - 1);
14545 /* len is STRLEN which is unsigned, need to copy to signed */
14548 vFAIL("Internal disaster");
14551 } /* End of label 'defchar:' */
14553 } /* End of giant switch on input character */
14555 /* Position parse to next real character */
14556 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
14557 FALSE /* Don't force to /x */ );
14558 if ( *RExC_parse == '{'
14559 && OP(REGNODE_p(ret)) != SBOL && ! regcurly(RExC_parse))
14561 if (RExC_strict || new_regcurly(RExC_parse, RExC_end)) {
14563 vFAIL("Unescaped left brace in regex is illegal here");
14565 ckWARNreg(RExC_parse + 1, "Unescaped left brace in regex is"
14566 " passed through");
14574 S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr)
14576 /* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'. It
14577 * sets up the bitmap and any flags, removing those code points from the
14578 * inversion list, setting it to NULL should it become completely empty */
14582 PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST;
14583 assert(PL_regkind[OP(node)] == ANYOF);
14585 /* There is no bitmap for this node type */
14586 if (OP(node) == ANYOFH) {
14590 ANYOF_BITMAP_ZERO(node);
14591 if (*invlist_ptr) {
14593 /* This gets set if we actually need to modify things */
14594 bool change_invlist = FALSE;
14598 /* Start looking through *invlist_ptr */
14599 invlist_iterinit(*invlist_ptr);
14600 while (invlist_iternext(*invlist_ptr, &start, &end)) {
14604 if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) {
14605 ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP;
14608 /* Quit if are above what we should change */
14609 if (start >= NUM_ANYOF_CODE_POINTS) {
14613 change_invlist = TRUE;
14615 /* Set all the bits in the range, up to the max that we are doing */
14616 high = (end < NUM_ANYOF_CODE_POINTS - 1)
14618 : NUM_ANYOF_CODE_POINTS - 1;
14619 for (i = start; i <= (int) high; i++) {
14620 if (! ANYOF_BITMAP_TEST(node, i)) {
14621 ANYOF_BITMAP_SET(node, i);
14625 invlist_iterfinish(*invlist_ptr);
14627 /* Done with loop; remove any code points that are in the bitmap from
14628 * *invlist_ptr; similarly for code points above the bitmap if we have
14629 * a flag to match all of them anyways */
14630 if (change_invlist) {
14631 _invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr);
14633 if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
14634 _invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr);
14637 /* If have completely emptied it, remove it completely */
14638 if (_invlist_len(*invlist_ptr) == 0) {
14639 SvREFCNT_dec_NN(*invlist_ptr);
14640 *invlist_ptr = NULL;
14645 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
14646 Character classes ([:foo:]) can also be negated ([:^foo:]).
14647 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
14648 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
14649 but trigger failures because they are currently unimplemented. */
14651 #define POSIXCC_DONE(c) ((c) == ':')
14652 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
14653 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
14654 #define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';')
14656 #define WARNING_PREFIX "Assuming NOT a POSIX class since "
14657 #define NO_BLANKS_POSIX_WARNING "no blanks are allowed in one"
14658 #define SEMI_COLON_POSIX_WARNING "a semi-colon was found instead of a colon"
14660 #define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1)
14662 /* 'posix_warnings' and 'warn_text' are names of variables in the following
14664 #define ADD_POSIX_WARNING(p, text) STMT_START { \
14665 if (posix_warnings) { \
14666 if (! RExC_warn_text ) RExC_warn_text = \
14667 (AV *) sv_2mortal((SV *) newAV()); \
14668 av_push(RExC_warn_text, Perl_newSVpvf(aTHX_ \
14672 REPORT_LOCATION_ARGS(p))); \
14675 #define CLEAR_POSIX_WARNINGS() \
14677 if (posix_warnings && RExC_warn_text) \
14678 av_clear(RExC_warn_text); \
14681 #define CLEAR_POSIX_WARNINGS_AND_RETURN(ret) \
14683 CLEAR_POSIX_WARNINGS(); \
14688 S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state,
14690 const char * const s, /* Where the putative posix class begins.
14691 Normally, this is one past the '['. This
14692 parameter exists so it can be somewhere
14693 besides RExC_parse. */
14694 char ** updated_parse_ptr, /* Where to set the updated parse pointer, or
14696 AV ** posix_warnings, /* Where to place any generated warnings, or
14698 const bool check_only /* Don't die if error */
14701 /* This parses what the caller thinks may be one of the three POSIX
14703 * 1) a character class, like [:blank:]
14704 * 2) a collating symbol, like [. .]
14705 * 3) an equivalence class, like [= =]
14706 * In the latter two cases, it croaks if it finds a syntactically legal
14707 * one, as these are not handled by Perl.
14709 * The main purpose is to look for a POSIX character class. It returns:
14710 * a) the class number
14711 * if it is a completely syntactically and semantically legal class.
14712 * 'updated_parse_ptr', if not NULL, is set to point to just after the
14713 * closing ']' of the class
14714 * b) OOB_NAMEDCLASS
14715 * if it appears that one of the three POSIX constructs was meant, but
14716 * its specification was somehow defective. 'updated_parse_ptr', if
14717 * not NULL, is set to point to the character just after the end
14718 * character of the class. See below for handling of warnings.
14719 * c) NOT_MEANT_TO_BE_A_POSIX_CLASS
14720 * if it doesn't appear that a POSIX construct was intended.
14721 * 'updated_parse_ptr' is not changed. No warnings nor errors are
14724 * In b) there may be errors or warnings generated. If 'check_only' is
14725 * TRUE, then any errors are discarded. Warnings are returned to the
14726 * caller via an AV* created into '*posix_warnings' if it is not NULL. If
14727 * instead it is NULL, warnings are suppressed.
14729 * The reason for this function, and its complexity is that a bracketed
14730 * character class can contain just about anything. But it's easy to
14731 * mistype the very specific posix class syntax but yielding a valid
14732 * regular bracketed class, so it silently gets compiled into something
14733 * quite unintended.
14735 * The solution adopted here maintains backward compatibility except that
14736 * it adds a warning if it looks like a posix class was intended but
14737 * improperly specified. The warning is not raised unless what is input
14738 * very closely resembles one of the 14 legal posix classes. To do this,
14739 * it uses fuzzy parsing. It calculates how many single-character edits it
14740 * would take to transform what was input into a legal posix class. Only
14741 * if that number is quite small does it think that the intention was a
14742 * posix class. Obviously these are heuristics, and there will be cases
14743 * where it errs on one side or another, and they can be tweaked as
14744 * experience informs.
14746 * The syntax for a legal posix class is:
14748 * qr/(?xa: \[ : \^? [[:lower:]]{4,6} : \] )/
14750 * What this routine considers syntactically to be an intended posix class
14751 * is this (the comments indicate some restrictions that the pattern
14754 * qr/(?x: \[? # The left bracket, possibly
14756 * \h* # possibly followed by blanks
14757 * (?: \^ \h* )? # possibly a misplaced caret
14758 * [:;]? # The opening class character,
14759 * # possibly omitted. A typo
14760 * # semi-colon can also be used.
14762 * \^? # possibly a correctly placed
14763 * # caret, but not if there was also
14764 * # a misplaced one
14766 * .{3,15} # The class name. If there are
14767 * # deviations from the legal syntax,
14768 * # its edit distance must be close
14769 * # to a real class name in order
14770 * # for it to be considered to be
14771 * # an intended posix class.
14773 * [[:punct:]]? # The closing class character,
14774 * # possibly omitted. If not a colon
14775 * # nor semi colon, the class name
14776 * # must be even closer to a valid
14779 * \]? # The right bracket, possibly
14783 * In the above, \h must be ASCII-only.
14785 * These are heuristics, and can be tweaked as field experience dictates.
14786 * There will be cases when someone didn't intend to specify a posix class
14787 * that this warns as being so. The goal is to minimize these, while
14788 * maximizing the catching of things intended to be a posix class that
14789 * aren't parsed as such.
14793 const char * const e = RExC_end;
14794 unsigned complement = 0; /* If to complement the class */
14795 bool found_problem = FALSE; /* Assume OK until proven otherwise */
14796 bool has_opening_bracket = FALSE;
14797 bool has_opening_colon = FALSE;
14798 int class_number = OOB_NAMEDCLASS; /* Out-of-bounds until find
14800 const char * possible_end = NULL; /* used for a 2nd parse pass */
14801 const char* name_start; /* ptr to class name first char */
14803 /* If the number of single-character typos the input name is away from a
14804 * legal name is no more than this number, it is considered to have meant
14805 * the legal name */
14806 int max_distance = 2;
14808 /* to store the name. The size determines the maximum length before we
14809 * decide that no posix class was intended. Should be at least
14810 * sizeof("alphanumeric") */
14812 STATIC_ASSERT_DECL(C_ARRAY_LENGTH(input_text) >= sizeof "alphanumeric");
14814 PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX;
14816 CLEAR_POSIX_WARNINGS();
14819 return NOT_MEANT_TO_BE_A_POSIX_CLASS;
14822 if (*(p - 1) != '[') {
14823 ADD_POSIX_WARNING(p, "it doesn't start with a '['");
14824 found_problem = TRUE;
14827 has_opening_bracket = TRUE;
14830 /* They could be confused and think you can put spaces between the
14833 found_problem = TRUE;
14837 } while (p < e && isBLANK(*p));
14839 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14842 /* For [. .] and [= =]. These are quite different internally from [: :],
14843 * so they are handled separately. */
14844 if (POSIXCC_NOTYET(*p) && p < e - 3) /* 1 for the close, and 1 for the ']'
14845 and 1 for at least one char in it
14848 const char open_char = *p;
14849 const char * temp_ptr = p + 1;
14851 /* These two constructs are not handled by perl, and if we find a
14852 * syntactically valid one, we croak. khw, who wrote this code, finds
14853 * this explanation of them very unclear:
14854 * http://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html
14855 * And searching the rest of the internet wasn't very helpful either.
14856 * It looks like just about any byte can be in these constructs,
14857 * depending on the locale. But unless the pattern is being compiled
14858 * under /l, which is very rare, Perl runs under the C or POSIX locale.
14859 * In that case, it looks like [= =] isn't allowed at all, and that
14860 * [. .] could be any single code point, but for longer strings the
14861 * constituent characters would have to be the ASCII alphabetics plus
14862 * the minus-hyphen. Any sensible locale definition would limit itself
14863 * to these. And any portable one definitely should. Trying to parse
14864 * the general case is a nightmare (see [perl #127604]). So, this code
14865 * looks only for interiors of these constructs that match:
14867 * Using \w relaxes the apparent rules a little, without adding much
14868 * danger of mistaking something else for one of these constructs.
14870 * [. .] in some implementations described on the internet is usable to
14871 * escape a character that otherwise is special in bracketed character
14872 * classes. For example [.].] means a literal right bracket instead of
14873 * the ending of the class
14875 * [= =] can legitimately contain a [. .] construct, but we don't
14876 * handle this case, as that [. .] construct will later get parsed
14877 * itself and croak then. And [= =] is checked for even when not under
14878 * /l, as Perl has long done so.
14880 * The code below relies on there being a trailing NUL, so it doesn't
14881 * have to keep checking if the parse ptr < e.
14883 if (temp_ptr[1] == open_char) {
14886 else while ( temp_ptr < e
14887 && (isWORDCHAR(*temp_ptr) || *temp_ptr == '-'))
14892 if (*temp_ptr == open_char) {
14894 if (*temp_ptr == ']') {
14896 if (! found_problem && ! check_only) {
14897 RExC_parse = (char *) temp_ptr;
14898 vFAIL3("POSIX syntax [%c %c] is reserved for future "
14899 "extensions", open_char, open_char);
14902 /* Here, the syntax wasn't completely valid, or else the call
14903 * is to check-only */
14904 if (updated_parse_ptr) {
14905 *updated_parse_ptr = (char *) temp_ptr;
14908 CLEAR_POSIX_WARNINGS_AND_RETURN(OOB_NAMEDCLASS);
14912 /* If we find something that started out to look like one of these
14913 * constructs, but isn't, we continue below so that it can be checked
14914 * for being a class name with a typo of '.' or '=' instead of a colon.
14918 /* Here, we think there is a possibility that a [: :] class was meant, and
14919 * we have the first real character. It could be they think the '^' comes
14922 found_problem = TRUE;
14923 ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon");
14928 found_problem = TRUE;
14932 } while (p < e && isBLANK(*p));
14934 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14938 /* But the first character should be a colon, which they could have easily
14939 * mistyped on a qwerty keyboard as a semi-colon (and which may be hard to
14940 * distinguish from a colon, so treat that as a colon). */
14943 has_opening_colon = TRUE;
14945 else if (*p == ';') {
14946 found_problem = TRUE;
14948 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
14949 has_opening_colon = TRUE;
14952 found_problem = TRUE;
14953 ADD_POSIX_WARNING(p, "there must be a starting ':'");
14955 /* Consider an initial punctuation (not one of the recognized ones) to
14956 * be a left terminator */
14957 if (*p != '^' && *p != ']' && isPUNCT(*p)) {
14962 /* They may think that you can put spaces between the components */
14964 found_problem = TRUE;
14968 } while (p < e && isBLANK(*p));
14970 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14975 /* We consider something like [^:^alnum:]] to not have been intended to
14976 * be a posix class, but XXX maybe we should */
14978 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
14985 /* Again, they may think that you can put spaces between the components */
14987 found_problem = TRUE;
14991 } while (p < e && isBLANK(*p));
14993 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14998 /* XXX This ']' may be a typo, and something else was meant. But
14999 * treating it as such creates enough complications, that that
15000 * possibility isn't currently considered here. So we assume that the
15001 * ']' is what is intended, and if we've already found an initial '[',
15002 * this leaves this construct looking like [:] or [:^], which almost
15003 * certainly weren't intended to be posix classes */
15004 if (has_opening_bracket) {
15005 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15008 /* But this function can be called when we parse the colon for
15009 * something like qr/[alpha:]]/, so we back up to look for the
15014 found_problem = TRUE;
15015 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15017 else if (*p != ':') {
15019 /* XXX We are currently very restrictive here, so this code doesn't
15020 * consider the possibility that, say, /[alpha.]]/ was intended to
15021 * be a posix class. */
15022 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15025 /* Here we have something like 'foo:]'. There was no initial colon,
15026 * and we back up over 'foo. XXX Unlike the going forward case, we
15027 * don't handle typos of non-word chars in the middle */
15028 has_opening_colon = FALSE;
15031 while (p > RExC_start && isWORDCHAR(*p)) {
15036 /* Here, we have positioned ourselves to where we think the first
15037 * character in the potential class is */
15040 /* Now the interior really starts. There are certain key characters that
15041 * can end the interior, or these could just be typos. To catch both
15042 * cases, we may have to do two passes. In the first pass, we keep on
15043 * going unless we come to a sequence that matches
15044 * qr/ [[:punct:]] [[:blank:]]* \] /xa
15045 * This means it takes a sequence to end the pass, so two typos in a row if
15046 * that wasn't what was intended. If the class is perfectly formed, just
15047 * this one pass is needed. We also stop if there are too many characters
15048 * being accumulated, but this number is deliberately set higher than any
15049 * real class. It is set high enough so that someone who thinks that
15050 * 'alphanumeric' is a correct name would get warned that it wasn't.
15051 * While doing the pass, we keep track of where the key characters were in
15052 * it. If we don't find an end to the class, and one of the key characters
15053 * was found, we redo the pass, but stop when we get to that character.
15054 * Thus the key character was considered a typo in the first pass, but a
15055 * terminator in the second. If two key characters are found, we stop at
15056 * the second one in the first pass. Again this can miss two typos, but
15057 * catches a single one
15059 * In the first pass, 'possible_end' starts as NULL, and then gets set to
15060 * point to the first key character. For the second pass, it starts as -1.
15066 bool has_blank = FALSE;
15067 bool has_upper = FALSE;
15068 bool has_terminating_colon = FALSE;
15069 bool has_terminating_bracket = FALSE;
15070 bool has_semi_colon = FALSE;
15071 unsigned int name_len = 0;
15072 int punct_count = 0;
15076 /* Squeeze out blanks when looking up the class name below */
15077 if (isBLANK(*p) ) {
15079 found_problem = TRUE;
15084 /* The name will end with a punctuation */
15086 const char * peek = p + 1;
15088 /* Treat any non-']' punctuation followed by a ']' (possibly
15089 * with intervening blanks) as trying to terminate the class.
15090 * ']]' is very likely to mean a class was intended (but
15091 * missing the colon), but the warning message that gets
15092 * generated shows the error position better if we exit the
15093 * loop at the bottom (eventually), so skip it here. */
15095 if (peek < e && isBLANK(*peek)) {
15097 found_problem = TRUE;
15100 } while (peek < e && isBLANK(*peek));
15103 if (peek < e && *peek == ']') {
15104 has_terminating_bracket = TRUE;
15106 has_terminating_colon = TRUE;
15108 else if (*p == ';') {
15109 has_semi_colon = TRUE;
15110 has_terminating_colon = TRUE;
15113 found_problem = TRUE;
15120 /* Here we have punctuation we thought didn't end the class.
15121 * Keep track of the position of the key characters that are
15122 * more likely to have been class-enders */
15123 if (*p == ']' || *p == '[' || *p == ':' || *p == ';') {
15125 /* Allow just one such possible class-ender not actually
15126 * ending the class. */
15127 if (possible_end) {
15133 /* If we have too many punctuation characters, no use in
15135 if (++punct_count > max_distance) {
15139 /* Treat the punctuation as a typo. */
15140 input_text[name_len++] = *p;
15143 else if (isUPPER(*p)) { /* Use lowercase for lookup */
15144 input_text[name_len++] = toLOWER(*p);
15146 found_problem = TRUE;
15148 } else if (! UTF || UTF8_IS_INVARIANT(*p)) {
15149 input_text[name_len++] = *p;
15153 input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL);
15157 /* The declaration of 'input_text' is how long we allow a potential
15158 * class name to be, before saying they didn't mean a class name at
15160 if (name_len >= C_ARRAY_LENGTH(input_text)) {
15165 /* We get to here when the possible class name hasn't been properly
15166 * terminated before:
15167 * 1) we ran off the end of the pattern; or
15168 * 2) found two characters, each of which might have been intended to
15169 * be the name's terminator
15170 * 3) found so many punctuation characters in the purported name,
15171 * that the edit distance to a valid one is exceeded
15172 * 4) we decided it was more characters than anyone could have
15173 * intended to be one. */
15175 found_problem = TRUE;
15177 /* In the final two cases, we know that looking up what we've
15178 * accumulated won't lead to a match, even a fuzzy one. */
15179 if ( name_len >= C_ARRAY_LENGTH(input_text)
15180 || punct_count > max_distance)
15182 /* If there was an intermediate key character that could have been
15183 * an intended end, redo the parse, but stop there */
15184 if (possible_end && possible_end != (char *) -1) {
15185 possible_end = (char *) -1; /* Special signal value to say
15186 we've done a first pass */
15191 /* Otherwise, it can't have meant to have been a class */
15192 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15195 /* If we ran off the end, and the final character was a punctuation
15196 * one, back up one, to look at that final one just below. Later, we
15197 * will restore the parse pointer if appropriate */
15198 if (name_len && p == e && isPUNCT(*(p-1))) {
15203 if (p < e && isPUNCT(*p)) {
15205 has_terminating_bracket = TRUE;
15207 /* If this is a 2nd ']', and the first one is just below this
15208 * one, consider that to be the real terminator. This gives a
15209 * uniform and better positioning for the warning message */
15211 && possible_end != (char *) -1
15212 && *possible_end == ']'
15213 && name_len && input_text[name_len - 1] == ']')
15218 /* And this is actually equivalent to having done the 2nd
15219 * pass now, so set it to not try again */
15220 possible_end = (char *) -1;
15225 has_terminating_colon = TRUE;
15227 else if (*p == ';') {
15228 has_semi_colon = TRUE;
15229 has_terminating_colon = TRUE;
15237 /* Here, we have a class name to look up. We can short circuit the
15238 * stuff below for short names that can't possibly be meant to be a
15239 * class name. (We can do this on the first pass, as any second pass
15240 * will yield an even shorter name) */
15241 if (name_len < 3) {
15242 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15245 /* Find which class it is. Initially switch on the length of the name.
15247 switch (name_len) {
15249 if (memEQs(name_start, 4, "word")) {
15250 /* this is not POSIX, this is the Perl \w */
15251 class_number = ANYOF_WORDCHAR;
15255 /* Names all of length 5: alnum alpha ascii blank cntrl digit
15256 * graph lower print punct space upper
15257 * Offset 4 gives the best switch position. */
15258 switch (name_start[4]) {
15260 if (memBEGINs(name_start, 5, "alph")) /* alpha */
15261 class_number = ANYOF_ALPHA;
15264 if (memBEGINs(name_start, 5, "spac")) /* space */
15265 class_number = ANYOF_SPACE;
15268 if (memBEGINs(name_start, 5, "grap")) /* graph */
15269 class_number = ANYOF_GRAPH;
15272 if (memBEGINs(name_start, 5, "asci")) /* ascii */
15273 class_number = ANYOF_ASCII;
15276 if (memBEGINs(name_start, 5, "blan")) /* blank */
15277 class_number = ANYOF_BLANK;
15280 if (memBEGINs(name_start, 5, "cntr")) /* cntrl */
15281 class_number = ANYOF_CNTRL;
15284 if (memBEGINs(name_start, 5, "alnu")) /* alnum */
15285 class_number = ANYOF_ALPHANUMERIC;
15288 if (memBEGINs(name_start, 5, "lowe")) /* lower */
15289 class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER;
15290 else if (memBEGINs(name_start, 5, "uppe")) /* upper */
15291 class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER;
15294 if (memBEGINs(name_start, 5, "digi")) /* digit */
15295 class_number = ANYOF_DIGIT;
15296 else if (memBEGINs(name_start, 5, "prin")) /* print */
15297 class_number = ANYOF_PRINT;
15298 else if (memBEGINs(name_start, 5, "punc")) /* punct */
15299 class_number = ANYOF_PUNCT;
15304 if (memEQs(name_start, 6, "xdigit"))
15305 class_number = ANYOF_XDIGIT;
15309 /* If the name exactly matches a posix class name the class number will
15310 * here be set to it, and the input almost certainly was meant to be a
15311 * posix class, so we can skip further checking. If instead the syntax
15312 * is exactly correct, but the name isn't one of the legal ones, we
15313 * will return that as an error below. But if neither of these apply,
15314 * it could be that no posix class was intended at all, or that one
15315 * was, but there was a typo. We tease these apart by doing fuzzy
15316 * matching on the name */
15317 if (class_number == OOB_NAMEDCLASS && found_problem) {
15318 const UV posix_names[][6] = {
15319 { 'a', 'l', 'n', 'u', 'm' },
15320 { 'a', 'l', 'p', 'h', 'a' },
15321 { 'a', 's', 'c', 'i', 'i' },
15322 { 'b', 'l', 'a', 'n', 'k' },
15323 { 'c', 'n', 't', 'r', 'l' },
15324 { 'd', 'i', 'g', 'i', 't' },
15325 { 'g', 'r', 'a', 'p', 'h' },
15326 { 'l', 'o', 'w', 'e', 'r' },
15327 { 'p', 'r', 'i', 'n', 't' },
15328 { 'p', 'u', 'n', 'c', 't' },
15329 { 's', 'p', 'a', 'c', 'e' },
15330 { 'u', 'p', 'p', 'e', 'r' },
15331 { 'w', 'o', 'r', 'd' },
15332 { 'x', 'd', 'i', 'g', 'i', 't' }
15334 /* The names of the above all have added NULs to make them the same
15335 * size, so we need to also have the real lengths */
15336 const UV posix_name_lengths[] = {
15337 sizeof("alnum") - 1,
15338 sizeof("alpha") - 1,
15339 sizeof("ascii") - 1,
15340 sizeof("blank") - 1,
15341 sizeof("cntrl") - 1,
15342 sizeof("digit") - 1,
15343 sizeof("graph") - 1,
15344 sizeof("lower") - 1,
15345 sizeof("print") - 1,
15346 sizeof("punct") - 1,
15347 sizeof("space") - 1,
15348 sizeof("upper") - 1,
15349 sizeof("word") - 1,
15350 sizeof("xdigit")- 1
15353 int temp_max = max_distance; /* Use a temporary, so if we
15354 reparse, we haven't changed the
15357 /* Use a smaller max edit distance if we are missing one of the
15359 if ( has_opening_bracket + has_opening_colon < 2
15360 || has_terminating_bracket + has_terminating_colon < 2)
15365 /* See if the input name is close to a legal one */
15366 for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) {
15368 /* Short circuit call if the lengths are too far apart to be
15370 if (abs( (int) (name_len - posix_name_lengths[i]))
15376 if (edit_distance(input_text,
15379 posix_name_lengths[i],
15383 { /* If it is close, it probably was intended to be a class */
15384 goto probably_meant_to_be;
15388 /* Here the input name is not close enough to a valid class name
15389 * for us to consider it to be intended to be a posix class. If
15390 * we haven't already done so, and the parse found a character that
15391 * could have been terminators for the name, but which we absorbed
15392 * as typos during the first pass, repeat the parse, signalling it
15393 * to stop at that character */
15394 if (possible_end && possible_end != (char *) -1) {
15395 possible_end = (char *) -1;
15400 /* Here neither pass found a close-enough class name */
15401 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15404 probably_meant_to_be:
15406 /* Here we think that a posix specification was intended. Update any
15408 if (updated_parse_ptr) {
15409 *updated_parse_ptr = (char *) p;
15412 /* If a posix class name was intended but incorrectly specified, we
15413 * output or return the warnings */
15414 if (found_problem) {
15416 /* We set flags for these issues in the parse loop above instead of
15417 * adding them to the list of warnings, because we can parse it
15418 * twice, and we only want one warning instance */
15420 ADD_POSIX_WARNING(p, "the name must be all lowercase letters");
15423 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15425 if (has_semi_colon) {
15426 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15428 else if (! has_terminating_colon) {
15429 ADD_POSIX_WARNING(p, "there is no terminating ':'");
15431 if (! has_terminating_bracket) {
15432 ADD_POSIX_WARNING(p, "there is no terminating ']'");
15435 if ( posix_warnings
15437 && av_top_index(RExC_warn_text) > -1)
15439 *posix_warnings = RExC_warn_text;
15442 else if (class_number != OOB_NAMEDCLASS) {
15443 /* If it is a known class, return the class. The class number
15444 * #defines are structured so each complement is +1 to the normal
15446 CLEAR_POSIX_WARNINGS_AND_RETURN(class_number + complement);
15448 else if (! check_only) {
15450 /* Here, it is an unrecognized class. This is an error (unless the
15451 * call is to check only, which we've already handled above) */
15452 const char * const complement_string = (complement)
15455 RExC_parse = (char *) p;
15456 vFAIL3utf8f("POSIX class [:%s%" UTF8f ":] unknown",
15458 UTF8fARG(UTF, RExC_parse - name_start - 2, name_start));
15462 return OOB_NAMEDCLASS;
15464 #undef ADD_POSIX_WARNING
15466 STATIC unsigned int
15467 S_regex_set_precedence(const U8 my_operator) {
15469 /* Returns the precedence in the (?[...]) construct of the input operator,
15470 * specified by its character representation. The precedence follows
15471 * general Perl rules, but it extends this so that ')' and ']' have (low)
15472 * precedence even though they aren't really operators */
15474 switch (my_operator) {
15490 NOT_REACHED; /* NOTREACHED */
15491 return 0; /* Silence compiler warning */
15494 STATIC regnode_offset
15495 S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist,
15496 I32 *flagp, U32 depth,
15497 char * const oregcomp_parse)
15499 /* Handle the (?[...]) construct to do set operations */
15501 U8 curchar; /* Current character being parsed */
15502 UV start, end; /* End points of code point ranges */
15503 SV* final = NULL; /* The end result inversion list */
15504 SV* result_string; /* 'final' stringified */
15505 AV* stack; /* stack of operators and operands not yet
15507 AV* fence_stack = NULL; /* A stack containing the positions in
15508 'stack' of where the undealt-with left
15509 parens would be if they were actually
15511 /* The 'volatile' is a workaround for an optimiser bug
15512 * in Solaris Studio 12.3. See RT #127455 */
15513 volatile IV fence = 0; /* Position of where most recent undealt-
15514 with left paren in stack is; -1 if none.
15516 STRLEN len; /* Temporary */
15517 regnode_offset node; /* Temporary, and final regnode returned by
15519 const bool save_fold = FOLD; /* Temporary */
15520 char *save_end, *save_parse; /* Temporaries */
15521 const bool in_locale = LOC; /* we turn off /l during processing */
15523 GET_RE_DEBUG_FLAGS_DECL;
15525 PERL_ARGS_ASSERT_HANDLE_REGEX_SETS;
15527 DEBUG_PARSE("xcls");
15530 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
15533 /* The use of this operator implies /u. This is required so that the
15534 * compile time values are valid in all runtime cases */
15535 REQUIRE_UNI_RULES(flagp, 0);
15537 ckWARNexperimental(RExC_parse,
15538 WARN_EXPERIMENTAL__REGEX_SETS,
15539 "The regex_sets feature is experimental");
15541 /* Everything in this construct is a metacharacter. Operands begin with
15542 * either a '\' (for an escape sequence), or a '[' for a bracketed
15543 * character class. Any other character should be an operator, or
15544 * parenthesis for grouping. Both types of operands are handled by calling
15545 * regclass() to parse them. It is called with a parameter to indicate to
15546 * return the computed inversion list. The parsing here is implemented via
15547 * a stack. Each entry on the stack is a single character representing one
15548 * of the operators; or else a pointer to an operand inversion list. */
15550 #define IS_OPERATOR(a) SvIOK(a)
15551 #define IS_OPERAND(a) (! IS_OPERATOR(a))
15553 /* The stack is kept in Łukasiewicz order. (That's pronounced similar
15554 * to luke-a-shave-itch (or -itz), but people who didn't want to bother
15555 * with pronouncing it called it Reverse Polish instead, but now that YOU
15556 * know how to pronounce it you can use the correct term, thus giving due
15557 * credit to the person who invented it, and impressing your geek friends.
15558 * Wikipedia says that the pronounciation of "Ł" has been changing so that
15559 * it is now more like an English initial W (as in wonk) than an L.)
15561 * This means that, for example, 'a | b & c' is stored on the stack as
15569 * where the numbers in brackets give the stack [array] element number.
15570 * In this implementation, parentheses are not stored on the stack.
15571 * Instead a '(' creates a "fence" so that the part of the stack below the
15572 * fence is invisible except to the corresponding ')' (this allows us to
15573 * replace testing for parens, by using instead subtraction of the fence
15574 * position). As new operands are processed they are pushed onto the stack
15575 * (except as noted in the next paragraph). New operators of higher
15576 * precedence than the current final one are inserted on the stack before
15577 * the lhs operand (so that when the rhs is pushed next, everything will be
15578 * in the correct positions shown above. When an operator of equal or
15579 * lower precedence is encountered in parsing, all the stacked operations
15580 * of equal or higher precedence are evaluated, leaving the result as the
15581 * top entry on the stack. This makes higher precedence operations
15582 * evaluate before lower precedence ones, and causes operations of equal
15583 * precedence to left associate.
15585 * The only unary operator '!' is immediately pushed onto the stack when
15586 * encountered. When an operand is encountered, if the top of the stack is
15587 * a '!", the complement is immediately performed, and the '!' popped. The
15588 * resulting value is treated as a new operand, and the logic in the
15589 * previous paragraph is executed. Thus in the expression
15591 * the stack looks like
15597 * as 'b' gets parsed, the latter gets evaluated to '!b', and the stack
15604 * A ')' is treated as an operator with lower precedence than all the
15605 * aforementioned ones, which causes all operations on the stack above the
15606 * corresponding '(' to be evaluated down to a single resultant operand.
15607 * Then the fence for the '(' is removed, and the operand goes through the
15608 * algorithm above, without the fence.
15610 * A separate stack is kept of the fence positions, so that the position of
15611 * the latest so-far unbalanced '(' is at the top of it.
15613 * The ']' ending the construct is treated as the lowest operator of all,
15614 * so that everything gets evaluated down to a single operand, which is the
15617 sv_2mortal((SV *)(stack = newAV()));
15618 sv_2mortal((SV *)(fence_stack = newAV()));
15620 while (RExC_parse < RExC_end) {
15621 I32 top_index; /* Index of top-most element in 'stack' */
15622 SV** top_ptr; /* Pointer to top 'stack' element */
15623 SV* current = NULL; /* To contain the current inversion list
15625 SV* only_to_avoid_leaks;
15627 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
15628 TRUE /* Force /x */ );
15629 if (RExC_parse >= RExC_end) { /* Fail */
15633 curchar = UCHARAT(RExC_parse);
15637 #ifdef ENABLE_REGEX_SETS_DEBUGGING
15638 /* Enable with -Accflags=-DENABLE_REGEX_SETS_DEBUGGING */
15639 DEBUG_U(dump_regex_sets_structures(pRExC_state,
15640 stack, fence, fence_stack));
15643 top_index = av_tindex_skip_len_mg(stack);
15646 SV** stacked_ptr; /* Ptr to something already on 'stack' */
15647 char stacked_operator; /* The topmost operator on the 'stack'. */
15648 SV* lhs; /* Operand to the left of the operator */
15649 SV* rhs; /* Operand to the right of the operator */
15650 SV* fence_ptr; /* Pointer to top element of the fence
15655 if ( RExC_parse < RExC_end - 2
15656 && UCHARAT(RExC_parse + 1) == '?'
15657 && UCHARAT(RExC_parse + 2) == '^')
15659 /* If is a '(?', could be an embedded '(?^flags:(?[...])'.
15660 * This happens when we have some thing like
15662 * my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
15664 * qr/(?[ \p{Digit} & $thai_or_lao ])/;
15666 * Here we would be handling the interpolated
15667 * '$thai_or_lao'. We handle this by a recursive call to
15668 * ourselves which returns the inversion list the
15669 * interpolated expression evaluates to. We use the flags
15670 * from the interpolated pattern. */
15671 U32 save_flags = RExC_flags;
15672 const char * save_parse;
15674 RExC_parse += 2; /* Skip past the '(?' */
15675 save_parse = RExC_parse;
15677 /* Parse the flags for the '(?'. We already know the first
15678 * flag to parse is a '^' */
15679 parse_lparen_question_flags(pRExC_state);
15681 if ( RExC_parse >= RExC_end - 4
15682 || UCHARAT(RExC_parse) != ':'
15683 || UCHARAT(++RExC_parse) != '('
15684 || UCHARAT(++RExC_parse) != '?'
15685 || UCHARAT(++RExC_parse) != '[')
15688 /* In combination with the above, this moves the
15689 * pointer to the point just after the first erroneous
15691 if (RExC_parse >= RExC_end - 4) {
15692 RExC_parse = RExC_end;
15694 else if (RExC_parse != save_parse) {
15695 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
15697 vFAIL("Expecting '(?flags:(?[...'");
15700 /* Recurse, with the meat of the embedded expression */
15702 (void) handle_regex_sets(pRExC_state, ¤t, flagp,
15703 depth+1, oregcomp_parse);
15705 /* Here, 'current' contains the embedded expression's
15706 * inversion list, and RExC_parse points to the trailing
15707 * ']'; the next character should be the ')' */
15709 if (UCHARAT(RExC_parse) != ')')
15710 vFAIL("Expecting close paren for nested extended charclass");
15712 /* Then the ')' matching the original '(' handled by this
15713 * case: statement */
15715 if (UCHARAT(RExC_parse) != ')')
15716 vFAIL("Expecting close paren for wrapper for nested extended charclass");
15718 RExC_flags = save_flags;
15719 goto handle_operand;
15722 /* A regular '('. Look behind for illegal syntax */
15723 if (top_index - fence >= 0) {
15724 /* If the top entry on the stack is an operator, it had
15725 * better be a '!', otherwise the entry below the top
15726 * operand should be an operator */
15727 if ( ! (top_ptr = av_fetch(stack, top_index, FALSE))
15728 || (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!')
15729 || ( IS_OPERAND(*top_ptr)
15730 && ( top_index - fence < 1
15731 || ! (stacked_ptr = av_fetch(stack,
15734 || ! IS_OPERATOR(*stacked_ptr))))
15737 vFAIL("Unexpected '(' with no preceding operator");
15741 /* Stack the position of this undealt-with left paren */
15742 av_push(fence_stack, newSViv(fence));
15743 fence = top_index + 1;
15747 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
15748 * multi-char folds are allowed. */
15749 if (!regclass(pRExC_state, flagp, depth+1,
15750 TRUE, /* means parse just the next thing */
15751 FALSE, /* don't allow multi-char folds */
15752 FALSE, /* don't silence non-portable warnings. */
15754 FALSE, /* Require return to be an ANYOF */
15757 FAIL2("panic: regclass returned failure to handle_sets, "
15758 "flags=%#" UVxf, (UV) *flagp);
15761 /* regclass() will return with parsing just the \ sequence,
15762 * leaving the parse pointer at the next thing to parse */
15764 goto handle_operand;
15766 case '[': /* Is a bracketed character class */
15768 /* See if this is a [:posix:] class. */
15769 bool is_posix_class = (OOB_NAMEDCLASS
15770 < handle_possible_posix(pRExC_state,
15774 TRUE /* checking only */));
15775 /* If it is a posix class, leave the parse pointer at the '['
15776 * to fool regclass() into thinking it is part of a
15777 * '[[:posix:]]'. */
15778 if (! is_posix_class) {
15782 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
15783 * multi-char folds are allowed. */
15784 if (!regclass(pRExC_state, flagp, depth+1,
15785 is_posix_class, /* parse the whole char
15786 class only if not a
15788 FALSE, /* don't allow multi-char folds */
15789 TRUE, /* silence non-portable warnings. */
15791 FALSE, /* Require return to be an ANYOF */
15794 FAIL2("panic: regclass returned failure to handle_sets, "
15795 "flags=%#" UVxf, (UV) *flagp);
15802 /* function call leaves parse pointing to the ']', except if we
15804 if (is_posix_class) {
15808 goto handle_operand;
15812 if (top_index >= 1) {
15813 goto join_operators;
15816 /* Only a single operand on the stack: are done */
15820 if (av_tindex_skip_len_mg(fence_stack) < 0) {
15821 if (UCHARAT(RExC_parse - 1) == ']') {
15825 vFAIL("Unexpected ')'");
15828 /* If nothing after the fence, is missing an operand */
15829 if (top_index - fence < 0) {
15833 /* If at least two things on the stack, treat this as an
15835 if (top_index - fence >= 1) {
15836 goto join_operators;
15839 /* Here only a single thing on the fenced stack, and there is a
15840 * fence. Get rid of it */
15841 fence_ptr = av_pop(fence_stack);
15843 fence = SvIV(fence_ptr);
15844 SvREFCNT_dec_NN(fence_ptr);
15851 /* Having gotten rid of the fence, we pop the operand at the
15852 * stack top and process it as a newly encountered operand */
15853 current = av_pop(stack);
15854 if (IS_OPERAND(current)) {
15855 goto handle_operand;
15867 /* These binary operators should have a left operand already
15869 if ( top_index - fence < 0
15870 || top_index - fence == 1
15871 || ( ! (top_ptr = av_fetch(stack, top_index, FALSE)))
15872 || ! IS_OPERAND(*top_ptr))
15874 goto unexpected_binary;
15877 /* If only the one operand is on the part of the stack visible
15878 * to us, we just place this operator in the proper position */
15879 if (top_index - fence < 2) {
15881 /* Place the operator before the operand */
15883 SV* lhs = av_pop(stack);
15884 av_push(stack, newSVuv(curchar));
15885 av_push(stack, lhs);
15889 /* But if there is something else on the stack, we need to
15890 * process it before this new operator if and only if the
15891 * stacked operation has equal or higher precedence than the
15896 /* The operator on the stack is supposed to be below both its
15898 if ( ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE))
15899 || IS_OPERAND(*stacked_ptr))
15901 /* But if not, it's legal and indicates we are completely
15902 * done if and only if we're currently processing a ']',
15903 * which should be the final thing in the expression */
15904 if (curchar == ']') {
15910 vFAIL2("Unexpected binary operator '%c' with no "
15911 "preceding operand", curchar);
15913 stacked_operator = (char) SvUV(*stacked_ptr);
15915 if (regex_set_precedence(curchar)
15916 > regex_set_precedence(stacked_operator))
15918 /* Here, the new operator has higher precedence than the
15919 * stacked one. This means we need to add the new one to
15920 * the stack to await its rhs operand (and maybe more
15921 * stuff). We put it before the lhs operand, leaving
15922 * untouched the stacked operator and everything below it
15924 lhs = av_pop(stack);
15925 assert(IS_OPERAND(lhs));
15927 av_push(stack, newSVuv(curchar));
15928 av_push(stack, lhs);
15932 /* Here, the new operator has equal or lower precedence than
15933 * what's already there. This means the operation already
15934 * there should be performed now, before the new one. */
15936 rhs = av_pop(stack);
15937 if (! IS_OPERAND(rhs)) {
15939 /* This can happen when a ! is not followed by an operand,
15940 * like in /(?[\t &!])/ */
15944 lhs = av_pop(stack);
15946 if (! IS_OPERAND(lhs)) {
15948 /* This can happen when there is an empty (), like in
15949 * /(?[[0]+()+])/ */
15953 switch (stacked_operator) {
15955 _invlist_intersection(lhs, rhs, &rhs);
15960 _invlist_union(lhs, rhs, &rhs);
15964 _invlist_subtract(lhs, rhs, &rhs);
15967 case '^': /* The union minus the intersection */
15972 _invlist_union(lhs, rhs, &u);
15973 _invlist_intersection(lhs, rhs, &i);
15974 _invlist_subtract(u, i, &rhs);
15975 SvREFCNT_dec_NN(i);
15976 SvREFCNT_dec_NN(u);
15982 /* Here, the higher precedence operation has been done, and the
15983 * result is in 'rhs'. We overwrite the stacked operator with
15984 * the result. Then we redo this code to either push the new
15985 * operator onto the stack or perform any higher precedence
15986 * stacked operation */
15987 only_to_avoid_leaks = av_pop(stack);
15988 SvREFCNT_dec(only_to_avoid_leaks);
15989 av_push(stack, rhs);
15992 case '!': /* Highest priority, right associative */
15994 /* If what's already at the top of the stack is another '!",
15995 * they just cancel each other out */
15996 if ( (top_ptr = av_fetch(stack, top_index, FALSE))
15997 && (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!'))
15999 only_to_avoid_leaks = av_pop(stack);
16000 SvREFCNT_dec(only_to_avoid_leaks);
16002 else { /* Otherwise, since it's right associative, just push
16004 av_push(stack, newSVuv(curchar));
16009 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16010 if (RExC_parse >= RExC_end) {
16013 vFAIL("Unexpected character");
16017 /* Here 'current' is the operand. If something is already on the
16018 * stack, we have to check if it is a !. But first, the code above
16019 * may have altered the stack in the time since we earlier set
16022 top_index = av_tindex_skip_len_mg(stack);
16023 if (top_index - fence >= 0) {
16024 /* If the top entry on the stack is an operator, it had better
16025 * be a '!', otherwise the entry below the top operand should
16026 * be an operator */
16027 top_ptr = av_fetch(stack, top_index, FALSE);
16029 if (IS_OPERATOR(*top_ptr)) {
16031 /* The only permissible operator at the top of the stack is
16032 * '!', which is applied immediately to this operand. */
16033 curchar = (char) SvUV(*top_ptr);
16034 if (curchar != '!') {
16035 SvREFCNT_dec(current);
16036 vFAIL2("Unexpected binary operator '%c' with no "
16037 "preceding operand", curchar);
16040 _invlist_invert(current);
16042 only_to_avoid_leaks = av_pop(stack);
16043 SvREFCNT_dec(only_to_avoid_leaks);
16045 /* And we redo with the inverted operand. This allows
16046 * handling multiple ! in a row */
16047 goto handle_operand;
16049 /* Single operand is ok only for the non-binary ')'
16051 else if ((top_index - fence == 0 && curchar != ')')
16052 || (top_index - fence > 0
16053 && (! (stacked_ptr = av_fetch(stack,
16056 || IS_OPERAND(*stacked_ptr))))
16058 SvREFCNT_dec(current);
16059 vFAIL("Operand with no preceding operator");
16063 /* Here there was nothing on the stack or the top element was
16064 * another operand. Just add this new one */
16065 av_push(stack, current);
16067 } /* End of switch on next parse token */
16069 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16070 } /* End of loop parsing through the construct */
16072 vFAIL("Syntax error in (?[...])");
16076 if (RExC_parse >= RExC_end || RExC_parse[1] != ')') {
16077 if (RExC_parse < RExC_end) {
16081 vFAIL("Unexpected ']' with no following ')' in (?[...");
16084 if (av_tindex_skip_len_mg(fence_stack) >= 0) {
16085 vFAIL("Unmatched (");
16088 if (av_tindex_skip_len_mg(stack) < 0 /* Was empty */
16089 || ((final = av_pop(stack)) == NULL)
16090 || ! IS_OPERAND(final)
16091 || ! is_invlist(final)
16092 || av_tindex_skip_len_mg(stack) >= 0) /* More left on stack */
16095 SvREFCNT_dec(final);
16096 vFAIL("Incomplete expression within '(?[ ])'");
16099 /* Here, 'final' is the resultant inversion list from evaluating the
16100 * expression. Return it if so requested */
16101 if (return_invlist) {
16102 *return_invlist = final;
16106 /* Otherwise generate a resultant node, based on 'final'. regclass() is
16107 * expecting a string of ranges and individual code points */
16108 invlist_iterinit(final);
16109 result_string = newSVpvs("");
16110 while (invlist_iternext(final, &start, &end)) {
16111 if (start == end) {
16112 Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}", start);
16115 Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}-\\x{%" UVXf "}",
16120 /* About to generate an ANYOF (or similar) node from the inversion list we
16121 * have calculated */
16122 save_parse = RExC_parse;
16123 RExC_parse = SvPV(result_string, len);
16124 save_end = RExC_end;
16125 RExC_end = RExC_parse + len;
16126 TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
16128 /* We turn off folding around the call, as the class we have constructed
16129 * already has all folding taken into consideration, and we don't want
16130 * regclass() to add to that */
16131 RExC_flags &= ~RXf_PMf_FOLD;
16132 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if multi-char
16133 * folds are allowed. */
16134 node = regclass(pRExC_state, flagp, depth+1,
16135 FALSE, /* means parse the whole char class */
16136 FALSE, /* don't allow multi-char folds */
16137 TRUE, /* silence non-portable warnings. The above may very
16138 well have generated non-portable code points, but
16139 they're valid on this machine */
16140 FALSE, /* similarly, no need for strict */
16141 FALSE, /* Require return to be an ANYOF */
16146 RExC_parse = save_parse + 1;
16147 RExC_end = save_end;
16148 SvREFCNT_dec_NN(final);
16149 SvREFCNT_dec_NN(result_string);
16152 RExC_flags |= RXf_PMf_FOLD;
16156 FAIL2("panic: regclass returned failure to handle_sets, flags=%#" UVxf,
16159 /* Fix up the node type if we are in locale. (We have pretended we are
16160 * under /u for the purposes of regclass(), as this construct will only
16161 * work under UTF-8 locales. But now we change the opcode to be ANYOFL (so
16162 * as to cause any warnings about bad locales to be output in regexec.c),
16163 * and add the flag that indicates to check if not in a UTF-8 locale. The
16164 * reason we above forbid optimization into something other than an ANYOF
16165 * node is simply to minimize the number of code changes in regexec.c.
16166 * Otherwise we would have to create new EXACTish node types and deal with
16167 * them. This decision could be revisited should this construct become
16170 * (One might think we could look at the resulting ANYOF node and suppress
16171 * the flag if everything is above 255, as those would be UTF-8 only,
16172 * but this isn't true, as the components that led to that result could
16173 * have been locale-affected, and just happen to cancel each other out
16174 * under UTF-8 locales.) */
16176 set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
16178 assert(OP(REGNODE_p(node)) == ANYOF);
16180 OP(REGNODE_p(node)) = ANYOFL;
16181 ANYOF_FLAGS(REGNODE_p(node))
16182 |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
16185 nextchar(pRExC_state);
16186 Set_Node_Length(REGNODE_p(node), RExC_parse - oregcomp_parse + 1); /* MJD */
16190 #ifdef ENABLE_REGEX_SETS_DEBUGGING
16193 S_dump_regex_sets_structures(pTHX_ RExC_state_t *pRExC_state,
16194 AV * stack, const IV fence, AV * fence_stack)
16195 { /* Dumps the stacks in handle_regex_sets() */
16197 const SSize_t stack_top = av_tindex_skip_len_mg(stack);
16198 const SSize_t fence_stack_top = av_tindex_skip_len_mg(fence_stack);
16201 PERL_ARGS_ASSERT_DUMP_REGEX_SETS_STRUCTURES;
16203 PerlIO_printf(Perl_debug_log, "\nParse position is:%s\n", RExC_parse);
16205 if (stack_top < 0) {
16206 PerlIO_printf(Perl_debug_log, "Nothing on stack\n");
16209 PerlIO_printf(Perl_debug_log, "Stack: (fence=%d)\n", (int) fence);
16210 for (i = stack_top; i >= 0; i--) {
16211 SV ** element_ptr = av_fetch(stack, i, FALSE);
16212 if (! element_ptr) {
16215 if (IS_OPERATOR(*element_ptr)) {
16216 PerlIO_printf(Perl_debug_log, "[%d]: %c\n",
16217 (int) i, (int) SvIV(*element_ptr));
16220 PerlIO_printf(Perl_debug_log, "[%d] ", (int) i);
16221 sv_dump(*element_ptr);
16226 if (fence_stack_top < 0) {
16227 PerlIO_printf(Perl_debug_log, "Nothing on fence_stack\n");
16230 PerlIO_printf(Perl_debug_log, "Fence_stack: \n");
16231 for (i = fence_stack_top; i >= 0; i--) {
16232 SV ** element_ptr = av_fetch(fence_stack, i, FALSE);
16233 if (! element_ptr) {
16236 PerlIO_printf(Perl_debug_log, "[%d]: %d\n",
16237 (int) i, (int) SvIV(*element_ptr));
16248 S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist)
16250 /* This adds the Latin1/above-Latin1 folding rules.
16252 * This should be called only for a Latin1-range code points, cp, which is
16253 * known to be involved in a simple fold with other code points above
16254 * Latin1. It would give false results if /aa has been specified.
16255 * Multi-char folds are outside the scope of this, and must be handled
16258 PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS;
16260 assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp));
16262 /* The rules that are valid for all Unicode versions are hard-coded in */
16267 add_cp_to_invlist(*invlist, KELVIN_SIGN);
16271 *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S);
16274 *invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU);
16275 *invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU);
16277 case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
16278 case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
16279 *invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN);
16281 case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
16282 *invlist = add_cp_to_invlist(*invlist,
16283 LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
16286 default: /* Other code points are checked against the data for the
16287 current Unicode version */
16289 Size_t folds_count;
16290 unsigned int first_fold;
16291 const unsigned int * remaining_folds;
16295 folded_cp = toFOLD(cp);
16298 U8 dummy_fold[UTF8_MAXBYTES_CASE+1];
16300 folded_cp = _to_fold_latin1(cp, dummy_fold, &dummy_len, 0);
16303 if (folded_cp > 255) {
16304 *invlist = add_cp_to_invlist(*invlist, folded_cp);
16307 folds_count = _inverse_folds(folded_cp, &first_fold,
16309 if (folds_count == 0) {
16311 /* Use deprecated warning to increase the chances of this being
16313 ckWARN2reg_d(RExC_parse,
16314 "Perl folding rules are not up-to-date for 0x%02X;"
16315 " please use the perlbug utility to report;", cp);
16320 if (first_fold > 255) {
16321 *invlist = add_cp_to_invlist(*invlist, first_fold);
16323 for (i = 0; i < folds_count - 1; i++) {
16324 if (remaining_folds[i] > 255) {
16325 *invlist = add_cp_to_invlist(*invlist,
16326 remaining_folds[i]);
16336 S_output_posix_warnings(pTHX_ RExC_state_t *pRExC_state, AV* posix_warnings)
16338 /* Output the elements of the array given by '*posix_warnings' as REGEXP
16342 const bool first_is_fatal = ckDEAD(packWARN(WARN_REGEXP));
16344 PERL_ARGS_ASSERT_OUTPUT_POSIX_WARNINGS;
16346 if (! TO_OUTPUT_WARNINGS(RExC_parse)) {
16350 while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) {
16351 if (first_is_fatal) { /* Avoid leaking this */
16352 av_undef(posix_warnings); /* This isn't necessary if the
16353 array is mortal, but is a
16355 (void) sv_2mortal(msg);
16358 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg));
16359 SvREFCNT_dec_NN(msg);
16362 UPDATE_WARNINGS_LOC(RExC_parse);
16366 S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count)
16368 /* This adds the string scalar <multi_string> to the array
16369 * <multi_char_matches>. <multi_string> is known to have exactly
16370 * <cp_count> code points in it. This is used when constructing a
16371 * bracketed character class and we find something that needs to match more
16372 * than a single character.
16374 * <multi_char_matches> is actually an array of arrays. Each top-level
16375 * element is an array that contains all the strings known so far that are
16376 * the same length. And that length (in number of code points) is the same
16377 * as the index of the top-level array. Hence, the [2] element is an
16378 * array, each element thereof is a string containing TWO code points;
16379 * while element [3] is for strings of THREE characters, and so on. Since
16380 * this is for multi-char strings there can never be a [0] nor [1] element.
16382 * When we rewrite the character class below, we will do so such that the
16383 * longest strings are written first, so that it prefers the longest
16384 * matching strings first. This is done even if it turns out that any
16385 * quantifier is non-greedy, out of this programmer's (khw) laziness. Tom
16386 * Christiansen has agreed that this is ok. This makes the test for the
16387 * ligature 'ffi' come before the test for 'ff', for example */
16390 AV** this_array_ptr;
16392 PERL_ARGS_ASSERT_ADD_MULTI_MATCH;
16394 if (! multi_char_matches) {
16395 multi_char_matches = newAV();
16398 if (av_exists(multi_char_matches, cp_count)) {
16399 this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE);
16400 this_array = *this_array_ptr;
16403 this_array = newAV();
16404 av_store(multi_char_matches, cp_count,
16407 av_push(this_array, multi_string);
16409 return multi_char_matches;
16412 /* The names of properties whose definitions are not known at compile time are
16413 * stored in this SV, after a constant heading. So if the length has been
16414 * changed since initialization, then there is a run-time definition. */
16415 #define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION \
16416 (SvCUR(listsv) != initial_listsv_len)
16418 /* There is a restricted set of white space characters that are legal when
16419 * ignoring white space in a bracketed character class. This generates the
16420 * code to skip them.
16422 * There is a line below that uses the same white space criteria but is outside
16423 * this macro. Both here and there must use the same definition */
16424 #define SKIP_BRACKETED_WHITE_SPACE(do_skip, p) \
16427 while (isBLANK_A(UCHARAT(p))) \
16434 STATIC regnode_offset
16435 S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth,
16436 const bool stop_at_1, /* Just parse the next thing, don't
16437 look for a full character class */
16438 bool allow_multi_folds,
16439 const bool silence_non_portable, /* Don't output warnings
16443 bool optimizable, /* ? Allow a non-ANYOF return
16445 SV** ret_invlist /* Return an inversion list, not a node */
16448 /* parse a bracketed class specification. Most of these will produce an
16449 * ANYOF node; but something like [a] will produce an EXACT node; [aA], an
16450 * EXACTFish node; [[:ascii:]], a POSIXA node; etc. It is more complex
16451 * under /i with multi-character folds: it will be rewritten following the
16452 * paradigm of this example, where the <multi-fold>s are characters which
16453 * fold to multiple character sequences:
16454 * /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
16455 * gets effectively rewritten as:
16456 * /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
16457 * reg() gets called (recursively) on the rewritten version, and this
16458 * function will return what it constructs. (Actually the <multi-fold>s
16459 * aren't physically removed from the [abcdefghi], it's just that they are
16460 * ignored in the recursion by means of a flag:
16461 * <RExC_in_multi_char_class>.)
16463 * ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS
16464 * characters, with the corresponding bit set if that character is in the
16465 * list. For characters above this, an inversion list is used. There
16466 * are extra bits for \w, etc. in locale ANYOFs, as what these match is not
16467 * determinable at compile time
16469 * On success, returns the offset at which any next node should be placed
16470 * into the regex engine program being compiled.
16472 * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
16473 * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
16478 UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
16480 UV value = OOB_UNICODE, save_value = OOB_UNICODE;
16481 regnode_offset ret = -1; /* Initialized to an illegal value */
16483 int namedclass = OOB_NAMEDCLASS;
16484 char *rangebegin = NULL;
16485 SV *listsv = NULL; /* List of \p{user-defined} whose definitions
16486 aren't available at the time this was called */
16487 STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
16488 than just initialized. */
16489 SV* properties = NULL; /* Code points that match \p{} \P{} */
16490 SV* posixes = NULL; /* Code points that match classes like [:word:],
16491 extended beyond the Latin1 range. These have to
16492 be kept separate from other code points for much
16493 of this function because their handling is
16494 different under /i, and for most classes under
16496 SV* nposixes = NULL; /* Similarly for [:^word:]. These are kept
16497 separate for a while from the non-complemented
16498 versions because of complications with /d
16500 SV* simple_posixes = NULL; /* But under some conditions, the classes can be
16501 treated more simply than the general case,
16502 leading to less compilation and execution
16504 UV element_count = 0; /* Number of distinct elements in the class.
16505 Optimizations may be possible if this is tiny */
16506 AV * multi_char_matches = NULL; /* Code points that fold to more than one
16507 character; used under /i */
16509 char * stop_ptr = RExC_end; /* where to stop parsing */
16511 /* ignore unescaped whitespace? */
16512 const bool skip_white = cBOOL( ret_invlist
16513 || (RExC_flags & RXf_PMf_EXTENDED_MORE));
16515 /* inversion list of code points this node matches only when the target
16516 * string is in UTF-8. These are all non-ASCII, < 256. (Because is under
16518 SV* upper_latin1_only_utf8_matches = NULL;
16520 /* Inversion list of code points this node matches regardless of things
16521 * like locale, folding, utf8ness of the target string */
16522 SV* cp_list = NULL;
16524 /* Like cp_list, but code points on this list need to be checked for things
16525 * that fold to/from them under /i */
16526 SV* cp_foldable_list = NULL;
16528 /* Like cp_list, but code points on this list are valid only when the
16529 * runtime locale is UTF-8 */
16530 SV* only_utf8_locale_list = NULL;
16532 /* In a range, if one of the endpoints is non-character-set portable,
16533 * meaning that it hard-codes a code point that may mean a different
16534 * charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a
16535 * mnemonic '\t' which each mean the same character no matter which
16536 * character set the platform is on. */
16537 unsigned int non_portable_endpoint = 0;
16539 /* Is the range unicode? which means on a platform that isn't 1-1 native
16540 * to Unicode (i.e. non-ASCII), each code point in it should be considered
16541 * to be a Unicode value. */
16542 bool unicode_range = FALSE;
16543 bool invert = FALSE; /* Is this class to be complemented */
16545 bool warn_super = ALWAYS_WARN_SUPER;
16547 const char * orig_parse = RExC_parse;
16549 /* This variable is used to mark where the end in the input is of something
16550 * that looks like a POSIX construct but isn't. During the parse, when
16551 * something looks like it could be such a construct is encountered, it is
16552 * checked for being one, but not if we've already checked this area of the
16553 * input. Only after this position is reached do we check again */
16554 char *not_posix_region_end = RExC_parse - 1;
16556 AV* posix_warnings = NULL;
16557 const bool do_posix_warnings = ckWARN(WARN_REGEXP);
16558 U8 op = END; /* The returned node-type, initialized to an impossible
16560 U8 anyof_flags = 0; /* flag bits if the node is an ANYOF-type */
16561 U32 posixl = 0; /* bit field of posix classes matched under /l */
16564 /* Flags as to what things aren't knowable until runtime. (Note that these are
16565 * mutually exclusive.) */
16566 #define HAS_USER_DEFINED_PROPERTY 0x01 /* /u any user-defined properties that
16567 haven't been defined as of yet */
16568 #define HAS_D_RUNTIME_DEPENDENCY 0x02 /* /d if the target being matched is
16570 #define HAS_L_RUNTIME_DEPENDENCY 0x04 /* /l what the posix classes match and
16571 what gets folded */
16572 U32 has_runtime_dependency = 0; /* OR of the above flags */
16574 GET_RE_DEBUG_FLAGS_DECL;
16576 PERL_ARGS_ASSERT_REGCLASS;
16578 PERL_UNUSED_ARG(depth);
16582 /* If wants an inversion list returned, we can't optimize to something
16585 optimizable = FALSE;
16588 DEBUG_PARSE("clas");
16590 #if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */ \
16591 || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0 \
16592 && UNICODE_DOT_DOT_VERSION == 0)
16593 allow_multi_folds = FALSE;
16596 /* We include the /i status at the beginning of this so that we can
16597 * know it at runtime */
16598 listsv = sv_2mortal(Perl_newSVpvf(aTHX_ "#%d\n", cBOOL(FOLD)));
16599 initial_listsv_len = SvCUR(listsv);
16600 SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated. */
16602 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
16604 assert(RExC_parse <= RExC_end);
16606 if (UCHARAT(RExC_parse) == '^') { /* Complement the class */
16609 allow_multi_folds = FALSE;
16611 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
16614 /* Check that they didn't say [:posix:] instead of [[:posix:]] */
16615 if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) {
16616 int maybe_class = handle_possible_posix(pRExC_state,
16618 ¬_posix_region_end,
16620 TRUE /* checking only */);
16621 if (maybe_class >= OOB_NAMEDCLASS && do_posix_warnings) {
16622 ckWARN4reg(not_posix_region_end,
16623 "POSIX syntax [%c %c] belongs inside character classes%s",
16624 *RExC_parse, *RExC_parse,
16625 (maybe_class == OOB_NAMEDCLASS)
16626 ? ((POSIXCC_NOTYET(*RExC_parse))
16627 ? " (but this one isn't implemented)"
16628 : " (but this one isn't fully valid)")
16634 /* If the caller wants us to just parse a single element, accomplish this
16635 * by faking the loop ending condition */
16636 if (stop_at_1 && RExC_end > RExC_parse) {
16637 stop_ptr = RExC_parse + 1;
16640 /* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */
16641 if (UCHARAT(RExC_parse) == ']')
16642 goto charclassloop;
16646 if ( posix_warnings
16647 && av_tindex_skip_len_mg(posix_warnings) >= 0
16648 && RExC_parse > not_posix_region_end)
16650 /* Warnings about posix class issues are considered tentative until
16651 * we are far enough along in the parse that we can no longer
16652 * change our mind, at which point we output them. This is done
16653 * each time through the loop so that a later class won't zap them
16654 * before they have been dealt with. */
16655 output_posix_warnings(pRExC_state, posix_warnings);
16658 if (RExC_parse >= stop_ptr) {
16662 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
16664 if (UCHARAT(RExC_parse) == ']') {
16670 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
16671 save_value = value;
16672 save_prevvalue = prevvalue;
16675 rangebegin = RExC_parse;
16677 non_portable_endpoint = 0;
16679 if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) {
16680 value = utf8n_to_uvchr((U8*)RExC_parse,
16681 RExC_end - RExC_parse,
16682 &numlen, UTF8_ALLOW_DEFAULT);
16683 RExC_parse += numlen;
16686 value = UCHARAT(RExC_parse++);
16688 if (value == '[') {
16689 char * posix_class_end;
16690 namedclass = handle_possible_posix(pRExC_state,
16693 do_posix_warnings ? &posix_warnings : NULL,
16694 FALSE /* die if error */);
16695 if (namedclass > OOB_NAMEDCLASS) {
16697 /* If there was an earlier attempt to parse this particular
16698 * posix class, and it failed, it was a false alarm, as this
16699 * successful one proves */
16700 if ( posix_warnings
16701 && av_tindex_skip_len_mg(posix_warnings) >= 0
16702 && not_posix_region_end >= RExC_parse
16703 && not_posix_region_end <= posix_class_end)
16705 av_undef(posix_warnings);
16708 RExC_parse = posix_class_end;
16710 else if (namedclass == OOB_NAMEDCLASS) {
16711 not_posix_region_end = posix_class_end;
16714 namedclass = OOB_NAMEDCLASS;
16717 else if ( RExC_parse - 1 > not_posix_region_end
16718 && MAYBE_POSIXCC(value))
16720 (void) handle_possible_posix(
16722 RExC_parse - 1, /* -1 because parse has already been
16724 ¬_posix_region_end,
16725 do_posix_warnings ? &posix_warnings : NULL,
16726 TRUE /* checking only */);
16728 else if ( strict && ! skip_white
16729 && ( _generic_isCC(value, _CC_VERTSPACE)
16730 || is_VERTWS_cp_high(value)))
16732 vFAIL("Literal vertical space in [] is illegal except under /x");
16734 else if (value == '\\') {
16735 /* Is a backslash; get the code point of the char after it */
16737 if (RExC_parse >= RExC_end) {
16738 vFAIL("Unmatched [");
16741 if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) {
16742 value = utf8n_to_uvchr((U8*)RExC_parse,
16743 RExC_end - RExC_parse,
16744 &numlen, UTF8_ALLOW_DEFAULT);
16745 RExC_parse += numlen;
16748 value = UCHARAT(RExC_parse++);
16750 /* Some compilers cannot handle switching on 64-bit integer
16751 * values, therefore value cannot be an UV. Yes, this will
16752 * be a problem later if we want switch on Unicode.
16753 * A similar issue a little bit later when switching on
16754 * namedclass. --jhi */
16756 /* If the \ is escaping white space when white space is being
16757 * skipped, it means that that white space is wanted literally, and
16758 * is already in 'value'. Otherwise, need to translate the escape
16759 * into what it signifies. */
16760 if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) {
16762 case 'w': namedclass = ANYOF_WORDCHAR; break;
16763 case 'W': namedclass = ANYOF_NWORDCHAR; break;
16764 case 's': namedclass = ANYOF_SPACE; break;
16765 case 'S': namedclass = ANYOF_NSPACE; break;
16766 case 'd': namedclass = ANYOF_DIGIT; break;
16767 case 'D': namedclass = ANYOF_NDIGIT; break;
16768 case 'v': namedclass = ANYOF_VERTWS; break;
16769 case 'V': namedclass = ANYOF_NVERTWS; break;
16770 case 'h': namedclass = ANYOF_HORIZWS; break;
16771 case 'H': namedclass = ANYOF_NHORIZWS; break;
16772 case 'N': /* Handle \N{NAME} in class */
16774 const char * const backslash_N_beg = RExC_parse - 2;
16777 if (! grok_bslash_N(pRExC_state,
16778 NULL, /* No regnode */
16779 &value, /* Yes single value */
16780 &cp_count, /* Multiple code pt count */
16786 if (*flagp & NEED_UTF8)
16787 FAIL("panic: grok_bslash_N set NEED_UTF8");
16789 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
16791 if (cp_count < 0) {
16792 vFAIL("\\N in a character class must be a named character: \\N{...}");
16794 else if (cp_count == 0) {
16795 ckWARNreg(RExC_parse,
16796 "Ignoring zero length \\N{} in character class");
16798 else { /* cp_count > 1 */
16799 if (! RExC_in_multi_char_class) {
16800 if (invert || range || *RExC_parse == '-') {
16803 vFAIL("\\N{} in inverted character class or as a range end-point is restricted to one character");
16805 ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class");
16806 break; /* <value> contains the first code
16807 point. Drop out of the switch to
16811 SV * multi_char_N = newSVpvn(backslash_N_beg,
16812 RExC_parse - backslash_N_beg);
16814 = add_multi_match(multi_char_matches,
16819 } /* End of cp_count != 1 */
16821 /* This element should not be processed further in this
16824 value = save_value;
16825 prevvalue = save_prevvalue;
16826 continue; /* Back to top of loop to get next char */
16829 /* Here, is a single code point, and <value> contains it */
16830 unicode_range = TRUE; /* \N{} are Unicode */
16838 /* \p means they want Unicode semantics */
16839 REQUIRE_UNI_RULES(flagp, 0);
16841 if (RExC_parse >= RExC_end)
16842 vFAIL2("Empty \\%c", (U8)value);
16843 if (*RExC_parse == '{') {
16844 const U8 c = (U8)value;
16845 e = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
16848 vFAIL2("Missing right brace on \\%c{}", c);
16853 /* White space is allowed adjacent to the braces and after
16854 * any '^', even when not under /x */
16855 while (isSPACE(*RExC_parse)) {
16859 if (UCHARAT(RExC_parse) == '^') {
16861 /* toggle. (The rhs xor gets the single bit that
16862 * differs between P and p; the other xor inverts just
16864 value ^= 'P' ^ 'p';
16867 while (isSPACE(*RExC_parse)) {
16872 if (e == RExC_parse)
16873 vFAIL2("Empty \\%c{}", c);
16875 n = e - RExC_parse;
16876 while (isSPACE(*(RExC_parse + n - 1)))
16879 } /* The \p isn't immediately followed by a '{' */
16880 else if (! isALPHA(*RExC_parse)) {
16881 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16882 vFAIL2("Character following \\%c must be '{' or a "
16883 "single-character Unicode property name",
16891 char* name = RExC_parse;
16893 /* Any message returned about expanding the definition */
16894 SV* msg = newSVpvs_flags("", SVs_TEMP);
16896 /* If set TRUE, the property is user-defined as opposed to
16897 * official Unicode */
16898 bool user_defined = FALSE;
16900 SV * prop_definition = parse_uniprop_string(
16901 name, n, UTF, FOLD,
16902 FALSE, /* This is compile-time */
16907 if (SvCUR(msg)) { /* Assumes any error causes a msg */
16908 assert(prop_definition == NULL);
16909 RExC_parse = e + 1;
16910 if (SvUTF8(msg)) { /* msg being UTF-8 makes the whole
16911 thing so, or else the display is
16915 /* diag_listed_as: Can't find Unicode property definition "%s" in regex; marked by <-- HERE in m/%s/ */
16916 vFAIL2utf8f("%" UTF8f, UTF8fARG(SvUTF8(msg),
16917 SvCUR(msg), SvPVX(msg)));
16920 if (! is_invlist(prop_definition)) {
16922 /* Here, the definition isn't known, so we have gotten
16923 * returned a string that will be evaluated if and when
16924 * encountered at runtime. We add it to the list of
16925 * such properties, along with whether it should be
16926 * complemented or not */
16927 if (value == 'P') {
16928 sv_catpvs(listsv, "!");
16931 sv_catpvs(listsv, "+");
16933 sv_catsv(listsv, prop_definition);
16935 has_runtime_dependency |= HAS_USER_DEFINED_PROPERTY;
16937 /* We don't know yet what this matches, so have to flag
16939 anyof_flags |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
16942 assert (prop_definition && is_invlist(prop_definition));
16944 /* Here we do have the complete property definition
16946 * Temporary workaround for [perl #133136]. For this
16947 * precise input that is in the .t that is failing,
16948 * load utf8.pm, which is what the test wants, so that
16949 * that .t passes */
16950 if ( memEQs(RExC_start, e + 1 - RExC_start,
16952 && ! hv_common(GvHVn(PL_incgv),
16954 "utf8.pm", sizeof("utf8.pm") - 1,
16955 0, HV_FETCH_ISEXISTS, NULL, 0))
16957 require_pv("utf8.pm");
16960 if (! user_defined &&
16961 /* We warn on matching an above-Unicode code point
16962 * if the match would return true, except don't
16963 * warn for \p{All}, which has exactly one element
16965 (_invlist_contains_cp(prop_definition, 0x110000)
16966 && (! (_invlist_len(prop_definition) == 1
16967 && *invlist_array(prop_definition) == 0))))
16972 /* Invert if asking for the complement */
16973 if (value == 'P') {
16974 _invlist_union_complement_2nd(properties,
16979 _invlist_union(properties, prop_definition, &properties);
16984 RExC_parse = e + 1;
16985 namedclass = ANYOF_UNIPROP; /* no official name, but it's
16989 case 'n': value = '\n'; break;
16990 case 'r': value = '\r'; break;
16991 case 't': value = '\t'; break;
16992 case 'f': value = '\f'; break;
16993 case 'b': value = '\b'; break;
16994 case 'e': value = ESC_NATIVE; break;
16995 case 'a': value = '\a'; break;
16997 RExC_parse--; /* function expects to be pointed at the 'o' */
16999 const char* error_msg;
17000 bool valid = grok_bslash_o(&RExC_parse,
17004 TO_OUTPUT_WARNINGS(RExC_parse),
17006 silence_non_portable,
17011 UPDATE_WARNINGS_LOC(RExC_parse - 1);
17013 non_portable_endpoint++;
17016 RExC_parse--; /* function expects to be pointed at the 'x' */
17018 const char* error_msg;
17019 bool valid = grok_bslash_x(&RExC_parse,
17023 TO_OUTPUT_WARNINGS(RExC_parse),
17025 silence_non_portable,
17030 UPDATE_WARNINGS_LOC(RExC_parse - 1);
17032 non_portable_endpoint++;
17035 value = grok_bslash_c(*RExC_parse, TO_OUTPUT_WARNINGS(RExC_parse));
17036 UPDATE_WARNINGS_LOC(RExC_parse);
17038 non_portable_endpoint++;
17040 case '0': case '1': case '2': case '3': case '4':
17041 case '5': case '6': case '7':
17043 /* Take 1-3 octal digits */
17044 I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
17045 numlen = (strict) ? 4 : 3;
17046 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
17047 RExC_parse += numlen;
17050 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
17051 vFAIL("Need exactly 3 octal digits");
17053 else if ( numlen < 3 /* like \08, \178 */
17054 && RExC_parse < RExC_end
17055 && isDIGIT(*RExC_parse)
17056 && ckWARN(WARN_REGEXP))
17058 reg_warn_non_literal_string(
17060 form_short_octal_warning(RExC_parse, numlen));
17063 non_portable_endpoint++;
17067 /* Allow \_ to not give an error */
17068 if (isWORDCHAR(value) && value != '_') {
17070 vFAIL2("Unrecognized escape \\%c in character class",
17074 ckWARN2reg(RExC_parse,
17075 "Unrecognized escape \\%c in character class passed through",
17080 } /* End of switch on char following backslash */
17081 } /* end of handling backslash escape sequences */
17083 /* Here, we have the current token in 'value' */
17085 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
17088 /* a bad range like a-\d, a-[:digit:]. The '-' is taken as a
17089 * literal, as is the character that began the false range, i.e.
17090 * the 'a' in the examples */
17092 const int w = (RExC_parse >= rangebegin)
17093 ? RExC_parse - rangebegin
17097 "False [] range \"%" UTF8f "\"",
17098 UTF8fARG(UTF, w, rangebegin));
17101 ckWARN2reg(RExC_parse,
17102 "False [] range \"%" UTF8f "\"",
17103 UTF8fARG(UTF, w, rangebegin));
17104 cp_list = add_cp_to_invlist(cp_list, '-');
17105 cp_foldable_list = add_cp_to_invlist(cp_foldable_list,
17109 range = 0; /* this was not a true range */
17110 element_count += 2; /* So counts for three values */
17113 classnum = namedclass_to_classnum(namedclass);
17115 if (LOC && namedclass < ANYOF_POSIXL_MAX
17116 #ifndef HAS_ISASCII
17117 && classnum != _CC_ASCII
17120 SV* scratch_list = NULL;
17122 /* What the Posix classes (like \w, [:space:]) match in locale
17123 * isn't knowable under locale until actual match time. A
17124 * special node is used for these which has extra space for a
17125 * bitmap, with a bit reserved for each named class that is to
17126 * be matched against. This isn't needed for \p{} and
17127 * pseudo-classes, as they are not affected by locale, and
17128 * hence are dealt with separately */
17129 POSIXL_SET(posixl, namedclass);
17130 has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
17131 anyof_flags |= ANYOF_MATCHES_POSIXL;
17133 /* The above-Latin1 characters are not subject to locale rules.
17134 * Just add them to the unconditionally-matched list */
17136 /* Get the list of the above-Latin1 code points this matches */
17137 _invlist_intersection_maybe_complement_2nd(PL_AboveLatin1,
17138 PL_XPosix_ptrs[classnum],
17140 /* Odd numbers are complements, like
17141 * NDIGIT, NASCII, ... */
17142 namedclass % 2 != 0,
17144 /* Checking if 'cp_list' is NULL first saves an extra clone.
17145 * Its reference count will be decremented at the next union,
17146 * etc, or if this is the only instance, at the end of the
17149 cp_list = scratch_list;
17152 _invlist_union(cp_list, scratch_list, &cp_list);
17153 SvREFCNT_dec_NN(scratch_list);
17155 continue; /* Go get next character */
17159 /* Here, is not /l, or is a POSIX class for which /l doesn't
17160 * matter (or is a Unicode property, which is skipped here). */
17161 if (namedclass >= ANYOF_POSIXL_MAX) { /* If a special class */
17162 if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */
17164 /* Here, should be \h, \H, \v, or \V. None of /d, /i
17165 * nor /l make a difference in what these match,
17166 * therefore we just add what they match to cp_list. */
17167 if (classnum != _CC_VERTSPACE) {
17168 assert( namedclass == ANYOF_HORIZWS
17169 || namedclass == ANYOF_NHORIZWS);
17171 /* It turns out that \h is just a synonym for
17173 classnum = _CC_BLANK;
17176 _invlist_union_maybe_complement_2nd(
17178 PL_XPosix_ptrs[classnum],
17179 namedclass % 2 != 0, /* Complement if odd
17180 (NHORIZWS, NVERTWS)
17185 else if ( AT_LEAST_UNI_SEMANTICS
17186 || classnum == _CC_ASCII
17187 || (DEPENDS_SEMANTICS && ( classnum == _CC_DIGIT
17188 || classnum == _CC_XDIGIT)))
17190 /* We usually have to worry about /d affecting what POSIX
17191 * classes match, with special code needed because we won't
17192 * know until runtime what all matches. But there is no
17193 * extra work needed under /u and /a; and [:ascii:] is
17194 * unaffected by /d; and :digit: and :xdigit: don't have
17195 * runtime differences under /d. So we can special case
17196 * these, and avoid some extra work below, and at runtime.
17198 _invlist_union_maybe_complement_2nd(
17200 ((AT_LEAST_ASCII_RESTRICTED)
17201 ? PL_Posix_ptrs[classnum]
17202 : PL_XPosix_ptrs[classnum]),
17203 namedclass % 2 != 0,
17206 else { /* Garden variety class. If is NUPPER, NALPHA, ...
17207 complement and use nposixes */
17208 SV** posixes_ptr = namedclass % 2 == 0
17211 _invlist_union_maybe_complement_2nd(
17213 PL_XPosix_ptrs[classnum],
17214 namedclass % 2 != 0,
17218 } /* end of namedclass \blah */
17220 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17222 /* If 'range' is set, 'value' is the ending of a range--check its
17223 * validity. (If value isn't a single code point in the case of a
17224 * range, we should have figured that out above in the code that
17225 * catches false ranges). Later, we will handle each individual code
17226 * point in the range. If 'range' isn't set, this could be the
17227 * beginning of a range, so check for that by looking ahead to see if
17228 * the next real character to be processed is the range indicator--the
17233 /* For unicode ranges, we have to test that the Unicode as opposed
17234 * to the native values are not decreasing. (Above 255, there is
17235 * no difference between native and Unicode) */
17236 if (unicode_range && prevvalue < 255 && value < 255) {
17237 if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) {
17238 goto backwards_range;
17243 if (prevvalue > value) /* b-a */ {
17248 w = RExC_parse - rangebegin;
17250 "Invalid [] range \"%" UTF8f "\"",
17251 UTF8fARG(UTF, w, rangebegin));
17252 NOT_REACHED; /* NOTREACHED */
17256 prevvalue = value; /* save the beginning of the potential range */
17257 if (! stop_at_1 /* Can't be a range if parsing just one thing */
17258 && *RExC_parse == '-')
17260 char* next_char_ptr = RExC_parse + 1;
17262 /* Get the next real char after the '-' */
17263 SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr);
17265 /* If the '-' is at the end of the class (just before the ']',
17266 * it is a literal minus; otherwise it is a range */
17267 if (next_char_ptr < RExC_end && *next_char_ptr != ']') {
17268 RExC_parse = next_char_ptr;
17270 /* a bad range like \w-, [:word:]- ? */
17271 if (namedclass > OOB_NAMEDCLASS) {
17272 if (strict || ckWARN(WARN_REGEXP)) {
17273 const int w = RExC_parse >= rangebegin
17274 ? RExC_parse - rangebegin
17277 vFAIL4("False [] range \"%*.*s\"",
17282 "False [] range \"%*.*s\"",
17286 cp_list = add_cp_to_invlist(cp_list, '-');
17289 range = 1; /* yeah, it's a range! */
17290 continue; /* but do it the next time */
17295 if (namedclass > OOB_NAMEDCLASS) {
17299 /* Here, we have a single value this time through the loop, and
17300 * <prevvalue> is the beginning of the range, if any; or <value> if
17303 /* non-Latin1 code point implies unicode semantics. */
17305 REQUIRE_UNI_RULES(flagp, 0);
17308 /* Ready to process either the single value, or the completed range.
17309 * For single-valued non-inverted ranges, we consider the possibility
17310 * of multi-char folds. (We made a conscious decision to not do this
17311 * for the other cases because it can often lead to non-intuitive
17312 * results. For example, you have the peculiar case that:
17313 * "s s" =~ /^[^\xDF]+$/i => Y
17314 * "ss" =~ /^[^\xDF]+$/i => N
17316 * See [perl #89750] */
17317 if (FOLD && allow_multi_folds && value == prevvalue) {
17318 if ( value == LATIN_SMALL_LETTER_SHARP_S
17319 || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
17322 /* Here <value> is indeed a multi-char fold. Get what it is */
17324 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
17327 UV folded = _to_uni_fold_flags(
17331 FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED
17332 ? FOLD_FLAGS_NOMIX_ASCII
17336 /* Here, <folded> should be the first character of the
17337 * multi-char fold of <value>, with <foldbuf> containing the
17338 * whole thing. But, if this fold is not allowed (because of
17339 * the flags), <fold> will be the same as <value>, and should
17340 * be processed like any other character, so skip the special
17342 if (folded != value) {
17344 /* Skip if we are recursed, currently parsing the class
17345 * again. Otherwise add this character to the list of
17346 * multi-char folds. */
17347 if (! RExC_in_multi_char_class) {
17348 STRLEN cp_count = utf8_length(foldbuf,
17349 foldbuf + foldlen);
17350 SV* multi_fold = sv_2mortal(newSVpvs(""));
17352 Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%" UVXf "}", value);
17355 = add_multi_match(multi_char_matches,
17361 /* This element should not be processed further in this
17364 value = save_value;
17365 prevvalue = save_prevvalue;
17371 if (strict && ckWARN(WARN_REGEXP)) {
17374 /* If the range starts above 255, everything is portable and
17375 * likely to be so for any forseeable character set, so don't
17377 if (unicode_range && non_portable_endpoint && prevvalue < 256) {
17378 vWARN(RExC_parse, "Both or neither range ends should be Unicode");
17380 else if (prevvalue != value) {
17382 /* Under strict, ranges that stop and/or end in an ASCII
17383 * printable should have each end point be a portable value
17384 * for it (preferably like 'A', but we don't warn if it is
17385 * a (portable) Unicode name or code point), and the range
17386 * must be be all digits or all letters of the same case.
17387 * Otherwise, the range is non-portable and unclear as to
17388 * what it contains */
17389 if ( (isPRINT_A(prevvalue) || isPRINT_A(value))
17390 && ( non_portable_endpoint
17391 || ! ( (isDIGIT_A(prevvalue) && isDIGIT_A(value))
17392 || (isLOWER_A(prevvalue) && isLOWER_A(value))
17393 || (isUPPER_A(prevvalue) && isUPPER_A(value))
17395 vWARN(RExC_parse, "Ranges of ASCII printables should"
17396 " be some subset of \"0-9\","
17397 " \"A-Z\", or \"a-z\"");
17399 else if (prevvalue >= FIRST_NON_ASCII_DECIMAL_DIGIT) {
17400 SSize_t index_start;
17401 SSize_t index_final;
17403 /* But the nature of Unicode and languages mean we
17404 * can't do the same checks for above-ASCII ranges,
17405 * except in the case of digit ones. These should
17406 * contain only digits from the same group of 10. The
17407 * ASCII case is handled just above. Hence here, the
17408 * range could be a range of digits. First some
17409 * unlikely special cases. Grandfather in that a range
17410 * ending in 19DA (NEW TAI LUE THAM DIGIT ONE) is bad
17411 * if its starting value is one of the 10 digits prior
17412 * to it. This is because it is an alternate way of
17413 * writing 19D1, and some people may expect it to be in
17414 * that group. But it is bad, because it won't give
17415 * the expected results. In Unicode 5.2 it was
17416 * considered to be in that group (of 11, hence), but
17417 * this was fixed in the next version */
17419 if (UNLIKELY(value == 0x19DA && prevvalue >= 0x19D0)) {
17420 goto warn_bad_digit_range;
17422 else if (UNLIKELY( prevvalue >= 0x1D7CE
17423 && value <= 0x1D7FF))
17425 /* This is the only other case currently in Unicode
17426 * where the algorithm below fails. The code
17427 * points just above are the end points of a single
17428 * range containing only decimal digits. It is 5
17429 * different series of 0-9. All other ranges of
17430 * digits currently in Unicode are just a single
17431 * series. (And mktables will notify us if a later
17432 * Unicode version breaks this.)
17434 * If the range being checked is at most 9 long,
17435 * and the digit values represented are in
17436 * numerical order, they are from the same series.
17438 if ( value - prevvalue > 9
17439 || ((( value - 0x1D7CE) % 10)
17440 <= (prevvalue - 0x1D7CE) % 10))
17442 goto warn_bad_digit_range;
17447 /* For all other ranges of digits in Unicode, the
17448 * algorithm is just to check if both end points
17449 * are in the same series, which is the same range.
17451 index_start = _invlist_search(
17452 PL_XPosix_ptrs[_CC_DIGIT],
17455 /* Warn if the range starts and ends with a digit,
17456 * and they are not in the same group of 10. */
17457 if ( index_start >= 0
17458 && ELEMENT_RANGE_MATCHES_INVLIST(index_start)
17460 _invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
17461 value)) != index_start
17462 && index_final >= 0
17463 && ELEMENT_RANGE_MATCHES_INVLIST(index_final))
17465 warn_bad_digit_range:
17466 vWARN(RExC_parse, "Ranges of digits should be"
17467 " from the same group of"
17474 if ((! range || prevvalue == value) && non_portable_endpoint) {
17475 if (isPRINT_A(value)) {
17478 if (isBACKSLASHED_PUNCT(value)) {
17479 literal[d++] = '\\';
17481 literal[d++] = (char) value;
17482 literal[d++] = '\0';
17485 "\"%.*s\" is more clearly written simply as \"%s\"",
17486 (int) (RExC_parse - rangebegin),
17491 else if isMNEMONIC_CNTRL(value) {
17493 "\"%.*s\" is more clearly written simply as \"%s\"",
17494 (int) (RExC_parse - rangebegin),
17496 cntrl_to_mnemonic((U8) value)
17502 /* Deal with this element of the class */
17505 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
17508 /* On non-ASCII platforms, for ranges that span all of 0..255, and ones
17509 * that don't require special handling, we can just add the range like
17510 * we do for ASCII platforms */
17511 if ((UNLIKELY(prevvalue == 0) && value >= 255)
17512 || ! (prevvalue < 256
17514 || (! non_portable_endpoint
17515 && ((isLOWER_A(prevvalue) && isLOWER_A(value))
17516 || (isUPPER_A(prevvalue)
17517 && isUPPER_A(value)))))))
17519 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
17523 /* Here, requires special handling. This can be because it is a
17524 * range whose code points are considered to be Unicode, and so
17525 * must be individually translated into native, or because its a
17526 * subrange of 'A-Z' or 'a-z' which each aren't contiguous in
17527 * EBCDIC, but we have defined them to include only the "expected"
17528 * upper or lower case ASCII alphabetics. Subranges above 255 are
17529 * the same in native and Unicode, so can be added as a range */
17530 U8 start = NATIVE_TO_LATIN1(prevvalue);
17532 U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255;
17533 for (j = start; j <= end; j++) {
17534 cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j));
17537 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
17543 range = 0; /* this range (if it was one) is done now */
17544 } /* End of loop through all the text within the brackets */
17546 if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) {
17547 output_posix_warnings(pRExC_state, posix_warnings);
17550 /* If anything in the class expands to more than one character, we have to
17551 * deal with them by building up a substitute parse string, and recursively
17552 * calling reg() on it, instead of proceeding */
17553 if (multi_char_matches) {
17554 SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
17557 char *save_end = RExC_end;
17558 char *save_parse = RExC_parse;
17559 char *save_start = RExC_start;
17560 Size_t constructed_prefix_len = 0; /* This gives the length of the
17561 constructed portion of the
17562 substitute parse. */
17563 bool first_time = TRUE; /* First multi-char occurrence doesn't get
17568 /* Only one level of recursion allowed */
17569 assert(RExC_copy_start_in_constructed == RExC_precomp);
17571 #if 0 /* Have decided not to deal with multi-char folds in inverted classes,
17572 because too confusing */
17574 sv_catpvs(substitute_parse, "(?:");
17578 /* Look at the longest folds first */
17579 for (cp_count = av_tindex_skip_len_mg(multi_char_matches);
17584 if (av_exists(multi_char_matches, cp_count)) {
17585 AV** this_array_ptr;
17588 this_array_ptr = (AV**) av_fetch(multi_char_matches,
17590 while ((this_sequence = av_pop(*this_array_ptr)) !=
17593 if (! first_time) {
17594 sv_catpvs(substitute_parse, "|");
17596 first_time = FALSE;
17598 sv_catpv(substitute_parse, SvPVX(this_sequence));
17603 /* If the character class contains anything else besides these
17604 * multi-character folds, have to include it in recursive parsing */
17605 if (element_count) {
17606 sv_catpvs(substitute_parse, "|[");
17607 constructed_prefix_len = SvCUR(substitute_parse);
17608 sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
17610 /* Put in a closing ']' only if not going off the end, as otherwise
17611 * we are adding something that really isn't there */
17612 if (RExC_parse < RExC_end) {
17613 sv_catpvs(substitute_parse, "]");
17617 sv_catpvs(substitute_parse, ")");
17620 /* This is a way to get the parse to skip forward a whole named
17621 * sequence instead of matching the 2nd character when it fails the
17623 sv_catpvs(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
17627 /* Set up the data structure so that any errors will be properly
17628 * reported. See the comments at the definition of
17629 * REPORT_LOCATION_ARGS for details */
17630 RExC_copy_start_in_input = (char *) orig_parse;
17631 RExC_start = RExC_parse = SvPV(substitute_parse, len);
17632 RExC_copy_start_in_constructed = RExC_start + constructed_prefix_len;
17633 RExC_end = RExC_parse + len;
17634 RExC_in_multi_char_class = 1;
17636 ret = reg(pRExC_state, 1, ®_flags, depth+1);
17638 *flagp |= reg_flags & (HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PARSE|NEED_UTF8);
17640 /* And restore so can parse the rest of the pattern */
17641 RExC_parse = save_parse;
17642 RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = save_start;
17643 RExC_end = save_end;
17644 RExC_in_multi_char_class = 0;
17645 SvREFCNT_dec_NN(multi_char_matches);
17649 /* If folding, we calculate all characters that could fold to or from the
17650 * ones already on the list */
17651 if (cp_foldable_list) {
17653 UV start, end; /* End points of code point ranges */
17655 SV* fold_intersection = NULL;
17658 /* Our calculated list will be for Unicode rules. For locale
17659 * matching, we have to keep a separate list that is consulted at
17660 * runtime only when the locale indicates Unicode rules (and we
17661 * don't include potential matches in the ASCII/Latin1 range, as
17662 * any code point could fold to any other, based on the run-time
17663 * locale). For non-locale, we just use the general list */
17665 use_list = &only_utf8_locale_list;
17668 use_list = &cp_list;
17671 /* Only the characters in this class that participate in folds need
17672 * be checked. Get the intersection of this class and all the
17673 * possible characters that are foldable. This can quickly narrow
17674 * down a large class */
17675 _invlist_intersection(PL_in_some_fold, cp_foldable_list,
17676 &fold_intersection);
17678 /* Now look at the foldable characters in this class individually */
17679 invlist_iterinit(fold_intersection);
17680 while (invlist_iternext(fold_intersection, &start, &end)) {
17684 /* Look at every character in the range */
17685 for (j = start; j <= end; j++) {
17686 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
17689 Size_t folds_count;
17690 unsigned int first_fold;
17691 const unsigned int * remaining_folds;
17695 /* Under /l, we don't know what code points below 256
17696 * fold to, except we do know the MICRO SIGN folds to
17697 * an above-255 character if the locale is UTF-8, so we
17698 * add it to the special list (in *use_list) Otherwise
17699 * we know now what things can match, though some folds
17700 * are valid under /d only if the target is UTF-8.
17701 * Those go in a separate list */
17702 if ( IS_IN_SOME_FOLD_L1(j)
17703 && ! (LOC && j != MICRO_SIGN))
17706 /* ASCII is always matched; non-ASCII is matched
17707 * only under Unicode rules (which could happen
17708 * under /l if the locale is a UTF-8 one */
17709 if (isASCII(j) || ! DEPENDS_SEMANTICS) {
17710 *use_list = add_cp_to_invlist(*use_list,
17711 PL_fold_latin1[j]);
17713 else if (j != PL_fold_latin1[j]) {
17714 upper_latin1_only_utf8_matches
17715 = add_cp_to_invlist(
17716 upper_latin1_only_utf8_matches,
17717 PL_fold_latin1[j]);
17721 if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j)
17722 && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
17724 add_above_Latin1_folds(pRExC_state,
17731 /* Here is an above Latin1 character. We don't have the
17732 * rules hard-coded for it. First, get its fold. This is
17733 * the simple fold, as the multi-character folds have been
17734 * handled earlier and separated out */
17735 folded = _to_uni_fold_flags(j, foldbuf, &foldlen,
17736 (ASCII_FOLD_RESTRICTED)
17737 ? FOLD_FLAGS_NOMIX_ASCII
17740 /* Single character fold of above Latin1. Add everything
17741 * in its fold closure to the list that this node should
17743 folds_count = _inverse_folds(folded, &first_fold,
17745 for (k = 0; k <= folds_count; k++) {
17746 UV c = (k == 0) /* First time through use itself */
17748 : (k == 1) /* 2nd time use, the first fold */
17751 /* Then the remaining ones */
17752 : remaining_folds[k-2];
17754 /* /aa doesn't allow folds between ASCII and non- */
17755 if (( ASCII_FOLD_RESTRICTED
17756 && (isASCII(c) != isASCII(j))))
17761 /* Folds under /l which cross the 255/256 boundary are
17762 * added to a separate list. (These are valid only
17763 * when the locale is UTF-8.) */
17764 if (c < 256 && LOC) {
17765 *use_list = add_cp_to_invlist(*use_list, c);
17769 if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
17771 cp_list = add_cp_to_invlist(cp_list, c);
17774 /* Similarly folds involving non-ascii Latin1
17775 * characters under /d are added to their list */
17776 upper_latin1_only_utf8_matches
17777 = add_cp_to_invlist(
17778 upper_latin1_only_utf8_matches,
17784 SvREFCNT_dec_NN(fold_intersection);
17787 /* Now that we have finished adding all the folds, there is no reason
17788 * to keep the foldable list separate */
17789 _invlist_union(cp_list, cp_foldable_list, &cp_list);
17790 SvREFCNT_dec_NN(cp_foldable_list);
17793 /* And combine the result (if any) with any inversion lists from posix
17794 * classes. The lists are kept separate up to now because we don't want to
17795 * fold the classes */
17796 if (simple_posixes) { /* These are the classes known to be unaffected by
17799 _invlist_union(cp_list, simple_posixes, &cp_list);
17800 SvREFCNT_dec_NN(simple_posixes);
17803 cp_list = simple_posixes;
17806 if (posixes || nposixes) {
17807 if (! DEPENDS_SEMANTICS) {
17809 /* For everything but /d, we can just add the current 'posixes' and
17810 * 'nposixes' to the main list */
17813 _invlist_union(cp_list, posixes, &cp_list);
17814 SvREFCNT_dec_NN(posixes);
17822 _invlist_union(cp_list, nposixes, &cp_list);
17823 SvREFCNT_dec_NN(nposixes);
17826 cp_list = nposixes;
17831 /* Under /d, things like \w match upper Latin1 characters only if
17832 * the target string is in UTF-8. But things like \W match all the
17833 * upper Latin1 characters if the target string is not in UTF-8.
17835 * Handle the case with something like \W separately */
17837 SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1, NULL);
17839 /* A complemented posix class matches all upper Latin1
17840 * characters if not in UTF-8. And it matches just certain
17841 * ones when in UTF-8. That means those certain ones are
17842 * matched regardless, so can just be added to the
17843 * unconditional list */
17845 _invlist_union(cp_list, nposixes, &cp_list);
17846 SvREFCNT_dec_NN(nposixes);
17850 cp_list = nposixes;
17853 /* Likewise for 'posixes' */
17854 _invlist_union(posixes, cp_list, &cp_list);
17856 /* Likewise for anything else in the range that matched only
17858 if (upper_latin1_only_utf8_matches) {
17859 _invlist_union(cp_list,
17860 upper_latin1_only_utf8_matches,
17862 SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
17863 upper_latin1_only_utf8_matches = NULL;
17866 /* If we don't match all the upper Latin1 characters regardless
17867 * of UTF-8ness, we have to set a flag to match the rest when
17869 _invlist_subtract(only_non_utf8_list, cp_list,
17870 &only_non_utf8_list);
17871 if (_invlist_len(only_non_utf8_list) != 0) {
17872 anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
17874 SvREFCNT_dec_NN(only_non_utf8_list);
17877 /* Here there were no complemented posix classes. That means
17878 * the upper Latin1 characters in 'posixes' match only when the
17879 * target string is in UTF-8. So we have to add them to the
17880 * list of those types of code points, while adding the
17881 * remainder to the unconditional list.
17883 * First calculate what they are */
17884 SV* nonascii_but_latin1_properties = NULL;
17885 _invlist_intersection(posixes, PL_UpperLatin1,
17886 &nonascii_but_latin1_properties);
17888 /* And add them to the final list of such characters. */
17889 _invlist_union(upper_latin1_only_utf8_matches,
17890 nonascii_but_latin1_properties,
17891 &upper_latin1_only_utf8_matches);
17893 /* Remove them from what now becomes the unconditional list */
17894 _invlist_subtract(posixes, nonascii_but_latin1_properties,
17897 /* And add those unconditional ones to the final list */
17899 _invlist_union(cp_list, posixes, &cp_list);
17900 SvREFCNT_dec_NN(posixes);
17907 SvREFCNT_dec(nonascii_but_latin1_properties);
17909 /* Get rid of any characters from the conditional list that we
17910 * now know are matched unconditionally, which may make that
17912 _invlist_subtract(upper_latin1_only_utf8_matches,
17914 &upper_latin1_only_utf8_matches);
17915 if (_invlist_len(upper_latin1_only_utf8_matches) == 0) {
17916 SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
17917 upper_latin1_only_utf8_matches = NULL;
17923 /* And combine the result (if any) with any inversion list from properties.
17924 * The lists are kept separate up to now so that we can distinguish the two
17925 * in regards to matching above-Unicode. A run-time warning is generated
17926 * if a Unicode property is matched against a non-Unicode code point. But,
17927 * we allow user-defined properties to match anything, without any warning,
17928 * and we also suppress the warning if there is a portion of the character
17929 * class that isn't a Unicode property, and which matches above Unicode, \W
17930 * or [\x{110000}] for example.
17931 * (Note that in this case, unlike the Posix one above, there is no
17932 * <upper_latin1_only_utf8_matches>, because having a Unicode property
17933 * forces Unicode semantics */
17937 /* If it matters to the final outcome, see if a non-property
17938 * component of the class matches above Unicode. If so, the
17939 * warning gets suppressed. This is true even if just a single
17940 * such code point is specified, as, though not strictly correct if
17941 * another such code point is matched against, the fact that they
17942 * are using above-Unicode code points indicates they should know
17943 * the issues involved */
17945 warn_super = ! (invert
17946 ^ (invlist_highest(cp_list) > PERL_UNICODE_MAX));
17949 _invlist_union(properties, cp_list, &cp_list);
17950 SvREFCNT_dec_NN(properties);
17953 cp_list = properties;
17958 |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
17960 /* Because an ANYOF node is the only one that warns, this node
17961 * can't be optimized into something else */
17962 optimizable = FALSE;
17966 /* Here, we have calculated what code points should be in the character
17969 * Now we can see about various optimizations. Fold calculation (which we
17970 * did above) needs to take place before inversion. Otherwise /[^k]/i
17971 * would invert to include K, which under /i would match k, which it
17972 * shouldn't. Therefore we can't invert folded locale now, as it won't be
17973 * folded until runtime */
17975 /* If we didn't do folding, it's because some information isn't available
17976 * until runtime; set the run-time fold flag for these We know to set the
17977 * flag if we have a non-NULL list for UTF-8 locales, or the class matches
17978 * at least one 0-255 range code point */
17981 /* Some things on the list might be unconditionally included because of
17982 * other components. Remove them, and clean up the list if it goes to
17984 if (only_utf8_locale_list && cp_list) {
17985 _invlist_subtract(only_utf8_locale_list, cp_list,
17986 &only_utf8_locale_list);
17988 if (_invlist_len(only_utf8_locale_list) == 0) {
17989 SvREFCNT_dec_NN(only_utf8_locale_list);
17990 only_utf8_locale_list = NULL;
17993 if ( only_utf8_locale_list
17994 || (cp_list && ( _invlist_contains_cp(cp_list, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE)
17995 || _invlist_contains_cp(cp_list, LATIN_SMALL_LETTER_DOTLESS_I))))
17997 has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18000 | ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
18002 else if (cp_list) { /* Look to see if a 0-255 code point is in list */
18004 invlist_iterinit(cp_list);
18005 if (invlist_iternext(cp_list, &start, &end) && start < 256) {
18006 anyof_flags |= ANYOFL_FOLD;
18007 has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18009 invlist_iterfinish(cp_list);
18012 else if ( DEPENDS_SEMANTICS
18013 && ( upper_latin1_only_utf8_matches
18014 || (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)))
18016 RExC_seen_d_op = TRUE;
18017 has_runtime_dependency |= HAS_D_RUNTIME_DEPENDENCY;
18020 /* Optimize inverted patterns (e.g. [^a-z]) when everything is known at
18024 && ! has_runtime_dependency)
18026 _invlist_invert(cp_list);
18028 /* Clear the invert flag since have just done it here */
18033 *ret_invlist = cp_list;
18038 /* All possible optimizations below still have these characteristics.
18039 * (Multi-char folds aren't SIMPLE, but they don't get this far in this
18041 *flagp |= HASWIDTH|SIMPLE;
18043 if (anyof_flags & ANYOF_LOCALE_FLAGS) {
18044 RExC_contains_locale = 1;
18047 /* Some character classes are equivalent to other nodes. Such nodes take
18048 * up less room, and some nodes require fewer operations to execute, than
18049 * ANYOF nodes. EXACTish nodes may be joinable with adjacent nodes to
18050 * improve efficiency. */
18053 PERL_UINT_FAST8_T i;
18054 Size_t partial_cp_count = 0;
18055 UV start[MAX_FOLD_FROMS+1] = { 0 }; /* +1 for the folded-to char */
18056 UV end[MAX_FOLD_FROMS+1] = { 0 };
18058 if (cp_list) { /* Count the code points in enough ranges that we would
18059 see all the ones possible in any fold in this version
18062 invlist_iterinit(cp_list);
18063 for (i = 0; i <= MAX_FOLD_FROMS; i++) {
18064 if (! invlist_iternext(cp_list, &start[i], &end[i])) {
18067 partial_cp_count += end[i] - start[i] + 1;
18070 invlist_iterfinish(cp_list);
18073 /* If we know at compile time that this matches every possible code
18074 * point, any run-time dependencies don't matter */
18075 if (start[0] == 0 && end[0] == UV_MAX) {
18077 ret = reganode(pRExC_state, OPFAIL, 0);
18080 ret = reg_node(pRExC_state, SANY);
18086 /* Similarly, for /l posix classes, if both a class and its
18087 * complement match, any run-time dependencies don't matter */
18089 for (namedclass = 0; namedclass < ANYOF_POSIXL_MAX;
18092 if ( POSIXL_TEST(posixl, namedclass) /* class */
18093 && POSIXL_TEST(posixl, namedclass + 1)) /* its complement */
18096 ret = reganode(pRExC_state, OPFAIL, 0);
18099 ret = reg_node(pRExC_state, SANY);
18105 /* For well-behaved locales, some classes are subsets of others,
18106 * so complementing the subset and including the non-complemented
18107 * superset should match everything, like [\D[:alnum:]], and
18108 * [[:^alpha:][:alnum:]], but some implementations of locales are
18109 * buggy, and khw thinks its a bad idea to have optimization change
18110 * behavior, even if it avoids an OS bug in a given case */
18112 #define isSINGLE_BIT_SET(n) isPOWER_OF_2(n)
18114 /* If is a single posix /l class, can optimize to just that op.
18115 * Such a node will not match anything in the Latin1 range, as that
18116 * is not determinable until runtime, but will match whatever the
18117 * class does outside that range. (Note that some classes won't
18118 * match anything outside the range, like [:ascii:]) */
18119 if ( isSINGLE_BIT_SET(posixl)
18120 && (partial_cp_count == 0 || start[0] > 255))
18123 SV * class_above_latin1 = NULL;
18124 bool already_inverted;
18125 bool are_equivalent;
18127 /* Compute which bit is set, which is the same thing as, e.g.,
18128 * ANYOF_CNTRL. From
18129 * https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn
18131 static const int MultiplyDeBruijnBitPosition2[32] =
18133 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
18134 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
18137 namedclass = MultiplyDeBruijnBitPosition2[(posixl
18138 * 0x077CB531U) >> 27];
18139 classnum = namedclass_to_classnum(namedclass);
18141 /* The named classes are such that the inverted number is one
18142 * larger than the non-inverted one */
18143 already_inverted = namedclass
18144 - classnum_to_namedclass(classnum);
18146 /* Create an inversion list of the official property, inverted
18147 * if the constructed node list is inverted, and restricted to
18148 * only the above latin1 code points, which are the only ones
18149 * known at compile time */
18150 _invlist_intersection_maybe_complement_2nd(
18152 PL_XPosix_ptrs[classnum],
18154 &class_above_latin1);
18155 are_equivalent = _invlistEQ(class_above_latin1, cp_list,
18157 SvREFCNT_dec_NN(class_above_latin1);
18159 if (are_equivalent) {
18161 /* Resolve the run-time inversion flag with this possibly
18162 * inverted class */
18163 invert = invert ^ already_inverted;
18165 ret = reg_node(pRExC_state,
18166 POSIXL + invert * (NPOSIXL - POSIXL));
18167 FLAGS(REGNODE_p(ret)) = classnum;
18173 /* khw can't think of any other possible transformation involving
18175 if (has_runtime_dependency & HAS_USER_DEFINED_PROPERTY) {
18179 if (! has_runtime_dependency) {
18181 /* If the list is empty, nothing matches. This happens, for
18182 * example, when a Unicode property that doesn't match anything is
18183 * the only element in the character class (perluniprops.pod notes
18184 * such properties). */
18185 if (partial_cp_count == 0) {
18187 ret = reg_node(pRExC_state, SANY);
18190 ret = reganode(pRExC_state, OPFAIL, 0);
18196 /* If matches everything but \n */
18197 if ( start[0] == 0 && end[0] == '\n' - 1
18198 && start[1] == '\n' + 1 && end[1] == UV_MAX)
18201 ret = reg_node(pRExC_state, REG_ANY);
18207 /* Next see if can optimize classes that contain just a few code points
18208 * into an EXACTish node. The reason to do this is to let the
18209 * optimizer join this node with adjacent EXACTish ones.
18211 * An EXACTFish node can be generated even if not under /i, and vice
18212 * versa. But care must be taken. An EXACTFish node has to be such
18213 * that it only matches precisely the code points in the class, but we
18214 * want to generate the least restrictive one that does that, to
18215 * increase the odds of being able to join with an adjacent node. For
18216 * example, if the class contains [kK], we have to make it an EXACTFAA
18217 * node to prevent the KELVIN SIGN from matching. Whether we are under
18218 * /i or not is irrelevant in this case. Less obvious is the pattern
18219 * qr/[\x{02BC}]n/i. U+02BC is MODIFIER LETTER APOSTROPHE. That is
18220 * supposed to match the single character U+0149 LATIN SMALL LETTER N
18221 * PRECEDED BY APOSTROPHE. And so even though there is no simple fold
18222 * that includes \X{02BC}, there is a multi-char fold that does, and so
18223 * the node generated for it must be an EXACTFish one. On the other
18224 * hand qr/:/i should generate a plain EXACT node since the colon
18225 * participates in no fold whatsoever, and having it EXACT tells the
18226 * optimizer the target string cannot match unless it has a colon in
18229 * We don't typically generate an EXACTish node if doing so would
18230 * require changing the pattern to UTF-8, as that affects /d and
18231 * otherwise is slower. However, under /i, not changing to UTF-8 can
18232 * miss some potential multi-character folds. We calculate the
18233 * EXACTish node, and then decide if something would be missed if we
18238 /* Only try if there are no more code points in the class than
18239 * in the max possible fold */
18240 && partial_cp_count > 0 && partial_cp_count <= MAX_FOLD_FROMS + 1
18242 && (start[0] < 256 || UTF || FOLD))
18244 if (partial_cp_count == 1 && ! upper_latin1_only_utf8_matches)
18246 /* We can always make a single code point class into an
18247 * EXACTish node. */
18251 /* Here is /l: Use EXACTL, except /li indicates EXACTFL,
18252 * as that means there is a fold not known until runtime so
18253 * shows as only a single code point here. */
18254 op = (FOLD) ? EXACTFL : EXACTL;
18256 else if (! FOLD) { /* Not /l and not /i */
18257 op = (start[0] < 256) ? EXACT : EXACT_ONLY8;
18259 else if (start[0] < 256) { /* /i, not /l, and the code point is
18262 /* Under /i, it gets a little tricky. A code point that
18263 * doesn't participate in a fold should be an EXACT node.
18264 * We know this one isn't the result of a simple fold, or
18265 * there'd be more than one code point in the list, but it
18266 * could be part of a multi- character fold. In that case
18267 * we better not create an EXACT node, as we would wrongly
18268 * be telling the optimizer that this code point must be in
18269 * the target string, and that is wrong. This is because
18270 * if the sequence around this code point forms a
18271 * multi-char fold, what needs to be in the string could be
18272 * the code point that folds to the sequence.
18274 * This handles the case of below-255 code points, as we
18275 * have an easy look up for those. The next clause handles
18276 * the above-256 one */
18277 op = IS_IN_SOME_FOLD_L1(start[0])
18281 else { /* /i, larger code point. Since we are under /i, and
18282 have just this code point, we know that it can't
18283 fold to something else, so PL_InMultiCharFold
18285 op = _invlist_contains_cp(PL_InMultiCharFold,
18293 else if ( ! (has_runtime_dependency & ~HAS_D_RUNTIME_DEPENDENCY)
18294 && _invlist_contains_cp(PL_in_some_fold, start[0]))
18296 /* Here, the only runtime dependency, if any, is from /d, and
18297 * the class matches more than one code point, and the lowest
18298 * code point participates in some fold. It might be that the
18299 * other code points are /i equivalent to this one, and hence
18300 * they would representable by an EXACTFish node. Above, we
18301 * eliminated classes that contain too many code points to be
18302 * EXACTFish, with the test for MAX_FOLD_FROMS
18304 * First, special case the ASCII fold pairs, like 'B' and 'b'.
18305 * We do this because we have EXACTFAA at our disposal for the
18307 if (partial_cp_count == 2 && isASCII(start[0])) {
18309 /* The only ASCII characters that participate in folds are
18311 assert(isALPHA(start[0]));
18312 if ( end[0] == start[0] /* First range is a single
18313 character, so 2nd exists */
18314 && isALPHA_FOLD_EQ(start[0], start[1]))
18317 /* Here, is part of an ASCII fold pair */
18319 if ( ASCII_FOLD_RESTRICTED
18320 || HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(start[0]))
18322 /* If the second clause just above was true, it
18323 * means we can't be under /i, or else the list
18324 * would have included more than this fold pair.
18325 * Therefore we have to exclude the possibility of
18326 * whatever else it is that folds to these, by
18327 * using EXACTFAA */
18330 else if (HAS_NONLATIN1_FOLD_CLOSURE(start[0])) {
18332 /* Here, there's no simple fold that start[0] is part
18333 * of, but there is a multi-character one. If we
18334 * are not under /i, we want to exclude that
18335 * possibility; if under /i, we want to include it
18337 op = (FOLD) ? EXACTFU : EXACTFAA;
18341 /* Here, the only possible fold start[0] particpates in
18342 * is with start[1]. /i or not isn't relevant */
18346 value = toFOLD(start[0]);
18349 else if ( ! upper_latin1_only_utf8_matches
18350 || ( _invlist_len(upper_latin1_only_utf8_matches)
18353 invlist_highest(upper_latin1_only_utf8_matches)]
18356 /* Here, the smallest character is non-ascii or there are
18357 * more than 2 code points matched by this node. Also, we
18358 * either don't have /d UTF-8 dependent matches, or if we
18359 * do, they look like they could be a single character that
18360 * is the fold of the lowest one in the always-match list.
18361 * This test quickly excludes most of the false positives
18362 * when there are /d UTF-8 depdendent matches. These are
18363 * like LATIN CAPITAL LETTER A WITH GRAVE matching LATIN
18364 * SMALL LETTER A WITH GRAVE iff the target string is
18365 * UTF-8. (We don't have to worry above about exceeding
18366 * the array bounds of PL_fold_latin1[] because any code
18367 * point in 'upper_latin1_only_utf8_matches' is below 256.)
18369 * EXACTFAA would apply only to pairs (hence exactly 2 code
18370 * points) in the ASCII range, so we can't use it here to
18371 * artificially restrict the fold domain, so we check if
18372 * the class does or does not match some EXACTFish node.
18373 * Further, if we aren't under /i, and and the folded-to
18374 * character is part of a multi-character fold, we can't do
18375 * this optimization, as the sequence around it could be
18376 * that multi-character fold, and we don't here know the
18377 * context, so we have to assume it is that multi-char
18378 * fold, to prevent potential bugs.
18380 * To do the general case, we first find the fold of the
18381 * lowest code point (which may be higher than the lowest
18382 * one), then find everything that folds to it. (The data
18383 * structure we have only maps from the folded code points,
18384 * so we have to do the earlier step.) */
18387 U8 foldbuf[UTF8_MAXBYTES_CASE];
18388 UV folded = _to_uni_fold_flags(start[0],
18389 foldbuf, &foldlen, 0);
18390 unsigned int first_fold;
18391 const unsigned int * remaining_folds;
18392 Size_t folds_to_this_cp_count = _inverse_folds(
18396 Size_t folds_count = folds_to_this_cp_count + 1;
18397 SV * fold_list = _new_invlist(folds_count);
18400 /* If there are UTF-8 dependent matches, create a temporary
18401 * list of what this node matches, including them. */
18402 SV * all_cp_list = NULL;
18403 SV ** use_this_list = &cp_list;
18405 if (upper_latin1_only_utf8_matches) {
18406 all_cp_list = _new_invlist(0);
18407 use_this_list = &all_cp_list;
18408 _invlist_union(cp_list,
18409 upper_latin1_only_utf8_matches,
18413 /* Having gotten everything that participates in the fold
18414 * containing the lowest code point, we turn that into an
18415 * inversion list, making sure everything is included. */
18416 fold_list = add_cp_to_invlist(fold_list, start[0]);
18417 fold_list = add_cp_to_invlist(fold_list, folded);
18418 if (folds_to_this_cp_count > 0) {
18419 fold_list = add_cp_to_invlist(fold_list, first_fold);
18420 for (i = 0; i + 1 < folds_to_this_cp_count; i++) {
18421 fold_list = add_cp_to_invlist(fold_list,
18422 remaining_folds[i]);
18426 /* If the fold list is identical to what's in this ANYOF
18427 * node, the node can be represented by an EXACTFish one
18429 if (_invlistEQ(*use_this_list, fold_list,
18430 0 /* Don't complement */ )
18433 /* But, we have to be careful, as mentioned above.
18434 * Just the right sequence of characters could match
18435 * this if it is part of a multi-character fold. That
18436 * IS what we want if we are under /i. But it ISN'T
18437 * what we want if not under /i, as it could match when
18438 * it shouldn't. So, when we aren't under /i and this
18439 * character participates in a multi-char fold, we
18440 * don't optimize into an EXACTFish node. So, for each
18441 * case below we have to check if we are folding
18442 * and if not, if it is not part of a multi-char fold.
18444 if (start[0] > 255) { /* Highish code point */
18445 if (FOLD || ! _invlist_contains_cp(
18446 PL_InMultiCharFold, folded))
18450 : (ASCII_FOLD_RESTRICTED)
18455 } /* Below, the lowest code point < 256 */
18458 && DEPENDS_SEMANTICS)
18459 { /* An EXACTF node containing a single character
18460 's', can be an EXACTFU if it doesn't get
18461 joined with an adjacent 's' */
18462 op = EXACTFU_S_EDGE;
18466 || ! HAS_NONLATIN1_FOLD_CLOSURE(start[0]))
18468 if (upper_latin1_only_utf8_matches) {
18471 /* We can't use the fold, as that only matches
18475 else if ( UNLIKELY(start[0] == MICRO_SIGN)
18477 { /* EXACTFUP is a special node for this
18479 op = (ASCII_FOLD_RESTRICTED)
18482 value = MICRO_SIGN;
18484 else if ( ASCII_FOLD_RESTRICTED
18485 && ! isASCII(start[0]))
18486 { /* For ASCII under /iaa, we can use EXACTFU
18498 SvREFCNT_dec_NN(fold_list);
18499 SvREFCNT_dec(all_cp_list);
18505 /* Here, we have calculated what EXACTish node we would use.
18506 * But we don't use it if it would require converting the
18507 * pattern to UTF-8, unless not using it could cause us to miss
18508 * some folds (hence be buggy) */
18510 if (! UTF && value > 255) {
18511 SV * in_multis = NULL;
18515 /* If there is no code point that is part of a multi-char
18516 * fold, then there aren't any matches, so we don't do this
18517 * optimization. Otherwise, it could match depending on
18518 * the context around us, so we do upgrade */
18519 _invlist_intersection(PL_InMultiCharFold, cp_list, &in_multis);
18520 if (UNLIKELY(_invlist_len(in_multis) != 0)) {
18521 REQUIRE_UTF8(flagp);
18529 U8 len = (UTF) ? UVCHR_SKIP(value) : 1;
18531 ret = regnode_guts(pRExC_state, op, len, "exact");
18532 FILL_NODE(ret, op);
18533 RExC_emit += 1 + STR_SZ(len);
18534 STR_LEN(REGNODE_p(ret)) = len;
18536 *STRING(REGNODE_p(ret)) = value;
18539 uvchr_to_utf8((U8 *) STRING(REGNODE_p(ret)), value);
18546 if (! has_runtime_dependency) {
18548 /* See if this can be turned into an ANYOFM node. Think about the
18549 * bit patterns in two different bytes. In some positions, the
18550 * bits in each will be 1; and in other positions both will be 0;
18551 * and in some positions the bit will be 1 in one byte, and 0 in
18552 * the other. Let 'n' be the number of positions where the bits
18553 * differ. We create a mask which has exactly 'n' 0 bits, each in
18554 * a position where the two bytes differ. Now take the set of all
18555 * bytes that when ANDed with the mask yield the same result. That
18556 * set has 2**n elements, and is representable by just two 8 bit
18557 * numbers: the result and the mask. Importantly, matching the set
18558 * can be vectorized by creating a word full of the result bytes,
18559 * and a word full of the mask bytes, yielding a significant speed
18560 * up. Here, see if this node matches such a set. As a concrete
18561 * example consider [01], and the byte representing '0' which is
18562 * 0x30 on ASCII machines. It has the bits 0011 0000. Take the
18563 * mask 1111 1110. If we AND 0x31 and 0x30 with that mask we get
18564 * 0x30. Any other bytes ANDed yield something else. So [01],
18565 * which is a common usage, is optimizable into ANYOFM, and can
18566 * benefit from the speed up. We can only do this on UTF-8
18567 * invariant bytes, because they have the same bit patterns under
18569 PERL_UINT_FAST8_T inverted = 0;
18571 const PERL_UINT_FAST8_T max_permissible = 0xFF;
18573 const PERL_UINT_FAST8_T max_permissible = 0x7F;
18575 /* If doesn't fit the criteria for ANYOFM, invert and try again.
18576 * If that works we will instead later generate an NANYOFM, and
18577 * invert back when through */
18578 if (invlist_highest(cp_list) > max_permissible) {
18579 _invlist_invert(cp_list);
18583 if (invlist_highest(cp_list) <= max_permissible) {
18584 UV this_start, this_end;
18585 UV lowest_cp = UV_MAX; /* inited to suppress compiler warn */
18586 U8 bits_differing = 0;
18587 Size_t full_cp_count = 0;
18588 bool first_time = TRUE;
18590 /* Go through the bytes and find the bit positions that differ
18592 invlist_iterinit(cp_list);
18593 while (invlist_iternext(cp_list, &this_start, &this_end)) {
18594 unsigned int i = this_start;
18597 if (! UVCHR_IS_INVARIANT(i)) {
18601 first_time = FALSE;
18602 lowest_cp = this_start;
18604 /* We have set up the code point to compare with.
18605 * Don't compare it with itself */
18609 /* Find the bit positions that differ from the lowest code
18610 * point in the node. Keep track of all such positions by
18612 for (; i <= this_end; i++) {
18613 if (! UVCHR_IS_INVARIANT(i)) {
18617 bits_differing |= i ^ lowest_cp;
18620 full_cp_count += this_end - this_start + 1;
18622 invlist_iterfinish(cp_list);
18624 /* At the end of the loop, we count how many bits differ from
18625 * the bits in lowest code point, call the count 'd'. If the
18626 * set we found contains 2**d elements, it is the closure of
18627 * all code points that differ only in those bit positions. To
18628 * convince yourself of that, first note that the number in the
18629 * closure must be a power of 2, which we test for. The only
18630 * way we could have that count and it be some differing set,
18631 * is if we got some code points that don't differ from the
18632 * lowest code point in any position, but do differ from each
18633 * other in some other position. That means one code point has
18634 * a 1 in that position, and another has a 0. But that would
18635 * mean that one of them differs from the lowest code point in
18636 * that position, which possibility we've already excluded. */
18637 if ( (inverted || full_cp_count > 1)
18638 && full_cp_count == 1U << PL_bitcount[bits_differing])
18642 op = ANYOFM + inverted;;
18644 /* We need to make the bits that differ be 0's */
18645 ANYOFM_mask = ~ bits_differing; /* This goes into FLAGS */
18647 /* The argument is the lowest code point */
18648 ret = reganode(pRExC_state, op, lowest_cp);
18649 FLAGS(REGNODE_p(ret)) = ANYOFM_mask;
18655 _invlist_invert(cp_list);
18663 if (! (anyof_flags & ANYOF_LOCALE_FLAGS)) {
18664 PERL_UINT_FAST8_T type;
18665 SV * intersection = NULL;
18666 SV* d_invlist = NULL;
18668 /* See if this matches any of the POSIX classes. The POSIXA and
18669 * POSIXD ones are about the same speed as ANYOF ops, but take less
18670 * room; the ones that have above-Latin1 code point matches are
18671 * somewhat faster than ANYOF. */
18673 for (type = POSIXA; type >= POSIXD; type--) {
18676 if (type == POSIXL) { /* But not /l posix classes */
18680 for (posix_class = 0;
18681 posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC;
18684 SV** our_code_points = &cp_list;
18685 SV** official_code_points;
18688 if (type == POSIXA) {
18689 official_code_points = &PL_Posix_ptrs[posix_class];
18692 official_code_points = &PL_XPosix_ptrs[posix_class];
18695 /* Skip non-existent classes of this type. e.g. \v only
18696 * has an entry in PL_XPosix_ptrs */
18697 if (! *official_code_points) {
18701 /* Try both the regular class, and its inversion */
18702 for (try_inverted = 0; try_inverted < 2; try_inverted++) {
18703 bool this_inverted = invert ^ try_inverted;
18705 if (type != POSIXD) {
18707 /* This class that isn't /d can't match if we have
18708 * /d dependencies */
18709 if (has_runtime_dependency
18710 & HAS_D_RUNTIME_DEPENDENCY)
18715 else /* is /d */ if (! this_inverted) {
18717 /* /d classes don't match anything non-ASCII below
18718 * 256 unconditionally (which cp_list contains) */
18719 _invlist_intersection(cp_list, PL_UpperLatin1,
18721 if (_invlist_len(intersection) != 0) {
18725 SvREFCNT_dec(d_invlist);
18726 d_invlist = invlist_clone(cp_list, NULL);
18728 /* But under UTF-8 it turns into using /u rules.
18729 * Add the things it matches under these conditions
18730 * so that we check below that these are identical
18731 * to what the tested class should match */
18732 if (upper_latin1_only_utf8_matches) {
18735 upper_latin1_only_utf8_matches,
18738 our_code_points = &d_invlist;
18740 else { /* POSIXD, inverted. If this doesn't have this
18741 flag set, it isn't /d. */
18742 if (! (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
18746 our_code_points = &cp_list;
18749 /* Here, have weeded out some things. We want to see
18750 * if the list of characters this node contains
18751 * ('*our_code_points') precisely matches those of the
18752 * class we are currently checking against
18753 * ('*official_code_points'). */
18754 if (_invlistEQ(*our_code_points,
18755 *official_code_points,
18758 /* Here, they precisely match. Optimize this ANYOF
18759 * node into its equivalent POSIX one of the
18760 * correct type, possibly inverted */
18761 ret = reg_node(pRExC_state, (try_inverted)
18765 FLAGS(REGNODE_p(ret)) = posix_class;
18766 SvREFCNT_dec(d_invlist);
18767 SvREFCNT_dec(intersection);
18773 SvREFCNT_dec(d_invlist);
18774 SvREFCNT_dec(intersection);
18777 /* If didn't find an optimization and there is no need for a
18778 * bitmap, optimize to indicate that */
18779 if ( start[0] >= NUM_ANYOF_CODE_POINTS
18781 && ! upper_latin1_only_utf8_matches)
18785 } /* End of seeing if can optimize it into a different node */
18787 is_anyof: /* It's going to be an ANYOF node. */
18788 if (op != ANYOFH) {
18789 op = (has_runtime_dependency & HAS_D_RUNTIME_DEPENDENCY)
18798 ret = regnode_guts(pRExC_state, op, regarglen[op], "anyof");
18799 FILL_NODE(ret, op); /* We set the argument later */
18800 RExC_emit += 1 + regarglen[op];
18801 ANYOF_FLAGS(REGNODE_p(ret)) = anyof_flags;
18803 /* Here, <cp_list> contains all the code points we can determine at
18804 * compile time that match under all conditions. Go through it, and
18805 * for things that belong in the bitmap, put them there, and delete from
18806 * <cp_list>. While we are at it, see if everything above 255 is in the
18807 * list, and if so, set a flag to speed up execution */
18809 populate_ANYOF_from_invlist(REGNODE_p(ret), &cp_list);
18812 ANYOF_POSIXL_SET_TO_BITMAP(REGNODE_p(ret), posixl);
18816 ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_INVERT;
18819 /* Here, the bitmap has been populated with all the Latin1 code points that
18820 * always match. Can now add to the overall list those that match only
18821 * when the target string is UTF-8 (<upper_latin1_only_utf8_matches>).
18823 if (upper_latin1_only_utf8_matches) {
18825 _invlist_union(cp_list,
18826 upper_latin1_only_utf8_matches,
18828 SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
18831 cp_list = upper_latin1_only_utf8_matches;
18833 ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
18836 set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
18837 (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
18839 only_utf8_locale_list);
18844 /* Here, the node is getting optimized into something that's not an ANYOF
18845 * one. Finish up. */
18847 Set_Node_Offset_Length(REGNODE_p(ret), orig_parse - RExC_start,
18848 RExC_parse - orig_parse);;
18849 SvREFCNT_dec(cp_list);;
18853 #undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
18856 S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state,
18857 regnode* const node,
18859 SV* const runtime_defns,
18860 SV* const only_utf8_locale_list)
18862 /* Sets the arg field of an ANYOF-type node 'node', using information about
18863 * the node passed-in. If there is nothing outside the node's bitmap, the
18864 * arg is set to ANYOF_ONLY_HAS_BITMAP. Otherwise, it sets the argument to
18865 * the count returned by add_data(), having allocated and stored an array,
18868 * av[0] stores the inversion list defining this class as far as known at
18869 * this time, or PL_sv_undef if nothing definite is now known.
18870 * av[1] stores the inversion list of code points that match only if the
18871 * current locale is UTF-8, or if none, PL_sv_undef if there is an
18872 * av[2], or no entry otherwise.
18873 * av[2] stores the list of user-defined properties whose subroutine
18874 * definitions aren't known at this time, or no entry if none. */
18878 PERL_ARGS_ASSERT_SET_ANYOF_ARG;
18880 if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) {
18881 assert(! (ANYOF_FLAGS(node)
18882 & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP));
18883 ARG_SET(node, ANYOF_ONLY_HAS_BITMAP);
18886 AV * const av = newAV();
18890 av_store(av, INVLIST_INDEX, cp_list);
18893 if (only_utf8_locale_list) {
18894 av_store(av, ONLY_LOCALE_MATCHES_INDEX, only_utf8_locale_list);
18897 if (runtime_defns) {
18898 av_store(av, DEFERRED_USER_DEFINED_INDEX, SvREFCNT_inc(runtime_defns));
18901 rv = newRV_noinc(MUTABLE_SV(av));
18902 n = add_data(pRExC_state, STR_WITH_LEN("s"));
18903 RExC_rxi->data->data[n] = (void*)rv;
18908 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
18910 Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog,
18911 const regnode* node,
18914 SV** only_utf8_locale_ptr,
18915 SV** output_invlist)
18918 /* For internal core use only.
18919 * Returns the inversion list for the input 'node' in the regex 'prog'.
18920 * If <doinit> is 'true', will attempt to create the inversion list if not
18922 * If <listsvp> is non-null, will return the printable contents of the
18923 * property definition. This can be used to get debugging information
18924 * even before the inversion list exists, by calling this function with
18925 * 'doinit' set to false, in which case the components that will be used
18926 * to eventually create the inversion list are returned (in a printable
18928 * If <only_utf8_locale_ptr> is not NULL, it is where this routine is to
18929 * store an inversion list of code points that should match only if the
18930 * execution-time locale is a UTF-8 one.
18931 * If <output_invlist> is not NULL, it is where this routine is to store an
18932 * inversion list of the code points that would be instead returned in
18933 * <listsvp> if this were NULL. Thus, what gets output in <listsvp>
18934 * when this parameter is used, is just the non-code point data that
18935 * will go into creating the inversion list. This currently should be just
18936 * user-defined properties whose definitions were not known at compile
18937 * time. Using this parameter allows for easier manipulation of the
18938 * inversion list's data by the caller. It is illegal to call this
18939 * function with this parameter set, but not <listsvp>
18941 * Tied intimately to how S_set_ANYOF_arg sets up the data structure. Note
18942 * that, in spite of this function's name, the inversion list it returns
18943 * may include the bitmap data as well */
18945 SV *si = NULL; /* Input initialization string */
18946 SV* invlist = NULL;
18948 RXi_GET_DECL(prog, progi);
18949 const struct reg_data * const data = prog ? progi->data : NULL;
18951 PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA;
18952 assert(! output_invlist || listsvp);
18954 if (data && data->count) {
18955 const U32 n = ARG(node);
18957 if (data->what[n] == 's') {
18958 SV * const rv = MUTABLE_SV(data->data[n]);
18959 AV * const av = MUTABLE_AV(SvRV(rv));
18960 SV **const ary = AvARRAY(av);
18962 invlist = ary[INVLIST_INDEX];
18964 if (av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX) {
18965 *only_utf8_locale_ptr = ary[ONLY_LOCALE_MATCHES_INDEX];
18968 if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
18969 si = ary[DEFERRED_USER_DEFINED_INDEX];
18972 if (doinit && (si || invlist)) {
18975 SV * msg = newSVpvs_flags("", SVs_TEMP);
18977 SV * prop_definition = handle_user_defined_property(
18978 "", 0, FALSE, /* There is no \p{}, \P{} */
18979 SvPVX_const(si)[1] - '0', /* /i or not has been
18980 stored here for just
18982 TRUE, /* run time */
18983 si, /* The property definition */
18986 0 /* base level call */
18990 assert(prop_definition == NULL);
18992 Perl_croak(aTHX_ "%" UTF8f,
18993 UTF8fARG(SvUTF8(msg), SvCUR(msg), SvPVX(msg)));
18997 _invlist_union(invlist, prop_definition, &invlist);
18998 SvREFCNT_dec_NN(prop_definition);
19001 invlist = prop_definition;
19004 STATIC_ASSERT_STMT(ONLY_LOCALE_MATCHES_INDEX == 1 + INVLIST_INDEX);
19005 STATIC_ASSERT_STMT(DEFERRED_USER_DEFINED_INDEX == 1 + ONLY_LOCALE_MATCHES_INDEX);
19007 av_store(av, INVLIST_INDEX, invlist);
19008 av_fill(av, (ary[ONLY_LOCALE_MATCHES_INDEX])
19009 ? ONLY_LOCALE_MATCHES_INDEX:
19017 /* If requested, return a printable version of what this ANYOF node matches
19020 SV* matches_string = NULL;
19022 /* This function can be called at compile-time, before everything gets
19023 * resolved, in which case we return the currently best available
19024 * information, which is the string that will eventually be used to do
19025 * that resolving, 'si' */
19027 /* Here, we only have 'si' (and possibly some passed-in data in
19028 * 'invlist', which is handled below) If the caller only wants
19029 * 'si', use that. */
19030 if (! output_invlist) {
19031 matches_string = newSVsv(si);
19034 /* But if the caller wants an inversion list of the node, we
19035 * need to parse 'si' and place as much as possible in the
19036 * desired output inversion list, making 'matches_string' only
19037 * contain the currently unresolvable things */
19038 const char *si_string = SvPVX(si);
19039 STRLEN remaining = SvCUR(si);
19043 /* Ignore everything before the first new-line */
19044 while (*si_string != '\n' && remaining > 0) {
19048 assert(remaining > 0);
19053 while (remaining > 0) {
19055 /* The data consists of just strings defining user-defined
19056 * property names, but in prior incarnations, and perhaps
19057 * somehow from pluggable regex engines, it could still
19058 * hold hex code point definitions. Each component of a
19059 * range would be separated by a tab, and each range by a
19060 * new-line. If these are found, instead add them to the
19061 * inversion list */
19062 I32 grok_flags = PERL_SCAN_SILENT_ILLDIGIT
19063 |PERL_SCAN_SILENT_NON_PORTABLE;
19064 STRLEN len = remaining;
19065 UV cp = grok_hex(si_string, &len, &grok_flags, NULL);
19067 /* If the hex decode routine found something, it should go
19068 * up to the next \n */
19069 if ( *(si_string + len) == '\n') {
19070 if (count) { /* 2nd code point on line */
19071 *output_invlist = _add_range_to_invlist(*output_invlist, prev_cp, cp);
19074 *output_invlist = add_cp_to_invlist(*output_invlist, cp);
19077 goto prepare_for_next_iteration;
19080 /* If the hex decode was instead for the lower range limit,
19081 * save it, and go parse the upper range limit */
19082 if (*(si_string + len) == '\t') {
19083 assert(count == 0);
19087 prepare_for_next_iteration:
19088 si_string += len + 1;
19089 remaining -= len + 1;
19093 /* Here, didn't find a legal hex number. Just add it from
19094 * here to the next \n */
19097 while (*(si_string + len) != '\n' && remaining > 0) {
19101 if (*(si_string + len) == '\n') {
19105 if (matches_string) {
19106 sv_catpvn(matches_string, si_string, len - 1);
19109 matches_string = newSVpvn(si_string, len - 1);
19112 sv_catpvs(matches_string, " ");
19113 } /* end of loop through the text */
19115 assert(matches_string);
19116 if (SvCUR(matches_string)) { /* Get rid of trailing blank */
19117 SvCUR_set(matches_string, SvCUR(matches_string) - 1);
19119 } /* end of has an 'si' */
19122 /* Add the stuff that's already known */
19125 /* Again, if the caller doesn't want the output inversion list, put
19126 * everything in 'matches-string' */
19127 if (! output_invlist) {
19128 if ( ! matches_string) {
19129 matches_string = newSVpvs("\n");
19131 sv_catsv(matches_string, invlist_contents(invlist,
19132 TRUE /* traditional style */
19135 else if (! *output_invlist) {
19136 *output_invlist = invlist_clone(invlist, NULL);
19139 _invlist_union(*output_invlist, invlist, output_invlist);
19143 *listsvp = matches_string;
19148 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
19150 /* reg_skipcomment()
19152 Absorbs an /x style # comment from the input stream,
19153 returning a pointer to the first character beyond the comment, or if the
19154 comment terminates the pattern without anything following it, this returns
19155 one past the final character of the pattern (in other words, RExC_end) and
19156 sets the REG_RUN_ON_COMMENT_SEEN flag.
19158 Note it's the callers responsibility to ensure that we are
19159 actually in /x mode
19163 PERL_STATIC_INLINE char*
19164 S_reg_skipcomment(RExC_state_t *pRExC_state, char* p)
19166 PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
19170 while (p < RExC_end) {
19171 if (*(++p) == '\n') {
19176 /* we ran off the end of the pattern without ending the comment, so we have
19177 * to add an \n when wrapping */
19178 RExC_seen |= REG_RUN_ON_COMMENT_SEEN;
19183 S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state,
19185 const bool force_to_xmod
19188 /* If the text at the current parse position '*p' is a '(?#...)' comment,
19189 * or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p'
19190 * is /x whitespace, advance '*p' so that on exit it points to the first
19191 * byte past all such white space and comments */
19193 const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED);
19195 PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT;
19197 assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p));
19200 if (RExC_end - (*p) >= 3
19202 && *(*p + 1) == '?'
19203 && *(*p + 2) == '#')
19205 while (*(*p) != ')') {
19206 if ((*p) == RExC_end)
19207 FAIL("Sequence (?#... not terminated");
19215 const char * save_p = *p;
19216 while ((*p) < RExC_end) {
19218 if ((len = is_PATWS_safe((*p), RExC_end, UTF))) {
19221 else if (*(*p) == '#') {
19222 (*p) = reg_skipcomment(pRExC_state, (*p));
19228 if (*p != save_p) {
19241 Advances the parse position by one byte, unless that byte is the beginning
19242 of a '(?#...)' style comment, or is /x whitespace and /x is in effect. In
19243 those two cases, the parse position is advanced beyond all such comments and
19246 This is the UTF, (?#...), and /x friendly way of saying RExC_parse++.
19250 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
19252 PERL_ARGS_ASSERT_NEXTCHAR;
19254 if (RExC_parse < RExC_end) {
19256 || UTF8_IS_INVARIANT(*RExC_parse)
19257 || UTF8_IS_START(*RExC_parse));
19259 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
19261 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
19262 FALSE /* Don't force /x */ );
19267 S_change_engine_size(pTHX_ RExC_state_t *pRExC_state, const Ptrdiff_t size)
19269 /* 'size' is the delta to add or subtract from the current memory allocated
19270 * to the regex engine being constructed */
19272 PERL_ARGS_ASSERT_CHANGE_ENGINE_SIZE;
19277 sizeof(regexp_internal) + (RExC_size + 1) * sizeof(regnode),
19278 /* +1 for REG_MAGIC */
19281 if ( RExC_rxi == NULL )
19282 FAIL("Regexp out of space");
19283 RXi_SET(RExC_rx, RExC_rxi);
19285 RExC_emit_start = RExC_rxi->program;
19287 Zero(REGNODE_p(RExC_emit), size, regnode);
19290 #ifdef RE_TRACK_PATTERN_OFFSETS
19291 Renew(RExC_offsets, 2*RExC_size+1, U32);
19293 Zero(RExC_offsets + 2*(RExC_size - size) + 1, 2 * size, U32);
19295 RExC_offsets[0] = RExC_size;
19299 STATIC regnode_offset
19300 S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name)
19302 /* Allocate a regnode for 'op', with 'extra_size' extra space. It aligns
19303 * and increments RExC_size and RExC_emit
19305 * It returns the regnode's offset into the regex engine program */
19307 const regnode_offset ret = RExC_emit;
19309 GET_RE_DEBUG_FLAGS_DECL;
19311 PERL_ARGS_ASSERT_REGNODE_GUTS;
19313 SIZE_ALIGN(RExC_size);
19314 change_engine_size(pRExC_state, (Ptrdiff_t) 1 + extra_size);
19315 NODE_ALIGN_FILL(REGNODE_p(ret));
19316 #ifndef RE_TRACK_PATTERN_OFFSETS
19317 PERL_UNUSED_ARG(name);
19318 PERL_UNUSED_ARG(op);
19320 assert(extra_size >= regarglen[op] || PL_regkind[op] == ANYOF);
19322 if (RExC_offsets) { /* MJD */
19324 ("%s:%d: (op %s) %s %" UVuf " (len %" UVuf ") (max %" UVuf ").\n",
19327 (UV)(RExC_emit) > RExC_offsets[0]
19328 ? "Overwriting end of array!\n" : "OK",
19330 (UV)(RExC_parse - RExC_start),
19331 (UV)RExC_offsets[0]));
19332 Set_Node_Offset(REGNODE_p(RExC_emit), RExC_parse + (op == END));
19339 - reg_node - emit a node
19341 STATIC regnode_offset /* Location. */
19342 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
19344 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node");
19345 regnode_offset ptr = ret;
19347 PERL_ARGS_ASSERT_REG_NODE;
19349 assert(regarglen[op] == 0);
19351 FILL_ADVANCE_NODE(ptr, op);
19357 - reganode - emit a node with an argument
19359 STATIC regnode_offset /* Location. */
19360 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
19362 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode");
19363 regnode_offset ptr = ret;
19365 PERL_ARGS_ASSERT_REGANODE;
19367 /* ANYOF are special cased to allow non-length 1 args */
19368 assert(regarglen[op] == 1);
19370 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
19375 STATIC regnode_offset
19376 S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2)
19378 /* emit a node with U32 and I32 arguments */
19380 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode");
19381 regnode_offset ptr = ret;
19383 PERL_ARGS_ASSERT_REG2LANODE;
19385 assert(regarglen[op] == 2);
19387 FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2);
19393 - reginsert - insert an operator in front of already-emitted operand
19395 * That means that on exit 'operand' is the offset of the newly inserted
19396 * operator, and the original operand has been relocated.
19398 * IMPORTANT NOTE - it is the *callers* responsibility to correctly
19399 * set up NEXT_OFF() of the inserted node if needed. Something like this:
19401 * reginsert(pRExC, OPFAIL, orig_emit, depth+1);
19402 * NEXT_OFF(orig_emit) = regarglen[OPFAIL] + NODE_STEP_REGNODE;
19404 * ALSO NOTE - FLAGS(newly-inserted-operator) will be set to 0 as well.
19407 S_reginsert(pTHX_ RExC_state_t *pRExC_state, const U8 op,
19408 const regnode_offset operand, const U32 depth)
19413 const int offset = regarglen[(U8)op];
19414 const int size = NODE_STEP_REGNODE + offset;
19415 GET_RE_DEBUG_FLAGS_DECL;
19417 PERL_ARGS_ASSERT_REGINSERT;
19418 PERL_UNUSED_CONTEXT;
19419 PERL_UNUSED_ARG(depth);
19420 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
19421 DEBUG_PARSE_FMT("inst"," - %s", PL_reg_name[op]);
19422 assert(!RExC_study_started); /* I believe we should never use reginsert once we have started
19423 studying. If this is wrong then we need to adjust RExC_recurse
19424 below like we do with RExC_open_parens/RExC_close_parens. */
19425 change_engine_size(pRExC_state, (Ptrdiff_t) size);
19426 src = REGNODE_p(RExC_emit);
19428 dst = REGNODE_p(RExC_emit);
19429 if (RExC_open_parens) {
19431 /*DEBUG_PARSE_FMT("inst"," - %" IVdf, (IV)RExC_npar);*/
19432 /* remember that RExC_npar is rex->nparens + 1,
19433 * iow it is 1 more than the number of parens seen in
19434 * the pattern so far. */
19435 for ( paren=0 ; paren < RExC_npar ; paren++ ) {
19436 /* note, RExC_open_parens[0] is the start of the
19437 * regex, it can't move. RExC_close_parens[0] is the end
19438 * of the regex, it *can* move. */
19439 if ( paren && RExC_open_parens[paren] >= operand ) {
19440 /*DEBUG_PARSE_FMT("open"," - %d", size);*/
19441 RExC_open_parens[paren] += size;
19443 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
19445 if ( RExC_close_parens[paren] >= operand ) {
19446 /*DEBUG_PARSE_FMT("close"," - %d", size);*/
19447 RExC_close_parens[paren] += size;
19449 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
19454 RExC_end_op += size;
19456 while (src > REGNODE_p(operand)) {
19457 StructCopy(--src, --dst, regnode);
19458 #ifdef RE_TRACK_PATTERN_OFFSETS
19459 if (RExC_offsets) { /* MJD 20010112 */
19461 ("%s(%d): (op %s) %s copy %" UVuf " -> %" UVuf " (max %" UVuf ").\n",
19465 (UV)(REGNODE_OFFSET(dst)) > RExC_offsets[0]
19466 ? "Overwriting end of array!\n" : "OK",
19467 (UV)REGNODE_OFFSET(src),
19468 (UV)REGNODE_OFFSET(dst),
19469 (UV)RExC_offsets[0]));
19470 Set_Node_Offset_To_R(REGNODE_OFFSET(dst), Node_Offset(src));
19471 Set_Node_Length_To_R(REGNODE_OFFSET(dst), Node_Length(src));
19476 place = REGNODE_p(operand); /* Op node, where operand used to be. */
19477 #ifdef RE_TRACK_PATTERN_OFFSETS
19478 if (RExC_offsets) { /* MJD */
19480 ("%s(%d): (op %s) %s %" UVuf " <- %" UVuf " (max %" UVuf ").\n",
19484 (UV)REGNODE_OFFSET(place) > RExC_offsets[0]
19485 ? "Overwriting end of array!\n" : "OK",
19486 (UV)REGNODE_OFFSET(place),
19487 (UV)(RExC_parse - RExC_start),
19488 (UV)RExC_offsets[0]));
19489 Set_Node_Offset(place, RExC_parse);
19490 Set_Node_Length(place, 1);
19493 src = NEXTOPER(place);
19495 FILL_NODE(operand, op);
19497 /* Zero out any arguments in the new node */
19498 Zero(src, offset, regnode);
19502 - regtail - set the next-pointer at the end of a node chain of p to val.
19503 - SEE ALSO: regtail_study
19506 S_regtail(pTHX_ RExC_state_t * pRExC_state,
19507 const regnode_offset p,
19508 const regnode_offset val,
19511 regnode_offset scan;
19512 GET_RE_DEBUG_FLAGS_DECL;
19514 PERL_ARGS_ASSERT_REGTAIL;
19516 PERL_UNUSED_ARG(depth);
19519 /* Find last node. */
19520 scan = (regnode_offset) p;
19522 regnode * const temp = regnext(REGNODE_p(scan));
19524 DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
19525 regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
19526 Perl_re_printf( aTHX_ "~ %s (%d) %s %s\n",
19527 SvPV_nolen_const(RExC_mysv), scan,
19528 (temp == NULL ? "->" : ""),
19529 (temp == NULL ? PL_reg_name[OP(REGNODE_p(val))] : "")
19534 scan = REGNODE_OFFSET(temp);
19537 if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
19538 ARG_SET(REGNODE_p(scan), val - scan);
19541 NEXT_OFF(REGNODE_p(scan)) = val - scan;
19547 - regtail_study - set the next-pointer at the end of a node chain of p to val.
19548 - Look for optimizable sequences at the same time.
19549 - currently only looks for EXACT chains.
19551 This is experimental code. The idea is to use this routine to perform
19552 in place optimizations on branches and groups as they are constructed,
19553 with the long term intention of removing optimization from study_chunk so
19554 that it is purely analytical.
19556 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
19557 to control which is which.
19560 /* TODO: All four parms should be const */
19563 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode_offset p,
19564 const regnode_offset val, U32 depth)
19566 regnode_offset scan;
19568 #ifdef EXPERIMENTAL_INPLACESCAN
19571 GET_RE_DEBUG_FLAGS_DECL;
19573 PERL_ARGS_ASSERT_REGTAIL_STUDY;
19576 /* Find last node. */
19580 regnode * const temp = regnext(REGNODE_p(scan));
19581 #ifdef EXPERIMENTAL_INPLACESCAN
19582 if (PL_regkind[OP(REGNODE_p(scan))] == EXACT) {
19583 bool unfolded_multi_char; /* Unexamined in this routine */
19584 if (join_exact(pRExC_state, scan, &min,
19585 &unfolded_multi_char, 1, REGNODE_p(val), depth+1))
19590 switch (OP(REGNODE_p(scan))) {
19595 case EXACTFU_S_EDGE:
19596 case EXACTFAA_NO_TRIE:
19599 case EXACTFU_ONLY8:
19603 if( exact == PSEUDO )
19604 exact= OP(REGNODE_p(scan));
19605 else if ( exact != OP(REGNODE_p(scan)) )
19614 DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
19615 regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
19616 Perl_re_printf( aTHX_ "~ %s (%d) -> %s\n",
19617 SvPV_nolen_const(RExC_mysv),
19619 PL_reg_name[exact]);
19623 scan = REGNODE_OFFSET(temp);
19626 DEBUG_PARSE_MSG("");
19627 regprop(RExC_rx, RExC_mysv, REGNODE_p(val), NULL, pRExC_state);
19628 Perl_re_printf( aTHX_
19629 "~ attach to %s (%" IVdf ") offset to %" IVdf "\n",
19630 SvPV_nolen_const(RExC_mysv),
19635 if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
19636 ARG_SET(REGNODE_p(scan), val - scan);
19639 NEXT_OFF(REGNODE_p(scan)) = val - scan;
19647 S_get_ANYOFM_contents(pTHX_ const regnode * n) {
19649 /* Returns an inversion list of all the code points matched by the
19650 * ANYOFM/NANYOFM node 'n' */
19652 SV * cp_list = _new_invlist(-1);
19653 const U8 lowest = (U8) ARG(n);
19656 U8 needed = 1U << PL_bitcount[ (U8) ~ FLAGS(n)];
19658 PERL_ARGS_ASSERT_GET_ANYOFM_CONTENTS;
19660 /* Starting with the lowest code point, any code point that ANDed with the
19661 * mask yields the lowest code point is in the set */
19662 for (i = lowest; i <= 0xFF; i++) {
19663 if ((i & FLAGS(n)) == ARG(n)) {
19664 cp_list = add_cp_to_invlist(cp_list, i);
19667 /* We know how many code points (a power of two) that are in the
19668 * set. No use looking once we've got that number */
19669 if (count >= needed) break;
19673 if (OP(n) == NANYOFM) {
19674 _invlist_invert(cp_list);
19680 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
19685 S_regdump_intflags(pTHX_ const char *lead, const U32 flags)
19690 ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8);
19692 for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) {
19693 if (flags & (1<<bit)) {
19694 if (!set++ && lead)
19695 Perl_re_printf( aTHX_ "%s", lead);
19696 Perl_re_printf( aTHX_ "%s ", PL_reg_intflags_name[bit]);
19701 Perl_re_printf( aTHX_ "\n");
19703 Perl_re_printf( aTHX_ "%s[none-set]\n", lead);
19708 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
19714 ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8);
19716 for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) {
19717 if (flags & (1<<bit)) {
19718 if ((1<<bit) & RXf_PMf_CHARSET) { /* Output separately, below */
19721 if (!set++ && lead)
19722 Perl_re_printf( aTHX_ "%s", lead);
19723 Perl_re_printf( aTHX_ "%s ", PL_reg_extflags_name[bit]);
19726 if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
19727 if (!set++ && lead) {
19728 Perl_re_printf( aTHX_ "%s", lead);
19731 case REGEX_UNICODE_CHARSET:
19732 Perl_re_printf( aTHX_ "UNICODE");
19734 case REGEX_LOCALE_CHARSET:
19735 Perl_re_printf( aTHX_ "LOCALE");
19737 case REGEX_ASCII_RESTRICTED_CHARSET:
19738 Perl_re_printf( aTHX_ "ASCII-RESTRICTED");
19740 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
19741 Perl_re_printf( aTHX_ "ASCII-MORE_RESTRICTED");
19744 Perl_re_printf( aTHX_ "UNKNOWN CHARACTER SET");
19750 Perl_re_printf( aTHX_ "\n");
19752 Perl_re_printf( aTHX_ "%s[none-set]\n", lead);
19758 Perl_regdump(pTHX_ const regexp *r)
19762 SV * const sv = sv_newmortal();
19763 SV *dsv= sv_newmortal();
19764 RXi_GET_DECL(r, ri);
19765 GET_RE_DEBUG_FLAGS_DECL;
19767 PERL_ARGS_ASSERT_REGDUMP;
19769 (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
19771 /* Header fields of interest. */
19772 for (i = 0; i < 2; i++) {
19773 if (r->substrs->data[i].substr) {
19774 RE_PV_QUOTED_DECL(s, 0, dsv,
19775 SvPVX_const(r->substrs->data[i].substr),
19776 RE_SV_DUMPLEN(r->substrs->data[i].substr),
19777 PL_dump_re_max_len);
19778 Perl_re_printf( aTHX_
19779 "%s %s%s at %" IVdf "..%" UVuf " ",
19780 i ? "floating" : "anchored",
19782 RE_SV_TAIL(r->substrs->data[i].substr),
19783 (IV)r->substrs->data[i].min_offset,
19784 (UV)r->substrs->data[i].max_offset);
19786 else if (r->substrs->data[i].utf8_substr) {
19787 RE_PV_QUOTED_DECL(s, 1, dsv,
19788 SvPVX_const(r->substrs->data[i].utf8_substr),
19789 RE_SV_DUMPLEN(r->substrs->data[i].utf8_substr),
19791 Perl_re_printf( aTHX_
19792 "%s utf8 %s%s at %" IVdf "..%" UVuf " ",
19793 i ? "floating" : "anchored",
19795 RE_SV_TAIL(r->substrs->data[i].utf8_substr),
19796 (IV)r->substrs->data[i].min_offset,
19797 (UV)r->substrs->data[i].max_offset);
19801 if (r->check_substr || r->check_utf8)
19802 Perl_re_printf( aTHX_
19804 ( r->check_substr == r->substrs->data[1].substr
19805 && r->check_utf8 == r->substrs->data[1].utf8_substr
19806 ? "(checking floating" : "(checking anchored"));
19807 if (r->intflags & PREGf_NOSCAN)
19808 Perl_re_printf( aTHX_ " noscan");
19809 if (r->extflags & RXf_CHECK_ALL)
19810 Perl_re_printf( aTHX_ " isall");
19811 if (r->check_substr || r->check_utf8)
19812 Perl_re_printf( aTHX_ ") ");
19814 if (ri->regstclass) {
19815 regprop(r, sv, ri->regstclass, NULL, NULL);
19816 Perl_re_printf( aTHX_ "stclass %s ", SvPVX_const(sv));
19818 if (r->intflags & PREGf_ANCH) {
19819 Perl_re_printf( aTHX_ "anchored");
19820 if (r->intflags & PREGf_ANCH_MBOL)
19821 Perl_re_printf( aTHX_ "(MBOL)");
19822 if (r->intflags & PREGf_ANCH_SBOL)
19823 Perl_re_printf( aTHX_ "(SBOL)");
19824 if (r->intflags & PREGf_ANCH_GPOS)
19825 Perl_re_printf( aTHX_ "(GPOS)");
19826 Perl_re_printf( aTHX_ " ");
19828 if (r->intflags & PREGf_GPOS_SEEN)
19829 Perl_re_printf( aTHX_ "GPOS:%" UVuf " ", (UV)r->gofs);
19830 if (r->intflags & PREGf_SKIP)
19831 Perl_re_printf( aTHX_ "plus ");
19832 if (r->intflags & PREGf_IMPLICIT)
19833 Perl_re_printf( aTHX_ "implicit ");
19834 Perl_re_printf( aTHX_ "minlen %" IVdf " ", (IV)r->minlen);
19835 if (r->extflags & RXf_EVAL_SEEN)
19836 Perl_re_printf( aTHX_ "with eval ");
19837 Perl_re_printf( aTHX_ "\n");
19839 regdump_extflags("r->extflags: ", r->extflags);
19840 regdump_intflags("r->intflags: ", r->intflags);
19843 PERL_ARGS_ASSERT_REGDUMP;
19844 PERL_UNUSED_CONTEXT;
19845 PERL_UNUSED_ARG(r);
19846 #endif /* DEBUGGING */
19849 /* Should be synchronized with ANYOF_ #defines in regcomp.h */
19852 # if _CC_WORDCHAR != 0 || _CC_DIGIT != 1 || _CC_ALPHA != 2 \
19853 || _CC_LOWER != 3 || _CC_UPPER != 4 || _CC_PUNCT != 5 \
19854 || _CC_PRINT != 6 || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8 \
19855 || _CC_CASED != 9 || _CC_SPACE != 10 || _CC_BLANK != 11 \
19856 || _CC_XDIGIT != 12 || _CC_CNTRL != 13 || _CC_ASCII != 14 \
19857 || _CC_VERTSPACE != 15
19858 # error Need to adjust order of anyofs[]
19860 static const char * const anyofs[] = {
19897 - regprop - printable representation of opcode, with run time support
19901 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state)
19906 RXi_GET_DECL(prog, progi);
19907 GET_RE_DEBUG_FLAGS_DECL;
19909 PERL_ARGS_ASSERT_REGPROP;
19913 if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */
19914 /* It would be nice to FAIL() here, but this may be called from
19915 regexec.c, and it would be hard to supply pRExC_state. */
19916 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
19917 (int)OP(o), (int)REGNODE_MAX);
19918 sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
19920 k = PL_regkind[OP(o)];
19923 sv_catpvs(sv, " ");
19924 /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
19925 * is a crude hack but it may be the best for now since
19926 * we have no flag "this EXACTish node was UTF-8"
19928 pv_pretty(sv, STRING(o), STR_LEN(o), PL_dump_re_max_len,
19929 PL_colors[0], PL_colors[1],
19930 PERL_PV_ESCAPE_UNI_DETECT |
19931 PERL_PV_ESCAPE_NONASCII |
19932 PERL_PV_PRETTY_ELLIPSES |
19933 PERL_PV_PRETTY_LTGT |
19934 PERL_PV_PRETTY_NOCLEAR
19936 } else if (k == TRIE) {
19937 /* print the details of the trie in dumpuntil instead, as
19938 * progi->data isn't available here */
19939 const char op = OP(o);
19940 const U32 n = ARG(o);
19941 const reg_ac_data * const ac = IS_TRIE_AC(op) ?
19942 (reg_ac_data *)progi->data->data[n] :
19944 const reg_trie_data * const trie
19945 = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
19947 Perl_sv_catpvf(aTHX_ sv, "-%s", PL_reg_name[o->flags]);
19948 DEBUG_TRIE_COMPILE_r({
19950 sv_catpvs(sv, "(JUMP)");
19951 Perl_sv_catpvf(aTHX_ sv,
19952 "<S:%" UVuf "/%" IVdf " W:%" UVuf " L:%" UVuf "/%" UVuf " C:%" UVuf "/%" UVuf ">",
19953 (UV)trie->startstate,
19954 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
19955 (UV)trie->wordcount,
19958 (UV)TRIE_CHARCOUNT(trie),
19959 (UV)trie->uniquecharcount
19962 if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
19963 sv_catpvs(sv, "[");
19964 (void) put_charclass_bitmap_innards(sv,
19965 ((IS_ANYOF_TRIE(op))
19967 : TRIE_BITMAP(trie)),
19973 sv_catpvs(sv, "]");
19975 } else if (k == CURLY) {
19976 U32 lo = ARG1(o), hi = ARG2(o);
19977 if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
19978 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
19979 Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo);
19980 if (hi == REG_INFTY)
19981 sv_catpvs(sv, "INFTY");
19983 Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi);
19984 sv_catpvs(sv, "}");
19986 else if (k == WHILEM && o->flags) /* Ordinal/of */
19987 Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
19988 else if (k == REF || k == OPEN || k == CLOSE
19989 || k == GROUPP || OP(o)==ACCEPT)
19991 AV *name_list= NULL;
19992 U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o);
19993 Perl_sv_catpvf(aTHX_ sv, "%" UVuf, (UV)parno); /* Parenth number */
19994 if ( RXp_PAREN_NAMES(prog) ) {
19995 name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
19996 } else if ( pRExC_state ) {
19997 name_list= RExC_paren_name_list;
20000 if ( k != REF || (OP(o) < NREF)) {
20001 SV **name= av_fetch(name_list, parno, 0 );
20003 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
20006 SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]);
20007 I32 *nums=(I32*)SvPVX(sv_dat);
20008 SV **name= av_fetch(name_list, nums[0], 0 );
20011 for ( n=0; n<SvIVX(sv_dat); n++ ) {
20012 Perl_sv_catpvf(aTHX_ sv, "%s%" IVdf,
20013 (n ? "," : ""), (IV)nums[n]);
20015 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
20019 if ( k == REF && reginfo) {
20020 U32 n = ARG(o); /* which paren pair */
20021 I32 ln = prog->offs[n].start;
20022 if (prog->lastparen < n || ln == -1 || prog->offs[n].end == -1)
20023 Perl_sv_catpvf(aTHX_ sv, ": FAIL");
20024 else if (ln == prog->offs[n].end)
20025 Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING");
20027 const char *s = reginfo->strbeg + ln;
20028 Perl_sv_catpvf(aTHX_ sv, ": ");
20029 Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0,
20030 PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE );
20033 } else if (k == GOSUB) {
20034 AV *name_list= NULL;
20035 if ( RXp_PAREN_NAMES(prog) ) {
20036 name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
20037 } else if ( pRExC_state ) {
20038 name_list= RExC_paren_name_list;
20041 /* Paren and offset */
20042 Perl_sv_catpvf(aTHX_ sv, "%d[%+d:%d]", (int)ARG(o),(int)ARG2L(o),
20043 (int)((o + (int)ARG2L(o)) - progi->program) );
20045 SV **name= av_fetch(name_list, ARG(o), 0 );
20047 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
20050 else if (k == LOGICAL)
20051 /* 2: embedded, otherwise 1 */
20052 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);
20053 else if (k == ANYOF) {
20054 const U8 flags = ANYOF_FLAGS(o);
20055 bool do_sep = FALSE; /* Do we need to separate various components of
20057 /* Set if there is still an unresolved user-defined property */
20058 SV *unresolved = NULL;
20060 /* Things that are ignored except when the runtime locale is UTF-8 */
20061 SV *only_utf8_locale_invlist = NULL;
20063 /* Code points that don't fit in the bitmap */
20064 SV *nonbitmap_invlist = NULL;
20066 /* And things that aren't in the bitmap, but are small enough to be */
20067 SV* bitmap_range_not_in_bitmap = NULL;
20069 const bool inverted = flags & ANYOF_INVERT;
20071 if (OP(o) == ANYOFL || OP(o) == ANYOFPOSIXL) {
20072 if (ANYOFL_UTF8_LOCALE_REQD(flags)) {
20073 sv_catpvs(sv, "{utf8-locale-reqd}");
20075 if (flags & ANYOFL_FOLD) {
20076 sv_catpvs(sv, "{i}");
20080 /* If there is stuff outside the bitmap, get it */
20081 if (ARG(o) != ANYOF_ONLY_HAS_BITMAP) {
20082 (void) _get_regclass_nonbitmap_data(prog, o, FALSE,
20084 &only_utf8_locale_invlist,
20085 &nonbitmap_invlist);
20086 /* The non-bitmap data may contain stuff that could fit in the
20087 * bitmap. This could come from a user-defined property being
20088 * finally resolved when this call was done; or much more likely
20089 * because there are matches that require UTF-8 to be valid, and so
20090 * aren't in the bitmap. This is teased apart later */
20091 _invlist_intersection(nonbitmap_invlist,
20093 &bitmap_range_not_in_bitmap);
20094 /* Leave just the things that don't fit into the bitmap */
20095 _invlist_subtract(nonbitmap_invlist,
20097 &nonbitmap_invlist);
20100 /* Obey this flag to add all above-the-bitmap code points */
20101 if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
20102 nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
20103 NUM_ANYOF_CODE_POINTS,
20107 /* Ready to start outputting. First, the initial left bracket */
20108 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
20110 if (OP(o) != ANYOFH) {
20111 /* Then all the things that could fit in the bitmap */
20112 do_sep = put_charclass_bitmap_innards(sv,
20114 bitmap_range_not_in_bitmap,
20115 only_utf8_locale_invlist,
20118 /* Can't try inverting for a
20119 * better display if there
20120 * are things that haven't
20122 unresolved != NULL);
20123 SvREFCNT_dec(bitmap_range_not_in_bitmap);
20125 /* If there are user-defined properties which haven't been defined
20126 * yet, output them. If the result is not to be inverted, it is
20127 * clearest to output them in a separate [] from the bitmap range
20128 * stuff. If the result is to be complemented, we have to show
20129 * everything in one [], as the inversion applies to the whole
20130 * thing. Use {braces} to separate them from anything in the
20131 * bitmap and anything above the bitmap. */
20134 if (! do_sep) { /* If didn't output anything in the bitmap
20136 sv_catpvs(sv, "^");
20138 sv_catpvs(sv, "{");
20141 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1],
20144 sv_catsv(sv, unresolved);
20146 sv_catpvs(sv, "}");
20148 do_sep = ! inverted;
20152 /* And, finally, add the above-the-bitmap stuff */
20153 if (nonbitmap_invlist && _invlist_len(nonbitmap_invlist)) {
20156 /* See if truncation size is overridden */
20157 const STRLEN dump_len = (PL_dump_re_max_len > 256)
20158 ? PL_dump_re_max_len
20161 /* This is output in a separate [] */
20163 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]);
20166 /* And, for easy of understanding, it is shown in the
20167 * uncomplemented form if possible. The one exception being if
20168 * there are unresolved items, where the inversion has to be
20169 * delayed until runtime */
20170 if (inverted && ! unresolved) {
20171 _invlist_invert(nonbitmap_invlist);
20172 _invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist);
20175 contents = invlist_contents(nonbitmap_invlist,
20176 FALSE /* output suitable for catsv */
20179 /* If the output is shorter than the permissible maximum, just do it. */
20180 if (SvCUR(contents) <= dump_len) {
20181 sv_catsv(sv, contents);
20184 const char * contents_string = SvPVX(contents);
20185 STRLEN i = dump_len;
20187 /* Otherwise, start at the permissible max and work back to the
20188 * first break possibility */
20189 while (i > 0 && contents_string[i] != ' ') {
20192 if (i == 0) { /* Fail-safe. Use the max if we couldn't
20193 find a legal break */
20197 sv_catpvn(sv, contents_string, i);
20198 sv_catpvs(sv, "...");
20201 SvREFCNT_dec_NN(contents);
20202 SvREFCNT_dec_NN(nonbitmap_invlist);
20205 /* And finally the matching, closing ']' */
20206 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
20208 SvREFCNT_dec(unresolved);
20210 else if (k == ANYOFM) {
20211 SV * cp_list = get_ANYOFM_contents(o);
20213 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
20214 if (OP(o) == NANYOFM) {
20215 _invlist_invert(cp_list);
20218 put_charclass_bitmap_innards(sv, NULL, cp_list, NULL, NULL, TRUE);
20219 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
20221 SvREFCNT_dec(cp_list);
20223 else if (k == POSIXD || k == NPOSIXD) {
20224 U8 index = FLAGS(o) * 2;
20225 if (index < C_ARRAY_LENGTH(anyofs)) {
20226 if (*anyofs[index] != '[') {
20227 sv_catpvs(sv, "[");
20229 sv_catpv(sv, anyofs[index]);
20230 if (*anyofs[index] != '[') {
20231 sv_catpvs(sv, "]");
20235 Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
20238 else if (k == BOUND || k == NBOUND) {
20239 /* Must be synced with order of 'bound_type' in regcomp.h */
20240 const char * const bounds[] = {
20241 "", /* Traditional */
20247 assert(FLAGS(o) < C_ARRAY_LENGTH(bounds));
20248 sv_catpv(sv, bounds[FLAGS(o)]);
20250 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
20251 Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
20252 else if (OP(o) == SBOL)
20253 Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^");
20255 /* add on the verb argument if there is one */
20256 if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) {
20258 Perl_sv_catpvf(aTHX_ sv, ":%" SVf,
20259 SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
20261 sv_catpvs(sv, ":NULL");
20264 PERL_UNUSED_CONTEXT;
20265 PERL_UNUSED_ARG(sv);
20266 PERL_UNUSED_ARG(o);
20267 PERL_UNUSED_ARG(prog);
20268 PERL_UNUSED_ARG(reginfo);
20269 PERL_UNUSED_ARG(pRExC_state);
20270 #endif /* DEBUGGING */
20276 Perl_re_intuit_string(pTHX_ REGEXP * const r)
20277 { /* Assume that RE_INTUIT is set */
20278 struct regexp *const prog = ReANY(r);
20279 GET_RE_DEBUG_FLAGS_DECL;
20281 PERL_ARGS_ASSERT_RE_INTUIT_STRING;
20282 PERL_UNUSED_CONTEXT;
20286 const char * const s = SvPV_nolen_const(RX_UTF8(r)
20287 ? prog->check_utf8 : prog->check_substr);
20289 if (!PL_colorset) reginitcolors();
20290 Perl_re_printf( aTHX_
20291 "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
20293 RX_UTF8(r) ? "utf8 " : "",
20294 PL_colors[5], PL_colors[0],
20297 (strlen(s) > PL_dump_re_max_len ? "..." : ""));
20300 /* use UTF8 check substring if regexp pattern itself is in UTF8 */
20301 return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr;
20307 handles refcounting and freeing the perl core regexp structure. When
20308 it is necessary to actually free the structure the first thing it
20309 does is call the 'free' method of the regexp_engine associated to
20310 the regexp, allowing the handling of the void *pprivate; member
20311 first. (This routine is not overridable by extensions, which is why
20312 the extensions free is called first.)
20314 See regdupe and regdupe_internal if you change anything here.
20316 #ifndef PERL_IN_XSUB_RE
20318 Perl_pregfree(pTHX_ REGEXP *r)
20324 Perl_pregfree2(pTHX_ REGEXP *rx)
20326 struct regexp *const r = ReANY(rx);
20327 GET_RE_DEBUG_FLAGS_DECL;
20329 PERL_ARGS_ASSERT_PREGFREE2;
20334 if (r->mother_re) {
20335 ReREFCNT_dec(r->mother_re);
20337 CALLREGFREE_PVT(rx); /* free the private data */
20338 SvREFCNT_dec(RXp_PAREN_NAMES(r));
20342 for (i = 0; i < 2; i++) {
20343 SvREFCNT_dec(r->substrs->data[i].substr);
20344 SvREFCNT_dec(r->substrs->data[i].utf8_substr);
20346 Safefree(r->substrs);
20348 RX_MATCH_COPY_FREE(rx);
20349 #ifdef PERL_ANY_COW
20350 SvREFCNT_dec(r->saved_copy);
20353 SvREFCNT_dec(r->qr_anoncv);
20354 if (r->recurse_locinput)
20355 Safefree(r->recurse_locinput);
20361 Copy ssv to dsv, both of which should of type SVt_REGEXP or SVt_PVLV,
20362 except that dsv will be created if NULL.
20364 This function is used in two main ways. First to implement
20365 $r = qr/....; $s = $$r;
20367 Secondly, it is used as a hacky workaround to the structural issue of
20369 being stored in the regexp structure which is in turn stored in
20370 PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
20371 could be PL_curpm in multiple contexts, and could require multiple
20372 result sets being associated with the pattern simultaneously, such
20373 as when doing a recursive match with (??{$qr})
20375 The solution is to make a lightweight copy of the regexp structure
20376 when a qr// is returned from the code executed by (??{$qr}) this
20377 lightweight copy doesn't actually own any of its data except for
20378 the starp/end and the actual regexp structure itself.
20384 Perl_reg_temp_copy(pTHX_ REGEXP *dsv, REGEXP *ssv)
20386 struct regexp *drx;
20387 struct regexp *const srx = ReANY(ssv);
20388 const bool islv = dsv && SvTYPE(dsv) == SVt_PVLV;
20390 PERL_ARGS_ASSERT_REG_TEMP_COPY;
20393 dsv = (REGEXP*) newSV_type(SVt_REGEXP);
20395 SvOK_off((SV *)dsv);
20397 /* For PVLVs, the head (sv_any) points to an XPVLV, while
20398 * the LV's xpvlenu_rx will point to a regexp body, which
20399 * we allocate here */
20400 REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
20401 assert(!SvPVX(dsv));
20402 ((XPV*)SvANY(dsv))->xpv_len_u.xpvlenu_rx = temp->sv_any;
20403 temp->sv_any = NULL;
20404 SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
20405 SvREFCNT_dec_NN(temp);
20406 /* SvCUR still resides in the xpvlv struct, so the regexp copy-
20407 ing below will not set it. */
20408 SvCUR_set(dsv, SvCUR(ssv));
20411 /* This ensures that SvTHINKFIRST(sv) is true, and hence that
20412 sv_force_normal(sv) is called. */
20416 SvFLAGS(dsv) |= SvFLAGS(ssv) & (SVf_POK|SVp_POK|SVf_UTF8);
20417 SvPV_set(dsv, RX_WRAPPED(ssv));
20418 /* We share the same string buffer as the original regexp, on which we
20419 hold a reference count, incremented when mother_re is set below.
20420 The string pointer is copied here, being part of the regexp struct.
20422 memcpy(&(drx->xpv_cur), &(srx->xpv_cur),
20423 sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
20427 const I32 npar = srx->nparens+1;
20428 Newx(drx->offs, npar, regexp_paren_pair);
20429 Copy(srx->offs, drx->offs, npar, regexp_paren_pair);
20431 if (srx->substrs) {
20433 Newx(drx->substrs, 1, struct reg_substr_data);
20434 StructCopy(srx->substrs, drx->substrs, struct reg_substr_data);
20436 for (i = 0; i < 2; i++) {
20437 SvREFCNT_inc_void(drx->substrs->data[i].substr);
20438 SvREFCNT_inc_void(drx->substrs->data[i].utf8_substr);
20441 /* check_substr and check_utf8, if non-NULL, point to either their
20442 anchored or float namesakes, and don't hold a second reference. */
20444 RX_MATCH_COPIED_off(dsv);
20445 #ifdef PERL_ANY_COW
20446 drx->saved_copy = NULL;
20448 drx->mother_re = ReREFCNT_inc(srx->mother_re ? srx->mother_re : ssv);
20449 SvREFCNT_inc_void(drx->qr_anoncv);
20450 if (srx->recurse_locinput)
20451 Newx(drx->recurse_locinput, srx->nparens + 1, char *);
20458 /* regfree_internal()
20460 Free the private data in a regexp. This is overloadable by
20461 extensions. Perl takes care of the regexp structure in pregfree(),
20462 this covers the *pprivate pointer which technically perl doesn't
20463 know about, however of course we have to handle the
20464 regexp_internal structure when no extension is in use.
20466 Note this is called before freeing anything in the regexp
20471 Perl_regfree_internal(pTHX_ REGEXP * const rx)
20473 struct regexp *const r = ReANY(rx);
20474 RXi_GET_DECL(r, ri);
20475 GET_RE_DEBUG_FLAGS_DECL;
20477 PERL_ARGS_ASSERT_REGFREE_INTERNAL;
20487 SV *dsv= sv_newmortal();
20488 RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
20489 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), PL_dump_re_max_len);
20490 Perl_re_printf( aTHX_ "%sFreeing REx:%s %s\n",
20491 PL_colors[4], PL_colors[5], s);
20495 #ifdef RE_TRACK_PATTERN_OFFSETS
20497 Safefree(ri->u.offsets); /* 20010421 MJD */
20499 if (ri->code_blocks)
20500 S_free_codeblocks(aTHX_ ri->code_blocks);
20503 int n = ri->data->count;
20506 /* If you add a ->what type here, update the comment in regcomp.h */
20507 switch (ri->data->what[n]) {
20513 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
20516 Safefree(ri->data->data[n]);
20522 { /* Aho Corasick add-on structure for a trie node.
20523 Used in stclass optimization only */
20525 reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
20526 #ifdef USE_ITHREADS
20530 refcount = --aho->refcount;
20533 PerlMemShared_free(aho->states);
20534 PerlMemShared_free(aho->fail);
20535 /* do this last!!!! */
20536 PerlMemShared_free(ri->data->data[n]);
20537 /* we should only ever get called once, so
20538 * assert as much, and also guard the free
20539 * which /might/ happen twice. At the least
20540 * it will make code anlyzers happy and it
20541 * doesn't cost much. - Yves */
20542 assert(ri->regstclass);
20543 if (ri->regstclass) {
20544 PerlMemShared_free(ri->regstclass);
20545 ri->regstclass = 0;
20552 /* trie structure. */
20554 reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
20555 #ifdef USE_ITHREADS
20559 refcount = --trie->refcount;
20562 PerlMemShared_free(trie->charmap);
20563 PerlMemShared_free(trie->states);
20564 PerlMemShared_free(trie->trans);
20566 PerlMemShared_free(trie->bitmap);
20568 PerlMemShared_free(trie->jump);
20569 PerlMemShared_free(trie->wordinfo);
20570 /* do this last!!!! */
20571 PerlMemShared_free(ri->data->data[n]);
20576 Perl_croak(aTHX_ "panic: regfree data code '%c'",
20577 ri->data->what[n]);
20580 Safefree(ri->data->what);
20581 Safefree(ri->data);
20587 #define av_dup_inc(s, t) MUTABLE_AV(sv_dup_inc((const SV *)s, t))
20588 #define hv_dup_inc(s, t) MUTABLE_HV(sv_dup_inc((const SV *)s, t))
20589 #define SAVEPVN(p, n) ((p) ? savepvn(p, n) : NULL)
20592 re_dup_guts - duplicate a regexp.
20594 This routine is expected to clone a given regexp structure. It is only
20595 compiled under USE_ITHREADS.
20597 After all of the core data stored in struct regexp is duplicated
20598 the regexp_engine.dupe method is used to copy any private data
20599 stored in the *pprivate pointer. This allows extensions to handle
20600 any duplication it needs to do.
20602 See pregfree() and regfree_internal() if you change anything here.
20604 #if defined(USE_ITHREADS)
20605 #ifndef PERL_IN_XSUB_RE
20607 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
20611 const struct regexp *r = ReANY(sstr);
20612 struct regexp *ret = ReANY(dstr);
20614 PERL_ARGS_ASSERT_RE_DUP_GUTS;
20616 npar = r->nparens+1;
20617 Newx(ret->offs, npar, regexp_paren_pair);
20618 Copy(r->offs, ret->offs, npar, regexp_paren_pair);
20620 if (ret->substrs) {
20621 /* Do it this way to avoid reading from *r after the StructCopy().
20622 That way, if any of the sv_dup_inc()s dislodge *r from the L1
20623 cache, it doesn't matter. */
20625 const bool anchored = r->check_substr
20626 ? r->check_substr == r->substrs->data[0].substr
20627 : r->check_utf8 == r->substrs->data[0].utf8_substr;
20628 Newx(ret->substrs, 1, struct reg_substr_data);
20629 StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
20631 for (i = 0; i < 2; i++) {
20632 ret->substrs->data[i].substr =
20633 sv_dup_inc(ret->substrs->data[i].substr, param);
20634 ret->substrs->data[i].utf8_substr =
20635 sv_dup_inc(ret->substrs->data[i].utf8_substr, param);
20638 /* check_substr and check_utf8, if non-NULL, point to either their
20639 anchored or float namesakes, and don't hold a second reference. */
20641 if (ret->check_substr) {
20643 assert(r->check_utf8 == r->substrs->data[0].utf8_substr);
20645 ret->check_substr = ret->substrs->data[0].substr;
20646 ret->check_utf8 = ret->substrs->data[0].utf8_substr;
20648 assert(r->check_substr == r->substrs->data[1].substr);
20649 assert(r->check_utf8 == r->substrs->data[1].utf8_substr);
20651 ret->check_substr = ret->substrs->data[1].substr;
20652 ret->check_utf8 = ret->substrs->data[1].utf8_substr;
20654 } else if (ret->check_utf8) {
20656 ret->check_utf8 = ret->substrs->data[0].utf8_substr;
20658 ret->check_utf8 = ret->substrs->data[1].utf8_substr;
20663 RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
20664 ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
20665 if (r->recurse_locinput)
20666 Newx(ret->recurse_locinput, r->nparens + 1, char *);
20669 RXi_SET(ret, CALLREGDUPE_PVT(dstr, param));
20671 if (RX_MATCH_COPIED(dstr))
20672 ret->subbeg = SAVEPVN(ret->subbeg, ret->sublen);
20674 ret->subbeg = NULL;
20675 #ifdef PERL_ANY_COW
20676 ret->saved_copy = NULL;
20679 /* Whether mother_re be set or no, we need to copy the string. We
20680 cannot refrain from copying it when the storage points directly to
20681 our mother regexp, because that's
20682 1: a buffer in a different thread
20683 2: something we no longer hold a reference on
20684 so we need to copy it locally. */
20685 RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED_const(sstr), SvCUR(sstr)+1);
20686 ret->mother_re = NULL;
20688 #endif /* PERL_IN_XSUB_RE */
20693 This is the internal complement to regdupe() which is used to copy
20694 the structure pointed to by the *pprivate pointer in the regexp.
20695 This is the core version of the extension overridable cloning hook.
20696 The regexp structure being duplicated will be copied by perl prior
20697 to this and will be provided as the regexp *r argument, however
20698 with the /old/ structures pprivate pointer value. Thus this routine
20699 may override any copying normally done by perl.
20701 It returns a pointer to the new regexp_internal structure.
20705 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
20708 struct regexp *const r = ReANY(rx);
20709 regexp_internal *reti;
20711 RXi_GET_DECL(r, ri);
20713 PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
20717 Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode),
20718 char, regexp_internal);
20719 Copy(ri->program, reti->program, len+1, regnode);
20722 if (ri->code_blocks) {
20724 Newx(reti->code_blocks, 1, struct reg_code_blocks);
20725 Newx(reti->code_blocks->cb, ri->code_blocks->count,
20726 struct reg_code_block);
20727 Copy(ri->code_blocks->cb, reti->code_blocks->cb,
20728 ri->code_blocks->count, struct reg_code_block);
20729 for (n = 0; n < ri->code_blocks->count; n++)
20730 reti->code_blocks->cb[n].src_regex = (REGEXP*)
20731 sv_dup_inc((SV*)(ri->code_blocks->cb[n].src_regex), param);
20732 reti->code_blocks->count = ri->code_blocks->count;
20733 reti->code_blocks->refcnt = 1;
20736 reti->code_blocks = NULL;
20738 reti->regstclass = NULL;
20741 struct reg_data *d;
20742 const int count = ri->data->count;
20745 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
20746 char, struct reg_data);
20747 Newx(d->what, count, U8);
20750 for (i = 0; i < count; i++) {
20751 d->what[i] = ri->data->what[i];
20752 switch (d->what[i]) {
20753 /* see also regcomp.h and regfree_internal() */
20754 case 'a': /* actually an AV, but the dup function is identical.
20755 values seem to be "plain sv's" generally. */
20756 case 'r': /* a compiled regex (but still just another SV) */
20757 case 's': /* an RV (currently only used for an RV to an AV by the ANYOF code)
20758 this use case should go away, the code could have used
20759 'a' instead - see S_set_ANYOF_arg() for array contents. */
20760 case 'S': /* actually an SV, but the dup function is identical. */
20761 case 'u': /* actually an HV, but the dup function is identical.
20762 values are "plain sv's" */
20763 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
20766 /* Synthetic Start Class - "Fake" charclass we generate to optimize
20767 * patterns which could start with several different things. Pre-TRIE
20768 * this was more important than it is now, however this still helps
20769 * in some places, for instance /x?a+/ might produce a SSC equivalent
20770 * to [xa]. This is used by Perl_re_intuit_start() and S_find_byclass()
20773 /* This is cheating. */
20774 Newx(d->data[i], 1, regnode_ssc);
20775 StructCopy(ri->data->data[i], d->data[i], regnode_ssc);
20776 reti->regstclass = (regnode*)d->data[i];
20779 /* AHO-CORASICK fail table */
20780 /* Trie stclasses are readonly and can thus be shared
20781 * without duplication. We free the stclass in pregfree
20782 * when the corresponding reg_ac_data struct is freed.
20784 reti->regstclass= ri->regstclass;
20787 /* TRIE transition table */
20789 ((reg_trie_data*)ri->data->data[i])->refcount++;
20792 case 'l': /* (?{...}) or (??{ ... }) code (cb->block) */
20793 case 'L': /* same when RExC_pm_flags & PMf_HAS_CV and code
20794 is not from another regexp */
20795 d->data[i] = ri->data->data[i];
20798 Perl_croak(aTHX_ "panic: re_dup_guts unknown data code '%c'",
20799 ri->data->what[i]);
20808 reti->name_list_idx = ri->name_list_idx;
20810 #ifdef RE_TRACK_PATTERN_OFFSETS
20811 if (ri->u.offsets) {
20812 Newx(reti->u.offsets, 2*len+1, U32);
20813 Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
20816 SetProgLen(reti, len);
20819 return (void*)reti;
20822 #endif /* USE_ITHREADS */
20824 #ifndef PERL_IN_XSUB_RE
20827 - regnext - dig the "next" pointer out of a node
20830 Perl_regnext(pTHX_ regnode *p)
20837 if (OP(p) > REGNODE_MAX) { /* regnode.type is unsigned */
20838 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
20839 (int)OP(p), (int)REGNODE_MAX);
20842 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
20852 S_re_croak2(pTHX_ bool utf8, const char* pat1, const char* pat2,...)
20855 STRLEN l1 = strlen(pat1);
20856 STRLEN l2 = strlen(pat2);
20859 const char *message;
20861 PERL_ARGS_ASSERT_RE_CROAK2;
20867 Copy(pat1, buf, l1 , char);
20868 Copy(pat2, buf + l1, l2 , char);
20869 buf[l1 + l2] = '\n';
20870 buf[l1 + l2 + 1] = '\0';
20871 va_start(args, pat2);
20872 msv = vmess(buf, &args);
20874 message = SvPV_const(msv, l1);
20877 Copy(message, buf, l1 , char);
20878 /* l1-1 to avoid \n */
20879 Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(utf8, l1-1, buf));
20882 /* XXX Here's a total kludge. But we need to re-enter for swash routines. */
20884 #ifndef PERL_IN_XSUB_RE
20886 Perl_save_re_context(pTHX)
20891 /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
20894 const REGEXP * const rx = PM_GETRE(PL_curpm);
20896 nparens = RX_NPARENS(rx);
20899 /* RT #124109. This is a complete hack; in the SWASHNEW case we know
20900 * that PL_curpm will be null, but that utf8.pm and the modules it
20901 * loads will only use $1..$3.
20902 * The t/porting/re_context.t test file checks this assumption.
20907 for (i = 1; i <= nparens; i++) {
20908 char digits[TYPE_CHARS(long)];
20909 const STRLEN len = my_snprintf(digits, sizeof(digits),
20911 GV *const *const gvp
20912 = (GV**)hv_fetch(PL_defstash, digits, len, 0);
20915 GV * const gv = *gvp;
20916 if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
20926 S_put_code_point(pTHX_ SV *sv, UV c)
20928 PERL_ARGS_ASSERT_PUT_CODE_POINT;
20931 Perl_sv_catpvf(aTHX_ sv, "\\x{%04" UVXf "}", c);
20933 else if (isPRINT(c)) {
20934 const char string = (char) c;
20936 /* We use {phrase} as metanotation in the class, so also escape literal
20938 if (isBACKSLASHED_PUNCT(c) || c == '{' || c == '}')
20939 sv_catpvs(sv, "\\");
20940 sv_catpvn(sv, &string, 1);
20942 else if (isMNEMONIC_CNTRL(c)) {
20943 Perl_sv_catpvf(aTHX_ sv, "%s", cntrl_to_mnemonic((U8) c));
20946 Perl_sv_catpvf(aTHX_ sv, "\\x%02X", (U8) c);
20950 #define MAX_PRINT_A MAX_PRINT_A_FOR_USE_ONLY_BY_REGCOMP_DOT_C
20953 S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals)
20955 /* Appends to 'sv' a displayable version of the range of code points from
20956 * 'start' to 'end'. Mnemonics (like '\r') are used for the few controls
20957 * that have them, when they occur at the beginning or end of the range.
20958 * It uses hex to output the remaining code points, unless 'allow_literals'
20959 * is true, in which case the printable ASCII ones are output as-is (though
20960 * some of these will be escaped by put_code_point()).
20962 * NOTE: This is designed only for printing ranges of code points that fit
20963 * inside an ANYOF bitmap. Higher code points are simply suppressed
20966 const unsigned int min_range_count = 3;
20968 assert(start <= end);
20970 PERL_ARGS_ASSERT_PUT_RANGE;
20972 while (start <= end) {
20974 const char * format;
20976 if (end - start < min_range_count) {
20978 /* Output chars individually when they occur in short ranges */
20979 for (; start <= end; start++) {
20980 put_code_point(sv, start);
20985 /* If permitted by the input options, and there is a possibility that
20986 * this range contains a printable literal, look to see if there is
20988 if (allow_literals && start <= MAX_PRINT_A) {
20990 /* If the character at the beginning of the range isn't an ASCII
20991 * printable, effectively split the range into two parts:
20992 * 1) the portion before the first such printable,
20994 * and output them separately. */
20995 if (! isPRINT_A(start)) {
20996 UV temp_end = start + 1;
20998 /* There is no point looking beyond the final possible
20999 * printable, in MAX_PRINT_A */
21000 UV max = MIN(end, MAX_PRINT_A);
21002 while (temp_end <= max && ! isPRINT_A(temp_end)) {
21006 /* Here, temp_end points to one beyond the first printable if
21007 * found, or to one beyond 'max' if not. If none found, make
21008 * sure that we use the entire range */
21009 if (temp_end > MAX_PRINT_A) {
21010 temp_end = end + 1;
21013 /* Output the first part of the split range: the part that
21014 * doesn't have printables, with the parameter set to not look
21015 * for literals (otherwise we would infinitely recurse) */
21016 put_range(sv, start, temp_end - 1, FALSE);
21018 /* The 2nd part of the range (if any) starts here. */
21021 /* We do a continue, instead of dropping down, because even if
21022 * the 2nd part is non-empty, it could be so short that we want
21023 * to output it as individual characters, as tested for at the
21024 * top of this loop. */
21028 /* Here, 'start' is a printable ASCII. If it is an alphanumeric,
21029 * output a sub-range of just the digits or letters, then process
21030 * the remaining portion as usual. */
21031 if (isALPHANUMERIC_A(start)) {
21032 UV mask = (isDIGIT_A(start))
21037 UV temp_end = start + 1;
21039 /* Find the end of the sub-range that includes just the
21040 * characters in the same class as the first character in it */
21041 while (temp_end <= end && _generic_isCC_A(temp_end, mask)) {
21046 /* For short ranges, don't duplicate the code above to output
21047 * them; just call recursively */
21048 if (temp_end - start < min_range_count) {
21049 put_range(sv, start, temp_end, FALSE);
21051 else { /* Output as a range */
21052 put_code_point(sv, start);
21053 sv_catpvs(sv, "-");
21054 put_code_point(sv, temp_end);
21056 start = temp_end + 1;
21060 /* We output any other printables as individual characters */
21061 if (isPUNCT_A(start) || isSPACE_A(start)) {
21062 while (start <= end && (isPUNCT_A(start)
21063 || isSPACE_A(start)))
21065 put_code_point(sv, start);
21070 } /* End of looking for literals */
21072 /* Here is not to output as a literal. Some control characters have
21073 * mnemonic names. Split off any of those at the beginning and end of
21074 * the range to print mnemonically. It isn't possible for many of
21075 * these to be in a row, so this won't overwhelm with output */
21077 && (isMNEMONIC_CNTRL(start) || isMNEMONIC_CNTRL(end)))
21079 while (isMNEMONIC_CNTRL(start) && start <= end) {
21080 put_code_point(sv, start);
21084 /* If this didn't take care of the whole range ... */
21085 if (start <= end) {
21087 /* Look backwards from the end to find the final non-mnemonic
21090 while (isMNEMONIC_CNTRL(temp_end)) {
21094 /* And separately output the interior range that doesn't start
21095 * or end with mnemonics */
21096 put_range(sv, start, temp_end, FALSE);
21098 /* Then output the mnemonic trailing controls */
21099 start = temp_end + 1;
21100 while (start <= end) {
21101 put_code_point(sv, start);
21108 /* As a final resort, output the range or subrange as hex. */
21110 this_end = (end < NUM_ANYOF_CODE_POINTS)
21112 : NUM_ANYOF_CODE_POINTS - 1;
21113 #if NUM_ANYOF_CODE_POINTS > 256
21114 format = (this_end < 256)
21115 ? "\\x%02" UVXf "-\\x%02" UVXf
21116 : "\\x{%04" UVXf "}-\\x{%04" UVXf "}";
21118 format = "\\x%02" UVXf "-\\x%02" UVXf;
21120 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
21121 Perl_sv_catpvf(aTHX_ sv, format, start, this_end);
21122 GCC_DIAG_RESTORE_STMT;
21128 S_put_charclass_bitmap_innards_invlist(pTHX_ SV *sv, SV* invlist)
21130 /* Concatenate onto the PV in 'sv' a displayable form of the inversion list
21134 bool allow_literals = TRUE;
21136 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_INVLIST;
21138 /* Generally, it is more readable if printable characters are output as
21139 * literals, but if a range (nearly) spans all of them, it's best to output
21140 * it as a single range. This code will use a single range if all but 2
21141 * ASCII printables are in it */
21142 invlist_iterinit(invlist);
21143 while (invlist_iternext(invlist, &start, &end)) {
21145 /* If the range starts beyond the final printable, it doesn't have any
21147 if (start > MAX_PRINT_A) {
21151 /* In both ASCII and EBCDIC, a SPACE is the lowest printable. To span
21152 * all but two, the range must start and end no later than 2 from
21154 if (start < ' ' + 2 && end > MAX_PRINT_A - 2) {
21155 if (end > MAX_PRINT_A) {
21161 if (end - start >= MAX_PRINT_A - ' ' - 2) {
21162 allow_literals = FALSE;
21167 invlist_iterfinish(invlist);
21169 /* Here we have figured things out. Output each range */
21170 invlist_iterinit(invlist);
21171 while (invlist_iternext(invlist, &start, &end)) {
21172 if (start >= NUM_ANYOF_CODE_POINTS) {
21175 put_range(sv, start, end, allow_literals);
21177 invlist_iterfinish(invlist);
21183 S_put_charclass_bitmap_innards_common(pTHX_
21184 SV* invlist, /* The bitmap */
21185 SV* posixes, /* Under /l, things like [:word:], \S */
21186 SV* only_utf8, /* Under /d, matches iff the target is UTF-8 */
21187 SV* not_utf8, /* /d, matches iff the target isn't UTF-8 */
21188 SV* only_utf8_locale, /* Under /l, matches if the locale is UTF-8 */
21189 const bool invert /* Is the result to be inverted? */
21192 /* Create and return an SV containing a displayable version of the bitmap
21193 * and associated information determined by the input parameters. If the
21194 * output would have been only the inversion indicator '^', NULL is instead
21200 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_COMMON;
21203 output = newSVpvs("^");
21206 output = newSVpvs("");
21209 /* First, the code points in the bitmap that are unconditionally there */
21210 put_charclass_bitmap_innards_invlist(output, invlist);
21212 /* Traditionally, these have been placed after the main code points */
21214 sv_catsv(output, posixes);
21217 if (only_utf8 && _invlist_len(only_utf8)) {
21218 Perl_sv_catpvf(aTHX_ output, "%s{utf8}%s", PL_colors[1], PL_colors[0]);
21219 put_charclass_bitmap_innards_invlist(output, only_utf8);
21222 if (not_utf8 && _invlist_len(not_utf8)) {
21223 Perl_sv_catpvf(aTHX_ output, "%s{not utf8}%s", PL_colors[1], PL_colors[0]);
21224 put_charclass_bitmap_innards_invlist(output, not_utf8);
21227 if (only_utf8_locale && _invlist_len(only_utf8_locale)) {
21228 Perl_sv_catpvf(aTHX_ output, "%s{utf8 locale}%s", PL_colors[1], PL_colors[0]);
21229 put_charclass_bitmap_innards_invlist(output, only_utf8_locale);
21231 /* This is the only list in this routine that can legally contain code
21232 * points outside the bitmap range. The call just above to
21233 * 'put_charclass_bitmap_innards_invlist' will simply suppress them, so
21234 * output them here. There's about a half-dozen possible, and none in
21235 * contiguous ranges longer than 2 */
21236 if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
21238 SV* above_bitmap = NULL;
21240 _invlist_subtract(only_utf8_locale, PL_InBitmap, &above_bitmap);
21242 invlist_iterinit(above_bitmap);
21243 while (invlist_iternext(above_bitmap, &start, &end)) {
21246 for (i = start; i <= end; i++) {
21247 put_code_point(output, i);
21250 invlist_iterfinish(above_bitmap);
21251 SvREFCNT_dec_NN(above_bitmap);
21255 if (invert && SvCUR(output) == 1) {
21263 S_put_charclass_bitmap_innards(pTHX_ SV *sv,
21265 SV *nonbitmap_invlist,
21266 SV *only_utf8_locale_invlist,
21267 const regnode * const node,
21268 const bool force_as_is_display)
21270 /* Appends to 'sv' a displayable version of the innards of the bracketed
21271 * character class defined by the other arguments:
21272 * 'bitmap' points to the bitmap, or NULL if to ignore that.
21273 * 'nonbitmap_invlist' is an inversion list of the code points that are in
21274 * the bitmap range, but for some reason aren't in the bitmap; NULL if
21275 * none. The reasons for this could be that they require some
21276 * condition such as the target string being or not being in UTF-8
21277 * (under /d), or because they came from a user-defined property that
21278 * was not resolved at the time of the regex compilation (under /u)
21279 * 'only_utf8_locale_invlist' is an inversion list of the code points that
21280 * are valid only if the runtime locale is a UTF-8 one; NULL if none
21281 * 'node' is the regex pattern ANYOF node. It is needed only when the
21282 * above two parameters are not null, and is passed so that this
21283 * routine can tease apart the various reasons for them.
21284 * 'force_as_is_display' is TRUE if this routine should definitely NOT try
21285 * to invert things to see if that leads to a cleaner display. If
21286 * FALSE, this routine is free to use its judgment about doing this.
21288 * It returns TRUE if there was actually something output. (It may be that
21289 * the bitmap, etc is empty.)
21291 * When called for outputting the bitmap of a non-ANYOF node, just pass the
21292 * bitmap, with the succeeding parameters set to NULL, and the final one to
21296 /* In general, it tries to display the 'cleanest' representation of the
21297 * innards, choosing whether to display them inverted or not, regardless of
21298 * whether the class itself is to be inverted. However, there are some
21299 * cases where it can't try inverting, as what actually matches isn't known
21300 * until runtime, and hence the inversion isn't either. */
21303 bool inverting_allowed = ! force_as_is_display;
21306 STRLEN orig_sv_cur = SvCUR(sv);
21308 SV* invlist; /* Inversion list we accumulate of code points that
21309 are unconditionally matched */
21310 SV* only_utf8 = NULL; /* Under /d, list of matches iff the target is
21312 SV* not_utf8 = NULL; /* /d, list of matches iff the target isn't UTF-8
21314 SV* posixes = NULL; /* Under /l, string of things like [:word:], \D */
21315 SV* only_utf8_locale = NULL; /* Under /l, list of matches if the locale
21318 SV* as_is_display; /* The output string when we take the inputs
21320 SV* inverted_display; /* The output string when we invert the inputs */
21322 U8 flags = (node) ? ANYOF_FLAGS(node) : 0;
21324 bool invert = cBOOL(flags & ANYOF_INVERT); /* Is the input to be inverted
21326 /* We are biased in favor of displaying things without them being inverted,
21327 * as that is generally easier to understand */
21328 const int bias = 5;
21330 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS;
21332 /* Start off with whatever code points are passed in. (We clone, so we
21333 * don't change the caller's list) */
21334 if (nonbitmap_invlist) {
21335 assert(invlist_highest(nonbitmap_invlist) < NUM_ANYOF_CODE_POINTS);
21336 invlist = invlist_clone(nonbitmap_invlist, NULL);
21338 else { /* Worst case size is every other code point is matched */
21339 invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2);
21343 if (OP(node) == ANYOFD) {
21345 /* This flag indicates that the code points below 0x100 in the
21346 * nonbitmap list are precisely the ones that match only when the
21347 * target is UTF-8 (they should all be non-ASCII). */
21348 if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
21350 _invlist_intersection(invlist, PL_UpperLatin1, &only_utf8);
21351 _invlist_subtract(invlist, only_utf8, &invlist);
21354 /* And this flag for matching all non-ASCII 0xFF and below */
21355 if (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
21357 not_utf8 = invlist_clone(PL_UpperLatin1, NULL);
21360 else if (OP(node) == ANYOFL || OP(node) == ANYOFPOSIXL) {
21362 /* If either of these flags are set, what matches isn't
21363 * determinable except during execution, so don't know enough here
21365 if (flags & (ANYOFL_FOLD|ANYOF_MATCHES_POSIXL)) {
21366 inverting_allowed = FALSE;
21369 /* What the posix classes match also varies at runtime, so these
21370 * will be output symbolically. */
21371 if (ANYOF_POSIXL_TEST_ANY_SET(node)) {
21374 posixes = newSVpvs("");
21375 for (i = 0; i < ANYOF_POSIXL_MAX; i++) {
21376 if (ANYOF_POSIXL_TEST(node, i)) {
21377 sv_catpv(posixes, anyofs[i]);
21384 /* Accumulate the bit map into the unconditional match list */
21386 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
21387 if (BITMAP_TEST(bitmap, i)) {
21390 i < NUM_ANYOF_CODE_POINTS && BITMAP_TEST(bitmap, i);
21393 invlist = _add_range_to_invlist(invlist, start, i-1);
21398 /* Make sure that the conditional match lists don't have anything in them
21399 * that match unconditionally; otherwise the output is quite confusing.
21400 * This could happen if the code that populates these misses some
21403 _invlist_subtract(only_utf8, invlist, &only_utf8);
21406 _invlist_subtract(not_utf8, invlist, ¬_utf8);
21409 if (only_utf8_locale_invlist) {
21411 /* Since this list is passed in, we have to make a copy before
21413 only_utf8_locale = invlist_clone(only_utf8_locale_invlist, NULL);
21415 _invlist_subtract(only_utf8_locale, invlist, &only_utf8_locale);
21417 /* And, it can get really weird for us to try outputting an inverted
21418 * form of this list when it has things above the bitmap, so don't even
21420 if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
21421 inverting_allowed = FALSE;
21425 /* Calculate what the output would be if we take the input as-is */
21426 as_is_display = put_charclass_bitmap_innards_common(invlist,
21433 /* If have to take the output as-is, just do that */
21434 if (! inverting_allowed) {
21435 if (as_is_display) {
21436 sv_catsv(sv, as_is_display);
21437 SvREFCNT_dec_NN(as_is_display);
21440 else { /* But otherwise, create the output again on the inverted input, and
21441 use whichever version is shorter */
21443 int inverted_bias, as_is_bias;
21445 /* We will apply our bias to whichever of the the results doesn't have
21455 inverted_bias = bias;
21458 /* Now invert each of the lists that contribute to the output,
21459 * excluding from the result things outside the possible range */
21461 /* For the unconditional inversion list, we have to add in all the
21462 * conditional code points, so that when inverted, they will be gone
21464 _invlist_union(only_utf8, invlist, &invlist);
21465 _invlist_union(not_utf8, invlist, &invlist);
21466 _invlist_union(only_utf8_locale, invlist, &invlist);
21467 _invlist_invert(invlist);
21468 _invlist_intersection(invlist, PL_InBitmap, &invlist);
21471 _invlist_invert(only_utf8);
21472 _invlist_intersection(only_utf8, PL_UpperLatin1, &only_utf8);
21474 else if (not_utf8) {
21476 /* If a code point matches iff the target string is not in UTF-8,
21477 * then complementing the result has it not match iff not in UTF-8,
21478 * which is the same thing as matching iff it is UTF-8. */
21479 only_utf8 = not_utf8;
21483 if (only_utf8_locale) {
21484 _invlist_invert(only_utf8_locale);
21485 _invlist_intersection(only_utf8_locale,
21487 &only_utf8_locale);
21490 inverted_display = put_charclass_bitmap_innards_common(
21495 only_utf8_locale, invert);
21497 /* Use the shortest representation, taking into account our bias
21498 * against showing it inverted */
21499 if ( inverted_display
21500 && ( ! as_is_display
21501 || ( SvCUR(inverted_display) + inverted_bias
21502 < SvCUR(as_is_display) + as_is_bias)))
21504 sv_catsv(sv, inverted_display);
21506 else if (as_is_display) {
21507 sv_catsv(sv, as_is_display);
21510 SvREFCNT_dec(as_is_display);
21511 SvREFCNT_dec(inverted_display);
21514 SvREFCNT_dec_NN(invlist);
21515 SvREFCNT_dec(only_utf8);
21516 SvREFCNT_dec(not_utf8);
21517 SvREFCNT_dec(posixes);
21518 SvREFCNT_dec(only_utf8_locale);
21520 return SvCUR(sv) > orig_sv_cur;
21523 #define CLEAR_OPTSTART \
21524 if (optstart) STMT_START { \
21525 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ \
21526 " (%" IVdf " nodes)\n", (IV)(node - optstart))); \
21530 #define DUMPUNTIL(b,e) \
21532 node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
21534 STATIC const regnode *
21535 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
21536 const regnode *last, const regnode *plast,
21537 SV* sv, I32 indent, U32 depth)
21539 U8 op = PSEUDO; /* Arbitrary non-END op. */
21540 const regnode *next;
21541 const regnode *optstart= NULL;
21543 RXi_GET_DECL(r, ri);
21544 GET_RE_DEBUG_FLAGS_DECL;
21546 PERL_ARGS_ASSERT_DUMPUNTIL;
21548 #ifdef DEBUG_DUMPUNTIL
21549 Perl_re_printf( aTHX_ "--- %d : %d - %d - %d\n", indent, node-start,
21550 last ? last-start : 0, plast ? plast-start : 0);
21553 if (plast && plast < last)
21556 while (PL_regkind[op] != END && (!last || node < last)) {
21558 /* While that wasn't END last time... */
21561 if (op == CLOSE || op == SRCLOSE || op == WHILEM)
21563 next = regnext((regnode *)node);
21566 if (OP(node) == OPTIMIZED) {
21567 if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
21574 regprop(r, sv, node, NULL, NULL);
21575 Perl_re_printf( aTHX_ "%4" IVdf ":%*s%s", (IV)(node - start),
21576 (int)(2*indent + 1), "", SvPVX_const(sv));
21578 if (OP(node) != OPTIMIZED) {
21579 if (next == NULL) /* Next ptr. */
21580 Perl_re_printf( aTHX_ " (0)");
21581 else if (PL_regkind[(U8)op] == BRANCH
21582 && PL_regkind[OP(next)] != BRANCH )
21583 Perl_re_printf( aTHX_ " (FAIL)");
21585 Perl_re_printf( aTHX_ " (%" IVdf ")", (IV)(next - start));
21586 Perl_re_printf( aTHX_ "\n");
21590 if (PL_regkind[(U8)op] == BRANCHJ) {
21593 const regnode *nnode = (OP(next) == LONGJMP
21594 ? regnext((regnode *)next)
21596 if (last && nnode > last)
21598 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
21601 else if (PL_regkind[(U8)op] == BRANCH) {
21603 DUMPUNTIL(NEXTOPER(node), next);
21605 else if ( PL_regkind[(U8)op] == TRIE ) {
21606 const regnode *this_trie = node;
21607 const char op = OP(node);
21608 const U32 n = ARG(node);
21609 const reg_ac_data * const ac = op>=AHOCORASICK ?
21610 (reg_ac_data *)ri->data->data[n] :
21612 const reg_trie_data * const trie =
21613 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
21615 AV *const trie_words
21616 = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
21618 const regnode *nextbranch= NULL;
21621 for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
21622 SV ** const elem_ptr = av_fetch(trie_words, word_idx, 0);
21624 Perl_re_indentf( aTHX_ "%s ",
21627 ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr),
21628 SvCUR(*elem_ptr), PL_dump_re_max_len,
21629 PL_colors[0], PL_colors[1],
21631 ? PERL_PV_ESCAPE_UNI
21633 | PERL_PV_PRETTY_ELLIPSES
21634 | PERL_PV_PRETTY_LTGT
21639 U16 dist= trie->jump[word_idx+1];
21640 Perl_re_printf( aTHX_ "(%" UVuf ")\n",
21641 (UV)((dist ? this_trie + dist : next) - start));
21644 nextbranch= this_trie + trie->jump[0];
21645 DUMPUNTIL(this_trie + dist, nextbranch);
21647 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
21648 nextbranch= regnext((regnode *)nextbranch);
21650 Perl_re_printf( aTHX_ "\n");
21653 if (last && next > last)
21658 else if ( op == CURLY ) { /* "next" might be very big: optimizer */
21659 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
21660 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
21662 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
21664 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
21666 else if ( op == PLUS || op == STAR) {
21667 DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
21669 else if (PL_regkind[(U8)op] == EXACT) {
21670 /* Literal string, where present. */
21671 node += NODE_SZ_STR(node) - 1;
21672 node = NEXTOPER(node);
21675 node = NEXTOPER(node);
21676 node += regarglen[(U8)op];
21678 if (op == CURLYX || op == OPEN || op == SROPEN)
21682 #ifdef DEBUG_DUMPUNTIL
21683 Perl_re_printf( aTHX_ "--- %d\n", (int)indent);
21688 #endif /* DEBUGGING */
21690 #ifndef PERL_IN_XSUB_RE
21692 #include "uni_keywords.h"
21695 Perl_init_uniprops(pTHX)
21699 PL_user_def_props = newHV();
21701 #ifdef USE_ITHREADS
21703 HvSHAREKEYS_off(PL_user_def_props);
21704 PL_user_def_props_aTHX = aTHX;
21708 /* Set up the inversion list global variables */
21710 PL_XPosix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
21711 PL_XPosix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALNUM]);
21712 PL_XPosix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALPHA]);
21713 PL_XPosix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXBLANK]);
21714 PL_XPosix_ptrs[_CC_CASED] = _new_invlist_C_array(uni_prop_ptrs[UNI_CASED]);
21715 PL_XPosix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXCNTRL]);
21716 PL_XPosix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXDIGIT]);
21717 PL_XPosix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXGRAPH]);
21718 PL_XPosix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXLOWER]);
21719 PL_XPosix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPRINT]);
21720 PL_XPosix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPUNCT]);
21721 PL_XPosix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXSPACE]);
21722 PL_XPosix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXUPPER]);
21723 PL_XPosix_ptrs[_CC_VERTSPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_VERTSPACE]);
21724 PL_XPosix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXWORD]);
21725 PL_XPosix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXXDIGIT]);
21727 PL_Posix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
21728 PL_Posix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALNUM]);
21729 PL_Posix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALPHA]);
21730 PL_Posix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXBLANK]);
21731 PL_Posix_ptrs[_CC_CASED] = PL_Posix_ptrs[_CC_ALPHA];
21732 PL_Posix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXCNTRL]);
21733 PL_Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXDIGIT]);
21734 PL_Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXGRAPH]);
21735 PL_Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXLOWER]);
21736 PL_Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPRINT]);
21737 PL_Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPUNCT]);
21738 PL_Posix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXSPACE]);
21739 PL_Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXUPPER]);
21740 PL_Posix_ptrs[_CC_VERTSPACE] = NULL;
21741 PL_Posix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXWORD]);
21742 PL_Posix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXXDIGIT]);
21744 PL_GCB_invlist = _new_invlist_C_array(_Perl_GCB_invlist);
21745 PL_SB_invlist = _new_invlist_C_array(_Perl_SB_invlist);
21746 PL_WB_invlist = _new_invlist_C_array(_Perl_WB_invlist);
21747 PL_LB_invlist = _new_invlist_C_array(_Perl_LB_invlist);
21748 PL_SCX_invlist = _new_invlist_C_array(_Perl_SCX_invlist);
21750 PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
21751 PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
21752 PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist);
21754 PL_Assigned_invlist = _new_invlist_C_array(uni_prop_ptrs[UNI_ASSIGNED]);
21756 PL_utf8_perl_idstart = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDSTART]);
21757 PL_utf8_perl_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDCONT]);
21759 PL_utf8_charname_begin = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_BEGIN]);
21760 PL_utf8_charname_continue = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_CONTINUE]);
21762 PL_in_some_fold = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_ANY_FOLDS]);
21763 PL_HasMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
21764 UNI__PERL_FOLDS_TO_MULTI_CHAR]);
21765 PL_InMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
21766 UNI__PERL_IS_IN_MULTI_CHAR_FOLD]);
21767 PL_NonFinalFold = _new_invlist_C_array(uni_prop_ptrs[
21768 UNI__PERL_NON_FINAL_FOLDS]);
21770 PL_utf8_toupper = _new_invlist_C_array(Uppercase_Mapping_invlist);
21771 PL_utf8_tolower = _new_invlist_C_array(Lowercase_Mapping_invlist);
21772 PL_utf8_totitle = _new_invlist_C_array(Titlecase_Mapping_invlist);
21773 PL_utf8_tofold = _new_invlist_C_array(Case_Folding_invlist);
21774 PL_utf8_tosimplefold = _new_invlist_C_array(Simple_Case_Folding_invlist);
21775 PL_utf8_foldclosures = _new_invlist_C_array(_Perl_IVCF_invlist);
21776 PL_utf8_mark = _new_invlist_C_array(uni_prop_ptrs[UNI_M]);
21777 PL_CCC_non0_non230 = _new_invlist_C_array(_Perl_CCC_non0_non230_invlist);
21780 /* The below are used only by deprecated functions. They could be removed */
21781 PL_utf8_xidcont = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDC]);
21782 PL_utf8_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI_IDC]);
21783 PL_utf8_xidstart = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDS]);
21789 This code was mainly added for backcompat to give a warning for non-portable
21790 code points in user-defined properties. But experiments showed that the
21791 warning in earlier perls were only omitted on overflow, which should be an
21792 error, so there really isnt a backcompat issue, and actually adding the
21793 warning when none was present before might cause breakage, for little gain. So
21794 khw left this code in, but not enabled. Tests were never added.
21797 Ei |const char *|get_extended_utf8_msg|const UV cp
21799 PERL_STATIC_INLINE const char *
21800 S_get_extended_utf8_msg(pTHX_ const UV cp)
21802 U8 dummy[UTF8_MAXBYTES + 1];
21806 uvchr_to_utf8_flags_msgs(dummy, cp, UNICODE_WARN_PERL_EXTENDED,
21809 msg = hv_fetchs(msgs, "text", 0);
21812 (void) sv_2mortal((SV *) msgs);
21814 return SvPVX(*msg);
21820 Perl_handle_user_defined_property(pTHX_
21822 /* Parses the contents of a user-defined property definition; returning the
21823 * expanded definition if possible. If so, the return is an inversion
21826 * If there are subroutines that are part of the expansion and which aren't
21827 * known at the time of the call to this function, this returns what
21828 * parse_uniprop_string() returned for the first one encountered.
21830 * If an error was found, NULL is returned, and 'msg' gets a suitable
21831 * message appended to it. (Appending allows the back trace of how we got
21832 * to the faulty definition to be displayed through nested calls of
21833 * user-defined subs.)
21835 * The caller IS responsible for freeing any returned SV.
21837 * The syntax of the contents is pretty much described in perlunicode.pod,
21838 * but we also allow comments on each line */
21840 const char * name, /* Name of property */
21841 const STRLEN name_len, /* The name's length in bytes */
21842 const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */
21843 const bool to_fold, /* ? Is this under /i */
21844 const bool runtime, /* ? Are we in compile- or run-time */
21845 SV* contents, /* The property's definition */
21846 bool *user_defined_ptr, /* This will be set TRUE as we wouldn't be
21847 getting called unless this is thought to be
21848 a user-defined property */
21849 SV * msg, /* Any error or warning msg(s) are appended to
21851 const STRLEN level) /* Recursion level of this call */
21854 const char * string = SvPV_const(contents, len);
21855 const char * const e = string + len;
21856 const bool is_contents_utf8 = cBOOL(SvUTF8(contents));
21857 const STRLEN msgs_length_on_entry = SvCUR(msg);
21859 const char * s0 = string; /* Points to first byte in the current line
21860 being parsed in 'string' */
21861 const char overflow_msg[] = "Code point too large in \"";
21862 SV* running_definition = NULL;
21864 PERL_ARGS_ASSERT_HANDLE_USER_DEFINED_PROPERTY;
21866 *user_defined_ptr = TRUE;
21868 /* Look at each line */
21870 const char * s; /* Current byte */
21871 char op = '+'; /* Default operation is 'union' */
21872 IV min = 0; /* range begin code point */
21873 IV max = -1; /* and range end */
21874 SV* this_definition;
21876 /* Skip comment lines */
21878 s0 = strchr(s0, '\n');
21886 /* For backcompat, allow an empty first line */
21892 /* First character in the line may optionally be the operation */
21901 /* If the line is one or two hex digits separated by blank space, its
21902 * a range; otherwise it is either another user-defined property or an
21907 if (! isXDIGIT(*s)) {
21908 goto check_if_property;
21911 do { /* Each new hex digit will add 4 bits. */
21912 if (min > ( (IV) MAX_LEGAL_CP >> 4)) {
21913 s = strchr(s, '\n');
21917 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
21918 sv_catpv(msg, overflow_msg);
21919 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
21920 UTF8fARG(is_contents_utf8, s - s0, s0));
21921 sv_catpvs(msg, "\"");
21925 /* Accumulate this digit into the value */
21926 min = (min << 4) + READ_XDIGIT(s);
21927 } while (isXDIGIT(*s));
21929 while (isBLANK(*s)) { s++; }
21931 /* We allow comments at the end of the line */
21933 s = strchr(s, '\n');
21939 else if (s < e && *s != '\n') {
21940 if (! isXDIGIT(*s)) {
21941 goto check_if_property;
21944 /* Look for the high point of the range */
21947 if (max > ( (IV) MAX_LEGAL_CP >> 4)) {
21948 s = strchr(s, '\n');
21952 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
21953 sv_catpv(msg, overflow_msg);
21954 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
21955 UTF8fARG(is_contents_utf8, s - s0, s0));
21956 sv_catpvs(msg, "\"");
21960 max = (max << 4) + READ_XDIGIT(s);
21961 } while (isXDIGIT(*s));
21963 while (isBLANK(*s)) { s++; }
21966 s = strchr(s, '\n');
21971 else if (s < e && *s != '\n') {
21972 goto check_if_property;
21976 if (max == -1) { /* The line only had one entry */
21979 else if (max < min) {
21980 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
21981 sv_catpvs(msg, "Illegal range in \"");
21982 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
21983 UTF8fARG(is_contents_utf8, s - s0, s0));
21984 sv_catpvs(msg, "\"");
21988 #if 0 /* See explanation at definition above of get_extended_utf8_msg() */
21990 if ( UNICODE_IS_PERL_EXTENDED(min)
21991 || UNICODE_IS_PERL_EXTENDED(max))
21993 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
21995 /* If both code points are non-portable, warn only on the lower
21997 sv_catpv(msg, get_extended_utf8_msg(
21998 (UNICODE_IS_PERL_EXTENDED(min))
22000 sv_catpvs(msg, " in \"");
22001 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
22002 UTF8fARG(is_contents_utf8, s - s0, s0));
22003 sv_catpvs(msg, "\"");
22008 /* Here, this line contains a legal range */
22009 this_definition = sv_2mortal(_new_invlist(2));
22010 this_definition = _add_range_to_invlist(this_definition, min, max);
22015 /* Here it isn't a legal range line. See if it is a legal property
22016 * line. First find the end of the meat of the line */
22017 s = strpbrk(s, "#\n");
22022 /* Ignore trailing blanks in keeping with the requirements of
22023 * parse_uniprop_string() */
22025 while (s > s0 && isBLANK_A(*s)) {
22030 this_definition = parse_uniprop_string(s0, s - s0,
22031 is_utf8, to_fold, runtime,
22032 user_defined_ptr, msg,
22034 ? level /* Don't increase level
22035 if input is empty */
22038 if (this_definition == NULL) {
22039 goto return_msg; /* 'msg' should have had the reason appended to
22040 it by the above call */
22043 if (! is_invlist(this_definition)) { /* Unknown at this time */
22044 return newSVsv(this_definition);
22048 s = strchr(s, '\n');
22058 _invlist_union(running_definition, this_definition,
22059 &running_definition);
22062 _invlist_subtract(running_definition, this_definition,
22063 &running_definition);
22066 _invlist_intersection(running_definition, this_definition,
22067 &running_definition);
22070 _invlist_union_complement_2nd(running_definition,
22071 this_definition, &running_definition);
22074 Perl_croak(aTHX_ "panic: %s: %d: Unexpected operation %d",
22075 __FILE__, __LINE__, op);
22079 /* Position past the '\n' */
22081 } /* End of loop through the lines of 'contents' */
22083 /* Here, we processed all the lines in 'contents' without error. If we
22084 * didn't add any warnings, simply return success */
22085 if (msgs_length_on_entry == SvCUR(msg)) {
22087 /* If the expansion was empty, the answer isn't nothing: its an empty
22088 * inversion list */
22089 if (running_definition == NULL) {
22090 running_definition = _new_invlist(1);
22093 return running_definition;
22096 /* Otherwise, add some explanatory text, but we will return success */
22100 if (name_len > 0) {
22101 sv_catpvs(msg, " in expansion of ");
22102 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
22105 return running_definition;
22108 /* As explained below, certain operations need to take place in the first
22109 * thread created. These macros switch contexts */
22110 #ifdef USE_ITHREADS
22111 # define DECLARATION_FOR_GLOBAL_CONTEXT \
22112 PerlInterpreter * save_aTHX = aTHX;
22113 # define SWITCH_TO_GLOBAL_CONTEXT \
22114 PERL_SET_CONTEXT((aTHX = PL_user_def_props_aTHX))
22115 # define RESTORE_CONTEXT PERL_SET_CONTEXT((aTHX = save_aTHX));
22116 # define CUR_CONTEXT aTHX
22117 # define ORIGINAL_CONTEXT save_aTHX
22119 # define DECLARATION_FOR_GLOBAL_CONTEXT
22120 # define SWITCH_TO_GLOBAL_CONTEXT NOOP
22121 # define RESTORE_CONTEXT NOOP
22122 # define CUR_CONTEXT NULL
22123 # define ORIGINAL_CONTEXT NULL
22127 S_delete_recursion_entry(pTHX_ void *key)
22129 /* Deletes the entry used to detect recursion when expanding user-defined
22130 * properties. This is a function so it can be set up to be called even if
22131 * the program unexpectedly quits */
22134 SV ** current_entry;
22135 const STRLEN key_len = strlen((const char *) key);
22136 DECLARATION_FOR_GLOBAL_CONTEXT;
22138 SWITCH_TO_GLOBAL_CONTEXT;
22140 /* If the entry is one of these types, it is a permanent entry, and not the
22141 * one used to detect recursions. This function should delete only the
22142 * recursion entry */
22143 current_entry = hv_fetch(PL_user_def_props, (const char *) key, key_len, 0);
22145 && ! is_invlist(*current_entry)
22146 && ! SvPOK(*current_entry))
22148 (void) hv_delete(PL_user_def_props, (const char *) key, key_len,
22156 Perl_parse_uniprop_string(pTHX_
22158 /* Parse the interior of a \p{}, \P{}. Returns its definition if knowable
22159 * now. If so, the return is an inversion list.
22161 * If the property is user-defined, it is a subroutine, which in turn
22162 * may call other subroutines. This function will call the whole nest of
22163 * them to get the definition they return; if some aren't known at the time
22164 * of the call to this function, the fully qualified name of the highest
22165 * level sub is returned. It is an error to call this function at runtime
22166 * without every sub defined.
22168 * If an error was found, NULL is returned, and 'msg' gets a suitable
22169 * message appended to it. (Appending allows the back trace of how we got
22170 * to the faulty definition to be displayed through nested calls of
22171 * user-defined subs.)
22173 * The caller should NOT try to free any returned inversion list.
22175 * Other parameters will be set on return as described below */
22177 const char * const name, /* The first non-blank in the \p{}, \P{} */
22178 const Size_t name_len, /* Its length in bytes, not including any
22180 const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */
22181 const bool to_fold, /* ? Is this under /i */
22182 const bool runtime, /* TRUE if this is being called at run time */
22183 bool *user_defined_ptr, /* Upon return from this function it will be
22184 set to TRUE if any component is a
22185 user-defined property */
22186 SV * msg, /* Any error or warning msg(s) are appended to
22188 const STRLEN level) /* Recursion level of this call */
22191 char* lookup_name; /* normalized name for lookup in our tables */
22192 unsigned lookup_len; /* Its length */
22193 bool stricter = FALSE; /* Some properties have stricter name
22194 normalization rules, which we decide upon
22195 based on parsing */
22197 /* nv= or numeric_value=, or possibly one of the cjk numeric properties
22198 * (though it requires extra effort to download them from Unicode and
22199 * compile perl to know about them) */
22200 bool is_nv_type = FALSE;
22202 unsigned int i, j = 0;
22203 int equals_pos = -1; /* Where the '=' is found, or negative if none */
22204 int slash_pos = -1; /* Where the '/' is found, or negative if none */
22205 int table_index = 0; /* The entry number for this property in the table
22206 of all Unicode property names */
22207 bool starts_with_In_or_Is = FALSE; /* ? Does the name start with 'In' or
22209 Size_t lookup_offset = 0; /* Used to ignore the first few characters of
22210 the normalized name in certain situations */
22211 Size_t non_pkg_begin = 0; /* Offset of first byte in 'name' that isn't
22212 part of a package name */
22213 bool could_be_user_defined = TRUE; /* ? Could this be a user-defined
22214 property rather than a Unicode
22216 SV * prop_definition = NULL; /* The returned definition of 'name' or NULL
22217 if an error. If it is an inversion list,
22218 it is the definition. Otherwise it is a
22219 string containing the fully qualified sub
22221 bool invert_return = FALSE; /* ? Do we need to complement the result before
22224 PERL_ARGS_ASSERT_PARSE_UNIPROP_STRING;
22226 /* The input will be normalized into 'lookup_name' */
22227 Newx(lookup_name, name_len, char);
22228 SAVEFREEPV(lookup_name);
22230 /* Parse the input. */
22231 for (i = 0; i < name_len; i++) {
22232 char cur = name[i];
22234 /* Most of the characters in the input will be of this ilk, being parts
22236 if (isIDCONT_A(cur)) {
22238 /* Case differences are ignored. Our lookup routine assumes
22239 * everything is lowercase, so normalize to that */
22240 if (isUPPER_A(cur)) {
22241 lookup_name[j++] = toLOWER_A(cur);
22245 if (cur == '_') { /* Don't include these in the normalized name */
22249 lookup_name[j++] = cur;
22251 /* The first character in a user-defined name must be of this type.
22253 if (i - non_pkg_begin == 0 && ! isIDFIRST_A(cur)) {
22254 could_be_user_defined = FALSE;
22260 /* Here, the character is not something typically in a name, But these
22261 * two types of characters (and the '_' above) can be freely ignored in
22262 * most situations. Later it may turn out we shouldn't have ignored
22263 * them, and we have to reparse, but we don't have enough information
22264 * yet to make that decision */
22265 if (cur == '-' || isSPACE_A(cur)) {
22266 could_be_user_defined = FALSE;
22270 /* An equals sign or single colon mark the end of the first part of
22271 * the property name */
22273 || (cur == ':' && (i >= name_len - 1 || name[i+1] != ':')))
22275 lookup_name[j++] = '='; /* Treat the colon as an '=' */
22276 equals_pos = j; /* Note where it occurred in the input */
22277 could_be_user_defined = FALSE;
22281 /* Otherwise, this character is part of the name. */
22282 lookup_name[j++] = cur;
22284 /* Here it isn't a single colon, so if it is a colon, it must be a
22288 /* A double colon should be a package qualifier. We note its
22289 * position and continue. Note that one could have
22290 * pkg1::pkg2::...::foo
22291 * so that the position at the end of the loop will be just after
22292 * the final qualifier */
22295 non_pkg_begin = i + 1;
22296 lookup_name[j++] = ':';
22298 else { /* Only word chars (and '::') can be in a user-defined name */
22299 could_be_user_defined = FALSE;
22301 } /* End of parsing through the lhs of the property name (or all of it if
22304 #define STRLENs(s) (sizeof("" s "") - 1)
22306 /* If there is a single package name 'utf8::', it is ambiguous. It could
22307 * be for a user-defined property, or it could be a Unicode property, as
22308 * all of them are considered to be for that package. For the purposes of
22309 * parsing the rest of the property, strip it off */
22310 if (non_pkg_begin == STRLENs("utf8::") && memBEGINPs(name, name_len, "utf8::")) {
22311 lookup_name += STRLENs("utf8::");
22312 j -= STRLENs("utf8::");
22313 equals_pos -= STRLENs("utf8::");
22316 /* Here, we are either done with the whole property name, if it was simple;
22317 * or are positioned just after the '=' if it is compound. */
22319 if (equals_pos >= 0) {
22320 assert(! stricter); /* We shouldn't have set this yet */
22322 /* Space immediately after the '=' is ignored */
22324 for (; i < name_len; i++) {
22325 if (! isSPACE_A(name[i])) {
22330 /* Certain properties whose values are numeric need special handling.
22331 * They may optionally be prefixed by 'is'. Ignore that prefix for the
22332 * purposes of checking if this is one of those properties */
22333 if (memBEGINPs(lookup_name, name_len, "is")) {
22337 /* Then check if it is one of these specially-handled properties. The
22338 * possibilities are hard-coded because easier this way, and the list
22339 * is unlikely to change.
22341 * All numeric value type properties are of this ilk, and are also
22342 * special in a different way later on. So find those first. There
22343 * are several numeric value type properties in the Unihan DB (which is
22344 * unlikely to be compiled with perl, but we handle it here in case it
22345 * does get compiled). They all end with 'numeric'. The interiors
22346 * aren't checked for the precise property. This would stop working if
22347 * a cjk property were to be created that ended with 'numeric' and
22348 * wasn't a numeric type */
22349 is_nv_type = memEQs(lookup_name + lookup_offset,
22350 j - 1 - lookup_offset, "numericvalue")
22351 || memEQs(lookup_name + lookup_offset,
22352 j - 1 - lookup_offset, "nv")
22353 || ( memENDPs(lookup_name + lookup_offset,
22354 j - 1 - lookup_offset, "numeric")
22355 && ( memBEGINPs(lookup_name + lookup_offset,
22356 j - 1 - lookup_offset, "cjk")
22357 || memBEGINPs(lookup_name + lookup_offset,
22358 j - 1 - lookup_offset, "k")));
22360 || memEQs(lookup_name + lookup_offset,
22361 j - 1 - lookup_offset, "canonicalcombiningclass")
22362 || memEQs(lookup_name + lookup_offset,
22363 j - 1 - lookup_offset, "ccc")
22364 || memEQs(lookup_name + lookup_offset,
22365 j - 1 - lookup_offset, "age")
22366 || memEQs(lookup_name + lookup_offset,
22367 j - 1 - lookup_offset, "in")
22368 || memEQs(lookup_name + lookup_offset,
22369 j - 1 - lookup_offset, "presentin"))
22373 /* Since the stuff after the '=' is a number, we can't throw away
22374 * '-' willy-nilly, as those could be a minus sign. Other stricter
22375 * rules also apply. However, these properties all can have the
22376 * rhs not be a number, in which case they contain at least one
22377 * alphabetic. In those cases, the stricter rules don't apply.
22378 * But the numeric type properties can have the alphas [Ee] to
22379 * signify an exponent, and it is still a number with stricter
22380 * rules. So look for an alpha that signifies not-strict */
22382 for (k = i; k < name_len; k++) {
22383 if ( isALPHA_A(name[k])
22384 && (! is_nv_type || ! isALPHA_FOLD_EQ(name[k], 'E')))
22394 /* A number may have a leading '+' or '-'. The latter is retained
22396 if (name[i] == '+') {
22399 else if (name[i] == '-') {
22400 lookup_name[j++] = '-';
22404 /* Skip leading zeros including single underscores separating the
22405 * zeros, or between the final leading zero and the first other
22407 for (; i < name_len - 1; i++) {
22408 if ( name[i] != '0'
22409 && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
22416 else { /* No '=' */
22418 /* Only a few properties without an '=' should be parsed with stricter
22419 * rules. The list is unlikely to change. */
22420 if ( memBEGINPs(lookup_name, j, "perl")
22421 && memNEs(lookup_name + 4, j - 4, "space")
22422 && memNEs(lookup_name + 4, j - 4, "word"))
22426 /* We set the inputs back to 0 and the code below will reparse,
22432 /* Here, we have either finished the property, or are positioned to parse
22433 * the remainder, and we know if stricter rules apply. Finish out, if not
22435 for (; i < name_len; i++) {
22436 char cur = name[i];
22438 /* In all instances, case differences are ignored, and we normalize to
22440 if (isUPPER_A(cur)) {
22441 lookup_name[j++] = toLOWER(cur);
22445 /* An underscore is skipped, but not under strict rules unless it
22446 * separates two digits */
22449 && ( i == 0 || (int) i == equals_pos || i == name_len- 1
22450 || ! isDIGIT_A(name[i-1]) || ! isDIGIT_A(name[i+1])))
22452 lookup_name[j++] = '_';
22457 /* Hyphens are skipped except under strict */
22458 if (cur == '-' && ! stricter) {
22462 /* XXX Bug in documentation. It says white space skipped adjacent to
22463 * non-word char. Maybe we should, but shouldn't skip it next to a dot
22465 if (isSPACE_A(cur) && ! stricter) {
22469 lookup_name[j++] = cur;
22471 /* Unless this is a non-trailing slash, we are done with it */
22472 if (i >= name_len - 1 || cur != '/') {
22478 /* A slash in the 'numeric value' property indicates that what follows
22479 * is a denominator. It can have a leading '+' and '0's that should be
22480 * skipped. But we have never allowed a negative denominator, so treat
22481 * a minus like every other character. (No need to rule out a second
22482 * '/', as that won't match anything anyway */
22485 if (i < name_len && name[i] == '+') {
22489 /* Skip leading zeros including underscores separating digits */
22490 for (; i < name_len - 1; i++) {
22491 if ( name[i] != '0'
22492 && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
22498 /* Store the first real character in the denominator */
22499 lookup_name[j++] = name[i];
22503 /* Here are completely done parsing the input 'name', and 'lookup_name'
22504 * contains a copy, normalized.
22506 * This special case is grandfathered in: 'L_' and 'GC=L_' are accepted and
22507 * different from without the underscores. */
22508 if ( ( UNLIKELY(memEQs(lookup_name, j, "l"))
22509 || UNLIKELY(memEQs(lookup_name, j, "gc=l")))
22510 && UNLIKELY(name[name_len-1] == '_'))
22512 lookup_name[j++] = '&';
22515 /* If the original input began with 'In' or 'Is', it could be a subroutine
22516 * call to a user-defined property instead of a Unicode property name. */
22517 if ( non_pkg_begin + name_len > 2
22518 && name[non_pkg_begin+0] == 'I'
22519 && (name[non_pkg_begin+1] == 'n' || name[non_pkg_begin+1] == 's'))
22521 starts_with_In_or_Is = TRUE;
22524 could_be_user_defined = FALSE;
22527 if (could_be_user_defined) {
22530 /* Here, the name could be for a user defined property, which are
22531 * implemented as subs. */
22532 user_sub = get_cvn_flags(name, name_len, 0);
22535 /* Here, there is a sub by the correct name. Normally we call it
22536 * to get the property definition */
22538 SV * user_sub_sv = MUTABLE_SV(user_sub);
22539 SV * error; /* Any error returned by calling 'user_sub' */
22540 SV * fq_name; /* Fully qualified property name */
22542 char to_fold_string[] = "0:"; /* The 0 gets overwritten with the
22544 SV ** saved_user_prop_ptr; /* Hash entry for this property */
22546 /* How many times to retry when another thread is in the middle of
22547 * expanding the same definition we want */
22548 PERL_INT_FAST8_T retry_countdown = 10;
22550 DECLARATION_FOR_GLOBAL_CONTEXT;
22552 /* If we get here, we know this property is user-defined */
22553 *user_defined_ptr = TRUE;
22555 /* We refuse to call a tainted subroutine; returning an error
22558 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22559 sv_catpvs(msg, "Insecure user-defined property");
22560 goto append_name_to_msg;
22563 /* In principal, we only call each subroutine property definition
22564 * once during the life of the program. This guarantees that the
22565 * property definition never changes. The results of the single
22566 * sub call are stored in a hash, which is used instead for future
22567 * references to this property. The property definition is thus
22568 * immutable. But, to allow the user to have a /i-dependent
22569 * definition, we call the sub once for non-/i, and once for /i,
22570 * should the need arise, passing the /i status as a parameter.
22572 * We start by constructing the hash key name, consisting of the
22573 * fully qualified subroutine name */
22574 fq_name = sv_2mortal(newSV(10)); /* 10 is just a guess */
22575 (void) cv_name(user_sub, fq_name, 0);
22577 /* But precede the sub name in the key with the /i status, so that
22578 * there is a key for /i and a different key for non-/i */
22579 to_fold_string[0] = to_fold + '0';
22580 sv_insert(fq_name, 0, 0, to_fold_string, 2);
22582 /* We only call the sub once throughout the life of the program
22583 * (with the /i, non-/i exception noted above). That means the
22584 * hash must be global and accessible to all threads. It is
22585 * created at program start-up, before any threads are created, so
22586 * is accessible to all children. But this creates some
22589 * 1) The keys can't be shared, or else problems arise; sharing is
22590 * turned off at hash creation time
22591 * 2) All SVs in it are there for the remainder of the life of the
22592 * program, and must be created in the same interpreter context
22593 * as the hash, or else they will be freed from the wrong pool
22594 * at global destruction time. This is handled by switching to
22595 * the hash's context to create each SV going into it, and then
22596 * immediately switching back
22597 * 3) All accesses to the hash must be controlled by a mutex, to
22598 * prevent two threads from getting an unstable state should
22599 * they simultaneously be accessing it. The code below is
22600 * crafted so that the mutex is locked whenever there is an
22601 * access and unlocked only when the next stable state is
22604 * The hash stores either the definition of the property if it was
22605 * valid, or, if invalid, the error message that was raised. We
22606 * use the type of SV to distinguish.
22608 * There's also the need to guard against the definition expansion
22609 * from infinitely recursing. This is handled by storing the aTHX
22610 * of the expanding thread during the expansion. Again the SV type
22611 * is used to distinguish this from the other two cases. If we
22612 * come to here and the hash entry for this property is our aTHX,
22613 * it means we have recursed, and the code assumes that we would
22614 * infinitely recurse, so instead stops and raises an error.
22615 * (Any recursion has always been treated as infinite recursion in
22618 * If instead, the entry is for a different aTHX, it means that
22619 * that thread has gotten here first, and hasn't finished expanding
22620 * the definition yet. We just have to wait until it is done. We
22621 * sleep and retry a few times, returning an error if the other
22622 * thread doesn't complete. */
22625 USER_PROP_MUTEX_LOCK;
22627 /* If we have an entry for this key, the subroutine has already
22628 * been called once with this /i status. */
22629 saved_user_prop_ptr = hv_fetch(PL_user_def_props,
22630 SvPVX(fq_name), SvCUR(fq_name), 0);
22631 if (saved_user_prop_ptr) {
22633 /* If the saved result is an inversion list, it is the valid
22634 * definition of this property */
22635 if (is_invlist(*saved_user_prop_ptr)) {
22636 prop_definition = *saved_user_prop_ptr;
22638 /* The SV in the hash won't be removed until global
22639 * destruction, so it is stable and we can unlock */
22640 USER_PROP_MUTEX_UNLOCK;
22642 /* The caller shouldn't try to free this SV */
22643 return prop_definition;
22646 /* Otherwise, if it is a string, it is the error message
22647 * that was returned when we first tried to evaluate this
22648 * property. Fail, and append the message */
22649 if (SvPOK(*saved_user_prop_ptr)) {
22650 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22651 sv_catsv(msg, *saved_user_prop_ptr);
22653 /* The SV in the hash won't be removed until global
22654 * destruction, so it is stable and we can unlock */
22655 USER_PROP_MUTEX_UNLOCK;
22660 assert(SvIOK(*saved_user_prop_ptr));
22662 /* Here, we have an unstable entry in the hash. Either another
22663 * thread is in the middle of expanding the property's
22664 * definition, or we are ourselves recursing. We use the aTHX
22665 * in it to distinguish */
22666 if (SvIV(*saved_user_prop_ptr) != PTR2IV(CUR_CONTEXT)) {
22668 /* Here, it's another thread doing the expanding. We've
22669 * looked as much as we are going to at the contents of the
22670 * hash entry. It's safe to unlock. */
22671 USER_PROP_MUTEX_UNLOCK;
22673 /* Retry a few times */
22674 if (retry_countdown-- > 0) {
22679 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22680 sv_catpvs(msg, "Timeout waiting for another thread to "
22682 goto append_name_to_msg;
22685 /* Here, we are recursing; don't dig any deeper */
22686 USER_PROP_MUTEX_UNLOCK;
22688 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22690 "Infinite recursion in user-defined property");
22691 goto append_name_to_msg;
22694 /* Here, this thread has exclusive control, and there is no entry
22695 * for this property in the hash. So we have the go ahead to
22696 * expand the definition ourselves. */
22700 /* Create a temporary placeholder in the hash to detect recursion
22702 SWITCH_TO_GLOBAL_CONTEXT;
22703 placeholder= newSVuv(PTR2IV(ORIGINAL_CONTEXT));
22704 (void) hv_store_ent(PL_user_def_props, fq_name, placeholder, 0);
22707 /* Now that we have a placeholder, we can let other threads
22709 USER_PROP_MUTEX_UNLOCK;
22711 /* Make sure the placeholder always gets destroyed */
22712 SAVEDESTRUCTOR_X(S_delete_recursion_entry, SvPVX(fq_name));
22717 /* Call the user's function, with the /i status as a parameter.
22718 * Note that we have gone to a lot of trouble to keep this call
22719 * from being within the locked mutex region. */
22720 XPUSHs(boolSV(to_fold));
22723 (void) call_sv(user_sub_sv, G_EVAL|G_SCALAR);
22728 if (SvTRUE(error)) {
22729 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22730 sv_catpvs(msg, "Error \"");
22731 sv_catsv(msg, error);
22732 sv_catpvs(msg, "\"");
22733 if (name_len > 0) {
22734 sv_catpvs(msg, " in expansion of ");
22735 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8,
22741 prop_definition = NULL;
22743 else { /* G_SCALAR guarantees a single return value */
22745 /* The contents is supposed to be the expansion of the property
22746 * definition. Call a function to check for valid syntax and
22748 prop_definition = handle_user_defined_property(name, name_len,
22749 is_utf8, to_fold, runtime,
22750 POPs, user_defined_ptr,
22755 /* Here, we have the results of the expansion. Replace the
22756 * placeholder with them. We need exclusive access to the hash,
22757 * and we can't let anyone else in, between when we delete the
22758 * placeholder and add the permanent entry */
22759 USER_PROP_MUTEX_LOCK;
22761 S_delete_recursion_entry(aTHX_ SvPVX(fq_name));
22763 if (! prop_definition || is_invlist(prop_definition)) {
22765 /* If we got success we use the inversion list defining the
22766 * property; otherwise use the error message */
22767 SWITCH_TO_GLOBAL_CONTEXT;
22768 (void) hv_store_ent(PL_user_def_props,
22771 ? newSVsv(prop_definition)
22777 /* All done, and the hash now has a permanent entry for this
22778 * property. Give up exclusive control */
22779 USER_PROP_MUTEX_UNLOCK;
22784 if (prop_definition) {
22786 /* If the definition is for something not known at this time,
22787 * we toss it, and go return the main property name, as that's
22788 * the one the user will be aware of */
22789 if (! is_invlist(prop_definition)) {
22790 SvREFCNT_dec_NN(prop_definition);
22791 goto definition_deferred;
22794 sv_2mortal(prop_definition);
22798 return prop_definition;
22800 } /* End of calling the subroutine for the user-defined property */
22801 } /* End of it could be a user-defined property */
22803 /* Here it wasn't a user-defined property that is known at this time. See
22804 * if it is a Unicode property */
22806 lookup_len = j; /* This is a more mnemonic name than 'j' */
22808 /* Get the index into our pointer table of the inversion list corresponding
22809 * to the property */
22810 table_index = match_uniprop((U8 *) lookup_name, lookup_len);
22812 /* If it didn't find the property ... */
22813 if (table_index == 0) {
22815 /* Try again stripping off any initial 'In' or 'Is' */
22816 if (starts_with_In_or_Is) {
22822 table_index = match_uniprop((U8 *) lookup_name, lookup_len);
22825 if (table_index == 0) {
22828 /* Here, we didn't find it. If not a numeric type property, and
22829 * can't be a user-defined one, it isn't a legal property */
22830 if (! is_nv_type) {
22831 if (! could_be_user_defined) {
22835 /* Here, the property name is legal as a user-defined one. At
22836 * compile time, it might just be that the subroutine for that
22837 * property hasn't been encountered yet, but at runtime, it's
22838 * an error to try to use an undefined one */
22840 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22841 sv_catpvs(msg, "Unknown user-defined property name");
22842 goto append_name_to_msg;
22845 goto definition_deferred;
22846 } /* End of isn't a numeric type property */
22848 /* The numeric type properties need more work to decide. What we
22849 * do is make sure we have the number in canonical form and look
22852 if (slash_pos < 0) { /* No slash */
22854 /* When it isn't a rational, take the input, convert it to a
22855 * NV, then create a canonical string representation of that
22860 /* Get the value */
22861 if (my_atof3(lookup_name + equals_pos, &value,
22862 lookup_len - equals_pos)
22863 != lookup_name + lookup_len)
22868 /* If the value is an integer, the canonical value is integral
22870 if (Perl_ceil(value) == value) {
22871 canonical = Perl_form(aTHX_ "%.*s%.0" NVff,
22872 equals_pos, lookup_name, value);
22874 else { /* Otherwise, it is %e with a known precision */
22877 canonical = Perl_form(aTHX_ "%.*s%.*" NVef,
22878 equals_pos, lookup_name,
22879 PL_E_FORMAT_PRECISION, value);
22881 /* The exponent generated is expecting two digits, whereas
22882 * %e on some systems will generate three. Remove leading
22883 * zeros in excess of 2 from the exponent. We start
22884 * looking for them after the '=' */
22885 exp_ptr = strchr(canonical + equals_pos, 'e');
22887 char * cur_ptr = exp_ptr + 2; /* past the 'e[+-]' */
22888 SSize_t excess_exponent_len = strlen(cur_ptr) - 2;
22890 assert(*(cur_ptr - 1) == '-' || *(cur_ptr - 1) == '+');
22892 if (excess_exponent_len > 0) {
22893 SSize_t leading_zeros = strspn(cur_ptr, "0");
22894 SSize_t excess_leading_zeros
22895 = MIN(leading_zeros, excess_exponent_len);
22896 if (excess_leading_zeros > 0) {
22897 Move(cur_ptr + excess_leading_zeros,
22899 strlen(cur_ptr) - excess_leading_zeros
22900 + 1, /* Copy the NUL as well */
22907 else { /* Has a slash. Create a rational in canonical form */
22908 UV numerator, denominator, gcd, trial;
22909 const char * end_ptr;
22910 const char * sign = "";
22912 /* We can't just find the numerator, denominator, and do the
22913 * division, then use the method above, because that is
22914 * inexact. And the input could be a rational that is within
22915 * epsilon (given our precision) of a valid rational, and would
22916 * then incorrectly compare valid.
22918 * We're only interested in the part after the '=' */
22919 const char * this_lookup_name = lookup_name + equals_pos;
22920 lookup_len -= equals_pos;
22921 slash_pos -= equals_pos;
22923 /* Handle any leading minus */
22924 if (this_lookup_name[0] == '-') {
22926 this_lookup_name++;
22931 /* Convert the numerator to numeric */
22932 end_ptr = this_lookup_name + slash_pos;
22933 if (! grok_atoUV(this_lookup_name, &numerator, &end_ptr)) {
22937 /* It better have included all characters before the slash */
22938 if (*end_ptr != '/') {
22942 /* Set to look at just the denominator */
22943 this_lookup_name += slash_pos;
22944 lookup_len -= slash_pos;
22945 end_ptr = this_lookup_name + lookup_len;
22947 /* Convert the denominator to numeric */
22948 if (! grok_atoUV(this_lookup_name, &denominator, &end_ptr)) {
22952 /* It better be the rest of the characters, and don't divide by
22954 if ( end_ptr != this_lookup_name + lookup_len
22955 || denominator == 0)
22960 /* Get the greatest common denominator using
22961 http://en.wikipedia.org/wiki/Euclidean_algorithm */
22963 trial = denominator;
22964 while (trial != 0) {
22966 trial = gcd % trial;
22970 /* If already in lowest possible terms, we have already tried
22971 * looking this up */
22976 /* Reduce the rational, which should put it in canonical form
22979 denominator /= gcd;
22981 canonical = Perl_form(aTHX_ "%.*s%s%" UVuf "/%" UVuf,
22982 equals_pos, lookup_name, sign, numerator, denominator);
22985 /* Here, we have the number in canonical form. Try that */
22986 table_index = match_uniprop((U8 *) canonical, strlen(canonical));
22987 if (table_index == 0) {
22990 } /* End of still didn't find the property in our table */
22991 } /* End of didn't find the property in our table */
22993 /* Here, we have a non-zero return, which is an index into a table of ptrs.
22994 * A negative return signifies that the real index is the absolute value,
22995 * but the result needs to be inverted */
22996 if (table_index < 0) {
22997 invert_return = TRUE;
22998 table_index = -table_index;
23001 /* Out-of band indices indicate a deprecated property. The proper index is
23002 * modulo it with the table size. And dividing by the table size yields
23003 * an offset into a table constructed by regen/mk_invlists.pl to contain
23004 * the corresponding warning message */
23005 if (table_index > MAX_UNI_KEYWORD_INDEX) {
23006 Size_t warning_offset = table_index / MAX_UNI_KEYWORD_INDEX;
23007 table_index %= MAX_UNI_KEYWORD_INDEX;
23008 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
23009 "Use of '%.*s' in \\p{} or \\P{} is deprecated because: %s",
23010 (int) name_len, name, deprecated_property_msgs[warning_offset]);
23013 /* In a few properties, a different property is used under /i. These are
23014 * unlikely to change, so are hard-coded here. */
23016 if ( table_index == UNI_XPOSIXUPPER
23017 || table_index == UNI_XPOSIXLOWER
23018 || table_index == UNI_TITLE)
23020 table_index = UNI_CASED;
23022 else if ( table_index == UNI_UPPERCASELETTER
23023 || table_index == UNI_LOWERCASELETTER
23024 # ifdef UNI_TITLECASELETTER /* Missing from early Unicodes */
23025 || table_index == UNI_TITLECASELETTER
23028 table_index = UNI_CASEDLETTER;
23030 else if ( table_index == UNI_POSIXUPPER
23031 || table_index == UNI_POSIXLOWER)
23033 table_index = UNI_POSIXALPHA;
23037 /* Create and return the inversion list */
23038 prop_definition =_new_invlist_C_array(uni_prop_ptrs[table_index]);
23039 if (invert_return) {
23040 _invlist_invert(prop_definition);
23042 sv_2mortal(prop_definition);
23043 return prop_definition;
23047 if (non_pkg_begin != 0) {
23048 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23049 sv_catpvs(msg, "Illegal user-defined property name");
23052 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23053 sv_catpvs(msg, "Can't find Unicode property definition");
23057 append_name_to_msg:
23059 const char * prefix = (runtime && level == 0) ? " \\p{" : " \"";
23060 const char * suffix = (runtime && level == 0) ? "}" : "\"";
23062 sv_catpv(msg, prefix);
23063 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
23064 sv_catpv(msg, suffix);
23069 definition_deferred:
23071 /* Here it could yet to be defined, so defer evaluation of this
23072 * until its needed at runtime. */
23073 prop_definition = newSVpvs_flags("", SVs_TEMP);
23075 /* To avoid any ambiguity, the package is always specified.
23076 * Use the current one if it wasn't included in our input */
23077 if (non_pkg_begin == 0) {
23078 const HV * pkg = (IN_PERL_COMPILETIME)
23080 : CopSTASH(PL_curcop);
23081 const char* pkgname = HvNAME(pkg);
23083 Perl_sv_catpvf(aTHX_ prop_definition, "%" UTF8f,
23084 UTF8fARG(is_utf8, strlen(pkgname), pkgname));
23085 sv_catpvs(prop_definition, "::");
23088 Perl_sv_catpvf(aTHX_ prop_definition, "%" UTF8f,
23089 UTF8fARG(is_utf8, name_len, name));
23090 sv_catpvs(prop_definition, "\n");
23092 *user_defined_ptr = TRUE;
23093 return prop_definition;
23099 * ex: set ts=8 sts=4 sw=4 et: