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) memCHRs("-[]\\^", 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 *save_copy_start; /* Provides one level of saving
135 and restoring 'copy_start' */
136 char *copy_start_in_input; /* Position in input string
137 corresponding to copy_start */
138 SSize_t whilem_seen; /* number of WHILEM in this expr */
139 regnode *emit_start; /* Start of emitted-code area */
140 regnode_offset emit; /* Code-emit pointer */
141 I32 naughty; /* How bad is this pattern? */
142 I32 sawback; /* Did we see \1, ...? */
144 SSize_t size; /* Number of regnode equivalents in
147 /* position beyond 'precomp' of the warning message furthest away from
148 * 'precomp'. During the parse, no warnings are raised for any problems
149 * earlier in the parse than this position. This works if warnings are
150 * raised the first time a given spot is parsed, and if only one
151 * independent warning is raised for any given spot */
152 Size_t latest_warn_offset;
154 I32 npar; /* Capture buffer count so far in the
155 parse, (OPEN) plus one. ("par" 0 is
157 I32 total_par; /* During initial parse, is either 0,
158 or -1; the latter indicating a
159 reparse is needed. After that pass,
160 it is what 'npar' became after the
161 pass. Hence, it being > 0 indicates
162 we are in a reparse situation */
163 I32 nestroot; /* root parens we are in - used by
166 regnode_offset *open_parens; /* offsets to open parens */
167 regnode_offset *close_parens; /* offsets to close parens */
168 I32 parens_buf_size; /* #slots malloced open/close_parens */
169 regnode *end_op; /* END node in program */
170 I32 utf8; /* whether the pattern is utf8 or not */
171 I32 orig_utf8; /* whether the pattern was originally in utf8 */
172 /* XXX use this for future optimisation of case
173 * where pattern must be upgraded to utf8. */
174 I32 uni_semantics; /* If a d charset modifier should use unicode
175 rules, even if the pattern is not in
177 HV *paren_names; /* Paren names */
179 regnode **recurse; /* Recurse regops */
180 I32 recurse_count; /* Number of recurse regops we have generated */
181 U8 *study_chunk_recursed; /* bitmap of which subs we have moved
183 U32 study_chunk_recursed_bytes; /* bytes in bitmap */
187 I32 override_recoding;
188 I32 recode_x_to_native;
189 I32 in_multi_char_class;
190 struct reg_code_blocks *code_blocks;/* positions of literal (?{})
192 int code_index; /* next code_blocks[] slot */
193 SSize_t maxlen; /* mininum possible number of chars in string to match */
194 scan_frame *frame_head;
195 scan_frame *frame_last;
199 #ifdef ADD_TO_REGEXEC
200 char *starttry; /* -Dr: where regtry was called. */
201 #define RExC_starttry (pRExC_state->starttry)
203 SV *runtime_code_qr; /* qr with the runtime code blocks */
205 const char *lastparse;
207 AV *paren_name_list; /* idx -> name */
208 U32 study_chunk_recursed_count;
212 #define RExC_lastparse (pRExC_state->lastparse)
213 #define RExC_lastnum (pRExC_state->lastnum)
214 #define RExC_paren_name_list (pRExC_state->paren_name_list)
215 #define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count)
216 #define RExC_mysv (pRExC_state->mysv1)
217 #define RExC_mysv1 (pRExC_state->mysv1)
218 #define RExC_mysv2 (pRExC_state->mysv2)
228 #define RExC_flags (pRExC_state->flags)
229 #define RExC_pm_flags (pRExC_state->pm_flags)
230 #define RExC_precomp (pRExC_state->precomp)
231 #define RExC_copy_start_in_input (pRExC_state->copy_start_in_input)
232 #define RExC_copy_start_in_constructed (pRExC_state->copy_start)
233 #define RExC_save_copy_start_in_constructed (pRExC_state->save_copy_start)
234 #define RExC_precomp_end (pRExC_state->precomp_end)
235 #define RExC_rx_sv (pRExC_state->rx_sv)
236 #define RExC_rx (pRExC_state->rx)
237 #define RExC_rxi (pRExC_state->rxi)
238 #define RExC_start (pRExC_state->start)
239 #define RExC_end (pRExC_state->end)
240 #define RExC_parse (pRExC_state->parse)
241 #define RExC_latest_warn_offset (pRExC_state->latest_warn_offset )
242 #define RExC_whilem_seen (pRExC_state->whilem_seen)
243 #define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs
244 under /d from /u ? */
246 #ifdef RE_TRACK_PATTERN_OFFSETS
247 # define RExC_offsets (RExC_rxi->u.offsets) /* I am not like the
250 #define RExC_emit (pRExC_state->emit)
251 #define RExC_emit_start (pRExC_state->emit_start)
252 #define RExC_sawback (pRExC_state->sawback)
253 #define RExC_seen (pRExC_state->seen)
254 #define RExC_size (pRExC_state->size)
255 #define RExC_maxlen (pRExC_state->maxlen)
256 #define RExC_npar (pRExC_state->npar)
257 #define RExC_total_parens (pRExC_state->total_par)
258 #define RExC_parens_buf_size (pRExC_state->parens_buf_size)
259 #define RExC_nestroot (pRExC_state->nestroot)
260 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
261 #define RExC_utf8 (pRExC_state->utf8)
262 #define RExC_uni_semantics (pRExC_state->uni_semantics)
263 #define RExC_orig_utf8 (pRExC_state->orig_utf8)
264 #define RExC_open_parens (pRExC_state->open_parens)
265 #define RExC_close_parens (pRExC_state->close_parens)
266 #define RExC_end_op (pRExC_state->end_op)
267 #define RExC_paren_names (pRExC_state->paren_names)
268 #define RExC_recurse (pRExC_state->recurse)
269 #define RExC_recurse_count (pRExC_state->recurse_count)
270 #define RExC_study_chunk_recursed (pRExC_state->study_chunk_recursed)
271 #define RExC_study_chunk_recursed_bytes \
272 (pRExC_state->study_chunk_recursed_bytes)
273 #define RExC_in_lookbehind (pRExC_state->in_lookbehind)
274 #define RExC_in_lookahead (pRExC_state->in_lookahead)
275 #define RExC_contains_locale (pRExC_state->contains_locale)
276 #define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
279 # define SET_recode_x_to_native(x) \
280 STMT_START { RExC_recode_x_to_native = (x); } STMT_END
282 # define SET_recode_x_to_native(x) NOOP
285 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
286 #define RExC_frame_head (pRExC_state->frame_head)
287 #define RExC_frame_last (pRExC_state->frame_last)
288 #define RExC_frame_count (pRExC_state->frame_count)
289 #define RExC_strict (pRExC_state->strict)
290 #define RExC_study_started (pRExC_state->study_started)
291 #define RExC_warn_text (pRExC_state->warn_text)
292 #define RExC_in_script_run (pRExC_state->in_script_run)
293 #define RExC_use_BRANCHJ (pRExC_state->use_BRANCHJ)
294 #define RExC_unlexed_names (pRExC_state->unlexed_names)
296 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
297 * a flag to disable back-off on the fixed/floating substrings - if it's
298 * a high complexity pattern we assume the benefit of avoiding a full match
299 * is worth the cost of checking for the substrings even if they rarely help.
301 #define RExC_naughty (pRExC_state->naughty)
302 #define TOO_NAUGHTY (10)
303 #define MARK_NAUGHTY(add) \
304 if (RExC_naughty < TOO_NAUGHTY) \
305 RExC_naughty += (add)
306 #define MARK_NAUGHTY_EXP(exp, add) \
307 if (RExC_naughty < TOO_NAUGHTY) \
308 RExC_naughty += RExC_naughty / (exp) + (add)
310 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
311 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
312 ((*s) == '{' && regcurly(s)))
315 * Flags to be passed up and down.
317 #define WORST 0 /* Worst case. */
318 #define HASWIDTH 0x01 /* Known to not match null strings, could match
321 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
322 * character. (There needs to be a case: in the switch statement in regexec.c
323 * for any node marked SIMPLE.) Note that this is not the same thing as
326 #define SPSTART 0x04 /* Starts with * or + */
327 #define POSTPONED 0x08 /* (?1),(?&name), (??{...}) or similar */
328 #define TRYAGAIN 0x10 /* Weeded out a declaration. */
329 #define RESTART_PARSE 0x20 /* Need to redo the parse */
330 #define NEED_UTF8 0x40 /* In conjunction with RESTART_PARSE, need to
331 calcuate sizes as UTF-8 */
333 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
335 /* whether trie related optimizations are enabled */
336 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
337 #define TRIE_STUDY_OPT
338 #define FULL_TRIE_STUDY
344 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
345 #define PBITVAL(paren) (1 << ((paren) & 7))
346 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
347 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
348 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
350 #define REQUIRE_UTF8(flagp) STMT_START { \
352 *flagp = RESTART_PARSE|NEED_UTF8; \
357 /* Change from /d into /u rules, and restart the parse. RExC_uni_semantics is
358 * a flag that indicates we need to override /d with /u as a result of
359 * something in the pattern. It should only be used in regards to calling
360 * set_regex_charset() or get_regex_charset() */
361 #define REQUIRE_UNI_RULES(flagp, restart_retval) \
363 if (DEPENDS_SEMANTICS) { \
364 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); \
365 RExC_uni_semantics = 1; \
366 if (RExC_seen_d_op && LIKELY(! IN_PARENS_PASS)) { \
367 /* No need to restart the parse if we haven't seen \
368 * anything that differs between /u and /d, and no need \
369 * to restart immediately if we're going to reparse \
370 * anyway to count parens */ \
371 *flagp |= RESTART_PARSE; \
372 return restart_retval; \
377 #define REQUIRE_BRANCHJ(flagp, restart_retval) \
379 RExC_use_BRANCHJ = 1; \
380 *flagp |= RESTART_PARSE; \
381 return restart_retval; \
384 /* Until we have completed the parse, we leave RExC_total_parens at 0 or
385 * less. After that, it must always be positive, because the whole re is
386 * considered to be surrounded by virtual parens. Setting it to negative
387 * indicates there is some construct that needs to know the actual number of
388 * parens to be properly handled. And that means an extra pass will be
389 * required after we've counted them all */
390 #define ALL_PARENS_COUNTED (RExC_total_parens > 0)
391 #define REQUIRE_PARENS_PASS \
392 STMT_START { /* No-op if have completed a pass */ \
393 if (! ALL_PARENS_COUNTED) RExC_total_parens = -1; \
395 #define IN_PARENS_PASS (RExC_total_parens < 0)
398 /* This is used to return failure (zero) early from the calling function if
399 * various flags in 'flags' are set. Two flags always cause a return:
400 * 'RESTART_PARSE' and 'NEED_UTF8'. 'extra' can be used to specify any
401 * additional flags that should cause a return; 0 if none. If the return will
402 * be done, '*flagp' is first set to be all of the flags that caused the
404 #define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra) \
406 if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) { \
407 *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra)); \
412 #define MUST_RESTART(flags) ((flags) & (RESTART_PARSE))
414 #define RETURN_FAIL_ON_RESTART(flags,flagp) \
415 RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0)
416 #define RETURN_FAIL_ON_RESTART_FLAGP(flagp) \
417 if (MUST_RESTART(*(flagp))) return 0
419 /* This converts the named class defined in regcomp.h to its equivalent class
420 * number defined in handy.h. */
421 #define namedclass_to_classnum(class) ((int) ((class) / 2))
422 #define classnum_to_namedclass(classnum) ((classnum) * 2)
424 #define _invlist_union_complement_2nd(a, b, output) \
425 _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
426 #define _invlist_intersection_complement_2nd(a, b, output) \
427 _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
429 /* We add a marker if we are deferring expansion of a property that is both
430 * 1) potentiallly user-defined; and
431 * 2) could also be an official Unicode property.
433 * Without this marker, any deferred expansion can only be for a user-defined
434 * one. This marker shouldn't conflict with any that could be in a legal name,
435 * and is appended to its name to indicate this. There is a string and
437 #define DEFERRED_COULD_BE_OFFICIAL_MARKERs "~"
438 #define DEFERRED_COULD_BE_OFFICIAL_MARKERc '~'
440 /* About scan_data_t.
442 During optimisation we recurse through the regexp program performing
443 various inplace (keyhole style) optimisations. In addition study_chunk
444 and scan_commit populate this data structure with information about
445 what strings MUST appear in the pattern. We look for the longest
446 string that must appear at a fixed location, and we look for the
447 longest string that may appear at a floating location. So for instance
452 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
453 strings (because they follow a .* construct). study_chunk will identify
454 both FOO and BAR as being the longest fixed and floating strings respectively.
456 The strings can be composites, for instance
460 will result in a composite fixed substring 'foo'.
462 For each string some basic information is maintained:
465 This is the position the string must appear at, or not before.
466 It also implicitly (when combined with minlenp) tells us how many
467 characters must match before the string we are searching for.
468 Likewise when combined with minlenp and the length of the string it
469 tells us how many characters must appear after the string we have
473 Only used for floating strings. This is the rightmost point that
474 the string can appear at. If set to SSize_t_MAX it indicates that the
475 string can occur infinitely far to the right.
476 For fixed strings, it is equal to min_offset.
479 A pointer to the minimum number of characters of the pattern that the
480 string was found inside. This is important as in the case of positive
481 lookahead or positive lookbehind we can have multiple patterns
486 The minimum length of the pattern overall is 3, the minimum length
487 of the lookahead part is 3, but the minimum length of the part that
488 will actually match is 1. So 'FOO's minimum length is 3, but the
489 minimum length for the F is 1. This is important as the minimum length
490 is used to determine offsets in front of and behind the string being
491 looked for. Since strings can be composites this is the length of the
492 pattern at the time it was committed with a scan_commit. Note that
493 the length is calculated by study_chunk, so that the minimum lengths
494 are not known until the full pattern has been compiled, thus the
495 pointer to the value.
499 In the case of lookbehind the string being searched for can be
500 offset past the start point of the final matching string.
501 If this value was just blithely removed from the min_offset it would
502 invalidate some of the calculations for how many chars must match
503 before or after (as they are derived from min_offset and minlen and
504 the length of the string being searched for).
505 When the final pattern is compiled and the data is moved from the
506 scan_data_t structure into the regexp structure the information
507 about lookbehind is factored in, with the information that would
508 have been lost precalculated in the end_shift field for the
511 The fields pos_min and pos_delta are used to store the minimum offset
512 and the delta to the maximum offset at the current point in the pattern.
516 struct scan_data_substrs {
517 SV *str; /* longest substring found in pattern */
518 SSize_t min_offset; /* earliest point in string it can appear */
519 SSize_t max_offset; /* latest point in string it can appear */
520 SSize_t *minlenp; /* pointer to the minlen relevant to the string */
521 SSize_t lookbehind; /* is the pos of the string modified by LB */
522 I32 flags; /* per substring SF_* and SCF_* flags */
525 typedef struct scan_data_t {
526 /*I32 len_min; unused */
527 /*I32 len_delta; unused */
531 SSize_t last_end; /* min value, <0 unless valid. */
532 SSize_t last_start_min;
533 SSize_t last_start_max;
534 U8 cur_is_floating; /* whether the last_* values should be set as
535 * the next fixed (0) or floating (1)
538 /* [0] is longest fixed substring so far, [1] is longest float so far */
539 struct scan_data_substrs substrs[2];
541 I32 flags; /* common SF_* and SCF_* flags */
543 SSize_t *last_closep;
544 regnode_ssc *start_class;
548 * Forward declarations for pregcomp()'s friends.
551 static const scan_data_t zero_scan_data = {
552 0, 0, NULL, 0, 0, 0, 0,
554 { NULL, 0, 0, 0, 0, 0 },
555 { NULL, 0, 0, 0, 0, 0 },
562 #define SF_BEFORE_SEOL 0x0001
563 #define SF_BEFORE_MEOL 0x0002
564 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
566 #define SF_IS_INF 0x0040
567 #define SF_HAS_PAR 0x0080
568 #define SF_IN_PAR 0x0100
569 #define SF_HAS_EVAL 0x0200
572 /* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
573 * longest substring in the pattern. When it is not set the optimiser keeps
574 * track of position, but does not keep track of the actual strings seen,
576 * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
579 * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
580 * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
581 * turned off because of the alternation (BRANCH). */
582 #define SCF_DO_SUBSTR 0x0400
584 #define SCF_DO_STCLASS_AND 0x0800
585 #define SCF_DO_STCLASS_OR 0x1000
586 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
587 #define SCF_WHILEM_VISITED_POS 0x2000
589 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
590 #define SCF_SEEN_ACCEPT 0x8000
591 #define SCF_TRIE_DOING_RESTUDY 0x10000
592 #define SCF_IN_DEFINE 0x20000
597 #define UTF cBOOL(RExC_utf8)
599 /* The enums for all these are ordered so things work out correctly */
600 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
601 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) \
602 == REGEX_DEPENDS_CHARSET)
603 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
604 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) \
605 >= REGEX_UNICODE_CHARSET)
606 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
607 == REGEX_ASCII_RESTRICTED_CHARSET)
608 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
609 >= REGEX_ASCII_RESTRICTED_CHARSET)
610 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) \
611 == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
613 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
615 /* For programs that want to be strictly Unicode compatible by dying if any
616 * attempt is made to match a non-Unicode code point against a Unicode
618 #define ALWAYS_WARN_SUPER ckDEAD(packWARN(WARN_NON_UNICODE))
620 #define OOB_NAMEDCLASS -1
622 /* There is no code point that is out-of-bounds, so this is problematic. But
623 * its only current use is to initialize a variable that is always set before
625 #define OOB_UNICODE 0xDEADBEEF
627 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
630 /* length of regex to show in messages that don't mark a position within */
631 #define RegexLengthToShowInErrorMessages 127
634 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
635 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
636 * op/pragma/warn/regcomp.
638 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
639 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
641 #define REPORT_LOCATION " in regex; marked by " MARKER1 \
642 " in m/%" UTF8f MARKER2 "%" UTF8f "/"
644 /* The code in this file in places uses one level of recursion with parsing
645 * rebased to an alternate string constructed by us in memory. This can take
646 * the form of something that is completely different from the input, or
647 * something that uses the input as part of the alternate. In the first case,
648 * there should be no possibility of an error, as we are in complete control of
649 * the alternate string. But in the second case we don't completely control
650 * the input portion, so there may be errors in that. Here's an example:
652 * is handled specially because \x{df} folds to a sequence of more than one
653 * character: 'ss'. What is done is to create and parse an alternate string,
654 * which looks like this:
655 * /(?:\x{DF}|[abc\x{DF}def])/ui
656 * where it uses the input unchanged in the middle of something it constructs,
657 * which is a branch for the DF outside the character class, and clustering
658 * parens around the whole thing. (It knows enough to skip the DF inside the
659 * class while in this substitute parse.) 'abc' and 'def' may have errors that
660 * need to be reported. The general situation looks like this:
662 * |<------- identical ------>|
664 * Input: ---------------------------------------------------------------
665 * Constructed: ---------------------------------------------------
667 * |<------- identical ------>|
669 * sI..eI is the portion of the input pattern we are concerned with here.
670 * sC..EC is the constructed substitute parse string.
671 * sC..tC is constructed by us
672 * tC..eC is an exact duplicate of the portion of the input pattern tI..eI.
673 * In the diagram, these are vertically aligned.
674 * eC..EC is also constructed by us.
675 * xC is the position in the substitute parse string where we found a
677 * xI is the position in the original pattern corresponding to xC.
679 * We want to display a message showing the real input string. Thus we need to
680 * translate from xC to xI. We know that xC >= tC, since the portion of the
681 * string sC..tC has been constructed by us, and so shouldn't have errors. We
683 * xI = tI + (xC - tC)
685 * When the substitute parse is constructed, the code needs to set:
688 * RExC_copy_start_in_input (tI)
689 * RExC_copy_start_in_constructed (tC)
690 * and restore them when done.
692 * During normal processing of the input pattern, both
693 * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to
694 * sI, so that xC equals xI.
697 #define sI RExC_precomp
698 #define eI RExC_precomp_end
699 #define sC RExC_start
701 #define tI RExC_copy_start_in_input
702 #define tC RExC_copy_start_in_constructed
703 #define xI(xC) (tI + (xC - tC))
704 #define xI_offset(xC) (xI(xC) - sI)
706 #define REPORT_LOCATION_ARGS(xC) \
708 (xI(xC) > eI) /* Don't run off end */ \
709 ? eI - sI /* Length before the <--HERE */ \
710 : ((xI_offset(xC) >= 0) \
712 : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %" \
713 IVdf " trying to output message for " \
715 __FILE__, __LINE__, (IV) xI_offset(xC), \
716 ((int) (eC - sC)), sC), 0)), \
717 sI), /* The input pattern printed up to the <--HERE */ \
719 (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */ \
720 (xI(xC) > eI) ? eI : xI(xC)) /* pattern after <--HERE */
722 /* Used to point after bad bytes for an error message, but avoid skipping
723 * past a nul byte. */
724 #define SKIP_IF_CHAR(s, e) (!*(s) ? 0 : UTF ? UTF8_SAFE_SKIP(s, e) : 1)
726 /* Set up to clean up after our imminent demise */
727 #define PREPARE_TO_DIE \
730 SAVEFREESV(RExC_rx_sv); \
731 if (RExC_open_parens) \
732 SAVEFREEPV(RExC_open_parens); \
733 if (RExC_close_parens) \
734 SAVEFREEPV(RExC_close_parens); \
738 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
739 * arg. Show regex, up to a maximum length. If it's too long, chop and add
742 #define _FAIL(code) STMT_START { \
743 const char *ellipses = ""; \
744 IV len = RExC_precomp_end - RExC_precomp; \
747 if (len > RegexLengthToShowInErrorMessages) { \
748 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
749 len = RegexLengthToShowInErrorMessages - 10; \
755 #define FAIL(msg) _FAIL( \
756 Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/", \
757 msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
759 #define FAIL2(msg,arg) _FAIL( \
760 Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \
761 arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
763 #define FAIL3(msg,arg1,arg2) _FAIL( \
764 Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \
765 arg1, arg2, UTF8fARG(UTF, len, RExC_precomp), ellipses))
768 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
770 #define Simple_vFAIL(m) STMT_START { \
771 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
772 m, REPORT_LOCATION_ARGS(RExC_parse)); \
776 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
778 #define vFAIL(m) STMT_START { \
784 * Like Simple_vFAIL(), but accepts two arguments.
786 #define Simple_vFAIL2(m,a1) STMT_START { \
787 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
788 REPORT_LOCATION_ARGS(RExC_parse)); \
792 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
794 #define vFAIL2(m,a1) STMT_START { \
796 Simple_vFAIL2(m, a1); \
801 * Like Simple_vFAIL(), but accepts three arguments.
803 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
804 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
805 REPORT_LOCATION_ARGS(RExC_parse)); \
809 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
811 #define vFAIL3(m,a1,a2) STMT_START { \
813 Simple_vFAIL3(m, a1, a2); \
817 * Like Simple_vFAIL(), but accepts four arguments.
819 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
820 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3, \
821 REPORT_LOCATION_ARGS(RExC_parse)); \
824 #define vFAIL4(m,a1,a2,a3) STMT_START { \
826 Simple_vFAIL4(m, a1, a2, a3); \
829 /* A specialized version of vFAIL2 that works with UTF8f */
830 #define vFAIL2utf8f(m, a1) STMT_START { \
832 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
833 REPORT_LOCATION_ARGS(RExC_parse)); \
836 #define vFAIL3utf8f(m, a1, a2) STMT_START { \
838 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
839 REPORT_LOCATION_ARGS(RExC_parse)); \
842 /* Setting this to NULL is a signal to not output warnings */
843 #define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE \
845 RExC_save_copy_start_in_constructed = RExC_copy_start_in_constructed;\
846 RExC_copy_start_in_constructed = NULL; \
848 #define RESTORE_WARNINGS \
849 RExC_copy_start_in_constructed = RExC_save_copy_start_in_constructed
851 /* Since a warning can be generated multiple times as the input is reparsed, we
852 * output it the first time we come to that point in the parse, but suppress it
853 * otherwise. 'RExC_copy_start_in_constructed' being NULL is a flag to not
854 * generate any warnings */
855 #define TO_OUTPUT_WARNINGS(loc) \
856 ( RExC_copy_start_in_constructed \
857 && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset)
859 /* After we've emitted a warning, we save the position in the input so we don't
861 #define UPDATE_WARNINGS_LOC(loc) \
863 if (TO_OUTPUT_WARNINGS(loc)) { \
864 RExC_latest_warn_offset = MAX(sI, MIN(eI, xI(loc))) \
869 /* 'warns' is the output of the packWARNx macro used in 'code' */
870 #define _WARN_HELPER(loc, warns, code) \
872 if (! RExC_copy_start_in_constructed) { \
873 Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none" \
874 " expected at '%s'", \
875 __FILE__, __LINE__, loc); \
877 if (TO_OUTPUT_WARNINGS(loc)) { \
881 UPDATE_WARNINGS_LOC(loc); \
885 /* m is not necessarily a "literal string", in this macro */
886 #define reg_warn_non_literal_string(loc, m) \
887 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
888 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
889 "%s" REPORT_LOCATION, \
890 m, REPORT_LOCATION_ARGS(loc)))
892 #define ckWARNreg(loc,m) \
893 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
894 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
896 REPORT_LOCATION_ARGS(loc)))
898 #define vWARN(loc, m) \
899 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
900 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
902 REPORT_LOCATION_ARGS(loc))) \
904 #define vWARN_dep(loc, m) \
905 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
906 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), \
908 REPORT_LOCATION_ARGS(loc)))
910 #define ckWARNdep(loc,m) \
911 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
912 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
914 REPORT_LOCATION_ARGS(loc)))
916 #define ckWARNregdep(loc,m) \
917 _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
918 Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, \
921 REPORT_LOCATION_ARGS(loc)))
923 #define ckWARN2reg_d(loc,m, a1) \
924 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
925 Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP), \
927 a1, REPORT_LOCATION_ARGS(loc)))
929 #define ckWARN2reg(loc, m, a1) \
930 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
931 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
933 a1, REPORT_LOCATION_ARGS(loc)))
935 #define vWARN3(loc, m, a1, a2) \
936 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
937 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
939 a1, a2, REPORT_LOCATION_ARGS(loc)))
941 #define ckWARN3reg(loc, m, a1, a2) \
942 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
943 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
946 REPORT_LOCATION_ARGS(loc)))
948 #define vWARN4(loc, m, a1, a2, a3) \
949 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
950 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
953 REPORT_LOCATION_ARGS(loc)))
955 #define ckWARN4reg(loc, m, a1, a2, a3) \
956 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
957 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
960 REPORT_LOCATION_ARGS(loc)))
962 #define vWARN5(loc, m, a1, a2, a3, a4) \
963 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
964 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
967 REPORT_LOCATION_ARGS(loc)))
969 #define ckWARNexperimental(loc, class, m) \
970 _WARN_HELPER(loc, packWARN(class), \
971 Perl_ck_warner_d(aTHX_ packWARN(class), \
973 REPORT_LOCATION_ARGS(loc)))
975 /* Convert between a pointer to a node and its offset from the beginning of the
977 #define REGNODE_p(offset) (RExC_emit_start + (offset))
978 #define REGNODE_OFFSET(node) ((node) - RExC_emit_start)
980 /* Macros for recording node offsets. 20001227 mjd@plover.com
981 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
982 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
983 * Element 0 holds the number n.
984 * Position is 1 indexed.
986 #ifndef RE_TRACK_PATTERN_OFFSETS
987 #define Set_Node_Offset_To_R(offset,byte)
988 #define Set_Node_Offset(node,byte)
989 #define Set_Cur_Node_Offset
990 #define Set_Node_Length_To_R(node,len)
991 #define Set_Node_Length(node,len)
992 #define Set_Node_Cur_Length(node,start)
993 #define Node_Offset(n)
994 #define Node_Length(n)
995 #define Set_Node_Offset_Length(node,offset,len)
996 #define ProgLen(ri) ri->u.proglen
997 #define SetProgLen(ri,x) ri->u.proglen = x
998 #define Track_Code(code)
1000 #define ProgLen(ri) ri->u.offsets[0]
1001 #define SetProgLen(ri,x) ri->u.offsets[0] = x
1002 #define Set_Node_Offset_To_R(offset,byte) STMT_START { \
1003 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
1004 __LINE__, (int)(offset), (int)(byte))); \
1005 if((offset) < 0) { \
1006 Perl_croak(aTHX_ "value of node is %d in Offset macro", \
1009 RExC_offsets[2*(offset)-1] = (byte); \
1013 #define Set_Node_Offset(node,byte) \
1014 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start)
1015 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
1017 #define Set_Node_Length_To_R(node,len) STMT_START { \
1018 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
1019 __LINE__, (int)(node), (int)(len))); \
1021 Perl_croak(aTHX_ "value of node is %d in Length macro", \
1024 RExC_offsets[2*(node)] = (len); \
1028 #define Set_Node_Length(node,len) \
1029 Set_Node_Length_To_R(REGNODE_OFFSET(node), len)
1030 #define Set_Node_Cur_Length(node, start) \
1031 Set_Node_Length(node, RExC_parse - start)
1033 /* Get offsets and lengths */
1034 #define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1])
1035 #define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))])
1037 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
1038 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset)); \
1039 Set_Node_Length_To_R(REGNODE_OFFSET(node), (len)); \
1042 #define Track_Code(code) STMT_START { code } STMT_END
1045 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
1046 #define EXPERIMENTAL_INPLACESCAN
1047 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
1051 Perl_re_printf(pTHX_ const char *fmt, ...)
1055 PerlIO *f= Perl_debug_log;
1056 PERL_ARGS_ASSERT_RE_PRINTF;
1058 result = PerlIO_vprintf(f, fmt, ap);
1064 Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
1068 PerlIO *f= Perl_debug_log;
1069 PERL_ARGS_ASSERT_RE_INDENTF;
1070 va_start(ap, depth);
1071 PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
1072 result = PerlIO_vprintf(f, fmt, ap);
1076 #endif /* DEBUGGING */
1078 #define DEBUG_RExC_seen() \
1079 DEBUG_OPTIMISE_MORE_r({ \
1080 Perl_re_printf( aTHX_ "RExC_seen: "); \
1082 if (RExC_seen & REG_ZERO_LEN_SEEN) \
1083 Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN "); \
1085 if (RExC_seen & REG_LOOKBEHIND_SEEN) \
1086 Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN "); \
1088 if (RExC_seen & REG_GPOS_SEEN) \
1089 Perl_re_printf( aTHX_ "REG_GPOS_SEEN "); \
1091 if (RExC_seen & REG_RECURSE_SEEN) \
1092 Perl_re_printf( aTHX_ "REG_RECURSE_SEEN "); \
1094 if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN) \
1095 Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN "); \
1097 if (RExC_seen & REG_VERBARG_SEEN) \
1098 Perl_re_printf( aTHX_ "REG_VERBARG_SEEN "); \
1100 if (RExC_seen & REG_CUTGROUP_SEEN) \
1101 Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN "); \
1103 if (RExC_seen & REG_RUN_ON_COMMENT_SEEN) \
1104 Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN "); \
1106 if (RExC_seen & REG_UNFOLDED_MULTI_SEEN) \
1107 Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN "); \
1109 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) \
1110 Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN "); \
1112 Perl_re_printf( aTHX_ "\n"); \
1115 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
1116 if ((flags) & flag) Perl_re_printf( aTHX_ "%s ", #flag)
1121 S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
1122 const char *close_str)
1127 Perl_re_printf( aTHX_ "%s", open_str);
1128 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
1129 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
1130 DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
1131 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
1132 DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
1133 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
1134 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
1135 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
1136 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
1137 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
1138 DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
1139 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
1140 DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
1141 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
1142 DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
1143 Perl_re_printf( aTHX_ "%s", close_str);
1148 S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
1149 U32 depth, int is_inf)
1151 GET_RE_DEBUG_FLAGS_DECL;
1153 DEBUG_OPTIMISE_MORE_r({
1156 Perl_re_indentf(aTHX_ "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
1160 (IV)data->pos_delta,
1164 S_debug_show_study_flags(aTHX_ data->flags," [","]");
1166 Perl_re_printf( aTHX_
1167 " Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
1169 (IV)(data->last_closep ? *((data)->last_closep) : -1),
1170 is_inf ? "INF " : ""
1173 if (data->last_found) {
1175 Perl_re_printf(aTHX_
1176 "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
1177 SvPVX_const(data->last_found),
1179 (IV)data->last_start_min,
1180 (IV)data->last_start_max
1183 for (i = 0; i < 2; i++) {
1184 Perl_re_printf(aTHX_
1185 " %s%s: '%s' @ %" IVdf "/%" IVdf,
1186 data->cur_is_floating == i ? "*" : "",
1187 i ? "Float" : "Fixed",
1188 SvPVX_const(data->substrs[i].str),
1189 (IV)data->substrs[i].min_offset,
1190 (IV)data->substrs[i].max_offset
1192 S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
1196 Perl_re_printf( aTHX_ "\n");
1202 S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
1203 regnode *scan, U32 depth, U32 flags)
1205 GET_RE_DEBUG_FLAGS_DECL;
1212 Next = regnext(scan);
1213 regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
1214 Perl_re_indentf( aTHX_ "%s>%3d: %s (%d)",
1217 REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
1218 Next ? (REG_NODE_NUM(Next)) : 0 );
1219 S_debug_show_study_flags(aTHX_ flags," [ ","]");
1220 Perl_re_printf( aTHX_ "\n");
1225 # define DEBUG_STUDYDATA(where, data, depth, is_inf) \
1226 S_debug_studydata(aTHX_ where, data, depth, is_inf)
1228 # define DEBUG_PEEP(str, scan, depth, flags) \
1229 S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
1232 # define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
1233 # define DEBUG_PEEP(str, scan, depth, flags) NOOP
1237 /* =========================================================
1238 * BEGIN edit_distance stuff.
1240 * This calculates how many single character changes of any type are needed to
1241 * transform a string into another one. It is taken from version 3.1 of
1243 * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1246 /* Our unsorted dictionary linked list. */
1247 /* Note we use UVs, not chars. */
1252 struct dictionary* next;
1254 typedef struct dictionary item;
1257 PERL_STATIC_INLINE item*
1258 push(UV key, item* curr)
1261 Newx(head, 1, item);
1269 PERL_STATIC_INLINE item*
1270 find(item* head, UV key)
1272 item* iterator = head;
1274 if (iterator->key == key){
1277 iterator = iterator->next;
1283 PERL_STATIC_INLINE item*
1284 uniquePush(item* head, UV key)
1286 item* iterator = head;
1289 if (iterator->key == key) {
1292 iterator = iterator->next;
1295 return push(key, head);
1298 PERL_STATIC_INLINE void
1299 dict_free(item* head)
1301 item* iterator = head;
1304 item* temp = iterator;
1305 iterator = iterator->next;
1312 /* End of Dictionary Stuff */
1314 /* All calculations/work are done here */
1316 S_edit_distance(const UV* src,
1318 const STRLEN x, /* length of src[] */
1319 const STRLEN y, /* length of tgt[] */
1320 const SSize_t maxDistance
1324 UV swapCount, swapScore, targetCharCount, i, j;
1326 UV score_ceil = x + y;
1328 PERL_ARGS_ASSERT_EDIT_DISTANCE;
1330 /* intialize matrix start values */
1331 Newx(scores, ( (x + 2) * (y + 2)), UV);
1332 scores[0] = score_ceil;
1333 scores[1 * (y + 2) + 0] = score_ceil;
1334 scores[0 * (y + 2) + 1] = score_ceil;
1335 scores[1 * (y + 2) + 1] = 0;
1336 head = uniquePush(uniquePush(head, src[0]), tgt[0]);
1341 for (i=1;i<=x;i++) {
1343 head = uniquePush(head, src[i]);
1344 scores[(i+1) * (y + 2) + 1] = i;
1345 scores[(i+1) * (y + 2) + 0] = score_ceil;
1348 for (j=1;j<=y;j++) {
1351 head = uniquePush(head, tgt[j]);
1352 scores[1 * (y + 2) + (j + 1)] = j;
1353 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1356 targetCharCount = find(head, tgt[j-1])->value;
1357 swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1359 if (src[i-1] != tgt[j-1]){
1360 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));
1364 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1368 find(head, src[i-1])->value = i;
1372 IV score = scores[(x+1) * (y + 2) + (y + 1)];
1375 return (maxDistance != 0 && maxDistance < score)?(-1):score;
1379 /* END of edit_distance() stuff
1380 * ========================================================= */
1382 /* is c a control character for which we have a mnemonic? */
1383 #define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
1386 S_cntrl_to_mnemonic(const U8 c)
1388 /* Returns the mnemonic string that represents character 'c', if one
1389 * exists; NULL otherwise. The only ones that exist for the purposes of
1390 * this routine are a few control characters */
1393 case '\a': return "\\a";
1394 case '\b': return "\\b";
1395 case ESC_NATIVE: return "\\e";
1396 case '\f': return "\\f";
1397 case '\n': return "\\n";
1398 case '\r': return "\\r";
1399 case '\t': return "\\t";
1405 /* Mark that we cannot extend a found fixed substring at this point.
1406 Update the longest found anchored substring or the longest found
1407 floating substrings if needed. */
1410 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1411 SSize_t *minlenp, int is_inf)
1413 const STRLEN l = CHR_SVLEN(data->last_found);
1414 SV * const longest_sv = data->substrs[data->cur_is_floating].str;
1415 const STRLEN old_l = CHR_SVLEN(longest_sv);
1416 GET_RE_DEBUG_FLAGS_DECL;
1418 PERL_ARGS_ASSERT_SCAN_COMMIT;
1420 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1421 const U8 i = data->cur_is_floating;
1422 SvSetMagicSV(longest_sv, data->last_found);
1423 data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
1426 data->substrs[0].max_offset = data->substrs[0].min_offset;
1428 data->substrs[1].max_offset = (l
1429 ? data->last_start_max
1430 : (data->pos_delta > SSize_t_MAX - data->pos_min
1432 : data->pos_min + data->pos_delta));
1434 || (STRLEN)data->substrs[1].max_offset > (STRLEN)SSize_t_MAX)
1435 data->substrs[1].max_offset = SSize_t_MAX;
1438 if (data->flags & SF_BEFORE_EOL)
1439 data->substrs[i].flags |= (data->flags & SF_BEFORE_EOL);
1441 data->substrs[i].flags &= ~SF_BEFORE_EOL;
1442 data->substrs[i].minlenp = minlenp;
1443 data->substrs[i].lookbehind = 0;
1446 SvCUR_set(data->last_found, 0);
1448 SV * const sv = data->last_found;
1449 if (SvUTF8(sv) && SvMAGICAL(sv)) {
1450 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1455 data->last_end = -1;
1456 data->flags &= ~SF_BEFORE_EOL;
1457 DEBUG_STUDYDATA("commit", data, 0, is_inf);
1460 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1461 * list that describes which code points it matches */
1464 S_ssc_anything(pTHX_ regnode_ssc *ssc)
1466 /* Set the SSC 'ssc' to match an empty string or any code point */
1468 PERL_ARGS_ASSERT_SSC_ANYTHING;
1470 assert(is_ANYOF_SYNTHETIC(ssc));
1472 /* mortalize so won't leak */
1473 ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
1474 ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING; /* Plus matches empty */
1478 S_ssc_is_anything(const regnode_ssc *ssc)
1480 /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1481 * point; FALSE otherwise. Thus, this is used to see if using 'ssc' buys
1482 * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1483 * in any way, so there's no point in using it */
1488 PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1490 assert(is_ANYOF_SYNTHETIC(ssc));
1492 if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1496 /* See if the list consists solely of the range 0 - Infinity */
1497 invlist_iterinit(ssc->invlist);
1498 ret = invlist_iternext(ssc->invlist, &start, &end)
1502 invlist_iterfinish(ssc->invlist);
1508 /* If e.g., both \w and \W are set, matches everything */
1509 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1511 for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1512 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1522 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1524 /* Initializes the SSC 'ssc'. This includes setting it to match an empty
1525 * string, any code point, or any posix class under locale */
1527 PERL_ARGS_ASSERT_SSC_INIT;
1529 Zero(ssc, 1, regnode_ssc);
1530 set_ANYOF_SYNTHETIC(ssc);
1531 ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1534 /* If any portion of the regex is to operate under locale rules that aren't
1535 * fully known at compile time, initialization includes it. The reason
1536 * this isn't done for all regexes is that the optimizer was written under
1537 * the assumption that locale was all-or-nothing. Given the complexity and
1538 * lack of documentation in the optimizer, and that there are inadequate
1539 * test cases for locale, many parts of it may not work properly, it is
1540 * safest to avoid locale unless necessary. */
1541 if (RExC_contains_locale) {
1542 ANYOF_POSIXL_SETALL(ssc);
1545 ANYOF_POSIXL_ZERO(ssc);
1550 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1551 const regnode_ssc *ssc)
1553 /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1554 * to the list of code points matched, and locale posix classes; hence does
1555 * not check its flags) */
1560 PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1562 assert(is_ANYOF_SYNTHETIC(ssc));
1564 invlist_iterinit(ssc->invlist);
1565 ret = invlist_iternext(ssc->invlist, &start, &end)
1569 invlist_iterfinish(ssc->invlist);
1575 if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1582 #define INVLIST_INDEX 0
1583 #define ONLY_LOCALE_MATCHES_INDEX 1
1584 #define DEFERRED_USER_DEFINED_INDEX 2
1587 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1588 const regnode_charclass* const node)
1590 /* Returns a mortal inversion list defining which code points are matched
1591 * by 'node', which is of type ANYOF. Handles complementing the result if
1592 * appropriate. If some code points aren't knowable at this time, the
1593 * returned list must, and will, contain every code point that is a
1598 SV* only_utf8_locale_invlist = NULL;
1600 const U32 n = ARG(node);
1601 bool new_node_has_latin1 = FALSE;
1602 const U8 flags = (inRANGE(OP(node), ANYOFH, ANYOFRb))
1604 : ANYOF_FLAGS(node);
1606 PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1608 /* Look at the data structure created by S_set_ANYOF_arg() */
1609 if (n != ANYOF_ONLY_HAS_BITMAP) {
1610 SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1611 AV * const av = MUTABLE_AV(SvRV(rv));
1612 SV **const ary = AvARRAY(av);
1613 assert(RExC_rxi->data->what[n] == 's');
1615 if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
1617 /* Here there are things that won't be known until runtime -- we
1618 * have to assume it could be anything */
1619 invlist = sv_2mortal(_new_invlist(1));
1620 return _add_range_to_invlist(invlist, 0, UV_MAX);
1622 else if (ary[INVLIST_INDEX]) {
1624 /* Use the node's inversion list */
1625 invlist = sv_2mortal(invlist_clone(ary[INVLIST_INDEX], NULL));
1628 /* Get the code points valid only under UTF-8 locales */
1629 if ( (flags & ANYOFL_FOLD)
1630 && av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX)
1632 only_utf8_locale_invlist = ary[ONLY_LOCALE_MATCHES_INDEX];
1637 invlist = sv_2mortal(_new_invlist(0));
1640 /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1641 * code points, and an inversion list for the others, but if there are code
1642 * points that should match only conditionally on the target string being
1643 * UTF-8, those are placed in the inversion list, and not the bitmap.
1644 * Since there are circumstances under which they could match, they are
1645 * included in the SSC. But if the ANYOF node is to be inverted, we have
1646 * to exclude them here, so that when we invert below, the end result
1647 * actually does include them. (Think about "\xe0" =~ /[^\xc0]/di;). We
1648 * have to do this here before we add the unconditionally matched code
1650 if (flags & ANYOF_INVERT) {
1651 _invlist_intersection_complement_2nd(invlist,
1656 /* Add in the points from the bit map */
1657 if (! inRANGE(OP(node), ANYOFH, ANYOFRb)) {
1658 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1659 if (ANYOF_BITMAP_TEST(node, i)) {
1660 unsigned int start = i++;
1662 for (; i < NUM_ANYOF_CODE_POINTS
1663 && ANYOF_BITMAP_TEST(node, i); ++i)
1667 invlist = _add_range_to_invlist(invlist, start, i-1);
1668 new_node_has_latin1 = TRUE;
1673 /* If this can match all upper Latin1 code points, have to add them
1674 * as well. But don't add them if inverting, as when that gets done below,
1675 * it would exclude all these characters, including the ones it shouldn't
1676 * that were added just above */
1677 if (! (flags & ANYOF_INVERT) && OP(node) == ANYOFD
1678 && (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1680 _invlist_union(invlist, PL_UpperLatin1, &invlist);
1683 /* Similarly for these */
1684 if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1685 _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1688 if (flags & ANYOF_INVERT) {
1689 _invlist_invert(invlist);
1691 else if (flags & ANYOFL_FOLD) {
1692 if (new_node_has_latin1) {
1694 /* Under /li, any 0-255 could fold to any other 0-255, depending on
1695 * the locale. We can skip this if there are no 0-255 at all. */
1696 _invlist_union(invlist, PL_Latin1, &invlist);
1698 invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I);
1699 invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
1702 if (_invlist_contains_cp(invlist, LATIN_SMALL_LETTER_DOTLESS_I)) {
1703 invlist = add_cp_to_invlist(invlist, 'I');
1705 if (_invlist_contains_cp(invlist,
1706 LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE))
1708 invlist = add_cp_to_invlist(invlist, 'i');
1713 /* Similarly add the UTF-8 locale possible matches. These have to be
1714 * deferred until after the non-UTF-8 locale ones are taken care of just
1715 * above, or it leads to wrong results under ANYOF_INVERT */
1716 if (only_utf8_locale_invlist) {
1717 _invlist_union_maybe_complement_2nd(invlist,
1718 only_utf8_locale_invlist,
1719 flags & ANYOF_INVERT,
1726 /* These two functions currently do the exact same thing */
1727 #define ssc_init_zero ssc_init
1729 #define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp))
1730 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1732 /* 'AND' a given class with another one. Can create false positives. 'ssc'
1733 * should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1734 * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1737 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1738 const regnode_charclass *and_with)
1740 /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1741 * another SSC or a regular ANYOF class. Can create false positives. */
1744 U8 and_with_flags = inRANGE(OP(and_with), ANYOFH, ANYOFRb)
1746 : ANYOF_FLAGS(and_with);
1749 PERL_ARGS_ASSERT_SSC_AND;
1751 assert(is_ANYOF_SYNTHETIC(ssc));
1753 /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1754 * the code point inversion list and just the relevant flags */
1755 if (is_ANYOF_SYNTHETIC(and_with)) {
1756 anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1757 anded_flags = and_with_flags;
1759 /* XXX This is a kludge around what appears to be deficiencies in the
1760 * optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag,
1761 * there are paths through the optimizer where it doesn't get weeded
1762 * out when it should. And if we don't make some extra provision for
1763 * it like the code just below, it doesn't get added when it should.
1764 * This solution is to add it only when AND'ing, which is here, and
1765 * only when what is being AND'ed is the pristine, original node
1766 * matching anything. Thus it is like adding it to ssc_anything() but
1767 * only when the result is to be AND'ed. Probably the same solution
1768 * could be adopted for the same problem we have with /l matching,
1769 * which is solved differently in S_ssc_init(), and that would lead to
1770 * fewer false positives than that solution has. But if this solution
1771 * creates bugs, the consequences are only that a warning isn't raised
1772 * that should be; while the consequences for having /l bugs is
1773 * incorrect matches */
1774 if (ssc_is_anything((regnode_ssc *)and_with)) {
1775 anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1779 anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1780 if (OP(and_with) == ANYOFD) {
1781 anded_flags = and_with_flags & ANYOF_COMMON_FLAGS;
1784 anded_flags = and_with_flags
1785 &( ANYOF_COMMON_FLAGS
1786 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1787 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1788 if (ANYOFL_UTF8_LOCALE_REQD(and_with_flags)) {
1790 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1795 ANYOF_FLAGS(ssc) &= anded_flags;
1797 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1798 * C2 is the list of code points in 'and-with'; P2, its posix classes.
1799 * 'and_with' may be inverted. When not inverted, we have the situation of
1801 * (C1 | P1) & (C2 | P2)
1802 * = (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1803 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1804 * <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2))
1805 * <= ((C1 & C2) | P1 | P2)
1806 * Alternatively, the last few steps could be:
1807 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1808 * <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2))
1809 * <= (C1 | C2 | (P1 & P2))
1810 * We favor the second approach if either P1 or P2 is non-empty. This is
1811 * because these components are a barrier to doing optimizations, as what
1812 * they match cannot be known until the moment of matching as they are
1813 * dependent on the current locale, 'AND"ing them likely will reduce or
1815 * But we can do better if we know that C1,P1 are in their initial state (a
1816 * frequent occurrence), each matching everything:
1817 * (<everything>) & (C2 | P2) = C2 | P2
1818 * Similarly, if C2,P2 are in their initial state (again a frequent
1819 * occurrence), the result is a no-op
1820 * (C1 | P1) & (<everything>) = C1 | P1
1823 * (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2)
1824 * = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1825 * <= (C1 & ~C2) | (P1 & ~P2)
1828 if ((and_with_flags & ANYOF_INVERT)
1829 && ! is_ANYOF_SYNTHETIC(and_with))
1833 ssc_intersection(ssc,
1835 FALSE /* Has already been inverted */
1838 /* If either P1 or P2 is empty, the intersection will be also; can skip
1840 if (! (and_with_flags & ANYOF_MATCHES_POSIXL)) {
1841 ANYOF_POSIXL_ZERO(ssc);
1843 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1845 /* Note that the Posix class component P from 'and_with' actually
1847 * P = Pa | Pb | ... | Pn
1848 * where each component is one posix class, such as in [\w\s].
1850 * ~P = ~(Pa | Pb | ... | Pn)
1851 * = ~Pa & ~Pb & ... & ~Pn
1852 * <= ~Pa | ~Pb | ... | ~Pn
1853 * The last is something we can easily calculate, but unfortunately
1854 * is likely to have many false positives. We could do better
1855 * in some (but certainly not all) instances if two classes in
1856 * P have known relationships. For example
1857 * :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1859 * :lower: & :print: = :lower:
1860 * And similarly for classes that must be disjoint. For example,
1861 * since \s and \w can have no elements in common based on rules in
1862 * the POSIX standard,
1863 * \w & ^\S = nothing
1864 * Unfortunately, some vendor locales do not meet the Posix
1865 * standard, in particular almost everything by Microsoft.
1866 * The loop below just changes e.g., \w into \W and vice versa */
1868 regnode_charclass_posixl temp;
1869 int add = 1; /* To calculate the index of the complement */
1871 Zero(&temp, 1, regnode_charclass_posixl);
1872 ANYOF_POSIXL_ZERO(&temp);
1873 for (i = 0; i < ANYOF_MAX; i++) {
1875 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1876 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1878 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1879 ANYOF_POSIXL_SET(&temp, i + add);
1881 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1883 ANYOF_POSIXL_AND(&temp, ssc);
1885 } /* else ssc already has no posixes */
1886 } /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC
1887 in its initial state */
1888 else if (! is_ANYOF_SYNTHETIC(and_with)
1889 || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1891 /* But if 'ssc' is in its initial state, the result is just 'and_with';
1892 * copy it over 'ssc' */
1893 if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1894 if (is_ANYOF_SYNTHETIC(and_with)) {
1895 StructCopy(and_with, ssc, regnode_ssc);
1898 ssc->invlist = anded_cp_list;
1899 ANYOF_POSIXL_ZERO(ssc);
1900 if (and_with_flags & ANYOF_MATCHES_POSIXL) {
1901 ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1905 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1906 || (and_with_flags & ANYOF_MATCHES_POSIXL))
1908 /* One or the other of P1, P2 is non-empty. */
1909 if (and_with_flags & ANYOF_MATCHES_POSIXL) {
1910 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1912 ssc_union(ssc, anded_cp_list, FALSE);
1914 else { /* P1 = P2 = empty */
1915 ssc_intersection(ssc, anded_cp_list, FALSE);
1921 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1922 const regnode_charclass *or_with)
1924 /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1925 * another SSC or a regular ANYOF class. Can create false positives if
1926 * 'or_with' is to be inverted. */
1930 U8 or_with_flags = inRANGE(OP(or_with), ANYOFH, ANYOFRb)
1932 : ANYOF_FLAGS(or_with);
1934 PERL_ARGS_ASSERT_SSC_OR;
1936 assert(is_ANYOF_SYNTHETIC(ssc));
1938 /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1939 * the code point inversion list and just the relevant flags */
1940 if (is_ANYOF_SYNTHETIC(or_with)) {
1941 ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1942 ored_flags = or_with_flags;
1945 ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
1946 ored_flags = or_with_flags & ANYOF_COMMON_FLAGS;
1947 if (OP(or_with) != ANYOFD) {
1950 & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1951 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1952 if (ANYOFL_UTF8_LOCALE_REQD(or_with_flags)) {
1954 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1959 ANYOF_FLAGS(ssc) |= ored_flags;
1961 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1962 * C2 is the list of code points in 'or-with'; P2, its posix classes.
1963 * 'or_with' may be inverted. When not inverted, we have the simple
1964 * situation of computing:
1965 * (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2)
1966 * If P1|P2 yields a situation with both a class and its complement are
1967 * set, like having both \w and \W, this matches all code points, and we
1968 * can delete these from the P component of the ssc going forward. XXX We
1969 * might be able to delete all the P components, but I (khw) am not certain
1970 * about this, and it is better to be safe.
1973 * (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2)
1974 * <= (C1 | P1) | ~C2
1975 * <= (C1 | ~C2) | P1
1976 * (which results in actually simpler code than the non-inverted case)
1979 if ((or_with_flags & ANYOF_INVERT)
1980 && ! is_ANYOF_SYNTHETIC(or_with))
1982 /* We ignore P2, leaving P1 going forward */
1983 } /* else Not inverted */
1984 else if (or_with_flags & ANYOF_MATCHES_POSIXL) {
1985 ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
1986 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1988 for (i = 0; i < ANYOF_MAX; i += 2) {
1989 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1991 ssc_match_all_cp(ssc);
1992 ANYOF_POSIXL_CLEAR(ssc, i);
1993 ANYOF_POSIXL_CLEAR(ssc, i+1);
2001 FALSE /* Already has been inverted */
2005 PERL_STATIC_INLINE void
2006 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
2008 PERL_ARGS_ASSERT_SSC_UNION;
2010 assert(is_ANYOF_SYNTHETIC(ssc));
2012 _invlist_union_maybe_complement_2nd(ssc->invlist,
2018 PERL_STATIC_INLINE void
2019 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
2021 const bool invert2nd)
2023 PERL_ARGS_ASSERT_SSC_INTERSECTION;
2025 assert(is_ANYOF_SYNTHETIC(ssc));
2027 _invlist_intersection_maybe_complement_2nd(ssc->invlist,
2033 PERL_STATIC_INLINE void
2034 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
2036 PERL_ARGS_ASSERT_SSC_ADD_RANGE;
2038 assert(is_ANYOF_SYNTHETIC(ssc));
2040 ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
2043 PERL_STATIC_INLINE void
2044 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
2046 /* AND just the single code point 'cp' into the SSC 'ssc' */
2048 SV* cp_list = _new_invlist(2);
2050 PERL_ARGS_ASSERT_SSC_CP_AND;
2052 assert(is_ANYOF_SYNTHETIC(ssc));
2054 cp_list = add_cp_to_invlist(cp_list, cp);
2055 ssc_intersection(ssc, cp_list,
2056 FALSE /* Not inverted */
2058 SvREFCNT_dec_NN(cp_list);
2061 PERL_STATIC_INLINE void
2062 S_ssc_clear_locale(regnode_ssc *ssc)
2064 /* Set the SSC 'ssc' to not match any locale things */
2065 PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
2067 assert(is_ANYOF_SYNTHETIC(ssc));
2069 ANYOF_POSIXL_ZERO(ssc);
2070 ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
2073 #define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
2076 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
2078 /* The synthetic start class is used to hopefully quickly winnow down
2079 * places where a pattern could start a match in the target string. If it
2080 * doesn't really narrow things down that much, there isn't much point to
2081 * having the overhead of using it. This function uses some very crude
2082 * heuristics to decide if to use the ssc or not.
2084 * It returns TRUE if 'ssc' rules out more than half what it considers to
2085 * be the "likely" possible matches, but of course it doesn't know what the
2086 * actual things being matched are going to be; these are only guesses
2088 * For /l matches, it assumes that the only likely matches are going to be
2089 * in the 0-255 range, uniformly distributed, so half of that is 127
2090 * For /a and /d matches, it assumes that the likely matches will be just
2091 * the ASCII range, so half of that is 63
2092 * For /u and there isn't anything matching above the Latin1 range, it
2093 * assumes that that is the only range likely to be matched, and uses
2094 * half that as the cut-off: 127. If anything matches above Latin1,
2095 * it assumes that all of Unicode could match (uniformly), except for
2096 * non-Unicode code points and things in the General Category "Other"
2097 * (unassigned, private use, surrogates, controls and formats). This
2098 * is a much large number. */
2100 U32 count = 0; /* Running total of number of code points matched by
2102 UV start, end; /* Start and end points of current range in inversion
2103 XXX outdated. UTF-8 locales are common, what about invert? list */
2104 const U32 max_code_points = (LOC)
2106 : (( ! UNI_SEMANTICS
2107 || invlist_highest(ssc->invlist) < 256)
2110 const U32 max_match = max_code_points / 2;
2112 PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
2114 invlist_iterinit(ssc->invlist);
2115 while (invlist_iternext(ssc->invlist, &start, &end)) {
2116 if (start >= max_code_points) {
2119 end = MIN(end, max_code_points - 1);
2120 count += end - start + 1;
2121 if (count >= max_match) {
2122 invlist_iterfinish(ssc->invlist);
2132 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
2134 /* The inversion list in the SSC is marked mortal; now we need a more
2135 * permanent copy, which is stored the same way that is done in a regular
2136 * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
2139 SV* invlist = invlist_clone(ssc->invlist, NULL);
2141 PERL_ARGS_ASSERT_SSC_FINALIZE;
2143 assert(is_ANYOF_SYNTHETIC(ssc));
2145 /* The code in this file assumes that all but these flags aren't relevant
2146 * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
2147 * by the time we reach here */
2148 assert(! (ANYOF_FLAGS(ssc)
2149 & ~( ANYOF_COMMON_FLAGS
2150 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2151 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
2153 populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
2155 set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist, NULL, NULL);
2156 SvREFCNT_dec(invlist);
2158 /* Make sure is clone-safe */
2159 ssc->invlist = NULL;
2161 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2162 ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
2163 OP(ssc) = ANYOFPOSIXL;
2165 else if (RExC_contains_locale) {
2169 assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
2172 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
2173 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
2174 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
2175 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \
2176 ? (TRIE_LIST_CUR( idx ) - 1) \
2182 dump_trie(trie,widecharmap,revcharmap)
2183 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
2184 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
2186 These routines dump out a trie in a somewhat readable format.
2187 The _interim_ variants are used for debugging the interim
2188 tables that are used to generate the final compressed
2189 representation which is what dump_trie expects.
2191 Part of the reason for their existence is to provide a form
2192 of documentation as to how the different representations function.
2197 Dumps the final compressed table form of the trie to Perl_debug_log.
2198 Used for debugging make_trie().
2202 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
2203 AV *revcharmap, U32 depth)
2206 SV *sv=sv_newmortal();
2207 int colwidth= widecharmap ? 6 : 4;
2209 GET_RE_DEBUG_FLAGS_DECL;
2211 PERL_ARGS_ASSERT_DUMP_TRIE;
2213 Perl_re_indentf( aTHX_ "Char : %-6s%-6s%-4s ",
2214 depth+1, "Match","Base","Ofs" );
2216 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2217 SV ** const tmp = av_fetch( revcharmap, state, 0);
2219 Perl_re_printf( aTHX_ "%*s",
2221 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2222 PL_colors[0], PL_colors[1],
2223 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2224 PERL_PV_ESCAPE_FIRSTCHAR
2229 Perl_re_printf( aTHX_ "\n");
2230 Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
2232 for( state = 0 ; state < trie->uniquecharcount ; state++ )
2233 Perl_re_printf( aTHX_ "%.*s", colwidth, "--------");
2234 Perl_re_printf( aTHX_ "\n");
2236 for( state = 1 ; state < trie->statecount ; state++ ) {
2237 const U32 base = trie->states[ state ].trans.base;
2239 Perl_re_indentf( aTHX_ "#%4" UVXf "|", depth+1, (UV)state);
2241 if ( trie->states[ state ].wordnum ) {
2242 Perl_re_printf( aTHX_ " W%4X", trie->states[ state ].wordnum );
2244 Perl_re_printf( aTHX_ "%6s", "" );
2247 Perl_re_printf( aTHX_ " @%4" UVXf " ", (UV)base );
2252 while( ( base + ofs < trie->uniquecharcount ) ||
2253 ( base + ofs - trie->uniquecharcount < trie->lasttrans
2254 && trie->trans[ base + ofs - trie->uniquecharcount ].check
2258 Perl_re_printf( aTHX_ "+%2" UVXf "[ ", (UV)ofs);
2260 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2261 if ( ( base + ofs >= trie->uniquecharcount )
2262 && ( base + ofs - trie->uniquecharcount
2264 && trie->trans[ base + ofs
2265 - trie->uniquecharcount ].check == state )
2267 Perl_re_printf( aTHX_ "%*" UVXf, colwidth,
2268 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
2271 Perl_re_printf( aTHX_ "%*s", colwidth," ." );
2275 Perl_re_printf( aTHX_ "]");
2278 Perl_re_printf( aTHX_ "\n" );
2280 Perl_re_indentf( aTHX_ "word_info N:(prev,len)=",
2282 for (word=1; word <= trie->wordcount; word++) {
2283 Perl_re_printf( aTHX_ " %d:(%d,%d)",
2284 (int)word, (int)(trie->wordinfo[word].prev),
2285 (int)(trie->wordinfo[word].len));
2287 Perl_re_printf( aTHX_ "\n" );
2290 Dumps a fully constructed but uncompressed trie in list form.
2291 List tries normally only are used for construction when the number of
2292 possible chars (trie->uniquecharcount) is very high.
2293 Used for debugging make_trie().
2296 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2297 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2301 SV *sv=sv_newmortal();
2302 int colwidth= widecharmap ? 6 : 4;
2303 GET_RE_DEBUG_FLAGS_DECL;
2305 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2307 /* print out the table precompression. */
2308 Perl_re_indentf( aTHX_ "State :Word | Transition Data\n",
2310 Perl_re_indentf( aTHX_ "%s",
2311 depth+1, "------:-----+-----------------\n" );
2313 for( state=1 ; state < next_alloc ; state ++ ) {
2316 Perl_re_indentf( aTHX_ " %4" UVXf " :",
2317 depth+1, (UV)state );
2318 if ( ! trie->states[ state ].wordnum ) {
2319 Perl_re_printf( aTHX_ "%5s| ","");
2321 Perl_re_printf( aTHX_ "W%4x| ",
2322 trie->states[ state ].wordnum
2325 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2326 SV ** const tmp = av_fetch( revcharmap,
2327 TRIE_LIST_ITEM(state, charid).forid, 0);
2329 Perl_re_printf( aTHX_ "%*s:%3X=%4" UVXf " | ",
2331 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2333 PL_colors[0], PL_colors[1],
2334 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2335 | PERL_PV_ESCAPE_FIRSTCHAR
2337 TRIE_LIST_ITEM(state, charid).forid,
2338 (UV)TRIE_LIST_ITEM(state, charid).newstate
2341 Perl_re_printf( aTHX_ "\n%*s| ",
2342 (int)((depth * 2) + 14), "");
2345 Perl_re_printf( aTHX_ "\n");
2350 Dumps a fully constructed but uncompressed trie in table form.
2351 This is the normal DFA style state transition table, with a few
2352 twists to facilitate compression later.
2353 Used for debugging make_trie().
2356 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2357 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2362 SV *sv=sv_newmortal();
2363 int colwidth= widecharmap ? 6 : 4;
2364 GET_RE_DEBUG_FLAGS_DECL;
2366 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2369 print out the table precompression so that we can do a visual check
2370 that they are identical.
2373 Perl_re_indentf( aTHX_ "Char : ", depth+1 );
2375 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2376 SV ** const tmp = av_fetch( revcharmap, charid, 0);
2378 Perl_re_printf( aTHX_ "%*s",
2380 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2381 PL_colors[0], PL_colors[1],
2382 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2383 PERL_PV_ESCAPE_FIRSTCHAR
2389 Perl_re_printf( aTHX_ "\n");
2390 Perl_re_indentf( aTHX_ "State+-", depth+1 );
2392 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2393 Perl_re_printf( aTHX_ "%.*s", colwidth,"--------");
2396 Perl_re_printf( aTHX_ "\n" );
2398 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2400 Perl_re_indentf( aTHX_ "%4" UVXf " : ",
2402 (UV)TRIE_NODENUM( state ) );
2404 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2405 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2407 Perl_re_printf( aTHX_ "%*" UVXf, colwidth, v );
2409 Perl_re_printf( aTHX_ "%*s", colwidth, "." );
2411 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2412 Perl_re_printf( aTHX_ " (%4" UVXf ")\n",
2413 (UV)trie->trans[ state ].check );
2415 Perl_re_printf( aTHX_ " (%4" UVXf ") W%4X\n",
2416 (UV)trie->trans[ state ].check,
2417 trie->states[ TRIE_NODENUM( state ) ].wordnum );
2425 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2426 startbranch: the first branch in the whole branch sequence
2427 first : start branch of sequence of branch-exact nodes.
2428 May be the same as startbranch
2429 last : Thing following the last branch.
2430 May be the same as tail.
2431 tail : item following the branch sequence
2432 count : words in the sequence
2433 flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2434 depth : indent depth
2436 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2438 A trie is an N'ary tree where the branches are determined by digital
2439 decomposition of the key. IE, at the root node you look up the 1st character and
2440 follow that branch repeat until you find the end of the branches. Nodes can be
2441 marked as "accepting" meaning they represent a complete word. Eg:
2445 would convert into the following structure. Numbers represent states, letters
2446 following numbers represent valid transitions on the letter from that state, if
2447 the number is in square brackets it represents an accepting state, otherwise it
2448 will be in parenthesis.
2450 +-h->+-e->[3]-+-r->(8)-+-s->[9]
2454 (1) +-i->(6)-+-s->[7]
2456 +-s->(3)-+-h->(4)-+-e->[5]
2458 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2460 This shows that when matching against the string 'hers' we will begin at state 1
2461 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2462 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2463 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2464 single traverse. We store a mapping from accepting to state to which word was
2465 matched, and then when we have multiple possibilities we try to complete the
2466 rest of the regex in the order in which they occurred in the alternation.
2468 The only prior NFA like behaviour that would be changed by the TRIE support is
2469 the silent ignoring of duplicate alternations which are of the form:
2471 / (DUPE|DUPE) X? (?{ ... }) Y /x
2473 Thus EVAL blocks following a trie may be called a different number of times with
2474 and without the optimisation. With the optimisations dupes will be silently
2475 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2476 the following demonstrates:
2478 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2480 which prints out 'word' three times, but
2482 'words'=~/(word|word|word)(?{ print $1 })S/
2484 which doesnt print it out at all. This is due to other optimisations kicking in.
2486 Example of what happens on a structural level:
2488 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2490 1: CURLYM[1] {1,32767}(18)
2501 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2502 and should turn into:
2504 1: CURLYM[1] {1,32767}(18)
2506 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2514 Cases where tail != last would be like /(?foo|bar)baz/:
2524 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2525 and would end up looking like:
2528 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2535 d = uvchr_to_utf8_flags(d, uv, 0);
2537 is the recommended Unicode-aware way of saying
2542 #define TRIE_STORE_REVCHAR(val) \
2545 SV *zlopp = newSV(UTF8_MAXBYTES); \
2546 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
2547 unsigned char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
2549 SvCUR_set(zlopp, kapow - flrbbbbb); \
2552 av_push(revcharmap, zlopp); \
2554 char ooooff = (char)val; \
2555 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
2559 /* This gets the next character from the input, folding it if not already
2561 #define TRIE_READ_CHAR STMT_START { \
2564 /* if it is UTF then it is either already folded, or does not need \
2566 uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \
2568 else if (folder == PL_fold_latin1) { \
2569 /* This folder implies Unicode rules, which in the range expressible \
2570 * by not UTF is the lower case, with the two exceptions, one of \
2571 * which should have been taken care of before calling this */ \
2572 assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \
2573 uvc = toLOWER_L1(*uc); \
2574 if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \
2577 /* raw data, will be folded later if needed */ \
2585 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
2586 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
2587 U32 ging = TRIE_LIST_LEN( state ) * 2; \
2588 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2589 TRIE_LIST_LEN( state ) = ging; \
2591 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
2592 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
2593 TRIE_LIST_CUR( state )++; \
2596 #define TRIE_LIST_NEW(state) STMT_START { \
2597 Newx( trie->states[ state ].trans.list, \
2598 4, reg_trie_trans_le ); \
2599 TRIE_LIST_CUR( state ) = 1; \
2600 TRIE_LIST_LEN( state ) = 4; \
2603 #define TRIE_HANDLE_WORD(state) STMT_START { \
2604 U16 dupe= trie->states[ state ].wordnum; \
2605 regnode * const noper_next = regnext( noper ); \
2608 /* store the word for dumping */ \
2610 if (OP(noper) != NOTHING) \
2611 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
2613 tmp = newSVpvn_utf8( "", 0, UTF ); \
2614 av_push( trie_words, tmp ); \
2618 trie->wordinfo[curword].prev = 0; \
2619 trie->wordinfo[curword].len = wordlen; \
2620 trie->wordinfo[curword].accept = state; \
2622 if ( noper_next < tail ) { \
2624 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2626 trie->jump[curword] = (U16)(noper_next - convert); \
2628 jumper = noper_next; \
2630 nextbranch= regnext(cur); \
2634 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
2635 /* chain, so that when the bits of chain are later */\
2636 /* linked together, the dups appear in the chain */\
2637 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2638 trie->wordinfo[dupe].prev = curword; \
2640 /* we haven't inserted this word yet. */ \
2641 trie->states[ state ].wordnum = curword; \
2646 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
2647 ( ( base + charid >= ucharcount \
2648 && base + charid < ubound \
2649 && state == trie->trans[ base - ucharcount + charid ].check \
2650 && trie->trans[ base - ucharcount + charid ].next ) \
2651 ? trie->trans[ base - ucharcount + charid ].next \
2652 : ( state==1 ? special : 0 ) \
2655 #define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder) \
2657 TRIE_BITMAP_SET(trie, uvc); \
2658 /* store the folded codepoint */ \
2660 TRIE_BITMAP_SET(trie, folder[(U8) uvc ]); \
2663 /* store first byte of utf8 representation of */ \
2664 /* variant codepoints */ \
2665 if (! UVCHR_IS_INVARIANT(uvc)) { \
2666 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc)); \
2671 #define MADE_JUMP_TRIE 2
2672 #define MADE_EXACT_TRIE 4
2675 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2676 regnode *first, regnode *last, regnode *tail,
2677 U32 word_count, U32 flags, U32 depth)
2679 /* first pass, loop through and scan words */
2680 reg_trie_data *trie;
2681 HV *widecharmap = NULL;
2682 AV *revcharmap = newAV();
2688 regnode *jumper = NULL;
2689 regnode *nextbranch = NULL;
2690 regnode *convert = NULL;
2691 U32 *prev_states; /* temp array mapping each state to previous one */
2692 /* we just use folder as a flag in utf8 */
2693 const U8 * folder = NULL;
2695 /* in the below add_data call we are storing either 'tu' or 'tuaa'
2696 * which stands for one trie structure, one hash, optionally followed
2699 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
2700 AV *trie_words = NULL;
2701 /* along with revcharmap, this only used during construction but both are
2702 * useful during debugging so we store them in the struct when debugging.
2705 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2706 STRLEN trie_charcount=0;
2708 SV *re_trie_maxbuff;
2709 GET_RE_DEBUG_FLAGS_DECL;
2711 PERL_ARGS_ASSERT_MAKE_TRIE;
2713 PERL_UNUSED_ARG(depth);
2717 case EXACT: case EXACT_REQ8: case EXACTL: break;
2721 case EXACTFLU8: folder = PL_fold_latin1; break;
2722 case EXACTF: folder = PL_fold; break;
2723 default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2726 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2728 trie->startstate = 1;
2729 trie->wordcount = word_count;
2730 RExC_rxi->data->data[ data_slot ] = (void*)trie;
2731 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2732 if (flags == EXACT || flags == EXACT_REQ8 || flags == EXACTL)
2733 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2734 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2735 trie->wordcount+1, sizeof(reg_trie_wordinfo));
2738 trie_words = newAV();
2741 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, GV_ADD);
2742 assert(re_trie_maxbuff);
2743 if (!SvIOK(re_trie_maxbuff)) {
2744 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2746 DEBUG_TRIE_COMPILE_r({
2747 Perl_re_indentf( aTHX_
2748 "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2750 REG_NODE_NUM(startbranch), REG_NODE_NUM(first),
2751 REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2754 /* Find the node we are going to overwrite */
2755 if ( first == startbranch && OP( last ) != BRANCH ) {
2756 /* whole branch chain */
2759 /* branch sub-chain */
2760 convert = NEXTOPER( first );
2763 /* -- First loop and Setup --
2765 We first traverse the branches and scan each word to determine if it
2766 contains widechars, and how many unique chars there are, this is
2767 important as we have to build a table with at least as many columns as we
2770 We use an array of integers to represent the character codes 0..255
2771 (trie->charmap) and we use a an HV* to store Unicode characters. We use
2772 the native representation of the character value as the key and IV's for
2775 *TODO* If we keep track of how many times each character is used we can
2776 remap the columns so that the table compression later on is more
2777 efficient in terms of memory by ensuring the most common value is in the
2778 middle and the least common are on the outside. IMO this would be better
2779 than a most to least common mapping as theres a decent chance the most
2780 common letter will share a node with the least common, meaning the node
2781 will not be compressible. With a middle is most common approach the worst
2782 case is when we have the least common nodes twice.
2786 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2787 regnode *noper = NEXTOPER( cur );
2791 U32 wordlen = 0; /* required init */
2792 STRLEN minchars = 0;
2793 STRLEN maxchars = 0;
2794 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2797 if (OP(noper) == NOTHING) {
2798 /* skip past a NOTHING at the start of an alternation
2799 * eg, /(?:)a|(?:b)/ should be the same as /a|b/
2801 regnode *noper_next= regnext(noper);
2802 if (noper_next < tail)
2807 && ( OP(noper) == flags
2808 || (flags == EXACT && OP(noper) == EXACT_REQ8)
2809 || (flags == EXACTFU && ( OP(noper) == EXACTFU_REQ8
2810 || OP(noper) == EXACTFUP))))
2812 uc= (U8*)STRING(noper);
2813 e= uc + STR_LEN(noper);
2820 if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2821 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2822 regardless of encoding */
2823 if (OP( noper ) == EXACTFUP) {
2824 /* false positives are ok, so just set this */
2825 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2829 for ( ; uc < e ; uc += len ) { /* Look at each char in the current
2831 TRIE_CHARCOUNT(trie)++;
2834 /* TRIE_READ_CHAR returns the current character, or its fold if /i
2835 * is in effect. Under /i, this character can match itself, or
2836 * anything that folds to it. If not under /i, it can match just
2837 * itself. Most folds are 1-1, for example k, K, and KELVIN SIGN
2838 * all fold to k, and all are single characters. But some folds
2839 * expand to more than one character, so for example LATIN SMALL
2840 * LIGATURE FFI folds to the three character sequence 'ffi'. If
2841 * the string beginning at 'uc' is 'ffi', it could be matched by
2842 * three characters, or just by the one ligature character. (It
2843 * could also be matched by two characters: LATIN SMALL LIGATURE FF
2844 * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2845 * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2846 * match.) The trie needs to know the minimum and maximum number
2847 * of characters that could match so that it can use size alone to
2848 * quickly reject many match attempts. The max is simple: it is
2849 * the number of folded characters in this branch (since a fold is
2850 * never shorter than what folds to it. */
2854 /* And the min is equal to the max if not under /i (indicated by
2855 * 'folder' being NULL), or there are no multi-character folds. If
2856 * there is a multi-character fold, the min is incremented just
2857 * once, for the character that folds to the sequence. Each
2858 * character in the sequence needs to be added to the list below of
2859 * characters in the trie, but we count only the first towards the
2860 * min number of characters needed. This is done through the
2861 * variable 'foldlen', which is returned by the macros that look
2862 * for these sequences as the number of bytes the sequence
2863 * occupies. Each time through the loop, we decrement 'foldlen' by
2864 * how many bytes the current char occupies. Only when it reaches
2865 * 0 do we increment 'minchars' or look for another multi-character
2867 if (folder == NULL) {
2870 else if (foldlen > 0) {
2871 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2876 /* See if *uc is the beginning of a multi-character fold. If
2877 * so, we decrement the length remaining to look at, to account
2878 * for the current character this iteration. (We can use 'uc'
2879 * instead of the fold returned by TRIE_READ_CHAR because for
2880 * non-UTF, the latin1_safe macro is smart enough to account
2881 * for all the unfolded characters, and because for UTF, the
2882 * string will already have been folded earlier in the
2883 * compilation process */
2885 if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2886 foldlen -= UTF8SKIP(uc);
2889 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2894 /* The current character (and any potential folds) should be added
2895 * to the possible matching characters for this position in this
2899 U8 folded= folder[ (U8) uvc ];
2900 if ( !trie->charmap[ folded ] ) {
2901 trie->charmap[ folded ]=( ++trie->uniquecharcount );
2902 TRIE_STORE_REVCHAR( folded );
2905 if ( !trie->charmap[ uvc ] ) {
2906 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2907 TRIE_STORE_REVCHAR( uvc );
2910 /* store the codepoint in the bitmap, and its folded
2912 TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
2913 set_bit = 0; /* We've done our bit :-) */
2917 /* XXX We could come up with the list of code points that fold
2918 * to this using PL_utf8_foldclosures, except not for
2919 * multi-char folds, as there may be multiple combinations
2920 * there that could work, which needs to wait until runtime to
2921 * resolve (The comment about LIGATURE FFI above is such an
2926 widecharmap = newHV();
2928 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2931 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
2933 if ( !SvTRUE( *svpp ) ) {
2934 sv_setiv( *svpp, ++trie->uniquecharcount );
2935 TRIE_STORE_REVCHAR(uvc);
2938 } /* end loop through characters in this branch of the trie */
2940 /* We take the min and max for this branch and combine to find the min
2941 * and max for all branches processed so far */
2942 if( cur == first ) {
2943 trie->minlen = minchars;
2944 trie->maxlen = maxchars;
2945 } else if (minchars < trie->minlen) {
2946 trie->minlen = minchars;
2947 } else if (maxchars > trie->maxlen) {
2948 trie->maxlen = maxchars;
2950 } /* end first pass */
2951 DEBUG_TRIE_COMPILE_r(
2952 Perl_re_indentf( aTHX_
2953 "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2955 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
2956 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2957 (int)trie->minlen, (int)trie->maxlen )
2961 We now know what we are dealing with in terms of unique chars and
2962 string sizes so we can calculate how much memory a naive
2963 representation using a flat table will take. If it's over a reasonable
2964 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
2965 conservative but potentially much slower representation using an array
2968 At the end we convert both representations into the same compressed
2969 form that will be used in regexec.c for matching with. The latter
2970 is a form that cannot be used to construct with but has memory
2971 properties similar to the list form and access properties similar
2972 to the table form making it both suitable for fast searches and
2973 small enough that its feasable to store for the duration of a program.
2975 See the comment in the code where the compressed table is produced
2976 inplace from the flat tabe representation for an explanation of how
2977 the compression works.
2982 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2985 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2986 > SvIV(re_trie_maxbuff) )
2989 Second Pass -- Array Of Lists Representation
2991 Each state will be represented by a list of charid:state records
2992 (reg_trie_trans_le) the first such element holds the CUR and LEN
2993 points of the allocated array. (See defines above).
2995 We build the initial structure using the lists, and then convert
2996 it into the compressed table form which allows faster lookups
2997 (but cant be modified once converted).
3000 STRLEN transcount = 1;
3002 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using list compiler\n",
3005 trie->states = (reg_trie_state *)
3006 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3007 sizeof(reg_trie_state) );
3011 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3013 regnode *noper = NEXTOPER( cur );
3014 U32 state = 1; /* required init */
3015 U16 charid = 0; /* sanity init */
3016 U32 wordlen = 0; /* required init */
3018 if (OP(noper) == NOTHING) {
3019 regnode *noper_next= regnext(noper);
3020 if (noper_next < tail)
3025 && ( OP(noper) == flags
3026 || (flags == EXACT && OP(noper) == EXACT_REQ8)
3027 || (flags == EXACTFU && ( OP(noper) == EXACTFU_REQ8
3028 || OP(noper) == EXACTFUP))))
3030 const U8 *uc= (U8*)STRING(noper);
3031 const U8 *e= uc + STR_LEN(noper);
3033 for ( ; uc < e ; uc += len ) {
3038 charid = trie->charmap[ uvc ];
3040 SV** const svpp = hv_fetch( widecharmap,
3047 charid=(U16)SvIV( *svpp );
3050 /* charid is now 0 if we dont know the char read, or
3051 * nonzero if we do */
3058 if ( !trie->states[ state ].trans.list ) {
3059 TRIE_LIST_NEW( state );
3062 check <= TRIE_LIST_USED( state );
3065 if ( TRIE_LIST_ITEM( state, check ).forid
3068 newstate = TRIE_LIST_ITEM( state, check ).newstate;
3073 newstate = next_alloc++;
3074 prev_states[newstate] = state;
3075 TRIE_LIST_PUSH( state, charid, newstate );
3080 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3084 TRIE_HANDLE_WORD(state);
3086 } /* end second pass */
3088 /* next alloc is the NEXT state to be allocated */
3089 trie->statecount = next_alloc;
3090 trie->states = (reg_trie_state *)
3091 PerlMemShared_realloc( trie->states,
3093 * sizeof(reg_trie_state) );
3095 /* and now dump it out before we compress it */
3096 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
3097 revcharmap, next_alloc,
3101 trie->trans = (reg_trie_trans *)
3102 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
3109 for( state=1 ; state < next_alloc ; state ++ ) {
3113 DEBUG_TRIE_COMPILE_MORE_r(
3114 Perl_re_printf( aTHX_ "tp: %d zp: %d ",tp,zp)
3118 if (trie->states[state].trans.list) {
3119 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
3123 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3124 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
3125 if ( forid < minid ) {
3127 } else if ( forid > maxid ) {
3131 if ( transcount < tp + maxid - minid + 1) {
3133 trie->trans = (reg_trie_trans *)
3134 PerlMemShared_realloc( trie->trans,
3136 * sizeof(reg_trie_trans) );
3137 Zero( trie->trans + (transcount / 2),
3141 base = trie->uniquecharcount + tp - minid;
3142 if ( maxid == minid ) {
3144 for ( ; zp < tp ; zp++ ) {
3145 if ( ! trie->trans[ zp ].next ) {
3146 base = trie->uniquecharcount + zp - minid;
3147 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
3149 trie->trans[ zp ].check = state;
3155 trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
3157 trie->trans[ tp ].check = state;
3162 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3163 const U32 tid = base
3164 - trie->uniquecharcount
3165 + TRIE_LIST_ITEM( state, idx ).forid;
3166 trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
3168 trie->trans[ tid ].check = state;
3170 tp += ( maxid - minid + 1 );
3172 Safefree(trie->states[ state ].trans.list);
3175 DEBUG_TRIE_COMPILE_MORE_r(
3176 Perl_re_printf( aTHX_ " base: %d\n",base);
3179 trie->states[ state ].trans.base=base;
3181 trie->lasttrans = tp + 1;
3185 Second Pass -- Flat Table Representation.
3187 we dont use the 0 slot of either trans[] or states[] so we add 1 to
3188 each. We know that we will need Charcount+1 trans at most to store
3189 the data (one row per char at worst case) So we preallocate both
3190 structures assuming worst case.
3192 We then construct the trie using only the .next slots of the entry
3195 We use the .check field of the first entry of the node temporarily
3196 to make compression both faster and easier by keeping track of how
3197 many non zero fields are in the node.
3199 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
3202 There are two terms at use here: state as a TRIE_NODEIDX() which is
3203 a number representing the first entry of the node, and state as a
3204 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
3205 and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
3206 if there are 2 entrys per node. eg:
3214 The table is internally in the right hand, idx form. However as we
3215 also have to deal with the states array which is indexed by nodenum
3216 we have to use TRIE_NODENUM() to convert.
3219 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using table compiler\n",
3222 trie->trans = (reg_trie_trans *)
3223 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
3224 * trie->uniquecharcount + 1,
3225 sizeof(reg_trie_trans) );
3226 trie->states = (reg_trie_state *)
3227 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3228 sizeof(reg_trie_state) );
3229 next_alloc = trie->uniquecharcount + 1;
3232 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3234 regnode *noper = NEXTOPER( cur );
3236 U32 state = 1; /* required init */
3238 U16 charid = 0; /* sanity init */
3239 U32 accept_state = 0; /* sanity init */
3241 U32 wordlen = 0; /* required init */
3243 if (OP(noper) == NOTHING) {
3244 regnode *noper_next= regnext(noper);
3245 if (noper_next < tail)
3250 && ( OP(noper) == flags
3251 || (flags == EXACT && OP(noper) == EXACT_REQ8)
3252 || (flags == EXACTFU && ( OP(noper) == EXACTFU_REQ8
3253 || OP(noper) == EXACTFUP))))
3255 const U8 *uc= (U8*)STRING(noper);
3256 const U8 *e= uc + STR_LEN(noper);
3258 for ( ; uc < e ; uc += len ) {
3263 charid = trie->charmap[ uvc ];
3265 SV* const * const svpp = hv_fetch( widecharmap,
3269 charid = svpp ? (U16)SvIV(*svpp) : 0;
3273 if ( !trie->trans[ state + charid ].next ) {
3274 trie->trans[ state + charid ].next = next_alloc;
3275 trie->trans[ state ].check++;
3276 prev_states[TRIE_NODENUM(next_alloc)]
3277 = TRIE_NODENUM(state);
3278 next_alloc += trie->uniquecharcount;
3280 state = trie->trans[ state + charid ].next;
3282 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3284 /* charid is now 0 if we dont know the char read, or
3285 * nonzero if we do */
3288 accept_state = TRIE_NODENUM( state );
3289 TRIE_HANDLE_WORD(accept_state);
3291 } /* end second pass */
3293 /* and now dump it out before we compress it */
3294 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3296 next_alloc, depth+1));
3300 * Inplace compress the table.*
3302 For sparse data sets the table constructed by the trie algorithm will
3303 be mostly 0/FAIL transitions or to put it another way mostly empty.
3304 (Note that leaf nodes will not contain any transitions.)
3306 This algorithm compresses the tables by eliminating most such
3307 transitions, at the cost of a modest bit of extra work during lookup:
3309 - Each states[] entry contains a .base field which indicates the
3310 index in the state[] array wheres its transition data is stored.
3312 - If .base is 0 there are no valid transitions from that node.
3314 - If .base is nonzero then charid is added to it to find an entry in
3317 -If trans[states[state].base+charid].check!=state then the
3318 transition is taken to be a 0/Fail transition. Thus if there are fail
3319 transitions at the front of the node then the .base offset will point
3320 somewhere inside the previous nodes data (or maybe even into a node
3321 even earlier), but the .check field determines if the transition is
3325 The following process inplace converts the table to the compressed
3326 table: We first do not compress the root node 1,and mark all its
3327 .check pointers as 1 and set its .base pointer as 1 as well. This
3328 allows us to do a DFA construction from the compressed table later,
3329 and ensures that any .base pointers we calculate later are greater
3332 - We set 'pos' to indicate the first entry of the second node.
3334 - We then iterate over the columns of the node, finding the first and
3335 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3336 and set the .check pointers accordingly, and advance pos
3337 appropriately and repreat for the next node. Note that when we copy
3338 the next pointers we have to convert them from the original
3339 NODEIDX form to NODENUM form as the former is not valid post
3342 - If a node has no transitions used we mark its base as 0 and do not
3343 advance the pos pointer.
3345 - If a node only has one transition we use a second pointer into the
3346 structure to fill in allocated fail transitions from other states.
3347 This pointer is independent of the main pointer and scans forward
3348 looking for null transitions that are allocated to a state. When it
3349 finds one it writes the single transition into the "hole". If the
3350 pointer doesnt find one the single transition is appended as normal.
3352 - Once compressed we can Renew/realloc the structures to release the
3355 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3356 specifically Fig 3.47 and the associated pseudocode.
3360 const U32 laststate = TRIE_NODENUM( next_alloc );
3363 trie->statecount = laststate;
3365 for ( state = 1 ; state < laststate ; state++ ) {
3367 const U32 stateidx = TRIE_NODEIDX( state );
3368 const U32 o_used = trie->trans[ stateidx ].check;
3369 U32 used = trie->trans[ stateidx ].check;
3370 trie->trans[ stateidx ].check = 0;
3373 used && charid < trie->uniquecharcount;
3376 if ( flag || trie->trans[ stateidx + charid ].next ) {
3377 if ( trie->trans[ stateidx + charid ].next ) {
3379 for ( ; zp < pos ; zp++ ) {
3380 if ( ! trie->trans[ zp ].next ) {
3384 trie->states[ state ].trans.base
3386 + trie->uniquecharcount
3388 trie->trans[ zp ].next
3389 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3391 trie->trans[ zp ].check = state;
3392 if ( ++zp > pos ) pos = zp;
3399 trie->states[ state ].trans.base
3400 = pos + trie->uniquecharcount - charid ;
3402 trie->trans[ pos ].next
3403 = SAFE_TRIE_NODENUM(
3404 trie->trans[ stateidx + charid ].next );
3405 trie->trans[ pos ].check = state;
3410 trie->lasttrans = pos + 1;
3411 trie->states = (reg_trie_state *)
3412 PerlMemShared_realloc( trie->states, laststate
3413 * sizeof(reg_trie_state) );
3414 DEBUG_TRIE_COMPILE_MORE_r(
3415 Perl_re_indentf( aTHX_ "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
3417 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3421 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3424 } /* end table compress */
3426 DEBUG_TRIE_COMPILE_MORE_r(
3427 Perl_re_indentf( aTHX_ "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
3429 (UV)trie->statecount,
3430 (UV)trie->lasttrans)
3432 /* resize the trans array to remove unused space */
3433 trie->trans = (reg_trie_trans *)
3434 PerlMemShared_realloc( trie->trans, trie->lasttrans
3435 * sizeof(reg_trie_trans) );
3437 { /* Modify the program and insert the new TRIE node */
3438 U8 nodetype =(U8)(flags & 0xFF);
3442 regnode *optimize = NULL;
3443 #ifdef RE_TRACK_PATTERN_OFFSETS
3446 U32 mjd_nodelen = 0;
3447 #endif /* RE_TRACK_PATTERN_OFFSETS */
3448 #endif /* DEBUGGING */
3450 This means we convert either the first branch or the first Exact,
3451 depending on whether the thing following (in 'last') is a branch
3452 or not and whther first is the startbranch (ie is it a sub part of
3453 the alternation or is it the whole thing.)
3454 Assuming its a sub part we convert the EXACT otherwise we convert
3455 the whole branch sequence, including the first.
3457 /* Find the node we are going to overwrite */
3458 if ( first != startbranch || OP( last ) == BRANCH ) {
3459 /* branch sub-chain */
3460 NEXT_OFF( first ) = (U16)(last - first);
3461 #ifdef RE_TRACK_PATTERN_OFFSETS
3463 mjd_offset= Node_Offset((convert));
3464 mjd_nodelen= Node_Length((convert));
3467 /* whole branch chain */
3469 #ifdef RE_TRACK_PATTERN_OFFSETS
3472 const regnode *nop = NEXTOPER( convert );
3473 mjd_offset= Node_Offset((nop));
3474 mjd_nodelen= Node_Length((nop));
3478 Perl_re_indentf( aTHX_ "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
3480 (UV)mjd_offset, (UV)mjd_nodelen)
3483 /* But first we check to see if there is a common prefix we can
3484 split out as an EXACT and put in front of the TRIE node. */
3485 trie->startstate= 1;
3486 if ( trie->bitmap && !widecharmap && !trie->jump ) {
3487 /* we want to find the first state that has more than
3488 * one transition, if that state is not the first state
3489 * then we have a common prefix which we can remove.
3492 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3494 I32 first_ofs = -1; /* keeps track of the ofs of the first
3495 transition, -1 means none */
3497 const U32 base = trie->states[ state ].trans.base;
3499 /* does this state terminate an alternation? */
3500 if ( trie->states[state].wordnum )
3503 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3504 if ( ( base + ofs >= trie->uniquecharcount ) &&
3505 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3506 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3508 if ( ++count > 1 ) {
3509 /* we have more than one transition */
3512 /* if this is the first state there is no common prefix
3513 * to extract, so we can exit */
3514 if ( state == 1 ) break;
3515 tmp = av_fetch( revcharmap, ofs, 0);
3516 ch = (U8*)SvPV_nolen_const( *tmp );
3518 /* if we are on count 2 then we need to initialize the
3519 * bitmap, and store the previous char if there was one
3522 /* clear the bitmap */
3523 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3525 Perl_re_indentf( aTHX_ "New Start State=%" UVuf " Class: [",
3528 if (first_ofs >= 0) {
3529 SV ** const tmp = av_fetch( revcharmap, first_ofs, 0);
3530 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3532 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3534 Perl_re_printf( aTHX_ "%s", (char*)ch)
3538 /* store the current firstchar in the bitmap */
3539 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3540 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch));
3546 /* This state has only one transition, its transition is part
3547 * of a common prefix - we need to concatenate the char it
3548 * represents to what we have so far. */
3549 SV **tmp = av_fetch( revcharmap, first_ofs, 0);
3551 char *ch = SvPV( *tmp, len );
3553 SV *sv=sv_newmortal();
3554 Perl_re_indentf( aTHX_ "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n",
3556 (UV)state, (UV)first_ofs,
3557 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3558 PL_colors[0], PL_colors[1],
3559 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3560 PERL_PV_ESCAPE_FIRSTCHAR
3565 OP( convert ) = nodetype;
3566 str=STRING(convert);
3567 setSTR_LEN(convert, 0);
3569 setSTR_LEN(convert, STR_LEN(convert) + len);
3575 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n"));
3580 trie->prefixlen = (state-1);
3582 regnode *n = convert+NODE_SZ_STR(convert);
3583 NEXT_OFF(convert) = NODE_SZ_STR(convert);
3584 trie->startstate = state;
3585 trie->minlen -= (state - 1);
3586 trie->maxlen -= (state - 1);
3588 /* At least the UNICOS C compiler choked on this
3589 * being argument to DEBUG_r(), so let's just have
3592 #ifdef PERL_EXT_RE_BUILD
3598 regnode *fix = convert;
3599 U32 word = trie->wordcount;
3600 #ifdef RE_TRACK_PATTERN_OFFSETS
3603 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3604 while( ++fix < n ) {
3605 Set_Node_Offset_Length(fix, 0, 0);
3608 SV ** const tmp = av_fetch( trie_words, word, 0 );
3610 if ( STR_LEN(convert) <= SvCUR(*tmp) )
3611 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3613 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3621 NEXT_OFF(convert) = (U16)(tail - convert);
3622 DEBUG_r(optimize= n);
3628 if ( trie->maxlen ) {
3629 NEXT_OFF( convert ) = (U16)(tail - convert);
3630 ARG_SET( convert, data_slot );
3631 /* Store the offset to the first unabsorbed branch in
3632 jump[0], which is otherwise unused by the jump logic.
3633 We use this when dumping a trie and during optimisation. */
3635 trie->jump[0] = (U16)(nextbranch - convert);
3637 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3638 * and there is a bitmap
3639 * and the first "jump target" node we found leaves enough room
3640 * then convert the TRIE node into a TRIEC node, with the bitmap
3641 * embedded inline in the opcode - this is hypothetically faster.
3643 if ( !trie->states[trie->startstate].wordnum
3645 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3647 OP( convert ) = TRIEC;
3648 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3649 PerlMemShared_free(trie->bitmap);
3652 OP( convert ) = TRIE;
3654 /* store the type in the flags */
3655 convert->flags = nodetype;
3659 + regarglen[ OP( convert ) ];
3661 /* XXX We really should free up the resource in trie now,
3662 as we won't use them - (which resources?) dmq */
3664 /* needed for dumping*/
3665 DEBUG_r(if (optimize) {
3666 regnode *opt = convert;
3668 while ( ++opt < optimize) {
3669 Set_Node_Offset_Length(opt, 0, 0);
3672 Try to clean up some of the debris left after the
3675 while( optimize < jumper ) {
3676 Track_Code( mjd_nodelen += Node_Length((optimize)); );
3677 OP( optimize ) = OPTIMIZED;
3678 Set_Node_Offset_Length(optimize, 0, 0);
3681 Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen);
3683 } /* end node insert */
3685 /* Finish populating the prev field of the wordinfo array. Walk back
3686 * from each accept state until we find another accept state, and if
3687 * so, point the first word's .prev field at the second word. If the
3688 * second already has a .prev field set, stop now. This will be the
3689 * case either if we've already processed that word's accept state,
3690 * or that state had multiple words, and the overspill words were
3691 * already linked up earlier.
3698 for (word=1; word <= trie->wordcount; word++) {
3700 if (trie->wordinfo[word].prev)
3702 state = trie->wordinfo[word].accept;
3704 state = prev_states[state];
3707 prev = trie->states[state].wordnum;
3711 trie->wordinfo[word].prev = prev;
3713 Safefree(prev_states);
3717 /* and now dump out the compressed format */
3718 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3720 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3722 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3723 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3725 SvREFCNT_dec_NN(revcharmap);
3729 : trie->startstate>1
3735 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3737 /* The Trie is constructed and compressed now so we can build a fail array if
3740 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3742 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3746 We find the fail state for each state in the trie, this state is the longest
3747 proper suffix of the current state's 'word' that is also a proper prefix of
3748 another word in our trie. State 1 represents the word '' and is thus the
3749 default fail state. This allows the DFA not to have to restart after its
3750 tried and failed a word at a given point, it simply continues as though it
3751 had been matching the other word in the first place.
3753 'abcdgu'=~/abcdefg|cdgu/
3754 When we get to 'd' we are still matching the first word, we would encounter
3755 'g' which would fail, which would bring us to the state representing 'd' in
3756 the second word where we would try 'g' and succeed, proceeding to match
3759 /* add a fail transition */
3760 const U32 trie_offset = ARG(source);
3761 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3763 const U32 ucharcount = trie->uniquecharcount;
3764 const U32 numstates = trie->statecount;
3765 const U32 ubound = trie->lasttrans + ucharcount;
3769 U32 base = trie->states[ 1 ].trans.base;
3772 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3774 GET_RE_DEBUG_FLAGS_DECL;
3776 PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3777 PERL_UNUSED_CONTEXT;
3779 PERL_UNUSED_ARG(depth);
3782 if ( OP(source) == TRIE ) {
3783 struct regnode_1 *op = (struct regnode_1 *)
3784 PerlMemShared_calloc(1, sizeof(struct regnode_1));
3785 StructCopy(source, op, struct regnode_1);
3786 stclass = (regnode *)op;
3788 struct regnode_charclass *op = (struct regnode_charclass *)
3789 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3790 StructCopy(source, op, struct regnode_charclass);
3791 stclass = (regnode *)op;
3793 OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3795 ARG_SET( stclass, data_slot );
3796 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3797 RExC_rxi->data->data[ data_slot ] = (void*)aho;
3798 aho->trie=trie_offset;
3799 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3800 Copy( trie->states, aho->states, numstates, reg_trie_state );
3801 Newx( q, numstates, U32);
3802 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3805 /* initialize fail[0..1] to be 1 so that we always have
3806 a valid final fail state */
3807 fail[ 0 ] = fail[ 1 ] = 1;
3809 for ( charid = 0; charid < ucharcount ; charid++ ) {
3810 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3812 q[ q_write ] = newstate;
3813 /* set to point at the root */
3814 fail[ q[ q_write++ ] ]=1;
3817 while ( q_read < q_write) {
3818 const U32 cur = q[ q_read++ % numstates ];
3819 base = trie->states[ cur ].trans.base;
3821 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3822 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3824 U32 fail_state = cur;
3827 fail_state = fail[ fail_state ];
3828 fail_base = aho->states[ fail_state ].trans.base;
3829 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3831 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3832 fail[ ch_state ] = fail_state;
3833 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3835 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
3837 q[ q_write++ % numstates] = ch_state;
3841 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3842 when we fail in state 1, this allows us to use the
3843 charclass scan to find a valid start char. This is based on the principle
3844 that theres a good chance the string being searched contains lots of stuff
3845 that cant be a start char.
3847 fail[ 0 ] = fail[ 1 ] = 0;
3848 DEBUG_TRIE_COMPILE_r({
3849 Perl_re_indentf( aTHX_ "Stclass Failtable (%" UVuf " states): 0",
3850 depth, (UV)numstates
3852 for( q_read=1; q_read<numstates; q_read++ ) {
3853 Perl_re_printf( aTHX_ ", %" UVuf, (UV)fail[q_read]);
3855 Perl_re_printf( aTHX_ "\n");
3858 /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3863 /* The below joins as many adjacent EXACTish nodes as possible into a single
3864 * one. The regop may be changed if the node(s) contain certain sequences that
3865 * require special handling. The joining is only done if:
3866 * 1) there is room in the current conglomerated node to entirely contain the
3868 * 2) they are compatible node types
3870 * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3871 * these get optimized out
3873 * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3874 * as possible, even if that means splitting an existing node so that its first
3875 * part is moved to the preceeding node. This would maximise the efficiency of
3876 * memEQ during matching.
3878 * If a node is to match under /i (folded), the number of characters it matches
3879 * can be different than its character length if it contains a multi-character
3880 * fold. *min_subtract is set to the total delta number of characters of the
3883 * And *unfolded_multi_char is set to indicate whether or not the node contains
3884 * an unfolded multi-char fold. This happens when it won't be known until
3885 * runtime whether the fold is valid or not; namely
3886 * 1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the
3887 * target string being matched against turns out to be UTF-8 is that fold
3889 * 2) for EXACTFL nodes whose folding rules depend on the locale in force at
3891 * (Multi-char folds whose components are all above the Latin1 range are not
3892 * run-time locale dependent, and have already been folded by the time this
3893 * function is called.)
3895 * This is as good a place as any to discuss the design of handling these
3896 * multi-character fold sequences. It's been wrong in Perl for a very long
3897 * time. There are three code points in Unicode whose multi-character folds
3898 * were long ago discovered to mess things up. The previous designs for
3899 * dealing with these involved assigning a special node for them. This
3900 * approach doesn't always work, as evidenced by this example:
3901 * "\xDFs" =~ /s\xDF/ui # Used to fail before these patches
3902 * Both sides fold to "sss", but if the pattern is parsed to create a node that
3903 * would match just the \xDF, it won't be able to handle the case where a
3904 * successful match would have to cross the node's boundary. The new approach
3905 * that hopefully generally solves the problem generates an EXACTFUP node
3906 * that is "sss" in this case.
3908 * It turns out that there are problems with all multi-character folds, and not
3909 * just these three. Now the code is general, for all such cases. The
3910 * approach taken is:
3911 * 1) This routine examines each EXACTFish node that could contain multi-
3912 * character folded sequences. Since a single character can fold into
3913 * such a sequence, the minimum match length for this node is less than
3914 * the number of characters in the node. This routine returns in
3915 * *min_subtract how many characters to subtract from the the actual
3916 * length of the string to get a real minimum match length; it is 0 if
3917 * there are no multi-char foldeds. This delta is used by the caller to
3918 * adjust the min length of the match, and the delta between min and max,
3919 * so that the optimizer doesn't reject these possibilities based on size
3922 * 2) For the sequence involving the LATIN SMALL LETTER SHARP S (U+00DF)
3923 * under /u, we fold it to 'ss' in regatom(), and in this routine, after
3924 * joining, we scan for occurrences of the sequence 'ss' in non-UTF-8
3925 * EXACTFU nodes. The node type of such nodes is then changed to
3926 * EXACTFUP, indicating it is problematic, and needs careful handling.
3927 * (The procedures in step 1) above are sufficient to handle this case in
3928 * UTF-8 encoded nodes.) The reason this is problematic is that this is
3929 * the only case where there is a possible fold length change in non-UTF-8
3930 * patterns. By reserving a special node type for problematic cases, the
3931 * far more common regular EXACTFU nodes can be processed faster.
3932 * regexec.c takes advantage of this.
3934 * EXACTFUP has been created as a grab-bag for (hopefully uncommon)
3935 * problematic cases. These all only occur when the pattern is not
3936 * UTF-8. In addition to the 'ss' sequence where there is a possible fold
3937 * length change, it handles the situation where the string cannot be
3938 * entirely folded. The strings in an EXACTFish node are folded as much
3939 * as possible during compilation in regcomp.c. This saves effort in
3940 * regex matching. By using an EXACTFUP node when it is not possible to
3941 * fully fold at compile time, regexec.c can know that everything in an
3942 * EXACTFU node is folded, so folding can be skipped at runtime. The only
3943 * case where folding in EXACTFU nodes can't be done at compile time is
3944 * the presumably uncommon MICRO SIGN, when the pattern isn't UTF-8. This
3945 * is because its fold requires UTF-8 to represent. Thus EXACTFUP nodes
3946 * handle two very different cases. Alternatively, there could have been
3947 * a node type where there are length changes, one for unfolded, and one
3948 * for both. If yet another special case needed to be created, the number
3949 * of required node types would have to go to 7. khw figures that even
3950 * though there are plenty of node types to spare, that the maintenance
3951 * cost wasn't worth the small speedup of doing it that way, especially
3952 * since he thinks the MICRO SIGN is rarely encountered in practice.
3954 * There are other cases where folding isn't done at compile time, but
3955 * none of them are under /u, and hence not for EXACTFU nodes. The folds
3956 * in EXACTFL nodes aren't known until runtime, and vary as the locale
3957 * changes. Some folds in EXACTF depend on if the runtime target string
3958 * is UTF-8 or not. (regatom() will create an EXACTFU node even under /di
3959 * when no fold in it depends on the UTF-8ness of the target string.)
3961 * 3) A problem remains for unfolded multi-char folds. (These occur when the
3962 * validity of the fold won't be known until runtime, and so must remain
3963 * unfolded for now. This happens for the sharp s in EXACTF and EXACTFAA
3964 * nodes when the pattern isn't in UTF-8. (Note, BTW, that there cannot
3965 * be an EXACTF node with a UTF-8 pattern.) They also occur for various
3966 * folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
3967 * The reason this is a problem is that the optimizer part of regexec.c
3968 * (probably unwittingly, in Perl_regexec_flags()) makes an assumption
3969 * that a character in the pattern corresponds to at most a single
3970 * character in the target string. (And I do mean character, and not byte
3971 * here, unlike other parts of the documentation that have never been
3972 * updated to account for multibyte Unicode.) Sharp s in EXACTF and
3973 * EXACTFL nodes can match the two character string 'ss'; in EXACTFAA
3974 * nodes it can match "\x{17F}\x{17F}". These, along with other ones in
3975 * EXACTFL nodes, violate the assumption, and they are the only instances
3976 * where it is violated. I'm reluctant to try to change the assumption,
3977 * as the code involved is impenetrable to me (khw), so instead the code
3978 * here punts. This routine examines EXACTFL nodes, and (when the pattern
3979 * isn't UTF-8) EXACTF and EXACTFAA for such unfolded folds, and returns a
3980 * boolean indicating whether or not the node contains such a fold. When
3981 * it is true, the caller sets a flag that later causes the optimizer in
3982 * this file to not set values for the floating and fixed string lengths,
3983 * and thus avoids the optimizer code in regexec.c that makes the invalid
3984 * assumption. Thus, there is no optimization based on string lengths for
3985 * EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
3986 * EXACTF and EXACTFAA nodes that contain the sharp s. (The reason the
3987 * assumption is wrong only in these cases is that all other non-UTF-8
3988 * folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
3989 * their expanded versions. (Again, we can't prefold sharp s to 'ss' in
3990 * EXACTF nodes because we don't know at compile time if it actually
3991 * matches 'ss' or not. For EXACTF nodes it will match iff the target
3992 * string is in UTF-8. This is in contrast to EXACTFU nodes, where it
3993 * always matches; and EXACTFAA where it never does. In an EXACTFAA node
3994 * in a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
3995 * problem; but in a non-UTF8 pattern, folding it to that above-Latin1
3996 * string would require the pattern to be forced into UTF-8, the overhead
3997 * of which we want to avoid. Similarly the unfolded multi-char folds in
3998 * EXACTFL nodes will match iff the locale at the time of match is a UTF-8
4001 * Similarly, the code that generates tries doesn't currently handle
4002 * not-already-folded multi-char folds, and it looks like a pain to change
4003 * that. Therefore, trie generation of EXACTFAA nodes with the sharp s
4004 * doesn't work. Instead, such an EXACTFAA is turned into a new regnode,
4005 * EXACTFAA_NO_TRIE, which the trie code knows not to handle. Most people
4006 * using /iaa matching will be doing so almost entirely with ASCII
4007 * strings, so this should rarely be encountered in practice */
4009 #define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
4010 if (PL_regkind[OP(scan)] == EXACT && OP(scan) != LEXACT \
4011 && OP(scan) != LEXACT_REQ8) \
4012 join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags), NULL, depth+1)
4015 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
4016 UV *min_subtract, bool *unfolded_multi_char,
4017 U32 flags, regnode *val, U32 depth)
4019 /* Merge several consecutive EXACTish nodes into one. */
4021 regnode *n = regnext(scan);
4023 regnode *next = scan + NODE_SZ_STR(scan);
4027 regnode *stop = scan;
4028 GET_RE_DEBUG_FLAGS_DECL;
4030 PERL_UNUSED_ARG(depth);
4033 PERL_ARGS_ASSERT_JOIN_EXACT;
4034 #ifndef EXPERIMENTAL_INPLACESCAN
4035 PERL_UNUSED_ARG(flags);
4036 PERL_UNUSED_ARG(val);
4038 DEBUG_PEEP("join", scan, depth, 0);
4040 assert(PL_regkind[OP(scan)] == EXACT);
4042 /* Look through the subsequent nodes in the chain. Skip NOTHING, merge
4043 * EXACT ones that are mergeable to the current one. */
4045 && ( PL_regkind[OP(n)] == NOTHING
4046 || (stringok && PL_regkind[OP(n)] == EXACT))
4048 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
4051 if (OP(n) == TAIL || n > next)
4053 if (PL_regkind[OP(n)] == NOTHING) {
4054 DEBUG_PEEP("skip:", n, depth, 0);
4055 NEXT_OFF(scan) += NEXT_OFF(n);
4056 next = n + NODE_STEP_REGNODE;
4063 else if (stringok) {
4064 const unsigned int oldl = STR_LEN(scan);
4065 regnode * const nnext = regnext(n);
4067 /* XXX I (khw) kind of doubt that this works on platforms (should
4068 * Perl ever run on one) where U8_MAX is above 255 because of lots
4069 * of other assumptions */
4070 /* Don't join if the sum can't fit into a single node */
4071 if (oldl + STR_LEN(n) > U8_MAX)
4074 /* Joining something that requires UTF-8 with something that
4075 * doesn't, means the result requires UTF-8. */
4076 if (OP(scan) == EXACT && (OP(n) == EXACT_REQ8)) {
4077 OP(scan) = EXACT_REQ8;
4079 else if (OP(scan) == EXACT_REQ8 && (OP(n) == EXACT)) {
4080 ; /* join is compatible, no need to change OP */
4082 else if ((OP(scan) == EXACTFU) && (OP(n) == EXACTFU_REQ8)) {
4083 OP(scan) = EXACTFU_REQ8;
4085 else if ((OP(scan) == EXACTFU_REQ8) && (OP(n) == EXACTFU)) {
4086 ; /* join is compatible, no need to change OP */
4088 else if (OP(scan) == EXACTFU && OP(n) == EXACTFU) {
4089 ; /* join is compatible, no need to change OP */
4091 else if (OP(scan) == EXACTFU && OP(n) == EXACTFU_S_EDGE) {
4093 /* Under /di, temporary EXACTFU_S_EDGE nodes are generated,
4094 * which can join with EXACTFU ones. We check for this case
4095 * here. These need to be resolved to either EXACTFU or
4096 * EXACTF at joining time. They have nothing in them that
4097 * would forbid them from being the more desirable EXACTFU
4098 * nodes except that they begin and/or end with a single [Ss].
4099 * The reason this is problematic is because they could be
4100 * joined in this loop with an adjacent node that ends and/or
4101 * begins with [Ss] which would then form the sequence 'ss',
4102 * which matches differently under /di than /ui, in which case
4103 * EXACTFU can't be used. If the 'ss' sequence doesn't get
4104 * formed, the nodes get absorbed into any adjacent EXACTFU
4105 * node. And if the only adjacent node is EXACTF, they get
4106 * absorbed into that, under the theory that a longer node is
4107 * better than two shorter ones, even if one is EXACTFU. Note
4108 * that EXACTFU_REQ8 is generated only for UTF-8 patterns,
4109 * and the EXACTFU_S_EDGE ones only for non-UTF-8. */
4111 if (STRING(n)[STR_LEN(n)-1] == 's') {
4113 /* Here the joined node would end with 's'. If the node
4114 * following the combination is an EXACTF one, it's better to
4115 * join this trailing edge 's' node with that one, leaving the
4116 * current one in 'scan' be the more desirable EXACTFU */
4117 if (OP(nnext) == EXACTF) {
4121 OP(scan) = EXACTFU_S_EDGE;
4123 } /* Otherwise, the beginning 's' of the 2nd node just
4124 becomes an interior 's' in 'scan' */
4126 else if (OP(scan) == EXACTF && OP(n) == EXACTF) {
4127 ; /* join is compatible, no need to change OP */
4129 else if (OP(scan) == EXACTF && OP(n) == EXACTFU_S_EDGE) {
4131 /* EXACTF nodes are compatible for joining with EXACTFU_S_EDGE
4132 * nodes. But the latter nodes can be also joined with EXACTFU
4133 * ones, and that is a better outcome, so if the node following
4134 * 'n' is EXACTFU, quit now so that those two can be joined
4136 if (OP(nnext) == EXACTFU) {
4140 /* The join is compatible, and the combined node will be
4141 * EXACTF. (These don't care if they begin or end with 's' */
4143 else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU_S_EDGE) {
4144 if ( STRING(scan)[STR_LEN(scan)-1] == 's'
4145 && STRING(n)[0] == 's')
4147 /* When combined, we have the sequence 'ss', which means we
4148 * have to remain /di */
4152 else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU) {
4153 if (STRING(n)[0] == 's') {
4154 ; /* Here the join is compatible and the combined node
4155 starts with 's', no need to change OP */
4157 else { /* Now the trailing 's' is in the interior */
4161 else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTF) {
4163 /* The join is compatible, and the combined node will be
4164 * EXACTF. (These don't care if they begin or end with 's' */
4167 else if (OP(scan) != OP(n)) {
4169 /* The only other compatible joinings are the same node type */
4173 DEBUG_PEEP("merg", n, depth, 0);
4176 NEXT_OFF(scan) += NEXT_OFF(n);
4177 setSTR_LEN(scan, STR_LEN(scan) + STR_LEN(n));
4178 next = n + NODE_SZ_STR(n);
4179 /* Now we can overwrite *n : */
4180 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
4188 #ifdef EXPERIMENTAL_INPLACESCAN
4189 if (flags && !NEXT_OFF(n)) {
4190 DEBUG_PEEP("atch", val, depth, 0);
4191 if (reg_off_by_arg[OP(n)]) {
4192 ARG_SET(n, val - n);
4195 NEXT_OFF(n) = val - n;
4202 /* This temporary node can now be turned into EXACTFU, and must, as
4203 * regexec.c doesn't handle it */
4204 if (OP(scan) == EXACTFU_S_EDGE) {
4209 *unfolded_multi_char = FALSE;
4211 /* Here, all the adjacent mergeable EXACTish nodes have been merged. We
4212 * can now analyze for sequences of problematic code points. (Prior to
4213 * this final joining, sequences could have been split over boundaries, and
4214 * hence missed). The sequences only happen in folding, hence for any
4215 * non-EXACT EXACTish node */
4216 if (OP(scan) != EXACT && OP(scan) != EXACT_REQ8 && OP(scan) != EXACTL) {
4217 U8* s0 = (U8*) STRING(scan);
4219 U8* s_end = s0 + STR_LEN(scan);
4221 int total_count_delta = 0; /* Total delta number of characters that
4222 multi-char folds expand to */
4224 /* One pass is made over the node's string looking for all the
4225 * possibilities. To avoid some tests in the loop, there are two main
4226 * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
4231 if (OP(scan) == EXACTFL) {
4234 /* An EXACTFL node would already have been changed to another
4235 * node type unless there is at least one character in it that
4236 * is problematic; likely a character whose fold definition
4237 * won't be known until runtime, and so has yet to be folded.
4238 * For all but the UTF-8 locale, folds are 1-1 in length, but
4239 * to handle the UTF-8 case, we need to create a temporary
4240 * folded copy using UTF-8 locale rules in order to analyze it.
4241 * This is because our macros that look to see if a sequence is
4242 * a multi-char fold assume everything is folded (otherwise the
4243 * tests in those macros would be too complicated and slow).
4244 * Note that here, the non-problematic folds will have already
4245 * been done, so we can just copy such characters. We actually
4246 * don't completely fold the EXACTFL string. We skip the
4247 * unfolded multi-char folds, as that would just create work
4248 * below to figure out the size they already are */
4250 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
4253 STRLEN s_len = UTF8SKIP(s);
4254 if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
4255 Copy(s, d, s_len, U8);
4258 else if (is_FOLDS_TO_MULTI_utf8(s)) {
4259 *unfolded_multi_char = TRUE;
4260 Copy(s, d, s_len, U8);
4263 else if (isASCII(*s)) {
4264 *(d++) = toFOLD(*s);
4268 _toFOLD_utf8_flags(s, s_end, d, &len, FOLD_FLAGS_FULL);
4274 /* Point the remainder of the routine to look at our temporary
4278 } /* End of creating folded copy of EXACTFL string */
4280 /* Examine the string for a multi-character fold sequence. UTF-8
4281 * patterns have all characters pre-folded by the time this code is
4283 while (s < s_end - 1) /* Can stop 1 before the end, as minimum
4284 length sequence we are looking for is 2 */
4286 int count = 0; /* How many characters in a multi-char fold */
4287 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
4288 if (! len) { /* Not a multi-char fold: get next char */
4293 { /* Here is a generic multi-char fold. */
4294 U8* multi_end = s + len;
4296 /* Count how many characters are in it. In the case of
4297 * /aa, no folds which contain ASCII code points are
4298 * allowed, so check for those, and skip if found. */
4299 if (OP(scan) != EXACTFAA && OP(scan) != EXACTFAA_NO_TRIE) {
4300 count = utf8_length(s, multi_end);
4304 while (s < multi_end) {
4307 goto next_iteration;
4317 /* The delta is how long the sequence is minus 1 (1 is how long
4318 * the character that folds to the sequence is) */
4319 total_count_delta += count - 1;
4323 /* We created a temporary folded copy of the string in EXACTFL
4324 * nodes. Therefore we need to be sure it doesn't go below zero,
4325 * as the real string could be shorter */
4326 if (OP(scan) == EXACTFL) {
4327 int total_chars = utf8_length((U8*) STRING(scan),
4328 (U8*) STRING(scan) + STR_LEN(scan));
4329 if (total_count_delta > total_chars) {
4330 total_count_delta = total_chars;
4334 *min_subtract += total_count_delta;
4337 else if (OP(scan) == EXACTFAA) {
4339 /* Non-UTF-8 pattern, EXACTFAA node. There can't be a multi-char
4340 * fold to the ASCII range (and there are no existing ones in the
4341 * upper latin1 range). But, as outlined in the comments preceding
4342 * this function, we need to flag any occurrences of the sharp s.
4343 * This character forbids trie formation (because of added
4345 #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
4346 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
4347 || UNICODE_DOT_DOT_VERSION > 0)
4349 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
4350 OP(scan) = EXACTFAA_NO_TRIE;
4351 *unfolded_multi_char = TRUE;
4359 /* Non-UTF-8 pattern, not EXACTFAA node. Look for the multi-char
4360 * folds that are all Latin1. As explained in the comments
4361 * preceding this function, we look also for the sharp s in EXACTF
4362 * and EXACTFL nodes; it can be in the final position. Otherwise
4363 * we can stop looking 1 byte earlier because have to find at least
4364 * two characters for a multi-fold */
4365 const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
4370 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
4371 if (! len) { /* Not a multi-char fold. */
4372 if (*s == LATIN_SMALL_LETTER_SHARP_S
4373 && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
4375 *unfolded_multi_char = TRUE;
4382 && isALPHA_FOLD_EQ(*s, 's')
4383 && isALPHA_FOLD_EQ(*(s+1), 's'))
4386 /* EXACTF nodes need to know that the minimum length
4387 * changed so that a sharp s in the string can match this
4388 * ss in the pattern, but they remain EXACTF nodes, as they
4389 * won't match this unless the target string is is UTF-8,
4390 * which we don't know until runtime. EXACTFL nodes can't
4391 * transform into EXACTFU nodes */
4392 if (OP(scan) != EXACTF && OP(scan) != EXACTFL) {
4393 OP(scan) = EXACTFUP;
4397 *min_subtract += len - 1;
4403 if ( STR_LEN(scan) == 1
4404 && isALPHA_A(* STRING(scan))
4405 && ( OP(scan) == EXACTFAA
4406 || ( OP(scan) == EXACTFU
4407 && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(scan)))))
4409 U8 mask = ~ ('A' ^ 'a'); /* These differ in just one bit */
4411 /* Replace a length 1 ASCII fold pair node with an ANYOFM node,
4412 * with the mask set to the complement of the bit that differs
4413 * between upper and lower case, and the lowest code point of the
4414 * pair (which the '&' forces) */
4416 ARG_SET(scan, *STRING(scan) & mask);
4422 /* Allow dumping but overwriting the collection of skipped
4423 * ops and/or strings with fake optimized ops */
4424 n = scan + NODE_SZ_STR(scan);
4432 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl", scan, depth, 0);});
4436 /* REx optimizer. Converts nodes into quicker variants "in place".
4437 Finds fixed substrings. */
4439 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
4440 to the position after last scanned or to NULL. */
4442 #define INIT_AND_WITHP \
4443 assert(!and_withp); \
4444 Newx(and_withp, 1, regnode_ssc); \
4445 SAVEFREEPV(and_withp)
4449 S_unwind_scan_frames(pTHX_ const void *p)
4451 scan_frame *f= (scan_frame *)p;
4453 scan_frame *n= f->next_frame;
4459 /* the return from this sub is the minimum length that could possibly match */
4461 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
4462 SSize_t *minlenp, SSize_t *deltap,
4467 regnode_ssc *and_withp,
4468 U32 flags, U32 depth)
4469 /* scanp: Start here (read-write). */
4470 /* deltap: Write maxlen-minlen here. */
4471 /* last: Stop before this one. */
4472 /* data: string data about the pattern */
4473 /* stopparen: treat close N as END */
4474 /* recursed: which subroutines have we recursed into */
4475 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
4478 /* There must be at least this number of characters to match */
4481 regnode *scan = *scanp, *next;
4483 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
4484 int is_inf_internal = 0; /* The studied chunk is infinite */
4485 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
4486 scan_data_t data_fake;
4487 SV *re_trie_maxbuff = NULL;
4488 regnode *first_non_open = scan;
4489 SSize_t stopmin = SSize_t_MAX;
4490 scan_frame *frame = NULL;
4491 GET_RE_DEBUG_FLAGS_DECL;
4493 PERL_ARGS_ASSERT_STUDY_CHUNK;
4494 RExC_study_started= 1;
4496 Zero(&data_fake, 1, scan_data_t);
4499 while (first_non_open && OP(first_non_open) == OPEN)
4500 first_non_open=regnext(first_non_open);
4506 RExC_study_chunk_recursed_count++;
4508 DEBUG_OPTIMISE_MORE_r(
4510 Perl_re_indentf( aTHX_ "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p",
4511 depth, (long)stopparen,
4512 (unsigned long)RExC_study_chunk_recursed_count,
4513 (unsigned long)depth, (unsigned long)recursed_depth,
4516 if (recursed_depth) {
4519 for ( j = 0 ; j < recursed_depth ; j++ ) {
4520 for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) {
4522 PAREN_TEST(RExC_study_chunk_recursed +
4523 ( j * RExC_study_chunk_recursed_bytes), i )
4526 !PAREN_TEST(RExC_study_chunk_recursed +
4527 (( j - 1 ) * RExC_study_chunk_recursed_bytes), i)
4530 Perl_re_printf( aTHX_ " %d",(int)i);
4534 if ( j + 1 < recursed_depth ) {
4535 Perl_re_printf( aTHX_ ",");
4539 Perl_re_printf( aTHX_ "\n");
4542 while ( scan && OP(scan) != END && scan < last ){
4543 UV min_subtract = 0; /* How mmany chars to subtract from the minimum
4544 node length to get a real minimum (because
4545 the folded version may be shorter) */
4546 bool unfolded_multi_char = FALSE;
4547 /* Peephole optimizer: */
4548 DEBUG_STUDYDATA("Peep", data, depth, is_inf);
4549 DEBUG_PEEP("Peep", scan, depth, flags);
4552 /* The reason we do this here is that we need to deal with things like
4553 * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT
4554 * parsing code, as each (?:..) is handled by a different invocation of
4557 JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);
4559 /* Follow the next-chain of the current node and optimize
4560 away all the NOTHINGs from it. */
4561 if (OP(scan) != CURLYX) {
4562 const int max = (reg_off_by_arg[OP(scan)]
4564 /* I32 may be smaller than U16 on CRAYs! */
4565 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
4566 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
4570 /* Skip NOTHING and LONGJMP. */
4571 while ( (n = regnext(n))
4572 && ( (PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
4573 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
4574 && off + noff < max)
4576 if (reg_off_by_arg[OP(scan)])
4579 NEXT_OFF(scan) = off;
4582 /* The principal pseudo-switch. Cannot be a switch, since we look into
4583 * several different things. */
4584 if ( OP(scan) == DEFINEP ) {
4586 SSize_t deltanext = 0;
4587 SSize_t fake_last_close = 0;
4588 I32 f = SCF_IN_DEFINE;
4590 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4591 scan = regnext(scan);
4592 assert( OP(scan) == IFTHEN );
4593 DEBUG_PEEP("expect IFTHEN", scan, depth, flags);
4595 data_fake.last_closep= &fake_last_close;
4597 next = regnext(scan);
4598 scan = NEXTOPER(NEXTOPER(scan));
4599 DEBUG_PEEP("scan", scan, depth, flags);
4600 DEBUG_PEEP("next", next, depth, flags);
4602 /* we suppose the run is continuous, last=next...
4603 * NOTE we dont use the return here! */
4604 /* DEFINEP study_chunk() recursion */
4605 (void)study_chunk(pRExC_state, &scan, &minlen,
4606 &deltanext, next, &data_fake, stopparen,
4607 recursed_depth, NULL, f, depth+1);
4612 OP(scan) == BRANCH ||
4613 OP(scan) == BRANCHJ ||
4616 next = regnext(scan);
4619 /* The op(next)==code check below is to see if we
4620 * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN"
4621 * IFTHEN is special as it might not appear in pairs.
4622 * Not sure whether BRANCH-BRANCHJ is possible, regardless
4623 * we dont handle it cleanly. */
4624 if (OP(next) == code || code == IFTHEN) {
4625 /* NOTE - There is similar code to this block below for
4626 * handling TRIE nodes on a re-study. If you change stuff here
4627 * check there too. */
4628 SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0;
4630 regnode * const startbranch=scan;
4632 if (flags & SCF_DO_SUBSTR) {
4633 /* Cannot merge strings after this. */
4634 scan_commit(pRExC_state, data, minlenp, is_inf);
4637 if (flags & SCF_DO_STCLASS)
4638 ssc_init_zero(pRExC_state, &accum);
4640 while (OP(scan) == code) {
4641 SSize_t deltanext, minnext, fake;
4643 regnode_ssc this_class;
4645 DEBUG_PEEP("Branch", scan, depth, flags);
4648 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4650 data_fake.whilem_c = data->whilem_c;
4651 data_fake.last_closep = data->last_closep;
4654 data_fake.last_closep = &fake;
4656 data_fake.pos_delta = delta;
4657 next = regnext(scan);
4659 scan = NEXTOPER(scan); /* everything */
4660 if (code != BRANCH) /* everything but BRANCH */
4661 scan = NEXTOPER(scan);
4663 if (flags & SCF_DO_STCLASS) {
4664 ssc_init(pRExC_state, &this_class);
4665 data_fake.start_class = &this_class;
4666 f = SCF_DO_STCLASS_AND;
4668 if (flags & SCF_WHILEM_VISITED_POS)
4669 f |= SCF_WHILEM_VISITED_POS;
4671 /* we suppose the run is continuous, last=next...*/
4672 /* recurse study_chunk() for each BRANCH in an alternation */
4673 minnext = study_chunk(pRExC_state, &scan, minlenp,
4674 &deltanext, next, &data_fake, stopparen,
4675 recursed_depth, NULL, f, depth+1);
4679 if (deltanext == SSize_t_MAX) {
4680 is_inf = is_inf_internal = 1;
4682 } else if (max1 < minnext + deltanext)
4683 max1 = minnext + deltanext;
4685 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4687 if (data_fake.flags & SCF_SEEN_ACCEPT) {
4688 if ( stopmin > minnext)
4689 stopmin = min + min1;
4690 flags &= ~SCF_DO_SUBSTR;
4692 data->flags |= SCF_SEEN_ACCEPT;
4695 if (data_fake.flags & SF_HAS_EVAL)
4696 data->flags |= SF_HAS_EVAL;
4697 data->whilem_c = data_fake.whilem_c;
4699 if (flags & SCF_DO_STCLASS)
4700 ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);
4702 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
4704 if (flags & SCF_DO_SUBSTR) {
4705 data->pos_min += min1;
4706 if (data->pos_delta >= SSize_t_MAX - (max1 - min1))
4707 data->pos_delta = SSize_t_MAX;
4709 data->pos_delta += max1 - min1;
4710 if (max1 != min1 || is_inf)
4711 data->cur_is_floating = 1;
4714 if (delta == SSize_t_MAX
4715 || SSize_t_MAX - delta - (max1 - min1) < 0)
4716 delta = SSize_t_MAX;
4718 delta += max1 - min1;
4719 if (flags & SCF_DO_STCLASS_OR) {
4720 ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);
4722 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4723 flags &= ~SCF_DO_STCLASS;
4726 else if (flags & SCF_DO_STCLASS_AND) {
4728 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
4729 flags &= ~SCF_DO_STCLASS;
4732 /* Switch to OR mode: cache the old value of
4733 * data->start_class */
4735 StructCopy(data->start_class, and_withp, regnode_ssc);
4736 flags &= ~SCF_DO_STCLASS_AND;
4737 StructCopy(&accum, data->start_class, regnode_ssc);
4738 flags |= SCF_DO_STCLASS_OR;
4742 if (PERL_ENABLE_TRIE_OPTIMISATION &&
4743 OP( startbranch ) == BRANCH )
4747 Assuming this was/is a branch we are dealing with: 'scan'
4748 now points at the item that follows the branch sequence,
4749 whatever it is. We now start at the beginning of the
4750 sequence and look for subsequences of
4756 which would be constructed from a pattern like
4759 If we can find such a subsequence we need to turn the first
4760 element into a trie and then add the subsequent branch exact
4761 strings to the trie.
4765 1. patterns where the whole set of branches can be
4768 2. patterns where only a subset can be converted.
4770 In case 1 we can replace the whole set with a single regop
4771 for the trie. In case 2 we need to keep the start and end
4774 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
4775 becomes BRANCH TRIE; BRANCH X;
4777 There is an additional case, that being where there is a
4778 common prefix, which gets split out into an EXACT like node
4779 preceding the TRIE node.
4781 If x(1..n)==tail then we can do a simple trie, if not we make
4782 a "jump" trie, such that when we match the appropriate word
4783 we "jump" to the appropriate tail node. Essentially we turn
4784 a nested if into a case structure of sorts.
4789 if (!re_trie_maxbuff) {
4790 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
4791 if (!SvIOK(re_trie_maxbuff))
4792 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
4794 if ( SvIV(re_trie_maxbuff)>=0 ) {
4796 regnode *first = (regnode *)NULL;
4797 regnode *prev = (regnode *)NULL;
4798 regnode *tail = scan;
4802 /* var tail is used because there may be a TAIL
4803 regop in the way. Ie, the exacts will point to the
4804 thing following the TAIL, but the last branch will
4805 point at the TAIL. So we advance tail. If we
4806 have nested (?:) we may have to move through several
4810 while ( OP( tail ) == TAIL ) {
4811 /* this is the TAIL generated by (?:) */
4812 tail = regnext( tail );
4816 DEBUG_TRIE_COMPILE_r({
4817 regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);
4818 Perl_re_indentf( aTHX_ "%s %" UVuf ":%s\n",
4820 "Looking for TRIE'able sequences. Tail node is ",
4821 (UV) REGNODE_OFFSET(tail),
4822 SvPV_nolen_const( RExC_mysv )
4828 Step through the branches
4829 cur represents each branch,
4830 noper is the first thing to be matched as part
4832 noper_next is the regnext() of that node.
4834 We normally handle a case like this
4835 /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also
4836 support building with NOJUMPTRIE, which restricts
4837 the trie logic to structures like /FOO|BAR/.
4839 If noper is a trieable nodetype then the branch is
4840 a possible optimization target. If we are building
4841 under NOJUMPTRIE then we require that noper_next is
4842 the same as scan (our current position in the regex
4845 Once we have two or more consecutive such branches
4846 we can create a trie of the EXACT's contents and
4847 stitch it in place into the program.
4849 If the sequence represents all of the branches in
4850 the alternation we replace the entire thing with a
4853 Otherwise when it is a subsequence we need to
4854 stitch it in place and replace only the relevant
4855 branches. This means the first branch has to remain
4856 as it is used by the alternation logic, and its
4857 next pointer, and needs to be repointed at the item
4858 on the branch chain following the last branch we
4859 have optimized away.
4861 This could be either a BRANCH, in which case the
4862 subsequence is internal, or it could be the item
4863 following the branch sequence in which case the
4864 subsequence is at the end (which does not
4865 necessarily mean the first node is the start of the
4868 TRIE_TYPE(X) is a define which maps the optype to a
4872 ----------------+-----------
4877 EXACTFU_REQ8 | EXACTFU
4881 EXACTFLU8 | EXACTFLU8
4885 #define TRIE_TYPE(X) ( ( NOTHING == (X) ) \
4887 : ( EXACT == (X) || EXACT_REQ8 == (X) ) \
4889 : ( EXACTFU == (X) \
4890 || EXACTFU_REQ8 == (X) \
4891 || EXACTFUP == (X) ) \
4893 : ( EXACTFAA == (X) ) \
4895 : ( EXACTL == (X) ) \
4897 : ( EXACTFLU8 == (X) ) \
4901 /* dont use tail as the end marker for this traverse */
4902 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
4903 regnode * const noper = NEXTOPER( cur );
4904 U8 noper_type = OP( noper );
4905 U8 noper_trietype = TRIE_TYPE( noper_type );
4906 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
4907 regnode * const noper_next = regnext( noper );
4908 U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
4909 U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0;
4912 DEBUG_TRIE_COMPILE_r({
4913 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4914 Perl_re_indentf( aTHX_ "- %d:%s (%d)",
4916 REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );
4918 regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);
4919 Perl_re_printf( aTHX_ " -> %d:%s",
4920 REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv));
4923 regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);
4924 Perl_re_printf( aTHX_ "\t=> %d:%s\t",
4925 REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv));
4927 Perl_re_printf( aTHX_ "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n",
4928 REG_NODE_NUM(first), REG_NODE_NUM(prev), REG_NODE_NUM(cur),
4929 PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]
4933 /* Is noper a trieable nodetype that can be merged
4934 * with the current trie (if there is one)? */
4938 ( noper_trietype == NOTHING )
4939 || ( trietype == NOTHING )
4940 || ( trietype == noper_trietype )
4943 && noper_next >= tail
4947 /* Handle mergable triable node Either we are
4948 * the first node in a new trieable sequence,
4949 * in which case we do some bookkeeping,
4950 * otherwise we update the end pointer. */
4953 if ( noper_trietype == NOTHING ) {
4954 #if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
4955 regnode * const noper_next = regnext( noper );
4956 U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
4957 U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
4960 if ( noper_next_trietype ) {
4961 trietype = noper_next_trietype;
4962 } else if (noper_next_type) {
4963 /* a NOTHING regop is 1 regop wide.
4964 * We need at least two for a trie
4965 * so we can't merge this in */
4969 trietype = noper_trietype;
4972 if ( trietype == NOTHING )
4973 trietype = noper_trietype;
4978 } /* end handle mergable triable node */
4980 /* handle unmergable node -
4981 * noper may either be a triable node which can
4982 * not be tried together with the current trie,
4983 * or a non triable node */
4985 /* If last is set and trietype is not
4986 * NOTHING then we have found at least two
4987 * triable branch sequences in a row of a
4988 * similar trietype so we can turn them
4989 * into a trie. If/when we allow NOTHING to
4990 * start a trie sequence this condition
4991 * will be required, and it isn't expensive
4992 * so we leave it in for now. */
4993 if ( trietype && trietype != NOTHING )
4994 make_trie( pRExC_state,
4995 startbranch, first, cur, tail,
4996 count, trietype, depth+1 );
4997 prev = NULL; /* note: we clear/update
4998 first, trietype etc below,
4999 so we dont do it here */
5003 && noper_next >= tail
5006 /* noper is triable, so we can start a new
5010 trietype = noper_trietype;
5012 /* if we already saw a first but the
5013 * current node is not triable then we have
5014 * to reset the first information. */
5019 } /* end handle unmergable node */
5020 } /* loop over branches */
5021 DEBUG_TRIE_COMPILE_r({
5022 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5023 Perl_re_indentf( aTHX_ "- %s (%d) <SCAN FINISHED> ",
5024 depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
5025 Perl_re_printf( aTHX_ "(First==%d, Last==%d, Cur==%d, tt==%s)\n",
5026 REG_NODE_NUM(first), REG_NODE_NUM(prev), REG_NODE_NUM(cur),
5027 PL_reg_name[trietype]
5031 if ( prev && trietype ) {
5032 if ( trietype != NOTHING ) {
5033 /* the last branch of the sequence was part of
5034 * a trie, so we have to construct it here
5035 * outside of the loop */
5036 made= make_trie( pRExC_state, startbranch,
5037 first, scan, tail, count,
5038 trietype, depth+1 );
5039 #ifdef TRIE_STUDY_OPT
5040 if ( ((made == MADE_EXACT_TRIE &&
5041 startbranch == first)
5042 || ( first_non_open == first )) &&
5044 flags |= SCF_TRIE_RESTUDY;
5045 if ( startbranch == first
5048 RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;
5053 /* at this point we know whatever we have is a
5054 * NOTHING sequence/branch AND if 'startbranch'
5055 * is 'first' then we can turn the whole thing
5058 if ( startbranch == first ) {
5060 /* the entire thing is a NOTHING sequence,
5061 * something like this: (?:|) So we can
5062 * turn it into a plain NOTHING op. */
5063 DEBUG_TRIE_COMPILE_r({
5064 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5065 Perl_re_indentf( aTHX_ "- %s (%d) <NOTHING BRANCH SEQUENCE>\n",
5067 SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
5070 OP(startbranch)= NOTHING;
5071 NEXT_OFF(startbranch)= tail - startbranch;
5072 for ( opt= startbranch + 1; opt < tail ; opt++ )
5076 } /* end if ( prev) */
5077 } /* TRIE_MAXBUF is non zero */
5081 else if ( code == BRANCHJ ) { /* single branch is optimized. */
5082 scan = NEXTOPER(NEXTOPER(scan));
5083 } else /* single branch is optimized. */
5084 scan = NEXTOPER(scan);
5086 } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) {
5088 regnode *start = NULL;
5089 regnode *end = NULL;
5090 U32 my_recursed_depth= recursed_depth;
5092 if (OP(scan) != SUSPEND) { /* GOSUB */
5093 /* Do setup, note this code has side effects beyond
5094 * the rest of this block. Specifically setting
5095 * RExC_recurse[] must happen at least once during
5098 RExC_recurse[ARG2L(scan)] = scan;
5099 start = REGNODE_p(RExC_open_parens[paren]);
5100 end = REGNODE_p(RExC_close_parens[paren]);
5102 /* NOTE we MUST always execute the above code, even
5103 * if we do nothing with a GOSUB */
5105 ( flags & SCF_IN_DEFINE )
5108 (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))
5110 ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )
5113 /* no need to do anything here if we are in a define. */
5114 /* or we are after some kind of infinite construct
5115 * so we can skip recursing into this item.
5116 * Since it is infinite we will not change the maxlen
5117 * or delta, and if we miss something that might raise
5118 * the minlen it will merely pessimise a little.
5120 * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/
5121 * might result in a minlen of 1 and not of 4,
5122 * but this doesn't make us mismatch, just try a bit
5123 * harder than we should.
5125 scan= regnext(scan);
5132 !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren)
5134 /* it is quite possible that there are more efficient ways
5135 * to do this. We maintain a bitmap per level of recursion
5136 * of which patterns we have entered so we can detect if a
5137 * pattern creates a possible infinite loop. When we
5138 * recurse down a level we copy the previous levels bitmap
5139 * down. When we are at recursion level 0 we zero the top
5140 * level bitmap. It would be nice to implement a different
5141 * more efficient way of doing this. In particular the top
5142 * level bitmap may be unnecessary.
5144 if (!recursed_depth) {
5145 Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);
5147 Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes),
5148 RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes),
5149 RExC_study_chunk_recursed_bytes, U8);
5151 /* we havent recursed into this paren yet, so recurse into it */
5152 DEBUG_STUDYDATA("gosub-set", data, depth, is_inf);
5153 PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren);
5154 my_recursed_depth= recursed_depth + 1;
5156 DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf);
5157 /* some form of infinite recursion, assume infinite length
5159 if (flags & SCF_DO_SUBSTR) {
5160 scan_commit(pRExC_state, data, minlenp, is_inf);
5161 data->cur_is_floating = 1;
5163 is_inf = is_inf_internal = 1;
5164 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5165 ssc_anything(data->start_class);
5166 flags &= ~SCF_DO_STCLASS;
5168 start= NULL; /* reset start so we dont recurse later on. */
5173 end = regnext(scan);
5176 scan_frame *newframe;
5178 if (!RExC_frame_last) {
5179 Newxz(newframe, 1, scan_frame);
5180 SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);
5181 RExC_frame_head= newframe;
5183 } else if (!RExC_frame_last->next_frame) {
5184 Newxz(newframe, 1, scan_frame);
5185 RExC_frame_last->next_frame= newframe;
5186 newframe->prev_frame= RExC_frame_last;
5189 newframe= RExC_frame_last->next_frame;
5191 RExC_frame_last= newframe;
5193 newframe->next_regnode = regnext(scan);
5194 newframe->last_regnode = last;
5195 newframe->stopparen = stopparen;
5196 newframe->prev_recursed_depth = recursed_depth;
5197 newframe->this_prev_frame= frame;
5199 DEBUG_STUDYDATA("frame-new", data, depth, is_inf);
5200 DEBUG_PEEP("fnew", scan, depth, flags);
5207 recursed_depth= my_recursed_depth;
5212 else if ( OP(scan) == EXACT
5213 || OP(scan) == LEXACT
5214 || OP(scan) == EXACT_REQ8
5215 || OP(scan) == LEXACT_REQ8
5216 || OP(scan) == EXACTL)
5218 SSize_t l = STR_LEN(scan);
5222 const U8 * const s = (U8*)STRING(scan);
5223 uc = utf8_to_uvchr_buf(s, s + l, NULL);
5224 l = utf8_length(s, s + l);
5226 uc = *((U8*)STRING(scan));
5229 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
5230 /* The code below prefers earlier match for fixed
5231 offset, later match for variable offset. */
5232 if (data->last_end == -1) { /* Update the start info. */
5233 data->last_start_min = data->pos_min;
5234 data->last_start_max = is_inf
5235 ? SSize_t_MAX : data->pos_min + data->pos_delta;
5237 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
5239 SvUTF8_on(data->last_found);
5241 SV * const sv = data->last_found;
5242 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5243 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5244 if (mg && mg->mg_len >= 0)
5245 mg->mg_len += utf8_length((U8*)STRING(scan),
5246 (U8*)STRING(scan)+STR_LEN(scan));
5248 data->last_end = data->pos_min + l;
5249 data->pos_min += l; /* As in the first entry. */
5250 data->flags &= ~SF_BEFORE_EOL;
5253 /* ANDing the code point leaves at most it, and not in locale, and
5254 * can't match null string */
5255 if (flags & SCF_DO_STCLASS_AND) {
5256 ssc_cp_and(data->start_class, uc);
5257 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5258 ssc_clear_locale(data->start_class);
5260 else if (flags & SCF_DO_STCLASS_OR) {
5261 ssc_add_cp(data->start_class, uc);
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;
5269 else if (PL_regkind[OP(scan)] == EXACT) {
5270 /* But OP != EXACT!, so is EXACTFish */
5271 SSize_t l = STR_LEN(scan);
5272 const U8 * s = (U8*)STRING(scan);
5274 /* Search for fixed substrings supports EXACT only. */
5275 if (flags & SCF_DO_SUBSTR) {
5277 scan_commit(pRExC_state, data, minlenp, is_inf);
5280 l = utf8_length(s, s + l);
5282 if (unfolded_multi_char) {
5283 RExC_seen |= REG_UNFOLDED_MULTI_SEEN;
5285 min += l - min_subtract;
5287 delta += min_subtract;
5288 if (flags & SCF_DO_SUBSTR) {
5289 data->pos_min += l - min_subtract;
5290 if (data->pos_min < 0) {
5293 data->pos_delta += min_subtract;
5295 data->cur_is_floating = 1; /* float */
5299 if (flags & SCF_DO_STCLASS) {
5300 SV* EXACTF_invlist = make_exactf_invlist(pRExC_state, scan);
5302 assert(EXACTF_invlist);
5303 if (flags & SCF_DO_STCLASS_AND) {
5304 if (OP(scan) != EXACTFL)
5305 ssc_clear_locale(data->start_class);
5306 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5307 ANYOF_POSIXL_ZERO(data->start_class);
5308 ssc_intersection(data->start_class, EXACTF_invlist, FALSE);
5310 else { /* SCF_DO_STCLASS_OR */
5311 ssc_union(data->start_class, EXACTF_invlist, FALSE);
5312 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5314 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5315 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5317 flags &= ~SCF_DO_STCLASS;
5318 SvREFCNT_dec(EXACTF_invlist);
5321 else if (REGNODE_VARIES(OP(scan))) {
5322 SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;
5323 I32 fl = 0, f = flags;
5324 regnode * const oscan = scan;
5325 regnode_ssc this_class;
5326 regnode_ssc *oclass = NULL;
5327 I32 next_is_eval = 0;
5329 switch (PL_regkind[OP(scan)]) {
5330 case WHILEM: /* End of (?:...)* . */
5331 scan = NEXTOPER(scan);
5334 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
5335 next = NEXTOPER(scan);
5336 if ( OP(next) == EXACT
5337 || OP(next) == LEXACT
5338 || OP(next) == EXACT_REQ8
5339 || OP(next) == LEXACT_REQ8
5340 || OP(next) == EXACTL
5341 || (flags & SCF_DO_STCLASS))
5344 maxcount = REG_INFTY;
5345 next = regnext(scan);
5346 scan = NEXTOPER(scan);
5350 if (flags & SCF_DO_SUBSTR)
5355 next = NEXTOPER(scan);
5357 /* This temporary node can now be turned into EXACTFU, and
5358 * must, as regexec.c doesn't handle it */
5359 if (OP(next) == EXACTFU_S_EDGE) {
5363 if ( STR_LEN(next) == 1
5364 && isALPHA_A(* STRING(next))
5365 && ( OP(next) == EXACTFAA
5366 || ( OP(next) == EXACTFU
5367 && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next)))))
5369 /* These differ in just one bit */
5370 U8 mask = ~ ('A' ^ 'a');
5372 assert(isALPHA_A(* STRING(next)));
5374 /* Then replace it by an ANYOFM node, with
5375 * the mask set to the complement of the
5376 * bit that differs between upper and lower
5377 * case, and the lowest code point of the
5378 * pair (which the '&' forces) */
5380 ARG_SET(next, *STRING(next) & mask);
5384 if (flags & SCF_DO_STCLASS) {
5386 maxcount = REG_INFTY;
5387 next = regnext(scan);
5388 scan = NEXTOPER(scan);
5391 if (flags & SCF_DO_SUBSTR) {
5392 scan_commit(pRExC_state, data, minlenp, is_inf);
5393 /* Cannot extend fixed substrings */
5394 data->cur_is_floating = 1; /* float */
5396 is_inf = is_inf_internal = 1;
5397 scan = regnext(scan);
5398 goto optimize_curly_tail;
5400 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
5401 && (scan->flags == stopparen))
5406 mincount = ARG1(scan);
5407 maxcount = ARG2(scan);
5409 next = regnext(scan);
5410 if (OP(scan) == CURLYX) {
5411 I32 lp = (data ? *(data->last_closep) : 0);
5412 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
5414 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
5415 next_is_eval = (OP(scan) == EVAL);
5417 if (flags & SCF_DO_SUBSTR) {
5419 scan_commit(pRExC_state, data, minlenp, is_inf);
5420 /* Cannot extend fixed substrings */
5421 pos_before = data->pos_min;
5425 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
5427 data->flags |= SF_IS_INF;
5429 if (flags & SCF_DO_STCLASS) {
5430 ssc_init(pRExC_state, &this_class);
5431 oclass = data->start_class;
5432 data->start_class = &this_class;
5433 f |= SCF_DO_STCLASS_AND;
5434 f &= ~SCF_DO_STCLASS_OR;
5436 /* Exclude from super-linear cache processing any {n,m}
5437 regops for which the combination of input pos and regex
5438 pos is not enough information to determine if a match
5441 For example, in the regex /foo(bar\s*){4,8}baz/ with the
5442 regex pos at the \s*, the prospects for a match depend not
5443 only on the input position but also on how many (bar\s*)
5444 repeats into the {4,8} we are. */
5445 if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
5446 f &= ~SCF_WHILEM_VISITED_POS;
5448 /* This will finish on WHILEM, setting scan, or on NULL: */
5449 /* recurse study_chunk() on loop bodies */
5450 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
5451 last, data, stopparen, recursed_depth, NULL,
5453 ? (f & ~SCF_DO_SUBSTR)
5457 if (flags & SCF_DO_STCLASS)
5458 data->start_class = oclass;
5459 if (mincount == 0 || minnext == 0) {
5460 if (flags & SCF_DO_STCLASS_OR) {
5461 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5463 else if (flags & SCF_DO_STCLASS_AND) {
5464 /* Switch to OR mode: cache the old value of
5465 * data->start_class */
5467 StructCopy(data->start_class, and_withp, regnode_ssc);
5468 flags &= ~SCF_DO_STCLASS_AND;
5469 StructCopy(&this_class, data->start_class, regnode_ssc);
5470 flags |= SCF_DO_STCLASS_OR;
5471 ANYOF_FLAGS(data->start_class)
5472 |= SSC_MATCHES_EMPTY_STRING;
5474 } else { /* Non-zero len */
5475 if (flags & SCF_DO_STCLASS_OR) {
5476 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5477 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5479 else if (flags & SCF_DO_STCLASS_AND)
5480 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5481 flags &= ~SCF_DO_STCLASS;
5483 if (!scan) /* It was not CURLYX, but CURLY. */
5485 if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR)
5486 /* ? quantifier ok, except for (?{ ... }) */
5487 && (next_is_eval || !(mincount == 0 && maxcount == 1))
5488 && (minnext == 0) && (deltanext == 0)
5489 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
5490 && maxcount <= REG_INFTY/3) /* Complement check for big
5493 _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP),
5494 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
5495 "Quantifier unexpected on zero-length expression "
5496 "in regex m/%" UTF8f "/",
5497 UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,
5501 min += minnext * mincount;
5502 is_inf_internal |= deltanext == SSize_t_MAX
5503 || (maxcount == REG_INFTY && minnext + deltanext > 0);
5504 is_inf |= is_inf_internal;
5506 delta = SSize_t_MAX;
5508 delta += (minnext + deltanext) * maxcount
5509 - minnext * mincount;
5511 /* Try powerful optimization CURLYX => CURLYN. */
5512 if ( OP(oscan) == CURLYX && data
5513 && data->flags & SF_IN_PAR
5514 && !(data->flags & SF_HAS_EVAL)
5515 && !deltanext && minnext == 1 ) {
5516 /* Try to optimize to CURLYN. */
5517 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
5518 regnode * const nxt1 = nxt;
5525 if (!REGNODE_SIMPLE(OP(nxt))
5526 && !(PL_regkind[OP(nxt)] == EXACT
5527 && STR_LEN(nxt) == 1))
5533 if (OP(nxt) != CLOSE)
5535 if (RExC_open_parens) {
5538 RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5541 RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2;
5543 /* Now we know that nxt2 is the only contents: */
5544 oscan->flags = (U8)ARG(nxt);
5546 OP(nxt1) = NOTHING; /* was OPEN. */
5549 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5550 NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
5551 NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
5552 OP(nxt) = OPTIMIZED; /* was CLOSE. */
5553 OP(nxt + 1) = OPTIMIZED; /* was count. */
5554 NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
5559 /* Try optimization CURLYX => CURLYM. */
5560 if ( OP(oscan) == CURLYX && data
5561 && !(data->flags & SF_HAS_PAR)
5562 && !(data->flags & SF_HAS_EVAL)
5563 && !deltanext /* atom is fixed width */
5564 && minnext != 0 /* CURLYM can't handle zero width */
5566 /* Nor characters whose fold at run-time may be
5567 * multi-character */
5568 && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)
5570 /* XXXX How to optimize if data == 0? */
5571 /* Optimize to a simpler form. */
5572 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
5576 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
5577 && (OP(nxt2) != WHILEM))
5579 OP(nxt2) = SUCCEED; /* Whas WHILEM */
5580 /* Need to optimize away parenths. */
5581 if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
5582 /* Set the parenth number. */
5583 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
5585 oscan->flags = (U8)ARG(nxt);
5586 if (RExC_open_parens) {
5588 RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5591 RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2)
5594 OP(nxt1) = OPTIMIZED; /* was OPEN. */
5595 OP(nxt) = OPTIMIZED; /* was CLOSE. */
5598 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5599 OP(nxt + 1) = OPTIMIZED; /* was count. */
5600 NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
5601 NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
5604 while ( nxt1 && (OP(nxt1) != WHILEM)) {
5605 regnode *nnxt = regnext(nxt1);
5607 if (reg_off_by_arg[OP(nxt1)])
5608 ARG_SET(nxt1, nxt2 - nxt1);
5609 else if (nxt2 - nxt1 < U16_MAX)
5610 NEXT_OFF(nxt1) = nxt2 - nxt1;
5612 OP(nxt) = NOTHING; /* Cannot beautify */
5617 /* Optimize again: */
5618 /* recurse study_chunk() on optimised CURLYX => CURLYM */
5619 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
5620 NULL, stopparen, recursed_depth, NULL, 0,
5626 else if ((OP(oscan) == CURLYX)
5627 && (flags & SCF_WHILEM_VISITED_POS)
5628 /* See the comment on a similar expression above.
5629 However, this time it's not a subexpression
5630 we care about, but the expression itself. */
5631 && (maxcount == REG_INFTY)
5633 /* This stays as CURLYX, we can put the count/of pair. */
5634 /* Find WHILEM (as in regexec.c) */
5635 regnode *nxt = oscan + NEXT_OFF(oscan);
5637 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
5639 nxt = PREVOPER(nxt);
5640 if (nxt->flags & 0xf) {
5641 /* we've already set whilem count on this node */
5642 } else if (++data->whilem_c < 16) {
5643 assert(data->whilem_c <= RExC_whilem_seen);
5644 nxt->flags = (U8)(data->whilem_c
5645 | (RExC_whilem_seen << 4)); /* On WHILEM */
5648 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
5650 if (flags & SCF_DO_SUBSTR) {
5651 SV *last_str = NULL;
5652 STRLEN last_chrs = 0;
5653 int counted = mincount != 0;
5655 if (data->last_end > 0 && mincount != 0) { /* Ends with a
5657 SSize_t b = pos_before >= data->last_start_min
5658 ? pos_before : data->last_start_min;
5660 const char * const s = SvPV_const(data->last_found, l);
5661 SSize_t old = b - data->last_start_min;
5665 old = utf8_hop_forward((U8*)s, old,
5666 (U8 *) SvEND(data->last_found))
5669 /* Get the added string: */
5670 last_str = newSVpvn_utf8(s + old, l, UTF);
5671 last_chrs = UTF ? utf8_length((U8*)(s + old),
5672 (U8*)(s + old + l)) : l;
5673 if (deltanext == 0 && pos_before == b) {
5674 /* What was added is a constant string */
5677 SvGROW(last_str, (mincount * l) + 1);
5678 repeatcpy(SvPVX(last_str) + l,
5679 SvPVX_const(last_str), l,
5681 SvCUR_set(last_str, SvCUR(last_str) * mincount);
5682 /* Add additional parts. */
5683 SvCUR_set(data->last_found,
5684 SvCUR(data->last_found) - l);
5685 sv_catsv(data->last_found, last_str);
5687 SV * sv = data->last_found;
5689 SvUTF8(sv) && SvMAGICAL(sv) ?
5690 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5691 if (mg && mg->mg_len >= 0)
5692 mg->mg_len += last_chrs * (mincount-1);
5694 last_chrs *= mincount;
5695 data->last_end += l * (mincount - 1);
5698 /* start offset must point into the last copy */
5699 data->last_start_min += minnext * (mincount - 1);
5700 data->last_start_max =
5703 : data->last_start_max +
5704 (maxcount - 1) * (minnext + data->pos_delta);
5707 /* It is counted once already... */
5708 data->pos_min += minnext * (mincount - counted);
5710 Perl_re_printf( aTHX_ "counted=%" UVuf " deltanext=%" UVuf
5711 " SSize_t_MAX=%" UVuf " minnext=%" UVuf
5712 " maxcount=%" UVuf " mincount=%" UVuf "\n",
5713 (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount,
5715 if (deltanext != SSize_t_MAX)
5716 Perl_re_printf( aTHX_ "LHS=%" UVuf " RHS=%" UVuf "\n",
5717 (UV)(-counted * deltanext + (minnext + deltanext) * maxcount
5718 - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta));
5720 if (deltanext == SSize_t_MAX
5721 || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta)
5722 data->pos_delta = SSize_t_MAX;
5724 data->pos_delta += - counted * deltanext +
5725 (minnext + deltanext) * maxcount - minnext * mincount;
5726 if (mincount != maxcount) {
5727 /* Cannot extend fixed substrings found inside
5729 scan_commit(pRExC_state, data, minlenp, is_inf);
5730 if (mincount && last_str) {
5731 SV * const sv = data->last_found;
5732 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5733 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5737 sv_setsv(sv, last_str);
5738 data->last_end = data->pos_min;
5739 data->last_start_min = data->pos_min - last_chrs;
5740 data->last_start_max = is_inf
5742 : data->pos_min + data->pos_delta - last_chrs;
5744 data->cur_is_floating = 1; /* float */
5746 SvREFCNT_dec(last_str);
5748 if (data && (fl & SF_HAS_EVAL))
5749 data->flags |= SF_HAS_EVAL;
5750 optimize_curly_tail:
5751 if (OP(oscan) != CURLYX) {
5752 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
5754 NEXT_OFF(oscan) += NEXT_OFF(next);
5760 Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d",
5765 if (flags & SCF_DO_SUBSTR) {
5766 /* Cannot expect anything... */
5767 scan_commit(pRExC_state, data, minlenp, is_inf);
5768 data->cur_is_floating = 1; /* float */
5770 is_inf = is_inf_internal = 1;
5771 if (flags & SCF_DO_STCLASS_OR) {
5772 if (OP(scan) == CLUMP) {
5773 /* Actually is any start char, but very few code points
5774 * aren't start characters */
5775 ssc_match_all_cp(data->start_class);
5778 ssc_anything(data->start_class);
5781 flags &= ~SCF_DO_STCLASS;
5785 else if (OP(scan) == LNBREAK) {
5786 if (flags & SCF_DO_STCLASS) {
5787 if (flags & SCF_DO_STCLASS_AND) {
5788 ssc_intersection(data->start_class,
5789 PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);
5790 ssc_clear_locale(data->start_class);
5791 ANYOF_FLAGS(data->start_class)
5792 &= ~SSC_MATCHES_EMPTY_STRING;
5794 else if (flags & SCF_DO_STCLASS_OR) {
5795 ssc_union(data->start_class,
5796 PL_XPosix_ptrs[_CC_VERTSPACE],
5798 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5800 /* See commit msg for
5801 * 749e076fceedeb708a624933726e7989f2302f6a */
5802 ANYOF_FLAGS(data->start_class)
5803 &= ~SSC_MATCHES_EMPTY_STRING;
5805 flags &= ~SCF_DO_STCLASS;
5808 if (delta != SSize_t_MAX)
5809 delta++; /* Because of the 2 char string cr-lf */
5810 if (flags & SCF_DO_SUBSTR) {
5811 /* Cannot expect anything... */
5812 scan_commit(pRExC_state, data, minlenp, is_inf);
5814 if (data->pos_delta != SSize_t_MAX) {
5815 data->pos_delta += 1;
5817 data->cur_is_floating = 1; /* float */
5820 else if (REGNODE_SIMPLE(OP(scan))) {
5822 if (flags & SCF_DO_SUBSTR) {
5823 scan_commit(pRExC_state, data, minlenp, is_inf);
5827 if (flags & SCF_DO_STCLASS) {
5829 SV* my_invlist = NULL;
5832 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5833 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5835 /* Some of the logic below assumes that switching
5836 locale on will only add false positives. */
5841 Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d",
5845 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5846 ssc_match_all_cp(data->start_class);
5851 SV* REG_ANY_invlist = _new_invlist(2);
5852 REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,
5854 if (flags & SCF_DO_STCLASS_OR) {
5855 ssc_union(data->start_class,
5857 TRUE /* TRUE => invert, hence all but \n
5861 else if (flags & SCF_DO_STCLASS_AND) {
5862 ssc_intersection(data->start_class,
5864 TRUE /* TRUE => invert */
5866 ssc_clear_locale(data->start_class);
5868 SvREFCNT_dec_NN(REG_ANY_invlist);
5880 if (flags & SCF_DO_STCLASS_AND)
5881 ssc_and(pRExC_state, data->start_class,
5882 (regnode_charclass *) scan);
5884 ssc_or(pRExC_state, data->start_class,
5885 (regnode_charclass *) scan);
5891 SV* cp_list = get_ANYOFM_contents(scan);
5893 if (flags & SCF_DO_STCLASS_OR) {
5894 ssc_union(data->start_class, cp_list, invert);
5896 else if (flags & SCF_DO_STCLASS_AND) {
5897 ssc_intersection(data->start_class, cp_list, invert);
5900 SvREFCNT_dec_NN(cp_list);
5909 cp_list = _add_range_to_invlist(cp_list,
5911 ANYOFRbase(scan) + ANYOFRdelta(scan));
5913 if (flags & SCF_DO_STCLASS_OR) {
5914 ssc_union(data->start_class, cp_list, invert);
5916 else if (flags & SCF_DO_STCLASS_AND) {
5917 ssc_intersection(data->start_class, cp_list, invert);
5920 SvREFCNT_dec_NN(cp_list);
5929 namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;
5930 if (flags & SCF_DO_STCLASS_AND) {
5931 bool was_there = cBOOL(
5932 ANYOF_POSIXL_TEST(data->start_class,
5934 ANYOF_POSIXL_ZERO(data->start_class);
5935 if (was_there) { /* Do an AND */
5936 ANYOF_POSIXL_SET(data->start_class, namedclass);
5938 /* No individual code points can now match */
5939 data->start_class->invlist
5940 = sv_2mortal(_new_invlist(0));
5943 int complement = namedclass + ((invert) ? -1 : 1);
5945 assert(flags & SCF_DO_STCLASS_OR);
5947 /* If the complement of this class was already there,
5948 * the result is that they match all code points,
5949 * (\d + \D == everything). Remove the classes from
5950 * future consideration. Locale is not relevant in
5952 if (ANYOF_POSIXL_TEST(data->start_class, complement)) {
5953 ssc_match_all_cp(data->start_class);
5954 ANYOF_POSIXL_CLEAR(data->start_class, namedclass);
5955 ANYOF_POSIXL_CLEAR(data->start_class, complement);
5957 else { /* The usual case; just add this class to the
5959 ANYOF_POSIXL_SET(data->start_class, namedclass);
5964 case NPOSIXA: /* For these, we always know the exact set of
5969 my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL);
5970 goto join_posix_and_ascii;
5978 my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL);
5980 /* NPOSIXD matches all upper Latin1 code points unless the
5981 * target string being matched is UTF-8, which is
5982 * unknowable until match time. Since we are going to
5983 * invert, we want to get rid of all of them so that the
5984 * inversion will match all */
5985 if (OP(scan) == NPOSIXD) {
5986 _invlist_subtract(my_invlist, PL_UpperLatin1,
5990 join_posix_and_ascii:
5992 if (flags & SCF_DO_STCLASS_AND) {
5993 ssc_intersection(data->start_class, my_invlist, invert);
5994 ssc_clear_locale(data->start_class);
5997 assert(flags & SCF_DO_STCLASS_OR);
5998 ssc_union(data->start_class, my_invlist, invert);
6000 SvREFCNT_dec(my_invlist);
6002 if (flags & SCF_DO_STCLASS_OR)
6003 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6004 flags &= ~SCF_DO_STCLASS;
6007 else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
6008 data->flags |= (OP(scan) == MEOL
6011 scan_commit(pRExC_state, data, minlenp, is_inf);
6014 else if ( PL_regkind[OP(scan)] == BRANCHJ
6015 /* Lookbehind, or need to calculate parens/evals/stclass: */
6016 && (scan->flags || data || (flags & SCF_DO_STCLASS))
6017 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM))
6019 if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
6020 || OP(scan) == UNLESSM )
6022 /* Negative Lookahead/lookbehind
6023 In this case we can't do fixed string optimisation.
6026 SSize_t deltanext, minnext, fake = 0;
6031 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6033 data_fake.whilem_c = data->whilem_c;
6034 data_fake.last_closep = data->last_closep;
6037 data_fake.last_closep = &fake;
6038 data_fake.pos_delta = delta;
6039 if ( flags & SCF_DO_STCLASS && !scan->flags
6040 && OP(scan) == IFMATCH ) { /* Lookahead */
6041 ssc_init(pRExC_state, &intrnl);
6042 data_fake.start_class = &intrnl;
6043 f |= SCF_DO_STCLASS_AND;
6045 if (flags & SCF_WHILEM_VISITED_POS)
6046 f |= SCF_WHILEM_VISITED_POS;
6047 next = regnext(scan);
6048 nscan = NEXTOPER(NEXTOPER(scan));
6050 /* recurse study_chunk() for lookahead body */
6051 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
6052 last, &data_fake, stopparen,
6053 recursed_depth, NULL, f, depth+1);
6056 || deltanext > (I32) U8_MAX
6057 || minnext > (I32)U8_MAX
6058 || minnext + deltanext > (I32)U8_MAX)
6060 FAIL2("Lookbehind longer than %" UVuf " not implemented",
6064 /* The 'next_off' field has been repurposed to count the
6065 * additional starting positions to try beyond the initial
6066 * one. (This leaves it at 0 for non-variable length
6067 * matches to avoid breakage for those not using this
6070 scan->next_off = deltanext;
6071 ckWARNexperimental(RExC_parse,
6072 WARN_EXPERIMENTAL__VLB,
6073 "Variable length lookbehind is experimental");
6075 scan->flags = (U8)minnext + deltanext;
6078 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6080 if (data_fake.flags & SF_HAS_EVAL)
6081 data->flags |= SF_HAS_EVAL;
6082 data->whilem_c = data_fake.whilem_c;
6084 if (f & SCF_DO_STCLASS_AND) {
6085 if (flags & SCF_DO_STCLASS_OR) {
6086 /* OR before, AND after: ideally we would recurse with
6087 * data_fake to get the AND applied by study of the
6088 * remainder of the pattern, and then derecurse;
6089 * *** HACK *** for now just treat as "no information".
6090 * See [perl #56690].
6092 ssc_init(pRExC_state, data->start_class);
6094 /* AND before and after: combine and continue. These
6095 * assertions are zero-length, so can match an EMPTY
6097 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6098 ANYOF_FLAGS(data->start_class)
6099 |= SSC_MATCHES_EMPTY_STRING;
6103 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
6105 /* Positive Lookahead/lookbehind
6106 In this case we can do fixed string optimisation,
6107 but we must be careful about it. Note in the case of
6108 lookbehind the positions will be offset by the minimum
6109 length of the pattern, something we won't know about
6110 until after the recurse.
6112 SSize_t deltanext, fake = 0;
6116 /* We use SAVEFREEPV so that when the full compile
6117 is finished perl will clean up the allocated
6118 minlens when it's all done. This way we don't
6119 have to worry about freeing them when we know
6120 they wont be used, which would be a pain.
6123 Newx( minnextp, 1, SSize_t );
6124 SAVEFREEPV(minnextp);
6127 StructCopy(data, &data_fake, scan_data_t);
6128 if ((flags & SCF_DO_SUBSTR) && data->last_found) {
6131 scan_commit(pRExC_state, &data_fake, minlenp, is_inf);
6132 data_fake.last_found=newSVsv(data->last_found);
6136 data_fake.last_closep = &fake;
6137 data_fake.flags = 0;
6138 data_fake.substrs[0].flags = 0;
6139 data_fake.substrs[1].flags = 0;
6140 data_fake.pos_delta = delta;
6142 data_fake.flags |= SF_IS_INF;
6143 if ( flags & SCF_DO_STCLASS && !scan->flags
6144 && OP(scan) == IFMATCH ) { /* Lookahead */
6145 ssc_init(pRExC_state, &intrnl);
6146 data_fake.start_class = &intrnl;
6147 f |= SCF_DO_STCLASS_AND;
6149 if (flags & SCF_WHILEM_VISITED_POS)
6150 f |= SCF_WHILEM_VISITED_POS;
6151 next = regnext(scan);
6152 nscan = NEXTOPER(NEXTOPER(scan));
6154 /* positive lookahead study_chunk() recursion */
6155 *minnextp = study_chunk(pRExC_state, &nscan, minnextp,
6156 &deltanext, last, &data_fake,
6157 stopparen, recursed_depth, NULL,
6160 assert(0); /* This code has never been tested since this
6161 is normally not compiled */
6163 || deltanext > (I32) U8_MAX
6164 || *minnextp > (I32)U8_MAX
6165 || *minnextp + deltanext > (I32)U8_MAX)
6167 FAIL2("Lookbehind longer than %" UVuf " not implemented",
6172 scan->next_off = deltanext;
6174 scan->flags = (U8)*minnextp + deltanext;
6179 if (f & SCF_DO_STCLASS_AND) {
6180 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6181 ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;
6184 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6186 if (data_fake.flags & SF_HAS_EVAL)
6187 data->flags |= SF_HAS_EVAL;
6188 data->whilem_c = data_fake.whilem_c;
6189 if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
6191 if (RExC_rx->minlen<*minnextp)
6192 RExC_rx->minlen=*minnextp;
6193 scan_commit(pRExC_state, &data_fake, minnextp, is_inf);
6194 SvREFCNT_dec_NN(data_fake.last_found);
6196 for (i = 0; i < 2; i++) {
6197 if (data_fake.substrs[i].minlenp != minlenp) {
6198 data->substrs[i].min_offset =
6199 data_fake.substrs[i].min_offset;
6200 data->substrs[i].max_offset =
6201 data_fake.substrs[i].max_offset;
6202 data->substrs[i].minlenp =
6203 data_fake.substrs[i].minlenp;
6204 data->substrs[i].lookbehind += scan->flags;
6212 else if (OP(scan) == OPEN) {
6213 if (stopparen != (I32)ARG(scan))
6216 else if (OP(scan) == CLOSE) {
6217 if (stopparen == (I32)ARG(scan)) {
6220 if ((I32)ARG(scan) == is_par) {
6221 next = regnext(scan);
6223 if ( next && (OP(next) != WHILEM) && next < last)
6224 is_par = 0; /* Disable optimization */
6227 *(data->last_closep) = ARG(scan);
6229 else if (OP(scan) == EVAL) {
6231 data->flags |= SF_HAS_EVAL;
6233 else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
6234 if (flags & SCF_DO_SUBSTR) {
6235 scan_commit(pRExC_state, data, minlenp, is_inf);
6236 flags &= ~SCF_DO_SUBSTR;
6238 if (data && OP(scan)==ACCEPT) {
6239 data->flags |= SCF_SEEN_ACCEPT;
6244 else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
6246 if (flags & SCF_DO_SUBSTR) {
6247 scan_commit(pRExC_state, data, minlenp, is_inf);
6248 data->cur_is_floating = 1; /* float */
6250 is_inf = is_inf_internal = 1;
6251 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
6252 ssc_anything(data->start_class);
6253 flags &= ~SCF_DO_STCLASS;
6255 else if (OP(scan) == GPOS) {
6256 if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&
6257 !(delta || is_inf || (data && data->pos_delta)))
6259 if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))
6260 RExC_rx->intflags |= PREGf_ANCH_GPOS;
6261 if (RExC_rx->gofs < (STRLEN)min)
6262 RExC_rx->gofs = min;
6264 RExC_rx->intflags |= PREGf_GPOS_FLOAT;
6268 #ifdef TRIE_STUDY_OPT
6269 #ifdef FULL_TRIE_STUDY
6270 else if (PL_regkind[OP(scan)] == TRIE) {
6271 /* NOTE - There is similar code to this block above for handling
6272 BRANCH nodes on the initial study. If you change stuff here
6274 regnode *trie_node= scan;
6275 regnode *tail= regnext(scan);
6276 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6277 SSize_t max1 = 0, min1 = SSize_t_MAX;
6280 if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */
6281 /* Cannot merge strings after this. */
6282 scan_commit(pRExC_state, data, minlenp, is_inf);
6284 if (flags & SCF_DO_STCLASS)
6285 ssc_init_zero(pRExC_state, &accum);
6291 const regnode *nextbranch= NULL;
6294 for ( word=1 ; word <= trie->wordcount ; word++)
6296 SSize_t deltanext=0, minnext=0, f = 0, fake;
6297 regnode_ssc this_class;
6299 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6301 data_fake.whilem_c = data->whilem_c;
6302 data_fake.last_closep = data->last_closep;
6305 data_fake.last_closep = &fake;
6306 data_fake.pos_delta = delta;
6307 if (flags & SCF_DO_STCLASS) {
6308 ssc_init(pRExC_state, &this_class);
6309 data_fake.start_class = &this_class;
6310 f = SCF_DO_STCLASS_AND;
6312 if (flags & SCF_WHILEM_VISITED_POS)
6313 f |= SCF_WHILEM_VISITED_POS;
6315 if (trie->jump[word]) {
6317 nextbranch = trie_node + trie->jump[0];
6318 scan= trie_node + trie->jump[word];
6319 /* We go from the jump point to the branch that follows
6320 it. Note this means we need the vestigal unused
6321 branches even though they arent otherwise used. */
6322 /* optimise study_chunk() for TRIE */
6323 minnext = study_chunk(pRExC_state, &scan, minlenp,
6324 &deltanext, (regnode *)nextbranch, &data_fake,
6325 stopparen, recursed_depth, NULL, f, depth+1);
6327 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
6328 nextbranch= regnext((regnode*)nextbranch);
6330 if (min1 > (SSize_t)(minnext + trie->minlen))
6331 min1 = minnext + trie->minlen;
6332 if (deltanext == SSize_t_MAX) {
6333 is_inf = is_inf_internal = 1;
6335 } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))
6336 max1 = minnext + deltanext + trie->maxlen;
6338 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6340 if (data_fake.flags & SCF_SEEN_ACCEPT) {
6341 if ( stopmin > min + min1)
6342 stopmin = min + min1;
6343 flags &= ~SCF_DO_SUBSTR;
6345 data->flags |= SCF_SEEN_ACCEPT;
6348 if (data_fake.flags & SF_HAS_EVAL)
6349 data->flags |= SF_HAS_EVAL;
6350 data->whilem_c = data_fake.whilem_c;
6352 if (flags & SCF_DO_STCLASS)
6353 ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);
6356 if (flags & SCF_DO_SUBSTR) {
6357 data->pos_min += min1;
6358 data->pos_delta += max1 - min1;
6359 if (max1 != min1 || is_inf)
6360 data->cur_is_floating = 1; /* float */
6363 if (delta != SSize_t_MAX) {
6364 if (SSize_t_MAX - (max1 - min1) >= delta)
6365 delta += max1 - min1;
6367 delta = SSize_t_MAX;
6369 if (flags & SCF_DO_STCLASS_OR) {
6370 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6372 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6373 flags &= ~SCF_DO_STCLASS;
6376 else if (flags & SCF_DO_STCLASS_AND) {
6378 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6379 flags &= ~SCF_DO_STCLASS;
6382 /* Switch to OR mode: cache the old value of
6383 * data->start_class */
6385 StructCopy(data->start_class, and_withp, regnode_ssc);
6386 flags &= ~SCF_DO_STCLASS_AND;
6387 StructCopy(&accum, data->start_class, regnode_ssc);
6388 flags |= SCF_DO_STCLASS_OR;
6395 else if (PL_regkind[OP(scan)] == TRIE) {
6396 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6399 min += trie->minlen;
6400 delta += (trie->maxlen - trie->minlen);
6401 flags &= ~SCF_DO_STCLASS; /* xxx */
6402 if (flags & SCF_DO_SUBSTR) {
6403 /* Cannot expect anything... */
6404 scan_commit(pRExC_state, data, minlenp, is_inf);
6405 data->pos_min += trie->minlen;
6406 data->pos_delta += (trie->maxlen - trie->minlen);
6407 if (trie->maxlen != trie->minlen)
6408 data->cur_is_floating = 1; /* float */
6410 if (trie->jump) /* no more substrings -- for now /grr*/
6411 flags &= ~SCF_DO_SUBSTR;
6413 #endif /* old or new */
6414 #endif /* TRIE_STUDY_OPT */
6416 /* Else: zero-length, ignore. */
6417 scan = regnext(scan);
6422 /* we need to unwind recursion. */
6425 DEBUG_STUDYDATA("frame-end", data, depth, is_inf);
6426 DEBUG_PEEP("fend", scan, depth, flags);
6428 /* restore previous context */
6429 last = frame->last_regnode;
6430 scan = frame->next_regnode;
6431 stopparen = frame->stopparen;
6432 recursed_depth = frame->prev_recursed_depth;
6434 RExC_frame_last = frame->prev_frame;
6435 frame = frame->this_prev_frame;
6436 goto fake_study_recurse;
6440 DEBUG_STUDYDATA("pre-fin", data, depth, is_inf);
6443 *deltap = is_inf_internal ? SSize_t_MAX : delta;
6445 if (flags & SCF_DO_SUBSTR && is_inf)
6446 data->pos_delta = SSize_t_MAX - data->pos_min;
6447 if (is_par > (I32)U8_MAX)
6449 if (is_par && pars==1 && data) {
6450 data->flags |= SF_IN_PAR;
6451 data->flags &= ~SF_HAS_PAR;
6453 else if (pars && data) {
6454 data->flags |= SF_HAS_PAR;
6455 data->flags &= ~SF_IN_PAR;
6457 if (flags & SCF_DO_STCLASS_OR)
6458 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6459 if (flags & SCF_TRIE_RESTUDY)
6460 data->flags |= SCF_TRIE_RESTUDY;
6462 DEBUG_STUDYDATA("post-fin", data, depth, is_inf);
6465 SSize_t final_minlen= min < stopmin ? min : stopmin;
6467 if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {
6468 if (final_minlen > SSize_t_MAX - delta)
6469 RExC_maxlen = SSize_t_MAX;
6470 else if (RExC_maxlen < final_minlen + delta)
6471 RExC_maxlen = final_minlen + delta;
6473 return final_minlen;
6475 NOT_REACHED; /* NOTREACHED */
6479 S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n)
6481 U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
6483 PERL_ARGS_ASSERT_ADD_DATA;
6485 Renewc(RExC_rxi->data,
6486 sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
6487 char, struct reg_data);
6489 Renew(RExC_rxi->data->what, count + n, U8);
6491 Newx(RExC_rxi->data->what, n, U8);
6492 RExC_rxi->data->count = count + n;
6493 Copy(s, RExC_rxi->data->what + count, n, U8);
6497 /*XXX: todo make this not included in a non debugging perl, but appears to be
6498 * used anyway there, in 'use re' */
6499 #ifndef PERL_IN_XSUB_RE
6501 Perl_reginitcolors(pTHX)
6503 const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
6505 char *t = savepv(s);
6509 t = strchr(t, '\t');
6515 PL_colors[i] = t = (char *)"";
6520 PL_colors[i++] = (char *)"";
6527 #ifdef TRIE_STUDY_OPT
6528 #define CHECK_RESTUDY_GOTO_butfirst(dOsomething) \
6531 (data.flags & SCF_TRIE_RESTUDY) \
6539 #define CHECK_RESTUDY_GOTO_butfirst
6543 * pregcomp - compile a regular expression into internal code
6545 * Decides which engine's compiler to call based on the hint currently in
6549 #ifndef PERL_IN_XSUB_RE
6551 /* return the currently in-scope regex engine (or the default if none) */
6553 regexp_engine const *
6554 Perl_current_re_engine(pTHX)
6556 if (IN_PERL_COMPILETIME) {
6557 HV * const table = GvHV(PL_hintgv);
6560 if (!table || !(PL_hints & HINT_LOCALIZE_HH))
6561 return &PL_core_reg_engine;
6562 ptr = hv_fetchs(table, "regcomp", FALSE);
6563 if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
6564 return &PL_core_reg_engine;
6565 return INT2PTR(regexp_engine*, SvIV(*ptr));
6569 if (!PL_curcop->cop_hints_hash)
6570 return &PL_core_reg_engine;
6571 ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
6572 if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
6573 return &PL_core_reg_engine;
6574 return INT2PTR(regexp_engine*, SvIV(ptr));
6580 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
6582 regexp_engine const *eng = current_re_engine();
6583 GET_RE_DEBUG_FLAGS_DECL;
6585 PERL_ARGS_ASSERT_PREGCOMP;
6587 /* Dispatch a request to compile a regexp to correct regexp engine. */
6589 Perl_re_printf( aTHX_ "Using engine %" UVxf "\n",
6592 return CALLREGCOMP_ENG(eng, pattern, flags);
6596 /* public(ish) entry point for the perl core's own regex compiling code.
6597 * It's actually a wrapper for Perl_re_op_compile that only takes an SV
6598 * pattern rather than a list of OPs, and uses the internal engine rather
6599 * than the current one */
6602 Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
6604 SV *pat = pattern; /* defeat constness! */
6605 PERL_ARGS_ASSERT_RE_COMPILE;
6606 return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
6607 #ifdef PERL_IN_XSUB_RE
6610 &PL_core_reg_engine,
6612 NULL, NULL, rx_flags, 0);
6617 S_free_codeblocks(pTHX_ struct reg_code_blocks *cbs)
6621 if (--cbs->refcnt > 0)
6623 for (n = 0; n < cbs->count; n++) {
6624 REGEXP *rx = cbs->cb[n].src_regex;
6626 cbs->cb[n].src_regex = NULL;
6627 SvREFCNT_dec_NN(rx);
6635 static struct reg_code_blocks *
6636 S_alloc_code_blocks(pTHX_ int ncode)
6638 struct reg_code_blocks *cbs;
6639 Newx(cbs, 1, struct reg_code_blocks);
6642 SAVEDESTRUCTOR_X(S_free_codeblocks, cbs);
6644 Newx(cbs->cb, ncode, struct reg_code_block);
6651 /* upgrade pattern pat_p of length plen_p to UTF8, and if there are code
6652 * blocks, recalculate the indices. Update pat_p and plen_p in-place to
6653 * point to the realloced string and length.
6655 * This is essentially a copy of Perl_bytes_to_utf8() with the code index
6659 S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state,
6660 char **pat_p, STRLEN *plen_p, int num_code_blocks)
6662 U8 *const src = (U8*)*pat_p;
6667 GET_RE_DEBUG_FLAGS_DECL;
6669 DEBUG_PARSE_r(Perl_re_printf( aTHX_
6670 "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
6672 /* 1 for each byte + 1 for each byte that expands to two, + trailing NUL */
6673 Newx(dst, *plen_p + variant_under_utf8_count(src, src + *plen_p) + 1, U8);
6676 while (s < *plen_p) {
6677 append_utf8_from_native_byte(src[s], &d);
6679 if (n < num_code_blocks) {
6680 assert(pRExC_state->code_blocks);
6681 if (!do_end && pRExC_state->code_blocks->cb[n].start == s) {
6682 pRExC_state->code_blocks->cb[n].start = d - dst - 1;
6683 assert(*(d - 1) == '(');
6686 else if (do_end && pRExC_state->code_blocks->cb[n].end == s) {
6687 pRExC_state->code_blocks->cb[n].end = d - dst - 1;
6688 assert(*(d - 1) == ')');
6697 *pat_p = (char*) dst;
6699 RExC_orig_utf8 = RExC_utf8 = 1;
6704 /* S_concat_pat(): concatenate a list of args to the pattern string pat,
6705 * while recording any code block indices, and handling overloading,
6706 * nested qr// objects etc. If pat is null, it will allocate a new
6707 * string, or just return the first arg, if there's only one.
6709 * Returns the malloced/updated pat.
6710 * patternp and pat_count is the array of SVs to be concatted;
6711 * oplist is the optional list of ops that generated the SVs;
6712 * recompile_p is a pointer to a boolean that will be set if
6713 * the regex will need to be recompiled.
6714 * delim, if non-null is an SV that will be inserted between each element
6718 S_concat_pat(pTHX_ RExC_state_t * const pRExC_state,
6719 SV *pat, SV ** const patternp, int pat_count,
6720 OP *oplist, bool *recompile_p, SV *delim)
6724 bool use_delim = FALSE;
6725 bool alloced = FALSE;
6727 /* if we know we have at least two args, create an empty string,
6728 * then concatenate args to that. For no args, return an empty string */
6729 if (!pat && pat_count != 1) {
6735 for (svp = patternp; svp < patternp + pat_count; svp++) {
6738 STRLEN orig_patlen = 0;
6740 SV *msv = use_delim ? delim : *svp;
6741 if (!msv) msv = &PL_sv_undef;
6743 /* if we've got a delimiter, we go round the loop twice for each
6744 * svp slot (except the last), using the delimiter the second
6753 if (SvTYPE(msv) == SVt_PVAV) {
6754 /* we've encountered an interpolated array within
6755 * the pattern, e.g. /...@a..../. Expand the list of elements,
6756 * then recursively append elements.
6757 * The code in this block is based on S_pushav() */
6759 AV *const av = (AV*)msv;
6760 const SSize_t maxarg = AvFILL(av) + 1;
6764 assert(oplist->op_type == OP_PADAV
6765 || oplist->op_type == OP_RV2AV);
6766 oplist = OpSIBLING(oplist);
6769 if (SvRMAGICAL(av)) {
6772 Newx(array, maxarg, SV*);
6774 for (i=0; i < maxarg; i++) {
6775 SV ** const svp = av_fetch(av, i, FALSE);
6776 array[i] = svp ? *svp : &PL_sv_undef;
6780 array = AvARRAY(av);
6782 pat = S_concat_pat(aTHX_ pRExC_state, pat,
6783 array, maxarg, NULL, recompile_p,
6785 GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV))));
6791 /* we make the assumption here that each op in the list of
6792 * op_siblings maps to one SV pushed onto the stack,
6793 * except for code blocks, with have both an OP_NULL and
6795 * This allows us to match up the list of SVs against the
6796 * list of OPs to find the next code block.
6798 * Note that PUSHMARK PADSV PADSV ..
6800 * PADRANGE PADSV PADSV ..
6801 * so the alignment still works. */
6804 if (oplist->op_type == OP_NULL
6805 && (oplist->op_flags & OPf_SPECIAL))
6807 assert(n < pRExC_state->code_blocks->count);
6808 pRExC_state->code_blocks->cb[n].start = pat ? SvCUR(pat) : 0;
6809 pRExC_state->code_blocks->cb[n].block = oplist;
6810 pRExC_state->code_blocks->cb[n].src_regex = NULL;
6813 oplist = OpSIBLING(oplist); /* skip CONST */
6816 oplist = OpSIBLING(oplist);;
6819 /* apply magic and QR overloading to arg */
6822 if (SvROK(msv) && SvAMAGIC(msv)) {
6823 SV *sv = AMG_CALLunary(msv, regexp_amg);
6827 if (SvTYPE(sv) != SVt_REGEXP)
6828 Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
6833 /* try concatenation overload ... */
6834 if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) &&
6835 (sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
6838 /* overloading involved: all bets are off over literal
6839 * code. Pretend we haven't seen it */
6841 pRExC_state->code_blocks->count -= n;
6845 /* ... or failing that, try "" overload */
6846 while (SvAMAGIC(msv)
6847 && (sv = AMG_CALLunary(msv, string_amg))
6851 && SvRV(msv) == SvRV(sv))
6856 if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
6860 /* this is a partially unrolled
6861 * sv_catsv_nomg(pat, msv);
6862 * that allows us to adjust code block indices if
6865 char *dst = SvPV_force_nomg(pat, dlen);
6867 if (SvUTF8(msv) && !SvUTF8(pat)) {
6868 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n);
6869 sv_setpvn(pat, dst, dlen);
6872 sv_catsv_nomg(pat, msv);
6876 /* We have only one SV to process, but we need to verify
6877 * it is properly null terminated or we will fail asserts
6878 * later. In theory we probably shouldn't get such SV's,
6879 * but if we do we should handle it gracefully. */
6880 if ( SvTYPE(msv) != SVt_PV || (SvLEN(msv) > SvCUR(msv) && *(SvEND(msv)) == 0) || SvIsCOW_shared_hash(msv) ) {
6881 /* not a string, or a string with a trailing null */
6884 /* a string with no trailing null, we need to copy it
6885 * so it has a trailing null */
6886 pat = sv_2mortal(newSVsv(msv));
6891 pRExC_state->code_blocks->cb[n-1].end = SvCUR(pat)-1;
6894 /* extract any code blocks within any embedded qr//'s */
6895 if (rx && SvTYPE(rx) == SVt_REGEXP
6896 && RX_ENGINE((REGEXP*)rx)->op_comp)
6899 RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
6900 if (ri->code_blocks && ri->code_blocks->count) {
6902 /* the presence of an embedded qr// with code means
6903 * we should always recompile: the text of the
6904 * qr// may not have changed, but it may be a
6905 * different closure than last time */
6907 if (pRExC_state->code_blocks) {
6908 int new_count = pRExC_state->code_blocks->count
6909 + ri->code_blocks->count;
6910 Renew(pRExC_state->code_blocks->cb,
6911 new_count, struct reg_code_block);
6912 pRExC_state->code_blocks->count = new_count;
6915 pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_
6916 ri->code_blocks->count);
6918 for (i=0; i < ri->code_blocks->count; i++) {
6919 struct reg_code_block *src, *dst;
6920 STRLEN offset = orig_patlen
6921 + ReANY((REGEXP *)rx)->pre_prefix;
6922 assert(n < pRExC_state->code_blocks->count);
6923 src = &ri->code_blocks->cb[i];
6924 dst = &pRExC_state->code_blocks->cb[n];
6925 dst->start = src->start + offset;
6926 dst->end = src->end + offset;
6927 dst->block = src->block;
6928 dst->src_regex = (REGEXP*) SvREFCNT_inc( (SV*)
6937 /* avoid calling magic multiple times on a single element e.g. =~ $qr */
6946 /* see if there are any run-time code blocks in the pattern.
6947 * False positives are allowed */
6950 S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
6951 char *pat, STRLEN plen)
6956 PERL_UNUSED_CONTEXT;
6958 for (s = 0; s < plen; s++) {
6959 if ( pRExC_state->code_blocks
6960 && n < pRExC_state->code_blocks->count
6961 && s == pRExC_state->code_blocks->cb[n].start)
6963 s = pRExC_state->code_blocks->cb[n].end;
6967 /* TODO ideally should handle [..], (#..), /#.../x to reduce false
6969 if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' &&
6971 || (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{'))
6978 /* Handle run-time code blocks. We will already have compiled any direct
6979 * or indirect literal code blocks. Now, take the pattern 'pat' and make a
6980 * copy of it, but with any literal code blocks blanked out and
6981 * appropriate chars escaped; then feed it into
6983 * eval "qr'modified_pattern'"
6987 * a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
6991 * qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
6993 * After eval_sv()-ing that, grab any new code blocks from the returned qr
6994 * and merge them with any code blocks of the original regexp.
6996 * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
6997 * instead, just save the qr and return FALSE; this tells our caller that
6998 * the original pattern needs upgrading to utf8.
7002 S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
7003 char *pat, STRLEN plen)
7007 GET_RE_DEBUG_FLAGS_DECL;
7009 if (pRExC_state->runtime_code_qr) {
7010 /* this is the second time we've been called; this should
7011 * only happen if the main pattern got upgraded to utf8
7012 * during compilation; re-use the qr we compiled first time
7013 * round (which should be utf8 too)
7015 qr = pRExC_state->runtime_code_qr;
7016 pRExC_state->runtime_code_qr = NULL;
7017 assert(RExC_utf8 && SvUTF8(qr));
7023 int newlen = plen + 7; /* allow for "qr''xx\0" extra chars */
7027 /* determine how many extra chars we need for ' and \ escaping */
7028 for (s = 0; s < plen; s++) {
7029 if (pat[s] == '\'' || pat[s] == '\\')
7033 Newx(newpat, newlen, char);
7035 *p++ = 'q'; *p++ = 'r'; *p++ = '\'';
7037 for (s = 0; s < plen; s++) {
7038 if ( pRExC_state->code_blocks
7039 && n < pRExC_state->code_blocks->count
7040 && s == pRExC_state->code_blocks->cb[n].start)
7042 /* blank out literal code block so that they aren't
7043 * recompiled: eg change from/to:
7053 assert(pat[s] == '(');
7054 assert(pat[s+1] == '?');
7058 while (s < pRExC_state->code_blocks->cb[n].end) {
7066 if (pat[s] == '\'' || pat[s] == '\\')
7071 if (pRExC_state->pm_flags & RXf_PMf_EXTENDED) {
7073 if (pRExC_state->pm_flags & RXf_PMf_EXTENDED_MORE) {
7079 Perl_re_printf( aTHX_
7080 "%sre-parsing pattern for runtime code:%s %s\n",
7081 PL_colors[4], PL_colors[5], newpat);
7084 sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
7090 PUSHSTACKi(PERLSI_REQUIRE);
7091 /* G_RE_REPARSING causes the toker to collapse \\ into \ when
7092 * parsing qr''; normally only q'' does this. It also alters
7094 eval_sv(sv, G_SCALAR|G_RE_REPARSING);
7095 SvREFCNT_dec_NN(sv);
7100 SV * const errsv = ERRSV;
7101 if (SvTRUE_NN(errsv))
7102 /* use croak_sv ? */
7103 Perl_croak_nocontext("%" SVf, SVfARG(errsv));
7105 assert(SvROK(qr_ref));
7107 assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
7108 /* the leaving below frees the tmp qr_ref.
7109 * Give qr a life of its own */
7117 if (!RExC_utf8 && SvUTF8(qr)) {
7118 /* first time through; the pattern got upgraded; save the
7119 * qr for the next time through */
7120 assert(!pRExC_state->runtime_code_qr);
7121 pRExC_state->runtime_code_qr = qr;
7126 /* extract any code blocks within the returned qr// */
7129 /* merge the main (r1) and run-time (r2) code blocks into one */
7131 RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
7132 struct reg_code_block *new_block, *dst;
7133 RExC_state_t * const r1 = pRExC_state; /* convenient alias */
7137 if (!r2->code_blocks || !r2->code_blocks->count) /* we guessed wrong */
7139 SvREFCNT_dec_NN(qr);
7143 if (!r1->code_blocks)
7144 r1->code_blocks = S_alloc_code_blocks(aTHX_ 0);
7146 r1c = r1->code_blocks->count;
7147 r2c = r2->code_blocks->count;
7149 Newx(new_block, r1c + r2c, struct reg_code_block);
7153 while (i1 < r1c || i2 < r2c) {
7154 struct reg_code_block *src;
7158 src = &r2->code_blocks->cb[i2++];
7162 src = &r1->code_blocks->cb[i1++];
7163 else if ( r1->code_blocks->cb[i1].start
7164 < r2->code_blocks->cb[i2].start)
7166 src = &r1->code_blocks->cb[i1++];
7167 assert(src->end < r2->code_blocks->cb[i2].start);
7170 assert( r1->code_blocks->cb[i1].start
7171 > r2->code_blocks->cb[i2].start);
7172 src = &r2->code_blocks->cb[i2++];
7174 assert(src->end < r1->code_blocks->cb[i1].start);
7177 assert(pat[src->start] == '(');
7178 assert(pat[src->end] == ')');
7179 dst->start = src->start;
7180 dst->end = src->end;
7181 dst->block = src->block;
7182 dst->src_regex = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
7186 r1->code_blocks->count += r2c;
7187 Safefree(r1->code_blocks->cb);
7188 r1->code_blocks->cb = new_block;
7191 SvREFCNT_dec_NN(qr);
7197 S_setup_longest(pTHX_ RExC_state_t *pRExC_state,
7198 struct reg_substr_datum *rsd,
7199 struct scan_data_substrs *sub,
7200 STRLEN longest_length)
7202 /* This is the common code for setting up the floating and fixed length
7203 * string data extracted from Perl_re_op_compile() below. Returns a boolean
7204 * as to whether succeeded or not */
7208 bool eol = cBOOL(sub->flags & SF_BEFORE_EOL);
7209 bool meol = cBOOL(sub->flags & SF_BEFORE_MEOL);
7211 if (! (longest_length
7212 || (eol /* Can't have SEOL and MULTI */
7213 && (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
7215 /* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */
7216 || (RExC_seen & REG_UNFOLDED_MULTI_SEEN))
7221 /* copy the information about the longest from the reg_scan_data
7222 over to the program. */
7223 if (SvUTF8(sub->str)) {
7225 rsd->utf8_substr = sub->str;
7227 rsd->substr = sub->str;
7228 rsd->utf8_substr = NULL;
7230 /* end_shift is how many chars that must be matched that
7231 follow this item. We calculate it ahead of time as once the
7232 lookbehind offset is added in we lose the ability to correctly
7234 ml = sub->minlenp ? *(sub->minlenp) : (SSize_t)longest_length;
7235 rsd->end_shift = ml - sub->min_offset
7237 /* XXX SvTAIL is always false here - did you mean FBMcf_TAIL
7239 + (SvTAIL(sub->str) != 0)
7243 t = (eol/* Can't have SEOL and MULTI */
7244 && (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
7245 fbm_compile(sub->str, t ? FBMcf_TAIL : 0);
7251 S_set_regex_pv(pTHX_ RExC_state_t *pRExC_state, REGEXP *Rx)
7253 /* Calculates and sets in the compiled pattern 'Rx' the string to compile,
7254 * properly wrapped with the right modifiers */
7256 bool has_p = ((RExC_rx->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
7257 bool has_charset = RExC_utf8 || (get_regex_charset(RExC_rx->extflags)
7258 != REGEX_DEPENDS_CHARSET);
7260 /* The caret is output if there are any defaults: if not all the STD
7261 * flags are set, or if no character set specifier is needed */
7263 (((RExC_rx->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
7265 bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN)
7266 == REG_RUN_ON_COMMENT_SEEN);
7267 U8 reganch = (U8)((RExC_rx->extflags & RXf_PMf_STD_PMMOD)
7268 >> RXf_PMf_STD_PMMOD_SHIFT);
7269 const char *fptr = STD_PAT_MODS; /*"msixxn"*/
7271 STRLEN pat_len = RExC_precomp_end - RExC_precomp;
7273 /* We output all the necessary flags; we never output a minus, as all
7274 * those are defaults, so are
7275 * covered by the caret */
7276 const STRLEN wraplen = pat_len + has_p + has_runon
7277 + has_default /* If needs a caret */
7278 + PL_bitcount[reganch] /* 1 char for each set standard flag */
7280 /* If needs a character set specifier */
7281 + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
7282 + (sizeof("(?:)") - 1);
7284 PERL_ARGS_ASSERT_SET_REGEX_PV;
7286 /* make sure PL_bitcount bounds not exceeded */
7287 assert(sizeof(STD_PAT_MODS) <= 8);
7289 p = sv_grow(MUTABLE_SV(Rx), wraplen + 1); /* +1 for the ending NUL */
7292 SvFLAGS(Rx) |= SVf_UTF8;
7295 /* If a default, cover it using the caret */
7297 *p++= DEFAULT_PAT_MOD;
7303 name = get_regex_charset_name(RExC_rx->extflags, &len);
7304 if (strEQ(name, DEPENDS_PAT_MODS)) { /* /d under UTF-8 => /u */
7306 name = UNICODE_PAT_MODS;
7307 len = sizeof(UNICODE_PAT_MODS) - 1;
7309 Copy(name, p, len, char);
7313 *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
7316 while((ch = *fptr++)) {
7324 Copy(RExC_precomp, p, pat_len, char);
7325 assert ((RX_WRAPPED(Rx) - p) < 16);
7326 RExC_rx->pre_prefix = p - RX_WRAPPED(Rx);
7329 /* Adding a trailing \n causes this to compile properly:
7330 my $R = qr / A B C # D E/x; /($R)/
7331 Otherwise the parens are considered part of the comment */
7336 SvCUR_set(Rx, p - RX_WRAPPED(Rx));
7340 * Perl_re_op_compile - the perl internal RE engine's function to compile a
7341 * regular expression into internal code.
7342 * The pattern may be passed either as:
7343 * a list of SVs (patternp plus pat_count)
7344 * a list of OPs (expr)
7345 * If both are passed, the SV list is used, but the OP list indicates
7346 * which SVs are actually pre-compiled code blocks
7348 * The SVs in the list have magic and qr overloading applied to them (and
7349 * the list may be modified in-place with replacement SVs in the latter
7352 * If the pattern hasn't changed from old_re, then old_re will be
7355 * eng is the current engine. If that engine has an op_comp method, then
7356 * handle directly (i.e. we assume that op_comp was us); otherwise, just
7357 * do the initial concatenation of arguments and pass on to the external
7360 * If is_bare_re is not null, set it to a boolean indicating whether the
7361 * arg list reduced (after overloading) to a single bare regex which has
7362 * been returned (i.e. /$qr/).
7364 * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
7366 * pm_flags contains the PMf_* flags, typically based on those from the
7367 * pm_flags field of the related PMOP. Currently we're only interested in
7368 * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL.
7370 * For many years this code had an initial sizing pass that calculated
7371 * (sometimes incorrectly, leading to security holes) the size needed for the
7372 * compiled pattern. That was changed by commit
7373 * 7c932d07cab18751bfc7515b4320436273a459e2 in 5.29, which reallocs the size, a
7374 * node at a time, as parsing goes along. Patches welcome to fix any obsolete
7375 * references to this sizing pass.
7377 * Now, an initial crude guess as to the size needed is made, based on the
7378 * length of the pattern. Patches welcome to improve that guess. That amount
7379 * of space is malloc'd and then immediately freed, and then clawed back node
7380 * by node. This design is to minimze, to the extent possible, memory churn
7381 * when doing the the reallocs.
7383 * A separate parentheses counting pass may be needed in some cases.
7384 * (Previously the sizing pass did this.) Patches welcome to reduce the number
7387 * The existence of a sizing pass necessitated design decisions that are no
7388 * longer needed. There are potential areas of simplification.
7390 * Beware that the optimization-preparation code in here knows about some
7391 * of the structure of the compiled regexp. [I'll say.]
7395 Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
7396 OP *expr, const regexp_engine* eng, REGEXP *old_re,
7397 bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags)
7400 REGEXP *Rx; /* Capital 'R' means points to a REGEXP */
7408 SV** new_patternp = patternp;
7410 /* these are all flags - maybe they should be turned
7411 * into a single int with different bit masks */
7412 I32 sawlookahead = 0;
7417 regex_charset initial_charset = get_regex_charset(orig_rx_flags);
7419 bool runtime_code = 0;
7421 RExC_state_t RExC_state;
7422 RExC_state_t * const pRExC_state = &RExC_state;
7423 #ifdef TRIE_STUDY_OPT
7425 RExC_state_t copyRExC_state;
7427 GET_RE_DEBUG_FLAGS_DECL;
7429 PERL_ARGS_ASSERT_RE_OP_COMPILE;
7431 DEBUG_r(if (!PL_colorset) reginitcolors());
7434 pRExC_state->warn_text = NULL;
7435 pRExC_state->unlexed_names = NULL;
7436 pRExC_state->code_blocks = NULL;
7439 *is_bare_re = FALSE;
7441 if (expr && (expr->op_type == OP_LIST ||
7442 (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
7443 /* allocate code_blocks if needed */
7447 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o))
7448 if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
7449 ncode++; /* count of DO blocks */
7452 pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode);
7456 /* compile-time pattern with just OP_CONSTs and DO blocks */
7461 /* find how many CONSTs there are */
7464 if (expr->op_type == OP_CONST)
7467 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7468 if (o->op_type == OP_CONST)
7472 /* fake up an SV array */
7474 assert(!new_patternp);
7475 Newx(new_patternp, n, SV*);
7476 SAVEFREEPV(new_patternp);
7480 if (expr->op_type == OP_CONST)
7481 new_patternp[n] = cSVOPx_sv(expr);
7483 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7484 if (o->op_type == OP_CONST)
7485 new_patternp[n++] = cSVOPo_sv;
7490 DEBUG_PARSE_r(Perl_re_printf( aTHX_
7491 "Assembling pattern from %d elements%s\n", pat_count,
7492 orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7494 /* set expr to the first arg op */
7496 if (pRExC_state->code_blocks && pRExC_state->code_blocks->count
7497 && expr->op_type != OP_CONST)
7499 expr = cLISTOPx(expr)->op_first;
7500 assert( expr->op_type == OP_PUSHMARK
7501 || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)
7502 || expr->op_type == OP_PADRANGE);
7503 expr = OpSIBLING(expr);
7506 pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,
7507 expr, &recompile, NULL);
7509 /* handle bare (possibly after overloading) regex: foo =~ $re */
7514 if (SvTYPE(re) == SVt_REGEXP) {
7518 DEBUG_PARSE_r(Perl_re_printf( aTHX_
7519 "Precompiled pattern%s\n",
7520 orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7526 exp = SvPV_nomg(pat, plen);
7528 if (!eng->op_comp) {
7529 if ((SvUTF8(pat) && IN_BYTES)
7530 || SvGMAGICAL(pat) || SvAMAGIC(pat))
7532 /* make a temporary copy; either to convert to bytes,
7533 * or to avoid repeating get-magic / overloaded stringify */
7534 pat = newSVpvn_flags(exp, plen, SVs_TEMP |
7535 (IN_BYTES ? 0 : SvUTF8(pat)));
7537 return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
7540 /* ignore the utf8ness if the pattern is 0 length */
7541 RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
7542 RExC_uni_semantics = 0;
7543 RExC_contains_locale = 0;
7544 RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT);
7545 RExC_in_script_run = 0;
7546 RExC_study_started = 0;
7547 pRExC_state->runtime_code_qr = NULL;
7548 RExC_frame_head= NULL;
7549 RExC_frame_last= NULL;
7550 RExC_frame_count= 0;
7551 RExC_latest_warn_offset = 0;
7552 RExC_use_BRANCHJ = 0;
7553 RExC_total_parens = 0;
7554 RExC_open_parens = NULL;
7555 RExC_close_parens = NULL;
7556 RExC_paren_names = NULL;
7558 RExC_seen_d_op = FALSE;
7560 RExC_paren_name_list = NULL;
7564 RExC_mysv1= sv_newmortal();
7565 RExC_mysv2= sv_newmortal();
7569 SV *dsv= sv_newmortal();
7570 RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7571 Perl_re_printf( aTHX_ "%sCompiling REx%s %s\n",
7572 PL_colors[4], PL_colors[5], s);
7575 /* we jump here if we have to recompile, e.g., from upgrading the pattern
7578 if ((pm_flags & PMf_USE_RE_EVAL)
7579 /* this second condition covers the non-regex literal case,
7580 * i.e. $foo =~ '(?{})'. */
7581 || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))
7583 runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);
7586 /* return old regex if pattern hasn't changed */
7587 /* XXX: note in the below we have to check the flags as well as the
7590 * Things get a touch tricky as we have to compare the utf8 flag
7591 * independently from the compile flags. */
7595 && !!RX_UTF8(old_re) == !!RExC_utf8
7596 && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )
7597 && RX_PRECOMP(old_re)
7598 && RX_PRELEN(old_re) == plen
7599 && memEQ(RX_PRECOMP(old_re), exp, plen)
7600 && !runtime_code /* with runtime code, always recompile */ )
7603 SV *dsv= sv_newmortal();
7604 RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7605 Perl_re_printf( aTHX_ "%sSkipping recompilation of unchanged REx%s %s\n",
7606 PL_colors[4], PL_colors[5], s);
7611 /* Allocate the pattern's SV */
7612 RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP);
7613 RExC_rx = ReANY(Rx);
7614 if ( RExC_rx == NULL )
7615 FAIL("Regexp out of space");
7617 rx_flags = orig_rx_flags;
7619 if ( (UTF || RExC_uni_semantics)
7620 && initial_charset == REGEX_DEPENDS_CHARSET)
7623 /* Set to use unicode semantics if the pattern is in utf8 and has the
7624 * 'depends' charset specified, as it means unicode when utf8 */
7625 set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
7626 RExC_uni_semantics = 1;
7629 RExC_pm_flags = pm_flags;
7632 assert(TAINTING_get || !TAINT_get);
7634 Perl_croak(aTHX_ "Eval-group in insecure regular expression");
7636 if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
7637 /* whoops, we have a non-utf8 pattern, whilst run-time code
7638 * got compiled as utf8. Try again with a utf8 pattern */
7639 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7640 pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7644 assert(!pRExC_state->runtime_code_qr);
7650 RExC_in_lookbehind = 0;
7651 RExC_in_lookahead = 0;
7652 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
7653 RExC_recode_x_to_native = 0;
7654 RExC_in_multi_char_class = 0;
7656 RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp;
7657 RExC_precomp_end = RExC_end = exp + plen;
7659 RExC_whilem_seen = 0;
7661 RExC_recurse = NULL;
7662 RExC_study_chunk_recursed = NULL;
7663 RExC_study_chunk_recursed_bytes= 0;
7664 RExC_recurse_count = 0;
7665 pRExC_state->code_index = 0;
7667 /* Initialize the string in the compiled pattern. This is so that there is
7668 * something to output if necessary */
7669 set_regex_pv(pRExC_state, Rx);
7672 Perl_re_printf( aTHX_
7673 "Starting parse and generation\n");
7675 RExC_lastparse=NULL;
7678 /* Allocate space and zero-initialize. Note, the two step process
7679 of zeroing when in debug mode, thus anything assigned has to
7680 happen after that */
7683 /* On the first pass of the parse, we guess how big this will be. Then
7684 * we grow in one operation to that amount and then give it back. As
7685 * we go along, we re-allocate what we need.
7687 * XXX Currently the guess is essentially that the pattern will be an
7688 * EXACT node with one byte input, one byte output. This is crude, and
7689 * better heuristics are welcome.
7691 * On any subsequent passes, we guess what we actually computed in the
7692 * latest earlier pass. Such a pass probably didn't complete so is
7693 * missing stuff. We could improve those guesses by knowing where the
7694 * parse stopped, and use the length so far plus apply the above
7695 * assumption to what's left. */
7696 RExC_size = STR_SZ(RExC_end - RExC_start);
7699 Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal);
7700 if ( RExC_rxi == NULL )
7701 FAIL("Regexp out of space");
7703 Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char);
7704 RXi_SET( RExC_rx, RExC_rxi );
7706 /* We start from 0 (over from 0 in the case this is a reparse. The first
7707 * node parsed will give back any excess memory we have allocated so far).
7711 /* non-zero initialization begins here */
7712 RExC_rx->engine= eng;
7713 RExC_rx->extflags = rx_flags;
7714 RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;
7716 if (pm_flags & PMf_IS_QR) {
7717 RExC_rxi->code_blocks = pRExC_state->code_blocks;
7718 if (RExC_rxi->code_blocks) {
7719 RExC_rxi->code_blocks->refcnt++;
7723 RExC_rx->intflags = 0;
7725 RExC_flags = rx_flags; /* don't let top level (?i) bleed */
7728 /* This NUL is guaranteed because the pattern comes from an SV*, and the sv
7729 * code makes sure the final byte is an uncounted NUL. But should this
7730 * ever not be the case, lots of things could read beyond the end of the
7731 * buffer: loops like
7732 * while(isFOO(*RExC_parse)) RExC_parse++;
7733 * strchr(RExC_parse, "foo");
7734 * etc. So it is worth noting. */
7735 assert(*RExC_end == '\0');
7739 RExC_parens_buf_size = 0;
7740 RExC_emit_start = RExC_rxi->program;
7741 pRExC_state->code_index = 0;
7743 *((char*) RExC_emit_start) = (char) REG_MAGIC;
7747 if (reg(pRExC_state, 0, &flags, 1)) {
7749 /* Success!, But we may need to redo the parse knowing how many parens
7750 * there actually are */
7751 if (IN_PARENS_PASS) {
7752 flags |= RESTART_PARSE;
7755 /* We have that number in RExC_npar */
7756 RExC_total_parens = RExC_npar;
7758 else if (! MUST_RESTART(flags)) {
7760 Perl_croak(aTHX_ "panic: reg returned failure to re_op_compile, flags=%#" UVxf, (UV) flags);
7763 /* Here, we either have success, or we have to redo the parse for some reason */
7764 if (MUST_RESTART(flags)) {
7766 /* It's possible to write a regexp in ascii that represents Unicode
7767 codepoints outside of the byte range, such as via \x{100}. If we
7768 detect such a sequence we have to convert the entire pattern to utf8
7769 and then recompile, as our sizing calculation will have been based
7770 on 1 byte == 1 character, but we will need to use utf8 to encode
7771 at least some part of the pattern, and therefore must convert the whole
7774 if (flags & NEED_UTF8) {
7776 /* We have stored the offset of the final warning output so far.
7777 * That must be adjusted. Any variant characters between the start
7778 * of the pattern and this warning count for 2 bytes in the final,
7779 * so just add them again */
7780 if (UNLIKELY(RExC_latest_warn_offset > 0)) {
7781 RExC_latest_warn_offset +=
7782 variant_under_utf8_count((U8 *) exp, (U8 *) exp
7783 + RExC_latest_warn_offset);
7785 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7786 pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7787 DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse after upgrade\n"));
7790 DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse\n"));
7793 if (ALL_PARENS_COUNTED) {
7794 /* Make enough room for all the known parens, and zero it */
7795 Renew(RExC_open_parens, RExC_total_parens, regnode_offset);
7796 Zero(RExC_open_parens, RExC_total_parens, regnode_offset);
7797 RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */
7799 Renew(RExC_close_parens, RExC_total_parens, regnode_offset);
7800 Zero(RExC_close_parens, RExC_total_parens, regnode_offset);
7802 else { /* Parse did not complete. Reinitialize the parentheses
7804 RExC_total_parens = 0;
7805 if (RExC_open_parens) {
7806 Safefree(RExC_open_parens);
7807 RExC_open_parens = NULL;
7809 if (RExC_close_parens) {
7810 Safefree(RExC_close_parens);
7811 RExC_close_parens = NULL;
7815 /* Clean up what we did in this parse */
7816 SvREFCNT_dec_NN(RExC_rx_sv);
7821 /* Here, we have successfully parsed and generated the pattern's program
7822 * for the regex engine. We are ready to finish things up and look for
7825 /* Update the string to compile, with correct modifiers, etc */
7826 set_regex_pv(pRExC_state, Rx);
7828 RExC_rx->nparens = RExC_total_parens - 1;
7830 /* Uses the upper 4 bits of the FLAGS field, so keep within that size */
7831 if (RExC_whilem_seen > 15)
7832 RExC_whilem_seen = 15;
7835 Perl_re_printf( aTHX_
7836 "Required size %" IVdf " nodes\n", (IV)RExC_size);
7838 RExC_lastparse=NULL;
7841 #ifdef RE_TRACK_PATTERN_OFFSETS
7842 DEBUG_OFFSETS_r(Perl_re_printf( aTHX_
7843 "%s %" UVuf " bytes for offset annotations.\n",
7844 RExC_offsets ? "Got" : "Couldn't get",
7845 (UV)((RExC_offsets[0] * 2 + 1))));
7846 DEBUG_OFFSETS_r(if (RExC_offsets) {
7847 const STRLEN len = RExC_offsets[0];
7849 GET_RE_DEBUG_FLAGS_DECL;
7850 Perl_re_printf( aTHX_
7851 "Offsets: [%" UVuf "]\n\t", (UV)RExC_offsets[0]);
7852 for (i = 1; i <= len; i++) {
7853 if (RExC_offsets[i*2-1] || RExC_offsets[i*2])
7854 Perl_re_printf( aTHX_ "%" UVuf ":%" UVuf "[%" UVuf "] ",
7855 (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]);
7857 Perl_re_printf( aTHX_ "\n");
7861 SetProgLen(RExC_rxi,RExC_size);
7864 DEBUG_DUMP_PRE_OPTIMIZE_r({
7865 SV * const sv = sv_newmortal();
7866 RXi_GET_DECL(RExC_rx, ri);
7868 Perl_re_printf( aTHX_ "Program before optimization:\n");
7870 (void)dumpuntil(RExC_rx, ri->program, ri->program + 1, NULL, NULL,
7875 Perl_re_printf( aTHX_ "Starting post parse optimization\n");
7878 /* XXXX To minimize changes to RE engine we always allocate
7879 3-units-long substrs field. */
7880 Newx(RExC_rx->substrs, 1, struct reg_substr_data);
7881 if (RExC_recurse_count) {
7882 Newx(RExC_recurse, RExC_recurse_count, regnode *);
7883 SAVEFREEPV(RExC_recurse);
7886 if (RExC_seen & REG_RECURSE_SEEN) {
7887 /* Note, RExC_total_parens is 1 + the number of parens in a pattern.
7888 * So its 1 if there are no parens. */
7889 RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) +
7890 ((RExC_total_parens & 0x07) != 0);
7891 Newx(RExC_study_chunk_recursed,
7892 RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
7893 SAVEFREEPV(RExC_study_chunk_recursed);
7897 RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;
7899 RExC_study_chunk_recursed_count= 0;
7901 Zero(RExC_rx->substrs, 1, struct reg_substr_data);
7902 if (RExC_study_chunk_recursed) {
7903 Zero(RExC_study_chunk_recursed,
7904 RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
7908 #ifdef TRIE_STUDY_OPT
7910 StructCopy(&zero_scan_data, &data, scan_data_t);
7911 copyRExC_state = RExC_state;
7914 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n"));
7916 RExC_state = copyRExC_state;
7917 if (seen & REG_TOP_LEVEL_BRANCHES_SEEN)
7918 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
7920 RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN;
7921 StructCopy(&zero_scan_data, &data, scan_data_t);
7924 StructCopy(&zero_scan_data, &data, scan_data_t);
7927 /* Dig out information for optimizations. */
7928 RExC_rx->extflags = RExC_flags; /* was pm_op */
7929 /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
7932 SvUTF8_on(Rx); /* Unicode in it? */
7933 RExC_rxi->regstclass = NULL;
7934 if (RExC_naughty >= TOO_NAUGHTY) /* Probably an expensive pattern. */
7935 RExC_rx->intflags |= PREGf_NAUGHTY;
7936 scan = RExC_rxi->program + 1; /* First BRANCH. */
7938 /* testing for BRANCH here tells us whether there is "must appear"
7939 data in the pattern. If there is then we can use it for optimisations */
7940 if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice.
7943 STRLEN longest_length[2];
7944 regnode_ssc ch_class; /* pointed to by data */
7946 SSize_t last_close = 0; /* pointed to by data */
7947 regnode *first= scan;
7948 regnode *first_next= regnext(first);
7952 * Skip introductions and multiplicators >= 1
7953 * so that we can extract the 'meat' of the pattern that must
7954 * match in the large if() sequence following.
7955 * NOTE that EXACT is NOT covered here, as it is normally
7956 * picked up by the optimiser separately.
7958 * This is unfortunate as the optimiser isnt handling lookahead
7959 * properly currently.
7962 while ((OP(first) == OPEN && (sawopen = 1)) ||
7963 /* An OR of *one* alternative - should not happen now. */
7964 (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
7965 /* for now we can't handle lookbehind IFMATCH*/
7966 (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
7967 (OP(first) == PLUS) ||
7968 (OP(first) == MINMOD) ||
7969 /* An {n,m} with n>0 */
7970 (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
7971 (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
7974 * the only op that could be a regnode is PLUS, all the rest
7975 * will be regnode_1 or regnode_2.
7977 * (yves doesn't think this is true)
7979 if (OP(first) == PLUS)
7982 if (OP(first) == MINMOD)
7984 first += regarglen[OP(first)];
7986 first = NEXTOPER(first);
7987 first_next= regnext(first);
7990 /* Starting-point info. */
7992 DEBUG_PEEP("first:", first, 0, 0);
7993 /* Ignore EXACT as we deal with it later. */
7994 if (PL_regkind[OP(first)] == EXACT) {
7995 if ( OP(first) == EXACT
7996 || OP(first) == LEXACT
7997 || OP(first) == EXACT_REQ8
7998 || OP(first) == LEXACT_REQ8
7999 || OP(first) == EXACTL)
8001 NOOP; /* Empty, get anchored substr later. */
8004 RExC_rxi->regstclass = first;
8007 else if (PL_regkind[OP(first)] == TRIE &&
8008 ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0)
8010 /* this can happen only on restudy */
8011 RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0);
8014 else if (REGNODE_SIMPLE(OP(first)))
8015 RExC_rxi->regstclass = first;
8016 else if (PL_regkind[OP(first)] == BOUND ||
8017 PL_regkind[OP(first)] == NBOUND)
8018 RExC_rxi->regstclass = first;
8019 else if (PL_regkind[OP(first)] == BOL) {
8020 RExC_rx->intflags |= (OP(first) == MBOL
8023 first = NEXTOPER(first);
8026 else if (OP(first) == GPOS) {
8027 RExC_rx->intflags |= PREGf_ANCH_GPOS;
8028 first = NEXTOPER(first);
8031 else if ((!sawopen || !RExC_sawback) &&
8033 (OP(first) == STAR &&
8034 PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
8035 !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks)
8037 /* turn .* into ^.* with an implied $*=1 */
8039 (OP(NEXTOPER(first)) == REG_ANY)
8042 RExC_rx->intflags |= (type | PREGf_IMPLICIT);
8043 first = NEXTOPER(first);
8046 if (sawplus && !sawminmod && !sawlookahead
8047 && (!sawopen || !RExC_sawback)
8048 && !pRExC_state->code_blocks) /* May examine pos and $& */
8049 /* x+ must match at the 1st pos of run of x's */
8050 RExC_rx->intflags |= PREGf_SKIP;
8052 /* Scan is after the zeroth branch, first is atomic matcher. */
8053 #ifdef TRIE_STUDY_OPT
8056 Perl_re_printf( aTHX_ "first at %" IVdf "\n",
8057 (IV)(first - scan + 1))
8061 Perl_re_printf( aTHX_ "first at %" IVdf "\n",
8062 (IV)(first - scan + 1))
8068 * If there's something expensive in the r.e., find the
8069 * longest literal string that must appear and make it the
8070 * regmust. Resolve ties in favor of later strings, since
8071 * the regstart check works with the beginning of the r.e.
8072 * and avoiding duplication strengthens checking. Not a
8073 * strong reason, but sufficient in the absence of others.
8074 * [Now we resolve ties in favor of the earlier string if
8075 * it happens that c_offset_min has been invalidated, since the
8076 * earlier string may buy us something the later one won't.]
8079 data.substrs[0].str = newSVpvs("");
8080 data.substrs[1].str = newSVpvs("");
8081 data.last_found = newSVpvs("");
8082 data.cur_is_floating = 0; /* initially any found substring is fixed */
8083 ENTER_with_name("study_chunk");
8084 SAVEFREESV(data.substrs[0].str);
8085 SAVEFREESV(data.substrs[1].str);
8086 SAVEFREESV(data.last_found);
8088 if (!RExC_rxi->regstclass) {
8089 ssc_init(pRExC_state, &ch_class);
8090 data.start_class = &ch_class;
8091 stclass_flag = SCF_DO_STCLASS_AND;
8092 } else /* XXXX Check for BOUND? */
8094 data.last_closep = &last_close;
8098 * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/
8099 * (NO top level branches)
8101 minlen = study_chunk(pRExC_state, &first, &minlen, &fake,
8102 scan + RExC_size, /* Up to end */
8104 SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
8105 | (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
8109 CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
8112 if ( RExC_total_parens == 1 && !data.cur_is_floating
8113 && data.last_start_min == 0 && data.last_end > 0
8114 && !RExC_seen_zerolen
8115 && !(RExC_seen & REG_VERBARG_SEEN)
8116 && !(RExC_seen & REG_GPOS_SEEN)
8118 RExC_rx->extflags |= RXf_CHECK_ALL;
8120 scan_commit(pRExC_state, &data,&minlen, 0);
8123 /* XXX this is done in reverse order because that's the way the
8124 * code was before it was parameterised. Don't know whether it
8125 * actually needs doing in reverse order. DAPM */
8126 for (i = 1; i >= 0; i--) {
8127 longest_length[i] = CHR_SVLEN(data.substrs[i].str);
8130 && SvCUR(data.substrs[0].str) /* ok to leave SvCUR */
8131 && data.substrs[0].min_offset
8132 == data.substrs[1].min_offset
8133 && SvCUR(data.substrs[0].str)
8134 == SvCUR(data.substrs[1].str)
8136 && S_setup_longest (aTHX_ pRExC_state,
8137 &(RExC_rx->substrs->data[i]),
8141 RExC_rx->substrs->data[i].min_offset =
8142 data.substrs[i].min_offset - data.substrs[i].lookbehind;
8144 RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset;
8145 /* Don't offset infinity */
8146 if (data.substrs[i].max_offset < SSize_t_MAX)
8147 RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind;
8148 SvREFCNT_inc_simple_void_NN(data.substrs[i].str);
8151 RExC_rx->substrs->data[i].substr = NULL;
8152 RExC_rx->substrs->data[i].utf8_substr = NULL;
8153 longest_length[i] = 0;
8157 LEAVE_with_name("study_chunk");
8159 if (RExC_rxi->regstclass
8160 && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY))
8161 RExC_rxi->regstclass = NULL;
8163 if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr)
8164 || RExC_rx->substrs->data[0].min_offset)
8166 && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8167 && is_ssc_worth_it(pRExC_state, data.start_class))
8169 const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8171 ssc_finalize(pRExC_state, data.start_class);
8173 Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8174 StructCopy(data.start_class,
8175 (regnode_ssc*)RExC_rxi->data->data[n],
8177 RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8178 RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
8179 DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
8180 regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8181 Perl_re_printf( aTHX_
8182 "synthetic stclass \"%s\".\n",
8183 SvPVX_const(sv));});
8184 data.start_class = NULL;
8187 /* A temporary algorithm prefers floated substr to fixed one of
8188 * same length to dig more info. */
8189 i = (longest_length[0] <= longest_length[1]);
8190 RExC_rx->substrs->check_ix = i;
8191 RExC_rx->check_end_shift = RExC_rx->substrs->data[i].end_shift;
8192 RExC_rx->check_substr = RExC_rx->substrs->data[i].substr;
8193 RExC_rx->check_utf8 = RExC_rx->substrs->data[i].utf8_substr;
8194 RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset;
8195 RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset;
8196 if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS)))
8197 RExC_rx->intflags |= PREGf_NOSCAN;
8199 if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) {
8200 RExC_rx->extflags |= RXf_USE_INTUIT;
8201 if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8))
8202 RExC_rx->extflags |= RXf_INTUIT_TAIL;
8205 /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
8206 if ( (STRLEN)minlen < longest_length[1] )
8207 minlen= longest_length[1];
8208 if ( (STRLEN)minlen < longest_length[0] )
8209 minlen= longest_length[0];
8213 /* Several toplevels. Best we can is to set minlen. */
8215 regnode_ssc ch_class;
8216 SSize_t last_close = 0;
8218 DEBUG_PARSE_r(Perl_re_printf( aTHX_ "\nMulti Top Level\n"));
8220 scan = RExC_rxi->program + 1;
8221 ssc_init(pRExC_state, &ch_class);
8222 data.start_class = &ch_class;
8223 data.last_closep = &last_close;
8227 * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../
8228 * (patterns WITH top level branches)
8230 minlen = study_chunk(pRExC_state,
8231 &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL,
8232 SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied
8233 ? SCF_TRIE_DOING_RESTUDY
8237 CHECK_RESTUDY_GOTO_butfirst(NOOP);
8239 RExC_rx->check_substr = NULL;
8240 RExC_rx->check_utf8 = NULL;
8241 RExC_rx->substrs->data[0].substr = NULL;
8242 RExC_rx->substrs->data[0].utf8_substr = NULL;
8243 RExC_rx->substrs->data[1].substr = NULL;
8244 RExC_rx->substrs->data[1].utf8_substr = NULL;
8246 if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8247 && is_ssc_worth_it(pRExC_state, data.start_class))
8249 const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8251 ssc_finalize(pRExC_state, data.start_class);
8253 Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8254 StructCopy(data.start_class,
8255 (regnode_ssc*)RExC_rxi->data->data[n],
8257 RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8258 RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
8259 DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
8260 regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8261 Perl_re_printf( aTHX_
8262 "synthetic stclass \"%s\".\n",
8263 SvPVX_const(sv));});
8264 data.start_class = NULL;
8268 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) {
8269 RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN;
8270 RExC_rx->maxlen = REG_INFTY;
8273 RExC_rx->maxlen = RExC_maxlen;
8276 /* Guard against an embedded (?=) or (?<=) with a longer minlen than
8277 the "real" pattern. */
8279 Perl_re_printf( aTHX_ "minlen: %" IVdf " RExC_rx->minlen:%" IVdf " maxlen:%" IVdf "\n",
8280 (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen);
8282 RExC_rx->minlenret = minlen;
8283 if (RExC_rx->minlen < minlen)
8284 RExC_rx->minlen = minlen;
8286 if (RExC_seen & REG_RECURSE_SEEN ) {
8287 RExC_rx->intflags |= PREGf_RECURSE_SEEN;
8288 Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *);
8290 if (RExC_seen & REG_GPOS_SEEN)
8291 RExC_rx->intflags |= PREGf_GPOS_SEEN;
8292 if (RExC_seen & REG_LOOKBEHIND_SEEN)
8293 RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the
8295 if (pRExC_state->code_blocks)
8296 RExC_rx->extflags |= RXf_EVAL_SEEN;
8297 if (RExC_seen & REG_VERBARG_SEEN)
8299 RExC_rx->intflags |= PREGf_VERBARG_SEEN;
8300 RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */
8302 if (RExC_seen & REG_CUTGROUP_SEEN)
8303 RExC_rx->intflags |= PREGf_CUTGROUP_SEEN;
8304 if (pm_flags & PMf_USE_RE_EVAL)
8305 RExC_rx->intflags |= PREGf_USE_RE_EVAL;
8306 if (RExC_paren_names)
8307 RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
8309 RXp_PAREN_NAMES(RExC_rx) = NULL;
8311 /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED
8312 * so it can be used in pp.c */
8313 if (RExC_rx->intflags & PREGf_ANCH)
8314 RExC_rx->extflags |= RXf_IS_ANCHORED;
8318 /* this is used to identify "special" patterns that might result
8319 * in Perl NOT calling the regex engine and instead doing the match "itself",
8320 * particularly special cases in split//. By having the regex compiler
8321 * do this pattern matching at a regop level (instead of by inspecting the pattern)
8322 * we avoid weird issues with equivalent patterns resulting in different behavior,
8323 * AND we allow non Perl engines to get the same optimizations by the setting the
8324 * flags appropriately - Yves */
8325 regnode *first = RExC_rxi->program + 1;
8327 regnode *next = regnext(first);
8330 if (PL_regkind[fop] == NOTHING && nop == END)
8331 RExC_rx->extflags |= RXf_NULL;
8332 else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END)
8333 /* when fop is SBOL first->flags will be true only when it was
8334 * produced by parsing /\A/, and not when parsing /^/. This is
8335 * very important for the split code as there we want to
8336 * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m.
8337 * See rt #122761 for more details. -- Yves */
8338 RExC_rx->extflags |= RXf_START_ONLY;
8339 else if (fop == PLUS
8340 && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE
8342 RExC_rx->extflags |= RXf_WHITE;
8343 else if ( RExC_rx->extflags & RXf_SPLIT
8344 && ( fop == EXACT || fop == LEXACT
8345 || fop == EXACT_REQ8 || fop == LEXACT_REQ8
8347 && STR_LEN(first) == 1
8348 && *(STRING(first)) == ' '
8350 RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
8354 if (RExC_contains_locale) {
8355 RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED;
8359 if (RExC_paren_names) {
8360 RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a"));
8361 RExC_rxi->data->data[RExC_rxi->name_list_idx]
8362 = (void*)SvREFCNT_inc(RExC_paren_name_list);
8365 RExC_rxi->name_list_idx = 0;
8367 while ( RExC_recurse_count > 0 ) {
8368 const regnode *scan = RExC_recurse[ --RExC_recurse_count ];
8370 * This data structure is set up in study_chunk() and is used
8371 * to calculate the distance between a GOSUB regopcode and
8372 * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's)
8375 * If for some reason someone writes code that optimises
8376 * away a GOSUB opcode then the assert should be changed to
8377 * an if(scan) to guard the ARG2L_SET() - Yves
8380 assert(scan && OP(scan) == GOSUB);
8381 ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan));
8384 Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair);
8385 /* assume we don't need to swap parens around before we match */
8387 Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n",
8388 (unsigned long)RExC_study_chunk_recursed_count);
8392 Perl_re_printf( aTHX_ "Final program:\n");
8396 if (RExC_open_parens) {
8397 Safefree(RExC_open_parens);
8398 RExC_open_parens = NULL;
8400 if (RExC_close_parens) {
8401 Safefree(RExC_close_parens);
8402 RExC_close_parens = NULL;
8406 /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated
8407 * by setting the regexp SV to readonly-only instead. If the
8408 * pattern's been recompiled, the USEDness should remain. */
8409 if (old_re && SvREADONLY(old_re))
8417 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
8420 PERL_ARGS_ASSERT_REG_NAMED_BUFF;
8422 PERL_UNUSED_ARG(value);
8424 if (flags & RXapif_FETCH) {
8425 return reg_named_buff_fetch(rx, key, flags);
8426 } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
8427 Perl_croak_no_modify();
8429 } else if (flags & RXapif_EXISTS) {
8430 return reg_named_buff_exists(rx, key, flags)
8433 } else if (flags & RXapif_REGNAMES) {
8434 return reg_named_buff_all(rx, flags);
8435 } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
8436 return reg_named_buff_scalar(rx, flags);
8438 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
8444 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
8447 PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
8448 PERL_UNUSED_ARG(lastkey);
8450 if (flags & RXapif_FIRSTKEY)
8451 return reg_named_buff_firstkey(rx, flags);
8452 else if (flags & RXapif_NEXTKEY)
8453 return reg_named_buff_nextkey(rx, flags);
8455 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter",
8462 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
8466 struct regexp *const rx = ReANY(r);
8468 PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
8470 if (rx && RXp_PAREN_NAMES(rx)) {
8471 HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
8474 SV* sv_dat=HeVAL(he_str);
8475 I32 *nums=(I32*)SvPVX(sv_dat);
8476 AV * const retarray = (flags & RXapif_ALL) ? newAV() : NULL;
8477 for ( i=0; i<SvIVX(sv_dat); i++ ) {
8478 if ((I32)(rx->nparens) >= nums[i]
8479 && rx->offs[nums[i]].start != -1
8480 && rx->offs[nums[i]].end != -1)
8483 CALLREG_NUMBUF_FETCH(r, nums[i], ret);
8488 ret = newSVsv(&PL_sv_undef);
8491 av_push(retarray, ret);
8494 return newRV_noinc(MUTABLE_SV(retarray));
8501 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
8504 struct regexp *const rx = ReANY(r);
8506 PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
8508 if (rx && RXp_PAREN_NAMES(rx)) {
8509 if (flags & RXapif_ALL) {
8510 return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
8512 SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
8514 SvREFCNT_dec_NN(sv);
8526 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
8528 struct regexp *const rx = ReANY(r);
8530 PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
8532 if ( rx && RXp_PAREN_NAMES(rx) ) {
8533 (void)hv_iterinit(RXp_PAREN_NAMES(rx));
8535 return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
8542 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
8544 struct regexp *const rx = ReANY(r);
8545 GET_RE_DEBUG_FLAGS_DECL;
8547 PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
8549 if (rx && RXp_PAREN_NAMES(rx)) {
8550 HV *hv = RXp_PAREN_NAMES(rx);
8552 while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8555 SV* sv_dat = HeVAL(temphe);
8556 I32 *nums = (I32*)SvPVX(sv_dat);
8557 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8558 if ((I32)(rx->lastparen) >= nums[i] &&
8559 rx->offs[nums[i]].start != -1 &&
8560 rx->offs[nums[i]].end != -1)
8566 if (parno || flags & RXapif_ALL) {
8567 return newSVhek(HeKEY_hek(temphe));
8575 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
8580 struct regexp *const rx = ReANY(r);
8582 PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
8584 if (rx && RXp_PAREN_NAMES(rx)) {
8585 if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
8586 return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
8587 } else if (flags & RXapif_ONE) {
8588 ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
8589 av = MUTABLE_AV(SvRV(ret));
8590 length = av_tindex(av);
8591 SvREFCNT_dec_NN(ret);
8592 return newSViv(length + 1);
8594 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar",
8599 return &PL_sv_undef;
8603 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
8605 struct regexp *const rx = ReANY(r);
8608 PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
8610 if (rx && RXp_PAREN_NAMES(rx)) {
8611 HV *hv= RXp_PAREN_NAMES(rx);
8613 (void)hv_iterinit(hv);
8614 while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8617 SV* sv_dat = HeVAL(temphe);
8618 I32 *nums = (I32*)SvPVX(sv_dat);
8619 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8620 if ((I32)(rx->lastparen) >= nums[i] &&
8621 rx->offs[nums[i]].start != -1 &&
8622 rx->offs[nums[i]].end != -1)
8628 if (parno || flags & RXapif_ALL) {
8629 av_push(av, newSVhek(HeKEY_hek(temphe)));
8634 return newRV_noinc(MUTABLE_SV(av));
8638 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
8641 struct regexp *const rx = ReANY(r);
8647 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
8649 if ( n == RX_BUFF_IDX_CARET_PREMATCH
8650 || n == RX_BUFF_IDX_CARET_FULLMATCH
8651 || n == RX_BUFF_IDX_CARET_POSTMATCH
8654 bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8656 /* on something like
8659 * the KEEPCOPY is set on the PMOP rather than the regex */
8660 if (PL_curpm && r == PM_GETRE(PL_curpm))
8661 keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8670 if (n == RX_BUFF_IDX_CARET_FULLMATCH)
8671 /* no need to distinguish between them any more */
8672 n = RX_BUFF_IDX_FULLMATCH;
8674 if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
8675 && rx->offs[0].start != -1)
8677 /* $`, ${^PREMATCH} */
8678 i = rx->offs[0].start;
8682 if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
8683 && rx->offs[0].end != -1)
8685 /* $', ${^POSTMATCH} */
8686 s = rx->subbeg - rx->suboffset + rx->offs[0].end;
8687 i = rx->sublen + rx->suboffset - rx->offs[0].end;
8690 if (inRANGE(n, 0, (I32)rx->nparens) &&
8691 (s1 = rx->offs[n].start) != -1 &&
8692 (t1 = rx->offs[n].end) != -1)
8694 /* $&, ${^MATCH}, $1 ... */
8696 s = rx->subbeg + s1 - rx->suboffset;
8701 assert(s >= rx->subbeg);
8702 assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) );
8704 #ifdef NO_TAINT_SUPPORT
8705 sv_setpvn(sv, s, i);
8707 const int oldtainted = TAINT_get;
8709 sv_setpvn(sv, s, i);
8710 TAINT_set(oldtainted);
8712 if (RXp_MATCH_UTF8(rx))
8717 if (RXp_MATCH_TAINTED(rx)) {
8718 if (SvTYPE(sv) >= SVt_PVMG) {
8719 MAGIC* const mg = SvMAGIC(sv);
8722 SvMAGIC_set(sv, mg->mg_moremagic);
8724 if ((mgt = SvMAGIC(sv))) {
8725 mg->mg_moremagic = mgt;
8726 SvMAGIC_set(sv, mg);
8743 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
8744 SV const * const value)
8746 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
8748 PERL_UNUSED_ARG(rx);
8749 PERL_UNUSED_ARG(paren);
8750 PERL_UNUSED_ARG(value);
8753 Perl_croak_no_modify();
8757 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
8760 struct regexp *const rx = ReANY(r);
8764 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
8766 if ( paren == RX_BUFF_IDX_CARET_PREMATCH
8767 || paren == RX_BUFF_IDX_CARET_FULLMATCH
8768 || paren == RX_BUFF_IDX_CARET_POSTMATCH
8771 bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8773 /* on something like
8776 * the KEEPCOPY is set on the PMOP rather than the regex */
8777 if (PL_curpm && r == PM_GETRE(PL_curpm))
8778 keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8784 /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
8786 case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
8787 case RX_BUFF_IDX_PREMATCH: /* $` */
8788 if (rx->offs[0].start != -1) {
8789 i = rx->offs[0].start;
8798 case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
8799 case RX_BUFF_IDX_POSTMATCH: /* $' */
8800 if (rx->offs[0].end != -1) {
8801 i = rx->sublen - rx->offs[0].end;
8803 s1 = rx->offs[0].end;
8810 default: /* $& / ${^MATCH}, $1, $2, ... */
8811 if (paren <= (I32)rx->nparens &&
8812 (s1 = rx->offs[paren].start) != -1 &&
8813 (t1 = rx->offs[paren].end) != -1)
8819 if (ckWARN(WARN_UNINITIALIZED))
8820 report_uninit((const SV *)sv);
8825 if (i > 0 && RXp_MATCH_UTF8(rx)) {
8826 const char * const s = rx->subbeg - rx->suboffset + s1;
8831 if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
8838 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
8840 PERL_ARGS_ASSERT_REG_QR_PACKAGE;
8841 PERL_UNUSED_ARG(rx);
8845 return newSVpvs("Regexp");
8848 /* Scans the name of a named buffer from the pattern.
8849 * If flags is REG_RSN_RETURN_NULL returns null.
8850 * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
8851 * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
8852 * to the parsed name as looked up in the RExC_paren_names hash.
8853 * If there is an error throws a vFAIL().. type exception.
8856 #define REG_RSN_RETURN_NULL 0
8857 #define REG_RSN_RETURN_NAME 1
8858 #define REG_RSN_RETURN_DATA 2
8861 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
8863 char *name_start = RExC_parse;
8866 PERL_ARGS_ASSERT_REG_SCAN_NAME;
8868 assert (RExC_parse <= RExC_end);
8869 if (RExC_parse == RExC_end) NOOP;
8870 else if (isIDFIRST_lazy_if_safe(RExC_parse, RExC_end, UTF)) {
8871 /* Note that the code here assumes well-formed UTF-8. Skip IDFIRST by
8872 * using do...while */
8875 RExC_parse += UTF8SKIP(RExC_parse);
8876 } while ( RExC_parse < RExC_end
8877 && isWORDCHAR_utf8_safe((U8*)RExC_parse, (U8*) RExC_end));
8881 } while (RExC_parse < RExC_end && isWORDCHAR(*RExC_parse));
8883 RExC_parse++; /* so the <- from the vFAIL is after the offending
8885 vFAIL("Group name must start with a non-digit word character");
8887 sv_name = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
8888 SVs_TEMP | (UTF ? SVf_UTF8 : 0));
8889 if ( flags == REG_RSN_RETURN_NAME)
8891 else if (flags==REG_RSN_RETURN_DATA) {
8894 if ( ! sv_name ) /* should not happen*/
8895 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
8896 if (RExC_paren_names)
8897 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
8899 sv_dat = HeVAL(he_str);
8900 if ( ! sv_dat ) { /* Didn't find group */
8902 /* It might be a forward reference; we can't fail until we
8903 * know, by completing the parse to get all the groups, and
8905 if (ALL_PARENS_COUNTED) {
8906 vFAIL("Reference to nonexistent named group");
8909 REQUIRE_PARENS_PASS;
8915 Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
8916 (unsigned long) flags);
8919 #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
8920 if (RExC_lastparse!=RExC_parse) { \
8921 Perl_re_printf( aTHX_ "%s", \
8922 Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse, \
8923 RExC_end - RExC_parse, 16, \
8925 PERL_PV_ESCAPE_UNI_DETECT | \
8926 PERL_PV_PRETTY_ELLIPSES | \
8927 PERL_PV_PRETTY_LTGT | \
8928 PERL_PV_ESCAPE_RE | \
8929 PERL_PV_PRETTY_EXACTSIZE \
8933 Perl_re_printf( aTHX_ "%16s",""); \
8935 if (RExC_lastnum!=RExC_emit) \
8936 Perl_re_printf( aTHX_ "|%4d", RExC_emit); \
8938 Perl_re_printf( aTHX_ "|%4s",""); \
8939 Perl_re_printf( aTHX_ "|%*s%-4s", \
8940 (int)((depth*2)), "", \
8943 RExC_lastnum=RExC_emit; \
8944 RExC_lastparse=RExC_parse; \
8949 #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
8950 DEBUG_PARSE_MSG((funcname)); \
8951 Perl_re_printf( aTHX_ "%4s","\n"); \
8953 #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({\
8954 DEBUG_PARSE_MSG((funcname)); \
8955 Perl_re_printf( aTHX_ fmt "\n",args); \
8958 /* This section of code defines the inversion list object and its methods. The
8959 * interfaces are highly subject to change, so as much as possible is static to
8960 * this file. An inversion list is here implemented as a malloc'd C UV array
8961 * as an SVt_INVLIST scalar.
8963 * An inversion list for Unicode is an array of code points, sorted by ordinal
8964 * number. Each element gives the code point that begins a range that extends
8965 * up-to but not including the code point given by the next element. The final
8966 * element gives the first code point of a range that extends to the platform's
8967 * infinity. The even-numbered elements (invlist[0], invlist[2], invlist[4],
8968 * ...) give ranges whose code points are all in the inversion list. We say
8969 * that those ranges are in the set. The odd-numbered elements give ranges
8970 * whose code points are not in the inversion list, and hence not in the set.
8971 * Thus, element [0] is the first code point in the list. Element [1]
8972 * is the first code point beyond that not in the list; and element [2] is the
8973 * first code point beyond that that is in the list. In other words, the first
8974 * range is invlist[0]..(invlist[1]-1), and all code points in that range are
8975 * in the inversion list. The second range is invlist[1]..(invlist[2]-1), and
8976 * all code points in that range are not in the inversion list. The third
8977 * range invlist[2]..(invlist[3]-1) gives code points that are in the inversion
8978 * list, and so forth. Thus every element whose index is divisible by two
8979 * gives the beginning of a range that is in the list, and every element whose
8980 * index is not divisible by two gives the beginning of a range not in the
8981 * list. If the final element's index is divisible by two, the inversion list
8982 * extends to the platform's infinity; otherwise the highest code point in the
8983 * inversion list is the contents of that element minus 1.
8985 * A range that contains just a single code point N will look like
8987 * invlist[i+1] == N+1
8989 * If N is UV_MAX (the highest representable code point on the machine), N+1 is
8990 * impossible to represent, so element [i+1] is omitted. The single element
8992 * invlist[0] == UV_MAX
8993 * contains just UV_MAX, but is interpreted as matching to infinity.
8995 * Taking the complement (inverting) an inversion list is quite simple, if the
8996 * first element is 0, remove it; otherwise add a 0 element at the beginning.
8997 * This implementation reserves an element at the beginning of each inversion
8998 * list to always contain 0; there is an additional flag in the header which
8999 * indicates if the list begins at the 0, or is offset to begin at the next
9000 * element. This means that the inversion list can be inverted without any
9001 * copying; just flip the flag.
9003 * More about inversion lists can be found in "Unicode Demystified"
9004 * Chapter 13 by Richard Gillam, published by Addison-Wesley.
9006 * The inversion list data structure is currently implemented as an SV pointing
9007 * to an array of UVs that the SV thinks are bytes. This allows us to have an
9008 * array of UV whose memory management is automatically handled by the existing
9009 * facilities for SV's.
9011 * Some of the methods should always be private to the implementation, and some
9012 * should eventually be made public */
9014 /* The header definitions are in F<invlist_inline.h> */
9016 #ifndef PERL_IN_XSUB_RE
9018 PERL_STATIC_INLINE UV*
9019 S__invlist_array_init(SV* const invlist, const bool will_have_0)
9021 /* Returns a pointer to the first element in the inversion list's array.
9022 * This is called upon initialization of an inversion list. Where the
9023 * array begins depends on whether the list has the code point U+0000 in it
9024 * or not. The other parameter tells it whether the code that follows this
9025 * call is about to put a 0 in the inversion list or not. The first
9026 * element is either the element reserved for 0, if TRUE, or the element
9027 * after it, if FALSE */
9029 bool* offset = get_invlist_offset_addr(invlist);
9030 UV* zero_addr = (UV *) SvPVX(invlist);
9032 PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
9035 assert(! _invlist_len(invlist));
9039 /* 1^1 = 0; 1^0 = 1 */
9040 *offset = 1 ^ will_have_0;
9041 return zero_addr + *offset;
9045 S_invlist_replace_list_destroys_src(pTHX_ SV * dest, SV * src)
9047 /* Replaces the inversion list in 'dest' with the one from 'src'. It
9048 * steals the list from 'src', so 'src' is made to have a NULL list. This
9049 * is similar to what SvSetMagicSV() would do, if it were implemented on
9050 * inversion lists, though this routine avoids a copy */
9052 const UV src_len = _invlist_len(src);
9053 const bool src_offset = *get_invlist_offset_addr(src);
9054 const STRLEN src_byte_len = SvLEN(src);
9055 char * array = SvPVX(src);
9057 const int oldtainted = TAINT_get;
9059 PERL_ARGS_ASSERT_INVLIST_REPLACE_LIST_DESTROYS_SRC;
9061 assert(is_invlist(src));
9062 assert(is_invlist(dest));
9063 assert(! invlist_is_iterating(src));
9064 assert(SvCUR(src) == 0 || SvCUR(src) < SvLEN(src));
9066 /* Make sure it ends in the right place with a NUL, as our inversion list
9067 * manipulations aren't careful to keep this true, but sv_usepvn_flags()
9069 array[src_byte_len - 1] = '\0';
9071 TAINT_NOT; /* Otherwise it breaks */
9072 sv_usepvn_flags(dest,
9076 /* This flag is documented to cause a copy to be avoided */
9077 SV_HAS_TRAILING_NUL);
9078 TAINT_set(oldtainted);
9083 /* Finish up copying over the other fields in an inversion list */
9084 *get_invlist_offset_addr(dest) = src_offset;
9085 invlist_set_len(dest, src_len, src_offset);
9086 *get_invlist_previous_index_addr(dest) = 0;
9087 invlist_iterfinish(dest);
9090 PERL_STATIC_INLINE IV*
9091 S_get_invlist_previous_index_addr(SV* invlist)
9093 /* Return the address of the IV that is reserved to hold the cached index
9095 PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
9097 assert(is_invlist(invlist));
9099 return &(((XINVLIST*) SvANY(invlist))->prev_index);
9102 PERL_STATIC_INLINE IV
9103 S_invlist_previous_index(SV* const invlist)
9105 /* Returns cached index of previous search */
9107 PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
9109 return *get_invlist_previous_index_addr(invlist);
9112 PERL_STATIC_INLINE void
9113 S_invlist_set_previous_index(SV* const invlist, const IV index)
9115 /* Caches <index> for later retrieval */
9117 PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
9119 assert(index == 0 || index < (int) _invlist_len(invlist));
9121 *get_invlist_previous_index_addr(invlist) = index;
9124 PERL_STATIC_INLINE void
9125 S_invlist_trim(SV* invlist)
9127 /* Free the not currently-being-used space in an inversion list */
9129 /* But don't free up the space needed for the 0 UV that is always at the
9130 * beginning of the list, nor the trailing NUL */
9131 const UV min_size = TO_INTERNAL_SIZE(1) + 1;
9133 PERL_ARGS_ASSERT_INVLIST_TRIM;
9135 assert(is_invlist(invlist));
9137 SvPV_renew(invlist, MAX(min_size, SvCUR(invlist) + 1));
9140 PERL_STATIC_INLINE void
9141 S_invlist_clear(pTHX_ SV* invlist) /* Empty the inversion list */
9143 PERL_ARGS_ASSERT_INVLIST_CLEAR;
9145 assert(is_invlist(invlist));
9147 invlist_set_len(invlist, 0, 0);
9148 invlist_trim(invlist);
9151 #endif /* ifndef PERL_IN_XSUB_RE */
9153 PERL_STATIC_INLINE bool
9154 S_invlist_is_iterating(SV* const invlist)
9156 PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
9158 return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX;
9161 #ifndef PERL_IN_XSUB_RE
9163 PERL_STATIC_INLINE UV
9164 S_invlist_max(SV* const invlist)
9166 /* Returns the maximum number of elements storable in the inversion list's
9167 * array, without having to realloc() */
9169 PERL_ARGS_ASSERT_INVLIST_MAX;
9171 assert(is_invlist(invlist));
9173 /* Assumes worst case, in which the 0 element is not counted in the
9174 * inversion list, so subtracts 1 for that */
9175 return SvLEN(invlist) == 0 /* This happens under _new_invlist_C_array */
9176 ? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1
9177 : FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1;
9181 S_initialize_invlist_guts(pTHX_ SV* invlist, const Size_t initial_size)
9183 PERL_ARGS_ASSERT_INITIALIZE_INVLIST_GUTS;
9185 /* First 1 is in case the zero element isn't in the list; second 1 is for
9187 SvGROW(invlist, TO_INTERNAL_SIZE(initial_size + 1) + 1);
9188 invlist_set_len(invlist, 0, 0);
9190 /* Force iterinit() to be used to get iteration to work */
9191 invlist_iterfinish(invlist);
9193 *get_invlist_previous_index_addr(invlist) = 0;
9194 SvPOK_on(invlist); /* This allows B to extract the PV */
9198 Perl__new_invlist(pTHX_ IV initial_size)
9201 /* Return a pointer to a newly constructed inversion list, with enough
9202 * space to store 'initial_size' elements. If that number is negative, a
9203 * system default is used instead */
9207 if (initial_size < 0) {
9211 new_list = newSV_type(SVt_INVLIST);
9212 initialize_invlist_guts(new_list, initial_size);
9218 Perl__new_invlist_C_array(pTHX_ const UV* const list)
9220 /* Return a pointer to a newly constructed inversion list, initialized to
9221 * point to <list>, which has to be in the exact correct inversion list
9222 * form, including internal fields. Thus this is a dangerous routine that
9223 * should not be used in the wrong hands. The passed in 'list' contains
9224 * several header fields at the beginning that are not part of the
9225 * inversion list body proper */
9227 const STRLEN length = (STRLEN) list[0];
9228 const UV version_id = list[1];
9229 const bool offset = cBOOL(list[2]);
9230 #define HEADER_LENGTH 3
9231 /* If any of the above changes in any way, you must change HEADER_LENGTH
9232 * (if appropriate) and regenerate INVLIST_VERSION_ID by running
9233 * perl -E 'say int(rand 2**31-1)'
9235 #define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and
9236 data structure type, so that one being
9237 passed in can be validated to be an
9238 inversion list of the correct vintage.
9241 SV* invlist = newSV_type(SVt_INVLIST);
9243 PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
9245 if (version_id != INVLIST_VERSION_ID) {
9246 Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
9249 /* The generated array passed in includes header elements that aren't part
9250 * of the list proper, so start it just after them */
9251 SvPV_set(invlist, (char *) (list + HEADER_LENGTH));
9253 SvLEN_set(invlist, 0); /* Means we own the contents, and the system
9254 shouldn't touch it */
9256 *(get_invlist_offset_addr(invlist)) = offset;
9258 /* The 'length' passed to us is the physical number of elements in the
9259 * inversion list. But if there is an offset the logical number is one
9261 invlist_set_len(invlist, length - offset, offset);
9263 invlist_set_previous_index(invlist, 0);
9265 /* Initialize the iteration pointer. */
9266 invlist_iterfinish(invlist);
9268 SvREADONLY_on(invlist);
9275 S__append_range_to_invlist(pTHX_ SV* const invlist,
9276 const UV start, const UV end)
9278 /* Subject to change or removal. Append the range from 'start' to 'end' at
9279 * the end of the inversion list. The range must be above any existing
9283 UV max = invlist_max(invlist);
9284 UV len = _invlist_len(invlist);
9287 PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
9289 if (len == 0) { /* Empty lists must be initialized */
9290 offset = start != 0;
9291 array = _invlist_array_init(invlist, ! offset);
9294 /* Here, the existing list is non-empty. The current max entry in the
9295 * list is generally the first value not in the set, except when the
9296 * set extends to the end of permissible values, in which case it is
9297 * the first entry in that final set, and so this call is an attempt to
9298 * append out-of-order */
9300 UV final_element = len - 1;
9301 array = invlist_array(invlist);
9302 if ( array[final_element] > start
9303 || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
9305 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",
9306 array[final_element], start,
9307 ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
9310 /* Here, it is a legal append. If the new range begins 1 above the end
9311 * of the range below it, it is extending the range below it, so the
9312 * new first value not in the set is one greater than the newly
9313 * extended range. */
9314 offset = *get_invlist_offset_addr(invlist);
9315 if (array[final_element] == start) {
9316 if (end != UV_MAX) {
9317 array[final_element] = end + 1;
9320 /* But if the end is the maximum representable on the machine,
9321 * assume that infinity was actually what was meant. Just let
9322 * the range that this would extend to have no end */
9323 invlist_set_len(invlist, len - 1, offset);
9329 /* Here the new range doesn't extend any existing set. Add it */
9331 len += 2; /* Includes an element each for the start and end of range */
9333 /* If wll overflow the existing space, extend, which may cause the array to
9336 invlist_extend(invlist, len);
9338 /* Have to set len here to avoid assert failure in invlist_array() */
9339 invlist_set_len(invlist, len, offset);
9341 array = invlist_array(invlist);
9344 invlist_set_len(invlist, len, offset);
9347 /* The next item on the list starts the range, the one after that is
9348 * one past the new range. */
9349 array[len - 2] = start;
9350 if (end != UV_MAX) {
9351 array[len - 1] = end + 1;
9354 /* But if the end is the maximum representable on the machine, just let
9355 * the range have no end */
9356 invlist_set_len(invlist, len - 1, offset);
9361 Perl__invlist_search(SV* const invlist, const UV cp)
9363 /* Searches the inversion list for the entry that contains the input code
9364 * point <cp>. If <cp> is not in the list, -1 is returned. Otherwise, the
9365 * return value is the index into the list's array of the range that
9366 * contains <cp>, that is, 'i' such that
9367 * array[i] <= cp < array[i+1]
9372 IV high = _invlist_len(invlist);
9373 const IV highest_element = high - 1;
9376 PERL_ARGS_ASSERT__INVLIST_SEARCH;
9378 /* If list is empty, return failure. */
9383 /* (We can't get the array unless we know the list is non-empty) */
9384 array = invlist_array(invlist);
9386 mid = invlist_previous_index(invlist);
9388 if (mid > highest_element) {
9389 mid = highest_element;
9392 /* <mid> contains the cache of the result of the previous call to this
9393 * function (0 the first time). See if this call is for the same result,
9394 * or if it is for mid-1. This is under the theory that calls to this
9395 * function will often be for related code points that are near each other.
9396 * And benchmarks show that caching gives better results. We also test
9397 * here if the code point is within the bounds of the list. These tests
9398 * replace others that would have had to be made anyway to make sure that
9399 * the array bounds were not exceeded, and these give us extra information
9400 * at the same time */
9401 if (cp >= array[mid]) {
9402 if (cp >= array[highest_element]) {
9403 return highest_element;
9406 /* Here, array[mid] <= cp < array[highest_element]. This means that
9407 * the final element is not the answer, so can exclude it; it also
9408 * means that <mid> is not the final element, so can refer to 'mid + 1'
9410 if (cp < array[mid + 1]) {
9416 else { /* cp < aray[mid] */
9417 if (cp < array[0]) { /* Fail if outside the array */
9421 if (cp >= array[mid - 1]) {
9426 /* Binary search. What we are looking for is <i> such that
9427 * array[i] <= cp < array[i+1]
9428 * The loop below converges on the i+1. Note that there may not be an
9429 * (i+1)th element in the array, and things work nonetheless */
9430 while (low < high) {
9431 mid = (low + high) / 2;
9432 assert(mid <= highest_element);
9433 if (array[mid] <= cp) { /* cp >= array[mid] */
9436 /* We could do this extra test to exit the loop early.
9437 if (cp < array[low]) {
9442 else { /* cp < array[mid] */
9449 invlist_set_previous_index(invlist, high);
9454 Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9455 const bool complement_b, SV** output)
9457 /* Take the union of two inversion lists and point '*output' to it. On
9458 * input, '*output' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9459 * even 'a' or 'b'). If to an inversion list, the contents of the original
9460 * list will be replaced by the union. The first list, 'a', may be
9461 * NULL, in which case a copy of the second list is placed in '*output'.
9462 * If 'complement_b' is TRUE, the union is taken of the complement
9463 * (inversion) of 'b' instead of b itself.
9465 * The basis for this comes from "Unicode Demystified" Chapter 13 by
9466 * Richard Gillam, published by Addison-Wesley, and explained at some
9467 * length there. The preface says to incorporate its examples into your
9468 * code at your own risk.
9470 * The algorithm is like a merge sort. */
9472 const UV* array_a; /* a's array */
9474 UV len_a; /* length of a's array */
9477 SV* u; /* the resulting union */
9481 UV i_a = 0; /* current index into a's array */
9485 /* running count, as explained in the algorithm source book; items are
9486 * stopped accumulating and are output when the count changes to/from 0.
9487 * The count is incremented when we start a range that's in an input's set,
9488 * and decremented when we start a range that's not in a set. So this
9489 * variable can be 0, 1, or 2. When it is 0 neither input is in their set,
9490 * and hence nothing goes into the union; 1, just one of the inputs is in
9491 * its set (and its current range gets added to the union); and 2 when both
9492 * inputs are in their sets. */
9495 PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
9497 assert(*output == NULL || is_invlist(*output));
9499 len_b = _invlist_len(b);
9502 /* Here, 'b' is empty, hence it's complement is all possible code
9503 * points. So if the union includes the complement of 'b', it includes
9504 * everything, and we need not even look at 'a'. It's easiest to
9505 * create a new inversion list that matches everything. */
9507 SV* everything = _add_range_to_invlist(NULL, 0, UV_MAX);
9509 if (*output == NULL) { /* If the output didn't exist, just point it
9511 *output = everything;
9513 else { /* Otherwise, replace its contents with the new list */
9514 invlist_replace_list_destroys_src(*output, everything);
9515 SvREFCNT_dec_NN(everything);
9521 /* Here, we don't want the complement of 'b', and since 'b' is empty,
9522 * the union will come entirely from 'a'. If 'a' is NULL or empty, the
9523 * output will be empty */
9525 if (a == NULL || _invlist_len(a) == 0) {
9526 if (*output == NULL) {
9527 *output = _new_invlist(0);
9530 invlist_clear(*output);
9535 /* Here, 'a' is not empty, but 'b' is, so 'a' entirely determines the
9536 * union. We can just return a copy of 'a' if '*output' doesn't point
9537 * to an existing list */
9538 if (*output == NULL) {
9539 *output = invlist_clone(a, NULL);
9543 /* If the output is to overwrite 'a', we have a no-op, as it's
9549 /* Here, '*output' is to be overwritten by 'a' */
9550 u = invlist_clone(a, NULL);
9551 invlist_replace_list_destroys_src(*output, u);
9557 /* Here 'b' is not empty. See about 'a' */
9559 if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
9561 /* Here, 'a' is empty (and b is not). That means the union will come
9562 * entirely from 'b'. If '*output' is NULL, we can directly return a
9563 * clone of 'b'. Otherwise, we replace the contents of '*output' with
9566 SV ** dest = (*output == NULL) ? output : &u;
9567 *dest = invlist_clone(b, NULL);
9569 _invlist_invert(*dest);
9573 invlist_replace_list_destroys_src(*output, u);
9580 /* Here both lists exist and are non-empty */
9581 array_a = invlist_array(a);
9582 array_b = invlist_array(b);
9584 /* If are to take the union of 'a' with the complement of b, set it
9585 * up so are looking at b's complement. */
9588 /* To complement, we invert: if the first element is 0, remove it. To
9589 * do this, we just pretend the array starts one later */
9590 if (array_b[0] == 0) {
9596 /* But if the first element is not zero, we pretend the list starts
9597 * at the 0 that is always stored immediately before the array. */
9603 /* Size the union for the worst case: that the sets are completely
9605 u = _new_invlist(len_a + len_b);
9607 /* Will contain U+0000 if either component does */
9608 array_u = _invlist_array_init(u, ( len_a > 0 && array_a[0] == 0)
9609 || (len_b > 0 && array_b[0] == 0));
9611 /* Go through each input list item by item, stopping when have exhausted
9613 while (i_a < len_a && i_b < len_b) {
9614 UV cp; /* The element to potentially add to the union's array */
9615 bool cp_in_set; /* is it in the the input list's set or not */
9617 /* We need to take one or the other of the two inputs for the union.
9618 * Since we are merging two sorted lists, we take the smaller of the
9619 * next items. In case of a tie, we take first the one that is in its
9620 * set. If we first took the one not in its set, it would decrement
9621 * the count, possibly to 0 which would cause it to be output as ending
9622 * the range, and the next time through we would take the same number,
9623 * and output it again as beginning the next range. By doing it the
9624 * opposite way, there is no possibility that the count will be
9625 * momentarily decremented to 0, and thus the two adjoining ranges will
9626 * be seamlessly merged. (In a tie and both are in the set or both not
9627 * in the set, it doesn't matter which we take first.) */
9628 if ( array_a[i_a] < array_b[i_b]
9629 || ( array_a[i_a] == array_b[i_b]
9630 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9632 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9633 cp = array_a[i_a++];
9636 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9637 cp = array_b[i_b++];
9640 /* Here, have chosen which of the two inputs to look at. Only output
9641 * if the running count changes to/from 0, which marks the
9642 * beginning/end of a range that's in the set */
9645 array_u[i_u++] = cp;
9652 array_u[i_u++] = cp;
9658 /* The loop above increments the index into exactly one of the input lists
9659 * each iteration, and ends when either index gets to its list end. That
9660 * means the other index is lower than its end, and so something is
9661 * remaining in that one. We decrement 'count', as explained below, if
9662 * that list is in its set. (i_a and i_b each currently index the element
9663 * beyond the one we care about.) */
9664 if ( (i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9665 || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9670 /* Above we decremented 'count' if the list that had unexamined elements in
9671 * it was in its set. This has made it so that 'count' being non-zero
9672 * means there isn't anything left to output; and 'count' equal to 0 means
9673 * that what is left to output is precisely that which is left in the
9674 * non-exhausted input list.
9676 * To see why, note first that the exhausted input obviously has nothing
9677 * left to add to the union. If it was in its set at its end, that means
9678 * the set extends from here to the platform's infinity, and hence so does
9679 * the union and the non-exhausted set is irrelevant. The exhausted set
9680 * also contributed 1 to 'count'. If 'count' was 2, it got decremented to
9681 * 1, but if it was 1, the non-exhausted set wasn't in its set, and so
9682 * 'count' remains at 1. This is consistent with the decremented 'count'
9683 * != 0 meaning there's nothing left to add to the union.
9685 * But if the exhausted input wasn't in its set, it contributed 0 to
9686 * 'count', and the rest of the union will be whatever the other input is.
9687 * If 'count' was 0, neither list was in its set, and 'count' remains 0;
9688 * otherwise it gets decremented to 0. This is consistent with 'count'
9689 * == 0 meaning the remainder of the union is whatever is left in the
9690 * non-exhausted list. */
9695 IV copy_count = len_a - i_a;
9696 if (copy_count > 0) { /* The non-exhausted input is 'a' */
9697 Copy(array_a + i_a, array_u + i_u, copy_count, UV);
9699 else { /* The non-exhausted input is b */
9700 copy_count = len_b - i_b;
9701 Copy(array_b + i_b, array_u + i_u, copy_count, UV);
9703 len_u = i_u + copy_count;
9706 /* Set the result to the final length, which can change the pointer to
9707 * array_u, so re-find it. (Note that it is unlikely that this will
9708 * change, as we are shrinking the space, not enlarging it) */
9709 if (len_u != _invlist_len(u)) {
9710 invlist_set_len(u, len_u, *get_invlist_offset_addr(u));
9712 array_u = invlist_array(u);
9715 if (*output == NULL) { /* Simply return the new inversion list */
9719 /* Otherwise, overwrite the inversion list that was in '*output'. We
9720 * could instead free '*output', and then set it to 'u', but experience
9721 * has shown [perl #127392] that if the input is a mortal, we can get a
9722 * huge build-up of these during regex compilation before they get
9724 invlist_replace_list_destroys_src(*output, u);
9732 Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9733 const bool complement_b, SV** i)
9735 /* Take the intersection of two inversion lists and point '*i' to it. On
9736 * input, '*i' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9737 * even 'a' or 'b'). If to an inversion list, the contents of the original
9738 * list will be replaced by the intersection. The first list, 'a', may be
9739 * NULL, in which case '*i' will be an empty list. If 'complement_b' is
9740 * TRUE, the result will be the intersection of 'a' and the complement (or
9741 * inversion) of 'b' instead of 'b' directly.
9743 * The basis for this comes from "Unicode Demystified" Chapter 13 by
9744 * Richard Gillam, published by Addison-Wesley, and explained at some
9745 * length there. The preface says to incorporate its examples into your
9746 * code at your own risk. In fact, it had bugs
9748 * The algorithm is like a merge sort, and is essentially the same as the
9752 const UV* array_a; /* a's array */
9754 UV len_a; /* length of a's array */
9757 SV* r; /* the resulting intersection */
9761 UV i_a = 0; /* current index into a's array */
9765 /* running count of how many of the two inputs are postitioned at ranges
9766 * that are in their sets. As explained in the algorithm source book,
9767 * items are stopped accumulating and are output when the count changes
9768 * to/from 2. The count is incremented when we start a range that's in an
9769 * input's set, and decremented when we start a range that's not in a set.
9770 * Only when it is 2 are we in the intersection. */
9773 PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
9775 assert(*i == NULL || is_invlist(*i));
9777 /* Special case if either one is empty */
9778 len_a = (a == NULL) ? 0 : _invlist_len(a);
9779 if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
9780 if (len_a != 0 && complement_b) {
9782 /* Here, 'a' is not empty, therefore from the enclosing 'if', 'b'
9783 * must be empty. Here, also we are using 'b's complement, which
9784 * hence must be every possible code point. Thus the intersection
9787 if (*i == a) { /* No-op */
9792 *i = invlist_clone(a, NULL);
9796 r = invlist_clone(a, NULL);
9797 invlist_replace_list_destroys_src(*i, r);
9802 /* Here, 'a' or 'b' is empty and not using the complement of 'b'. The
9803 * intersection must be empty */
9805 *i = _new_invlist(0);
9813 /* Here both lists exist and are non-empty */
9814 array_a = invlist_array(a);
9815 array_b = invlist_array(b);
9817 /* If are to take the intersection of 'a' with the complement of b, set it
9818 * up so are looking at b's complement. */
9821 /* To complement, we invert: if the first element is 0, remove it. To
9822 * do this, we just pretend the array starts one later */
9823 if (array_b[0] == 0) {
9829 /* But if the first element is not zero, we pretend the list starts
9830 * at the 0 that is always stored immediately before the array. */
9836 /* Size the intersection for the worst case: that the intersection ends up
9837 * fragmenting everything to be completely disjoint */
9838 r= _new_invlist(len_a + len_b);
9840 /* Will contain U+0000 iff both components do */
9841 array_r = _invlist_array_init(r, len_a > 0 && array_a[0] == 0
9842 && len_b > 0 && array_b[0] == 0);
9844 /* Go through each list item by item, stopping when have exhausted one of
9846 while (i_a < len_a && i_b < len_b) {
9847 UV cp; /* The element to potentially add to the intersection's
9849 bool cp_in_set; /* Is it in the input list's set or not */
9851 /* We need to take one or the other of the two inputs for the
9852 * intersection. Since we are merging two sorted lists, we take the
9853 * smaller of the next items. In case of a tie, we take first the one
9854 * that is not in its set (a difference from the union algorithm). If
9855 * we first took the one in its set, it would increment the count,
9856 * possibly to 2 which would cause it to be output as starting a range
9857 * in the intersection, and the next time through we would take that
9858 * same number, and output it again as ending the set. By doing the
9859 * opposite of this, there is no possibility that the count will be
9860 * momentarily incremented to 2. (In a tie and both are in the set or
9861 * both not in the set, it doesn't matter which we take first.) */
9862 if ( array_a[i_a] < array_b[i_b]
9863 || ( array_a[i_a] == array_b[i_b]
9864 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9866 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9867 cp = array_a[i_a++];
9870 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9874 /* Here, have chosen which of the two inputs to look at. Only output
9875 * if the running count changes to/from 2, which marks the
9876 * beginning/end of a range that's in the intersection */
9880 array_r[i_r++] = cp;
9885 array_r[i_r++] = cp;
9892 /* The loop above increments the index into exactly one of the input lists
9893 * each iteration, and ends when either index gets to its list end. That
9894 * means the other index is lower than its end, and so something is
9895 * remaining in that one. We increment 'count', as explained below, if the
9896 * exhausted list was in its set. (i_a and i_b each currently index the
9897 * element beyond the one we care about.) */
9898 if ( (i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9899 || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9904 /* Above we incremented 'count' if the exhausted list was in its set. This
9905 * has made it so that 'count' being below 2 means there is nothing left to
9906 * output; otheriwse what's left to add to the intersection is precisely
9907 * that which is left in the non-exhausted input list.
9909 * To see why, note first that the exhausted input obviously has nothing
9910 * left to affect the intersection. If it was in its set at its end, that
9911 * means the set extends from here to the platform's infinity, and hence
9912 * anything in the non-exhausted's list will be in the intersection, and
9913 * anything not in it won't be. Hence, the rest of the intersection is
9914 * precisely what's in the non-exhausted list The exhausted set also
9915 * contributed 1 to 'count', meaning 'count' was at least 1. Incrementing
9916 * it means 'count' is now at least 2. This is consistent with the
9917 * incremented 'count' being >= 2 means to add the non-exhausted list to
9920 * But if the exhausted input wasn't in its set, it contributed 0 to
9921 * 'count', and the intersection can't include anything further; the
9922 * non-exhausted set is irrelevant. 'count' was at most 1, and doesn't get
9923 * incremented. This is consistent with 'count' being < 2 meaning nothing
9924 * further to add to the intersection. */
9925 if (count < 2) { /* Nothing left to put in the intersection. */
9928 else { /* copy the non-exhausted list, unchanged. */
9929 IV copy_count = len_a - i_a;
9930 if (copy_count > 0) { /* a is the one with stuff left */
9931 Copy(array_a + i_a, array_r + i_r, copy_count, UV);
9933 else { /* b is the one with stuff left */
9934 copy_count = len_b - i_b;
9935 Copy(array_b + i_b, array_r + i_r, copy_count, UV);
9937 len_r = i_r + copy_count;
9940 /* Set the result to the final length, which can change the pointer to
9941 * array_r, so re-find it. (Note that it is unlikely that this will
9942 * change, as we are shrinking the space, not enlarging it) */
9943 if (len_r != _invlist_len(r)) {
9944 invlist_set_len(r, len_r, *get_invlist_offset_addr(r));
9946 array_r = invlist_array(r);
9949 if (*i == NULL) { /* Simply return the calculated intersection */
9952 else { /* Otherwise, replace the existing inversion list in '*i'. We could
9953 instead free '*i', and then set it to 'r', but experience has
9954 shown [perl #127392] that if the input is a mortal, we can get a
9955 huge build-up of these during regex compilation before they get
9958 invlist_replace_list_destroys_src(*i, r);
9970 Perl__add_range_to_invlist(pTHX_ SV* invlist, UV start, UV end)
9972 /* Add the range from 'start' to 'end' inclusive to the inversion list's
9973 * set. A pointer to the inversion list is returned. This may actually be
9974 * a new list, in which case the passed in one has been destroyed. The
9975 * passed-in inversion list can be NULL, in which case a new one is created
9976 * with just the one range in it. The new list is not necessarily
9977 * NUL-terminated. Space is not freed if the inversion list shrinks as a
9978 * result of this function. The gain would not be large, and in many
9979 * cases, this is called multiple times on a single inversion list, so
9980 * anything freed may almost immediately be needed again.
9982 * This used to mostly call the 'union' routine, but that is much more
9983 * heavyweight than really needed for a single range addition */
9985 UV* array; /* The array implementing the inversion list */
9986 UV len; /* How many elements in 'array' */
9987 SSize_t i_s; /* index into the invlist array where 'start'
9989 SSize_t i_e = 0; /* And the index where 'end' should go */
9990 UV cur_highest; /* The highest code point in the inversion list
9991 upon entry to this function */
9993 /* This range becomes the whole inversion list if none already existed */
9994 if (invlist == NULL) {
9995 invlist = _new_invlist(2);
9996 _append_range_to_invlist(invlist, start, end);
10000 /* Likewise, if the inversion list is currently empty */
10001 len = _invlist_len(invlist);
10003 _append_range_to_invlist(invlist, start, end);
10007 /* Starting here, we have to know the internals of the list */
10008 array = invlist_array(invlist);
10010 /* If the new range ends higher than the current highest ... */
10011 cur_highest = invlist_highest(invlist);
10012 if (end > cur_highest) {
10014 /* If the whole range is higher, we can just append it */
10015 if (start > cur_highest) {
10016 _append_range_to_invlist(invlist, start, end);
10020 /* Otherwise, add the portion that is higher ... */
10021 _append_range_to_invlist(invlist, cur_highest + 1, end);
10023 /* ... and continue on below to handle the rest. As a result of the
10024 * above append, we know that the index of the end of the range is the
10025 * final even numbered one of the array. Recall that the final element
10026 * always starts a range that extends to infinity. If that range is in
10027 * the set (meaning the set goes from here to infinity), it will be an
10028 * even index, but if it isn't in the set, it's odd, and the final
10029 * range in the set is one less, which is even. */
10030 if (end == UV_MAX) {
10038 /* We have dealt with appending, now see about prepending. If the new
10039 * range starts lower than the current lowest ... */
10040 if (start < array[0]) {
10042 /* Adding something which has 0 in it is somewhat tricky, and uncommon.
10043 * Let the union code handle it, rather than having to know the
10044 * trickiness in two code places. */
10045 if (UNLIKELY(start == 0)) {
10048 range_invlist = _new_invlist(2);
10049 _append_range_to_invlist(range_invlist, start, end);
10051 _invlist_union(invlist, range_invlist, &invlist);
10053 SvREFCNT_dec_NN(range_invlist);
10058 /* If the whole new range comes before the first entry, and doesn't
10059 * extend it, we have to insert it as an additional range */
10060 if (end < array[0] - 1) {
10062 goto splice_in_new_range;
10065 /* Here the new range adjoins the existing first range, extending it
10069 /* And continue on below to handle the rest. We know that the index of
10070 * the beginning of the range is the first one of the array */
10073 else { /* Not prepending any part of the new range to the existing list.
10074 * Find where in the list it should go. This finds i_s, such that:
10075 * invlist[i_s] <= start < array[i_s+1]
10077 i_s = _invlist_search(invlist, start);
10080 /* At this point, any extending before the beginning of the inversion list
10081 * and/or after the end has been done. This has made it so that, in the
10082 * code below, each endpoint of the new range is either in a range that is
10083 * in the set, or is in a gap between two ranges that are. This means we
10084 * don't have to worry about exceeding the array bounds.
10086 * Find where in the list the new range ends (but we can skip this if we
10087 * have already determined what it is, or if it will be the same as i_s,
10088 * which we already have computed) */
10090 i_e = (start == end)
10092 : _invlist_search(invlist, end);
10095 /* Here generally invlist[i_e] <= end < array[i_e+1]. But if invlist[i_e]
10096 * is a range that goes to infinity there is no element at invlist[i_e+1],
10097 * so only the first relation holds. */
10099 if ( ! ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10101 /* Here, the ranges on either side of the beginning of the new range
10102 * are in the set, and this range starts in the gap between them.
10104 * The new range extends the range above it downwards if the new range
10105 * ends at or above that range's start */
10106 const bool extends_the_range_above = ( end == UV_MAX
10107 || end + 1 >= array[i_s+1]);
10109 /* The new range extends the range below it upwards if it begins just
10110 * after where that range ends */
10111 if (start == array[i_s]) {
10113 /* If the new range fills the entire gap between the other ranges,
10114 * they will get merged together. Other ranges may also get
10115 * merged, depending on how many of them the new range spans. In
10116 * the general case, we do the merge later, just once, after we
10117 * figure out how many to merge. But in the case where the new
10118 * range exactly spans just this one gap (possibly extending into
10119 * the one above), we do the merge here, and an early exit. This
10120 * is done here to avoid having to special case later. */
10121 if (i_e - i_s <= 1) {
10123 /* If i_e - i_s == 1, it means that the new range terminates
10124 * within the range above, and hence 'extends_the_range_above'
10125 * must be true. (If the range above it extends to infinity,
10126 * 'i_s+2' will be above the array's limit, but 'len-i_s-2'
10127 * will be 0, so no harm done.) */
10128 if (extends_the_range_above) {
10129 Move(array + i_s + 2, array + i_s, len - i_s - 2, UV);
10130 invlist_set_len(invlist,
10132 *(get_invlist_offset_addr(invlist)));
10136 /* Here, i_e must == i_s. We keep them in sync, as they apply
10137 * to the same range, and below we are about to decrement i_s
10142 /* Here, the new range is adjacent to the one below. (It may also
10143 * span beyond the range above, but that will get resolved later.)
10144 * Extend the range below to include this one. */
10145 array[i_s] = (end == UV_MAX) ? UV_MAX : end + 1;
10147 start = array[i_s];
10149 else if (extends_the_range_above) {
10151 /* Here the new range only extends the range above it, but not the
10152 * one below. It merges with the one above. Again, we keep i_e
10153 * and i_s in sync if they point to the same range */
10158 array[i_s] = start;
10162 /* Here, we've dealt with the new range start extending any adjoining
10165 * If the new range extends to infinity, it is now the final one,
10166 * regardless of what was there before */
10167 if (UNLIKELY(end == UV_MAX)) {
10168 invlist_set_len(invlist, i_s + 1, *(get_invlist_offset_addr(invlist)));
10172 /* If i_e started as == i_s, it has also been dealt with,
10173 * and been updated to the new i_s, which will fail the following if */
10174 if (! ELEMENT_RANGE_MATCHES_INVLIST(i_e)) {
10176 /* Here, the ranges on either side of the end of the new range are in
10177 * the set, and this range ends in the gap between them.
10179 * If this range is adjacent to (hence extends) the range above it, it
10180 * becomes part of that range; likewise if it extends the range below,
10181 * it becomes part of that range */
10182 if (end + 1 == array[i_e+1]) {
10184 array[i_e] = start;
10186 else if (start <= array[i_e]) {
10187 array[i_e] = end + 1;
10194 /* If the range fits entirely in an existing range (as possibly already
10195 * extended above), it doesn't add anything new */
10196 if (ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10200 /* Here, no part of the range is in the list. Must add it. It will
10201 * occupy 2 more slots */
10202 splice_in_new_range:
10204 invlist_extend(invlist, len + 2);
10205 array = invlist_array(invlist);
10206 /* Move the rest of the array down two slots. Don't include any
10208 Move(array + i_e + 1, array + i_e + 3, len - i_e - 1, UV);
10210 /* Do the actual splice */
10211 array[i_e+1] = start;
10212 array[i_e+2] = end + 1;
10213 invlist_set_len(invlist, len + 2, *(get_invlist_offset_addr(invlist)));
10217 /* Here the new range crossed the boundaries of a pre-existing range. The
10218 * code above has adjusted things so that both ends are in ranges that are
10219 * in the set. This means everything in between must also be in the set.
10220 * Just squash things together */
10221 Move(array + i_e + 1, array + i_s + 1, len - i_e - 1, UV);
10222 invlist_set_len(invlist,
10224 *(get_invlist_offset_addr(invlist)));
10230 Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0,
10231 UV** other_elements_ptr)
10233 /* Create and return an inversion list whose contents are to be populated
10234 * by the caller. The caller gives the number of elements (in 'size') and
10235 * the very first element ('element0'). This function will set
10236 * '*other_elements_ptr' to an array of UVs, where the remaining elements
10237 * are to be placed.
10239 * Obviously there is some trust involved that the caller will properly
10240 * fill in the other elements of the array.
10242 * (The first element needs to be passed in, as the underlying code does
10243 * things differently depending on whether it is zero or non-zero) */
10245 SV* invlist = _new_invlist(size);
10248 PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST;
10250 invlist = add_cp_to_invlist(invlist, element0);
10251 offset = *get_invlist_offset_addr(invlist);
10253 invlist_set_len(invlist, size, offset);
10254 *other_elements_ptr = invlist_array(invlist) + 1;
10260 #ifndef PERL_IN_XSUB_RE
10262 Perl__invlist_invert(pTHX_ SV* const invlist)
10264 /* Complement the input inversion list. This adds a 0 if the list didn't
10265 * have a zero; removes it otherwise. As described above, the data
10266 * structure is set up so that this is very efficient */
10268 PERL_ARGS_ASSERT__INVLIST_INVERT;
10270 assert(! invlist_is_iterating(invlist));
10272 /* The inverse of matching nothing is matching everything */
10273 if (_invlist_len(invlist) == 0) {
10274 _append_range_to_invlist(invlist, 0, UV_MAX);
10278 *get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist);
10282 Perl_invlist_clone(pTHX_ SV* const invlist, SV* new_invlist)
10284 /* Return a new inversion list that is a copy of the input one, which is
10285 * unchanged. The new list will not be mortal even if the old one was. */
10287 const STRLEN nominal_length = _invlist_len(invlist);
10288 const STRLEN physical_length = SvCUR(invlist);
10289 const bool offset = *(get_invlist_offset_addr(invlist));
10291 PERL_ARGS_ASSERT_INVLIST_CLONE;
10293 if (new_invlist == NULL) {
10294 new_invlist = _new_invlist(nominal_length);
10297 sv_upgrade(new_invlist, SVt_INVLIST);
10298 initialize_invlist_guts(new_invlist, nominal_length);
10301 *(get_invlist_offset_addr(new_invlist)) = offset;
10302 invlist_set_len(new_invlist, nominal_length, offset);
10303 Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char);
10305 return new_invlist;
10310 PERL_STATIC_INLINE UV
10311 S_invlist_lowest(SV* const invlist)
10313 /* Returns the lowest code point that matches an inversion list. This API
10314 * has an ambiguity, as it returns 0 under either the lowest is actually
10315 * 0, or if the list is empty. If this distinction matters to you, check
10316 * for emptiness before calling this function */
10318 UV len = _invlist_len(invlist);
10321 PERL_ARGS_ASSERT_INVLIST_LOWEST;
10327 array = invlist_array(invlist);
10333 S_invlist_contents(pTHX_ SV* const invlist, const bool traditional_style)
10335 /* Get the contents of an inversion list into a string SV so that they can
10336 * be printed out. If 'traditional_style' is TRUE, it uses the format
10337 * traditionally done for debug tracing; otherwise it uses a format
10338 * suitable for just copying to the output, with blanks between ranges and
10339 * a dash between range components */
10343 const char intra_range_delimiter = (traditional_style ? '\t' : '-');
10344 const char inter_range_delimiter = (traditional_style ? '\n' : ' ');
10346 if (traditional_style) {
10347 output = newSVpvs("\n");
10350 output = newSVpvs("");
10353 PERL_ARGS_ASSERT_INVLIST_CONTENTS;
10355 assert(! invlist_is_iterating(invlist));
10357 invlist_iterinit(invlist);
10358 while (invlist_iternext(invlist, &start, &end)) {
10359 if (end == UV_MAX) {
10360 Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%cINFTY%c",
10361 start, intra_range_delimiter,
10362 inter_range_delimiter);
10364 else if (end != start) {
10365 Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c%04" UVXf "%c",
10367 intra_range_delimiter,
10368 end, inter_range_delimiter);
10371 Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c",
10372 start, inter_range_delimiter);
10376 if (SvCUR(output) && ! traditional_style) {/* Get rid of trailing blank */
10377 SvCUR_set(output, SvCUR(output) - 1);
10383 #ifndef PERL_IN_XSUB_RE
10385 Perl__invlist_dump(pTHX_ PerlIO *file, I32 level,
10386 const char * const indent, SV* const invlist)
10388 /* Designed to be called only by do_sv_dump(). Dumps out the ranges of the
10389 * inversion list 'invlist' to 'file' at 'level' Each line is prefixed by
10390 * the string 'indent'. The output looks like this:
10391 [0] 0x000A .. 0x000D
10393 [4] 0x2028 .. 0x2029
10394 [6] 0x3104 .. INFTY
10395 * This means that the first range of code points matched by the list are
10396 * 0xA through 0xD; the second range contains only the single code point
10397 * 0x85, etc. An inversion list is an array of UVs. Two array elements
10398 * are used to define each range (except if the final range extends to
10399 * infinity, only a single element is needed). The array index of the
10400 * first element for the corresponding range is given in brackets. */
10405 PERL_ARGS_ASSERT__INVLIST_DUMP;
10407 if (invlist_is_iterating(invlist)) {
10408 Perl_dump_indent(aTHX_ level, file,
10409 "%sCan't dump inversion list because is in middle of iterating\n",
10414 invlist_iterinit(invlist);
10415 while (invlist_iternext(invlist, &start, &end)) {
10416 if (end == UV_MAX) {
10417 Perl_dump_indent(aTHX_ level, file,
10418 "%s[%" UVuf "] 0x%04" UVXf " .. INFTY\n",
10419 indent, (UV)count, start);
10421 else if (end != start) {
10422 Perl_dump_indent(aTHX_ level, file,
10423 "%s[%" UVuf "] 0x%04" UVXf " .. 0x%04" UVXf "\n",
10424 indent, (UV)count, start, end);
10427 Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf "\n",
10428 indent, (UV)count, start);
10436 #if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE)
10438 Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b)
10440 /* Return a boolean as to if the two passed in inversion lists are
10441 * identical. The final argument, if TRUE, says to take the complement of
10442 * the second inversion list before doing the comparison */
10444 const UV len_a = _invlist_len(a);
10445 UV len_b = _invlist_len(b);
10447 const UV* array_a = NULL;
10448 const UV* array_b = NULL;
10450 PERL_ARGS_ASSERT__INVLISTEQ;
10452 /* This code avoids accessing the arrays unless it knows the length is
10457 return ! complement_b;
10461 array_a = invlist_array(a);
10465 array_b = invlist_array(b);
10468 /* If are to compare 'a' with the complement of b, set it
10469 * up so are looking at b's complement. */
10470 if (complement_b) {
10472 /* The complement of nothing is everything, so <a> would have to have
10473 * just one element, starting at zero (ending at infinity) */
10475 return (len_a == 1 && array_a[0] == 0);
10477 if (array_b[0] == 0) {
10479 /* Otherwise, to complement, we invert. Here, the first element is
10480 * 0, just remove it. To do this, we just pretend the array starts
10488 /* But if the first element is not zero, we pretend the list starts
10489 * at the 0 that is always stored immediately before the array. */
10495 return len_a == len_b
10496 && memEQ(array_a, array_b, len_a * sizeof(array_a[0]));
10502 * As best we can, determine the characters that can match the start of
10503 * the given EXACTF-ish node. This is for use in creating ssc nodes, so there
10504 * can be false positive matches
10506 * Returns the invlist as a new SV*; it is the caller's responsibility to
10507 * call SvREFCNT_dec() when done with it.
10510 S_make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node)
10513 const U8 * s = (U8*)STRING(node);
10514 SSize_t bytelen = STR_LEN(node);
10516 /* Start out big enough for 2 separate code points */
10517 SV* invlist = _new_invlist(4);
10519 PERL_ARGS_ASSERT_MAKE_EXACTF_INVLIST;
10524 /* We punt and assume can match anything if the node begins
10525 * with a multi-character fold. Things are complicated. For
10526 * example, /ffi/i could match any of:
10527 * "\N{LATIN SMALL LIGATURE FFI}"
10528 * "\N{LATIN SMALL LIGATURE FF}I"
10529 * "F\N{LATIN SMALL LIGATURE FI}"
10530 * plus several other things; and making sure we have all the
10531 * possibilities is hard. */
10532 if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) {
10533 invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10536 /* Any Latin1 range character can potentially match any
10537 * other depending on the locale, and in Turkic locales, U+130 and
10539 if (OP(node) == EXACTFL) {
10540 _invlist_union(invlist, PL_Latin1, &invlist);
10541 invlist = add_cp_to_invlist(invlist,
10542 LATIN_SMALL_LETTER_DOTLESS_I);
10543 invlist = add_cp_to_invlist(invlist,
10544 LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10547 /* But otherwise, it matches at least itself. We can
10548 * quickly tell if it has a distinct fold, and if so,
10549 * it matches that as well */
10550 invlist = add_cp_to_invlist(invlist, uc);
10551 if (IS_IN_SOME_FOLD_L1(uc))
10552 invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]);
10555 /* Some characters match above-Latin1 ones under /i. This
10556 * is true of EXACTFL ones when the locale is UTF-8 */
10557 if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc)
10558 && (! isASCII(uc) || (OP(node) != EXACTFAA
10559 && OP(node) != EXACTFAA_NO_TRIE)))
10561 add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist);
10565 else { /* Pattern is UTF-8 */
10566 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
10567 const U8* e = s + bytelen;
10570 fc = uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
10572 /* The only code points that aren't folded in a UTF EXACTFish
10573 * node are are the problematic ones in EXACTFL nodes */
10574 if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) {
10575 /* We need to check for the possibility that this EXACTFL
10576 * node begins with a multi-char fold. Therefore we fold
10577 * the first few characters of it so that we can make that
10583 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) {
10585 *(d++) = (U8) toFOLD(*s);
10586 if (fc < 0) { /* Save the first fold */
10593 UV fold = toFOLD_utf8_safe(s, e, d, &len);
10594 if (fc < 0) { /* Save the first fold */
10602 /* And set up so the code below that looks in this folded
10603 * buffer instead of the node's string */
10608 /* When we reach here 's' points to the fold of the first
10609 * character(s) of the node; and 'e' points to far enough along
10610 * the folded string to be just past any possible multi-char
10613 * Unlike the non-UTF-8 case, the macro for determining if a
10614 * string is a multi-char fold requires all the characters to
10615 * already be folded. This is because of all the complications
10616 * if not. Note that they are folded anyway, except in EXACTFL
10617 * nodes. Like the non-UTF case above, we punt if the node
10618 * begins with a multi-char fold */
10620 if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) {
10621 invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10623 else { /* Single char fold */
10625 unsigned int first_fold;
10626 const unsigned int * remaining_folds;
10627 Size_t folds_count;
10629 /* It matches itself */
10630 invlist = add_cp_to_invlist(invlist, fc);
10632 /* ... plus all the things that fold to it, which are found in
10633 * PL_utf8_foldclosures */
10634 folds_count = _inverse_folds(fc, &first_fold,
10636 for (k = 0; k < folds_count; k++) {
10637 UV c = (k == 0) ? first_fold : remaining_folds[k-1];
10639 /* /aa doesn't allow folds between ASCII and non- */
10640 if ( (OP(node) == EXACTFAA || OP(node) == EXACTFAA_NO_TRIE)
10641 && isASCII(c) != isASCII(fc))
10646 invlist = add_cp_to_invlist(invlist, c);
10649 if (OP(node) == EXACTFL) {
10651 /* If either [iI] are present in an EXACTFL node the above code
10652 * should have added its normal case pair, but under a Turkish
10653 * locale they could match instead the case pairs from it. Add
10654 * those as potential matches as well */
10655 if (isALPHA_FOLD_EQ(fc, 'I')) {
10656 invlist = add_cp_to_invlist(invlist,
10657 LATIN_SMALL_LETTER_DOTLESS_I);
10658 invlist = add_cp_to_invlist(invlist,
10659 LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10661 else if (fc == LATIN_SMALL_LETTER_DOTLESS_I) {
10662 invlist = add_cp_to_invlist(invlist, 'I');
10664 else if (fc == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) {
10665 invlist = add_cp_to_invlist(invlist, 'i');
10674 #undef HEADER_LENGTH
10675 #undef TO_INTERNAL_SIZE
10676 #undef FROM_INTERNAL_SIZE
10677 #undef INVLIST_VERSION_ID
10679 /* End of inversion list object */
10682 S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state)
10684 /* This parses the flags that are in either the '(?foo)' or '(?foo:bar)'
10685 * constructs, and updates RExC_flags with them. On input, RExC_parse
10686 * should point to the first flag; it is updated on output to point to the
10687 * final ')' or ':'. There needs to be at least one flag, or this will
10690 /* for (?g), (?gc), and (?o) warnings; warning
10691 about (?c) will warn about (?g) -- japhy */
10693 #define WASTED_O 0x01
10694 #define WASTED_G 0x02
10695 #define WASTED_C 0x04
10696 #define WASTED_GC (WASTED_G|WASTED_C)
10697 I32 wastedflags = 0x00;
10698 U32 posflags = 0, negflags = 0;
10699 U32 *flagsp = &posflags;
10700 char has_charset_modifier = '\0';
10702 bool has_use_defaults = FALSE;
10703 const char* const seqstart = RExC_parse - 1; /* Point to the '?' */
10704 int x_mod_count = 0;
10706 PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS;
10708 /* '^' as an initial flag sets certain defaults */
10709 if (UCHARAT(RExC_parse) == '^') {
10711 has_use_defaults = TRUE;
10712 STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
10713 cs = (RExC_uni_semantics)
10714 ? REGEX_UNICODE_CHARSET
10715 : REGEX_DEPENDS_CHARSET;
10716 set_regex_charset(&RExC_flags, cs);
10719 cs = get_regex_charset(RExC_flags);
10720 if ( cs == REGEX_DEPENDS_CHARSET
10721 && RExC_uni_semantics)
10723 cs = REGEX_UNICODE_CHARSET;
10727 while (RExC_parse < RExC_end) {
10728 /* && memCHRs("iogcmsx", *RExC_parse) */
10729 /* (?g), (?gc) and (?o) are useless here
10730 and must be globally applied -- japhy */
10731 switch (*RExC_parse) {
10733 /* Code for the imsxn flags */
10734 CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count);
10736 case LOCALE_PAT_MOD:
10737 if (has_charset_modifier) {
10738 goto excess_modifier;
10740 else if (flagsp == &negflags) {
10743 cs = REGEX_LOCALE_CHARSET;
10744 has_charset_modifier = LOCALE_PAT_MOD;
10746 case UNICODE_PAT_MOD:
10747 if (has_charset_modifier) {
10748 goto excess_modifier;
10750 else if (flagsp == &negflags) {
10753 cs = REGEX_UNICODE_CHARSET;
10754 has_charset_modifier = UNICODE_PAT_MOD;
10756 case ASCII_RESTRICT_PAT_MOD:
10757 if (flagsp == &negflags) {
10760 if (has_charset_modifier) {
10761 if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
10762 goto excess_modifier;
10764 /* Doubled modifier implies more restricted */
10765 cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
10768 cs = REGEX_ASCII_RESTRICTED_CHARSET;
10770 has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
10772 case DEPENDS_PAT_MOD:
10773 if (has_use_defaults) {
10774 goto fail_modifiers;
10776 else if (flagsp == &negflags) {
10779 else if (has_charset_modifier) {
10780 goto excess_modifier;
10783 /* The dual charset means unicode semantics if the
10784 * pattern (or target, not known until runtime) are
10785 * utf8, or something in the pattern indicates unicode
10787 cs = (RExC_uni_semantics)
10788 ? REGEX_UNICODE_CHARSET
10789 : REGEX_DEPENDS_CHARSET;
10790 has_charset_modifier = DEPENDS_PAT_MOD;
10794 if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
10795 vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
10797 else if (has_charset_modifier == *(RExC_parse - 1)) {
10798 vFAIL2("Regexp modifier \"%c\" may not appear twice",
10799 *(RExC_parse - 1));
10802 vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
10804 NOT_REACHED; /*NOTREACHED*/
10807 vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"",
10808 *(RExC_parse - 1));
10809 NOT_REACHED; /*NOTREACHED*/
10810 case ONCE_PAT_MOD: /* 'o' */
10811 case GLOBAL_PAT_MOD: /* 'g' */
10812 if (ckWARN(WARN_REGEXP)) {
10813 const I32 wflagbit = *RExC_parse == 'o'
10816 if (! (wastedflags & wflagbit) ) {
10817 wastedflags |= wflagbit;
10818 /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10821 "Useless (%s%c) - %suse /%c modifier",
10822 flagsp == &negflags ? "?-" : "?",
10824 flagsp == &negflags ? "don't " : "",
10831 case CONTINUE_PAT_MOD: /* 'c' */
10832 if (ckWARN(WARN_REGEXP)) {
10833 if (! (wastedflags & WASTED_C) ) {
10834 wastedflags |= WASTED_GC;
10835 /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10838 "Useless (%sc) - %suse /gc modifier",
10839 flagsp == &negflags ? "?-" : "?",
10840 flagsp == &negflags ? "don't " : ""
10845 case KEEPCOPY_PAT_MOD: /* 'p' */
10846 if (flagsp == &negflags) {
10847 ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
10849 *flagsp |= RXf_PMf_KEEPCOPY;
10853 /* A flag is a default iff it is following a minus, so
10854 * if there is a minus, it means will be trying to
10855 * re-specify a default which is an error */
10856 if (has_use_defaults || flagsp == &negflags) {
10857 goto fail_modifiers;
10859 flagsp = &negflags;
10860 wastedflags = 0; /* reset so (?g-c) warns twice */
10866 if ((posflags & (RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE)) == RXf_PMf_EXTENDED) {
10867 negflags |= RXf_PMf_EXTENDED_MORE;
10869 RExC_flags |= posflags;
10871 if (negflags & RXf_PMf_EXTENDED) {
10872 negflags |= RXf_PMf_EXTENDED_MORE;
10874 RExC_flags &= ~negflags;
10875 set_regex_charset(&RExC_flags, cs);
10880 RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
10881 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
10882 vFAIL2utf8f("Sequence (%" UTF8f "...) not recognized",
10883 UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
10884 NOT_REACHED; /*NOTREACHED*/
10887 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10890 vFAIL("Sequence (?... not terminated");
10894 - reg - regular expression, i.e. main body or parenthesized thing
10896 * Caller must absorb opening parenthesis.
10898 * Combining parenthesis handling with the base level of regular expression
10899 * is a trifle forced, but the need to tie the tails of the branches to what
10900 * follows makes it hard to avoid.
10902 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
10904 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
10906 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
10909 PERL_STATIC_INLINE regnode_offset
10910 S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state,
10912 char * parse_start,
10916 regnode_offset ret;
10917 char* name_start = RExC_parse;
10919 SV *sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
10920 GET_RE_DEBUG_FLAGS_DECL;
10922 PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF;
10924 if (RExC_parse == name_start || *RExC_parse != ch) {
10925 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
10926 vFAIL2("Sequence %.3s... not terminated", parse_start);
10930 num = add_data( pRExC_state, STR_WITH_LEN("S"));
10931 RExC_rxi->data->data[num]=(void*)sv_dat;
10932 SvREFCNT_inc_simple_void_NN(sv_dat);
10935 ret = reganode(pRExC_state,
10938 : (ASCII_FOLD_RESTRICTED)
10940 : (AT_LEAST_UNI_SEMANTICS)
10946 *flagp |= HASWIDTH;
10948 Set_Node_Offset(REGNODE_p(ret), parse_start+1);
10949 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
10951 nextchar(pRExC_state);
10955 /* On success, returns the offset at which any next node should be placed into
10956 * the regex engine program being compiled.
10958 * Returns 0 otherwise, with *flagp set to indicate why:
10959 * TRYAGAIN at the end of (?) that only sets flags.
10960 * RESTART_PARSE if the parse needs to be restarted, or'd with
10961 * NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
10962 * Otherwise would only return 0 if regbranch() returns 0, which cannot
10964 STATIC regnode_offset
10965 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp, U32 depth)
10966 /* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter.
10967 * 2 is like 1, but indicates that nextchar() has been called to advance
10968 * RExC_parse beyond the '('. Things like '(?' are indivisible tokens, and
10969 * this flag alerts us to the need to check for that */
10971 regnode_offset ret = 0; /* Will be the head of the group. */
10973 regnode_offset lastbr;
10974 regnode_offset ender = 0;
10977 U32 oregflags = RExC_flags;
10978 bool have_branch = 0;
10980 I32 freeze_paren = 0;
10981 I32 after_freeze = 0;
10982 I32 num; /* numeric backreferences */
10983 SV * max_open; /* Max number of unclosed parens */
10985 char * parse_start = RExC_parse; /* MJD */
10986 char * const oregcomp_parse = RExC_parse;
10988 GET_RE_DEBUG_FLAGS_DECL;
10990 PERL_ARGS_ASSERT_REG;
10991 DEBUG_PARSE("reg ");
10993 max_open = get_sv(RE_COMPILE_RECURSION_LIMIT, GV_ADD);
10995 if (!SvIOK(max_open)) {
10996 sv_setiv(max_open, RE_COMPILE_RECURSION_INIT);
10998 if (depth > 4 * (UV) SvIV(max_open)) { /* We increase depth by 4 for each
11000 vFAIL("Too many nested open parens");
11003 *flagp = 0; /* Tentatively. */
11005 if (RExC_in_lookbehind) {
11006 RExC_in_lookbehind++;
11008 if (RExC_in_lookahead) {
11009 RExC_in_lookahead++;
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 if (paren == 's') {
11226 /* Here, we're starting a new regular script run */
11227 ret = reg_node(pRExC_state, SROPEN);
11228 RExC_in_script_run = 1;
11233 /* Here, we are starting an atomic script run. This is
11234 * handled by recursing to deal with the atomic portion
11235 * separately, enclosed in SROPEN ... SRCLOSE nodes */
11237 ret = reg_node(pRExC_state, SROPEN);
11239 RExC_in_script_run = 1;
11241 atomic = reg(pRExC_state, 'r', &flags, depth);
11242 if (flags & (RESTART_PARSE|NEED_UTF8)) {
11243 *flagp = flags & (RESTART_PARSE|NEED_UTF8);
11247 if (! REGTAIL(pRExC_state, ret, atomic)) {
11248 REQUIRE_BRANCHJ(flagp, 0);
11251 if (! REGTAIL(pRExC_state, atomic, reg_node(pRExC_state,
11254 REQUIRE_BRANCHJ(flagp, 0);
11257 RExC_in_script_run = 0;
11263 lookbehind_alpha_assertions:
11264 RExC_seen |= REG_LOOKBEHIND_SEEN;
11265 RExC_in_lookbehind++;
11270 RExC_seen_zerolen++;
11276 /* An empty negative lookahead assertion simply is failure */
11277 if (paren == 'A' && RExC_parse == start_arg) {
11278 ret=reganode(pRExC_state, OPFAIL, 0);
11279 nextchar(pRExC_state);
11283 RExC_parse = start_arg;
11288 "'(*%" UTF8f "' requires a terminating ':'",
11289 UTF8fARG(UTF, verb_len, start_verb));
11290 NOT_REACHED; /*NOTREACHED*/
11292 } /* End of switch */
11295 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
11297 if (has_upper || verb_len == 0) {
11299 "Unknown verb pattern '%" UTF8f "'",
11300 UTF8fARG(UTF, verb_len, start_verb));
11304 "Unknown '(*...)' construct '%" UTF8f "'",
11305 UTF8fARG(UTF, verb_len, start_verb));
11308 if ( RExC_parse == start_arg ) {
11311 if ( arg_required && !start_arg ) {
11312 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
11313 verb_len, start_verb);
11315 if (internal_argval == -1) {
11316 ret = reganode(pRExC_state, op, 0);
11318 ret = reg2Lanode(pRExC_state, op, 0, internal_argval);
11320 RExC_seen |= REG_VERBARG_SEEN;
11322 SV *sv = newSVpvn( start_arg,
11323 RExC_parse - start_arg);
11324 ARG(REGNODE_p(ret)) = add_data( pRExC_state,
11325 STR_WITH_LEN("S"));
11326 RExC_rxi->data->data[ARG(REGNODE_p(ret))]=(void*)sv;
11327 FLAGS(REGNODE_p(ret)) = 1;
11329 FLAGS(REGNODE_p(ret)) = 0;
11331 if ( internal_argval != -1 )
11332 ARG2L_SET(REGNODE_p(ret), internal_argval);
11333 nextchar(pRExC_state);
11336 else if (*RExC_parse == '?') { /* (?...) */
11337 bool is_logical = 0;
11338 const char * const seqstart = RExC_parse;
11339 const char * endptr;
11340 if (has_intervening_patws) {
11342 vFAIL("In '(?...)', the '(' and '?' must be adjacent");
11345 RExC_parse++; /* past the '?' */
11346 paren = *RExC_parse; /* might be a trailing NUL, if not
11348 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11349 if (RExC_parse > RExC_end) {
11352 ret = 0; /* For look-ahead/behind. */
11355 case 'P': /* (?P...) variants for those used to PCRE/Python */
11356 paren = *RExC_parse;
11357 if ( paren == '<') { /* (?P<...>) named capture */
11359 if (RExC_parse >= RExC_end) {
11360 vFAIL("Sequence (?P<... not terminated");
11362 goto named_capture;
11364 else if (paren == '>') { /* (?P>name) named recursion */
11366 if (RExC_parse >= RExC_end) {
11367 vFAIL("Sequence (?P>... not terminated");
11369 goto named_recursion;
11371 else if (paren == '=') { /* (?P=...) named backref */
11373 return handle_named_backref(pRExC_state, flagp,
11376 RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
11377 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11378 vFAIL3("Sequence (%.*s...) not recognized",
11379 RExC_parse-seqstart, seqstart);
11380 NOT_REACHED; /*NOTREACHED*/
11381 case '<': /* (?<...) */
11382 /* If you want to support (?<*...), first reconcile with GH #17363 */
11383 if (*RExC_parse == '!')
11385 else if (*RExC_parse != '=')
11392 case '\'': /* (?'...') */
11393 name_start = RExC_parse;
11394 svname = reg_scan_name(pRExC_state, REG_RSN_RETURN_NAME);
11395 if ( RExC_parse == name_start
11396 || RExC_parse >= RExC_end
11397 || *RExC_parse != paren)
11399 vFAIL2("Sequence (?%c... not terminated",
11400 paren=='>' ? '<' : paren);
11405 if (!svname) /* shouldn't happen */
11407 "panic: reg_scan_name returned NULL");
11408 if (!RExC_paren_names) {
11409 RExC_paren_names= newHV();
11410 sv_2mortal(MUTABLE_SV(RExC_paren_names));
11412 RExC_paren_name_list= newAV();
11413 sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
11416 he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
11418 sv_dat = HeVAL(he_str);
11420 /* croak baby croak */
11422 "panic: paren_name hash element allocation failed");
11423 } else if ( SvPOK(sv_dat) ) {
11424 /* (?|...) can mean we have dupes so scan to check
11425 its already been stored. Maybe a flag indicating
11426 we are inside such a construct would be useful,
11427 but the arrays are likely to be quite small, so
11428 for now we punt -- dmq */
11429 IV count = SvIV(sv_dat);
11430 I32 *pv = (I32*)SvPVX(sv_dat);
11432 for ( i = 0 ; i < count ; i++ ) {
11433 if ( pv[i] == RExC_npar ) {
11439 pv = (I32*)SvGROW(sv_dat,
11440 SvCUR(sv_dat) + sizeof(I32)+1);
11441 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
11442 pv[count] = RExC_npar;
11443 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
11446 (void)SvUPGRADE(sv_dat, SVt_PVNV);
11447 sv_setpvn(sv_dat, (char *)&(RExC_npar),
11450 SvIV_set(sv_dat, 1);
11453 /* Yes this does cause a memory leak in debugging Perls
11455 if (!av_store(RExC_paren_name_list,
11456 RExC_npar, SvREFCNT_inc_NN(svname)))
11457 SvREFCNT_dec_NN(svname);
11460 /*sv_dump(sv_dat);*/
11462 nextchar(pRExC_state);
11464 goto capturing_parens;
11467 RExC_seen |= REG_LOOKBEHIND_SEEN;
11468 RExC_in_lookbehind++;
11470 if (RExC_parse >= RExC_end) {
11471 vFAIL("Sequence (?... not terminated");
11473 RExC_seen_zerolen++;
11475 case '=': /* (?=...) */
11476 RExC_seen_zerolen++;
11477 RExC_in_lookahead++;
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 (! inRANGE(RExC_parse[0], '1', '9')) {
11538 vFAIL("Illegal pattern");
11540 goto parse_recursion;
11542 case '-': /* (?-1) */
11543 if (! inRANGE(RExC_parse[0], '1', '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 (ALL_PARENS_COUNTED) {
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 (ALL_PARENS_COUNTED) {
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, RExC_end);
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 if (! REGTAIL(pRExC_state, ret, eval)) {
11714 REQUIRE_BRANCHJ(flagp, 0);
11716 /* deal with the length of this later - MJD */
11719 ret = reg2Lanode(pRExC_state, EVAL, n, 0);
11720 Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1);
11721 Set_Node_Offset(REGNODE_p(ret), parse_start);
11724 case '(': /* (?(?{...})...) and (?(?=...)...) */
11727 const int DEFINE_len = sizeof("DEFINE") - 1;
11728 if ( RExC_parse < RExC_end - 1
11729 && ( ( RExC_parse[0] == '?' /* (?(?...)) */
11730 && ( RExC_parse[1] == '='
11731 || RExC_parse[1] == '!'
11732 || RExC_parse[1] == '<'
11733 || RExC_parse[1] == '{'))
11734 || ( RExC_parse[0] == '*' /* (?(*...)) */
11735 && ( memBEGINs(RExC_parse + 1,
11736 (Size_t) (RExC_end - (RExC_parse + 1)),
11738 || memBEGINs(RExC_parse + 1,
11739 (Size_t) (RExC_end - (RExC_parse + 1)),
11741 || memBEGINs(RExC_parse + 1,
11742 (Size_t) (RExC_end - (RExC_parse + 1)),
11744 || memBEGINs(RExC_parse + 1,
11745 (Size_t) (RExC_end - (RExC_parse + 1)),
11747 || memBEGINs(RExC_parse + 1,
11748 (Size_t) (RExC_end - (RExC_parse + 1)),
11749 "positive_lookahead:")
11750 || memBEGINs(RExC_parse + 1,
11751 (Size_t) (RExC_end - (RExC_parse + 1)),
11752 "positive_lookbehind:")
11753 || memBEGINs(RExC_parse + 1,
11754 (Size_t) (RExC_end - (RExC_parse + 1)),
11755 "negative_lookahead:")
11756 || memBEGINs(RExC_parse + 1,
11757 (Size_t) (RExC_end - (RExC_parse + 1)),
11758 "negative_lookbehind:"))))
11759 ) { /* Lookahead or eval. */
11761 regnode_offset tail;
11763 ret = reg_node(pRExC_state, LOGICAL);
11764 FLAGS(REGNODE_p(ret)) = 1;
11766 tail = reg(pRExC_state, 1, &flag, depth+1);
11767 RETURN_FAIL_ON_RESTART(flag, flagp);
11768 if (! REGTAIL(pRExC_state, ret, tail)) {
11769 REQUIRE_BRANCHJ(flagp, 0);
11773 else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
11774 || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
11776 char ch = RExC_parse[0] == '<' ? '>' : '\'';
11777 char *name_start= RExC_parse++;
11779 SV *sv_dat=reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
11780 if ( RExC_parse == name_start
11781 || RExC_parse >= RExC_end
11782 || *RExC_parse != ch)
11784 vFAIL2("Sequence (?(%c... not terminated",
11785 (ch == '>' ? '<' : ch));
11789 num = add_data( pRExC_state, STR_WITH_LEN("S"));
11790 RExC_rxi->data->data[num]=(void*)sv_dat;
11791 SvREFCNT_inc_simple_void_NN(sv_dat);
11793 ret = reganode(pRExC_state, GROUPPN, num);
11794 goto insert_if_check_paren;
11796 else if (memBEGINs(RExC_parse,
11797 (STRLEN) (RExC_end - RExC_parse),
11800 ret = reganode(pRExC_state, DEFINEP, 0);
11801 RExC_parse += DEFINE_len;
11803 goto insert_if_check_paren;
11805 else if (RExC_parse[0] == 'R') {
11807 /* parno == 0 => /(?(R)YES|NO)/ "in any form of recursion OR eval"
11808 * parno == 1 => /(?(R0)YES|NO)/ "in GOSUB (?0) / (?R)"
11809 * parno == 2 => /(?(R1)YES|NO)/ "in GOSUB (?1) (parno-1)"
11812 if (RExC_parse[0] == '0') {
11816 else if (inRANGE(RExC_parse[0], '1', '9')) {
11819 if (grok_atoUV(RExC_parse, &uv, &endptr)
11822 parno = (I32)uv + 1;
11823 RExC_parse = (char*)endptr;
11825 /* else "Switch condition not recognized" below */
11826 } else if (RExC_parse[0] == '&') {
11829 sv_dat = reg_scan_name(pRExC_state,
11830 REG_RSN_RETURN_DATA);
11832 parno = 1 + *((I32 *)SvPVX(sv_dat));
11834 ret = reganode(pRExC_state, INSUBP, parno);
11835 goto insert_if_check_paren;
11837 else if (inRANGE(RExC_parse[0], '1', '9')) {
11842 if (grok_atoUV(RExC_parse, &uv, &endptr)
11846 RExC_parse = (char*)endptr;
11849 vFAIL("panic: grok_atoUV returned FALSE");
11851 ret = reganode(pRExC_state, GROUPP, parno);
11853 insert_if_check_paren:
11854 if (UCHARAT(RExC_parse) != ')') {
11856 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
11858 vFAIL("Switch condition not recognized");
11860 nextchar(pRExC_state);
11862 if (! REGTAIL(pRExC_state, ret, reganode(pRExC_state,
11865 REQUIRE_BRANCHJ(flagp, 0);
11867 br = regbranch(pRExC_state, &flags, 1, depth+1);
11869 RETURN_FAIL_ON_RESTART(flags,flagp);
11870 FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
11873 if (! REGTAIL(pRExC_state, br, reganode(pRExC_state,
11876 REQUIRE_BRANCHJ(flagp, 0);
11878 c = UCHARAT(RExC_parse);
11879 nextchar(pRExC_state);
11880 if (flags&HASWIDTH)
11881 *flagp |= HASWIDTH;
11884 vFAIL("(?(DEFINE)....) does not allow branches");
11886 /* Fake one for optimizer. */
11887 lastbr = reganode(pRExC_state, IFTHEN, 0);
11889 if (!regbranch(pRExC_state, &flags, 1, depth+1)) {
11890 RETURN_FAIL_ON_RESTART(flags, flagp);
11891 FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
11894 if (! REGTAIL(pRExC_state, ret, lastbr)) {
11895 REQUIRE_BRANCHJ(flagp, 0);
11897 if (flags&HASWIDTH)
11898 *flagp |= HASWIDTH;
11899 c = UCHARAT(RExC_parse);
11900 nextchar(pRExC_state);
11905 if (RExC_parse >= RExC_end)
11906 vFAIL("Switch (?(condition)... not terminated");
11908 vFAIL("Switch (?(condition)... contains too many branches");
11910 ender = reg_node(pRExC_state, TAIL);
11911 if (! REGTAIL(pRExC_state, br, ender)) {
11912 REQUIRE_BRANCHJ(flagp, 0);
11915 if (! REGTAIL(pRExC_state, lastbr, ender)) {
11916 REQUIRE_BRANCHJ(flagp, 0);
11918 if (! REGTAIL(pRExC_state,
11921 NEXTOPER(REGNODE_p(lastbr)))),
11924 REQUIRE_BRANCHJ(flagp, 0);
11928 if (! REGTAIL(pRExC_state, ret, ender)) {
11929 REQUIRE_BRANCHJ(flagp, 0);
11931 #if 0 /* Removing this doesn't cause failures in the test suite -- khw */
11932 RExC_size++; /* XXX WHY do we need this?!!
11933 For large programs it seems to be required
11934 but I can't figure out why. -- dmq*/
11939 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
11941 vFAIL("Unknown switch condition (?(...))");
11943 case '[': /* (?[ ... ]) */
11944 return handle_regex_sets(pRExC_state, NULL, flagp, depth+1,
11946 case 0: /* A NUL */
11947 RExC_parse--; /* for vFAIL to print correctly */
11948 vFAIL("Sequence (? incomplete");
11952 if (RExC_strict) { /* [perl #132851] */
11953 ckWARNreg(RExC_parse, "Empty (?) without any modifiers");
11956 case '*': /* If you want to support (?*...), first reconcile with GH #17363 */
11958 default: /* e.g., (?i) */
11959 RExC_parse = (char *) seqstart + 1;
11961 parse_lparen_question_flags(pRExC_state);
11962 if (UCHARAT(RExC_parse) != ':') {
11963 if (RExC_parse < RExC_end)
11964 nextchar(pRExC_state);
11969 nextchar(pRExC_state);
11974 else if (!(RExC_flags & RXf_PMf_NOCAPTURE)) { /* (...) */
11978 if (! ALL_PARENS_COUNTED) {
11979 /* If we are in our first pass through (and maybe only pass),
11980 * we need to allocate memory for the capturing parentheses
11984 if (!RExC_parens_buf_size) {
11985 /* first guess at number of parens we might encounter */
11986 RExC_parens_buf_size = 10;
11988 /* setup RExC_open_parens, which holds the address of each
11989 * OPEN tag, and to make things simpler for the 0 index the
11990 * start of the program - this is used later for offsets */
11991 Newxz(RExC_open_parens, RExC_parens_buf_size,
11993 RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */
11995 /* setup RExC_close_parens, which holds the address of each
11996 * CLOSE tag, and to make things simpler for the 0 index
11997 * the end of the program - this is used later for offsets
11999 Newxz(RExC_close_parens, RExC_parens_buf_size,
12001 /* we dont know where end op starts yet, so we dont need to
12002 * set RExC_close_parens[0] like we do RExC_open_parens[0]
12005 else if (RExC_npar > RExC_parens_buf_size) {
12006 I32 old_size = RExC_parens_buf_size;
12008 RExC_parens_buf_size *= 2;
12010 Renew(RExC_open_parens, RExC_parens_buf_size,
12012 Zero(RExC_open_parens + old_size,
12013 RExC_parens_buf_size - old_size, regnode_offset);
12015 Renew(RExC_close_parens, RExC_parens_buf_size,
12017 Zero(RExC_close_parens + old_size,
12018 RExC_parens_buf_size - old_size, regnode_offset);
12022 ret = reganode(pRExC_state, OPEN, parno);
12023 if (!RExC_nestroot)
12024 RExC_nestroot = parno;
12025 if (RExC_open_parens && !RExC_open_parens[parno])
12027 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12028 "%*s%*s Setting open paren #%" IVdf " to %d\n",
12029 22, "| |", (int)(depth * 2 + 1), "",
12031 RExC_open_parens[parno]= ret;
12034 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
12035 Set_Node_Offset(REGNODE_p(ret), RExC_parse); /* MJD */
12038 /* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */
12047 /* Pick up the branches, linking them together. */
12048 parse_start = RExC_parse; /* MJD */
12049 br = regbranch(pRExC_state, &flags, 1, depth+1);
12051 /* branch_len = (paren != 0); */
12054 RETURN_FAIL_ON_RESTART(flags, flagp);
12055 FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12057 if (*RExC_parse == '|') {
12058 if (RExC_use_BRANCHJ) {
12059 reginsert(pRExC_state, BRANCHJ, br, depth+1);
12062 reginsert(pRExC_state, BRANCH, br, depth+1);
12063 Set_Node_Length(REGNODE_p(br), paren != 0);
12064 Set_Node_Offset_To_R(br, parse_start-RExC_start);
12068 else if (paren == ':') {
12069 *flagp |= flags&SIMPLE;
12071 if (is_open) { /* Starts with OPEN. */
12072 if (! REGTAIL(pRExC_state, ret, br)) { /* OPEN -> first. */
12073 REQUIRE_BRANCHJ(flagp, 0);
12076 else if (paren != '?') /* Not Conditional */
12078 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
12080 while (*RExC_parse == '|') {
12081 if (RExC_use_BRANCHJ) {
12084 ender = reganode(pRExC_state, LONGJMP, 0);
12086 /* Append to the previous. */
12087 shut_gcc_up = REGTAIL(pRExC_state,
12088 REGNODE_OFFSET(NEXTOPER(NEXTOPER(REGNODE_p(lastbr)))),
12090 PERL_UNUSED_VAR(shut_gcc_up);
12092 nextchar(pRExC_state);
12093 if (freeze_paren) {
12094 if (RExC_npar > after_freeze)
12095 after_freeze = RExC_npar;
12096 RExC_npar = freeze_paren;
12098 br = regbranch(pRExC_state, &flags, 0, depth+1);
12101 RETURN_FAIL_ON_RESTART(flags, flagp);
12102 FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12104 if (! REGTAIL(pRExC_state, lastbr, br)) { /* BRANCH -> BRANCH. */
12105 REQUIRE_BRANCHJ(flagp, 0);
12108 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
12111 if (have_branch || paren != ':') {
12114 /* Make a closing node, and hook it on the end. */
12117 ender = reg_node(pRExC_state, TAIL);
12120 ender = reganode(pRExC_state, CLOSE, parno);
12121 if ( RExC_close_parens ) {
12122 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12123 "%*s%*s Setting close paren #%" IVdf " to %d\n",
12124 22, "| |", (int)(depth * 2 + 1), "",
12125 (IV)parno, ender));
12126 RExC_close_parens[parno]= ender;
12127 if (RExC_nestroot == parno)
12130 Set_Node_Offset(REGNODE_p(ender), RExC_parse+1); /* MJD */
12131 Set_Node_Length(REGNODE_p(ender), 1); /* MJD */
12134 ender = reg_node(pRExC_state, SRCLOSE);
12135 RExC_in_script_run = 0;
12145 *flagp &= ~HASWIDTH;
12147 case 't': /* aTomic */
12149 ender = reg_node(pRExC_state, SUCCEED);
12152 ender = reg_node(pRExC_state, END);
12153 assert(!RExC_end_op); /* there can only be one! */
12154 RExC_end_op = REGNODE_p(ender);
12155 if (RExC_close_parens) {
12156 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12157 "%*s%*s Setting close paren #0 (END) to %d\n",
12158 22, "| |", (int)(depth * 2 + 1), "",
12161 RExC_close_parens[0]= ender;
12166 DEBUG_PARSE_MSG("lsbr");
12167 regprop(RExC_rx, RExC_mysv1, REGNODE_p(lastbr), NULL, pRExC_state);
12168 regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender), NULL, pRExC_state);
12169 Perl_re_printf( aTHX_ "~ tying lastbr %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12170 SvPV_nolen_const(RExC_mysv1),
12172 SvPV_nolen_const(RExC_mysv2),
12174 (IV)(ender - lastbr)
12177 if (! REGTAIL(pRExC_state, lastbr, ender)) {
12178 REQUIRE_BRANCHJ(flagp, 0);
12182 char is_nothing= 1;
12184 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
12186 /* Hook the tails of the branches to the closing node. */
12187 for (br = REGNODE_p(ret); br; br = regnext(br)) {
12188 const U8 op = PL_regkind[OP(br)];
12189 if (op == BRANCH) {
12190 if (! REGTAIL_STUDY(pRExC_state,
12191 REGNODE_OFFSET(NEXTOPER(br)),
12194 REQUIRE_BRANCHJ(flagp, 0);
12196 if ( OP(NEXTOPER(br)) != NOTHING
12197 || regnext(NEXTOPER(br)) != REGNODE_p(ender))
12200 else if (op == BRANCHJ) {
12201 bool shut_gcc_up = REGTAIL_STUDY(pRExC_state,
12202 REGNODE_OFFSET(NEXTOPER(NEXTOPER(br))),
12204 PERL_UNUSED_VAR(shut_gcc_up);
12205 /* for now we always disable this optimisation * /
12206 if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING
12207 || regnext(NEXTOPER(NEXTOPER(br))) != REGNODE_p(ender))
12213 regnode * ret_as_regnode = REGNODE_p(ret);
12214 br= PL_regkind[OP(ret_as_regnode)] != BRANCH
12215 ? regnext(ret_as_regnode)
12218 DEBUG_PARSE_MSG("NADA");
12219 regprop(RExC_rx, RExC_mysv1, ret_as_regnode,
12220 NULL, pRExC_state);
12221 regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender),
12222 NULL, pRExC_state);
12223 Perl_re_printf( aTHX_ "~ converting ret %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12224 SvPV_nolen_const(RExC_mysv1),
12225 (IV)REG_NODE_NUM(ret_as_regnode),
12226 SvPV_nolen_const(RExC_mysv2),
12232 if (OP(REGNODE_p(ender)) == TAIL) {
12234 RExC_emit= REGNODE_OFFSET(br) + 1;
12237 for ( opt= br + 1; opt < REGNODE_p(ender) ; opt++ )
12238 OP(opt)= OPTIMIZED;
12239 NEXT_OFF(br)= REGNODE_p(ender) - br;
12247 /* Even/odd or x=don't care: 010101x10x */
12248 static const char parens[] = "=!aA<,>Bbt";
12249 /* flag below is set to 0 up through 'A'; 1 for larger */
12251 if (paren && (p = strchr(parens, paren))) {
12252 U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
12253 int flag = (p - parens) > 3;
12255 if (paren == '>' || paren == 't') {
12256 node = SUSPEND, flag = 0;
12259 reginsert(pRExC_state, node, ret, depth+1);
12260 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12261 Set_Node_Offset(REGNODE_p(ret), parse_start + 1);
12262 FLAGS(REGNODE_p(ret)) = flag;
12263 if (! REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL)))
12265 REQUIRE_BRANCHJ(flagp, 0);
12270 /* Check for proper termination. */
12272 /* restore original flags, but keep (?p) and, if we've encountered
12273 * something in the parse that changes /d rules into /u, keep the /u */
12274 RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY);
12275 if (DEPENDS_SEMANTICS && RExC_uni_semantics) {
12276 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
12278 if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') {
12279 RExC_parse = oregcomp_parse;
12280 vFAIL("Unmatched (");
12282 nextchar(pRExC_state);
12284 else if (!paren && RExC_parse < RExC_end) {
12285 if (*RExC_parse == ')') {
12287 vFAIL("Unmatched )");
12290 FAIL("Junk on end of regexp"); /* "Can't happen". */
12291 NOT_REACHED; /* NOTREACHED */
12294 if (RExC_in_lookbehind) {
12295 RExC_in_lookbehind--;
12297 if (RExC_in_lookahead) {
12298 RExC_in_lookahead--;
12300 if (after_freeze > RExC_npar)
12301 RExC_npar = after_freeze;
12306 - regbranch - one alternative of an | operator
12308 * Implements the concatenation operator.
12310 * On success, returns the offset at which any next node should be placed into
12311 * the regex engine program being compiled.
12313 * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
12314 * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
12317 STATIC regnode_offset
12318 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
12320 regnode_offset ret;
12321 regnode_offset chain = 0;
12322 regnode_offset latest;
12323 I32 flags = 0, c = 0;
12324 GET_RE_DEBUG_FLAGS_DECL;
12326 PERL_ARGS_ASSERT_REGBRANCH;
12328 DEBUG_PARSE("brnc");
12333 if (RExC_use_BRANCHJ)
12334 ret = reganode(pRExC_state, BRANCHJ, 0);
12336 ret = reg_node(pRExC_state, BRANCH);
12337 Set_Node_Length(REGNODE_p(ret), 1);
12341 *flagp = WORST; /* Tentatively. */
12343 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
12344 FALSE /* Don't force to /x */ );
12345 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
12346 flags &= ~TRYAGAIN;
12347 latest = regpiece(pRExC_state, &flags, depth+1);
12349 if (flags & TRYAGAIN)
12351 RETURN_FAIL_ON_RESTART(flags, flagp);
12352 FAIL2("panic: regpiece returned failure, flags=%#" UVxf, (UV) flags);
12356 *flagp |= flags&(HASWIDTH|POSTPONED);
12357 if (chain == 0) /* First piece. */
12358 *flagp |= flags&SPSTART;
12360 /* FIXME adding one for every branch after the first is probably
12361 * excessive now we have TRIE support. (hv) */
12363 if (! REGTAIL(pRExC_state, chain, latest)) {
12364 /* XXX We could just redo this branch, but figuring out what
12365 * bookkeeping needs to be reset is a pain, and it's likely
12366 * that other branches that goto END will also be too large */
12367 REQUIRE_BRANCHJ(flagp, 0);
12373 if (chain == 0) { /* Loop ran zero times. */
12374 chain = reg_node(pRExC_state, NOTHING);
12379 *flagp |= flags&SIMPLE;
12386 - regpiece - something followed by possible quantifier * + ? {n,m}
12388 * Note that the branching code sequences used for ? and the general cases
12389 * of * and + are somewhat optimized: they use the same NOTHING node as
12390 * both the endmarker for their branch list and the body of the last branch.
12391 * It might seem that this node could be dispensed with entirely, but the
12392 * endmarker role is not redundant.
12394 * On success, returns the offset at which any next node should be placed into
12395 * the regex engine program being compiled.
12397 * Returns 0 otherwise, with *flagp set to indicate why:
12398 * TRYAGAIN if regatom() returns 0 with TRYAGAIN.
12399 * RESTART_PARSE if the parse needs to be restarted, or'd with
12400 * NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
12402 STATIC regnode_offset
12403 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
12405 regnode_offset ret;
12409 const char * const origparse = RExC_parse;
12411 I32 max = REG_INFTY;
12412 #ifdef RE_TRACK_PATTERN_OFFSETS
12415 const char *maxpos = NULL;
12418 /* Save the original in case we change the emitted regop to a FAIL. */
12419 const regnode_offset orig_emit = RExC_emit;
12421 GET_RE_DEBUG_FLAGS_DECL;
12423 PERL_ARGS_ASSERT_REGPIECE;
12425 DEBUG_PARSE("piec");
12427 ret = regatom(pRExC_state, &flags, depth+1);
12429 RETURN_FAIL_ON_RESTART_OR_FLAGS(flags, flagp, TRYAGAIN);
12430 FAIL2("panic: regatom returned failure, flags=%#" UVxf, (UV) flags);
12435 if (op == '{' && regcurly(RExC_parse)) {
12437 #ifdef RE_TRACK_PATTERN_OFFSETS
12438 parse_start = RExC_parse; /* MJD */
12440 next = RExC_parse + 1;
12441 while (isDIGIT(*next) || *next == ',') {
12442 if (*next == ',') {
12450 if (*next == '}') { /* got one */
12451 const char* endptr;
12455 if (isDIGIT(*RExC_parse)) {
12457 if (!grok_atoUV(RExC_parse, &uv, &endptr))
12458 vFAIL("Invalid quantifier in {,}");
12459 if (uv >= REG_INFTY)
12460 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12465 if (*maxpos == ',')
12468 maxpos = RExC_parse;
12469 if (isDIGIT(*maxpos)) {
12471 if (!grok_atoUV(maxpos, &uv, &endptr))
12472 vFAIL("Invalid quantifier in {,}");
12473 if (uv >= REG_INFTY)
12474 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12477 max = REG_INFTY; /* meaning "infinity" */
12480 nextchar(pRExC_state);
12481 if (max < min) { /* If can't match, warn and optimize to fail
12483 reginsert(pRExC_state, OPFAIL, orig_emit, depth+1);
12484 ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
12485 NEXT_OFF(REGNODE_p(orig_emit)) =
12486 regarglen[OPFAIL] + NODE_STEP_REGNODE;
12489 else if (min == max && *RExC_parse == '?')
12491 ckWARN2reg(RExC_parse + 1,
12492 "Useless use of greediness modifier '%c'",
12497 if ((flags&SIMPLE)) {
12498 if (min == 0 && max == REG_INFTY) {
12499 reginsert(pRExC_state, STAR, ret, depth+1);
12501 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12504 if (min == 1 && max == REG_INFTY) {
12505 reginsert(pRExC_state, PLUS, ret, depth+1);
12507 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12510 MARK_NAUGHTY_EXP(2, 2);
12511 reginsert(pRExC_state, CURLY, ret, depth+1);
12512 Set_Node_Offset(REGNODE_p(ret), parse_start+1); /* MJD */
12513 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12516 const regnode_offset w = reg_node(pRExC_state, WHILEM);
12518 FLAGS(REGNODE_p(w)) = 0;
12519 if (! REGTAIL(pRExC_state, ret, w)) {
12520 REQUIRE_BRANCHJ(flagp, 0);
12522 if (RExC_use_BRANCHJ) {
12523 reginsert(pRExC_state, LONGJMP, ret, depth+1);
12524 reginsert(pRExC_state, NOTHING, ret, depth+1);
12525 NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over LONGJMP. */
12527 reginsert(pRExC_state, CURLYX, ret, depth+1);
12529 Set_Node_Offset(REGNODE_p(ret), parse_start+1);
12530 Set_Node_Length(REGNODE_p(ret),
12531 op == '{' ? (RExC_parse - parse_start) : 1);
12533 if (RExC_use_BRANCHJ)
12534 NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over NOTHING to
12536 if (! REGTAIL(pRExC_state, ret, reg_node(pRExC_state,
12539 REQUIRE_BRANCHJ(flagp, 0);
12541 RExC_whilem_seen++;
12542 MARK_NAUGHTY_EXP(1, 4); /* compound interest */
12544 FLAGS(REGNODE_p(ret)) = 0;
12549 *flagp |= HASWIDTH;
12550 ARG1_SET(REGNODE_p(ret), (U16)min);
12551 ARG2_SET(REGNODE_p(ret), (U16)max);
12552 if (max == REG_INFTY)
12553 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12559 if (!ISMULT1(op)) {
12564 #if 0 /* Now runtime fix should be reliable. */
12566 /* if this is reinstated, don't forget to put this back into perldiag:
12568 =item Regexp *+ operand could be empty at {#} in regex m/%s/
12570 (F) The part of the regexp subject to either the * or + quantifier
12571 could match an empty string. The {#} shows in the regular
12572 expression about where the problem was discovered.
12576 if (!(flags&HASWIDTH) && op != '?')
12577 vFAIL("Regexp *+ operand could be empty");
12580 #ifdef RE_TRACK_PATTERN_OFFSETS
12581 parse_start = RExC_parse;
12583 nextchar(pRExC_state);
12585 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
12591 else if (op == '+') {
12595 else if (op == '?') {
12600 if (!(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
12601 ckWARN2reg(RExC_parse,
12602 "%" UTF8f " matches null string many times",
12603 UTF8fARG(UTF, (RExC_parse >= origparse
12604 ? RExC_parse - origparse
12609 if (*RExC_parse == '?') {
12610 nextchar(pRExC_state);
12611 reginsert(pRExC_state, MINMOD, ret, depth+1);
12612 if (! REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE)) {
12613 REQUIRE_BRANCHJ(flagp, 0);
12616 else if (*RExC_parse == '+') {
12617 regnode_offset ender;
12618 nextchar(pRExC_state);
12619 ender = reg_node(pRExC_state, SUCCEED);
12620 if (! REGTAIL(pRExC_state, ret, ender)) {
12621 REQUIRE_BRANCHJ(flagp, 0);
12623 reginsert(pRExC_state, SUSPEND, ret, depth+1);
12624 ender = reg_node(pRExC_state, TAIL);
12625 if (! REGTAIL(pRExC_state, ret, ender)) {
12626 REQUIRE_BRANCHJ(flagp, 0);
12630 if (ISMULT2(RExC_parse)) {
12632 vFAIL("Nested quantifiers");
12639 S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state,
12640 regnode_offset * node_p,
12648 /* This routine teases apart the various meanings of \N and returns
12649 * accordingly. The input parameters constrain which meaning(s) is/are valid
12650 * in the current context.
12652 * Exactly one of <node_p> and <code_point_p> must be non-NULL.
12654 * If <code_point_p> is not NULL, the context is expecting the result to be a
12655 * single code point. If this \N instance turns out to a single code point,
12656 * the function returns TRUE and sets *code_point_p to that code point.
12658 * If <node_p> is not NULL, the context is expecting the result to be one of
12659 * the things representable by a regnode. If this \N instance turns out to be
12660 * one such, the function generates the regnode, returns TRUE and sets *node_p
12661 * to point to the offset of that regnode into the regex engine program being
12664 * If this instance of \N isn't legal in any context, this function will
12665 * generate a fatal error and not return.
12667 * On input, RExC_parse should point to the first char following the \N at the
12668 * time of the call. On successful return, RExC_parse will have been updated
12669 * to point to just after the sequence identified by this routine. Also
12670 * *flagp has been updated as needed.
12672 * When there is some problem with the current context and this \N instance,
12673 * the function returns FALSE, without advancing RExC_parse, nor setting
12674 * *node_p, nor *code_point_p, nor *flagp.
12676 * If <cp_count> is not NULL, the caller wants to know the length (in code
12677 * points) that this \N sequence matches. This is set, and the input is
12678 * parsed for errors, even if the function returns FALSE, as detailed below.
12680 * There are 6 possibilities here, as detailed in the next 6 paragraphs.
12682 * Probably the most common case is for the \N to specify a single code point.
12683 * *cp_count will be set to 1, and *code_point_p will be set to that code
12686 * Another possibility is for the input to be an empty \N{}. This is no
12687 * longer accepted, and will generate a fatal error.
12689 * Another possibility is for a custom charnames handler to be in effect which
12690 * translates the input name to an empty string. *cp_count will be set to 0.
12691 * *node_p will be set to a generated NOTHING node.
12693 * Still another possibility is for the \N to mean [^\n]. *cp_count will be
12694 * set to 0. *node_p will be set to a generated REG_ANY node.
12696 * The fifth possibility is that \N resolves to a sequence of more than one
12697 * code points. *cp_count will be set to the number of code points in the
12698 * sequence. *node_p will be set to a generated node returned by this
12699 * function calling S_reg().
12701 * The final possibility is that it is premature to be calling this function;
12702 * the parse needs to be restarted. This can happen when this changes from
12703 * /d to /u rules, or when the pattern needs to be upgraded to UTF-8. The
12704 * latter occurs only when the fifth possibility would otherwise be in
12705 * effect, and is because one of those code points requires the pattern to be
12706 * recompiled as UTF-8. The function returns FALSE, and sets the
12707 * RESTART_PARSE and NEED_UTF8 flags in *flagp, as appropriate. When this
12708 * happens, the caller needs to desist from continuing parsing, and return
12709 * this information to its caller. This is not set for when there is only one
12710 * code point, as this can be called as part of an ANYOF node, and they can
12711 * store above-Latin1 code points without the pattern having to be in UTF-8.
12713 * For non-single-quoted regexes, the tokenizer has resolved character and
12714 * sequence names inside \N{...} into their Unicode values, normalizing the
12715 * result into what we should see here: '\N{U+c1.c2...}', where c1... are the
12716 * hex-represented code points in the sequence. This is done there because
12717 * the names can vary based on what charnames pragma is in scope at the time,
12718 * so we need a way to take a snapshot of what they resolve to at the time of
12719 * the original parse. [perl #56444].
12721 * That parsing is skipped for single-quoted regexes, so here we may get
12722 * '\N{NAME}', which is parsed now. If the single-quoted regex is something
12723 * like '\N{U+41}', that code point is Unicode, and has to be translated into
12724 * the native character set for non-ASCII platforms. The other possibilities
12725 * are already native, so no translation is done. */
12727 char * endbrace; /* points to '}' following the name */
12728 char* p = RExC_parse; /* Temporary */
12730 SV * substitute_parse = NULL;
12735 GET_RE_DEBUG_FLAGS_DECL;
12737 PERL_ARGS_ASSERT_GROK_BSLASH_N;
12739 GET_RE_DEBUG_FLAGS;
12741 assert(cBOOL(node_p) ^ cBOOL(code_point_p)); /* Exactly one should be set */
12742 assert(! (node_p && cp_count)); /* At most 1 should be set */
12744 if (cp_count) { /* Initialize return for the most common case */
12748 /* The [^\n] meaning of \N ignores spaces and comments under the /x
12749 * modifier. The other meanings do not, so use a temporary until we find
12750 * out which we are being called with */
12751 skip_to_be_ignored_text(pRExC_state, &p,
12752 FALSE /* Don't force to /x */ );
12754 /* Disambiguate between \N meaning a named character versus \N meaning
12755 * [^\n]. The latter is assumed when the {...} following the \N is a legal
12756 * quantifier, or if there is no '{' at all */
12757 if (*p != '{' || regcurly(p)) {
12767 *node_p = reg_node(pRExC_state, REG_ANY);
12768 *flagp |= HASWIDTH|SIMPLE;
12770 Set_Node_Length(REGNODE_p(*(node_p)), 1); /* MJD */
12774 /* The test above made sure that the next real character is a '{', but
12775 * under the /x modifier, it could be separated by space (or a comment and
12776 * \n) and this is not allowed (for consistency with \x{...} and the
12777 * tokenizer handling of \N{NAME}). */
12778 if (*RExC_parse != '{') {
12779 vFAIL("Missing braces on \\N{}");
12782 RExC_parse++; /* Skip past the '{' */
12784 endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
12785 if (! endbrace) { /* no trailing brace */
12786 vFAIL2("Missing right brace on \\%c{}", 'N');
12789 /* Here, we have decided it should be a named character or sequence. These
12790 * imply Unicode semantics */
12791 REQUIRE_UNI_RULES(flagp, FALSE);
12793 /* \N{_} is what toke.c returns to us to indicate a name that evaluates to
12794 * nothing at all (not allowed under strict) */
12795 if (endbrace - RExC_parse == 1 && *RExC_parse == '_') {
12796 RExC_parse = endbrace;
12798 RExC_parse++; /* Position after the "}" */
12799 vFAIL("Zero length \\N{}");
12805 nextchar(pRExC_state);
12810 *node_p = reg_node(pRExC_state, NOTHING);
12814 if (endbrace - RExC_parse < 2 || ! strBEGINs(RExC_parse, "U+")) {
12816 /* Here, the name isn't of the form U+.... This can happen if the
12817 * pattern is single-quoted, so didn't get evaluated in toke.c. Now
12818 * is the time to find out what the name means */
12820 const STRLEN name_len = endbrace - RExC_parse;
12821 SV * value_sv; /* What does this name evaluate to */
12823 const U8 * value; /* string of name's value */
12824 STRLEN value_len; /* and its length */
12826 /* RExC_unlexed_names is a hash of names that weren't evaluated by
12827 * toke.c, and their values. Make sure is initialized */
12828 if (! RExC_unlexed_names) {
12829 RExC_unlexed_names = newHV();
12832 /* If we have already seen this name in this pattern, use that. This
12833 * allows us to only call the charnames handler once per name per
12834 * pattern. A broken or malicious handler could return something
12835 * different each time, which could cause the results to vary depending
12836 * on if something gets added or subtracted from the pattern that
12837 * causes the number of passes to change, for example */
12838 if ((value_svp = hv_fetch(RExC_unlexed_names, RExC_parse,
12841 value_sv = *value_svp;
12843 else { /* Otherwise we have to go out and get the name */
12844 const char * error_msg = NULL;
12845 value_sv = get_and_check_backslash_N_name(RExC_parse, endbrace,
12849 RExC_parse = endbrace;
12853 /* If no error message, should have gotten a valid return */
12856 /* Save the name's meaning for later use */
12857 if (! hv_store(RExC_unlexed_names, RExC_parse, name_len,
12860 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
12864 /* Here, we have the value the name evaluates to in 'value_sv' */
12865 value = (U8 *) SvPV(value_sv, value_len);
12867 /* See if the result is one code point vs 0 or multiple */
12868 if (inRANGE(value_len, 1, ((UV) SvUTF8(value_sv)
12872 /* Here, exactly one code point. If that isn't what is wanted,
12874 if (! code_point_p) {
12879 /* Convert from string to numeric code point */
12880 *code_point_p = (SvUTF8(value_sv))
12881 ? valid_utf8_to_uvchr(value, NULL)
12884 /* Have parsed this entire single code point \N{...}. *cp_count
12885 * has already been set to 1, so don't do it again. */
12886 RExC_parse = endbrace;
12887 nextchar(pRExC_state);
12889 } /* End of is a single code point */
12891 /* Count the code points, if caller desires. The API says to do this
12892 * even if we will later return FALSE */
12896 *cp_count = (SvUTF8(value_sv))
12897 ? utf8_length(value, value + value_len)
12901 /* Fail if caller doesn't want to handle a multi-code-point sequence.
12902 * But don't back the pointer up if the caller wants to know how many
12903 * code points there are (they need to handle it themselves in this
12912 /* Convert this to a sub-pattern of the form "(?: ... )", and then call
12913 * reg recursively to parse it. That way, it retains its atomicness,
12914 * while not having to worry about any special handling that some code
12915 * points may have. */
12917 substitute_parse = newSVpvs("?:");
12918 sv_catsv(substitute_parse, value_sv);
12919 sv_catpv(substitute_parse, ")");
12921 /* The value should already be native, so no need to convert on EBCDIC
12923 assert(! RExC_recode_x_to_native);
12926 else { /* \N{U+...} */
12927 Size_t count = 0; /* code point count kept internally */
12929 /* We can get to here when the input is \N{U+...} or when toke.c has
12930 * converted a name to the \N{U+...} form. This include changing a
12931 * name that evaluates to multiple code points to \N{U+c1.c2.c3 ...} */
12933 RExC_parse += 2; /* Skip past the 'U+' */
12935 /* Code points are separated by dots. The '}' terminates the whole
12938 do { /* Loop until the ending brace */
12940 char * start_digit; /* The first of the current code point */
12941 if (! isXDIGIT(*RExC_parse)) {
12943 vFAIL("Invalid hexadecimal number in \\N{U+...}");
12946 start_digit = RExC_parse;
12949 /* Loop through the hex digits of the current code point */
12951 /* Adding this digit will shift the result 4 bits. If that
12952 * result would be above the legal max, it's overflow */
12953 if (cp > MAX_LEGAL_CP >> 4) {
12955 /* Find the end of the code point */
12958 } while (isXDIGIT(*RExC_parse) || *RExC_parse == '_');
12960 /* Be sure to synchronize this message with the similar one
12962 vFAIL4("Use of code point 0x%.*s is not allowed; the"
12963 " permissible max is 0x%" UVxf,
12964 (int) (RExC_parse - start_digit), start_digit,
12968 /* Accumulate this (valid) digit into the running total */
12969 cp = (cp << 4) + READ_XDIGIT(RExC_parse);
12971 /* READ_XDIGIT advanced the input pointer. Ignore a single
12972 * underscore separator */
12973 if (*RExC_parse == '_' && isXDIGIT(RExC_parse[1])) {
12976 } while (isXDIGIT(*RExC_parse));
12978 /* Here, have accumulated the next code point */
12979 if (RExC_parse >= endbrace) { /* If done ... */
12984 /* Here, is a single code point; fail if doesn't want that */
12985 if (! code_point_p) {
12990 /* A single code point is easy to handle; just return it */
12991 *code_point_p = UNI_TO_NATIVE(cp);
12992 RExC_parse = endbrace;
12993 nextchar(pRExC_state);
12997 /* Here, the only legal thing would be a multiple character
12998 * sequence (of the form "\N{U+c1.c2. ... }". So the next
12999 * character must be a dot (and the one after that can't be the
13000 * endbrace, or we'd have something like \N{U+100.} ) */
13001 if (*RExC_parse != '.' || RExC_parse + 1 >= endbrace) {
13002 RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */
13003 ? UTF8SKIP(RExC_parse)
13005 if (RExC_parse >= endbrace) { /* Guard against malformed utf8 */
13006 RExC_parse = endbrace;
13008 vFAIL("Invalid hexadecimal number in \\N{U+...}");
13011 /* Here, looks like its really a multiple character sequence. Fail
13012 * if that's not what the caller wants. But continue with counting
13013 * and error checking if they still want a count */
13014 if (! node_p && ! cp_count) {
13018 /* What is done here is to convert this to a sub-pattern of the
13019 * form \x{char1}\x{char2}... and then call reg recursively to
13020 * parse it (enclosing in "(?: ... )" ). That way, it retains its
13021 * atomicness, while not having to worry about special handling
13022 * that some code points may have. We don't create a subpattern,
13023 * but go through the motions of code point counting and error
13024 * checking, if the caller doesn't want a node returned. */
13026 if (node_p && count == 1) {
13027 substitute_parse = newSVpvs("?:");
13033 /* Convert to notation the rest of the code understands */
13034 sv_catpvs(substitute_parse, "\\x{");
13035 sv_catpvn(substitute_parse, start_digit,
13036 RExC_parse - start_digit);
13037 sv_catpvs(substitute_parse, "}");
13040 /* Move to after the dot (or ending brace the final time through.)
13045 } while (RExC_parse < endbrace);
13047 if (! node_p) { /* Doesn't want the node */
13054 sv_catpvs(substitute_parse, ")");
13056 /* The values are Unicode, and therefore have to be converted to native
13057 * on a non-Unicode (meaning non-ASCII) platform. */
13058 SET_recode_x_to_native(1);
13061 /* Here, we have the string the name evaluates to, ready to be parsed,
13062 * stored in 'substitute_parse' as a series of valid "\x{...}\x{...}"
13063 * constructs. This can be called from within a substitute parse already.
13064 * The error reporting mechanism doesn't work for 2 levels of this, but the
13065 * code above has validated this new construct, so there should be no
13066 * errors generated by the below. And this isn' an exact copy, so the
13067 * mechanism to seamlessly deal with this won't work, so turn off warnings
13069 save_start = RExC_start;
13070 orig_end = RExC_end;
13072 RExC_parse = RExC_start = SvPVX(substitute_parse);
13073 RExC_end = RExC_parse + SvCUR(substitute_parse);
13074 TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
13076 *node_p = reg(pRExC_state, 1, &flags, depth+1);
13078 /* Restore the saved values */
13080 RExC_start = save_start;
13081 RExC_parse = endbrace;
13082 RExC_end = orig_end;
13083 SET_recode_x_to_native(0);
13085 SvREFCNT_dec_NN(substitute_parse);
13088 RETURN_FAIL_ON_RESTART(flags, flagp);
13089 FAIL2("panic: reg returned failure to grok_bslash_N, flags=%#" UVxf,
13092 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
13094 nextchar(pRExC_state);
13100 PERL_STATIC_INLINE U8
13101 S_compute_EXACTish(RExC_state_t *pRExC_state)
13105 PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
13113 op = get_regex_charset(RExC_flags);
13114 if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
13115 op--; /* /a is same as /u, and map /aa's offset to what /a's would have
13116 been, so there is no hole */
13119 return op + EXACTF;
13123 S_new_regcurly(const char *s, const char *e)
13125 /* This is a temporary function designed to match the most lenient form of
13126 * a {m,n} quantifier we ever envision, with either number omitted, and
13127 * spaces anywhere between/before/after them.
13129 * If this function fails, then the string it matches is very unlikely to
13130 * ever be considered a valid quantifier, so we can allow the '{' that
13131 * begins it to be considered as a literal */
13133 bool has_min = FALSE;
13134 bool has_max = FALSE;
13136 PERL_ARGS_ASSERT_NEW_REGCURLY;
13138 if (s >= e || *s++ != '{')
13141 while (s < e && isSPACE(*s)) {
13144 while (s < e && isDIGIT(*s)) {
13148 while (s < e && isSPACE(*s)) {
13154 while (s < e && isSPACE(*s)) {
13157 while (s < e && isDIGIT(*s)) {
13161 while (s < e && isSPACE(*s)) {
13166 return s < e && *s == '}' && (has_min || has_max);
13169 /* Parse backref decimal value, unless it's too big to sensibly be a backref,
13170 * in which case return I32_MAX (rather than possibly 32-bit wrapping) */
13173 S_backref_value(char *p, char *e)
13175 const char* endptr = e;
13177 if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX)
13184 - regatom - the lowest level
13186 Try to identify anything special at the start of the current parse position.
13187 If there is, then handle it as required. This may involve generating a
13188 single regop, such as for an assertion; or it may involve recursing, such as
13189 to handle a () structure.
13191 If the string doesn't start with something special then we gobble up
13192 as much literal text as we can. If we encounter a quantifier, we have to
13193 back off the final literal character, as that quantifier applies to just it
13194 and not to the whole string of literals.
13196 Once we have been able to handle whatever type of thing started the
13197 sequence, we return the offset into the regex engine program being compiled
13198 at which any next regnode should be placed.
13200 Returns 0, setting *flagp to TRYAGAIN if reg() returns 0 with TRYAGAIN.
13201 Returns 0, setting *flagp to RESTART_PARSE if the parse needs to be
13202 restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
13203 Otherwise does not return 0.
13205 Note: we have to be careful with escapes, as they can be both literal
13206 and special, and in the case of \10 and friends, context determines which.
13208 A summary of the code structure is:
13210 switch (first_byte) {
13211 cases for each special:
13212 handle this special;
13215 switch (2nd byte) {
13216 cases for each unambiguous special:
13217 handle this special;
13219 cases for each ambigous special/literal:
13221 if (special) handle here
13223 default: // unambiguously literal:
13226 default: // is a literal char
13229 create EXACTish node for literal;
13230 while (more input and node isn't full) {
13231 switch (input_byte) {
13232 cases for each special;
13233 make sure parse pointer is set so that the next call to
13234 regatom will see this special first
13235 goto loopdone; // EXACTish node terminated by prev. char
13237 append char to EXACTISH node;
13239 get next input byte;
13243 return the generated node;
13245 Specifically there are two separate switches for handling
13246 escape sequences, with the one for handling literal escapes requiring
13247 a dummy entry for all of the special escapes that are actually handled
13252 STATIC regnode_offset
13253 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
13256 regnode_offset ret = 0;
13262 GET_RE_DEBUG_FLAGS_DECL;
13264 *flagp = WORST; /* Tentatively. */
13266 DEBUG_PARSE("atom");
13268 PERL_ARGS_ASSERT_REGATOM;
13271 parse_start = RExC_parse;
13272 assert(RExC_parse < RExC_end);
13273 switch ((U8)*RExC_parse) {
13275 RExC_seen_zerolen++;
13276 nextchar(pRExC_state);
13277 if (RExC_flags & RXf_PMf_MULTILINE)
13278 ret = reg_node(pRExC_state, MBOL);
13280 ret = reg_node(pRExC_state, SBOL);
13281 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13284 nextchar(pRExC_state);
13286 RExC_seen_zerolen++;
13287 if (RExC_flags & RXf_PMf_MULTILINE)
13288 ret = reg_node(pRExC_state, MEOL);
13290 ret = reg_node(pRExC_state, SEOL);
13291 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13294 nextchar(pRExC_state);
13295 if (RExC_flags & RXf_PMf_SINGLELINE)
13296 ret = reg_node(pRExC_state, SANY);
13298 ret = reg_node(pRExC_state, REG_ANY);
13299 *flagp |= HASWIDTH|SIMPLE;
13301 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13305 char * const oregcomp_parse = ++RExC_parse;
13306 ret = regclass(pRExC_state, flagp, depth+1,
13307 FALSE, /* means parse the whole char class */
13308 TRUE, /* allow multi-char folds */
13309 FALSE, /* don't silence non-portable warnings. */
13310 (bool) RExC_strict,
13311 TRUE, /* Allow an optimized regnode result */
13314 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13315 FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13318 if (*RExC_parse != ']') {
13319 RExC_parse = oregcomp_parse;
13320 vFAIL("Unmatched [");
13322 nextchar(pRExC_state);
13323 Set_Node_Length(REGNODE_p(ret), RExC_parse - oregcomp_parse + 1); /* MJD */
13327 nextchar(pRExC_state);
13328 ret = reg(pRExC_state, 2, &flags, depth+1);
13330 if (flags & TRYAGAIN) {
13331 if (RExC_parse >= RExC_end) {
13332 /* Make parent create an empty node if needed. */
13333 *flagp |= TRYAGAIN;
13338 RETURN_FAIL_ON_RESTART(flags, flagp);
13339 FAIL2("panic: reg returned failure to regatom, flags=%#" UVxf,
13342 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
13346 if (flags & TRYAGAIN) {
13347 *flagp |= TRYAGAIN;
13350 vFAIL("Internal urp");
13351 /* Supposed to be caught earlier. */
13357 vFAIL("Quantifier follows nothing");
13362 This switch handles escape sequences that resolve to some kind
13363 of special regop and not to literal text. Escape sequences that
13364 resolve to literal text are handled below in the switch marked
13367 Every entry in this switch *must* have a corresponding entry
13368 in the literal escape switch. However, the opposite is not
13369 required, as the default for this switch is to jump to the
13370 literal text handling code.
13373 switch ((U8)*RExC_parse) {
13374 /* Special Escapes */
13376 RExC_seen_zerolen++;
13377 ret = reg_node(pRExC_state, SBOL);
13378 /* SBOL is shared with /^/ so we set the flags so we can tell
13379 * /\A/ from /^/ in split. */
13380 FLAGS(REGNODE_p(ret)) = 1;
13382 goto finish_meta_pat;
13384 ret = reg_node(pRExC_state, GPOS);
13385 RExC_seen |= REG_GPOS_SEEN;
13387 goto finish_meta_pat;
13389 if (!RExC_in_lookbehind && !RExC_in_lookahead) {
13390 RExC_seen_zerolen++;
13391 ret = reg_node(pRExC_state, KEEPS);
13393 /* XXX:dmq : disabling in-place substitution seems to
13394 * be necessary here to avoid cases of memory corruption, as
13395 * with: C<$_="x" x 80; s/x\K/y/> -- rgs
13397 RExC_seen |= REG_LOOKBEHIND_SEEN;
13398 goto finish_meta_pat;
13401 ++RExC_parse; /* advance past the 'K' */
13402 vFAIL("\\K not permitted in lookahead/lookbehind");
13405 ret = reg_node(pRExC_state, SEOL);
13407 RExC_seen_zerolen++; /* Do not optimize RE away */
13408 goto finish_meta_pat;
13410 ret = reg_node(pRExC_state, EOS);
13412 RExC_seen_zerolen++; /* Do not optimize RE away */
13413 goto finish_meta_pat;
13415 vFAIL("\\C no longer supported");
13417 ret = reg_node(pRExC_state, CLUMP);
13418 *flagp |= HASWIDTH;
13419 goto finish_meta_pat;
13427 regex_charset charset = get_regex_charset(RExC_flags);
13429 RExC_seen_zerolen++;
13430 RExC_seen |= REG_LOOKBEHIND_SEEN;
13431 op = BOUND + charset;
13433 if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') {
13434 flags = TRADITIONAL_BOUND;
13435 if (op > BOUNDA) { /* /aa is same as /a */
13441 char name = *RExC_parse;
13442 char * endbrace = NULL;
13444 endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
13447 vFAIL2("Missing right brace on \\%c{}", name);
13449 /* XXX Need to decide whether to take spaces or not. Should be
13450 * consistent with \p{}, but that currently is SPACE, which
13451 * means vertical too, which seems wrong
13452 * while (isBLANK(*RExC_parse)) {
13455 if (endbrace == RExC_parse) {
13456 RExC_parse++; /* After the '}' */
13457 vFAIL2("Empty \\%c{}", name);
13459 length = endbrace - RExC_parse;
13460 /*while (isBLANK(*(RExC_parse + length - 1))) {
13463 switch (*RExC_parse) {
13466 && (memNEs(RExC_parse + 1, length - 1, "cb")))
13468 goto bad_bound_type;
13473 if (length != 2 || *(RExC_parse + 1) != 'b') {
13474 goto bad_bound_type;
13479 if (length != 2 || *(RExC_parse + 1) != 'b') {
13480 goto bad_bound_type;
13485 if (length != 2 || *(RExC_parse + 1) != 'b') {
13486 goto bad_bound_type;
13492 RExC_parse = endbrace;
13494 "'%" UTF8f "' is an unknown bound type",
13495 UTF8fARG(UTF, length, endbrace - length));
13496 NOT_REACHED; /*NOTREACHED*/
13498 RExC_parse = endbrace;
13499 REQUIRE_UNI_RULES(flagp, 0);
13504 else if (op >= BOUNDA) { /* /aa is same as /a */
13508 /* Don't have to worry about UTF-8, in this message because
13509 * to get here the contents of the \b must be ASCII */
13510 ckWARN4reg(RExC_parse + 1, /* Include the '}' in msg */
13511 "Using /u for '%.*s' instead of /%s",
13513 endbrace - length + 1,
13514 (charset == REGEX_ASCII_RESTRICTED_CHARSET)
13515 ? ASCII_RESTRICT_PAT_MODS
13516 : ASCII_MORE_RESTRICT_PAT_MODS);
13521 RExC_seen_d_op = TRUE;
13523 else if (op == BOUNDL) {
13524 RExC_contains_locale = 1;
13528 op += NBOUND - BOUND;
13531 ret = reg_node(pRExC_state, op);
13532 FLAGS(REGNODE_p(ret)) = flags;
13536 goto finish_meta_pat;
13540 ret = reg_node(pRExC_state, LNBREAK);
13541 *flagp |= HASWIDTH|SIMPLE;
13542 goto finish_meta_pat;
13556 /* These all have the same meaning inside [brackets], and it knows
13557 * how to do the best optimizations for them. So, pretend we found
13558 * these within brackets, and let it do the work */
13561 ret = regclass(pRExC_state, flagp, depth+1,
13562 TRUE, /* means just parse this element */
13563 FALSE, /* don't allow multi-char folds */
13564 FALSE, /* don't silence non-portable warnings. It
13565 would be a bug if these returned
13567 (bool) RExC_strict,
13568 TRUE, /* Allow an optimized regnode result */
13570 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13571 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
13572 * multi-char folds are allowed. */
13574 FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13577 RExC_parse--; /* regclass() leaves this one too far ahead */
13580 /* The escapes above that don't take a parameter can't be
13581 * followed by a '{'. But 'pX', 'p{foo}' and
13582 * correspondingly 'P' can be */
13583 if ( RExC_parse - parse_start == 1
13584 && UCHARAT(RExC_parse + 1) == '{'
13585 && UNLIKELY(! new_regcurly(RExC_parse + 1, RExC_end)))
13588 vFAIL("Unescaped left brace in regex is illegal here");
13590 Set_Node_Offset(REGNODE_p(ret), parse_start);
13591 Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1); /* MJD */
13592 nextchar(pRExC_state);
13595 /* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the
13596 * \N{...} evaluates to a sequence of more than one code points).
13597 * The function call below returns a regnode, which is our result.
13598 * The parameters cause it to fail if the \N{} evaluates to a
13599 * single code point; we handle those like any other literal. The
13600 * reason that the multicharacter case is handled here and not as
13601 * part of the EXACtish code is because of quantifiers. In
13602 * /\N{BLAH}+/, the '+' applies to the whole thing, and doing it
13603 * this way makes that Just Happen. dmq.
13604 * join_exact() will join this up with adjacent EXACTish nodes
13605 * later on, if appropriate. */
13607 if (grok_bslash_N(pRExC_state,
13608 &ret, /* Want a regnode returned */
13609 NULL, /* Fail if evaluates to a single code
13611 NULL, /* Don't need a count of how many code
13620 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13622 /* Here, evaluates to a single code point. Go get that */
13623 RExC_parse = parse_start;
13626 case 'k': /* Handle \k<NAME> and \k'NAME' */
13630 if ( RExC_parse >= RExC_end - 1
13631 || (( ch = RExC_parse[1]) != '<'
13636 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
13637 vFAIL2("Sequence %.2s... not terminated", parse_start);
13640 ret = handle_named_backref(pRExC_state,
13652 case '1': case '2': case '3': case '4':
13653 case '5': case '6': case '7': case '8': case '9':
13658 if (*RExC_parse == 'g') {
13662 if (*RExC_parse == '{') {
13666 if (*RExC_parse == '-') {
13670 if (hasbrace && !isDIGIT(*RExC_parse)) {
13671 if (isrel) RExC_parse--;
13673 goto parse_named_seq;
13676 if (RExC_parse >= RExC_end) {
13677 goto unterminated_g;
13679 num = S_backref_value(RExC_parse, RExC_end);
13681 vFAIL("Reference to invalid group 0");
13682 else if (num == I32_MAX) {
13683 if (isDIGIT(*RExC_parse))
13684 vFAIL("Reference to nonexistent group");
13687 vFAIL("Unterminated \\g... pattern");
13691 num = RExC_npar - num;
13693 vFAIL("Reference to nonexistent or unclosed group");
13697 num = S_backref_value(RExC_parse, RExC_end);
13698 /* bare \NNN might be backref or octal - if it is larger
13699 * than or equal RExC_npar then it is assumed to be an
13700 * octal escape. Note RExC_npar is +1 from the actual
13701 * number of parens. */
13702 /* Note we do NOT check if num == I32_MAX here, as that is
13703 * handled by the RExC_npar check */
13706 /* any numeric escape < 10 is always a backref */
13708 /* any numeric escape < RExC_npar is a backref */
13709 && num >= RExC_npar
13710 /* cannot be an octal escape if it starts with 8 */
13711 && *RExC_parse != '8'
13712 /* cannot be an octal escape if it starts with 9 */
13713 && *RExC_parse != '9'
13715 /* Probably not meant to be a backref, instead likely
13716 * to be an octal character escape, e.g. \35 or \777.
13717 * The above logic should make it obvious why using
13718 * octal escapes in patterns is problematic. - Yves */
13719 RExC_parse = parse_start;
13724 /* At this point RExC_parse points at a numeric escape like
13725 * \12 or \88 or something similar, which we should NOT treat
13726 * as an octal escape. It may or may not be a valid backref
13727 * escape. For instance \88888888 is unlikely to be a valid
13729 while (isDIGIT(*RExC_parse))
13732 if (*RExC_parse != '}')
13733 vFAIL("Unterminated \\g{...} pattern");
13736 if (num >= (I32)RExC_npar) {
13738 /* It might be a forward reference; we can't fail until we
13739 * know, by completing the parse to get all the groups, and
13740 * then reparsing */
13741 if (ALL_PARENS_COUNTED) {
13742 if (num >= RExC_total_parens) {
13743 vFAIL("Reference to nonexistent group");
13747 REQUIRE_PARENS_PASS;
13751 ret = reganode(pRExC_state,
13754 : (ASCII_FOLD_RESTRICTED)
13756 : (AT_LEAST_UNI_SEMANTICS)
13762 if (OP(REGNODE_p(ret)) == REFF) {
13763 RExC_seen_d_op = TRUE;
13765 *flagp |= HASWIDTH;
13767 /* override incorrect value set in reganode MJD */
13768 Set_Node_Offset(REGNODE_p(ret), parse_start);
13769 Set_Node_Cur_Length(REGNODE_p(ret), parse_start-1);
13770 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
13771 FALSE /* Don't force to /x */ );
13775 if (RExC_parse >= RExC_end)
13776 FAIL("Trailing \\");
13779 /* Do not generate "unrecognized" warnings here, we fall
13780 back into the quick-grab loop below */
13781 RExC_parse = parse_start;
13783 } /* end of switch on a \foo sequence */
13788 /* '#' comments should have been spaced over before this function was
13790 assert((RExC_flags & RXf_PMf_EXTENDED) == 0);
13792 if (RExC_flags & RXf_PMf_EXTENDED) {
13793 RExC_parse = reg_skipcomment( pRExC_state, RExC_parse );
13794 if (RExC_parse < RExC_end)
13804 /* Here, we have determined that the next thing is probably a
13805 * literal character. RExC_parse points to the first byte of its
13806 * definition. (It still may be an escape sequence that evaluates
13807 * to a single character) */
13812 char *s, *old_s = NULL, *old_old_s = NULL;
13814 U32 max_string_len = 255;
13816 /* We may have to reparse the node, artificially stopping filling
13817 * it early, based on info gleaned in the first parse. This
13818 * variable gives where we stop. Make it above the normal stopping
13819 * place first time through; otherwise it would stop too early */
13820 U32 upper_fill = max_string_len + 1;
13822 /* We start out as an EXACT node, even if under /i, until we find a
13823 * character which is in a fold. The algorithm now segregates into
13824 * separate nodes, characters that fold from those that don't under
13825 * /i. (This hopefully will create nodes that are fixed strings
13826 * even under /i, giving the optimizer something to grab on to.)
13827 * So, if a node has something in it and the next character is in
13828 * the opposite category, that node is closed up, and the function
13829 * returns. Then regatom is called again, and a new node is
13830 * created for the new category. */
13831 U8 node_type = EXACT;
13833 /* Assume the node will be fully used; the excess is given back at
13834 * the end. Under /i, we may need to temporarily add the fold of
13835 * an extra character or two at the end to check for splitting
13836 * multi-char folds, so allocate extra space for that. We can't
13837 * make any other length assumptions, as a byte input sequence
13838 * could shrink down. */
13839 Ptrdiff_t current_string_nodes = STR_SZ(max_string_len
13843 ? UTF8_MAXBYTES_CASE
13844 /* Max non-UTF-8 expansion is 2 */ : 2)));
13846 bool next_is_quantifier;
13847 char * oldp = NULL;
13849 /* We can convert EXACTF nodes to EXACTFU if they contain only
13850 * characters that match identically regardless of the target
13851 * string's UTF8ness. The reason to do this is that EXACTF is not
13852 * trie-able, EXACTFU is, and EXACTFU requires fewer operations at
13855 * Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they
13856 * contain only above-Latin1 characters (hence must be in UTF8),
13857 * which don't participate in folds with Latin1-range characters,
13858 * as the latter's folds aren't known until runtime. */
13859 bool maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC);
13861 /* Single-character EXACTish nodes are almost always SIMPLE. This
13862 * allows us to override this as encountered */
13863 U8 maybe_SIMPLE = SIMPLE;
13865 /* Does this node contain something that can't match unless the
13866 * target string is (also) in UTF-8 */
13867 bool requires_utf8_target = FALSE;
13869 /* The sequence 'ss' is problematic in non-UTF-8 patterns. */
13870 bool has_ss = FALSE;
13872 /* So is the MICRO SIGN */
13873 bool has_micro_sign = FALSE;
13875 /* Set when we fill up the current node and there is still more
13876 * text to process */
13879 /* Allocate an EXACT node. The node_type may change below to
13880 * another EXACTish node, but since the size of the node doesn't
13881 * change, it works */
13882 ret = regnode_guts(pRExC_state, node_type, current_string_nodes,
13884 FILL_NODE(ret, node_type);
13887 s = STRING(REGNODE_p(ret));
13898 maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC);
13899 maybe_SIMPLE = SIMPLE;
13900 requires_utf8_target = FALSE;
13902 has_micro_sign = FALSE;
13906 /* This breaks under rare circumstances. If folding, we do not
13907 * want to split a node at a character that is a non-final in a
13908 * multi-char fold, as an input string could just happen to want to
13909 * match across the node boundary. The code at the end of the loop
13910 * looks for this, and backs off until it finds not such a
13911 * character, but it is possible (though extremely, extremely
13912 * unlikely) for all characters in the node to be non-final fold
13913 * ones, in which case we just leave the node fully filled, and
13914 * hope that it doesn't match the string in just the wrong place */
13916 assert( ! UTF /* Is at the beginning of a character */
13917 || UTF8_IS_INVARIANT(UCHARAT(RExC_parse))
13918 || UTF8_IS_START(UCHARAT(RExC_parse)));
13920 overflowed = FALSE;
13922 /* Here, we have a literal character. Find the maximal string of
13923 * them in the input that we can fit into a single EXACTish node.
13924 * We quit at the first non-literal or when the node gets full, or
13925 * under /i the categorization of folding/non-folding character
13927 while (p < RExC_end && len < upper_fill) {
13929 /* In most cases each iteration adds one byte to the output.
13930 * The exceptions override this */
13931 Size_t added_len = 1;
13937 /* White space has already been ignored */
13938 assert( (RExC_flags & RXf_PMf_EXTENDED) == 0
13939 || ! is_PATWS_safe((p), RExC_end, UTF));
13951 /* Literal Escapes Switch
13953 This switch is meant to handle escape sequences that
13954 resolve to a literal character.
13956 Every escape sequence that represents something
13957 else, like an assertion or a char class, is handled
13958 in the switch marked 'Special Escapes' above in this
13959 routine, but also has an entry here as anything that
13960 isn't explicitly mentioned here will be treated as
13961 an unescaped equivalent literal.
13964 switch ((U8)*++p) {
13966 /* These are all the special escapes. */
13967 case 'A': /* Start assertion */
13968 case 'b': case 'B': /* Word-boundary assertion*/
13969 case 'C': /* Single char !DANGEROUS! */
13970 case 'd': case 'D': /* digit class */
13971 case 'g': case 'G': /* generic-backref, pos assertion */
13972 case 'h': case 'H': /* HORIZWS */
13973 case 'k': case 'K': /* named backref, keep marker */
13974 case 'p': case 'P': /* Unicode property */
13975 case 'R': /* LNBREAK */
13976 case 's': case 'S': /* space class */
13977 case 'v': case 'V': /* VERTWS */
13978 case 'w': case 'W': /* word class */
13979 case 'X': /* eXtended Unicode "combining
13980 character sequence" */
13981 case 'z': case 'Z': /* End of line/string assertion */
13985 /* Anything after here is an escape that resolves to a
13986 literal. (Except digits, which may or may not)
13992 case 'N': /* Handle a single-code point named character. */
13993 RExC_parse = p + 1;
13994 if (! grok_bslash_N(pRExC_state,
13995 NULL, /* Fail if evaluates to
13996 anything other than a
13997 single code point */
13998 &ender, /* The returned single code
14000 NULL, /* Don't need a count of
14001 how many code points */
14006 if (*flagp & NEED_UTF8)
14007 FAIL("panic: grok_bslash_N set NEED_UTF8");
14008 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
14010 /* Here, it wasn't a single code point. Go close
14011 * up this EXACTish node. The switch() prior to
14012 * this switch handles the other cases */
14013 RExC_parse = p = oldp;
14017 RExC_parse = parse_start;
14019 /* The \N{} means the pattern, if previously /d,
14020 * becomes /u. That means it can't be an EXACTF node,
14021 * but an EXACTFU */
14022 if (node_type == EXACTF) {
14023 node_type = EXACTFU;
14025 /* If the node already contains something that
14026 * differs between EXACTF and EXACTFU, reparse it
14028 if (! maybe_exactfu) {
14049 ender = ESC_NATIVE;
14059 const char* error_msg;
14061 bool valid = grok_bslash_o(&p,
14065 TO_OUTPUT_WARNINGS(p),
14066 (bool) RExC_strict,
14067 TRUE, /* Output warnings
14072 RExC_parse = p; /* going to die anyway; point
14073 to exact spot of failure */
14076 UPDATE_WARNINGS_LOC(p - 1);
14082 UV result = UV_MAX; /* initialize to erroneous
14084 const char* error_msg;
14086 bool valid = grok_bslash_x(&p,
14090 TO_OUTPUT_WARNINGS(p),
14091 (bool) RExC_strict,
14092 TRUE, /* Silence warnings
14097 RExC_parse = p; /* going to die anyway; point
14098 to exact spot of failure */
14101 UPDATE_WARNINGS_LOC(p - 1);
14105 if (ender < 0x100) {
14106 if (RExC_recode_x_to_native) {
14107 ender = LATIN1_TO_NATIVE(ender);
14115 ender = grok_bslash_c(*p, TO_OUTPUT_WARNINGS(p));
14116 UPDATE_WARNINGS_LOC(p);
14119 case '8': case '9': /* must be a backreference */
14121 /* we have an escape like \8 which cannot be an octal escape
14122 * so we exit the loop, and let the outer loop handle this
14123 * escape which may or may not be a legitimate backref. */
14125 case '1': case '2': case '3':case '4':
14126 case '5': case '6': case '7':
14127 /* When we parse backslash escapes there is ambiguity
14128 * between backreferences and octal escapes. Any escape
14129 * from \1 - \9 is a backreference, any multi-digit
14130 * escape which does not start with 0 and which when
14131 * evaluated as decimal could refer to an already
14132 * parsed capture buffer is a back reference. Anything
14135 * Note this implies that \118 could be interpreted as
14136 * 118 OR as "\11" . "8" depending on whether there
14137 * were 118 capture buffers defined already in the
14140 /* NOTE, RExC_npar is 1 more than the actual number of
14141 * parens we have seen so far, hence the "<" as opposed
14143 if ( !isDIGIT(p[1]) || S_backref_value(p, RExC_end) < RExC_npar)
14144 { /* Not to be treated as an octal constant, go
14152 I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
14154 ender = grok_oct(p, &numlen, &flags, NULL);
14156 if ( isDIGIT(*p) /* like \08, \178 */
14157 && ckWARN(WARN_REGEXP)
14160 reg_warn_non_literal_string(
14162 form_short_octal_warning(p, numlen));
14168 FAIL("Trailing \\");
14171 if (isALPHANUMERIC(*p)) {
14172 /* An alpha followed by '{' is going to fail next
14173 * iteration, so don't output this warning in that
14175 if (! isALPHA(*p) || *(p + 1) != '{') {
14176 ckWARN2reg(p + 1, "Unrecognized escape \\%.1s"
14177 " passed through", p);
14180 goto normal_default;
14181 } /* End of switch on '\' */
14184 /* Trying to gain new uses for '{' without breaking too
14185 * much existing code is hard. The solution currently
14187 * 1) If there is no ambiguity that a '{' should always
14188 * be taken literally, at the start of a construct, we
14190 * 2) If the literal '{' conflicts with our desired use
14191 * of it as a metacharacter, we die. The deprecation
14192 * cycles for this have come and gone.
14193 * 3) If there is ambiguity, we raise a simple warning.
14194 * This could happen, for example, if the user
14195 * intended it to introduce a quantifier, but slightly
14196 * misspelled the quantifier. Without this warning,
14197 * the quantifier would silently be taken as a literal
14198 * string of characters instead of a meta construct */
14199 if (len || (p > RExC_start && isALPHA_A(*(p - 1)))) {
14201 || ( p > parse_start + 1
14202 && isALPHA_A(*(p - 1))
14203 && *(p - 2) == '\\')
14204 || new_regcurly(p, RExC_end))
14206 RExC_parse = p + 1;
14207 vFAIL("Unescaped left brace in regex is "
14210 ckWARNreg(p + 1, "Unescaped left brace in regex is"
14211 " passed through");
14213 goto normal_default;
14216 if (p > RExC_parse && RExC_strict) {
14217 ckWARN2reg(p + 1, "Unescaped literal '%c'", *p);
14220 default: /* A literal character */
14222 if (! UTF8_IS_INVARIANT(*p) && UTF) {
14224 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
14225 &numlen, UTF8_ALLOW_DEFAULT);
14231 } /* End of switch on the literal */
14233 /* Here, have looked at the literal character, and <ender>
14234 * contains its ordinal; <p> points to the character after it.
14238 REQUIRE_UTF8(flagp);
14241 /* We need to check if the next non-ignored thing is a
14242 * quantifier. Move <p> to after anything that should be
14243 * ignored, which, as a side effect, positions <p> for the next
14244 * loop iteration */
14245 skip_to_be_ignored_text(pRExC_state, &p,
14246 FALSE /* Don't force to /x */ );
14248 /* If the next thing is a quantifier, it applies to this
14249 * character only, which means that this character has to be in
14250 * its own node and can't just be appended to the string in an
14251 * existing node, so if there are already other characters in
14252 * the node, close the node with just them, and set up to do
14253 * this character again next time through, when it will be the
14254 * only thing in its new node */
14256 next_is_quantifier = LIKELY(p < RExC_end)
14257 && UNLIKELY(ISMULT2(p));
14259 if (next_is_quantifier && LIKELY(len)) {
14264 /* Ready to add 'ender' to the node */
14266 if (! FOLD) { /* The simple case, just append the literal */
14269 /* Don't output if it would overflow */
14270 if (UNLIKELY(len > max_string_len - ((UTF)
14271 ? UVCHR_SKIP(ender)
14278 if (UVCHR_IS_INVARIANT(ender) || ! UTF) {
14279 *(s++) = (char) ender;
14282 U8 * new_s = uvchr_to_utf8((U8*)s, ender);
14283 added_len = (char *) new_s - s;
14284 s = (char *) new_s;
14287 requires_utf8_target = TRUE;
14291 else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) {
14293 /* Here are folding under /l, and the code point is
14294 * problematic. If this is the first character in the
14295 * node, change the node type to folding. Otherwise, if
14296 * this is the first problematic character, close up the
14297 * existing node, so can start a new node with this one */
14299 node_type = EXACTFL;
14300 RExC_contains_locale = 1;
14302 else if (node_type == EXACT) {
14307 /* This problematic code point means we can't simplify
14309 maybe_exactfu = FALSE;
14311 /* Here, we are adding a problematic fold character.
14312 * "Problematic" in this context means that its fold isn't
14313 * known until runtime. (The non-problematic code points
14314 * are the above-Latin1 ones that fold to also all
14315 * above-Latin1. Their folds don't vary no matter what the
14316 * locale is.) But here we have characters whose fold
14317 * depends on the locale. We just add in the unfolded
14318 * character, and wait until runtime to fold it */
14319 goto not_fold_common;
14321 else /* regular fold; see if actually is in a fold */
14322 if ( (ender < 256 && ! IS_IN_SOME_FOLD_L1(ender))
14324 && ! _invlist_contains_cp(PL_in_some_fold, ender)))
14326 /* Here, folding, but the character isn't in a fold.
14328 * Start a new node if previous characters in the node were
14330 if (len && node_type != EXACT) {
14335 /* Here, continuing a node with non-folded characters. Add
14337 goto not_fold_common;
14339 else { /* Here, does participate in some fold */
14341 /* If this is the first character in the node, change its
14342 * type to folding. Otherwise, if this is the first
14343 * folding character in the node, close up the existing
14344 * node, so can start a new node with this one. */
14346 node_type = compute_EXACTish(pRExC_state);
14348 else if (node_type == EXACT) {
14353 if (UTF) { /* Alway use the folded value for UTF-8
14355 if (UVCHR_IS_INVARIANT(ender)) {
14356 if (UNLIKELY(len + 1 > max_string_len)) {
14361 *(s)++ = (U8) toFOLD(ender);
14364 UV folded = _to_uni_fold_flags(
14366 (U8 *) s, /* We have allocated extra space
14367 in 's' so can't run off the
14370 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
14371 ? FOLD_FLAGS_NOMIX_ASCII
14373 if (UNLIKELY(len + added_len > max_string_len)) {
14381 && LIKELY(folded != GREEK_SMALL_LETTER_MU))
14383 /* U+B5 folds to the MU, so its possible for a
14384 * non-UTF-8 target to match it */
14385 requires_utf8_target = TRUE;
14389 else { /* Here is non-UTF8. */
14391 /* The fold will be one or (rarely) two characters.
14392 * Check that there's room for at least a single one
14393 * before setting any flags, etc. Because otherwise an
14394 * overflowing character could cause a flag to be set
14395 * even though it doesn't end up in this node. (For
14396 * the two character fold, we check again, before
14397 * setting any flags) */
14398 if (UNLIKELY(len + 1 > max_string_len)) {
14403 #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
14404 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
14405 || UNICODE_DOT_DOT_VERSION > 0)
14407 /* On non-ancient Unicodes, check for the only possible
14408 * multi-char fold */
14409 if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) {
14411 /* This potential multi-char fold means the node
14412 * can't be simple (because it could match more
14413 * than a single char). And in some cases it will
14414 * match 'ss', so set that flag */
14418 /* It can't change to be an EXACTFU (unless already
14419 * is one). We fold it iff under /u rules. */
14420 if (node_type != EXACTFU) {
14421 maybe_exactfu = FALSE;
14424 if (UNLIKELY(len + 2 > max_string_len)) {
14433 goto done_with_this_char;
14436 else if ( UNLIKELY(isALPHA_FOLD_EQ(ender, 's'))
14438 && UNLIKELY(isALPHA_FOLD_EQ(*(s-1), 's')))
14440 /* Also, the sequence 'ss' is special when not
14441 * under /u. If the target string is UTF-8, it
14442 * should match SHARP S; otherwise it won't. So,
14443 * here we have to exclude the possibility of this
14444 * node moving to /u.*/
14446 maybe_exactfu = FALSE;
14449 /* Here, the fold will be a single character */
14451 if (UNLIKELY(ender == MICRO_SIGN)) {
14452 has_micro_sign = TRUE;
14454 else if (PL_fold[ender] != PL_fold_latin1[ender]) {
14456 /* If the character's fold differs between /d and
14457 * /u, this can't change to be an EXACTFU node */
14458 maybe_exactfu = FALSE;
14461 *(s++) = (DEPENDS_SEMANTICS)
14462 ? (char) toFOLD(ender)
14464 /* Under /u, the fold of any character in
14465 * the 0-255 range happens to be its
14466 * lowercase equivalent, except for LATIN
14467 * SMALL LETTER SHARP S, which was handled
14468 * above, and the MICRO SIGN, whose fold
14469 * requires UTF-8 to represent. */
14470 : (char) toLOWER_L1(ender);
14472 } /* End of adding current character to the node */
14474 done_with_this_char:
14478 if (next_is_quantifier) {
14480 /* Here, the next input is a quantifier, and to get here,
14481 * the current character is the only one in the node. */
14485 } /* End of loop through literal characters */
14487 /* Here we have either exhausted the input or run out of room in
14488 * the node. If the former, we are done. (If we encountered a
14489 * character that can't be in the node, transfer is made directly
14490 * to <loopdone>, and so we wouldn't have fallen off the end of the
14492 if (LIKELY(! overflowed)) {
14496 /* Here we have run out of room. We can grow plain EXACT and
14497 * LEXACT nodes. If the pattern is gigantic enough, though,
14498 * eventually we'll have to artificially chunk the pattern into
14499 * multiple nodes. */
14500 if (! LOC && (node_type == EXACT || node_type == LEXACT)) {
14501 Size_t overhead = 1 + regarglen[OP(REGNODE_p(ret))];
14502 Size_t overhead_expansion = 0;
14504 Size_t max_nodes_for_string;
14508 /* Here we couldn't fit the final character in the current
14509 * node, so it will have to be reparsed, no matter what else we
14513 /* If would have overflowed a regular EXACT node, switch
14514 * instead to an LEXACT. The code below is structured so that
14515 * the actual growing code is common to changing from an EXACT
14516 * or just increasing the LEXACT size. This means that we have
14517 * to save the string in the EXACT case before growing, and
14518 * then copy it afterwards to its new location */
14519 if (node_type == EXACT) {
14520 overhead_expansion = regarglen[LEXACT] - regarglen[EXACT];
14521 RExC_emit += overhead_expansion;
14522 Copy(s0, temp, len, char);
14525 /* Ready to grow. If it was a plain EXACT, the string was
14526 * saved, and the first few bytes of it overwritten by adding
14527 * an argument field. We assume, as we do elsewhere in this
14528 * file, that one byte of remaining input will translate into
14529 * one byte of output, and if that's too small, we grow again,
14530 * if too large the excess memory is freed at the end */
14532 max_nodes_for_string = U16_MAX - overhead - overhead_expansion;
14533 achievable = MIN(max_nodes_for_string,
14534 current_string_nodes + STR_SZ(RExC_end - p));
14535 delta = achievable - current_string_nodes;
14537 /* If there is just no more room, go finish up this chunk of
14543 change_engine_size(pRExC_state, delta + overhead_expansion);
14544 current_string_nodes += delta;
14546 = sizeof(struct regnode) * current_string_nodes;
14547 upper_fill = max_string_len + 1;
14549 /* If the length was small, we know this was originally an
14550 * EXACT node now converted to LEXACT, and the string has to be
14551 * restored. Otherwise the string was untouched. 260 is just
14552 * a number safely above 255 so don't have to worry about
14553 * getting it precise */
14555 node_type = LEXACT;
14556 FILL_NODE(ret, node_type);
14557 s0 = STRING(REGNODE_p(ret));
14558 Copy(temp, s0, len, char);
14562 goto continue_parse;
14565 bool splittable = FALSE;
14566 bool backed_up = FALSE;
14570 /* Here is /i. Running out of room creates a problem if we are
14571 * folding, and the split happens in the middle of a
14572 * multi-character fold, as a match that should have occurred,
14573 * won't, due to the way nodes are matched, and our artificial
14574 * boundary. So back off until we aren't splitting such a
14575 * fold. If there is no such place to back off to, we end up
14576 * taking the entire node as-is. This can happen if the node
14577 * consists entirely of 'f' or entirely of 's' characters (or
14578 * things that fold to them) as 'ff' and 'ss' are
14579 * multi-character folds.
14581 * The Unicode standard says that multi character folds consist
14582 * of either two or three characters. That means we would be
14583 * splitting one if the final character in the node is at the
14584 * beginning of either type, or is the second of a three
14588 * ender is the code point of the character that won't fit
14590 * s points to just beyond the final byte in the node.
14591 * It's where we would place ender if there were
14592 * room, and where in fact we do place ender's fold
14593 * in the code below, as we've over-allocated space
14594 * for s0 (hence s) to allow for this
14595 * e starts at 's' and advances as we append things.
14596 * old_s is the same as 's'. (If ender had fit, 's' would
14597 * have been advanced to beyond it).
14598 * old_old_s points to the beginning byte of the final
14599 * character in the node
14600 * p points to the beginning byte in the input of the
14601 * character beyond 'ender'.
14602 * oldp points to the beginning byte in the input of
14605 * In the case of /il, we haven't folded anything that could be
14606 * affected by the locale. That means only above-Latin1
14607 * characters that fold to other above-latin1 characters get
14608 * folded at compile time. To check where a good place to
14609 * split nodes is, everything in it will have to be folded.
14610 * The boolean 'maybe_exactfu' keeps track in /il if there are
14611 * any unfolded characters in the node. */
14612 bool need_to_fold_loc = LOC && ! maybe_exactfu;
14614 /* If we do need to fold the node, we need a place to store the
14615 * folded copy, and a way to map back to the unfolded original
14617 char * locfold_buf = NULL;
14618 Size_t * loc_correspondence = NULL;
14620 if (! need_to_fold_loc) { /* The normal case. Just
14621 initialize to the actual node */
14624 s = old_old_s; /* Point to the beginning of the final char
14625 that fits in the node */
14629 /* Here, we have filled a /il node, and there are unfolded
14630 * characters in it. If the runtime locale turns out to be
14631 * UTF-8, there are possible multi-character folds, just
14632 * like when not under /l. The node hence can't terminate
14633 * in the middle of such a fold. To determine this, we
14634 * have to create a folded copy of this node. That means
14635 * reparsing the node, folding everything assuming a UTF-8
14636 * locale. (If at runtime it isn't such a locale, the
14637 * actions here wouldn't have been necessary, but we have
14638 * to assume the worst case.) If we find we need to back
14639 * off the folded string, we do so, and then map that
14640 * position back to the original unfolded node, which then
14641 * gets output, truncated at that spot */
14643 char * redo_p = RExC_parse;
14647 /* Allow enough space assuming a single byte input folds to
14648 * a single byte output, plus assume that the two unparsed
14649 * characters (that we may need) fold to the largest number
14650 * of bytes possible, plus extra for one more worst case
14651 * scenario. In the loop below, if we start eating into
14652 * that final spare space, we enlarge this initial space */
14653 Size_t size = max_string_len + (3 * UTF8_MAXBYTES_CASE) + 1;
14655 Newxz(locfold_buf, size, char);
14656 Newxz(loc_correspondence, size, Size_t);
14658 /* Redo this node's parse, folding into 'locfold_buf' */
14659 redo_p = RExC_parse;
14660 old_redo_e = redo_e = locfold_buf;
14661 while (redo_p <= oldp) {
14663 old_redo_e = redo_e;
14664 loc_correspondence[redo_e - locfold_buf]
14665 = redo_p - RExC_parse;
14670 (void) _to_utf8_fold_flags((U8 *) redo_p,
14675 redo_e += added_len;
14676 redo_p += UTF8SKIP(redo_p);
14680 /* Note that if this code is run on some ancient
14681 * Unicode versions, SHARP S doesn't fold to 'ss',
14682 * but rather than clutter the code with #ifdef's,
14683 * as is done above, we ignore that possibility.
14684 * This is ok because this code doesn't affect what
14685 * gets matched, but merely where the node gets
14687 if (UCHARAT(redo_p) != LATIN_SMALL_LETTER_SHARP_S) {
14688 *redo_e++ = toLOWER_L1(UCHARAT(redo_p));
14698 /* If we're getting so close to the end that a
14699 * worst-case fold in the next character would cause us
14700 * to overflow, increase, assuming one byte output byte
14701 * per one byte input one, plus room for another worst
14703 if ( redo_p <= oldp
14704 && redo_e > locfold_buf + size
14705 - (UTF8_MAXBYTES_CASE + 1))
14707 Size_t new_size = size
14709 + UTF8_MAXBYTES_CASE + 1;
14710 Ptrdiff_t e_offset = redo_e - locfold_buf;
14712 Renew(locfold_buf, new_size, char);
14713 Renew(loc_correspondence, new_size, Size_t);
14716 redo_e = locfold_buf + e_offset;
14720 /* Set so that things are in terms of the folded, temporary
14723 s_start = locfold_buf;
14728 /* Here, we have 's', 's_start' and 'e' set up to point to the
14729 * input that goes into the node, folded.
14731 * If the final character of the node and the fold of ender
14732 * form the first two characters of a three character fold, we
14733 * need to peek ahead at the next (unparsed) character in the
14734 * input to determine if the three actually do form such a
14735 * fold. Just looking at that character is not generally
14736 * sufficient, as it could be, for example, an escape sequence
14737 * that evaluates to something else, and it needs to be folded.
14739 * khw originally thought to just go through the parse loop one
14740 * extra time, but that doesn't work easily as that iteration
14741 * could cause things to think that the parse is over and to
14742 * goto loopdone. The character could be a '$' for example, or
14743 * the character beyond could be a quantifier, and other
14744 * glitches as well.
14746 * The solution used here for peeking ahead is to look at that
14747 * next character. If it isn't ASCII punctuation, then it will
14748 * be something that continues in an EXACTish node if there
14749 * were space. We append the fold of it to s, having reserved
14750 * enough room in s0 for the purpose. If we can't reasonably
14751 * peek ahead, we instead assume the worst case: that it is
14752 * something that would form the completion of a multi-char
14755 * If we can't split between s and ender, we work backwards
14756 * character-by-character down to s0. At each current point
14757 * see if we are at the beginning of a multi-char fold. If so,
14758 * that means we would be splitting the fold across nodes, and
14759 * so we back up one and try again.
14761 * If we're not at the beginning, we still could be at the
14762 * final two characters of a (rare) three character fold. We
14763 * check if the sequence starting at the character before the
14764 * current position (and including the current and next
14765 * characters) is a three character fold. If not, the node can
14766 * be split here. If it is, we have to backup two characters
14769 * Otherwise, the node can be split at the current position.
14771 * The same logic is used for UTF-8 patterns and not */
14775 /* Append the fold of ender */
14776 (void) _to_uni_fold_flags(
14780 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
14781 ? FOLD_FLAGS_NOMIX_ASCII
14785 /* 's' and the character folded to by ender may be the
14786 * first two of a three-character fold, in which case the
14787 * node should not be split here. That may mean examining
14788 * the so-far unparsed character starting at 'p'. But if
14789 * ender folded to more than one character, we already have
14790 * three characters to look at. Also, we first check if
14791 * the sequence consisting of s and the next character form
14792 * the first two of some three character fold. If not,
14793 * there's no need to peek ahead. */
14794 if ( added_len <= UTF8SKIP(e - added_len)
14795 && UNLIKELY(is_THREE_CHAR_FOLD_HEAD_utf8_safe(s, e)))
14797 /* Here, the two do form the beginning of a potential
14798 * three character fold. The unexamined character may
14799 * or may not complete it. Peek at it. It might be
14800 * something that ends the node or an escape sequence,
14801 * in which case we don't know without a lot of work
14802 * what it evaluates to, so we have to assume the worst
14803 * case: that it does complete the fold, and so we
14804 * can't split here. All such instances will have
14805 * that character be an ASCII punctuation character,
14806 * like a backslash. So, for that case, backup one and
14807 * drop down to try at that position */
14809 s = (char *) utf8_hop_back((U8 *) s, -1,
14814 /* Here, since it's not punctuation, it must be a
14815 * real character, and we can append its fold to
14816 * 'e' (having deliberately reserved enough space
14817 * for this eventuality) and drop down to check if
14818 * the three actually do form a folded sequence */
14819 (void) _to_utf8_fold_flags(
14820 (U8 *) p, (U8 *) RExC_end,
14823 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
14824 ? FOLD_FLAGS_NOMIX_ASCII
14830 /* Here, we either have three characters available in
14831 * sequence starting at 's', or we have two characters and
14832 * know that the following one can't possibly be part of a
14833 * three character fold. We go through the node backwards
14834 * until we find a place where we can split it without
14835 * breaking apart a multi-character fold. At any given
14836 * point we have to worry about if such a fold begins at
14837 * the current 's', and also if a three-character fold
14838 * begins at s-1, (containing s and s+1). Splitting in
14839 * either case would break apart a fold */
14841 char *prev_s = (char *) utf8_hop_back((U8 *) s, -1,
14844 /* If is a multi-char fold, can't split here. Backup
14845 * one char and try again */
14846 if (UNLIKELY(is_MULTI_CHAR_FOLD_utf8_safe(s, e))) {
14852 /* If the two characters beginning at 's' are part of a
14853 * three character fold starting at the character
14854 * before s, we can't split either before or after s.
14855 * Backup two chars and try again */
14856 if ( LIKELY(s > s_start)
14857 && UNLIKELY(is_THREE_CHAR_FOLD_utf8_safe(prev_s, e)))
14860 s = (char *) utf8_hop_back((U8 *) s, -1, (U8 *) s_start);
14865 /* Here there's no multi-char fold between s and the
14866 * next character following it. We can split */
14870 } while (s > s_start); /* End of loops backing up through the node */
14872 /* Here we either couldn't find a place to split the node,
14873 * or else we broke out of the loop setting 'splittable' to
14874 * true. In the latter case, the place to split is between
14875 * the first and second characters in the sequence starting
14881 else { /* Pattern not UTF-8 */
14882 if ( ender != LATIN_SMALL_LETTER_SHARP_S
14883 || ASCII_FOLD_RESTRICTED)
14885 *e++ = toLOWER_L1(ender);
14893 && UNLIKELY(is_THREE_CHAR_FOLD_HEAD_latin1_safe(s, e)))
14900 if ( UCHARAT(p) != LATIN_SMALL_LETTER_SHARP_S
14901 || ASCII_FOLD_RESTRICTED)
14903 *e++ = toLOWER_L1(ender);
14913 if (UNLIKELY(is_MULTI_CHAR_FOLD_latin1_safe(s, e))) {
14919 if ( LIKELY(s > s_start)
14920 && UNLIKELY(is_THREE_CHAR_FOLD_latin1_safe(s - 1, e)))
14930 } while (s > s_start);
14937 /* Here, we are done backing up. If we didn't backup at all
14938 * (the likely case), just proceed */
14941 /* If we did find a place to split, reparse the entire node
14942 * stopping where we have calculated. */
14945 /* If we created a temporary folded string under /l, we
14946 * have to map that back to the original */
14947 if (need_to_fold_loc) {
14948 upper_fill = loc_correspondence[s - s_start];
14949 Safefree(locfold_buf);
14950 Safefree(loc_correspondence);
14952 if (upper_fill == 0) {
14953 FAIL2("panic: loc_correspondence[%d] is 0",
14954 (int) (s - s_start));
14958 upper_fill = s - s0;
14962 else if (need_to_fold_loc) {
14963 Safefree(locfold_buf);
14964 Safefree(loc_correspondence);
14967 /* Here the node consists entirely of non-final multi-char
14968 * folds. (Likely it is all 'f's or all 's's.) There's no
14969 * decent place to split it, so give up and just take the
14973 } /* End of verifying node ends with an appropriate char */
14975 /* We need to start the next node at the character that didn't fit
14979 loopdone: /* Jumped to when encounters something that shouldn't be
14982 /* Free up any over-allocated space; cast is to silence bogus
14983 * warning in MS VC */
14984 change_engine_size(pRExC_state,
14985 - (Ptrdiff_t) (current_string_nodes - STR_SZ(len)));
14987 /* I (khw) don't know if you can get here with zero length, but the
14988 * old code handled this situation by creating a zero-length EXACT
14989 * node. Might as well be NOTHING instead */
14991 OP(REGNODE_p(ret)) = NOTHING;
14995 /* If the node type is EXACT here, check to see if it
14996 * should be EXACTL, or EXACT_REQ8. */
14997 if (node_type == EXACT) {
14999 node_type = EXACTL;
15001 else if (requires_utf8_target) {
15002 node_type = EXACT_REQ8;
15005 else if (node_type == LEXACT) {
15006 if (requires_utf8_target) {
15007 node_type = LEXACT_REQ8;
15011 if ( UNLIKELY(has_micro_sign || has_ss)
15012 && (node_type == EXACTFU || ( node_type == EXACTF
15013 && maybe_exactfu)))
15014 { /* These two conditions are problematic in non-UTF-8
15017 node_type = EXACTFUP;
15019 else if (node_type == EXACTFL) {
15021 /* 'maybe_exactfu' is deliberately set above to
15022 * indicate this node type, where all code points in it
15024 if (maybe_exactfu) {
15025 node_type = EXACTFLU8;
15028 _invlist_contains_cp(PL_HasMultiCharFold, ender)))
15030 /* A character that folds to more than one will
15031 * match multiple characters, so can't be SIMPLE.
15032 * We don't have to worry about this with EXACTFLU8
15033 * nodes just above, as they have already been
15034 * folded (since the fold doesn't vary at run
15035 * time). Here, if the final character in the node
15036 * folds to multiple, it can't be simple. (This
15037 * only has an effect if the node has only a single
15038 * character, hence the final one, as elsewhere we
15039 * turn off simple for nodes whose length > 1 */
15043 else if (node_type == EXACTF) { /* Means is /di */
15045 /* This intermediate variable is needed solely because
15046 * the asserts in the macro where used exceed Win32's
15047 * literal string capacity */
15048 char first_char = * STRING(REGNODE_p(ret));
15050 /* If 'maybe_exactfu' is clear, then we need to stay
15051 * /di. If it is set, it means there are no code
15052 * points that match differently depending on UTF8ness
15053 * of the target string, so it can become an EXACTFU
15055 if (! maybe_exactfu) {
15056 RExC_seen_d_op = TRUE;
15058 else if ( isALPHA_FOLD_EQ(first_char, 's')
15059 || isALPHA_FOLD_EQ(ender, 's'))
15061 /* But, if the node begins or ends in an 's' we
15062 * have to defer changing it into an EXACTFU, as
15063 * the node could later get joined with another one
15064 * that ends or begins with 's' creating an 'ss'
15065 * sequence which would then wrongly match the
15066 * sharp s without the target being UTF-8. We
15067 * create a special node that we resolve later when
15068 * we join nodes together */
15070 node_type = EXACTFU_S_EDGE;
15073 node_type = EXACTFU;
15077 if (requires_utf8_target && node_type == EXACTFU) {
15078 node_type = EXACTFU_REQ8;
15082 OP(REGNODE_p(ret)) = node_type;
15083 setSTR_LEN(REGNODE_p(ret), len);
15084 RExC_emit += STR_SZ(len);
15086 /* If the node isn't a single character, it can't be SIMPLE */
15087 if (len > (Size_t) ((UTF) ? UTF8SKIP(STRING(REGNODE_p(ret))) : 1)) {
15091 *flagp |= HASWIDTH | maybe_SIMPLE;
15094 Set_Node_Length(REGNODE_p(ret), p - parse_start - 1);
15098 /* len is STRLEN which is unsigned, need to copy to signed */
15101 vFAIL("Internal disaster");
15104 } /* End of label 'defchar:' */
15106 } /* End of giant switch on input character */
15108 /* Position parse to next real character */
15109 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
15110 FALSE /* Don't force to /x */ );
15111 if ( *RExC_parse == '{'
15112 && OP(REGNODE_p(ret)) != SBOL && ! regcurly(RExC_parse))
15114 if (RExC_strict || new_regcurly(RExC_parse, RExC_end)) {
15116 vFAIL("Unescaped left brace in regex is illegal here");
15118 ckWARNreg(RExC_parse + 1, "Unescaped left brace in regex is"
15119 " passed through");
15127 S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr)
15129 /* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'. It
15130 * sets up the bitmap and any flags, removing those code points from the
15131 * inversion list, setting it to NULL should it become completely empty */
15135 PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST;
15136 assert(PL_regkind[OP(node)] == ANYOF);
15138 /* There is no bitmap for this node type */
15139 if (inRANGE(OP(node), ANYOFH, ANYOFRb)) {
15143 ANYOF_BITMAP_ZERO(node);
15144 if (*invlist_ptr) {
15146 /* This gets set if we actually need to modify things */
15147 bool change_invlist = FALSE;
15151 /* Start looking through *invlist_ptr */
15152 invlist_iterinit(*invlist_ptr);
15153 while (invlist_iternext(*invlist_ptr, &start, &end)) {
15157 if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) {
15158 ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP;
15161 /* Quit if are above what we should change */
15162 if (start >= NUM_ANYOF_CODE_POINTS) {
15166 change_invlist = TRUE;
15168 /* Set all the bits in the range, up to the max that we are doing */
15169 high = (end < NUM_ANYOF_CODE_POINTS - 1)
15171 : NUM_ANYOF_CODE_POINTS - 1;
15172 for (i = start; i <= (int) high; i++) {
15173 if (! ANYOF_BITMAP_TEST(node, i)) {
15174 ANYOF_BITMAP_SET(node, i);
15178 invlist_iterfinish(*invlist_ptr);
15180 /* Done with loop; remove any code points that are in the bitmap from
15181 * *invlist_ptr; similarly for code points above the bitmap if we have
15182 * a flag to match all of them anyways */
15183 if (change_invlist) {
15184 _invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr);
15186 if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
15187 _invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr);
15190 /* If have completely emptied it, remove it completely */
15191 if (_invlist_len(*invlist_ptr) == 0) {
15192 SvREFCNT_dec_NN(*invlist_ptr);
15193 *invlist_ptr = NULL;
15198 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
15199 Character classes ([:foo:]) can also be negated ([:^foo:]).
15200 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
15201 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
15202 but trigger failures because they are currently unimplemented. */
15204 #define POSIXCC_DONE(c) ((c) == ':')
15205 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
15206 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
15207 #define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';')
15209 #define WARNING_PREFIX "Assuming NOT a POSIX class since "
15210 #define NO_BLANKS_POSIX_WARNING "no blanks are allowed in one"
15211 #define SEMI_COLON_POSIX_WARNING "a semi-colon was found instead of a colon"
15213 #define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1)
15215 /* 'posix_warnings' and 'warn_text' are names of variables in the following
15217 #define ADD_POSIX_WARNING(p, text) STMT_START { \
15218 if (posix_warnings) { \
15219 if (! RExC_warn_text ) RExC_warn_text = \
15220 (AV *) sv_2mortal((SV *) newAV()); \
15221 av_push(RExC_warn_text, Perl_newSVpvf(aTHX_ \
15225 REPORT_LOCATION_ARGS(p))); \
15228 #define CLEAR_POSIX_WARNINGS() \
15230 if (posix_warnings && RExC_warn_text) \
15231 av_clear(RExC_warn_text); \
15234 #define CLEAR_POSIX_WARNINGS_AND_RETURN(ret) \
15236 CLEAR_POSIX_WARNINGS(); \
15241 S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state,
15243 const char * const s, /* Where the putative posix class begins.
15244 Normally, this is one past the '['. This
15245 parameter exists so it can be somewhere
15246 besides RExC_parse. */
15247 char ** updated_parse_ptr, /* Where to set the updated parse pointer, or
15249 AV ** posix_warnings, /* Where to place any generated warnings, or
15251 const bool check_only /* Don't die if error */
15254 /* This parses what the caller thinks may be one of the three POSIX
15256 * 1) a character class, like [:blank:]
15257 * 2) a collating symbol, like [. .]
15258 * 3) an equivalence class, like [= =]
15259 * In the latter two cases, it croaks if it finds a syntactically legal
15260 * one, as these are not handled by Perl.
15262 * The main purpose is to look for a POSIX character class. It returns:
15263 * a) the class number
15264 * if it is a completely syntactically and semantically legal class.
15265 * 'updated_parse_ptr', if not NULL, is set to point to just after the
15266 * closing ']' of the class
15267 * b) OOB_NAMEDCLASS
15268 * if it appears that one of the three POSIX constructs was meant, but
15269 * its specification was somehow defective. 'updated_parse_ptr', if
15270 * not NULL, is set to point to the character just after the end
15271 * character of the class. See below for handling of warnings.
15272 * c) NOT_MEANT_TO_BE_A_POSIX_CLASS
15273 * if it doesn't appear that a POSIX construct was intended.
15274 * 'updated_parse_ptr' is not changed. No warnings nor errors are
15277 * In b) there may be errors or warnings generated. If 'check_only' is
15278 * TRUE, then any errors are discarded. Warnings are returned to the
15279 * caller via an AV* created into '*posix_warnings' if it is not NULL. If
15280 * instead it is NULL, warnings are suppressed.
15282 * The reason for this function, and its complexity is that a bracketed
15283 * character class can contain just about anything. But it's easy to
15284 * mistype the very specific posix class syntax but yielding a valid
15285 * regular bracketed class, so it silently gets compiled into something
15286 * quite unintended.
15288 * The solution adopted here maintains backward compatibility except that
15289 * it adds a warning if it looks like a posix class was intended but
15290 * improperly specified. The warning is not raised unless what is input
15291 * very closely resembles one of the 14 legal posix classes. To do this,
15292 * it uses fuzzy parsing. It calculates how many single-character edits it
15293 * would take to transform what was input into a legal posix class. Only
15294 * if that number is quite small does it think that the intention was a
15295 * posix class. Obviously these are heuristics, and there will be cases
15296 * where it errs on one side or another, and they can be tweaked as
15297 * experience informs.
15299 * The syntax for a legal posix class is:
15301 * qr/(?xa: \[ : \^? [[:lower:]]{4,6} : \] )/
15303 * What this routine considers syntactically to be an intended posix class
15304 * is this (the comments indicate some restrictions that the pattern
15307 * qr/(?x: \[? # The left bracket, possibly
15309 * \h* # possibly followed by blanks
15310 * (?: \^ \h* )? # possibly a misplaced caret
15311 * [:;]? # The opening class character,
15312 * # possibly omitted. A typo
15313 * # semi-colon can also be used.
15315 * \^? # possibly a correctly placed
15316 * # caret, but not if there was also
15317 * # a misplaced one
15319 * .{3,15} # The class name. If there are
15320 * # deviations from the legal syntax,
15321 * # its edit distance must be close
15322 * # to a real class name in order
15323 * # for it to be considered to be
15324 * # an intended posix class.
15326 * [[:punct:]]? # The closing class character,
15327 * # possibly omitted. If not a colon
15328 * # nor semi colon, the class name
15329 * # must be even closer to a valid
15332 * \]? # The right bracket, possibly
15336 * In the above, \h must be ASCII-only.
15338 * These are heuristics, and can be tweaked as field experience dictates.
15339 * There will be cases when someone didn't intend to specify a posix class
15340 * that this warns as being so. The goal is to minimize these, while
15341 * maximizing the catching of things intended to be a posix class that
15342 * aren't parsed as such.
15346 const char * const e = RExC_end;
15347 unsigned complement = 0; /* If to complement the class */
15348 bool found_problem = FALSE; /* Assume OK until proven otherwise */
15349 bool has_opening_bracket = FALSE;
15350 bool has_opening_colon = FALSE;
15351 int class_number = OOB_NAMEDCLASS; /* Out-of-bounds until find
15353 const char * possible_end = NULL; /* used for a 2nd parse pass */
15354 const char* name_start; /* ptr to class name first char */
15356 /* If the number of single-character typos the input name is away from a
15357 * legal name is no more than this number, it is considered to have meant
15358 * the legal name */
15359 int max_distance = 2;
15361 /* to store the name. The size determines the maximum length before we
15362 * decide that no posix class was intended. Should be at least
15363 * sizeof("alphanumeric") */
15365 STATIC_ASSERT_DECL(C_ARRAY_LENGTH(input_text) >= sizeof "alphanumeric");
15367 PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX;
15369 CLEAR_POSIX_WARNINGS();
15372 return NOT_MEANT_TO_BE_A_POSIX_CLASS;
15375 if (*(p - 1) != '[') {
15376 ADD_POSIX_WARNING(p, "it doesn't start with a '['");
15377 found_problem = TRUE;
15380 has_opening_bracket = TRUE;
15383 /* They could be confused and think you can put spaces between the
15386 found_problem = TRUE;
15390 } while (p < e && isBLANK(*p));
15392 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15395 /* For [. .] and [= =]. These are quite different internally from [: :],
15396 * so they are handled separately. */
15397 if (POSIXCC_NOTYET(*p) && p < e - 3) /* 1 for the close, and 1 for the ']'
15398 and 1 for at least one char in it
15401 const char open_char = *p;
15402 const char * temp_ptr = p + 1;
15404 /* These two constructs are not handled by perl, and if we find a
15405 * syntactically valid one, we croak. khw, who wrote this code, finds
15406 * this explanation of them very unclear:
15407 * http://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html
15408 * And searching the rest of the internet wasn't very helpful either.
15409 * It looks like just about any byte can be in these constructs,
15410 * depending on the locale. But unless the pattern is being compiled
15411 * under /l, which is very rare, Perl runs under the C or POSIX locale.
15412 * In that case, it looks like [= =] isn't allowed at all, and that
15413 * [. .] could be any single code point, but for longer strings the
15414 * constituent characters would have to be the ASCII alphabetics plus
15415 * the minus-hyphen. Any sensible locale definition would limit itself
15416 * to these. And any portable one definitely should. Trying to parse
15417 * the general case is a nightmare (see [perl #127604]). So, this code
15418 * looks only for interiors of these constructs that match:
15420 * Using \w relaxes the apparent rules a little, without adding much
15421 * danger of mistaking something else for one of these constructs.
15423 * [. .] in some implementations described on the internet is usable to
15424 * escape a character that otherwise is special in bracketed character
15425 * classes. For example [.].] means a literal right bracket instead of
15426 * the ending of the class
15428 * [= =] can legitimately contain a [. .] construct, but we don't
15429 * handle this case, as that [. .] construct will later get parsed
15430 * itself and croak then. And [= =] is checked for even when not under
15431 * /l, as Perl has long done so.
15433 * The code below relies on there being a trailing NUL, so it doesn't
15434 * have to keep checking if the parse ptr < e.
15436 if (temp_ptr[1] == open_char) {
15439 else while ( temp_ptr < e
15440 && (isWORDCHAR(*temp_ptr) || *temp_ptr == '-'))
15445 if (*temp_ptr == open_char) {
15447 if (*temp_ptr == ']') {
15449 if (! found_problem && ! check_only) {
15450 RExC_parse = (char *) temp_ptr;
15451 vFAIL3("POSIX syntax [%c %c] is reserved for future "
15452 "extensions", open_char, open_char);
15455 /* Here, the syntax wasn't completely valid, or else the call
15456 * is to check-only */
15457 if (updated_parse_ptr) {
15458 *updated_parse_ptr = (char *) temp_ptr;
15461 CLEAR_POSIX_WARNINGS_AND_RETURN(OOB_NAMEDCLASS);
15465 /* If we find something that started out to look like one of these
15466 * constructs, but isn't, we continue below so that it can be checked
15467 * for being a class name with a typo of '.' or '=' instead of a colon.
15471 /* Here, we think there is a possibility that a [: :] class was meant, and
15472 * we have the first real character. It could be they think the '^' comes
15475 found_problem = TRUE;
15476 ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon");
15481 found_problem = TRUE;
15485 } while (p < e && isBLANK(*p));
15487 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15491 /* But the first character should be a colon, which they could have easily
15492 * mistyped on a qwerty keyboard as a semi-colon (and which may be hard to
15493 * distinguish from a colon, so treat that as a colon). */
15496 has_opening_colon = TRUE;
15498 else if (*p == ';') {
15499 found_problem = TRUE;
15501 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15502 has_opening_colon = TRUE;
15505 found_problem = TRUE;
15506 ADD_POSIX_WARNING(p, "there must be a starting ':'");
15508 /* Consider an initial punctuation (not one of the recognized ones) to
15509 * be a left terminator */
15510 if (*p != '^' && *p != ']' && isPUNCT(*p)) {
15515 /* They may think that you can put spaces between the components */
15517 found_problem = TRUE;
15521 } while (p < e && isBLANK(*p));
15523 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15528 /* We consider something like [^:^alnum:]] to not have been intended to
15529 * be a posix class, but XXX maybe we should */
15531 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15538 /* Again, they may think that you can put spaces between the components */
15540 found_problem = TRUE;
15544 } while (p < e && isBLANK(*p));
15546 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15551 /* XXX This ']' may be a typo, and something else was meant. But
15552 * treating it as such creates enough complications, that that
15553 * possibility isn't currently considered here. So we assume that the
15554 * ']' is what is intended, and if we've already found an initial '[',
15555 * this leaves this construct looking like [:] or [:^], which almost
15556 * certainly weren't intended to be posix classes */
15557 if (has_opening_bracket) {
15558 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15561 /* But this function can be called when we parse the colon for
15562 * something like qr/[alpha:]]/, so we back up to look for the
15567 found_problem = TRUE;
15568 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15570 else if (*p != ':') {
15572 /* XXX We are currently very restrictive here, so this code doesn't
15573 * consider the possibility that, say, /[alpha.]]/ was intended to
15574 * be a posix class. */
15575 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15578 /* Here we have something like 'foo:]'. There was no initial colon,
15579 * and we back up over 'foo. XXX Unlike the going forward case, we
15580 * don't handle typos of non-word chars in the middle */
15581 has_opening_colon = FALSE;
15584 while (p > RExC_start && isWORDCHAR(*p)) {
15589 /* Here, we have positioned ourselves to where we think the first
15590 * character in the potential class is */
15593 /* Now the interior really starts. There are certain key characters that
15594 * can end the interior, or these could just be typos. To catch both
15595 * cases, we may have to do two passes. In the first pass, we keep on
15596 * going unless we come to a sequence that matches
15597 * qr/ [[:punct:]] [[:blank:]]* \] /xa
15598 * This means it takes a sequence to end the pass, so two typos in a row if
15599 * that wasn't what was intended. If the class is perfectly formed, just
15600 * this one pass is needed. We also stop if there are too many characters
15601 * being accumulated, but this number is deliberately set higher than any
15602 * real class. It is set high enough so that someone who thinks that
15603 * 'alphanumeric' is a correct name would get warned that it wasn't.
15604 * While doing the pass, we keep track of where the key characters were in
15605 * it. If we don't find an end to the class, and one of the key characters
15606 * was found, we redo the pass, but stop when we get to that character.
15607 * Thus the key character was considered a typo in the first pass, but a
15608 * terminator in the second. If two key characters are found, we stop at
15609 * the second one in the first pass. Again this can miss two typos, but
15610 * catches a single one
15612 * In the first pass, 'possible_end' starts as NULL, and then gets set to
15613 * point to the first key character. For the second pass, it starts as -1.
15619 bool has_blank = FALSE;
15620 bool has_upper = FALSE;
15621 bool has_terminating_colon = FALSE;
15622 bool has_terminating_bracket = FALSE;
15623 bool has_semi_colon = FALSE;
15624 unsigned int name_len = 0;
15625 int punct_count = 0;
15629 /* Squeeze out blanks when looking up the class name below */
15630 if (isBLANK(*p) ) {
15632 found_problem = TRUE;
15637 /* The name will end with a punctuation */
15639 const char * peek = p + 1;
15641 /* Treat any non-']' punctuation followed by a ']' (possibly
15642 * with intervening blanks) as trying to terminate the class.
15643 * ']]' is very likely to mean a class was intended (but
15644 * missing the colon), but the warning message that gets
15645 * generated shows the error position better if we exit the
15646 * loop at the bottom (eventually), so skip it here. */
15648 if (peek < e && isBLANK(*peek)) {
15650 found_problem = TRUE;
15653 } while (peek < e && isBLANK(*peek));
15656 if (peek < e && *peek == ']') {
15657 has_terminating_bracket = TRUE;
15659 has_terminating_colon = TRUE;
15661 else if (*p == ';') {
15662 has_semi_colon = TRUE;
15663 has_terminating_colon = TRUE;
15666 found_problem = TRUE;
15673 /* Here we have punctuation we thought didn't end the class.
15674 * Keep track of the position of the key characters that are
15675 * more likely to have been class-enders */
15676 if (*p == ']' || *p == '[' || *p == ':' || *p == ';') {
15678 /* Allow just one such possible class-ender not actually
15679 * ending the class. */
15680 if (possible_end) {
15686 /* If we have too many punctuation characters, no use in
15688 if (++punct_count > max_distance) {
15692 /* Treat the punctuation as a typo. */
15693 input_text[name_len++] = *p;
15696 else if (isUPPER(*p)) { /* Use lowercase for lookup */
15697 input_text[name_len++] = toLOWER(*p);
15699 found_problem = TRUE;
15701 } else if (! UTF || UTF8_IS_INVARIANT(*p)) {
15702 input_text[name_len++] = *p;
15706 input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL);
15710 /* The declaration of 'input_text' is how long we allow a potential
15711 * class name to be, before saying they didn't mean a class name at
15713 if (name_len >= C_ARRAY_LENGTH(input_text)) {
15718 /* We get to here when the possible class name hasn't been properly
15719 * terminated before:
15720 * 1) we ran off the end of the pattern; or
15721 * 2) found two characters, each of which might have been intended to
15722 * be the name's terminator
15723 * 3) found so many punctuation characters in the purported name,
15724 * that the edit distance to a valid one is exceeded
15725 * 4) we decided it was more characters than anyone could have
15726 * intended to be one. */
15728 found_problem = TRUE;
15730 /* In the final two cases, we know that looking up what we've
15731 * accumulated won't lead to a match, even a fuzzy one. */
15732 if ( name_len >= C_ARRAY_LENGTH(input_text)
15733 || punct_count > max_distance)
15735 /* If there was an intermediate key character that could have been
15736 * an intended end, redo the parse, but stop there */
15737 if (possible_end && possible_end != (char *) -1) {
15738 possible_end = (char *) -1; /* Special signal value to say
15739 we've done a first pass */
15744 /* Otherwise, it can't have meant to have been a class */
15745 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15748 /* If we ran off the end, and the final character was a punctuation
15749 * one, back up one, to look at that final one just below. Later, we
15750 * will restore the parse pointer if appropriate */
15751 if (name_len && p == e && isPUNCT(*(p-1))) {
15756 if (p < e && isPUNCT(*p)) {
15758 has_terminating_bracket = TRUE;
15760 /* If this is a 2nd ']', and the first one is just below this
15761 * one, consider that to be the real terminator. This gives a
15762 * uniform and better positioning for the warning message */
15764 && possible_end != (char *) -1
15765 && *possible_end == ']'
15766 && name_len && input_text[name_len - 1] == ']')
15771 /* And this is actually equivalent to having done the 2nd
15772 * pass now, so set it to not try again */
15773 possible_end = (char *) -1;
15778 has_terminating_colon = TRUE;
15780 else if (*p == ';') {
15781 has_semi_colon = TRUE;
15782 has_terminating_colon = TRUE;
15790 /* Here, we have a class name to look up. We can short circuit the
15791 * stuff below for short names that can't possibly be meant to be a
15792 * class name. (We can do this on the first pass, as any second pass
15793 * will yield an even shorter name) */
15794 if (name_len < 3) {
15795 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15798 /* Find which class it is. Initially switch on the length of the name.
15800 switch (name_len) {
15802 if (memEQs(name_start, 4, "word")) {
15803 /* this is not POSIX, this is the Perl \w */
15804 class_number = ANYOF_WORDCHAR;
15808 /* Names all of length 5: alnum alpha ascii blank cntrl digit
15809 * graph lower print punct space upper
15810 * Offset 4 gives the best switch position. */
15811 switch (name_start[4]) {
15813 if (memBEGINs(name_start, 5, "alph")) /* alpha */
15814 class_number = ANYOF_ALPHA;
15817 if (memBEGINs(name_start, 5, "spac")) /* space */
15818 class_number = ANYOF_SPACE;
15821 if (memBEGINs(name_start, 5, "grap")) /* graph */
15822 class_number = ANYOF_GRAPH;
15825 if (memBEGINs(name_start, 5, "asci")) /* ascii */
15826 class_number = ANYOF_ASCII;
15829 if (memBEGINs(name_start, 5, "blan")) /* blank */
15830 class_number = ANYOF_BLANK;
15833 if (memBEGINs(name_start, 5, "cntr")) /* cntrl */
15834 class_number = ANYOF_CNTRL;
15837 if (memBEGINs(name_start, 5, "alnu")) /* alnum */
15838 class_number = ANYOF_ALPHANUMERIC;
15841 if (memBEGINs(name_start, 5, "lowe")) /* lower */
15842 class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER;
15843 else if (memBEGINs(name_start, 5, "uppe")) /* upper */
15844 class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER;
15847 if (memBEGINs(name_start, 5, "digi")) /* digit */
15848 class_number = ANYOF_DIGIT;
15849 else if (memBEGINs(name_start, 5, "prin")) /* print */
15850 class_number = ANYOF_PRINT;
15851 else if (memBEGINs(name_start, 5, "punc")) /* punct */
15852 class_number = ANYOF_PUNCT;
15857 if (memEQs(name_start, 6, "xdigit"))
15858 class_number = ANYOF_XDIGIT;
15862 /* If the name exactly matches a posix class name the class number will
15863 * here be set to it, and the input almost certainly was meant to be a
15864 * posix class, so we can skip further checking. If instead the syntax
15865 * is exactly correct, but the name isn't one of the legal ones, we
15866 * will return that as an error below. But if neither of these apply,
15867 * it could be that no posix class was intended at all, or that one
15868 * was, but there was a typo. We tease these apart by doing fuzzy
15869 * matching on the name */
15870 if (class_number == OOB_NAMEDCLASS && found_problem) {
15871 const UV posix_names[][6] = {
15872 { 'a', 'l', 'n', 'u', 'm' },
15873 { 'a', 'l', 'p', 'h', 'a' },
15874 { 'a', 's', 'c', 'i', 'i' },
15875 { 'b', 'l', 'a', 'n', 'k' },
15876 { 'c', 'n', 't', 'r', 'l' },
15877 { 'd', 'i', 'g', 'i', 't' },
15878 { 'g', 'r', 'a', 'p', 'h' },
15879 { 'l', 'o', 'w', 'e', 'r' },
15880 { 'p', 'r', 'i', 'n', 't' },
15881 { 'p', 'u', 'n', 'c', 't' },
15882 { 's', 'p', 'a', 'c', 'e' },
15883 { 'u', 'p', 'p', 'e', 'r' },
15884 { 'w', 'o', 'r', 'd' },
15885 { 'x', 'd', 'i', 'g', 'i', 't' }
15887 /* The names of the above all have added NULs to make them the same
15888 * size, so we need to also have the real lengths */
15889 const UV posix_name_lengths[] = {
15890 sizeof("alnum") - 1,
15891 sizeof("alpha") - 1,
15892 sizeof("ascii") - 1,
15893 sizeof("blank") - 1,
15894 sizeof("cntrl") - 1,
15895 sizeof("digit") - 1,
15896 sizeof("graph") - 1,
15897 sizeof("lower") - 1,
15898 sizeof("print") - 1,
15899 sizeof("punct") - 1,
15900 sizeof("space") - 1,
15901 sizeof("upper") - 1,
15902 sizeof("word") - 1,
15903 sizeof("xdigit")- 1
15906 int temp_max = max_distance; /* Use a temporary, so if we
15907 reparse, we haven't changed the
15910 /* Use a smaller max edit distance if we are missing one of the
15912 if ( has_opening_bracket + has_opening_colon < 2
15913 || has_terminating_bracket + has_terminating_colon < 2)
15918 /* See if the input name is close to a legal one */
15919 for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) {
15921 /* Short circuit call if the lengths are too far apart to be
15923 if (abs( (int) (name_len - posix_name_lengths[i]))
15929 if (edit_distance(input_text,
15932 posix_name_lengths[i],
15936 { /* If it is close, it probably was intended to be a class */
15937 goto probably_meant_to_be;
15941 /* Here the input name is not close enough to a valid class name
15942 * for us to consider it to be intended to be a posix class. If
15943 * we haven't already done so, and the parse found a character that
15944 * could have been terminators for the name, but which we absorbed
15945 * as typos during the first pass, repeat the parse, signalling it
15946 * to stop at that character */
15947 if (possible_end && possible_end != (char *) -1) {
15948 possible_end = (char *) -1;
15953 /* Here neither pass found a close-enough class name */
15954 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15957 probably_meant_to_be:
15959 /* Here we think that a posix specification was intended. Update any
15961 if (updated_parse_ptr) {
15962 *updated_parse_ptr = (char *) p;
15965 /* If a posix class name was intended but incorrectly specified, we
15966 * output or return the warnings */
15967 if (found_problem) {
15969 /* We set flags for these issues in the parse loop above instead of
15970 * adding them to the list of warnings, because we can parse it
15971 * twice, and we only want one warning instance */
15973 ADD_POSIX_WARNING(p, "the name must be all lowercase letters");
15976 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15978 if (has_semi_colon) {
15979 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15981 else if (! has_terminating_colon) {
15982 ADD_POSIX_WARNING(p, "there is no terminating ':'");
15984 if (! has_terminating_bracket) {
15985 ADD_POSIX_WARNING(p, "there is no terminating ']'");
15988 if ( posix_warnings
15990 && av_top_index(RExC_warn_text) > -1)
15992 *posix_warnings = RExC_warn_text;
15995 else if (class_number != OOB_NAMEDCLASS) {
15996 /* If it is a known class, return the class. The class number
15997 * #defines are structured so each complement is +1 to the normal
15999 CLEAR_POSIX_WARNINGS_AND_RETURN(class_number + complement);
16001 else if (! check_only) {
16003 /* Here, it is an unrecognized class. This is an error (unless the
16004 * call is to check only, which we've already handled above) */
16005 const char * const complement_string = (complement)
16008 RExC_parse = (char *) p;
16009 vFAIL3utf8f("POSIX class [:%s%" UTF8f ":] unknown",
16011 UTF8fARG(UTF, RExC_parse - name_start - 2, name_start));
16015 return OOB_NAMEDCLASS;
16017 #undef ADD_POSIX_WARNING
16019 STATIC unsigned int
16020 S_regex_set_precedence(const U8 my_operator) {
16022 /* Returns the precedence in the (?[...]) construct of the input operator,
16023 * specified by its character representation. The precedence follows
16024 * general Perl rules, but it extends this so that ')' and ']' have (low)
16025 * precedence even though they aren't really operators */
16027 switch (my_operator) {
16043 NOT_REACHED; /* NOTREACHED */
16044 return 0; /* Silence compiler warning */
16047 STATIC regnode_offset
16048 S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist,
16049 I32 *flagp, U32 depth,
16050 char * const oregcomp_parse)
16052 /* Handle the (?[...]) construct to do set operations */
16054 U8 curchar; /* Current character being parsed */
16055 UV start, end; /* End points of code point ranges */
16056 SV* final = NULL; /* The end result inversion list */
16057 SV* result_string; /* 'final' stringified */
16058 AV* stack; /* stack of operators and operands not yet
16060 AV* fence_stack = NULL; /* A stack containing the positions in
16061 'stack' of where the undealt-with left
16062 parens would be if they were actually
16064 /* The 'volatile' is a workaround for an optimiser bug
16065 * in Solaris Studio 12.3. See RT #127455 */
16066 volatile IV fence = 0; /* Position of where most recent undealt-
16067 with left paren in stack is; -1 if none.
16069 STRLEN len; /* Temporary */
16070 regnode_offset node; /* Temporary, and final regnode returned by
16072 const bool save_fold = FOLD; /* Temporary */
16073 char *save_end, *save_parse; /* Temporaries */
16074 const bool in_locale = LOC; /* we turn off /l during processing */
16076 GET_RE_DEBUG_FLAGS_DECL;
16078 PERL_ARGS_ASSERT_HANDLE_REGEX_SETS;
16080 DEBUG_PARSE("xcls");
16083 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
16086 /* The use of this operator implies /u. This is required so that the
16087 * compile time values are valid in all runtime cases */
16088 REQUIRE_UNI_RULES(flagp, 0);
16090 ckWARNexperimental(RExC_parse,
16091 WARN_EXPERIMENTAL__REGEX_SETS,
16092 "The regex_sets feature is experimental");
16094 /* Everything in this construct is a metacharacter. Operands begin with
16095 * either a '\' (for an escape sequence), or a '[' for a bracketed
16096 * character class. Any other character should be an operator, or
16097 * parenthesis for grouping. Both types of operands are handled by calling
16098 * regclass() to parse them. It is called with a parameter to indicate to
16099 * return the computed inversion list. The parsing here is implemented via
16100 * a stack. Each entry on the stack is a single character representing one
16101 * of the operators; or else a pointer to an operand inversion list. */
16103 #define IS_OPERATOR(a) SvIOK(a)
16104 #define IS_OPERAND(a) (! IS_OPERATOR(a))
16106 /* The stack is kept in Łukasiewicz order. (That's pronounced similar
16107 * to luke-a-shave-itch (or -itz), but people who didn't want to bother
16108 * with pronouncing it called it Reverse Polish instead, but now that YOU
16109 * know how to pronounce it you can use the correct term, thus giving due
16110 * credit to the person who invented it, and impressing your geek friends.
16111 * Wikipedia says that the pronounciation of "Ł" has been changing so that
16112 * it is now more like an English initial W (as in wonk) than an L.)
16114 * This means that, for example, 'a | b & c' is stored on the stack as
16122 * where the numbers in brackets give the stack [array] element number.
16123 * In this implementation, parentheses are not stored on the stack.
16124 * Instead a '(' creates a "fence" so that the part of the stack below the
16125 * fence is invisible except to the corresponding ')' (this allows us to
16126 * replace testing for parens, by using instead subtraction of the fence
16127 * position). As new operands are processed they are pushed onto the stack
16128 * (except as noted in the next paragraph). New operators of higher
16129 * precedence than the current final one are inserted on the stack before
16130 * the lhs operand (so that when the rhs is pushed next, everything will be
16131 * in the correct positions shown above. When an operator of equal or
16132 * lower precedence is encountered in parsing, all the stacked operations
16133 * of equal or higher precedence are evaluated, leaving the result as the
16134 * top entry on the stack. This makes higher precedence operations
16135 * evaluate before lower precedence ones, and causes operations of equal
16136 * precedence to left associate.
16138 * The only unary operator '!' is immediately pushed onto the stack when
16139 * encountered. When an operand is encountered, if the top of the stack is
16140 * a '!", the complement is immediately performed, and the '!' popped. The
16141 * resulting value is treated as a new operand, and the logic in the
16142 * previous paragraph is executed. Thus in the expression
16144 * the stack looks like
16150 * as 'b' gets parsed, the latter gets evaluated to '!b', and the stack
16157 * A ')' is treated as an operator with lower precedence than all the
16158 * aforementioned ones, which causes all operations on the stack above the
16159 * corresponding '(' to be evaluated down to a single resultant operand.
16160 * Then the fence for the '(' is removed, and the operand goes through the
16161 * algorithm above, without the fence.
16163 * A separate stack is kept of the fence positions, so that the position of
16164 * the latest so-far unbalanced '(' is at the top of it.
16166 * The ']' ending the construct is treated as the lowest operator of all,
16167 * so that everything gets evaluated down to a single operand, which is the
16170 sv_2mortal((SV *)(stack = newAV()));
16171 sv_2mortal((SV *)(fence_stack = newAV()));
16173 while (RExC_parse < RExC_end) {
16174 I32 top_index; /* Index of top-most element in 'stack' */
16175 SV** top_ptr; /* Pointer to top 'stack' element */
16176 SV* current = NULL; /* To contain the current inversion list
16178 SV* only_to_avoid_leaks;
16180 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
16181 TRUE /* Force /x */ );
16182 if (RExC_parse >= RExC_end) { /* Fail */
16186 curchar = UCHARAT(RExC_parse);
16190 #ifdef ENABLE_REGEX_SETS_DEBUGGING
16191 /* Enable with -Accflags=-DENABLE_REGEX_SETS_DEBUGGING */
16192 DEBUG_U(dump_regex_sets_structures(pRExC_state,
16193 stack, fence, fence_stack));
16196 top_index = av_tindex_skip_len_mg(stack);
16199 SV** stacked_ptr; /* Ptr to something already on 'stack' */
16200 char stacked_operator; /* The topmost operator on the 'stack'. */
16201 SV* lhs; /* Operand to the left of the operator */
16202 SV* rhs; /* Operand to the right of the operator */
16203 SV* fence_ptr; /* Pointer to top element of the fence
16208 if ( RExC_parse < RExC_end - 2
16209 && UCHARAT(RExC_parse + 1) == '?'
16210 && UCHARAT(RExC_parse + 2) == '^')
16212 /* If is a '(?', could be an embedded '(?^flags:(?[...])'.
16213 * This happens when we have some thing like
16215 * my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
16217 * qr/(?[ \p{Digit} & $thai_or_lao ])/;
16219 * Here we would be handling the interpolated
16220 * '$thai_or_lao'. We handle this by a recursive call to
16221 * ourselves which returns the inversion list the
16222 * interpolated expression evaluates to. We use the flags
16223 * from the interpolated pattern. */
16224 U32 save_flags = RExC_flags;
16225 const char * save_parse;
16227 RExC_parse += 2; /* Skip past the '(?' */
16228 save_parse = RExC_parse;
16230 /* Parse the flags for the '(?'. We already know the first
16231 * flag to parse is a '^' */
16232 parse_lparen_question_flags(pRExC_state);
16234 if ( RExC_parse >= RExC_end - 4
16235 || UCHARAT(RExC_parse) != ':'
16236 || UCHARAT(++RExC_parse) != '('
16237 || UCHARAT(++RExC_parse) != '?'
16238 || UCHARAT(++RExC_parse) != '[')
16241 /* In combination with the above, this moves the
16242 * pointer to the point just after the first erroneous
16244 if (RExC_parse >= RExC_end - 4) {
16245 RExC_parse = RExC_end;
16247 else if (RExC_parse != save_parse) {
16248 RExC_parse += (UTF)
16249 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
16252 vFAIL("Expecting '(?flags:(?[...'");
16255 /* Recurse, with the meat of the embedded expression */
16257 if (! handle_regex_sets(pRExC_state, ¤t, flagp,
16258 depth+1, oregcomp_parse))
16260 RETURN_FAIL_ON_RESTART(*flagp, flagp);
16263 /* Here, 'current' contains the embedded expression's
16264 * inversion list, and RExC_parse points to the trailing
16265 * ']'; the next character should be the ')' */
16267 if (UCHARAT(RExC_parse) != ')')
16268 vFAIL("Expecting close paren for nested extended charclass");
16270 /* Then the ')' matching the original '(' handled by this
16271 * case: statement */
16273 if (UCHARAT(RExC_parse) != ')')
16274 vFAIL("Expecting close paren for wrapper for nested extended charclass");
16276 RExC_flags = save_flags;
16277 goto handle_operand;
16280 /* A regular '('. Look behind for illegal syntax */
16281 if (top_index - fence >= 0) {
16282 /* If the top entry on the stack is an operator, it had
16283 * better be a '!', otherwise the entry below the top
16284 * operand should be an operator */
16285 if ( ! (top_ptr = av_fetch(stack, top_index, FALSE))
16286 || (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!')
16287 || ( IS_OPERAND(*top_ptr)
16288 && ( top_index - fence < 1
16289 || ! (stacked_ptr = av_fetch(stack,
16292 || ! IS_OPERATOR(*stacked_ptr))))
16295 vFAIL("Unexpected '(' with no preceding operator");
16299 /* Stack the position of this undealt-with left paren */
16300 av_push(fence_stack, newSViv(fence));
16301 fence = top_index + 1;
16305 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
16306 * multi-char folds are allowed. */
16307 if (!regclass(pRExC_state, flagp, depth+1,
16308 TRUE, /* means parse just the next thing */
16309 FALSE, /* don't allow multi-char folds */
16310 FALSE, /* don't silence non-portable warnings. */
16312 FALSE, /* Require return to be an ANYOF */
16315 RETURN_FAIL_ON_RESTART(*flagp, flagp);
16316 goto regclass_failed;
16319 /* regclass() will return with parsing just the \ sequence,
16320 * leaving the parse pointer at the next thing to parse */
16322 goto handle_operand;
16324 case '[': /* Is a bracketed character class */
16326 /* See if this is a [:posix:] class. */
16327 bool is_posix_class = (OOB_NAMEDCLASS
16328 < handle_possible_posix(pRExC_state,
16332 TRUE /* checking only */));
16333 /* If it is a posix class, leave the parse pointer at the '['
16334 * to fool regclass() into thinking it is part of a
16335 * '[[:posix:]]'. */
16336 if (! is_posix_class) {
16340 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
16341 * multi-char folds are allowed. */
16342 if (!regclass(pRExC_state, flagp, depth+1,
16343 is_posix_class, /* parse the whole char
16344 class only if not a
16346 FALSE, /* don't allow multi-char folds */
16347 TRUE, /* silence non-portable warnings. */
16349 FALSE, /* Require return to be an ANYOF */
16352 RETURN_FAIL_ON_RESTART(*flagp, flagp);
16353 goto regclass_failed;
16360 /* function call leaves parse pointing to the ']', except if we
16362 if (is_posix_class) {
16366 goto handle_operand;
16370 if (top_index >= 1) {
16371 goto join_operators;
16374 /* Only a single operand on the stack: are done */
16378 if (av_tindex_skip_len_mg(fence_stack) < 0) {
16379 if (UCHARAT(RExC_parse - 1) == ']') {
16383 vFAIL("Unexpected ')'");
16386 /* If nothing after the fence, is missing an operand */
16387 if (top_index - fence < 0) {
16391 /* If at least two things on the stack, treat this as an
16393 if (top_index - fence >= 1) {
16394 goto join_operators;
16397 /* Here only a single thing on the fenced stack, and there is a
16398 * fence. Get rid of it */
16399 fence_ptr = av_pop(fence_stack);
16401 fence = SvIV(fence_ptr);
16402 SvREFCNT_dec_NN(fence_ptr);
16409 /* Having gotten rid of the fence, we pop the operand at the
16410 * stack top and process it as a newly encountered operand */
16411 current = av_pop(stack);
16412 if (IS_OPERAND(current)) {
16413 goto handle_operand;
16425 /* These binary operators should have a left operand already
16427 if ( top_index - fence < 0
16428 || top_index - fence == 1
16429 || ( ! (top_ptr = av_fetch(stack, top_index, FALSE)))
16430 || ! IS_OPERAND(*top_ptr))
16432 goto unexpected_binary;
16435 /* If only the one operand is on the part of the stack visible
16436 * to us, we just place this operator in the proper position */
16437 if (top_index - fence < 2) {
16439 /* Place the operator before the operand */
16441 SV* lhs = av_pop(stack);
16442 av_push(stack, newSVuv(curchar));
16443 av_push(stack, lhs);
16447 /* But if there is something else on the stack, we need to
16448 * process it before this new operator if and only if the
16449 * stacked operation has equal or higher precedence than the
16454 /* The operator on the stack is supposed to be below both its
16456 if ( ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE))
16457 || IS_OPERAND(*stacked_ptr))
16459 /* But if not, it's legal and indicates we are completely
16460 * done if and only if we're currently processing a ']',
16461 * which should be the final thing in the expression */
16462 if (curchar == ']') {
16468 vFAIL2("Unexpected binary operator '%c' with no "
16469 "preceding operand", curchar);
16471 stacked_operator = (char) SvUV(*stacked_ptr);
16473 if (regex_set_precedence(curchar)
16474 > regex_set_precedence(stacked_operator))
16476 /* Here, the new operator has higher precedence than the
16477 * stacked one. This means we need to add the new one to
16478 * the stack to await its rhs operand (and maybe more
16479 * stuff). We put it before the lhs operand, leaving
16480 * untouched the stacked operator and everything below it
16482 lhs = av_pop(stack);
16483 assert(IS_OPERAND(lhs));
16485 av_push(stack, newSVuv(curchar));
16486 av_push(stack, lhs);
16490 /* Here, the new operator has equal or lower precedence than
16491 * what's already there. This means the operation already
16492 * there should be performed now, before the new one. */
16494 rhs = av_pop(stack);
16495 if (! IS_OPERAND(rhs)) {
16497 /* This can happen when a ! is not followed by an operand,
16498 * like in /(?[\t &!])/ */
16502 lhs = av_pop(stack);
16504 if (! IS_OPERAND(lhs)) {
16506 /* This can happen when there is an empty (), like in
16507 * /(?[[0]+()+])/ */
16511 switch (stacked_operator) {
16513 _invlist_intersection(lhs, rhs, &rhs);
16518 _invlist_union(lhs, rhs, &rhs);
16522 _invlist_subtract(lhs, rhs, &rhs);
16525 case '^': /* The union minus the intersection */
16530 _invlist_union(lhs, rhs, &u);
16531 _invlist_intersection(lhs, rhs, &i);
16532 _invlist_subtract(u, i, &rhs);
16533 SvREFCNT_dec_NN(i);
16534 SvREFCNT_dec_NN(u);
16540 /* Here, the higher precedence operation has been done, and the
16541 * result is in 'rhs'. We overwrite the stacked operator with
16542 * the result. Then we redo this code to either push the new
16543 * operator onto the stack or perform any higher precedence
16544 * stacked operation */
16545 only_to_avoid_leaks = av_pop(stack);
16546 SvREFCNT_dec(only_to_avoid_leaks);
16547 av_push(stack, rhs);
16550 case '!': /* Highest priority, right associative */
16552 /* If what's already at the top of the stack is another '!",
16553 * they just cancel each other out */
16554 if ( (top_ptr = av_fetch(stack, top_index, FALSE))
16555 && (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!'))
16557 only_to_avoid_leaks = av_pop(stack);
16558 SvREFCNT_dec(only_to_avoid_leaks);
16560 else { /* Otherwise, since it's right associative, just push
16562 av_push(stack, newSVuv(curchar));
16567 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16568 if (RExC_parse >= RExC_end) {
16571 vFAIL("Unexpected character");
16575 /* Here 'current' is the operand. If something is already on the
16576 * stack, we have to check if it is a !. But first, the code above
16577 * may have altered the stack in the time since we earlier set
16580 top_index = av_tindex_skip_len_mg(stack);
16581 if (top_index - fence >= 0) {
16582 /* If the top entry on the stack is an operator, it had better
16583 * be a '!', otherwise the entry below the top operand should
16584 * be an operator */
16585 top_ptr = av_fetch(stack, top_index, FALSE);
16587 if (IS_OPERATOR(*top_ptr)) {
16589 /* The only permissible operator at the top of the stack is
16590 * '!', which is applied immediately to this operand. */
16591 curchar = (char) SvUV(*top_ptr);
16592 if (curchar != '!') {
16593 SvREFCNT_dec(current);
16594 vFAIL2("Unexpected binary operator '%c' with no "
16595 "preceding operand", curchar);
16598 _invlist_invert(current);
16600 only_to_avoid_leaks = av_pop(stack);
16601 SvREFCNT_dec(only_to_avoid_leaks);
16603 /* And we redo with the inverted operand. This allows
16604 * handling multiple ! in a row */
16605 goto handle_operand;
16607 /* Single operand is ok only for the non-binary ')'
16609 else if ((top_index - fence == 0 && curchar != ')')
16610 || (top_index - fence > 0
16611 && (! (stacked_ptr = av_fetch(stack,
16614 || IS_OPERAND(*stacked_ptr))))
16616 SvREFCNT_dec(current);
16617 vFAIL("Operand with no preceding operator");
16621 /* Here there was nothing on the stack or the top element was
16622 * another operand. Just add this new one */
16623 av_push(stack, current);
16625 } /* End of switch on next parse token */
16627 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16628 } /* End of loop parsing through the construct */
16630 vFAIL("Syntax error in (?[...])");
16634 if (RExC_parse >= RExC_end || RExC_parse[1] != ')') {
16635 if (RExC_parse < RExC_end) {
16639 vFAIL("Unexpected ']' with no following ')' in (?[...");
16642 if (av_tindex_skip_len_mg(fence_stack) >= 0) {
16643 vFAIL("Unmatched (");
16646 if (av_tindex_skip_len_mg(stack) < 0 /* Was empty */
16647 || ((final = av_pop(stack)) == NULL)
16648 || ! IS_OPERAND(final)
16649 || ! is_invlist(final)
16650 || av_tindex_skip_len_mg(stack) >= 0) /* More left on stack */
16653 SvREFCNT_dec(final);
16654 vFAIL("Incomplete expression within '(?[ ])'");
16657 /* Here, 'final' is the resultant inversion list from evaluating the
16658 * expression. Return it if so requested */
16659 if (return_invlist) {
16660 *return_invlist = final;
16664 /* Otherwise generate a resultant node, based on 'final'. regclass() is
16665 * expecting a string of ranges and individual code points */
16666 invlist_iterinit(final);
16667 result_string = newSVpvs("");
16668 while (invlist_iternext(final, &start, &end)) {
16669 if (start == end) {
16670 Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}", start);
16673 Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}-\\x{%" UVXf "}",
16678 /* About to generate an ANYOF (or similar) node from the inversion list we
16679 * have calculated */
16680 save_parse = RExC_parse;
16681 RExC_parse = SvPV(result_string, len);
16682 save_end = RExC_end;
16683 RExC_end = RExC_parse + len;
16684 TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
16686 /* We turn off folding around the call, as the class we have constructed
16687 * already has all folding taken into consideration, and we don't want
16688 * regclass() to add to that */
16689 RExC_flags &= ~RXf_PMf_FOLD;
16690 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if multi-char
16691 * folds are allowed. */
16692 node = regclass(pRExC_state, flagp, depth+1,
16693 FALSE, /* means parse the whole char class */
16694 FALSE, /* don't allow multi-char folds */
16695 TRUE, /* silence non-portable warnings. The above may very
16696 well have generated non-portable code points, but
16697 they're valid on this machine */
16698 FALSE, /* similarly, no need for strict */
16700 /* We can optimize into something besides an ANYOF, except
16701 * under /l, which needs to be ANYOF because of runtime
16702 * checks for locale sanity, etc */
16708 RExC_parse = save_parse + 1;
16709 RExC_end = save_end;
16710 SvREFCNT_dec_NN(final);
16711 SvREFCNT_dec_NN(result_string);
16714 RExC_flags |= RXf_PMf_FOLD;
16718 RETURN_FAIL_ON_RESTART(*flagp, flagp);
16719 goto regclass_failed;
16722 /* Fix up the node type if we are in locale. (We have pretended we are
16723 * under /u for the purposes of regclass(), as this construct will only
16724 * work under UTF-8 locales. But now we change the opcode to be ANYOFL (so
16725 * as to cause any warnings about bad locales to be output in regexec.c),
16726 * and add the flag that indicates to check if not in a UTF-8 locale. The
16727 * reason we above forbid optimization into something other than an ANYOF
16728 * node is simply to minimize the number of code changes in regexec.c.
16729 * Otherwise we would have to create new EXACTish node types and deal with
16730 * them. This decision could be revisited should this construct become
16733 * (One might think we could look at the resulting ANYOF node and suppress
16734 * the flag if everything is above 255, as those would be UTF-8 only,
16735 * but this isn't true, as the components that led to that result could
16736 * have been locale-affected, and just happen to cancel each other out
16737 * under UTF-8 locales.) */
16739 set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
16741 assert(OP(REGNODE_p(node)) == ANYOF);
16743 OP(REGNODE_p(node)) = ANYOFL;
16744 ANYOF_FLAGS(REGNODE_p(node))
16745 |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
16748 nextchar(pRExC_state);
16749 Set_Node_Length(REGNODE_p(node), RExC_parse - oregcomp_parse + 1); /* MJD */
16753 FAIL2("panic: regclass returned failure to handle_sets, " "flags=%#" UVxf,
16757 #ifdef ENABLE_REGEX_SETS_DEBUGGING
16760 S_dump_regex_sets_structures(pTHX_ RExC_state_t *pRExC_state,
16761 AV * stack, const IV fence, AV * fence_stack)
16762 { /* Dumps the stacks in handle_regex_sets() */
16764 const SSize_t stack_top = av_tindex_skip_len_mg(stack);
16765 const SSize_t fence_stack_top = av_tindex_skip_len_mg(fence_stack);
16768 PERL_ARGS_ASSERT_DUMP_REGEX_SETS_STRUCTURES;
16770 PerlIO_printf(Perl_debug_log, "\nParse position is:%s\n", RExC_parse);
16772 if (stack_top < 0) {
16773 PerlIO_printf(Perl_debug_log, "Nothing on stack\n");
16776 PerlIO_printf(Perl_debug_log, "Stack: (fence=%d)\n", (int) fence);
16777 for (i = stack_top; i >= 0; i--) {
16778 SV ** element_ptr = av_fetch(stack, i, FALSE);
16779 if (! element_ptr) {
16782 if (IS_OPERATOR(*element_ptr)) {
16783 PerlIO_printf(Perl_debug_log, "[%d]: %c\n",
16784 (int) i, (int) SvIV(*element_ptr));
16787 PerlIO_printf(Perl_debug_log, "[%d] ", (int) i);
16788 sv_dump(*element_ptr);
16793 if (fence_stack_top < 0) {
16794 PerlIO_printf(Perl_debug_log, "Nothing on fence_stack\n");
16797 PerlIO_printf(Perl_debug_log, "Fence_stack: \n");
16798 for (i = fence_stack_top; i >= 0; i--) {
16799 SV ** element_ptr = av_fetch(fence_stack, i, FALSE);
16800 if (! element_ptr) {
16803 PerlIO_printf(Perl_debug_log, "[%d]: %d\n",
16804 (int) i, (int) SvIV(*element_ptr));
16815 S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist)
16817 /* This adds the Latin1/above-Latin1 folding rules.
16819 * This should be called only for a Latin1-range code points, cp, which is
16820 * known to be involved in a simple fold with other code points above
16821 * Latin1. It would give false results if /aa has been specified.
16822 * Multi-char folds are outside the scope of this, and must be handled
16825 PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS;
16827 assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp));
16829 /* The rules that are valid for all Unicode versions are hard-coded in */
16834 add_cp_to_invlist(*invlist, KELVIN_SIGN);
16838 *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S);
16841 *invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU);
16842 *invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU);
16844 case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
16845 case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
16846 *invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN);
16848 case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
16849 *invlist = add_cp_to_invlist(*invlist,
16850 LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
16853 default: /* Other code points are checked against the data for the
16854 current Unicode version */
16856 Size_t folds_count;
16857 unsigned int first_fold;
16858 const unsigned int * remaining_folds;
16862 folded_cp = toFOLD(cp);
16865 U8 dummy_fold[UTF8_MAXBYTES_CASE+1];
16867 folded_cp = _to_fold_latin1(cp, dummy_fold, &dummy_len, 0);
16870 if (folded_cp > 255) {
16871 *invlist = add_cp_to_invlist(*invlist, folded_cp);
16874 folds_count = _inverse_folds(folded_cp, &first_fold,
16876 if (folds_count == 0) {
16878 /* Use deprecated warning to increase the chances of this being
16880 ckWARN2reg_d(RExC_parse,
16881 "Perl folding rules are not up-to-date for 0x%02X;"
16882 " please use the perlbug utility to report;", cp);
16887 if (first_fold > 255) {
16888 *invlist = add_cp_to_invlist(*invlist, first_fold);
16890 for (i = 0; i < folds_count - 1; i++) {
16891 if (remaining_folds[i] > 255) {
16892 *invlist = add_cp_to_invlist(*invlist,
16893 remaining_folds[i]);
16903 S_output_posix_warnings(pTHX_ RExC_state_t *pRExC_state, AV* posix_warnings)
16905 /* Output the elements of the array given by '*posix_warnings' as REGEXP
16909 const bool first_is_fatal = ckDEAD(packWARN(WARN_REGEXP));
16911 PERL_ARGS_ASSERT_OUTPUT_POSIX_WARNINGS;
16913 if (! TO_OUTPUT_WARNINGS(RExC_parse)) {
16917 while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) {
16918 if (first_is_fatal) { /* Avoid leaking this */
16919 av_undef(posix_warnings); /* This isn't necessary if the
16920 array is mortal, but is a
16922 (void) sv_2mortal(msg);
16925 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg));
16926 SvREFCNT_dec_NN(msg);
16929 UPDATE_WARNINGS_LOC(RExC_parse);
16932 PERL_STATIC_INLINE Size_t
16933 S_find_first_differing_byte_pos(const U8 * s1, const U8 * s2, const Size_t max)
16935 const U8 * const start = s1;
16936 const U8 * const send = start + max;
16938 PERL_ARGS_ASSERT_FIND_FIRST_DIFFERING_BYTE_POS;
16940 while (s1 < send && *s1 == *s2) {
16949 S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count)
16951 /* This adds the string scalar <multi_string> to the array
16952 * <multi_char_matches>. <multi_string> is known to have exactly
16953 * <cp_count> code points in it. This is used when constructing a
16954 * bracketed character class and we find something that needs to match more
16955 * than a single character.
16957 * <multi_char_matches> is actually an array of arrays. Each top-level
16958 * element is an array that contains all the strings known so far that are
16959 * the same length. And that length (in number of code points) is the same
16960 * as the index of the top-level array. Hence, the [2] element is an
16961 * array, each element thereof is a string containing TWO code points;
16962 * while element [3] is for strings of THREE characters, and so on. Since
16963 * this is for multi-char strings there can never be a [0] nor [1] element.
16965 * When we rewrite the character class below, we will do so such that the
16966 * longest strings are written first, so that it prefers the longest
16967 * matching strings first. This is done even if it turns out that any
16968 * quantifier is non-greedy, out of this programmer's (khw) laziness. Tom
16969 * Christiansen has agreed that this is ok. This makes the test for the
16970 * ligature 'ffi' come before the test for 'ff', for example */
16973 AV** this_array_ptr;
16975 PERL_ARGS_ASSERT_ADD_MULTI_MATCH;
16977 if (! multi_char_matches) {
16978 multi_char_matches = newAV();
16981 if (av_exists(multi_char_matches, cp_count)) {
16982 this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE);
16983 this_array = *this_array_ptr;
16986 this_array = newAV();
16987 av_store(multi_char_matches, cp_count,
16990 av_push(this_array, multi_string);
16992 return multi_char_matches;
16995 /* The names of properties whose definitions are not known at compile time are
16996 * stored in this SV, after a constant heading. So if the length has been
16997 * changed since initialization, then there is a run-time definition. */
16998 #define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION \
16999 (SvCUR(listsv) != initial_listsv_len)
17001 /* There is a restricted set of white space characters that are legal when
17002 * ignoring white space in a bracketed character class. This generates the
17003 * code to skip them.
17005 * There is a line below that uses the same white space criteria but is outside
17006 * this macro. Both here and there must use the same definition */
17007 #define SKIP_BRACKETED_WHITE_SPACE(do_skip, p) \
17010 while (isBLANK_A(UCHARAT(p))) \
17017 STATIC regnode_offset
17018 S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth,
17019 const bool stop_at_1, /* Just parse the next thing, don't
17020 look for a full character class */
17021 bool allow_mutiple_chars,
17022 const bool silence_non_portable, /* Don't output warnings
17026 bool optimizable, /* ? Allow a non-ANYOF return
17028 SV** ret_invlist /* Return an inversion list, not a node */
17031 /* parse a bracketed class specification. Most of these will produce an
17032 * ANYOF node; but something like [a] will produce an EXACT node; [aA], an
17033 * EXACTFish node; [[:ascii:]], a POSIXA node; etc. It is more complex
17034 * under /i with multi-character folds: it will be rewritten following the
17035 * paradigm of this example, where the <multi-fold>s are characters which
17036 * fold to multiple character sequences:
17037 * /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
17038 * gets effectively rewritten as:
17039 * /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
17040 * reg() gets called (recursively) on the rewritten version, and this
17041 * function will return what it constructs. (Actually the <multi-fold>s
17042 * aren't physically removed from the [abcdefghi], it's just that they are
17043 * ignored in the recursion by means of a flag:
17044 * <RExC_in_multi_char_class>.)
17046 * ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS
17047 * characters, with the corresponding bit set if that character is in the
17048 * list. For characters above this, an inversion list is used. There
17049 * are extra bits for \w, etc. in locale ANYOFs, as what these match is not
17050 * determinable at compile time
17052 * On success, returns the offset at which any next node should be placed
17053 * into the regex engine program being compiled.
17055 * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
17056 * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
17061 UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
17063 UV value = OOB_UNICODE, save_value = OOB_UNICODE;
17064 regnode_offset ret = -1; /* Initialized to an illegal value */
17066 int namedclass = OOB_NAMEDCLASS;
17067 char *rangebegin = NULL;
17068 SV *listsv = NULL; /* List of \p{user-defined} whose definitions
17069 aren't available at the time this was called */
17070 STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
17071 than just initialized. */
17072 SV* properties = NULL; /* Code points that match \p{} \P{} */
17073 SV* posixes = NULL; /* Code points that match classes like [:word:],
17074 extended beyond the Latin1 range. These have to
17075 be kept separate from other code points for much
17076 of this function because their handling is
17077 different under /i, and for most classes under
17079 SV* nposixes = NULL; /* Similarly for [:^word:]. These are kept
17080 separate for a while from the non-complemented
17081 versions because of complications with /d
17083 SV* simple_posixes = NULL; /* But under some conditions, the classes can be
17084 treated more simply than the general case,
17085 leading to less compilation and execution
17087 UV element_count = 0; /* Number of distinct elements in the class.
17088 Optimizations may be possible if this is tiny */
17089 AV * multi_char_matches = NULL; /* Code points that fold to more than one
17090 character; used under /i */
17092 char * stop_ptr = RExC_end; /* where to stop parsing */
17094 /* ignore unescaped whitespace? */
17095 const bool skip_white = cBOOL( ret_invlist
17096 || (RExC_flags & RXf_PMf_EXTENDED_MORE));
17098 /* inversion list of code points this node matches only when the target
17099 * string is in UTF-8. These are all non-ASCII, < 256. (Because is under
17101 SV* upper_latin1_only_utf8_matches = NULL;
17103 /* Inversion list of code points this node matches regardless of things
17104 * like locale, folding, utf8ness of the target string */
17105 SV* cp_list = NULL;
17107 /* Like cp_list, but code points on this list need to be checked for things
17108 * that fold to/from them under /i */
17109 SV* cp_foldable_list = NULL;
17111 /* Like cp_list, but code points on this list are valid only when the
17112 * runtime locale is UTF-8 */
17113 SV* only_utf8_locale_list = NULL;
17115 /* In a range, if one of the endpoints is non-character-set portable,
17116 * meaning that it hard-codes a code point that may mean a different
17117 * charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a
17118 * mnemonic '\t' which each mean the same character no matter which
17119 * character set the platform is on. */
17120 unsigned int non_portable_endpoint = 0;
17122 /* Is the range unicode? which means on a platform that isn't 1-1 native
17123 * to Unicode (i.e. non-ASCII), each code point in it should be considered
17124 * to be a Unicode value. */
17125 bool unicode_range = FALSE;
17126 bool invert = FALSE; /* Is this class to be complemented */
17128 bool warn_super = ALWAYS_WARN_SUPER;
17130 const char * orig_parse = RExC_parse;
17132 /* This variable is used to mark where the end in the input is of something
17133 * that looks like a POSIX construct but isn't. During the parse, when
17134 * something looks like it could be such a construct is encountered, it is
17135 * checked for being one, but not if we've already checked this area of the
17136 * input. Only after this position is reached do we check again */
17137 char *not_posix_region_end = RExC_parse - 1;
17139 AV* posix_warnings = NULL;
17140 const bool do_posix_warnings = ckWARN(WARN_REGEXP);
17141 U8 op = END; /* The returned node-type, initialized to an impossible
17143 U8 anyof_flags = 0; /* flag bits if the node is an ANYOF-type */
17144 U32 posixl = 0; /* bit field of posix classes matched under /l */
17147 /* Flags as to what things aren't knowable until runtime. (Note that these are
17148 * mutually exclusive.) */
17149 #define HAS_USER_DEFINED_PROPERTY 0x01 /* /u any user-defined properties that
17150 haven't been defined as of yet */
17151 #define HAS_D_RUNTIME_DEPENDENCY 0x02 /* /d if the target being matched is
17153 #define HAS_L_RUNTIME_DEPENDENCY 0x04 /* /l what the posix classes match and
17154 what gets folded */
17155 U32 has_runtime_dependency = 0; /* OR of the above flags */
17157 GET_RE_DEBUG_FLAGS_DECL;
17159 PERL_ARGS_ASSERT_REGCLASS;
17161 PERL_UNUSED_ARG(depth);
17165 /* If wants an inversion list returned, we can't optimize to something
17168 optimizable = FALSE;
17171 DEBUG_PARSE("clas");
17173 #if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */ \
17174 || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0 \
17175 && UNICODE_DOT_DOT_VERSION == 0)
17176 allow_mutiple_chars = FALSE;
17179 /* We include the /i status at the beginning of this so that we can
17180 * know it at runtime */
17181 listsv = sv_2mortal(Perl_newSVpvf(aTHX_ "#%d\n", cBOOL(FOLD)));
17182 initial_listsv_len = SvCUR(listsv);
17183 SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated. */
17185 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17187 assert(RExC_parse <= RExC_end);
17189 if (UCHARAT(RExC_parse) == '^') { /* Complement the class */
17192 allow_mutiple_chars = FALSE;
17194 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17197 /* Check that they didn't say [:posix:] instead of [[:posix:]] */
17198 if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) {
17199 int maybe_class = handle_possible_posix(pRExC_state,
17201 ¬_posix_region_end,
17203 TRUE /* checking only */);
17204 if (maybe_class >= OOB_NAMEDCLASS && do_posix_warnings) {
17205 ckWARN4reg(not_posix_region_end,
17206 "POSIX syntax [%c %c] belongs inside character classes%s",
17207 *RExC_parse, *RExC_parse,
17208 (maybe_class == OOB_NAMEDCLASS)
17209 ? ((POSIXCC_NOTYET(*RExC_parse))
17210 ? " (but this one isn't implemented)"
17211 : " (but this one isn't fully valid)")
17217 /* If the caller wants us to just parse a single element, accomplish this
17218 * by faking the loop ending condition */
17219 if (stop_at_1 && RExC_end > RExC_parse) {
17220 stop_ptr = RExC_parse + 1;
17223 /* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */
17224 if (UCHARAT(RExC_parse) == ']')
17225 goto charclassloop;
17229 if ( posix_warnings
17230 && av_tindex_skip_len_mg(posix_warnings) >= 0
17231 && RExC_parse > not_posix_region_end)
17233 /* Warnings about posix class issues are considered tentative until
17234 * we are far enough along in the parse that we can no longer
17235 * change our mind, at which point we output them. This is done
17236 * each time through the loop so that a later class won't zap them
17237 * before they have been dealt with. */
17238 output_posix_warnings(pRExC_state, posix_warnings);
17241 if (RExC_parse >= stop_ptr) {
17245 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17247 if (UCHARAT(RExC_parse) == ']') {
17253 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
17254 save_value = value;
17255 save_prevvalue = prevvalue;
17258 rangebegin = RExC_parse;
17260 non_portable_endpoint = 0;
17262 if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) {
17263 value = utf8n_to_uvchr((U8*)RExC_parse,
17264 RExC_end - RExC_parse,
17265 &numlen, UTF8_ALLOW_DEFAULT);
17266 RExC_parse += numlen;
17269 value = UCHARAT(RExC_parse++);
17271 if (value == '[') {
17272 char * posix_class_end;
17273 namedclass = handle_possible_posix(pRExC_state,
17276 do_posix_warnings ? &posix_warnings : NULL,
17277 FALSE /* die if error */);
17278 if (namedclass > OOB_NAMEDCLASS) {
17280 /* If there was an earlier attempt to parse this particular
17281 * posix class, and it failed, it was a false alarm, as this
17282 * successful one proves */
17283 if ( posix_warnings
17284 && av_tindex_skip_len_mg(posix_warnings) >= 0
17285 && not_posix_region_end >= RExC_parse
17286 && not_posix_region_end <= posix_class_end)
17288 av_undef(posix_warnings);
17291 RExC_parse = posix_class_end;
17293 else if (namedclass == OOB_NAMEDCLASS) {
17294 not_posix_region_end = posix_class_end;
17297 namedclass = OOB_NAMEDCLASS;
17300 else if ( RExC_parse - 1 > not_posix_region_end
17301 && MAYBE_POSIXCC(value))
17303 (void) handle_possible_posix(
17305 RExC_parse - 1, /* -1 because parse has already been
17307 ¬_posix_region_end,
17308 do_posix_warnings ? &posix_warnings : NULL,
17309 TRUE /* checking only */);
17311 else if ( strict && ! skip_white
17312 && ( _generic_isCC(value, _CC_VERTSPACE)
17313 || is_VERTWS_cp_high(value)))
17315 vFAIL("Literal vertical space in [] is illegal except under /x");
17317 else if (value == '\\') {
17318 /* Is a backslash; get the code point of the char after it */
17320 if (RExC_parse >= RExC_end) {
17321 vFAIL("Unmatched [");
17324 if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) {
17325 value = utf8n_to_uvchr((U8*)RExC_parse,
17326 RExC_end - RExC_parse,
17327 &numlen, UTF8_ALLOW_DEFAULT);
17328 RExC_parse += numlen;
17331 value = UCHARAT(RExC_parse++);
17333 /* Some compilers cannot handle switching on 64-bit integer
17334 * values, therefore value cannot be an UV. Yes, this will
17335 * be a problem later if we want switch on Unicode.
17336 * A similar issue a little bit later when switching on
17337 * namedclass. --jhi */
17339 /* If the \ is escaping white space when white space is being
17340 * skipped, it means that that white space is wanted literally, and
17341 * is already in 'value'. Otherwise, need to translate the escape
17342 * into what it signifies. */
17343 if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) {
17345 case 'w': namedclass = ANYOF_WORDCHAR; break;
17346 case 'W': namedclass = ANYOF_NWORDCHAR; break;
17347 case 's': namedclass = ANYOF_SPACE; break;
17348 case 'S': namedclass = ANYOF_NSPACE; break;
17349 case 'd': namedclass = ANYOF_DIGIT; break;
17350 case 'D': namedclass = ANYOF_NDIGIT; break;
17351 case 'v': namedclass = ANYOF_VERTWS; break;
17352 case 'V': namedclass = ANYOF_NVERTWS; break;
17353 case 'h': namedclass = ANYOF_HORIZWS; break;
17354 case 'H': namedclass = ANYOF_NHORIZWS; break;
17355 case 'N': /* Handle \N{NAME} in class */
17357 const char * const backslash_N_beg = RExC_parse - 2;
17360 if (! grok_bslash_N(pRExC_state,
17361 NULL, /* No regnode */
17362 &value, /* Yes single value */
17363 &cp_count, /* Multiple code pt count */
17369 if (*flagp & NEED_UTF8)
17370 FAIL("panic: grok_bslash_N set NEED_UTF8");
17372 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
17374 if (cp_count < 0) {
17375 vFAIL("\\N in a character class must be a named character: \\N{...}");
17377 else if (cp_count == 0) {
17378 ckWARNreg(RExC_parse,
17379 "Ignoring zero length \\N{} in character class");
17381 else { /* cp_count > 1 */
17382 assert(cp_count > 1);
17383 if (! RExC_in_multi_char_class) {
17384 if ( ! allow_mutiple_chars
17387 || *RExC_parse == '-')
17391 vFAIL("\\N{} here is restricted to one character");
17393 ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class");
17394 break; /* <value> contains the first code
17395 point. Drop out of the switch to
17399 SV * multi_char_N = newSVpvn(backslash_N_beg,
17400 RExC_parse - backslash_N_beg);
17402 = add_multi_match(multi_char_matches,
17407 } /* End of cp_count != 1 */
17409 /* This element should not be processed further in this
17412 value = save_value;
17413 prevvalue = save_prevvalue;
17414 continue; /* Back to top of loop to get next char */
17417 /* Here, is a single code point, and <value> contains it */
17418 unicode_range = TRUE; /* \N{} are Unicode */
17426 /* \p means they want Unicode semantics */
17427 REQUIRE_UNI_RULES(flagp, 0);
17429 if (RExC_parse >= RExC_end)
17430 vFAIL2("Empty \\%c", (U8)value);
17431 if (*RExC_parse == '{') {
17432 const U8 c = (U8)value;
17433 e = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
17436 vFAIL2("Missing right brace on \\%c{}", c);
17441 /* White space is allowed adjacent to the braces and after
17442 * any '^', even when not under /x */
17443 while (isSPACE(*RExC_parse)) {
17447 if (UCHARAT(RExC_parse) == '^') {
17449 /* toggle. (The rhs xor gets the single bit that
17450 * differs between P and p; the other xor inverts just
17452 value ^= 'P' ^ 'p';
17455 while (isSPACE(*RExC_parse)) {
17460 if (e == RExC_parse)
17461 vFAIL2("Empty \\%c{}", c);
17463 n = e - RExC_parse;
17464 while (isSPACE(*(RExC_parse + n - 1)))
17467 } /* The \p isn't immediately followed by a '{' */
17468 else if (! isALPHA(*RExC_parse)) {
17469 RExC_parse += (UTF)
17470 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
17472 vFAIL2("Character following \\%c must be '{' or a "
17473 "single-character Unicode property name",
17481 char* name = RExC_parse;
17483 /* Any message returned about expanding the definition */
17484 SV* msg = newSVpvs_flags("", SVs_TEMP);
17486 /* If set TRUE, the property is user-defined as opposed to
17487 * official Unicode */
17488 bool user_defined = FALSE;
17490 SV * prop_definition = parse_uniprop_string(
17491 name, n, UTF, FOLD,
17492 FALSE, /* This is compile-time */
17494 /* We can't defer this defn when
17495 * the full result is required in
17497 ! cBOOL(ret_invlist),
17503 if (SvCUR(msg)) { /* Assumes any error causes a msg */
17504 assert(prop_definition == NULL);
17505 RExC_parse = e + 1;
17506 if (SvUTF8(msg)) { /* msg being UTF-8 makes the whole
17507 thing so, or else the display is
17511 /* diag_listed_as: Can't find Unicode property definition "%s" in regex; marked by <-- HERE in m/%s/ */
17512 vFAIL2utf8f("%" UTF8f, UTF8fARG(SvUTF8(msg),
17513 SvCUR(msg), SvPVX(msg)));
17516 if (! is_invlist(prop_definition)) {
17518 /* Here, the definition isn't known, so we have gotten
17519 * returned a string that will be evaluated if and when
17520 * encountered at runtime. We add it to the list of
17521 * such properties, along with whether it should be
17522 * complemented or not */
17523 if (value == 'P') {
17524 sv_catpvs(listsv, "!");
17527 sv_catpvs(listsv, "+");
17529 sv_catsv(listsv, prop_definition);
17531 has_runtime_dependency |= HAS_USER_DEFINED_PROPERTY;
17533 /* We don't know yet what this matches, so have to flag
17535 anyof_flags |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
17538 assert (prop_definition && is_invlist(prop_definition));
17540 /* Here we do have the complete property definition
17542 * Temporary workaround for [perl #133136]. For this
17543 * precise input that is in the .t that is failing,
17544 * load utf8.pm, which is what the test wants, so that
17545 * that .t passes */
17546 if ( memEQs(RExC_start, e + 1 - RExC_start,
17548 && ! hv_common(GvHVn(PL_incgv),
17550 "utf8.pm", sizeof("utf8.pm") - 1,
17551 0, HV_FETCH_ISEXISTS, NULL, 0))
17553 require_pv("utf8.pm");
17556 if (! user_defined &&
17557 /* We warn on matching an above-Unicode code point
17558 * if the match would return true, except don't
17559 * warn for \p{All}, which has exactly one element
17561 (_invlist_contains_cp(prop_definition, 0x110000)
17562 && (! (_invlist_len(prop_definition) == 1
17563 && *invlist_array(prop_definition) == 0))))
17568 /* Invert if asking for the complement */
17569 if (value == 'P') {
17570 _invlist_union_complement_2nd(properties,
17575 _invlist_union(properties, prop_definition, &properties);
17580 RExC_parse = e + 1;
17581 namedclass = ANYOF_UNIPROP; /* no official name, but it's
17585 case 'n': value = '\n'; break;
17586 case 'r': value = '\r'; break;
17587 case 't': value = '\t'; break;
17588 case 'f': value = '\f'; break;
17589 case 'b': value = '\b'; break;
17590 case 'e': value = ESC_NATIVE; break;
17591 case 'a': value = '\a'; break;
17593 RExC_parse--; /* function expects to be pointed at the 'o' */
17595 const char* error_msg;
17596 bool valid = grok_bslash_o(&RExC_parse,
17600 TO_OUTPUT_WARNINGS(RExC_parse),
17602 silence_non_portable,
17607 UPDATE_WARNINGS_LOC(RExC_parse - 1);
17609 non_portable_endpoint++;
17612 RExC_parse--; /* function expects to be pointed at the 'x' */
17614 const char* error_msg;
17615 bool valid = grok_bslash_x(&RExC_parse,
17619 TO_OUTPUT_WARNINGS(RExC_parse),
17621 silence_non_portable,
17626 UPDATE_WARNINGS_LOC(RExC_parse - 1);
17628 non_portable_endpoint++;
17631 value = grok_bslash_c(*RExC_parse, TO_OUTPUT_WARNINGS(RExC_parse));
17632 UPDATE_WARNINGS_LOC(RExC_parse);
17634 non_portable_endpoint++;
17636 case '0': case '1': case '2': case '3': case '4':
17637 case '5': case '6': case '7':
17639 /* Take 1-3 octal digits */
17640 I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
17641 numlen = (strict) ? 4 : 3;
17642 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
17643 RExC_parse += numlen;
17646 RExC_parse += (UTF)
17647 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
17649 vFAIL("Need exactly 3 octal digits");
17651 else if ( numlen < 3 /* like \08, \178 */
17652 && RExC_parse < RExC_end
17653 && isDIGIT(*RExC_parse)
17654 && ckWARN(WARN_REGEXP))
17656 reg_warn_non_literal_string(
17658 form_short_octal_warning(RExC_parse, numlen));
17661 non_portable_endpoint++;
17665 /* Allow \_ to not give an error */
17666 if (isWORDCHAR(value) && value != '_') {
17668 vFAIL2("Unrecognized escape \\%c in character class",
17672 ckWARN2reg(RExC_parse,
17673 "Unrecognized escape \\%c in character class passed through",
17678 } /* End of switch on char following backslash */
17679 } /* end of handling backslash escape sequences */
17681 /* Here, we have the current token in 'value' */
17683 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
17686 /* a bad range like a-\d, a-[:digit:]. The '-' is taken as a
17687 * literal, as is the character that began the false range, i.e.
17688 * the 'a' in the examples */
17690 const int w = (RExC_parse >= rangebegin)
17691 ? RExC_parse - rangebegin
17695 "False [] range \"%" UTF8f "\"",
17696 UTF8fARG(UTF, w, rangebegin));
17699 ckWARN2reg(RExC_parse,
17700 "False [] range \"%" UTF8f "\"",
17701 UTF8fARG(UTF, w, rangebegin));
17702 cp_list = add_cp_to_invlist(cp_list, '-');
17703 cp_foldable_list = add_cp_to_invlist(cp_foldable_list,
17707 range = 0; /* this was not a true range */
17708 element_count += 2; /* So counts for three values */
17711 classnum = namedclass_to_classnum(namedclass);
17713 if (LOC && namedclass < ANYOF_POSIXL_MAX
17714 #ifndef HAS_ISASCII
17715 && classnum != _CC_ASCII
17718 SV* scratch_list = NULL;
17720 /* What the Posix classes (like \w, [:space:]) match isn't
17721 * generally knowable under locale until actual match time. A
17722 * special node is used for these which has extra space for a
17723 * bitmap, with a bit reserved for each named class that is to
17724 * be matched against. (This isn't needed for \p{} and
17725 * pseudo-classes, as they are not affected by locale, and
17726 * hence are dealt with separately.) However, if a named class
17727 * and its complement are both present, then it matches
17728 * everything, and there is no runtime dependency. Odd numbers
17729 * are the complements of the next lower number, so xor works.
17730 * (Note that something like [\w\D] should match everything,
17731 * because \d should be a proper subset of \w. But rather than
17732 * trust that the locale is well behaved, we leave this to
17733 * runtime to sort out) */
17734 if (POSIXL_TEST(posixl, namedclass ^ 1)) {
17735 cp_list = _add_range_to_invlist(cp_list, 0, UV_MAX);
17736 POSIXL_ZERO(posixl);
17737 has_runtime_dependency &= ~HAS_L_RUNTIME_DEPENDENCY;
17738 anyof_flags &= ~ANYOF_MATCHES_POSIXL;
17739 continue; /* We could ignore the rest of the class, but
17740 best to parse it for any errors */
17742 else { /* Here, isn't the complement of any already parsed
17744 POSIXL_SET(posixl, namedclass);
17745 has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
17746 anyof_flags |= ANYOF_MATCHES_POSIXL;
17748 /* The above-Latin1 characters are not subject to locale
17749 * rules. Just add them to the unconditionally-matched
17752 /* Get the list of the above-Latin1 code points this
17754 _invlist_intersection_maybe_complement_2nd(PL_AboveLatin1,
17755 PL_XPosix_ptrs[classnum],
17757 /* Odd numbers are complements,
17758 * like NDIGIT, NASCII, ... */
17759 namedclass % 2 != 0,
17761 /* Checking if 'cp_list' is NULL first saves an extra
17762 * clone. Its reference count will be decremented at the
17763 * next union, etc, or if this is the only instance, at the
17764 * end of the routine */
17766 cp_list = scratch_list;
17769 _invlist_union(cp_list, scratch_list, &cp_list);
17770 SvREFCNT_dec_NN(scratch_list);
17772 continue; /* Go get next character */
17777 /* Here, is not /l, or is a POSIX class for which /l doesn't
17778 * matter (or is a Unicode property, which is skipped here). */
17779 if (namedclass >= ANYOF_POSIXL_MAX) { /* If a special class */
17780 if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */
17782 /* Here, should be \h, \H, \v, or \V. None of /d, /i
17783 * nor /l make a difference in what these match,
17784 * therefore we just add what they match to cp_list. */
17785 if (classnum != _CC_VERTSPACE) {
17786 assert( namedclass == ANYOF_HORIZWS
17787 || namedclass == ANYOF_NHORIZWS);
17789 /* It turns out that \h is just a synonym for
17791 classnum = _CC_BLANK;
17794 _invlist_union_maybe_complement_2nd(
17796 PL_XPosix_ptrs[classnum],
17797 namedclass % 2 != 0, /* Complement if odd
17798 (NHORIZWS, NVERTWS)
17803 else if ( AT_LEAST_UNI_SEMANTICS
17804 || classnum == _CC_ASCII
17805 || (DEPENDS_SEMANTICS && ( classnum == _CC_DIGIT
17806 || classnum == _CC_XDIGIT)))
17808 /* We usually have to worry about /d affecting what POSIX
17809 * classes match, with special code needed because we won't
17810 * know until runtime what all matches. But there is no
17811 * extra work needed under /u and /a; and [:ascii:] is
17812 * unaffected by /d; and :digit: and :xdigit: don't have
17813 * runtime differences under /d. So we can special case
17814 * these, and avoid some extra work below, and at runtime.
17816 _invlist_union_maybe_complement_2nd(
17818 ((AT_LEAST_ASCII_RESTRICTED)
17819 ? PL_Posix_ptrs[classnum]
17820 : PL_XPosix_ptrs[classnum]),
17821 namedclass % 2 != 0,
17824 else { /* Garden variety class. If is NUPPER, NALPHA, ...
17825 complement and use nposixes */
17826 SV** posixes_ptr = namedclass % 2 == 0
17829 _invlist_union_maybe_complement_2nd(
17831 PL_XPosix_ptrs[classnum],
17832 namedclass % 2 != 0,
17836 } /* end of namedclass \blah */
17838 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17840 /* If 'range' is set, 'value' is the ending of a range--check its
17841 * validity. (If value isn't a single code point in the case of a
17842 * range, we should have figured that out above in the code that
17843 * catches false ranges). Later, we will handle each individual code
17844 * point in the range. If 'range' isn't set, this could be the
17845 * beginning of a range, so check for that by looking ahead to see if
17846 * the next real character to be processed is the range indicator--the
17851 /* For unicode ranges, we have to test that the Unicode as opposed
17852 * to the native values are not decreasing. (Above 255, there is
17853 * no difference between native and Unicode) */
17854 if (unicode_range && prevvalue < 255 && value < 255) {
17855 if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) {
17856 goto backwards_range;
17861 if (prevvalue > value) /* b-a */ {
17866 w = RExC_parse - rangebegin;
17868 "Invalid [] range \"%" UTF8f "\"",
17869 UTF8fARG(UTF, w, rangebegin));
17870 NOT_REACHED; /* NOTREACHED */
17874 prevvalue = value; /* save the beginning of the potential range */
17875 if (! stop_at_1 /* Can't be a range if parsing just one thing */
17876 && *RExC_parse == '-')
17878 char* next_char_ptr = RExC_parse + 1;
17880 /* Get the next real char after the '-' */
17881 SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr);
17883 /* If the '-' is at the end of the class (just before the ']',
17884 * it is a literal minus; otherwise it is a range */
17885 if (next_char_ptr < RExC_end && *next_char_ptr != ']') {
17886 RExC_parse = next_char_ptr;
17888 /* a bad range like \w-, [:word:]- ? */
17889 if (namedclass > OOB_NAMEDCLASS) {
17890 if (strict || ckWARN(WARN_REGEXP)) {
17891 const int w = RExC_parse >= rangebegin
17892 ? RExC_parse - rangebegin
17895 vFAIL4("False [] range \"%*.*s\"",
17900 "False [] range \"%*.*s\"",
17904 cp_list = add_cp_to_invlist(cp_list, '-');
17907 range = 1; /* yeah, it's a range! */
17908 continue; /* but do it the next time */
17913 if (namedclass > OOB_NAMEDCLASS) {
17917 /* Here, we have a single value this time through the loop, and
17918 * <prevvalue> is the beginning of the range, if any; or <value> if
17921 /* non-Latin1 code point implies unicode semantics. */
17923 REQUIRE_UNI_RULES(flagp, 0);
17926 /* Ready to process either the single value, or the completed range.
17927 * For single-valued non-inverted ranges, we consider the possibility
17928 * of multi-char folds. (We made a conscious decision to not do this
17929 * for the other cases because it can often lead to non-intuitive
17930 * results. For example, you have the peculiar case that:
17931 * "s s" =~ /^[^\xDF]+$/i => Y
17932 * "ss" =~ /^[^\xDF]+$/i => N
17934 * See [perl #89750] */
17935 if (FOLD && allow_mutiple_chars && value == prevvalue) {
17936 if ( value == LATIN_SMALL_LETTER_SHARP_S
17937 || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
17940 /* Here <value> is indeed a multi-char fold. Get what it is */
17942 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
17945 UV folded = _to_uni_fold_flags(
17949 FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED
17950 ? FOLD_FLAGS_NOMIX_ASCII
17954 /* Here, <folded> should be the first character of the
17955 * multi-char fold of <value>, with <foldbuf> containing the
17956 * whole thing. But, if this fold is not allowed (because of
17957 * the flags), <fold> will be the same as <value>, and should
17958 * be processed like any other character, so skip the special
17960 if (folded != value) {
17962 /* Skip if we are recursed, currently parsing the class
17963 * again. Otherwise add this character to the list of
17964 * multi-char folds. */
17965 if (! RExC_in_multi_char_class) {
17966 STRLEN cp_count = utf8_length(foldbuf,
17967 foldbuf + foldlen);
17968 SV* multi_fold = sv_2mortal(newSVpvs(""));
17970 Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%" UVXf "}", value);
17973 = add_multi_match(multi_char_matches,
17979 /* This element should not be processed further in this
17982 value = save_value;
17983 prevvalue = save_prevvalue;
17989 if (strict && ckWARN(WARN_REGEXP)) {
17992 /* If the range starts above 255, everything is portable and
17993 * likely to be so for any forseeable character set, so don't
17995 if (unicode_range && non_portable_endpoint && prevvalue < 256) {
17996 vWARN(RExC_parse, "Both or neither range ends should be Unicode");
17998 else if (prevvalue != value) {
18000 /* Under strict, ranges that stop and/or end in an ASCII
18001 * printable should have each end point be a portable value
18002 * for it (preferably like 'A', but we don't warn if it is
18003 * a (portable) Unicode name or code point), and the range
18004 * must be be all digits or all letters of the same case.
18005 * Otherwise, the range is non-portable and unclear as to
18006 * what it contains */
18007 if ( (isPRINT_A(prevvalue) || isPRINT_A(value))
18008 && ( non_portable_endpoint
18009 || ! ( (isDIGIT_A(prevvalue) && isDIGIT_A(value))
18010 || (isLOWER_A(prevvalue) && isLOWER_A(value))
18011 || (isUPPER_A(prevvalue) && isUPPER_A(value))
18013 vWARN(RExC_parse, "Ranges of ASCII printables should"
18014 " be some subset of \"0-9\","
18015 " \"A-Z\", or \"a-z\"");
18017 else if (prevvalue >= FIRST_NON_ASCII_DECIMAL_DIGIT) {
18018 SSize_t index_start;
18019 SSize_t index_final;
18021 /* But the nature of Unicode and languages mean we
18022 * can't do the same checks for above-ASCII ranges,
18023 * except in the case of digit ones. These should
18024 * contain only digits from the same group of 10. The
18025 * ASCII case is handled just above. Hence here, the
18026 * range could be a range of digits. First some
18027 * unlikely special cases. Grandfather in that a range
18028 * ending in 19DA (NEW TAI LUE THAM DIGIT ONE) is bad
18029 * if its starting value is one of the 10 digits prior
18030 * to it. This is because it is an alternate way of
18031 * writing 19D1, and some people may expect it to be in
18032 * that group. But it is bad, because it won't give
18033 * the expected results. In Unicode 5.2 it was
18034 * considered to be in that group (of 11, hence), but
18035 * this was fixed in the next version */
18037 if (UNLIKELY(value == 0x19DA && prevvalue >= 0x19D0)) {
18038 goto warn_bad_digit_range;
18040 else if (UNLIKELY( prevvalue >= 0x1D7CE
18041 && value <= 0x1D7FF))
18043 /* This is the only other case currently in Unicode
18044 * where the algorithm below fails. The code
18045 * points just above are the end points of a single
18046 * range containing only decimal digits. It is 5
18047 * different series of 0-9. All other ranges of
18048 * digits currently in Unicode are just a single
18049 * series. (And mktables will notify us if a later
18050 * Unicode version breaks this.)
18052 * If the range being checked is at most 9 long,
18053 * and the digit values represented are in
18054 * numerical order, they are from the same series.
18056 if ( value - prevvalue > 9
18057 || ((( value - 0x1D7CE) % 10)
18058 <= (prevvalue - 0x1D7CE) % 10))
18060 goto warn_bad_digit_range;
18065 /* For all other ranges of digits in Unicode, the
18066 * algorithm is just to check if both end points
18067 * are in the same series, which is the same range.
18069 index_start = _invlist_search(
18070 PL_XPosix_ptrs[_CC_DIGIT],
18073 /* Warn if the range starts and ends with a digit,
18074 * and they are not in the same group of 10. */
18075 if ( index_start >= 0
18076 && ELEMENT_RANGE_MATCHES_INVLIST(index_start)
18078 _invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
18079 value)) != index_start
18080 && index_final >= 0
18081 && ELEMENT_RANGE_MATCHES_INVLIST(index_final))
18083 warn_bad_digit_range:
18084 vWARN(RExC_parse, "Ranges of digits should be"
18085 " from the same group of"
18092 if ((! range || prevvalue == value) && non_portable_endpoint) {
18093 if (isPRINT_A(value)) {
18096 if (isBACKSLASHED_PUNCT(value)) {
18097 literal[d++] = '\\';
18099 literal[d++] = (char) value;
18100 literal[d++] = '\0';
18103 "\"%.*s\" is more clearly written simply as \"%s\"",
18104 (int) (RExC_parse - rangebegin),
18109 else if (isMNEMONIC_CNTRL(value)) {
18111 "\"%.*s\" is more clearly written simply as \"%s\"",
18112 (int) (RExC_parse - rangebegin),
18114 cntrl_to_mnemonic((U8) value)
18120 /* Deal with this element of the class */
18123 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18126 /* On non-ASCII platforms, for ranges that span all of 0..255, and ones
18127 * that don't require special handling, we can just add the range like
18128 * we do for ASCII platforms */
18129 if ((UNLIKELY(prevvalue == 0) && value >= 255)
18130 || ! (prevvalue < 256
18132 || (! non_portable_endpoint
18133 && ((isLOWER_A(prevvalue) && isLOWER_A(value))
18134 || (isUPPER_A(prevvalue)
18135 && isUPPER_A(value)))))))
18137 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18141 /* Here, requires special handling. This can be because it is a
18142 * range whose code points are considered to be Unicode, and so
18143 * must be individually translated into native, or because its a
18144 * subrange of 'A-Z' or 'a-z' which each aren't contiguous in
18145 * EBCDIC, but we have defined them to include only the "expected"
18146 * upper or lower case ASCII alphabetics. Subranges above 255 are
18147 * the same in native and Unicode, so can be added as a range */
18148 U8 start = NATIVE_TO_LATIN1(prevvalue);
18150 U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255;
18151 for (j = start; j <= end; j++) {
18152 cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j));
18155 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18161 range = 0; /* this range (if it was one) is done now */
18162 } /* End of loop through all the text within the brackets */
18164 if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) {
18165 output_posix_warnings(pRExC_state, posix_warnings);
18168 /* If anything in the class expands to more than one character, we have to
18169 * deal with them by building up a substitute parse string, and recursively
18170 * calling reg() on it, instead of proceeding */
18171 if (multi_char_matches) {
18172 SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
18175 char *save_end = RExC_end;
18176 char *save_parse = RExC_parse;
18177 char *save_start = RExC_start;
18178 Size_t constructed_prefix_len = 0; /* This gives the length of the
18179 constructed portion of the
18180 substitute parse. */
18181 bool first_time = TRUE; /* First multi-char occurrence doesn't get
18186 /* Only one level of recursion allowed */
18187 assert(RExC_copy_start_in_constructed == RExC_precomp);
18189 #if 0 /* Have decided not to deal with multi-char folds in inverted classes,
18190 because too confusing */
18192 sv_catpvs(substitute_parse, "(?:");
18196 /* Look at the longest folds first */
18197 for (cp_count = av_tindex_skip_len_mg(multi_char_matches);
18202 if (av_exists(multi_char_matches, cp_count)) {
18203 AV** this_array_ptr;
18206 this_array_ptr = (AV**) av_fetch(multi_char_matches,
18208 while ((this_sequence = av_pop(*this_array_ptr)) !=
18211 if (! first_time) {
18212 sv_catpvs(substitute_parse, "|");
18214 first_time = FALSE;
18216 sv_catpv(substitute_parse, SvPVX(this_sequence));
18221 /* If the character class contains anything else besides these
18222 * multi-character folds, have to include it in recursive parsing */
18223 if (element_count) {
18224 sv_catpvs(substitute_parse, "|[");
18225 constructed_prefix_len = SvCUR(substitute_parse);
18226 sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
18228 /* Put in a closing ']' only if not going off the end, as otherwise
18229 * we are adding something that really isn't there */
18230 if (RExC_parse < RExC_end) {
18231 sv_catpvs(substitute_parse, "]");
18235 sv_catpvs(substitute_parse, ")");
18238 /* This is a way to get the parse to skip forward a whole named
18239 * sequence instead of matching the 2nd character when it fails the
18241 sv_catpvs(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
18245 /* Set up the data structure so that any errors will be properly
18246 * reported. See the comments at the definition of
18247 * REPORT_LOCATION_ARGS for details */
18248 RExC_copy_start_in_input = (char *) orig_parse;
18249 RExC_start = RExC_parse = SvPV(substitute_parse, len);
18250 RExC_copy_start_in_constructed = RExC_start + constructed_prefix_len;
18251 RExC_end = RExC_parse + len;
18252 RExC_in_multi_char_class = 1;
18254 ret = reg(pRExC_state, 1, ®_flags, depth+1);
18256 *flagp |= reg_flags & (HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PARSE|NEED_UTF8);
18258 /* And restore so can parse the rest of the pattern */
18259 RExC_parse = save_parse;
18260 RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = save_start;
18261 RExC_end = save_end;
18262 RExC_in_multi_char_class = 0;
18263 SvREFCNT_dec_NN(multi_char_matches);
18267 /* If folding, we calculate all characters that could fold to or from the
18268 * ones already on the list */
18269 if (cp_foldable_list) {
18271 UV start, end; /* End points of code point ranges */
18273 SV* fold_intersection = NULL;
18276 /* Our calculated list will be for Unicode rules. For locale
18277 * matching, we have to keep a separate list that is consulted at
18278 * runtime only when the locale indicates Unicode rules (and we
18279 * don't include potential matches in the ASCII/Latin1 range, as
18280 * any code point could fold to any other, based on the run-time
18281 * locale). For non-locale, we just use the general list */
18283 use_list = &only_utf8_locale_list;
18286 use_list = &cp_list;
18289 /* Only the characters in this class that participate in folds need
18290 * be checked. Get the intersection of this class and all the
18291 * possible characters that are foldable. This can quickly narrow
18292 * down a large class */
18293 _invlist_intersection(PL_in_some_fold, cp_foldable_list,
18294 &fold_intersection);
18296 /* Now look at the foldable characters in this class individually */
18297 invlist_iterinit(fold_intersection);
18298 while (invlist_iternext(fold_intersection, &start, &end)) {
18302 /* Look at every character in the range */
18303 for (j = start; j <= end; j++) {
18304 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
18307 Size_t folds_count;
18308 unsigned int first_fold;
18309 const unsigned int * remaining_folds;
18313 /* Under /l, we don't know what code points below 256
18314 * fold to, except we do know the MICRO SIGN folds to
18315 * an above-255 character if the locale is UTF-8, so we
18316 * add it to the special list (in *use_list) Otherwise
18317 * we know now what things can match, though some folds
18318 * are valid under /d only if the target is UTF-8.
18319 * Those go in a separate list */
18320 if ( IS_IN_SOME_FOLD_L1(j)
18321 && ! (LOC && j != MICRO_SIGN))
18324 /* ASCII is always matched; non-ASCII is matched
18325 * only under Unicode rules (which could happen
18326 * under /l if the locale is a UTF-8 one */
18327 if (isASCII(j) || ! DEPENDS_SEMANTICS) {
18328 *use_list = add_cp_to_invlist(*use_list,
18329 PL_fold_latin1[j]);
18331 else if (j != PL_fold_latin1[j]) {
18332 upper_latin1_only_utf8_matches
18333 = add_cp_to_invlist(
18334 upper_latin1_only_utf8_matches,
18335 PL_fold_latin1[j]);
18339 if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j)
18340 && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
18342 add_above_Latin1_folds(pRExC_state,
18349 /* Here is an above Latin1 character. We don't have the
18350 * rules hard-coded for it. First, get its fold. This is
18351 * the simple fold, as the multi-character folds have been
18352 * handled earlier and separated out */
18353 folded = _to_uni_fold_flags(j, foldbuf, &foldlen,
18354 (ASCII_FOLD_RESTRICTED)
18355 ? FOLD_FLAGS_NOMIX_ASCII
18358 /* Single character fold of above Latin1. Add everything
18359 * in its fold closure to the list that this node should
18361 folds_count = _inverse_folds(folded, &first_fold,
18363 for (k = 0; k <= folds_count; k++) {
18364 UV c = (k == 0) /* First time through use itself */
18366 : (k == 1) /* 2nd time use, the first fold */
18369 /* Then the remaining ones */
18370 : remaining_folds[k-2];
18372 /* /aa doesn't allow folds between ASCII and non- */
18373 if (( ASCII_FOLD_RESTRICTED
18374 && (isASCII(c) != isASCII(j))))
18379 /* Folds under /l which cross the 255/256 boundary are
18380 * added to a separate list. (These are valid only
18381 * when the locale is UTF-8.) */
18382 if (c < 256 && LOC) {
18383 *use_list = add_cp_to_invlist(*use_list, c);
18387 if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
18389 cp_list = add_cp_to_invlist(cp_list, c);
18392 /* Similarly folds involving non-ascii Latin1
18393 * characters under /d are added to their list */
18394 upper_latin1_only_utf8_matches
18395 = add_cp_to_invlist(
18396 upper_latin1_only_utf8_matches,
18402 SvREFCNT_dec_NN(fold_intersection);
18405 /* Now that we have finished adding all the folds, there is no reason
18406 * to keep the foldable list separate */
18407 _invlist_union(cp_list, cp_foldable_list, &cp_list);
18408 SvREFCNT_dec_NN(cp_foldable_list);
18411 /* And combine the result (if any) with any inversion lists from posix
18412 * classes. The lists are kept separate up to now because we don't want to
18413 * fold the classes */
18414 if (simple_posixes) { /* These are the classes known to be unaffected by
18417 _invlist_union(cp_list, simple_posixes, &cp_list);
18418 SvREFCNT_dec_NN(simple_posixes);
18421 cp_list = simple_posixes;
18424 if (posixes || nposixes) {
18425 if (! DEPENDS_SEMANTICS) {
18427 /* For everything but /d, we can just add the current 'posixes' and
18428 * 'nposixes' to the main list */
18431 _invlist_union(cp_list, posixes, &cp_list);
18432 SvREFCNT_dec_NN(posixes);
18440 _invlist_union(cp_list, nposixes, &cp_list);
18441 SvREFCNT_dec_NN(nposixes);
18444 cp_list = nposixes;
18449 /* Under /d, things like \w match upper Latin1 characters only if
18450 * the target string is in UTF-8. But things like \W match all the
18451 * upper Latin1 characters if the target string is not in UTF-8.
18453 * Handle the case with something like \W separately */
18455 SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1, NULL);
18457 /* A complemented posix class matches all upper Latin1
18458 * characters if not in UTF-8. And it matches just certain
18459 * ones when in UTF-8. That means those certain ones are
18460 * matched regardless, so can just be added to the
18461 * unconditional list */
18463 _invlist_union(cp_list, nposixes, &cp_list);
18464 SvREFCNT_dec_NN(nposixes);
18468 cp_list = nposixes;
18471 /* Likewise for 'posixes' */
18472 _invlist_union(posixes, cp_list, &cp_list);
18473 SvREFCNT_dec(posixes);
18475 /* Likewise for anything else in the range that matched only
18477 if (upper_latin1_only_utf8_matches) {
18478 _invlist_union(cp_list,
18479 upper_latin1_only_utf8_matches,
18481 SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
18482 upper_latin1_only_utf8_matches = NULL;
18485 /* If we don't match all the upper Latin1 characters regardless
18486 * of UTF-8ness, we have to set a flag to match the rest when
18488 _invlist_subtract(only_non_utf8_list, cp_list,
18489 &only_non_utf8_list);
18490 if (_invlist_len(only_non_utf8_list) != 0) {
18491 anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
18493 SvREFCNT_dec_NN(only_non_utf8_list);
18496 /* Here there were no complemented posix classes. That means
18497 * the upper Latin1 characters in 'posixes' match only when the
18498 * target string is in UTF-8. So we have to add them to the
18499 * list of those types of code points, while adding the
18500 * remainder to the unconditional list.
18502 * First calculate what they are */
18503 SV* nonascii_but_latin1_properties = NULL;
18504 _invlist_intersection(posixes, PL_UpperLatin1,
18505 &nonascii_but_latin1_properties);
18507 /* And add them to the final list of such characters. */
18508 _invlist_union(upper_latin1_only_utf8_matches,
18509 nonascii_but_latin1_properties,
18510 &upper_latin1_only_utf8_matches);
18512 /* Remove them from what now becomes the unconditional list */
18513 _invlist_subtract(posixes, nonascii_but_latin1_properties,
18516 /* And add those unconditional ones to the final list */
18518 _invlist_union(cp_list, posixes, &cp_list);
18519 SvREFCNT_dec_NN(posixes);
18526 SvREFCNT_dec(nonascii_but_latin1_properties);
18528 /* Get rid of any characters from the conditional list that we
18529 * now know are matched unconditionally, which may make that
18531 _invlist_subtract(upper_latin1_only_utf8_matches,
18533 &upper_latin1_only_utf8_matches);
18534 if (_invlist_len(upper_latin1_only_utf8_matches) == 0) {
18535 SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
18536 upper_latin1_only_utf8_matches = NULL;
18542 /* And combine the result (if any) with any inversion list from properties.
18543 * The lists are kept separate up to now so that we can distinguish the two
18544 * in regards to matching above-Unicode. A run-time warning is generated
18545 * if a Unicode property is matched against a non-Unicode code point. But,
18546 * we allow user-defined properties to match anything, without any warning,
18547 * and we also suppress the warning if there is a portion of the character
18548 * class that isn't a Unicode property, and which matches above Unicode, \W
18549 * or [\x{110000}] for example.
18550 * (Note that in this case, unlike the Posix one above, there is no
18551 * <upper_latin1_only_utf8_matches>, because having a Unicode property
18552 * forces Unicode semantics */
18556 /* If it matters to the final outcome, see if a non-property
18557 * component of the class matches above Unicode. If so, the
18558 * warning gets suppressed. This is true even if just a single
18559 * such code point is specified, as, though not strictly correct if
18560 * another such code point is matched against, the fact that they
18561 * are using above-Unicode code points indicates they should know
18562 * the issues involved */
18564 warn_super = ! (invert
18565 ^ (invlist_highest(cp_list) > PERL_UNICODE_MAX));
18568 _invlist_union(properties, cp_list, &cp_list);
18569 SvREFCNT_dec_NN(properties);
18572 cp_list = properties;
18577 |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
18579 /* Because an ANYOF node is the only one that warns, this node
18580 * can't be optimized into something else */
18581 optimizable = FALSE;
18585 /* Here, we have calculated what code points should be in the character
18588 * Now we can see about various optimizations. Fold calculation (which we
18589 * did above) needs to take place before inversion. Otherwise /[^k]/i
18590 * would invert to include K, which under /i would match k, which it
18591 * shouldn't. Therefore we can't invert folded locale now, as it won't be
18592 * folded until runtime */
18594 /* If we didn't do folding, it's because some information isn't available
18595 * until runtime; set the run-time fold flag for these We know to set the
18596 * flag if we have a non-NULL list for UTF-8 locales, or the class matches
18597 * at least one 0-255 range code point */
18600 /* Some things on the list might be unconditionally included because of
18601 * other components. Remove them, and clean up the list if it goes to
18603 if (only_utf8_locale_list && cp_list) {
18604 _invlist_subtract(only_utf8_locale_list, cp_list,
18605 &only_utf8_locale_list);
18607 if (_invlist_len(only_utf8_locale_list) == 0) {
18608 SvREFCNT_dec_NN(only_utf8_locale_list);
18609 only_utf8_locale_list = NULL;
18612 if ( only_utf8_locale_list
18613 || (cp_list && ( _invlist_contains_cp(cp_list, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE)
18614 || _invlist_contains_cp(cp_list, LATIN_SMALL_LETTER_DOTLESS_I))))
18616 has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18619 | ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
18621 else if (cp_list && invlist_lowest(cp_list) < 256) {
18622 /* If nothing is below 256, has no locale dependency; otherwise it
18624 anyof_flags |= ANYOFL_FOLD;
18625 has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18628 else if ( DEPENDS_SEMANTICS
18629 && ( upper_latin1_only_utf8_matches
18630 || (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)))
18632 RExC_seen_d_op = TRUE;
18633 has_runtime_dependency |= HAS_D_RUNTIME_DEPENDENCY;
18636 /* Optimize inverted patterns (e.g. [^a-z]) when everything is known at
18640 && ! has_runtime_dependency)
18642 _invlist_invert(cp_list);
18644 /* Clear the invert flag since have just done it here */
18649 *ret_invlist = cp_list;
18654 /* All possible optimizations below still have these characteristics.
18655 * (Multi-char folds aren't SIMPLE, but they don't get this far in this
18657 *flagp |= HASWIDTH|SIMPLE;
18659 if (anyof_flags & ANYOF_LOCALE_FLAGS) {
18660 RExC_contains_locale = 1;
18663 /* Some character classes are equivalent to other nodes. Such nodes take
18664 * up less room, and some nodes require fewer operations to execute, than
18665 * ANYOF nodes. EXACTish nodes may be joinable with adjacent nodes to
18666 * improve efficiency. */
18669 PERL_UINT_FAST8_T i;
18670 UV partial_cp_count = 0;
18671 UV start[MAX_FOLD_FROMS+1] = { 0 }; /* +1 for the folded-to char */
18672 UV end[MAX_FOLD_FROMS+1] = { 0 };
18673 bool single_range = FALSE;
18675 if (cp_list) { /* Count the code points in enough ranges that we would
18676 see all the ones possible in any fold in this version
18679 invlist_iterinit(cp_list);
18680 for (i = 0; i <= MAX_FOLD_FROMS; i++) {
18681 if (! invlist_iternext(cp_list, &start[i], &end[i])) {
18684 partial_cp_count += end[i] - start[i] + 1;
18688 single_range = TRUE;
18690 invlist_iterfinish(cp_list);
18693 /* If we know at compile time that this matches every possible code
18694 * point, any run-time dependencies don't matter */
18695 if (start[0] == 0 && end[0] == UV_MAX) {
18697 ret = reganode(pRExC_state, OPFAIL, 0);
18700 ret = reg_node(pRExC_state, SANY);
18706 /* Similarly, for /l posix classes, if both a class and its
18707 * complement match, any run-time dependencies don't matter */
18709 for (namedclass = 0; namedclass < ANYOF_POSIXL_MAX;
18712 if ( POSIXL_TEST(posixl, namedclass) /* class */
18713 && POSIXL_TEST(posixl, namedclass + 1)) /* its complement */
18716 ret = reganode(pRExC_state, OPFAIL, 0);
18719 ret = reg_node(pRExC_state, SANY);
18726 /* For well-behaved locales, some classes are subsets of others,
18727 * so complementing the subset and including the non-complemented
18728 * superset should match everything, like [\D[:alnum:]], and
18729 * [[:^alpha:][:alnum:]], but some implementations of locales are
18730 * buggy, and khw thinks its a bad idea to have optimization change
18731 * behavior, even if it avoids an OS bug in a given case */
18733 #define isSINGLE_BIT_SET(n) isPOWER_OF_2(n)
18735 /* If is a single posix /l class, can optimize to just that op.
18736 * Such a node will not match anything in the Latin1 range, as that
18737 * is not determinable until runtime, but will match whatever the
18738 * class does outside that range. (Note that some classes won't
18739 * match anything outside the range, like [:ascii:]) */
18740 if ( isSINGLE_BIT_SET(posixl)
18741 && (partial_cp_count == 0 || start[0] > 255))
18744 SV * class_above_latin1 = NULL;
18745 bool already_inverted;
18746 bool are_equivalent;
18748 /* Compute which bit is set, which is the same thing as, e.g.,
18749 * ANYOF_CNTRL. From
18750 * https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn
18752 static const int MultiplyDeBruijnBitPosition2[32] =
18754 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
18755 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
18758 namedclass = MultiplyDeBruijnBitPosition2[(posixl
18759 * 0x077CB531U) >> 27];
18760 classnum = namedclass_to_classnum(namedclass);
18762 /* The named classes are such that the inverted number is one
18763 * larger than the non-inverted one */
18764 already_inverted = namedclass
18765 - classnum_to_namedclass(classnum);
18767 /* Create an inversion list of the official property, inverted
18768 * if the constructed node list is inverted, and restricted to
18769 * only the above latin1 code points, which are the only ones
18770 * known at compile time */
18771 _invlist_intersection_maybe_complement_2nd(
18773 PL_XPosix_ptrs[classnum],
18775 &class_above_latin1);
18776 are_equivalent = _invlistEQ(class_above_latin1, cp_list,
18778 SvREFCNT_dec_NN(class_above_latin1);
18780 if (are_equivalent) {
18782 /* Resolve the run-time inversion flag with this possibly
18783 * inverted class */
18784 invert = invert ^ already_inverted;
18786 ret = reg_node(pRExC_state,
18787 POSIXL + invert * (NPOSIXL - POSIXL));
18788 FLAGS(REGNODE_p(ret)) = classnum;
18794 /* khw can't think of any other possible transformation involving
18796 if (has_runtime_dependency & HAS_USER_DEFINED_PROPERTY) {
18800 if (! has_runtime_dependency) {
18802 /* If the list is empty, nothing matches. This happens, for
18803 * example, when a Unicode property that doesn't match anything is
18804 * the only element in the character class (perluniprops.pod notes
18805 * such properties). */
18806 if (partial_cp_count == 0) {
18808 ret = reg_node(pRExC_state, SANY);
18811 ret = reganode(pRExC_state, OPFAIL, 0);
18817 /* If matches everything but \n */
18818 if ( start[0] == 0 && end[0] == '\n' - 1
18819 && start[1] == '\n' + 1 && end[1] == UV_MAX)
18822 ret = reg_node(pRExC_state, REG_ANY);
18828 /* Next see if can optimize classes that contain just a few code points
18829 * into an EXACTish node. The reason to do this is to let the
18830 * optimizer join this node with adjacent EXACTish ones, and ANYOF
18831 * nodes require conversion to code point from UTF-8.
18833 * An EXACTFish node can be generated even if not under /i, and vice
18834 * versa. But care must be taken. An EXACTFish node has to be such
18835 * that it only matches precisely the code points in the class, but we
18836 * want to generate the least restrictive one that does that, to
18837 * increase the odds of being able to join with an adjacent node. For
18838 * example, if the class contains [kK], we have to make it an EXACTFAA
18839 * node to prevent the KELVIN SIGN from matching. Whether we are under
18840 * /i or not is irrelevant in this case. Less obvious is the pattern
18841 * qr/[\x{02BC}]n/i. U+02BC is MODIFIER LETTER APOSTROPHE. That is
18842 * supposed to match the single character U+0149 LATIN SMALL LETTER N
18843 * PRECEDED BY APOSTROPHE. And so even though there is no simple fold
18844 * that includes \X{02BC}, there is a multi-char fold that does, and so
18845 * the node generated for it must be an EXACTFish one. On the other
18846 * hand qr/:/i should generate a plain EXACT node since the colon
18847 * participates in no fold whatsoever, and having it EXACT tells the
18848 * optimizer the target string cannot match unless it has a colon in
18854 /* Only try if there are no more code points in the class than
18855 * in the max possible fold */
18856 && inRANGE(partial_cp_count, 1, MAX_FOLD_FROMS + 1))
18858 if (partial_cp_count == 1 && ! upper_latin1_only_utf8_matches)
18860 /* We can always make a single code point class into an
18861 * EXACTish node. */
18865 /* Here is /l: Use EXACTL, except if there is a fold not
18866 * known until runtime so shows as only a single code point
18867 * here. For code points above 255, we know which can
18868 * cause problems by having a potential fold to the Latin1
18871 || ( start[0] > 255
18872 && ! is_PROBLEMATIC_LOCALE_FOLD_cp(start[0])))
18880 else if (! FOLD) { /* Not /l and not /i */
18881 op = (start[0] < 256) ? EXACT : EXACT_REQ8;
18883 else if (start[0] < 256) { /* /i, not /l, and the code point is
18886 /* Under /i, it gets a little tricky. A code point that
18887 * doesn't participate in a fold should be an EXACT node.
18888 * We know this one isn't the result of a simple fold, or
18889 * there'd be more than one code point in the list, but it
18890 * could be part of a multi- character fold. In that case
18891 * we better not create an EXACT node, as we would wrongly
18892 * be telling the optimizer that this code point must be in
18893 * the target string, and that is wrong. This is because
18894 * if the sequence around this code point forms a
18895 * multi-char fold, what needs to be in the string could be
18896 * the code point that folds to the sequence.
18898 * This handles the case of below-255 code points, as we
18899 * have an easy look up for those. The next clause handles
18900 * the above-256 one */
18901 op = IS_IN_SOME_FOLD_L1(start[0])
18905 else { /* /i, larger code point. Since we are under /i, and
18906 have just this code point, we know that it can't
18907 fold to something else, so PL_InMultiCharFold
18909 op = _invlist_contains_cp(PL_InMultiCharFold,
18917 else if ( ! (has_runtime_dependency & ~HAS_D_RUNTIME_DEPENDENCY)
18918 && _invlist_contains_cp(PL_in_some_fold, start[0]))
18920 /* Here, the only runtime dependency, if any, is from /d, and
18921 * the class matches more than one code point, and the lowest
18922 * code point participates in some fold. It might be that the
18923 * other code points are /i equivalent to this one, and hence
18924 * they would representable by an EXACTFish node. Above, we
18925 * eliminated classes that contain too many code points to be
18926 * EXACTFish, with the test for MAX_FOLD_FROMS
18928 * First, special case the ASCII fold pairs, like 'B' and 'b'.
18929 * We do this because we have EXACTFAA at our disposal for the
18931 if (partial_cp_count == 2 && isASCII(start[0])) {
18933 /* The only ASCII characters that participate in folds are
18935 assert(isALPHA(start[0]));
18936 if ( end[0] == start[0] /* First range is a single
18937 character, so 2nd exists */
18938 && isALPHA_FOLD_EQ(start[0], start[1]))
18941 /* Here, is part of an ASCII fold pair */
18943 if ( ASCII_FOLD_RESTRICTED
18944 || HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(start[0]))
18946 /* If the second clause just above was true, it
18947 * means we can't be under /i, or else the list
18948 * would have included more than this fold pair.
18949 * Therefore we have to exclude the possibility of
18950 * whatever else it is that folds to these, by
18951 * using EXACTFAA */
18954 else if (HAS_NONLATIN1_FOLD_CLOSURE(start[0])) {
18956 /* Here, there's no simple fold that start[0] is part
18957 * of, but there is a multi-character one. If we
18958 * are not under /i, we want to exclude that
18959 * possibility; if under /i, we want to include it
18961 op = (FOLD) ? EXACTFU : EXACTFAA;
18965 /* Here, the only possible fold start[0] particpates in
18966 * is with start[1]. /i or not isn't relevant */
18970 value = toFOLD(start[0]);
18973 else if ( ! upper_latin1_only_utf8_matches
18974 || ( _invlist_len(upper_latin1_only_utf8_matches)
18977 invlist_highest(upper_latin1_only_utf8_matches)]
18980 /* Here, the smallest character is non-ascii or there are
18981 * more than 2 code points matched by this node. Also, we
18982 * either don't have /d UTF-8 dependent matches, or if we
18983 * do, they look like they could be a single character that
18984 * is the fold of the lowest one in the always-match list.
18985 * This test quickly excludes most of the false positives
18986 * when there are /d UTF-8 depdendent matches. These are
18987 * like LATIN CAPITAL LETTER A WITH GRAVE matching LATIN
18988 * SMALL LETTER A WITH GRAVE iff the target string is
18989 * UTF-8. (We don't have to worry above about exceeding
18990 * the array bounds of PL_fold_latin1[] because any code
18991 * point in 'upper_latin1_only_utf8_matches' is below 256.)
18993 * EXACTFAA would apply only to pairs (hence exactly 2 code
18994 * points) in the ASCII range, so we can't use it here to
18995 * artificially restrict the fold domain, so we check if
18996 * the class does or does not match some EXACTFish node.
18997 * Further, if we aren't under /i, and and the folded-to
18998 * character is part of a multi-character fold, we can't do
18999 * this optimization, as the sequence around it could be
19000 * that multi-character fold, and we don't here know the
19001 * context, so we have to assume it is that multi-char
19002 * fold, to prevent potential bugs.
19004 * To do the general case, we first find the fold of the
19005 * lowest code point (which may be higher than the lowest
19006 * one), then find everything that folds to it. (The data
19007 * structure we have only maps from the folded code points,
19008 * so we have to do the earlier step.) */
19011 U8 foldbuf[UTF8_MAXBYTES_CASE];
19012 UV folded = _to_uni_fold_flags(start[0],
19013 foldbuf, &foldlen, 0);
19014 unsigned int first_fold;
19015 const unsigned int * remaining_folds;
19016 Size_t folds_to_this_cp_count = _inverse_folds(
19020 Size_t folds_count = folds_to_this_cp_count + 1;
19021 SV * fold_list = _new_invlist(folds_count);
19024 /* If there are UTF-8 dependent matches, create a temporary
19025 * list of what this node matches, including them. */
19026 SV * all_cp_list = NULL;
19027 SV ** use_this_list = &cp_list;
19029 if (upper_latin1_only_utf8_matches) {
19030 all_cp_list = _new_invlist(0);
19031 use_this_list = &all_cp_list;
19032 _invlist_union(cp_list,
19033 upper_latin1_only_utf8_matches,
19037 /* Having gotten everything that participates in the fold
19038 * containing the lowest code point, we turn that into an
19039 * inversion list, making sure everything is included. */
19040 fold_list = add_cp_to_invlist(fold_list, start[0]);
19041 fold_list = add_cp_to_invlist(fold_list, folded);
19042 if (folds_to_this_cp_count > 0) {
19043 fold_list = add_cp_to_invlist(fold_list, first_fold);
19044 for (i = 0; i + 1 < folds_to_this_cp_count; i++) {
19045 fold_list = add_cp_to_invlist(fold_list,
19046 remaining_folds[i]);
19050 /* If the fold list is identical to what's in this ANYOF
19051 * node, the node can be represented by an EXACTFish one
19053 if (_invlistEQ(*use_this_list, fold_list,
19054 0 /* Don't complement */ )
19057 /* But, we have to be careful, as mentioned above.
19058 * Just the right sequence of characters could match
19059 * this if it is part of a multi-character fold. That
19060 * IS what we want if we are under /i. But it ISN'T
19061 * what we want if not under /i, as it could match when
19062 * it shouldn't. So, when we aren't under /i and this
19063 * character participates in a multi-char fold, we
19064 * don't optimize into an EXACTFish node. So, for each
19065 * case below we have to check if we are folding
19066 * and if not, if it is not part of a multi-char fold.
19068 if (start[0] > 255) { /* Highish code point */
19069 if (FOLD || ! _invlist_contains_cp(
19070 PL_InMultiCharFold, folded))
19074 : (ASCII_FOLD_RESTRICTED)
19079 } /* Below, the lowest code point < 256 */
19082 && DEPENDS_SEMANTICS)
19083 { /* An EXACTF node containing a single character
19084 's', can be an EXACTFU if it doesn't get
19085 joined with an adjacent 's' */
19086 op = EXACTFU_S_EDGE;
19090 || ! HAS_NONLATIN1_FOLD_CLOSURE(start[0]))
19092 if (upper_latin1_only_utf8_matches) {
19095 /* We can't use the fold, as that only matches
19099 else if ( UNLIKELY(start[0] == MICRO_SIGN)
19101 { /* EXACTFUP is a special node for this
19103 op = (ASCII_FOLD_RESTRICTED)
19106 value = MICRO_SIGN;
19108 else if ( ASCII_FOLD_RESTRICTED
19109 && ! isASCII(start[0]))
19110 { /* For ASCII under /iaa, we can use EXACTFU
19122 SvREFCNT_dec_NN(fold_list);
19123 SvREFCNT_dec(all_cp_list);
19130 /* Here, we have calculated what EXACTish node to use. Have to
19131 * convert to UTF-8 if not already there */
19134 SvREFCNT_dec(cp_list);;
19135 REQUIRE_UTF8(flagp);
19138 /* This is a kludge to the special casing issues with this
19139 * ligature under /aa. FB05 should fold to FB06, but the
19140 * call above to _to_uni_fold_flags() didn't find this, as
19141 * it didn't use the /aa restriction in order to not miss
19142 * other folds that would be affected. This is the only
19143 * instance likely to ever be a problem in all of Unicode.
19144 * So special case it. */
19145 if ( value == LATIN_SMALL_LIGATURE_LONG_S_T
19146 && ASCII_FOLD_RESTRICTED)
19148 value = LATIN_SMALL_LIGATURE_ST;
19152 len = (UTF) ? UVCHR_SKIP(value) : 1;
19154 ret = regnode_guts(pRExC_state, op, len, "exact");
19155 FILL_NODE(ret, op);
19156 RExC_emit += 1 + STR_SZ(len);
19157 setSTR_LEN(REGNODE_p(ret), len);
19159 *STRINGs(REGNODE_p(ret)) = (U8) value;
19162 uvchr_to_utf8((U8 *) STRINGs(REGNODE_p(ret)), value);
19168 if (! has_runtime_dependency) {
19170 /* See if this can be turned into an ANYOFM node. Think about the
19171 * bit patterns in two different bytes. In some positions, the
19172 * bits in each will be 1; and in other positions both will be 0;
19173 * and in some positions the bit will be 1 in one byte, and 0 in
19174 * the other. Let 'n' be the number of positions where the bits
19175 * differ. We create a mask which has exactly 'n' 0 bits, each in
19176 * a position where the two bytes differ. Now take the set of all
19177 * bytes that when ANDed with the mask yield the same result. That
19178 * set has 2**n elements, and is representable by just two 8 bit
19179 * numbers: the result and the mask. Importantly, matching the set
19180 * can be vectorized by creating a word full of the result bytes,
19181 * and a word full of the mask bytes, yielding a significant speed
19182 * up. Here, see if this node matches such a set. As a concrete
19183 * example consider [01], and the byte representing '0' which is
19184 * 0x30 on ASCII machines. It has the bits 0011 0000. Take the
19185 * mask 1111 1110. If we AND 0x31 and 0x30 with that mask we get
19186 * 0x30. Any other bytes ANDed yield something else. So [01],
19187 * which is a common usage, is optimizable into ANYOFM, and can
19188 * benefit from the speed up. We can only do this on UTF-8
19189 * invariant bytes, because they have the same bit patterns under
19191 PERL_UINT_FAST8_T inverted = 0;
19193 const PERL_UINT_FAST8_T max_permissible = 0xFF;
19195 const PERL_UINT_FAST8_T max_permissible = 0x7F;
19197 /* If doesn't fit the criteria for ANYOFM, invert and try again.
19198 * If that works we will instead later generate an NANYOFM, and
19199 * invert back when through */
19200 if (invlist_highest(cp_list) > max_permissible) {
19201 _invlist_invert(cp_list);
19205 if (invlist_highest(cp_list) <= max_permissible) {
19206 UV this_start, this_end;
19207 UV lowest_cp = UV_MAX; /* init'ed to suppress compiler warn */
19208 U8 bits_differing = 0;
19209 Size_t full_cp_count = 0;
19210 bool first_time = TRUE;
19212 /* Go through the bytes and find the bit positions that differ
19214 invlist_iterinit(cp_list);
19215 while (invlist_iternext(cp_list, &this_start, &this_end)) {
19216 unsigned int i = this_start;
19219 if (! UVCHR_IS_INVARIANT(i)) {
19223 first_time = FALSE;
19224 lowest_cp = this_start;
19226 /* We have set up the code point to compare with.
19227 * Don't compare it with itself */
19231 /* Find the bit positions that differ from the lowest code
19232 * point in the node. Keep track of all such positions by
19234 for (; i <= this_end; i++) {
19235 if (! UVCHR_IS_INVARIANT(i)) {
19239 bits_differing |= i ^ lowest_cp;
19242 full_cp_count += this_end - this_start + 1;
19245 /* At the end of the loop, we count how many bits differ from
19246 * the bits in lowest code point, call the count 'd'. If the
19247 * set we found contains 2**d elements, it is the closure of
19248 * all code points that differ only in those bit positions. To
19249 * convince yourself of that, first note that the number in the
19250 * closure must be a power of 2, which we test for. The only
19251 * way we could have that count and it be some differing set,
19252 * is if we got some code points that don't differ from the
19253 * lowest code point in any position, but do differ from each
19254 * other in some other position. That means one code point has
19255 * a 1 in that position, and another has a 0. But that would
19256 * mean that one of them differs from the lowest code point in
19257 * that position, which possibility we've already excluded. */
19258 if ( (inverted || full_cp_count > 1)
19259 && full_cp_count == 1U << PL_bitcount[bits_differing])
19263 op = ANYOFM + inverted;;
19265 /* We need to make the bits that differ be 0's */
19266 ANYOFM_mask = ~ bits_differing; /* This goes into FLAGS */
19268 /* The argument is the lowest code point */
19269 ret = reganode(pRExC_state, op, lowest_cp);
19270 FLAGS(REGNODE_p(ret)) = ANYOFM_mask;
19274 invlist_iterfinish(cp_list);
19278 _invlist_invert(cp_list);
19285 /* XXX We could create an ANYOFR_LOW node here if we saved above if
19286 * all were invariants, it wasn't inverted, and there is a single
19287 * range. This would be faster than some of the posix nodes we
19288 * create below like /\d/a, but would be twice the size. Without
19289 * having actually measured the gain, khw doesn't think the
19290 * tradeoff is really worth it */
19293 if (! (anyof_flags & ANYOF_LOCALE_FLAGS)) {
19294 PERL_UINT_FAST8_T type;
19295 SV * intersection = NULL;
19296 SV* d_invlist = NULL;
19298 /* See if this matches any of the POSIX classes. The POSIXA and
19299 * POSIXD ones are about the same speed as ANYOF ops, but take less
19300 * room; the ones that have above-Latin1 code point matches are
19301 * somewhat faster than ANYOF. */
19303 for (type = POSIXA; type >= POSIXD; type--) {
19306 if (type == POSIXL) { /* But not /l posix classes */
19310 for (posix_class = 0;
19311 posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC;
19314 SV** our_code_points = &cp_list;
19315 SV** official_code_points;
19318 if (type == POSIXA) {
19319 official_code_points = &PL_Posix_ptrs[posix_class];
19322 official_code_points = &PL_XPosix_ptrs[posix_class];
19325 /* Skip non-existent classes of this type. e.g. \v only
19326 * has an entry in PL_XPosix_ptrs */
19327 if (! *official_code_points) {
19331 /* Try both the regular class, and its inversion */
19332 for (try_inverted = 0; try_inverted < 2; try_inverted++) {
19333 bool this_inverted = invert ^ try_inverted;
19335 if (type != POSIXD) {
19337 /* This class that isn't /d can't match if we have
19338 * /d dependencies */
19339 if (has_runtime_dependency
19340 & HAS_D_RUNTIME_DEPENDENCY)
19345 else /* is /d */ if (! this_inverted) {
19347 /* /d classes don't match anything non-ASCII below
19348 * 256 unconditionally (which cp_list contains) */
19349 _invlist_intersection(cp_list, PL_UpperLatin1,
19351 if (_invlist_len(intersection) != 0) {
19355 SvREFCNT_dec(d_invlist);
19356 d_invlist = invlist_clone(cp_list, NULL);
19358 /* But under UTF-8 it turns into using /u rules.
19359 * Add the things it matches under these conditions
19360 * so that we check below that these are identical
19361 * to what the tested class should match */
19362 if (upper_latin1_only_utf8_matches) {
19365 upper_latin1_only_utf8_matches,
19368 our_code_points = &d_invlist;
19370 else { /* POSIXD, inverted. If this doesn't have this
19371 flag set, it isn't /d. */
19372 if (! (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
19376 our_code_points = &cp_list;
19379 /* Here, have weeded out some things. We want to see
19380 * if the list of characters this node contains
19381 * ('*our_code_points') precisely matches those of the
19382 * class we are currently checking against
19383 * ('*official_code_points'). */
19384 if (_invlistEQ(*our_code_points,
19385 *official_code_points,
19388 /* Here, they precisely match. Optimize this ANYOF
19389 * node into its equivalent POSIX one of the
19390 * correct type, possibly inverted */
19391 ret = reg_node(pRExC_state, (try_inverted)
19395 FLAGS(REGNODE_p(ret)) = posix_class;
19396 SvREFCNT_dec(d_invlist);
19397 SvREFCNT_dec(intersection);
19403 SvREFCNT_dec(d_invlist);
19404 SvREFCNT_dec(intersection);
19407 /* If it is a single contiguous range, ANYOFR is an efficient regnode,
19408 * both in size and speed. Currently, a 20 bit range base (smallest
19409 * code point in the range), and a 12 bit maximum delta are packed into
19410 * a 32 bit word. This allows for using it on all of the Unicode code
19411 * points except for the highest plane, which is only for private use
19412 * code points. khw doubts that a bigger delta is likely in real world
19415 && ! has_runtime_dependency
19416 && anyof_flags == 0
19417 && start[0] < (1 << ANYOFR_BASE_BITS)
19418 && end[0] - start[0]
19419 < ((1U << (sizeof(((struct regnode_1 *)NULL)->arg1)
19420 * CHARBITS - ANYOFR_BASE_BITS))))
19423 U8 low_utf8[UTF8_MAXBYTES+1];
19424 U8 high_utf8[UTF8_MAXBYTES+1];
19426 ret = reganode(pRExC_state, ANYOFR,
19427 (start[0] | (end[0] - start[0]) << ANYOFR_BASE_BITS));
19429 /* Place the lowest UTF-8 start byte in the flags field, so as to
19430 * allow efficient ruling out at run time of many possible inputs.
19432 (void) uvchr_to_utf8(low_utf8, start[0]);
19433 (void) uvchr_to_utf8(high_utf8, end[0]);
19435 /* If all code points share the same first byte, this can be an
19436 * ANYOFRb. Otherwise store the lowest UTF-8 start byte which can
19437 * quickly rule out many inputs at run-time without having to
19438 * compute the code point from UTF-8. For EBCDIC, we use I8, as
19439 * not doing that transformation would not rule out nearly so many
19441 if (low_utf8[0] == high_utf8[0]) {
19442 OP(REGNODE_p(ret)) = ANYOFRb;
19443 ANYOF_FLAGS(REGNODE_p(ret)) = low_utf8[0];
19446 ANYOF_FLAGS(REGNODE_p(ret))
19447 = NATIVE_UTF8_TO_I8(low_utf8[0]);
19453 /* If didn't find an optimization and there is no need for a bitmap,
19454 * optimize to indicate that */
19455 if ( start[0] >= NUM_ANYOF_CODE_POINTS
19457 && ! upper_latin1_only_utf8_matches
19458 && anyof_flags == 0)
19460 U8 low_utf8[UTF8_MAXBYTES+1];
19461 UV highest_cp = invlist_highest(cp_list);
19463 /* Currently the maximum allowed code point by the system is
19464 * IV_MAX. Higher ones are reserved for future internal use. This
19465 * particular regnode can be used for higher ones, but we can't
19466 * calculate the code point of those. IV_MAX suffices though, as
19467 * it will be a large first byte */
19468 Size_t low_len = uvchr_to_utf8(low_utf8, MIN(start[0], IV_MAX))
19471 /* We store the lowest possible first byte of the UTF-8
19472 * representation, using the flags field. This allows for quick
19473 * ruling out of some inputs without having to convert from UTF-8
19474 * to code point. For EBCDIC, we use I8, as not doing that
19475 * transformation would not rule out nearly so many things */
19476 anyof_flags = NATIVE_UTF8_TO_I8(low_utf8[0]);
19480 /* If the first UTF-8 start byte for the highest code point in the
19481 * range is suitably small, we may be able to get an upper bound as
19483 if (highest_cp <= IV_MAX) {
19484 U8 high_utf8[UTF8_MAXBYTES+1];
19485 Size_t high_len = uvchr_to_utf8(high_utf8, highest_cp)
19488 /* If the lowest and highest are the same, we can get an exact
19489 * first byte instead of a just minimum or even a sequence of
19490 * exact leading bytes. We signal these with different
19492 if (low_utf8[0] == high_utf8[0]) {
19493 Size_t len = find_first_differing_byte_pos(low_utf8,
19495 MIN(low_len, high_len));
19499 /* No need to convert to I8 for EBCDIC as this is an
19501 anyof_flags = low_utf8[0];
19506 ret = regnode_guts(pRExC_state, op,
19507 regarglen[op] + STR_SZ(len),
19509 FILL_NODE(ret, op);
19510 ((struct regnode_anyofhs *) REGNODE_p(ret))->str_len
19512 Copy(low_utf8, /* Add the common bytes */
19513 ((struct regnode_anyofhs *) REGNODE_p(ret))->string,
19515 RExC_emit += NODE_SZ_STR(REGNODE_p(ret));
19516 set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
19517 NULL, only_utf8_locale_list);
19521 else if (NATIVE_UTF8_TO_I8(high_utf8[0]) <= MAX_ANYOF_HRx_BYTE)
19524 /* Here, the high byte is not the same as the low, but is
19525 * small enough that its reasonable to have a loose upper
19526 * bound, which is packed in with the strict lower bound.
19527 * See comments at the definition of MAX_ANYOF_HRx_BYTE.
19528 * On EBCDIC platforms, I8 is used. On ASCII platforms I8
19529 * is the same thing as UTF-8 */
19532 U8 max_range_diff = MAX_ANYOF_HRx_BYTE - anyof_flags;
19533 U8 range_diff = NATIVE_UTF8_TO_I8(high_utf8[0])
19536 if (range_diff <= max_range_diff / 8) {
19539 else if (range_diff <= max_range_diff / 4) {
19542 else if (range_diff <= max_range_diff / 2) {
19545 anyof_flags = (anyof_flags - 0xC0) << 2 | bits;
19550 goto done_finding_op;
19552 } /* End of seeing if can optimize it into a different node */
19554 is_anyof: /* It's going to be an ANYOF node. */
19555 op = (has_runtime_dependency & HAS_D_RUNTIME_DEPENDENCY)
19565 ret = regnode_guts(pRExC_state, op, regarglen[op], "anyof");
19566 FILL_NODE(ret, op); /* We set the argument later */
19567 RExC_emit += 1 + regarglen[op];
19568 ANYOF_FLAGS(REGNODE_p(ret)) = anyof_flags;
19570 /* Here, <cp_list> contains all the code points we can determine at
19571 * compile time that match under all conditions. Go through it, and
19572 * for things that belong in the bitmap, put them there, and delete from
19573 * <cp_list>. While we are at it, see if everything above 255 is in the
19574 * list, and if so, set a flag to speed up execution */
19576 populate_ANYOF_from_invlist(REGNODE_p(ret), &cp_list);
19579 ANYOF_POSIXL_SET_TO_BITMAP(REGNODE_p(ret), posixl);
19583 ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_INVERT;
19586 /* Here, the bitmap has been populated with all the Latin1 code points that
19587 * always match. Can now add to the overall list those that match only
19588 * when the target string is UTF-8 (<upper_latin1_only_utf8_matches>).
19590 if (upper_latin1_only_utf8_matches) {
19592 _invlist_union(cp_list,
19593 upper_latin1_only_utf8_matches,
19595 SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
19598 cp_list = upper_latin1_only_utf8_matches;
19600 ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
19603 set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
19604 (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
19607 only_utf8_locale_list);
19608 SvREFCNT_dec(cp_list);;
19609 SvREFCNT_dec(only_utf8_locale_list);
19614 /* Here, the node is getting optimized into something that's not an ANYOF
19615 * one. Finish up. */
19617 Set_Node_Offset_Length(REGNODE_p(ret), orig_parse - RExC_start,
19618 RExC_parse - orig_parse);;
19619 SvREFCNT_dec(cp_list);;
19620 SvREFCNT_dec(only_utf8_locale_list);
19624 #undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
19627 S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state,
19628 regnode* const node,
19630 SV* const runtime_defns,
19631 SV* const only_utf8_locale_list)
19633 /* Sets the arg field of an ANYOF-type node 'node', using information about
19634 * the node passed-in. If there is nothing outside the node's bitmap, the
19635 * arg is set to ANYOF_ONLY_HAS_BITMAP. Otherwise, it sets the argument to
19636 * the count returned by add_data(), having allocated and stored an array,
19639 * av[0] stores the inversion list defining this class as far as known at
19640 * this time, or PL_sv_undef if nothing definite is now known.
19641 * av[1] stores the inversion list of code points that match only if the
19642 * current locale is UTF-8, or if none, PL_sv_undef if there is an
19643 * av[2], or no entry otherwise.
19644 * av[2] stores the list of user-defined properties whose subroutine
19645 * definitions aren't known at this time, or no entry if none. */
19649 PERL_ARGS_ASSERT_SET_ANYOF_ARG;
19651 if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) {
19652 assert(! (ANYOF_FLAGS(node)
19653 & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP));
19654 ARG_SET(node, ANYOF_ONLY_HAS_BITMAP);
19657 AV * const av = newAV();
19661 av_store(av, INVLIST_INDEX, SvREFCNT_inc_NN(cp_list));
19664 if (only_utf8_locale_list) {
19665 av_store(av, ONLY_LOCALE_MATCHES_INDEX,
19666 SvREFCNT_inc_NN(only_utf8_locale_list));
19669 if (runtime_defns) {
19670 av_store(av, DEFERRED_USER_DEFINED_INDEX,
19671 SvREFCNT_inc_NN(runtime_defns));
19674 rv = newRV_noinc(MUTABLE_SV(av));
19675 n = add_data(pRExC_state, STR_WITH_LEN("s"));
19676 RExC_rxi->data->data[n] = (void*)rv;
19681 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
19683 Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog,
19684 const regnode* node,
19687 SV** only_utf8_locale_ptr,
19688 SV** output_invlist)
19691 /* For internal core use only.
19692 * Returns the inversion list for the input 'node' in the regex 'prog'.
19693 * If <doinit> is 'true', will attempt to create the inversion list if not
19695 * If <listsvp> is non-null, will return the printable contents of the
19696 * property definition. This can be used to get debugging information
19697 * even before the inversion list exists, by calling this function with
19698 * 'doinit' set to false, in which case the components that will be used
19699 * to eventually create the inversion list are returned (in a printable
19701 * If <only_utf8_locale_ptr> is not NULL, it is where this routine is to
19702 * store an inversion list of code points that should match only if the
19703 * execution-time locale is a UTF-8 one.
19704 * If <output_invlist> is not NULL, it is where this routine is to store an
19705 * inversion list of the code points that would be instead returned in
19706 * <listsvp> if this were NULL. Thus, what gets output in <listsvp>
19707 * when this parameter is used, is just the non-code point data that
19708 * will go into creating the inversion list. This currently should be just
19709 * user-defined properties whose definitions were not known at compile
19710 * time. Using this parameter allows for easier manipulation of the
19711 * inversion list's data by the caller. It is illegal to call this
19712 * function with this parameter set, but not <listsvp>
19714 * Tied intimately to how S_set_ANYOF_arg sets up the data structure. Note
19715 * that, in spite of this function's name, the inversion list it returns
19716 * may include the bitmap data as well */
19718 SV *si = NULL; /* Input initialization string */
19719 SV* invlist = NULL;
19721 RXi_GET_DECL(prog, progi);
19722 const struct reg_data * const data = prog ? progi->data : NULL;
19724 PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA;
19725 assert(! output_invlist || listsvp);
19727 if (data && data->count) {
19728 const U32 n = ARG(node);
19730 if (data->what[n] == 's') {
19731 SV * const rv = MUTABLE_SV(data->data[n]);
19732 AV * const av = MUTABLE_AV(SvRV(rv));
19733 SV **const ary = AvARRAY(av);
19735 invlist = ary[INVLIST_INDEX];
19737 if (av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX) {
19738 *only_utf8_locale_ptr = ary[ONLY_LOCALE_MATCHES_INDEX];
19741 if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
19742 si = ary[DEFERRED_USER_DEFINED_INDEX];
19745 if (doinit && (si || invlist)) {
19748 SV * msg = newSVpvs_flags("", SVs_TEMP);
19750 SV * prop_definition = handle_user_defined_property(
19751 "", 0, FALSE, /* There is no \p{}, \P{} */
19752 SvPVX_const(si)[1] - '0', /* /i or not has been
19753 stored here for just
19755 TRUE, /* run time */
19756 FALSE, /* This call must find the defn */
19757 si, /* The property definition */
19760 0 /* base level call */
19764 assert(prop_definition == NULL);
19766 Perl_croak(aTHX_ "%" UTF8f,
19767 UTF8fARG(SvUTF8(msg), SvCUR(msg), SvPVX(msg)));
19771 _invlist_union(invlist, prop_definition, &invlist);
19772 SvREFCNT_dec_NN(prop_definition);
19775 invlist = prop_definition;
19778 STATIC_ASSERT_STMT(ONLY_LOCALE_MATCHES_INDEX == 1 + INVLIST_INDEX);
19779 STATIC_ASSERT_STMT(DEFERRED_USER_DEFINED_INDEX == 1 + ONLY_LOCALE_MATCHES_INDEX);
19781 ary[INVLIST_INDEX] = invlist;
19782 av_fill(av, (ary[ONLY_LOCALE_MATCHES_INDEX])
19783 ? ONLY_LOCALE_MATCHES_INDEX
19791 /* If requested, return a printable version of what this ANYOF node matches
19794 SV* matches_string = NULL;
19796 /* This function can be called at compile-time, before everything gets
19797 * resolved, in which case we return the currently best available
19798 * information, which is the string that will eventually be used to do
19799 * that resolving, 'si' */
19801 /* Here, we only have 'si' (and possibly some passed-in data in
19802 * 'invlist', which is handled below) If the caller only wants
19803 * 'si', use that. */
19804 if (! output_invlist) {
19805 matches_string = newSVsv(si);
19808 /* But if the caller wants an inversion list of the node, we
19809 * need to parse 'si' and place as much as possible in the
19810 * desired output inversion list, making 'matches_string' only
19811 * contain the currently unresolvable things */
19812 const char *si_string = SvPVX(si);
19813 STRLEN remaining = SvCUR(si);
19817 /* Ignore everything before and including the first new-line */
19818 si_string = (const char *) memchr(si_string, '\n', SvCUR(si));
19819 assert (si_string != NULL);
19821 remaining = SvPVX(si) + SvCUR(si) - si_string;
19823 while (remaining > 0) {
19825 /* The data consists of just strings defining user-defined
19826 * property names, but in prior incarnations, and perhaps
19827 * somehow from pluggable regex engines, it could still
19828 * hold hex code point definitions. Each component of a
19829 * range would be separated by a tab, and each range by a
19830 * new-line. If these are found, instead add them to the
19831 * inversion list */
19832 I32 grok_flags = PERL_SCAN_SILENT_ILLDIGIT
19833 |PERL_SCAN_SILENT_NON_PORTABLE;
19834 STRLEN len = remaining;
19835 UV cp = grok_hex(si_string, &len, &grok_flags, NULL);
19837 /* If the hex decode routine found something, it should go
19838 * up to the next \n */
19839 if ( *(si_string + len) == '\n') {
19840 if (count) { /* 2nd code point on line */
19841 *output_invlist = _add_range_to_invlist(*output_invlist, prev_cp, cp);
19844 *output_invlist = add_cp_to_invlist(*output_invlist, cp);
19847 goto prepare_for_next_iteration;
19850 /* If the hex decode was instead for the lower range limit,
19851 * save it, and go parse the upper range limit */
19852 if (*(si_string + len) == '\t') {
19853 assert(count == 0);
19857 prepare_for_next_iteration:
19858 si_string += len + 1;
19859 remaining -= len + 1;
19863 /* Here, didn't find a legal hex number. Just add the text
19864 * from here up to the next \n, omitting any trailing
19868 len = strcspn(si_string,
19869 DEFERRED_COULD_BE_OFFICIAL_MARKERs "\n");
19871 if (matches_string) {
19872 sv_catpvn(matches_string, si_string, len);
19875 matches_string = newSVpvn(si_string, len);
19877 sv_catpvs(matches_string, " ");
19881 && UCHARAT(si_string)
19882 == DEFERRED_COULD_BE_OFFICIAL_MARKERc)
19887 if (remaining && UCHARAT(si_string) == '\n') {
19891 } /* end of loop through the text */
19893 assert(matches_string);
19894 if (SvCUR(matches_string)) { /* Get rid of trailing blank */
19895 SvCUR_set(matches_string, SvCUR(matches_string) - 1);
19897 } /* end of has an 'si' */
19900 /* Add the stuff that's already known */
19903 /* Again, if the caller doesn't want the output inversion list, put
19904 * everything in 'matches-string' */
19905 if (! output_invlist) {
19906 if ( ! matches_string) {
19907 matches_string = newSVpvs("\n");
19909 sv_catsv(matches_string, invlist_contents(invlist,
19910 TRUE /* traditional style */
19913 else if (! *output_invlist) {
19914 *output_invlist = invlist_clone(invlist, NULL);
19917 _invlist_union(*output_invlist, invlist, output_invlist);
19921 *listsvp = matches_string;
19926 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
19928 /* reg_skipcomment()
19930 Absorbs an /x style # comment from the input stream,
19931 returning a pointer to the first character beyond the comment, or if the
19932 comment terminates the pattern without anything following it, this returns
19933 one past the final character of the pattern (in other words, RExC_end) and
19934 sets the REG_RUN_ON_COMMENT_SEEN flag.
19936 Note it's the callers responsibility to ensure that we are
19937 actually in /x mode
19941 PERL_STATIC_INLINE char*
19942 S_reg_skipcomment(RExC_state_t *pRExC_state, char* p)
19944 PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
19948 while (p < RExC_end) {
19949 if (*(++p) == '\n') {
19954 /* we ran off the end of the pattern without ending the comment, so we have
19955 * to add an \n when wrapping */
19956 RExC_seen |= REG_RUN_ON_COMMENT_SEEN;
19961 S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state,
19963 const bool force_to_xmod
19966 /* If the text at the current parse position '*p' is a '(?#...)' comment,
19967 * or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p'
19968 * is /x whitespace, advance '*p' so that on exit it points to the first
19969 * byte past all such white space and comments */
19971 const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED);
19973 PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT;
19975 assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p));
19978 if (RExC_end - (*p) >= 3
19980 && *(*p + 1) == '?'
19981 && *(*p + 2) == '#')
19983 while (*(*p) != ')') {
19984 if ((*p) == RExC_end)
19985 FAIL("Sequence (?#... not terminated");
19993 const char * save_p = *p;
19994 while ((*p) < RExC_end) {
19996 if ((len = is_PATWS_safe((*p), RExC_end, UTF))) {
19999 else if (*(*p) == '#') {
20000 (*p) = reg_skipcomment(pRExC_state, (*p));
20006 if (*p != save_p) {
20019 Advances the parse position by one byte, unless that byte is the beginning
20020 of a '(?#...)' style comment, or is /x whitespace and /x is in effect. In
20021 those two cases, the parse position is advanced beyond all such comments and
20024 This is the UTF, (?#...), and /x friendly way of saying RExC_parse++.
20028 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
20030 PERL_ARGS_ASSERT_NEXTCHAR;
20032 if (RExC_parse < RExC_end) {
20034 || UTF8_IS_INVARIANT(*RExC_parse)
20035 || UTF8_IS_START(*RExC_parse));
20037 RExC_parse += (UTF)
20038 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
20041 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
20042 FALSE /* Don't force /x */ );
20047 S_change_engine_size(pTHX_ RExC_state_t *pRExC_state, const Ptrdiff_t size)
20049 /* 'size' is the delta number of smallest regnode equivalents to add or
20050 * subtract from the current memory allocated to the regex engine being
20053 PERL_ARGS_ASSERT_CHANGE_ENGINE_SIZE;
20058 sizeof(regexp_internal) + (RExC_size + 1) * sizeof(regnode),
20059 /* +1 for REG_MAGIC */
20062 if ( RExC_rxi == NULL )
20063 FAIL("Regexp out of space");
20064 RXi_SET(RExC_rx, RExC_rxi);
20066 RExC_emit_start = RExC_rxi->program;
20068 Zero(REGNODE_p(RExC_emit), size, regnode);
20071 #ifdef RE_TRACK_PATTERN_OFFSETS
20072 Renew(RExC_offsets, 2*RExC_size+1, U32);
20074 Zero(RExC_offsets + 2*(RExC_size - size) + 1, 2 * size, U32);
20076 RExC_offsets[0] = RExC_size;
20080 STATIC regnode_offset
20081 S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name)
20083 /* Allocate a regnode for 'op', with 'extra_size' extra (smallest) regnode
20084 * equivalents space. It aligns and increments RExC_size
20086 * It returns the regnode's offset into the regex engine program */
20088 const regnode_offset ret = RExC_emit;
20090 GET_RE_DEBUG_FLAGS_DECL;
20092 PERL_ARGS_ASSERT_REGNODE_GUTS;
20094 SIZE_ALIGN(RExC_size);
20095 change_engine_size(pRExC_state, (Ptrdiff_t) 1 + extra_size);
20096 NODE_ALIGN_FILL(REGNODE_p(ret));
20097 #ifndef RE_TRACK_PATTERN_OFFSETS
20098 PERL_UNUSED_ARG(name);
20099 PERL_UNUSED_ARG(op);
20101 assert(extra_size >= regarglen[op] || PL_regkind[op] == ANYOF);
20103 if (RExC_offsets) { /* MJD */
20105 ("%s:%d: (op %s) %s %" UVuf " (len %" UVuf ") (max %" UVuf ").\n",
20108 (UV)(RExC_emit) > RExC_offsets[0]
20109 ? "Overwriting end of array!\n" : "OK",
20111 (UV)(RExC_parse - RExC_start),
20112 (UV)RExC_offsets[0]));
20113 Set_Node_Offset(REGNODE_p(RExC_emit), RExC_parse + (op == END));
20120 - reg_node - emit a node
20122 STATIC regnode_offset /* Location. */
20123 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
20125 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node");
20126 regnode_offset ptr = ret;
20128 PERL_ARGS_ASSERT_REG_NODE;
20130 assert(regarglen[op] == 0);
20132 FILL_ADVANCE_NODE(ptr, op);
20138 - reganode - emit a node with an argument
20140 STATIC regnode_offset /* Location. */
20141 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
20143 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode");
20144 regnode_offset ptr = ret;
20146 PERL_ARGS_ASSERT_REGANODE;
20148 /* ANYOF are special cased to allow non-length 1 args */
20149 assert(regarglen[op] == 1);
20151 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
20156 STATIC regnode_offset
20157 S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2)
20159 /* emit a node with U32 and I32 arguments */
20161 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode");
20162 regnode_offset ptr = ret;
20164 PERL_ARGS_ASSERT_REG2LANODE;
20166 assert(regarglen[op] == 2);
20168 FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2);
20174 - reginsert - insert an operator in front of already-emitted operand
20176 * That means that on exit 'operand' is the offset of the newly inserted
20177 * operator, and the original operand has been relocated.
20179 * IMPORTANT NOTE - it is the *callers* responsibility to correctly
20180 * set up NEXT_OFF() of the inserted node if needed. Something like this:
20182 * reginsert(pRExC, OPFAIL, orig_emit, depth+1);
20183 * NEXT_OFF(orig_emit) = regarglen[OPFAIL] + NODE_STEP_REGNODE;
20185 * ALSO NOTE - FLAGS(newly-inserted-operator) will be set to 0 as well.
20188 S_reginsert(pTHX_ RExC_state_t *pRExC_state, const U8 op,
20189 const regnode_offset operand, const U32 depth)
20194 const int offset = regarglen[(U8)op];
20195 const int size = NODE_STEP_REGNODE + offset;
20196 GET_RE_DEBUG_FLAGS_DECL;
20198 PERL_ARGS_ASSERT_REGINSERT;
20199 PERL_UNUSED_CONTEXT;
20200 PERL_UNUSED_ARG(depth);
20201 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
20202 DEBUG_PARSE_FMT("inst"," - %s", PL_reg_name[op]);
20203 assert(!RExC_study_started); /* I believe we should never use reginsert once we have started
20204 studying. If this is wrong then we need to adjust RExC_recurse
20205 below like we do with RExC_open_parens/RExC_close_parens. */
20206 change_engine_size(pRExC_state, (Ptrdiff_t) size);
20207 src = REGNODE_p(RExC_emit);
20209 dst = REGNODE_p(RExC_emit);
20211 /* If we are in a "count the parentheses" pass, the numbers are unreliable,
20212 * and [perl #133871] shows this can lead to problems, so skip this
20213 * realignment of parens until a later pass when they are reliable */
20214 if (! IN_PARENS_PASS && RExC_open_parens) {
20216 /*DEBUG_PARSE_FMT("inst"," - %" IVdf, (IV)RExC_npar);*/
20217 /* remember that RExC_npar is rex->nparens + 1,
20218 * iow it is 1 more than the number of parens seen in
20219 * the pattern so far. */
20220 for ( paren=0 ; paren < RExC_npar ; paren++ ) {
20221 /* note, RExC_open_parens[0] is the start of the
20222 * regex, it can't move. RExC_close_parens[0] is the end
20223 * of the regex, it *can* move. */
20224 if ( paren && RExC_open_parens[paren] >= operand ) {
20225 /*DEBUG_PARSE_FMT("open"," - %d", size);*/
20226 RExC_open_parens[paren] += size;
20228 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
20230 if ( RExC_close_parens[paren] >= operand ) {
20231 /*DEBUG_PARSE_FMT("close"," - %d", size);*/
20232 RExC_close_parens[paren] += size;
20234 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
20239 RExC_end_op += size;
20241 while (src > REGNODE_p(operand)) {
20242 StructCopy(--src, --dst, regnode);
20243 #ifdef RE_TRACK_PATTERN_OFFSETS
20244 if (RExC_offsets) { /* MJD 20010112 */
20246 ("%s(%d): (op %s) %s copy %" UVuf " -> %" UVuf " (max %" UVuf ").\n",
20250 (UV)(REGNODE_OFFSET(dst)) > RExC_offsets[0]
20251 ? "Overwriting end of array!\n" : "OK",
20252 (UV)REGNODE_OFFSET(src),
20253 (UV)REGNODE_OFFSET(dst),
20254 (UV)RExC_offsets[0]));
20255 Set_Node_Offset_To_R(REGNODE_OFFSET(dst), Node_Offset(src));
20256 Set_Node_Length_To_R(REGNODE_OFFSET(dst), Node_Length(src));
20261 place = REGNODE_p(operand); /* Op node, where operand used to be. */
20262 #ifdef RE_TRACK_PATTERN_OFFSETS
20263 if (RExC_offsets) { /* MJD */
20265 ("%s(%d): (op %s) %s %" UVuf " <- %" UVuf " (max %" UVuf ").\n",
20269 (UV)REGNODE_OFFSET(place) > RExC_offsets[0]
20270 ? "Overwriting end of array!\n" : "OK",
20271 (UV)REGNODE_OFFSET(place),
20272 (UV)(RExC_parse - RExC_start),
20273 (UV)RExC_offsets[0]));
20274 Set_Node_Offset(place, RExC_parse);
20275 Set_Node_Length(place, 1);
20278 src = NEXTOPER(place);
20280 FILL_NODE(operand, op);
20282 /* Zero out any arguments in the new node */
20283 Zero(src, offset, regnode);
20287 - regtail - set the next-pointer at the end of a node chain of p to val. If
20288 that value won't fit in the space available, instead returns FALSE.
20289 (Except asserts if we can't fit in the largest space the regex
20290 engine is designed for.)
20291 - SEE ALSO: regtail_study
20294 S_regtail(pTHX_ RExC_state_t * pRExC_state,
20295 const regnode_offset p,
20296 const regnode_offset val,
20299 regnode_offset scan;
20300 GET_RE_DEBUG_FLAGS_DECL;
20302 PERL_ARGS_ASSERT_REGTAIL;
20304 PERL_UNUSED_ARG(depth);
20307 /* Find last node. */
20308 scan = (regnode_offset) p;
20310 regnode * const temp = regnext(REGNODE_p(scan));
20312 DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
20313 regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
20314 Perl_re_printf( aTHX_ "~ %s (%d) %s %s\n",
20315 SvPV_nolen_const(RExC_mysv), scan,
20316 (temp == NULL ? "->" : ""),
20317 (temp == NULL ? PL_reg_name[OP(REGNODE_p(val))] : "")
20322 scan = REGNODE_OFFSET(temp);
20325 assert(val >= scan);
20326 if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
20327 assert((UV) (val - scan) <= U32_MAX);
20328 ARG_SET(REGNODE_p(scan), val - scan);
20331 if (val - scan > U16_MAX) {
20332 /* Populate this with something that won't loop and will likely
20333 * lead to a crash if the caller ignores the failure return, and
20334 * execution continues */
20335 NEXT_OFF(REGNODE_p(scan)) = U16_MAX;
20338 NEXT_OFF(REGNODE_p(scan)) = val - scan;
20346 - regtail_study - set the next-pointer at the end of a node chain of p to val.
20347 - Look for optimizable sequences at the same time.
20348 - currently only looks for EXACT chains.
20350 This is experimental code. The idea is to use this routine to perform
20351 in place optimizations on branches and groups as they are constructed,
20352 with the long term intention of removing optimization from study_chunk so
20353 that it is purely analytical.
20355 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
20356 to control which is which.
20358 This used to return a value that was ignored. It was a problem that it is
20359 #ifdef'd to be another function that didn't return a value. khw has changed it
20360 so both currently return a pass/fail return.
20363 /* TODO: All four parms should be const */
20366 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode_offset p,
20367 const regnode_offset val, U32 depth)
20369 regnode_offset scan;
20371 #ifdef EXPERIMENTAL_INPLACESCAN
20374 GET_RE_DEBUG_FLAGS_DECL;
20376 PERL_ARGS_ASSERT_REGTAIL_STUDY;
20379 /* Find last node. */
20383 regnode * const temp = regnext(REGNODE_p(scan));
20384 #ifdef EXPERIMENTAL_INPLACESCAN
20385 if (PL_regkind[OP(REGNODE_p(scan))] == EXACT) {
20386 bool unfolded_multi_char; /* Unexamined in this routine */
20387 if (join_exact(pRExC_state, scan, &min,
20388 &unfolded_multi_char, 1, REGNODE_p(val), depth+1))
20389 return TRUE; /* Was return EXACT */
20393 switch (OP(REGNODE_p(scan))) {
20400 case EXACTFU_S_EDGE:
20401 case EXACTFAA_NO_TRIE:
20408 if( exact == PSEUDO )
20409 exact= OP(REGNODE_p(scan));
20410 else if ( exact != OP(REGNODE_p(scan)) )
20419 DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
20420 regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
20421 Perl_re_printf( aTHX_ "~ %s (%d) -> %s\n",
20422 SvPV_nolen_const(RExC_mysv),
20424 PL_reg_name[exact]);
20428 scan = REGNODE_OFFSET(temp);
20431 DEBUG_PARSE_MSG("");
20432 regprop(RExC_rx, RExC_mysv, REGNODE_p(val), NULL, pRExC_state);
20433 Perl_re_printf( aTHX_
20434 "~ attach to %s (%" IVdf ") offset to %" IVdf "\n",
20435 SvPV_nolen_const(RExC_mysv),
20440 if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
20441 assert((UV) (val - scan) <= U32_MAX);
20442 ARG_SET(REGNODE_p(scan), val - scan);
20445 if (val - scan > U16_MAX) {
20446 /* Populate this with something that won't loop and will likely
20447 * lead to a crash if the caller ignores the failure return, and
20448 * execution continues */
20449 NEXT_OFF(REGNODE_p(scan)) = U16_MAX;
20452 NEXT_OFF(REGNODE_p(scan)) = val - scan;
20455 return TRUE; /* Was 'return exact' */
20460 S_get_ANYOFM_contents(pTHX_ const regnode * n) {
20462 /* Returns an inversion list of all the code points matched by the
20463 * ANYOFM/NANYOFM node 'n' */
20465 SV * cp_list = _new_invlist(-1);
20466 const U8 lowest = (U8) ARG(n);
20469 U8 needed = 1U << PL_bitcount[ (U8) ~ FLAGS(n)];
20471 PERL_ARGS_ASSERT_GET_ANYOFM_CONTENTS;
20473 /* Starting with the lowest code point, any code point that ANDed with the
20474 * mask yields the lowest code point is in the set */
20475 for (i = lowest; i <= 0xFF; i++) {
20476 if ((i & FLAGS(n)) == ARG(n)) {
20477 cp_list = add_cp_to_invlist(cp_list, i);
20480 /* We know how many code points (a power of two) that are in the
20481 * set. No use looking once we've got that number */
20482 if (count >= needed) break;
20486 if (OP(n) == NANYOFM) {
20487 _invlist_invert(cp_list);
20493 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
20498 S_regdump_intflags(pTHX_ const char *lead, const U32 flags)
20503 ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8);
20505 for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) {
20506 if (flags & (1<<bit)) {
20507 if (!set++ && lead)
20508 Perl_re_printf( aTHX_ "%s", lead);
20509 Perl_re_printf( aTHX_ "%s ", PL_reg_intflags_name[bit]);
20514 Perl_re_printf( aTHX_ "\n");
20516 Perl_re_printf( aTHX_ "%s[none-set]\n", lead);
20521 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
20527 ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8);
20529 for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) {
20530 if (flags & (1<<bit)) {
20531 if ((1<<bit) & RXf_PMf_CHARSET) { /* Output separately, below */
20534 if (!set++ && lead)
20535 Perl_re_printf( aTHX_ "%s", lead);
20536 Perl_re_printf( aTHX_ "%s ", PL_reg_extflags_name[bit]);
20539 if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
20540 if (!set++ && lead) {
20541 Perl_re_printf( aTHX_ "%s", lead);
20544 case REGEX_UNICODE_CHARSET:
20545 Perl_re_printf( aTHX_ "UNICODE");
20547 case REGEX_LOCALE_CHARSET:
20548 Perl_re_printf( aTHX_ "LOCALE");
20550 case REGEX_ASCII_RESTRICTED_CHARSET:
20551 Perl_re_printf( aTHX_ "ASCII-RESTRICTED");
20553 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
20554 Perl_re_printf( aTHX_ "ASCII-MORE_RESTRICTED");
20557 Perl_re_printf( aTHX_ "UNKNOWN CHARACTER SET");
20563 Perl_re_printf( aTHX_ "\n");
20565 Perl_re_printf( aTHX_ "%s[none-set]\n", lead);
20571 Perl_regdump(pTHX_ const regexp *r)
20575 SV * const sv = sv_newmortal();
20576 SV *dsv= sv_newmortal();
20577 RXi_GET_DECL(r, ri);
20578 GET_RE_DEBUG_FLAGS_DECL;
20580 PERL_ARGS_ASSERT_REGDUMP;
20582 (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
20584 /* Header fields of interest. */
20585 for (i = 0; i < 2; i++) {
20586 if (r->substrs->data[i].substr) {
20587 RE_PV_QUOTED_DECL(s, 0, dsv,
20588 SvPVX_const(r->substrs->data[i].substr),
20589 RE_SV_DUMPLEN(r->substrs->data[i].substr),
20590 PL_dump_re_max_len);
20591 Perl_re_printf( aTHX_
20592 "%s %s%s at %" IVdf "..%" UVuf " ",
20593 i ? "floating" : "anchored",
20595 RE_SV_TAIL(r->substrs->data[i].substr),
20596 (IV)r->substrs->data[i].min_offset,
20597 (UV)r->substrs->data[i].max_offset);
20599 else if (r->substrs->data[i].utf8_substr) {
20600 RE_PV_QUOTED_DECL(s, 1, dsv,
20601 SvPVX_const(r->substrs->data[i].utf8_substr),
20602 RE_SV_DUMPLEN(r->substrs->data[i].utf8_substr),
20604 Perl_re_printf( aTHX_
20605 "%s utf8 %s%s at %" IVdf "..%" UVuf " ",
20606 i ? "floating" : "anchored",
20608 RE_SV_TAIL(r->substrs->data[i].utf8_substr),
20609 (IV)r->substrs->data[i].min_offset,
20610 (UV)r->substrs->data[i].max_offset);
20614 if (r->check_substr || r->check_utf8)
20615 Perl_re_printf( aTHX_
20617 ( r->check_substr == r->substrs->data[1].substr
20618 && r->check_utf8 == r->substrs->data[1].utf8_substr
20619 ? "(checking floating" : "(checking anchored"));
20620 if (r->intflags & PREGf_NOSCAN)
20621 Perl_re_printf( aTHX_ " noscan");
20622 if (r->extflags & RXf_CHECK_ALL)
20623 Perl_re_printf( aTHX_ " isall");
20624 if (r->check_substr || r->check_utf8)
20625 Perl_re_printf( aTHX_ ") ");
20627 if (ri->regstclass) {
20628 regprop(r, sv, ri->regstclass, NULL, NULL);
20629 Perl_re_printf( aTHX_ "stclass %s ", SvPVX_const(sv));
20631 if (r->intflags & PREGf_ANCH) {
20632 Perl_re_printf( aTHX_ "anchored");
20633 if (r->intflags & PREGf_ANCH_MBOL)
20634 Perl_re_printf( aTHX_ "(MBOL)");
20635 if (r->intflags & PREGf_ANCH_SBOL)
20636 Perl_re_printf( aTHX_ "(SBOL)");
20637 if (r->intflags & PREGf_ANCH_GPOS)
20638 Perl_re_printf( aTHX_ "(GPOS)");
20639 Perl_re_printf( aTHX_ " ");
20641 if (r->intflags & PREGf_GPOS_SEEN)
20642 Perl_re_printf( aTHX_ "GPOS:%" UVuf " ", (UV)r->gofs);
20643 if (r->intflags & PREGf_SKIP)
20644 Perl_re_printf( aTHX_ "plus ");
20645 if (r->intflags & PREGf_IMPLICIT)
20646 Perl_re_printf( aTHX_ "implicit ");
20647 Perl_re_printf( aTHX_ "minlen %" IVdf " ", (IV)r->minlen);
20648 if (r->extflags & RXf_EVAL_SEEN)
20649 Perl_re_printf( aTHX_ "with eval ");
20650 Perl_re_printf( aTHX_ "\n");
20652 regdump_extflags("r->extflags: ", r->extflags);
20653 regdump_intflags("r->intflags: ", r->intflags);
20656 PERL_ARGS_ASSERT_REGDUMP;
20657 PERL_UNUSED_CONTEXT;
20658 PERL_UNUSED_ARG(r);
20659 #endif /* DEBUGGING */
20662 /* Should be synchronized with ANYOF_ #defines in regcomp.h */
20665 # if _CC_WORDCHAR != 0 || _CC_DIGIT != 1 || _CC_ALPHA != 2 \
20666 || _CC_LOWER != 3 || _CC_UPPER != 4 || _CC_PUNCT != 5 \
20667 || _CC_PRINT != 6 || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8 \
20668 || _CC_CASED != 9 || _CC_SPACE != 10 || _CC_BLANK != 11 \
20669 || _CC_XDIGIT != 12 || _CC_CNTRL != 13 || _CC_ASCII != 14 \
20670 || _CC_VERTSPACE != 15
20671 # error Need to adjust order of anyofs[]
20673 static const char * const anyofs[] = {
20710 - regprop - printable representation of opcode, with run time support
20714 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state)
20719 RXi_GET_DECL(prog, progi);
20720 GET_RE_DEBUG_FLAGS_DECL;
20722 PERL_ARGS_ASSERT_REGPROP;
20726 if (OP(o) > REGNODE_MAX) { /* regnode.type is unsigned */
20727 if (pRExC_state) { /* This gives more info, if we have it */
20728 FAIL3("panic: corrupted regexp opcode %d > %d",
20729 (int)OP(o), (int)REGNODE_MAX);
20732 Perl_croak(aTHX_ "panic: corrupted regexp opcode %d > %d",
20733 (int)OP(o), (int)REGNODE_MAX);
20736 sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
20738 k = PL_regkind[OP(o)];
20741 sv_catpvs(sv, " ");
20742 /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
20743 * is a crude hack but it may be the best for now since
20744 * we have no flag "this EXACTish node was UTF-8"
20746 pv_pretty(sv, STRING(o), STR_LEN(o), PL_dump_re_max_len,
20747 PL_colors[0], PL_colors[1],
20748 PERL_PV_ESCAPE_UNI_DETECT |
20749 PERL_PV_ESCAPE_NONASCII |
20750 PERL_PV_PRETTY_ELLIPSES |
20751 PERL_PV_PRETTY_LTGT |
20752 PERL_PV_PRETTY_NOCLEAR
20754 } else if (k == TRIE) {
20755 /* print the details of the trie in dumpuntil instead, as
20756 * progi->data isn't available here */
20757 const char op = OP(o);
20758 const U32 n = ARG(o);
20759 const reg_ac_data * const ac = IS_TRIE_AC(op) ?
20760 (reg_ac_data *)progi->data->data[n] :
20762 const reg_trie_data * const trie
20763 = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
20765 Perl_sv_catpvf(aTHX_ sv, "-%s", PL_reg_name[o->flags]);
20766 DEBUG_TRIE_COMPILE_r({
20768 sv_catpvs(sv, "(JUMP)");
20769 Perl_sv_catpvf(aTHX_ sv,
20770 "<S:%" UVuf "/%" IVdf " W:%" UVuf " L:%" UVuf "/%" UVuf " C:%" UVuf "/%" UVuf ">",
20771 (UV)trie->startstate,
20772 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
20773 (UV)trie->wordcount,
20776 (UV)TRIE_CHARCOUNT(trie),
20777 (UV)trie->uniquecharcount
20780 if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
20781 sv_catpvs(sv, "[");
20782 (void) put_charclass_bitmap_innards(sv,
20783 ((IS_ANYOF_TRIE(op))
20785 : TRIE_BITMAP(trie)),
20792 sv_catpvs(sv, "]");
20794 } else if (k == CURLY) {
20795 U32 lo = ARG1(o), hi = ARG2(o);
20796 if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
20797 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
20798 Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo);
20799 if (hi == REG_INFTY)
20800 sv_catpvs(sv, "INFTY");
20802 Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi);
20803 sv_catpvs(sv, "}");
20805 else if (k == WHILEM && o->flags) /* Ordinal/of */
20806 Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
20807 else if (k == REF || k == OPEN || k == CLOSE
20808 || k == GROUPP || OP(o)==ACCEPT)
20810 AV *name_list= NULL;
20811 U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o);
20812 Perl_sv_catpvf(aTHX_ sv, "%" UVuf, (UV)parno); /* Parenth number */
20813 if ( RXp_PAREN_NAMES(prog) ) {
20814 name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
20815 } else if ( pRExC_state ) {
20816 name_list= RExC_paren_name_list;
20819 if ( k != REF || (OP(o) < REFN)) {
20820 SV **name= av_fetch(name_list, parno, 0 );
20822 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
20825 SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]);
20826 I32 *nums=(I32*)SvPVX(sv_dat);
20827 SV **name= av_fetch(name_list, nums[0], 0 );
20830 for ( n=0; n<SvIVX(sv_dat); n++ ) {
20831 Perl_sv_catpvf(aTHX_ sv, "%s%" IVdf,
20832 (n ? "," : ""), (IV)nums[n]);
20834 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
20838 if ( k == REF && reginfo) {
20839 U32 n = ARG(o); /* which paren pair */
20840 I32 ln = prog->offs[n].start;
20841 if (prog->lastparen < n || ln == -1 || prog->offs[n].end == -1)
20842 Perl_sv_catpvf(aTHX_ sv, ": FAIL");
20843 else if (ln == prog->offs[n].end)
20844 Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING");
20846 const char *s = reginfo->strbeg + ln;
20847 Perl_sv_catpvf(aTHX_ sv, ": ");
20848 Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0,
20849 PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE );
20852 } else if (k == GOSUB) {
20853 AV *name_list= NULL;
20854 if ( RXp_PAREN_NAMES(prog) ) {
20855 name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
20856 } else if ( pRExC_state ) {
20857 name_list= RExC_paren_name_list;
20860 /* Paren and offset */
20861 Perl_sv_catpvf(aTHX_ sv, "%d[%+d:%d]", (int)ARG(o),(int)ARG2L(o),
20862 (int)((o + (int)ARG2L(o)) - progi->program) );
20864 SV **name= av_fetch(name_list, ARG(o), 0 );
20866 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
20869 else if (k == LOGICAL)
20870 /* 2: embedded, otherwise 1 */
20871 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);
20872 else if (k == ANYOF || k == ANYOFR) {
20876 bool do_sep = FALSE; /* Do we need to separate various components of
20878 /* Set if there is still an unresolved user-defined property */
20879 SV *unresolved = NULL;
20881 /* Things that are ignored except when the runtime locale is UTF-8 */
20882 SV *only_utf8_locale_invlist = NULL;
20884 /* Code points that don't fit in the bitmap */
20885 SV *nonbitmap_invlist = NULL;
20887 /* And things that aren't in the bitmap, but are small enough to be */
20888 SV* bitmap_range_not_in_bitmap = NULL;
20892 if (inRANGE(OP(o), ANYOFH, ANYOFRb)) {
20898 flags = ANYOF_FLAGS(o);
20899 bitmap = ANYOF_BITMAP(o);
20903 if (OP(o) == ANYOFL || OP(o) == ANYOFPOSIXL) {
20904 if (ANYOFL_UTF8_LOCALE_REQD(flags)) {
20905 sv_catpvs(sv, "{utf8-locale-reqd}");
20907 if (flags & ANYOFL_FOLD) {
20908 sv_catpvs(sv, "{i}");
20912 inverted = flags & ANYOF_INVERT;
20914 /* If there is stuff outside the bitmap, get it */
20915 if (arg != ANYOF_ONLY_HAS_BITMAP) {
20916 if (inRANGE(OP(o), ANYOFR, ANYOFRb)) {
20917 nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
20919 ANYOFRbase(o) + ANYOFRdelta(o));
20922 (void) _get_regclass_nonbitmap_data(prog, o, FALSE,
20924 &only_utf8_locale_invlist,
20925 &nonbitmap_invlist);
20928 /* The non-bitmap data may contain stuff that could fit in the
20929 * bitmap. This could come from a user-defined property being
20930 * finally resolved when this call was done; or much more likely
20931 * because there are matches that require UTF-8 to be valid, and so
20932 * aren't in the bitmap (or ANYOFR). This is teased apart later */
20933 _invlist_intersection(nonbitmap_invlist,
20935 &bitmap_range_not_in_bitmap);
20936 /* Leave just the things that don't fit into the bitmap */
20937 _invlist_subtract(nonbitmap_invlist,
20939 &nonbitmap_invlist);
20942 /* Obey this flag to add all above-the-bitmap code points */
20943 if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
20944 nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
20945 NUM_ANYOF_CODE_POINTS,
20949 /* Ready to start outputting. First, the initial left bracket */
20950 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
20952 /* ANYOFH by definition doesn't have anything that will fit inside the
20953 * bitmap; ANYOFR may or may not. */
20954 if ( ! inRANGE(OP(o), ANYOFH, ANYOFHr)
20955 && ( ! inRANGE(OP(o), ANYOFR, ANYOFRb)
20956 || ANYOFRbase(o) < NUM_ANYOF_CODE_POINTS))
20958 /* Then all the things that could fit in the bitmap */
20959 do_sep = put_charclass_bitmap_innards(sv,
20961 bitmap_range_not_in_bitmap,
20962 only_utf8_locale_invlist,
20966 /* Can't try inverting for a
20967 * better display if there
20968 * are things that haven't
20971 || inRANGE(OP(o), ANYOFR, ANYOFRb));
20972 SvREFCNT_dec(bitmap_range_not_in_bitmap);
20974 /* If there are user-defined properties which haven't been defined
20975 * yet, output them. If the result is not to be inverted, it is
20976 * clearest to output them in a separate [] from the bitmap range
20977 * stuff. If the result is to be complemented, we have to show
20978 * everything in one [], as the inversion applies to the whole
20979 * thing. Use {braces} to separate them from anything in the
20980 * bitmap and anything above the bitmap. */
20983 if (! do_sep) { /* If didn't output anything in the bitmap
20985 sv_catpvs(sv, "^");
20987 sv_catpvs(sv, "{");
20990 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1],
20993 sv_catsv(sv, unresolved);
20995 sv_catpvs(sv, "}");
20997 do_sep = ! inverted;
21001 /* And, finally, add the above-the-bitmap stuff */
21002 if (nonbitmap_invlist && _invlist_len(nonbitmap_invlist)) {
21005 /* See if truncation size is overridden */
21006 const STRLEN dump_len = (PL_dump_re_max_len > 256)
21007 ? PL_dump_re_max_len
21010 /* This is output in a separate [] */
21012 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]);
21015 /* And, for easy of understanding, it is shown in the
21016 * uncomplemented form if possible. The one exception being if
21017 * there are unresolved items, where the inversion has to be
21018 * delayed until runtime */
21019 if (inverted && ! unresolved) {
21020 _invlist_invert(nonbitmap_invlist);
21021 _invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist);
21024 contents = invlist_contents(nonbitmap_invlist,
21025 FALSE /* output suitable for catsv */
21028 /* If the output is shorter than the permissible maximum, just do it. */
21029 if (SvCUR(contents) <= dump_len) {
21030 sv_catsv(sv, contents);
21033 const char * contents_string = SvPVX(contents);
21034 STRLEN i = dump_len;
21036 /* Otherwise, start at the permissible max and work back to the
21037 * first break possibility */
21038 while (i > 0 && contents_string[i] != ' ') {
21041 if (i == 0) { /* Fail-safe. Use the max if we couldn't
21042 find a legal break */
21046 sv_catpvn(sv, contents_string, i);
21047 sv_catpvs(sv, "...");
21050 SvREFCNT_dec_NN(contents);
21051 SvREFCNT_dec_NN(nonbitmap_invlist);
21054 /* And finally the matching, closing ']' */
21055 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
21057 if (OP(o) == ANYOFHs) {
21058 Perl_sv_catpvf(aTHX_ sv, " (Leading UTF-8 bytes=%s", _byte_dump_string((U8 *) ((struct regnode_anyofhs *) o)->string, FLAGS(o), 1));
21060 else if (inRANGE(OP(o), ANYOFH, ANYOFRb)) {
21061 U8 lowest = (OP(o) != ANYOFHr)
21063 : LOWEST_ANYOF_HRx_BYTE(FLAGS(o));
21064 U8 highest = (OP(o) == ANYOFHr)
21065 ? HIGHEST_ANYOF_HRx_BYTE(FLAGS(o))
21066 : (OP(o) == ANYOFH || OP(o) == ANYOFR)
21069 Perl_sv_catpvf(aTHX_ sv, " (First UTF-8 byte=%02X", lowest);
21070 if (lowest != highest) {
21071 Perl_sv_catpvf(aTHX_ sv, "-%02X", highest);
21073 Perl_sv_catpvf(aTHX_ sv, ")");
21076 SvREFCNT_dec(unresolved);
21078 else if (k == ANYOFM) {
21079 SV * cp_list = get_ANYOFM_contents(o);
21081 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
21082 if (OP(o) == NANYOFM) {
21083 _invlist_invert(cp_list);
21086 put_charclass_bitmap_innards(sv, NULL, cp_list, NULL, NULL, 0, TRUE);
21087 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
21089 SvREFCNT_dec(cp_list);
21091 else if (k == POSIXD || k == NPOSIXD) {
21092 U8 index = FLAGS(o) * 2;
21093 if (index < C_ARRAY_LENGTH(anyofs)) {
21094 if (*anyofs[index] != '[') {
21095 sv_catpvs(sv, "[");
21097 sv_catpv(sv, anyofs[index]);
21098 if (*anyofs[index] != '[') {
21099 sv_catpvs(sv, "]");
21103 Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
21106 else if (k == BOUND || k == NBOUND) {
21107 /* Must be synced with order of 'bound_type' in regcomp.h */
21108 const char * const bounds[] = {
21109 "", /* Traditional */
21115 assert(FLAGS(o) < C_ARRAY_LENGTH(bounds));
21116 sv_catpv(sv, bounds[FLAGS(o)]);
21118 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH)) {
21119 Perl_sv_catpvf(aTHX_ sv, "[%d", -(o->flags));
21121 Perl_sv_catpvf(aTHX_ sv, "..-%d", o->flags - o->next_off);
21123 Perl_sv_catpvf(aTHX_ sv, "]");
21125 else if (OP(o) == SBOL)
21126 Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^");
21128 /* add on the verb argument if there is one */
21129 if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) {
21131 Perl_sv_catpvf(aTHX_ sv, ":%" SVf,
21132 SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
21134 sv_catpvs(sv, ":NULL");
21137 PERL_UNUSED_CONTEXT;
21138 PERL_UNUSED_ARG(sv);
21139 PERL_UNUSED_ARG(o);
21140 PERL_UNUSED_ARG(prog);
21141 PERL_UNUSED_ARG(reginfo);
21142 PERL_UNUSED_ARG(pRExC_state);
21143 #endif /* DEBUGGING */
21149 Perl_re_intuit_string(pTHX_ REGEXP * const r)
21150 { /* Assume that RE_INTUIT is set */
21151 struct regexp *const prog = ReANY(r);
21152 GET_RE_DEBUG_FLAGS_DECL;
21154 PERL_ARGS_ASSERT_RE_INTUIT_STRING;
21155 PERL_UNUSED_CONTEXT;
21159 const char * const s = SvPV_nolen_const(RX_UTF8(r)
21160 ? prog->check_utf8 : prog->check_substr);
21162 if (!PL_colorset) reginitcolors();
21163 Perl_re_printf( aTHX_
21164 "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
21166 RX_UTF8(r) ? "utf8 " : "",
21167 PL_colors[5], PL_colors[0],
21170 (strlen(s) > PL_dump_re_max_len ? "..." : ""));
21173 /* use UTF8 check substring if regexp pattern itself is in UTF8 */
21174 return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr;
21180 handles refcounting and freeing the perl core regexp structure. When
21181 it is necessary to actually free the structure the first thing it
21182 does is call the 'free' method of the regexp_engine associated to
21183 the regexp, allowing the handling of the void *pprivate; member
21184 first. (This routine is not overridable by extensions, which is why
21185 the extensions free is called first.)
21187 See regdupe and regdupe_internal if you change anything here.
21189 #ifndef PERL_IN_XSUB_RE
21191 Perl_pregfree(pTHX_ REGEXP *r)
21197 Perl_pregfree2(pTHX_ REGEXP *rx)
21199 struct regexp *const r = ReANY(rx);
21200 GET_RE_DEBUG_FLAGS_DECL;
21202 PERL_ARGS_ASSERT_PREGFREE2;
21207 if (r->mother_re) {
21208 ReREFCNT_dec(r->mother_re);
21210 CALLREGFREE_PVT(rx); /* free the private data */
21211 SvREFCNT_dec(RXp_PAREN_NAMES(r));
21215 for (i = 0; i < 2; i++) {
21216 SvREFCNT_dec(r->substrs->data[i].substr);
21217 SvREFCNT_dec(r->substrs->data[i].utf8_substr);
21219 Safefree(r->substrs);
21221 RX_MATCH_COPY_FREE(rx);
21222 #ifdef PERL_ANY_COW
21223 SvREFCNT_dec(r->saved_copy);
21226 SvREFCNT_dec(r->qr_anoncv);
21227 if (r->recurse_locinput)
21228 Safefree(r->recurse_locinput);
21234 Copy ssv to dsv, both of which should of type SVt_REGEXP or SVt_PVLV,
21235 except that dsv will be created if NULL.
21237 This function is used in two main ways. First to implement
21238 $r = qr/....; $s = $$r;
21240 Secondly, it is used as a hacky workaround to the structural issue of
21242 being stored in the regexp structure which is in turn stored in
21243 PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
21244 could be PL_curpm in multiple contexts, and could require multiple
21245 result sets being associated with the pattern simultaneously, such
21246 as when doing a recursive match with (??{$qr})
21248 The solution is to make a lightweight copy of the regexp structure
21249 when a qr// is returned from the code executed by (??{$qr}) this
21250 lightweight copy doesn't actually own any of its data except for
21251 the starp/end and the actual regexp structure itself.
21257 Perl_reg_temp_copy(pTHX_ REGEXP *dsv, REGEXP *ssv)
21259 struct regexp *drx;
21260 struct regexp *const srx = ReANY(ssv);
21261 const bool islv = dsv && SvTYPE(dsv) == SVt_PVLV;
21263 PERL_ARGS_ASSERT_REG_TEMP_COPY;
21266 dsv = (REGEXP*) newSV_type(SVt_REGEXP);
21268 assert(SvTYPE(dsv) == SVt_REGEXP || (SvTYPE(dsv) == SVt_PVLV));
21270 /* our only valid caller, sv_setsv_flags(), should have done
21271 * a SV_CHECK_THINKFIRST_COW_DROP() by now */
21272 assert(!SvOOK(dsv));
21273 assert(!SvIsCOW(dsv));
21274 assert(!SvROK(dsv));
21276 if (SvPVX_const(dsv)) {
21278 Safefree(SvPVX(dsv));
21283 SvOK_off((SV *)dsv);
21286 /* For PVLVs, the head (sv_any) points to an XPVLV, while
21287 * the LV's xpvlenu_rx will point to a regexp body, which
21288 * we allocate here */
21289 REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
21290 assert(!SvPVX(dsv));
21291 ((XPV*)SvANY(dsv))->xpv_len_u.xpvlenu_rx = temp->sv_any;
21292 temp->sv_any = NULL;
21293 SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
21294 SvREFCNT_dec_NN(temp);
21295 /* SvCUR still resides in the xpvlv struct, so the regexp copy-
21296 ing below will not set it. */
21297 SvCUR_set(dsv, SvCUR(ssv));
21300 /* This ensures that SvTHINKFIRST(sv) is true, and hence that
21301 sv_force_normal(sv) is called. */
21305 SvFLAGS(dsv) |= SvFLAGS(ssv) & (SVf_POK|SVp_POK|SVf_UTF8);
21306 SvPV_set(dsv, RX_WRAPPED(ssv));
21307 /* We share the same string buffer as the original regexp, on which we
21308 hold a reference count, incremented when mother_re is set below.
21309 The string pointer is copied here, being part of the regexp struct.
21311 memcpy(&(drx->xpv_cur), &(srx->xpv_cur),
21312 sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
21316 const I32 npar = srx->nparens+1;
21317 Newx(drx->offs, npar, regexp_paren_pair);
21318 Copy(srx->offs, drx->offs, npar, regexp_paren_pair);
21320 if (srx->substrs) {
21322 Newx(drx->substrs, 1, struct reg_substr_data);
21323 StructCopy(srx->substrs, drx->substrs, struct reg_substr_data);
21325 for (i = 0; i < 2; i++) {
21326 SvREFCNT_inc_void(drx->substrs->data[i].substr);
21327 SvREFCNT_inc_void(drx->substrs->data[i].utf8_substr);
21330 /* check_substr and check_utf8, if non-NULL, point to either their
21331 anchored or float namesakes, and don't hold a second reference. */
21333 RX_MATCH_COPIED_off(dsv);
21334 #ifdef PERL_ANY_COW
21335 drx->saved_copy = NULL;
21337 drx->mother_re = ReREFCNT_inc(srx->mother_re ? srx->mother_re : ssv);
21338 SvREFCNT_inc_void(drx->qr_anoncv);
21339 if (srx->recurse_locinput)
21340 Newx(drx->recurse_locinput, srx->nparens + 1, char *);
21347 /* regfree_internal()
21349 Free the private data in a regexp. This is overloadable by
21350 extensions. Perl takes care of the regexp structure in pregfree(),
21351 this covers the *pprivate pointer which technically perl doesn't
21352 know about, however of course we have to handle the
21353 regexp_internal structure when no extension is in use.
21355 Note this is called before freeing anything in the regexp
21360 Perl_regfree_internal(pTHX_ REGEXP * const rx)
21362 struct regexp *const r = ReANY(rx);
21363 RXi_GET_DECL(r, ri);
21364 GET_RE_DEBUG_FLAGS_DECL;
21366 PERL_ARGS_ASSERT_REGFREE_INTERNAL;
21376 SV *dsv= sv_newmortal();
21377 RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
21378 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), PL_dump_re_max_len);
21379 Perl_re_printf( aTHX_ "%sFreeing REx:%s %s\n",
21380 PL_colors[4], PL_colors[5], s);
21384 #ifdef RE_TRACK_PATTERN_OFFSETS
21386 Safefree(ri->u.offsets); /* 20010421 MJD */
21388 if (ri->code_blocks)
21389 S_free_codeblocks(aTHX_ ri->code_blocks);
21392 int n = ri->data->count;
21395 /* If you add a ->what type here, update the comment in regcomp.h */
21396 switch (ri->data->what[n]) {
21402 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
21405 Safefree(ri->data->data[n]);
21411 { /* Aho Corasick add-on structure for a trie node.
21412 Used in stclass optimization only */
21414 reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
21415 #ifdef USE_ITHREADS
21419 refcount = --aho->refcount;
21422 PerlMemShared_free(aho->states);
21423 PerlMemShared_free(aho->fail);
21424 /* do this last!!!! */
21425 PerlMemShared_free(ri->data->data[n]);
21426 /* we should only ever get called once, so
21427 * assert as much, and also guard the free
21428 * which /might/ happen twice. At the least
21429 * it will make code anlyzers happy and it
21430 * doesn't cost much. - Yves */
21431 assert(ri->regstclass);
21432 if (ri->regstclass) {
21433 PerlMemShared_free(ri->regstclass);
21434 ri->regstclass = 0;
21441 /* trie structure. */
21443 reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
21444 #ifdef USE_ITHREADS
21448 refcount = --trie->refcount;
21451 PerlMemShared_free(trie->charmap);
21452 PerlMemShared_free(trie->states);
21453 PerlMemShared_free(trie->trans);
21455 PerlMemShared_free(trie->bitmap);
21457 PerlMemShared_free(trie->jump);
21458 PerlMemShared_free(trie->wordinfo);
21459 /* do this last!!!! */
21460 PerlMemShared_free(ri->data->data[n]);
21465 Perl_croak(aTHX_ "panic: regfree data code '%c'",
21466 ri->data->what[n]);
21469 Safefree(ri->data->what);
21470 Safefree(ri->data);
21476 #define av_dup_inc(s, t) MUTABLE_AV(sv_dup_inc((const SV *)s, t))
21477 #define hv_dup_inc(s, t) MUTABLE_HV(sv_dup_inc((const SV *)s, t))
21478 #define SAVEPVN(p, n) ((p) ? savepvn(p, n) : NULL)
21481 re_dup_guts - duplicate a regexp.
21483 This routine is expected to clone a given regexp structure. It is only
21484 compiled under USE_ITHREADS.
21486 After all of the core data stored in struct regexp is duplicated
21487 the regexp_engine.dupe method is used to copy any private data
21488 stored in the *pprivate pointer. This allows extensions to handle
21489 any duplication it needs to do.
21491 See pregfree() and regfree_internal() if you change anything here.
21493 #if defined(USE_ITHREADS)
21494 #ifndef PERL_IN_XSUB_RE
21496 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
21500 const struct regexp *r = ReANY(sstr);
21501 struct regexp *ret = ReANY(dstr);
21503 PERL_ARGS_ASSERT_RE_DUP_GUTS;
21505 npar = r->nparens+1;
21506 Newx(ret->offs, npar, regexp_paren_pair);
21507 Copy(r->offs, ret->offs, npar, regexp_paren_pair);
21509 if (ret->substrs) {
21510 /* Do it this way to avoid reading from *r after the StructCopy().
21511 That way, if any of the sv_dup_inc()s dislodge *r from the L1
21512 cache, it doesn't matter. */
21514 const bool anchored = r->check_substr
21515 ? r->check_substr == r->substrs->data[0].substr
21516 : r->check_utf8 == r->substrs->data[0].utf8_substr;
21517 Newx(ret->substrs, 1, struct reg_substr_data);
21518 StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
21520 for (i = 0; i < 2; i++) {
21521 ret->substrs->data[i].substr =
21522 sv_dup_inc(ret->substrs->data[i].substr, param);
21523 ret->substrs->data[i].utf8_substr =
21524 sv_dup_inc(ret->substrs->data[i].utf8_substr, param);
21527 /* check_substr and check_utf8, if non-NULL, point to either their
21528 anchored or float namesakes, and don't hold a second reference. */
21530 if (ret->check_substr) {
21532 assert(r->check_utf8 == r->substrs->data[0].utf8_substr);
21534 ret->check_substr = ret->substrs->data[0].substr;
21535 ret->check_utf8 = ret->substrs->data[0].utf8_substr;
21537 assert(r->check_substr == r->substrs->data[1].substr);
21538 assert(r->check_utf8 == r->substrs->data[1].utf8_substr);
21540 ret->check_substr = ret->substrs->data[1].substr;
21541 ret->check_utf8 = ret->substrs->data[1].utf8_substr;
21543 } else if (ret->check_utf8) {
21545 ret->check_utf8 = ret->substrs->data[0].utf8_substr;
21547 ret->check_utf8 = ret->substrs->data[1].utf8_substr;
21552 RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
21553 ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
21554 if (r->recurse_locinput)
21555 Newx(ret->recurse_locinput, r->nparens + 1, char *);
21558 RXi_SET(ret, CALLREGDUPE_PVT(dstr, param));
21560 if (RX_MATCH_COPIED(dstr))
21561 ret->subbeg = SAVEPVN(ret->subbeg, ret->sublen);
21563 ret->subbeg = NULL;
21564 #ifdef PERL_ANY_COW
21565 ret->saved_copy = NULL;
21568 /* Whether mother_re be set or no, we need to copy the string. We
21569 cannot refrain from copying it when the storage points directly to
21570 our mother regexp, because that's
21571 1: a buffer in a different thread
21572 2: something we no longer hold a reference on
21573 so we need to copy it locally. */
21574 RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED_const(sstr), SvCUR(sstr)+1);
21575 /* set malloced length to a non-zero value so it will be freed
21576 * (otherwise in combination with SVf_FAKE it looks like an alien
21577 * buffer). It doesn't have to be the actual malloced size, since it
21578 * should never be grown */
21579 SvLEN_set(dstr, SvCUR(sstr)+1);
21580 ret->mother_re = NULL;
21582 #endif /* PERL_IN_XSUB_RE */
21587 This is the internal complement to regdupe() which is used to copy
21588 the structure pointed to by the *pprivate pointer in the regexp.
21589 This is the core version of the extension overridable cloning hook.
21590 The regexp structure being duplicated will be copied by perl prior
21591 to this and will be provided as the regexp *r argument, however
21592 with the /old/ structures pprivate pointer value. Thus this routine
21593 may override any copying normally done by perl.
21595 It returns a pointer to the new regexp_internal structure.
21599 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
21602 struct regexp *const r = ReANY(rx);
21603 regexp_internal *reti;
21605 RXi_GET_DECL(r, ri);
21607 PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
21611 Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode),
21612 char, regexp_internal);
21613 Copy(ri->program, reti->program, len+1, regnode);
21616 if (ri->code_blocks) {
21618 Newx(reti->code_blocks, 1, struct reg_code_blocks);
21619 Newx(reti->code_blocks->cb, ri->code_blocks->count,
21620 struct reg_code_block);
21621 Copy(ri->code_blocks->cb, reti->code_blocks->cb,
21622 ri->code_blocks->count, struct reg_code_block);
21623 for (n = 0; n < ri->code_blocks->count; n++)
21624 reti->code_blocks->cb[n].src_regex = (REGEXP*)
21625 sv_dup_inc((SV*)(ri->code_blocks->cb[n].src_regex), param);
21626 reti->code_blocks->count = ri->code_blocks->count;
21627 reti->code_blocks->refcnt = 1;
21630 reti->code_blocks = NULL;
21632 reti->regstclass = NULL;
21635 struct reg_data *d;
21636 const int count = ri->data->count;
21639 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
21640 char, struct reg_data);
21641 Newx(d->what, count, U8);
21644 for (i = 0; i < count; i++) {
21645 d->what[i] = ri->data->what[i];
21646 switch (d->what[i]) {
21647 /* see also regcomp.h and regfree_internal() */
21648 case 'a': /* actually an AV, but the dup function is identical.
21649 values seem to be "plain sv's" generally. */
21650 case 'r': /* a compiled regex (but still just another SV) */
21651 case 's': /* an RV (currently only used for an RV to an AV by the ANYOF code)
21652 this use case should go away, the code could have used
21653 'a' instead - see S_set_ANYOF_arg() for array contents. */
21654 case 'S': /* actually an SV, but the dup function is identical. */
21655 case 'u': /* actually an HV, but the dup function is identical.
21656 values are "plain sv's" */
21657 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
21660 /* Synthetic Start Class - "Fake" charclass we generate to optimize
21661 * patterns which could start with several different things. Pre-TRIE
21662 * this was more important than it is now, however this still helps
21663 * in some places, for instance /x?a+/ might produce a SSC equivalent
21664 * to [xa]. This is used by Perl_re_intuit_start() and S_find_byclass()
21667 /* This is cheating. */
21668 Newx(d->data[i], 1, regnode_ssc);
21669 StructCopy(ri->data->data[i], d->data[i], regnode_ssc);
21670 reti->regstclass = (regnode*)d->data[i];
21673 /* AHO-CORASICK fail table */
21674 /* Trie stclasses are readonly and can thus be shared
21675 * without duplication. We free the stclass in pregfree
21676 * when the corresponding reg_ac_data struct is freed.
21678 reti->regstclass= ri->regstclass;
21681 /* TRIE transition table */
21683 ((reg_trie_data*)ri->data->data[i])->refcount++;
21686 case 'l': /* (?{...}) or (??{ ... }) code (cb->block) */
21687 case 'L': /* same when RExC_pm_flags & PMf_HAS_CV and code
21688 is not from another regexp */
21689 d->data[i] = ri->data->data[i];
21692 Perl_croak(aTHX_ "panic: re_dup_guts unknown data code '%c'",
21693 ri->data->what[i]);
21702 reti->name_list_idx = ri->name_list_idx;
21704 #ifdef RE_TRACK_PATTERN_OFFSETS
21705 if (ri->u.offsets) {
21706 Newx(reti->u.offsets, 2*len+1, U32);
21707 Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
21710 SetProgLen(reti, len);
21713 return (void*)reti;
21716 #endif /* USE_ITHREADS */
21718 #ifndef PERL_IN_XSUB_RE
21721 - regnext - dig the "next" pointer out of a node
21724 Perl_regnext(pTHX_ regnode *p)
21731 if (OP(p) > REGNODE_MAX) { /* regnode.type is unsigned */
21732 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
21733 (int)OP(p), (int)REGNODE_MAX);
21736 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
21746 S_re_croak2(pTHX_ bool utf8, const char* pat1, const char* pat2,...)
21749 STRLEN l1 = strlen(pat1);
21750 STRLEN l2 = strlen(pat2);
21753 const char *message;
21755 PERL_ARGS_ASSERT_RE_CROAK2;
21761 Copy(pat1, buf, l1 , char);
21762 Copy(pat2, buf + l1, l2 , char);
21763 buf[l1 + l2] = '\n';
21764 buf[l1 + l2 + 1] = '\0';
21765 va_start(args, pat2);
21766 msv = vmess(buf, &args);
21768 message = SvPV_const(msv, l1);
21771 Copy(message, buf, l1 , char);
21772 /* l1-1 to avoid \n */
21773 Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(utf8, l1-1, buf));
21776 /* XXX Here's a total kludge. But we need to re-enter for swash routines. */
21778 #ifndef PERL_IN_XSUB_RE
21780 Perl_save_re_context(pTHX)
21785 /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
21788 const REGEXP * const rx = PM_GETRE(PL_curpm);
21790 nparens = RX_NPARENS(rx);
21793 /* RT #124109. This is a complete hack; in the SWASHNEW case we know
21794 * that PL_curpm will be null, but that utf8.pm and the modules it
21795 * loads will only use $1..$3.
21796 * The t/porting/re_context.t test file checks this assumption.
21801 for (i = 1; i <= nparens; i++) {
21802 char digits[TYPE_CHARS(long)];
21803 const STRLEN len = my_snprintf(digits, sizeof(digits),
21805 GV *const *const gvp
21806 = (GV**)hv_fetch(PL_defstash, digits, len, 0);
21809 GV * const gv = *gvp;
21810 if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
21820 S_put_code_point(pTHX_ SV *sv, UV c)
21822 PERL_ARGS_ASSERT_PUT_CODE_POINT;
21825 Perl_sv_catpvf(aTHX_ sv, "\\x{%04" UVXf "}", c);
21827 else if (isPRINT(c)) {
21828 const char string = (char) c;
21830 /* We use {phrase} as metanotation in the class, so also escape literal
21832 if (isBACKSLASHED_PUNCT(c) || c == '{' || c == '}')
21833 sv_catpvs(sv, "\\");
21834 sv_catpvn(sv, &string, 1);
21836 else if (isMNEMONIC_CNTRL(c)) {
21837 Perl_sv_catpvf(aTHX_ sv, "%s", cntrl_to_mnemonic((U8) c));
21840 Perl_sv_catpvf(aTHX_ sv, "\\x%02X", (U8) c);
21844 #define MAX_PRINT_A MAX_PRINT_A_FOR_USE_ONLY_BY_REGCOMP_DOT_C
21847 S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals)
21849 /* Appends to 'sv' a displayable version of the range of code points from
21850 * 'start' to 'end'. Mnemonics (like '\r') are used for the few controls
21851 * that have them, when they occur at the beginning or end of the range.
21852 * It uses hex to output the remaining code points, unless 'allow_literals'
21853 * is true, in which case the printable ASCII ones are output as-is (though
21854 * some of these will be escaped by put_code_point()).
21856 * NOTE: This is designed only for printing ranges of code points that fit
21857 * inside an ANYOF bitmap. Higher code points are simply suppressed
21860 const unsigned int min_range_count = 3;
21862 assert(start <= end);
21864 PERL_ARGS_ASSERT_PUT_RANGE;
21866 while (start <= end) {
21868 const char * format;
21870 if (end - start < min_range_count) {
21872 /* Output chars individually when they occur in short ranges */
21873 for (; start <= end; start++) {
21874 put_code_point(sv, start);
21879 /* If permitted by the input options, and there is a possibility that
21880 * this range contains a printable literal, look to see if there is
21882 if (allow_literals && start <= MAX_PRINT_A) {
21884 /* If the character at the beginning of the range isn't an ASCII
21885 * printable, effectively split the range into two parts:
21886 * 1) the portion before the first such printable,
21888 * and output them separately. */
21889 if (! isPRINT_A(start)) {
21890 UV temp_end = start + 1;
21892 /* There is no point looking beyond the final possible
21893 * printable, in MAX_PRINT_A */
21894 UV max = MIN(end, MAX_PRINT_A);
21896 while (temp_end <= max && ! isPRINT_A(temp_end)) {
21900 /* Here, temp_end points to one beyond the first printable if
21901 * found, or to one beyond 'max' if not. If none found, make
21902 * sure that we use the entire range */
21903 if (temp_end > MAX_PRINT_A) {
21904 temp_end = end + 1;
21907 /* Output the first part of the split range: the part that
21908 * doesn't have printables, with the parameter set to not look
21909 * for literals (otherwise we would infinitely recurse) */
21910 put_range(sv, start, temp_end - 1, FALSE);
21912 /* The 2nd part of the range (if any) starts here. */
21915 /* We do a continue, instead of dropping down, because even if
21916 * the 2nd part is non-empty, it could be so short that we want
21917 * to output it as individual characters, as tested for at the
21918 * top of this loop. */
21922 /* Here, 'start' is a printable ASCII. If it is an alphanumeric,
21923 * output a sub-range of just the digits or letters, then process
21924 * the remaining portion as usual. */
21925 if (isALPHANUMERIC_A(start)) {
21926 UV mask = (isDIGIT_A(start))
21931 UV temp_end = start + 1;
21933 /* Find the end of the sub-range that includes just the
21934 * characters in the same class as the first character in it */
21935 while (temp_end <= end && _generic_isCC_A(temp_end, mask)) {
21940 /* For short ranges, don't duplicate the code above to output
21941 * them; just call recursively */
21942 if (temp_end - start < min_range_count) {
21943 put_range(sv, start, temp_end, FALSE);
21945 else { /* Output as a range */
21946 put_code_point(sv, start);
21947 sv_catpvs(sv, "-");
21948 put_code_point(sv, temp_end);
21950 start = temp_end + 1;
21954 /* We output any other printables as individual characters */
21955 if (isPUNCT_A(start) || isSPACE_A(start)) {
21956 while (start <= end && (isPUNCT_A(start)
21957 || isSPACE_A(start)))
21959 put_code_point(sv, start);
21964 } /* End of looking for literals */
21966 /* Here is not to output as a literal. Some control characters have
21967 * mnemonic names. Split off any of those at the beginning and end of
21968 * the range to print mnemonically. It isn't possible for many of
21969 * these to be in a row, so this won't overwhelm with output */
21971 && (isMNEMONIC_CNTRL(start) || isMNEMONIC_CNTRL(end)))
21973 while (isMNEMONIC_CNTRL(start) && start <= end) {
21974 put_code_point(sv, start);
21978 /* If this didn't take care of the whole range ... */
21979 if (start <= end) {
21981 /* Look backwards from the end to find the final non-mnemonic
21984 while (isMNEMONIC_CNTRL(temp_end)) {
21988 /* And separately output the interior range that doesn't start
21989 * or end with mnemonics */
21990 put_range(sv, start, temp_end, FALSE);
21992 /* Then output the mnemonic trailing controls */
21993 start = temp_end + 1;
21994 while (start <= end) {
21995 put_code_point(sv, start);
22002 /* As a final resort, output the range or subrange as hex. */
22004 if (start >= NUM_ANYOF_CODE_POINTS) {
22007 else { /* Have to split range at the bitmap boundary */
22008 this_end = (end < NUM_ANYOF_CODE_POINTS)
22010 : NUM_ANYOF_CODE_POINTS - 1;
22012 #if NUM_ANYOF_CODE_POINTS > 256
22013 format = (this_end < 256)
22014 ? "\\x%02" UVXf "-\\x%02" UVXf
22015 : "\\x{%04" UVXf "}-\\x{%04" UVXf "}";
22017 format = "\\x%02" UVXf "-\\x%02" UVXf;
22019 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
22020 Perl_sv_catpvf(aTHX_ sv, format, start, this_end);
22021 GCC_DIAG_RESTORE_STMT;
22027 S_put_charclass_bitmap_innards_invlist(pTHX_ SV *sv, SV* invlist)
22029 /* Concatenate onto the PV in 'sv' a displayable form of the inversion list
22033 bool allow_literals = TRUE;
22035 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_INVLIST;
22037 /* Generally, it is more readable if printable characters are output as
22038 * literals, but if a range (nearly) spans all of them, it's best to output
22039 * it as a single range. This code will use a single range if all but 2
22040 * ASCII printables are in it */
22041 invlist_iterinit(invlist);
22042 while (invlist_iternext(invlist, &start, &end)) {
22044 /* If the range starts beyond the final printable, it doesn't have any
22046 if (start > MAX_PRINT_A) {
22050 /* In both ASCII and EBCDIC, a SPACE is the lowest printable. To span
22051 * all but two, the range must start and end no later than 2 from
22053 if (start < ' ' + 2 && end > MAX_PRINT_A - 2) {
22054 if (end > MAX_PRINT_A) {
22060 if (end - start >= MAX_PRINT_A - ' ' - 2) {
22061 allow_literals = FALSE;
22066 invlist_iterfinish(invlist);
22068 /* Here we have figured things out. Output each range */
22069 invlist_iterinit(invlist);
22070 while (invlist_iternext(invlist, &start, &end)) {
22071 if (start >= NUM_ANYOF_CODE_POINTS) {
22074 put_range(sv, start, end, allow_literals);
22076 invlist_iterfinish(invlist);
22082 S_put_charclass_bitmap_innards_common(pTHX_
22083 SV* invlist, /* The bitmap */
22084 SV* posixes, /* Under /l, things like [:word:], \S */
22085 SV* only_utf8, /* Under /d, matches iff the target is UTF-8 */
22086 SV* not_utf8, /* /d, matches iff the target isn't UTF-8 */
22087 SV* only_utf8_locale, /* Under /l, matches if the locale is UTF-8 */
22088 const bool invert /* Is the result to be inverted? */
22091 /* Create and return an SV containing a displayable version of the bitmap
22092 * and associated information determined by the input parameters. If the
22093 * output would have been only the inversion indicator '^', NULL is instead
22099 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_COMMON;
22102 output = newSVpvs("^");
22105 output = newSVpvs("");
22108 /* First, the code points in the bitmap that are unconditionally there */
22109 put_charclass_bitmap_innards_invlist(output, invlist);
22111 /* Traditionally, these have been placed after the main code points */
22113 sv_catsv(output, posixes);
22116 if (only_utf8 && _invlist_len(only_utf8)) {
22117 Perl_sv_catpvf(aTHX_ output, "%s{utf8}%s", PL_colors[1], PL_colors[0]);
22118 put_charclass_bitmap_innards_invlist(output, only_utf8);
22121 if (not_utf8 && _invlist_len(not_utf8)) {
22122 Perl_sv_catpvf(aTHX_ output, "%s{not utf8}%s", PL_colors[1], PL_colors[0]);
22123 put_charclass_bitmap_innards_invlist(output, not_utf8);
22126 if (only_utf8_locale && _invlist_len(only_utf8_locale)) {
22127 Perl_sv_catpvf(aTHX_ output, "%s{utf8 locale}%s", PL_colors[1], PL_colors[0]);
22128 put_charclass_bitmap_innards_invlist(output, only_utf8_locale);
22130 /* This is the only list in this routine that can legally contain code
22131 * points outside the bitmap range. The call just above to
22132 * 'put_charclass_bitmap_innards_invlist' will simply suppress them, so
22133 * output them here. There's about a half-dozen possible, and none in
22134 * contiguous ranges longer than 2 */
22135 if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
22137 SV* above_bitmap = NULL;
22139 _invlist_subtract(only_utf8_locale, PL_InBitmap, &above_bitmap);
22141 invlist_iterinit(above_bitmap);
22142 while (invlist_iternext(above_bitmap, &start, &end)) {
22145 for (i = start; i <= end; i++) {
22146 put_code_point(output, i);
22149 invlist_iterfinish(above_bitmap);
22150 SvREFCNT_dec_NN(above_bitmap);
22154 if (invert && SvCUR(output) == 1) {
22162 S_put_charclass_bitmap_innards(pTHX_ SV *sv,
22164 SV *nonbitmap_invlist,
22165 SV *only_utf8_locale_invlist,
22166 const regnode * const node,
22168 const bool force_as_is_display)
22170 /* Appends to 'sv' a displayable version of the innards of the bracketed
22171 * character class defined by the other arguments:
22172 * 'bitmap' points to the bitmap, or NULL if to ignore that.
22173 * 'nonbitmap_invlist' is an inversion list of the code points that are in
22174 * the bitmap range, but for some reason aren't in the bitmap; NULL if
22175 * none. The reasons for this could be that they require some
22176 * condition such as the target string being or not being in UTF-8
22177 * (under /d), or because they came from a user-defined property that
22178 * was not resolved at the time of the regex compilation (under /u)
22179 * 'only_utf8_locale_invlist' is an inversion list of the code points that
22180 * are valid only if the runtime locale is a UTF-8 one; NULL if none
22181 * 'node' is the regex pattern ANYOF node. It is needed only when the
22182 * above two parameters are not null, and is passed so that this
22183 * routine can tease apart the various reasons for them.
22184 * 'flags' is the flags field of 'node'
22185 * 'force_as_is_display' is TRUE if this routine should definitely NOT try
22186 * to invert things to see if that leads to a cleaner display. If
22187 * FALSE, this routine is free to use its judgment about doing this.
22189 * It returns TRUE if there was actually something output. (It may be that
22190 * the bitmap, etc is empty.)
22192 * When called for outputting the bitmap of a non-ANYOF node, just pass the
22193 * bitmap, with the succeeding parameters set to NULL, and the final one to
22197 /* In general, it tries to display the 'cleanest' representation of the
22198 * innards, choosing whether to display them inverted or not, regardless of
22199 * whether the class itself is to be inverted. However, there are some
22200 * cases where it can't try inverting, as what actually matches isn't known
22201 * until runtime, and hence the inversion isn't either. */
22204 bool inverting_allowed = ! force_as_is_display;
22207 STRLEN orig_sv_cur = SvCUR(sv);
22209 SV* invlist; /* Inversion list we accumulate of code points that
22210 are unconditionally matched */
22211 SV* only_utf8 = NULL; /* Under /d, list of matches iff the target is
22213 SV* not_utf8 = NULL; /* /d, list of matches iff the target isn't UTF-8
22215 SV* posixes = NULL; /* Under /l, string of things like [:word:], \D */
22216 SV* only_utf8_locale = NULL; /* Under /l, list of matches if the locale
22219 SV* as_is_display; /* The output string when we take the inputs
22221 SV* inverted_display; /* The output string when we invert the inputs */
22223 bool invert = cBOOL(flags & ANYOF_INVERT); /* Is the input to be inverted
22225 /* We are biased in favor of displaying things without them being inverted,
22226 * as that is generally easier to understand */
22227 const int bias = 5;
22229 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS;
22231 /* Start off with whatever code points are passed in. (We clone, so we
22232 * don't change the caller's list) */
22233 if (nonbitmap_invlist) {
22234 assert(invlist_highest(nonbitmap_invlist) < NUM_ANYOF_CODE_POINTS);
22235 invlist = invlist_clone(nonbitmap_invlist, NULL);
22237 else { /* Worst case size is every other code point is matched */
22238 invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2);
22242 if (OP(node) == ANYOFD) {
22244 /* This flag indicates that the code points below 0x100 in the
22245 * nonbitmap list are precisely the ones that match only when the
22246 * target is UTF-8 (they should all be non-ASCII). */
22247 if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
22249 _invlist_intersection(invlist, PL_UpperLatin1, &only_utf8);
22250 _invlist_subtract(invlist, only_utf8, &invlist);
22253 /* And this flag for matching all non-ASCII 0xFF and below */
22254 if (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
22256 not_utf8 = invlist_clone(PL_UpperLatin1, NULL);
22259 else if (OP(node) == ANYOFL || OP(node) == ANYOFPOSIXL) {
22261 /* If either of these flags are set, what matches isn't
22262 * determinable except during execution, so don't know enough here
22264 if (flags & (ANYOFL_FOLD|ANYOF_MATCHES_POSIXL)) {
22265 inverting_allowed = FALSE;
22268 /* What the posix classes match also varies at runtime, so these
22269 * will be output symbolically. */
22270 if (ANYOF_POSIXL_TEST_ANY_SET(node)) {
22273 posixes = newSVpvs("");
22274 for (i = 0; i < ANYOF_POSIXL_MAX; i++) {
22275 if (ANYOF_POSIXL_TEST(node, i)) {
22276 sv_catpv(posixes, anyofs[i]);
22283 /* Accumulate the bit map into the unconditional match list */
22285 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
22286 if (BITMAP_TEST(bitmap, i)) {
22289 i < NUM_ANYOF_CODE_POINTS && BITMAP_TEST(bitmap, i);
22292 invlist = _add_range_to_invlist(invlist, start, i-1);
22297 /* Make sure that the conditional match lists don't have anything in them
22298 * that match unconditionally; otherwise the output is quite confusing.
22299 * This could happen if the code that populates these misses some
22302 _invlist_subtract(only_utf8, invlist, &only_utf8);
22305 _invlist_subtract(not_utf8, invlist, ¬_utf8);
22308 if (only_utf8_locale_invlist) {
22310 /* Since this list is passed in, we have to make a copy before
22312 only_utf8_locale = invlist_clone(only_utf8_locale_invlist, NULL);
22314 _invlist_subtract(only_utf8_locale, invlist, &only_utf8_locale);
22316 /* And, it can get really weird for us to try outputting an inverted
22317 * form of this list when it has things above the bitmap, so don't even
22319 if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
22320 inverting_allowed = FALSE;
22324 /* Calculate what the output would be if we take the input as-is */
22325 as_is_display = put_charclass_bitmap_innards_common(invlist,
22332 /* If have to take the output as-is, just do that */
22333 if (! inverting_allowed) {
22334 if (as_is_display) {
22335 sv_catsv(sv, as_is_display);
22336 SvREFCNT_dec_NN(as_is_display);
22339 else { /* But otherwise, create the output again on the inverted input, and
22340 use whichever version is shorter */
22342 int inverted_bias, as_is_bias;
22344 /* We will apply our bias to whichever of the the results doesn't have
22354 inverted_bias = bias;
22357 /* Now invert each of the lists that contribute to the output,
22358 * excluding from the result things outside the possible range */
22360 /* For the unconditional inversion list, we have to add in all the
22361 * conditional code points, so that when inverted, they will be gone
22363 _invlist_union(only_utf8, invlist, &invlist);
22364 _invlist_union(not_utf8, invlist, &invlist);
22365 _invlist_union(only_utf8_locale, invlist, &invlist);
22366 _invlist_invert(invlist);
22367 _invlist_intersection(invlist, PL_InBitmap, &invlist);
22370 _invlist_invert(only_utf8);
22371 _invlist_intersection(only_utf8, PL_UpperLatin1, &only_utf8);
22373 else if (not_utf8) {
22375 /* If a code point matches iff the target string is not in UTF-8,
22376 * then complementing the result has it not match iff not in UTF-8,
22377 * which is the same thing as matching iff it is UTF-8. */
22378 only_utf8 = not_utf8;
22382 if (only_utf8_locale) {
22383 _invlist_invert(only_utf8_locale);
22384 _invlist_intersection(only_utf8_locale,
22386 &only_utf8_locale);
22389 inverted_display = put_charclass_bitmap_innards_common(
22394 only_utf8_locale, invert);
22396 /* Use the shortest representation, taking into account our bias
22397 * against showing it inverted */
22398 if ( inverted_display
22399 && ( ! as_is_display
22400 || ( SvCUR(inverted_display) + inverted_bias
22401 < SvCUR(as_is_display) + as_is_bias)))
22403 sv_catsv(sv, inverted_display);
22405 else if (as_is_display) {
22406 sv_catsv(sv, as_is_display);
22409 SvREFCNT_dec(as_is_display);
22410 SvREFCNT_dec(inverted_display);
22413 SvREFCNT_dec_NN(invlist);
22414 SvREFCNT_dec(only_utf8);
22415 SvREFCNT_dec(not_utf8);
22416 SvREFCNT_dec(posixes);
22417 SvREFCNT_dec(only_utf8_locale);
22419 return SvCUR(sv) > orig_sv_cur;
22422 #define CLEAR_OPTSTART \
22423 if (optstart) STMT_START { \
22424 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ \
22425 " (%" IVdf " nodes)\n", (IV)(node - optstart))); \
22429 #define DUMPUNTIL(b,e) \
22431 node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
22433 STATIC const regnode *
22434 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
22435 const regnode *last, const regnode *plast,
22436 SV* sv, I32 indent, U32 depth)
22438 U8 op = PSEUDO; /* Arbitrary non-END op. */
22439 const regnode *next;
22440 const regnode *optstart= NULL;
22442 RXi_GET_DECL(r, ri);
22443 GET_RE_DEBUG_FLAGS_DECL;
22445 PERL_ARGS_ASSERT_DUMPUNTIL;
22447 #ifdef DEBUG_DUMPUNTIL
22448 Perl_re_printf( aTHX_ "--- %d : %d - %d - %d\n", indent, node-start,
22449 last ? last-start : 0, plast ? plast-start : 0);
22452 if (plast && plast < last)
22455 while (PL_regkind[op] != END && (!last || node < last)) {
22457 /* While that wasn't END last time... */
22460 if (op == CLOSE || op == SRCLOSE || op == WHILEM)
22462 next = regnext((regnode *)node);
22465 if (OP(node) == OPTIMIZED) {
22466 if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
22473 regprop(r, sv, node, NULL, NULL);
22474 Perl_re_printf( aTHX_ "%4" IVdf ":%*s%s", (IV)(node - start),
22475 (int)(2*indent + 1), "", SvPVX_const(sv));
22477 if (OP(node) != OPTIMIZED) {
22478 if (next == NULL) /* Next ptr. */
22479 Perl_re_printf( aTHX_ " (0)");
22480 else if (PL_regkind[(U8)op] == BRANCH
22481 && PL_regkind[OP(next)] != BRANCH )
22482 Perl_re_printf( aTHX_ " (FAIL)");
22484 Perl_re_printf( aTHX_ " (%" IVdf ")", (IV)(next - start));
22485 Perl_re_printf( aTHX_ "\n");
22489 if (PL_regkind[(U8)op] == BRANCHJ) {
22492 const regnode *nnode = (OP(next) == LONGJMP
22493 ? regnext((regnode *)next)
22495 if (last && nnode > last)
22497 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
22500 else if (PL_regkind[(U8)op] == BRANCH) {
22502 DUMPUNTIL(NEXTOPER(node), next);
22504 else if ( PL_regkind[(U8)op] == TRIE ) {
22505 const regnode *this_trie = node;
22506 const char op = OP(node);
22507 const U32 n = ARG(node);
22508 const reg_ac_data * const ac = op>=AHOCORASICK ?
22509 (reg_ac_data *)ri->data->data[n] :
22511 const reg_trie_data * const trie =
22512 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
22514 AV *const trie_words
22515 = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
22517 const regnode *nextbranch= NULL;
22520 for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
22521 SV ** const elem_ptr = av_fetch(trie_words, word_idx, 0);
22523 Perl_re_indentf( aTHX_ "%s ",
22526 ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr),
22527 SvCUR(*elem_ptr), PL_dump_re_max_len,
22528 PL_colors[0], PL_colors[1],
22530 ? PERL_PV_ESCAPE_UNI
22532 | PERL_PV_PRETTY_ELLIPSES
22533 | PERL_PV_PRETTY_LTGT
22538 U16 dist= trie->jump[word_idx+1];
22539 Perl_re_printf( aTHX_ "(%" UVuf ")\n",
22540 (UV)((dist ? this_trie + dist : next) - start));
22543 nextbranch= this_trie + trie->jump[0];
22544 DUMPUNTIL(this_trie + dist, nextbranch);
22546 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
22547 nextbranch= regnext((regnode *)nextbranch);
22549 Perl_re_printf( aTHX_ "\n");
22552 if (last && next > last)
22557 else if ( op == CURLY ) { /* "next" might be very big: optimizer */
22558 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
22559 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
22561 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
22563 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
22565 else if ( op == PLUS || op == STAR) {
22566 DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
22568 else if (PL_regkind[(U8)op] == EXACT || op == ANYOFHs) {
22569 /* Literal string, where present. */
22570 node += NODE_SZ_STR(node) - 1;
22571 node = NEXTOPER(node);
22574 node = NEXTOPER(node);
22575 node += regarglen[(U8)op];
22577 if (op == CURLYX || op == OPEN || op == SROPEN)
22581 #ifdef DEBUG_DUMPUNTIL
22582 Perl_re_printf( aTHX_ "--- %d\n", (int)indent);
22587 #endif /* DEBUGGING */
22589 #ifndef PERL_IN_XSUB_RE
22591 #include "uni_keywords.h"
22594 Perl_init_uniprops(pTHX)
22599 char * dump_len_string;
22601 dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN");
22602 if ( ! dump_len_string
22603 || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL))
22605 PL_dump_re_max_len = 60; /* A reasonable default */
22609 PL_user_def_props = newHV();
22611 #ifdef USE_ITHREADS
22613 HvSHAREKEYS_off(PL_user_def_props);
22614 PL_user_def_props_aTHX = aTHX;
22618 /* Set up the inversion list interpreter-level variables */
22620 PL_XPosix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
22621 PL_XPosix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALNUM]);
22622 PL_XPosix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALPHA]);
22623 PL_XPosix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXBLANK]);
22624 PL_XPosix_ptrs[_CC_CASED] = _new_invlist_C_array(uni_prop_ptrs[UNI_CASED]);
22625 PL_XPosix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXCNTRL]);
22626 PL_XPosix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXDIGIT]);
22627 PL_XPosix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXGRAPH]);
22628 PL_XPosix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXLOWER]);
22629 PL_XPosix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPRINT]);
22630 PL_XPosix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPUNCT]);
22631 PL_XPosix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXSPACE]);
22632 PL_XPosix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXUPPER]);
22633 PL_XPosix_ptrs[_CC_VERTSPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_VERTSPACE]);
22634 PL_XPosix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXWORD]);
22635 PL_XPosix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXXDIGIT]);
22637 PL_Posix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
22638 PL_Posix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALNUM]);
22639 PL_Posix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALPHA]);
22640 PL_Posix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXBLANK]);
22641 PL_Posix_ptrs[_CC_CASED] = PL_Posix_ptrs[_CC_ALPHA];
22642 PL_Posix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXCNTRL]);
22643 PL_Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXDIGIT]);
22644 PL_Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXGRAPH]);
22645 PL_Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXLOWER]);
22646 PL_Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPRINT]);
22647 PL_Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPUNCT]);
22648 PL_Posix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXSPACE]);
22649 PL_Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXUPPER]);
22650 PL_Posix_ptrs[_CC_VERTSPACE] = NULL;
22651 PL_Posix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXWORD]);
22652 PL_Posix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXXDIGIT]);
22654 PL_GCB_invlist = _new_invlist_C_array(_Perl_GCB_invlist);
22655 PL_SB_invlist = _new_invlist_C_array(_Perl_SB_invlist);
22656 PL_WB_invlist = _new_invlist_C_array(_Perl_WB_invlist);
22657 PL_LB_invlist = _new_invlist_C_array(_Perl_LB_invlist);
22658 PL_SCX_invlist = _new_invlist_C_array(_Perl_SCX_invlist);
22660 PL_InBitmap = _new_invlist_C_array(InBitmap_invlist);
22661 PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
22662 PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
22663 PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist);
22665 PL_Assigned_invlist = _new_invlist_C_array(uni_prop_ptrs[UNI_ASSIGNED]);
22667 PL_utf8_perl_idstart = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDSTART]);
22668 PL_utf8_perl_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDCONT]);
22670 PL_utf8_charname_begin = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_BEGIN]);
22671 PL_utf8_charname_continue = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_CONTINUE]);
22673 PL_in_some_fold = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_ANY_FOLDS]);
22674 PL_HasMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
22675 UNI__PERL_FOLDS_TO_MULTI_CHAR]);
22676 PL_InMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
22677 UNI__PERL_IS_IN_MULTI_CHAR_FOLD]);
22678 PL_utf8_toupper = _new_invlist_C_array(Uppercase_Mapping_invlist);
22679 PL_utf8_tolower = _new_invlist_C_array(Lowercase_Mapping_invlist);
22680 PL_utf8_totitle = _new_invlist_C_array(Titlecase_Mapping_invlist);
22681 PL_utf8_tofold = _new_invlist_C_array(Case_Folding_invlist);
22682 PL_utf8_tosimplefold = _new_invlist_C_array(Simple_Case_Folding_invlist);
22683 PL_utf8_foldclosures = _new_invlist_C_array(_Perl_IVCF_invlist);
22684 PL_utf8_mark = _new_invlist_C_array(uni_prop_ptrs[UNI_M]);
22685 PL_CCC_non0_non230 = _new_invlist_C_array(_Perl_CCC_non0_non230_invlist);
22686 PL_Private_Use = _new_invlist_C_array(uni_prop_ptrs[UNI_CO]);
22689 /* The below are used only by deprecated functions. They could be removed */
22690 PL_utf8_xidcont = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDC]);
22691 PL_utf8_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI_IDC]);
22692 PL_utf8_xidstart = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDS]);
22698 This code was mainly added for backcompat to give a warning for non-portable
22699 code points in user-defined properties. But experiments showed that the
22700 warning in earlier perls were only omitted on overflow, which should be an
22701 error, so there really isnt a backcompat issue, and actually adding the
22702 warning when none was present before might cause breakage, for little gain. So
22703 khw left this code in, but not enabled. Tests were never added.
22706 Ei |const char *|get_extended_utf8_msg|const UV cp
22708 PERL_STATIC_INLINE const char *
22709 S_get_extended_utf8_msg(pTHX_ const UV cp)
22711 U8 dummy[UTF8_MAXBYTES + 1];
22715 uvchr_to_utf8_flags_msgs(dummy, cp, UNICODE_WARN_PERL_EXTENDED,
22718 msg = hv_fetchs(msgs, "text", 0);
22721 (void) sv_2mortal((SV *) msgs);
22723 return SvPVX(*msg);
22729 Perl_handle_user_defined_property(pTHX_
22731 /* Parses the contents of a user-defined property definition; returning the
22732 * expanded definition if possible. If so, the return is an inversion
22735 * If there are subroutines that are part of the expansion and which aren't
22736 * known at the time of the call to this function, this returns what
22737 * parse_uniprop_string() returned for the first one encountered.
22739 * If an error was found, NULL is returned, and 'msg' gets a suitable
22740 * message appended to it. (Appending allows the back trace of how we got
22741 * to the faulty definition to be displayed through nested calls of
22742 * user-defined subs.)
22744 * The caller IS responsible for freeing any returned SV.
22746 * The syntax of the contents is pretty much described in perlunicode.pod,
22747 * but we also allow comments on each line */
22749 const char * name, /* Name of property */
22750 const STRLEN name_len, /* The name's length in bytes */
22751 const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */
22752 const bool to_fold, /* ? Is this under /i */
22753 const bool runtime, /* ? Are we in compile- or run-time */
22754 const bool deferrable, /* Is it ok for this property's full definition
22755 to be deferred until later? */
22756 SV* contents, /* The property's definition */
22757 bool *user_defined_ptr, /* This will be set TRUE as we wouldn't be
22758 getting called unless this is thought to be
22759 a user-defined property */
22760 SV * msg, /* Any error or warning msg(s) are appended to
22762 const STRLEN level) /* Recursion level of this call */
22765 const char * string = SvPV_const(contents, len);
22766 const char * const e = string + len;
22767 const bool is_contents_utf8 = cBOOL(SvUTF8(contents));
22768 const STRLEN msgs_length_on_entry = SvCUR(msg);
22770 const char * s0 = string; /* Points to first byte in the current line
22771 being parsed in 'string' */
22772 const char overflow_msg[] = "Code point too large in \"";
22773 SV* running_definition = NULL;
22775 PERL_ARGS_ASSERT_HANDLE_USER_DEFINED_PROPERTY;
22777 *user_defined_ptr = TRUE;
22779 /* Look at each line */
22781 const char * s; /* Current byte */
22782 char op = '+'; /* Default operation is 'union' */
22783 IV min = 0; /* range begin code point */
22784 IV max = -1; /* and range end */
22785 SV* this_definition;
22787 /* Skip comment lines */
22789 s0 = strchr(s0, '\n');
22797 /* For backcompat, allow an empty first line */
22803 /* First character in the line may optionally be the operation */
22812 /* If the line is one or two hex digits separated by blank space, its
22813 * a range; otherwise it is either another user-defined property or an
22818 if (! isXDIGIT(*s)) {
22819 goto check_if_property;
22822 do { /* Each new hex digit will add 4 bits. */
22823 if (min > ( (IV) MAX_LEGAL_CP >> 4)) {
22824 s = strchr(s, '\n');
22828 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22829 sv_catpv(msg, overflow_msg);
22830 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
22831 UTF8fARG(is_contents_utf8, s - s0, s0));
22832 sv_catpvs(msg, "\"");
22833 goto return_failure;
22836 /* Accumulate this digit into the value */
22837 min = (min << 4) + READ_XDIGIT(s);
22838 } while (isXDIGIT(*s));
22840 while (isBLANK(*s)) { s++; }
22842 /* We allow comments at the end of the line */
22844 s = strchr(s, '\n');
22850 else if (s < e && *s != '\n') {
22851 if (! isXDIGIT(*s)) {
22852 goto check_if_property;
22855 /* Look for the high point of the range */
22858 if (max > ( (IV) MAX_LEGAL_CP >> 4)) {
22859 s = strchr(s, '\n');
22863 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22864 sv_catpv(msg, overflow_msg);
22865 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
22866 UTF8fARG(is_contents_utf8, s - s0, s0));
22867 sv_catpvs(msg, "\"");
22868 goto return_failure;
22871 max = (max << 4) + READ_XDIGIT(s);
22872 } while (isXDIGIT(*s));
22874 while (isBLANK(*s)) { s++; }
22877 s = strchr(s, '\n');
22882 else if (s < e && *s != '\n') {
22883 goto check_if_property;
22887 if (max == -1) { /* The line only had one entry */
22890 else if (max < min) {
22891 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22892 sv_catpvs(msg, "Illegal range in \"");
22893 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
22894 UTF8fARG(is_contents_utf8, s - s0, s0));
22895 sv_catpvs(msg, "\"");
22896 goto return_failure;
22899 #if 0 /* See explanation at definition above of get_extended_utf8_msg() */
22901 if ( UNICODE_IS_PERL_EXTENDED(min)
22902 || UNICODE_IS_PERL_EXTENDED(max))
22904 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22906 /* If both code points are non-portable, warn only on the lower
22908 sv_catpv(msg, get_extended_utf8_msg(
22909 (UNICODE_IS_PERL_EXTENDED(min))
22911 sv_catpvs(msg, " in \"");
22912 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
22913 UTF8fARG(is_contents_utf8, s - s0, s0));
22914 sv_catpvs(msg, "\"");
22919 /* Here, this line contains a legal range */
22920 this_definition = sv_2mortal(_new_invlist(2));
22921 this_definition = _add_range_to_invlist(this_definition, min, max);
22926 /* Here it isn't a legal range line. See if it is a legal property
22927 * line. First find the end of the meat of the line */
22928 s = strpbrk(s, "#\n");
22933 /* Ignore trailing blanks in keeping with the requirements of
22934 * parse_uniprop_string() */
22936 while (s > s0 && isBLANK_A(*s)) {
22941 this_definition = parse_uniprop_string(s0, s - s0,
22942 is_utf8, to_fold, runtime,
22944 user_defined_ptr, msg,
22946 ? level /* Don't increase level
22947 if input is empty */
22950 if (this_definition == NULL) {
22951 goto return_failure; /* 'msg' should have had the reason
22952 appended to it by the above call */
22955 if (! is_invlist(this_definition)) { /* Unknown at this time */
22956 return newSVsv(this_definition);
22960 s = strchr(s, '\n');
22970 _invlist_union(running_definition, this_definition,
22971 &running_definition);
22974 _invlist_subtract(running_definition, this_definition,
22975 &running_definition);
22978 _invlist_intersection(running_definition, this_definition,
22979 &running_definition);
22982 _invlist_union_complement_2nd(running_definition,
22983 this_definition, &running_definition);
22986 Perl_croak(aTHX_ "panic: %s: %d: Unexpected operation %d",
22987 __FILE__, __LINE__, op);
22991 /* Position past the '\n' */
22993 } /* End of loop through the lines of 'contents' */
22995 /* Here, we processed all the lines in 'contents' without error. If we
22996 * didn't add any warnings, simply return success */
22997 if (msgs_length_on_entry == SvCUR(msg)) {
22999 /* If the expansion was empty, the answer isn't nothing: its an empty
23000 * inversion list */
23001 if (running_definition == NULL) {
23002 running_definition = _new_invlist(1);
23005 return running_definition;
23008 /* Otherwise, add some explanatory text, but we will return success */
23012 running_definition = NULL;
23016 if (name_len > 0) {
23017 sv_catpvs(msg, " in expansion of ");
23018 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
23021 return running_definition;
23024 /* As explained below, certain operations need to take place in the first
23025 * thread created. These macros switch contexts */
23026 #ifdef USE_ITHREADS
23027 # define DECLARATION_FOR_GLOBAL_CONTEXT \
23028 PerlInterpreter * save_aTHX = aTHX;
23029 # define SWITCH_TO_GLOBAL_CONTEXT \
23030 PERL_SET_CONTEXT((aTHX = PL_user_def_props_aTHX))
23031 # define RESTORE_CONTEXT PERL_SET_CONTEXT((aTHX = save_aTHX));
23032 # define CUR_CONTEXT aTHX
23033 # define ORIGINAL_CONTEXT save_aTHX
23035 # define DECLARATION_FOR_GLOBAL_CONTEXT
23036 # define SWITCH_TO_GLOBAL_CONTEXT NOOP
23037 # define RESTORE_CONTEXT NOOP
23038 # define CUR_CONTEXT NULL
23039 # define ORIGINAL_CONTEXT NULL
23043 S_delete_recursion_entry(pTHX_ void *key)
23045 /* Deletes the entry used to detect recursion when expanding user-defined
23046 * properties. This is a function so it can be set up to be called even if
23047 * the program unexpectedly quits */
23050 SV ** current_entry;
23051 const STRLEN key_len = strlen((const char *) key);
23052 DECLARATION_FOR_GLOBAL_CONTEXT;
23054 SWITCH_TO_GLOBAL_CONTEXT;
23056 /* If the entry is one of these types, it is a permanent entry, and not the
23057 * one used to detect recursions. This function should delete only the
23058 * recursion entry */
23059 current_entry = hv_fetch(PL_user_def_props, (const char *) key, key_len, 0);
23061 && ! is_invlist(*current_entry)
23062 && ! SvPOK(*current_entry))
23064 (void) hv_delete(PL_user_def_props, (const char *) key, key_len,
23072 S_get_fq_name(pTHX_
23073 const char * const name, /* The first non-blank in the \p{}, \P{} */
23074 const Size_t name_len, /* Its length in bytes, not including any trailing space */
23075 const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */
23076 const bool has_colon_colon
23079 /* Returns a mortal SV containing the fully qualified version of the input
23084 fq_name = newSVpvs_flags("", SVs_TEMP);
23086 /* Use the current package if it wasn't included in our input */
23087 if (! has_colon_colon) {
23088 const HV * pkg = (IN_PERL_COMPILETIME)
23090 : CopSTASH(PL_curcop);
23091 const char* pkgname = HvNAME(pkg);
23093 Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f,
23094 UTF8fARG(is_utf8, strlen(pkgname), pkgname));
23095 sv_catpvs(fq_name, "::");
23098 Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f,
23099 UTF8fARG(is_utf8, name_len, name));
23104 Perl_parse_uniprop_string(pTHX_
23106 /* Parse the interior of a \p{}, \P{}. Returns its definition if knowable
23107 * now. If so, the return is an inversion list.
23109 * If the property is user-defined, it is a subroutine, which in turn
23110 * may call other subroutines. This function will call the whole nest of
23111 * them to get the definition they return; if some aren't known at the time
23112 * of the call to this function, the fully qualified name of the highest
23113 * level sub is returned. It is an error to call this function at runtime
23114 * without every sub defined.
23116 * If an error was found, NULL is returned, and 'msg' gets a suitable
23117 * message appended to it. (Appending allows the back trace of how we got
23118 * to the faulty definition to be displayed through nested calls of
23119 * user-defined subs.)
23121 * The caller should NOT try to free any returned inversion list.
23123 * Other parameters will be set on return as described below */
23125 const char * const name, /* The first non-blank in the \p{}, \P{} */
23126 Size_t name_len, /* Its length in bytes, not including any
23128 const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */
23129 const bool to_fold, /* ? Is this under /i */
23130 const bool runtime, /* TRUE if this is being called at run time */
23131 const bool deferrable, /* TRUE if it's ok for the definition to not be
23132 known at this call */
23133 bool *user_defined_ptr, /* Upon return from this function it will be
23134 set to TRUE if any component is a
23135 user-defined property */
23136 SV * msg, /* Any error or warning msg(s) are appended to
23138 const STRLEN level) /* Recursion level of this call */
23141 char* lookup_name; /* normalized name for lookup in our tables */
23142 unsigned lookup_len; /* Its length */
23143 bool stricter = FALSE; /* Some properties have stricter name
23144 normalization rules, which we decide upon
23145 based on parsing */
23147 /* nv= or numeric_value=, or possibly one of the cjk numeric properties
23148 * (though it requires extra effort to download them from Unicode and
23149 * compile perl to know about them) */
23150 bool is_nv_type = FALSE;
23152 unsigned int i, j = 0;
23153 int equals_pos = -1; /* Where the '=' is found, or negative if none */
23154 int slash_pos = -1; /* Where the '/' is found, or negative if none */
23155 int table_index = 0; /* The entry number for this property in the table
23156 of all Unicode property names */
23157 bool starts_with_Is = FALSE; /* ? Does the name start with 'Is' */
23158 Size_t lookup_offset = 0; /* Used to ignore the first few characters of
23159 the normalized name in certain situations */
23160 Size_t non_pkg_begin = 0; /* Offset of first byte in 'name' that isn't
23161 part of a package name */
23162 Size_t lun_non_pkg_begin = 0; /* Similarly for 'lookup_name' */
23163 bool could_be_user_defined = TRUE; /* ? Could this be a user-defined
23164 property rather than a Unicode
23166 SV * prop_definition = NULL; /* The returned definition of 'name' or NULL
23167 if an error. If it is an inversion list,
23168 it is the definition. Otherwise it is a
23169 string containing the fully qualified sub
23171 SV * fq_name = NULL; /* For user-defined properties, the fully
23173 bool invert_return = FALSE; /* ? Do we need to complement the result before
23175 bool stripped_utf8_pkg = FALSE; /* Set TRUE if the input includes an
23176 explicit utf8:: package that we strip
23178 /* The expansion of properties that could be either user-defined or
23179 * official unicode ones is deferred until runtime, including a marker for
23180 * those that might be in the latter category. This boolean indicates if
23181 * we've seen that marker. If not, what we're parsing can't be such an
23182 * official Unicode property whose expansion was deferred */
23183 bool could_be_deferred_official = FALSE;
23185 PERL_ARGS_ASSERT_PARSE_UNIPROP_STRING;
23187 /* The input will be normalized into 'lookup_name' */
23188 Newx(lookup_name, name_len, char);
23189 SAVEFREEPV(lookup_name);
23191 /* Parse the input. */
23192 for (i = 0; i < name_len; i++) {
23193 char cur = name[i];
23195 /* Most of the characters in the input will be of this ilk, being parts
23197 if (isIDCONT_A(cur)) {
23199 /* Case differences are ignored. Our lookup routine assumes
23200 * everything is lowercase, so normalize to that */
23201 if (isUPPER_A(cur)) {
23202 lookup_name[j++] = toLOWER_A(cur);
23206 if (cur == '_') { /* Don't include these in the normalized name */
23210 lookup_name[j++] = cur;
23212 /* The first character in a user-defined name must be of this type.
23214 if (i - non_pkg_begin == 0 && ! isIDFIRST_A(cur)) {
23215 could_be_user_defined = FALSE;
23221 /* Here, the character is not something typically in a name, But these
23222 * two types of characters (and the '_' above) can be freely ignored in
23223 * most situations. Later it may turn out we shouldn't have ignored
23224 * them, and we have to reparse, but we don't have enough information
23225 * yet to make that decision */
23226 if (cur == '-' || isSPACE_A(cur)) {
23227 could_be_user_defined = FALSE;
23231 /* An equals sign or single colon mark the end of the first part of
23232 * the property name */
23234 || (cur == ':' && (i >= name_len - 1 || name[i+1] != ':')))
23236 lookup_name[j++] = '='; /* Treat the colon as an '=' */
23237 equals_pos = j; /* Note where it occurred in the input */
23238 could_be_user_defined = FALSE;
23242 /* If this looks like it is a marker we inserted at compile time,
23243 * set a flag and otherwise ignore it. If it isn't in the final
23244 * position, keep it as it would have been user input. */
23245 if ( UNLIKELY(cur == DEFERRED_COULD_BE_OFFICIAL_MARKERc)
23247 && could_be_user_defined
23248 && i == name_len - 1)
23251 could_be_deferred_official = TRUE;
23255 /* Otherwise, this character is part of the name. */
23256 lookup_name[j++] = cur;
23258 /* Here it isn't a single colon, so if it is a colon, it must be a
23262 /* A double colon should be a package qualifier. We note its
23263 * position and continue. Note that one could have
23264 * pkg1::pkg2::...::foo
23265 * so that the position at the end of the loop will be just after
23266 * the final qualifier */
23269 non_pkg_begin = i + 1;
23270 lookup_name[j++] = ':';
23271 lun_non_pkg_begin = j;
23273 else { /* Only word chars (and '::') can be in a user-defined name */
23274 could_be_user_defined = FALSE;
23276 } /* End of parsing through the lhs of the property name (or all of it if
23279 #define STRLENs(s) (sizeof("" s "") - 1)
23281 /* If there is a single package name 'utf8::', it is ambiguous. It could
23282 * be for a user-defined property, or it could be a Unicode property, as
23283 * all of them are considered to be for that package. For the purposes of
23284 * parsing the rest of the property, strip it off */
23285 if (non_pkg_begin == STRLENs("utf8::") && memBEGINPs(name, name_len, "utf8::")) {
23286 lookup_name += STRLENs("utf8::");
23287 j -= STRLENs("utf8::");
23288 equals_pos -= STRLENs("utf8::");
23289 stripped_utf8_pkg = TRUE;
23292 /* Here, we are either done with the whole property name, if it was simple;
23293 * or are positioned just after the '=' if it is compound. */
23295 if (equals_pos >= 0) {
23296 assert(! stricter); /* We shouldn't have set this yet */
23298 /* Space immediately after the '=' is ignored */
23300 for (; i < name_len; i++) {
23301 if (! isSPACE_A(name[i])) {
23306 /* Most punctuation after the equals indicates a subpattern, like
23308 if ( isPUNCT_A(name[i])
23313 /* A backslash means the real delimitter is the next character,
23314 * but it must be punctuation */
23315 && (name[i] != '\\' || (i < name_len && isPUNCT_A(name[i+1]))))
23317 /* Find the property. The table includes the equals sign, so we
23319 table_index = match_uniprop((U8 *) lookup_name, j);
23321 const char * const * prop_values
23322 = UNI_prop_value_ptrs[table_index];
23324 Size_t subpattern_len;
23325 REGEXP * subpattern_re;
23326 char open = name[i++];
23328 const char * pos_in_brackets;
23331 /* Backslash => delimitter is the character following. We
23332 * already checked that it is punctuation */
23333 if (open == '\\') {
23338 /* This data structure is constructed so that the matching
23339 * closing bracket is 3 past its matching opening. The second
23340 * set of closing is so that if the opening is something like
23341 * ']', the closing will be that as well. Something similar is
23342 * done in toke.c */
23343 pos_in_brackets = memCHRs("([<)]>)]>", open);
23344 close = (pos_in_brackets) ? pos_in_brackets[3] : open;
23347 || name[name_len-1] != close
23348 || (escaped && name[name_len-2] != '\\')
23349 /* Also make sure that there are enough characters.
23350 * e.g., '\\\' would show up incorrectly as legal even
23351 * though it is too short */
23352 || (SSize_t) (name_len - i - 1 - escaped) < 0)
23354 sv_catpvs(msg, "Unicode property wildcard not terminated");
23355 goto append_name_to_msg;
23358 Perl_ck_warner_d(aTHX_
23359 packWARN(WARN_EXPERIMENTAL__UNIPROP_WILDCARDS),
23360 "The Unicode property wildcards feature is experimental");
23362 /* Now create and compile the wildcard subpattern. Use /iaa
23363 * because nothing outside of ASCII will match, and it the
23364 * property values should all match /i. Note that when the
23365 * pattern fails to compile, our added text to the user's
23366 * pattern will be displayed to the user, which is not so
23368 subpattern_len = name_len - i - 1 - escaped;
23369 subpattern = Perl_newSVpvf(aTHX_ "(?iaa:%.*s)",
23370 (unsigned) subpattern_len,
23372 subpattern = sv_2mortal(subpattern);
23373 subpattern_re = re_compile(subpattern, 0);
23374 assert(subpattern_re); /* Should have died if didn't compile
23377 /* For each legal property value, see if the supplied pattern
23379 while (*prop_values) {
23380 const char * const entry = *prop_values;
23381 const Size_t len = strlen(entry);
23382 SV* entry_sv = newSVpvn_flags(entry, len, SVs_TEMP);
23384 if (pregexec(subpattern_re,
23386 (char *) entry + len,
23390 { /* Here, matched. Add to the returned list */
23391 Size_t total_len = j + len;
23392 SV * sub_invlist = NULL;
23393 char * this_string;
23395 /* We know this is a legal \p{property=value}. Call
23396 * the function to return the list of code points that
23398 Newxz(this_string, total_len + 1, char);
23399 Copy(lookup_name, this_string, j, char);
23400 my_strlcat(this_string, entry, total_len + 1);
23401 SAVEFREEPV(this_string);
23402 sub_invlist = parse_uniprop_string(this_string,
23411 _invlist_union(prop_definition, sub_invlist,
23415 prop_values++; /* Next iteration, look at next propvalue */
23416 } /* End of looking through property values; (the data
23417 structure is terminated by a NULL ptr) */
23419 SvREFCNT_dec_NN(subpattern_re);
23421 if (prop_definition) {
23422 return prop_definition;
23425 sv_catpvs(msg, "No Unicode property value wildcard matches:");
23426 goto append_name_to_msg;
23429 /* Here's how khw thinks we should proceed to handle the properties
23430 * not yet done: Bidi Mirroring Glyph
23431 Bidi Paired Bracket
23432 Case Folding (both full and simple)
23433 Decomposition Mapping
23434 Equivalent Unified Ideograph
23437 Lowercase Mapping (both full and simple)
23439 Titlecase Mapping (both full and simple)
23440 Uppercase Mapping (both full and simple)
23441 * Move the part that looks at the property values into a perl
23442 * script, like utf8_heavy.pl was done. This makes things somewhat
23443 * easier, but most importantly, it avoids always adding all these
23444 * strings to the memory usage when the feature is little-used.
23446 * The property values would all be concatenated into a single
23447 * string per property with each value on a separate line, and the
23448 * code point it's for on alternating lines. Then we match the
23449 * user's input pattern m//mg, without having to worry about their
23450 * uses of '^' and '$'. Only the values that aren't the default
23451 * would be in the strings. Code points would be in UTF-8. The
23452 * search pattern that we would construct would look like
23453 * (?: \n (code-point_re) \n (?aam: user-re ) \n )
23454 * And so $1 would contain the code point that matched the user-re.
23455 * For properties where the default is the code point itself, such
23456 * as any of the case changing mappings, the string would otherwise
23457 * consist of all Unicode code points in UTF-8 strung together.
23458 * This would be impractical. So instead, examine their compiled
23459 * pattern, looking at the ssc. If none, reject the pattern as an
23460 * error. Otherwise run the pattern against every code point in
23461 * the ssc. The ssc is kind of like tr18's 3.9 Possible Match Sets
23462 * And it might be good to create an API to return the ssc.
23464 * For the name properties, a new function could be created in
23465 * charnames which essentially does the same thing as above,
23466 * sharing Name.pl with the other charname functions. Don't know
23467 * about loose name matching, or algorithmically determined names.
23468 * Decomposition.pl similarly.
23470 * It might be that a new pattern modifier would have to be
23471 * created, like /t for resTricTed, which changed the behavior of
23472 * some constructs in their subpattern, like \A. */
23473 } /* End of is a wildcard subppattern */
23476 /* Certain properties whose values are numeric need special handling.
23477 * They may optionally be prefixed by 'is'. Ignore that prefix for the
23478 * purposes of checking if this is one of those properties */
23479 if (memBEGINPs(lookup_name, j, "is")) {
23483 /* Then check if it is one of these specially-handled properties. The
23484 * possibilities are hard-coded because easier this way, and the list
23485 * is unlikely to change.
23487 * All numeric value type properties are of this ilk, and are also
23488 * special in a different way later on. So find those first. There
23489 * are several numeric value type properties in the Unihan DB (which is
23490 * unlikely to be compiled with perl, but we handle it here in case it
23491 * does get compiled). They all end with 'numeric'. The interiors
23492 * aren't checked for the precise property. This would stop working if
23493 * a cjk property were to be created that ended with 'numeric' and
23494 * wasn't a numeric type */
23495 is_nv_type = memEQs(lookup_name + lookup_offset,
23496 j - 1 - lookup_offset, "numericvalue")
23497 || memEQs(lookup_name + lookup_offset,
23498 j - 1 - lookup_offset, "nv")
23499 || ( memENDPs(lookup_name + lookup_offset,
23500 j - 1 - lookup_offset, "numeric")
23501 && ( memBEGINPs(lookup_name + lookup_offset,
23502 j - 1 - lookup_offset, "cjk")
23503 || memBEGINPs(lookup_name + lookup_offset,
23504 j - 1 - lookup_offset, "k")));
23506 || memEQs(lookup_name + lookup_offset,
23507 j - 1 - lookup_offset, "canonicalcombiningclass")
23508 || memEQs(lookup_name + lookup_offset,
23509 j - 1 - lookup_offset, "ccc")
23510 || memEQs(lookup_name + lookup_offset,
23511 j - 1 - lookup_offset, "age")
23512 || memEQs(lookup_name + lookup_offset,
23513 j - 1 - lookup_offset, "in")
23514 || memEQs(lookup_name + lookup_offset,
23515 j - 1 - lookup_offset, "presentin"))
23519 /* Since the stuff after the '=' is a number, we can't throw away
23520 * '-' willy-nilly, as those could be a minus sign. Other stricter
23521 * rules also apply. However, these properties all can have the
23522 * rhs not be a number, in which case they contain at least one
23523 * alphabetic. In those cases, the stricter rules don't apply.
23524 * But the numeric type properties can have the alphas [Ee] to
23525 * signify an exponent, and it is still a number with stricter
23526 * rules. So look for an alpha that signifies not-strict */
23528 for (k = i; k < name_len; k++) {
23529 if ( isALPHA_A(name[k])
23530 && (! is_nv_type || ! isALPHA_FOLD_EQ(name[k], 'E')))
23540 /* A number may have a leading '+' or '-'. The latter is retained
23542 if (name[i] == '+') {
23545 else if (name[i] == '-') {
23546 lookup_name[j++] = '-';
23550 /* Skip leading zeros including single underscores separating the
23551 * zeros, or between the final leading zero and the first other
23553 for (; i < name_len - 1; i++) {
23554 if ( name[i] != '0'
23555 && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
23562 else { /* No '=' */
23564 /* Only a few properties without an '=' should be parsed with stricter
23565 * rules. The list is unlikely to change. */
23566 if ( memBEGINPs(lookup_name, j, "perl")
23567 && memNEs(lookup_name + 4, j - 4, "space")
23568 && memNEs(lookup_name + 4, j - 4, "word"))
23572 /* We set the inputs back to 0 and the code below will reparse,
23578 /* Here, we have either finished the property, or are positioned to parse
23579 * the remainder, and we know if stricter rules apply. Finish out, if not
23581 for (; i < name_len; i++) {
23582 char cur = name[i];
23584 /* In all instances, case differences are ignored, and we normalize to
23586 if (isUPPER_A(cur)) {
23587 lookup_name[j++] = toLOWER(cur);
23591 /* An underscore is skipped, but not under strict rules unless it
23592 * separates two digits */
23595 && ( i == 0 || (int) i == equals_pos || i == name_len- 1
23596 || ! isDIGIT_A(name[i-1]) || ! isDIGIT_A(name[i+1])))
23598 lookup_name[j++] = '_';
23603 /* Hyphens are skipped except under strict */
23604 if (cur == '-' && ! stricter) {
23608 /* XXX Bug in documentation. It says white space skipped adjacent to
23609 * non-word char. Maybe we should, but shouldn't skip it next to a dot
23611 if (isSPACE_A(cur) && ! stricter) {
23615 lookup_name[j++] = cur;
23617 /* Unless this is a non-trailing slash, we are done with it */
23618 if (i >= name_len - 1 || cur != '/') {
23624 /* A slash in the 'numeric value' property indicates that what follows
23625 * is a denominator. It can have a leading '+' and '0's that should be
23626 * skipped. But we have never allowed a negative denominator, so treat
23627 * a minus like every other character. (No need to rule out a second
23628 * '/', as that won't match anything anyway */
23631 if (i < name_len && name[i] == '+') {
23635 /* Skip leading zeros including underscores separating digits */
23636 for (; i < name_len - 1; i++) {
23637 if ( name[i] != '0'
23638 && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
23644 /* Store the first real character in the denominator */
23645 if (i < name_len) {
23646 lookup_name[j++] = name[i];
23651 /* Here are completely done parsing the input 'name', and 'lookup_name'
23652 * contains a copy, normalized.
23654 * This special case is grandfathered in: 'L_' and 'GC=L_' are accepted and
23655 * different from without the underscores. */
23656 if ( ( UNLIKELY(memEQs(lookup_name, j, "l"))
23657 || UNLIKELY(memEQs(lookup_name, j, "gc=l")))
23658 && UNLIKELY(name[name_len-1] == '_'))
23660 lookup_name[j++] = '&';
23663 /* If the original input began with 'In' or 'Is', it could be a subroutine
23664 * call to a user-defined property instead of a Unicode property name. */
23665 if ( name_len - non_pkg_begin > 2
23666 && name[non_pkg_begin+0] == 'I'
23667 && (name[non_pkg_begin+1] == 'n' || name[non_pkg_begin+1] == 's'))
23669 /* Names that start with In have different characterstics than those
23670 * that start with Is */
23671 if (name[non_pkg_begin+1] == 's') {
23672 starts_with_Is = TRUE;
23676 could_be_user_defined = FALSE;
23679 if (could_be_user_defined) {
23682 /* If the user defined property returns the empty string, it could
23683 * easily be because the pattern is being compiled before the data it
23684 * actually needs to compile is available. This could be argued to be
23685 * a bug in the perl code, but this is a change of behavior for Perl,
23686 * so we handle it. This means that intentionally returning nothing
23687 * will not be resolved until runtime */
23688 bool empty_return = FALSE;
23690 /* Here, the name could be for a user defined property, which are
23691 * implemented as subs. */
23692 user_sub = get_cvn_flags(name, name_len, 0);
23695 /* Here, the property name could be a user-defined one, but there
23696 * is no subroutine to handle it (as of now). Defer handling it
23697 * until runtime. Otherwise, a block defined by Unicode in a later
23698 * release would get the synonym InFoo added for it, and existing
23699 * code that used that name would suddenly break if it referred to
23700 * the property before the sub was declared. See [perl #134146] */
23702 goto definition_deferred;
23705 /* Here, we are at runtime, and didn't find the user property. It
23706 * could be an official property, but only if no package was
23707 * specified, or just the utf8:: package. */
23708 if (could_be_deferred_official) {
23709 lookup_name += lun_non_pkg_begin;
23710 j -= lun_non_pkg_begin;
23712 else if (! stripped_utf8_pkg) {
23713 goto unknown_user_defined;
23716 /* Drop down to look up in the official properties */
23719 const char insecure[] = "Insecure user-defined property";
23721 /* Here, there is a sub by the correct name. Normally we call it
23722 * to get the property definition */
23724 SV * user_sub_sv = MUTABLE_SV(user_sub);
23725 SV * error; /* Any error returned by calling 'user_sub' */
23726 SV * key; /* The key into the hash of user defined sub names
23729 SV ** saved_user_prop_ptr; /* Hash entry for this property */
23731 /* How many times to retry when another thread is in the middle of
23732 * expanding the same definition we want */
23733 PERL_INT_FAST8_T retry_countdown = 10;
23735 DECLARATION_FOR_GLOBAL_CONTEXT;
23737 /* If we get here, we know this property is user-defined */
23738 *user_defined_ptr = TRUE;
23740 /* We refuse to call a potentially tainted subroutine; returning an
23743 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23744 sv_catpvn(msg, insecure, sizeof(insecure) - 1);
23745 goto append_name_to_msg;
23748 /* In principal, we only call each subroutine property definition
23749 * once during the life of the program. This guarantees that the
23750 * property definition never changes. The results of the single
23751 * sub call are stored in a hash, which is used instead for future
23752 * references to this property. The property definition is thus
23753 * immutable. But, to allow the user to have a /i-dependent
23754 * definition, we call the sub once for non-/i, and once for /i,
23755 * should the need arise, passing the /i status as a parameter.
23757 * We start by constructing the hash key name, consisting of the
23758 * fully qualified subroutine name, preceded by the /i status, so
23759 * that there is a key for /i and a different key for non-/i */
23760 key = newSVpvn(((to_fold) ? "1" : "0"), 1);
23761 fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8,
23762 non_pkg_begin != 0);
23763 sv_catsv(key, fq_name);
23766 /* We only call the sub once throughout the life of the program
23767 * (with the /i, non-/i exception noted above). That means the
23768 * hash must be global and accessible to all threads. It is
23769 * created at program start-up, before any threads are created, so
23770 * is accessible to all children. But this creates some
23773 * 1) The keys can't be shared, or else problems arise; sharing is
23774 * turned off at hash creation time
23775 * 2) All SVs in it are there for the remainder of the life of the
23776 * program, and must be created in the same interpreter context
23777 * as the hash, or else they will be freed from the wrong pool
23778 * at global destruction time. This is handled by switching to
23779 * the hash's context to create each SV going into it, and then
23780 * immediately switching back
23781 * 3) All accesses to the hash must be controlled by a mutex, to
23782 * prevent two threads from getting an unstable state should
23783 * they simultaneously be accessing it. The code below is
23784 * crafted so that the mutex is locked whenever there is an
23785 * access and unlocked only when the next stable state is
23788 * The hash stores either the definition of the property if it was
23789 * valid, or, if invalid, the error message that was raised. We
23790 * use the type of SV to distinguish.
23792 * There's also the need to guard against the definition expansion
23793 * from infinitely recursing. This is handled by storing the aTHX
23794 * of the expanding thread during the expansion. Again the SV type
23795 * is used to distinguish this from the other two cases. If we
23796 * come to here and the hash entry for this property is our aTHX,
23797 * it means we have recursed, and the code assumes that we would
23798 * infinitely recurse, so instead stops and raises an error.
23799 * (Any recursion has always been treated as infinite recursion in
23802 * If instead, the entry is for a different aTHX, it means that
23803 * that thread has gotten here first, and hasn't finished expanding
23804 * the definition yet. We just have to wait until it is done. We
23805 * sleep and retry a few times, returning an error if the other
23806 * thread doesn't complete. */
23809 USER_PROP_MUTEX_LOCK;
23811 /* If we have an entry for this key, the subroutine has already
23812 * been called once with this /i status. */
23813 saved_user_prop_ptr = hv_fetch(PL_user_def_props,
23814 SvPVX(key), SvCUR(key), 0);
23815 if (saved_user_prop_ptr) {
23817 /* If the saved result is an inversion list, it is the valid
23818 * definition of this property */
23819 if (is_invlist(*saved_user_prop_ptr)) {
23820 prop_definition = *saved_user_prop_ptr;
23822 /* The SV in the hash won't be removed until global
23823 * destruction, so it is stable and we can unlock */
23824 USER_PROP_MUTEX_UNLOCK;
23826 /* The caller shouldn't try to free this SV */
23827 return prop_definition;
23830 /* Otherwise, if it is a string, it is the error message
23831 * that was returned when we first tried to evaluate this
23832 * property. Fail, and append the message */
23833 if (SvPOK(*saved_user_prop_ptr)) {
23834 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23835 sv_catsv(msg, *saved_user_prop_ptr);
23837 /* The SV in the hash won't be removed until global
23838 * destruction, so it is stable and we can unlock */
23839 USER_PROP_MUTEX_UNLOCK;
23844 assert(SvIOK(*saved_user_prop_ptr));
23846 /* Here, we have an unstable entry in the hash. Either another
23847 * thread is in the middle of expanding the property's
23848 * definition, or we are ourselves recursing. We use the aTHX
23849 * in it to distinguish */
23850 if (SvIV(*saved_user_prop_ptr) != PTR2IV(CUR_CONTEXT)) {
23852 /* Here, it's another thread doing the expanding. We've
23853 * looked as much as we are going to at the contents of the
23854 * hash entry. It's safe to unlock. */
23855 USER_PROP_MUTEX_UNLOCK;
23857 /* Retry a few times */
23858 if (retry_countdown-- > 0) {
23863 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23864 sv_catpvs(msg, "Timeout waiting for another thread to "
23866 goto append_name_to_msg;
23869 /* Here, we are recursing; don't dig any deeper */
23870 USER_PROP_MUTEX_UNLOCK;
23872 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23874 "Infinite recursion in user-defined property");
23875 goto append_name_to_msg;
23878 /* Here, this thread has exclusive control, and there is no entry
23879 * for this property in the hash. So we have the go ahead to
23880 * expand the definition ourselves. */
23882 PUSHSTACKi(PERLSI_MAGIC);
23885 /* Create a temporary placeholder in the hash to detect recursion
23887 SWITCH_TO_GLOBAL_CONTEXT;
23888 placeholder= newSVuv(PTR2IV(ORIGINAL_CONTEXT));
23889 (void) hv_store_ent(PL_user_def_props, key, placeholder, 0);
23892 /* Now that we have a placeholder, we can let other threads
23894 USER_PROP_MUTEX_UNLOCK;
23896 /* Make sure the placeholder always gets destroyed */
23897 SAVEDESTRUCTOR_X(S_delete_recursion_entry, SvPVX(key));
23902 /* Call the user's function, with the /i status as a parameter.
23903 * Note that we have gone to a lot of trouble to keep this call
23904 * from being within the locked mutex region. */
23905 XPUSHs(boolSV(to_fold));
23908 /* The following block was taken from swash_init(). Presumably
23909 * they apply to here as well, though we no longer use a swash --
23913 /* We might get here via a subroutine signature which uses a utf8
23914 * parameter name, at which point PL_subname will have been set
23915 * but not yet used. */
23916 save_item(PL_subname);
23918 (void) call_sv(user_sub_sv, G_EVAL|G_SCALAR);
23923 if (TAINT_get || SvTRUE(error)) {
23924 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23925 if (SvTRUE(error)) {
23926 sv_catpvs(msg, "Error \"");
23927 sv_catsv(msg, error);
23928 sv_catpvs(msg, "\"");
23931 if (SvTRUE(error)) sv_catpvs(msg, "; ");
23932 sv_catpvn(msg, insecure, sizeof(insecure) - 1);
23935 if (name_len > 0) {
23936 sv_catpvs(msg, " in expansion of ");
23937 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8,
23943 prop_definition = NULL;
23945 else { /* G_SCALAR guarantees a single return value */
23946 SV * contents = POPs;
23948 /* The contents is supposed to be the expansion of the property
23949 * definition. If the definition is deferrable, and we got an
23950 * empty string back, set a flag to later defer it (after clean
23953 && (! SvPOK(contents) || SvCUR(contents) == 0))
23955 empty_return = TRUE;
23957 else { /* Otherwise, call a function to check for valid syntax,
23960 prop_definition = handle_user_defined_property(
23962 is_utf8, to_fold, runtime,
23964 contents, user_defined_ptr,
23970 /* Here, we have the results of the expansion. Delete the
23971 * placeholder, and if the definition is now known, replace it with
23972 * that definition. We need exclusive access to the hash, and we
23973 * can't let anyone else in, between when we delete the placeholder
23974 * and add the permanent entry */
23975 USER_PROP_MUTEX_LOCK;
23977 S_delete_recursion_entry(aTHX_ SvPVX(key));
23979 if ( ! empty_return
23980 && (! prop_definition || is_invlist(prop_definition)))
23982 /* If we got success we use the inversion list defining the
23983 * property; otherwise use the error message */
23984 SWITCH_TO_GLOBAL_CONTEXT;
23985 (void) hv_store_ent(PL_user_def_props,
23988 ? newSVsv(prop_definition)
23994 /* All done, and the hash now has a permanent entry for this
23995 * property. Give up exclusive control */
23996 USER_PROP_MUTEX_UNLOCK;
24002 if (empty_return) {
24003 goto definition_deferred;
24006 if (prop_definition) {
24008 /* If the definition is for something not known at this time,
24009 * we toss it, and go return the main property name, as that's
24010 * the one the user will be aware of */
24011 if (! is_invlist(prop_definition)) {
24012 SvREFCNT_dec_NN(prop_definition);
24013 goto definition_deferred;
24016 sv_2mortal(prop_definition);
24020 return prop_definition;
24022 } /* End of calling the subroutine for the user-defined property */
24023 } /* End of it could be a user-defined property */
24025 /* Here it wasn't a user-defined property that is known at this time. See
24026 * if it is a Unicode property */
24028 lookup_len = j; /* This is a more mnemonic name than 'j' */
24030 /* Get the index into our pointer table of the inversion list corresponding
24031 * to the property */
24032 table_index = match_uniprop((U8 *) lookup_name, lookup_len);
24034 /* If it didn't find the property ... */
24035 if (table_index == 0) {
24037 /* Try again stripping off any initial 'Is'. This is because we
24038 * promise that an initial Is is optional. The same isn't true of
24039 * names that start with 'In'. Those can match only blocks, and the
24040 * lookup table already has those accounted for. */
24041 if (starts_with_Is) {
24047 table_index = match_uniprop((U8 *) lookup_name, lookup_len);
24050 if (table_index == 0) {
24053 /* Here, we didn't find it. If not a numeric type property, and
24054 * can't be a user-defined one, it isn't a legal property */
24055 if (! is_nv_type) {
24056 if (! could_be_user_defined) {
24060 /* Here, the property name is legal as a user-defined one. At
24061 * compile time, it might just be that the subroutine for that
24062 * property hasn't been encountered yet, but at runtime, it's
24063 * an error to try to use an undefined one */
24064 if (! deferrable) {
24065 goto unknown_user_defined;;
24068 goto definition_deferred;
24069 } /* End of isn't a numeric type property */
24071 /* The numeric type properties need more work to decide. What we
24072 * do is make sure we have the number in canonical form and look
24075 if (slash_pos < 0) { /* No slash */
24077 /* When it isn't a rational, take the input, convert it to a
24078 * NV, then create a canonical string representation of that
24082 SSize_t value_len = lookup_len - equals_pos;
24084 /* Get the value */
24085 if ( value_len <= 0
24086 || my_atof3(lookup_name + equals_pos, &value,
24088 != lookup_name + lookup_len)
24093 /* If the value is an integer, the canonical value is integral
24095 if (Perl_ceil(value) == value) {
24096 canonical = Perl_form(aTHX_ "%.*s%.0" NVff,
24097 equals_pos, lookup_name, value);
24099 else { /* Otherwise, it is %e with a known precision */
24102 canonical = Perl_form(aTHX_ "%.*s%.*" NVef,
24103 equals_pos, lookup_name,
24104 PL_E_FORMAT_PRECISION, value);
24106 /* The exponent generated is expecting two digits, whereas
24107 * %e on some systems will generate three. Remove leading
24108 * zeros in excess of 2 from the exponent. We start
24109 * looking for them after the '=' */
24110 exp_ptr = strchr(canonical + equals_pos, 'e');
24112 char * cur_ptr = exp_ptr + 2; /* past the 'e[+-]' */
24113 SSize_t excess_exponent_len = strlen(cur_ptr) - 2;
24115 assert(*(cur_ptr - 1) == '-' || *(cur_ptr - 1) == '+');
24117 if (excess_exponent_len > 0) {
24118 SSize_t leading_zeros = strspn(cur_ptr, "0");
24119 SSize_t excess_leading_zeros
24120 = MIN(leading_zeros, excess_exponent_len);
24121 if (excess_leading_zeros > 0) {
24122 Move(cur_ptr + excess_leading_zeros,
24124 strlen(cur_ptr) - excess_leading_zeros
24125 + 1, /* Copy the NUL as well */
24132 else { /* Has a slash. Create a rational in canonical form */
24133 UV numerator, denominator, gcd, trial;
24134 const char * end_ptr;
24135 const char * sign = "";
24137 /* We can't just find the numerator, denominator, and do the
24138 * division, then use the method above, because that is
24139 * inexact. And the input could be a rational that is within
24140 * epsilon (given our precision) of a valid rational, and would
24141 * then incorrectly compare valid.
24143 * We're only interested in the part after the '=' */
24144 const char * this_lookup_name = lookup_name + equals_pos;
24145 lookup_len -= equals_pos;
24146 slash_pos -= equals_pos;
24148 /* Handle any leading minus */
24149 if (this_lookup_name[0] == '-') {
24151 this_lookup_name++;
24156 /* Convert the numerator to numeric */
24157 end_ptr = this_lookup_name + slash_pos;
24158 if (! grok_atoUV(this_lookup_name, &numerator, &end_ptr)) {
24162 /* It better have included all characters before the slash */
24163 if (*end_ptr != '/') {
24167 /* Set to look at just the denominator */
24168 this_lookup_name += slash_pos;
24169 lookup_len -= slash_pos;
24170 end_ptr = this_lookup_name + lookup_len;
24172 /* Convert the denominator to numeric */
24173 if (! grok_atoUV(this_lookup_name, &denominator, &end_ptr)) {
24177 /* It better be the rest of the characters, and don't divide by
24179 if ( end_ptr != this_lookup_name + lookup_len
24180 || denominator == 0)
24185 /* Get the greatest common denominator using
24186 http://en.wikipedia.org/wiki/Euclidean_algorithm */
24188 trial = denominator;
24189 while (trial != 0) {
24191 trial = gcd % trial;
24195 /* If already in lowest possible terms, we have already tried
24196 * looking this up */
24201 /* Reduce the rational, which should put it in canonical form
24204 denominator /= gcd;
24206 canonical = Perl_form(aTHX_ "%.*s%s%" UVuf "/%" UVuf,
24207 equals_pos, lookup_name, sign, numerator, denominator);
24210 /* Here, we have the number in canonical form. Try that */
24211 table_index = match_uniprop((U8 *) canonical, strlen(canonical));
24212 if (table_index == 0) {
24215 } /* End of still didn't find the property in our table */
24216 } /* End of didn't find the property in our table */
24218 /* Here, we have a non-zero return, which is an index into a table of ptrs.
24219 * A negative return signifies that the real index is the absolute value,
24220 * but the result needs to be inverted */
24221 if (table_index < 0) {
24222 invert_return = TRUE;
24223 table_index = -table_index;
24226 /* Out-of band indices indicate a deprecated property. The proper index is
24227 * modulo it with the table size. And dividing by the table size yields
24228 * an offset into a table constructed by regen/mk_invlists.pl to contain
24229 * the corresponding warning message */
24230 if (table_index > MAX_UNI_KEYWORD_INDEX) {
24231 Size_t warning_offset = table_index / MAX_UNI_KEYWORD_INDEX;
24232 table_index %= MAX_UNI_KEYWORD_INDEX;
24233 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
24234 "Use of '%.*s' in \\p{} or \\P{} is deprecated because: %s",
24235 (int) name_len, name, deprecated_property_msgs[warning_offset]);
24238 /* In a few properties, a different property is used under /i. These are
24239 * unlikely to change, so are hard-coded here. */
24241 if ( table_index == UNI_XPOSIXUPPER
24242 || table_index == UNI_XPOSIXLOWER
24243 || table_index == UNI_TITLE)
24245 table_index = UNI_CASED;
24247 else if ( table_index == UNI_UPPERCASELETTER
24248 || table_index == UNI_LOWERCASELETTER
24249 # ifdef UNI_TITLECASELETTER /* Missing from early Unicodes */
24250 || table_index == UNI_TITLECASELETTER
24253 table_index = UNI_CASEDLETTER;
24255 else if ( table_index == UNI_POSIXUPPER
24256 || table_index == UNI_POSIXLOWER)
24258 table_index = UNI_POSIXALPHA;
24262 /* Create and return the inversion list */
24263 prop_definition =_new_invlist_C_array(uni_prop_ptrs[table_index]);
24264 sv_2mortal(prop_definition);
24267 /* See if there is a private use override to add to this definition */
24269 COPHH * hinthash = (IN_PERL_COMPILETIME)
24270 ? CopHINTHASH_get(&PL_compiling)
24271 : CopHINTHASH_get(PL_curcop);
24272 SV * pu_overrides = cophh_fetch_pv(hinthash, "private_use", 0, 0);
24274 if (UNLIKELY(pu_overrides && SvPOK(pu_overrides))) {
24276 /* See if there is an element in the hints hash for this table */
24277 SV * pu_lookup = Perl_newSVpvf(aTHX_ "%d=", table_index);
24278 const char * pos = strstr(SvPVX(pu_overrides), SvPVX(pu_lookup));
24282 SV * pu_definition;
24284 SV * expanded_prop_definition =
24285 sv_2mortal(invlist_clone(prop_definition, NULL));
24287 /* If so, it's definition is the string from here to the next
24288 * \a character. And its format is the same as a user-defined
24290 pos += SvCUR(pu_lookup);
24291 pu_definition = newSVpvn(pos, strchr(pos, '\a') - pos);
24292 pu_invlist = handle_user_defined_property(lookup_name,
24295 0, /* Not folded */
24303 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24304 sv_catpvs(msg, "Insecure private-use override");
24305 goto append_name_to_msg;
24308 /* For now, as a safety measure, make sure that it doesn't
24309 * override non-private use code points */
24310 _invlist_intersection(pu_invlist, PL_Private_Use, &pu_invlist);
24312 /* Add it to the list to be returned */
24313 _invlist_union(prop_definition, pu_invlist,
24314 &expanded_prop_definition);
24315 prop_definition = expanded_prop_definition;
24316 Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__PRIVATE_USE), "The private_use feature is experimental");
24321 if (invert_return) {
24322 _invlist_invert(prop_definition);
24324 return prop_definition;
24326 unknown_user_defined:
24327 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24328 sv_catpvs(msg, "Unknown user-defined property name");
24329 goto append_name_to_msg;
24332 if (non_pkg_begin != 0) {
24333 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24334 sv_catpvs(msg, "Illegal user-defined property name");
24337 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24338 sv_catpvs(msg, "Can't find Unicode property definition");
24342 append_name_to_msg:
24344 const char * prefix = (runtime && level == 0) ? " \\p{" : " \"";
24345 const char * suffix = (runtime && level == 0) ? "}" : "\"";
24347 sv_catpv(msg, prefix);
24348 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
24349 sv_catpv(msg, suffix);
24354 definition_deferred:
24357 bool is_qualified = non_pkg_begin != 0; /* If has "::" */
24359 /* Here it could yet to be defined, so defer evaluation of this until
24360 * its needed at runtime. We need the fully qualified property name to
24361 * avoid ambiguity */
24363 fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8,
24367 /* If it didn't come with a package, or the package is utf8::, this
24368 * actually could be an official Unicode property whose inclusion we
24369 * are deferring until runtime to make sure that it isn't overridden by
24370 * a user-defined property of the same name (which we haven't
24371 * encountered yet). Add a marker to indicate this possibility, for
24372 * use at such time when we first need the definition during pattern
24373 * matching execution */
24374 if (! is_qualified || memBEGINPs(name, non_pkg_begin, "utf8::")) {
24375 sv_catpvs(fq_name, DEFERRED_COULD_BE_OFFICIAL_MARKERs);
24378 /* We also need a trailing newline */
24379 sv_catpvs(fq_name, "\n");
24381 *user_defined_ptr = TRUE;
24389 * ex: set ts=8 sts=4 sw=4 et: