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 /* Note on debug output:
76 * This is set up so that -Dr turns on debugging like all other flags that are
77 * enabled by -DDEBUGGING. -Drv gives more verbose output. This applies to
78 * all regular expressions encountered in a program, and gives a huge amount of
79 * output for all but the shortest programs.
81 * The ability to output pattern debugging information lexically, and with much
82 * finer grained control was added, with 'use re qw(Debug ....);' available even
83 * in non-DEBUGGING builds. This is accomplished by copying the contents of
84 * regcomp.c to ext/re/re_comp.c, and regexec.c is copied to ext/re/re_exec.c.
85 * Those files are compiled and linked into the perl executable, and they are
86 * compiled essentially as if DEBUGGING were enabled, and controlled by calls
89 * That would normally mean linking errors when two functions of the same name
90 * are attempted to be placed into the same executable. That is solved in one
92 * 1) Static functions aren't known outside the file they are in, so for the
93 * many functions of that type in this file, it just isn't a problem.
94 * 2) Most externally known functions are enclosed in
95 * #ifndef PERL_IN_XSUB_RE
98 * blocks, so there is only one defintion for them in the whole
99 * executable, the one in regcomp.c (or regexec.c). The implication of
100 * that is any debugging info that comes from them is controlled only by
101 * -Dr. Further, any static function they call will also be the version
102 * in regcomp.c (or regexec.c), so its debugging will also be by -Dr.
103 * 3) About a dozen external functions are re-#defined in ext/re/re_top.h, to
104 * have different names, so that what gets loaded in the executable is
105 * 'Perl_foo' from regcomp.c (and regexec.c), and the identical function
106 * from re_comp.c (and re_exec.c), but with the name 'my_foo' Debugging
107 * in the 'Perl_foo' versions is controlled by -Dr, but the 'my_foo'
108 * versions and their callees are under control of re.pm. The catch is
109 * that references to all these go through the regexp_engine structure,
110 * which is initialized in regcomp.h to the Perl_foo versions, and
111 * substituted out in lexical scopes where 'use re' is in effect to the
112 * 'my_foo' ones. That structure is public API, so it would be a hard
113 * sell to add any additional members.
114 * 4) For functions in regcomp.c and re_comp.c that are called only from,
115 * respectively, regexec.c and re_exec.c, they can have two different
116 * names, depending on #ifdef'ing PERL_IN_XSUB_RE, in both regexec.c and
119 * The bottom line is that if you add code to one of the public functions
120 * listed in ext/re/re_top.h, debugging automagically works. But if you write
121 * a new function that needs to do debugging or there is a chain of calls from
122 * it that need to do debugging, all functions in the chain should use options
125 * A function may have to be split so that debugging stuff is static, but it
126 * calls out to some other function that only gets compiled in regcomp.c to
127 * access data that we don't want to duplicate.
131 #define PERL_IN_REGCOMP_C
135 #ifdef PERL_IN_XSUB_RE
136 # include "re_comp.h"
137 EXTERN_C const struct regexp_engine my_reg_engine;
138 EXTERN_C const struct regexp_engine wild_reg_engine;
140 # include "regcomp.h"
143 #include "invlist_inline.h"
144 #include "unicode_constants.h"
146 #define HAS_NONLATIN1_FOLD_CLOSURE(i) \
147 _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
148 #define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
149 _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
150 #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
151 #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
154 #define STATIC static
157 /* this is a chain of data about sub patterns we are processing that
158 need to be handled separately/specially in study_chunk. Its so
159 we can simulate recursion without losing state. */
161 typedef struct scan_frame {
162 regnode *last_regnode; /* last node to process in this frame */
163 regnode *next_regnode; /* next node to process when last is reached */
164 U32 prev_recursed_depth;
165 I32 stopparen; /* what stopparen do we use */
166 bool in_gosub; /* this or an outer frame is for GOSUB */
168 struct scan_frame *this_prev_frame; /* this previous frame */
169 struct scan_frame *prev_frame; /* previous frame */
170 struct scan_frame *next_frame; /* next frame */
173 /* Certain characters are output as a sequence with the first being a
175 #define isBACKSLASHED_PUNCT(c) memCHRs("-[]\\^", c)
178 struct RExC_state_t {
179 U32 flags; /* RXf_* are we folding, multilining? */
180 U32 pm_flags; /* PMf_* stuff from the calling PMOP */
181 char *precomp; /* uncompiled string. */
182 char *precomp_end; /* pointer to end of uncompiled string. */
183 REGEXP *rx_sv; /* The SV that is the regexp. */
184 regexp *rx; /* perl core regexp structure */
185 regexp_internal *rxi; /* internal data for regexp object
187 char *start; /* Start of input for compile */
188 char *end; /* End of input for compile */
189 char *parse; /* Input-scan pointer. */
190 char *copy_start; /* start of copy of input within
191 constructed parse string */
192 char *save_copy_start; /* Provides one level of saving
193 and restoring 'copy_start' */
194 char *copy_start_in_input; /* Position in input string
195 corresponding to copy_start */
196 SSize_t whilem_seen; /* number of WHILEM in this expr */
197 regnode *emit_start; /* Start of emitted-code area */
198 regnode_offset emit; /* Code-emit pointer */
199 I32 naughty; /* How bad is this pattern? */
200 I32 sawback; /* Did we see \1, ...? */
201 SSize_t size; /* Number of regnode equivalents in
203 Size_t sets_depth; /* Counts recursion depth of already-
204 compiled regex set patterns */
207 I32 parens_buf_size; /* #slots malloced open/close_parens */
208 regnode_offset *open_parens; /* offsets to open parens */
209 regnode_offset *close_parens; /* offsets to close parens */
210 HV *paren_names; /* Paren names */
212 /* position beyond 'precomp' of the warning message furthest away from
213 * 'precomp'. During the parse, no warnings are raised for any problems
214 * earlier in the parse than this position. This works if warnings are
215 * raised the first time a given spot is parsed, and if only one
216 * independent warning is raised for any given spot */
217 Size_t latest_warn_offset;
219 I32 npar; /* Capture buffer count so far in the
220 parse, (OPEN) plus one. ("par" 0 is
222 I32 total_par; /* During initial parse, is either 0,
223 or -1; the latter indicating a
224 reparse is needed. After that pass,
225 it is what 'npar' became after the
226 pass. Hence, it being > 0 indicates
227 we are in a reparse situation */
228 I32 nestroot; /* root parens we are in - used by
231 regnode *end_op; /* END node in program */
232 I32 utf8; /* whether the pattern is utf8 or not */
233 I32 orig_utf8; /* whether the pattern was originally in utf8 */
234 /* XXX use this for future optimisation of case
235 * where pattern must be upgraded to utf8. */
236 I32 uni_semantics; /* If a d charset modifier should use unicode
237 rules, even if the pattern is not in
240 I32 recurse_count; /* Number of recurse regops we have generated */
241 regnode **recurse; /* Recurse regops */
242 U8 *study_chunk_recursed; /* bitmap of which subs we have moved
244 U32 study_chunk_recursed_bytes; /* bytes in bitmap */
248 I32 override_recoding;
249 I32 recode_x_to_native;
250 I32 in_multi_char_class;
251 int code_index; /* next code_blocks[] slot */
252 struct reg_code_blocks *code_blocks;/* positions of literal (?{})
254 SSize_t maxlen; /* mininum possible number of chars in string to match */
255 scan_frame *frame_head;
256 scan_frame *frame_last;
260 SV *runtime_code_qr; /* qr with the runtime code blocks */
262 const char *lastparse;
264 U32 study_chunk_recursed_count;
265 AV *paren_name_list; /* idx -> name */
269 #define RExC_lastparse (pRExC_state->lastparse)
270 #define RExC_lastnum (pRExC_state->lastnum)
271 #define RExC_paren_name_list (pRExC_state->paren_name_list)
272 #define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count)
273 #define RExC_mysv (pRExC_state->mysv1)
274 #define RExC_mysv1 (pRExC_state->mysv1)
275 #define RExC_mysv2 (pRExC_state->mysv2)
283 bool sWARN_EXPERIMENTAL__VLB;
284 bool sWARN_EXPERIMENTAL__REGEX_SETS;
287 #define RExC_flags (pRExC_state->flags)
288 #define RExC_pm_flags (pRExC_state->pm_flags)
289 #define RExC_precomp (pRExC_state->precomp)
290 #define RExC_copy_start_in_input (pRExC_state->copy_start_in_input)
291 #define RExC_copy_start_in_constructed (pRExC_state->copy_start)
292 #define RExC_save_copy_start_in_constructed (pRExC_state->save_copy_start)
293 #define RExC_precomp_end (pRExC_state->precomp_end)
294 #define RExC_rx_sv (pRExC_state->rx_sv)
295 #define RExC_rx (pRExC_state->rx)
296 #define RExC_rxi (pRExC_state->rxi)
297 #define RExC_start (pRExC_state->start)
298 #define RExC_end (pRExC_state->end)
299 #define RExC_parse (pRExC_state->parse)
300 #define RExC_latest_warn_offset (pRExC_state->latest_warn_offset )
301 #define RExC_whilem_seen (pRExC_state->whilem_seen)
302 #define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs
303 under /d from /u ? */
305 #ifdef RE_TRACK_PATTERN_OFFSETS
306 # define RExC_offsets (RExC_rxi->u.offsets) /* I am not like the
309 #define RExC_emit (pRExC_state->emit)
310 #define RExC_emit_start (pRExC_state->emit_start)
311 #define RExC_sawback (pRExC_state->sawback)
312 #define RExC_seen (pRExC_state->seen)
313 #define RExC_size (pRExC_state->size)
314 #define RExC_maxlen (pRExC_state->maxlen)
315 #define RExC_npar (pRExC_state->npar)
316 #define RExC_total_parens (pRExC_state->total_par)
317 #define RExC_parens_buf_size (pRExC_state->parens_buf_size)
318 #define RExC_nestroot (pRExC_state->nestroot)
319 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
320 #define RExC_utf8 (pRExC_state->utf8)
321 #define RExC_uni_semantics (pRExC_state->uni_semantics)
322 #define RExC_orig_utf8 (pRExC_state->orig_utf8)
323 #define RExC_open_parens (pRExC_state->open_parens)
324 #define RExC_close_parens (pRExC_state->close_parens)
325 #define RExC_end_op (pRExC_state->end_op)
326 #define RExC_paren_names (pRExC_state->paren_names)
327 #define RExC_recurse (pRExC_state->recurse)
328 #define RExC_recurse_count (pRExC_state->recurse_count)
329 #define RExC_sets_depth (pRExC_state->sets_depth)
330 #define RExC_study_chunk_recursed (pRExC_state->study_chunk_recursed)
331 #define RExC_study_chunk_recursed_bytes \
332 (pRExC_state->study_chunk_recursed_bytes)
333 #define RExC_in_lookbehind (pRExC_state->in_lookbehind)
334 #define RExC_in_lookahead (pRExC_state->in_lookahead)
335 #define RExC_contains_locale (pRExC_state->contains_locale)
336 #define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
339 # define SET_recode_x_to_native(x) \
340 STMT_START { RExC_recode_x_to_native = (x); } STMT_END
342 # define SET_recode_x_to_native(x) NOOP
345 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
346 #define RExC_frame_head (pRExC_state->frame_head)
347 #define RExC_frame_last (pRExC_state->frame_last)
348 #define RExC_frame_count (pRExC_state->frame_count)
349 #define RExC_strict (pRExC_state->strict)
350 #define RExC_study_started (pRExC_state->study_started)
351 #define RExC_warn_text (pRExC_state->warn_text)
352 #define RExC_in_script_run (pRExC_state->in_script_run)
353 #define RExC_use_BRANCHJ (pRExC_state->use_BRANCHJ)
354 #define RExC_warned_WARN_EXPERIMENTAL__VLB (pRExC_state->sWARN_EXPERIMENTAL__VLB)
355 #define RExC_warned_WARN_EXPERIMENTAL__REGEX_SETS (pRExC_state->sWARN_EXPERIMENTAL__REGEX_SETS)
356 #define RExC_unlexed_names (pRExC_state->unlexed_names)
358 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
359 * a flag to disable back-off on the fixed/floating substrings - if it's
360 * a high complexity pattern we assume the benefit of avoiding a full match
361 * is worth the cost of checking for the substrings even if they rarely help.
363 #define RExC_naughty (pRExC_state->naughty)
364 #define TOO_NAUGHTY (10)
365 #define MARK_NAUGHTY(add) \
366 if (RExC_naughty < TOO_NAUGHTY) \
367 RExC_naughty += (add)
368 #define MARK_NAUGHTY_EXP(exp, add) \
369 if (RExC_naughty < TOO_NAUGHTY) \
370 RExC_naughty += RExC_naughty / (exp) + (add)
372 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
373 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
374 ((*s) == '{' && regcurly(s)))
377 * Flags to be passed up and down.
379 #define WORST 0 /* Worst case. */
380 #define HASWIDTH 0x01 /* Known to not match null strings, could match
383 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
384 * character. (There needs to be a case: in the switch statement in regexec.c
385 * for any node marked SIMPLE.) Note that this is not the same thing as
388 #define SPSTART 0x04 /* Starts with * or + */
389 #define POSTPONED 0x08 /* (?1),(?&name), (??{...}) or similar */
390 #define TRYAGAIN 0x10 /* Weeded out a declaration. */
391 #define RESTART_PARSE 0x20 /* Need to redo the parse */
392 #define NEED_UTF8 0x40 /* In conjunction with RESTART_PARSE, need to
393 calcuate sizes as UTF-8 */
395 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
397 /* whether trie related optimizations are enabled */
398 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
399 #define TRIE_STUDY_OPT
400 #define FULL_TRIE_STUDY
406 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
407 #define PBITVAL(paren) (1 << ((paren) & 7))
408 #define PAREN_OFFSET(depth) \
409 (RExC_study_chunk_recursed + (depth) * RExC_study_chunk_recursed_bytes)
410 #define PAREN_TEST(depth, paren) \
411 (PBYTE(PAREN_OFFSET(depth), paren) & PBITVAL(paren))
412 #define PAREN_SET(depth, paren) \
413 (PBYTE(PAREN_OFFSET(depth), paren) |= PBITVAL(paren))
414 #define PAREN_UNSET(depth, paren) \
415 (PBYTE(PAREN_OFFSET(depth), paren) &= ~PBITVAL(paren))
417 #define REQUIRE_UTF8(flagp) STMT_START { \
419 *flagp = RESTART_PARSE|NEED_UTF8; \
424 /* Change from /d into /u rules, and restart the parse. RExC_uni_semantics is
425 * a flag that indicates we need to override /d with /u as a result of
426 * something in the pattern. It should only be used in regards to calling
427 * set_regex_charset() or get_regex_charset() */
428 #define REQUIRE_UNI_RULES(flagp, restart_retval) \
430 if (DEPENDS_SEMANTICS) { \
431 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); \
432 RExC_uni_semantics = 1; \
433 if (RExC_seen_d_op && LIKELY(! IN_PARENS_PASS)) { \
434 /* No need to restart the parse if we haven't seen \
435 * anything that differs between /u and /d, and no need \
436 * to restart immediately if we're going to reparse \
437 * anyway to count parens */ \
438 *flagp |= RESTART_PARSE; \
439 return restart_retval; \
444 #define REQUIRE_BRANCHJ(flagp, restart_retval) \
446 RExC_use_BRANCHJ = 1; \
447 *flagp |= RESTART_PARSE; \
448 return restart_retval; \
451 /* Until we have completed the parse, we leave RExC_total_parens at 0 or
452 * less. After that, it must always be positive, because the whole re is
453 * considered to be surrounded by virtual parens. Setting it to negative
454 * indicates there is some construct that needs to know the actual number of
455 * parens to be properly handled. And that means an extra pass will be
456 * required after we've counted them all */
457 #define ALL_PARENS_COUNTED (RExC_total_parens > 0)
458 #define REQUIRE_PARENS_PASS \
459 STMT_START { /* No-op if have completed a pass */ \
460 if (! ALL_PARENS_COUNTED) RExC_total_parens = -1; \
462 #define IN_PARENS_PASS (RExC_total_parens < 0)
465 /* This is used to return failure (zero) early from the calling function if
466 * various flags in 'flags' are set. Two flags always cause a return:
467 * 'RESTART_PARSE' and 'NEED_UTF8'. 'extra' can be used to specify any
468 * additional flags that should cause a return; 0 if none. If the return will
469 * be done, '*flagp' is first set to be all of the flags that caused the
471 #define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra) \
473 if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) { \
474 *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra)); \
479 #define MUST_RESTART(flags) ((flags) & (RESTART_PARSE))
481 #define RETURN_FAIL_ON_RESTART(flags,flagp) \
482 RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0)
483 #define RETURN_FAIL_ON_RESTART_FLAGP(flagp) \
484 if (MUST_RESTART(*(flagp))) return 0
486 /* This converts the named class defined in regcomp.h to its equivalent class
487 * number defined in handy.h. */
488 #define namedclass_to_classnum(class) ((int) ((class) / 2))
489 #define classnum_to_namedclass(classnum) ((classnum) * 2)
491 #define _invlist_union_complement_2nd(a, b, output) \
492 _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
493 #define _invlist_intersection_complement_2nd(a, b, output) \
494 _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
496 /* We add a marker if we are deferring expansion of a property that is both
497 * 1) potentiallly user-defined; and
498 * 2) could also be an official Unicode property.
500 * Without this marker, any deferred expansion can only be for a user-defined
501 * one. This marker shouldn't conflict with any that could be in a legal name,
502 * and is appended to its name to indicate this. There is a string and
504 #define DEFERRED_COULD_BE_OFFICIAL_MARKERs "~"
505 #define DEFERRED_COULD_BE_OFFICIAL_MARKERc '~'
507 /* What is infinity for optimization purposes */
508 #define OPTIMIZE_INFTY SSize_t_MAX
510 /* About scan_data_t.
512 During optimisation we recurse through the regexp program performing
513 various inplace (keyhole style) optimisations. In addition study_chunk
514 and scan_commit populate this data structure with information about
515 what strings MUST appear in the pattern. We look for the longest
516 string that must appear at a fixed location, and we look for the
517 longest string that may appear at a floating location. So for instance
522 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
523 strings (because they follow a .* construct). study_chunk will identify
524 both FOO and BAR as being the longest fixed and floating strings respectively.
526 The strings can be composites, for instance
530 will result in a composite fixed substring 'foo'.
532 For each string some basic information is maintained:
535 This is the position the string must appear at, or not before.
536 It also implicitly (when combined with minlenp) tells us how many
537 characters must match before the string we are searching for.
538 Likewise when combined with minlenp and the length of the string it
539 tells us how many characters must appear after the string we have
543 Only used for floating strings. This is the rightmost point that
544 the string can appear at. If set to OPTIMIZE_INFTY it indicates that the
545 string can occur infinitely far to the right.
546 For fixed strings, it is equal to min_offset.
549 A pointer to the minimum number of characters of the pattern that the
550 string was found inside. This is important as in the case of positive
551 lookahead or positive lookbehind we can have multiple patterns
556 The minimum length of the pattern overall is 3, the minimum length
557 of the lookahead part is 3, but the minimum length of the part that
558 will actually match is 1. So 'FOO's minimum length is 3, but the
559 minimum length for the F is 1. This is important as the minimum length
560 is used to determine offsets in front of and behind the string being
561 looked for. Since strings can be composites this is the length of the
562 pattern at the time it was committed with a scan_commit. Note that
563 the length is calculated by study_chunk, so that the minimum lengths
564 are not known until the full pattern has been compiled, thus the
565 pointer to the value.
569 In the case of lookbehind the string being searched for can be
570 offset past the start point of the final matching string.
571 If this value was just blithely removed from the min_offset it would
572 invalidate some of the calculations for how many chars must match
573 before or after (as they are derived from min_offset and minlen and
574 the length of the string being searched for).
575 When the final pattern is compiled and the data is moved from the
576 scan_data_t structure into the regexp structure the information
577 about lookbehind is factored in, with the information that would
578 have been lost precalculated in the end_shift field for the
581 The fields pos_min and pos_delta are used to store the minimum offset
582 and the delta to the maximum offset at the current point in the pattern.
586 struct scan_data_substrs {
587 SV *str; /* longest substring found in pattern */
588 SSize_t min_offset; /* earliest point in string it can appear */
589 SSize_t max_offset; /* latest point in string it can appear */
590 SSize_t *minlenp; /* pointer to the minlen relevant to the string */
591 SSize_t lookbehind; /* is the pos of the string modified by LB */
592 I32 flags; /* per substring SF_* and SCF_* flags */
595 typedef struct scan_data_t {
596 /*I32 len_min; unused */
597 /*I32 len_delta; unused */
601 SSize_t last_end; /* min value, <0 unless valid. */
602 SSize_t last_start_min;
603 SSize_t last_start_max;
604 U8 cur_is_floating; /* whether the last_* values should be set as
605 * the next fixed (0) or floating (1)
608 /* [0] is longest fixed substring so far, [1] is longest float so far */
609 struct scan_data_substrs substrs[2];
611 I32 flags; /* common SF_* and SCF_* flags */
613 SSize_t *last_closep;
614 regnode_ssc *start_class;
618 * Forward declarations for pregcomp()'s friends.
621 static const scan_data_t zero_scan_data = {
622 0, 0, NULL, 0, 0, 0, 0,
624 { NULL, 0, 0, 0, 0, 0 },
625 { NULL, 0, 0, 0, 0, 0 },
632 #define SF_BEFORE_SEOL 0x0001
633 #define SF_BEFORE_MEOL 0x0002
634 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
636 #define SF_IS_INF 0x0040
637 #define SF_HAS_PAR 0x0080
638 #define SF_IN_PAR 0x0100
639 #define SF_HAS_EVAL 0x0200
642 /* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
643 * longest substring in the pattern. When it is not set the optimiser keeps
644 * track of position, but does not keep track of the actual strings seen,
646 * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
649 * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
650 * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
651 * turned off because of the alternation (BRANCH). */
652 #define SCF_DO_SUBSTR 0x0400
654 #define SCF_DO_STCLASS_AND 0x0800
655 #define SCF_DO_STCLASS_OR 0x1000
656 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
657 #define SCF_WHILEM_VISITED_POS 0x2000
659 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
660 #define SCF_SEEN_ACCEPT 0x8000
661 #define SCF_TRIE_DOING_RESTUDY 0x10000
662 #define SCF_IN_DEFINE 0x20000
667 #define UTF cBOOL(RExC_utf8)
669 /* The enums for all these are ordered so things work out correctly */
670 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
671 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) \
672 == REGEX_DEPENDS_CHARSET)
673 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
674 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) \
675 >= REGEX_UNICODE_CHARSET)
676 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
677 == REGEX_ASCII_RESTRICTED_CHARSET)
678 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
679 >= REGEX_ASCII_RESTRICTED_CHARSET)
680 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) \
681 == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
683 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
685 /* For programs that want to be strictly Unicode compatible by dying if any
686 * attempt is made to match a non-Unicode code point against a Unicode
688 #define ALWAYS_WARN_SUPER ckDEAD(packWARN(WARN_NON_UNICODE))
690 #define OOB_NAMEDCLASS -1
692 /* There is no code point that is out-of-bounds, so this is problematic. But
693 * its only current use is to initialize a variable that is always set before
695 #define OOB_UNICODE 0xDEADBEEF
697 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
700 /* length of regex to show in messages that don't mark a position within */
701 #define RegexLengthToShowInErrorMessages 127
704 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
705 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
706 * op/pragma/warn/regcomp.
708 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
709 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
711 #define REPORT_LOCATION " in regex; marked by " MARKER1 \
712 " in m/%" UTF8f MARKER2 "%" UTF8f "/"
714 /* The code in this file in places uses one level of recursion with parsing
715 * rebased to an alternate string constructed by us in memory. This can take
716 * the form of something that is completely different from the input, or
717 * something that uses the input as part of the alternate. In the first case,
718 * there should be no possibility of an error, as we are in complete control of
719 * the alternate string. But in the second case we don't completely control
720 * the input portion, so there may be errors in that. Here's an example:
722 * is handled specially because \x{df} folds to a sequence of more than one
723 * character: 'ss'. What is done is to create and parse an alternate string,
724 * which looks like this:
725 * /(?:\x{DF}|[abc\x{DF}def])/ui
726 * where it uses the input unchanged in the middle of something it constructs,
727 * which is a branch for the DF outside the character class, and clustering
728 * parens around the whole thing. (It knows enough to skip the DF inside the
729 * class while in this substitute parse.) 'abc' and 'def' may have errors that
730 * need to be reported. The general situation looks like this:
732 * |<------- identical ------>|
734 * Input: ---------------------------------------------------------------
735 * Constructed: ---------------------------------------------------
737 * |<------- identical ------>|
739 * sI..eI is the portion of the input pattern we are concerned with here.
740 * sC..EC is the constructed substitute parse string.
741 * sC..tC is constructed by us
742 * tC..eC is an exact duplicate of the portion of the input pattern tI..eI.
743 * In the diagram, these are vertically aligned.
744 * eC..EC is also constructed by us.
745 * xC is the position in the substitute parse string where we found a
747 * xI is the position in the original pattern corresponding to xC.
749 * We want to display a message showing the real input string. Thus we need to
750 * translate from xC to xI. We know that xC >= tC, since the portion of the
751 * string sC..tC has been constructed by us, and so shouldn't have errors. We
753 * xI = tI + (xC - tC)
755 * When the substitute parse is constructed, the code needs to set:
758 * RExC_copy_start_in_input (tI)
759 * RExC_copy_start_in_constructed (tC)
760 * and restore them when done.
762 * During normal processing of the input pattern, both
763 * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to
764 * sI, so that xC equals xI.
767 #define sI RExC_precomp
768 #define eI RExC_precomp_end
769 #define sC RExC_start
771 #define tI RExC_copy_start_in_input
772 #define tC RExC_copy_start_in_constructed
773 #define xI(xC) (tI + (xC - tC))
774 #define xI_offset(xC) (xI(xC) - sI)
776 #define REPORT_LOCATION_ARGS(xC) \
778 (xI(xC) > eI) /* Don't run off end */ \
779 ? eI - sI /* Length before the <--HERE */ \
780 : ((xI_offset(xC) >= 0) \
782 : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %" \
783 IVdf " trying to output message for " \
785 __FILE__, __LINE__, (IV) xI_offset(xC), \
786 ((int) (eC - sC)), sC), 0)), \
787 sI), /* The input pattern printed up to the <--HERE */ \
789 (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */ \
790 (xI(xC) > eI) ? eI : xI(xC)) /* pattern after <--HERE */
792 /* Used to point after bad bytes for an error message, but avoid skipping
793 * past a nul byte. */
794 #define SKIP_IF_CHAR(s, e) (!*(s) ? 0 : UTF ? UTF8_SAFE_SKIP(s, e) : 1)
796 /* Set up to clean up after our imminent demise */
797 #define PREPARE_TO_DIE \
800 SAVEFREESV(RExC_rx_sv); \
801 if (RExC_open_parens) \
802 SAVEFREEPV(RExC_open_parens); \
803 if (RExC_close_parens) \
804 SAVEFREEPV(RExC_close_parens); \
808 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
809 * arg. Show regex, up to a maximum length. If it's too long, chop and add
812 #define _FAIL(code) STMT_START { \
813 const char *ellipses = ""; \
814 IV len = RExC_precomp_end - RExC_precomp; \
817 if (len > RegexLengthToShowInErrorMessages) { \
818 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
819 len = RegexLengthToShowInErrorMessages - 10; \
825 #define FAIL(msg) _FAIL( \
826 Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/", \
827 msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
829 #define FAIL2(msg,arg) _FAIL( \
830 Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \
831 arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
833 #define FAIL3(msg,arg1,arg2) _FAIL( \
834 Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \
835 arg1, arg2, UTF8fARG(UTF, len, RExC_precomp), ellipses))
838 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
840 #define Simple_vFAIL(m) STMT_START { \
841 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
842 m, REPORT_LOCATION_ARGS(RExC_parse)); \
846 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
848 #define vFAIL(m) STMT_START { \
854 * Like Simple_vFAIL(), but accepts two arguments.
856 #define Simple_vFAIL2(m,a1) STMT_START { \
857 S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, \
858 REPORT_LOCATION_ARGS(RExC_parse)); \
862 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
864 #define vFAIL2(m,a1) STMT_START { \
866 Simple_vFAIL2(m, a1); \
871 * Like Simple_vFAIL(), but accepts three arguments.
873 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
874 S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, a2, \
875 REPORT_LOCATION_ARGS(RExC_parse)); \
879 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
881 #define vFAIL3(m,a1,a2) STMT_START { \
883 Simple_vFAIL3(m, a1, a2); \
887 * Like Simple_vFAIL(), but accepts four arguments.
889 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
890 S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, a2, a3, \
891 REPORT_LOCATION_ARGS(RExC_parse)); \
894 #define vFAIL4(m,a1,a2,a3) STMT_START { \
896 Simple_vFAIL4(m, a1, a2, a3); \
899 /* A specialized version of vFAIL2 that works with UTF8f */
900 #define vFAIL2utf8f(m, a1) STMT_START { \
902 S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, \
903 REPORT_LOCATION_ARGS(RExC_parse)); \
906 #define vFAIL3utf8f(m, a1, a2) STMT_START { \
908 S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, a2, \
909 REPORT_LOCATION_ARGS(RExC_parse)); \
912 /* Setting this to NULL is a signal to not output warnings */
913 #define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE \
915 RExC_save_copy_start_in_constructed = RExC_copy_start_in_constructed;\
916 RExC_copy_start_in_constructed = NULL; \
918 #define RESTORE_WARNINGS \
919 RExC_copy_start_in_constructed = RExC_save_copy_start_in_constructed
921 /* Since a warning can be generated multiple times as the input is reparsed, we
922 * output it the first time we come to that point in the parse, but suppress it
923 * otherwise. 'RExC_copy_start_in_constructed' being NULL is a flag to not
924 * generate any warnings */
925 #define TO_OUTPUT_WARNINGS(loc) \
926 ( RExC_copy_start_in_constructed \
927 && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset)
929 /* After we've emitted a warning, we save the position in the input so we don't
931 #define UPDATE_WARNINGS_LOC(loc) \
933 if (TO_OUTPUT_WARNINGS(loc)) { \
934 RExC_latest_warn_offset = MAX(sI, MIN(eI, xI(loc))) \
939 /* 'warns' is the output of the packWARNx macro used in 'code' */
940 #define _WARN_HELPER(loc, warns, code) \
942 if (! RExC_copy_start_in_constructed) { \
943 Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none" \
944 " expected at '%s'", \
945 __FILE__, __LINE__, loc); \
947 if (TO_OUTPUT_WARNINGS(loc)) { \
951 UPDATE_WARNINGS_LOC(loc); \
955 /* m is not necessarily a "literal string", in this macro */
956 #define warn_non_literal_string(loc, packed_warn, m) \
957 _WARN_HELPER(loc, packed_warn, \
958 Perl_warner(aTHX_ packed_warn, \
959 "%s" REPORT_LOCATION, \
960 m, REPORT_LOCATION_ARGS(loc)))
961 #define reg_warn_non_literal_string(loc, m) \
962 warn_non_literal_string(loc, packWARN(WARN_REGEXP), m)
964 #define ckWARN2_non_literal_string(loc, packwarn, m, a1) \
967 Size_t format_size = strlen(m) + strlen(REPORT_LOCATION)+ 1;\
968 Newx(format, format_size, char); \
969 my_strlcpy(format, m, format_size); \
970 my_strlcat(format, REPORT_LOCATION, format_size); \
971 SAVEFREEPV(format); \
972 _WARN_HELPER(loc, packwarn, \
973 Perl_ck_warner(aTHX_ packwarn, \
975 a1, REPORT_LOCATION_ARGS(loc))); \
978 #define ckWARNreg(loc,m) \
979 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
980 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
982 REPORT_LOCATION_ARGS(loc)))
984 #define vWARN(loc, m) \
985 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
986 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
988 REPORT_LOCATION_ARGS(loc))) \
990 #define vWARN_dep(loc, m) \
991 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
992 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), \
994 REPORT_LOCATION_ARGS(loc)))
996 #define ckWARNdep(loc,m) \
997 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
998 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
1000 REPORT_LOCATION_ARGS(loc)))
1002 #define ckWARNregdep(loc,m) \
1003 _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
1004 Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, \
1006 m REPORT_LOCATION, \
1007 REPORT_LOCATION_ARGS(loc)))
1009 #define ckWARN2reg_d(loc,m, a1) \
1010 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
1011 Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP), \
1012 m REPORT_LOCATION, \
1013 a1, REPORT_LOCATION_ARGS(loc)))
1015 #define ckWARN2reg(loc, m, a1) \
1016 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
1017 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
1018 m REPORT_LOCATION, \
1019 a1, REPORT_LOCATION_ARGS(loc)))
1021 #define vWARN3(loc, m, a1, a2) \
1022 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
1023 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
1024 m REPORT_LOCATION, \
1025 a1, a2, REPORT_LOCATION_ARGS(loc)))
1027 #define ckWARN3reg(loc, m, a1, a2) \
1028 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
1029 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
1030 m REPORT_LOCATION, \
1032 REPORT_LOCATION_ARGS(loc)))
1034 #define vWARN4(loc, m, a1, a2, a3) \
1035 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
1036 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
1037 m REPORT_LOCATION, \
1039 REPORT_LOCATION_ARGS(loc)))
1041 #define ckWARN4reg(loc, m, a1, a2, a3) \
1042 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
1043 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
1044 m REPORT_LOCATION, \
1046 REPORT_LOCATION_ARGS(loc)))
1048 #define vWARN5(loc, m, a1, a2, a3, a4) \
1049 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
1050 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
1051 m REPORT_LOCATION, \
1053 REPORT_LOCATION_ARGS(loc)))
1055 #define ckWARNexperimental(loc, class, m) \
1057 if (! RExC_warned_ ## class) { /* warn once per compilation */ \
1058 RExC_warned_ ## class = 1; \
1059 _WARN_HELPER(loc, packWARN(class), \
1060 Perl_ck_warner_d(aTHX_ packWARN(class), \
1061 m REPORT_LOCATION, \
1062 REPORT_LOCATION_ARGS(loc)));\
1066 /* Convert between a pointer to a node and its offset from the beginning of the
1068 #define REGNODE_p(offset) (RExC_emit_start + (offset))
1069 #define REGNODE_OFFSET(node) ((node) - RExC_emit_start)
1071 /* Macros for recording node offsets. 20001227 mjd@plover.com
1072 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
1073 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
1074 * Element 0 holds the number n.
1075 * Position is 1 indexed.
1077 #ifndef RE_TRACK_PATTERN_OFFSETS
1078 #define Set_Node_Offset_To_R(offset,byte)
1079 #define Set_Node_Offset(node,byte)
1080 #define Set_Cur_Node_Offset
1081 #define Set_Node_Length_To_R(node,len)
1082 #define Set_Node_Length(node,len)
1083 #define Set_Node_Cur_Length(node,start)
1084 #define Node_Offset(n)
1085 #define Node_Length(n)
1086 #define Set_Node_Offset_Length(node,offset,len)
1087 #define ProgLen(ri) ri->u.proglen
1088 #define SetProgLen(ri,x) ri->u.proglen = x
1089 #define Track_Code(code)
1091 #define ProgLen(ri) ri->u.offsets[0]
1092 #define SetProgLen(ri,x) ri->u.offsets[0] = x
1093 #define Set_Node_Offset_To_R(offset,byte) STMT_START { \
1094 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
1095 __LINE__, (int)(offset), (int)(byte))); \
1096 if((offset) < 0) { \
1097 Perl_croak(aTHX_ "value of node is %d in Offset macro", \
1100 RExC_offsets[2*(offset)-1] = (byte); \
1104 #define Set_Node_Offset(node,byte) \
1105 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start)
1106 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
1108 #define Set_Node_Length_To_R(node,len) STMT_START { \
1109 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
1110 __LINE__, (int)(node), (int)(len))); \
1112 Perl_croak(aTHX_ "value of node is %d in Length macro", \
1115 RExC_offsets[2*(node)] = (len); \
1119 #define Set_Node_Length(node,len) \
1120 Set_Node_Length_To_R(REGNODE_OFFSET(node), len)
1121 #define Set_Node_Cur_Length(node, start) \
1122 Set_Node_Length(node, RExC_parse - start)
1124 /* Get offsets and lengths */
1125 #define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1])
1126 #define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))])
1128 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
1129 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset)); \
1130 Set_Node_Length_To_R(REGNODE_OFFSET(node), (len)); \
1133 #define Track_Code(code) STMT_START { code } STMT_END
1136 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
1137 #define EXPERIMENTAL_INPLACESCAN
1138 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
1142 Perl_re_printf(pTHX_ const char *fmt, ...)
1146 PerlIO *f= Perl_debug_log;
1147 PERL_ARGS_ASSERT_RE_PRINTF;
1149 result = PerlIO_vprintf(f, fmt, ap);
1155 Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
1159 PerlIO *f= Perl_debug_log;
1160 PERL_ARGS_ASSERT_RE_INDENTF;
1161 va_start(ap, depth);
1162 PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
1163 result = PerlIO_vprintf(f, fmt, ap);
1167 #endif /* DEBUGGING */
1169 #define DEBUG_RExC_seen() \
1170 DEBUG_OPTIMISE_MORE_r({ \
1171 Perl_re_printf( aTHX_ "RExC_seen: "); \
1173 if (RExC_seen & REG_ZERO_LEN_SEEN) \
1174 Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN "); \
1176 if (RExC_seen & REG_LOOKBEHIND_SEEN) \
1177 Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN "); \
1179 if (RExC_seen & REG_GPOS_SEEN) \
1180 Perl_re_printf( aTHX_ "REG_GPOS_SEEN "); \
1182 if (RExC_seen & REG_RECURSE_SEEN) \
1183 Perl_re_printf( aTHX_ "REG_RECURSE_SEEN "); \
1185 if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN) \
1186 Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN "); \
1188 if (RExC_seen & REG_VERBARG_SEEN) \
1189 Perl_re_printf( aTHX_ "REG_VERBARG_SEEN "); \
1191 if (RExC_seen & REG_CUTGROUP_SEEN) \
1192 Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN "); \
1194 if (RExC_seen & REG_RUN_ON_COMMENT_SEEN) \
1195 Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN "); \
1197 if (RExC_seen & REG_UNFOLDED_MULTI_SEEN) \
1198 Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN "); \
1200 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) \
1201 Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN "); \
1203 Perl_re_printf( aTHX_ "\n"); \
1206 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
1207 if ((flags) & flag) Perl_re_printf( aTHX_ "%s ", #flag)
1212 S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
1213 const char *close_str)
1218 Perl_re_printf( aTHX_ "%s", open_str);
1219 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
1220 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
1221 DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
1222 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
1223 DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
1224 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
1225 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
1226 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
1227 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
1228 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
1229 DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
1230 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
1231 DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
1232 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
1233 DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
1234 Perl_re_printf( aTHX_ "%s", close_str);
1239 S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
1240 U32 depth, int is_inf)
1242 DECLARE_AND_GET_RE_DEBUG_FLAGS;
1244 DEBUG_OPTIMISE_MORE_r({
1247 Perl_re_indentf(aTHX_ "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
1251 (IV)data->pos_delta,
1255 S_debug_show_study_flags(aTHX_ data->flags," [","]");
1257 Perl_re_printf( aTHX_
1258 " Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
1260 (IV)(data->last_closep ? *((data)->last_closep) : -1),
1261 is_inf ? "INF " : ""
1264 if (data->last_found) {
1266 Perl_re_printf(aTHX_
1267 "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
1268 SvPVX_const(data->last_found),
1270 (IV)data->last_start_min,
1271 (IV)data->last_start_max
1274 for (i = 0; i < 2; i++) {
1275 Perl_re_printf(aTHX_
1276 " %s%s: '%s' @ %" IVdf "/%" IVdf,
1277 data->cur_is_floating == i ? "*" : "",
1278 i ? "Float" : "Fixed",
1279 SvPVX_const(data->substrs[i].str),
1280 (IV)data->substrs[i].min_offset,
1281 (IV)data->substrs[i].max_offset
1283 S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
1287 Perl_re_printf( aTHX_ "\n");
1293 S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
1294 regnode *scan, U32 depth, U32 flags)
1296 DECLARE_AND_GET_RE_DEBUG_FLAGS;
1303 Next = regnext(scan);
1304 regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
1305 Perl_re_indentf( aTHX_ "%s>%3d: %s (%d)",
1308 REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
1309 Next ? (REG_NODE_NUM(Next)) : 0 );
1310 S_debug_show_study_flags(aTHX_ flags," [ ","]");
1311 Perl_re_printf( aTHX_ "\n");
1316 # define DEBUG_STUDYDATA(where, data, depth, is_inf) \
1317 S_debug_studydata(aTHX_ where, data, depth, is_inf)
1319 # define DEBUG_PEEP(str, scan, depth, flags) \
1320 S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
1323 # define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
1324 # define DEBUG_PEEP(str, scan, depth, flags) NOOP
1328 /* =========================================================
1329 * BEGIN edit_distance stuff.
1331 * This calculates how many single character changes of any type are needed to
1332 * transform a string into another one. It is taken from version 3.1 of
1334 * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1337 /* Our unsorted dictionary linked list. */
1338 /* Note we use UVs, not chars. */
1343 struct dictionary* next;
1345 typedef struct dictionary item;
1348 PERL_STATIC_INLINE item*
1349 push(UV key, item* curr)
1352 Newx(head, 1, item);
1360 PERL_STATIC_INLINE item*
1361 find(item* head, UV key)
1363 item* iterator = head;
1365 if (iterator->key == key){
1368 iterator = iterator->next;
1374 PERL_STATIC_INLINE item*
1375 uniquePush(item* head, UV key)
1377 item* iterator = head;
1380 if (iterator->key == key) {
1383 iterator = iterator->next;
1386 return push(key, head);
1389 PERL_STATIC_INLINE void
1390 dict_free(item* head)
1392 item* iterator = head;
1395 item* temp = iterator;
1396 iterator = iterator->next;
1403 /* End of Dictionary Stuff */
1405 /* All calculations/work are done here */
1407 S_edit_distance(const UV* src,
1409 const STRLEN x, /* length of src[] */
1410 const STRLEN y, /* length of tgt[] */
1411 const SSize_t maxDistance
1415 UV swapCount, swapScore, targetCharCount, i, j;
1417 UV score_ceil = x + y;
1419 PERL_ARGS_ASSERT_EDIT_DISTANCE;
1421 /* intialize matrix start values */
1422 Newx(scores, ( (x + 2) * (y + 2)), UV);
1423 scores[0] = score_ceil;
1424 scores[1 * (y + 2) + 0] = score_ceil;
1425 scores[0 * (y + 2) + 1] = score_ceil;
1426 scores[1 * (y + 2) + 1] = 0;
1427 head = uniquePush(uniquePush(head, src[0]), tgt[0]);
1432 for (i=1;i<=x;i++) {
1434 head = uniquePush(head, src[i]);
1435 scores[(i+1) * (y + 2) + 1] = i;
1436 scores[(i+1) * (y + 2) + 0] = score_ceil;
1439 for (j=1;j<=y;j++) {
1442 head = uniquePush(head, tgt[j]);
1443 scores[1 * (y + 2) + (j + 1)] = j;
1444 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1447 targetCharCount = find(head, tgt[j-1])->value;
1448 swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1450 if (src[i-1] != tgt[j-1]){
1451 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));
1455 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1459 find(head, src[i-1])->value = i;
1463 IV score = scores[(x+1) * (y + 2) + (y + 1)];
1466 return (maxDistance != 0 && maxDistance < score)?(-1):score;
1470 /* END of edit_distance() stuff
1471 * ========================================================= */
1473 /* Mark that we cannot extend a found fixed substring at this point.
1474 Update the longest found anchored substring or the longest found
1475 floating substrings if needed. */
1478 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1479 SSize_t *minlenp, int is_inf)
1481 const STRLEN l = CHR_SVLEN(data->last_found);
1482 SV * const longest_sv = data->substrs[data->cur_is_floating].str;
1483 const STRLEN old_l = CHR_SVLEN(longest_sv);
1484 DECLARE_AND_GET_RE_DEBUG_FLAGS;
1486 PERL_ARGS_ASSERT_SCAN_COMMIT;
1488 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1489 const U8 i = data->cur_is_floating;
1490 SvSetMagicSV(longest_sv, data->last_found);
1491 data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
1494 data->substrs[0].max_offset = data->substrs[0].min_offset;
1496 data->substrs[1].max_offset =
1500 ? data->last_start_max
1501 /* temporary underflow guard for 5.32 */
1502 : data->pos_delta < 0 ? OPTIMIZE_INFTY
1503 : (data->pos_delta > OPTIMIZE_INFTY - data->pos_min
1505 : data->pos_min + data->pos_delta));
1508 data->substrs[i].flags &= ~SF_BEFORE_EOL;
1509 data->substrs[i].flags |= data->flags & SF_BEFORE_EOL;
1510 data->substrs[i].minlenp = minlenp;
1511 data->substrs[i].lookbehind = 0;
1514 SvCUR_set(data->last_found, 0);
1516 SV * const sv = data->last_found;
1517 if (SvUTF8(sv) && SvMAGICAL(sv)) {
1518 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1523 data->last_end = -1;
1524 data->flags &= ~SF_BEFORE_EOL;
1525 DEBUG_STUDYDATA("commit", data, 0, is_inf);
1528 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1529 * list that describes which code points it matches */
1532 S_ssc_anything(pTHX_ regnode_ssc *ssc)
1534 /* Set the SSC 'ssc' to match an empty string or any code point */
1536 PERL_ARGS_ASSERT_SSC_ANYTHING;
1538 assert(is_ANYOF_SYNTHETIC(ssc));
1540 /* mortalize so won't leak */
1541 ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
1542 ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING; /* Plus matches empty */
1546 S_ssc_is_anything(const regnode_ssc *ssc)
1548 /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1549 * point; FALSE otherwise. Thus, this is used to see if using 'ssc' buys
1550 * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1551 * in any way, so there's no point in using it */
1556 PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1558 assert(is_ANYOF_SYNTHETIC(ssc));
1560 if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1564 /* See if the list consists solely of the range 0 - Infinity */
1565 invlist_iterinit(ssc->invlist);
1566 ret = invlist_iternext(ssc->invlist, &start, &end)
1570 invlist_iterfinish(ssc->invlist);
1576 /* If e.g., both \w and \W are set, matches everything */
1577 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1579 for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1580 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1590 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1592 /* Initializes the SSC 'ssc'. This includes setting it to match an empty
1593 * string, any code point, or any posix class under locale */
1595 PERL_ARGS_ASSERT_SSC_INIT;
1597 Zero(ssc, 1, regnode_ssc);
1598 set_ANYOF_SYNTHETIC(ssc);
1599 ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1602 /* If any portion of the regex is to operate under locale rules that aren't
1603 * fully known at compile time, initialization includes it. The reason
1604 * this isn't done for all regexes is that the optimizer was written under
1605 * the assumption that locale was all-or-nothing. Given the complexity and
1606 * lack of documentation in the optimizer, and that there are inadequate
1607 * test cases for locale, many parts of it may not work properly, it is
1608 * safest to avoid locale unless necessary. */
1609 if (RExC_contains_locale) {
1610 ANYOF_POSIXL_SETALL(ssc);
1613 ANYOF_POSIXL_ZERO(ssc);
1618 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1619 const regnode_ssc *ssc)
1621 /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1622 * to the list of code points matched, and locale posix classes; hence does
1623 * not check its flags) */
1628 PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1630 assert(is_ANYOF_SYNTHETIC(ssc));
1632 invlist_iterinit(ssc->invlist);
1633 ret = invlist_iternext(ssc->invlist, &start, &end)
1637 invlist_iterfinish(ssc->invlist);
1643 if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1650 #define INVLIST_INDEX 0
1651 #define ONLY_LOCALE_MATCHES_INDEX 1
1652 #define DEFERRED_USER_DEFINED_INDEX 2
1655 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1656 const regnode_charclass* const node)
1658 /* Returns a mortal inversion list defining which code points are matched
1659 * by 'node', which is of type ANYOF. Handles complementing the result if
1660 * appropriate. If some code points aren't knowable at this time, the
1661 * returned list must, and will, contain every code point that is a
1666 SV* only_utf8_locale_invlist = NULL;
1668 const U32 n = ARG(node);
1669 bool new_node_has_latin1 = FALSE;
1670 const U8 flags = (inRANGE(OP(node), ANYOFH, ANYOFRb))
1672 : ANYOF_FLAGS(node);
1674 PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1676 /* Look at the data structure created by S_set_ANYOF_arg() */
1677 if (n != ANYOF_ONLY_HAS_BITMAP) {
1678 SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1679 AV * const av = MUTABLE_AV(SvRV(rv));
1680 SV **const ary = AvARRAY(av);
1681 assert(RExC_rxi->data->what[n] == 's');
1683 if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
1685 /* Here there are things that won't be known until runtime -- we
1686 * have to assume it could be anything */
1687 invlist = sv_2mortal(_new_invlist(1));
1688 return _add_range_to_invlist(invlist, 0, UV_MAX);
1690 else if (ary[INVLIST_INDEX]) {
1692 /* Use the node's inversion list */
1693 invlist = sv_2mortal(invlist_clone(ary[INVLIST_INDEX], NULL));
1696 /* Get the code points valid only under UTF-8 locales */
1697 if ( (flags & ANYOFL_FOLD)
1698 && av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX)
1700 only_utf8_locale_invlist = ary[ONLY_LOCALE_MATCHES_INDEX];
1705 invlist = sv_2mortal(_new_invlist(0));
1708 /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1709 * code points, and an inversion list for the others, but if there are code
1710 * points that should match only conditionally on the target string being
1711 * UTF-8, those are placed in the inversion list, and not the bitmap.
1712 * Since there are circumstances under which they could match, they are
1713 * included in the SSC. But if the ANYOF node is to be inverted, we have
1714 * to exclude them here, so that when we invert below, the end result
1715 * actually does include them. (Think about "\xe0" =~ /[^\xc0]/di;). We
1716 * have to do this here before we add the unconditionally matched code
1718 if (flags & ANYOF_INVERT) {
1719 _invlist_intersection_complement_2nd(invlist,
1724 /* Add in the points from the bit map */
1725 if (! inRANGE(OP(node), ANYOFH, ANYOFRb)) {
1726 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1727 if (ANYOF_BITMAP_TEST(node, i)) {
1728 unsigned int start = i++;
1730 for (; i < NUM_ANYOF_CODE_POINTS
1731 && ANYOF_BITMAP_TEST(node, i); ++i)
1735 invlist = _add_range_to_invlist(invlist, start, i-1);
1736 new_node_has_latin1 = TRUE;
1741 /* If this can match all upper Latin1 code points, have to add them
1742 * as well. But don't add them if inverting, as when that gets done below,
1743 * it would exclude all these characters, including the ones it shouldn't
1744 * that were added just above */
1745 if (! (flags & ANYOF_INVERT) && OP(node) == ANYOFD
1746 && (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1748 _invlist_union(invlist, PL_UpperLatin1, &invlist);
1751 /* Similarly for these */
1752 if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1753 _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1756 if (flags & ANYOF_INVERT) {
1757 _invlist_invert(invlist);
1759 else if (flags & ANYOFL_FOLD) {
1760 if (new_node_has_latin1) {
1762 /* Under /li, any 0-255 could fold to any other 0-255, depending on
1763 * the locale. We can skip this if there are no 0-255 at all. */
1764 _invlist_union(invlist, PL_Latin1, &invlist);
1766 invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I);
1767 invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
1770 if (_invlist_contains_cp(invlist, LATIN_SMALL_LETTER_DOTLESS_I)) {
1771 invlist = add_cp_to_invlist(invlist, 'I');
1773 if (_invlist_contains_cp(invlist,
1774 LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE))
1776 invlist = add_cp_to_invlist(invlist, 'i');
1781 /* Similarly add the UTF-8 locale possible matches. These have to be
1782 * deferred until after the non-UTF-8 locale ones are taken care of just
1783 * above, or it leads to wrong results under ANYOF_INVERT */
1784 if (only_utf8_locale_invlist) {
1785 _invlist_union_maybe_complement_2nd(invlist,
1786 only_utf8_locale_invlist,
1787 flags & ANYOF_INVERT,
1794 /* These two functions currently do the exact same thing */
1795 #define ssc_init_zero ssc_init
1797 #define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp))
1798 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1800 /* 'AND' a given class with another one. Can create false positives. 'ssc'
1801 * should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1802 * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1805 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1806 const regnode_charclass *and_with)
1808 /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1809 * another SSC or a regular ANYOF class. Can create false positives. */
1812 U8 and_with_flags = inRANGE(OP(and_with), ANYOFH, ANYOFRb)
1814 : ANYOF_FLAGS(and_with);
1817 PERL_ARGS_ASSERT_SSC_AND;
1819 assert(is_ANYOF_SYNTHETIC(ssc));
1821 /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1822 * the code point inversion list and just the relevant flags */
1823 if (is_ANYOF_SYNTHETIC(and_with)) {
1824 anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1825 anded_flags = and_with_flags;
1827 /* XXX This is a kludge around what appears to be deficiencies in the
1828 * optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag,
1829 * there are paths through the optimizer where it doesn't get weeded
1830 * out when it should. And if we don't make some extra provision for
1831 * it like the code just below, it doesn't get added when it should.
1832 * This solution is to add it only when AND'ing, which is here, and
1833 * only when what is being AND'ed is the pristine, original node
1834 * matching anything. Thus it is like adding it to ssc_anything() but
1835 * only when the result is to be AND'ed. Probably the same solution
1836 * could be adopted for the same problem we have with /l matching,
1837 * which is solved differently in S_ssc_init(), and that would lead to
1838 * fewer false positives than that solution has. But if this solution
1839 * creates bugs, the consequences are only that a warning isn't raised
1840 * that should be; while the consequences for having /l bugs is
1841 * incorrect matches */
1842 if (ssc_is_anything((regnode_ssc *)and_with)) {
1843 anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1847 anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1848 if (OP(and_with) == ANYOFD) {
1849 anded_flags = and_with_flags & ANYOF_COMMON_FLAGS;
1852 anded_flags = and_with_flags
1853 &( ANYOF_COMMON_FLAGS
1854 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1855 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1856 if (ANYOFL_UTF8_LOCALE_REQD(and_with_flags)) {
1858 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1863 ANYOF_FLAGS(ssc) &= anded_flags;
1865 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1866 * C2 is the list of code points in 'and-with'; P2, its posix classes.
1867 * 'and_with' may be inverted. When not inverted, we have the situation of
1869 * (C1 | P1) & (C2 | P2)
1870 * = (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1871 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1872 * <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2))
1873 * <= ((C1 & C2) | P1 | P2)
1874 * Alternatively, the last few steps could be:
1875 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1876 * <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2))
1877 * <= (C1 | C2 | (P1 & P2))
1878 * We favor the second approach if either P1 or P2 is non-empty. This is
1879 * because these components are a barrier to doing optimizations, as what
1880 * they match cannot be known until the moment of matching as they are
1881 * dependent on the current locale, 'AND"ing them likely will reduce or
1883 * But we can do better if we know that C1,P1 are in their initial state (a
1884 * frequent occurrence), each matching everything:
1885 * (<everything>) & (C2 | P2) = C2 | P2
1886 * Similarly, if C2,P2 are in their initial state (again a frequent
1887 * occurrence), the result is a no-op
1888 * (C1 | P1) & (<everything>) = C1 | P1
1891 * (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2)
1892 * = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1893 * <= (C1 & ~C2) | (P1 & ~P2)
1896 if ((and_with_flags & ANYOF_INVERT)
1897 && ! is_ANYOF_SYNTHETIC(and_with))
1901 ssc_intersection(ssc,
1903 FALSE /* Has already been inverted */
1906 /* If either P1 or P2 is empty, the intersection will be also; can skip
1908 if (! (and_with_flags & ANYOF_MATCHES_POSIXL)) {
1909 ANYOF_POSIXL_ZERO(ssc);
1911 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1913 /* Note that the Posix class component P from 'and_with' actually
1915 * P = Pa | Pb | ... | Pn
1916 * where each component is one posix class, such as in [\w\s].
1918 * ~P = ~(Pa | Pb | ... | Pn)
1919 * = ~Pa & ~Pb & ... & ~Pn
1920 * <= ~Pa | ~Pb | ... | ~Pn
1921 * The last is something we can easily calculate, but unfortunately
1922 * is likely to have many false positives. We could do better
1923 * in some (but certainly not all) instances if two classes in
1924 * P have known relationships. For example
1925 * :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1927 * :lower: & :print: = :lower:
1928 * And similarly for classes that must be disjoint. For example,
1929 * since \s and \w can have no elements in common based on rules in
1930 * the POSIX standard,
1931 * \w & ^\S = nothing
1932 * Unfortunately, some vendor locales do not meet the Posix
1933 * standard, in particular almost everything by Microsoft.
1934 * The loop below just changes e.g., \w into \W and vice versa */
1936 regnode_charclass_posixl temp;
1937 int add = 1; /* To calculate the index of the complement */
1939 Zero(&temp, 1, regnode_charclass_posixl);
1940 ANYOF_POSIXL_ZERO(&temp);
1941 for (i = 0; i < ANYOF_MAX; i++) {
1943 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1944 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1946 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1947 ANYOF_POSIXL_SET(&temp, i + add);
1949 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1951 ANYOF_POSIXL_AND(&temp, ssc);
1953 } /* else ssc already has no posixes */
1954 } /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC
1955 in its initial state */
1956 else if (! is_ANYOF_SYNTHETIC(and_with)
1957 || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1959 /* But if 'ssc' is in its initial state, the result is just 'and_with';
1960 * copy it over 'ssc' */
1961 if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1962 if (is_ANYOF_SYNTHETIC(and_with)) {
1963 StructCopy(and_with, ssc, regnode_ssc);
1966 ssc->invlist = anded_cp_list;
1967 ANYOF_POSIXL_ZERO(ssc);
1968 if (and_with_flags & ANYOF_MATCHES_POSIXL) {
1969 ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1973 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1974 || (and_with_flags & ANYOF_MATCHES_POSIXL))
1976 /* One or the other of P1, P2 is non-empty. */
1977 if (and_with_flags & ANYOF_MATCHES_POSIXL) {
1978 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1980 ssc_union(ssc, anded_cp_list, FALSE);
1982 else { /* P1 = P2 = empty */
1983 ssc_intersection(ssc, anded_cp_list, FALSE);
1989 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1990 const regnode_charclass *or_with)
1992 /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1993 * another SSC or a regular ANYOF class. Can create false positives if
1994 * 'or_with' is to be inverted. */
1998 U8 or_with_flags = inRANGE(OP(or_with), ANYOFH, ANYOFRb)
2000 : ANYOF_FLAGS(or_with);
2002 PERL_ARGS_ASSERT_SSC_OR;
2004 assert(is_ANYOF_SYNTHETIC(ssc));
2006 /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
2007 * the code point inversion list and just the relevant flags */
2008 if (is_ANYOF_SYNTHETIC(or_with)) {
2009 ored_cp_list = ((regnode_ssc*) or_with)->invlist;
2010 ored_flags = or_with_flags;
2013 ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
2014 ored_flags = or_with_flags & ANYOF_COMMON_FLAGS;
2015 if (OP(or_with) != ANYOFD) {
2018 & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2019 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
2020 if (ANYOFL_UTF8_LOCALE_REQD(or_with_flags)) {
2022 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
2027 ANYOF_FLAGS(ssc) |= ored_flags;
2029 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
2030 * C2 is the list of code points in 'or-with'; P2, its posix classes.
2031 * 'or_with' may be inverted. When not inverted, we have the simple
2032 * situation of computing:
2033 * (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2)
2034 * If P1|P2 yields a situation with both a class and its complement are
2035 * set, like having both \w and \W, this matches all code points, and we
2036 * can delete these from the P component of the ssc going forward. XXX We
2037 * might be able to delete all the P components, but I (khw) am not certain
2038 * about this, and it is better to be safe.
2041 * (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2)
2042 * <= (C1 | P1) | ~C2
2043 * <= (C1 | ~C2) | P1
2044 * (which results in actually simpler code than the non-inverted case)
2047 if ((or_with_flags & ANYOF_INVERT)
2048 && ! is_ANYOF_SYNTHETIC(or_with))
2050 /* We ignore P2, leaving P1 going forward */
2051 } /* else Not inverted */
2052 else if (or_with_flags & ANYOF_MATCHES_POSIXL) {
2053 ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
2054 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2056 for (i = 0; i < ANYOF_MAX; i += 2) {
2057 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
2059 ssc_match_all_cp(ssc);
2060 ANYOF_POSIXL_CLEAR(ssc, i);
2061 ANYOF_POSIXL_CLEAR(ssc, i+1);
2069 FALSE /* Already has been inverted */
2074 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
2076 PERL_ARGS_ASSERT_SSC_UNION;
2078 assert(is_ANYOF_SYNTHETIC(ssc));
2080 _invlist_union_maybe_complement_2nd(ssc->invlist,
2087 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
2089 const bool invert2nd)
2091 PERL_ARGS_ASSERT_SSC_INTERSECTION;
2093 assert(is_ANYOF_SYNTHETIC(ssc));
2095 _invlist_intersection_maybe_complement_2nd(ssc->invlist,
2102 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
2104 PERL_ARGS_ASSERT_SSC_ADD_RANGE;
2106 assert(is_ANYOF_SYNTHETIC(ssc));
2108 ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
2112 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
2114 /* AND just the single code point 'cp' into the SSC 'ssc' */
2116 SV* cp_list = _new_invlist(2);
2118 PERL_ARGS_ASSERT_SSC_CP_AND;
2120 assert(is_ANYOF_SYNTHETIC(ssc));
2122 cp_list = add_cp_to_invlist(cp_list, cp);
2123 ssc_intersection(ssc, cp_list,
2124 FALSE /* Not inverted */
2126 SvREFCNT_dec_NN(cp_list);
2130 S_ssc_clear_locale(regnode_ssc *ssc)
2132 /* Set the SSC 'ssc' to not match any locale things */
2133 PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
2135 assert(is_ANYOF_SYNTHETIC(ssc));
2137 ANYOF_POSIXL_ZERO(ssc);
2138 ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
2141 #define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
2144 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
2146 /* The synthetic start class is used to hopefully quickly winnow down
2147 * places where a pattern could start a match in the target string. If it
2148 * doesn't really narrow things down that much, there isn't much point to
2149 * having the overhead of using it. This function uses some very crude
2150 * heuristics to decide if to use the ssc or not.
2152 * It returns TRUE if 'ssc' rules out more than half what it considers to
2153 * be the "likely" possible matches, but of course it doesn't know what the
2154 * actual things being matched are going to be; these are only guesses
2156 * For /l matches, it assumes that the only likely matches are going to be
2157 * in the 0-255 range, uniformly distributed, so half of that is 127
2158 * For /a and /d matches, it assumes that the likely matches will be just
2159 * the ASCII range, so half of that is 63
2160 * For /u and there isn't anything matching above the Latin1 range, it
2161 * assumes that that is the only range likely to be matched, and uses
2162 * half that as the cut-off: 127. If anything matches above Latin1,
2163 * it assumes that all of Unicode could match (uniformly), except for
2164 * non-Unicode code points and things in the General Category "Other"
2165 * (unassigned, private use, surrogates, controls and formats). This
2166 * is a much large number. */
2168 U32 count = 0; /* Running total of number of code points matched by
2170 UV start, end; /* Start and end points of current range in inversion
2171 XXX outdated. UTF-8 locales are common, what about invert? list */
2172 const U32 max_code_points = (LOC)
2174 : (( ! UNI_SEMANTICS
2175 || invlist_highest(ssc->invlist) < 256)
2178 const U32 max_match = max_code_points / 2;
2180 PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
2182 invlist_iterinit(ssc->invlist);
2183 while (invlist_iternext(ssc->invlist, &start, &end)) {
2184 if (start >= max_code_points) {
2187 end = MIN(end, max_code_points - 1);
2188 count += end - start + 1;
2189 if (count >= max_match) {
2190 invlist_iterfinish(ssc->invlist);
2200 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
2202 /* The inversion list in the SSC is marked mortal; now we need a more
2203 * permanent copy, which is stored the same way that is done in a regular
2204 * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
2207 SV* invlist = invlist_clone(ssc->invlist, NULL);
2209 PERL_ARGS_ASSERT_SSC_FINALIZE;
2211 assert(is_ANYOF_SYNTHETIC(ssc));
2213 /* The code in this file assumes that all but these flags aren't relevant
2214 * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
2215 * by the time we reach here */
2216 assert(! (ANYOF_FLAGS(ssc)
2217 & ~( ANYOF_COMMON_FLAGS
2218 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2219 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
2221 populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
2223 set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist, NULL, NULL);
2224 SvREFCNT_dec(invlist);
2226 /* Make sure is clone-safe */
2227 ssc->invlist = NULL;
2229 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2230 ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
2231 OP(ssc) = ANYOFPOSIXL;
2233 else if (RExC_contains_locale) {
2237 assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
2240 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
2241 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
2242 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
2243 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \
2244 ? (TRIE_LIST_CUR( idx ) - 1) \
2250 dump_trie(trie,widecharmap,revcharmap)
2251 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
2252 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
2254 These routines dump out a trie in a somewhat readable format.
2255 The _interim_ variants are used for debugging the interim
2256 tables that are used to generate the final compressed
2257 representation which is what dump_trie expects.
2259 Part of the reason for their existence is to provide a form
2260 of documentation as to how the different representations function.
2265 Dumps the final compressed table form of the trie to Perl_debug_log.
2266 Used for debugging make_trie().
2270 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
2271 AV *revcharmap, U32 depth)
2274 SV *sv=sv_newmortal();
2275 int colwidth= widecharmap ? 6 : 4;
2277 DECLARE_AND_GET_RE_DEBUG_FLAGS;
2279 PERL_ARGS_ASSERT_DUMP_TRIE;
2281 Perl_re_indentf( aTHX_ "Char : %-6s%-6s%-4s ",
2282 depth+1, "Match","Base","Ofs" );
2284 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2285 SV ** const tmp = av_fetch( revcharmap, state, 0);
2287 Perl_re_printf( aTHX_ "%*s",
2289 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2290 PL_colors[0], PL_colors[1],
2291 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2292 PERL_PV_ESCAPE_FIRSTCHAR
2297 Perl_re_printf( aTHX_ "\n");
2298 Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
2300 for( state = 0 ; state < trie->uniquecharcount ; state++ )
2301 Perl_re_printf( aTHX_ "%.*s", colwidth, "--------");
2302 Perl_re_printf( aTHX_ "\n");
2304 for( state = 1 ; state < trie->statecount ; state++ ) {
2305 const U32 base = trie->states[ state ].trans.base;
2307 Perl_re_indentf( aTHX_ "#%4" UVXf "|", depth+1, (UV)state);
2309 if ( trie->states[ state ].wordnum ) {
2310 Perl_re_printf( aTHX_ " W%4X", trie->states[ state ].wordnum );
2312 Perl_re_printf( aTHX_ "%6s", "" );
2315 Perl_re_printf( aTHX_ " @%4" UVXf " ", (UV)base );
2320 while( ( base + ofs < trie->uniquecharcount ) ||
2321 ( base + ofs - trie->uniquecharcount < trie->lasttrans
2322 && trie->trans[ base + ofs - trie->uniquecharcount ].check
2326 Perl_re_printf( aTHX_ "+%2" UVXf "[ ", (UV)ofs);
2328 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2329 if ( ( base + ofs >= trie->uniquecharcount )
2330 && ( base + ofs - trie->uniquecharcount
2332 && trie->trans[ base + ofs
2333 - trie->uniquecharcount ].check == state )
2335 Perl_re_printf( aTHX_ "%*" UVXf, colwidth,
2336 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
2339 Perl_re_printf( aTHX_ "%*s", colwidth," ." );
2343 Perl_re_printf( aTHX_ "]");
2346 Perl_re_printf( aTHX_ "\n" );
2348 Perl_re_indentf( aTHX_ "word_info N:(prev,len)=",
2350 for (word=1; word <= trie->wordcount; word++) {
2351 Perl_re_printf( aTHX_ " %d:(%d,%d)",
2352 (int)word, (int)(trie->wordinfo[word].prev),
2353 (int)(trie->wordinfo[word].len));
2355 Perl_re_printf( aTHX_ "\n" );
2358 Dumps a fully constructed but uncompressed trie in list form.
2359 List tries normally only are used for construction when the number of
2360 possible chars (trie->uniquecharcount) is very high.
2361 Used for debugging make_trie().
2364 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2365 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2369 SV *sv=sv_newmortal();
2370 int colwidth= widecharmap ? 6 : 4;
2371 DECLARE_AND_GET_RE_DEBUG_FLAGS;
2373 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2375 /* print out the table precompression. */
2376 Perl_re_indentf( aTHX_ "State :Word | Transition Data\n",
2378 Perl_re_indentf( aTHX_ "%s",
2379 depth+1, "------:-----+-----------------\n" );
2381 for( state=1 ; state < next_alloc ; state ++ ) {
2384 Perl_re_indentf( aTHX_ " %4" UVXf " :",
2385 depth+1, (UV)state );
2386 if ( ! trie->states[ state ].wordnum ) {
2387 Perl_re_printf( aTHX_ "%5s| ","");
2389 Perl_re_printf( aTHX_ "W%4x| ",
2390 trie->states[ state ].wordnum
2393 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2394 SV ** const tmp = av_fetch( revcharmap,
2395 TRIE_LIST_ITEM(state, charid).forid, 0);
2397 Perl_re_printf( aTHX_ "%*s:%3X=%4" UVXf " | ",
2399 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2401 PL_colors[0], PL_colors[1],
2402 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2403 | PERL_PV_ESCAPE_FIRSTCHAR
2405 TRIE_LIST_ITEM(state, charid).forid,
2406 (UV)TRIE_LIST_ITEM(state, charid).newstate
2409 Perl_re_printf( aTHX_ "\n%*s| ",
2410 (int)((depth * 2) + 14), "");
2413 Perl_re_printf( aTHX_ "\n");
2418 Dumps a fully constructed but uncompressed trie in table form.
2419 This is the normal DFA style state transition table, with a few
2420 twists to facilitate compression later.
2421 Used for debugging make_trie().
2424 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2425 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2430 SV *sv=sv_newmortal();
2431 int colwidth= widecharmap ? 6 : 4;
2432 DECLARE_AND_GET_RE_DEBUG_FLAGS;
2434 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2437 print out the table precompression so that we can do a visual check
2438 that they are identical.
2441 Perl_re_indentf( aTHX_ "Char : ", depth+1 );
2443 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2444 SV ** const tmp = av_fetch( revcharmap, charid, 0);
2446 Perl_re_printf( aTHX_ "%*s",
2448 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2449 PL_colors[0], PL_colors[1],
2450 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2451 PERL_PV_ESCAPE_FIRSTCHAR
2457 Perl_re_printf( aTHX_ "\n");
2458 Perl_re_indentf( aTHX_ "State+-", depth+1 );
2460 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2461 Perl_re_printf( aTHX_ "%.*s", colwidth,"--------");
2464 Perl_re_printf( aTHX_ "\n" );
2466 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2468 Perl_re_indentf( aTHX_ "%4" UVXf " : ",
2470 (UV)TRIE_NODENUM( state ) );
2472 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2473 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2475 Perl_re_printf( aTHX_ "%*" UVXf, colwidth, v );
2477 Perl_re_printf( aTHX_ "%*s", colwidth, "." );
2479 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2480 Perl_re_printf( aTHX_ " (%4" UVXf ")\n",
2481 (UV)trie->trans[ state ].check );
2483 Perl_re_printf( aTHX_ " (%4" UVXf ") W%4X\n",
2484 (UV)trie->trans[ state ].check,
2485 trie->states[ TRIE_NODENUM( state ) ].wordnum );
2493 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2494 startbranch: the first branch in the whole branch sequence
2495 first : start branch of sequence of branch-exact nodes.
2496 May be the same as startbranch
2497 last : Thing following the last branch.
2498 May be the same as tail.
2499 tail : item following the branch sequence
2500 count : words in the sequence
2501 flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2502 depth : indent depth
2504 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2506 A trie is an N'ary tree where the branches are determined by digital
2507 decomposition of the key. IE, at the root node you look up the 1st character and
2508 follow that branch repeat until you find the end of the branches. Nodes can be
2509 marked as "accepting" meaning they represent a complete word. Eg:
2513 would convert into the following structure. Numbers represent states, letters
2514 following numbers represent valid transitions on the letter from that state, if
2515 the number is in square brackets it represents an accepting state, otherwise it
2516 will be in parenthesis.
2518 +-h->+-e->[3]-+-r->(8)-+-s->[9]
2522 (1) +-i->(6)-+-s->[7]
2524 +-s->(3)-+-h->(4)-+-e->[5]
2526 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2528 This shows that when matching against the string 'hers' we will begin at state 1
2529 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2530 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2531 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2532 single traverse. We store a mapping from accepting to state to which word was
2533 matched, and then when we have multiple possibilities we try to complete the
2534 rest of the regex in the order in which they occurred in the alternation.
2536 The only prior NFA like behaviour that would be changed by the TRIE support is
2537 the silent ignoring of duplicate alternations which are of the form:
2539 / (DUPE|DUPE) X? (?{ ... }) Y /x
2541 Thus EVAL blocks following a trie may be called a different number of times with
2542 and without the optimisation. With the optimisations dupes will be silently
2543 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2544 the following demonstrates:
2546 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2548 which prints out 'word' three times, but
2550 'words'=~/(word|word|word)(?{ print $1 })S/
2552 which doesnt print it out at all. This is due to other optimisations kicking in.
2554 Example of what happens on a structural level:
2556 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2558 1: CURLYM[1] {1,32767}(18)
2569 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2570 and should turn into:
2572 1: CURLYM[1] {1,32767}(18)
2574 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2582 Cases where tail != last would be like /(?foo|bar)baz/:
2592 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2593 and would end up looking like:
2596 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2603 d = uvchr_to_utf8_flags(d, uv, 0);
2605 is the recommended Unicode-aware way of saying
2610 #define TRIE_STORE_REVCHAR(val) \
2613 SV *zlopp = newSV(UTF8_MAXBYTES); \
2614 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
2615 unsigned char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
2617 SvCUR_set(zlopp, kapow - flrbbbbb); \
2620 av_push(revcharmap, zlopp); \
2622 char ooooff = (char)val; \
2623 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
2627 /* This gets the next character from the input, folding it if not already
2629 #define TRIE_READ_CHAR STMT_START { \
2632 /* if it is UTF then it is either already folded, or does not need \
2634 uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \
2636 else if (folder == PL_fold_latin1) { \
2637 /* This folder implies Unicode rules, which in the range expressible \
2638 * by not UTF is the lower case, with the two exceptions, one of \
2639 * which should have been taken care of before calling this */ \
2640 assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \
2641 uvc = toLOWER_L1(*uc); \
2642 if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \
2645 /* raw data, will be folded later if needed */ \
2653 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
2654 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
2655 U32 ging = TRIE_LIST_LEN( state ) * 2; \
2656 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2657 TRIE_LIST_LEN( state ) = ging; \
2659 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
2660 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
2661 TRIE_LIST_CUR( state )++; \
2664 #define TRIE_LIST_NEW(state) STMT_START { \
2665 Newx( trie->states[ state ].trans.list, \
2666 4, reg_trie_trans_le ); \
2667 TRIE_LIST_CUR( state ) = 1; \
2668 TRIE_LIST_LEN( state ) = 4; \
2671 #define TRIE_HANDLE_WORD(state) STMT_START { \
2672 U16 dupe= trie->states[ state ].wordnum; \
2673 regnode * const noper_next = regnext( noper ); \
2676 /* store the word for dumping */ \
2678 if (OP(noper) != NOTHING) \
2679 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
2681 tmp = newSVpvn_utf8( "", 0, UTF ); \
2682 av_push( trie_words, tmp ); \
2686 trie->wordinfo[curword].prev = 0; \
2687 trie->wordinfo[curword].len = wordlen; \
2688 trie->wordinfo[curword].accept = state; \
2690 if ( noper_next < tail ) { \
2692 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2694 trie->jump[curword] = (U16)(noper_next - convert); \
2696 jumper = noper_next; \
2698 nextbranch= regnext(cur); \
2702 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
2703 /* chain, so that when the bits of chain are later */\
2704 /* linked together, the dups appear in the chain */\
2705 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2706 trie->wordinfo[dupe].prev = curword; \
2708 /* we haven't inserted this word yet. */ \
2709 trie->states[ state ].wordnum = curword; \
2714 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
2715 ( ( base + charid >= ucharcount \
2716 && base + charid < ubound \
2717 && state == trie->trans[ base - ucharcount + charid ].check \
2718 && trie->trans[ base - ucharcount + charid ].next ) \
2719 ? trie->trans[ base - ucharcount + charid ].next \
2720 : ( state==1 ? special : 0 ) \
2723 #define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder) \
2725 TRIE_BITMAP_SET(trie, uvc); \
2726 /* store the folded codepoint */ \
2728 TRIE_BITMAP_SET(trie, folder[(U8) uvc ]); \
2731 /* store first byte of utf8 representation of */ \
2732 /* variant codepoints */ \
2733 if (! UVCHR_IS_INVARIANT(uvc)) { \
2734 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc)); \
2739 #define MADE_JUMP_TRIE 2
2740 #define MADE_EXACT_TRIE 4
2743 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2744 regnode *first, regnode *last, regnode *tail,
2745 U32 word_count, U32 flags, U32 depth)
2747 /* first pass, loop through and scan words */
2748 reg_trie_data *trie;
2749 HV *widecharmap = NULL;
2750 AV *revcharmap = newAV();
2756 regnode *jumper = NULL;
2757 regnode *nextbranch = NULL;
2758 regnode *convert = NULL;
2759 U32 *prev_states; /* temp array mapping each state to previous one */
2760 /* we just use folder as a flag in utf8 */
2761 const U8 * folder = NULL;
2763 /* in the below add_data call we are storing either 'tu' or 'tuaa'
2764 * which stands for one trie structure, one hash, optionally followed
2767 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
2768 AV *trie_words = NULL;
2769 /* along with revcharmap, this only used during construction but both are
2770 * useful during debugging so we store them in the struct when debugging.
2773 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2774 STRLEN trie_charcount=0;
2776 SV *re_trie_maxbuff;
2777 DECLARE_AND_GET_RE_DEBUG_FLAGS;
2779 PERL_ARGS_ASSERT_MAKE_TRIE;
2781 PERL_UNUSED_ARG(depth);
2785 case EXACT: case EXACT_REQ8: case EXACTL: break;
2789 case EXACTFLU8: folder = PL_fold_latin1; break;
2790 case EXACTF: folder = PL_fold; break;
2791 default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2794 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2796 trie->startstate = 1;
2797 trie->wordcount = word_count;
2798 RExC_rxi->data->data[ data_slot ] = (void*)trie;
2799 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2800 if (flags == EXACT || flags == EXACT_REQ8 || flags == EXACTL)
2801 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2802 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2803 trie->wordcount+1, sizeof(reg_trie_wordinfo));
2806 trie_words = newAV();
2809 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, GV_ADD);
2810 assert(re_trie_maxbuff);
2811 if (!SvIOK(re_trie_maxbuff)) {
2812 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2814 DEBUG_TRIE_COMPILE_r({
2815 Perl_re_indentf( aTHX_
2816 "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2818 REG_NODE_NUM(startbranch), REG_NODE_NUM(first),
2819 REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2822 /* Find the node we are going to overwrite */
2823 if ( first == startbranch && OP( last ) != BRANCH ) {
2824 /* whole branch chain */
2827 /* branch sub-chain */
2828 convert = NEXTOPER( first );
2831 /* -- First loop and Setup --
2833 We first traverse the branches and scan each word to determine if it
2834 contains widechars, and how many unique chars there are, this is
2835 important as we have to build a table with at least as many columns as we
2838 We use an array of integers to represent the character codes 0..255
2839 (trie->charmap) and we use a an HV* to store Unicode characters. We use
2840 the native representation of the character value as the key and IV's for
2843 *TODO* If we keep track of how many times each character is used we can
2844 remap the columns so that the table compression later on is more
2845 efficient in terms of memory by ensuring the most common value is in the
2846 middle and the least common are on the outside. IMO this would be better
2847 than a most to least common mapping as theres a decent chance the most
2848 common letter will share a node with the least common, meaning the node
2849 will not be compressible. With a middle is most common approach the worst
2850 case is when we have the least common nodes twice.
2854 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2855 regnode *noper = NEXTOPER( cur );
2859 U32 wordlen = 0; /* required init */
2860 STRLEN minchars = 0;
2861 STRLEN maxchars = 0;
2862 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2865 if (OP(noper) == NOTHING) {
2866 /* skip past a NOTHING at the start of an alternation
2867 * eg, /(?:)a|(?:b)/ should be the same as /a|b/
2869 * If the next node is not something we are supposed to process
2870 * we will just ignore it due to the condition guarding the
2874 regnode *noper_next= regnext(noper);
2875 if (noper_next < tail)
2880 && ( OP(noper) == flags
2881 || (flags == EXACT && OP(noper) == EXACT_REQ8)
2882 || (flags == EXACTFU && ( OP(noper) == EXACTFU_REQ8
2883 || OP(noper) == EXACTFUP))))
2885 uc= (U8*)STRING(noper);
2886 e= uc + STR_LEN(noper);
2893 if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2894 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2895 regardless of encoding */
2896 if (OP( noper ) == EXACTFUP) {
2897 /* false positives are ok, so just set this */
2898 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2902 for ( ; uc < e ; uc += len ) { /* Look at each char in the current
2904 TRIE_CHARCOUNT(trie)++;
2907 /* TRIE_READ_CHAR returns the current character, or its fold if /i
2908 * is in effect. Under /i, this character can match itself, or
2909 * anything that folds to it. If not under /i, it can match just
2910 * itself. Most folds are 1-1, for example k, K, and KELVIN SIGN
2911 * all fold to k, and all are single characters. But some folds
2912 * expand to more than one character, so for example LATIN SMALL
2913 * LIGATURE FFI folds to the three character sequence 'ffi'. If
2914 * the string beginning at 'uc' is 'ffi', it could be matched by
2915 * three characters, or just by the one ligature character. (It
2916 * could also be matched by two characters: LATIN SMALL LIGATURE FF
2917 * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2918 * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2919 * match.) The trie needs to know the minimum and maximum number
2920 * of characters that could match so that it can use size alone to
2921 * quickly reject many match attempts. The max is simple: it is
2922 * the number of folded characters in this branch (since a fold is
2923 * never shorter than what folds to it. */
2927 /* And the min is equal to the max if not under /i (indicated by
2928 * 'folder' being NULL), or there are no multi-character folds. If
2929 * there is a multi-character fold, the min is incremented just
2930 * once, for the character that folds to the sequence. Each
2931 * character in the sequence needs to be added to the list below of
2932 * characters in the trie, but we count only the first towards the
2933 * min number of characters needed. This is done through the
2934 * variable 'foldlen', which is returned by the macros that look
2935 * for these sequences as the number of bytes the sequence
2936 * occupies. Each time through the loop, we decrement 'foldlen' by
2937 * how many bytes the current char occupies. Only when it reaches
2938 * 0 do we increment 'minchars' or look for another multi-character
2940 if (folder == NULL) {
2943 else if (foldlen > 0) {
2944 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2949 /* See if *uc is the beginning of a multi-character fold. If
2950 * so, we decrement the length remaining to look at, to account
2951 * for the current character this iteration. (We can use 'uc'
2952 * instead of the fold returned by TRIE_READ_CHAR because for
2953 * non-UTF, the latin1_safe macro is smart enough to account
2954 * for all the unfolded characters, and because for UTF, the
2955 * string will already have been folded earlier in the
2956 * compilation process */
2958 if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2959 foldlen -= UTF8SKIP(uc);
2962 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2967 /* The current character (and any potential folds) should be added
2968 * to the possible matching characters for this position in this
2972 U8 folded= folder[ (U8) uvc ];
2973 if ( !trie->charmap[ folded ] ) {
2974 trie->charmap[ folded ]=( ++trie->uniquecharcount );
2975 TRIE_STORE_REVCHAR( folded );
2978 if ( !trie->charmap[ uvc ] ) {
2979 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2980 TRIE_STORE_REVCHAR( uvc );
2983 /* store the codepoint in the bitmap, and its folded
2985 TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
2986 set_bit = 0; /* We've done our bit :-) */
2990 /* XXX We could come up with the list of code points that fold
2991 * to this using PL_utf8_foldclosures, except not for
2992 * multi-char folds, as there may be multiple combinations
2993 * there that could work, which needs to wait until runtime to
2994 * resolve (The comment about LIGATURE FFI above is such an
2999 widecharmap = newHV();
3001 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
3004 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
3006 if ( !SvTRUE( *svpp ) ) {
3007 sv_setiv( *svpp, ++trie->uniquecharcount );
3008 TRIE_STORE_REVCHAR(uvc);
3011 } /* end loop through characters in this branch of the trie */
3013 /* We take the min and max for this branch and combine to find the min
3014 * and max for all branches processed so far */
3015 if( cur == first ) {
3016 trie->minlen = minchars;
3017 trie->maxlen = maxchars;
3018 } else if (minchars < trie->minlen) {
3019 trie->minlen = minchars;
3020 } else if (maxchars > trie->maxlen) {
3021 trie->maxlen = maxchars;
3023 } /* end first pass */
3024 DEBUG_TRIE_COMPILE_r(
3025 Perl_re_indentf( aTHX_
3026 "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
3028 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
3029 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
3030 (int)trie->minlen, (int)trie->maxlen )
3034 We now know what we are dealing with in terms of unique chars and
3035 string sizes so we can calculate how much memory a naive
3036 representation using a flat table will take. If it's over a reasonable
3037 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
3038 conservative but potentially much slower representation using an array
3041 At the end we convert both representations into the same compressed
3042 form that will be used in regexec.c for matching with. The latter
3043 is a form that cannot be used to construct with but has memory
3044 properties similar to the list form and access properties similar
3045 to the table form making it both suitable for fast searches and
3046 small enough that its feasable to store for the duration of a program.
3048 See the comment in the code where the compressed table is produced
3049 inplace from the flat tabe representation for an explanation of how
3050 the compression works.
3055 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
3058 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
3059 > SvIV(re_trie_maxbuff) )
3062 Second Pass -- Array Of Lists Representation
3064 Each state will be represented by a list of charid:state records
3065 (reg_trie_trans_le) the first such element holds the CUR and LEN
3066 points of the allocated array. (See defines above).
3068 We build the initial structure using the lists, and then convert
3069 it into the compressed table form which allows faster lookups
3070 (but cant be modified once converted).
3073 STRLEN transcount = 1;
3075 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using list compiler\n",
3078 trie->states = (reg_trie_state *)
3079 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3080 sizeof(reg_trie_state) );
3084 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3086 regnode *noper = NEXTOPER( cur );
3087 U32 state = 1; /* required init */
3088 U16 charid = 0; /* sanity init */
3089 U32 wordlen = 0; /* required init */
3091 if (OP(noper) == NOTHING) {
3092 regnode *noper_next= regnext(noper);
3093 if (noper_next < tail)
3095 /* we will undo this assignment if noper does not
3096 * point at a trieable type in the else clause of
3097 * the following statement. */
3101 && ( OP(noper) == flags
3102 || (flags == EXACT && OP(noper) == EXACT_REQ8)
3103 || (flags == EXACTFU && ( OP(noper) == EXACTFU_REQ8
3104 || OP(noper) == EXACTFUP))))
3106 const U8 *uc= (U8*)STRING(noper);
3107 const U8 *e= uc + STR_LEN(noper);
3109 for ( ; uc < e ; uc += len ) {
3114 charid = trie->charmap[ uvc ];
3116 SV** const svpp = hv_fetch( widecharmap,
3123 charid=(U16)SvIV( *svpp );
3126 /* charid is now 0 if we dont know the char read, or
3127 * nonzero if we do */
3134 if ( !trie->states[ state ].trans.list ) {
3135 TRIE_LIST_NEW( state );
3138 check <= TRIE_LIST_USED( state );
3141 if ( TRIE_LIST_ITEM( state, check ).forid
3144 newstate = TRIE_LIST_ITEM( state, check ).newstate;
3149 newstate = next_alloc++;
3150 prev_states[newstate] = state;
3151 TRIE_LIST_PUSH( state, charid, newstate );
3156 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3160 /* If we end up here it is because we skipped past a NOTHING, but did not end up
3161 * on a trieable type. So we need to reset noper back to point at the first regop
3162 * in the branch before we call TRIE_HANDLE_WORD()
3164 noper= NEXTOPER(cur);
3166 TRIE_HANDLE_WORD(state);
3168 } /* end second pass */
3170 /* next alloc is the NEXT state to be allocated */
3171 trie->statecount = next_alloc;
3172 trie->states = (reg_trie_state *)
3173 PerlMemShared_realloc( trie->states,
3175 * sizeof(reg_trie_state) );
3177 /* and now dump it out before we compress it */
3178 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
3179 revcharmap, next_alloc,
3183 trie->trans = (reg_trie_trans *)
3184 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
3191 for( state=1 ; state < next_alloc ; state ++ ) {
3195 DEBUG_TRIE_COMPILE_MORE_r(
3196 Perl_re_printf( aTHX_ "tp: %d zp: %d ",tp,zp)
3200 if (trie->states[state].trans.list) {
3201 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
3205 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3206 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
3207 if ( forid < minid ) {
3209 } else if ( forid > maxid ) {
3213 if ( transcount < tp + maxid - minid + 1) {
3215 trie->trans = (reg_trie_trans *)
3216 PerlMemShared_realloc( trie->trans,
3218 * sizeof(reg_trie_trans) );
3219 Zero( trie->trans + (transcount / 2),
3223 base = trie->uniquecharcount + tp - minid;
3224 if ( maxid == minid ) {
3226 for ( ; zp < tp ; zp++ ) {
3227 if ( ! trie->trans[ zp ].next ) {
3228 base = trie->uniquecharcount + zp - minid;
3229 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
3231 trie->trans[ zp ].check = state;
3237 trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
3239 trie->trans[ tp ].check = state;
3244 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3245 const U32 tid = base
3246 - trie->uniquecharcount
3247 + TRIE_LIST_ITEM( state, idx ).forid;
3248 trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
3250 trie->trans[ tid ].check = state;
3252 tp += ( maxid - minid + 1 );
3254 Safefree(trie->states[ state ].trans.list);
3257 DEBUG_TRIE_COMPILE_MORE_r(
3258 Perl_re_printf( aTHX_ " base: %d\n",base);
3261 trie->states[ state ].trans.base=base;
3263 trie->lasttrans = tp + 1;
3267 Second Pass -- Flat Table Representation.
3269 we dont use the 0 slot of either trans[] or states[] so we add 1 to
3270 each. We know that we will need Charcount+1 trans at most to store
3271 the data (one row per char at worst case) So we preallocate both
3272 structures assuming worst case.
3274 We then construct the trie using only the .next slots of the entry
3277 We use the .check field of the first entry of the node temporarily
3278 to make compression both faster and easier by keeping track of how
3279 many non zero fields are in the node.
3281 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
3284 There are two terms at use here: state as a TRIE_NODEIDX() which is
3285 a number representing the first entry of the node, and state as a
3286 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
3287 and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
3288 if there are 2 entrys per node. eg:
3296 The table is internally in the right hand, idx form. However as we
3297 also have to deal with the states array which is indexed by nodenum
3298 we have to use TRIE_NODENUM() to convert.
3301 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using table compiler\n",
3304 trie->trans = (reg_trie_trans *)
3305 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
3306 * trie->uniquecharcount + 1,
3307 sizeof(reg_trie_trans) );
3308 trie->states = (reg_trie_state *)
3309 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3310 sizeof(reg_trie_state) );
3311 next_alloc = trie->uniquecharcount + 1;
3314 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3316 regnode *noper = NEXTOPER( cur );
3318 U32 state = 1; /* required init */
3320 U16 charid = 0; /* sanity init */
3321 U32 accept_state = 0; /* sanity init */
3323 U32 wordlen = 0; /* required init */
3325 if (OP(noper) == NOTHING) {
3326 regnode *noper_next= regnext(noper);
3327 if (noper_next < tail)
3329 /* we will undo this assignment if noper does not
3330 * point at a trieable type in the else clause of
3331 * the following statement. */
3335 && ( OP(noper) == flags
3336 || (flags == EXACT && OP(noper) == EXACT_REQ8)
3337 || (flags == EXACTFU && ( OP(noper) == EXACTFU_REQ8
3338 || OP(noper) == EXACTFUP))))
3340 const U8 *uc= (U8*)STRING(noper);
3341 const U8 *e= uc + STR_LEN(noper);
3343 for ( ; uc < e ; uc += len ) {
3348 charid = trie->charmap[ uvc ];
3350 SV* const * const svpp = hv_fetch( widecharmap,
3354 charid = svpp ? (U16)SvIV(*svpp) : 0;
3358 if ( !trie->trans[ state + charid ].next ) {
3359 trie->trans[ state + charid ].next = next_alloc;
3360 trie->trans[ state ].check++;
3361 prev_states[TRIE_NODENUM(next_alloc)]
3362 = TRIE_NODENUM(state);
3363 next_alloc += trie->uniquecharcount;
3365 state = trie->trans[ state + charid ].next;
3367 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3369 /* charid is now 0 if we dont know the char read, or
3370 * nonzero if we do */
3373 /* If we end up here it is because we skipped past a NOTHING, but did not end up
3374 * on a trieable type. So we need to reset noper back to point at the first regop
3375 * in the branch before we call TRIE_HANDLE_WORD().
3377 noper= NEXTOPER(cur);
3379 accept_state = TRIE_NODENUM( state );
3380 TRIE_HANDLE_WORD(accept_state);
3382 } /* end second pass */
3384 /* and now dump it out before we compress it */
3385 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3387 next_alloc, depth+1));
3391 * Inplace compress the table.*
3393 For sparse data sets the table constructed by the trie algorithm will
3394 be mostly 0/FAIL transitions or to put it another way mostly empty.
3395 (Note that leaf nodes will not contain any transitions.)
3397 This algorithm compresses the tables by eliminating most such
3398 transitions, at the cost of a modest bit of extra work during lookup:
3400 - Each states[] entry contains a .base field which indicates the
3401 index in the state[] array wheres its transition data is stored.
3403 - If .base is 0 there are no valid transitions from that node.
3405 - If .base is nonzero then charid is added to it to find an entry in
3408 -If trans[states[state].base+charid].check!=state then the
3409 transition is taken to be a 0/Fail transition. Thus if there are fail
3410 transitions at the front of the node then the .base offset will point
3411 somewhere inside the previous nodes data (or maybe even into a node
3412 even earlier), but the .check field determines if the transition is
3416 The following process inplace converts the table to the compressed
3417 table: We first do not compress the root node 1,and mark all its
3418 .check pointers as 1 and set its .base pointer as 1 as well. This
3419 allows us to do a DFA construction from the compressed table later,
3420 and ensures that any .base pointers we calculate later are greater
3423 - We set 'pos' to indicate the first entry of the second node.
3425 - We then iterate over the columns of the node, finding the first and
3426 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3427 and set the .check pointers accordingly, and advance pos
3428 appropriately and repreat for the next node. Note that when we copy
3429 the next pointers we have to convert them from the original
3430 NODEIDX form to NODENUM form as the former is not valid post
3433 - If a node has no transitions used we mark its base as 0 and do not
3434 advance the pos pointer.
3436 - If a node only has one transition we use a second pointer into the
3437 structure to fill in allocated fail transitions from other states.
3438 This pointer is independent of the main pointer and scans forward
3439 looking for null transitions that are allocated to a state. When it
3440 finds one it writes the single transition into the "hole". If the
3441 pointer doesnt find one the single transition is appended as normal.
3443 - Once compressed we can Renew/realloc the structures to release the
3446 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3447 specifically Fig 3.47 and the associated pseudocode.
3451 const U32 laststate = TRIE_NODENUM( next_alloc );
3454 trie->statecount = laststate;
3456 for ( state = 1 ; state < laststate ; state++ ) {
3458 const U32 stateidx = TRIE_NODEIDX( state );
3459 const U32 o_used = trie->trans[ stateidx ].check;
3460 U32 used = trie->trans[ stateidx ].check;
3461 trie->trans[ stateidx ].check = 0;
3464 used && charid < trie->uniquecharcount;
3467 if ( flag || trie->trans[ stateidx + charid ].next ) {
3468 if ( trie->trans[ stateidx + charid ].next ) {
3470 for ( ; zp < pos ; zp++ ) {
3471 if ( ! trie->trans[ zp ].next ) {
3475 trie->states[ state ].trans.base
3477 + trie->uniquecharcount
3479 trie->trans[ zp ].next
3480 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3482 trie->trans[ zp ].check = state;
3483 if ( ++zp > pos ) pos = zp;
3490 trie->states[ state ].trans.base
3491 = pos + trie->uniquecharcount - charid ;
3493 trie->trans[ pos ].next
3494 = SAFE_TRIE_NODENUM(
3495 trie->trans[ stateidx + charid ].next );
3496 trie->trans[ pos ].check = state;
3501 trie->lasttrans = pos + 1;
3502 trie->states = (reg_trie_state *)
3503 PerlMemShared_realloc( trie->states, laststate
3504 * sizeof(reg_trie_state) );
3505 DEBUG_TRIE_COMPILE_MORE_r(
3506 Perl_re_indentf( aTHX_ "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
3508 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3512 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3515 } /* end table compress */
3517 DEBUG_TRIE_COMPILE_MORE_r(
3518 Perl_re_indentf( aTHX_ "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
3520 (UV)trie->statecount,
3521 (UV)trie->lasttrans)
3523 /* resize the trans array to remove unused space */
3524 trie->trans = (reg_trie_trans *)
3525 PerlMemShared_realloc( trie->trans, trie->lasttrans
3526 * sizeof(reg_trie_trans) );
3528 { /* Modify the program and insert the new TRIE node */
3529 U8 nodetype =(U8)(flags & 0xFF);
3533 regnode *optimize = NULL;
3534 #ifdef RE_TRACK_PATTERN_OFFSETS
3537 U32 mjd_nodelen = 0;
3538 #endif /* RE_TRACK_PATTERN_OFFSETS */
3539 #endif /* DEBUGGING */
3541 This means we convert either the first branch or the first Exact,
3542 depending on whether the thing following (in 'last') is a branch
3543 or not and whther first is the startbranch (ie is it a sub part of
3544 the alternation or is it the whole thing.)
3545 Assuming its a sub part we convert the EXACT otherwise we convert
3546 the whole branch sequence, including the first.
3548 /* Find the node we are going to overwrite */
3549 if ( first != startbranch || OP( last ) == BRANCH ) {
3550 /* branch sub-chain */
3551 NEXT_OFF( first ) = (U16)(last - first);
3552 #ifdef RE_TRACK_PATTERN_OFFSETS
3554 mjd_offset= Node_Offset((convert));
3555 mjd_nodelen= Node_Length((convert));
3558 /* whole branch chain */
3560 #ifdef RE_TRACK_PATTERN_OFFSETS
3563 const regnode *nop = NEXTOPER( convert );
3564 mjd_offset= Node_Offset((nop));
3565 mjd_nodelen= Node_Length((nop));
3569 Perl_re_indentf( aTHX_ "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
3571 (UV)mjd_offset, (UV)mjd_nodelen)
3574 /* But first we check to see if there is a common prefix we can
3575 split out as an EXACT and put in front of the TRIE node. */
3576 trie->startstate= 1;
3577 if ( trie->bitmap && !widecharmap && !trie->jump ) {
3578 /* we want to find the first state that has more than
3579 * one transition, if that state is not the first state
3580 * then we have a common prefix which we can remove.
3583 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3585 I32 first_ofs = -1; /* keeps track of the ofs of the first
3586 transition, -1 means none */
3588 const U32 base = trie->states[ state ].trans.base;
3590 /* does this state terminate an alternation? */
3591 if ( trie->states[state].wordnum )
3594 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3595 if ( ( base + ofs >= trie->uniquecharcount ) &&
3596 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3597 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3599 if ( ++count > 1 ) {
3600 /* we have more than one transition */
3603 /* if this is the first state there is no common prefix
3604 * to extract, so we can exit */
3605 if ( state == 1 ) break;
3606 tmp = av_fetch( revcharmap, ofs, 0);
3607 ch = (U8*)SvPV_nolen_const( *tmp );
3609 /* if we are on count 2 then we need to initialize the
3610 * bitmap, and store the previous char if there was one
3613 /* clear the bitmap */
3614 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3616 Perl_re_indentf( aTHX_ "New Start State=%" UVuf " Class: [",
3619 if (first_ofs >= 0) {
3620 SV ** const tmp = av_fetch( revcharmap, first_ofs, 0);
3621 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3623 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3625 Perl_re_printf( aTHX_ "%s", (char*)ch)
3629 /* store the current firstchar in the bitmap */
3630 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3631 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch));
3637 /* This state has only one transition, its transition is part
3638 * of a common prefix - we need to concatenate the char it
3639 * represents to what we have so far. */
3640 SV **tmp = av_fetch( revcharmap, first_ofs, 0);
3642 char *ch = SvPV( *tmp, len );
3644 SV *sv=sv_newmortal();
3645 Perl_re_indentf( aTHX_ "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n",
3647 (UV)state, (UV)first_ofs,
3648 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3649 PL_colors[0], PL_colors[1],
3650 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3651 PERL_PV_ESCAPE_FIRSTCHAR
3656 OP( convert ) = nodetype;
3657 str=STRING(convert);
3658 setSTR_LEN(convert, 0);
3660 assert( ( STR_LEN(convert) + len ) < 256 );
3661 setSTR_LEN(convert, (U8)(STR_LEN(convert) + len));
3667 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n"));
3672 trie->prefixlen = (state-1);
3674 regnode *n = convert+NODE_SZ_STR(convert);
3675 assert( NODE_SZ_STR(convert) <= U16_MAX );
3676 NEXT_OFF(convert) = (U16)(NODE_SZ_STR(convert));
3677 trie->startstate = state;
3678 trie->minlen -= (state - 1);
3679 trie->maxlen -= (state - 1);
3681 /* At least the UNICOS C compiler choked on this
3682 * being argument to DEBUG_r(), so let's just have
3685 #ifdef PERL_EXT_RE_BUILD
3691 regnode *fix = convert;
3692 U32 word = trie->wordcount;
3693 #ifdef RE_TRACK_PATTERN_OFFSETS
3696 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3697 while( ++fix < n ) {
3698 Set_Node_Offset_Length(fix, 0, 0);
3701 SV ** const tmp = av_fetch( trie_words, word, 0 );
3703 if ( STR_LEN(convert) <= SvCUR(*tmp) )
3704 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3706 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3714 NEXT_OFF(convert) = (U16)(tail - convert);
3715 DEBUG_r(optimize= n);
3721 if ( trie->maxlen ) {
3722 NEXT_OFF( convert ) = (U16)(tail - convert);
3723 ARG_SET( convert, data_slot );
3724 /* Store the offset to the first unabsorbed branch in
3725 jump[0], which is otherwise unused by the jump logic.
3726 We use this when dumping a trie and during optimisation. */
3728 trie->jump[0] = (U16)(nextbranch - convert);
3730 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3731 * and there is a bitmap
3732 * and the first "jump target" node we found leaves enough room
3733 * then convert the TRIE node into a TRIEC node, with the bitmap
3734 * embedded inline in the opcode - this is hypothetically faster.
3736 if ( !trie->states[trie->startstate].wordnum
3738 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3740 OP( convert ) = TRIEC;
3741 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3742 PerlMemShared_free(trie->bitmap);
3745 OP( convert ) = TRIE;
3747 /* store the type in the flags */
3748 convert->flags = nodetype;
3752 + regarglen[ OP( convert ) ];
3754 /* XXX We really should free up the resource in trie now,
3755 as we won't use them - (which resources?) dmq */
3757 /* needed for dumping*/
3758 DEBUG_r(if (optimize) {
3759 regnode *opt = convert;
3761 while ( ++opt < optimize) {
3762 Set_Node_Offset_Length(opt, 0, 0);
3765 Try to clean up some of the debris left after the
3768 while( optimize < jumper ) {
3769 Track_Code( mjd_nodelen += Node_Length((optimize)); );
3770 OP( optimize ) = OPTIMIZED;
3771 Set_Node_Offset_Length(optimize, 0, 0);
3774 Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen);
3776 } /* end node insert */
3778 /* Finish populating the prev field of the wordinfo array. Walk back
3779 * from each accept state until we find another accept state, and if
3780 * so, point the first word's .prev field at the second word. If the
3781 * second already has a .prev field set, stop now. This will be the
3782 * case either if we've already processed that word's accept state,
3783 * or that state had multiple words, and the overspill words were
3784 * already linked up earlier.
3791 for (word=1; word <= trie->wordcount; word++) {
3793 if (trie->wordinfo[word].prev)
3795 state = trie->wordinfo[word].accept;
3797 state = prev_states[state];
3800 prev = trie->states[state].wordnum;
3804 trie->wordinfo[word].prev = prev;
3806 Safefree(prev_states);
3810 /* and now dump out the compressed format */
3811 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3813 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3815 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3816 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3818 SvREFCNT_dec_NN(revcharmap);
3822 : trie->startstate>1
3828 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3830 /* The Trie is constructed and compressed now so we can build a fail array if
3833 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3835 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3839 We find the fail state for each state in the trie, this state is the longest
3840 proper suffix of the current state's 'word' that is also a proper prefix of
3841 another word in our trie. State 1 represents the word '' and is thus the
3842 default fail state. This allows the DFA not to have to restart after its
3843 tried and failed a word at a given point, it simply continues as though it
3844 had been matching the other word in the first place.
3846 'abcdgu'=~/abcdefg|cdgu/
3847 When we get to 'd' we are still matching the first word, we would encounter
3848 'g' which would fail, which would bring us to the state representing 'd' in
3849 the second word where we would try 'g' and succeed, proceeding to match
3852 /* add a fail transition */
3853 const U32 trie_offset = ARG(source);
3854 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3856 const U32 ucharcount = trie->uniquecharcount;
3857 const U32 numstates = trie->statecount;
3858 const U32 ubound = trie->lasttrans + ucharcount;
3862 U32 base = trie->states[ 1 ].trans.base;
3865 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3867 DECLARE_AND_GET_RE_DEBUG_FLAGS;
3869 PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3870 PERL_UNUSED_CONTEXT;
3872 PERL_UNUSED_ARG(depth);
3875 if ( OP(source) == TRIE ) {
3876 struct regnode_1 *op = (struct regnode_1 *)
3877 PerlMemShared_calloc(1, sizeof(struct regnode_1));
3878 StructCopy(source, op, struct regnode_1);
3879 stclass = (regnode *)op;
3881 struct regnode_charclass *op = (struct regnode_charclass *)
3882 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3883 StructCopy(source, op, struct regnode_charclass);
3884 stclass = (regnode *)op;
3886 OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3888 ARG_SET( stclass, data_slot );
3889 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3890 RExC_rxi->data->data[ data_slot ] = (void*)aho;
3891 aho->trie=trie_offset;
3892 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3893 Copy( trie->states, aho->states, numstates, reg_trie_state );
3894 Newx( q, numstates, U32);
3895 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3898 /* initialize fail[0..1] to be 1 so that we always have
3899 a valid final fail state */
3900 fail[ 0 ] = fail[ 1 ] = 1;
3902 for ( charid = 0; charid < ucharcount ; charid++ ) {
3903 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3905 q[ q_write ] = newstate;
3906 /* set to point at the root */
3907 fail[ q[ q_write++ ] ]=1;
3910 while ( q_read < q_write) {
3911 const U32 cur = q[ q_read++ % numstates ];
3912 base = trie->states[ cur ].trans.base;
3914 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3915 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3917 U32 fail_state = cur;
3920 fail_state = fail[ fail_state ];
3921 fail_base = aho->states[ fail_state ].trans.base;
3922 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3924 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3925 fail[ ch_state ] = fail_state;
3926 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3928 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
3930 q[ q_write++ % numstates] = ch_state;
3934 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3935 when we fail in state 1, this allows us to use the
3936 charclass scan to find a valid start char. This is based on the principle
3937 that theres a good chance the string being searched contains lots of stuff
3938 that cant be a start char.
3940 fail[ 0 ] = fail[ 1 ] = 0;
3941 DEBUG_TRIE_COMPILE_r({
3942 Perl_re_indentf( aTHX_ "Stclass Failtable (%" UVuf " states): 0",
3943 depth, (UV)numstates
3945 for( q_read=1; q_read<numstates; q_read++ ) {
3946 Perl_re_printf( aTHX_ ", %" UVuf, (UV)fail[q_read]);
3948 Perl_re_printf( aTHX_ "\n");
3951 /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3956 /* The below joins as many adjacent EXACTish nodes as possible into a single
3957 * one. The regop may be changed if the node(s) contain certain sequences that
3958 * require special handling. The joining is only done if:
3959 * 1) there is room in the current conglomerated node to entirely contain the
3961 * 2) they are compatible node types
3963 * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3964 * these get optimized out
3966 * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3967 * as possible, even if that means splitting an existing node so that its first
3968 * part is moved to the preceeding node. This would maximise the efficiency of
3969 * memEQ during matching.
3971 * If a node is to match under /i (folded), the number of characters it matches
3972 * can be different than its character length if it contains a multi-character
3973 * fold. *min_subtract is set to the total delta number of characters of the
3976 * And *unfolded_multi_char is set to indicate whether or not the node contains
3977 * an unfolded multi-char fold. This happens when it won't be known until
3978 * runtime whether the fold is valid or not; namely
3979 * 1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the
3980 * target string being matched against turns out to be UTF-8 is that fold
3982 * 2) for EXACTFL nodes whose folding rules depend on the locale in force at
3984 * (Multi-char folds whose components are all above the Latin1 range are not
3985 * run-time locale dependent, and have already been folded by the time this
3986 * function is called.)
3988 * This is as good a place as any to discuss the design of handling these
3989 * multi-character fold sequences. It's been wrong in Perl for a very long
3990 * time. There are three code points in Unicode whose multi-character folds
3991 * were long ago discovered to mess things up. The previous designs for
3992 * dealing with these involved assigning a special node for them. This
3993 * approach doesn't always work, as evidenced by this example:
3994 * "\xDFs" =~ /s\xDF/ui # Used to fail before these patches
3995 * Both sides fold to "sss", but if the pattern is parsed to create a node that
3996 * would match just the \xDF, it won't be able to handle the case where a
3997 * successful match would have to cross the node's boundary. The new approach
3998 * that hopefully generally solves the problem generates an EXACTFUP node
3999 * that is "sss" in this case.
4001 * It turns out that there are problems with all multi-character folds, and not
4002 * just these three. Now the code is general, for all such cases. The
4003 * approach taken is:
4004 * 1) This routine examines each EXACTFish node that could contain multi-
4005 * character folded sequences. Since a single character can fold into
4006 * such a sequence, the minimum match length for this node is less than
4007 * the number of characters in the node. This routine returns in
4008 * *min_subtract how many characters to subtract from the actual
4009 * length of the string to get a real minimum match length; it is 0 if
4010 * there are no multi-char foldeds. This delta is used by the caller to
4011 * adjust the min length of the match, and the delta between min and max,
4012 * so that the optimizer doesn't reject these possibilities based on size
4015 * 2) For the sequence involving the LATIN SMALL LETTER SHARP S (U+00DF)
4016 * under /u, we fold it to 'ss' in regatom(), and in this routine, after
4017 * joining, we scan for occurrences of the sequence 'ss' in non-UTF-8
4018 * EXACTFU nodes. The node type of such nodes is then changed to
4019 * EXACTFUP, indicating it is problematic, and needs careful handling.
4020 * (The procedures in step 1) above are sufficient to handle this case in
4021 * UTF-8 encoded nodes.) The reason this is problematic is that this is
4022 * the only case where there is a possible fold length change in non-UTF-8
4023 * patterns. By reserving a special node type for problematic cases, the
4024 * far more common regular EXACTFU nodes can be processed faster.
4025 * regexec.c takes advantage of this.
4027 * EXACTFUP has been created as a grab-bag for (hopefully uncommon)
4028 * problematic cases. These all only occur when the pattern is not
4029 * UTF-8. In addition to the 'ss' sequence where there is a possible fold
4030 * length change, it handles the situation where the string cannot be
4031 * entirely folded. The strings in an EXACTFish node are folded as much
4032 * as possible during compilation in regcomp.c. This saves effort in
4033 * regex matching. By using an EXACTFUP node when it is not possible to
4034 * fully fold at compile time, regexec.c can know that everything in an
4035 * EXACTFU node is folded, so folding can be skipped at runtime. The only
4036 * case where folding in EXACTFU nodes can't be done at compile time is
4037 * the presumably uncommon MICRO SIGN, when the pattern isn't UTF-8. This
4038 * is because its fold requires UTF-8 to represent. Thus EXACTFUP nodes
4039 * handle two very different cases. Alternatively, there could have been
4040 * a node type where there are length changes, one for unfolded, and one
4041 * for both. If yet another special case needed to be created, the number
4042 * of required node types would have to go to 7. khw figures that even
4043 * though there are plenty of node types to spare, that the maintenance
4044 * cost wasn't worth the small speedup of doing it that way, especially
4045 * since he thinks the MICRO SIGN is rarely encountered in practice.
4047 * There are other cases where folding isn't done at compile time, but
4048 * none of them are under /u, and hence not for EXACTFU nodes. The folds
4049 * in EXACTFL nodes aren't known until runtime, and vary as the locale
4050 * changes. Some folds in EXACTF depend on if the runtime target string
4051 * is UTF-8 or not. (regatom() will create an EXACTFU node even under /di
4052 * when no fold in it depends on the UTF-8ness of the target string.)
4054 * 3) A problem remains for unfolded multi-char folds. (These occur when the
4055 * validity of the fold won't be known until runtime, and so must remain
4056 * unfolded for now. This happens for the sharp s in EXACTF and EXACTFAA
4057 * nodes when the pattern isn't in UTF-8. (Note, BTW, that there cannot
4058 * be an EXACTF node with a UTF-8 pattern.) They also occur for various
4059 * folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
4060 * The reason this is a problem is that the optimizer part of regexec.c
4061 * (probably unwittingly, in Perl_regexec_flags()) makes an assumption
4062 * that a character in the pattern corresponds to at most a single
4063 * character in the target string. (And I do mean character, and not byte
4064 * here, unlike other parts of the documentation that have never been
4065 * updated to account for multibyte Unicode.) Sharp s in EXACTF and
4066 * EXACTFL nodes can match the two character string 'ss'; in EXACTFAA
4067 * nodes it can match "\x{17F}\x{17F}". These, along with other ones in
4068 * EXACTFL nodes, violate the assumption, and they are the only instances
4069 * where it is violated. I'm reluctant to try to change the assumption,
4070 * as the code involved is impenetrable to me (khw), so instead the code
4071 * here punts. This routine examines EXACTFL nodes, and (when the pattern
4072 * isn't UTF-8) EXACTF and EXACTFAA for such unfolded folds, and returns a
4073 * boolean indicating whether or not the node contains such a fold. When
4074 * it is true, the caller sets a flag that later causes the optimizer in
4075 * this file to not set values for the floating and fixed string lengths,
4076 * and thus avoids the optimizer code in regexec.c that makes the invalid
4077 * assumption. Thus, there is no optimization based on string lengths for
4078 * EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
4079 * EXACTF and EXACTFAA nodes that contain the sharp s. (The reason the
4080 * assumption is wrong only in these cases is that all other non-UTF-8
4081 * folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
4082 * their expanded versions. (Again, we can't prefold sharp s to 'ss' in
4083 * EXACTF nodes because we don't know at compile time if it actually
4084 * matches 'ss' or not. For EXACTF nodes it will match iff the target
4085 * string is in UTF-8. This is in contrast to EXACTFU nodes, where it
4086 * always matches; and EXACTFAA where it never does. In an EXACTFAA node
4087 * in a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
4088 * problem; but in a non-UTF8 pattern, folding it to that above-Latin1
4089 * string would require the pattern to be forced into UTF-8, the overhead
4090 * of which we want to avoid. Similarly the unfolded multi-char folds in
4091 * EXACTFL nodes will match iff the locale at the time of match is a UTF-8
4094 * Similarly, the code that generates tries doesn't currently handle
4095 * not-already-folded multi-char folds, and it looks like a pain to change
4096 * that. Therefore, trie generation of EXACTFAA nodes with the sharp s
4097 * doesn't work. Instead, such an EXACTFAA is turned into a new regnode,
4098 * EXACTFAA_NO_TRIE, which the trie code knows not to handle. Most people
4099 * using /iaa matching will be doing so almost entirely with ASCII
4100 * strings, so this should rarely be encountered in practice */
4103 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
4104 UV *min_subtract, bool *unfolded_multi_char,
4105 U32 flags, regnode *val, U32 depth)
4107 /* Merge several consecutive EXACTish nodes into one. */
4109 regnode *n = regnext(scan);
4111 regnode *next = scan + NODE_SZ_STR(scan);
4115 regnode *stop = scan;
4116 DECLARE_AND_GET_RE_DEBUG_FLAGS;
4118 PERL_UNUSED_ARG(depth);
4121 PERL_ARGS_ASSERT_JOIN_EXACT;
4122 #ifndef EXPERIMENTAL_INPLACESCAN
4123 PERL_UNUSED_ARG(flags);
4124 PERL_UNUSED_ARG(val);
4126 DEBUG_PEEP("join", scan, depth, 0);
4128 assert(PL_regkind[OP(scan)] == EXACT);
4130 /* Look through the subsequent nodes in the chain. Skip NOTHING, merge
4131 * EXACT ones that are mergeable to the current one. */
4133 && ( PL_regkind[OP(n)] == NOTHING
4134 || (stringok && PL_regkind[OP(n)] == EXACT))
4136 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
4139 if (OP(n) == TAIL || n > next)
4141 if (PL_regkind[OP(n)] == NOTHING) {
4142 DEBUG_PEEP("skip:", n, depth, 0);
4143 NEXT_OFF(scan) += NEXT_OFF(n);
4144 next = n + NODE_STEP_REGNODE;
4151 else if (stringok) {
4152 const unsigned int oldl = STR_LEN(scan);
4153 regnode * const nnext = regnext(n);
4155 /* XXX I (khw) kind of doubt that this works on platforms (should
4156 * Perl ever run on one) where U8_MAX is above 255 because of lots
4157 * of other assumptions */
4158 /* Don't join if the sum can't fit into a single node */
4159 if (oldl + STR_LEN(n) > U8_MAX)
4162 /* Joining something that requires UTF-8 with something that
4163 * doesn't, means the result requires UTF-8. */
4164 if (OP(scan) == EXACT && (OP(n) == EXACT_REQ8)) {
4165 OP(scan) = EXACT_REQ8;
4167 else if (OP(scan) == EXACT_REQ8 && (OP(n) == EXACT)) {
4168 ; /* join is compatible, no need to change OP */
4170 else if ((OP(scan) == EXACTFU) && (OP(n) == EXACTFU_REQ8)) {
4171 OP(scan) = EXACTFU_REQ8;
4173 else if ((OP(scan) == EXACTFU_REQ8) && (OP(n) == EXACTFU)) {
4174 ; /* join is compatible, no need to change OP */
4176 else if (OP(scan) == EXACTFU && OP(n) == EXACTFU) {
4177 ; /* join is compatible, no need to change OP */
4179 else if (OP(scan) == EXACTFU && OP(n) == EXACTFU_S_EDGE) {
4181 /* Under /di, temporary EXACTFU_S_EDGE nodes are generated,
4182 * which can join with EXACTFU ones. We check for this case
4183 * here. These need to be resolved to either EXACTFU or
4184 * EXACTF at joining time. They have nothing in them that
4185 * would forbid them from being the more desirable EXACTFU
4186 * nodes except that they begin and/or end with a single [Ss].
4187 * The reason this is problematic is because they could be
4188 * joined in this loop with an adjacent node that ends and/or
4189 * begins with [Ss] which would then form the sequence 'ss',
4190 * which matches differently under /di than /ui, in which case
4191 * EXACTFU can't be used. If the 'ss' sequence doesn't get
4192 * formed, the nodes get absorbed into any adjacent EXACTFU
4193 * node. And if the only adjacent node is EXACTF, they get
4194 * absorbed into that, under the theory that a longer node is
4195 * better than two shorter ones, even if one is EXACTFU. Note
4196 * that EXACTFU_REQ8 is generated only for UTF-8 patterns,
4197 * and the EXACTFU_S_EDGE ones only for non-UTF-8. */
4199 if (STRING(n)[STR_LEN(n)-1] == 's') {
4201 /* Here the joined node would end with 's'. If the node
4202 * following the combination is an EXACTF one, it's better to
4203 * join this trailing edge 's' node with that one, leaving the
4204 * current one in 'scan' be the more desirable EXACTFU */
4205 if (OP(nnext) == EXACTF) {
4209 OP(scan) = EXACTFU_S_EDGE;
4211 } /* Otherwise, the beginning 's' of the 2nd node just
4212 becomes an interior 's' in 'scan' */
4214 else if (OP(scan) == EXACTF && OP(n) == EXACTF) {
4215 ; /* join is compatible, no need to change OP */
4217 else if (OP(scan) == EXACTF && OP(n) == EXACTFU_S_EDGE) {
4219 /* EXACTF nodes are compatible for joining with EXACTFU_S_EDGE
4220 * nodes. But the latter nodes can be also joined with EXACTFU
4221 * ones, and that is a better outcome, so if the node following
4222 * 'n' is EXACTFU, quit now so that those two can be joined
4224 if (OP(nnext) == EXACTFU) {
4228 /* The join is compatible, and the combined node will be
4229 * EXACTF. (These don't care if they begin or end with 's' */
4231 else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU_S_EDGE) {
4232 if ( STRING(scan)[STR_LEN(scan)-1] == 's'
4233 && STRING(n)[0] == 's')
4235 /* When combined, we have the sequence 'ss', which means we
4236 * have to remain /di */
4240 else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU) {
4241 if (STRING(n)[0] == 's') {
4242 ; /* Here the join is compatible and the combined node
4243 starts with 's', no need to change OP */
4245 else { /* Now the trailing 's' is in the interior */
4249 else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTF) {
4251 /* The join is compatible, and the combined node will be
4252 * EXACTF. (These don't care if they begin or end with 's' */
4255 else if (OP(scan) != OP(n)) {
4257 /* The only other compatible joinings are the same node type */
4261 DEBUG_PEEP("merg", n, depth, 0);
4264 NEXT_OFF(scan) += NEXT_OFF(n);
4265 assert( ( STR_LEN(scan) + STR_LEN(n) ) < 256 );
4266 setSTR_LEN(scan, (U8)(STR_LEN(scan) + STR_LEN(n)));
4267 next = n + NODE_SZ_STR(n);
4268 /* Now we can overwrite *n : */
4269 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
4277 #ifdef EXPERIMENTAL_INPLACESCAN
4278 if (flags && !NEXT_OFF(n)) {
4279 DEBUG_PEEP("atch", val, depth, 0);
4280 if (reg_off_by_arg[OP(n)]) {
4281 ARG_SET(n, val - n);
4284 NEXT_OFF(n) = val - n;
4291 /* This temporary node can now be turned into EXACTFU, and must, as
4292 * regexec.c doesn't handle it */
4293 if (OP(scan) == EXACTFU_S_EDGE) {
4298 *unfolded_multi_char = FALSE;
4300 /* Here, all the adjacent mergeable EXACTish nodes have been merged. We
4301 * can now analyze for sequences of problematic code points. (Prior to
4302 * this final joining, sequences could have been split over boundaries, and
4303 * hence missed). The sequences only happen in folding, hence for any
4304 * non-EXACT EXACTish node */
4305 if (OP(scan) != EXACT && OP(scan) != EXACT_REQ8 && OP(scan) != EXACTL) {
4306 U8* s0 = (U8*) STRING(scan);
4308 U8* s_end = s0 + STR_LEN(scan);
4310 int total_count_delta = 0; /* Total delta number of characters that
4311 multi-char folds expand to */
4313 /* One pass is made over the node's string looking for all the
4314 * possibilities. To avoid some tests in the loop, there are two main
4315 * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
4320 if (OP(scan) == EXACTFL) {
4323 /* An EXACTFL node would already have been changed to another
4324 * node type unless there is at least one character in it that
4325 * is problematic; likely a character whose fold definition
4326 * won't be known until runtime, and so has yet to be folded.
4327 * For all but the UTF-8 locale, folds are 1-1 in length, but
4328 * to handle the UTF-8 case, we need to create a temporary
4329 * folded copy using UTF-8 locale rules in order to analyze it.
4330 * This is because our macros that look to see if a sequence is
4331 * a multi-char fold assume everything is folded (otherwise the
4332 * tests in those macros would be too complicated and slow).
4333 * Note that here, the non-problematic folds will have already
4334 * been done, so we can just copy such characters. We actually
4335 * don't completely fold the EXACTFL string. We skip the
4336 * unfolded multi-char folds, as that would just create work
4337 * below to figure out the size they already are */
4339 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
4342 STRLEN s_len = UTF8SKIP(s);
4343 if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
4344 Copy(s, d, s_len, U8);
4347 else if (is_FOLDS_TO_MULTI_utf8(s)) {
4348 *unfolded_multi_char = TRUE;
4349 Copy(s, d, s_len, U8);
4352 else if (isASCII(*s)) {
4353 *(d++) = toFOLD(*s);
4357 _toFOLD_utf8_flags(s, s_end, d, &len, FOLD_FLAGS_FULL);
4363 /* Point the remainder of the routine to look at our temporary
4367 } /* End of creating folded copy of EXACTFL string */
4369 /* Examine the string for a multi-character fold sequence. UTF-8
4370 * patterns have all characters pre-folded by the time this code is
4372 while (s < s_end - 1) /* Can stop 1 before the end, as minimum
4373 length sequence we are looking for is 2 */
4375 int count = 0; /* How many characters in a multi-char fold */
4376 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
4377 if (! len) { /* Not a multi-char fold: get next char */
4382 { /* Here is a generic multi-char fold. */
4383 U8* multi_end = s + len;
4385 /* Count how many characters are in it. In the case of
4386 * /aa, no folds which contain ASCII code points are
4387 * allowed, so check for those, and skip if found. */
4388 if (OP(scan) != EXACTFAA && OP(scan) != EXACTFAA_NO_TRIE) {
4389 count = utf8_length(s, multi_end);
4393 while (s < multi_end) {
4396 goto next_iteration;
4406 /* The delta is how long the sequence is minus 1 (1 is how long
4407 * the character that folds to the sequence is) */
4408 total_count_delta += count - 1;
4412 /* We created a temporary folded copy of the string in EXACTFL
4413 * nodes. Therefore we need to be sure it doesn't go below zero,
4414 * as the real string could be shorter */
4415 if (OP(scan) == EXACTFL) {
4416 int total_chars = utf8_length((U8*) STRING(scan),
4417 (U8*) STRING(scan) + STR_LEN(scan));
4418 if (total_count_delta > total_chars) {
4419 total_count_delta = total_chars;
4423 *min_subtract += total_count_delta;
4426 else if (OP(scan) == EXACTFAA) {
4428 /* Non-UTF-8 pattern, EXACTFAA node. There can't be a multi-char
4429 * fold to the ASCII range (and there are no existing ones in the
4430 * upper latin1 range). But, as outlined in the comments preceding
4431 * this function, we need to flag any occurrences of the sharp s.
4432 * This character forbids trie formation (because of added
4434 #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
4435 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
4436 || UNICODE_DOT_DOT_VERSION > 0)
4438 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
4439 OP(scan) = EXACTFAA_NO_TRIE;
4440 *unfolded_multi_char = TRUE;
4446 else if (OP(scan) != EXACTFAA_NO_TRIE) {
4448 /* Non-UTF-8 pattern, not EXACTFAA node. Look for the multi-char
4449 * folds that are all Latin1. As explained in the comments
4450 * preceding this function, we look also for the sharp s in EXACTF
4451 * and EXACTFL nodes; it can be in the final position. Otherwise
4452 * we can stop looking 1 byte earlier because have to find at least
4453 * two characters for a multi-fold */
4454 const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
4459 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
4460 if (! len) { /* Not a multi-char fold. */
4461 if (*s == LATIN_SMALL_LETTER_SHARP_S
4462 && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
4464 *unfolded_multi_char = TRUE;
4471 && isALPHA_FOLD_EQ(*s, 's')
4472 && isALPHA_FOLD_EQ(*(s+1), 's'))
4475 /* EXACTF nodes need to know that the minimum length
4476 * changed so that a sharp s in the string can match this
4477 * ss in the pattern, but they remain EXACTF nodes, as they
4478 * won't match this unless the target string is in UTF-8,
4479 * which we don't know until runtime. EXACTFL nodes can't
4480 * transform into EXACTFU nodes */
4481 if (OP(scan) != EXACTF && OP(scan) != EXACTFL) {
4482 OP(scan) = EXACTFUP;
4486 *min_subtract += len - 1;
4494 /* Allow dumping but overwriting the collection of skipped
4495 * ops and/or strings with fake optimized ops */
4496 n = scan + NODE_SZ_STR(scan);
4504 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl", scan, depth, 0);});
4508 /* REx optimizer. Converts nodes into quicker variants "in place".
4509 Finds fixed substrings. */
4511 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
4512 to the position after last scanned or to NULL. */
4514 #define INIT_AND_WITHP \
4515 assert(!and_withp); \
4516 Newx(and_withp, 1, regnode_ssc); \
4517 SAVEFREEPV(and_withp)
4521 S_unwind_scan_frames(pTHX_ const void *p)
4523 scan_frame *f= (scan_frame *)p;
4525 scan_frame *n= f->next_frame;
4531 /* Follow the next-chain of the current node and optimize away
4532 all the NOTHINGs from it.
4535 S_rck_elide_nothing(pTHX_ regnode *node)
4539 PERL_ARGS_ASSERT_RCK_ELIDE_NOTHING;
4541 if (OP(node) != CURLYX) {
4542 const int max = (reg_off_by_arg[OP(node)]
4544 /* I32 may be smaller than U16 on CRAYs! */
4545 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
4546 int off = (reg_off_by_arg[OP(node)] ? ARG(node) : NEXT_OFF(node));
4550 /* Skip NOTHING and LONGJMP. */
4554 (PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
4555 || ((OP(n) == LONGJMP) && (noff = ARG(n)))
4561 if (reg_off_by_arg[OP(node)])
4564 NEXT_OFF(node) = off;
4569 /* the return from this sub is the minimum length that could possibly match */
4571 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
4572 SSize_t *minlenp, SSize_t *deltap,
4577 regnode_ssc *and_withp,
4578 U32 flags, U32 depth, bool was_mutate_ok)
4579 /* scanp: Start here (read-write). */
4580 /* deltap: Write maxlen-minlen here. */
4581 /* last: Stop before this one. */
4582 /* data: string data about the pattern */
4583 /* stopparen: treat close N as END */
4584 /* recursed: which subroutines have we recursed into */
4585 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
4588 SSize_t final_minlen;
4589 /* There must be at least this number of characters to match */
4592 regnode *scan = *scanp, *next;
4594 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
4595 int is_inf_internal = 0; /* The studied chunk is infinite */
4596 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
4597 scan_data_t data_fake;
4598 SV *re_trie_maxbuff = NULL;
4599 regnode *first_non_open = scan;
4600 SSize_t stopmin = OPTIMIZE_INFTY;
4601 scan_frame *frame = NULL;
4602 DECLARE_AND_GET_RE_DEBUG_FLAGS;
4604 PERL_ARGS_ASSERT_STUDY_CHUNK;
4605 RExC_study_started= 1;
4607 Zero(&data_fake, 1, scan_data_t);
4610 while (first_non_open && OP(first_non_open) == OPEN)
4611 first_non_open=regnext(first_non_open);
4617 RExC_study_chunk_recursed_count++;
4619 DEBUG_OPTIMISE_MORE_r(
4621 Perl_re_indentf( aTHX_ "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p",
4622 depth, (long)stopparen,
4623 (unsigned long)RExC_study_chunk_recursed_count,
4624 (unsigned long)depth, (unsigned long)recursed_depth,
4627 if (recursed_depth) {
4630 for ( j = 0 ; j < recursed_depth ; j++ ) {
4631 for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) {
4632 if (PAREN_TEST(j, i) && (!j || !PAREN_TEST(j - 1, i))) {
4633 Perl_re_printf( aTHX_ " %d",(int)i);
4637 if ( j + 1 < recursed_depth ) {
4638 Perl_re_printf( aTHX_ ",");
4642 Perl_re_printf( aTHX_ "\n");
4645 while ( scan && OP(scan) != END && scan < last ){
4646 UV min_subtract = 0; /* How mmany chars to subtract from the minimum
4647 node length to get a real minimum (because
4648 the folded version may be shorter) */
4649 bool unfolded_multi_char = FALSE;
4650 /* avoid mutating ops if we are anywhere within the recursed or
4651 * enframed handling for a GOSUB: the outermost level will handle it.
4653 bool mutate_ok = was_mutate_ok && !(frame && frame->in_gosub);
4654 /* Peephole optimizer: */
4655 DEBUG_STUDYDATA("Peep", data, depth, is_inf);
4656 DEBUG_PEEP("Peep", scan, depth, flags);
4659 /* The reason we do this here is that we need to deal with things like
4660 * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT
4661 * parsing code, as each (?:..) is handled by a different invocation of
4664 if (PL_regkind[OP(scan)] == EXACT
4665 && OP(scan) != LEXACT
4666 && OP(scan) != LEXACT_REQ8
4669 join_exact(pRExC_state, scan, &min_subtract, &unfolded_multi_char,
4670 0, NULL, depth + 1);
4673 /* Follow the next-chain of the current node and optimize
4674 away all the NOTHINGs from it.
4676 rck_elide_nothing(scan);
4678 /* The principal pseudo-switch. Cannot be a switch, since we look into
4679 * several different things. */
4680 if ( OP(scan) == DEFINEP ) {
4682 SSize_t deltanext = 0;
4683 SSize_t fake_last_close = 0;
4684 I32 f = SCF_IN_DEFINE;
4686 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4687 scan = regnext(scan);
4688 assert( OP(scan) == IFTHEN );
4689 DEBUG_PEEP("expect IFTHEN", scan, depth, flags);
4691 data_fake.last_closep= &fake_last_close;
4693 next = regnext(scan);
4694 scan = NEXTOPER(NEXTOPER(scan));
4695 DEBUG_PEEP("scan", scan, depth, flags);
4696 DEBUG_PEEP("next", next, depth, flags);
4698 /* we suppose the run is continuous, last=next...
4699 * NOTE we dont use the return here! */
4700 /* DEFINEP study_chunk() recursion */
4701 (void)study_chunk(pRExC_state, &scan, &minlen,
4702 &deltanext, next, &data_fake, stopparen,
4703 recursed_depth, NULL, f, depth+1, mutate_ok);
4708 OP(scan) == BRANCH ||
4709 OP(scan) == BRANCHJ ||
4712 next = regnext(scan);
4715 /* The op(next)==code check below is to see if we
4716 * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN"
4717 * IFTHEN is special as it might not appear in pairs.
4718 * Not sure whether BRANCH-BRANCHJ is possible, regardless
4719 * we dont handle it cleanly. */
4720 if (OP(next) == code || code == IFTHEN) {
4721 /* NOTE - There is similar code to this block below for
4722 * handling TRIE nodes on a re-study. If you change stuff here
4723 * check there too. */
4724 SSize_t max1 = 0, min1 = OPTIMIZE_INFTY, num = 0;
4726 regnode * const startbranch=scan;
4728 if (flags & SCF_DO_SUBSTR) {
4729 /* Cannot merge strings after this. */
4730 scan_commit(pRExC_state, data, minlenp, is_inf);
4733 if (flags & SCF_DO_STCLASS)
4734 ssc_init_zero(pRExC_state, &accum);
4736 while (OP(scan) == code) {
4737 SSize_t deltanext, minnext, fake;
4739 regnode_ssc this_class;
4741 DEBUG_PEEP("Branch", scan, depth, flags);
4744 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4746 data_fake.whilem_c = data->whilem_c;
4747 data_fake.last_closep = data->last_closep;
4750 data_fake.last_closep = &fake;
4752 data_fake.pos_delta = delta;
4753 next = regnext(scan);
4755 scan = NEXTOPER(scan); /* everything */
4756 if (code != BRANCH) /* everything but BRANCH */
4757 scan = NEXTOPER(scan);
4759 if (flags & SCF_DO_STCLASS) {
4760 ssc_init(pRExC_state, &this_class);
4761 data_fake.start_class = &this_class;
4762 f = SCF_DO_STCLASS_AND;
4764 if (flags & SCF_WHILEM_VISITED_POS)
4765 f |= SCF_WHILEM_VISITED_POS;
4767 /* we suppose the run is continuous, last=next...*/
4768 /* recurse study_chunk() for each BRANCH in an alternation */
4769 minnext = study_chunk(pRExC_state, &scan, minlenp,
4770 &deltanext, next, &data_fake, stopparen,
4771 recursed_depth, NULL, f, depth+1,
4776 if (deltanext == OPTIMIZE_INFTY) {
4777 is_inf = is_inf_internal = 1;
4778 max1 = OPTIMIZE_INFTY;
4779 } else if (max1 < minnext + deltanext)
4780 max1 = minnext + deltanext;
4782 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4784 if (data_fake.flags & SCF_SEEN_ACCEPT) {
4785 if ( stopmin > minnext)
4786 stopmin = min + min1;
4787 flags &= ~SCF_DO_SUBSTR;
4789 data->flags |= SCF_SEEN_ACCEPT;
4792 if (data_fake.flags & SF_HAS_EVAL)
4793 data->flags |= SF_HAS_EVAL;
4794 data->whilem_c = data_fake.whilem_c;
4796 if (flags & SCF_DO_STCLASS)
4797 ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);
4799 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
4801 if (flags & SCF_DO_SUBSTR) {
4802 data->pos_min += min1;
4803 if (data->pos_delta >= OPTIMIZE_INFTY - (max1 - min1))
4804 data->pos_delta = OPTIMIZE_INFTY;
4806 data->pos_delta += max1 - min1;
4807 if (max1 != min1 || is_inf)
4808 data->cur_is_floating = 1;
4811 if (delta == OPTIMIZE_INFTY
4812 || OPTIMIZE_INFTY - delta - (max1 - min1) < 0)
4813 delta = OPTIMIZE_INFTY;
4815 delta += max1 - min1;
4816 if (flags & SCF_DO_STCLASS_OR) {
4817 ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);
4819 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4820 flags &= ~SCF_DO_STCLASS;
4823 else if (flags & SCF_DO_STCLASS_AND) {
4825 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
4826 flags &= ~SCF_DO_STCLASS;
4829 /* Switch to OR mode: cache the old value of
4830 * data->start_class */
4832 StructCopy(data->start_class, and_withp, regnode_ssc);
4833 flags &= ~SCF_DO_STCLASS_AND;
4834 StructCopy(&accum, data->start_class, regnode_ssc);
4835 flags |= SCF_DO_STCLASS_OR;
4839 if (PERL_ENABLE_TRIE_OPTIMISATION
4840 && OP(startbranch) == BRANCH
4845 Assuming this was/is a branch we are dealing with: 'scan'
4846 now points at the item that follows the branch sequence,
4847 whatever it is. We now start at the beginning of the
4848 sequence and look for subsequences of
4854 which would be constructed from a pattern like
4857 If we can find such a subsequence we need to turn the first
4858 element into a trie and then add the subsequent branch exact
4859 strings to the trie.
4863 1. patterns where the whole set of branches can be
4866 2. patterns where only a subset can be converted.
4868 In case 1 we can replace the whole set with a single regop
4869 for the trie. In case 2 we need to keep the start and end
4872 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
4873 becomes BRANCH TRIE; BRANCH X;
4875 There is an additional case, that being where there is a
4876 common prefix, which gets split out into an EXACT like node
4877 preceding the TRIE node.
4879 If x(1..n)==tail then we can do a simple trie, if not we make
4880 a "jump" trie, such that when we match the appropriate word
4881 we "jump" to the appropriate tail node. Essentially we turn
4882 a nested if into a case structure of sorts.
4887 if (!re_trie_maxbuff) {
4888 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
4889 if (!SvIOK(re_trie_maxbuff))
4890 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
4892 if ( SvIV(re_trie_maxbuff)>=0 ) {
4894 regnode *first = (regnode *)NULL;
4895 regnode *prev = (regnode *)NULL;
4896 regnode *tail = scan;
4900 /* var tail is used because there may be a TAIL
4901 regop in the way. Ie, the exacts will point to the
4902 thing following the TAIL, but the last branch will
4903 point at the TAIL. So we advance tail. If we
4904 have nested (?:) we may have to move through several
4908 while ( OP( tail ) == TAIL ) {
4909 /* this is the TAIL generated by (?:) */
4910 tail = regnext( tail );
4914 DEBUG_TRIE_COMPILE_r({
4915 regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);
4916 Perl_re_indentf( aTHX_ "%s %" UVuf ":%s\n",
4918 "Looking for TRIE'able sequences. Tail node is ",
4919 (UV) REGNODE_OFFSET(tail),
4920 SvPV_nolen_const( RExC_mysv )
4926 Step through the branches
4927 cur represents each branch,
4928 noper is the first thing to be matched as part
4930 noper_next is the regnext() of that node.
4932 We normally handle a case like this
4933 /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also
4934 support building with NOJUMPTRIE, which restricts
4935 the trie logic to structures like /FOO|BAR/.
4937 If noper is a trieable nodetype then the branch is
4938 a possible optimization target. If we are building
4939 under NOJUMPTRIE then we require that noper_next is
4940 the same as scan (our current position in the regex
4943 Once we have two or more consecutive such branches
4944 we can create a trie of the EXACT's contents and
4945 stitch it in place into the program.
4947 If the sequence represents all of the branches in
4948 the alternation we replace the entire thing with a
4951 Otherwise when it is a subsequence we need to
4952 stitch it in place and replace only the relevant
4953 branches. This means the first branch has to remain
4954 as it is used by the alternation logic, and its
4955 next pointer, and needs to be repointed at the item
4956 on the branch chain following the last branch we
4957 have optimized away.
4959 This could be either a BRANCH, in which case the
4960 subsequence is internal, or it could be the item
4961 following the branch sequence in which case the
4962 subsequence is at the end (which does not
4963 necessarily mean the first node is the start of the
4966 TRIE_TYPE(X) is a define which maps the optype to a
4970 ----------------+-----------
4975 EXACTFU_REQ8 | EXACTFU
4979 EXACTFLU8 | EXACTFLU8
4983 #define TRIE_TYPE(X) ( ( NOTHING == (X) ) \
4985 : ( EXACT == (X) || EXACT_REQ8 == (X) ) \
4987 : ( EXACTFU == (X) \
4988 || EXACTFU_REQ8 == (X) \
4989 || EXACTFUP == (X) ) \
4991 : ( EXACTFAA == (X) ) \
4993 : ( EXACTL == (X) ) \
4995 : ( EXACTFLU8 == (X) ) \
4999 /* dont use tail as the end marker for this traverse */
5000 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
5001 regnode * const noper = NEXTOPER( cur );
5002 U8 noper_type = OP( noper );
5003 U8 noper_trietype = TRIE_TYPE( noper_type );
5004 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
5005 regnode * const noper_next = regnext( noper );
5006 U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
5007 U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0;
5010 DEBUG_TRIE_COMPILE_r({
5011 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5012 Perl_re_indentf( aTHX_ "- %d:%s (%d)",
5014 REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );
5016 regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);
5017 Perl_re_printf( aTHX_ " -> %d:%s",
5018 REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv));
5021 regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);
5022 Perl_re_printf( aTHX_ "\t=> %d:%s\t",
5023 REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv));
5025 Perl_re_printf( aTHX_ "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n",
5026 REG_NODE_NUM(first), REG_NODE_NUM(prev), REG_NODE_NUM(cur),
5027 PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]
5031 /* Is noper a trieable nodetype that can be merged
5032 * with the current trie (if there is one)? */
5036 ( noper_trietype == NOTHING )
5037 || ( trietype == NOTHING )
5038 || ( trietype == noper_trietype )
5041 && noper_next >= tail
5045 /* Handle mergable triable node Either we are
5046 * the first node in a new trieable sequence,
5047 * in which case we do some bookkeeping,
5048 * otherwise we update the end pointer. */
5051 if ( noper_trietype == NOTHING ) {
5052 #if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
5053 regnode * const noper_next = regnext( noper );
5054 U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
5055 U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
5058 if ( noper_next_trietype ) {
5059 trietype = noper_next_trietype;
5060 } else if (noper_next_type) {
5061 /* a NOTHING regop is 1 regop wide.
5062 * We need at least two for a trie
5063 * so we can't merge this in */
5067 trietype = noper_trietype;
5070 if ( trietype == NOTHING )
5071 trietype = noper_trietype;
5076 } /* end handle mergable triable node */
5078 /* handle unmergable node -
5079 * noper may either be a triable node which can
5080 * not be tried together with the current trie,
5081 * or a non triable node */
5083 /* If last is set and trietype is not
5084 * NOTHING then we have found at least two
5085 * triable branch sequences in a row of a
5086 * similar trietype so we can turn them
5087 * into a trie. If/when we allow NOTHING to
5088 * start a trie sequence this condition
5089 * will be required, and it isn't expensive
5090 * so we leave it in for now. */
5091 if ( trietype && trietype != NOTHING )
5092 make_trie( pRExC_state,
5093 startbranch, first, cur, tail,
5094 count, trietype, depth+1 );
5095 prev = NULL; /* note: we clear/update
5096 first, trietype etc below,
5097 so we dont do it here */
5101 && noper_next >= tail
5104 /* noper is triable, so we can start a new
5108 trietype = noper_trietype;
5110 /* if we already saw a first but the
5111 * current node is not triable then we have
5112 * to reset the first information. */
5117 } /* end handle unmergable node */
5118 } /* loop over branches */
5119 DEBUG_TRIE_COMPILE_r({
5120 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5121 Perl_re_indentf( aTHX_ "- %s (%d) <SCAN FINISHED> ",
5122 depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
5123 Perl_re_printf( aTHX_ "(First==%d, Last==%d, Cur==%d, tt==%s)\n",
5124 REG_NODE_NUM(first), REG_NODE_NUM(prev), REG_NODE_NUM(cur),
5125 PL_reg_name[trietype]
5129 if ( prev && trietype ) {
5130 if ( trietype != NOTHING ) {
5131 /* the last branch of the sequence was part of
5132 * a trie, so we have to construct it here
5133 * outside of the loop */
5134 made= make_trie( pRExC_state, startbranch,
5135 first, scan, tail, count,
5136 trietype, depth+1 );
5137 #ifdef TRIE_STUDY_OPT
5138 if ( ((made == MADE_EXACT_TRIE &&
5139 startbranch == first)
5140 || ( first_non_open == first )) &&
5142 flags |= SCF_TRIE_RESTUDY;
5143 if ( startbranch == first
5146 RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;
5151 /* at this point we know whatever we have is a
5152 * NOTHING sequence/branch AND if 'startbranch'
5153 * is 'first' then we can turn the whole thing
5156 if ( startbranch == first ) {
5158 /* the entire thing is a NOTHING sequence,
5159 * something like this: (?:|) So we can
5160 * turn it into a plain NOTHING op. */
5161 DEBUG_TRIE_COMPILE_r({
5162 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5163 Perl_re_indentf( aTHX_ "- %s (%d) <NOTHING BRANCH SEQUENCE>\n",
5165 SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
5168 OP(startbranch)= NOTHING;
5169 NEXT_OFF(startbranch)= tail - startbranch;
5170 for ( opt= startbranch + 1; opt < tail ; opt++ )
5174 } /* end if ( prev) */
5175 } /* TRIE_MAXBUF is non zero */
5179 else if ( code == BRANCHJ ) { /* single branch is optimized. */
5180 scan = NEXTOPER(NEXTOPER(scan));
5181 } else /* single branch is optimized. */
5182 scan = NEXTOPER(scan);
5184 } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) {
5186 regnode *start = NULL;
5187 regnode *end = NULL;
5188 U32 my_recursed_depth= recursed_depth;
5190 if (OP(scan) != SUSPEND) { /* GOSUB */
5191 /* Do setup, note this code has side effects beyond
5192 * the rest of this block. Specifically setting
5193 * RExC_recurse[] must happen at least once during
5196 RExC_recurse[ARG2L(scan)] = scan;
5197 start = REGNODE_p(RExC_open_parens[paren]);
5198 end = REGNODE_p(RExC_close_parens[paren]);
5200 /* NOTE we MUST always execute the above code, even
5201 * if we do nothing with a GOSUB */
5203 ( flags & SCF_IN_DEFINE )
5206 (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))
5208 ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )
5211 /* no need to do anything here if we are in a define. */
5212 /* or we are after some kind of infinite construct
5213 * so we can skip recursing into this item.
5214 * Since it is infinite we will not change the maxlen
5215 * or delta, and if we miss something that might raise
5216 * the minlen it will merely pessimise a little.
5218 * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/
5219 * might result in a minlen of 1 and not of 4,
5220 * but this doesn't make us mismatch, just try a bit
5221 * harder than we should.
5223 scan= regnext(scan);
5229 || !PAREN_TEST(recursed_depth - 1, paren)
5231 /* it is quite possible that there are more efficient ways
5232 * to do this. We maintain a bitmap per level of recursion
5233 * of which patterns we have entered so we can detect if a
5234 * pattern creates a possible infinite loop. When we
5235 * recurse down a level we copy the previous levels bitmap
5236 * down. When we are at recursion level 0 we zero the top
5237 * level bitmap. It would be nice to implement a different
5238 * more efficient way of doing this. In particular the top
5239 * level bitmap may be unnecessary.
5241 if (!recursed_depth) {
5242 Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);
5244 Copy(PAREN_OFFSET(recursed_depth - 1),
5245 PAREN_OFFSET(recursed_depth),
5246 RExC_study_chunk_recursed_bytes, U8);
5248 /* we havent recursed into this paren yet, so recurse into it */
5249 DEBUG_STUDYDATA("gosub-set", data, depth, is_inf);
5250 PAREN_SET(recursed_depth, paren);
5251 my_recursed_depth= recursed_depth + 1;
5253 DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf);
5254 /* some form of infinite recursion, assume infinite length
5256 if (flags & SCF_DO_SUBSTR) {
5257 scan_commit(pRExC_state, data, minlenp, is_inf);
5258 data->cur_is_floating = 1;
5260 is_inf = is_inf_internal = 1;
5261 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5262 ssc_anything(data->start_class);
5263 flags &= ~SCF_DO_STCLASS;
5265 start= NULL; /* reset start so we dont recurse later on. */
5270 end = regnext(scan);
5273 scan_frame *newframe;
5275 if (!RExC_frame_last) {
5276 Newxz(newframe, 1, scan_frame);
5277 SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);
5278 RExC_frame_head= newframe;
5280 } else if (!RExC_frame_last->next_frame) {
5281 Newxz(newframe, 1, scan_frame);
5282 RExC_frame_last->next_frame= newframe;
5283 newframe->prev_frame= RExC_frame_last;
5286 newframe= RExC_frame_last->next_frame;
5288 RExC_frame_last= newframe;
5290 newframe->next_regnode = regnext(scan);
5291 newframe->last_regnode = last;
5292 newframe->stopparen = stopparen;
5293 newframe->prev_recursed_depth = recursed_depth;
5294 newframe->this_prev_frame= frame;
5295 newframe->in_gosub = (
5296 (frame && frame->in_gosub) || OP(scan) == GOSUB
5299 DEBUG_STUDYDATA("frame-new", data, depth, is_inf);
5300 DEBUG_PEEP("fnew", scan, depth, flags);
5307 recursed_depth= my_recursed_depth;
5312 else if ( OP(scan) == EXACT
5313 || OP(scan) == LEXACT
5314 || OP(scan) == EXACT_REQ8
5315 || OP(scan) == LEXACT_REQ8
5316 || OP(scan) == EXACTL)
5318 SSize_t bytelen = STR_LEN(scan), charlen;
5322 const U8 * const s = (U8*)STRING(scan);
5323 uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
5324 charlen = utf8_length(s, s + bytelen);
5326 uc = *((U8*)STRING(scan));
5330 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
5331 /* The code below prefers earlier match for fixed
5332 offset, later match for variable offset. */
5333 if (data->last_end == -1) { /* Update the start info. */
5334 data->last_start_min = data->pos_min;
5335 data->last_start_max =
5336 is_inf ? OPTIMIZE_INFTY
5337 : (data->pos_delta > OPTIMIZE_INFTY - data->pos_min)
5338 ? OPTIMIZE_INFTY : data->pos_min + data->pos_delta;
5340 sv_catpvn(data->last_found, STRING(scan), bytelen);
5342 SvUTF8_on(data->last_found);
5344 SV * const sv = data->last_found;
5345 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5346 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5347 if (mg && mg->mg_len >= 0)
5348 mg->mg_len += charlen;
5350 data->last_end = data->pos_min + charlen;
5351 data->pos_min += charlen; /* As in the first entry. */
5352 data->flags &= ~SF_BEFORE_EOL;
5355 /* ANDing the code point leaves at most it, and not in locale, and
5356 * can't match null string */
5357 if (flags & SCF_DO_STCLASS_AND) {
5358 ssc_cp_and(data->start_class, uc);
5359 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5360 ssc_clear_locale(data->start_class);
5362 else if (flags & SCF_DO_STCLASS_OR) {
5363 ssc_add_cp(data->start_class, uc);
5364 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5366 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5367 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5369 flags &= ~SCF_DO_STCLASS;
5371 else if (PL_regkind[OP(scan)] == EXACT) {
5372 /* But OP != EXACT!, so is EXACTFish */
5373 SSize_t bytelen = STR_LEN(scan), charlen;
5374 const U8 * s = (U8*)STRING(scan);
5376 /* Replace a length 1 ASCII fold pair node with an ANYOFM node,
5377 * with the mask set to the complement of the bit that differs
5378 * between upper and lower case, and the lowest code point of the
5379 * pair (which the '&' forces) */
5382 && ( OP(scan) == EXACTFAA
5383 || ( OP(scan) == EXACTFU
5384 && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(*s)))
5387 U8 mask = ~ ('A' ^ 'a'); /* These differ in just one bit */
5390 ARG_SET(scan, *s & mask);
5392 /* we're not EXACTFish any more, so restudy */
5396 /* Search for fixed substrings supports EXACT only. */
5397 if (flags & SCF_DO_SUBSTR) {
5399 scan_commit(pRExC_state, data, minlenp, is_inf);
5401 charlen = UTF ? (SSize_t) utf8_length(s, s + bytelen) : bytelen;
5402 if (unfolded_multi_char) {
5403 RExC_seen |= REG_UNFOLDED_MULTI_SEEN;
5405 min += charlen - min_subtract;
5407 delta += min_subtract;
5408 if (flags & SCF_DO_SUBSTR) {
5409 data->pos_min += charlen - min_subtract;
5410 if (data->pos_min < 0) {
5413 data->pos_delta += min_subtract;
5415 data->cur_is_floating = 1; /* float */
5419 if (flags & SCF_DO_STCLASS) {
5420 SV* EXACTF_invlist = make_exactf_invlist(pRExC_state, scan);
5422 assert(EXACTF_invlist);
5423 if (flags & SCF_DO_STCLASS_AND) {
5424 if (OP(scan) != EXACTFL)
5425 ssc_clear_locale(data->start_class);
5426 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5427 ANYOF_POSIXL_ZERO(data->start_class);
5428 ssc_intersection(data->start_class, EXACTF_invlist, FALSE);
5430 else { /* SCF_DO_STCLASS_OR */
5431 ssc_union(data->start_class, EXACTF_invlist, FALSE);
5432 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5434 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5435 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5437 flags &= ~SCF_DO_STCLASS;
5438 SvREFCNT_dec(EXACTF_invlist);
5441 else if (REGNODE_VARIES(OP(scan))) {
5442 SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;
5443 I32 fl = 0, f = flags;
5444 regnode * const oscan = scan;
5445 regnode_ssc this_class;
5446 regnode_ssc *oclass = NULL;
5447 I32 next_is_eval = 0;
5449 switch (PL_regkind[OP(scan)]) {
5450 case WHILEM: /* End of (?:...)* . */
5451 scan = NEXTOPER(scan);
5454 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
5455 next = NEXTOPER(scan);
5456 if ( OP(next) == EXACT
5457 || OP(next) == LEXACT
5458 || OP(next) == EXACT_REQ8
5459 || OP(next) == LEXACT_REQ8
5460 || OP(next) == EXACTL
5461 || (flags & SCF_DO_STCLASS))
5464 maxcount = REG_INFTY;
5465 next = regnext(scan);
5466 scan = NEXTOPER(scan);
5470 if (flags & SCF_DO_SUBSTR)
5475 next = NEXTOPER(scan);
5477 /* This temporary node can now be turned into EXACTFU, and
5478 * must, as regexec.c doesn't handle it */
5479 if (OP(next) == EXACTFU_S_EDGE && mutate_ok) {
5483 if ( STR_LEN(next) == 1
5484 && isALPHA_A(* STRING(next))
5485 && ( OP(next) == EXACTFAA
5486 || ( OP(next) == EXACTFU
5487 && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next))))
5490 /* These differ in just one bit */
5491 U8 mask = ~ ('A' ^ 'a');
5493 assert(isALPHA_A(* STRING(next)));
5495 /* Then replace it by an ANYOFM node, with
5496 * the mask set to the complement of the
5497 * bit that differs between upper and lower
5498 * case, and the lowest code point of the
5499 * pair (which the '&' forces) */
5501 ARG_SET(next, *STRING(next) & mask);
5505 if (flags & SCF_DO_STCLASS) {
5507 maxcount = REG_INFTY;
5508 next = regnext(scan);
5509 scan = NEXTOPER(scan);
5512 if (flags & SCF_DO_SUBSTR) {
5513 scan_commit(pRExC_state, data, minlenp, is_inf);
5514 /* Cannot extend fixed substrings */
5515 data->cur_is_floating = 1; /* float */
5517 is_inf = is_inf_internal = 1;
5518 scan = regnext(scan);
5519 goto optimize_curly_tail;
5521 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
5522 && (scan->flags == stopparen))
5527 mincount = ARG1(scan);
5528 maxcount = ARG2(scan);
5530 next = regnext(scan);
5531 if (OP(scan) == CURLYX) {
5532 I32 lp = (data ? *(data->last_closep) : 0);
5533 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
5535 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
5536 next_is_eval = (OP(scan) == EVAL);
5538 if (flags & SCF_DO_SUBSTR) {
5540 scan_commit(pRExC_state, data, minlenp, is_inf);
5541 /* Cannot extend fixed substrings */
5542 pos_before = data->pos_min;
5546 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
5548 data->flags |= SF_IS_INF;
5550 if (flags & SCF_DO_STCLASS) {
5551 ssc_init(pRExC_state, &this_class);
5552 oclass = data->start_class;
5553 data->start_class = &this_class;
5554 f |= SCF_DO_STCLASS_AND;
5555 f &= ~SCF_DO_STCLASS_OR;
5557 /* Exclude from super-linear cache processing any {n,m}
5558 regops for which the combination of input pos and regex
5559 pos is not enough information to determine if a match
5562 For example, in the regex /foo(bar\s*){4,8}baz/ with the
5563 regex pos at the \s*, the prospects for a match depend not
5564 only on the input position but also on how many (bar\s*)
5565 repeats into the {4,8} we are. */
5566 if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
5567 f &= ~SCF_WHILEM_VISITED_POS;
5569 /* This will finish on WHILEM, setting scan, or on NULL: */
5570 /* recurse study_chunk() on loop bodies */
5571 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
5572 last, data, stopparen, recursed_depth, NULL,
5574 ? (f & ~SCF_DO_SUBSTR)
5576 , depth+1, mutate_ok);
5578 if (flags & SCF_DO_STCLASS)
5579 data->start_class = oclass;
5580 if (mincount == 0 || minnext == 0) {
5581 if (flags & SCF_DO_STCLASS_OR) {
5582 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5584 else if (flags & SCF_DO_STCLASS_AND) {
5585 /* Switch to OR mode: cache the old value of
5586 * data->start_class */
5588 StructCopy(data->start_class, and_withp, regnode_ssc);
5589 flags &= ~SCF_DO_STCLASS_AND;
5590 StructCopy(&this_class, data->start_class, regnode_ssc);
5591 flags |= SCF_DO_STCLASS_OR;
5592 ANYOF_FLAGS(data->start_class)
5593 |= SSC_MATCHES_EMPTY_STRING;
5595 } else { /* Non-zero len */
5596 if (flags & SCF_DO_STCLASS_OR) {
5597 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5598 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5600 else if (flags & SCF_DO_STCLASS_AND)
5601 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5602 flags &= ~SCF_DO_STCLASS;
5604 if (!scan) /* It was not CURLYX, but CURLY. */
5606 if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR)
5607 /* ? quantifier ok, except for (?{ ... }) */
5608 && (next_is_eval || !(mincount == 0 && maxcount == 1))
5609 && (minnext == 0) && (deltanext == 0)
5610 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
5611 && maxcount <= REG_INFTY/3) /* Complement check for big
5614 _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP),
5615 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
5616 "Quantifier unexpected on zero-length expression "
5617 "in regex m/%" UTF8f "/",
5618 UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,
5622 if ( ( minnext > 0 && mincount >= SSize_t_MAX / minnext )
5623 || min >= SSize_t_MAX - minnext * mincount )
5625 FAIL("Regexp out of space");
5628 min += minnext * mincount;
5629 is_inf_internal |= deltanext == OPTIMIZE_INFTY
5630 || (maxcount == REG_INFTY && minnext + deltanext > 0);
5631 is_inf |= is_inf_internal;
5633 delta = OPTIMIZE_INFTY;
5635 delta += (minnext + deltanext) * maxcount
5636 - minnext * mincount;
5638 /* Try powerful optimization CURLYX => CURLYN. */
5639 if ( OP(oscan) == CURLYX && data
5640 && data->flags & SF_IN_PAR
5641 && !(data->flags & SF_HAS_EVAL)
5642 && !deltanext && minnext == 1
5645 /* Try to optimize to CURLYN. */
5646 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
5647 regnode * const nxt1 = nxt;
5654 if (!REGNODE_SIMPLE(OP(nxt))
5655 && !(PL_regkind[OP(nxt)] == EXACT
5656 && STR_LEN(nxt) == 1))
5662 if (OP(nxt) != CLOSE)
5664 if (RExC_open_parens) {
5667 RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5670 RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2;
5672 /* Now we know that nxt2 is the only contents: */
5673 oscan->flags = (U8)ARG(nxt);
5675 OP(nxt1) = NOTHING; /* was OPEN. */
5678 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5679 NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
5680 NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
5681 OP(nxt) = OPTIMIZED; /* was CLOSE. */
5682 OP(nxt + 1) = OPTIMIZED; /* was count. */
5683 NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
5688 /* Try optimization CURLYX => CURLYM. */
5689 if ( OP(oscan) == CURLYX && data
5690 && !(data->flags & SF_HAS_PAR)
5691 && !(data->flags & SF_HAS_EVAL)
5692 && !deltanext /* atom is fixed width */
5693 && minnext != 0 /* CURLYM can't handle zero width */
5694 /* Nor characters whose fold at run-time may be
5695 * multi-character */
5696 && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)
5699 /* XXXX How to optimize if data == 0? */
5700 /* Optimize to a simpler form. */
5701 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
5705 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
5706 && (OP(nxt2) != WHILEM))
5708 OP(nxt2) = SUCCEED; /* Whas WHILEM */
5709 /* Need to optimize away parenths. */
5710 if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
5711 /* Set the parenth number. */
5712 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
5714 oscan->flags = (U8)ARG(nxt);
5715 if (RExC_open_parens) {
5717 RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5720 RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2)
5723 OP(nxt1) = OPTIMIZED; /* was OPEN. */
5724 OP(nxt) = OPTIMIZED; /* was CLOSE. */
5727 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5728 OP(nxt + 1) = OPTIMIZED; /* was count. */
5729 NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
5730 NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
5733 while ( nxt1 && (OP(nxt1) != WHILEM)) {
5734 regnode *nnxt = regnext(nxt1);
5736 if (reg_off_by_arg[OP(nxt1)])
5737 ARG_SET(nxt1, nxt2 - nxt1);
5738 else if (nxt2 - nxt1 < U16_MAX)
5739 NEXT_OFF(nxt1) = nxt2 - nxt1;
5741 OP(nxt) = NOTHING; /* Cannot beautify */
5746 /* Optimize again: */
5747 /* recurse study_chunk() on optimised CURLYX => CURLYM */
5748 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
5749 NULL, stopparen, recursed_depth, NULL, 0,
5750 depth+1, mutate_ok);
5755 else if ((OP(oscan) == CURLYX)
5756 && (flags & SCF_WHILEM_VISITED_POS)
5757 /* See the comment on a similar expression above.
5758 However, this time it's not a subexpression
5759 we care about, but the expression itself. */
5760 && (maxcount == REG_INFTY)
5762 /* This stays as CURLYX, we can put the count/of pair. */
5763 /* Find WHILEM (as in regexec.c) */
5764 regnode *nxt = oscan + NEXT_OFF(oscan);
5766 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
5768 nxt = PREVOPER(nxt);
5769 if (nxt->flags & 0xf) {
5770 /* we've already set whilem count on this node */
5771 } else if (++data->whilem_c < 16) {
5772 assert(data->whilem_c <= RExC_whilem_seen);
5773 nxt->flags = (U8)(data->whilem_c
5774 | (RExC_whilem_seen << 4)); /* On WHILEM */
5777 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
5779 if (flags & SCF_DO_SUBSTR) {
5780 SV *last_str = NULL;
5781 STRLEN last_chrs = 0;
5782 int counted = mincount != 0;
5784 if (data->last_end > 0 && mincount != 0) { /* Ends with a
5786 SSize_t b = pos_before >= data->last_start_min
5787 ? pos_before : data->last_start_min;
5789 const char * const s = SvPV_const(data->last_found, l);
5790 SSize_t old = b - data->last_start_min;
5794 old = utf8_hop_forward((U8*)s, old,
5795 (U8 *) SvEND(data->last_found))
5798 /* Get the added string: */
5799 last_str = newSVpvn_utf8(s + old, l, UTF);
5800 last_chrs = UTF ? utf8_length((U8*)(s + old),
5801 (U8*)(s + old + l)) : l;
5802 if (deltanext == 0 && pos_before == b) {
5803 /* What was added is a constant string */
5806 SvGROW(last_str, (mincount * l) + 1);
5807 repeatcpy(SvPVX(last_str) + l,
5808 SvPVX_const(last_str), l,
5810 SvCUR_set(last_str, SvCUR(last_str) * mincount);
5811 /* Add additional parts. */
5812 SvCUR_set(data->last_found,
5813 SvCUR(data->last_found) - l);
5814 sv_catsv(data->last_found, last_str);
5816 SV * sv = data->last_found;
5818 SvUTF8(sv) && SvMAGICAL(sv) ?
5819 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5820 if (mg && mg->mg_len >= 0)
5821 mg->mg_len += last_chrs * (mincount-1);
5823 last_chrs *= mincount;
5824 data->last_end += l * (mincount - 1);
5827 /* start offset must point into the last copy */
5828 data->last_start_min += minnext * (mincount - 1);
5829 data->last_start_max =
5832 : data->last_start_max +
5833 (maxcount - 1) * (minnext + data->pos_delta);
5836 /* It is counted once already... */
5837 data->pos_min += minnext * (mincount - counted);
5839 Perl_re_printf( aTHX_ "counted=%" UVuf " deltanext=%" UVuf
5840 " OPTIMIZE_INFTY=%" UVuf " minnext=%" UVuf
5841 " maxcount=%" UVuf " mincount=%" UVuf "\n",
5842 (UV)counted, (UV)deltanext, (UV)OPTIMIZE_INFTY, (UV)minnext, (UV)maxcount,
5844 if (deltanext != OPTIMIZE_INFTY)
5845 Perl_re_printf( aTHX_ "LHS=%" UVuf " RHS=%" UVuf "\n",
5846 (UV)(-counted * deltanext + (minnext + deltanext) * maxcount
5847 - minnext * mincount), (UV)(OPTIMIZE_INFTY - data->pos_delta));
5849 if (deltanext == OPTIMIZE_INFTY
5850 || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= OPTIMIZE_INFTY - data->pos_delta)
5851 data->pos_delta = OPTIMIZE_INFTY;
5853 data->pos_delta += - counted * deltanext +
5854 (minnext + deltanext) * maxcount - minnext * mincount;
5855 if (mincount != maxcount) {
5856 /* Cannot extend fixed substrings found inside
5858 scan_commit(pRExC_state, data, minlenp, is_inf);
5859 if (mincount && last_str) {
5860 SV * const sv = data->last_found;
5861 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5862 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5866 sv_setsv(sv, last_str);
5867 data->last_end = data->pos_min;
5868 data->last_start_min = data->pos_min - last_chrs;
5869 data->last_start_max = is_inf
5871 : data->pos_min + data->pos_delta - last_chrs;
5873 data->cur_is_floating = 1; /* float */
5875 SvREFCNT_dec(last_str);
5877 if (data && (fl & SF_HAS_EVAL))
5878 data->flags |= SF_HAS_EVAL;
5879 optimize_curly_tail:
5880 rck_elide_nothing(oscan);
5884 Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d",
5888 if (flags & SCF_DO_SUBSTR) {
5889 /* Cannot expect anything... */
5890 scan_commit(pRExC_state, data, minlenp, is_inf);
5891 data->cur_is_floating = 1; /* float */
5893 is_inf = is_inf_internal = 1;
5894 if (flags & SCF_DO_STCLASS_OR) {
5895 if (OP(scan) == CLUMP) {
5896 /* Actually is any start char, but very few code points
5897 * aren't start characters */
5898 ssc_match_all_cp(data->start_class);
5901 ssc_anything(data->start_class);
5904 flags &= ~SCF_DO_STCLASS;
5908 else if (OP(scan) == LNBREAK) {
5909 if (flags & SCF_DO_STCLASS) {
5910 if (flags & SCF_DO_STCLASS_AND) {
5911 ssc_intersection(data->start_class,
5912 PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);
5913 ssc_clear_locale(data->start_class);
5914 ANYOF_FLAGS(data->start_class)
5915 &= ~SSC_MATCHES_EMPTY_STRING;
5917 else if (flags & SCF_DO_STCLASS_OR) {
5918 ssc_union(data->start_class,
5919 PL_XPosix_ptrs[_CC_VERTSPACE],
5921 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5923 /* See commit msg for
5924 * 749e076fceedeb708a624933726e7989f2302f6a */
5925 ANYOF_FLAGS(data->start_class)
5926 &= ~SSC_MATCHES_EMPTY_STRING;
5928 flags &= ~SCF_DO_STCLASS;
5931 if (delta != OPTIMIZE_INFTY)
5932 delta++; /* Because of the 2 char string cr-lf */
5933 if (flags & SCF_DO_SUBSTR) {
5934 /* Cannot expect anything... */
5935 scan_commit(pRExC_state, data, minlenp, is_inf);
5937 if (data->pos_delta != OPTIMIZE_INFTY) {
5938 data->pos_delta += 1;
5940 data->cur_is_floating = 1; /* float */
5943 else if (REGNODE_SIMPLE(OP(scan))) {
5945 if (flags & SCF_DO_SUBSTR) {
5946 scan_commit(pRExC_state, data, minlenp, is_inf);
5950 if (flags & SCF_DO_STCLASS) {
5952 SV* my_invlist = NULL;
5955 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5956 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5958 /* Some of the logic below assumes that switching
5959 locale on will only add false positives. */
5964 Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d",
5968 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5969 ssc_match_all_cp(data->start_class);
5974 SV* REG_ANY_invlist = _new_invlist(2);
5975 REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,
5977 if (flags & SCF_DO_STCLASS_OR) {
5978 ssc_union(data->start_class,
5980 TRUE /* TRUE => invert, hence all but \n
5984 else if (flags & SCF_DO_STCLASS_AND) {
5985 ssc_intersection(data->start_class,
5987 TRUE /* TRUE => invert */
5989 ssc_clear_locale(data->start_class);
5991 SvREFCNT_dec_NN(REG_ANY_invlist);
6003 if (flags & SCF_DO_STCLASS_AND)
6004 ssc_and(pRExC_state, data->start_class,
6005 (regnode_charclass *) scan);
6007 ssc_or(pRExC_state, data->start_class,
6008 (regnode_charclass *) scan);
6011 case NANYOFM: /* NANYOFM already contains the inversion of the
6012 input ANYOF data, so, unlike things like
6013 NPOSIXA, don't change 'invert' to TRUE */
6017 SV* cp_list = get_ANYOFM_contents(scan);
6019 if (flags & SCF_DO_STCLASS_OR) {
6020 ssc_union(data->start_class, cp_list, invert);
6022 else if (flags & SCF_DO_STCLASS_AND) {
6023 ssc_intersection(data->start_class, cp_list, invert);
6026 SvREFCNT_dec_NN(cp_list);
6035 cp_list = _add_range_to_invlist(cp_list,
6037 ANYOFRbase(scan) + ANYOFRdelta(scan));
6039 if (flags & SCF_DO_STCLASS_OR) {
6040 ssc_union(data->start_class, cp_list, invert);
6042 else if (flags & SCF_DO_STCLASS_AND) {
6043 ssc_intersection(data->start_class, cp_list, invert);
6046 SvREFCNT_dec_NN(cp_list);
6055 namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;
6056 if (flags & SCF_DO_STCLASS_AND) {
6057 bool was_there = cBOOL(
6058 ANYOF_POSIXL_TEST(data->start_class,
6060 ANYOF_POSIXL_ZERO(data->start_class);
6061 if (was_there) { /* Do an AND */
6062 ANYOF_POSIXL_SET(data->start_class, namedclass);
6064 /* No individual code points can now match */
6065 data->start_class->invlist
6066 = sv_2mortal(_new_invlist(0));
6069 int complement = namedclass + ((invert) ? -1 : 1);
6071 assert(flags & SCF_DO_STCLASS_OR);
6073 /* If the complement of this class was already there,
6074 * the result is that they match all code points,
6075 * (\d + \D == everything). Remove the classes from
6076 * future consideration. Locale is not relevant in
6078 if (ANYOF_POSIXL_TEST(data->start_class, complement)) {
6079 ssc_match_all_cp(data->start_class);
6080 ANYOF_POSIXL_CLEAR(data->start_class, namedclass);
6081 ANYOF_POSIXL_CLEAR(data->start_class, complement);
6083 else { /* The usual case; just add this class to the
6085 ANYOF_POSIXL_SET(data->start_class, namedclass);
6090 case NPOSIXA: /* For these, we always know the exact set of
6095 my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL);
6096 goto join_posix_and_ascii;
6104 my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL);
6106 /* NPOSIXD matches all upper Latin1 code points unless the
6107 * target string being matched is UTF-8, which is
6108 * unknowable until match time. Since we are going to
6109 * invert, we want to get rid of all of them so that the
6110 * inversion will match all */
6111 if (OP(scan) == NPOSIXD) {
6112 _invlist_subtract(my_invlist, PL_UpperLatin1,
6116 join_posix_and_ascii:
6118 if (flags & SCF_DO_STCLASS_AND) {
6119 ssc_intersection(data->start_class, my_invlist, invert);
6120 ssc_clear_locale(data->start_class);
6123 assert(flags & SCF_DO_STCLASS_OR);
6124 ssc_union(data->start_class, my_invlist, invert);
6126 SvREFCNT_dec(my_invlist);
6128 if (flags & SCF_DO_STCLASS_OR)
6129 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6130 flags &= ~SCF_DO_STCLASS;
6133 else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
6134 data->flags |= (OP(scan) == MEOL
6137 scan_commit(pRExC_state, data, minlenp, is_inf);
6140 else if ( PL_regkind[OP(scan)] == BRANCHJ
6141 /* Lookbehind, or need to calculate parens/evals/stclass: */
6142 && (scan->flags || data || (flags & SCF_DO_STCLASS))
6143 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM))
6145 if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
6146 || OP(scan) == UNLESSM )
6148 /* Negative Lookahead/lookbehind
6149 In this case we can't do fixed string optimisation.
6152 SSize_t deltanext, minnext, fake = 0;
6157 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6159 data_fake.whilem_c = data->whilem_c;
6160 data_fake.last_closep = data->last_closep;
6163 data_fake.last_closep = &fake;
6164 data_fake.pos_delta = delta;
6165 if ( flags & SCF_DO_STCLASS && !scan->flags
6166 && OP(scan) == IFMATCH ) { /* Lookahead */
6167 ssc_init(pRExC_state, &intrnl);
6168 data_fake.start_class = &intrnl;
6169 f |= SCF_DO_STCLASS_AND;
6171 if (flags & SCF_WHILEM_VISITED_POS)
6172 f |= SCF_WHILEM_VISITED_POS;
6173 next = regnext(scan);
6174 nscan = NEXTOPER(NEXTOPER(scan));
6176 /* recurse study_chunk() for lookahead body */
6177 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
6178 last, &data_fake, stopparen,
6179 recursed_depth, NULL, f, depth+1,
6183 || deltanext > (I32) U8_MAX
6184 || minnext > (I32)U8_MAX
6185 || minnext + deltanext > (I32)U8_MAX)
6187 FAIL2("Lookbehind longer than %" UVuf " not implemented",
6191 /* The 'next_off' field has been repurposed to count the
6192 * additional starting positions to try beyond the initial
6193 * one. (This leaves it at 0 for non-variable length
6194 * matches to avoid breakage for those not using this
6197 scan->next_off = deltanext;
6198 ckWARNexperimental(RExC_parse,
6199 WARN_EXPERIMENTAL__VLB,
6200 "Variable length lookbehind is experimental");
6202 scan->flags = (U8)minnext + deltanext;
6205 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6207 if (data_fake.flags & SF_HAS_EVAL)
6208 data->flags |= SF_HAS_EVAL;
6209 data->whilem_c = data_fake.whilem_c;
6211 if (f & SCF_DO_STCLASS_AND) {
6212 if (flags & SCF_DO_STCLASS_OR) {
6213 /* OR before, AND after: ideally we would recurse with
6214 * data_fake to get the AND applied by study of the
6215 * remainder of the pattern, and then derecurse;
6216 * *** HACK *** for now just treat as "no information".
6217 * See [perl #56690].
6219 ssc_init(pRExC_state, data->start_class);
6221 /* AND before and after: combine and continue. These
6222 * assertions are zero-length, so can match an EMPTY
6224 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6225 ANYOF_FLAGS(data->start_class)
6226 |= SSC_MATCHES_EMPTY_STRING;
6230 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
6232 /* Positive Lookahead/lookbehind
6233 In this case we can do fixed string optimisation,
6234 but we must be careful about it. Note in the case of
6235 lookbehind the positions will be offset by the minimum
6236 length of the pattern, something we won't know about
6237 until after the recurse.
6239 SSize_t deltanext, fake = 0;
6243 /* We use SAVEFREEPV so that when the full compile
6244 is finished perl will clean up the allocated
6245 minlens when it's all done. This way we don't
6246 have to worry about freeing them when we know
6247 they wont be used, which would be a pain.
6250 Newx( minnextp, 1, SSize_t );
6251 SAVEFREEPV(minnextp);
6254 StructCopy(data, &data_fake, scan_data_t);
6255 if ((flags & SCF_DO_SUBSTR) && data->last_found) {
6258 scan_commit(pRExC_state, &data_fake, minlenp, is_inf);
6259 data_fake.last_found=newSVsv(data->last_found);
6263 data_fake.last_closep = &fake;
6264 data_fake.flags = 0;
6265 data_fake.substrs[0].flags = 0;
6266 data_fake.substrs[1].flags = 0;
6267 data_fake.pos_delta = delta;
6269 data_fake.flags |= SF_IS_INF;
6270 if ( flags & SCF_DO_STCLASS && !scan->flags
6271 && OP(scan) == IFMATCH ) { /* Lookahead */
6272 ssc_init(pRExC_state, &intrnl);
6273 data_fake.start_class = &intrnl;
6274 f |= SCF_DO_STCLASS_AND;
6276 if (flags & SCF_WHILEM_VISITED_POS)
6277 f |= SCF_WHILEM_VISITED_POS;
6278 next = regnext(scan);
6279 nscan = NEXTOPER(NEXTOPER(scan));
6281 /* positive lookahead study_chunk() recursion */
6282 *minnextp = study_chunk(pRExC_state, &nscan, minnextp,
6283 &deltanext, last, &data_fake,
6284 stopparen, recursed_depth, NULL,
6285 f, depth+1, mutate_ok);
6287 assert(0); /* This code has never been tested since this
6288 is normally not compiled */
6290 || deltanext > (I32) U8_MAX
6291 || *minnextp > (I32)U8_MAX
6292 || *minnextp + deltanext > (I32)U8_MAX)
6294 FAIL2("Lookbehind longer than %" UVuf " not implemented",
6299 scan->next_off = deltanext;
6301 scan->flags = (U8)*minnextp + deltanext;
6306 if (f & SCF_DO_STCLASS_AND) {
6307 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6308 ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;
6311 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6313 if (data_fake.flags & SF_HAS_EVAL)
6314 data->flags |= SF_HAS_EVAL;
6315 data->whilem_c = data_fake.whilem_c;
6316 if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
6318 if (RExC_rx->minlen<*minnextp)
6319 RExC_rx->minlen=*minnextp;
6320 scan_commit(pRExC_state, &data_fake, minnextp, is_inf);
6321 SvREFCNT_dec_NN(data_fake.last_found);
6323 for (i = 0; i < 2; i++) {
6324 if (data_fake.substrs[i].minlenp != minlenp) {
6325 data->substrs[i].min_offset =
6326 data_fake.substrs[i].min_offset;
6327 data->substrs[i].max_offset =
6328 data_fake.substrs[i].max_offset;
6329 data->substrs[i].minlenp =
6330 data_fake.substrs[i].minlenp;
6331 data->substrs[i].lookbehind += scan->flags;
6339 else if (OP(scan) == OPEN) {
6340 if (stopparen != (I32)ARG(scan))
6343 else if (OP(scan) == CLOSE) {
6344 if (stopparen == (I32)ARG(scan)) {
6347 if ((I32)ARG(scan) == is_par) {
6348 next = regnext(scan);
6350 if ( next && (OP(next) != WHILEM) && next < last)
6351 is_par = 0; /* Disable optimization */
6354 *(data->last_closep) = ARG(scan);
6356 else if (OP(scan) == EVAL) {
6358 data->flags |= SF_HAS_EVAL;
6360 else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
6361 if (flags & SCF_DO_SUBSTR) {
6362 scan_commit(pRExC_state, data, minlenp, is_inf);
6363 flags &= ~SCF_DO_SUBSTR;
6365 if (data && OP(scan)==ACCEPT) {
6366 data->flags |= SCF_SEEN_ACCEPT;
6371 else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
6373 if (flags & SCF_DO_SUBSTR) {
6374 scan_commit(pRExC_state, data, minlenp, is_inf);
6375 data->cur_is_floating = 1; /* float */
6377 is_inf = is_inf_internal = 1;
6378 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
6379 ssc_anything(data->start_class);
6380 flags &= ~SCF_DO_STCLASS;
6382 else if (OP(scan) == GPOS) {
6383 if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&
6384 !(delta || is_inf || (data && data->pos_delta)))
6386 if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))
6387 RExC_rx->intflags |= PREGf_ANCH_GPOS;
6388 if (RExC_rx->gofs < (STRLEN)min)
6389 RExC_rx->gofs = min;
6391 RExC_rx->intflags |= PREGf_GPOS_FLOAT;
6395 #ifdef TRIE_STUDY_OPT
6396 #ifdef FULL_TRIE_STUDY
6397 else if (PL_regkind[OP(scan)] == TRIE) {
6398 /* NOTE - There is similar code to this block above for handling
6399 BRANCH nodes on the initial study. If you change stuff here
6401 regnode *trie_node= scan;
6402 regnode *tail= regnext(scan);
6403 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6404 SSize_t max1 = 0, min1 = OPTIMIZE_INFTY;
6407 if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */
6408 /* Cannot merge strings after this. */
6409 scan_commit(pRExC_state, data, minlenp, is_inf);
6411 if (flags & SCF_DO_STCLASS)
6412 ssc_init_zero(pRExC_state, &accum);
6418 const regnode *nextbranch= NULL;
6421 for ( word=1 ; word <= trie->wordcount ; word++)
6423 SSize_t deltanext=0, minnext=0, f = 0, fake;
6424 regnode_ssc this_class;
6426 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6428 data_fake.whilem_c = data->whilem_c;
6429 data_fake.last_closep = data->last_closep;
6432 data_fake.last_closep = &fake;
6433 data_fake.pos_delta = delta;
6434 if (flags & SCF_DO_STCLASS) {
6435 ssc_init(pRExC_state, &this_class);
6436 data_fake.start_class = &this_class;
6437 f = SCF_DO_STCLASS_AND;
6439 if (flags & SCF_WHILEM_VISITED_POS)
6440 f |= SCF_WHILEM_VISITED_POS;
6442 if (trie->jump[word]) {
6444 nextbranch = trie_node + trie->jump[0];
6445 scan= trie_node + trie->jump[word];
6446 /* We go from the jump point to the branch that follows
6447 it. Note this means we need the vestigal unused
6448 branches even though they arent otherwise used. */
6449 /* optimise study_chunk() for TRIE */
6450 minnext = study_chunk(pRExC_state, &scan, minlenp,
6451 &deltanext, (regnode *)nextbranch, &data_fake,
6452 stopparen, recursed_depth, NULL, f, depth+1,
6455 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
6456 nextbranch= regnext((regnode*)nextbranch);
6458 if (min1 > (SSize_t)(minnext + trie->minlen))
6459 min1 = minnext + trie->minlen;
6460 if (deltanext == OPTIMIZE_INFTY) {
6461 is_inf = is_inf_internal = 1;
6462 max1 = OPTIMIZE_INFTY;
6463 } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))
6464 max1 = minnext + deltanext + trie->maxlen;
6466 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6468 if (data_fake.flags & SCF_SEEN_ACCEPT) {
6469 if ( stopmin > min + min1)
6470 stopmin = min + min1;
6471 flags &= ~SCF_DO_SUBSTR;
6473 data->flags |= SCF_SEEN_ACCEPT;
6476 if (data_fake.flags & SF_HAS_EVAL)
6477 data->flags |= SF_HAS_EVAL;
6478 data->whilem_c = data_fake.whilem_c;
6480 if (flags & SCF_DO_STCLASS)
6481 ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);
6484 if (flags & SCF_DO_SUBSTR) {
6485 data->pos_min += min1;
6486 data->pos_delta += max1 - min1;
6487 if (max1 != min1 || is_inf)
6488 data->cur_is_floating = 1; /* float */
6491 if (delta != OPTIMIZE_INFTY) {
6492 if (OPTIMIZE_INFTY - (max1 - min1) >= delta)
6493 delta += max1 - min1;
6495 delta = OPTIMIZE_INFTY;
6497 if (flags & SCF_DO_STCLASS_OR) {
6498 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6500 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6501 flags &= ~SCF_DO_STCLASS;
6504 else if (flags & SCF_DO_STCLASS_AND) {
6506 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6507 flags &= ~SCF_DO_STCLASS;
6510 /* Switch to OR mode: cache the old value of
6511 * data->start_class */
6513 StructCopy(data->start_class, and_withp, regnode_ssc);
6514 flags &= ~SCF_DO_STCLASS_AND;
6515 StructCopy(&accum, data->start_class, regnode_ssc);
6516 flags |= SCF_DO_STCLASS_OR;
6523 else if (PL_regkind[OP(scan)] == TRIE) {
6524 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6527 min += trie->minlen;
6528 delta += (trie->maxlen - trie->minlen);
6529 flags &= ~SCF_DO_STCLASS; /* xxx */
6530 if (flags & SCF_DO_SUBSTR) {
6531 /* Cannot expect anything... */
6532 scan_commit(pRExC_state, data, minlenp, is_inf);
6533 data->pos_min += trie->minlen;
6534 data->pos_delta += (trie->maxlen - trie->minlen);
6535 if (trie->maxlen != trie->minlen)
6536 data->cur_is_floating = 1; /* float */
6538 if (trie->jump) /* no more substrings -- for now /grr*/
6539 flags &= ~SCF_DO_SUBSTR;
6541 else if (OP(scan) == REGEX_SET) {
6542 Perl_croak(aTHX_ "panic: %s regnode should be resolved"
6543 " before optimization", reg_name[REGEX_SET]);
6546 #endif /* old or new */
6547 #endif /* TRIE_STUDY_OPT */
6549 /* Else: zero-length, ignore. */
6550 scan = regnext(scan);
6555 /* we need to unwind recursion. */
6558 DEBUG_STUDYDATA("frame-end", data, depth, is_inf);
6559 DEBUG_PEEP("fend", scan, depth, flags);
6561 /* restore previous context */
6562 last = frame->last_regnode;
6563 scan = frame->next_regnode;
6564 stopparen = frame->stopparen;
6565 recursed_depth = frame->prev_recursed_depth;
6567 RExC_frame_last = frame->prev_frame;
6568 frame = frame->this_prev_frame;
6569 goto fake_study_recurse;
6573 DEBUG_STUDYDATA("pre-fin", data, depth, is_inf);
6576 *deltap = is_inf_internal ? OPTIMIZE_INFTY : delta;
6578 if (flags & SCF_DO_SUBSTR && is_inf)
6579 data->pos_delta = OPTIMIZE_INFTY - data->pos_min;
6580 if (is_par > (I32)U8_MAX)
6582 if (is_par && pars==1 && data) {
6583 data->flags |= SF_IN_PAR;
6584 data->flags &= ~SF_HAS_PAR;
6586 else if (pars && data) {
6587 data->flags |= SF_HAS_PAR;
6588 data->flags &= ~SF_IN_PAR;
6590 if (flags & SCF_DO_STCLASS_OR)
6591 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6592 if (flags & SCF_TRIE_RESTUDY)
6593 data->flags |= SCF_TRIE_RESTUDY;
6595 DEBUG_STUDYDATA("post-fin", data, depth, is_inf);
6597 final_minlen = min < stopmin
6600 if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {
6601 if (final_minlen > OPTIMIZE_INFTY - delta)
6602 RExC_maxlen = OPTIMIZE_INFTY;
6603 else if (RExC_maxlen < final_minlen + delta)
6604 RExC_maxlen = final_minlen + delta;
6606 return final_minlen;
6610 S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n)
6612 U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
6614 PERL_ARGS_ASSERT_ADD_DATA;
6616 Renewc(RExC_rxi->data,
6617 sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
6618 char, struct reg_data);
6620 Renew(RExC_rxi->data->what, count + n, U8);
6622 Newx(RExC_rxi->data->what, n, U8);
6623 RExC_rxi->data->count = count + n;
6624 Copy(s, RExC_rxi->data->what + count, n, U8);
6628 /*XXX: todo make this not included in a non debugging perl, but appears to be
6629 * used anyway there, in 'use re' */
6630 #ifndef PERL_IN_XSUB_RE
6632 Perl_reginitcolors(pTHX)
6634 const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
6636 char *t = savepv(s);
6640 t = strchr(t, '\t');
6646 PL_colors[i] = t = (char *)"";
6651 PL_colors[i++] = (char *)"";
6658 #ifdef TRIE_STUDY_OPT
6659 #define CHECK_RESTUDY_GOTO_butfirst(dOsomething) \
6662 (data.flags & SCF_TRIE_RESTUDY) \
6670 #define CHECK_RESTUDY_GOTO_butfirst
6674 * pregcomp - compile a regular expression into internal code
6676 * Decides which engine's compiler to call based on the hint currently in
6680 #ifndef PERL_IN_XSUB_RE
6682 /* return the currently in-scope regex engine (or the default if none) */
6684 regexp_engine const *
6685 Perl_current_re_engine(pTHX)
6687 if (IN_PERL_COMPILETIME) {
6688 HV * const table = GvHV(PL_hintgv);
6691 if (!table || !(PL_hints & HINT_LOCALIZE_HH))
6692 return &PL_core_reg_engine;
6693 ptr = hv_fetchs(table, "regcomp", FALSE);
6694 if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
6695 return &PL_core_reg_engine;
6696 return INT2PTR(regexp_engine*, SvIV(*ptr));
6700 if (!PL_curcop->cop_hints_hash)
6701 return &PL_core_reg_engine;
6702 ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
6703 if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
6704 return &PL_core_reg_engine;
6705 return INT2PTR(regexp_engine*, SvIV(ptr));
6711 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
6713 regexp_engine const *eng = current_re_engine();
6714 DECLARE_AND_GET_RE_DEBUG_FLAGS;
6716 PERL_ARGS_ASSERT_PREGCOMP;
6718 /* Dispatch a request to compile a regexp to correct regexp engine. */
6720 Perl_re_printf( aTHX_ "Using engine %" UVxf "\n",
6723 return CALLREGCOMP_ENG(eng, pattern, flags);
6727 /* public(ish) entry point for the perl core's own regex compiling code.
6728 * It's actually a wrapper for Perl_re_op_compile that only takes an SV
6729 * pattern rather than a list of OPs, and uses the internal engine rather
6730 * than the current one */
6733 Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
6735 SV *pat = pattern; /* defeat constness! */
6737 PERL_ARGS_ASSERT_RE_COMPILE;
6739 return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
6740 #ifdef PERL_IN_XSUB_RE
6743 &PL_core_reg_engine,
6745 NULL, NULL, rx_flags, 0);
6749 S_free_codeblocks(pTHX_ struct reg_code_blocks *cbs)
6753 if (--cbs->refcnt > 0)
6755 for (n = 0; n < cbs->count; n++) {
6756 REGEXP *rx = cbs->cb[n].src_regex;
6758 cbs->cb[n].src_regex = NULL;
6759 SvREFCNT_dec_NN(rx);
6767 static struct reg_code_blocks *
6768 S_alloc_code_blocks(pTHX_ int ncode)
6770 struct reg_code_blocks *cbs;
6771 Newx(cbs, 1, struct reg_code_blocks);
6774 SAVEDESTRUCTOR_X(S_free_codeblocks, cbs);
6776 Newx(cbs->cb, ncode, struct reg_code_block);
6783 /* upgrade pattern pat_p of length plen_p to UTF8, and if there are code
6784 * blocks, recalculate the indices. Update pat_p and plen_p in-place to
6785 * point to the realloced string and length.
6787 * This is essentially a copy of Perl_bytes_to_utf8() with the code index
6791 S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state,
6792 char **pat_p, STRLEN *plen_p, int num_code_blocks)
6794 U8 *const src = (U8*)*pat_p;
6799 DECLARE_AND_GET_RE_DEBUG_FLAGS;
6801 DEBUG_PARSE_r(Perl_re_printf( aTHX_
6802 "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
6804 /* 1 for each byte + 1 for each byte that expands to two, + trailing NUL */
6805 Newx(dst, *plen_p + variant_under_utf8_count(src, src + *plen_p) + 1, U8);
6808 while (s < *plen_p) {
6809 append_utf8_from_native_byte(src[s], &d);
6811 if (n < num_code_blocks) {
6812 assert(pRExC_state->code_blocks);
6813 if (!do_end && pRExC_state->code_blocks->cb[n].start == s) {
6814 pRExC_state->code_blocks->cb[n].start = d - dst - 1;
6815 assert(*(d - 1) == '(');
6818 else if (do_end && pRExC_state->code_blocks->cb[n].end == s) {
6819 pRExC_state->code_blocks->cb[n].end = d - dst - 1;
6820 assert(*(d - 1) == ')');
6829 *pat_p = (char*) dst;
6831 RExC_orig_utf8 = RExC_utf8 = 1;
6836 /* S_concat_pat(): concatenate a list of args to the pattern string pat,
6837 * while recording any code block indices, and handling overloading,
6838 * nested qr// objects etc. If pat is null, it will allocate a new
6839 * string, or just return the first arg, if there's only one.
6841 * Returns the malloced/updated pat.
6842 * patternp and pat_count is the array of SVs to be concatted;
6843 * oplist is the optional list of ops that generated the SVs;
6844 * recompile_p is a pointer to a boolean that will be set if
6845 * the regex will need to be recompiled.
6846 * delim, if non-null is an SV that will be inserted between each element
6850 S_concat_pat(pTHX_ RExC_state_t * const pRExC_state,
6851 SV *pat, SV ** const patternp, int pat_count,
6852 OP *oplist, bool *recompile_p, SV *delim)
6856 bool use_delim = FALSE;
6857 bool alloced = FALSE;
6859 /* if we know we have at least two args, create an empty string,
6860 * then concatenate args to that. For no args, return an empty string */
6861 if (!pat && pat_count != 1) {
6867 for (svp = patternp; svp < patternp + pat_count; svp++) {
6870 STRLEN orig_patlen = 0;
6872 SV *msv = use_delim ? delim : *svp;
6873 if (!msv) msv = &PL_sv_undef;
6875 /* if we've got a delimiter, we go round the loop twice for each
6876 * svp slot (except the last), using the delimiter the second
6885 if (SvTYPE(msv) == SVt_PVAV) {
6886 /* we've encountered an interpolated array within
6887 * the pattern, e.g. /...@a..../. Expand the list of elements,
6888 * then recursively append elements.
6889 * The code in this block is based on S_pushav() */
6891 AV *const av = (AV*)msv;
6892 const SSize_t maxarg = AvFILL(av) + 1;
6896 assert(oplist->op_type == OP_PADAV
6897 || oplist->op_type == OP_RV2AV);
6898 oplist = OpSIBLING(oplist);
6901 if (SvRMAGICAL(av)) {
6904 Newx(array, maxarg, SV*);
6906 for (i=0; i < maxarg; i++) {
6907 SV ** const svp = av_fetch(av, i, FALSE);
6908 array[i] = svp ? *svp : &PL_sv_undef;
6912 array = AvARRAY(av);
6914 pat = S_concat_pat(aTHX_ pRExC_state, pat,
6915 array, maxarg, NULL, recompile_p,
6917 GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV))));
6923 /* we make the assumption here that each op in the list of
6924 * op_siblings maps to one SV pushed onto the stack,
6925 * except for code blocks, with have both an OP_NULL and
6927 * This allows us to match up the list of SVs against the
6928 * list of OPs to find the next code block.
6930 * Note that PUSHMARK PADSV PADSV ..
6932 * PADRANGE PADSV PADSV ..
6933 * so the alignment still works. */
6936 if (oplist->op_type == OP_NULL
6937 && (oplist->op_flags & OPf_SPECIAL))
6939 assert(n < pRExC_state->code_blocks->count);
6940 pRExC_state->code_blocks->cb[n].start = pat ? SvCUR(pat) : 0;
6941 pRExC_state->code_blocks->cb[n].block = oplist;
6942 pRExC_state->code_blocks->cb[n].src_regex = NULL;
6945 oplist = OpSIBLING(oplist); /* skip CONST */
6948 oplist = OpSIBLING(oplist);;
6951 /* apply magic and QR overloading to arg */
6954 if (SvROK(msv) && SvAMAGIC(msv)) {
6955 SV *sv = AMG_CALLunary(msv, regexp_amg);
6959 if (SvTYPE(sv) != SVt_REGEXP)
6960 Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
6965 /* try concatenation overload ... */
6966 if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) &&
6967 (sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
6970 /* overloading involved: all bets are off over literal
6971 * code. Pretend we haven't seen it */
6973 pRExC_state->code_blocks->count -= n;
6977 /* ... or failing that, try "" overload */
6978 while (SvAMAGIC(msv)
6979 && (sv = AMG_CALLunary(msv, string_amg))
6983 && SvRV(msv) == SvRV(sv))
6988 if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
6992 /* this is a partially unrolled
6993 * sv_catsv_nomg(pat, msv);
6994 * that allows us to adjust code block indices if
6997 char *dst = SvPV_force_nomg(pat, dlen);
6999 if (SvUTF8(msv) && !SvUTF8(pat)) {
7000 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n);
7001 sv_setpvn(pat, dst, dlen);
7004 sv_catsv_nomg(pat, msv);
7008 /* We have only one SV to process, but we need to verify
7009 * it is properly null terminated or we will fail asserts
7010 * later. In theory we probably shouldn't get such SV's,
7011 * but if we do we should handle it gracefully. */
7012 if ( SvTYPE(msv) != SVt_PV || (SvLEN(msv) > SvCUR(msv) && *(SvEND(msv)) == 0) || SvIsCOW_shared_hash(msv) ) {
7013 /* not a string, or a string with a trailing null */
7016 /* a string with no trailing null, we need to copy it
7017 * so it has a trailing null */
7018 pat = sv_2mortal(newSVsv(msv));
7023 pRExC_state->code_blocks->cb[n-1].end = SvCUR(pat)-1;
7026 /* extract any code blocks within any embedded qr//'s */
7027 if (rx && SvTYPE(rx) == SVt_REGEXP
7028 && RX_ENGINE((REGEXP*)rx)->op_comp)
7031 RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
7032 if (ri->code_blocks && ri->code_blocks->count) {
7034 /* the presence of an embedded qr// with code means
7035 * we should always recompile: the text of the
7036 * qr// may not have changed, but it may be a
7037 * different closure than last time */
7039 if (pRExC_state->code_blocks) {
7040 int new_count = pRExC_state->code_blocks->count
7041 + ri->code_blocks->count;
7042 Renew(pRExC_state->code_blocks->cb,
7043 new_count, struct reg_code_block);
7044 pRExC_state->code_blocks->count = new_count;
7047 pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_
7048 ri->code_blocks->count);
7050 for (i=0; i < ri->code_blocks->count; i++) {
7051 struct reg_code_block *src, *dst;
7052 STRLEN offset = orig_patlen
7053 + ReANY((REGEXP *)rx)->pre_prefix;
7054 assert(n < pRExC_state->code_blocks->count);
7055 src = &ri->code_blocks->cb[i];
7056 dst = &pRExC_state->code_blocks->cb[n];
7057 dst->start = src->start + offset;
7058 dst->end = src->end + offset;
7059 dst->block = src->block;
7060 dst->src_regex = (REGEXP*) SvREFCNT_inc( (SV*)
7069 /* avoid calling magic multiple times on a single element e.g. =~ $qr */
7078 /* see if there are any run-time code blocks in the pattern.
7079 * False positives are allowed */
7082 S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
7083 char *pat, STRLEN plen)
7088 PERL_UNUSED_CONTEXT;
7090 for (s = 0; s < plen; s++) {
7091 if ( pRExC_state->code_blocks
7092 && n < pRExC_state->code_blocks->count
7093 && s == pRExC_state->code_blocks->cb[n].start)
7095 s = pRExC_state->code_blocks->cb[n].end;
7099 /* TODO ideally should handle [..], (#..), /#.../x to reduce false
7101 if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' &&
7103 || (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{'))
7110 /* Handle run-time code blocks. We will already have compiled any direct
7111 * or indirect literal code blocks. Now, take the pattern 'pat' and make a
7112 * copy of it, but with any literal code blocks blanked out and
7113 * appropriate chars escaped; then feed it into
7115 * eval "qr'modified_pattern'"
7119 * a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
7123 * qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
7125 * After eval_sv()-ing that, grab any new code blocks from the returned qr
7126 * and merge them with any code blocks of the original regexp.
7128 * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
7129 * instead, just save the qr and return FALSE; this tells our caller that
7130 * the original pattern needs upgrading to utf8.
7134 S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
7135 char *pat, STRLEN plen)
7139 DECLARE_AND_GET_RE_DEBUG_FLAGS;
7141 if (pRExC_state->runtime_code_qr) {
7142 /* this is the second time we've been called; this should
7143 * only happen if the main pattern got upgraded to utf8
7144 * during compilation; re-use the qr we compiled first time
7145 * round (which should be utf8 too)
7147 qr = pRExC_state->runtime_code_qr;
7148 pRExC_state->runtime_code_qr = NULL;
7149 assert(RExC_utf8 && SvUTF8(qr));
7155 int newlen = plen + 7; /* allow for "qr''xx\0" extra chars */
7159 /* determine how many extra chars we need for ' and \ escaping */
7160 for (s = 0; s < plen; s++) {
7161 if (pat[s] == '\'' || pat[s] == '\\')
7165 Newx(newpat, newlen, char);
7167 *p++ = 'q'; *p++ = 'r'; *p++ = '\'';
7169 for (s = 0; s < plen; s++) {
7170 if ( pRExC_state->code_blocks
7171 && n < pRExC_state->code_blocks->count
7172 && s == pRExC_state->code_blocks->cb[n].start)
7174 /* blank out literal code block so that they aren't
7175 * recompiled: eg change from/to:
7185 assert(pat[s] == '(');
7186 assert(pat[s+1] == '?');
7190 while (s < pRExC_state->code_blocks->cb[n].end) {
7198 if (pat[s] == '\'' || pat[s] == '\\')
7203 if (pRExC_state->pm_flags & RXf_PMf_EXTENDED) {
7205 if (pRExC_state->pm_flags & RXf_PMf_EXTENDED_MORE) {
7211 Perl_re_printf( aTHX_
7212 "%sre-parsing pattern for runtime code:%s %s\n",
7213 PL_colors[4], PL_colors[5], newpat);
7216 sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
7222 PUSHSTACKi(PERLSI_REQUIRE);
7223 /* G_RE_REPARSING causes the toker to collapse \\ into \ when
7224 * parsing qr''; normally only q'' does this. It also alters
7226 eval_sv(sv, G_SCALAR|G_RE_REPARSING);
7227 SvREFCNT_dec_NN(sv);
7232 SV * const errsv = ERRSV;
7233 if (SvTRUE_NN(errsv))
7234 /* use croak_sv ? */
7235 Perl_croak_nocontext("%" SVf, SVfARG(errsv));
7237 assert(SvROK(qr_ref));
7239 assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
7240 /* the leaving below frees the tmp qr_ref.
7241 * Give qr a life of its own */
7249 if (!RExC_utf8 && SvUTF8(qr)) {
7250 /* first time through; the pattern got upgraded; save the
7251 * qr for the next time through */
7252 assert(!pRExC_state->runtime_code_qr);
7253 pRExC_state->runtime_code_qr = qr;
7258 /* extract any code blocks within the returned qr// */
7261 /* merge the main (r1) and run-time (r2) code blocks into one */
7263 RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
7264 struct reg_code_block *new_block, *dst;
7265 RExC_state_t * const r1 = pRExC_state; /* convenient alias */
7269 if (!r2->code_blocks || !r2->code_blocks->count) /* we guessed wrong */
7271 SvREFCNT_dec_NN(qr);
7275 if (!r1->code_blocks)
7276 r1->code_blocks = S_alloc_code_blocks(aTHX_ 0);
7278 r1c = r1->code_blocks->count;
7279 r2c = r2->code_blocks->count;
7281 Newx(new_block, r1c + r2c, struct reg_code_block);
7285 while (i1 < r1c || i2 < r2c) {
7286 struct reg_code_block *src;
7290 src = &r2->code_blocks->cb[i2++];
7294 src = &r1->code_blocks->cb[i1++];
7295 else if ( r1->code_blocks->cb[i1].start
7296 < r2->code_blocks->cb[i2].start)
7298 src = &r1->code_blocks->cb[i1++];
7299 assert(src->end < r2->code_blocks->cb[i2].start);
7302 assert( r1->code_blocks->cb[i1].start
7303 > r2->code_blocks->cb[i2].start);
7304 src = &r2->code_blocks->cb[i2++];
7306 assert(src->end < r1->code_blocks->cb[i1].start);
7309 assert(pat[src->start] == '(');
7310 assert(pat[src->end] == ')');
7311 dst->start = src->start;
7312 dst->end = src->end;
7313 dst->block = src->block;
7314 dst->src_regex = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
7318 r1->code_blocks->count += r2c;
7319 Safefree(r1->code_blocks->cb);
7320 r1->code_blocks->cb = new_block;
7323 SvREFCNT_dec_NN(qr);
7329 S_setup_longest(pTHX_ RExC_state_t *pRExC_state,
7330 struct reg_substr_datum *rsd,
7331 struct scan_data_substrs *sub,
7332 STRLEN longest_length)
7334 /* This is the common code for setting up the floating and fixed length
7335 * string data extracted from Perl_re_op_compile() below. Returns a boolean
7336 * as to whether succeeded or not */
7340 bool eol = cBOOL(sub->flags & SF_BEFORE_EOL);
7341 bool meol = cBOOL(sub->flags & SF_BEFORE_MEOL);
7343 if (! (longest_length
7344 || (eol /* Can't have SEOL and MULTI */
7345 && (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
7347 /* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */
7348 || (RExC_seen & REG_UNFOLDED_MULTI_SEEN))
7353 /* copy the information about the longest from the reg_scan_data
7354 over to the program. */
7355 if (SvUTF8(sub->str)) {
7357 rsd->utf8_substr = sub->str;
7359 rsd->substr = sub->str;
7360 rsd->utf8_substr = NULL;
7362 /* end_shift is how many chars that must be matched that
7363 follow this item. We calculate it ahead of time as once the
7364 lookbehind offset is added in we lose the ability to correctly
7366 ml = sub->minlenp ? *(sub->minlenp) : (SSize_t)longest_length;
7367 rsd->end_shift = ml - sub->min_offset
7369 /* XXX SvTAIL is always false here - did you mean FBMcf_TAIL
7371 + (SvTAIL(sub->str) != 0)
7375 t = (eol/* Can't have SEOL and MULTI */
7376 && (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
7377 fbm_compile(sub->str, t ? FBMcf_TAIL : 0);
7383 S_set_regex_pv(pTHX_ RExC_state_t *pRExC_state, REGEXP *Rx)
7385 /* Calculates and sets in the compiled pattern 'Rx' the string to compile,
7386 * properly wrapped with the right modifiers */
7388 bool has_p = ((RExC_rx->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
7389 bool has_charset = RExC_utf8 || (get_regex_charset(RExC_rx->extflags)
7390 != REGEX_DEPENDS_CHARSET);
7392 /* The caret is output if there are any defaults: if not all the STD
7393 * flags are set, or if no character set specifier is needed */
7395 (((RExC_rx->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
7397 bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN)
7398 == REG_RUN_ON_COMMENT_SEEN);
7399 U8 reganch = (U8)((RExC_rx->extflags & RXf_PMf_STD_PMMOD)
7400 >> RXf_PMf_STD_PMMOD_SHIFT);
7401 const char *fptr = STD_PAT_MODS; /*"msixxn"*/
7403 STRLEN pat_len = RExC_precomp_end - RExC_precomp;
7405 /* We output all the necessary flags; we never output a minus, as all
7406 * those are defaults, so are
7407 * covered by the caret */
7408 const STRLEN wraplen = pat_len + has_p + has_runon
7409 + has_default /* If needs a caret */
7410 + PL_bitcount[reganch] /* 1 char for each set standard flag */
7412 /* If needs a character set specifier */
7413 + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
7414 + (sizeof("(?:)") - 1);
7416 PERL_ARGS_ASSERT_SET_REGEX_PV;
7418 /* make sure PL_bitcount bounds not exceeded */
7419 STATIC_ASSERT_STMT(sizeof(STD_PAT_MODS) <= 8);
7421 p = sv_grow(MUTABLE_SV(Rx), wraplen + 1); /* +1 for the ending NUL */
7424 SvFLAGS(Rx) |= SVf_UTF8;
7427 /* If a default, cover it using the caret */
7429 *p++= DEFAULT_PAT_MOD;
7435 name = get_regex_charset_name(RExC_rx->extflags, &len);
7436 if (strEQ(name, DEPENDS_PAT_MODS)) { /* /d under UTF-8 => /u */
7438 name = UNICODE_PAT_MODS;
7439 len = sizeof(UNICODE_PAT_MODS) - 1;
7441 Copy(name, p, len, char);
7445 *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
7448 while((ch = *fptr++)) {
7456 Copy(RExC_precomp, p, pat_len, char);
7457 assert ((RX_WRAPPED(Rx) - p) < 16);
7458 RExC_rx->pre_prefix = p - RX_WRAPPED(Rx);
7461 /* Adding a trailing \n causes this to compile properly:
7462 my $R = qr / A B C # D E/x; /($R)/
7463 Otherwise the parens are considered part of the comment */
7468 SvCUR_set(Rx, p - RX_WRAPPED(Rx));
7472 * Perl_re_op_compile - the perl internal RE engine's function to compile a
7473 * regular expression into internal code.
7474 * The pattern may be passed either as:
7475 * a list of SVs (patternp plus pat_count)
7476 * a list of OPs (expr)
7477 * If both are passed, the SV list is used, but the OP list indicates
7478 * which SVs are actually pre-compiled code blocks
7480 * The SVs in the list have magic and qr overloading applied to them (and
7481 * the list may be modified in-place with replacement SVs in the latter
7484 * If the pattern hasn't changed from old_re, then old_re will be
7487 * eng is the current engine. If that engine has an op_comp method, then
7488 * handle directly (i.e. we assume that op_comp was us); otherwise, just
7489 * do the initial concatenation of arguments and pass on to the external
7492 * If is_bare_re is not null, set it to a boolean indicating whether the
7493 * arg list reduced (after overloading) to a single bare regex which has
7494 * been returned (i.e. /$qr/).
7496 * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
7498 * pm_flags contains the PMf_* flags, typically based on those from the
7499 * pm_flags field of the related PMOP. Currently we're only interested in
7500 * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL, PMf_WILDCARD.
7502 * For many years this code had an initial sizing pass that calculated
7503 * (sometimes incorrectly, leading to security holes) the size needed for the
7504 * compiled pattern. That was changed by commit
7505 * 7c932d07cab18751bfc7515b4320436273a459e2 in 5.29, which reallocs the size, a
7506 * node at a time, as parsing goes along. Patches welcome to fix any obsolete
7507 * references to this sizing pass.
7509 * Now, an initial crude guess as to the size needed is made, based on the
7510 * length of the pattern. Patches welcome to improve that guess. That amount
7511 * of space is malloc'd and then immediately freed, and then clawed back node
7512 * by node. This design is to minimze, to the extent possible, memory churn
7513 * when doing the reallocs.
7515 * A separate parentheses counting pass may be needed in some cases.
7516 * (Previously the sizing pass did this.) Patches welcome to reduce the number
7519 * The existence of a sizing pass necessitated design decisions that are no
7520 * longer needed. There are potential areas of simplification.
7522 * Beware that the optimization-preparation code in here knows about some
7523 * of the structure of the compiled regexp. [I'll say.]
7527 Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
7528 OP *expr, const regexp_engine* eng, REGEXP *old_re,
7529 bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags)
7532 REGEXP *Rx; /* Capital 'R' means points to a REGEXP */
7540 SV** new_patternp = patternp;
7542 /* these are all flags - maybe they should be turned
7543 * into a single int with different bit masks */
7544 I32 sawlookahead = 0;
7549 regex_charset initial_charset = get_regex_charset(orig_rx_flags);
7551 bool runtime_code = 0;
7553 RExC_state_t RExC_state;
7554 RExC_state_t * const pRExC_state = &RExC_state;
7555 #ifdef TRIE_STUDY_OPT
7557 RExC_state_t copyRExC_state;
7559 DECLARE_AND_GET_RE_DEBUG_FLAGS;
7561 PERL_ARGS_ASSERT_RE_OP_COMPILE;
7563 DEBUG_r(if (!PL_colorset) reginitcolors());
7566 pRExC_state->warn_text = NULL;
7567 pRExC_state->unlexed_names = NULL;
7568 pRExC_state->code_blocks = NULL;
7571 *is_bare_re = FALSE;
7573 if (expr && (expr->op_type == OP_LIST ||
7574 (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
7575 /* allocate code_blocks if needed */
7579 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o))
7580 if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
7581 ncode++; /* count of DO blocks */
7584 pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode);
7588 /* compile-time pattern with just OP_CONSTs and DO blocks */
7593 /* find how many CONSTs there are */
7596 if (expr->op_type == OP_CONST)
7599 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7600 if (o->op_type == OP_CONST)
7604 /* fake up an SV array */
7606 assert(!new_patternp);
7607 Newx(new_patternp, n, SV*);
7608 SAVEFREEPV(new_patternp);
7612 if (expr->op_type == OP_CONST)
7613 new_patternp[n] = cSVOPx_sv(expr);
7615 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7616 if (o->op_type == OP_CONST)
7617 new_patternp[n++] = cSVOPo_sv;
7622 DEBUG_PARSE_r(Perl_re_printf( aTHX_
7623 "Assembling pattern from %d elements%s\n", pat_count,
7624 orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7626 /* set expr to the first arg op */
7628 if (pRExC_state->code_blocks && pRExC_state->code_blocks->count
7629 && expr->op_type != OP_CONST)
7631 expr = cLISTOPx(expr)->op_first;
7632 assert( expr->op_type == OP_PUSHMARK
7633 || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)
7634 || expr->op_type == OP_PADRANGE);
7635 expr = OpSIBLING(expr);
7638 pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,
7639 expr, &recompile, NULL);
7641 /* handle bare (possibly after overloading) regex: foo =~ $re */
7646 if (SvTYPE(re) == SVt_REGEXP) {
7650 DEBUG_PARSE_r(Perl_re_printf( aTHX_
7651 "Precompiled pattern%s\n",
7652 orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7658 exp = SvPV_nomg(pat, plen);
7660 if (!eng->op_comp) {
7661 if ((SvUTF8(pat) && IN_BYTES)
7662 || SvGMAGICAL(pat) || SvAMAGIC(pat))
7664 /* make a temporary copy; either to convert to bytes,
7665 * or to avoid repeating get-magic / overloaded stringify */
7666 pat = newSVpvn_flags(exp, plen, SVs_TEMP |
7667 (IN_BYTES ? 0 : SvUTF8(pat)));
7669 return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
7672 /* ignore the utf8ness if the pattern is 0 length */
7673 RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
7674 RExC_uni_semantics = 0;
7675 RExC_contains_locale = 0;
7676 RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT);
7677 RExC_in_script_run = 0;
7678 RExC_study_started = 0;
7679 pRExC_state->runtime_code_qr = NULL;
7680 RExC_frame_head= NULL;
7681 RExC_frame_last= NULL;
7682 RExC_frame_count= 0;
7683 RExC_latest_warn_offset = 0;
7684 RExC_use_BRANCHJ = 0;
7685 RExC_warned_WARN_EXPERIMENTAL__VLB = 0;
7686 RExC_warned_WARN_EXPERIMENTAL__REGEX_SETS = 0;
7687 RExC_total_parens = 0;
7688 RExC_open_parens = NULL;
7689 RExC_close_parens = NULL;
7690 RExC_paren_names = NULL;
7692 RExC_seen_d_op = FALSE;
7694 RExC_paren_name_list = NULL;
7698 RExC_mysv1= sv_newmortal();
7699 RExC_mysv2= sv_newmortal();
7703 SV *dsv= sv_newmortal();
7704 RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7705 Perl_re_printf( aTHX_ "%sCompiling REx%s %s\n",
7706 PL_colors[4], PL_colors[5], s);
7709 /* we jump here if we have to recompile, e.g., from upgrading the pattern
7712 if ((pm_flags & PMf_USE_RE_EVAL)
7713 /* this second condition covers the non-regex literal case,
7714 * i.e. $foo =~ '(?{})'. */
7715 || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))
7717 runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);
7720 /* return old regex if pattern hasn't changed */
7721 /* XXX: note in the below we have to check the flags as well as the
7724 * Things get a touch tricky as we have to compare the utf8 flag
7725 * independently from the compile flags. */
7729 && !!RX_UTF8(old_re) == !!RExC_utf8
7730 && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )
7731 && RX_PRECOMP(old_re)
7732 && RX_PRELEN(old_re) == plen
7733 && memEQ(RX_PRECOMP(old_re), exp, plen)
7734 && !runtime_code /* with runtime code, always recompile */ )
7737 SV *dsv= sv_newmortal();
7738 RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7739 Perl_re_printf( aTHX_ "%sSkipping recompilation of unchanged REx%s %s\n",
7740 PL_colors[4], PL_colors[5], s);
7745 /* Allocate the pattern's SV */
7746 RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP);
7747 RExC_rx = ReANY(Rx);
7748 if ( RExC_rx == NULL )
7749 FAIL("Regexp out of space");
7751 rx_flags = orig_rx_flags;
7753 if ( (UTF || RExC_uni_semantics)
7754 && initial_charset == REGEX_DEPENDS_CHARSET)
7757 /* Set to use unicode semantics if the pattern is in utf8 and has the
7758 * 'depends' charset specified, as it means unicode when utf8 */
7759 set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
7760 RExC_uni_semantics = 1;
7763 RExC_pm_flags = pm_flags;
7766 assert(TAINTING_get || !TAINT_get);
7768 Perl_croak(aTHX_ "Eval-group in insecure regular expression");
7770 if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
7771 /* whoops, we have a non-utf8 pattern, whilst run-time code
7772 * got compiled as utf8. Try again with a utf8 pattern */
7773 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7774 pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7778 assert(!pRExC_state->runtime_code_qr);
7784 RExC_in_lookbehind = 0;
7785 RExC_in_lookahead = 0;
7786 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
7787 RExC_recode_x_to_native = 0;
7788 RExC_in_multi_char_class = 0;
7790 RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp;
7791 RExC_precomp_end = RExC_end = exp + plen;
7793 RExC_whilem_seen = 0;
7795 RExC_recurse = NULL;
7796 RExC_study_chunk_recursed = NULL;
7797 RExC_study_chunk_recursed_bytes= 0;
7798 RExC_recurse_count = 0;
7799 RExC_sets_depth = 0;
7800 pRExC_state->code_index = 0;
7802 /* Initialize the string in the compiled pattern. This is so that there is
7803 * something to output if necessary */
7804 set_regex_pv(pRExC_state, Rx);
7807 Perl_re_printf( aTHX_
7808 "Starting parse and generation\n");
7810 RExC_lastparse=NULL;
7813 /* Allocate space and zero-initialize. Note, the two step process
7814 of zeroing when in debug mode, thus anything assigned has to
7815 happen after that */
7818 /* On the first pass of the parse, we guess how big this will be. Then
7819 * we grow in one operation to that amount and then give it back. As
7820 * we go along, we re-allocate what we need.
7822 * XXX Currently the guess is essentially that the pattern will be an
7823 * EXACT node with one byte input, one byte output. This is crude, and
7824 * better heuristics are welcome.
7826 * On any subsequent passes, we guess what we actually computed in the
7827 * latest earlier pass. Such a pass probably didn't complete so is
7828 * missing stuff. We could improve those guesses by knowing where the
7829 * parse stopped, and use the length so far plus apply the above
7830 * assumption to what's left. */
7831 RExC_size = STR_SZ(RExC_end - RExC_start);
7834 Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal);
7835 if ( RExC_rxi == NULL )
7836 FAIL("Regexp out of space");
7838 Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char);
7839 RXi_SET( RExC_rx, RExC_rxi );
7841 /* We start from 0 (over from 0 in the case this is a reparse. The first
7842 * node parsed will give back any excess memory we have allocated so far).
7846 /* non-zero initialization begins here */
7847 RExC_rx->engine= eng;
7848 RExC_rx->extflags = rx_flags;
7849 RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;
7851 if (pm_flags & PMf_IS_QR) {
7852 RExC_rxi->code_blocks = pRExC_state->code_blocks;
7853 if (RExC_rxi->code_blocks) {
7854 RExC_rxi->code_blocks->refcnt++;
7858 RExC_rx->intflags = 0;
7860 RExC_flags = rx_flags; /* don't let top level (?i) bleed */
7863 /* This NUL is guaranteed because the pattern comes from an SV*, and the sv
7864 * code makes sure the final byte is an uncounted NUL. But should this
7865 * ever not be the case, lots of things could read beyond the end of the
7866 * buffer: loops like
7867 * while(isFOO(*RExC_parse)) RExC_parse++;
7868 * strchr(RExC_parse, "foo");
7869 * etc. So it is worth noting. */
7870 assert(*RExC_end == '\0');
7874 RExC_parens_buf_size = 0;
7875 RExC_emit_start = RExC_rxi->program;
7876 pRExC_state->code_index = 0;
7878 *((char*) RExC_emit_start) = (char) REG_MAGIC;
7882 if (reg(pRExC_state, 0, &flags, 1)) {
7884 /* Success!, But we may need to redo the parse knowing how many parens
7885 * there actually are */
7886 if (IN_PARENS_PASS) {
7887 flags |= RESTART_PARSE;
7890 /* We have that number in RExC_npar */
7891 RExC_total_parens = RExC_npar;
7893 /* XXX For backporting, use long jumps if there is any possibility of
7895 if (RExC_size > U16_MAX && ! RExC_use_BRANCHJ) {
7896 RExC_use_BRANCHJ = TRUE;
7897 flags |= RESTART_PARSE;
7900 else if (! MUST_RESTART(flags)) {
7902 Perl_croak(aTHX_ "panic: reg returned failure to re_op_compile, flags=%#" UVxf, (UV) flags);
7905 /* Here, we either have success, or we have to redo the parse for some reason */
7906 if (MUST_RESTART(flags)) {
7908 /* It's possible to write a regexp in ascii that represents Unicode
7909 codepoints outside of the byte range, such as via \x{100}. If we
7910 detect such a sequence we have to convert the entire pattern to utf8
7911 and then recompile, as our sizing calculation will have been based
7912 on 1 byte == 1 character, but we will need to use utf8 to encode
7913 at least some part of the pattern, and therefore must convert the whole
7916 if (flags & NEED_UTF8) {
7918 /* We have stored the offset of the final warning output so far.
7919 * That must be adjusted. Any variant characters between the start
7920 * of the pattern and this warning count for 2 bytes in the final,
7921 * so just add them again */
7922 if (UNLIKELY(RExC_latest_warn_offset > 0)) {
7923 RExC_latest_warn_offset +=
7924 variant_under_utf8_count((U8 *) exp, (U8 *) exp
7925 + RExC_latest_warn_offset);
7927 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7928 pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7929 DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse after upgrade\n"));
7932 DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse\n"));
7935 if (ALL_PARENS_COUNTED) {
7936 /* Make enough room for all the known parens, and zero it */
7937 Renew(RExC_open_parens, RExC_total_parens, regnode_offset);
7938 Zero(RExC_open_parens, RExC_total_parens, regnode_offset);
7939 RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */
7941 Renew(RExC_close_parens, RExC_total_parens, regnode_offset);
7942 Zero(RExC_close_parens, RExC_total_parens, regnode_offset);
7944 else { /* Parse did not complete. Reinitialize the parentheses
7946 RExC_total_parens = 0;
7947 if (RExC_open_parens) {
7948 Safefree(RExC_open_parens);
7949 RExC_open_parens = NULL;
7951 if (RExC_close_parens) {
7952 Safefree(RExC_close_parens);
7953 RExC_close_parens = NULL;
7957 /* Clean up what we did in this parse */
7958 SvREFCNT_dec_NN(RExC_rx_sv);
7963 /* Here, we have successfully parsed and generated the pattern's program
7964 * for the regex engine. We are ready to finish things up and look for
7967 /* Update the string to compile, with correct modifiers, etc */
7968 set_regex_pv(pRExC_state, Rx);
7970 RExC_rx->nparens = RExC_total_parens - 1;
7972 /* Uses the upper 4 bits of the FLAGS field, so keep within that size */
7973 if (RExC_whilem_seen > 15)
7974 RExC_whilem_seen = 15;
7977 Perl_re_printf( aTHX_
7978 "Required size %" IVdf " nodes\n", (IV)RExC_size);
7980 RExC_lastparse=NULL;
7983 #ifdef RE_TRACK_PATTERN_OFFSETS
7984 DEBUG_OFFSETS_r(Perl_re_printf( aTHX_
7985 "%s %" UVuf " bytes for offset annotations.\n",
7986 RExC_offsets ? "Got" : "Couldn't get",
7987 (UV)((RExC_offsets[0] * 2 + 1))));
7988 DEBUG_OFFSETS_r(if (RExC_offsets) {
7989 const STRLEN len = RExC_offsets[0];
7991 DECLARE_AND_GET_RE_DEBUG_FLAGS;
7992 Perl_re_printf( aTHX_
7993 "Offsets: [%" UVuf "]\n\t", (UV)RExC_offsets[0]);
7994 for (i = 1; i <= len; i++) {
7995 if (RExC_offsets[i*2-1] || RExC_offsets[i*2])
7996 Perl_re_printf( aTHX_ "%" UVuf ":%" UVuf "[%" UVuf "] ",
7997 (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]);
7999 Perl_re_printf( aTHX_ "\n");
8003 SetProgLen(RExC_rxi,RExC_size);
8006 DEBUG_DUMP_PRE_OPTIMIZE_r({
8007 SV * const sv = sv_newmortal();
8008 RXi_GET_DECL(RExC_rx, ri);
8010 Perl_re_printf( aTHX_ "Program before optimization:\n");
8012 (void)dumpuntil(RExC_rx, ri->program, ri->program + 1, NULL, NULL,
8017 Perl_re_printf( aTHX_ "Starting post parse optimization\n");
8020 /* XXXX To minimize changes to RE engine we always allocate
8021 3-units-long substrs field. */
8022 Newx(RExC_rx->substrs, 1, struct reg_substr_data);
8023 if (RExC_recurse_count) {
8024 Newx(RExC_recurse, RExC_recurse_count, regnode *);
8025 SAVEFREEPV(RExC_recurse);
8028 if (RExC_seen & REG_RECURSE_SEEN) {
8029 /* Note, RExC_total_parens is 1 + the number of parens in a pattern.
8030 * So its 1 if there are no parens. */
8031 RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) +
8032 ((RExC_total_parens & 0x07) != 0);
8033 Newx(RExC_study_chunk_recursed,
8034 RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
8035 SAVEFREEPV(RExC_study_chunk_recursed);
8039 RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;
8041 RExC_study_chunk_recursed_count= 0;
8043 Zero(RExC_rx->substrs, 1, struct reg_substr_data);
8044 if (RExC_study_chunk_recursed) {
8045 Zero(RExC_study_chunk_recursed,
8046 RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
8050 #ifdef TRIE_STUDY_OPT
8052 StructCopy(&zero_scan_data, &data, scan_data_t);
8053 copyRExC_state = RExC_state;
8056 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n"));
8058 RExC_state = copyRExC_state;
8059 if (seen & REG_TOP_LEVEL_BRANCHES_SEEN)
8060 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
8062 RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN;
8063 StructCopy(&zero_scan_data, &data, scan_data_t);
8066 StructCopy(&zero_scan_data, &data, scan_data_t);
8069 /* Dig out information for optimizations. */
8070 RExC_rx->extflags = RExC_flags; /* was pm_op */
8071 /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
8074 SvUTF8_on(Rx); /* Unicode in it? */
8075 RExC_rxi->regstclass = NULL;
8076 if (RExC_naughty >= TOO_NAUGHTY) /* Probably an expensive pattern. */
8077 RExC_rx->intflags |= PREGf_NAUGHTY;
8078 scan = RExC_rxi->program + 1; /* First BRANCH. */
8080 /* testing for BRANCH here tells us whether there is "must appear"
8081 data in the pattern. If there is then we can use it for optimisations */
8082 if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice.
8085 STRLEN longest_length[2];
8086 regnode_ssc ch_class; /* pointed to by data */
8088 SSize_t last_close = 0; /* pointed to by data */
8089 regnode *first= scan;
8090 regnode *first_next= regnext(first);
8094 * Skip introductions and multiplicators >= 1
8095 * so that we can extract the 'meat' of the pattern that must
8096 * match in the large if() sequence following.
8097 * NOTE that EXACT is NOT covered here, as it is normally
8098 * picked up by the optimiser separately.
8100 * This is unfortunate as the optimiser isnt handling lookahead
8101 * properly currently.
8104 while ((OP(first) == OPEN && (sawopen = 1)) ||
8105 /* An OR of *one* alternative - should not happen now. */
8106 (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
8107 /* for now we can't handle lookbehind IFMATCH*/
8108 (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
8109 (OP(first) == PLUS) ||
8110 (OP(first) == MINMOD) ||
8111 /* An {n,m} with n>0 */
8112 (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
8113 (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
8116 * the only op that could be a regnode is PLUS, all the rest
8117 * will be regnode_1 or regnode_2.
8119 * (yves doesn't think this is true)
8121 if (OP(first) == PLUS)
8124 if (OP(first) == MINMOD)
8126 first += regarglen[OP(first)];
8128 first = NEXTOPER(first);
8129 first_next= regnext(first);
8132 /* Starting-point info. */
8134 DEBUG_PEEP("first:", first, 0, 0);
8135 /* Ignore EXACT as we deal with it later. */
8136 if (PL_regkind[OP(first)] == EXACT) {
8137 if ( OP(first) == EXACT
8138 || OP(first) == LEXACT
8139 || OP(first) == EXACT_REQ8
8140 || OP(first) == LEXACT_REQ8
8141 || OP(first) == EXACTL)
8143 NOOP; /* Empty, get anchored substr later. */
8146 RExC_rxi->regstclass = first;
8149 else if (PL_regkind[OP(first)] == TRIE &&
8150 ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0)
8152 /* this can happen only on restudy */
8153 RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0);
8156 else if (REGNODE_SIMPLE(OP(first)))
8157 RExC_rxi->regstclass = first;
8158 else if (PL_regkind[OP(first)] == BOUND ||
8159 PL_regkind[OP(first)] == NBOUND)
8160 RExC_rxi->regstclass = first;
8161 else if (PL_regkind[OP(first)] == BOL) {
8162 RExC_rx->intflags |= (OP(first) == MBOL
8165 first = NEXTOPER(first);
8168 else if (OP(first) == GPOS) {
8169 RExC_rx->intflags |= PREGf_ANCH_GPOS;
8170 first = NEXTOPER(first);
8173 else if ((!sawopen || !RExC_sawback) &&
8175 (OP(first) == STAR &&
8176 PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
8177 !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks)
8179 /* turn .* into ^.* with an implied $*=1 */
8181 (OP(NEXTOPER(first)) == REG_ANY)
8184 RExC_rx->intflags |= (type | PREGf_IMPLICIT);
8185 first = NEXTOPER(first);
8188 if (sawplus && !sawminmod && !sawlookahead
8189 && (!sawopen || !RExC_sawback)
8190 && !pRExC_state->code_blocks) /* May examine pos and $& */
8191 /* x+ must match at the 1st pos of run of x's */
8192 RExC_rx->intflags |= PREGf_SKIP;
8194 /* Scan is after the zeroth branch, first is atomic matcher. */
8195 #ifdef TRIE_STUDY_OPT
8198 Perl_re_printf( aTHX_ "first at %" IVdf "\n",
8199 (IV)(first - scan + 1))
8203 Perl_re_printf( aTHX_ "first at %" IVdf "\n",
8204 (IV)(first - scan + 1))
8210 * If there's something expensive in the r.e., find the
8211 * longest literal string that must appear and make it the
8212 * regmust. Resolve ties in favor of later strings, since
8213 * the regstart check works with the beginning of the r.e.
8214 * and avoiding duplication strengthens checking. Not a
8215 * strong reason, but sufficient in the absence of others.
8216 * [Now we resolve ties in favor of the earlier string if
8217 * it happens that c_offset_min has been invalidated, since the
8218 * earlier string may buy us something the later one won't.]
8221 data.substrs[0].str = newSVpvs("");
8222 data.substrs[1].str = newSVpvs("");
8223 data.last_found = newSVpvs("");
8224 data.cur_is_floating = 0; /* initially any found substring is fixed */
8225 ENTER_with_name("study_chunk");
8226 SAVEFREESV(data.substrs[0].str);
8227 SAVEFREESV(data.substrs[1].str);
8228 SAVEFREESV(data.last_found);
8230 if (!RExC_rxi->regstclass) {
8231 ssc_init(pRExC_state, &ch_class);
8232 data.start_class = &ch_class;
8233 stclass_flag = SCF_DO_STCLASS_AND;
8234 } else /* XXXX Check for BOUND? */
8236 data.last_closep = &last_close;
8240 * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/
8241 * (NO top level branches)
8243 minlen = study_chunk(pRExC_state, &first, &minlen, &fake,
8244 scan + RExC_size, /* Up to end */
8246 SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
8247 | (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
8251 CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
8254 if ( RExC_total_parens == 1 && !data.cur_is_floating
8255 && data.last_start_min == 0 && data.last_end > 0
8256 && !RExC_seen_zerolen
8257 && !(RExC_seen & REG_VERBARG_SEEN)
8258 && !(RExC_seen & REG_GPOS_SEEN)
8260 RExC_rx->extflags |= RXf_CHECK_ALL;
8262 scan_commit(pRExC_state, &data,&minlen, 0);
8265 /* XXX this is done in reverse order because that's the way the
8266 * code was before it was parameterised. Don't know whether it
8267 * actually needs doing in reverse order. DAPM */
8268 for (i = 1; i >= 0; i--) {
8269 longest_length[i] = CHR_SVLEN(data.substrs[i].str);
8272 && SvCUR(data.substrs[0].str) /* ok to leave SvCUR */
8273 && data.substrs[0].min_offset
8274 == data.substrs[1].min_offset
8275 && SvCUR(data.substrs[0].str)
8276 == SvCUR(data.substrs[1].str)
8278 && S_setup_longest (aTHX_ pRExC_state,
8279 &(RExC_rx->substrs->data[i]),
8283 RExC_rx->substrs->data[i].min_offset =
8284 data.substrs[i].min_offset - data.substrs[i].lookbehind;
8286 RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset;
8287 /* Don't offset infinity */
8288 if (data.substrs[i].max_offset < OPTIMIZE_INFTY)
8289 RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind;
8290 SvREFCNT_inc_simple_void_NN(data.substrs[i].str);
8293 RExC_rx->substrs->data[i].substr = NULL;
8294 RExC_rx->substrs->data[i].utf8_substr = NULL;
8295 longest_length[i] = 0;
8299 LEAVE_with_name("study_chunk");
8301 if (RExC_rxi->regstclass
8302 && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY))
8303 RExC_rxi->regstclass = NULL;
8305 if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr)
8306 || RExC_rx->substrs->data[0].min_offset)
8308 && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8309 && is_ssc_worth_it(pRExC_state, data.start_class))
8311 const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8313 ssc_finalize(pRExC_state, data.start_class);
8315 Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8316 StructCopy(data.start_class,
8317 (regnode_ssc*)RExC_rxi->data->data[n],
8319 RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8320 RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
8321 DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
8322 regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8323 Perl_re_printf( aTHX_
8324 "synthetic stclass \"%s\".\n",
8325 SvPVX_const(sv));});
8326 data.start_class = NULL;
8329 /* A temporary algorithm prefers floated substr to fixed one of
8330 * same length to dig more info. */
8331 i = (longest_length[0] <= longest_length[1]);
8332 RExC_rx->substrs->check_ix = i;
8333 RExC_rx->check_end_shift = RExC_rx->substrs->data[i].end_shift;
8334 RExC_rx->check_substr = RExC_rx->substrs->data[i].substr;
8335 RExC_rx->check_utf8 = RExC_rx->substrs->data[i].utf8_substr;
8336 RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset;
8337 RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset;
8338 if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS)))
8339 RExC_rx->intflags |= PREGf_NOSCAN;
8341 if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) {
8342 RExC_rx->extflags |= RXf_USE_INTUIT;
8343 if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8))
8344 RExC_rx->extflags |= RXf_INTUIT_TAIL;
8347 /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
8348 if ( (STRLEN)minlen < longest_length[1] )
8349 minlen= longest_length[1];
8350 if ( (STRLEN)minlen < longest_length[0] )
8351 minlen= longest_length[0];
8355 /* Several toplevels. Best we can is to set minlen. */
8357 regnode_ssc ch_class;
8358 SSize_t last_close = 0;
8360 DEBUG_PARSE_r(Perl_re_printf( aTHX_ "\nMulti Top Level\n"));
8362 scan = RExC_rxi->program + 1;
8363 ssc_init(pRExC_state, &ch_class);
8364 data.start_class = &ch_class;
8365 data.last_closep = &last_close;
8369 * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../
8370 * (patterns WITH top level branches)
8372 minlen = study_chunk(pRExC_state,
8373 &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL,
8374 SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied
8375 ? SCF_TRIE_DOING_RESTUDY
8379 CHECK_RESTUDY_GOTO_butfirst(NOOP);
8381 RExC_rx->check_substr = NULL;
8382 RExC_rx->check_utf8 = NULL;
8383 RExC_rx->substrs->data[0].substr = NULL;
8384 RExC_rx->substrs->data[0].utf8_substr = NULL;
8385 RExC_rx->substrs->data[1].substr = NULL;
8386 RExC_rx->substrs->data[1].utf8_substr = NULL;
8388 if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8389 && is_ssc_worth_it(pRExC_state, data.start_class))
8391 const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8393 ssc_finalize(pRExC_state, data.start_class);
8395 Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8396 StructCopy(data.start_class,
8397 (regnode_ssc*)RExC_rxi->data->data[n],
8399 RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8400 RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
8401 DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
8402 regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8403 Perl_re_printf( aTHX_
8404 "synthetic stclass \"%s\".\n",
8405 SvPVX_const(sv));});
8406 data.start_class = NULL;
8410 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) {
8411 RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN;
8412 RExC_rx->maxlen = REG_INFTY;
8415 RExC_rx->maxlen = RExC_maxlen;
8418 /* Guard against an embedded (?=) or (?<=) with a longer minlen than
8419 the "real" pattern. */
8421 Perl_re_printf( aTHX_ "minlen: %" IVdf " RExC_rx->minlen:%" IVdf " maxlen:%" IVdf "\n",
8422 (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen);
8424 RExC_rx->minlenret = minlen;
8425 if (RExC_rx->minlen < minlen)
8426 RExC_rx->minlen = minlen;
8428 if (RExC_seen & REG_RECURSE_SEEN ) {
8429 RExC_rx->intflags |= PREGf_RECURSE_SEEN;
8430 Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *);
8432 if (RExC_seen & REG_GPOS_SEEN)
8433 RExC_rx->intflags |= PREGf_GPOS_SEEN;
8434 if (RExC_seen & REG_LOOKBEHIND_SEEN)
8435 RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the
8437 if (pRExC_state->code_blocks)
8438 RExC_rx->extflags |= RXf_EVAL_SEEN;
8439 if (RExC_seen & REG_VERBARG_SEEN)
8441 RExC_rx->intflags |= PREGf_VERBARG_SEEN;
8442 RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */
8444 if (RExC_seen & REG_CUTGROUP_SEEN)
8445 RExC_rx->intflags |= PREGf_CUTGROUP_SEEN;
8446 if (pm_flags & PMf_USE_RE_EVAL)
8447 RExC_rx->intflags |= PREGf_USE_RE_EVAL;
8448 if (RExC_paren_names)
8449 RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
8451 RXp_PAREN_NAMES(RExC_rx) = NULL;
8453 /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED
8454 * so it can be used in pp.c */
8455 if (RExC_rx->intflags & PREGf_ANCH)
8456 RExC_rx->extflags |= RXf_IS_ANCHORED;
8460 /* this is used to identify "special" patterns that might result
8461 * in Perl NOT calling the regex engine and instead doing the match "itself",
8462 * particularly special cases in split//. By having the regex compiler
8463 * do this pattern matching at a regop level (instead of by inspecting the pattern)
8464 * we avoid weird issues with equivalent patterns resulting in different behavior,
8465 * AND we allow non Perl engines to get the same optimizations by the setting the
8466 * flags appropriately - Yves */
8467 regnode *first = RExC_rxi->program + 1;
8469 regnode *next = regnext(first);
8472 if (PL_regkind[fop] == NOTHING && nop == END)
8473 RExC_rx->extflags |= RXf_NULL;
8474 else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END)
8475 /* when fop is SBOL first->flags will be true only when it was
8476 * produced by parsing /\A/, and not when parsing /^/. This is
8477 * very important for the split code as there we want to
8478 * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m.
8479 * See rt #122761 for more details. -- Yves */
8480 RExC_rx->extflags |= RXf_START_ONLY;
8481 else if (fop == PLUS
8482 && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE
8484 RExC_rx->extflags |= RXf_WHITE;
8485 else if ( RExC_rx->extflags & RXf_SPLIT
8486 && ( fop == EXACT || fop == LEXACT
8487 || fop == EXACT_REQ8 || fop == LEXACT_REQ8
8489 && STR_LEN(first) == 1
8490 && *(STRING(first)) == ' '
8492 RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
8496 if (RExC_contains_locale) {
8497 RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED;
8501 if (RExC_paren_names) {
8502 RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a"));
8503 RExC_rxi->data->data[RExC_rxi->name_list_idx]
8504 = (void*)SvREFCNT_inc(RExC_paren_name_list);
8507 RExC_rxi->name_list_idx = 0;
8509 while ( RExC_recurse_count > 0 ) {
8510 const regnode *scan = RExC_recurse[ --RExC_recurse_count ];
8512 * This data structure is set up in study_chunk() and is used
8513 * to calculate the distance between a GOSUB regopcode and
8514 * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's)
8517 * If for some reason someone writes code that optimises
8518 * away a GOSUB opcode then the assert should be changed to
8519 * an if(scan) to guard the ARG2L_SET() - Yves
8522 assert(scan && OP(scan) == GOSUB);
8523 ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan));
8526 Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair);
8527 /* assume we don't need to swap parens around before we match */
8529 Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n",
8530 (unsigned long)RExC_study_chunk_recursed_count);
8534 Perl_re_printf( aTHX_ "Final program:\n");
8538 if (RExC_open_parens) {
8539 Safefree(RExC_open_parens);
8540 RExC_open_parens = NULL;
8542 if (RExC_close_parens) {
8543 Safefree(RExC_close_parens);
8544 RExC_close_parens = NULL;
8548 /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated
8549 * by setting the regexp SV to readonly-only instead. If the
8550 * pattern's been recompiled, the USEDness should remain. */
8551 if (old_re && SvREADONLY(old_re))
8559 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
8562 PERL_ARGS_ASSERT_REG_NAMED_BUFF;
8564 PERL_UNUSED_ARG(value);
8566 if (flags & RXapif_FETCH) {
8567 return reg_named_buff_fetch(rx, key, flags);
8568 } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
8569 Perl_croak_no_modify();
8571 } else if (flags & RXapif_EXISTS) {
8572 return reg_named_buff_exists(rx, key, flags)
8575 } else if (flags & RXapif_REGNAMES) {
8576 return reg_named_buff_all(rx, flags);
8577 } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
8578 return reg_named_buff_scalar(rx, flags);
8580 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
8586 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
8589 PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
8590 PERL_UNUSED_ARG(lastkey);
8592 if (flags & RXapif_FIRSTKEY)
8593 return reg_named_buff_firstkey(rx, flags);
8594 else if (flags & RXapif_NEXTKEY)
8595 return reg_named_buff_nextkey(rx, flags);
8597 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter",
8604 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
8608 struct regexp *const rx = ReANY(r);
8610 PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
8612 if (rx && RXp_PAREN_NAMES(rx)) {
8613 HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
8616 SV* sv_dat=HeVAL(he_str);
8617 I32 *nums=(I32*)SvPVX(sv_dat);
8618 AV * const retarray = (flags & RXapif_ALL) ? newAV() : NULL;
8619 for ( i=0; i<SvIVX(sv_dat); i++ ) {
8620 if ((I32)(rx->nparens) >= nums[i]
8621 && rx->offs[nums[i]].start != -1
8622 && rx->offs[nums[i]].end != -1)
8625 CALLREG_NUMBUF_FETCH(r, nums[i], ret);
8630 ret = newSVsv(&PL_sv_undef);
8633 av_push(retarray, ret);
8636 return newRV_noinc(MUTABLE_SV(retarray));
8643 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
8646 struct regexp *const rx = ReANY(r);
8648 PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
8650 if (rx && RXp_PAREN_NAMES(rx)) {
8651 if (flags & RXapif_ALL) {
8652 return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
8654 SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
8656 SvREFCNT_dec_NN(sv);
8668 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
8670 struct regexp *const rx = ReANY(r);
8672 PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
8674 if ( rx && RXp_PAREN_NAMES(rx) ) {
8675 (void)hv_iterinit(RXp_PAREN_NAMES(rx));
8677 return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
8684 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
8686 struct regexp *const rx = ReANY(r);
8687 DECLARE_AND_GET_RE_DEBUG_FLAGS;
8689 PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
8691 if (rx && RXp_PAREN_NAMES(rx)) {
8692 HV *hv = RXp_PAREN_NAMES(rx);
8694 while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8697 SV* sv_dat = HeVAL(temphe);
8698 I32 *nums = (I32*)SvPVX(sv_dat);
8699 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8700 if ((I32)(rx->lastparen) >= nums[i] &&
8701 rx->offs[nums[i]].start != -1 &&
8702 rx->offs[nums[i]].end != -1)
8708 if (parno || flags & RXapif_ALL) {
8709 return newSVhek(HeKEY_hek(temphe));
8717 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
8722 struct regexp *const rx = ReANY(r);
8724 PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
8726 if (rx && RXp_PAREN_NAMES(rx)) {
8727 if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
8728 return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
8729 } else if (flags & RXapif_ONE) {
8730 ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
8731 av = MUTABLE_AV(SvRV(ret));
8732 length = av_tindex(av);
8733 SvREFCNT_dec_NN(ret);
8734 return newSViv(length + 1);
8736 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar",
8741 return &PL_sv_undef;
8745 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
8747 struct regexp *const rx = ReANY(r);
8750 PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
8752 if (rx && RXp_PAREN_NAMES(rx)) {
8753 HV *hv= RXp_PAREN_NAMES(rx);
8755 (void)hv_iterinit(hv);
8756 while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8759 SV* sv_dat = HeVAL(temphe);
8760 I32 *nums = (I32*)SvPVX(sv_dat);
8761 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8762 if ((I32)(rx->lastparen) >= nums[i] &&
8763 rx->offs[nums[i]].start != -1 &&
8764 rx->offs[nums[i]].end != -1)
8770 if (parno || flags & RXapif_ALL) {
8771 av_push(av, newSVhek(HeKEY_hek(temphe)));
8776 return newRV_noinc(MUTABLE_SV(av));
8780 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
8783 struct regexp *const rx = ReANY(r);
8789 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
8791 if ( n == RX_BUFF_IDX_CARET_PREMATCH
8792 || n == RX_BUFF_IDX_CARET_FULLMATCH
8793 || n == RX_BUFF_IDX_CARET_POSTMATCH
8796 bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8798 /* on something like
8801 * the KEEPCOPY is set on the PMOP rather than the regex */
8802 if (PL_curpm && r == PM_GETRE(PL_curpm))
8803 keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8812 if (n == RX_BUFF_IDX_CARET_FULLMATCH)
8813 /* no need to distinguish between them any more */
8814 n = RX_BUFF_IDX_FULLMATCH;
8816 if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
8817 && rx->offs[0].start != -1)
8819 /* $`, ${^PREMATCH} */
8820 i = rx->offs[0].start;
8824 if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
8825 && rx->offs[0].end != -1)
8827 /* $', ${^POSTMATCH} */
8828 s = rx->subbeg - rx->suboffset + rx->offs[0].end;
8829 i = rx->sublen + rx->suboffset - rx->offs[0].end;
8832 if (inRANGE(n, 0, (I32)rx->nparens) &&
8833 (s1 = rx->offs[n].start) != -1 &&
8834 (t1 = rx->offs[n].end) != -1)
8836 /* $&, ${^MATCH}, $1 ... */
8838 s = rx->subbeg + s1 - rx->suboffset;
8843 assert(s >= rx->subbeg);
8844 assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) );
8846 #ifdef NO_TAINT_SUPPORT
8847 sv_setpvn(sv, s, i);
8849 const int oldtainted = TAINT_get;
8851 sv_setpvn(sv, s, i);
8852 TAINT_set(oldtainted);
8854 if (RXp_MATCH_UTF8(rx))
8859 if (RXp_MATCH_TAINTED(rx)) {
8860 if (SvTYPE(sv) >= SVt_PVMG) {
8861 MAGIC* const mg = SvMAGIC(sv);
8864 SvMAGIC_set(sv, mg->mg_moremagic);
8866 if ((mgt = SvMAGIC(sv))) {
8867 mg->mg_moremagic = mgt;
8868 SvMAGIC_set(sv, mg);
8885 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
8886 SV const * const value)
8888 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
8890 PERL_UNUSED_ARG(rx);
8891 PERL_UNUSED_ARG(paren);
8892 PERL_UNUSED_ARG(value);
8895 Perl_croak_no_modify();
8899 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
8902 struct regexp *const rx = ReANY(r);
8906 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
8908 if ( paren == RX_BUFF_IDX_CARET_PREMATCH
8909 || paren == RX_BUFF_IDX_CARET_FULLMATCH
8910 || paren == RX_BUFF_IDX_CARET_POSTMATCH
8913 bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8915 /* on something like
8918 * the KEEPCOPY is set on the PMOP rather than the regex */
8919 if (PL_curpm && r == PM_GETRE(PL_curpm))
8920 keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8926 /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
8928 case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
8929 case RX_BUFF_IDX_PREMATCH: /* $` */
8930 if (rx->offs[0].start != -1) {
8931 i = rx->offs[0].start;
8940 case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
8941 case RX_BUFF_IDX_POSTMATCH: /* $' */
8942 if (rx->offs[0].end != -1) {
8943 i = rx->sublen - rx->offs[0].end;
8945 s1 = rx->offs[0].end;
8952 default: /* $& / ${^MATCH}, $1, $2, ... */
8953 if (paren <= (I32)rx->nparens &&
8954 (s1 = rx->offs[paren].start) != -1 &&
8955 (t1 = rx->offs[paren].end) != -1)
8961 if (ckWARN(WARN_UNINITIALIZED))
8962 report_uninit((const SV *)sv);
8967 if (i > 0 && RXp_MATCH_UTF8(rx)) {
8968 const char * const s = rx->subbeg - rx->suboffset + s1;
8973 if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
8980 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
8982 PERL_ARGS_ASSERT_REG_QR_PACKAGE;
8983 PERL_UNUSED_ARG(rx);
8987 return newSVpvs("Regexp");
8990 /* Scans the name of a named buffer from the pattern.
8991 * If flags is REG_RSN_RETURN_NULL returns null.
8992 * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
8993 * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
8994 * to the parsed name as looked up in the RExC_paren_names hash.
8995 * If there is an error throws a vFAIL().. type exception.
8998 #define REG_RSN_RETURN_NULL 0
8999 #define REG_RSN_RETURN_NAME 1
9000 #define REG_RSN_RETURN_DATA 2
9003 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
9005 char *name_start = RExC_parse;
9008 PERL_ARGS_ASSERT_REG_SCAN_NAME;
9010 assert (RExC_parse <= RExC_end);
9011 if (RExC_parse == RExC_end) NOOP;
9012 else if (isIDFIRST_lazy_if_safe(RExC_parse, RExC_end, UTF)) {
9013 /* Note that the code here assumes well-formed UTF-8. Skip IDFIRST by
9014 * using do...while */
9017 RExC_parse += UTF8SKIP(RExC_parse);
9018 } while ( RExC_parse < RExC_end
9019 && isWORDCHAR_utf8_safe((U8*)RExC_parse, (U8*) RExC_end));
9023 } while (RExC_parse < RExC_end && isWORDCHAR(*RExC_parse));
9025 RExC_parse++; /* so the <- from the vFAIL is after the offending
9027 vFAIL("Group name must start with a non-digit word character");
9029 sv_name = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
9030 SVs_TEMP | (UTF ? SVf_UTF8 : 0));
9031 if ( flags == REG_RSN_RETURN_NAME)
9033 else if (flags==REG_RSN_RETURN_DATA) {
9036 if ( ! sv_name ) /* should not happen*/
9037 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
9038 if (RExC_paren_names)
9039 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
9041 sv_dat = HeVAL(he_str);
9042 if ( ! sv_dat ) { /* Didn't find group */
9044 /* It might be a forward reference; we can't fail until we
9045 * know, by completing the parse to get all the groups, and
9047 if (ALL_PARENS_COUNTED) {
9048 vFAIL("Reference to nonexistent named group");
9051 REQUIRE_PARENS_PASS;
9057 Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
9058 (unsigned long) flags);
9061 #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
9062 if (RExC_lastparse!=RExC_parse) { \
9063 Perl_re_printf( aTHX_ "%s", \
9064 Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse, \
9065 RExC_end - RExC_parse, 16, \
9067 PERL_PV_ESCAPE_UNI_DETECT | \
9068 PERL_PV_PRETTY_ELLIPSES | \
9069 PERL_PV_PRETTY_LTGT | \
9070 PERL_PV_ESCAPE_RE | \
9071 PERL_PV_PRETTY_EXACTSIZE \
9075 Perl_re_printf( aTHX_ "%16s",""); \
9077 if (RExC_lastnum!=RExC_emit) \
9078 Perl_re_printf( aTHX_ "|%4zu", RExC_emit); \
9080 Perl_re_printf( aTHX_ "|%4s",""); \
9081 Perl_re_printf( aTHX_ "|%*s%-4s", \
9082 (int)((depth*2)), "", \
9085 RExC_lastnum=RExC_emit; \
9086 RExC_lastparse=RExC_parse; \
9091 #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
9092 DEBUG_PARSE_MSG((funcname)); \
9093 Perl_re_printf( aTHX_ "%4s","\n"); \
9095 #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({\
9096 DEBUG_PARSE_MSG((funcname)); \
9097 Perl_re_printf( aTHX_ fmt "\n",args); \
9100 /* This section of code defines the inversion list object and its methods. The
9101 * interfaces are highly subject to change, so as much as possible is static to
9102 * this file. An inversion list is here implemented as a malloc'd C UV array
9103 * as an SVt_INVLIST scalar.
9105 * An inversion list for Unicode is an array of code points, sorted by ordinal
9106 * number. Each element gives the code point that begins a range that extends
9107 * up-to but not including the code point given by the next element. The final
9108 * element gives the first code point of a range that extends to the platform's
9109 * infinity. The even-numbered elements (invlist[0], invlist[2], invlist[4],
9110 * ...) give ranges whose code points are all in the inversion list. We say
9111 * that those ranges are in the set. The odd-numbered elements give ranges
9112 * whose code points are not in the inversion list, and hence not in the set.
9113 * Thus, element [0] is the first code point in the list. Element [1]
9114 * is the first code point beyond that not in the list; and element [2] is the
9115 * first code point beyond that that is in the list. In other words, the first
9116 * range is invlist[0]..(invlist[1]-1), and all code points in that range are
9117 * in the inversion list. The second range is invlist[1]..(invlist[2]-1), and
9118 * all code points in that range are not in the inversion list. The third
9119 * range invlist[2]..(invlist[3]-1) gives code points that are in the inversion
9120 * list, and so forth. Thus every element whose index is divisible by two
9121 * gives the beginning of a range that is in the list, and every element whose
9122 * index is not divisible by two gives the beginning of a range not in the
9123 * list. If the final element's index is divisible by two, the inversion list
9124 * extends to the platform's infinity; otherwise the highest code point in the
9125 * inversion list is the contents of that element minus 1.
9127 * A range that contains just a single code point N will look like
9129 * invlist[i+1] == N+1
9131 * If N is UV_MAX (the highest representable code point on the machine), N+1 is
9132 * impossible to represent, so element [i+1] is omitted. The single element
9134 * invlist[0] == UV_MAX
9135 * contains just UV_MAX, but is interpreted as matching to infinity.
9137 * Taking the complement (inverting) an inversion list is quite simple, if the
9138 * first element is 0, remove it; otherwise add a 0 element at the beginning.
9139 * This implementation reserves an element at the beginning of each inversion
9140 * list to always contain 0; there is an additional flag in the header which
9141 * indicates if the list begins at the 0, or is offset to begin at the next
9142 * element. This means that the inversion list can be inverted without any
9143 * copying; just flip the flag.
9145 * More about inversion lists can be found in "Unicode Demystified"
9146 * Chapter 13 by Richard Gillam, published by Addison-Wesley.
9148 * The inversion list data structure is currently implemented as an SV pointing
9149 * to an array of UVs that the SV thinks are bytes. This allows us to have an
9150 * array of UV whose memory management is automatically handled by the existing
9151 * facilities for SV's.
9153 * Some of the methods should always be private to the implementation, and some
9154 * should eventually be made public */
9156 /* The header definitions are in F<invlist_inline.h> */
9158 #ifndef PERL_IN_XSUB_RE
9160 PERL_STATIC_INLINE UV*
9161 S__invlist_array_init(SV* const invlist, const bool will_have_0)
9163 /* Returns a pointer to the first element in the inversion list's array.
9164 * This is called upon initialization of an inversion list. Where the
9165 * array begins depends on whether the list has the code point U+0000 in it
9166 * or not. The other parameter tells it whether the code that follows this
9167 * call is about to put a 0 in the inversion list or not. The first
9168 * element is either the element reserved for 0, if TRUE, or the element
9169 * after it, if FALSE */
9171 bool* offset = get_invlist_offset_addr(invlist);
9172 UV* zero_addr = (UV *) SvPVX(invlist);
9174 PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
9177 assert(! _invlist_len(invlist));
9181 /* 1^1 = 0; 1^0 = 1 */
9182 *offset = 1 ^ will_have_0;
9183 return zero_addr + *offset;
9187 S_invlist_replace_list_destroys_src(pTHX_ SV * dest, SV * src)
9189 /* Replaces the inversion list in 'dest' with the one from 'src'. It
9190 * steals the list from 'src', so 'src' is made to have a NULL list. This
9191 * is similar to what SvSetMagicSV() would do, if it were implemented on
9192 * inversion lists, though this routine avoids a copy */
9194 const UV src_len = _invlist_len(src);
9195 const bool src_offset = *get_invlist_offset_addr(src);
9196 const STRLEN src_byte_len = SvLEN(src);
9197 char * array = SvPVX(src);
9199 const int oldtainted = TAINT_get;
9201 PERL_ARGS_ASSERT_INVLIST_REPLACE_LIST_DESTROYS_SRC;
9203 assert(is_invlist(src));
9204 assert(is_invlist(dest));
9205 assert(! invlist_is_iterating(src));
9206 assert(SvCUR(src) == 0 || SvCUR(src) < SvLEN(src));
9208 /* Make sure it ends in the right place with a NUL, as our inversion list
9209 * manipulations aren't careful to keep this true, but sv_usepvn_flags()
9211 array[src_byte_len - 1] = '\0';
9213 TAINT_NOT; /* Otherwise it breaks */
9214 sv_usepvn_flags(dest,
9218 /* This flag is documented to cause a copy to be avoided */
9219 SV_HAS_TRAILING_NUL);
9220 TAINT_set(oldtainted);
9225 /* Finish up copying over the other fields in an inversion list */
9226 *get_invlist_offset_addr(dest) = src_offset;
9227 invlist_set_len(dest, src_len, src_offset);
9228 *get_invlist_previous_index_addr(dest) = 0;
9229 invlist_iterfinish(dest);
9232 PERL_STATIC_INLINE IV*
9233 S_get_invlist_previous_index_addr(SV* invlist)
9235 /* Return the address of the IV that is reserved to hold the cached index
9237 PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
9239 assert(is_invlist(invlist));
9241 return &(((XINVLIST*) SvANY(invlist))->prev_index);
9244 PERL_STATIC_INLINE IV
9245 S_invlist_previous_index(SV* const invlist)
9247 /* Returns cached index of previous search */
9249 PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
9251 return *get_invlist_previous_index_addr(invlist);
9254 PERL_STATIC_INLINE void
9255 S_invlist_set_previous_index(SV* const invlist, const IV index)
9257 /* Caches <index> for later retrieval */
9259 PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
9261 assert(index == 0 || index < (int) _invlist_len(invlist));
9263 *get_invlist_previous_index_addr(invlist) = index;
9266 PERL_STATIC_INLINE void
9267 S_invlist_trim(SV* invlist)
9269 /* Free the not currently-being-used space in an inversion list */
9271 /* But don't free up the space needed for the 0 UV that is always at the
9272 * beginning of the list, nor the trailing NUL */
9273 const UV min_size = TO_INTERNAL_SIZE(1) + 1;
9275 PERL_ARGS_ASSERT_INVLIST_TRIM;
9277 assert(is_invlist(invlist));
9279 SvPV_renew(invlist, MAX(min_size, SvCUR(invlist) + 1));
9282 PERL_STATIC_INLINE void
9283 S_invlist_clear(pTHX_ SV* invlist) /* Empty the inversion list */
9285 PERL_ARGS_ASSERT_INVLIST_CLEAR;
9287 assert(is_invlist(invlist));
9289 invlist_set_len(invlist, 0, 0);
9290 invlist_trim(invlist);
9293 #endif /* ifndef PERL_IN_XSUB_RE */
9295 PERL_STATIC_INLINE bool
9296 S_invlist_is_iterating(SV* const invlist)
9298 PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
9300 return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX;
9303 #ifndef PERL_IN_XSUB_RE
9305 PERL_STATIC_INLINE UV
9306 S_invlist_max(SV* const invlist)
9308 /* Returns the maximum number of elements storable in the inversion list's
9309 * array, without having to realloc() */
9311 PERL_ARGS_ASSERT_INVLIST_MAX;
9313 assert(is_invlist(invlist));
9315 /* Assumes worst case, in which the 0 element is not counted in the
9316 * inversion list, so subtracts 1 for that */
9317 return SvLEN(invlist) == 0 /* This happens under _new_invlist_C_array */
9318 ? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1
9319 : FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1;
9323 S_initialize_invlist_guts(pTHX_ SV* invlist, const Size_t initial_size)
9325 PERL_ARGS_ASSERT_INITIALIZE_INVLIST_GUTS;
9327 /* First 1 is in case the zero element isn't in the list; second 1 is for
9329 SvGROW(invlist, TO_INTERNAL_SIZE(initial_size + 1) + 1);
9330 invlist_set_len(invlist, 0, 0);
9332 /* Force iterinit() to be used to get iteration to work */
9333 invlist_iterfinish(invlist);
9335 *get_invlist_previous_index_addr(invlist) = 0;
9336 SvPOK_on(invlist); /* This allows B to extract the PV */
9340 Perl__new_invlist(pTHX_ IV initial_size)
9343 /* Return a pointer to a newly constructed inversion list, with enough
9344 * space to store 'initial_size' elements. If that number is negative, a
9345 * system default is used instead */
9349 if (initial_size < 0) {
9353 new_list = newSV_type(SVt_INVLIST);
9354 initialize_invlist_guts(new_list, initial_size);
9360 Perl__new_invlist_C_array(pTHX_ const UV* const list)
9362 /* Return a pointer to a newly constructed inversion list, initialized to
9363 * point to <list>, which has to be in the exact correct inversion list
9364 * form, including internal fields. Thus this is a dangerous routine that
9365 * should not be used in the wrong hands. The passed in 'list' contains
9366 * several header fields at the beginning that are not part of the
9367 * inversion list body proper */
9369 const STRLEN length = (STRLEN) list[0];
9370 const UV version_id = list[1];
9371 const bool offset = cBOOL(list[2]);
9372 #define HEADER_LENGTH 3
9373 /* If any of the above changes in any way, you must change HEADER_LENGTH
9374 * (if appropriate) and regenerate INVLIST_VERSION_ID by running
9375 * perl -E 'say int(rand 2**31-1)'
9377 #define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and
9378 data structure type, so that one being
9379 passed in can be validated to be an
9380 inversion list of the correct vintage.
9383 SV* invlist = newSV_type(SVt_INVLIST);
9385 PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
9387 if (version_id != INVLIST_VERSION_ID) {
9388 Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
9391 /* The generated array passed in includes header elements that aren't part
9392 * of the list proper, so start it just after them */
9393 SvPV_set(invlist, (char *) (list + HEADER_LENGTH));
9395 SvLEN_set(invlist, 0); /* Means we own the contents, and the system
9396 shouldn't touch it */
9398 *(get_invlist_offset_addr(invlist)) = offset;
9400 /* The 'length' passed to us is the physical number of elements in the
9401 * inversion list. But if there is an offset the logical number is one
9403 invlist_set_len(invlist, length - offset, offset);
9405 invlist_set_previous_index(invlist, 0);
9407 /* Initialize the iteration pointer. */
9408 invlist_iterfinish(invlist);
9410 SvREADONLY_on(invlist);
9417 S__append_range_to_invlist(pTHX_ SV* const invlist,
9418 const UV start, const UV end)
9420 /* Subject to change or removal. Append the range from 'start' to 'end' at
9421 * the end of the inversion list. The range must be above any existing
9425 UV max = invlist_max(invlist);
9426 UV len = _invlist_len(invlist);
9429 PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
9431 if (len == 0) { /* Empty lists must be initialized */
9432 offset = start != 0;
9433 array = _invlist_array_init(invlist, ! offset);
9436 /* Here, the existing list is non-empty. The current max entry in the
9437 * list is generally the first value not in the set, except when the
9438 * set extends to the end of permissible values, in which case it is
9439 * the first entry in that final set, and so this call is an attempt to
9440 * append out-of-order */
9442 UV final_element = len - 1;
9443 array = invlist_array(invlist);
9444 if ( array[final_element] > start
9445 || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
9447 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",
9448 array[final_element], start,
9449 ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
9452 /* Here, it is a legal append. If the new range begins 1 above the end
9453 * of the range below it, it is extending the range below it, so the
9454 * new first value not in the set is one greater than the newly
9455 * extended range. */
9456 offset = *get_invlist_offset_addr(invlist);
9457 if (array[final_element] == start) {
9458 if (end != UV_MAX) {
9459 array[final_element] = end + 1;
9462 /* But if the end is the maximum representable on the machine,
9463 * assume that infinity was actually what was meant. Just let
9464 * the range that this would extend to have no end */
9465 invlist_set_len(invlist, len - 1, offset);
9471 /* Here the new range doesn't extend any existing set. Add it */
9473 len += 2; /* Includes an element each for the start and end of range */
9475 /* If wll overflow the existing space, extend, which may cause the array to
9478 invlist_extend(invlist, len);
9480 /* Have to set len here to avoid assert failure in invlist_array() */
9481 invlist_set_len(invlist, len, offset);
9483 array = invlist_array(invlist);
9486 invlist_set_len(invlist, len, offset);
9489 /* The next item on the list starts the range, the one after that is
9490 * one past the new range. */
9491 array[len - 2] = start;
9492 if (end != UV_MAX) {
9493 array[len - 1] = end + 1;
9496 /* But if the end is the maximum representable on the machine, just let
9497 * the range have no end */
9498 invlist_set_len(invlist, len - 1, offset);
9503 Perl__invlist_search(SV* const invlist, const UV cp)
9505 /* Searches the inversion list for the entry that contains the input code
9506 * point <cp>. If <cp> is not in the list, -1 is returned. Otherwise, the
9507 * return value is the index into the list's array of the range that
9508 * contains <cp>, that is, 'i' such that
9509 * array[i] <= cp < array[i+1]
9514 IV high = _invlist_len(invlist);
9515 const IV highest_element = high - 1;
9518 PERL_ARGS_ASSERT__INVLIST_SEARCH;
9520 /* If list is empty, return failure. */
9525 /* (We can't get the array unless we know the list is non-empty) */
9526 array = invlist_array(invlist);
9528 mid = invlist_previous_index(invlist);
9530 if (mid > highest_element) {
9531 mid = highest_element;
9534 /* <mid> contains the cache of the result of the previous call to this
9535 * function (0 the first time). See if this call is for the same result,
9536 * or if it is for mid-1. This is under the theory that calls to this
9537 * function will often be for related code points that are near each other.
9538 * And benchmarks show that caching gives better results. We also test
9539 * here if the code point is within the bounds of the list. These tests
9540 * replace others that would have had to be made anyway to make sure that
9541 * the array bounds were not exceeded, and these give us extra information
9542 * at the same time */
9543 if (cp >= array[mid]) {
9544 if (cp >= array[highest_element]) {
9545 return highest_element;
9548 /* Here, array[mid] <= cp < array[highest_element]. This means that
9549 * the final element is not the answer, so can exclude it; it also
9550 * means that <mid> is not the final element, so can refer to 'mid + 1'
9552 if (cp < array[mid + 1]) {
9558 else { /* cp < aray[mid] */
9559 if (cp < array[0]) { /* Fail if outside the array */
9563 if (cp >= array[mid - 1]) {
9568 /* Binary search. What we are looking for is <i> such that
9569 * array[i] <= cp < array[i+1]
9570 * The loop below converges on the i+1. Note that there may not be an
9571 * (i+1)th element in the array, and things work nonetheless */
9572 while (low < high) {
9573 mid = (low + high) / 2;
9574 assert(mid <= highest_element);
9575 if (array[mid] <= cp) { /* cp >= array[mid] */
9578 /* We could do this extra test to exit the loop early.
9579 if (cp < array[low]) {
9584 else { /* cp < array[mid] */
9591 invlist_set_previous_index(invlist, high);
9596 Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9597 const bool complement_b, SV** output)
9599 /* Take the union of two inversion lists and point '*output' to it. On
9600 * input, '*output' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9601 * even 'a' or 'b'). If to an inversion list, the contents of the original
9602 * list will be replaced by the union. The first list, 'a', may be
9603 * NULL, in which case a copy of the second list is placed in '*output'.
9604 * If 'complement_b' is TRUE, the union is taken of the complement
9605 * (inversion) of 'b' instead of b itself.
9607 * The basis for this comes from "Unicode Demystified" Chapter 13 by
9608 * Richard Gillam, published by Addison-Wesley, and explained at some
9609 * length there. The preface says to incorporate its examples into your
9610 * code at your own risk.
9612 * The algorithm is like a merge sort. */
9614 const UV* array_a; /* a's array */
9616 UV len_a; /* length of a's array */
9619 SV* u; /* the resulting union */
9623 UV i_a = 0; /* current index into a's array */
9627 /* running count, as explained in the algorithm source book; items are
9628 * stopped accumulating and are output when the count changes to/from 0.
9629 * The count is incremented when we start a range that's in an input's set,
9630 * and decremented when we start a range that's not in a set. So this
9631 * variable can be 0, 1, or 2. When it is 0 neither input is in their set,
9632 * and hence nothing goes into the union; 1, just one of the inputs is in
9633 * its set (and its current range gets added to the union); and 2 when both
9634 * inputs are in their sets. */
9637 PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
9639 assert(*output == NULL || is_invlist(*output));
9641 len_b = _invlist_len(b);
9644 /* Here, 'b' is empty, hence it's complement is all possible code
9645 * points. So if the union includes the complement of 'b', it includes
9646 * everything, and we need not even look at 'a'. It's easiest to
9647 * create a new inversion list that matches everything. */
9649 SV* everything = _add_range_to_invlist(NULL, 0, UV_MAX);
9651 if (*output == NULL) { /* If the output didn't exist, just point it
9653 *output = everything;
9655 else { /* Otherwise, replace its contents with the new list */
9656 invlist_replace_list_destroys_src(*output, everything);
9657 SvREFCNT_dec_NN(everything);
9663 /* Here, we don't want the complement of 'b', and since 'b' is empty,
9664 * the union will come entirely from 'a'. If 'a' is NULL or empty, the
9665 * output will be empty */
9667 if (a == NULL || _invlist_len(a) == 0) {
9668 if (*output == NULL) {
9669 *output = _new_invlist(0);
9672 invlist_clear(*output);
9677 /* Here, 'a' is not empty, but 'b' is, so 'a' entirely determines the
9678 * union. We can just return a copy of 'a' if '*output' doesn't point
9679 * to an existing list */
9680 if (*output == NULL) {
9681 *output = invlist_clone(a, NULL);
9685 /* If the output is to overwrite 'a', we have a no-op, as it's
9691 /* Here, '*output' is to be overwritten by 'a' */
9692 u = invlist_clone(a, NULL);
9693 invlist_replace_list_destroys_src(*output, u);
9699 /* Here 'b' is not empty. See about 'a' */
9701 if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
9703 /* Here, 'a' is empty (and b is not). That means the union will come
9704 * entirely from 'b'. If '*output' is NULL, we can directly return a
9705 * clone of 'b'. Otherwise, we replace the contents of '*output' with
9708 SV ** dest = (*output == NULL) ? output : &u;
9709 *dest = invlist_clone(b, NULL);
9711 _invlist_invert(*dest);
9715 invlist_replace_list_destroys_src(*output, u);
9722 /* Here both lists exist and are non-empty */
9723 array_a = invlist_array(a);
9724 array_b = invlist_array(b);
9726 /* If are to take the union of 'a' with the complement of b, set it
9727 * up so are looking at b's complement. */
9730 /* To complement, we invert: if the first element is 0, remove it. To
9731 * do this, we just pretend the array starts one later */
9732 if (array_b[0] == 0) {
9738 /* But if the first element is not zero, we pretend the list starts
9739 * at the 0 that is always stored immediately before the array. */
9745 /* Size the union for the worst case: that the sets are completely
9747 u = _new_invlist(len_a + len_b);
9749 /* Will contain U+0000 if either component does */
9750 array_u = _invlist_array_init(u, ( len_a > 0 && array_a[0] == 0)
9751 || (len_b > 0 && array_b[0] == 0));
9753 /* Go through each input list item by item, stopping when have exhausted
9755 while (i_a < len_a && i_b < len_b) {
9756 UV cp; /* The element to potentially add to the union's array */
9757 bool cp_in_set; /* is it in the input list's set or not */
9759 /* We need to take one or the other of the two inputs for the union.
9760 * Since we are merging two sorted lists, we take the smaller of the
9761 * next items. In case of a tie, we take first the one that is in its
9762 * set. If we first took the one not in its set, it would decrement
9763 * the count, possibly to 0 which would cause it to be output as ending
9764 * the range, and the next time through we would take the same number,
9765 * and output it again as beginning the next range. By doing it the
9766 * opposite way, there is no possibility that the count will be
9767 * momentarily decremented to 0, and thus the two adjoining ranges will
9768 * be seamlessly merged. (In a tie and both are in the set or both not
9769 * in the set, it doesn't matter which we take first.) */
9770 if ( array_a[i_a] < array_b[i_b]
9771 || ( array_a[i_a] == array_b[i_b]
9772 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9774 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9775 cp = array_a[i_a++];
9778 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9779 cp = array_b[i_b++];
9782 /* Here, have chosen which of the two inputs to look at. Only output
9783 * if the running count changes to/from 0, which marks the
9784 * beginning/end of a range that's in the set */
9787 array_u[i_u++] = cp;
9794 array_u[i_u++] = cp;
9800 /* The loop above increments the index into exactly one of the input lists
9801 * each iteration, and ends when either index gets to its list end. That
9802 * means the other index is lower than its end, and so something is
9803 * remaining in that one. We decrement 'count', as explained below, if
9804 * that list is in its set. (i_a and i_b each currently index the element
9805 * beyond the one we care about.) */
9806 if ( (i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9807 || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9812 /* Above we decremented 'count' if the list that had unexamined elements in
9813 * it was in its set. This has made it so that 'count' being non-zero
9814 * means there isn't anything left to output; and 'count' equal to 0 means
9815 * that what is left to output is precisely that which is left in the
9816 * non-exhausted input list.
9818 * To see why, note first that the exhausted input obviously has nothing
9819 * left to add to the union. If it was in its set at its end, that means
9820 * the set extends from here to the platform's infinity, and hence so does
9821 * the union and the non-exhausted set is irrelevant. The exhausted set
9822 * also contributed 1 to 'count'. If 'count' was 2, it got decremented to
9823 * 1, but if it was 1, the non-exhausted set wasn't in its set, and so
9824 * 'count' remains at 1. This is consistent with the decremented 'count'
9825 * != 0 meaning there's nothing left to add to the union.
9827 * But if the exhausted input wasn't in its set, it contributed 0 to
9828 * 'count', and the rest of the union will be whatever the other input is.
9829 * If 'count' was 0, neither list was in its set, and 'count' remains 0;
9830 * otherwise it gets decremented to 0. This is consistent with 'count'
9831 * == 0 meaning the remainder of the union is whatever is left in the
9832 * non-exhausted list. */
9837 IV copy_count = len_a - i_a;
9838 if (copy_count > 0) { /* The non-exhausted input is 'a' */
9839 Copy(array_a + i_a, array_u + i_u, copy_count, UV);
9841 else { /* The non-exhausted input is b */
9842 copy_count = len_b - i_b;
9843 Copy(array_b + i_b, array_u + i_u, copy_count, UV);
9845 len_u = i_u + copy_count;
9848 /* Set the result to the final length, which can change the pointer to
9849 * array_u, so re-find it. (Note that it is unlikely that this will
9850 * change, as we are shrinking the space, not enlarging it) */
9851 if (len_u != _invlist_len(u)) {
9852 invlist_set_len(u, len_u, *get_invlist_offset_addr(u));
9854 array_u = invlist_array(u);
9857 if (*output == NULL) { /* Simply return the new inversion list */
9861 /* Otherwise, overwrite the inversion list that was in '*output'. We
9862 * could instead free '*output', and then set it to 'u', but experience
9863 * has shown [perl #127392] that if the input is a mortal, we can get a
9864 * huge build-up of these during regex compilation before they get
9866 invlist_replace_list_destroys_src(*output, u);
9874 Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9875 const bool complement_b, SV** i)
9877 /* Take the intersection of two inversion lists and point '*i' to it. On
9878 * input, '*i' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9879 * even 'a' or 'b'). If to an inversion list, the contents of the original
9880 * list will be replaced by the intersection. The first list, 'a', may be
9881 * NULL, in which case '*i' will be an empty list. If 'complement_b' is
9882 * TRUE, the result will be the intersection of 'a' and the complement (or
9883 * inversion) of 'b' instead of 'b' directly.
9885 * The basis for this comes from "Unicode Demystified" Chapter 13 by
9886 * Richard Gillam, published by Addison-Wesley, and explained at some
9887 * length there. The preface says to incorporate its examples into your
9888 * code at your own risk. In fact, it had bugs
9890 * The algorithm is like a merge sort, and is essentially the same as the
9894 const UV* array_a; /* a's array */
9896 UV len_a; /* length of a's array */
9899 SV* r; /* the resulting intersection */
9903 UV i_a = 0; /* current index into a's array */
9907 /* running count of how many of the two inputs are postitioned at ranges
9908 * that are in their sets. As explained in the algorithm source book,
9909 * items are stopped accumulating and are output when the count changes
9910 * to/from 2. The count is incremented when we start a range that's in an
9911 * input's set, and decremented when we start a range that's not in a set.
9912 * Only when it is 2 are we in the intersection. */
9915 PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
9917 assert(*i == NULL || is_invlist(*i));
9919 /* Special case if either one is empty */
9920 len_a = (a == NULL) ? 0 : _invlist_len(a);
9921 if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
9922 if (len_a != 0 && complement_b) {
9924 /* Here, 'a' is not empty, therefore from the enclosing 'if', 'b'
9925 * must be empty. Here, also we are using 'b's complement, which
9926 * hence must be every possible code point. Thus the intersection
9929 if (*i == a) { /* No-op */
9934 *i = invlist_clone(a, NULL);
9938 r = invlist_clone(a, NULL);
9939 invlist_replace_list_destroys_src(*i, r);
9944 /* Here, 'a' or 'b' is empty and not using the complement of 'b'. The
9945 * intersection must be empty */
9947 *i = _new_invlist(0);
9955 /* Here both lists exist and are non-empty */
9956 array_a = invlist_array(a);
9957 array_b = invlist_array(b);
9959 /* If are to take the intersection of 'a' with the complement of b, set it
9960 * up so are looking at b's complement. */
9963 /* To complement, we invert: if the first element is 0, remove it. To
9964 * do this, we just pretend the array starts one later */
9965 if (array_b[0] == 0) {
9971 /* But if the first element is not zero, we pretend the list starts
9972 * at the 0 that is always stored immediately before the array. */
9978 /* Size the intersection for the worst case: that the intersection ends up
9979 * fragmenting everything to be completely disjoint */
9980 r= _new_invlist(len_a + len_b);
9982 /* Will contain U+0000 iff both components do */
9983 array_r = _invlist_array_init(r, len_a > 0 && array_a[0] == 0
9984 && len_b > 0 && array_b[0] == 0);
9986 /* Go through each list item by item, stopping when have exhausted one of
9988 while (i_a < len_a && i_b < len_b) {
9989 UV cp; /* The element to potentially add to the intersection's
9991 bool cp_in_set; /* Is it in the input list's set or not */
9993 /* We need to take one or the other of the two inputs for the
9994 * intersection. Since we are merging two sorted lists, we take the
9995 * smaller of the next items. In case of a tie, we take first the one
9996 * that is not in its set (a difference from the union algorithm). If
9997 * we first took the one in its set, it would increment the count,
9998 * possibly to 2 which would cause it to be output as starting a range
9999 * in the intersection, and the next time through we would take that
10000 * same number, and output it again as ending the set. By doing the
10001 * opposite of this, there is no possibility that the count will be
10002 * momentarily incremented to 2. (In a tie and both are in the set or
10003 * both not in the set, it doesn't matter which we take first.) */
10004 if ( array_a[i_a] < array_b[i_b]
10005 || ( array_a[i_a] == array_b[i_b]
10006 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
10008 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
10009 cp = array_a[i_a++];
10012 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
10013 cp= array_b[i_b++];
10016 /* Here, have chosen which of the two inputs to look at. Only output
10017 * if the running count changes to/from 2, which marks the
10018 * beginning/end of a range that's in the intersection */
10022 array_r[i_r++] = cp;
10027 array_r[i_r++] = cp;
10034 /* The loop above increments the index into exactly one of the input lists
10035 * each iteration, and ends when either index gets to its list end. That
10036 * means the other index is lower than its end, and so something is
10037 * remaining in that one. We increment 'count', as explained below, if the
10038 * exhausted list was in its set. (i_a and i_b each currently index the
10039 * element beyond the one we care about.) */
10040 if ( (i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
10041 || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
10046 /* Above we incremented 'count' if the exhausted list was in its set. This
10047 * has made it so that 'count' being below 2 means there is nothing left to
10048 * output; otheriwse what's left to add to the intersection is precisely
10049 * that which is left in the non-exhausted input list.
10051 * To see why, note first that the exhausted input obviously has nothing
10052 * left to affect the intersection. If it was in its set at its end, that
10053 * means the set extends from here to the platform's infinity, and hence
10054 * anything in the non-exhausted's list will be in the intersection, and
10055 * anything not in it won't be. Hence, the rest of the intersection is
10056 * precisely what's in the non-exhausted list The exhausted set also
10057 * contributed 1 to 'count', meaning 'count' was at least 1. Incrementing
10058 * it means 'count' is now at least 2. This is consistent with the
10059 * incremented 'count' being >= 2 means to add the non-exhausted list to
10060 * the intersection.
10062 * But if the exhausted input wasn't in its set, it contributed 0 to
10063 * 'count', and the intersection can't include anything further; the
10064 * non-exhausted set is irrelevant. 'count' was at most 1, and doesn't get
10065 * incremented. This is consistent with 'count' being < 2 meaning nothing
10066 * further to add to the intersection. */
10067 if (count < 2) { /* Nothing left to put in the intersection. */
10070 else { /* copy the non-exhausted list, unchanged. */
10071 IV copy_count = len_a - i_a;
10072 if (copy_count > 0) { /* a is the one with stuff left */
10073 Copy(array_a + i_a, array_r + i_r, copy_count, UV);
10075 else { /* b is the one with stuff left */
10076 copy_count = len_b - i_b;
10077 Copy(array_b + i_b, array_r + i_r, copy_count, UV);
10079 len_r = i_r + copy_count;
10082 /* Set the result to the final length, which can change the pointer to
10083 * array_r, so re-find it. (Note that it is unlikely that this will
10084 * change, as we are shrinking the space, not enlarging it) */
10085 if (len_r != _invlist_len(r)) {
10086 invlist_set_len(r, len_r, *get_invlist_offset_addr(r));
10088 array_r = invlist_array(r);
10091 if (*i == NULL) { /* Simply return the calculated intersection */
10094 else { /* Otherwise, replace the existing inversion list in '*i'. We could
10095 instead free '*i', and then set it to 'r', but experience has
10096 shown [perl #127392] that if the input is a mortal, we can get a
10097 huge build-up of these during regex compilation before they get
10100 invlist_replace_list_destroys_src(*i, r);
10105 SvREFCNT_dec_NN(r);
10112 Perl__add_range_to_invlist(pTHX_ SV* invlist, UV start, UV end)
10114 /* Add the range from 'start' to 'end' inclusive to the inversion list's
10115 * set. A pointer to the inversion list is returned. This may actually be
10116 * a new list, in which case the passed in one has been destroyed. The
10117 * passed-in inversion list can be NULL, in which case a new one is created
10118 * with just the one range in it. The new list is not necessarily
10119 * NUL-terminated. Space is not freed if the inversion list shrinks as a
10120 * result of this function. The gain would not be large, and in many
10121 * cases, this is called multiple times on a single inversion list, so
10122 * anything freed may almost immediately be needed again.
10124 * This used to mostly call the 'union' routine, but that is much more
10125 * heavyweight than really needed for a single range addition */
10127 UV* array; /* The array implementing the inversion list */
10128 UV len; /* How many elements in 'array' */
10129 SSize_t i_s; /* index into the invlist array where 'start'
10131 SSize_t i_e = 0; /* And the index where 'end' should go */
10132 UV cur_highest; /* The highest code point in the inversion list
10133 upon entry to this function */
10135 /* This range becomes the whole inversion list if none already existed */
10136 if (invlist == NULL) {
10137 invlist = _new_invlist(2);
10138 _append_range_to_invlist(invlist, start, end);
10142 /* Likewise, if the inversion list is currently empty */
10143 len = _invlist_len(invlist);
10145 _append_range_to_invlist(invlist, start, end);
10149 /* Starting here, we have to know the internals of the list */
10150 array = invlist_array(invlist);
10152 /* If the new range ends higher than the current highest ... */
10153 cur_highest = invlist_highest(invlist);
10154 if (end > cur_highest) {
10156 /* If the whole range is higher, we can just append it */
10157 if (start > cur_highest) {
10158 _append_range_to_invlist(invlist, start, end);
10162 /* Otherwise, add the portion that is higher ... */
10163 _append_range_to_invlist(invlist, cur_highest + 1, end);
10165 /* ... and continue on below to handle the rest. As a result of the
10166 * above append, we know that the index of the end of the range is the
10167 * final even numbered one of the array. Recall that the final element
10168 * always starts a range that extends to infinity. If that range is in
10169 * the set (meaning the set goes from here to infinity), it will be an
10170 * even index, but if it isn't in the set, it's odd, and the final
10171 * range in the set is one less, which is even. */
10172 if (end == UV_MAX) {
10180 /* We have dealt with appending, now see about prepending. If the new
10181 * range starts lower than the current lowest ... */
10182 if (start < array[0]) {
10184 /* Adding something which has 0 in it is somewhat tricky, and uncommon.
10185 * Let the union code handle it, rather than having to know the
10186 * trickiness in two code places. */
10187 if (UNLIKELY(start == 0)) {
10190 range_invlist = _new_invlist(2);
10191 _append_range_to_invlist(range_invlist, start, end);
10193 _invlist_union(invlist, range_invlist, &invlist);
10195 SvREFCNT_dec_NN(range_invlist);
10200 /* If the whole new range comes before the first entry, and doesn't
10201 * extend it, we have to insert it as an additional range */
10202 if (end < array[0] - 1) {
10204 goto splice_in_new_range;
10207 /* Here the new range adjoins the existing first range, extending it
10211 /* And continue on below to handle the rest. We know that the index of
10212 * the beginning of the range is the first one of the array */
10215 else { /* Not prepending any part of the new range to the existing list.
10216 * Find where in the list it should go. This finds i_s, such that:
10217 * invlist[i_s] <= start < array[i_s+1]
10219 i_s = _invlist_search(invlist, start);
10222 /* At this point, any extending before the beginning of the inversion list
10223 * and/or after the end has been done. This has made it so that, in the
10224 * code below, each endpoint of the new range is either in a range that is
10225 * in the set, or is in a gap between two ranges that are. This means we
10226 * don't have to worry about exceeding the array bounds.
10228 * Find where in the list the new range ends (but we can skip this if we
10229 * have already determined what it is, or if it will be the same as i_s,
10230 * which we already have computed) */
10232 i_e = (start == end)
10234 : _invlist_search(invlist, end);
10237 /* Here generally invlist[i_e] <= end < array[i_e+1]. But if invlist[i_e]
10238 * is a range that goes to infinity there is no element at invlist[i_e+1],
10239 * so only the first relation holds. */
10241 if ( ! ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10243 /* Here, the ranges on either side of the beginning of the new range
10244 * are in the set, and this range starts in the gap between them.
10246 * The new range extends the range above it downwards if the new range
10247 * ends at or above that range's start */
10248 const bool extends_the_range_above = ( end == UV_MAX
10249 || end + 1 >= array[i_s+1]);
10251 /* The new range extends the range below it upwards if it begins just
10252 * after where that range ends */
10253 if (start == array[i_s]) {
10255 /* If the new range fills the entire gap between the other ranges,
10256 * they will get merged together. Other ranges may also get
10257 * merged, depending on how many of them the new range spans. In
10258 * the general case, we do the merge later, just once, after we
10259 * figure out how many to merge. But in the case where the new
10260 * range exactly spans just this one gap (possibly extending into
10261 * the one above), we do the merge here, and an early exit. This
10262 * is done here to avoid having to special case later. */
10263 if (i_e - i_s <= 1) {
10265 /* If i_e - i_s == 1, it means that the new range terminates
10266 * within the range above, and hence 'extends_the_range_above'
10267 * must be true. (If the range above it extends to infinity,
10268 * 'i_s+2' will be above the array's limit, but 'len-i_s-2'
10269 * will be 0, so no harm done.) */
10270 if (extends_the_range_above) {
10271 Move(array + i_s + 2, array + i_s, len - i_s - 2, UV);
10272 invlist_set_len(invlist,
10274 *(get_invlist_offset_addr(invlist)));
10278 /* Here, i_e must == i_s. We keep them in sync, as they apply
10279 * to the same range, and below we are about to decrement i_s
10284 /* Here, the new range is adjacent to the one below. (It may also
10285 * span beyond the range above, but that will get resolved later.)
10286 * Extend the range below to include this one. */
10287 array[i_s] = (end == UV_MAX) ? UV_MAX : end + 1;
10289 start = array[i_s];
10291 else if (extends_the_range_above) {
10293 /* Here the new range only extends the range above it, but not the
10294 * one below. It merges with the one above. Again, we keep i_e
10295 * and i_s in sync if they point to the same range */
10300 array[i_s] = start;
10304 /* Here, we've dealt with the new range start extending any adjoining
10307 * If the new range extends to infinity, it is now the final one,
10308 * regardless of what was there before */
10309 if (UNLIKELY(end == UV_MAX)) {
10310 invlist_set_len(invlist, i_s + 1, *(get_invlist_offset_addr(invlist)));
10314 /* If i_e started as == i_s, it has also been dealt with,
10315 * and been updated to the new i_s, which will fail the following if */
10316 if (! ELEMENT_RANGE_MATCHES_INVLIST(i_e)) {
10318 /* Here, the ranges on either side of the end of the new range are in
10319 * the set, and this range ends in the gap between them.
10321 * If this range is adjacent to (hence extends) the range above it, it
10322 * becomes part of that range; likewise if it extends the range below,
10323 * it becomes part of that range */
10324 if (end + 1 == array[i_e+1]) {
10326 array[i_e] = start;
10328 else if (start <= array[i_e]) {
10329 array[i_e] = end + 1;
10336 /* If the range fits entirely in an existing range (as possibly already
10337 * extended above), it doesn't add anything new */
10338 if (ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10342 /* Here, no part of the range is in the list. Must add it. It will
10343 * occupy 2 more slots */
10344 splice_in_new_range:
10346 invlist_extend(invlist, len + 2);
10347 array = invlist_array(invlist);
10348 /* Move the rest of the array down two slots. Don't include any
10350 Move(array + i_e + 1, array + i_e + 3, len - i_e - 1, UV);
10352 /* Do the actual splice */
10353 array[i_e+1] = start;
10354 array[i_e+2] = end + 1;
10355 invlist_set_len(invlist, len + 2, *(get_invlist_offset_addr(invlist)));
10359 /* Here the new range crossed the boundaries of a pre-existing range. The
10360 * code above has adjusted things so that both ends are in ranges that are
10361 * in the set. This means everything in between must also be in the set.
10362 * Just squash things together */
10363 Move(array + i_e + 1, array + i_s + 1, len - i_e - 1, UV);
10364 invlist_set_len(invlist,
10366 *(get_invlist_offset_addr(invlist)));
10372 Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0,
10373 UV** other_elements_ptr)
10375 /* Create and return an inversion list whose contents are to be populated
10376 * by the caller. The caller gives the number of elements (in 'size') and
10377 * the very first element ('element0'). This function will set
10378 * '*other_elements_ptr' to an array of UVs, where the remaining elements
10379 * are to be placed.
10381 * Obviously there is some trust involved that the caller will properly
10382 * fill in the other elements of the array.
10384 * (The first element needs to be passed in, as the underlying code does
10385 * things differently depending on whether it is zero or non-zero) */
10387 SV* invlist = _new_invlist(size);
10390 PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST;
10392 invlist = add_cp_to_invlist(invlist, element0);
10393 offset = *get_invlist_offset_addr(invlist);
10395 invlist_set_len(invlist, size, offset);
10396 *other_elements_ptr = invlist_array(invlist) + 1;
10402 #ifndef PERL_IN_XSUB_RE
10404 Perl__invlist_invert(pTHX_ SV* const invlist)
10406 /* Complement the input inversion list. This adds a 0 if the list didn't
10407 * have a zero; removes it otherwise. As described above, the data
10408 * structure is set up so that this is very efficient */
10410 PERL_ARGS_ASSERT__INVLIST_INVERT;
10412 assert(! invlist_is_iterating(invlist));
10414 /* The inverse of matching nothing is matching everything */
10415 if (_invlist_len(invlist) == 0) {
10416 _append_range_to_invlist(invlist, 0, UV_MAX);
10420 *get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist);
10424 Perl_invlist_clone(pTHX_ SV* const invlist, SV* new_invlist)
10426 /* Return a new inversion list that is a copy of the input one, which is
10427 * unchanged. The new list will not be mortal even if the old one was. */
10429 const STRLEN nominal_length = _invlist_len(invlist);
10430 const STRLEN physical_length = SvCUR(invlist);
10431 const bool offset = *(get_invlist_offset_addr(invlist));
10433 PERL_ARGS_ASSERT_INVLIST_CLONE;
10435 if (new_invlist == NULL) {
10436 new_invlist = _new_invlist(nominal_length);
10439 sv_upgrade(new_invlist, SVt_INVLIST);
10440 initialize_invlist_guts(new_invlist, nominal_length);
10443 *(get_invlist_offset_addr(new_invlist)) = offset;
10444 invlist_set_len(new_invlist, nominal_length, offset);
10445 Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char);
10447 return new_invlist;
10452 PERL_STATIC_INLINE UV
10453 S_invlist_lowest(SV* const invlist)
10455 /* Returns the lowest code point that matches an inversion list. This API
10456 * has an ambiguity, as it returns 0 under either the lowest is actually
10457 * 0, or if the list is empty. If this distinction matters to you, check
10458 * for emptiness before calling this function */
10460 UV len = _invlist_len(invlist);
10463 PERL_ARGS_ASSERT_INVLIST_LOWEST;
10469 array = invlist_array(invlist);
10475 S_invlist_contents(pTHX_ SV* const invlist, const bool traditional_style)
10477 /* Get the contents of an inversion list into a string SV so that they can
10478 * be printed out. If 'traditional_style' is TRUE, it uses the format
10479 * traditionally done for debug tracing; otherwise it uses a format
10480 * suitable for just copying to the output, with blanks between ranges and
10481 * a dash between range components */
10485 const char intra_range_delimiter = (traditional_style ? '\t' : '-');
10486 const char inter_range_delimiter = (traditional_style ? '\n' : ' ');
10488 if (traditional_style) {
10489 output = newSVpvs("\n");
10492 output = newSVpvs("");
10495 PERL_ARGS_ASSERT_INVLIST_CONTENTS;
10497 assert(! invlist_is_iterating(invlist));
10499 invlist_iterinit(invlist);
10500 while (invlist_iternext(invlist, &start, &end)) {
10501 if (end == UV_MAX) {
10502 Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%cINFTY%c",
10503 start, intra_range_delimiter,
10504 inter_range_delimiter);
10506 else if (end != start) {
10507 Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c%04" UVXf "%c",
10509 intra_range_delimiter,
10510 end, inter_range_delimiter);
10513 Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c",
10514 start, inter_range_delimiter);
10518 if (SvCUR(output) && ! traditional_style) {/* Get rid of trailing blank */
10519 SvCUR_set(output, SvCUR(output) - 1);
10525 #ifndef PERL_IN_XSUB_RE
10527 Perl__invlist_dump(pTHX_ PerlIO *file, I32 level,
10528 const char * const indent, SV* const invlist)
10530 /* Designed to be called only by do_sv_dump(). Dumps out the ranges of the
10531 * inversion list 'invlist' to 'file' at 'level' Each line is prefixed by
10532 * the string 'indent'. The output looks like this:
10533 [0] 0x000A .. 0x000D
10535 [4] 0x2028 .. 0x2029
10536 [6] 0x3104 .. INFTY
10537 * This means that the first range of code points matched by the list are
10538 * 0xA through 0xD; the second range contains only the single code point
10539 * 0x85, etc. An inversion list is an array of UVs. Two array elements
10540 * are used to define each range (except if the final range extends to
10541 * infinity, only a single element is needed). The array index of the
10542 * first element for the corresponding range is given in brackets. */
10547 PERL_ARGS_ASSERT__INVLIST_DUMP;
10549 if (invlist_is_iterating(invlist)) {
10550 Perl_dump_indent(aTHX_ level, file,
10551 "%sCan't dump inversion list because is in middle of iterating\n",
10556 invlist_iterinit(invlist);
10557 while (invlist_iternext(invlist, &start, &end)) {
10558 if (end == UV_MAX) {
10559 Perl_dump_indent(aTHX_ level, file,
10560 "%s[%" UVuf "] 0x%04" UVXf " .. INFTY\n",
10561 indent, (UV)count, start);
10563 else if (end != start) {
10564 Perl_dump_indent(aTHX_ level, file,
10565 "%s[%" UVuf "] 0x%04" UVXf " .. 0x%04" UVXf "\n",
10566 indent, (UV)count, start, end);
10569 Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf "\n",
10570 indent, (UV)count, start);
10578 #if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE)
10580 Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b)
10582 /* Return a boolean as to if the two passed in inversion lists are
10583 * identical. The final argument, if TRUE, says to take the complement of
10584 * the second inversion list before doing the comparison */
10586 const UV len_a = _invlist_len(a);
10587 UV len_b = _invlist_len(b);
10589 const UV* array_a = NULL;
10590 const UV* array_b = NULL;
10592 PERL_ARGS_ASSERT__INVLISTEQ;
10594 /* This code avoids accessing the arrays unless it knows the length is
10599 return ! complement_b;
10603 array_a = invlist_array(a);
10607 array_b = invlist_array(b);
10610 /* If are to compare 'a' with the complement of b, set it
10611 * up so are looking at b's complement. */
10612 if (complement_b) {
10614 /* The complement of nothing is everything, so <a> would have to have
10615 * just one element, starting at zero (ending at infinity) */
10617 return (len_a == 1 && array_a[0] == 0);
10619 if (array_b[0] == 0) {
10621 /* Otherwise, to complement, we invert. Here, the first element is
10622 * 0, just remove it. To do this, we just pretend the array starts
10630 /* But if the first element is not zero, we pretend the list starts
10631 * at the 0 that is always stored immediately before the array. */
10637 return len_a == len_b
10638 && memEQ(array_a, array_b, len_a * sizeof(array_a[0]));
10644 * As best we can, determine the characters that can match the start of
10645 * the given EXACTF-ish node. This is for use in creating ssc nodes, so there
10646 * can be false positive matches
10648 * Returns the invlist as a new SV*; it is the caller's responsibility to
10649 * call SvREFCNT_dec() when done with it.
10652 S_make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node)
10655 const U8 * s = (U8*)STRING(node);
10656 SSize_t bytelen = STR_LEN(node);
10658 /* Start out big enough for 2 separate code points */
10659 SV* invlist = _new_invlist(4);
10661 PERL_ARGS_ASSERT_MAKE_EXACTF_INVLIST;
10666 /* We punt and assume can match anything if the node begins
10667 * with a multi-character fold. Things are complicated. For
10668 * example, /ffi/i could match any of:
10669 * "\N{LATIN SMALL LIGATURE FFI}"
10670 * "\N{LATIN SMALL LIGATURE FF}I"
10671 * "F\N{LATIN SMALL LIGATURE FI}"
10672 * plus several other things; and making sure we have all the
10673 * possibilities is hard. */
10674 if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) {
10675 invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10678 /* Any Latin1 range character can potentially match any
10679 * other depending on the locale, and in Turkic locales, U+130 and
10681 if (OP(node) == EXACTFL) {
10682 _invlist_union(invlist, PL_Latin1, &invlist);
10683 invlist = add_cp_to_invlist(invlist,
10684 LATIN_SMALL_LETTER_DOTLESS_I);
10685 invlist = add_cp_to_invlist(invlist,
10686 LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10689 /* But otherwise, it matches at least itself. We can
10690 * quickly tell if it has a distinct fold, and if so,
10691 * it matches that as well */
10692 invlist = add_cp_to_invlist(invlist, uc);
10693 if (IS_IN_SOME_FOLD_L1(uc))
10694 invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]);
10697 /* Some characters match above-Latin1 ones under /i. This
10698 * is true of EXACTFL ones when the locale is UTF-8 */
10699 if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc)
10700 && (! isASCII(uc) || (OP(node) != EXACTFAA
10701 && OP(node) != EXACTFAA_NO_TRIE)))
10703 add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist);
10707 else { /* Pattern is UTF-8 */
10708 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
10709 const U8* e = s + bytelen;
10712 fc = uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
10714 /* The only code points that aren't folded in a UTF EXACTFish
10715 * node are the problematic ones in EXACTFL nodes */
10716 if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) {
10717 /* We need to check for the possibility that this EXACTFL
10718 * node begins with a multi-char fold. Therefore we fold
10719 * the first few characters of it so that we can make that
10725 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) {
10727 *(d++) = (U8) toFOLD(*s);
10728 if (fc < 0) { /* Save the first fold */
10735 UV fold = toFOLD_utf8_safe(s, e, d, &len);
10736 if (fc < 0) { /* Save the first fold */
10744 /* And set up so the code below that looks in this folded
10745 * buffer instead of the node's string */
10750 /* When we reach here 's' points to the fold of the first
10751 * character(s) of the node; and 'e' points to far enough along
10752 * the folded string to be just past any possible multi-char
10755 * Unlike the non-UTF-8 case, the macro for determining if a
10756 * string is a multi-char fold requires all the characters to
10757 * already be folded. This is because of all the complications
10758 * if not. Note that they are folded anyway, except in EXACTFL
10759 * nodes. Like the non-UTF case above, we punt if the node
10760 * begins with a multi-char fold */
10762 if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) {
10763 invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10765 else { /* Single char fold */
10768 const U32 * remaining_folds;
10769 Size_t folds_count;
10771 /* It matches itself */
10772 invlist = add_cp_to_invlist(invlist, fc);
10774 /* ... plus all the things that fold to it, which are found in
10775 * PL_utf8_foldclosures */
10776 folds_count = _inverse_folds(fc, &first_fold,
10778 for (k = 0; k < folds_count; k++) {
10779 UV c = (k == 0) ? first_fold : remaining_folds[k-1];
10781 /* /aa doesn't allow folds between ASCII and non- */
10782 if ( (OP(node) == EXACTFAA || OP(node) == EXACTFAA_NO_TRIE)
10783 && isASCII(c) != isASCII(fc))
10788 invlist = add_cp_to_invlist(invlist, c);
10791 if (OP(node) == EXACTFL) {
10793 /* If either [iI] are present in an EXACTFL node the above code
10794 * should have added its normal case pair, but under a Turkish
10795 * locale they could match instead the case pairs from it. Add
10796 * those as potential matches as well */
10797 if (isALPHA_FOLD_EQ(fc, 'I')) {
10798 invlist = add_cp_to_invlist(invlist,
10799 LATIN_SMALL_LETTER_DOTLESS_I);
10800 invlist = add_cp_to_invlist(invlist,
10801 LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10803 else if (fc == LATIN_SMALL_LETTER_DOTLESS_I) {
10804 invlist = add_cp_to_invlist(invlist, 'I');
10806 else if (fc == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) {
10807 invlist = add_cp_to_invlist(invlist, 'i');
10816 #undef HEADER_LENGTH
10817 #undef TO_INTERNAL_SIZE
10818 #undef FROM_INTERNAL_SIZE
10819 #undef INVLIST_VERSION_ID
10821 /* End of inversion list object */
10824 S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state)
10826 /* This parses the flags that are in either the '(?foo)' or '(?foo:bar)'
10827 * constructs, and updates RExC_flags with them. On input, RExC_parse
10828 * should point to the first flag; it is updated on output to point to the
10829 * final ')' or ':'. There needs to be at least one flag, or this will
10832 /* for (?g), (?gc), and (?o) warnings; warning
10833 about (?c) will warn about (?g) -- japhy */
10835 #define WASTED_O 0x01
10836 #define WASTED_G 0x02
10837 #define WASTED_C 0x04
10838 #define WASTED_GC (WASTED_G|WASTED_C)
10839 I32 wastedflags = 0x00;
10840 U32 posflags = 0, negflags = 0;
10841 U32 *flagsp = &posflags;
10842 char has_charset_modifier = '\0';
10844 bool has_use_defaults = FALSE;
10845 const char* const seqstart = RExC_parse - 1; /* Point to the '?' */
10846 int x_mod_count = 0;
10848 PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS;
10850 /* '^' as an initial flag sets certain defaults */
10851 if (UCHARAT(RExC_parse) == '^') {
10853 has_use_defaults = TRUE;
10854 STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
10855 cs = (RExC_uni_semantics)
10856 ? REGEX_UNICODE_CHARSET
10857 : REGEX_DEPENDS_CHARSET;
10858 set_regex_charset(&RExC_flags, cs);
10861 cs = get_regex_charset(RExC_flags);
10862 if ( cs == REGEX_DEPENDS_CHARSET
10863 && RExC_uni_semantics)
10865 cs = REGEX_UNICODE_CHARSET;
10869 while (RExC_parse < RExC_end) {
10870 /* && memCHRs("iogcmsx", *RExC_parse) */
10871 /* (?g), (?gc) and (?o) are useless here
10872 and must be globally applied -- japhy */
10873 if ((RExC_pm_flags & PMf_WILDCARD)) {
10874 if (flagsp == & negflags) {
10875 if (*RExC_parse == 'm') {
10877 /* diag_listed_as: Use of %s is not allowed in Unicode
10878 property wildcard subpatterns in regex; marked by <--
10880 vFAIL("Use of modifier '-m' is not allowed in Unicode"
10881 " property wildcard subpatterns");
10885 if (*RExC_parse == 's') {
10886 goto modifier_illegal_in_wildcard;
10891 switch (*RExC_parse) {
10893 /* Code for the imsxn flags */
10894 CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count);
10896 case LOCALE_PAT_MOD:
10897 if (has_charset_modifier) {
10898 goto excess_modifier;
10900 else if (flagsp == &negflags) {
10903 cs = REGEX_LOCALE_CHARSET;
10904 has_charset_modifier = LOCALE_PAT_MOD;
10906 case UNICODE_PAT_MOD:
10907 if (has_charset_modifier) {
10908 goto excess_modifier;
10910 else if (flagsp == &negflags) {
10913 cs = REGEX_UNICODE_CHARSET;
10914 has_charset_modifier = UNICODE_PAT_MOD;
10916 case ASCII_RESTRICT_PAT_MOD:
10917 if (flagsp == &negflags) {
10920 if (has_charset_modifier) {
10921 if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
10922 goto excess_modifier;
10924 /* Doubled modifier implies more restricted */
10925 cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
10928 cs = REGEX_ASCII_RESTRICTED_CHARSET;
10930 has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
10932 case DEPENDS_PAT_MOD:
10933 if (has_use_defaults) {
10934 goto fail_modifiers;
10936 else if (flagsp == &negflags) {
10939 else if (has_charset_modifier) {
10940 goto excess_modifier;
10943 /* The dual charset means unicode semantics if the
10944 * pattern (or target, not known until runtime) are
10945 * utf8, or something in the pattern indicates unicode
10947 cs = (RExC_uni_semantics)
10948 ? REGEX_UNICODE_CHARSET
10949 : REGEX_DEPENDS_CHARSET;
10950 has_charset_modifier = DEPENDS_PAT_MOD;
10954 if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
10955 vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
10957 else if (has_charset_modifier == *(RExC_parse - 1)) {
10958 vFAIL2("Regexp modifier \"%c\" may not appear twice",
10959 *(RExC_parse - 1));
10962 vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
10964 NOT_REACHED; /*NOTREACHED*/
10967 vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"",
10968 *(RExC_parse - 1));
10969 NOT_REACHED; /*NOTREACHED*/
10970 case GLOBAL_PAT_MOD: /* 'g' */
10971 if (RExC_pm_flags & PMf_WILDCARD) {
10972 goto modifier_illegal_in_wildcard;
10975 case ONCE_PAT_MOD: /* 'o' */
10976 if (ckWARN(WARN_REGEXP)) {
10977 const I32 wflagbit = *RExC_parse == 'o'
10980 if (! (wastedflags & wflagbit) ) {
10981 wastedflags |= wflagbit;
10982 /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10985 "Useless (%s%c) - %suse /%c modifier",
10986 flagsp == &negflags ? "?-" : "?",
10988 flagsp == &negflags ? "don't " : "",
10995 case CONTINUE_PAT_MOD: /* 'c' */
10996 if (RExC_pm_flags & PMf_WILDCARD) {
10997 goto modifier_illegal_in_wildcard;
10999 if (ckWARN(WARN_REGEXP)) {
11000 if (! (wastedflags & WASTED_C) ) {
11001 wastedflags |= WASTED_GC;
11002 /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
11005 "Useless (%sc) - %suse /gc modifier",
11006 flagsp == &negflags ? "?-" : "?",
11007 flagsp == &negflags ? "don't " : ""
11012 case KEEPCOPY_PAT_MOD: /* 'p' */
11013 if (RExC_pm_flags & PMf_WILDCARD) {
11014 goto modifier_illegal_in_wildcard;
11016 if (flagsp == &negflags) {
11017 ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
11019 *flagsp |= RXf_PMf_KEEPCOPY;
11023 /* A flag is a default iff it is following a minus, so
11024 * if there is a minus, it means will be trying to
11025 * re-specify a default which is an error */
11026 if (has_use_defaults || flagsp == &negflags) {
11027 goto fail_modifiers;
11029 flagsp = &negflags;
11030 wastedflags = 0; /* reset so (?g-c) warns twice */
11036 if ( (RExC_pm_flags & PMf_WILDCARD)
11037 && cs != REGEX_ASCII_MORE_RESTRICTED_CHARSET)
11040 /* diag_listed_as: Use of %s is not allowed in Unicode
11041 property wildcard subpatterns in regex; marked by <--
11043 vFAIL2("Use of modifier '%c' is not allowed in Unicode"
11044 " property wildcard subpatterns",
11045 has_charset_modifier);
11048 if ((posflags & (RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE)) == RXf_PMf_EXTENDED) {
11049 negflags |= RXf_PMf_EXTENDED_MORE;
11051 RExC_flags |= posflags;
11053 if (negflags & RXf_PMf_EXTENDED) {
11054 negflags |= RXf_PMf_EXTENDED_MORE;
11056 RExC_flags &= ~negflags;
11057 set_regex_charset(&RExC_flags, cs);
11062 RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
11063 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11064 vFAIL2utf8f("Sequence (%" UTF8f "...) not recognized",
11065 UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
11066 NOT_REACHED; /*NOTREACHED*/
11069 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11072 vFAIL("Sequence (?... not terminated");
11074 modifier_illegal_in_wildcard:
11076 /* diag_listed_as: Use of %s is not allowed in Unicode property wildcard
11077 subpatterns in regex; marked by <-- HERE in m/%s/ */
11078 vFAIL2("Use of modifier '%c' is not allowed in Unicode property wildcard"
11079 " subpatterns", *(RExC_parse - 1));
11083 - reg - regular expression, i.e. main body or parenthesized thing
11085 * Caller must absorb opening parenthesis.
11087 * Combining parenthesis handling with the base level of regular expression
11088 * is a trifle forced, but the need to tie the tails of the branches to what
11089 * follows makes it hard to avoid.
11091 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
11093 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
11095 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
11098 STATIC regnode_offset
11099 S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state,
11101 char * parse_start,
11105 regnode_offset ret;
11106 char* name_start = RExC_parse;
11108 SV *sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
11109 DECLARE_AND_GET_RE_DEBUG_FLAGS;
11111 PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF;
11113 if (RExC_parse == name_start || *RExC_parse != ch) {
11114 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
11115 vFAIL2("Sequence %.3s... not terminated", parse_start);
11119 num = add_data( pRExC_state, STR_WITH_LEN("S"));
11120 RExC_rxi->data->data[num]=(void*)sv_dat;
11121 SvREFCNT_inc_simple_void_NN(sv_dat);
11124 ret = reganode(pRExC_state,
11127 : (ASCII_FOLD_RESTRICTED)
11129 : (AT_LEAST_UNI_SEMANTICS)
11135 *flagp |= HASWIDTH;
11137 Set_Node_Offset(REGNODE_p(ret), parse_start+1);
11138 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
11140 nextchar(pRExC_state);
11144 /* On success, returns the offset at which any next node should be placed into
11145 * the regex engine program being compiled.
11147 * Returns 0 otherwise, with *flagp set to indicate why:
11148 * TRYAGAIN at the end of (?) that only sets flags.
11149 * RESTART_PARSE if the parse needs to be restarted, or'd with
11150 * NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
11151 * Otherwise would only return 0 if regbranch() returns 0, which cannot
11153 STATIC regnode_offset
11154 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp, U32 depth)
11155 /* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter.
11156 * 2 is like 1, but indicates that nextchar() has been called to advance
11157 * RExC_parse beyond the '('. Things like '(?' are indivisible tokens, and
11158 * this flag alerts us to the need to check for that */
11160 regnode_offset ret = 0; /* Will be the head of the group. */
11162 regnode_offset lastbr;
11163 regnode_offset ender = 0;
11166 U32 oregflags = RExC_flags;
11167 bool have_branch = 0;
11169 I32 freeze_paren = 0;
11170 I32 after_freeze = 0;
11171 I32 num; /* numeric backreferences */
11172 SV * max_open; /* Max number of unclosed parens */
11174 char * parse_start = RExC_parse; /* MJD */
11175 char * const oregcomp_parse = RExC_parse;
11177 DECLARE_AND_GET_RE_DEBUG_FLAGS;
11179 PERL_ARGS_ASSERT_REG;
11180 DEBUG_PARSE("reg ");
11182 max_open = get_sv(RE_COMPILE_RECURSION_LIMIT, GV_ADD);
11184 if (!SvIOK(max_open)) {
11185 sv_setiv(max_open, RE_COMPILE_RECURSION_INIT);
11187 if (depth > 4 * (UV) SvIV(max_open)) { /* We increase depth by 4 for each
11189 vFAIL("Too many nested open parens");
11192 *flagp = 0; /* Tentatively. */
11194 if (RExC_in_lookbehind) {
11195 RExC_in_lookbehind++;
11197 if (RExC_in_lookahead) {
11198 RExC_in_lookahead++;
11201 /* Having this true makes it feasible to have a lot fewer tests for the
11202 * parse pointer being in scope. For example, we can write
11203 * while(isFOO(*RExC_parse)) RExC_parse++;
11205 * while(RExC_parse < RExC_end && isFOO(*RExC_parse)) RExC_parse++;
11207 assert(*RExC_end == '\0');
11209 /* Make an OPEN node, if parenthesized. */
11212 /* Under /x, space and comments can be gobbled up between the '(' and
11213 * here (if paren ==2). The forms '(*VERB' and '(?...' disallow such
11214 * intervening space, as the sequence is a token, and a token should be
11216 bool has_intervening_patws = (paren == 2)
11217 && *(RExC_parse - 1) != '(';
11219 if (RExC_parse >= RExC_end) {
11220 vFAIL("Unmatched (");
11223 if (paren == 'r') { /* Atomic script run */
11227 else if ( *RExC_parse == '*') { /* (*VERB:ARG), (*construct:...) */
11228 char *start_verb = RExC_parse + 1;
11230 char *start_arg = NULL;
11231 unsigned char op = 0;
11232 int arg_required = 0;
11233 int internal_argval = -1; /* if >-1 we are not allowed an argument*/
11234 bool has_upper = FALSE;
11236 if (has_intervening_patws) {
11237 RExC_parse++; /* past the '*' */
11239 /* For strict backwards compatibility, don't change the message
11240 * now that we also have lowercase operands */
11241 if (isUPPER(*RExC_parse)) {
11242 vFAIL("In '(*VERB...)', the '(' and '*' must be adjacent");
11245 vFAIL("In '(*...)', the '(' and '*' must be adjacent");
11248 while (RExC_parse < RExC_end && *RExC_parse != ')' ) {
11249 if ( *RExC_parse == ':' ) {
11250 start_arg = RExC_parse + 1;
11254 if (isUPPER(*RExC_parse)) {
11260 RExC_parse += UTF8SKIP(RExC_parse);
11263 verb_len = RExC_parse - start_verb;
11265 if (RExC_parse >= RExC_end) {
11266 goto unterminated_verb_pattern;
11269 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11270 while ( RExC_parse < RExC_end && *RExC_parse != ')' ) {
11271 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11273 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
11274 unterminated_verb_pattern:
11276 vFAIL("Unterminated verb pattern argument");
11279 vFAIL("Unterminated '(*...' argument");
11283 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
11285 vFAIL("Unterminated verb pattern");
11288 vFAIL("Unterminated '(*...' construct");
11293 /* Here, we know that RExC_parse < RExC_end */
11295 switch ( *start_verb ) {
11296 case 'A': /* (*ACCEPT) */
11297 if ( memEQs(start_verb, verb_len,"ACCEPT") ) {
11299 internal_argval = RExC_nestroot;
11302 case 'C': /* (*COMMIT) */
11303 if ( memEQs(start_verb, verb_len,"COMMIT") )
11306 case 'F': /* (*FAIL) */
11307 if ( verb_len==1 || memEQs(start_verb, verb_len,"FAIL") ) {
11311 case ':': /* (*:NAME) */
11312 case 'M': /* (*MARK:NAME) */
11313 if ( verb_len==0 || memEQs(start_verb, verb_len,"MARK") ) {
11318 case 'P': /* (*PRUNE) */
11319 if ( memEQs(start_verb, verb_len,"PRUNE") )
11322 case 'S': /* (*SKIP) */
11323 if ( memEQs(start_verb, verb_len,"SKIP") )
11326 case 'T': /* (*THEN) */
11327 /* [19:06] <TimToady> :: is then */
11328 if ( memEQs(start_verb, verb_len,"THEN") ) {
11330 RExC_seen |= REG_CUTGROUP_SEEN;
11334 if ( memEQs(start_verb, verb_len, "asr")
11335 || memEQs(start_verb, verb_len, "atomic_script_run"))
11337 paren = 'r'; /* Mnemonic: recursed run */
11340 else if (memEQs(start_verb, verb_len, "atomic")) {
11341 paren = 't'; /* AtOMIC */
11342 goto alpha_assertions;
11346 if ( memEQs(start_verb, verb_len, "plb")
11347 || memEQs(start_verb, verb_len, "positive_lookbehind"))
11350 goto lookbehind_alpha_assertions;
11352 else if ( memEQs(start_verb, verb_len, "pla")
11353 || memEQs(start_verb, verb_len, "positive_lookahead"))
11356 goto alpha_assertions;
11360 if ( memEQs(start_verb, verb_len, "nlb")
11361 || memEQs(start_verb, verb_len, "negative_lookbehind"))
11364 goto lookbehind_alpha_assertions;
11366 else if ( memEQs(start_verb, verb_len, "nla")
11367 || memEQs(start_verb, verb_len, "negative_lookahead"))
11370 goto alpha_assertions;
11374 if ( memEQs(start_verb, verb_len, "sr")
11375 || memEQs(start_verb, verb_len, "script_run"))
11377 regnode_offset atomic;
11383 /* This indicates Unicode rules. */
11384 REQUIRE_UNI_RULES(flagp, 0);
11390 RExC_parse = start_arg;
11392 if (RExC_in_script_run) {
11394 /* Nested script runs are treated as no-ops, because
11395 * if the nested one fails, the outer one must as
11396 * well. It could fail sooner, and avoid (??{} with
11397 * side effects, but that is explicitly documented as
11398 * undefined behavior. */
11402 if (paren == 's') {
11407 /* But, the atomic part of a nested atomic script run
11408 * isn't a no-op, but can be treated just like a '(?>'
11414 if (paren == 's') {
11415 /* Here, we're starting a new regular script run */
11416 ret = reg_node(pRExC_state, SROPEN);
11417 RExC_in_script_run = 1;
11422 /* Here, we are starting an atomic script run. This is
11423 * handled by recursing to deal with the atomic portion
11424 * separately, enclosed in SROPEN ... SRCLOSE nodes */
11426 ret = reg_node(pRExC_state, SROPEN);
11428 RExC_in_script_run = 1;
11430 atomic = reg(pRExC_state, 'r', &flags, depth);
11431 if (flags & (RESTART_PARSE|NEED_UTF8)) {
11432 *flagp = flags & (RESTART_PARSE|NEED_UTF8);
11436 if (! REGTAIL(pRExC_state, ret, atomic)) {
11437 REQUIRE_BRANCHJ(flagp, 0);
11440 if (! REGTAIL(pRExC_state, atomic, reg_node(pRExC_state,
11443 REQUIRE_BRANCHJ(flagp, 0);
11446 RExC_in_script_run = 0;
11452 lookbehind_alpha_assertions:
11453 RExC_seen |= REG_LOOKBEHIND_SEEN;
11454 RExC_in_lookbehind++;
11459 RExC_seen_zerolen++;
11465 /* An empty negative lookahead assertion simply is failure */
11466 if (paren == 'A' && RExC_parse == start_arg) {
11467 ret=reganode(pRExC_state, OPFAIL, 0);
11468 nextchar(pRExC_state);
11472 RExC_parse = start_arg;
11477 "'(*%" UTF8f "' requires a terminating ':'",
11478 UTF8fARG(UTF, verb_len, start_verb));
11479 NOT_REACHED; /*NOTREACHED*/
11481 } /* End of switch */
11484 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
11486 if (has_upper || verb_len == 0) {
11488 "Unknown verb pattern '%" UTF8f "'",
11489 UTF8fARG(UTF, verb_len, start_verb));
11493 "Unknown '(*...)' construct '%" UTF8f "'",
11494 UTF8fARG(UTF, verb_len, start_verb));
11497 if ( RExC_parse == start_arg ) {
11500 if ( arg_required && !start_arg ) {
11501 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
11502 (int) verb_len, start_verb);
11504 if (internal_argval == -1) {
11505 ret = reganode(pRExC_state, op, 0);
11507 ret = reg2Lanode(pRExC_state, op, 0, internal_argval);
11509 RExC_seen |= REG_VERBARG_SEEN;
11511 SV *sv = newSVpvn( start_arg,
11512 RExC_parse - start_arg);
11513 ARG(REGNODE_p(ret)) = add_data( pRExC_state,
11514 STR_WITH_LEN("S"));
11515 RExC_rxi->data->data[ARG(REGNODE_p(ret))]=(void*)sv;
11516 FLAGS(REGNODE_p(ret)) = 1;
11518 FLAGS(REGNODE_p(ret)) = 0;
11520 if ( internal_argval != -1 )
11521 ARG2L_SET(REGNODE_p(ret), internal_argval);
11522 nextchar(pRExC_state);
11525 else if (*RExC_parse == '?') { /* (?...) */
11526 bool is_logical = 0;
11527 const char * const seqstart = RExC_parse;
11528 const char * endptr;
11529 const char non_existent_group_msg[]
11530 = "Reference to nonexistent group";
11531 const char impossible_group[] = "Invalid reference to group";
11533 if (has_intervening_patws) {
11535 vFAIL("In '(?...)', the '(' and '?' must be adjacent");
11538 RExC_parse++; /* past the '?' */
11539 paren = *RExC_parse; /* might be a trailing NUL, if not
11541 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11542 if (RExC_parse > RExC_end) {
11545 ret = 0; /* For look-ahead/behind. */
11548 case 'P': /* (?P...) variants for those used to PCRE/Python */
11549 paren = *RExC_parse;
11550 if ( paren == '<') { /* (?P<...>) named capture */
11552 if (RExC_parse >= RExC_end) {
11553 vFAIL("Sequence (?P<... not terminated");
11555 goto named_capture;
11557 else if (paren == '>') { /* (?P>name) named recursion */
11559 if (RExC_parse >= RExC_end) {
11560 vFAIL("Sequence (?P>... not terminated");
11562 goto named_recursion;
11564 else if (paren == '=') { /* (?P=...) named backref */
11566 return handle_named_backref(pRExC_state, flagp,
11569 RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
11570 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11571 vFAIL3("Sequence (%.*s...) not recognized",
11572 (int) (RExC_parse - seqstart), seqstart);
11573 NOT_REACHED; /*NOTREACHED*/
11574 case '<': /* (?<...) */
11575 /* If you want to support (?<*...), first reconcile with GH #17363 */
11576 if (*RExC_parse == '!')
11578 else if (*RExC_parse != '=')
11585 case '\'': /* (?'...') */
11586 name_start = RExC_parse;
11587 svname = reg_scan_name(pRExC_state, REG_RSN_RETURN_NAME);
11588 if ( RExC_parse == name_start
11589 || RExC_parse >= RExC_end
11590 || *RExC_parse != paren)
11592 vFAIL2("Sequence (?%c... not terminated",
11593 paren=='>' ? '<' : (char) paren);
11598 if (!svname) /* shouldn't happen */
11600 "panic: reg_scan_name returned NULL");
11601 if (!RExC_paren_names) {
11602 RExC_paren_names= newHV();
11603 sv_2mortal(MUTABLE_SV(RExC_paren_names));
11605 RExC_paren_name_list= newAV();
11606 sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
11609 he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
11611 sv_dat = HeVAL(he_str);
11613 /* croak baby croak */
11615 "panic: paren_name hash element allocation failed");
11616 } else if ( SvPOK(sv_dat) ) {
11617 /* (?|...) can mean we have dupes so scan to check
11618 its already been stored. Maybe a flag indicating
11619 we are inside such a construct would be useful,
11620 but the arrays are likely to be quite small, so
11621 for now we punt -- dmq */
11622 IV count = SvIV(sv_dat);
11623 I32 *pv = (I32*)SvPVX(sv_dat);
11625 for ( i = 0 ; i < count ; i++ ) {
11626 if ( pv[i] == RExC_npar ) {
11632 pv = (I32*)SvGROW(sv_dat,
11633 SvCUR(sv_dat) + sizeof(I32)+1);
11634 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
11635 pv[count] = RExC_npar;
11636 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
11639 (void)SvUPGRADE(sv_dat, SVt_PVNV);
11640 sv_setpvn(sv_dat, (char *)&(RExC_npar),
11643 SvIV_set(sv_dat, 1);
11646 /* Yes this does cause a memory leak in debugging Perls
11648 if (!av_store(RExC_paren_name_list,
11649 RExC_npar, SvREFCNT_inc_NN(svname)))
11650 SvREFCNT_dec_NN(svname);
11653 /*sv_dump(sv_dat);*/
11655 nextchar(pRExC_state);
11657 goto capturing_parens;
11660 RExC_seen |= REG_LOOKBEHIND_SEEN;
11661 RExC_in_lookbehind++;
11663 if (RExC_parse >= RExC_end) {
11664 vFAIL("Sequence (?... not terminated");
11666 RExC_seen_zerolen++;
11668 case '=': /* (?=...) */
11669 RExC_seen_zerolen++;
11670 RExC_in_lookahead++;
11672 case '!': /* (?!...) */
11673 RExC_seen_zerolen++;
11674 /* check if we're really just a "FAIL" assertion */
11675 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
11676 FALSE /* Don't force to /x */ );
11677 if (*RExC_parse == ')') {
11678 ret=reganode(pRExC_state, OPFAIL, 0);
11679 nextchar(pRExC_state);
11683 case '|': /* (?|...) */
11684 /* branch reset, behave like a (?:...) except that
11685 buffers in alternations share the same numbers */
11687 after_freeze = freeze_paren = RExC_npar;
11689 /* XXX This construct currently requires an extra pass.
11690 * Investigation would be required to see if that could be
11692 REQUIRE_PARENS_PASS;
11694 case ':': /* (?:...) */
11695 case '>': /* (?>...) */
11697 case '$': /* (?$...) */
11698 case '@': /* (?@...) */
11699 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
11701 case '0' : /* (?0) */
11702 case 'R' : /* (?R) */
11703 if (RExC_parse == RExC_end || *RExC_parse != ')')
11704 FAIL("Sequence (?R) not terminated");
11706 RExC_seen |= REG_RECURSE_SEEN;
11708 /* XXX These constructs currently require an extra pass.
11709 * It probably could be changed */
11710 REQUIRE_PARENS_PASS;
11712 *flagp |= POSTPONED;
11713 goto gen_recurse_regop;
11715 /* named and numeric backreferences */
11716 case '&': /* (?&NAME) */
11717 parse_start = RExC_parse - 1;
11720 SV *sv_dat = reg_scan_name(pRExC_state,
11721 REG_RSN_RETURN_DATA);
11722 num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
11724 if (RExC_parse >= RExC_end || *RExC_parse != ')')
11725 vFAIL("Sequence (?&... not terminated");
11726 goto gen_recurse_regop;
11729 if (! inRANGE(RExC_parse[0], '1', '9')) {
11731 vFAIL("Illegal pattern");
11733 goto parse_recursion;
11735 case '-': /* (?-1) */
11736 if (! inRANGE(RExC_parse[0], '1', '9')) {
11737 RExC_parse--; /* rewind to let it be handled later */
11741 case '1': case '2': case '3': case '4': /* (?1) */
11742 case '5': case '6': case '7': case '8': case '9':
11743 RExC_parse = (char *) seqstart + 1; /* Point to the digit */
11746 bool is_neg = FALSE;
11748 parse_start = RExC_parse - 1; /* MJD */
11749 if (*RExC_parse == '-') {
11754 if (grok_atoUV(RExC_parse, &unum, &endptr)
11758 RExC_parse = (char*)endptr;
11760 else { /* Overflow, or something like that. Position
11761 beyond all digits for the message */
11762 while (RExC_parse < RExC_end && isDIGIT(*RExC_parse)) {
11765 vFAIL(impossible_group);
11768 /* -num is always representable on 1 and 2's complement
11773 if (*RExC_parse!=')')
11774 vFAIL("Expecting close bracket");
11777 if (paren == '-' || paren == '+') {
11779 /* Don't overflow */
11780 if (UNLIKELY(I32_MAX - RExC_npar < num)) {
11782 vFAIL(impossible_group);
11786 Diagram of capture buffer numbering.
11787 Top line is the normal capture buffer numbers
11788 Bottom line is the negative indexing as from
11792 /(a(x)y)(a(b(c(?+2)d)e)f)(g(h))/
11793 /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
11794 - 5 4 3 2 1 X Y x x
11796 Resolve to absolute group. Recall that RExC_npar is +1 of
11797 the actual parenthesis group number. For lookahead, we
11798 have to compensate for that. Using the above example, when
11799 we get to Y in the parse, num is 2 and RExC_npar is 6. We
11800 want 7 for +2, and 4 for -2.
11802 if ( paren == '+' ) {
11808 if (paren == '-' && num < 1) {
11810 vFAIL(non_existent_group_msg);
11814 if (num >= RExC_npar) {
11816 /* It might be a forward reference; we can't fail until we
11817 * know, by completing the parse to get all the groups, and
11818 * then reparsing */
11819 if (ALL_PARENS_COUNTED) {
11820 if (num >= RExC_total_parens) {
11822 vFAIL(non_existent_group_msg);
11826 REQUIRE_PARENS_PASS;
11830 /* We keep track how many GOSUB items we have produced.
11831 To start off the ARG2L() of the GOSUB holds its "id",
11832 which is used later in conjunction with RExC_recurse
11833 to calculate the offset we need to jump for the GOSUB,
11834 which it will store in the final representation.
11835 We have to defer the actual calculation until much later
11836 as the regop may move.
11838 ret = reg2Lanode(pRExC_state, GOSUB, num, RExC_recurse_count);
11839 RExC_recurse_count++;
11840 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11841 "%*s%*s Recurse #%" UVuf " to %" IVdf "\n",
11842 22, "| |", (int)(depth * 2 + 1), "",
11843 (UV)ARG(REGNODE_p(ret)),
11844 (IV)ARG2L(REGNODE_p(ret))));
11845 RExC_seen |= REG_RECURSE_SEEN;
11847 Set_Node_Length(REGNODE_p(ret),
11848 1 + regarglen[OP(REGNODE_p(ret))]); /* MJD */
11849 Set_Node_Offset(REGNODE_p(ret), parse_start); /* MJD */
11851 *flagp |= POSTPONED;
11852 assert(*RExC_parse == ')');
11853 nextchar(pRExC_state);
11858 case '?': /* (??...) */
11860 if (*RExC_parse != '{') {
11861 RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
11862 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11864 "Sequence (%" UTF8f "...) not recognized",
11865 UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
11866 NOT_REACHED; /*NOTREACHED*/
11868 *flagp |= POSTPONED;
11872 case '{': /* (?{...}) */
11875 struct reg_code_block *cb;
11878 RExC_seen_zerolen++;
11880 if ( !pRExC_state->code_blocks
11881 || pRExC_state->code_index
11882 >= pRExC_state->code_blocks->count
11883 || pRExC_state->code_blocks->cb[pRExC_state->code_index].start
11884 != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
11887 if (RExC_pm_flags & PMf_USE_RE_EVAL)
11888 FAIL("panic: Sequence (?{...}): no code block found\n");
11889 FAIL("Eval-group not allowed at runtime, use re 'eval'");
11891 /* this is a pre-compiled code block (?{...}) */
11892 cb = &pRExC_state->code_blocks->cb[pRExC_state->code_index];
11893 RExC_parse = RExC_start + cb->end;
11895 if (cb->src_regex) {
11896 n = add_data(pRExC_state, STR_WITH_LEN("rl"));
11897 RExC_rxi->data->data[n] =
11898 (void*)SvREFCNT_inc((SV*)cb->src_regex);
11899 RExC_rxi->data->data[n+1] = (void*)o;
11902 n = add_data(pRExC_state,
11903 (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l", 1);
11904 RExC_rxi->data->data[n] = (void*)o;
11906 pRExC_state->code_index++;
11907 nextchar(pRExC_state);
11910 regnode_offset eval;
11911 ret = reg_node(pRExC_state, LOGICAL);
11913 eval = reg2Lanode(pRExC_state, EVAL,
11916 /* for later propagation into (??{})
11918 RExC_flags & RXf_PMf_COMPILETIME
11920 FLAGS(REGNODE_p(ret)) = 2;
11921 if (! REGTAIL(pRExC_state, ret, eval)) {
11922 REQUIRE_BRANCHJ(flagp, 0);
11924 /* deal with the length of this later - MJD */
11927 ret = reg2Lanode(pRExC_state, EVAL, n, 0);
11928 Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1);
11929 Set_Node_Offset(REGNODE_p(ret), parse_start);
11932 case '(': /* (?(?{...})...) and (?(?=...)...) */
11935 const int DEFINE_len = sizeof("DEFINE") - 1;
11936 if ( RExC_parse < RExC_end - 1
11937 && ( ( RExC_parse[0] == '?' /* (?(?...)) */
11938 && ( RExC_parse[1] == '='
11939 || RExC_parse[1] == '!'
11940 || RExC_parse[1] == '<'
11941 || RExC_parse[1] == '{'))
11942 || ( RExC_parse[0] == '*' /* (?(*...)) */
11943 && ( memBEGINs(RExC_parse + 1,
11944 (Size_t) (RExC_end - (RExC_parse + 1)),
11946 || memBEGINs(RExC_parse + 1,
11947 (Size_t) (RExC_end - (RExC_parse + 1)),
11949 || memBEGINs(RExC_parse + 1,
11950 (Size_t) (RExC_end - (RExC_parse + 1)),
11952 || memBEGINs(RExC_parse + 1,
11953 (Size_t) (RExC_end - (RExC_parse + 1)),
11955 || memBEGINs(RExC_parse + 1,
11956 (Size_t) (RExC_end - (RExC_parse + 1)),
11957 "positive_lookahead:")
11958 || memBEGINs(RExC_parse + 1,
11959 (Size_t) (RExC_end - (RExC_parse + 1)),
11960 "positive_lookbehind:")
11961 || memBEGINs(RExC_parse + 1,
11962 (Size_t) (RExC_end - (RExC_parse + 1)),
11963 "negative_lookahead:")
11964 || memBEGINs(RExC_parse + 1,
11965 (Size_t) (RExC_end - (RExC_parse + 1)),
11966 "negative_lookbehind:"))))
11967 ) { /* Lookahead or eval. */
11969 regnode_offset tail;
11971 ret = reg_node(pRExC_state, LOGICAL);
11972 FLAGS(REGNODE_p(ret)) = 1;
11974 tail = reg(pRExC_state, 1, &flag, depth+1);
11975 RETURN_FAIL_ON_RESTART(flag, flagp);
11976 if (! REGTAIL(pRExC_state, ret, tail)) {
11977 REQUIRE_BRANCHJ(flagp, 0);
11981 else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
11982 || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
11984 char ch = RExC_parse[0] == '<' ? '>' : '\'';
11985 char *name_start= RExC_parse++;
11987 SV *sv_dat=reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
11988 if ( RExC_parse == name_start
11989 || RExC_parse >= RExC_end
11990 || *RExC_parse != ch)
11992 vFAIL2("Sequence (?(%c... not terminated",
11993 (ch == '>' ? '<' : ch));
11997 num = add_data( pRExC_state, STR_WITH_LEN("S"));
11998 RExC_rxi->data->data[num]=(void*)sv_dat;
11999 SvREFCNT_inc_simple_void_NN(sv_dat);
12001 ret = reganode(pRExC_state, GROUPPN, num);
12002 goto insert_if_check_paren;
12004 else if (memBEGINs(RExC_parse,
12005 (STRLEN) (RExC_end - RExC_parse),
12008 ret = reganode(pRExC_state, DEFINEP, 0);
12009 RExC_parse += DEFINE_len;
12011 goto insert_if_check_paren;
12013 else if (RExC_parse[0] == 'R') {
12015 /* parno == 0 => /(?(R)YES|NO)/ "in any form of recursion OR eval"
12016 * parno == 1 => /(?(R0)YES|NO)/ "in GOSUB (?0) / (?R)"
12017 * parno == 2 => /(?(R1)YES|NO)/ "in GOSUB (?1) (parno-1)"
12020 if (RExC_parse[0] == '0') {
12024 else if (inRANGE(RExC_parse[0], '1', '9')) {
12027 if (grok_atoUV(RExC_parse, &uv, &endptr)
12030 parno = (I32)uv + 1;
12031 RExC_parse = (char*)endptr;
12033 /* else "Switch condition not recognized" below */
12034 } else if (RExC_parse[0] == '&') {
12037 sv_dat = reg_scan_name(pRExC_state,
12038 REG_RSN_RETURN_DATA);
12040 parno = 1 + *((I32 *)SvPVX(sv_dat));
12042 ret = reganode(pRExC_state, INSUBP, parno);
12043 goto insert_if_check_paren;
12045 else if (inRANGE(RExC_parse[0], '1', '9')) {
12050 if (grok_atoUV(RExC_parse, &uv, &endptr)
12054 RExC_parse = (char*)endptr;
12057 vFAIL("panic: grok_atoUV returned FALSE");
12059 ret = reganode(pRExC_state, GROUPP, parno);
12061 insert_if_check_paren:
12062 if (UCHARAT(RExC_parse) != ')') {
12064 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
12066 vFAIL("Switch condition not recognized");
12068 nextchar(pRExC_state);
12070 if (! REGTAIL(pRExC_state, ret, reganode(pRExC_state,
12073 REQUIRE_BRANCHJ(flagp, 0);
12075 br = regbranch(pRExC_state, &flags, 1, depth+1);
12077 RETURN_FAIL_ON_RESTART(flags,flagp);
12078 FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
12081 if (! REGTAIL(pRExC_state, br, reganode(pRExC_state,
12084 REQUIRE_BRANCHJ(flagp, 0);
12086 c = UCHARAT(RExC_parse);
12087 nextchar(pRExC_state);
12088 if (flags&HASWIDTH)
12089 *flagp |= HASWIDTH;
12092 vFAIL("(?(DEFINE)....) does not allow branches");
12094 /* Fake one for optimizer. */
12095 lastbr = reganode(pRExC_state, IFTHEN, 0);
12097 if (!regbranch(pRExC_state, &flags, 1, depth+1)) {
12098 RETURN_FAIL_ON_RESTART(flags, flagp);
12099 FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
12102 if (! REGTAIL(pRExC_state, ret, lastbr)) {
12103 REQUIRE_BRANCHJ(flagp, 0);
12105 if (flags&HASWIDTH)
12106 *flagp |= HASWIDTH;
12107 c = UCHARAT(RExC_parse);
12108 nextchar(pRExC_state);
12113 if (RExC_parse >= RExC_end)
12114 vFAIL("Switch (?(condition)... not terminated");
12116 vFAIL("Switch (?(condition)... contains too many branches");
12118 ender = reg_node(pRExC_state, TAIL);
12119 if (! REGTAIL(pRExC_state, br, ender)) {
12120 REQUIRE_BRANCHJ(flagp, 0);
12123 if (! REGTAIL(pRExC_state, lastbr, ender)) {
12124 REQUIRE_BRANCHJ(flagp, 0);
12126 if (! REGTAIL(pRExC_state,
12129 NEXTOPER(REGNODE_p(lastbr)))),
12132 REQUIRE_BRANCHJ(flagp, 0);
12136 if (! REGTAIL(pRExC_state, ret, ender)) {
12137 REQUIRE_BRANCHJ(flagp, 0);
12139 #if 0 /* Removing this doesn't cause failures in the test suite -- khw */
12140 RExC_size++; /* XXX WHY do we need this?!!
12141 For large programs it seems to be required
12142 but I can't figure out why. -- dmq*/
12147 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
12149 vFAIL("Unknown switch condition (?(...))");
12151 case '[': /* (?[ ... ]) */
12152 return handle_regex_sets(pRExC_state, NULL, flagp, depth+1,
12154 case 0: /* A NUL */
12155 RExC_parse--; /* for vFAIL to print correctly */
12156 vFAIL("Sequence (? incomplete");
12160 if (RExC_strict) { /* [perl #132851] */
12161 ckWARNreg(RExC_parse, "Empty (?) without any modifiers");
12164 case '*': /* If you want to support (?*...), first reconcile with GH #17363 */
12166 default: /* e.g., (?i) */
12167 RExC_parse = (char *) seqstart + 1;
12169 parse_lparen_question_flags(pRExC_state);
12170 if (UCHARAT(RExC_parse) != ':') {
12171 if (RExC_parse < RExC_end)
12172 nextchar(pRExC_state);
12177 nextchar(pRExC_state);
12182 else if (!(RExC_flags & RXf_PMf_NOCAPTURE)) { /* (...) */
12186 if (! ALL_PARENS_COUNTED) {
12187 /* If we are in our first pass through (and maybe only pass),
12188 * we need to allocate memory for the capturing parentheses
12192 if (!RExC_parens_buf_size) {
12193 /* first guess at number of parens we might encounter */
12194 RExC_parens_buf_size = 10;
12196 /* setup RExC_open_parens, which holds the address of each
12197 * OPEN tag, and to make things simpler for the 0 index the
12198 * start of the program - this is used later for offsets */
12199 Newxz(RExC_open_parens, RExC_parens_buf_size,
12201 RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */
12203 /* setup RExC_close_parens, which holds the address of each
12204 * CLOSE tag, and to make things simpler for the 0 index
12205 * the end of the program - this is used later for offsets
12207 Newxz(RExC_close_parens, RExC_parens_buf_size,
12209 /* we dont know where end op starts yet, so we dont need to
12210 * set RExC_close_parens[0] like we do RExC_open_parens[0]
12213 else if (RExC_npar > RExC_parens_buf_size) {
12214 I32 old_size = RExC_parens_buf_size;
12216 RExC_parens_buf_size *= 2;
12218 Renew(RExC_open_parens, RExC_parens_buf_size,
12220 Zero(RExC_open_parens + old_size,
12221 RExC_parens_buf_size - old_size, regnode_offset);
12223 Renew(RExC_close_parens, RExC_parens_buf_size,
12225 Zero(RExC_close_parens + old_size,
12226 RExC_parens_buf_size - old_size, regnode_offset);
12230 ret = reganode(pRExC_state, OPEN, parno);
12231 if (!RExC_nestroot)
12232 RExC_nestroot = parno;
12233 if (RExC_open_parens && !RExC_open_parens[parno])
12235 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12236 "%*s%*s Setting open paren #%" IVdf " to %zu\n",
12237 22, "| |", (int)(depth * 2 + 1), "",
12239 RExC_open_parens[parno]= ret;
12242 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
12243 Set_Node_Offset(REGNODE_p(ret), RExC_parse); /* MJD */
12246 /* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */
12255 /* Pick up the branches, linking them together. */
12256 parse_start = RExC_parse; /* MJD */
12257 br = regbranch(pRExC_state, &flags, 1, depth+1);
12259 /* branch_len = (paren != 0); */
12262 RETURN_FAIL_ON_RESTART(flags, flagp);
12263 FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12265 if (*RExC_parse == '|') {
12266 if (RExC_use_BRANCHJ) {
12267 reginsert(pRExC_state, BRANCHJ, br, depth+1);
12270 reginsert(pRExC_state, BRANCH, br, depth+1);
12271 Set_Node_Length(REGNODE_p(br), paren != 0);
12272 Set_Node_Offset_To_R(br, parse_start-RExC_start);
12276 else if (paren == ':') {
12277 *flagp |= flags&SIMPLE;
12279 if (is_open) { /* Starts with OPEN. */
12280 if (! REGTAIL(pRExC_state, ret, br)) { /* OPEN -> first. */
12281 REQUIRE_BRANCHJ(flagp, 0);
12284 else if (paren != '?') /* Not Conditional */
12286 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
12288 while (*RExC_parse == '|') {
12289 if (RExC_use_BRANCHJ) {
12292 ender = reganode(pRExC_state, LONGJMP, 0);
12294 /* Append to the previous. */
12295 shut_gcc_up = REGTAIL(pRExC_state,
12296 REGNODE_OFFSET(NEXTOPER(NEXTOPER(REGNODE_p(lastbr)))),
12298 PERL_UNUSED_VAR(shut_gcc_up);
12300 nextchar(pRExC_state);
12301 if (freeze_paren) {
12302 if (RExC_npar > after_freeze)
12303 after_freeze = RExC_npar;
12304 RExC_npar = freeze_paren;
12306 br = regbranch(pRExC_state, &flags, 0, depth+1);
12309 RETURN_FAIL_ON_RESTART(flags, flagp);
12310 FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12312 if (! REGTAIL(pRExC_state, lastbr, br)) { /* BRANCH -> BRANCH. */
12313 REQUIRE_BRANCHJ(flagp, 0);
12316 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
12319 if (have_branch || paren != ':') {
12322 /* Make a closing node, and hook it on the end. */
12325 ender = reg_node(pRExC_state, TAIL);
12328 ender = reganode(pRExC_state, CLOSE, parno);
12329 if ( RExC_close_parens ) {
12330 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12331 "%*s%*s Setting close paren #%" IVdf " to %zu\n",
12332 22, "| |", (int)(depth * 2 + 1), "",
12333 (IV)parno, ender));
12334 RExC_close_parens[parno]= ender;
12335 if (RExC_nestroot == parno)
12338 Set_Node_Offset(REGNODE_p(ender), RExC_parse+1); /* MJD */
12339 Set_Node_Length(REGNODE_p(ender), 1); /* MJD */
12342 ender = reg_node(pRExC_state, SRCLOSE);
12343 RExC_in_script_run = 0;
12353 *flagp &= ~HASWIDTH;
12355 case 't': /* aTomic */
12357 ender = reg_node(pRExC_state, SUCCEED);
12360 ender = reg_node(pRExC_state, END);
12361 assert(!RExC_end_op); /* there can only be one! */
12362 RExC_end_op = REGNODE_p(ender);
12363 if (RExC_close_parens) {
12364 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12365 "%*s%*s Setting close paren #0 (END) to %zu\n",
12366 22, "| |", (int)(depth * 2 + 1), "",
12369 RExC_close_parens[0]= ender;
12374 DEBUG_PARSE_MSG("lsbr");
12375 regprop(RExC_rx, RExC_mysv1, REGNODE_p(lastbr), NULL, pRExC_state);
12376 regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender), NULL, pRExC_state);
12377 Perl_re_printf( aTHX_ "~ tying lastbr %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12378 SvPV_nolen_const(RExC_mysv1),
12380 SvPV_nolen_const(RExC_mysv2),
12382 (IV)(ender - lastbr)
12385 if (! REGTAIL(pRExC_state, lastbr, ender)) {
12386 REQUIRE_BRANCHJ(flagp, 0);
12390 char is_nothing= 1;
12392 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
12394 /* Hook the tails of the branches to the closing node. */
12395 for (br = REGNODE_p(ret); br; br = regnext(br)) {
12396 const U8 op = PL_regkind[OP(br)];
12397 if (op == BRANCH) {
12398 if (! REGTAIL_STUDY(pRExC_state,
12399 REGNODE_OFFSET(NEXTOPER(br)),
12402 REQUIRE_BRANCHJ(flagp, 0);
12404 if ( OP(NEXTOPER(br)) != NOTHING
12405 || regnext(NEXTOPER(br)) != REGNODE_p(ender))
12408 else if (op == BRANCHJ) {
12409 bool shut_gcc_up = REGTAIL_STUDY(pRExC_state,
12410 REGNODE_OFFSET(NEXTOPER(NEXTOPER(br))),
12412 PERL_UNUSED_VAR(shut_gcc_up);
12413 /* for now we always disable this optimisation * /
12414 if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING
12415 || regnext(NEXTOPER(NEXTOPER(br))) != REGNODE_p(ender))
12421 regnode * ret_as_regnode = REGNODE_p(ret);
12422 br= PL_regkind[OP(ret_as_regnode)] != BRANCH
12423 ? regnext(ret_as_regnode)
12426 DEBUG_PARSE_MSG("NADA");
12427 regprop(RExC_rx, RExC_mysv1, ret_as_regnode,
12428 NULL, pRExC_state);
12429 regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender),
12430 NULL, pRExC_state);
12431 Perl_re_printf( aTHX_ "~ converting ret %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12432 SvPV_nolen_const(RExC_mysv1),
12433 (IV)REG_NODE_NUM(ret_as_regnode),
12434 SvPV_nolen_const(RExC_mysv2),
12440 if (OP(REGNODE_p(ender)) == TAIL) {
12442 RExC_emit= REGNODE_OFFSET(br) + 1;
12445 for ( opt= br + 1; opt < REGNODE_p(ender) ; opt++ )
12446 OP(opt)= OPTIMIZED;
12447 NEXT_OFF(br)= REGNODE_p(ender) - br;
12455 /* Even/odd or x=don't care: 010101x10x */
12456 static const char parens[] = "=!aA<,>Bbt";
12457 /* flag below is set to 0 up through 'A'; 1 for larger */
12459 if (paren && (p = strchr(parens, paren))) {
12460 U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
12461 int flag = (p - parens) > 3;
12463 if (paren == '>' || paren == 't') {
12464 node = SUSPEND, flag = 0;
12467 reginsert(pRExC_state, node, ret, depth+1);
12468 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12469 Set_Node_Offset(REGNODE_p(ret), parse_start + 1);
12470 FLAGS(REGNODE_p(ret)) = flag;
12471 if (! REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL)))
12473 REQUIRE_BRANCHJ(flagp, 0);
12478 /* Check for proper termination. */
12480 /* restore original flags, but keep (?p) and, if we've encountered
12481 * something in the parse that changes /d rules into /u, keep the /u */
12482 RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY);
12483 if (DEPENDS_SEMANTICS && RExC_uni_semantics) {
12484 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
12486 if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') {
12487 RExC_parse = oregcomp_parse;
12488 vFAIL("Unmatched (");
12490 nextchar(pRExC_state);
12492 else if (!paren && RExC_parse < RExC_end) {
12493 if (*RExC_parse == ')') {
12495 vFAIL("Unmatched )");
12498 FAIL("Junk on end of regexp"); /* "Can't happen". */
12499 NOT_REACHED; /* NOTREACHED */
12502 if (RExC_in_lookbehind) {
12503 RExC_in_lookbehind--;
12505 if (RExC_in_lookahead) {
12506 RExC_in_lookahead--;
12508 if (after_freeze > RExC_npar)
12509 RExC_npar = after_freeze;
12514 - regbranch - one alternative of an | operator
12516 * Implements the concatenation operator.
12518 * On success, returns the offset at which any next node should be placed into
12519 * the regex engine program being compiled.
12521 * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
12522 * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
12525 STATIC regnode_offset
12526 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
12528 regnode_offset ret;
12529 regnode_offset chain = 0;
12530 regnode_offset latest;
12531 I32 flags = 0, c = 0;
12532 DECLARE_AND_GET_RE_DEBUG_FLAGS;
12534 PERL_ARGS_ASSERT_REGBRANCH;
12536 DEBUG_PARSE("brnc");
12541 if (RExC_use_BRANCHJ)
12542 ret = reganode(pRExC_state, BRANCHJ, 0);
12544 ret = reg_node(pRExC_state, BRANCH);
12545 Set_Node_Length(REGNODE_p(ret), 1);
12549 *flagp = WORST; /* Tentatively. */
12551 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
12552 FALSE /* Don't force to /x */ );
12553 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
12554 flags &= ~TRYAGAIN;
12555 latest = regpiece(pRExC_state, &flags, depth+1);
12557 if (flags & TRYAGAIN)
12559 RETURN_FAIL_ON_RESTART(flags, flagp);
12560 FAIL2("panic: regpiece returned failure, flags=%#" UVxf, (UV) flags);
12564 *flagp |= flags&(HASWIDTH|POSTPONED);
12565 if (chain == 0) /* First piece. */
12566 *flagp |= flags&SPSTART;
12568 /* FIXME adding one for every branch after the first is probably
12569 * excessive now we have TRIE support. (hv) */
12571 if (! REGTAIL(pRExC_state, chain, latest)) {
12572 /* XXX We could just redo this branch, but figuring out what
12573 * bookkeeping needs to be reset is a pain, and it's likely
12574 * that other branches that goto END will also be too large */
12575 REQUIRE_BRANCHJ(flagp, 0);
12581 if (chain == 0) { /* Loop ran zero times. */
12582 chain = reg_node(pRExC_state, NOTHING);
12587 *flagp |= flags&SIMPLE;
12594 - regpiece - something followed by possible quantifier * + ? {n,m}
12596 * Note that the branching code sequences used for ? and the general cases
12597 * of * and + are somewhat optimized: they use the same NOTHING node as
12598 * both the endmarker for their branch list and the body of the last branch.
12599 * It might seem that this node could be dispensed with entirely, but the
12600 * endmarker role is not redundant.
12602 * On success, returns the offset at which any next node should be placed into
12603 * the regex engine program being compiled.
12605 * Returns 0 otherwise, with *flagp set to indicate why:
12606 * TRYAGAIN if regatom() returns 0 with TRYAGAIN.
12607 * RESTART_PARSE if the parse needs to be restarted, or'd with
12608 * NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
12610 STATIC regnode_offset
12611 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
12613 regnode_offset ret;
12617 const char * const origparse = RExC_parse;
12619 I32 max = REG_INFTY;
12620 #ifdef RE_TRACK_PATTERN_OFFSETS
12623 const char *maxpos = NULL;
12626 /* Save the original in case we change the emitted regop to a FAIL. */
12627 const regnode_offset orig_emit = RExC_emit;
12629 DECLARE_AND_GET_RE_DEBUG_FLAGS;
12631 PERL_ARGS_ASSERT_REGPIECE;
12633 DEBUG_PARSE("piec");
12635 ret = regatom(pRExC_state, &flags, depth+1);
12637 RETURN_FAIL_ON_RESTART_OR_FLAGS(flags, flagp, TRYAGAIN);
12638 FAIL2("panic: regatom returned failure, flags=%#" UVxf, (UV) flags);
12643 if (op == '{' && regcurly(RExC_parse)) {
12645 #ifdef RE_TRACK_PATTERN_OFFSETS
12646 parse_start = RExC_parse; /* MJD */
12648 next = RExC_parse + 1;
12649 while (isDIGIT(*next) || *next == ',') {
12650 if (*next == ',') {
12658 if (*next == '}') { /* got one */
12659 const char* endptr;
12663 if (isDIGIT(*RExC_parse)) {
12665 if (!grok_atoUV(RExC_parse, &uv, &endptr))
12666 vFAIL("Invalid quantifier in {,}");
12667 if (uv >= REG_INFTY)
12668 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12673 if (*maxpos == ',')
12676 maxpos = RExC_parse;
12677 if (isDIGIT(*maxpos)) {
12679 if (!grok_atoUV(maxpos, &uv, &endptr))
12680 vFAIL("Invalid quantifier in {,}");
12681 if (uv >= REG_INFTY)
12682 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12685 max = REG_INFTY; /* meaning "infinity" */
12688 nextchar(pRExC_state);
12689 if (max < min) { /* If can't match, warn and optimize to fail
12691 reginsert(pRExC_state, OPFAIL, orig_emit, depth+1);
12692 ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
12693 NEXT_OFF(REGNODE_p(orig_emit)) =
12694 regarglen[OPFAIL] + NODE_STEP_REGNODE;
12697 else if (min == max && *RExC_parse == '?')
12699 ckWARN2reg(RExC_parse + 1,
12700 "Useless use of greediness modifier '%c'",
12705 if ((flags&SIMPLE)) {
12706 if (min == 0 && max == REG_INFTY) {
12708 /* Going from 0..inf is currently forbidden in wildcard
12709 * subpatterns. The only reason is to make it harder to
12710 * write patterns that take a long long time to halt, and
12711 * because the use of this construct isn't necessary in
12712 * matching Unicode property values */
12713 if (RExC_pm_flags & PMf_WILDCARD) {
12715 /* diag_listed_as: Use of %s is not allowed in Unicode
12716 property wildcard subpatterns in regex; marked by
12717 <-- HERE in m/%s/ */
12718 vFAIL("Use of quantifier '*' is not allowed in"
12719 " Unicode property wildcard subpatterns");
12720 /* Note, don't need to worry about {0,}, as a '}' isn't
12721 * legal at all in wildcards, so wouldn't get this far
12724 reginsert(pRExC_state, STAR, ret, depth+1);
12726 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12729 if (min == 1 && max == REG_INFTY) {
12730 reginsert(pRExC_state, PLUS, ret, depth+1);
12732 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12735 MARK_NAUGHTY_EXP(2, 2);
12736 reginsert(pRExC_state, CURLY, ret, depth+1);
12737 Set_Node_Offset(REGNODE_p(ret), parse_start+1); /* MJD */
12738 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12741 const regnode_offset w = reg_node(pRExC_state, WHILEM);
12743 FLAGS(REGNODE_p(w)) = 0;
12744 if (! REGTAIL(pRExC_state, ret, w)) {
12745 REQUIRE_BRANCHJ(flagp, 0);
12747 if (RExC_use_BRANCHJ) {
12748 reginsert(pRExC_state, LONGJMP, ret, depth+1);
12749 reginsert(pRExC_state, NOTHING, ret, depth+1);
12750 NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over LONGJMP. */
12752 reginsert(pRExC_state, CURLYX, ret, depth+1);
12754 Set_Node_Offset(REGNODE_p(ret), parse_start+1);
12755 Set_Node_Length(REGNODE_p(ret),
12756 op == '{' ? (RExC_parse - parse_start) : 1);
12758 if (RExC_use_BRANCHJ)
12759 NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over NOTHING to
12761 if (! REGTAIL(pRExC_state, ret, reg_node(pRExC_state,
12764 REQUIRE_BRANCHJ(flagp, 0);
12766 RExC_whilem_seen++;
12767 MARK_NAUGHTY_EXP(1, 4); /* compound interest */
12769 FLAGS(REGNODE_p(ret)) = 0;
12774 *flagp |= HASWIDTH;
12775 ARG1_SET(REGNODE_p(ret), (U16)min);
12776 ARG2_SET(REGNODE_p(ret), (U16)max);
12777 if (max == REG_INFTY)
12778 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12784 if (!ISMULT1(op)) {
12789 #if 0 /* Now runtime fix should be reliable. */
12791 /* if this is reinstated, don't forget to put this back into perldiag:
12793 =item Regexp *+ operand could be empty at {#} in regex m/%s/
12795 (F) The part of the regexp subject to either the * or + quantifier
12796 could match an empty string. The {#} shows in the regular
12797 expression about where the problem was discovered.
12801 if (!(flags&HASWIDTH) && op != '?')
12802 vFAIL("Regexp *+ operand could be empty");
12805 #ifdef RE_TRACK_PATTERN_OFFSETS
12806 parse_start = RExC_parse;
12808 nextchar(pRExC_state);
12810 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
12816 else if (op == '+') {
12820 else if (op == '?') {
12825 if (!(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
12826 if (origparse[0] == '\\' && origparse[1] == 'K') {
12828 "%" UTF8f " is forbidden - matches null string many times",
12829 UTF8fARG(UTF, (RExC_parse >= origparse
12830 ? RExC_parse - origparse
12835 ckWARN2reg(RExC_parse,
12836 "%" UTF8f " matches null string many times",
12837 UTF8fARG(UTF, (RExC_parse >= origparse
12838 ? RExC_parse - origparse
12844 if (*RExC_parse == '?') {
12845 nextchar(pRExC_state);
12846 reginsert(pRExC_state, MINMOD, ret, depth+1);
12847 if (! REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE)) {
12848 REQUIRE_BRANCHJ(flagp, 0);
12851 else if (*RExC_parse == '+') {
12852 regnode_offset ender;
12853 nextchar(pRExC_state);
12854 ender = reg_node(pRExC_state, SUCCEED);
12855 if (! REGTAIL(pRExC_state, ret, ender)) {
12856 REQUIRE_BRANCHJ(flagp, 0);
12858 reginsert(pRExC_state, SUSPEND, ret, depth+1);
12859 ender = reg_node(pRExC_state, TAIL);
12860 if (! REGTAIL(pRExC_state, ret, ender)) {
12861 REQUIRE_BRANCHJ(flagp, 0);
12865 if (ISMULT2(RExC_parse)) {
12867 vFAIL("Nested quantifiers");
12874 S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state,
12875 regnode_offset * node_p,
12883 /* This routine teases apart the various meanings of \N and returns
12884 * accordingly. The input parameters constrain which meaning(s) is/are valid
12885 * in the current context.
12887 * Exactly one of <node_p> and <code_point_p> must be non-NULL.
12889 * If <code_point_p> is not NULL, the context is expecting the result to be a
12890 * single code point. If this \N instance turns out to a single code point,
12891 * the function returns TRUE and sets *code_point_p to that code point.
12893 * If <node_p> is not NULL, the context is expecting the result to be one of
12894 * the things representable by a regnode. If this \N instance turns out to be
12895 * one such, the function generates the regnode, returns TRUE and sets *node_p
12896 * to point to the offset of that regnode into the regex engine program being
12899 * If this instance of \N isn't legal in any context, this function will
12900 * generate a fatal error and not return.
12902 * On input, RExC_parse should point to the first char following the \N at the
12903 * time of the call. On successful return, RExC_parse will have been updated
12904 * to point to just after the sequence identified by this routine. Also
12905 * *flagp has been updated as needed.
12907 * When there is some problem with the current context and this \N instance,
12908 * the function returns FALSE, without advancing RExC_parse, nor setting
12909 * *node_p, nor *code_point_p, nor *flagp.
12911 * If <cp_count> is not NULL, the caller wants to know the length (in code
12912 * points) that this \N sequence matches. This is set, and the input is
12913 * parsed for errors, even if the function returns FALSE, as detailed below.
12915 * There are 6 possibilities here, as detailed in the next 6 paragraphs.
12917 * Probably the most common case is for the \N to specify a single code point.
12918 * *cp_count will be set to 1, and *code_point_p will be set to that code
12921 * Another possibility is for the input to be an empty \N{}. This is no
12922 * longer accepted, and will generate a fatal error.
12924 * Another possibility is for a custom charnames handler to be in effect which
12925 * translates the input name to an empty string. *cp_count will be set to 0.
12926 * *node_p will be set to a generated NOTHING node.
12928 * Still another possibility is for the \N to mean [^\n]. *cp_count will be
12929 * set to 0. *node_p will be set to a generated REG_ANY node.
12931 * The fifth possibility is that \N resolves to a sequence of more than one
12932 * code points. *cp_count will be set to the number of code points in the
12933 * sequence. *node_p will be set to a generated node returned by this
12934 * function calling S_reg().
12936 * The final possibility is that it is premature to be calling this function;
12937 * the parse needs to be restarted. This can happen when this changes from
12938 * /d to /u rules, or when the pattern needs to be upgraded to UTF-8. The
12939 * latter occurs only when the fifth possibility would otherwise be in
12940 * effect, and is because one of those code points requires the pattern to be
12941 * recompiled as UTF-8. The function returns FALSE, and sets the
12942 * RESTART_PARSE and NEED_UTF8 flags in *flagp, as appropriate. When this
12943 * happens, the caller needs to desist from continuing parsing, and return
12944 * this information to its caller. This is not set for when there is only one
12945 * code point, as this can be called as part of an ANYOF node, and they can
12946 * store above-Latin1 code points without the pattern having to be in UTF-8.
12948 * For non-single-quoted regexes, the tokenizer has resolved character and
12949 * sequence names inside \N{...} into their Unicode values, normalizing the
12950 * result into what we should see here: '\N{U+c1.c2...}', where c1... are the
12951 * hex-represented code points in the sequence. This is done there because
12952 * the names can vary based on what charnames pragma is in scope at the time,
12953 * so we need a way to take a snapshot of what they resolve to at the time of
12954 * the original parse. [perl #56444].
12956 * That parsing is skipped for single-quoted regexes, so here we may get
12957 * '\N{NAME}', which is parsed now. If the single-quoted regex is something
12958 * like '\N{U+41}', that code point is Unicode, and has to be translated into
12959 * the native character set for non-ASCII platforms. The other possibilities
12960 * are already native, so no translation is done. */
12962 char * endbrace; /* points to '}' following the name */
12963 char* p = RExC_parse; /* Temporary */
12965 SV * substitute_parse = NULL;
12970 DECLARE_AND_GET_RE_DEBUG_FLAGS;
12972 PERL_ARGS_ASSERT_GROK_BSLASH_N;
12974 assert(cBOOL(node_p) ^ cBOOL(code_point_p)); /* Exactly one should be set */
12975 assert(! (node_p && cp_count)); /* At most 1 should be set */
12977 if (cp_count) { /* Initialize return for the most common case */
12981 /* The [^\n] meaning of \N ignores spaces and comments under the /x
12982 * modifier. The other meanings do not, so use a temporary until we find
12983 * out which we are being called with */
12984 skip_to_be_ignored_text(pRExC_state, &p,
12985 FALSE /* Don't force to /x */ );
12987 /* Disambiguate between \N meaning a named character versus \N meaning
12988 * [^\n]. The latter is assumed when the {...} following the \N is a legal
12989 * quantifier, or if there is no '{' at all */
12990 if (*p != '{' || regcurly(p)) {
13000 *node_p = reg_node(pRExC_state, REG_ANY);
13001 *flagp |= HASWIDTH|SIMPLE;
13003 Set_Node_Length(REGNODE_p(*(node_p)), 1); /* MJD */
13007 /* The test above made sure that the next real character is a '{', but
13008 * under the /x modifier, it could be separated by space (or a comment and
13009 * \n) and this is not allowed (for consistency with \x{...} and the
13010 * tokenizer handling of \N{NAME}). */
13011 if (*RExC_parse != '{') {
13012 vFAIL("Missing braces on \\N{}");
13015 RExC_parse++; /* Skip past the '{' */
13017 endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
13018 if (! endbrace) { /* no trailing brace */
13019 vFAIL2("Missing right brace on \\%c{}", 'N');
13022 /* Here, we have decided it should be a named character or sequence. These
13023 * imply Unicode semantics */
13024 REQUIRE_UNI_RULES(flagp, FALSE);
13026 /* \N{_} is what toke.c returns to us to indicate a name that evaluates to
13027 * nothing at all (not allowed under strict) */
13028 if (endbrace - RExC_parse == 1 && *RExC_parse == '_') {
13029 RExC_parse = endbrace;
13031 RExC_parse++; /* Position after the "}" */
13032 vFAIL("Zero length \\N{}");
13038 nextchar(pRExC_state);
13043 *node_p = reg_node(pRExC_state, NOTHING);
13047 if (endbrace - RExC_parse < 2 || ! strBEGINs(RExC_parse, "U+")) {
13049 /* Here, the name isn't of the form U+.... This can happen if the
13050 * pattern is single-quoted, so didn't get evaluated in toke.c. Now
13051 * is the time to find out what the name means */
13053 const STRLEN name_len = endbrace - RExC_parse;
13054 SV * value_sv; /* What does this name evaluate to */
13056 const U8 * value; /* string of name's value */
13057 STRLEN value_len; /* and its length */
13059 /* RExC_unlexed_names is a hash of names that weren't evaluated by
13060 * toke.c, and their values. Make sure is initialized */
13061 if (! RExC_unlexed_names) {
13062 RExC_unlexed_names = newHV();
13065 /* If we have already seen this name in this pattern, use that. This
13066 * allows us to only call the charnames handler once per name per
13067 * pattern. A broken or malicious handler could return something
13068 * different each time, which could cause the results to vary depending
13069 * on if something gets added or subtracted from the pattern that
13070 * causes the number of passes to change, for example */
13071 if ((value_svp = hv_fetch(RExC_unlexed_names, RExC_parse,
13074 value_sv = *value_svp;
13076 else { /* Otherwise we have to go out and get the name */
13077 const char * error_msg = NULL;
13078 value_sv = get_and_check_backslash_N_name(RExC_parse, endbrace,
13082 RExC_parse = endbrace;
13086 /* If no error message, should have gotten a valid return */
13089 /* Save the name's meaning for later use */
13090 if (! hv_store(RExC_unlexed_names, RExC_parse, name_len,
13093 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
13097 /* Here, we have the value the name evaluates to in 'value_sv' */
13098 value = (U8 *) SvPV(value_sv, value_len);
13100 /* See if the result is one code point vs 0 or multiple */
13101 if (inRANGE(value_len, 1, ((UV) SvUTF8(value_sv)
13105 /* Here, exactly one code point. If that isn't what is wanted,
13107 if (! code_point_p) {
13112 /* Convert from string to numeric code point */
13113 *code_point_p = (SvUTF8(value_sv))
13114 ? valid_utf8_to_uvchr(value, NULL)
13117 /* Have parsed this entire single code point \N{...}. *cp_count
13118 * has already been set to 1, so don't do it again. */
13119 RExC_parse = endbrace;
13120 nextchar(pRExC_state);
13122 } /* End of is a single code point */
13124 /* Count the code points, if caller desires. The API says to do this
13125 * even if we will later return FALSE */
13129 *cp_count = (SvUTF8(value_sv))
13130 ? utf8_length(value, value + value_len)
13134 /* Fail if caller doesn't want to handle a multi-code-point sequence.
13135 * But don't back the pointer up if the caller wants to know how many
13136 * code points there are (they need to handle it themselves in this
13145 /* Convert this to a sub-pattern of the form "(?: ... )", and then call
13146 * reg recursively to parse it. That way, it retains its atomicness,
13147 * while not having to worry about any special handling that some code
13148 * points may have. */
13150 substitute_parse = newSVpvs("?:");
13151 sv_catsv(substitute_parse, value_sv);
13152 sv_catpv(substitute_parse, ")");
13154 /* The value should already be native, so no need to convert on EBCDIC
13156 assert(! RExC_recode_x_to_native);
13159 else { /* \N{U+...} */
13160 Size_t count = 0; /* code point count kept internally */
13162 /* We can get to here when the input is \N{U+...} or when toke.c has
13163 * converted a name to the \N{U+...} form. This include changing a
13164 * name that evaluates to multiple code points to \N{U+c1.c2.c3 ...} */
13166 RExC_parse += 2; /* Skip past the 'U+' */
13168 /* Code points are separated by dots. The '}' terminates the whole
13171 do { /* Loop until the ending brace */
13172 I32 flags = PERL_SCAN_SILENT_OVERFLOW
13173 | PERL_SCAN_SILENT_ILLDIGIT
13174 | PERL_SCAN_NOTIFY_ILLDIGIT
13175 | PERL_SCAN_ALLOW_MEDIAL_UNDERSCORES
13176 | PERL_SCAN_DISALLOW_PREFIX;
13177 STRLEN len = endbrace - RExC_parse;
13179 char * start_digit = RExC_parse;
13180 UV cp = grok_hex(RExC_parse, &len, &flags, &overflow_value);
13185 vFAIL("Invalid hexadecimal number in \\N{U+...}");
13190 if (cp > MAX_LEGAL_CP) {
13191 vFAIL(form_cp_too_large_msg(16, start_digit, len, 0));
13194 if (RExC_parse >= endbrace) { /* Got to the closing '}' */
13199 /* Here, is a single code point; fail if doesn't want that */
13200 if (! code_point_p) {
13205 /* A single code point is easy to handle; just return it */
13206 *code_point_p = UNI_TO_NATIVE(cp);
13207 RExC_parse = endbrace;
13208 nextchar(pRExC_state);
13212 /* Here, the parse stopped bfore the ending brace. This is legal
13213 * only if that character is a dot separating code points, like a
13214 * multiple character sequence (of the form "\N{U+c1.c2. ... }".
13215 * So the next character must be a dot (and the one after that
13216 * can't be the endbrace, or we'd have something like \N{U+100.} )
13218 if (*RExC_parse != '.' || RExC_parse + 1 >= endbrace) {
13219 RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */
13220 ? UTF8SKIP(RExC_parse)
13222 RExC_parse = MIN(endbrace, RExC_parse);/* Guard against
13227 /* Here, looks like its really a multiple character sequence. Fail
13228 * if that's not what the caller wants. But continue with counting
13229 * and error checking if they still want a count */
13230 if (! node_p && ! cp_count) {
13234 /* What is done here is to convert this to a sub-pattern of the
13235 * form \x{char1}\x{char2}... and then call reg recursively to
13236 * parse it (enclosing in "(?: ... )" ). That way, it retains its
13237 * atomicness, while not having to worry about special handling
13238 * that some code points may have. We don't create a subpattern,
13239 * but go through the motions of code point counting and error
13240 * checking, if the caller doesn't want a node returned. */
13242 if (node_p && ! substitute_parse) {
13243 substitute_parse = newSVpvs("?:");
13249 /* Convert to notation the rest of the code understands */
13250 sv_catpvs(substitute_parse, "\\x{");
13251 sv_catpvn(substitute_parse, start_digit,
13252 RExC_parse - start_digit);
13253 sv_catpvs(substitute_parse, "}");
13256 /* Move to after the dot (or ending brace the final time through.)
13261 } while (RExC_parse < endbrace);
13263 if (! node_p) { /* Doesn't want the node */
13270 sv_catpvs(substitute_parse, ")");
13272 /* The values are Unicode, and therefore have to be converted to native
13273 * on a non-Unicode (meaning non-ASCII) platform. */
13274 SET_recode_x_to_native(1);
13277 /* Here, we have the string the name evaluates to, ready to be parsed,
13278 * stored in 'substitute_parse' as a series of valid "\x{...}\x{...}"
13279 * constructs. This can be called from within a substitute parse already.
13280 * The error reporting mechanism doesn't work for 2 levels of this, but the
13281 * code above has validated this new construct, so there should be no
13282 * errors generated by the below. And this isn' an exact copy, so the
13283 * mechanism to seamlessly deal with this won't work, so turn off warnings
13285 save_start = RExC_start;
13286 orig_end = RExC_end;
13288 RExC_parse = RExC_start = SvPVX(substitute_parse);
13289 RExC_end = RExC_parse + SvCUR(substitute_parse);
13290 TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
13292 *node_p = reg(pRExC_state, 1, &flags, depth+1);
13294 /* Restore the saved values */
13296 RExC_start = save_start;
13297 RExC_parse = endbrace;
13298 RExC_end = orig_end;
13299 SET_recode_x_to_native(0);
13301 SvREFCNT_dec_NN(substitute_parse);
13304 RETURN_FAIL_ON_RESTART(flags, flagp);
13305 FAIL2("panic: reg returned failure to grok_bslash_N, flags=%#" UVxf,
13308 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
13310 nextchar(pRExC_state);
13317 S_compute_EXACTish(RExC_state_t *pRExC_state)
13321 PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
13329 op = get_regex_charset(RExC_flags);
13330 if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
13331 op--; /* /a is same as /u, and map /aa's offset to what /a's would have
13332 been, so there is no hole */
13335 return op + EXACTF;
13339 S_new_regcurly(const char *s, const char *e)
13341 /* This is a temporary function designed to match the most lenient form of
13342 * a {m,n} quantifier we ever envision, with either number omitted, and
13343 * spaces anywhere between/before/after them.
13345 * If this function fails, then the string it matches is very unlikely to
13346 * ever be considered a valid quantifier, so we can allow the '{' that
13347 * begins it to be considered as a literal */
13349 bool has_min = FALSE;
13350 bool has_max = FALSE;
13352 PERL_ARGS_ASSERT_NEW_REGCURLY;
13354 if (s >= e || *s++ != '{')
13357 while (s < e && isSPACE(*s)) {
13360 while (s < e && isDIGIT(*s)) {
13364 while (s < e && isSPACE(*s)) {
13370 while (s < e && isSPACE(*s)) {
13373 while (s < e && isDIGIT(*s)) {
13377 while (s < e && isSPACE(*s)) {
13382 return s < e && *s == '}' && (has_min || has_max);
13385 /* Parse backref decimal value, unless it's too big to sensibly be a backref,
13386 * in which case return I32_MAX (rather than possibly 32-bit wrapping) */
13389 S_backref_value(char *p, char *e)
13391 const char* endptr = e;
13393 if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX)
13400 - regatom - the lowest level
13402 Try to identify anything special at the start of the current parse position.
13403 If there is, then handle it as required. This may involve generating a
13404 single regop, such as for an assertion; or it may involve recursing, such as
13405 to handle a () structure.
13407 If the string doesn't start with something special then we gobble up
13408 as much literal text as we can. If we encounter a quantifier, we have to
13409 back off the final literal character, as that quantifier applies to just it
13410 and not to the whole string of literals.
13412 Once we have been able to handle whatever type of thing started the
13413 sequence, we return the offset into the regex engine program being compiled
13414 at which any next regnode should be placed.
13416 Returns 0, setting *flagp to TRYAGAIN if reg() returns 0 with TRYAGAIN.
13417 Returns 0, setting *flagp to RESTART_PARSE if the parse needs to be
13418 restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
13419 Otherwise does not return 0.
13421 Note: we have to be careful with escapes, as they can be both literal
13422 and special, and in the case of \10 and friends, context determines which.
13424 A summary of the code structure is:
13426 switch (first_byte) {
13427 cases for each special:
13428 handle this special;
13431 switch (2nd byte) {
13432 cases for each unambiguous special:
13433 handle this special;
13435 cases for each ambigous special/literal:
13437 if (special) handle here
13439 default: // unambiguously literal:
13442 default: // is a literal char
13445 create EXACTish node for literal;
13446 while (more input and node isn't full) {
13447 switch (input_byte) {
13448 cases for each special;
13449 make sure parse pointer is set so that the next call to
13450 regatom will see this special first
13451 goto loopdone; // EXACTish node terminated by prev. char
13453 append char to EXACTISH node;
13455 get next input byte;
13459 return the generated node;
13461 Specifically there are two separate switches for handling
13462 escape sequences, with the one for handling literal escapes requiring
13463 a dummy entry for all of the special escapes that are actually handled
13468 STATIC regnode_offset
13469 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
13472 regnode_offset ret = 0;
13478 DECLARE_AND_GET_RE_DEBUG_FLAGS;
13480 *flagp = WORST; /* Tentatively. */
13482 DEBUG_PARSE("atom");
13484 PERL_ARGS_ASSERT_REGATOM;
13487 parse_start = RExC_parse;
13488 assert(RExC_parse < RExC_end);
13489 switch ((U8)*RExC_parse) {
13491 RExC_seen_zerolen++;
13492 nextchar(pRExC_state);
13493 if (RExC_flags & RXf_PMf_MULTILINE)
13494 ret = reg_node(pRExC_state, MBOL);
13496 ret = reg_node(pRExC_state, SBOL);
13497 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13500 nextchar(pRExC_state);
13502 RExC_seen_zerolen++;
13503 if (RExC_flags & RXf_PMf_MULTILINE)
13504 ret = reg_node(pRExC_state, MEOL);
13506 ret = reg_node(pRExC_state, SEOL);
13507 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13510 nextchar(pRExC_state);
13511 if (RExC_flags & RXf_PMf_SINGLELINE)
13512 ret = reg_node(pRExC_state, SANY);
13514 ret = reg_node(pRExC_state, REG_ANY);
13515 *flagp |= HASWIDTH|SIMPLE;
13517 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13521 char * const oregcomp_parse = ++RExC_parse;
13522 ret = regclass(pRExC_state, flagp, depth+1,
13523 FALSE, /* means parse the whole char class */
13524 TRUE, /* allow multi-char folds */
13525 FALSE, /* don't silence non-portable warnings. */
13526 (bool) RExC_strict,
13527 TRUE, /* Allow an optimized regnode result */
13530 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13531 FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13534 if (*RExC_parse != ']') {
13535 RExC_parse = oregcomp_parse;
13536 vFAIL("Unmatched [");
13538 nextchar(pRExC_state);
13539 Set_Node_Length(REGNODE_p(ret), RExC_parse - oregcomp_parse + 1); /* MJD */
13543 nextchar(pRExC_state);
13544 ret = reg(pRExC_state, 2, &flags, depth+1);
13546 if (flags & TRYAGAIN) {
13547 if (RExC_parse >= RExC_end) {
13548 /* Make parent create an empty node if needed. */
13549 *flagp |= TRYAGAIN;
13554 RETURN_FAIL_ON_RESTART(flags, flagp);
13555 FAIL2("panic: reg returned failure to regatom, flags=%#" UVxf,
13558 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
13562 if (flags & TRYAGAIN) {
13563 *flagp |= TRYAGAIN;
13566 vFAIL("Internal urp");
13567 /* Supposed to be caught earlier. */
13573 vFAIL("Quantifier follows nothing");
13578 This switch handles escape sequences that resolve to some kind
13579 of special regop and not to literal text. Escape sequences that
13580 resolve to literal text are handled below in the switch marked
13583 Every entry in this switch *must* have a corresponding entry
13584 in the literal escape switch. However, the opposite is not
13585 required, as the default for this switch is to jump to the
13586 literal text handling code.
13589 switch ((U8)*RExC_parse) {
13590 /* Special Escapes */
13592 RExC_seen_zerolen++;
13593 /* Under wildcards, this is changed to match \n; should be
13594 * invisible to the user, as they have to compile under /m */
13595 if (RExC_pm_flags & PMf_WILDCARD) {
13596 ret = reg_node(pRExC_state, MBOL);
13599 ret = reg_node(pRExC_state, SBOL);
13600 /* SBOL is shared with /^/ so we set the flags so we can tell
13601 * /\A/ from /^/ in split. */
13602 FLAGS(REGNODE_p(ret)) = 1;
13603 *flagp |= SIMPLE; /* Wrong, but too late to fix for 5.32 */
13605 goto finish_meta_pat;
13607 if (RExC_pm_flags & PMf_WILDCARD) {
13609 /* diag_listed_as: Use of %s is not allowed in Unicode property
13610 wildcard subpatterns in regex; marked by <-- HERE in m/%s/
13612 vFAIL("Use of '\\G' is not allowed in Unicode property"
13613 " wildcard subpatterns");
13615 ret = reg_node(pRExC_state, GPOS);
13616 RExC_seen |= REG_GPOS_SEEN;
13618 goto finish_meta_pat;
13620 if (!RExC_in_lookbehind && !RExC_in_lookahead) {
13621 RExC_seen_zerolen++;
13622 ret = reg_node(pRExC_state, KEEPS);
13624 /* XXX:dmq : disabling in-place substitution seems to
13625 * be necessary here to avoid cases of memory corruption, as
13626 * with: C<$_="x" x 80; s/x\K/y/> -- rgs
13628 RExC_seen |= REG_LOOKBEHIND_SEEN;
13629 goto finish_meta_pat;
13632 ++RExC_parse; /* advance past the 'K' */
13633 vFAIL("\\K not permitted in lookahead/lookbehind");
13636 if (RExC_pm_flags & PMf_WILDCARD) {
13637 /* See comment under \A above */
13638 ret = reg_node(pRExC_state, MEOL);
13641 ret = reg_node(pRExC_state, SEOL);
13642 *flagp |= SIMPLE; /* Wrong, but too late to fix for 5.32 */
13644 RExC_seen_zerolen++; /* Do not optimize RE away */
13645 goto finish_meta_pat;
13647 if (RExC_pm_flags & PMf_WILDCARD) {
13648 /* See comment under \A above */
13649 ret = reg_node(pRExC_state, MEOL);
13652 ret = reg_node(pRExC_state, EOS);
13653 *flagp |= SIMPLE; /* Wrong, but too late to fix for 5.32 */
13655 RExC_seen_zerolen++; /* Do not optimize RE away */
13656 goto finish_meta_pat;
13658 vFAIL("\\C no longer supported");
13660 ret = reg_node(pRExC_state, CLUMP);
13661 *flagp |= HASWIDTH;
13662 goto finish_meta_pat;
13670 regex_charset charset = get_regex_charset(RExC_flags);
13672 RExC_seen_zerolen++;
13673 RExC_seen |= REG_LOOKBEHIND_SEEN;
13674 op = BOUND + charset;
13676 if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') {
13677 flags = TRADITIONAL_BOUND;
13678 if (op > BOUNDA) { /* /aa is same as /a */
13684 char name = *RExC_parse;
13685 char * endbrace = NULL;
13687 endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
13690 vFAIL2("Missing right brace on \\%c{}", name);
13692 /* XXX Need to decide whether to take spaces or not. Should be
13693 * consistent with \p{}, but that currently is SPACE, which
13694 * means vertical too, which seems wrong
13695 * while (isBLANK(*RExC_parse)) {
13698 if (endbrace == RExC_parse) {
13699 RExC_parse++; /* After the '}' */
13700 vFAIL2("Empty \\%c{}", name);
13702 length = endbrace - RExC_parse;
13703 /*while (isBLANK(*(RExC_parse + length - 1))) {
13706 switch (*RExC_parse) {
13709 && (memNEs(RExC_parse + 1, length - 1, "cb")))
13711 goto bad_bound_type;
13716 if (length != 2 || *(RExC_parse + 1) != 'b') {
13717 goto bad_bound_type;
13722 if (length != 2 || *(RExC_parse + 1) != 'b') {
13723 goto bad_bound_type;
13728 if (length != 2 || *(RExC_parse + 1) != 'b') {
13729 goto bad_bound_type;
13735 RExC_parse = endbrace;
13737 "'%" UTF8f "' is an unknown bound type",
13738 UTF8fARG(UTF, length, endbrace - length));
13739 NOT_REACHED; /*NOTREACHED*/
13741 RExC_parse = endbrace;
13742 REQUIRE_UNI_RULES(flagp, 0);
13747 else if (op >= BOUNDA) { /* /aa is same as /a */
13751 /* Don't have to worry about UTF-8, in this message because
13752 * to get here the contents of the \b must be ASCII */
13753 ckWARN4reg(RExC_parse + 1, /* Include the '}' in msg */
13754 "Using /u for '%.*s' instead of /%s",
13756 endbrace - length + 1,
13757 (charset == REGEX_ASCII_RESTRICTED_CHARSET)
13758 ? ASCII_RESTRICT_PAT_MODS
13759 : ASCII_MORE_RESTRICT_PAT_MODS);
13764 RExC_seen_d_op = TRUE;
13766 else if (op == BOUNDL) {
13767 RExC_contains_locale = 1;
13771 op += NBOUND - BOUND;
13774 ret = reg_node(pRExC_state, op);
13775 FLAGS(REGNODE_p(ret)) = flags;
13779 goto finish_meta_pat;
13783 ret = reg_node(pRExC_state, LNBREAK);
13784 *flagp |= HASWIDTH|SIMPLE;
13785 goto finish_meta_pat;
13799 /* These all have the same meaning inside [brackets], and it knows
13800 * how to do the best optimizations for them. So, pretend we found
13801 * these within brackets, and let it do the work */
13804 ret = regclass(pRExC_state, flagp, depth+1,
13805 TRUE, /* means just parse this element */
13806 FALSE, /* don't allow multi-char folds */
13807 FALSE, /* don't silence non-portable warnings. It
13808 would be a bug if these returned
13810 (bool) RExC_strict,
13811 TRUE, /* Allow an optimized regnode result */
13813 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13814 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
13815 * multi-char folds are allowed. */
13817 FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13820 RExC_parse--; /* regclass() leaves this one too far ahead */
13823 /* The escapes above that don't take a parameter can't be
13824 * followed by a '{'. But 'pX', 'p{foo}' and
13825 * correspondingly 'P' can be */
13826 if ( RExC_parse - parse_start == 1
13827 && UCHARAT(RExC_parse + 1) == '{'
13828 && UNLIKELY(! new_regcurly(RExC_parse + 1, RExC_end)))
13831 vFAIL("Unescaped left brace in regex is illegal here");
13833 Set_Node_Offset(REGNODE_p(ret), parse_start);
13834 Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1); /* MJD */
13835 nextchar(pRExC_state);
13838 /* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the
13839 * \N{...} evaluates to a sequence of more than one code points).
13840 * The function call below returns a regnode, which is our result.
13841 * The parameters cause it to fail if the \N{} evaluates to a
13842 * single code point; we handle those like any other literal. The
13843 * reason that the multicharacter case is handled here and not as
13844 * part of the EXACtish code is because of quantifiers. In
13845 * /\N{BLAH}+/, the '+' applies to the whole thing, and doing it
13846 * this way makes that Just Happen. dmq.
13847 * join_exact() will join this up with adjacent EXACTish nodes
13848 * later on, if appropriate. */
13850 if (grok_bslash_N(pRExC_state,
13851 &ret, /* Want a regnode returned */
13852 NULL, /* Fail if evaluates to a single code
13854 NULL, /* Don't need a count of how many code
13863 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13865 /* Here, evaluates to a single code point. Go get that */
13866 RExC_parse = parse_start;
13869 case 'k': /* Handle \k<NAME> and \k'NAME' */
13873 if ( RExC_parse >= RExC_end - 1
13874 || (( ch = RExC_parse[1]) != '<'
13879 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
13880 vFAIL2("Sequence %.2s... not terminated", parse_start);
13883 ret = handle_named_backref(pRExC_state,
13895 case '1': case '2': case '3': case '4':
13896 case '5': case '6': case '7': case '8': case '9':
13901 if (*RExC_parse == 'g') {
13905 if (*RExC_parse == '{') {
13909 if (*RExC_parse == '-') {
13913 if (hasbrace && !isDIGIT(*RExC_parse)) {
13914 if (isrel) RExC_parse--;
13916 goto parse_named_seq;
13919 if (RExC_parse >= RExC_end) {
13920 goto unterminated_g;
13922 num = S_backref_value(RExC_parse, RExC_end);
13924 vFAIL("Reference to invalid group 0");
13925 else if (num == I32_MAX) {
13926 if (isDIGIT(*RExC_parse))
13927 vFAIL("Reference to nonexistent group");
13930 vFAIL("Unterminated \\g... pattern");
13934 num = RExC_npar - num;
13936 vFAIL("Reference to nonexistent or unclosed group");
13940 num = S_backref_value(RExC_parse, RExC_end);
13941 /* bare \NNN might be backref or octal - if it is larger
13942 * than or equal RExC_npar then it is assumed to be an
13943 * octal escape. Note RExC_npar is +1 from the actual
13944 * number of parens. */
13945 /* Note we do NOT check if num == I32_MAX here, as that is
13946 * handled by the RExC_npar check */
13949 /* any numeric escape < 10 is always a backref */
13951 /* any numeric escape < RExC_npar is a backref */
13952 && num >= RExC_npar
13953 /* cannot be an octal escape if it starts with 8 */
13954 && *RExC_parse != '8'
13955 /* cannot be an octal escape if it starts with 9 */
13956 && *RExC_parse != '9'
13958 /* Probably not meant to be a backref, instead likely
13959 * to be an octal character escape, e.g. \35 or \777.
13960 * The above logic should make it obvious why using
13961 * octal escapes in patterns is problematic. - Yves */
13962 RExC_parse = parse_start;
13967 /* At this point RExC_parse points at a numeric escape like
13968 * \12 or \88 or something similar, which we should NOT treat
13969 * as an octal escape. It may or may not be a valid backref
13970 * escape. For instance \88888888 is unlikely to be a valid
13972 while (isDIGIT(*RExC_parse))
13975 if (*RExC_parse != '}')
13976 vFAIL("Unterminated \\g{...} pattern");
13979 if (num >= (I32)RExC_npar) {
13981 /* It might be a forward reference; we can't fail until we
13982 * know, by completing the parse to get all the groups, and
13983 * then reparsing */
13984 if (ALL_PARENS_COUNTED) {
13985 if (num >= RExC_total_parens) {
13986 vFAIL("Reference to nonexistent group");
13990 REQUIRE_PARENS_PASS;
13994 ret = reganode(pRExC_state,
13997 : (ASCII_FOLD_RESTRICTED)
13999 : (AT_LEAST_UNI_SEMANTICS)
14005 if (OP(REGNODE_p(ret)) == REFF) {
14006 RExC_seen_d_op = TRUE;
14008 *flagp |= HASWIDTH;
14010 /* override incorrect value set in reganode MJD */
14011 Set_Node_Offset(REGNODE_p(ret), parse_start);
14012 Set_Node_Cur_Length(REGNODE_p(ret), parse_start-1);
14013 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
14014 FALSE /* Don't force to /x */ );
14018 if (RExC_parse >= RExC_end)
14019 FAIL("Trailing \\");
14022 /* Do not generate "unrecognized" warnings here, we fall
14023 back into the quick-grab loop below */
14024 RExC_parse = parse_start;
14026 } /* end of switch on a \foo sequence */
14031 /* '#' comments should have been spaced over before this function was
14033 assert((RExC_flags & RXf_PMf_EXTENDED) == 0);
14035 if (RExC_flags & RXf_PMf_EXTENDED) {
14036 RExC_parse = reg_skipcomment( pRExC_state, RExC_parse );
14037 if (RExC_parse < RExC_end)
14047 /* Here, we have determined that the next thing is probably a
14048 * literal character. RExC_parse points to the first byte of its
14049 * definition. (It still may be an escape sequence that evaluates
14050 * to a single character) */
14055 char *s, *old_s = NULL, *old_old_s = NULL;
14057 U32 max_string_len = 255;
14059 /* We may have to reparse the node, artificially stopping filling
14060 * it early, based on info gleaned in the first parse. This
14061 * variable gives where we stop. Make it above the normal stopping
14062 * place first time through; otherwise it would stop too early */
14063 U32 upper_fill = max_string_len + 1;
14065 /* We start out as an EXACT node, even if under /i, until we find a
14066 * character which is in a fold. The algorithm now segregates into
14067 * separate nodes, characters that fold from those that don't under
14068 * /i. (This hopefully will create nodes that are fixed strings
14069 * even under /i, giving the optimizer something to grab on to.)
14070 * So, if a node has something in it and the next character is in
14071 * the opposite category, that node is closed up, and the function
14072 * returns. Then regatom is called again, and a new node is
14073 * created for the new category. */
14074 U8 node_type = EXACT;
14076 /* Assume the node will be fully used; the excess is given back at
14077 * the end. Under /i, we may need to temporarily add the fold of
14078 * an extra character or two at the end to check for splitting
14079 * multi-char folds, so allocate extra space for that. We can't
14080 * make any other length assumptions, as a byte input sequence
14081 * could shrink down. */
14082 Ptrdiff_t current_string_nodes = STR_SZ(max_string_len
14086 ? UTF8_MAXBYTES_CASE
14087 /* Max non-UTF-8 expansion is 2 */ : 2)));
14089 bool next_is_quantifier;
14090 char * oldp = NULL;
14092 /* We can convert EXACTF nodes to EXACTFU if they contain only
14093 * characters that match identically regardless of the target
14094 * string's UTF8ness. The reason to do this is that EXACTF is not
14095 * trie-able, EXACTFU is, and EXACTFU requires fewer operations at
14098 * Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they
14099 * contain only above-Latin1 characters (hence must be in UTF8),
14100 * which don't participate in folds with Latin1-range characters,
14101 * as the latter's folds aren't known until runtime. */
14102 bool maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC);
14104 /* Single-character EXACTish nodes are almost always SIMPLE. This
14105 * allows us to override this as encountered */
14106 U8 maybe_SIMPLE = SIMPLE;
14108 /* Does this node contain something that can't match unless the
14109 * target string is (also) in UTF-8 */
14110 bool requires_utf8_target = FALSE;
14112 /* The sequence 'ss' is problematic in non-UTF-8 patterns. */
14113 bool has_ss = FALSE;
14115 /* So is the MICRO SIGN */
14116 bool has_micro_sign = FALSE;
14118 /* Set when we fill up the current node and there is still more
14119 * text to process */
14122 /* Allocate an EXACT node. The node_type may change below to
14123 * another EXACTish node, but since the size of the node doesn't
14124 * change, it works */
14125 ret = regnode_guts(pRExC_state, node_type, current_string_nodes,
14127 FILL_NODE(ret, node_type);
14130 s = STRING(REGNODE_p(ret));
14141 maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC);
14142 maybe_SIMPLE = SIMPLE;
14143 requires_utf8_target = FALSE;
14145 has_micro_sign = FALSE;
14149 /* This breaks under rare circumstances. If folding, we do not
14150 * want to split a node at a character that is a non-final in a
14151 * multi-char fold, as an input string could just happen to want to
14152 * match across the node boundary. The code at the end of the loop
14153 * looks for this, and backs off until it finds not such a
14154 * character, but it is possible (though extremely, extremely
14155 * unlikely) for all characters in the node to be non-final fold
14156 * ones, in which case we just leave the node fully filled, and
14157 * hope that it doesn't match the string in just the wrong place */
14159 assert( ! UTF /* Is at the beginning of a character */
14160 || UTF8_IS_INVARIANT(UCHARAT(RExC_parse))
14161 || UTF8_IS_START(UCHARAT(RExC_parse)));
14163 overflowed = FALSE;
14165 /* Here, we have a literal character. Find the maximal string of
14166 * them in the input that we can fit into a single EXACTish node.
14167 * We quit at the first non-literal or when the node gets full, or
14168 * under /i the categorization of folding/non-folding character
14170 while (p < RExC_end && len < upper_fill) {
14172 /* In most cases each iteration adds one byte to the output.
14173 * The exceptions override this */
14174 Size_t added_len = 1;
14180 /* White space has already been ignored */
14181 assert( (RExC_flags & RXf_PMf_EXTENDED) == 0
14182 || ! is_PATWS_safe((p), RExC_end, UTF));
14185 const char* message;
14198 /* Literal Escapes Switch
14200 This switch is meant to handle escape sequences that
14201 resolve to a literal character.
14203 Every escape sequence that represents something
14204 else, like an assertion or a char class, is handled
14205 in the switch marked 'Special Escapes' above in this
14206 routine, but also has an entry here as anything that
14207 isn't explicitly mentioned here will be treated as
14208 an unescaped equivalent literal.
14211 switch ((U8)*++p) {
14213 /* These are all the special escapes. */
14214 case 'A': /* Start assertion */
14215 case 'b': case 'B': /* Word-boundary assertion*/
14216 case 'C': /* Single char !DANGEROUS! */
14217 case 'd': case 'D': /* digit class */
14218 case 'g': case 'G': /* generic-backref, pos assertion */
14219 case 'h': case 'H': /* HORIZWS */
14220 case 'k': case 'K': /* named backref, keep marker */
14221 case 'p': case 'P': /* Unicode property */
14222 case 'R': /* LNBREAK */
14223 case 's': case 'S': /* space class */
14224 case 'v': case 'V': /* VERTWS */
14225 case 'w': case 'W': /* word class */
14226 case 'X': /* eXtended Unicode "combining
14227 character sequence" */
14228 case 'z': case 'Z': /* End of line/string assertion */
14232 /* Anything after here is an escape that resolves to a
14233 literal. (Except digits, which may or may not)
14239 case 'N': /* Handle a single-code point named character. */
14240 RExC_parse = p + 1;
14241 if (! grok_bslash_N(pRExC_state,
14242 NULL, /* Fail if evaluates to
14243 anything other than a
14244 single code point */
14245 &ender, /* The returned single code
14247 NULL, /* Don't need a count of
14248 how many code points */
14253 if (*flagp & NEED_UTF8)
14254 FAIL("panic: grok_bslash_N set NEED_UTF8");
14255 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
14257 /* Here, it wasn't a single code point. Go close
14258 * up this EXACTish node. The switch() prior to
14259 * this switch handles the other cases */
14260 RExC_parse = p = oldp;
14264 RExC_parse = parse_start;
14266 /* The \N{} means the pattern, if previously /d,
14267 * becomes /u. That means it can't be an EXACTF node,
14268 * but an EXACTFU */
14269 if (node_type == EXACTF) {
14270 node_type = EXACTFU;
14272 /* If the node already contains something that
14273 * differs between EXACTF and EXACTFU, reparse it
14275 if (! maybe_exactfu) {
14296 ender = ESC_NATIVE;
14304 if (! grok_bslash_o(&p,
14309 (bool) RExC_strict,
14310 FALSE, /* No illegal cp's */
14313 RExC_parse = p; /* going to die anyway; point to
14314 exact spot of failure */
14318 if (message && TO_OUTPUT_WARNINGS(p)) {
14319 warn_non_literal_string(p, packed_warn, message);
14323 if (! grok_bslash_x(&p,
14328 (bool) RExC_strict,
14329 FALSE, /* No illegal cp's */
14332 RExC_parse = p; /* going to die anyway; point
14333 to exact spot of failure */
14337 if (message && TO_OUTPUT_WARNINGS(p)) {
14338 warn_non_literal_string(p, packed_warn, message);
14342 if (ender < 0x100) {
14343 if (RExC_recode_x_to_native) {
14344 ender = LATIN1_TO_NATIVE(ender);
14351 if (! grok_bslash_c(*p, &grok_c_char,
14352 &message, &packed_warn))
14354 /* going to die anyway; point to exact spot of
14356 RExC_parse = p + ((UTF)
14357 ? UTF8_SAFE_SKIP(p, RExC_end)
14362 ender = grok_c_char;
14364 if (message && TO_OUTPUT_WARNINGS(p)) {
14365 warn_non_literal_string(p, packed_warn, message);
14369 case '8': case '9': /* must be a backreference */
14371 /* we have an escape like \8 which cannot be an octal escape
14372 * so we exit the loop, and let the outer loop handle this
14373 * escape which may or may not be a legitimate backref. */
14375 case '1': case '2': case '3':case '4':
14376 case '5': case '6': case '7':
14377 /* When we parse backslash escapes there is ambiguity
14378 * between backreferences and octal escapes. Any escape
14379 * from \1 - \9 is a backreference, any multi-digit
14380 * escape which does not start with 0 and which when
14381 * evaluated as decimal could refer to an already
14382 * parsed capture buffer is a back reference. Anything
14385 * Note this implies that \118 could be interpreted as
14386 * 118 OR as "\11" . "8" depending on whether there
14387 * were 118 capture buffers defined already in the
14390 /* NOTE, RExC_npar is 1 more than the actual number of
14391 * parens we have seen so far, hence the "<" as opposed
14393 if ( !isDIGIT(p[1]) || S_backref_value(p, RExC_end) < RExC_npar)
14394 { /* Not to be treated as an octal constant, go
14402 I32 flags = PERL_SCAN_SILENT_ILLDIGIT
14403 | PERL_SCAN_NOTIFY_ILLDIGIT;
14405 ender = grok_oct(p, &numlen, &flags, NULL);
14407 if ( (flags & PERL_SCAN_NOTIFY_ILLDIGIT)
14408 && isDIGIT(*p) /* like \08, \178 */
14409 && ckWARN(WARN_REGEXP))
14411 reg_warn_non_literal_string(
14413 form_alien_digit_msg(8, numlen, p,
14414 RExC_end, UTF, FALSE));
14420 FAIL("Trailing \\");
14423 if (isALPHANUMERIC(*p)) {
14424 /* An alpha followed by '{' is going to fail next
14425 * iteration, so don't output this warning in that
14427 if (! isALPHA(*p) || *(p + 1) != '{') {
14428 ckWARN2reg(p + 1, "Unrecognized escape \\%.1s"
14429 " passed through", p);
14432 goto normal_default;
14433 } /* End of switch on '\' */
14436 /* Trying to gain new uses for '{' without breaking too
14437 * much existing code is hard. The solution currently
14439 * 1) If there is no ambiguity that a '{' should always
14440 * be taken literally, at the start of a construct, we
14442 * 2) If the literal '{' conflicts with our desired use
14443 * of it as a metacharacter, we die. The deprecation
14444 * cycles for this have come and gone.
14445 * 3) If there is ambiguity, we raise a simple warning.
14446 * This could happen, for example, if the user
14447 * intended it to introduce a quantifier, but slightly
14448 * misspelled the quantifier. Without this warning,
14449 * the quantifier would silently be taken as a literal
14450 * string of characters instead of a meta construct */
14451 if (len || (p > RExC_start && isALPHA_A(*(p - 1)))) {
14453 || ( p > parse_start + 1
14454 && isALPHA_A(*(p - 1))
14455 && *(p - 2) == '\\')
14456 || new_regcurly(p, RExC_end))
14458 RExC_parse = p + 1;
14459 vFAIL("Unescaped left brace in regex is "
14462 ckWARNreg(p + 1, "Unescaped left brace in regex is"
14463 " passed through");
14465 goto normal_default;
14468 if (p > RExC_parse && RExC_strict) {
14469 ckWARN2reg(p + 1, "Unescaped literal '%c'", *p);
14472 default: /* A literal character */
14474 if (! UTF8_IS_INVARIANT(*p) && UTF) {
14476 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
14477 &numlen, UTF8_ALLOW_DEFAULT);
14483 } /* End of switch on the literal */
14485 /* Here, have looked at the literal character, and <ender>
14486 * contains its ordinal; <p> points to the character after it.
14490 REQUIRE_UTF8(flagp);
14491 if ( UNICODE_IS_PERL_EXTENDED(ender)
14492 && TO_OUTPUT_WARNINGS(p))
14494 ckWARN2_non_literal_string(p,
14495 packWARN(WARN_PORTABLE),
14496 PL_extended_cp_format,
14501 /* We need to check if the next non-ignored thing is a
14502 * quantifier. Move <p> to after anything that should be
14503 * ignored, which, as a side effect, positions <p> for the next
14504 * loop iteration */
14505 skip_to_be_ignored_text(pRExC_state, &p,
14506 FALSE /* Don't force to /x */ );
14508 /* If the next thing is a quantifier, it applies to this
14509 * character only, which means that this character has to be in
14510 * its own node and can't just be appended to the string in an
14511 * existing node, so if there are already other characters in
14512 * the node, close the node with just them, and set up to do
14513 * this character again next time through, when it will be the
14514 * only thing in its new node */
14516 next_is_quantifier = LIKELY(p < RExC_end)
14517 && UNLIKELY(ISMULT2(p));
14519 if (next_is_quantifier && LIKELY(len)) {
14524 /* Ready to add 'ender' to the node */
14526 if (! FOLD) { /* The simple case, just append the literal */
14529 /* Don't output if it would overflow */
14530 if (UNLIKELY(len > max_string_len - ((UTF)
14531 ? UVCHR_SKIP(ender)
14538 if (UVCHR_IS_INVARIANT(ender) || ! UTF) {
14539 *(s++) = (char) ender;
14542 U8 * new_s = uvchr_to_utf8((U8*)s, ender);
14543 added_len = (char *) new_s - s;
14544 s = (char *) new_s;
14547 requires_utf8_target = TRUE;
14551 else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) {
14553 /* Here are folding under /l, and the code point is
14554 * problematic. If this is the first character in the
14555 * node, change the node type to folding. Otherwise, if
14556 * this is the first problematic character, close up the
14557 * existing node, so can start a new node with this one */
14559 node_type = EXACTFL;
14560 RExC_contains_locale = 1;
14562 else if (node_type == EXACT) {
14567 /* This problematic code point means we can't simplify
14569 maybe_exactfu = FALSE;
14571 /* Here, we are adding a problematic fold character.
14572 * "Problematic" in this context means that its fold isn't
14573 * known until runtime. (The non-problematic code points
14574 * are the above-Latin1 ones that fold to also all
14575 * above-Latin1. Their folds don't vary no matter what the
14576 * locale is.) But here we have characters whose fold
14577 * depends on the locale. We just add in the unfolded
14578 * character, and wait until runtime to fold it */
14579 goto not_fold_common;
14581 else /* regular fold; see if actually is in a fold */
14582 if ( (ender < 256 && ! IS_IN_SOME_FOLD_L1(ender))
14584 && ! _invlist_contains_cp(PL_in_some_fold, ender)))
14586 /* Here, folding, but the character isn't in a fold.
14588 * Start a new node if previous characters in the node were
14590 if (len && node_type != EXACT) {
14595 /* Here, continuing a node with non-folded characters. Add
14597 goto not_fold_common;
14599 else { /* Here, does participate in some fold */
14601 /* If this is the first character in the node, change its
14602 * type to folding. Otherwise, if this is the first
14603 * folding character in the node, close up the existing
14604 * node, so can start a new node with this one. */
14606 node_type = compute_EXACTish(pRExC_state);
14608 else if (node_type == EXACT) {
14613 if (UTF) { /* Alway use the folded value for UTF-8
14615 if (UVCHR_IS_INVARIANT(ender)) {
14616 if (UNLIKELY(len + 1 > max_string_len)) {
14621 *(s)++ = (U8) toFOLD(ender);
14624 UV folded = _to_uni_fold_flags(
14626 (U8 *) s, /* We have allocated extra space
14627 in 's' so can't run off the
14630 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
14631 ? FOLD_FLAGS_NOMIX_ASCII
14633 if (UNLIKELY(len + added_len > max_string_len)) {
14641 && LIKELY(folded != GREEK_SMALL_LETTER_MU))
14643 /* U+B5 folds to the MU, so its possible for a
14644 * non-UTF-8 target to match it */
14645 requires_utf8_target = TRUE;
14649 else { /* Here is non-UTF8. */
14651 /* The fold will be one or (rarely) two characters.
14652 * Check that there's room for at least a single one
14653 * before setting any flags, etc. Because otherwise an
14654 * overflowing character could cause a flag to be set
14655 * even though it doesn't end up in this node. (For
14656 * the two character fold, we check again, before
14657 * setting any flags) */
14658 if (UNLIKELY(len + 1 > max_string_len)) {
14663 #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
14664 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
14665 || UNICODE_DOT_DOT_VERSION > 0)
14667 /* On non-ancient Unicodes, check for the only possible
14668 * multi-char fold */
14669 if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) {
14671 /* This potential multi-char fold means the node
14672 * can't be simple (because it could match more
14673 * than a single char). And in some cases it will
14674 * match 'ss', so set that flag */
14678 /* It can't change to be an EXACTFU (unless already
14679 * is one). We fold it iff under /u rules. */
14680 if (node_type != EXACTFU) {
14681 maybe_exactfu = FALSE;
14684 if (UNLIKELY(len + 2 > max_string_len)) {
14693 goto done_with_this_char;
14696 else if ( UNLIKELY(isALPHA_FOLD_EQ(ender, 's'))
14698 && UNLIKELY(isALPHA_FOLD_EQ(*(s-1), 's')))
14700 /* Also, the sequence 'ss' is special when not
14701 * under /u. If the target string is UTF-8, it
14702 * should match SHARP S; otherwise it won't. So,
14703 * here we have to exclude the possibility of this
14704 * node moving to /u.*/
14706 maybe_exactfu = FALSE;
14709 /* Here, the fold will be a single character */
14711 if (UNLIKELY(ender == MICRO_SIGN)) {
14712 has_micro_sign = TRUE;
14714 else if (PL_fold[ender] != PL_fold_latin1[ender]) {
14716 /* If the character's fold differs between /d and
14717 * /u, this can't change to be an EXACTFU node */
14718 maybe_exactfu = FALSE;
14721 *(s++) = (DEPENDS_SEMANTICS)
14722 ? (char) toFOLD(ender)
14724 /* Under /u, the fold of any character in
14725 * the 0-255 range happens to be its
14726 * lowercase equivalent, except for LATIN
14727 * SMALL LETTER SHARP S, which was handled
14728 * above, and the MICRO SIGN, whose fold
14729 * requires UTF-8 to represent. */
14730 : (char) toLOWER_L1(ender);
14732 } /* End of adding current character to the node */
14734 done_with_this_char:
14738 if (next_is_quantifier) {
14740 /* Here, the next input is a quantifier, and to get here,
14741 * the current character is the only one in the node. */
14745 } /* End of loop through literal characters */
14747 /* Here we have either exhausted the input or run out of room in
14748 * the node. If the former, we are done. (If we encountered a
14749 * character that can't be in the node, transfer is made directly
14750 * to <loopdone>, and so we wouldn't have fallen off the end of the
14752 if (LIKELY(! overflowed)) {
14756 /* Here we have run out of room. We can grow plain EXACT and
14757 * LEXACT nodes. If the pattern is gigantic enough, though,
14758 * eventually we'll have to artificially chunk the pattern into
14759 * multiple nodes. */
14760 if (! LOC && (node_type == EXACT || node_type == LEXACT)) {
14761 Size_t overhead = 1 + regarglen[OP(REGNODE_p(ret))];
14762 Size_t overhead_expansion = 0;
14764 Size_t max_nodes_for_string;
14768 /* Here we couldn't fit the final character in the current
14769 * node, so it will have to be reparsed, no matter what else we
14773 /* If would have overflowed a regular EXACT node, switch
14774 * instead to an LEXACT. The code below is structured so that
14775 * the actual growing code is common to changing from an EXACT
14776 * or just increasing the LEXACT size. This means that we have
14777 * to save the string in the EXACT case before growing, and
14778 * then copy it afterwards to its new location */
14779 if (node_type == EXACT) {
14780 overhead_expansion = regarglen[LEXACT] - regarglen[EXACT];
14781 RExC_emit += overhead_expansion;
14782 Copy(s0, temp, len, char);
14785 /* Ready to grow. If it was a plain EXACT, the string was
14786 * saved, and the first few bytes of it overwritten by adding
14787 * an argument field. We assume, as we do elsewhere in this
14788 * file, that one byte of remaining input will translate into
14789 * one byte of output, and if that's too small, we grow again,
14790 * if too large the excess memory is freed at the end */
14792 max_nodes_for_string = U16_MAX - overhead - overhead_expansion;
14793 achievable = MIN(max_nodes_for_string,
14794 current_string_nodes + STR_SZ(RExC_end - p));
14795 delta = achievable - current_string_nodes;
14797 /* If there is just no more room, go finish up this chunk of
14803 change_engine_size(pRExC_state, delta + overhead_expansion);
14804 current_string_nodes += delta;
14806 = sizeof(struct regnode) * current_string_nodes;
14807 upper_fill = max_string_len + 1;
14809 /* If the length was small, we know this was originally an
14810 * EXACT node now converted to LEXACT, and the string has to be
14811 * restored. Otherwise the string was untouched. 260 is just
14812 * a number safely above 255 so don't have to worry about
14813 * getting it precise */
14815 node_type = LEXACT;
14816 FILL_NODE(ret, node_type);
14817 s0 = STRING(REGNODE_p(ret));
14818 Copy(temp, s0, len, char);
14822 goto continue_parse;
14825 bool splittable = FALSE;
14826 bool backed_up = FALSE;
14827 char * e; /* should this be U8? */
14828 char * s_start; /* should this be U8? */
14830 /* Here is /i. Running out of room creates a problem if we are
14831 * folding, and the split happens in the middle of a
14832 * multi-character fold, as a match that should have occurred,
14833 * won't, due to the way nodes are matched, and our artificial
14834 * boundary. So back off until we aren't splitting such a
14835 * fold. If there is no such place to back off to, we end up
14836 * taking the entire node as-is. This can happen if the node
14837 * consists entirely of 'f' or entirely of 's' characters (or
14838 * things that fold to them) as 'ff' and 'ss' are
14839 * multi-character folds.
14841 * The Unicode standard says that multi character folds consist
14842 * of either two or three characters. That means we would be
14843 * splitting one if the final character in the node is at the
14844 * beginning of either type, or is the second of a three
14848 * ender is the code point of the character that won't fit
14850 * s points to just beyond the final byte in the node.
14851 * It's where we would place ender if there were
14852 * room, and where in fact we do place ender's fold
14853 * in the code below, as we've over-allocated space
14854 * for s0 (hence s) to allow for this
14855 * e starts at 's' and advances as we append things.
14856 * old_s is the same as 's'. (If ender had fit, 's' would
14857 * have been advanced to beyond it).
14858 * old_old_s points to the beginning byte of the final
14859 * character in the node
14860 * p points to the beginning byte in the input of the
14861 * character beyond 'ender'.
14862 * oldp points to the beginning byte in the input of
14865 * In the case of /il, we haven't folded anything that could be
14866 * affected by the locale. That means only above-Latin1
14867 * characters that fold to other above-latin1 characters get
14868 * folded at compile time. To check where a good place to
14869 * split nodes is, everything in it will have to be folded.
14870 * The boolean 'maybe_exactfu' keeps track in /il if there are
14871 * any unfolded characters in the node. */
14872 bool need_to_fold_loc = LOC && ! maybe_exactfu;
14874 /* If we do need to fold the node, we need a place to store the
14875 * folded copy, and a way to map back to the unfolded original
14877 char * locfold_buf = NULL;
14878 Size_t * loc_correspondence = NULL;
14880 if (! need_to_fold_loc) { /* The normal case. Just
14881 initialize to the actual node */
14884 s = old_old_s; /* Point to the beginning of the final char
14885 that fits in the node */
14889 /* Here, we have filled a /il node, and there are unfolded
14890 * characters in it. If the runtime locale turns out to be
14891 * UTF-8, there are possible multi-character folds, just
14892 * like when not under /l. The node hence can't terminate
14893 * in the middle of such a fold. To determine this, we
14894 * have to create a folded copy of this node. That means
14895 * reparsing the node, folding everything assuming a UTF-8
14896 * locale. (If at runtime it isn't such a locale, the
14897 * actions here wouldn't have been necessary, but we have
14898 * to assume the worst case.) If we find we need to back
14899 * off the folded string, we do so, and then map that
14900 * position back to the original unfolded node, which then
14901 * gets output, truncated at that spot */
14903 char * redo_p = RExC_parse;
14907 /* Allow enough space assuming a single byte input folds to
14908 * a single byte output, plus assume that the two unparsed
14909 * characters (that we may need) fold to the largest number
14910 * of bytes possible, plus extra for one more worst case
14911 * scenario. In the loop below, if we start eating into
14912 * that final spare space, we enlarge this initial space */
14913 Size_t size = max_string_len + (3 * UTF8_MAXBYTES_CASE) + 1;
14915 Newxz(locfold_buf, size, char);
14916 Newxz(loc_correspondence, size, Size_t);
14918 /* Redo this node's parse, folding into 'locfold_buf' */
14919 redo_p = RExC_parse;
14920 old_redo_e = redo_e = locfold_buf;
14921 while (redo_p <= oldp) {
14923 old_redo_e = redo_e;
14924 loc_correspondence[redo_e - locfold_buf]
14925 = redo_p - RExC_parse;
14930 (void) _to_utf8_fold_flags((U8 *) redo_p,
14935 redo_e += added_len;
14936 redo_p += UTF8SKIP(redo_p);
14940 /* Note that if this code is run on some ancient
14941 * Unicode versions, SHARP S doesn't fold to 'ss',
14942 * but rather than clutter the code with #ifdef's,
14943 * as is done above, we ignore that possibility.
14944 * This is ok because this code doesn't affect what
14945 * gets matched, but merely where the node gets
14947 if (UCHARAT(redo_p) != LATIN_SMALL_LETTER_SHARP_S) {
14948 *redo_e++ = toLOWER_L1(UCHARAT(redo_p));
14958 /* If we're getting so close to the end that a
14959 * worst-case fold in the next character would cause us
14960 * to overflow, increase, assuming one byte output byte
14961 * per one byte input one, plus room for another worst
14963 if ( redo_p <= oldp
14964 && redo_e > locfold_buf + size
14965 - (UTF8_MAXBYTES_CASE + 1))
14967 Size_t new_size = size
14969 + UTF8_MAXBYTES_CASE + 1;
14970 Ptrdiff_t e_offset = redo_e - locfold_buf;
14972 Renew(locfold_buf, new_size, char);
14973 Renew(loc_correspondence, new_size, Size_t);
14976 redo_e = locfold_buf + e_offset;
14980 /* Set so that things are in terms of the folded, temporary
14983 s_start = locfold_buf;
14988 /* Here, we have 's', 's_start' and 'e' set up to point to the
14989 * input that goes into the node, folded.
14991 * If the final character of the node and the fold of ender
14992 * form the first two characters of a three character fold, we
14993 * need to peek ahead at the next (unparsed) character in the
14994 * input to determine if the three actually do form such a
14995 * fold. Just looking at that character is not generally
14996 * sufficient, as it could be, for example, an escape sequence
14997 * that evaluates to something else, and it needs to be folded.
14999 * khw originally thought to just go through the parse loop one
15000 * extra time, but that doesn't work easily as that iteration
15001 * could cause things to think that the parse is over and to
15002 * goto loopdone. The character could be a '$' for example, or
15003 * the character beyond could be a quantifier, and other
15004 * glitches as well.
15006 * The solution used here for peeking ahead is to look at that
15007 * next character. If it isn't ASCII punctuation, then it will
15008 * be something that continues in an EXACTish node if there
15009 * were space. We append the fold of it to s, having reserved
15010 * enough room in s0 for the purpose. If we can't reasonably
15011 * peek ahead, we instead assume the worst case: that it is
15012 * something that would form the completion of a multi-char
15015 * If we can't split between s and ender, we work backwards
15016 * character-by-character down to s0. At each current point
15017 * see if we are at the beginning of a multi-char fold. If so,
15018 * that means we would be splitting the fold across nodes, and
15019 * so we back up one and try again.
15021 * If we're not at the beginning, we still could be at the
15022 * final two characters of a (rare) three character fold. We
15023 * check if the sequence starting at the character before the
15024 * current position (and including the current and next
15025 * characters) is a three character fold. If not, the node can
15026 * be split here. If it is, we have to backup two characters
15029 * Otherwise, the node can be split at the current position.
15031 * The same logic is used for UTF-8 patterns and not */
15035 /* Append the fold of ender */
15036 (void) _to_uni_fold_flags(
15040 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
15041 ? FOLD_FLAGS_NOMIX_ASCII
15045 /* 's' and the character folded to by ender may be the
15046 * first two of a three-character fold, in which case the
15047 * node should not be split here. That may mean examining
15048 * the so-far unparsed character starting at 'p'. But if
15049 * ender folded to more than one character, we already have
15050 * three characters to look at. Also, we first check if
15051 * the sequence consisting of s and the next character form
15052 * the first two of some three character fold. If not,
15053 * there's no need to peek ahead. */
15054 if ( added_len <= UTF8SKIP(e - added_len)
15055 && UNLIKELY(is_THREE_CHAR_FOLD_HEAD_utf8_safe(s, e)))
15057 /* Here, the two do form the beginning of a potential
15058 * three character fold. The unexamined character may
15059 * or may not complete it. Peek at it. It might be
15060 * something that ends the node or an escape sequence,
15061 * in which case we don't know without a lot of work
15062 * what it evaluates to, so we have to assume the worst
15063 * case: that it does complete the fold, and so we
15064 * can't split here. All such instances will have
15065 * that character be an ASCII punctuation character,
15066 * like a backslash. So, for that case, backup one and
15067 * drop down to try at that position */
15069 s = (char *) utf8_hop_back((U8 *) s, -1,
15074 /* Here, since it's not punctuation, it must be a
15075 * real character, and we can append its fold to
15076 * 'e' (having deliberately reserved enough space
15077 * for this eventuality) and drop down to check if
15078 * the three actually do form a folded sequence */
15079 (void) _to_utf8_fold_flags(
15080 (U8 *) p, (U8 *) RExC_end,
15083 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
15084 ? FOLD_FLAGS_NOMIX_ASCII
15090 /* Here, we either have three characters available in
15091 * sequence starting at 's', or we have two characters and
15092 * know that the following one can't possibly be part of a
15093 * three character fold. We go through the node backwards
15094 * until we find a place where we can split it without
15095 * breaking apart a multi-character fold. At any given
15096 * point we have to worry about if such a fold begins at
15097 * the current 's', and also if a three-character fold
15098 * begins at s-1, (containing s and s+1). Splitting in
15099 * either case would break apart a fold */
15101 char *prev_s = (char *) utf8_hop_back((U8 *) s, -1,
15104 /* If is a multi-char fold, can't split here. Backup
15105 * one char and try again */
15106 if (UNLIKELY(is_MULTI_CHAR_FOLD_utf8_safe(s, e))) {
15112 /* If the two characters beginning at 's' are part of a
15113 * three character fold starting at the character
15114 * before s, we can't split either before or after s.
15115 * Backup two chars and try again */
15116 if ( LIKELY(s > s_start)
15117 && UNLIKELY(is_THREE_CHAR_FOLD_utf8_safe(prev_s, e)))
15120 s = (char *) utf8_hop_back((U8 *) s, -1, (U8 *) s_start);
15125 /* Here there's no multi-char fold between s and the
15126 * next character following it. We can split */
15130 } while (s > s_start); /* End of loops backing up through the node */
15132 /* Here we either couldn't find a place to split the node,
15133 * or else we broke out of the loop setting 'splittable' to
15134 * true. In the latter case, the place to split is between
15135 * the first and second characters in the sequence starting
15141 else { /* Pattern not UTF-8 */
15142 if ( ender != LATIN_SMALL_LETTER_SHARP_S
15143 || ASCII_FOLD_RESTRICTED)
15145 assert( toLOWER_L1(ender) < 256 );
15146 *e++ = (char)(toLOWER_L1(ender)); /* should e and the cast be U8? */
15154 && UNLIKELY(is_THREE_CHAR_FOLD_HEAD_latin1_safe(s, e)))
15161 if ( UCHARAT(p) != LATIN_SMALL_LETTER_SHARP_S
15162 || ASCII_FOLD_RESTRICTED)
15164 assert( toLOWER_L1(ender) < 256 );
15165 *e++ = (char)(toLOWER_L1(ender)); /* should e and the cast be U8? */
15175 if (UNLIKELY(is_MULTI_CHAR_FOLD_latin1_safe(s, e))) {
15181 if ( LIKELY(s > s_start)
15182 && UNLIKELY(is_THREE_CHAR_FOLD_latin1_safe(s - 1, e)))
15192 } while (s > s_start);
15199 /* Here, we are done backing up. If we didn't backup at all
15200 * (the likely case), just proceed */
15203 /* If we did find a place to split, reparse the entire node
15204 * stopping where we have calculated. */
15207 /* If we created a temporary folded string under /l, we
15208 * have to map that back to the original */
15209 if (need_to_fold_loc) {
15210 upper_fill = loc_correspondence[s - s_start];
15211 if (upper_fill == 0) {
15212 FAIL2("panic: loc_correspondence[%d] is 0",
15213 (int) (s - s_start));
15217 upper_fill = s - s0;
15222 /* Here the node consists entirely of non-final multi-char
15223 * folds. (Likely it is all 'f's or all 's's.) There's no
15224 * decent place to split it, so give up and just take the
15229 if (need_to_fold_loc) {
15230 Safefree(locfold_buf);
15231 Safefree(loc_correspondence);
15233 } /* End of verifying node ends with an appropriate char */
15235 /* We need to start the next node at the character that didn't fit
15239 loopdone: /* Jumped to when encounters something that shouldn't be
15242 /* Free up any over-allocated space; cast is to silence bogus
15243 * warning in MS VC */
15244 change_engine_size(pRExC_state,
15245 - (Ptrdiff_t) (current_string_nodes - STR_SZ(len)));
15247 /* I (khw) don't know if you can get here with zero length, but the
15248 * old code handled this situation by creating a zero-length EXACT
15249 * node. Might as well be NOTHING instead */
15251 OP(REGNODE_p(ret)) = NOTHING;
15255 /* If the node type is EXACT here, check to see if it
15256 * should be EXACTL, or EXACT_REQ8. */
15257 if (node_type == EXACT) {
15259 node_type = EXACTL;
15261 else if (requires_utf8_target) {
15262 node_type = EXACT_REQ8;
15265 else if (node_type == LEXACT) {
15266 if (requires_utf8_target) {
15267 node_type = LEXACT_REQ8;
15271 if ( UNLIKELY(has_micro_sign || has_ss)
15272 && (node_type == EXACTFU || ( node_type == EXACTF
15273 && maybe_exactfu)))
15274 { /* These two conditions are problematic in non-UTF-8
15277 node_type = EXACTFUP;
15279 else if (node_type == EXACTFL) {
15281 /* 'maybe_exactfu' is deliberately set above to
15282 * indicate this node type, where all code points in it
15284 if (maybe_exactfu) {
15285 node_type = EXACTFLU8;
15288 _invlist_contains_cp(PL_HasMultiCharFold, ender)))
15290 /* A character that folds to more than one will
15291 * match multiple characters, so can't be SIMPLE.
15292 * We don't have to worry about this with EXACTFLU8
15293 * nodes just above, as they have already been
15294 * folded (since the fold doesn't vary at run
15295 * time). Here, if the final character in the node
15296 * folds to multiple, it can't be simple. (This
15297 * only has an effect if the node has only a single
15298 * character, hence the final one, as elsewhere we
15299 * turn off simple for nodes whose length > 1 */
15303 else if (node_type == EXACTF) { /* Means is /di */
15305 /* This intermediate variable is needed solely because
15306 * the asserts in the macro where used exceed Win32's
15307 * literal string capacity */
15308 char first_char = * STRING(REGNODE_p(ret));
15310 /* If 'maybe_exactfu' is clear, then we need to stay
15311 * /di. If it is set, it means there are no code
15312 * points that match differently depending on UTF8ness
15313 * of the target string, so it can become an EXACTFU
15315 if (! maybe_exactfu) {
15316 RExC_seen_d_op = TRUE;
15318 else if ( isALPHA_FOLD_EQ(first_char, 's')
15319 || isALPHA_FOLD_EQ(ender, 's'))
15321 /* But, if the node begins or ends in an 's' we
15322 * have to defer changing it into an EXACTFU, as
15323 * the node could later get joined with another one
15324 * that ends or begins with 's' creating an 'ss'
15325 * sequence which would then wrongly match the
15326 * sharp s without the target being UTF-8. We
15327 * create a special node that we resolve later when
15328 * we join nodes together */
15330 node_type = EXACTFU_S_EDGE;
15333 node_type = EXACTFU;
15337 if (requires_utf8_target && node_type == EXACTFU) {
15338 node_type = EXACTFU_REQ8;
15342 OP(REGNODE_p(ret)) = node_type;
15343 setSTR_LEN(REGNODE_p(ret), len);
15344 RExC_emit += STR_SZ(len);
15346 /* If the node isn't a single character, it can't be SIMPLE */
15347 if (len > (Size_t) ((UTF) ? UTF8SKIP(STRING(REGNODE_p(ret))) : 1)) {
15351 *flagp |= HASWIDTH | maybe_SIMPLE;
15354 Set_Node_Length(REGNODE_p(ret), p - parse_start - 1);
15358 /* len is STRLEN which is unsigned, need to copy to signed */
15361 vFAIL("Internal disaster");
15364 } /* End of label 'defchar:' */
15366 } /* End of giant switch on input character */
15368 /* Position parse to next real character */
15369 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
15370 FALSE /* Don't force to /x */ );
15371 if ( *RExC_parse == '{'
15372 && OP(REGNODE_p(ret)) != SBOL && ! regcurly(RExC_parse))
15374 if (RExC_strict || new_regcurly(RExC_parse, RExC_end)) {
15376 vFAIL("Unescaped left brace in regex is illegal here");
15378 ckWARNreg(RExC_parse + 1, "Unescaped left brace in regex is"
15379 " passed through");
15387 S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr)
15389 /* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'. It
15390 * sets up the bitmap and any flags, removing those code points from the
15391 * inversion list, setting it to NULL should it become completely empty */
15395 PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST;
15396 assert(PL_regkind[OP(node)] == ANYOF);
15398 /* There is no bitmap for this node type */
15399 if (inRANGE(OP(node), ANYOFH, ANYOFRb)) {
15403 ANYOF_BITMAP_ZERO(node);
15404 if (*invlist_ptr) {
15406 /* This gets set if we actually need to modify things */
15407 bool change_invlist = FALSE;
15411 /* Start looking through *invlist_ptr */
15412 invlist_iterinit(*invlist_ptr);
15413 while (invlist_iternext(*invlist_ptr, &start, &end)) {
15417 if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) {
15418 ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP;
15421 /* Quit if are above what we should change */
15422 if (start >= NUM_ANYOF_CODE_POINTS) {
15426 change_invlist = TRUE;
15428 /* Set all the bits in the range, up to the max that we are doing */
15429 high = (end < NUM_ANYOF_CODE_POINTS - 1)
15431 : NUM_ANYOF_CODE_POINTS - 1;
15432 for (i = start; i <= (int) high; i++) {
15433 if (! ANYOF_BITMAP_TEST(node, i)) {
15434 ANYOF_BITMAP_SET(node, i);
15438 invlist_iterfinish(*invlist_ptr);
15440 /* Done with loop; remove any code points that are in the bitmap from
15441 * *invlist_ptr; similarly for code points above the bitmap if we have
15442 * a flag to match all of them anyways */
15443 if (change_invlist) {
15444 _invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr);
15446 if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
15447 _invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr);
15450 /* If have completely emptied it, remove it completely */
15451 if (_invlist_len(*invlist_ptr) == 0) {
15452 SvREFCNT_dec_NN(*invlist_ptr);
15453 *invlist_ptr = NULL;
15458 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
15459 Character classes ([:foo:]) can also be negated ([:^foo:]).
15460 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
15461 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
15462 but trigger failures because they are currently unimplemented. */
15464 #define POSIXCC_DONE(c) ((c) == ':')
15465 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
15466 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
15467 #define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';')
15469 #define WARNING_PREFIX "Assuming NOT a POSIX class since "
15470 #define NO_BLANKS_POSIX_WARNING "no blanks are allowed in one"
15471 #define SEMI_COLON_POSIX_WARNING "a semi-colon was found instead of a colon"
15473 #define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1)
15475 /* 'posix_warnings' and 'warn_text' are names of variables in the following
15477 #define ADD_POSIX_WARNING(p, text) STMT_START { \
15478 if (posix_warnings) { \
15479 if (! RExC_warn_text ) RExC_warn_text = \
15480 (AV *) sv_2mortal((SV *) newAV()); \
15481 av_push(RExC_warn_text, Perl_newSVpvf(aTHX_ \
15485 REPORT_LOCATION_ARGS(p))); \
15488 #define CLEAR_POSIX_WARNINGS() \
15490 if (posix_warnings && RExC_warn_text) \
15491 av_clear(RExC_warn_text); \
15494 #define CLEAR_POSIX_WARNINGS_AND_RETURN(ret) \
15496 CLEAR_POSIX_WARNINGS(); \
15501 S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state,
15503 const char * const s, /* Where the putative posix class begins.
15504 Normally, this is one past the '['. This
15505 parameter exists so it can be somewhere
15506 besides RExC_parse. */
15507 char ** updated_parse_ptr, /* Where to set the updated parse pointer, or
15509 AV ** posix_warnings, /* Where to place any generated warnings, or
15511 const bool check_only /* Don't die if error */
15514 /* This parses what the caller thinks may be one of the three POSIX
15516 * 1) a character class, like [:blank:]
15517 * 2) a collating symbol, like [. .]
15518 * 3) an equivalence class, like [= =]
15519 * In the latter two cases, it croaks if it finds a syntactically legal
15520 * one, as these are not handled by Perl.
15522 * The main purpose is to look for a POSIX character class. It returns:
15523 * a) the class number
15524 * if it is a completely syntactically and semantically legal class.
15525 * 'updated_parse_ptr', if not NULL, is set to point to just after the
15526 * closing ']' of the class
15527 * b) OOB_NAMEDCLASS
15528 * if it appears that one of the three POSIX constructs was meant, but
15529 * its specification was somehow defective. 'updated_parse_ptr', if
15530 * not NULL, is set to point to the character just after the end
15531 * character of the class. See below for handling of warnings.
15532 * c) NOT_MEANT_TO_BE_A_POSIX_CLASS
15533 * if it doesn't appear that a POSIX construct was intended.
15534 * 'updated_parse_ptr' is not changed. No warnings nor errors are
15537 * In b) there may be errors or warnings generated. If 'check_only' is
15538 * TRUE, then any errors are discarded. Warnings are returned to the
15539 * caller via an AV* created into '*posix_warnings' if it is not NULL. If
15540 * instead it is NULL, warnings are suppressed.
15542 * The reason for this function, and its complexity is that a bracketed
15543 * character class can contain just about anything. But it's easy to
15544 * mistype the very specific posix class syntax but yielding a valid
15545 * regular bracketed class, so it silently gets compiled into something
15546 * quite unintended.
15548 * The solution adopted here maintains backward compatibility except that
15549 * it adds a warning if it looks like a posix class was intended but
15550 * improperly specified. The warning is not raised unless what is input
15551 * very closely resembles one of the 14 legal posix classes. To do this,
15552 * it uses fuzzy parsing. It calculates how many single-character edits it
15553 * would take to transform what was input into a legal posix class. Only
15554 * if that number is quite small does it think that the intention was a
15555 * posix class. Obviously these are heuristics, and there will be cases
15556 * where it errs on one side or another, and they can be tweaked as
15557 * experience informs.
15559 * The syntax for a legal posix class is:
15561 * qr/(?xa: \[ : \^? [[:lower:]]{4,6} : \] )/
15563 * What this routine considers syntactically to be an intended posix class
15564 * is this (the comments indicate some restrictions that the pattern
15567 * qr/(?x: \[? # The left bracket, possibly
15569 * \h* # possibly followed by blanks
15570 * (?: \^ \h* )? # possibly a misplaced caret
15571 * [:;]? # The opening class character,
15572 * # possibly omitted. A typo
15573 * # semi-colon can also be used.
15575 * \^? # possibly a correctly placed
15576 * # caret, but not if there was also
15577 * # a misplaced one
15579 * .{3,15} # The class name. If there are
15580 * # deviations from the legal syntax,
15581 * # its edit distance must be close
15582 * # to a real class name in order
15583 * # for it to be considered to be
15584 * # an intended posix class.
15586 * [[:punct:]]? # The closing class character,
15587 * # possibly omitted. If not a colon
15588 * # nor semi colon, the class name
15589 * # must be even closer to a valid
15592 * \]? # The right bracket, possibly
15596 * In the above, \h must be ASCII-only.
15598 * These are heuristics, and can be tweaked as field experience dictates.
15599 * There will be cases when someone didn't intend to specify a posix class
15600 * that this warns as being so. The goal is to minimize these, while
15601 * maximizing the catching of things intended to be a posix class that
15602 * aren't parsed as such.
15606 const char * const e = RExC_end;
15607 unsigned complement = 0; /* If to complement the class */
15608 bool found_problem = FALSE; /* Assume OK until proven otherwise */
15609 bool has_opening_bracket = FALSE;
15610 bool has_opening_colon = FALSE;
15611 int class_number = OOB_NAMEDCLASS; /* Out-of-bounds until find
15613 const char * possible_end = NULL; /* used for a 2nd parse pass */
15614 const char* name_start; /* ptr to class name first char */
15616 /* If the number of single-character typos the input name is away from a
15617 * legal name is no more than this number, it is considered to have meant
15618 * the legal name */
15619 int max_distance = 2;
15621 /* to store the name. The size determines the maximum length before we
15622 * decide that no posix class was intended. Should be at least
15623 * sizeof("alphanumeric") */
15625 STATIC_ASSERT_DECL(C_ARRAY_LENGTH(input_text) >= sizeof "alphanumeric");
15627 PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX;
15629 CLEAR_POSIX_WARNINGS();
15632 return NOT_MEANT_TO_BE_A_POSIX_CLASS;
15635 if (*(p - 1) != '[') {
15636 ADD_POSIX_WARNING(p, "it doesn't start with a '['");
15637 found_problem = TRUE;
15640 has_opening_bracket = TRUE;
15643 /* They could be confused and think you can put spaces between the
15646 found_problem = TRUE;
15650 } while (p < e && isBLANK(*p));
15652 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15655 /* For [. .] and [= =]. These are quite different internally from [: :],
15656 * so they are handled separately. */
15657 if (POSIXCC_NOTYET(*p) && p < e - 3) /* 1 for the close, and 1 for the ']'
15658 and 1 for at least one char in it
15661 const char open_char = *p;
15662 const char * temp_ptr = p + 1;
15664 /* These two constructs are not handled by perl, and if we find a
15665 * syntactically valid one, we croak. khw, who wrote this code, finds
15666 * this explanation of them very unclear:
15667 * http://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html
15668 * And searching the rest of the internet wasn't very helpful either.
15669 * It looks like just about any byte can be in these constructs,
15670 * depending on the locale. But unless the pattern is being compiled
15671 * under /l, which is very rare, Perl runs under the C or POSIX locale.
15672 * In that case, it looks like [= =] isn't allowed at all, and that
15673 * [. .] could be any single code point, but for longer strings the
15674 * constituent characters would have to be the ASCII alphabetics plus
15675 * the minus-hyphen. Any sensible locale definition would limit itself
15676 * to these. And any portable one definitely should. Trying to parse
15677 * the general case is a nightmare (see [perl #127604]). So, this code
15678 * looks only for interiors of these constructs that match:
15680 * Using \w relaxes the apparent rules a little, without adding much
15681 * danger of mistaking something else for one of these constructs.
15683 * [. .] in some implementations described on the internet is usable to
15684 * escape a character that otherwise is special in bracketed character
15685 * classes. For example [.].] means a literal right bracket instead of
15686 * the ending of the class
15688 * [= =] can legitimately contain a [. .] construct, but we don't
15689 * handle this case, as that [. .] construct will later get parsed
15690 * itself and croak then. And [= =] is checked for even when not under
15691 * /l, as Perl has long done so.
15693 * The code below relies on there being a trailing NUL, so it doesn't
15694 * have to keep checking if the parse ptr < e.
15696 if (temp_ptr[1] == open_char) {
15699 else while ( temp_ptr < e
15700 && (isWORDCHAR(*temp_ptr) || *temp_ptr == '-'))
15705 if (*temp_ptr == open_char) {
15707 if (*temp_ptr == ']') {
15709 if (! found_problem && ! check_only) {
15710 RExC_parse = (char *) temp_ptr;
15711 vFAIL3("POSIX syntax [%c %c] is reserved for future "
15712 "extensions", open_char, open_char);
15715 /* Here, the syntax wasn't completely valid, or else the call
15716 * is to check-only */
15717 if (updated_parse_ptr) {
15718 *updated_parse_ptr = (char *) temp_ptr;
15721 CLEAR_POSIX_WARNINGS_AND_RETURN(OOB_NAMEDCLASS);
15725 /* If we find something that started out to look like one of these
15726 * constructs, but isn't, we continue below so that it can be checked
15727 * for being a class name with a typo of '.' or '=' instead of a colon.
15731 /* Here, we think there is a possibility that a [: :] class was meant, and
15732 * we have the first real character. It could be they think the '^' comes
15735 found_problem = TRUE;
15736 ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon");
15741 found_problem = TRUE;
15745 } while (p < e && isBLANK(*p));
15747 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15751 /* But the first character should be a colon, which they could have easily
15752 * mistyped on a qwerty keyboard as a semi-colon (and which may be hard to
15753 * distinguish from a colon, so treat that as a colon). */
15756 has_opening_colon = TRUE;
15758 else if (*p == ';') {
15759 found_problem = TRUE;
15761 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15762 has_opening_colon = TRUE;
15765 found_problem = TRUE;
15766 ADD_POSIX_WARNING(p, "there must be a starting ':'");
15768 /* Consider an initial punctuation (not one of the recognized ones) to
15769 * be a left terminator */
15770 if (*p != '^' && *p != ']' && isPUNCT(*p)) {
15775 /* They may think that you can put spaces between the components */
15777 found_problem = TRUE;
15781 } while (p < e && isBLANK(*p));
15783 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15788 /* We consider something like [^:^alnum:]] to not have been intended to
15789 * be a posix class, but XXX maybe we should */
15791 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15798 /* Again, they may think that you can put spaces between the components */
15800 found_problem = TRUE;
15804 } while (p < e && isBLANK(*p));
15806 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15811 /* XXX This ']' may be a typo, and something else was meant. But
15812 * treating it as such creates enough complications, that that
15813 * possibility isn't currently considered here. So we assume that the
15814 * ']' is what is intended, and if we've already found an initial '[',
15815 * this leaves this construct looking like [:] or [:^], which almost
15816 * certainly weren't intended to be posix classes */
15817 if (has_opening_bracket) {
15818 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15821 /* But this function can be called when we parse the colon for
15822 * something like qr/[alpha:]]/, so we back up to look for the
15827 found_problem = TRUE;
15828 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15830 else if (*p != ':') {
15832 /* XXX We are currently very restrictive here, so this code doesn't
15833 * consider the possibility that, say, /[alpha.]]/ was intended to
15834 * be a posix class. */
15835 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15838 /* Here we have something like 'foo:]'. There was no initial colon,
15839 * and we back up over 'foo. XXX Unlike the going forward case, we
15840 * don't handle typos of non-word chars in the middle */
15841 has_opening_colon = FALSE;
15844 while (p > RExC_start && isWORDCHAR(*p)) {
15849 /* Here, we have positioned ourselves to where we think the first
15850 * character in the potential class is */
15853 /* Now the interior really starts. There are certain key characters that
15854 * can end the interior, or these could just be typos. To catch both
15855 * cases, we may have to do two passes. In the first pass, we keep on
15856 * going unless we come to a sequence that matches
15857 * qr/ [[:punct:]] [[:blank:]]* \] /xa
15858 * This means it takes a sequence to end the pass, so two typos in a row if
15859 * that wasn't what was intended. If the class is perfectly formed, just
15860 * this one pass is needed. We also stop if there are too many characters
15861 * being accumulated, but this number is deliberately set higher than any
15862 * real class. It is set high enough so that someone who thinks that
15863 * 'alphanumeric' is a correct name would get warned that it wasn't.
15864 * While doing the pass, we keep track of where the key characters were in
15865 * it. If we don't find an end to the class, and one of the key characters
15866 * was found, we redo the pass, but stop when we get to that character.
15867 * Thus the key character was considered a typo in the first pass, but a
15868 * terminator in the second. If two key characters are found, we stop at
15869 * the second one in the first pass. Again this can miss two typos, but
15870 * catches a single one
15872 * In the first pass, 'possible_end' starts as NULL, and then gets set to
15873 * point to the first key character. For the second pass, it starts as -1.
15879 bool has_blank = FALSE;
15880 bool has_upper = FALSE;
15881 bool has_terminating_colon = FALSE;
15882 bool has_terminating_bracket = FALSE;
15883 bool has_semi_colon = FALSE;
15884 unsigned int name_len = 0;
15885 int punct_count = 0;
15889 /* Squeeze out blanks when looking up the class name below */
15890 if (isBLANK(*p) ) {
15892 found_problem = TRUE;
15897 /* The name will end with a punctuation */
15899 const char * peek = p + 1;
15901 /* Treat any non-']' punctuation followed by a ']' (possibly
15902 * with intervening blanks) as trying to terminate the class.
15903 * ']]' is very likely to mean a class was intended (but
15904 * missing the colon), but the warning message that gets
15905 * generated shows the error position better if we exit the
15906 * loop at the bottom (eventually), so skip it here. */
15908 if (peek < e && isBLANK(*peek)) {
15910 found_problem = TRUE;
15913 } while (peek < e && isBLANK(*peek));
15916 if (peek < e && *peek == ']') {
15917 has_terminating_bracket = TRUE;
15919 has_terminating_colon = TRUE;
15921 else if (*p == ';') {
15922 has_semi_colon = TRUE;
15923 has_terminating_colon = TRUE;
15926 found_problem = TRUE;
15933 /* Here we have punctuation we thought didn't end the class.
15934 * Keep track of the position of the key characters that are
15935 * more likely to have been class-enders */
15936 if (*p == ']' || *p == '[' || *p == ':' || *p == ';') {
15938 /* Allow just one such possible class-ender not actually
15939 * ending the class. */
15940 if (possible_end) {
15946 /* If we have too many punctuation characters, no use in
15948 if (++punct_count > max_distance) {
15952 /* Treat the punctuation as a typo. */
15953 input_text[name_len++] = *p;
15956 else if (isUPPER(*p)) { /* Use lowercase for lookup */
15957 input_text[name_len++] = toLOWER(*p);
15959 found_problem = TRUE;
15961 } else if (! UTF || UTF8_IS_INVARIANT(*p)) {
15962 input_text[name_len++] = *p;
15966 input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL);
15970 /* The declaration of 'input_text' is how long we allow a potential
15971 * class name to be, before saying they didn't mean a class name at
15973 if (name_len >= C_ARRAY_LENGTH(input_text)) {
15978 /* We get to here when the possible class name hasn't been properly
15979 * terminated before:
15980 * 1) we ran off the end of the pattern; or
15981 * 2) found two characters, each of which might have been intended to
15982 * be the name's terminator
15983 * 3) found so many punctuation characters in the purported name,
15984 * that the edit distance to a valid one is exceeded
15985 * 4) we decided it was more characters than anyone could have
15986 * intended to be one. */
15988 found_problem = TRUE;
15990 /* In the final two cases, we know that looking up what we've
15991 * accumulated won't lead to a match, even a fuzzy one. */
15992 if ( name_len >= C_ARRAY_LENGTH(input_text)
15993 || punct_count > max_distance)
15995 /* If there was an intermediate key character that could have been
15996 * an intended end, redo the parse, but stop there */
15997 if (possible_end && possible_end != (char *) -1) {
15998 possible_end = (char *) -1; /* Special signal value to say
15999 we've done a first pass */
16004 /* Otherwise, it can't have meant to have been a class */
16005 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
16008 /* If we ran off the end, and the final character was a punctuation
16009 * one, back up one, to look at that final one just below. Later, we
16010 * will restore the parse pointer if appropriate */
16011 if (name_len && p == e && isPUNCT(*(p-1))) {
16016 if (p < e && isPUNCT(*p)) {
16018 has_terminating_bracket = TRUE;
16020 /* If this is a 2nd ']', and the first one is just below this
16021 * one, consider that to be the real terminator. This gives a
16022 * uniform and better positioning for the warning message */
16024 && possible_end != (char *) -1
16025 && *possible_end == ']'
16026 && name_len && input_text[name_len - 1] == ']')
16031 /* And this is actually equivalent to having done the 2nd
16032 * pass now, so set it to not try again */
16033 possible_end = (char *) -1;
16038 has_terminating_colon = TRUE;
16040 else if (*p == ';') {
16041 has_semi_colon = TRUE;
16042 has_terminating_colon = TRUE;
16050 /* Here, we have a class name to look up. We can short circuit the
16051 * stuff below for short names that can't possibly be meant to be a
16052 * class name. (We can do this on the first pass, as any second pass
16053 * will yield an even shorter name) */
16054 if (name_len < 3) {
16055 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
16058 /* Find which class it is. Initially switch on the length of the name.
16060 switch (name_len) {
16062 if (memEQs(name_start, 4, "word")) {
16063 /* this is not POSIX, this is the Perl \w */
16064 class_number = ANYOF_WORDCHAR;
16068 /* Names all of length 5: alnum alpha ascii blank cntrl digit
16069 * graph lower print punct space upper
16070 * Offset 4 gives the best switch position. */
16071 switch (name_start[4]) {
16073 if (memBEGINs(name_start, 5, "alph")) /* alpha */
16074 class_number = ANYOF_ALPHA;
16077 if (memBEGINs(name_start, 5, "spac")) /* space */
16078 class_number = ANYOF_SPACE;
16081 if (memBEGINs(name_start, 5, "grap")) /* graph */
16082 class_number = ANYOF_GRAPH;
16085 if (memBEGINs(name_start, 5, "asci")) /* ascii */
16086 class_number = ANYOF_ASCII;
16089 if (memBEGINs(name_start, 5, "blan")) /* blank */
16090 class_number = ANYOF_BLANK;
16093 if (memBEGINs(name_start, 5, "cntr")) /* cntrl */
16094 class_number = ANYOF_CNTRL;
16097 if (memBEGINs(name_start, 5, "alnu")) /* alnum */
16098 class_number = ANYOF_ALPHANUMERIC;
16101 if (memBEGINs(name_start, 5, "lowe")) /* lower */
16102 class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER;
16103 else if (memBEGINs(name_start, 5, "uppe")) /* upper */
16104 class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER;
16107 if (memBEGINs(name_start, 5, "digi")) /* digit */
16108 class_number = ANYOF_DIGIT;
16109 else if (memBEGINs(name_start, 5, "prin")) /* print */
16110 class_number = ANYOF_PRINT;
16111 else if (memBEGINs(name_start, 5, "punc")) /* punct */
16112 class_number = ANYOF_PUNCT;
16117 if (memEQs(name_start, 6, "xdigit"))
16118 class_number = ANYOF_XDIGIT;
16122 /* If the name exactly matches a posix class name the class number will
16123 * here be set to it, and the input almost certainly was meant to be a
16124 * posix class, so we can skip further checking. If instead the syntax
16125 * is exactly correct, but the name isn't one of the legal ones, we
16126 * will return that as an error below. But if neither of these apply,
16127 * it could be that no posix class was intended at all, or that one
16128 * was, but there was a typo. We tease these apart by doing fuzzy
16129 * matching on the name */
16130 if (class_number == OOB_NAMEDCLASS && found_problem) {
16131 const UV posix_names[][6] = {
16132 { 'a', 'l', 'n', 'u', 'm' },
16133 { 'a', 'l', 'p', 'h', 'a' },
16134 { 'a', 's', 'c', 'i', 'i' },
16135 { 'b', 'l', 'a', 'n', 'k' },
16136 { 'c', 'n', 't', 'r', 'l' },
16137 { 'd', 'i', 'g', 'i', 't' },
16138 { 'g', 'r', 'a', 'p', 'h' },
16139 { 'l', 'o', 'w', 'e', 'r' },
16140 { 'p', 'r', 'i', 'n', 't' },
16141 { 'p', 'u', 'n', 'c', 't' },
16142 { 's', 'p', 'a', 'c', 'e' },
16143 { 'u', 'p', 'p', 'e', 'r' },
16144 { 'w', 'o', 'r', 'd' },
16145 { 'x', 'd', 'i', 'g', 'i', 't' }
16147 /* The names of the above all have added NULs to make them the same
16148 * size, so we need to also have the real lengths */
16149 const UV posix_name_lengths[] = {
16150 sizeof("alnum") - 1,
16151 sizeof("alpha") - 1,
16152 sizeof("ascii") - 1,
16153 sizeof("blank") - 1,
16154 sizeof("cntrl") - 1,
16155 sizeof("digit") - 1,
16156 sizeof("graph") - 1,
16157 sizeof("lower") - 1,
16158 sizeof("print") - 1,
16159 sizeof("punct") - 1,
16160 sizeof("space") - 1,
16161 sizeof("upper") - 1,
16162 sizeof("word") - 1,
16163 sizeof("xdigit")- 1
16166 int temp_max = max_distance; /* Use a temporary, so if we
16167 reparse, we haven't changed the
16170 /* Use a smaller max edit distance if we are missing one of the
16172 if ( has_opening_bracket + has_opening_colon < 2
16173 || has_terminating_bracket + has_terminating_colon < 2)
16178 /* See if the input name is close to a legal one */
16179 for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) {
16181 /* Short circuit call if the lengths are too far apart to be
16183 if (abs( (int) (name_len - posix_name_lengths[i]))
16189 if (edit_distance(input_text,
16192 posix_name_lengths[i],
16196 { /* If it is close, it probably was intended to be a class */
16197 goto probably_meant_to_be;
16201 /* Here the input name is not close enough to a valid class name
16202 * for us to consider it to be intended to be a posix class. If
16203 * we haven't already done so, and the parse found a character that
16204 * could have been terminators for the name, but which we absorbed
16205 * as typos during the first pass, repeat the parse, signalling it
16206 * to stop at that character */
16207 if (possible_end && possible_end != (char *) -1) {
16208 possible_end = (char *) -1;
16213 /* Here neither pass found a close-enough class name */
16214 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
16217 probably_meant_to_be:
16219 /* Here we think that a posix specification was intended. Update any
16221 if (updated_parse_ptr) {
16222 *updated_parse_ptr = (char *) p;
16225 /* If a posix class name was intended but incorrectly specified, we
16226 * output or return the warnings */
16227 if (found_problem) {
16229 /* We set flags for these issues in the parse loop above instead of
16230 * adding them to the list of warnings, because we can parse it
16231 * twice, and we only want one warning instance */
16233 ADD_POSIX_WARNING(p, "the name must be all lowercase letters");
16236 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
16238 if (has_semi_colon) {
16239 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
16241 else if (! has_terminating_colon) {
16242 ADD_POSIX_WARNING(p, "there is no terminating ':'");
16244 if (! has_terminating_bracket) {
16245 ADD_POSIX_WARNING(p, "there is no terminating ']'");
16248 if ( posix_warnings
16250 && av_top_index(RExC_warn_text) > -1)
16252 *posix_warnings = RExC_warn_text;
16255 else if (class_number != OOB_NAMEDCLASS) {
16256 /* If it is a known class, return the class. The class number
16257 * #defines are structured so each complement is +1 to the normal
16259 CLEAR_POSIX_WARNINGS_AND_RETURN(class_number + complement);
16261 else if (! check_only) {
16263 /* Here, it is an unrecognized class. This is an error (unless the
16264 * call is to check only, which we've already handled above) */
16265 const char * const complement_string = (complement)
16268 RExC_parse = (char *) p;
16269 vFAIL3utf8f("POSIX class [:%s%" UTF8f ":] unknown",
16271 UTF8fARG(UTF, RExC_parse - name_start - 2, name_start));
16275 return OOB_NAMEDCLASS;
16277 #undef ADD_POSIX_WARNING
16279 STATIC unsigned int
16280 S_regex_set_precedence(const U8 my_operator) {
16282 /* Returns the precedence in the (?[...]) construct of the input operator,
16283 * specified by its character representation. The precedence follows
16284 * general Perl rules, but it extends this so that ')' and ']' have (low)
16285 * precedence even though they aren't really operators */
16287 switch (my_operator) {
16303 NOT_REACHED; /* NOTREACHED */
16304 return 0; /* Silence compiler warning */
16307 STATIC regnode_offset
16308 S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist,
16309 I32 *flagp, U32 depth,
16310 char * const oregcomp_parse)
16312 /* Handle the (?[...]) construct to do set operations */
16314 U8 curchar; /* Current character being parsed */
16315 UV start, end; /* End points of code point ranges */
16316 SV* final = NULL; /* The end result inversion list */
16317 SV* result_string; /* 'final' stringified */
16318 AV* stack; /* stack of operators and operands not yet
16320 AV* fence_stack = NULL; /* A stack containing the positions in
16321 'stack' of where the undealt-with left
16322 parens would be if they were actually
16324 /* The 'volatile' is a workaround for an optimiser bug
16325 * in Solaris Studio 12.3. See RT #127455 */
16326 volatile IV fence = 0; /* Position of where most recent undealt-
16327 with left paren in stack is; -1 if none.
16329 STRLEN len; /* Temporary */
16330 regnode_offset node; /* Temporary, and final regnode returned by
16332 const bool save_fold = FOLD; /* Temporary */
16333 char *save_end, *save_parse; /* Temporaries */
16334 const bool in_locale = LOC; /* we turn off /l during processing */
16336 DECLARE_AND_GET_RE_DEBUG_FLAGS;
16338 PERL_ARGS_ASSERT_HANDLE_REGEX_SETS;
16339 PERL_UNUSED_ARG(oregcomp_parse); /* Only for Set_Node_Length */
16341 DEBUG_PARSE("xcls");
16344 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
16347 /* The use of this operator implies /u. This is required so that the
16348 * compile time values are valid in all runtime cases */
16349 REQUIRE_UNI_RULES(flagp, 0);
16351 ckWARNexperimental(RExC_parse,
16352 WARN_EXPERIMENTAL__REGEX_SETS,
16353 "The regex_sets feature is experimental");
16355 /* Everything in this construct is a metacharacter. Operands begin with
16356 * either a '\' (for an escape sequence), or a '[' for a bracketed
16357 * character class. Any other character should be an operator, or
16358 * parenthesis for grouping. Both types of operands are handled by calling
16359 * regclass() to parse them. It is called with a parameter to indicate to
16360 * return the computed inversion list. The parsing here is implemented via
16361 * a stack. Each entry on the stack is a single character representing one
16362 * of the operators; or else a pointer to an operand inversion list. */
16364 #define IS_OPERATOR(a) SvIOK(a)
16365 #define IS_OPERAND(a) (! IS_OPERATOR(a))
16367 /* The stack is kept in Łukasiewicz order. (That's pronounced similar
16368 * to luke-a-shave-itch (or -itz), but people who didn't want to bother
16369 * with pronouncing it called it Reverse Polish instead, but now that YOU
16370 * know how to pronounce it you can use the correct term, thus giving due
16371 * credit to the person who invented it, and impressing your geek friends.
16372 * Wikipedia says that the pronounciation of "Ł" has been changing so that
16373 * it is now more like an English initial W (as in wonk) than an L.)
16375 * This means that, for example, 'a | b & c' is stored on the stack as
16383 * where the numbers in brackets give the stack [array] element number.
16384 * In this implementation, parentheses are not stored on the stack.
16385 * Instead a '(' creates a "fence" so that the part of the stack below the
16386 * fence is invisible except to the corresponding ')' (this allows us to
16387 * replace testing for parens, by using instead subtraction of the fence
16388 * position). As new operands are processed they are pushed onto the stack
16389 * (except as noted in the next paragraph). New operators of higher
16390 * precedence than the current final one are inserted on the stack before
16391 * the lhs operand (so that when the rhs is pushed next, everything will be
16392 * in the correct positions shown above. When an operator of equal or
16393 * lower precedence is encountered in parsing, all the stacked operations
16394 * of equal or higher precedence are evaluated, leaving the result as the
16395 * top entry on the stack. This makes higher precedence operations
16396 * evaluate before lower precedence ones, and causes operations of equal
16397 * precedence to left associate.
16399 * The only unary operator '!' is immediately pushed onto the stack when
16400 * encountered. When an operand is encountered, if the top of the stack is
16401 * a '!", the complement is immediately performed, and the '!' popped. The
16402 * resulting value is treated as a new operand, and the logic in the
16403 * previous paragraph is executed. Thus in the expression
16405 * the stack looks like
16411 * as 'b' gets parsed, the latter gets evaluated to '!b', and the stack
16418 * A ')' is treated as an operator with lower precedence than all the
16419 * aforementioned ones, which causes all operations on the stack above the
16420 * corresponding '(' to be evaluated down to a single resultant operand.
16421 * Then the fence for the '(' is removed, and the operand goes through the
16422 * algorithm above, without the fence.
16424 * A separate stack is kept of the fence positions, so that the position of
16425 * the latest so-far unbalanced '(' is at the top of it.
16427 * The ']' ending the construct is treated as the lowest operator of all,
16428 * so that everything gets evaluated down to a single operand, which is the
16431 sv_2mortal((SV *)(stack = newAV()));
16432 sv_2mortal((SV *)(fence_stack = newAV()));
16434 while (RExC_parse < RExC_end) {
16435 I32 top_index; /* Index of top-most element in 'stack' */
16436 SV** top_ptr; /* Pointer to top 'stack' element */
16437 SV* current = NULL; /* To contain the current inversion list
16439 SV* only_to_avoid_leaks;
16441 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
16442 TRUE /* Force /x */ );
16443 if (RExC_parse >= RExC_end) { /* Fail */
16447 curchar = UCHARAT(RExC_parse);
16451 #ifdef ENABLE_REGEX_SETS_DEBUGGING
16452 /* Enable with -Accflags=-DENABLE_REGEX_SETS_DEBUGGING */
16453 DEBUG_U(dump_regex_sets_structures(pRExC_state,
16454 stack, fence, fence_stack));
16457 top_index = av_tindex_skip_len_mg(stack);
16460 SV** stacked_ptr; /* Ptr to something already on 'stack' */
16461 char stacked_operator; /* The topmost operator on the 'stack'. */
16462 SV* lhs; /* Operand to the left of the operator */
16463 SV* rhs; /* Operand to the right of the operator */
16464 SV* fence_ptr; /* Pointer to top element of the fence
16468 if ( RExC_parse < RExC_end - 2
16469 && UCHARAT(RExC_parse + 1) == '?'
16470 && UCHARAT(RExC_parse + 2) == '^')
16472 const regnode_offset orig_emit = RExC_emit;
16473 SV * resultant_invlist;
16475 /* If is a '(?^', could be an embedded '(?^flags:(?[...])'.
16476 * This happens when we have some thing like
16478 * my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
16480 * qr/(?[ \p{Digit} & $thai_or_lao ])/;
16482 * Here we would be handling the interpolated
16483 * '$thai_or_lao'. We handle this by a recursive call to
16484 * reg which returns the inversion list the
16485 * interpolated expression evaluates to. Actually, the
16486 * return is a special regnode containing a pointer to that
16487 * inversion list. If the return isn't that regnode alone,
16488 * we know that this wasn't such an interpolation, which is
16489 * an error: we need to get a single inversion list back
16490 * from the recursion */
16495 node = reg(pRExC_state, 2, flagp, depth+1);
16496 RETURN_FAIL_ON_RESTART(*flagp, flagp);
16498 if ( OP(REGNODE_p(node)) != REGEX_SET
16499 /* If more than a single node returned, the nested
16500 * parens evaluated to more than just a (?[...]),
16501 * which isn't legal */
16502 || RExC_emit != orig_emit
16503 + NODE_STEP_REGNODE
16504 + regarglen[REGEX_SET])
16506 vFAIL("Expecting interpolated extended charclass");
16508 resultant_invlist = (SV *) ARGp(REGNODE_p(node));
16509 current = invlist_clone(resultant_invlist, NULL);
16510 SvREFCNT_dec(resultant_invlist);
16513 RExC_emit = orig_emit;
16514 goto handle_operand;
16517 /* A regular '('. Look behind for illegal syntax */
16518 if (top_index - fence >= 0) {
16519 /* If the top entry on the stack is an operator, it had
16520 * better be a '!', otherwise the entry below the top
16521 * operand should be an operator */
16522 if ( ! (top_ptr = av_fetch(stack, top_index, FALSE))
16523 || (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!')
16524 || ( IS_OPERAND(*top_ptr)
16525 && ( top_index - fence < 1
16526 || ! (stacked_ptr = av_fetch(stack,
16529 || ! IS_OPERATOR(*stacked_ptr))))
16532 vFAIL("Unexpected '(' with no preceding operator");
16536 /* Stack the position of this undealt-with left paren */
16537 av_push(fence_stack, newSViv(fence));
16538 fence = top_index + 1;
16542 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
16543 * multi-char folds are allowed. */
16544 if (!regclass(pRExC_state, flagp, depth+1,
16545 TRUE, /* means parse just the next thing */
16546 FALSE, /* don't allow multi-char folds */
16547 FALSE, /* don't silence non-portable warnings. */
16549 FALSE, /* Require return to be an ANYOF */
16552 RETURN_FAIL_ON_RESTART(*flagp, flagp);
16553 goto regclass_failed;
16558 /* regclass() will return with parsing just the \ sequence,
16559 * leaving the parse pointer at the next thing to parse */
16561 goto handle_operand;
16563 case '[': /* Is a bracketed character class */
16565 /* See if this is a [:posix:] class. */
16566 bool is_posix_class = (OOB_NAMEDCLASS
16567 < handle_possible_posix(pRExC_state,
16571 TRUE /* checking only */));
16572 /* If it is a posix class, leave the parse pointer at the '['
16573 * to fool regclass() into thinking it is part of a
16574 * '[[:posix:]]'. */
16575 if (! is_posix_class) {
16579 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
16580 * multi-char folds are allowed. */
16581 if (!regclass(pRExC_state, flagp, depth+1,
16582 is_posix_class, /* parse the whole char
16583 class only if not a
16585 FALSE, /* don't allow multi-char folds */
16586 TRUE, /* silence non-portable warnings. */
16588 FALSE, /* Require return to be an ANYOF */
16591 RETURN_FAIL_ON_RESTART(*flagp, flagp);
16592 goto regclass_failed;
16597 /* function call leaves parse pointing to the ']', except if we
16599 if (is_posix_class) {
16603 goto handle_operand;
16607 if (top_index >= 1) {
16608 goto join_operators;
16611 /* Only a single operand on the stack: are done */
16615 if (av_tindex_skip_len_mg(fence_stack) < 0) {
16616 if (UCHARAT(RExC_parse - 1) == ']') {
16620 vFAIL("Unexpected ')'");
16623 /* If nothing after the fence, is missing an operand */
16624 if (top_index - fence < 0) {
16628 /* If at least two things on the stack, treat this as an
16630 if (top_index - fence >= 1) {
16631 goto join_operators;
16634 /* Here only a single thing on the fenced stack, and there is a
16635 * fence. Get rid of it */
16636 fence_ptr = av_pop(fence_stack);
16638 fence = SvIV(fence_ptr);
16639 SvREFCNT_dec_NN(fence_ptr);
16646 /* Having gotten rid of the fence, we pop the operand at the
16647 * stack top and process it as a newly encountered operand */
16648 current = av_pop(stack);
16649 if (IS_OPERAND(current)) {
16650 goto handle_operand;
16662 /* These binary operators should have a left operand already
16664 if ( top_index - fence < 0
16665 || top_index - fence == 1
16666 || ( ! (top_ptr = av_fetch(stack, top_index, FALSE)))
16667 || ! IS_OPERAND(*top_ptr))
16669 goto unexpected_binary;
16672 /* If only the one operand is on the part of the stack visible
16673 * to us, we just place this operator in the proper position */
16674 if (top_index - fence < 2) {
16676 /* Place the operator before the operand */
16678 SV* lhs = av_pop(stack);
16679 av_push(stack, newSVuv(curchar));
16680 av_push(stack, lhs);
16684 /* But if there is something else on the stack, we need to
16685 * process it before this new operator if and only if the
16686 * stacked operation has equal or higher precedence than the
16691 /* The operator on the stack is supposed to be below both its
16693 if ( ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE))
16694 || IS_OPERAND(*stacked_ptr))
16696 /* But if not, it's legal and indicates we are completely
16697 * done if and only if we're currently processing a ']',
16698 * which should be the final thing in the expression */
16699 if (curchar == ']') {
16705 vFAIL2("Unexpected binary operator '%c' with no "
16706 "preceding operand", curchar);
16708 stacked_operator = (char) SvUV(*stacked_ptr);
16710 if (regex_set_precedence(curchar)
16711 > regex_set_precedence(stacked_operator))
16713 /* Here, the new operator has higher precedence than the
16714 * stacked one. This means we need to add the new one to
16715 * the stack to await its rhs operand (and maybe more
16716 * stuff). We put it before the lhs operand, leaving
16717 * untouched the stacked operator and everything below it
16719 lhs = av_pop(stack);
16720 assert(IS_OPERAND(lhs));
16722 av_push(stack, newSVuv(curchar));
16723 av_push(stack, lhs);
16727 /* Here, the new operator has equal or lower precedence than
16728 * what's already there. This means the operation already
16729 * there should be performed now, before the new one. */
16731 rhs = av_pop(stack);
16732 if (! IS_OPERAND(rhs)) {
16734 /* This can happen when a ! is not followed by an operand,
16735 * like in /(?[\t &!])/ */
16739 lhs = av_pop(stack);
16741 if (! IS_OPERAND(lhs)) {
16743 /* This can happen when there is an empty (), like in
16744 * /(?[[0]+()+])/ */
16748 switch (stacked_operator) {
16750 _invlist_intersection(lhs, rhs, &rhs);
16755 _invlist_union(lhs, rhs, &rhs);
16759 _invlist_subtract(lhs, rhs, &rhs);
16762 case '^': /* The union minus the intersection */
16767 _invlist_union(lhs, rhs, &u);
16768 _invlist_intersection(lhs, rhs, &i);
16769 _invlist_subtract(u, i, &rhs);
16770 SvREFCNT_dec_NN(i);
16771 SvREFCNT_dec_NN(u);
16777 /* Here, the higher precedence operation has been done, and the
16778 * result is in 'rhs'. We overwrite the stacked operator with
16779 * the result. Then we redo this code to either push the new
16780 * operator onto the stack or perform any higher precedence
16781 * stacked operation */
16782 only_to_avoid_leaks = av_pop(stack);
16783 SvREFCNT_dec(only_to_avoid_leaks);
16784 av_push(stack, rhs);
16787 case '!': /* Highest priority, right associative */
16789 /* If what's already at the top of the stack is another '!",
16790 * they just cancel each other out */
16791 if ( (top_ptr = av_fetch(stack, top_index, FALSE))
16792 && (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!'))
16794 only_to_avoid_leaks = av_pop(stack);
16795 SvREFCNT_dec(only_to_avoid_leaks);
16797 else { /* Otherwise, since it's right associative, just push
16799 av_push(stack, newSVuv(curchar));
16804 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16805 if (RExC_parse >= RExC_end) {
16808 vFAIL("Unexpected character");
16812 /* Here 'current' is the operand. If something is already on the
16813 * stack, we have to check if it is a !. But first, the code above
16814 * may have altered the stack in the time since we earlier set
16817 top_index = av_tindex_skip_len_mg(stack);
16818 if (top_index - fence >= 0) {
16819 /* If the top entry on the stack is an operator, it had better
16820 * be a '!', otherwise the entry below the top operand should
16821 * be an operator */
16822 top_ptr = av_fetch(stack, top_index, FALSE);
16824 if (IS_OPERATOR(*top_ptr)) {
16826 /* The only permissible operator at the top of the stack is
16827 * '!', which is applied immediately to this operand. */
16828 curchar = (char) SvUV(*top_ptr);
16829 if (curchar != '!') {
16830 SvREFCNT_dec(current);
16831 vFAIL2("Unexpected binary operator '%c' with no "
16832 "preceding operand", curchar);
16835 _invlist_invert(current);
16837 only_to_avoid_leaks = av_pop(stack);
16838 SvREFCNT_dec(only_to_avoid_leaks);
16840 /* And we redo with the inverted operand. This allows
16841 * handling multiple ! in a row */
16842 goto handle_operand;
16844 /* Single operand is ok only for the non-binary ')'
16846 else if ((top_index - fence == 0 && curchar != ')')
16847 || (top_index - fence > 0
16848 && (! (stacked_ptr = av_fetch(stack,
16851 || IS_OPERAND(*stacked_ptr))))
16853 SvREFCNT_dec(current);
16854 vFAIL("Operand with no preceding operator");
16858 /* Here there was nothing on the stack or the top element was
16859 * another operand. Just add this new one */
16860 av_push(stack, current);
16862 } /* End of switch on next parse token */
16864 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16865 } /* End of loop parsing through the construct */
16867 vFAIL("Syntax error in (?[...])");
16871 if (RExC_parse >= RExC_end || RExC_parse[1] != ')') {
16872 if (RExC_parse < RExC_end) {
16876 vFAIL("Unexpected ']' with no following ')' in (?[...");
16879 if (av_tindex_skip_len_mg(fence_stack) >= 0) {
16880 vFAIL("Unmatched (");
16883 if (av_tindex_skip_len_mg(stack) < 0 /* Was empty */
16884 || ((final = av_pop(stack)) == NULL)
16885 || ! IS_OPERAND(final)
16886 || ! is_invlist(final)
16887 || av_tindex_skip_len_mg(stack) >= 0) /* More left on stack */
16890 SvREFCNT_dec(final);
16891 vFAIL("Incomplete expression within '(?[ ])'");
16894 /* Here, 'final' is the resultant inversion list from evaluating the
16895 * expression. Return it if so requested */
16896 if (return_invlist) {
16897 *return_invlist = final;
16901 if (RExC_sets_depth) { /* If within a recursive call, return in a special
16904 node = regpnode(pRExC_state, REGEX_SET, final);
16908 /* Otherwise generate a resultant node, based on 'final'. regclass()
16909 * is expecting a string of ranges and individual code points */
16910 invlist_iterinit(final);
16911 result_string = newSVpvs("");
16912 while (invlist_iternext(final, &start, &end)) {
16913 if (start == end) {
16914 Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}", start);
16917 Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}-\\x{%"
16918 UVXf "}", start, end);
16922 /* About to generate an ANYOF (or similar) node from the inversion list
16923 * we have calculated */
16924 save_parse = RExC_parse;
16925 RExC_parse = SvPV(result_string, len);
16926 save_end = RExC_end;
16927 RExC_end = RExC_parse + len;
16928 TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
16930 /* We turn off folding around the call, as the class we have
16931 * constructed already has all folding taken into consideration, and we
16932 * don't want regclass() to add to that */
16933 RExC_flags &= ~RXf_PMf_FOLD;
16934 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if multi-char
16935 * folds are allowed. */
16936 node = regclass(pRExC_state, flagp, depth+1,
16937 FALSE, /* means parse the whole char class */
16938 FALSE, /* don't allow multi-char folds */
16939 TRUE, /* silence non-portable warnings. The above may
16940 very well have generated non-portable code
16941 points, but they're valid on this machine */
16942 FALSE, /* similarly, no need for strict */
16944 /* We can optimize into something besides an ANYOF,
16945 * except under /l, which needs to be ANYOF because of
16946 * runtime checks for locale sanity, etc */
16952 RExC_parse = save_parse + 1;
16953 RExC_end = save_end;
16954 SvREFCNT_dec_NN(final);
16955 SvREFCNT_dec_NN(result_string);
16958 RExC_flags |= RXf_PMf_FOLD;
16962 RETURN_FAIL_ON_RESTART(*flagp, flagp);
16963 goto regclass_failed;
16966 /* Fix up the node type if we are in locale. (We have pretended we are
16967 * under /u for the purposes of regclass(), as this construct will only
16968 * work under UTF-8 locales. But now we change the opcode to be ANYOFL
16969 * (so as to cause any warnings about bad locales to be output in
16970 * regexec.c), and add the flag that indicates to check if not in a
16971 * UTF-8 locale. The reason we above forbid optimization into
16972 * something other than an ANYOF node is simply to minimize the number
16973 * of code changes in regexec.c. Otherwise we would have to create new
16974 * EXACTish node types and deal with them. This decision could be
16975 * revisited should this construct become popular.
16977 * (One might think we could look at the resulting ANYOF node and
16978 * suppress the flag if everything is above 255, as those would be
16979 * UTF-8 only, but this isn't true, as the components that led to that
16980 * result could have been locale-affected, and just happen to cancel
16981 * each other out under UTF-8 locales.) */
16983 set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
16985 assert(OP(REGNODE_p(node)) == ANYOF);
16987 OP(REGNODE_p(node)) = ANYOFL;
16988 ANYOF_FLAGS(REGNODE_p(node))
16989 |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
16993 nextchar(pRExC_state);
16994 Set_Node_Length(REGNODE_p(node), RExC_parse - oregcomp_parse + 1); /* MJD */
16998 FAIL2("panic: regclass returned failure to handle_sets, " "flags=%#" UVxf,
17002 #ifdef ENABLE_REGEX_SETS_DEBUGGING
17005 S_dump_regex_sets_structures(pTHX_ RExC_state_t *pRExC_state,
17006 AV * stack, const IV fence, AV * fence_stack)
17007 { /* Dumps the stacks in handle_regex_sets() */
17009 const SSize_t stack_top = av_tindex_skip_len_mg(stack);
17010 const SSize_t fence_stack_top = av_tindex_skip_len_mg(fence_stack);
17013 PERL_ARGS_ASSERT_DUMP_REGEX_SETS_STRUCTURES;
17015 PerlIO_printf(Perl_debug_log, "\nParse position is:%s\n", RExC_parse);
17017 if (stack_top < 0) {
17018 PerlIO_printf(Perl_debug_log, "Nothing on stack\n");
17021 PerlIO_printf(Perl_debug_log, "Stack: (fence=%d)\n", (int) fence);
17022 for (i = stack_top; i >= 0; i--) {
17023 SV ** element_ptr = av_fetch(stack, i, FALSE);
17024 if (! element_ptr) {
17027 if (IS_OPERATOR(*element_ptr)) {
17028 PerlIO_printf(Perl_debug_log, "[%d]: %c\n",
17029 (int) i, (int) SvIV(*element_ptr));
17032 PerlIO_printf(Perl_debug_log, "[%d] ", (int) i);
17033 sv_dump(*element_ptr);
17038 if (fence_stack_top < 0) {
17039 PerlIO_printf(Perl_debug_log, "Nothing on fence_stack\n");
17042 PerlIO_printf(Perl_debug_log, "Fence_stack: \n");
17043 for (i = fence_stack_top; i >= 0; i--) {
17044 SV ** element_ptr = av_fetch(fence_stack, i, FALSE);
17045 if (! element_ptr) {
17048 PerlIO_printf(Perl_debug_log, "[%d]: %d\n",
17049 (int) i, (int) SvIV(*element_ptr));
17060 S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist)
17062 /* This adds the Latin1/above-Latin1 folding rules.
17064 * This should be called only for a Latin1-range code points, cp, which is
17065 * known to be involved in a simple fold with other code points above
17066 * Latin1. It would give false results if /aa has been specified.
17067 * Multi-char folds are outside the scope of this, and must be handled
17070 PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS;
17072 assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp));
17074 /* The rules that are valid for all Unicode versions are hard-coded in */
17079 add_cp_to_invlist(*invlist, KELVIN_SIGN);
17083 *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S);
17086 *invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU);
17087 *invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU);
17089 case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
17090 case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
17091 *invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN);
17093 case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
17094 *invlist = add_cp_to_invlist(*invlist,
17095 LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
17098 default: /* Other code points are checked against the data for the
17099 current Unicode version */
17101 Size_t folds_count;
17103 const U32 * remaining_folds;
17107 folded_cp = toFOLD(cp);
17110 U8 dummy_fold[UTF8_MAXBYTES_CASE+1];
17112 folded_cp = _to_fold_latin1(cp, dummy_fold, &dummy_len, 0);
17115 if (folded_cp > 255) {
17116 *invlist = add_cp_to_invlist(*invlist, folded_cp);
17119 folds_count = _inverse_folds(folded_cp, &first_fold,
17121 if (folds_count == 0) {
17123 /* Use deprecated warning to increase the chances of this being
17125 ckWARN2reg_d(RExC_parse,
17126 "Perl folding rules are not up-to-date for 0x%02X;"
17127 " please use the perlbug utility to report;", cp);
17132 if (first_fold > 255) {
17133 *invlist = add_cp_to_invlist(*invlist, first_fold);
17135 for (i = 0; i < folds_count - 1; i++) {
17136 if (remaining_folds[i] > 255) {
17137 *invlist = add_cp_to_invlist(*invlist,
17138 remaining_folds[i]);
17148 S_output_posix_warnings(pTHX_ RExC_state_t *pRExC_state, AV* posix_warnings)
17150 /* Output the elements of the array given by '*posix_warnings' as REGEXP
17154 const bool first_is_fatal = ckDEAD(packWARN(WARN_REGEXP));
17156 PERL_ARGS_ASSERT_OUTPUT_POSIX_WARNINGS;
17158 if (! TO_OUTPUT_WARNINGS(RExC_parse)) {
17159 CLEAR_POSIX_WARNINGS();
17163 while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) {
17164 if (first_is_fatal) { /* Avoid leaking this */
17165 av_undef(posix_warnings); /* This isn't necessary if the
17166 array is mortal, but is a
17168 (void) sv_2mortal(msg);
17171 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg));
17172 SvREFCNT_dec_NN(msg);
17175 UPDATE_WARNINGS_LOC(RExC_parse);
17178 PERL_STATIC_INLINE Size_t
17179 S_find_first_differing_byte_pos(const U8 * s1, const U8 * s2, const Size_t max)
17181 const U8 * const start = s1;
17182 const U8 * const send = start + max;
17184 PERL_ARGS_ASSERT_FIND_FIRST_DIFFERING_BYTE_POS;
17186 while (s1 < send && *s1 == *s2) {
17195 S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count)
17197 /* This adds the string scalar <multi_string> to the array
17198 * <multi_char_matches>. <multi_string> is known to have exactly
17199 * <cp_count> code points in it. This is used when constructing a
17200 * bracketed character class and we find something that needs to match more
17201 * than a single character.
17203 * <multi_char_matches> is actually an array of arrays. Each top-level
17204 * element is an array that contains all the strings known so far that are
17205 * the same length. And that length (in number of code points) is the same
17206 * as the index of the top-level array. Hence, the [2] element is an
17207 * array, each element thereof is a string containing TWO code points;
17208 * while element [3] is for strings of THREE characters, and so on. Since
17209 * this is for multi-char strings there can never be a [0] nor [1] element.
17211 * When we rewrite the character class below, we will do so such that the
17212 * longest strings are written first, so that it prefers the longest
17213 * matching strings first. This is done even if it turns out that any
17214 * quantifier is non-greedy, out of this programmer's (khw) laziness. Tom
17215 * Christiansen has agreed that this is ok. This makes the test for the
17216 * ligature 'ffi' come before the test for 'ff', for example */
17219 AV** this_array_ptr;
17221 PERL_ARGS_ASSERT_ADD_MULTI_MATCH;
17223 if (! multi_char_matches) {
17224 multi_char_matches = newAV();
17227 if (av_exists(multi_char_matches, cp_count)) {
17228 this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE);
17229 this_array = *this_array_ptr;
17232 this_array = newAV();
17233 av_store(multi_char_matches, cp_count,
17236 av_push(this_array, multi_string);
17238 return multi_char_matches;
17241 /* The names of properties whose definitions are not known at compile time are
17242 * stored in this SV, after a constant heading. So if the length has been
17243 * changed since initialization, then there is a run-time definition. */
17244 #define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION \
17245 (SvCUR(listsv) != initial_listsv_len)
17247 /* There is a restricted set of white space characters that are legal when
17248 * ignoring white space in a bracketed character class. This generates the
17249 * code to skip them.
17251 * There is a line below that uses the same white space criteria but is outside
17252 * this macro. Both here and there must use the same definition */
17253 #define SKIP_BRACKETED_WHITE_SPACE(do_skip, p) \
17256 while (isBLANK_A(UCHARAT(p))) \
17263 STATIC regnode_offset
17264 S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth,
17265 const bool stop_at_1, /* Just parse the next thing, don't
17266 look for a full character class */
17267 bool allow_mutiple_chars,
17268 const bool silence_non_portable, /* Don't output warnings
17272 bool optimizable, /* ? Allow a non-ANYOF return
17274 SV** ret_invlist /* Return an inversion list, not a node */
17277 /* parse a bracketed class specification. Most of these will produce an
17278 * ANYOF node; but something like [a] will produce an EXACT node; [aA], an
17279 * EXACTFish node; [[:ascii:]], a POSIXA node; etc. It is more complex
17280 * under /i with multi-character folds: it will be rewritten following the
17281 * paradigm of this example, where the <multi-fold>s are characters which
17282 * fold to multiple character sequences:
17283 * /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
17284 * gets effectively rewritten as:
17285 * /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
17286 * reg() gets called (recursively) on the rewritten version, and this
17287 * function will return what it constructs. (Actually the <multi-fold>s
17288 * aren't physically removed from the [abcdefghi], it's just that they are
17289 * ignored in the recursion by means of a flag:
17290 * <RExC_in_multi_char_class>.)
17292 * ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS
17293 * characters, with the corresponding bit set if that character is in the
17294 * list. For characters above this, an inversion list is used. There
17295 * are extra bits for \w, etc. in locale ANYOFs, as what these match is not
17296 * determinable at compile time
17298 * On success, returns the offset at which any next node should be placed
17299 * into the regex engine program being compiled.
17301 * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
17302 * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
17307 UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
17309 UV value = OOB_UNICODE, save_value = OOB_UNICODE;
17310 regnode_offset ret = -1; /* Initialized to an illegal value */
17312 int namedclass = OOB_NAMEDCLASS;
17313 char *rangebegin = NULL;
17314 SV *listsv = NULL; /* List of \p{user-defined} whose definitions
17315 aren't available at the time this was called */
17316 STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
17317 than just initialized. */
17318 SV* properties = NULL; /* Code points that match \p{} \P{} */
17319 SV* posixes = NULL; /* Code points that match classes like [:word:],
17320 extended beyond the Latin1 range. These have to
17321 be kept separate from other code points for much
17322 of this function because their handling is
17323 different under /i, and for most classes under
17325 SV* nposixes = NULL; /* Similarly for [:^word:]. These are kept
17326 separate for a while from the non-complemented
17327 versions because of complications with /d
17329 SV* simple_posixes = NULL; /* But under some conditions, the classes can be
17330 treated more simply than the general case,
17331 leading to less compilation and execution
17333 UV element_count = 0; /* Number of distinct elements in the class.
17334 Optimizations may be possible if this is tiny */
17335 AV * multi_char_matches = NULL; /* Code points that fold to more than one
17336 character; used under /i */
17338 char * stop_ptr = RExC_end; /* where to stop parsing */
17340 /* ignore unescaped whitespace? */
17341 const bool skip_white = cBOOL( ret_invlist
17342 || (RExC_flags & RXf_PMf_EXTENDED_MORE));
17344 /* inversion list of code points this node matches only when the target
17345 * string is in UTF-8. These are all non-ASCII, < 256. (Because is under
17347 SV* upper_latin1_only_utf8_matches = NULL;
17349 /* Inversion list of code points this node matches regardless of things
17350 * like locale, folding, utf8ness of the target string */
17351 SV* cp_list = NULL;
17353 /* Like cp_list, but code points on this list need to be checked for things
17354 * that fold to/from them under /i */
17355 SV* cp_foldable_list = NULL;
17357 /* Like cp_list, but code points on this list are valid only when the
17358 * runtime locale is UTF-8 */
17359 SV* only_utf8_locale_list = NULL;
17361 /* In a range, if one of the endpoints is non-character-set portable,
17362 * meaning that it hard-codes a code point that may mean a different
17363 * charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a
17364 * mnemonic '\t' which each mean the same character no matter which
17365 * character set the platform is on. */
17366 unsigned int non_portable_endpoint = 0;
17368 /* Is the range unicode? which means on a platform that isn't 1-1 native
17369 * to Unicode (i.e. non-ASCII), each code point in it should be considered
17370 * to be a Unicode value. */
17371 bool unicode_range = FALSE;
17372 bool invert = FALSE; /* Is this class to be complemented */
17374 bool warn_super = ALWAYS_WARN_SUPER;
17376 const char * orig_parse = RExC_parse;
17378 /* This variable is used to mark where the end in the input is of something
17379 * that looks like a POSIX construct but isn't. During the parse, when
17380 * something looks like it could be such a construct is encountered, it is
17381 * checked for being one, but not if we've already checked this area of the
17382 * input. Only after this position is reached do we check again */
17383 char *not_posix_region_end = RExC_parse - 1;
17385 AV* posix_warnings = NULL;
17386 const bool do_posix_warnings = ckWARN(WARN_REGEXP);
17387 U8 op = END; /* The returned node-type, initialized to an impossible
17389 U8 anyof_flags = 0; /* flag bits if the node is an ANYOF-type */
17390 U32 posixl = 0; /* bit field of posix classes matched under /l */
17393 /* Flags as to what things aren't knowable until runtime. (Note that these are
17394 * mutually exclusive.) */
17395 #define HAS_USER_DEFINED_PROPERTY 0x01 /* /u any user-defined properties that
17396 haven't been defined as of yet */
17397 #define HAS_D_RUNTIME_DEPENDENCY 0x02 /* /d if the target being matched is
17399 #define HAS_L_RUNTIME_DEPENDENCY 0x04 /* /l what the posix classes match and
17400 what gets folded */
17401 U32 has_runtime_dependency = 0; /* OR of the above flags */
17403 DECLARE_AND_GET_RE_DEBUG_FLAGS;
17405 PERL_ARGS_ASSERT_REGCLASS;
17407 PERL_UNUSED_ARG(depth);
17410 assert(! (ret_invlist && allow_mutiple_chars));
17412 /* If wants an inversion list returned, we can't optimize to something
17415 optimizable = FALSE;
17418 DEBUG_PARSE("clas");
17420 #if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */ \
17421 || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0 \
17422 && UNICODE_DOT_DOT_VERSION == 0)
17423 allow_mutiple_chars = FALSE;
17426 /* We include the /i status at the beginning of this so that we can
17427 * know it at runtime */
17428 listsv = sv_2mortal(Perl_newSVpvf(aTHX_ "#%d\n", cBOOL(FOLD)));
17429 initial_listsv_len = SvCUR(listsv);
17430 SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated. */
17432 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17434 assert(RExC_parse <= RExC_end);
17436 if (UCHARAT(RExC_parse) == '^') { /* Complement the class */
17439 allow_mutiple_chars = FALSE;
17441 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17444 /* Check that they didn't say [:posix:] instead of [[:posix:]] */
17445 if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) {
17446 int maybe_class = handle_possible_posix(pRExC_state,
17448 ¬_posix_region_end,
17450 TRUE /* checking only */);
17451 if (maybe_class >= OOB_NAMEDCLASS && do_posix_warnings) {
17452 ckWARN4reg(not_posix_region_end,
17453 "POSIX syntax [%c %c] belongs inside character classes%s",
17454 *RExC_parse, *RExC_parse,
17455 (maybe_class == OOB_NAMEDCLASS)
17456 ? ((POSIXCC_NOTYET(*RExC_parse))
17457 ? " (but this one isn't implemented)"
17458 : " (but this one isn't fully valid)")
17464 /* If the caller wants us to just parse a single element, accomplish this
17465 * by faking the loop ending condition */
17466 if (stop_at_1 && RExC_end > RExC_parse) {
17467 stop_ptr = RExC_parse + 1;
17470 /* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */
17471 if (UCHARAT(RExC_parse) == ']')
17472 goto charclassloop;
17476 if ( posix_warnings
17477 && av_tindex_skip_len_mg(posix_warnings) >= 0
17478 && RExC_parse > not_posix_region_end)
17480 /* Warnings about posix class issues are considered tentative until
17481 * we are far enough along in the parse that we can no longer
17482 * change our mind, at which point we output them. This is done
17483 * each time through the loop so that a later class won't zap them
17484 * before they have been dealt with. */
17485 output_posix_warnings(pRExC_state, posix_warnings);
17488 if (RExC_parse >= stop_ptr) {
17492 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17494 if (UCHARAT(RExC_parse) == ']') {
17500 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
17501 save_value = value;
17502 save_prevvalue = prevvalue;
17505 rangebegin = RExC_parse;
17507 non_portable_endpoint = 0;
17509 if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) {
17510 value = utf8n_to_uvchr((U8*)RExC_parse,
17511 RExC_end - RExC_parse,
17512 &numlen, UTF8_ALLOW_DEFAULT);
17513 RExC_parse += numlen;
17516 value = UCHARAT(RExC_parse++);
17518 if (value == '[') {
17519 char * posix_class_end;
17520 namedclass = handle_possible_posix(pRExC_state,
17523 do_posix_warnings ? &posix_warnings : NULL,
17524 FALSE /* die if error */);
17525 if (namedclass > OOB_NAMEDCLASS) {
17527 /* If there was an earlier attempt to parse this particular
17528 * posix class, and it failed, it was a false alarm, as this
17529 * successful one proves */
17530 if ( posix_warnings
17531 && av_tindex_skip_len_mg(posix_warnings) >= 0
17532 && not_posix_region_end >= RExC_parse
17533 && not_posix_region_end <= posix_class_end)
17535 av_undef(posix_warnings);
17538 RExC_parse = posix_class_end;
17540 else if (namedclass == OOB_NAMEDCLASS) {
17541 not_posix_region_end = posix_class_end;
17544 namedclass = OOB_NAMEDCLASS;
17547 else if ( RExC_parse - 1 > not_posix_region_end
17548 && MAYBE_POSIXCC(value))
17550 (void) handle_possible_posix(
17552 RExC_parse - 1, /* -1 because parse has already been
17554 ¬_posix_region_end,
17555 do_posix_warnings ? &posix_warnings : NULL,
17556 TRUE /* checking only */);
17558 else if ( strict && ! skip_white
17559 && ( _generic_isCC(value, _CC_VERTSPACE)
17560 || is_VERTWS_cp_high(value)))
17562 vFAIL("Literal vertical space in [] is illegal except under /x");
17564 else if (value == '\\') {
17565 /* Is a backslash; get the code point of the char after it */
17567 if (RExC_parse >= RExC_end) {
17568 vFAIL("Unmatched [");
17571 if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) {
17572 value = utf8n_to_uvchr((U8*)RExC_parse,
17573 RExC_end - RExC_parse,
17574 &numlen, UTF8_ALLOW_DEFAULT);
17575 RExC_parse += numlen;
17578 value = UCHARAT(RExC_parse++);
17580 /* Some compilers cannot handle switching on 64-bit integer
17581 * values, therefore value cannot be an UV. Yes, this will
17582 * be a problem later if we want switch on Unicode.
17583 * A similar issue a little bit later when switching on
17584 * namedclass. --jhi */
17586 /* If the \ is escaping white space when white space is being
17587 * skipped, it means that that white space is wanted literally, and
17588 * is already in 'value'. Otherwise, need to translate the escape
17589 * into what it signifies. */
17590 if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) {
17591 const char * message;
17595 case 'w': namedclass = ANYOF_WORDCHAR; break;
17596 case 'W': namedclass = ANYOF_NWORDCHAR; break;
17597 case 's': namedclass = ANYOF_SPACE; break;
17598 case 'S': namedclass = ANYOF_NSPACE; break;
17599 case 'd': namedclass = ANYOF_DIGIT; break;
17600 case 'D': namedclass = ANYOF_NDIGIT; break;
17601 case 'v': namedclass = ANYOF_VERTWS; break;
17602 case 'V': namedclass = ANYOF_NVERTWS; break;
17603 case 'h': namedclass = ANYOF_HORIZWS; break;
17604 case 'H': namedclass = ANYOF_NHORIZWS; break;
17605 case 'N': /* Handle \N{NAME} in class */
17607 const char * const backslash_N_beg = RExC_parse - 2;
17610 if (! grok_bslash_N(pRExC_state,
17611 NULL, /* No regnode */
17612 &value, /* Yes single value */
17613 &cp_count, /* Multiple code pt count */
17619 if (*flagp & NEED_UTF8)
17620 FAIL("panic: grok_bslash_N set NEED_UTF8");
17622 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
17624 if (cp_count < 0) {
17625 vFAIL("\\N in a character class must be a named character: \\N{...}");
17627 else if (cp_count == 0) {
17628 ckWARNreg(RExC_parse,
17629 "Ignoring zero length \\N{} in character class");
17631 else { /* cp_count > 1 */
17632 assert(cp_count > 1);
17633 if (! RExC_in_multi_char_class) {
17634 if ( ! allow_mutiple_chars
17637 || *RExC_parse == '-')
17641 vFAIL("\\N{} here is restricted to one character");
17643 ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class");
17644 break; /* <value> contains the first code
17645 point. Drop out of the switch to
17649 SV * multi_char_N = newSVpvn(backslash_N_beg,
17650 RExC_parse - backslash_N_beg);
17652 = add_multi_match(multi_char_matches,
17657 } /* End of cp_count != 1 */
17659 /* This element should not be processed further in this
17662 value = save_value;
17663 prevvalue = save_prevvalue;
17664 continue; /* Back to top of loop to get next char */
17667 /* Here, is a single code point, and <value> contains it */
17668 unicode_range = TRUE; /* \N{} are Unicode */
17676 if (RExC_pm_flags & PMf_WILDCARD) {
17678 /* diag_listed_as: Use of %s is not allowed in Unicode
17679 property wildcard subpatterns in regex; marked by <--
17681 vFAIL3("Use of '\\%c%c' is not allowed in Unicode property"
17682 " wildcard subpatterns", (char) value, *(RExC_parse - 1));
17685 /* \p means they want Unicode semantics */
17686 REQUIRE_UNI_RULES(flagp, 0);
17688 if (RExC_parse >= RExC_end)
17689 vFAIL2("Empty \\%c", (U8)value);
17690 if (*RExC_parse == '{') {
17691 const U8 c = (U8)value;
17692 e = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
17695 vFAIL2("Missing right brace on \\%c{}", c);
17700 /* White space is allowed adjacent to the braces and after
17701 * any '^', even when not under /x */
17702 while (isSPACE(*RExC_parse)) {
17706 if (UCHARAT(RExC_parse) == '^') {
17708 /* toggle. (The rhs xor gets the single bit that
17709 * differs between P and p; the other xor inverts just
17711 value ^= 'P' ^ 'p';
17714 while (isSPACE(*RExC_parse)) {
17719 if (e == RExC_parse)
17720 vFAIL2("Empty \\%c{}", c);
17722 n = e - RExC_parse;
17723 while (isSPACE(*(RExC_parse + n - 1)))
17726 } /* The \p isn't immediately followed by a '{' */
17727 else if (! isALPHA(*RExC_parse)) {
17728 RExC_parse += (UTF)
17729 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
17731 vFAIL2("Character following \\%c must be '{' or a "
17732 "single-character Unicode property name",
17740 char* name = RExC_parse;
17742 /* Any message returned about expanding the definition */
17743 SV* msg = newSVpvs_flags("", SVs_TEMP);
17745 /* If set TRUE, the property is user-defined as opposed to
17746 * official Unicode */
17747 bool user_defined = FALSE;
17748 AV * strings = NULL;
17750 SV * prop_definition = parse_uniprop_string(
17751 name, n, UTF, FOLD,
17752 FALSE, /* This is compile-time */
17754 /* We can't defer this defn when
17755 * the full result is required in
17757 ! cBOOL(ret_invlist),
17764 if (SvCUR(msg)) { /* Assumes any error causes a msg */
17765 assert(prop_definition == NULL);
17766 RExC_parse = e + 1;
17767 if (SvUTF8(msg)) { /* msg being UTF-8 makes the whole
17768 thing so, or else the display is
17772 /* diag_listed_as: Can't find Unicode property definition "%s" in regex; marked by <-- HERE in m/%s/ */
17773 vFAIL2utf8f("%" UTF8f, UTF8fARG(SvUTF8(msg),
17774 SvCUR(msg), SvPVX(msg)));
17777 assert(prop_definition || strings);
17781 if (! prop_definition) {
17782 RExC_parse = e + 1;
17783 vFAIL("Unicode string properties are not implemented in (?[...])");
17787 "Using just the single character results"
17788 " returned by \\p{} in (?[...])");
17791 else if (! RExC_in_multi_char_class) {
17792 if (invert ^ (value == 'P')) {
17793 RExC_parse = e + 1;
17794 vFAIL("Inverting a character class which contains"
17795 " a multi-character sequence is illegal");
17798 /* For each multi-character string ... */
17799 while (av_tindex(strings) >= 0) {
17800 /* ... Each entry is itself an array of code
17802 AV * this_string = (AV *) av_shift( strings);
17803 STRLEN cp_count = av_tindex(this_string) + 1;
17804 SV * final = newSV(cp_count * 4);
17807 /* Create another string of sequences of \x{...} */
17808 while (av_tindex(this_string) >= 0) {
17809 SV * character = av_shift(this_string);
17810 UV cp = SvUV(character);
17813 REQUIRE_UTF8(flagp);
17815 Perl_sv_catpvf(aTHX_ final, "\\x{%" UVXf "}",
17817 SvREFCNT_dec_NN(character);
17819 SvREFCNT_dec_NN(this_string);
17821 /* And add that to the list of such things */
17823 = add_multi_match(multi_char_matches,
17828 SvREFCNT_dec_NN(strings);
17831 if (! prop_definition) { /* If we got only a string,
17832 this iteration didn't really
17833 find a character */
17836 else if (! is_invlist(prop_definition)) {
17838 /* Here, the definition isn't known, so we have gotten
17839 * returned a string that will be evaluated if and when
17840 * encountered at runtime. We add it to the list of
17841 * such properties, along with whether it should be
17842 * complemented or not */
17843 if (value == 'P') {
17844 sv_catpvs(listsv, "!");
17847 sv_catpvs(listsv, "+");
17849 sv_catsv(listsv, prop_definition);
17851 has_runtime_dependency |= HAS_USER_DEFINED_PROPERTY;
17853 /* We don't know yet what this matches, so have to flag
17855 anyof_flags |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
17858 assert (prop_definition && is_invlist(prop_definition));
17860 /* Here we do have the complete property definition
17862 * Temporary workaround for [perl #133136]. For this
17863 * precise input that is in the .t that is failing,
17864 * load utf8.pm, which is what the test wants, so that
17865 * that .t passes */
17866 if ( memEQs(RExC_start, e + 1 - RExC_start,
17868 && ! hv_common(GvHVn(PL_incgv),
17870 "utf8.pm", sizeof("utf8.pm") - 1,
17871 0, HV_FETCH_ISEXISTS, NULL, 0))
17873 require_pv("utf8.pm");
17876 if (! user_defined &&
17877 /* We warn on matching an above-Unicode code point
17878 * if the match would return true, except don't
17879 * warn for \p{All}, which has exactly one element
17881 (_invlist_contains_cp(prop_definition, 0x110000)
17882 && (! (_invlist_len(prop_definition) == 1
17883 && *invlist_array(prop_definition) == 0))))
17888 /* Invert if asking for the complement */
17889 if (value == 'P') {
17890 _invlist_union_complement_2nd(properties,
17895 _invlist_union(properties, prop_definition, &properties);
17900 RExC_parse = e + 1;
17901 namedclass = ANYOF_UNIPROP; /* no official name, but it's
17905 case 'n': value = '\n'; break;
17906 case 'r': value = '\r'; break;
17907 case 't': value = '\t'; break;
17908 case 'f': value = '\f'; break;
17909 case 'b': value = '\b'; break;
17910 case 'e': value = ESC_NATIVE; break;
17911 case 'a': value = '\a'; break;
17913 RExC_parse--; /* function expects to be pointed at the 'o' */
17914 if (! grok_bslash_o(&RExC_parse,
17920 cBOOL(range), /* MAX_UV allowed for range
17926 else if (message && TO_OUTPUT_WARNINGS(RExC_parse)) {
17927 warn_non_literal_string(RExC_parse, packed_warn, message);
17931 non_portable_endpoint++;
17935 RExC_parse--; /* function expects to be pointed at the 'x' */
17936 if (! grok_bslash_x(&RExC_parse,
17942 cBOOL(range), /* MAX_UV allowed for range
17948 else if (message && TO_OUTPUT_WARNINGS(RExC_parse)) {
17949 warn_non_literal_string(RExC_parse, packed_warn, message);
17953 non_portable_endpoint++;
17957 if (! grok_bslash_c(*RExC_parse, &grok_c_char, &message,
17960 /* going to die anyway; point to exact spot of
17962 RExC_parse += (UTF)
17963 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
17968 value = grok_c_char;
17970 if (message && TO_OUTPUT_WARNINGS(RExC_parse)) {
17971 warn_non_literal_string(RExC_parse, packed_warn, message);
17974 non_portable_endpoint++;
17976 case '0': case '1': case '2': case '3': case '4':
17977 case '5': case '6': case '7':
17979 /* Take 1-3 octal digits */
17980 I32 flags = PERL_SCAN_SILENT_ILLDIGIT
17981 | PERL_SCAN_NOTIFY_ILLDIGIT;
17982 numlen = (strict) ? 4 : 3;
17983 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
17984 RExC_parse += numlen;
17987 RExC_parse += (UTF)
17988 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
17990 vFAIL("Need exactly 3 octal digits");
17992 else if ( (flags & PERL_SCAN_NOTIFY_ILLDIGIT)
17993 && RExC_parse < RExC_end
17994 && isDIGIT(*RExC_parse)
17995 && ckWARN(WARN_REGEXP))
17997 reg_warn_non_literal_string(
17999 form_alien_digit_msg(8, numlen, RExC_parse,
18000 RExC_end, UTF, FALSE));
18004 non_portable_endpoint++;
18009 /* Allow \_ to not give an error */
18010 if (isWORDCHAR(value) && value != '_') {
18012 vFAIL2("Unrecognized escape \\%c in character class",
18016 ckWARN2reg(RExC_parse,
18017 "Unrecognized escape \\%c in character class passed through",
18022 } /* End of switch on char following backslash */
18023 } /* end of handling backslash escape sequences */
18025 /* Here, we have the current token in 'value' */
18027 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
18030 /* a bad range like a-\d, a-[:digit:]. The '-' is taken as a
18031 * literal, as is the character that began the false range, i.e.
18032 * the 'a' in the examples */
18034 const int w = (RExC_parse >= rangebegin)
18035 ? RExC_parse - rangebegin
18039 "False [] range \"%" UTF8f "\"",
18040 UTF8fARG(UTF, w, rangebegin));
18043 ckWARN2reg(RExC_parse,
18044 "False [] range \"%" UTF8f "\"",
18045 UTF8fARG(UTF, w, rangebegin));
18046 cp_list = add_cp_to_invlist(cp_list, '-');
18047 cp_foldable_list = add_cp_to_invlist(cp_foldable_list,
18051 range = 0; /* this was not a true range */
18052 element_count += 2; /* So counts for three values */
18055 classnum = namedclass_to_classnum(namedclass);
18057 if (LOC && namedclass < ANYOF_POSIXL_MAX
18058 #ifndef HAS_ISASCII
18059 && classnum != _CC_ASCII
18062 SV* scratch_list = NULL;
18064 /* What the Posix classes (like \w, [:space:]) match isn't
18065 * generally knowable under locale until actual match time. A
18066 * special node is used for these which has extra space for a
18067 * bitmap, with a bit reserved for each named class that is to
18068 * be matched against. (This isn't needed for \p{} and
18069 * pseudo-classes, as they are not affected by locale, and
18070 * hence are dealt with separately.) However, if a named class
18071 * and its complement are both present, then it matches
18072 * everything, and there is no runtime dependency. Odd numbers
18073 * are the complements of the next lower number, so xor works.
18074 * (Note that something like [\w\D] should match everything,
18075 * because \d should be a proper subset of \w. But rather than
18076 * trust that the locale is well behaved, we leave this to
18077 * runtime to sort out) */
18078 if (POSIXL_TEST(posixl, namedclass ^ 1)) {
18079 cp_list = _add_range_to_invlist(cp_list, 0, UV_MAX);
18080 POSIXL_ZERO(posixl);
18081 has_runtime_dependency &= ~HAS_L_RUNTIME_DEPENDENCY;
18082 anyof_flags &= ~ANYOF_MATCHES_POSIXL;
18083 continue; /* We could ignore the rest of the class, but
18084 best to parse it for any errors */
18086 else { /* Here, isn't the complement of any already parsed
18088 POSIXL_SET(posixl, namedclass);
18089 has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18090 anyof_flags |= ANYOF_MATCHES_POSIXL;
18092 /* The above-Latin1 characters are not subject to locale
18093 * rules. Just add them to the unconditionally-matched
18096 /* Get the list of the above-Latin1 code points this
18098 _invlist_intersection_maybe_complement_2nd(PL_AboveLatin1,
18099 PL_XPosix_ptrs[classnum],
18101 /* Odd numbers are complements,
18102 * like NDIGIT, NASCII, ... */
18103 namedclass % 2 != 0,
18105 /* Checking if 'cp_list' is NULL first saves an extra
18106 * clone. Its reference count will be decremented at the
18107 * next union, etc, or if this is the only instance, at the
18108 * end of the routine */
18110 cp_list = scratch_list;
18113 _invlist_union(cp_list, scratch_list, &cp_list);
18114 SvREFCNT_dec_NN(scratch_list);
18116 continue; /* Go get next character */
18121 /* Here, is not /l, or is a POSIX class for which /l doesn't
18122 * matter (or is a Unicode property, which is skipped here). */
18123 if (namedclass >= ANYOF_POSIXL_MAX) { /* If a special class */
18124 if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */
18126 /* Here, should be \h, \H, \v, or \V. None of /d, /i
18127 * nor /l make a difference in what these match,
18128 * therefore we just add what they match to cp_list. */
18129 if (classnum != _CC_VERTSPACE) {
18130 assert( namedclass == ANYOF_HORIZWS
18131 || namedclass == ANYOF_NHORIZWS);
18133 /* It turns out that \h is just a synonym for
18135 classnum = _CC_BLANK;
18138 _invlist_union_maybe_complement_2nd(
18140 PL_XPosix_ptrs[classnum],
18141 namedclass % 2 != 0, /* Complement if odd
18142 (NHORIZWS, NVERTWS)
18147 else if ( AT_LEAST_UNI_SEMANTICS
18148 || classnum == _CC_ASCII
18149 || (DEPENDS_SEMANTICS && ( classnum == _CC_DIGIT
18150 || classnum == _CC_XDIGIT)))
18152 /* We usually have to worry about /d affecting what POSIX
18153 * classes match, with special code needed because we won't
18154 * know until runtime what all matches. But there is no
18155 * extra work needed under /u and /a; and [:ascii:] is
18156 * unaffected by /d; and :digit: and :xdigit: don't have
18157 * runtime differences under /d. So we can special case
18158 * these, and avoid some extra work below, and at runtime.
18160 _invlist_union_maybe_complement_2nd(
18162 ((AT_LEAST_ASCII_RESTRICTED)
18163 ? PL_Posix_ptrs[classnum]
18164 : PL_XPosix_ptrs[classnum]),
18165 namedclass % 2 != 0,
18168 else { /* Garden variety class. If is NUPPER, NALPHA, ...
18169 complement and use nposixes */
18170 SV** posixes_ptr = namedclass % 2 == 0
18173 _invlist_union_maybe_complement_2nd(
18175 PL_XPosix_ptrs[classnum],
18176 namedclass % 2 != 0,
18180 } /* end of namedclass \blah */
18182 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
18184 /* If 'range' is set, 'value' is the ending of a range--check its
18185 * validity. (If value isn't a single code point in the case of a
18186 * range, we should have figured that out above in the code that
18187 * catches false ranges). Later, we will handle each individual code
18188 * point in the range. If 'range' isn't set, this could be the
18189 * beginning of a range, so check for that by looking ahead to see if
18190 * the next real character to be processed is the range indicator--the
18195 /* For unicode ranges, we have to test that the Unicode as opposed
18196 * to the native values are not decreasing. (Above 255, there is
18197 * no difference between native and Unicode) */
18198 if (unicode_range && prevvalue < 255 && value < 255) {
18199 if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) {
18200 goto backwards_range;
18205 if (prevvalue > value) /* b-a */ {
18210 w = RExC_parse - rangebegin;
18212 "Invalid [] range \"%" UTF8f "\"",
18213 UTF8fARG(UTF, w, rangebegin));
18214 NOT_REACHED; /* NOTREACHED */
18218 prevvalue = value; /* save the beginning of the potential range */
18219 if (! stop_at_1 /* Can't be a range if parsing just one thing */
18220 && *RExC_parse == '-')
18222 char* next_char_ptr = RExC_parse + 1;
18224 /* Get the next real char after the '-' */
18225 SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr);
18227 /* If the '-' is at the end of the class (just before the ']',
18228 * it is a literal minus; otherwise it is a range */
18229 if (next_char_ptr < RExC_end && *next_char_ptr != ']') {
18230 RExC_parse = next_char_ptr;
18232 /* a bad range like \w-, [:word:]- ? */
18233 if (namedclass > OOB_NAMEDCLASS) {
18234 if (strict || ckWARN(WARN_REGEXP)) {
18235 const int w = RExC_parse >= rangebegin
18236 ? RExC_parse - rangebegin
18239 vFAIL4("False [] range \"%*.*s\"",
18244 "False [] range \"%*.*s\"",
18248 cp_list = add_cp_to_invlist(cp_list, '-');
18251 range = 1; /* yeah, it's a range! */
18252 continue; /* but do it the next time */
18257 if (namedclass > OOB_NAMEDCLASS) {
18261 /* Here, we have a single value this time through the loop, and
18262 * <prevvalue> is the beginning of the range, if any; or <value> if
18265 /* non-Latin1 code point implies unicode semantics. */
18267 if (value > MAX_LEGAL_CP && ( value != UV_MAX
18268 || prevvalue > MAX_LEGAL_CP))
18270 vFAIL(form_cp_too_large_msg(16, NULL, 0, value));
18272 REQUIRE_UNI_RULES(flagp, 0);
18273 if ( ! silence_non_portable
18274 && UNICODE_IS_PERL_EXTENDED(value)
18275 && TO_OUTPUT_WARNINGS(RExC_parse))
18277 ckWARN2_non_literal_string(RExC_parse,
18278 packWARN(WARN_PORTABLE),
18279 PL_extended_cp_format,
18284 /* Ready to process either the single value, or the completed range.
18285 * For single-valued non-inverted ranges, we consider the possibility
18286 * of multi-char folds. (We made a conscious decision to not do this
18287 * for the other cases because it can often lead to non-intuitive
18288 * results. For example, you have the peculiar case that:
18289 * "s s" =~ /^[^\xDF]+$/i => Y
18290 * "ss" =~ /^[^\xDF]+$/i => N
18292 * See [perl #89750] */
18293 if (FOLD && allow_mutiple_chars && value == prevvalue) {
18294 if ( value == LATIN_SMALL_LETTER_SHARP_S
18295 || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
18298 /* Here <value> is indeed a multi-char fold. Get what it is */
18300 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
18303 UV folded = _to_uni_fold_flags(
18307 FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED
18308 ? FOLD_FLAGS_NOMIX_ASCII
18312 /* Here, <folded> should be the first character of the
18313 * multi-char fold of <value>, with <foldbuf> containing the
18314 * whole thing. But, if this fold is not allowed (because of
18315 * the flags), <fold> will be the same as <value>, and should
18316 * be processed like any other character, so skip the special
18318 if (folded != value) {
18320 /* Skip if we are recursed, currently parsing the class
18321 * again. Otherwise add this character to the list of
18322 * multi-char folds. */
18323 if (! RExC_in_multi_char_class) {
18324 STRLEN cp_count = utf8_length(foldbuf,
18325 foldbuf + foldlen);
18326 SV* multi_fold = sv_2mortal(newSVpvs(""));
18328 Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%" UVXf "}", value);
18331 = add_multi_match(multi_char_matches,
18337 /* This element should not be processed further in this
18340 value = save_value;
18341 prevvalue = save_prevvalue;
18347 if (strict && ckWARN(WARN_REGEXP)) {
18350 /* If the range starts above 255, everything is portable and
18351 * likely to be so for any forseeable character set, so don't
18353 if (unicode_range && non_portable_endpoint && prevvalue < 256) {
18354 vWARN(RExC_parse, "Both or neither range ends should be Unicode");
18356 else if (prevvalue != value) {
18358 /* Under strict, ranges that stop and/or end in an ASCII
18359 * printable should have each end point be a portable value
18360 * for it (preferably like 'A', but we don't warn if it is
18361 * a (portable) Unicode name or code point), and the range
18362 * must be all digits or all letters of the same case.
18363 * Otherwise, the range is non-portable and unclear as to
18364 * what it contains */
18365 if ( (isPRINT_A(prevvalue) || isPRINT_A(value))
18366 && ( non_portable_endpoint
18367 || ! ( (isDIGIT_A(prevvalue) && isDIGIT_A(value))
18368 || (isLOWER_A(prevvalue) && isLOWER_A(value))
18369 || (isUPPER_A(prevvalue) && isUPPER_A(value))
18371 vWARN(RExC_parse, "Ranges of ASCII printables should"
18372 " be some subset of \"0-9\","
18373 " \"A-Z\", or \"a-z\"");
18375 else if (prevvalue >= FIRST_NON_ASCII_DECIMAL_DIGIT) {
18376 SSize_t index_start;
18377 SSize_t index_final;
18379 /* But the nature of Unicode and languages mean we
18380 * can't do the same checks for above-ASCII ranges,
18381 * except in the case of digit ones. These should
18382 * contain only digits from the same group of 10. The
18383 * ASCII case is handled just above. Hence here, the
18384 * range could be a range of digits. First some
18385 * unlikely special cases. Grandfather in that a range
18386 * ending in 19DA (NEW TAI LUE THAM DIGIT ONE) is bad
18387 * if its starting value is one of the 10 digits prior
18388 * to it. This is because it is an alternate way of
18389 * writing 19D1, and some people may expect it to be in
18390 * that group. But it is bad, because it won't give
18391 * the expected results. In Unicode 5.2 it was
18392 * considered to be in that group (of 11, hence), but
18393 * this was fixed in the next version */
18395 if (UNLIKELY(value == 0x19DA && prevvalue >= 0x19D0)) {
18396 goto warn_bad_digit_range;
18398 else if (UNLIKELY( prevvalue >= 0x1D7CE
18399 && value <= 0x1D7FF))
18401 /* This is the only other case currently in Unicode
18402 * where the algorithm below fails. The code
18403 * points just above are the end points of a single
18404 * range containing only decimal digits. It is 5
18405 * different series of 0-9. All other ranges of
18406 * digits currently in Unicode are just a single
18407 * series. (And mktables will notify us if a later
18408 * Unicode version breaks this.)
18410 * If the range being checked is at most 9 long,
18411 * and the digit values represented are in
18412 * numerical order, they are from the same series.
18414 if ( value - prevvalue > 9
18415 || ((( value - 0x1D7CE) % 10)
18416 <= (prevvalue - 0x1D7CE) % 10))
18418 goto warn_bad_digit_range;
18423 /* For all other ranges of digits in Unicode, the
18424 * algorithm is just to check if both end points
18425 * are in the same series, which is the same range.
18427 index_start = _invlist_search(
18428 PL_XPosix_ptrs[_CC_DIGIT],
18431 /* Warn if the range starts and ends with a digit,
18432 * and they are not in the same group of 10. */
18433 if ( index_start >= 0
18434 && ELEMENT_RANGE_MATCHES_INVLIST(index_start)
18436 _invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
18437 value)) != index_start
18438 && index_final >= 0
18439 && ELEMENT_RANGE_MATCHES_INVLIST(index_final))
18441 warn_bad_digit_range:
18442 vWARN(RExC_parse, "Ranges of digits should be"
18443 " from the same group of"
18450 if ((! range || prevvalue == value) && non_portable_endpoint) {
18451 if (isPRINT_A(value)) {
18454 if (isBACKSLASHED_PUNCT(value)) {
18455 literal[d++] = '\\';
18457 literal[d++] = (char) value;
18458 literal[d++] = '\0';
18461 "\"%.*s\" is more clearly written simply as \"%s\"",
18462 (int) (RExC_parse - rangebegin),
18467 else if (isMNEMONIC_CNTRL(value)) {
18469 "\"%.*s\" is more clearly written simply as \"%s\"",
18470 (int) (RExC_parse - rangebegin),
18472 cntrl_to_mnemonic((U8) value)
18478 /* Deal with this element of the class */
18481 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18484 /* On non-ASCII platforms, for ranges that span all of 0..255, and ones
18485 * that don't require special handling, we can just add the range like
18486 * we do for ASCII platforms */
18487 if ((UNLIKELY(prevvalue == 0) && value >= 255)
18488 || ! (prevvalue < 256
18490 || (! non_portable_endpoint
18491 && ((isLOWER_A(prevvalue) && isLOWER_A(value))
18492 || (isUPPER_A(prevvalue)
18493 && isUPPER_A(value)))))))
18495 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18499 /* Here, requires special handling. This can be because it is a
18500 * range whose code points are considered to be Unicode, and so
18501 * must be individually translated into native, or because its a
18502 * subrange of 'A-Z' or 'a-z' which each aren't contiguous in
18503 * EBCDIC, but we have defined them to include only the "expected"
18504 * upper or lower case ASCII alphabetics. Subranges above 255 are
18505 * the same in native and Unicode, so can be added as a range */
18506 U8 start = NATIVE_TO_LATIN1(prevvalue);
18508 U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255;
18509 for (j = start; j <= end; j++) {
18510 cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j));
18513 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18519 range = 0; /* this range (if it was one) is done now */
18520 } /* End of loop through all the text within the brackets */
18522 if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) {
18523 output_posix_warnings(pRExC_state, posix_warnings);
18526 /* If anything in the class expands to more than one character, we have to
18527 * deal with them by building up a substitute parse string, and recursively
18528 * calling reg() on it, instead of proceeding */
18529 if (multi_char_matches) {
18530 SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
18533 char *save_end = RExC_end;
18534 char *save_parse = RExC_parse;
18535 char *save_start = RExC_start;
18536 Size_t constructed_prefix_len = 0; /* This gives the length of the
18537 constructed portion of the
18538 substitute parse. */
18539 bool first_time = TRUE; /* First multi-char occurrence doesn't get
18544 /* Only one level of recursion allowed */
18545 assert(RExC_copy_start_in_constructed == RExC_precomp);
18547 #if 0 /* Have decided not to deal with multi-char folds in inverted classes,
18548 because too confusing */
18550 sv_catpvs(substitute_parse, "(?:");
18554 /* Look at the longest strings first */
18555 for (cp_count = av_tindex_skip_len_mg(multi_char_matches);
18560 if (av_exists(multi_char_matches, cp_count)) {
18561 AV** this_array_ptr;
18564 this_array_ptr = (AV**) av_fetch(multi_char_matches,
18566 while ((this_sequence = av_pop(*this_array_ptr)) !=
18569 if (! first_time) {
18570 sv_catpvs(substitute_parse, "|");
18572 first_time = FALSE;
18574 sv_catpv(substitute_parse, SvPVX(this_sequence));
18579 /* If the character class contains anything else besides these
18580 * multi-character strings, have to include it in recursive parsing */
18581 if (element_count) {
18582 bool has_l_bracket = orig_parse > RExC_start && *(orig_parse - 1) == '[';
18584 sv_catpvs(substitute_parse, "|");
18585 if (has_l_bracket) { /* Add an [ if the original had one */
18586 sv_catpvs(substitute_parse, "[");
18588 constructed_prefix_len = SvCUR(substitute_parse);
18589 sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
18591 /* Put in a closing ']' to match any opening one, but not if going
18592 * off the end, as otherwise we are adding something that really
18594 if (has_l_bracket && RExC_parse < RExC_end) {
18595 sv_catpvs(substitute_parse, "]");
18599 sv_catpvs(substitute_parse, ")");
18602 /* This is a way to get the parse to skip forward a whole named
18603 * sequence instead of matching the 2nd character when it fails the
18605 sv_catpvs(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
18609 /* Set up the data structure so that any errors will be properly
18610 * reported. See the comments at the definition of
18611 * REPORT_LOCATION_ARGS for details */
18612 RExC_copy_start_in_input = (char *) orig_parse;
18613 RExC_start = RExC_parse = SvPV(substitute_parse, len);
18614 RExC_copy_start_in_constructed = RExC_start + constructed_prefix_len;
18615 RExC_end = RExC_parse + len;
18616 RExC_in_multi_char_class = 1;
18618 ret = reg(pRExC_state, 1, ®_flags, depth+1);
18620 *flagp |= reg_flags & (HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PARSE|NEED_UTF8);
18622 /* And restore so can parse the rest of the pattern */
18623 RExC_parse = save_parse;
18624 RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = save_start;
18625 RExC_end = save_end;
18626 RExC_in_multi_char_class = 0;
18627 SvREFCNT_dec_NN(multi_char_matches);
18631 /* If folding, we calculate all characters that could fold to or from the
18632 * ones already on the list */
18633 if (cp_foldable_list) {
18635 UV start, end; /* End points of code point ranges */
18637 SV* fold_intersection = NULL;
18640 /* Our calculated list will be for Unicode rules. For locale
18641 * matching, we have to keep a separate list that is consulted at
18642 * runtime only when the locale indicates Unicode rules (and we
18643 * don't include potential matches in the ASCII/Latin1 range, as
18644 * any code point could fold to any other, based on the run-time
18645 * locale). For non-locale, we just use the general list */
18647 use_list = &only_utf8_locale_list;
18650 use_list = &cp_list;
18653 /* Only the characters in this class that participate in folds need
18654 * be checked. Get the intersection of this class and all the
18655 * possible characters that are foldable. This can quickly narrow
18656 * down a large class */
18657 _invlist_intersection(PL_in_some_fold, cp_foldable_list,
18658 &fold_intersection);
18660 /* Now look at the foldable characters in this class individually */
18661 invlist_iterinit(fold_intersection);
18662 while (invlist_iternext(fold_intersection, &start, &end)) {
18666 /* Look at every character in the range */
18667 for (j = start; j <= end; j++) {
18668 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
18671 Size_t folds_count;
18673 const U32 * remaining_folds;
18677 /* Under /l, we don't know what code points below 256
18678 * fold to, except we do know the MICRO SIGN folds to
18679 * an above-255 character if the locale is UTF-8, so we
18680 * add it to the special list (in *use_list) Otherwise
18681 * we know now what things can match, though some folds
18682 * are valid under /d only if the target is UTF-8.
18683 * Those go in a separate list */
18684 if ( IS_IN_SOME_FOLD_L1(j)
18685 && ! (LOC && j != MICRO_SIGN))
18688 /* ASCII is always matched; non-ASCII is matched
18689 * only under Unicode rules (which could happen
18690 * under /l if the locale is a UTF-8 one */
18691 if (isASCII(j) || ! DEPENDS_SEMANTICS) {
18692 *use_list = add_cp_to_invlist(*use_list,
18693 PL_fold_latin1[j]);
18695 else if (j != PL_fold_latin1[j]) {
18696 upper_latin1_only_utf8_matches
18697 = add_cp_to_invlist(
18698 upper_latin1_only_utf8_matches,
18699 PL_fold_latin1[j]);
18703 if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j)
18704 && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
18706 add_above_Latin1_folds(pRExC_state,
18713 /* Here is an above Latin1 character. We don't have the
18714 * rules hard-coded for it. First, get its fold. This is
18715 * the simple fold, as the multi-character folds have been
18716 * handled earlier and separated out */
18717 folded = _to_uni_fold_flags(j, foldbuf, &foldlen,
18718 (ASCII_FOLD_RESTRICTED)
18719 ? FOLD_FLAGS_NOMIX_ASCII
18722 /* Single character fold of above Latin1. Add everything
18723 * in its fold closure to the list that this node should
18725 folds_count = _inverse_folds(folded, &first_fold,
18727 for (k = 0; k <= folds_count; k++) {
18728 UV c = (k == 0) /* First time through use itself */
18730 : (k == 1) /* 2nd time use, the first fold */
18733 /* Then the remaining ones */
18734 : remaining_folds[k-2];
18736 /* /aa doesn't allow folds between ASCII and non- */
18737 if (( ASCII_FOLD_RESTRICTED
18738 && (isASCII(c) != isASCII(j))))
18743 /* Folds under /l which cross the 255/256 boundary are
18744 * added to a separate list. (These are valid only
18745 * when the locale is UTF-8.) */
18746 if (c < 256 && LOC) {
18747 *use_list = add_cp_to_invlist(*use_list, c);
18751 if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
18753 cp_list = add_cp_to_invlist(cp_list, c);
18756 /* Similarly folds involving non-ascii Latin1
18757 * characters under /d are added to their list */
18758 upper_latin1_only_utf8_matches
18759 = add_cp_to_invlist(
18760 upper_latin1_only_utf8_matches,
18766 SvREFCNT_dec_NN(fold_intersection);
18769 /* Now that we have finished adding all the folds, there is no reason
18770 * to keep the foldable list separate */
18771 _invlist_union(cp_list, cp_foldable_list, &cp_list);
18772 SvREFCNT_dec_NN(cp_foldable_list);
18775 /* And combine the result (if any) with any inversion lists from posix
18776 * classes. The lists are kept separate up to now because we don't want to
18777 * fold the classes */
18778 if (simple_posixes) { /* These are the classes known to be unaffected by
18781 _invlist_union(cp_list, simple_posixes, &cp_list);
18782 SvREFCNT_dec_NN(simple_posixes);
18785 cp_list = simple_posixes;
18788 if (posixes || nposixes) {
18789 if (! DEPENDS_SEMANTICS) {
18791 /* For everything but /d, we can just add the current 'posixes' and
18792 * 'nposixes' to the main list */
18795 _invlist_union(cp_list, posixes, &cp_list);
18796 SvREFCNT_dec_NN(posixes);
18804 _invlist_union(cp_list, nposixes, &cp_list);
18805 SvREFCNT_dec_NN(nposixes);
18808 cp_list = nposixes;
18813 /* Under /d, things like \w match upper Latin1 characters only if
18814 * the target string is in UTF-8. But things like \W match all the
18815 * upper Latin1 characters if the target string is not in UTF-8.
18817 * Handle the case with something like \W separately */
18819 SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1, NULL);
18821 /* A complemented posix class matches all upper Latin1
18822 * characters if not in UTF-8. And it matches just certain
18823 * ones when in UTF-8. That means those certain ones are
18824 * matched regardless, so can just be added to the
18825 * unconditional list */
18827 _invlist_union(cp_list, nposixes, &cp_list);
18828 SvREFCNT_dec_NN(nposixes);
18832 cp_list = nposixes;
18835 /* Likewise for 'posixes' */
18836 _invlist_union(posixes, cp_list, &cp_list);
18837 SvREFCNT_dec(posixes);
18839 /* Likewise for anything else in the range that matched only
18841 if (upper_latin1_only_utf8_matches) {
18842 _invlist_union(cp_list,
18843 upper_latin1_only_utf8_matches,
18845 SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
18846 upper_latin1_only_utf8_matches = NULL;
18849 /* If we don't match all the upper Latin1 characters regardless
18850 * of UTF-8ness, we have to set a flag to match the rest when
18852 _invlist_subtract(only_non_utf8_list, cp_list,
18853 &only_non_utf8_list);
18854 if (_invlist_len(only_non_utf8_list) != 0) {
18855 anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
18857 SvREFCNT_dec_NN(only_non_utf8_list);
18860 /* Here there were no complemented posix classes. That means
18861 * the upper Latin1 characters in 'posixes' match only when the
18862 * target string is in UTF-8. So we have to add them to the
18863 * list of those types of code points, while adding the
18864 * remainder to the unconditional list.
18866 * First calculate what they are */
18867 SV* nonascii_but_latin1_properties = NULL;
18868 _invlist_intersection(posixes, PL_UpperLatin1,
18869 &nonascii_but_latin1_properties);
18871 /* And add them to the final list of such characters. */
18872 _invlist_union(upper_latin1_only_utf8_matches,
18873 nonascii_but_latin1_properties,
18874 &upper_latin1_only_utf8_matches);
18876 /* Remove them from what now becomes the unconditional list */
18877 _invlist_subtract(posixes, nonascii_but_latin1_properties,
18880 /* And add those unconditional ones to the final list */
18882 _invlist_union(cp_list, posixes, &cp_list);
18883 SvREFCNT_dec_NN(posixes);
18890 SvREFCNT_dec(nonascii_but_latin1_properties);
18892 /* Get rid of any characters from the conditional list that we
18893 * now know are matched unconditionally, which may make that
18895 _invlist_subtract(upper_latin1_only_utf8_matches,
18897 &upper_latin1_only_utf8_matches);
18898 if (_invlist_len(upper_latin1_only_utf8_matches) == 0) {
18899 SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
18900 upper_latin1_only_utf8_matches = NULL;
18906 /* And combine the result (if any) with any inversion list from properties.
18907 * The lists are kept separate up to now so that we can distinguish the two
18908 * in regards to matching above-Unicode. A run-time warning is generated
18909 * if a Unicode property is matched against a non-Unicode code point. But,
18910 * we allow user-defined properties to match anything, without any warning,
18911 * and we also suppress the warning if there is a portion of the character
18912 * class that isn't a Unicode property, and which matches above Unicode, \W
18913 * or [\x{110000}] for example.
18914 * (Note that in this case, unlike the Posix one above, there is no
18915 * <upper_latin1_only_utf8_matches>, because having a Unicode property
18916 * forces Unicode semantics */
18920 /* If it matters to the final outcome, see if a non-property
18921 * component of the class matches above Unicode. If so, the
18922 * warning gets suppressed. This is true even if just a single
18923 * such code point is specified, as, though not strictly correct if
18924 * another such code point is matched against, the fact that they
18925 * are using above-Unicode code points indicates they should know
18926 * the issues involved */
18928 warn_super = ! (invert
18929 ^ (invlist_highest(cp_list) > PERL_UNICODE_MAX));
18932 _invlist_union(properties, cp_list, &cp_list);
18933 SvREFCNT_dec_NN(properties);
18936 cp_list = properties;
18941 |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
18943 /* Because an ANYOF node is the only one that warns, this node
18944 * can't be optimized into something else */
18945 optimizable = FALSE;
18949 /* Here, we have calculated what code points should be in the character
18952 * Now we can see about various optimizations. Fold calculation (which we
18953 * did above) needs to take place before inversion. Otherwise /[^k]/i
18954 * would invert to include K, which under /i would match k, which it
18955 * shouldn't. Therefore we can't invert folded locale now, as it won't be
18956 * folded until runtime */
18958 /* If we didn't do folding, it's because some information isn't available
18959 * until runtime; set the run-time fold flag for these We know to set the
18960 * flag if we have a non-NULL list for UTF-8 locales, or the class matches
18961 * at least one 0-255 range code point */
18964 /* Some things on the list might be unconditionally included because of
18965 * other components. Remove them, and clean up the list if it goes to
18967 if (only_utf8_locale_list && cp_list) {
18968 _invlist_subtract(only_utf8_locale_list, cp_list,
18969 &only_utf8_locale_list);
18971 if (_invlist_len(only_utf8_locale_list) == 0) {
18972 SvREFCNT_dec_NN(only_utf8_locale_list);
18973 only_utf8_locale_list = NULL;
18976 if ( only_utf8_locale_list
18977 || (cp_list && ( _invlist_contains_cp(cp_list, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE)
18978 || _invlist_contains_cp(cp_list, LATIN_SMALL_LETTER_DOTLESS_I))))
18980 has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18983 | ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
18985 else if (cp_list && invlist_lowest(cp_list) < 256) {
18986 /* If nothing is below 256, has no locale dependency; otherwise it
18988 anyof_flags |= ANYOFL_FOLD;
18989 has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18992 else if ( DEPENDS_SEMANTICS
18993 && ( upper_latin1_only_utf8_matches
18994 || (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)))
18996 RExC_seen_d_op = TRUE;
18997 has_runtime_dependency |= HAS_D_RUNTIME_DEPENDENCY;
19000 /* Optimize inverted patterns (e.g. [^a-z]) when everything is known at
19004 && ! has_runtime_dependency)
19006 _invlist_invert(cp_list);
19008 /* Clear the invert flag since have just done it here */
19012 /* All possible optimizations below still have these characteristics.
19013 * (Multi-char folds aren't SIMPLE, but they don't get this far in this
19015 *flagp |= HASWIDTH|SIMPLE;
19018 *ret_invlist = cp_list;
19020 return (cp_list) ? RExC_emit : 0;
19023 if (anyof_flags & ANYOF_LOCALE_FLAGS) {
19024 RExC_contains_locale = 1;
19027 /* Some character classes are equivalent to other nodes. Such nodes take
19028 * up less room, and some nodes require fewer operations to execute, than
19029 * ANYOF nodes. EXACTish nodes may be joinable with adjacent nodes to
19030 * improve efficiency. */
19033 PERL_UINT_FAST8_T i;
19034 UV partial_cp_count = 0;
19035 UV start[MAX_FOLD_FROMS+1] = { 0 }; /* +1 for the folded-to char */
19036 UV end[MAX_FOLD_FROMS+1] = { 0 };
19037 bool single_range = FALSE;
19039 if (cp_list) { /* Count the code points in enough ranges that we would
19040 see all the ones possible in any fold in this version
19043 invlist_iterinit(cp_list);
19044 for (i = 0; i <= MAX_FOLD_FROMS; i++) {
19045 if (! invlist_iternext(cp_list, &start[i], &end[i])) {
19048 partial_cp_count += end[i] - start[i] + 1;
19052 single_range = TRUE;
19054 invlist_iterfinish(cp_list);
19057 /* If we know at compile time that this matches every possible code
19058 * point, any run-time dependencies don't matter */
19059 if (start[0] == 0 && end[0] == UV_MAX) {
19061 ret = reganode(pRExC_state, OPFAIL, 0);
19064 ret = reg_node(pRExC_state, SANY);
19070 /* Similarly, for /l posix classes, if both a class and its
19071 * complement match, any run-time dependencies don't matter */
19073 for (namedclass = 0; namedclass < ANYOF_POSIXL_MAX;
19076 if ( POSIXL_TEST(posixl, namedclass) /* class */
19077 && POSIXL_TEST(posixl, namedclass + 1)) /* its complement */
19080 ret = reganode(pRExC_state, OPFAIL, 0);
19083 ret = reg_node(pRExC_state, SANY);
19090 /* For well-behaved locales, some classes are subsets of others,
19091 * so complementing the subset and including the non-complemented
19092 * superset should match everything, like [\D[:alnum:]], and
19093 * [[:^alpha:][:alnum:]], but some implementations of locales are
19094 * buggy, and khw thinks its a bad idea to have optimization change
19095 * behavior, even if it avoids an OS bug in a given case */
19097 #define isSINGLE_BIT_SET(n) isPOWER_OF_2(n)
19099 /* If is a single posix /l class, can optimize to just that op.
19100 * Such a node will not match anything in the Latin1 range, as that
19101 * is not determinable until runtime, but will match whatever the
19102 * class does outside that range. (Note that some classes won't
19103 * match anything outside the range, like [:ascii:]) */
19104 if ( isSINGLE_BIT_SET(posixl)
19105 && (partial_cp_count == 0 || start[0] > 255))
19108 SV * class_above_latin1 = NULL;
19109 bool already_inverted;
19110 bool are_equivalent;
19112 /* Compute which bit is set, which is the same thing as, e.g.,
19113 * ANYOF_CNTRL. From
19114 * https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn
19116 static const int MultiplyDeBruijnBitPosition2[32] =
19118 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
19119 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
19122 namedclass = MultiplyDeBruijnBitPosition2[(posixl
19123 * 0x077CB531U) >> 27];
19124 classnum = namedclass_to_classnum(namedclass);
19126 /* The named classes are such that the inverted number is one
19127 * larger than the non-inverted one */
19128 already_inverted = namedclass
19129 - classnum_to_namedclass(classnum);
19131 /* Create an inversion list of the official property, inverted
19132 * if the constructed node list is inverted, and restricted to
19133 * only the above latin1 code points, which are the only ones
19134 * known at compile time */
19135 _invlist_intersection_maybe_complement_2nd(
19137 PL_XPosix_ptrs[classnum],
19139 &class_above_latin1);
19140 are_equivalent = _invlistEQ(class_above_latin1, cp_list,
19142 SvREFCNT_dec_NN(class_above_latin1);
19144 if (are_equivalent) {
19146 /* Resolve the run-time inversion flag with this possibly
19147 * inverted class */
19148 invert = invert ^ already_inverted;
19150 ret = reg_node(pRExC_state,
19151 POSIXL + invert * (NPOSIXL - POSIXL));
19152 FLAGS(REGNODE_p(ret)) = classnum;
19158 /* khw can't think of any other possible transformation involving
19160 if (has_runtime_dependency & HAS_USER_DEFINED_PROPERTY) {
19164 if (! has_runtime_dependency) {
19166 /* If the list is empty, nothing matches. This happens, for
19167 * example, when a Unicode property that doesn't match anything is
19168 * the only element in the character class (perluniprops.pod notes
19169 * such properties). */
19170 if (partial_cp_count == 0) {
19172 ret = reg_node(pRExC_state, SANY);
19175 ret = reganode(pRExC_state, OPFAIL, 0);
19181 /* If matches everything but \n */
19182 if ( start[0] == 0 && end[0] == '\n' - 1
19183 && start[1] == '\n' + 1 && end[1] == UV_MAX)
19186 ret = reg_node(pRExC_state, REG_ANY);
19192 /* Next see if can optimize classes that contain just a few code points
19193 * into an EXACTish node. The reason to do this is to let the
19194 * optimizer join this node with adjacent EXACTish ones, and ANYOF
19195 * nodes require conversion to code point from UTF-8.
19197 * An EXACTFish node can be generated even if not under /i, and vice
19198 * versa. But care must be taken. An EXACTFish node has to be such
19199 * that it only matches precisely the code points in the class, but we
19200 * want to generate the least restrictive one that does that, to
19201 * increase the odds of being able to join with an adjacent node. For
19202 * example, if the class contains [kK], we have to make it an EXACTFAA
19203 * node to prevent the KELVIN SIGN from matching. Whether we are under
19204 * /i or not is irrelevant in this case. Less obvious is the pattern
19205 * qr/[\x{02BC}]n/i. U+02BC is MODIFIER LETTER APOSTROPHE. That is
19206 * supposed to match the single character U+0149 LATIN SMALL LETTER N
19207 * PRECEDED BY APOSTROPHE. And so even though there is no simple fold
19208 * that includes \X{02BC}, there is a multi-char fold that does, and so
19209 * the node generated for it must be an EXACTFish one. On the other
19210 * hand qr/:/i should generate a plain EXACT node since the colon
19211 * participates in no fold whatsoever, and having it EXACT tells the
19212 * optimizer the target string cannot match unless it has a colon in
19218 /* Only try if there are no more code points in the class than
19219 * in the max possible fold */
19220 && inRANGE(partial_cp_count, 1, MAX_FOLD_FROMS + 1))
19222 if (partial_cp_count == 1 && ! upper_latin1_only_utf8_matches)
19224 /* We can always make a single code point class into an
19225 * EXACTish node. */
19229 /* Here is /l: Use EXACTL, except if there is a fold not
19230 * known until runtime so shows as only a single code point
19231 * here. For code points above 255, we know which can
19232 * cause problems by having a potential fold to the Latin1
19235 || ( start[0] > 255
19236 && ! is_PROBLEMATIC_LOCALE_FOLD_cp(start[0])))
19244 else if (! FOLD) { /* Not /l and not /i */
19245 op = (start[0] < 256) ? EXACT : EXACT_REQ8;
19247 else if (start[0] < 256) { /* /i, not /l, and the code point is
19250 /* Under /i, it gets a little tricky. A code point that
19251 * doesn't participate in a fold should be an EXACT node.
19252 * We know this one isn't the result of a simple fold, or
19253 * there'd be more than one code point in the list, but it
19254 * could be part of a multi- character fold. In that case
19255 * we better not create an EXACT node, as we would wrongly
19256 * be telling the optimizer that this code point must be in
19257 * the target string, and that is wrong. This is because
19258 * if the sequence around this code point forms a
19259 * multi-char fold, what needs to be in the string could be
19260 * the code point that folds to the sequence.
19262 * This handles the case of below-255 code points, as we
19263 * have an easy look up for those. The next clause handles
19264 * the above-256 one */
19265 op = IS_IN_SOME_FOLD_L1(start[0])
19269 else { /* /i, larger code point. Since we are under /i, and
19270 have just this code point, we know that it can't
19271 fold to something else, so PL_InMultiCharFold
19273 op = _invlist_contains_cp(PL_InMultiCharFold,
19281 else if ( ! (has_runtime_dependency & ~HAS_D_RUNTIME_DEPENDENCY)
19282 && _invlist_contains_cp(PL_in_some_fold, start[0]))
19284 /* Here, the only runtime dependency, if any, is from /d, and
19285 * the class matches more than one code point, and the lowest
19286 * code point participates in some fold. It might be that the
19287 * other code points are /i equivalent to this one, and hence
19288 * they would representable by an EXACTFish node. Above, we
19289 * eliminated classes that contain too many code points to be
19290 * EXACTFish, with the test for MAX_FOLD_FROMS
19292 * First, special case the ASCII fold pairs, like 'B' and 'b'.
19293 * We do this because we have EXACTFAA at our disposal for the
19295 if (partial_cp_count == 2 && isASCII(start[0])) {
19297 /* The only ASCII characters that participate in folds are
19299 assert(isALPHA(start[0]));
19300 if ( end[0] == start[0] /* First range is a single
19301 character, so 2nd exists */
19302 && isALPHA_FOLD_EQ(start[0], start[1]))
19305 /* Here, is part of an ASCII fold pair */
19307 if ( ASCII_FOLD_RESTRICTED
19308 || HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(start[0]))
19310 /* If the second clause just above was true, it
19311 * means we can't be under /i, or else the list
19312 * would have included more than this fold pair.
19313 * Therefore we have to exclude the possibility of
19314 * whatever else it is that folds to these, by
19315 * using EXACTFAA */
19318 else if (HAS_NONLATIN1_FOLD_CLOSURE(start[0])) {
19320 /* Here, there's no simple fold that start[0] is part
19321 * of, but there is a multi-character one. If we
19322 * are not under /i, we want to exclude that
19323 * possibility; if under /i, we want to include it
19325 op = (FOLD) ? EXACTFU : EXACTFAA;
19329 /* Here, the only possible fold start[0] particpates in
19330 * is with start[1]. /i or not isn't relevant */
19334 value = toFOLD(start[0]);
19337 else if ( ! upper_latin1_only_utf8_matches
19338 || ( _invlist_len(upper_latin1_only_utf8_matches)
19341 invlist_highest(upper_latin1_only_utf8_matches)]
19344 /* Here, the smallest character is non-ascii or there are
19345 * more than 2 code points matched by this node. Also, we
19346 * either don't have /d UTF-8 dependent matches, or if we
19347 * do, they look like they could be a single character that
19348 * is the fold of the lowest one in the always-match list.
19349 * This test quickly excludes most of the false positives
19350 * when there are /d UTF-8 depdendent matches. These are
19351 * like LATIN CAPITAL LETTER A WITH GRAVE matching LATIN
19352 * SMALL LETTER A WITH GRAVE iff the target string is
19353 * UTF-8. (We don't have to worry above about exceeding
19354 * the array bounds of PL_fold_latin1[] because any code
19355 * point in 'upper_latin1_only_utf8_matches' is below 256.)
19357 * EXACTFAA would apply only to pairs (hence exactly 2 code
19358 * points) in the ASCII range, so we can't use it here to
19359 * artificially restrict the fold domain, so we check if
19360 * the class does or does not match some EXACTFish node.
19361 * Further, if we aren't under /i, and the folded-to
19362 * character is part of a multi-character fold, we can't do
19363 * this optimization, as the sequence around it could be
19364 * that multi-character fold, and we don't here know the
19365 * context, so we have to assume it is that multi-char
19366 * fold, to prevent potential bugs.
19368 * To do the general case, we first find the fold of the
19369 * lowest code point (which may be higher than the lowest
19370 * one), then find everything that folds to it. (The data
19371 * structure we have only maps from the folded code points,
19372 * so we have to do the earlier step.) */
19375 U8 foldbuf[UTF8_MAXBYTES_CASE];
19376 UV folded = _to_uni_fold_flags(start[0],
19377 foldbuf, &foldlen, 0);
19379 const U32 * remaining_folds;
19380 Size_t folds_to_this_cp_count = _inverse_folds(
19384 Size_t folds_count = folds_to_this_cp_count + 1;
19385 SV * fold_list = _new_invlist(folds_count);
19388 /* If there are UTF-8 dependent matches, create a temporary
19389 * list of what this node matches, including them. */
19390 SV * all_cp_list = NULL;
19391 SV ** use_this_list = &cp_list;
19393 if (upper_latin1_only_utf8_matches) {
19394 all_cp_list = _new_invlist(0);
19395 use_this_list = &all_cp_list;
19396 _invlist_union(cp_list,
19397 upper_latin1_only_utf8_matches,
19401 /* Having gotten everything that participates in the fold
19402 * containing the lowest code point, we turn that into an
19403 * inversion list, making sure everything is included. */
19404 fold_list = add_cp_to_invlist(fold_list, start[0]);
19405 fold_list = add_cp_to_invlist(fold_list, folded);
19406 if (folds_to_this_cp_count > 0) {
19407 fold_list = add_cp_to_invlist(fold_list, first_fold);
19408 for (i = 0; i + 1 < folds_to_this_cp_count; i++) {
19409 fold_list = add_cp_to_invlist(fold_list,
19410 remaining_folds[i]);
19414 /* If the fold list is identical to what's in this ANYOF
19415 * node, the node can be represented by an EXACTFish one
19417 if (_invlistEQ(*use_this_list, fold_list,
19418 0 /* Don't complement */ )
19421 /* But, we have to be careful, as mentioned above.
19422 * Just the right sequence of characters could match
19423 * this if it is part of a multi-character fold. That
19424 * IS what we want if we are under /i. But it ISN'T
19425 * what we want if not under /i, as it could match when
19426 * it shouldn't. So, when we aren't under /i and this
19427 * character participates in a multi-char fold, we
19428 * don't optimize into an EXACTFish node. So, for each
19429 * case below we have to check if we are folding
19430 * and if not, if it is not part of a multi-char fold.
19432 if (start[0] > 255) { /* Highish code point */
19433 if (FOLD || ! _invlist_contains_cp(
19434 PL_InMultiCharFold, folded))
19438 : (ASCII_FOLD_RESTRICTED)
19443 } /* Below, the lowest code point < 256 */
19446 && DEPENDS_SEMANTICS)
19447 { /* An EXACTF node containing a single character
19448 's', can be an EXACTFU if it doesn't get
19449 joined with an adjacent 's' */
19450 op = EXACTFU_S_EDGE;
19454 || ! HAS_NONLATIN1_FOLD_CLOSURE(start[0]))
19456 if (upper_latin1_only_utf8_matches) {
19459 /* We can't use the fold, as that only matches
19463 else if ( UNLIKELY(start[0] == MICRO_SIGN)
19465 { /* EXACTFUP is a special node for this
19467 op = (ASCII_FOLD_RESTRICTED)
19470 value = MICRO_SIGN;
19472 else if ( ASCII_FOLD_RESTRICTED
19473 && ! isASCII(start[0]))
19474 { /* For ASCII under /iaa, we can use EXACTFU
19486 SvREFCNT_dec_NN(fold_list);
19487 SvREFCNT_dec(all_cp_list);
19494 /* Here, we have calculated what EXACTish node to use. Have to
19495 * convert to UTF-8 if not already there */
19498 SvREFCNT_dec(cp_list);;
19499 REQUIRE_UTF8(flagp);
19502 /* This is a kludge to the special casing issues with this
19503 * ligature under /aa. FB05 should fold to FB06, but the
19504 * call above to _to_uni_fold_flags() didn't find this, as
19505 * it didn't use the /aa restriction in order to not miss
19506 * other folds that would be affected. This is the only
19507 * instance likely to ever be a problem in all of Unicode.
19508 * So special case it. */
19509 if ( value == LATIN_SMALL_LIGATURE_LONG_S_T
19510 && ASCII_FOLD_RESTRICTED)
19512 value = LATIN_SMALL_LIGATURE_ST;
19516 len = (UTF) ? UVCHR_SKIP(value) : 1;
19518 ret = regnode_guts(pRExC_state, op, len, "exact");
19519 FILL_NODE(ret, op);
19520 RExC_emit += 1 + STR_SZ(len);
19521 setSTR_LEN(REGNODE_p(ret), len);
19523 *STRINGs(REGNODE_p(ret)) = (U8) value;
19526 uvchr_to_utf8((U8 *) STRINGs(REGNODE_p(ret)), value);
19532 if (! has_runtime_dependency) {
19534 /* See if this can be turned into an ANYOFM node. Think about the
19535 * bit patterns in two different bytes. In some positions, the
19536 * bits in each will be 1; and in other positions both will be 0;
19537 * and in some positions the bit will be 1 in one byte, and 0 in
19538 * the other. Let 'n' be the number of positions where the bits
19539 * differ. We create a mask which has exactly 'n' 0 bits, each in
19540 * a position where the two bytes differ. Now take the set of all
19541 * bytes that when ANDed with the mask yield the same result. That
19542 * set has 2**n elements, and is representable by just two 8 bit
19543 * numbers: the result and the mask. Importantly, matching the set
19544 * can be vectorized by creating a word full of the result bytes,
19545 * and a word full of the mask bytes, yielding a significant speed
19546 * up. Here, see if this node matches such a set. As a concrete
19547 * example consider [01], and the byte representing '0' which is
19548 * 0x30 on ASCII machines. It has the bits 0011 0000. Take the
19549 * mask 1111 1110. If we AND 0x31 and 0x30 with that mask we get
19550 * 0x30. Any other bytes ANDed yield something else. So [01],
19551 * which is a common usage, is optimizable into ANYOFM, and can
19552 * benefit from the speed up. We can only do this on UTF-8
19553 * invariant bytes, because they have the same bit patterns under
19555 PERL_UINT_FAST8_T inverted = 0;
19557 const PERL_UINT_FAST8_T max_permissible = 0xFF;
19559 const PERL_UINT_FAST8_T max_permissible = 0x7F;
19561 /* If doesn't fit the criteria for ANYOFM, invert and try again.
19562 * If that works we will instead later generate an NANYOFM, and
19563 * invert back when through */
19564 if (invlist_highest(cp_list) > max_permissible) {
19565 _invlist_invert(cp_list);
19569 if (invlist_highest(cp_list) <= max_permissible) {
19570 UV this_start, this_end;
19571 UV lowest_cp = UV_MAX; /* init'ed to suppress compiler warn */
19572 U8 bits_differing = 0;
19573 Size_t full_cp_count = 0;
19574 bool first_time = TRUE;
19576 /* Go through the bytes and find the bit positions that differ
19578 invlist_iterinit(cp_list);
19579 while (invlist_iternext(cp_list, &this_start, &this_end)) {
19580 unsigned int i = this_start;
19583 if (! UVCHR_IS_INVARIANT(i)) {
19587 first_time = FALSE;
19588 lowest_cp = this_start;
19590 /* We have set up the code point to compare with.
19591 * Don't compare it with itself */
19595 /* Find the bit positions that differ from the lowest code
19596 * point in the node. Keep track of all such positions by
19598 for (; i <= this_end; i++) {
19599 if (! UVCHR_IS_INVARIANT(i)) {
19603 bits_differing |= i ^ lowest_cp;
19606 full_cp_count += this_end - this_start + 1;
19609 /* At the end of the loop, we count how many bits differ from
19610 * the bits in lowest code point, call the count 'd'. If the
19611 * set we found contains 2**d elements, it is the closure of
19612 * all code points that differ only in those bit positions. To
19613 * convince yourself of that, first note that the number in the
19614 * closure must be a power of 2, which we test for. The only
19615 * way we could have that count and it be some differing set,
19616 * is if we got some code points that don't differ from the
19617 * lowest code point in any position, but do differ from each
19618 * other in some other position. That means one code point has
19619 * a 1 in that position, and another has a 0. But that would
19620 * mean that one of them differs from the lowest code point in
19621 * that position, which possibility we've already excluded. */
19622 if ( (inverted || full_cp_count > 1)
19623 && full_cp_count == 1U << PL_bitcount[bits_differing])
19627 op = ANYOFM + inverted;;
19629 /* We need to make the bits that differ be 0's */
19630 ANYOFM_mask = ~ bits_differing; /* This goes into FLAGS */
19632 /* The argument is the lowest code point */
19633 ret = reganode(pRExC_state, op, lowest_cp);
19634 FLAGS(REGNODE_p(ret)) = ANYOFM_mask;
19638 invlist_iterfinish(cp_list);
19642 _invlist_invert(cp_list);
19649 /* XXX We could create an ANYOFR_LOW node here if we saved above if
19650 * all were invariants, it wasn't inverted, and there is a single
19651 * range. This would be faster than some of the posix nodes we
19652 * create below like /\d/a, but would be twice the size. Without
19653 * having actually measured the gain, khw doesn't think the
19654 * tradeoff is really worth it */
19657 if (! (anyof_flags & ANYOF_LOCALE_FLAGS)) {
19658 PERL_UINT_FAST8_T type;
19659 SV * intersection = NULL;
19660 SV* d_invlist = NULL;
19662 /* See if this matches any of the POSIX classes. The POSIXA and
19663 * POSIXD ones are about the same speed as ANYOF ops, but take less
19664 * room; the ones that have above-Latin1 code point matches are
19665 * somewhat faster than ANYOF. */
19667 for (type = POSIXA; type >= POSIXD; type--) {
19670 if (type == POSIXL) { /* But not /l posix classes */
19674 for (posix_class = 0;
19675 posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC;
19678 SV** our_code_points = &cp_list;
19679 SV** official_code_points;
19682 if (type == POSIXA) {
19683 official_code_points = &PL_Posix_ptrs[posix_class];
19686 official_code_points = &PL_XPosix_ptrs[posix_class];
19689 /* Skip non-existent classes of this type. e.g. \v only
19690 * has an entry in PL_XPosix_ptrs */
19691 if (! *official_code_points) {
19695 /* Try both the regular class, and its inversion */
19696 for (try_inverted = 0; try_inverted < 2; try_inverted++) {
19697 bool this_inverted = invert ^ try_inverted;
19699 if (type != POSIXD) {
19701 /* This class that isn't /d can't match if we have
19702 * /d dependencies */
19703 if (has_runtime_dependency
19704 & HAS_D_RUNTIME_DEPENDENCY)
19709 else /* is /d */ if (! this_inverted) {
19711 /* /d classes don't match anything non-ASCII below
19712 * 256 unconditionally (which cp_list contains) */
19713 _invlist_intersection(cp_list, PL_UpperLatin1,
19715 if (_invlist_len(intersection) != 0) {
19719 SvREFCNT_dec(d_invlist);
19720 d_invlist = invlist_clone(cp_list, NULL);
19722 /* But under UTF-8 it turns into using /u rules.
19723 * Add the things it matches under these conditions
19724 * so that we check below that these are identical
19725 * to what the tested class should match */
19726 if (upper_latin1_only_utf8_matches) {
19729 upper_latin1_only_utf8_matches,
19732 our_code_points = &d_invlist;
19734 else { /* POSIXD, inverted. If this doesn't have this
19735 flag set, it isn't /d. */
19736 if (! (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
19740 our_code_points = &cp_list;
19743 /* Here, have weeded out some things. We want to see
19744 * if the list of characters this node contains
19745 * ('*our_code_points') precisely matches those of the
19746 * class we are currently checking against
19747 * ('*official_code_points'). */
19748 if (_invlistEQ(*our_code_points,
19749 *official_code_points,
19752 /* Here, they precisely match. Optimize this ANYOF
19753 * node into its equivalent POSIX one of the
19754 * correct type, possibly inverted */
19755 ret = reg_node(pRExC_state, (try_inverted)
19759 FLAGS(REGNODE_p(ret)) = posix_class;
19760 SvREFCNT_dec(d_invlist);
19761 SvREFCNT_dec(intersection);
19767 SvREFCNT_dec(d_invlist);
19768 SvREFCNT_dec(intersection);
19771 /* If it is a single contiguous range, ANYOFR is an efficient regnode,
19772 * both in size and speed. Currently, a 20 bit range base (smallest
19773 * code point in the range), and a 12 bit maximum delta are packed into
19774 * a 32 bit word. This allows for using it on all of the Unicode code
19775 * points except for the highest plane, which is only for private use
19776 * code points. khw doubts that a bigger delta is likely in real world
19779 && ! has_runtime_dependency
19780 && anyof_flags == 0
19781 && start[0] < (1 << ANYOFR_BASE_BITS)
19782 && end[0] - start[0]
19783 < ((1U << (sizeof(((struct regnode_1 *)NULL)->arg1)
19784 * CHARBITS - ANYOFR_BASE_BITS))))
19787 U8 low_utf8[UTF8_MAXBYTES+1];
19788 U8 high_utf8[UTF8_MAXBYTES+1];
19790 ret = reganode(pRExC_state, ANYOFR,
19791 (start[0] | (end[0] - start[0]) << ANYOFR_BASE_BITS));
19793 /* Place the lowest UTF-8 start byte in the flags field, so as to
19794 * allow efficient ruling out at run time of many possible inputs.
19796 (void) uvchr_to_utf8(low_utf8, start[0]);
19797 (void) uvchr_to_utf8(high_utf8, end[0]);
19799 /* If all code points share the same first byte, this can be an
19800 * ANYOFRb. Otherwise store the lowest UTF-8 start byte which can
19801 * quickly rule out many inputs at run-time without having to
19802 * compute the code point from UTF-8. For EBCDIC, we use I8, as
19803 * not doing that transformation would not rule out nearly so many
19805 if (low_utf8[0] == high_utf8[0]) {
19806 OP(REGNODE_p(ret)) = ANYOFRb;
19807 ANYOF_FLAGS(REGNODE_p(ret)) = low_utf8[0];
19810 ANYOF_FLAGS(REGNODE_p(ret))
19811 = NATIVE_UTF8_TO_I8(low_utf8[0]);
19817 /* If didn't find an optimization and there is no need for a bitmap,
19818 * optimize to indicate that */
19819 if ( start[0] >= NUM_ANYOF_CODE_POINTS
19821 && ! upper_latin1_only_utf8_matches
19822 && anyof_flags == 0)
19824 U8 low_utf8[UTF8_MAXBYTES+1];
19825 UV highest_cp = invlist_highest(cp_list);
19827 /* Currently the maximum allowed code point by the system is
19828 * IV_MAX. Higher ones are reserved for future internal use. This
19829 * particular regnode can be used for higher ones, but we can't
19830 * calculate the code point of those. IV_MAX suffices though, as
19831 * it will be a large first byte */
19832 Size_t low_len = uvchr_to_utf8(low_utf8, MIN(start[0], IV_MAX))
19835 /* We store the lowest possible first byte of the UTF-8
19836 * representation, using the flags field. This allows for quick
19837 * ruling out of some inputs without having to convert from UTF-8
19838 * to code point. For EBCDIC, we use I8, as not doing that
19839 * transformation would not rule out nearly so many things */
19840 anyof_flags = NATIVE_UTF8_TO_I8(low_utf8[0]);
19844 /* If the first UTF-8 start byte for the highest code point in the
19845 * range is suitably small, we may be able to get an upper bound as
19847 if (highest_cp <= IV_MAX) {
19848 U8 high_utf8[UTF8_MAXBYTES+1];
19849 Size_t high_len = uvchr_to_utf8(high_utf8, highest_cp)
19852 /* If the lowest and highest are the same, we can get an exact
19853 * first byte instead of a just minimum or even a sequence of
19854 * exact leading bytes. We signal these with different
19856 if (low_utf8[0] == high_utf8[0]) {
19857 Size_t len = find_first_differing_byte_pos(low_utf8,
19859 MIN(low_len, high_len));
19863 /* No need to convert to I8 for EBCDIC as this is an
19865 anyof_flags = low_utf8[0];
19870 ret = regnode_guts(pRExC_state, op,
19871 regarglen[op] + STR_SZ(len),
19873 FILL_NODE(ret, op);
19874 ((struct regnode_anyofhs *) REGNODE_p(ret))->str_len
19876 Copy(low_utf8, /* Add the common bytes */
19877 ((struct regnode_anyofhs *) REGNODE_p(ret))->string,
19879 RExC_emit += NODE_SZ_STR(REGNODE_p(ret));
19880 set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
19881 NULL, only_utf8_locale_list);
19885 else if (NATIVE_UTF8_TO_I8(high_utf8[0]) <= MAX_ANYOF_HRx_BYTE)
19888 /* Here, the high byte is not the same as the low, but is
19889 * small enough that its reasonable to have a loose upper
19890 * bound, which is packed in with the strict lower bound.
19891 * See comments at the definition of MAX_ANYOF_HRx_BYTE.
19892 * On EBCDIC platforms, I8 is used. On ASCII platforms I8
19893 * is the same thing as UTF-8 */
19896 U8 max_range_diff = MAX_ANYOF_HRx_BYTE - anyof_flags;
19897 U8 range_diff = NATIVE_UTF8_TO_I8(high_utf8[0])
19900 if (range_diff <= max_range_diff / 8) {
19903 else if (range_diff <= max_range_diff / 4) {
19906 else if (range_diff <= max_range_diff / 2) {
19909 anyof_flags = (anyof_flags - 0xC0) << 2 | bits;
19914 goto done_finding_op;
19916 } /* End of seeing if can optimize it into a different node */
19918 is_anyof: /* It's going to be an ANYOF node. */
19919 op = (has_runtime_dependency & HAS_D_RUNTIME_DEPENDENCY)
19929 ret = regnode_guts(pRExC_state, op, regarglen[op], "anyof");
19930 FILL_NODE(ret, op); /* We set the argument later */
19931 RExC_emit += 1 + regarglen[op];
19932 ANYOF_FLAGS(REGNODE_p(ret)) = anyof_flags;
19934 /* Here, <cp_list> contains all the code points we can determine at
19935 * compile time that match under all conditions. Go through it, and
19936 * for things that belong in the bitmap, put them there, and delete from
19937 * <cp_list>. While we are at it, see if everything above 255 is in the
19938 * list, and if so, set a flag to speed up execution */
19940 populate_ANYOF_from_invlist(REGNODE_p(ret), &cp_list);
19943 ANYOF_POSIXL_SET_TO_BITMAP(REGNODE_p(ret), posixl);
19947 ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_INVERT;
19950 /* Here, the bitmap has been populated with all the Latin1 code points that
19951 * always match. Can now add to the overall list those that match only
19952 * when the target string is UTF-8 (<upper_latin1_only_utf8_matches>).
19954 if (upper_latin1_only_utf8_matches) {
19956 _invlist_union(cp_list,
19957 upper_latin1_only_utf8_matches,
19959 SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
19962 cp_list = upper_latin1_only_utf8_matches;
19964 ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
19967 set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
19968 (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
19971 only_utf8_locale_list);
19972 SvREFCNT_dec(cp_list);;
19973 SvREFCNT_dec(only_utf8_locale_list);
19978 /* Here, the node is getting optimized into something that's not an ANYOF
19979 * one. Finish up. */
19981 Set_Node_Offset_Length(REGNODE_p(ret), orig_parse - RExC_start,
19982 RExC_parse - orig_parse);;
19983 SvREFCNT_dec(cp_list);;
19984 SvREFCNT_dec(only_utf8_locale_list);
19988 #undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
19991 S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state,
19992 regnode* const node,
19994 SV* const runtime_defns,
19995 SV* const only_utf8_locale_list)
19997 /* Sets the arg field of an ANYOF-type node 'node', using information about
19998 * the node passed-in. If there is nothing outside the node's bitmap, the
19999 * arg is set to ANYOF_ONLY_HAS_BITMAP. Otherwise, it sets the argument to
20000 * the count returned by add_data(), having allocated and stored an array,
20003 * av[0] stores the inversion list defining this class as far as known at
20004 * this time, or PL_sv_undef if nothing definite is now known.
20005 * av[1] stores the inversion list of code points that match only if the
20006 * current locale is UTF-8, or if none, PL_sv_undef if there is an
20007 * av[2], or no entry otherwise.
20008 * av[2] stores the list of user-defined properties whose subroutine
20009 * definitions aren't known at this time, or no entry if none. */
20013 PERL_ARGS_ASSERT_SET_ANYOF_ARG;
20015 if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) {
20016 assert(! (ANYOF_FLAGS(node)
20017 & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP));
20018 ARG_SET(node, ANYOF_ONLY_HAS_BITMAP);
20021 AV * const av = newAV();
20025 av_store(av, INVLIST_INDEX, SvREFCNT_inc_NN(cp_list));
20028 /* (Note that if any of this changes, the size calculations in
20029 * S_optimize_regclass() might need to be updated.) */
20031 if (only_utf8_locale_list) {
20032 av_store(av, ONLY_LOCALE_MATCHES_INDEX,
20033 SvREFCNT_inc_NN(only_utf8_locale_list));
20036 if (runtime_defns) {
20037 av_store(av, DEFERRED_USER_DEFINED_INDEX,
20038 SvREFCNT_inc_NN(runtime_defns));
20041 rv = newRV_noinc(MUTABLE_SV(av));
20042 n = add_data(pRExC_state, STR_WITH_LEN("s"));
20043 RExC_rxi->data->data[n] = (void*)rv;
20050 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
20051 Perl_get_regclass_nonbitmap_data(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV** only_utf8_locale_ptr, SV** output_invlist)
20053 Perl_get_re_gclass_nonbitmap_data(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV** only_utf8_locale_ptr, SV** output_invlist)
20057 /* For internal core use only.
20058 * Returns the inversion list for the input 'node' in the regex 'prog'.
20059 * If <doinit> is 'true', will attempt to create the inversion list if not
20061 * If <listsvp> is non-null, will return the printable contents of the
20062 * property definition. This can be used to get debugging information
20063 * even before the inversion list exists, by calling this function with
20064 * 'doinit' set to false, in which case the components that will be used
20065 * to eventually create the inversion list are returned (in a printable
20067 * If <only_utf8_locale_ptr> is not NULL, it is where this routine is to
20068 * store an inversion list of code points that should match only if the
20069 * execution-time locale is a UTF-8 one.
20070 * If <output_invlist> is not NULL, it is where this routine is to store an
20071 * inversion list of the code points that would be instead returned in
20072 * <listsvp> if this were NULL. Thus, what gets output in <listsvp>
20073 * when this parameter is used, is just the non-code point data that
20074 * will go into creating the inversion list. This currently should be just
20075 * user-defined properties whose definitions were not known at compile
20076 * time. Using this parameter allows for easier manipulation of the
20077 * inversion list's data by the caller. It is illegal to call this
20078 * function with this parameter set, but not <listsvp>
20080 * Tied intimately to how S_set_ANYOF_arg sets up the data structure. Note
20081 * that, in spite of this function's name, the inversion list it returns
20082 * may include the bitmap data as well */
20084 SV *si = NULL; /* Input initialization string */
20085 SV* invlist = NULL;
20087 RXi_GET_DECL(prog, progi);
20088 const struct reg_data * const data = prog ? progi->data : NULL;
20090 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
20091 PERL_ARGS_ASSERT_GET_REGCLASS_NONBITMAP_DATA;
20093 PERL_ARGS_ASSERT_GET_RE_GCLASS_NONBITMAP_DATA;
20095 assert(! output_invlist || listsvp);
20097 if (data && data->count) {
20098 const U32 n = ARG(node);
20100 if (data->what[n] == 's') {
20101 SV * const rv = MUTABLE_SV(data->data[n]);
20102 AV * const av = MUTABLE_AV(SvRV(rv));
20103 SV **const ary = AvARRAY(av);
20105 invlist = ary[INVLIST_INDEX];
20107 if (av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX) {
20108 *only_utf8_locale_ptr = ary[ONLY_LOCALE_MATCHES_INDEX];
20111 if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
20112 si = ary[DEFERRED_USER_DEFINED_INDEX];
20115 if (doinit && (si || invlist)) {
20118 SV * msg = newSVpvs_flags("", SVs_TEMP);
20120 SV * prop_definition = handle_user_defined_property(
20121 "", 0, FALSE, /* There is no \p{}, \P{} */
20122 SvPVX_const(si)[1] - '0', /* /i or not has been
20123 stored here for just
20125 TRUE, /* run time */
20126 FALSE, /* This call must find the defn */
20127 si, /* The property definition */
20130 0 /* base level call */
20134 assert(prop_definition == NULL);
20136 Perl_croak(aTHX_ "%" UTF8f,
20137 UTF8fARG(SvUTF8(msg), SvCUR(msg), SvPVX(msg)));
20141 _invlist_union(invlist, prop_definition, &invlist);
20142 SvREFCNT_dec_NN(prop_definition);
20145 invlist = prop_definition;
20148 STATIC_ASSERT_STMT(ONLY_LOCALE_MATCHES_INDEX == 1 + INVLIST_INDEX);
20149 STATIC_ASSERT_STMT(DEFERRED_USER_DEFINED_INDEX == 1 + ONLY_LOCALE_MATCHES_INDEX);
20151 ary[INVLIST_INDEX] = invlist;
20152 av_fill(av, (ary[ONLY_LOCALE_MATCHES_INDEX])
20153 ? ONLY_LOCALE_MATCHES_INDEX
20161 /* If requested, return a printable version of what this ANYOF node matches
20164 SV* matches_string = NULL;
20166 /* This function can be called at compile-time, before everything gets
20167 * resolved, in which case we return the currently best available
20168 * information, which is the string that will eventually be used to do
20169 * that resolving, 'si' */
20171 /* Here, we only have 'si' (and possibly some passed-in data in
20172 * 'invlist', which is handled below) If the caller only wants
20173 * 'si', use that. */
20174 if (! output_invlist) {
20175 matches_string = newSVsv(si);
20178 /* But if the caller wants an inversion list of the node, we
20179 * need to parse 'si' and place as much as possible in the
20180 * desired output inversion list, making 'matches_string' only
20181 * contain the currently unresolvable things */
20182 const char *si_string = SvPVX(si);
20183 STRLEN remaining = SvCUR(si);
20187 /* Ignore everything before and including the first new-line */
20188 si_string = (const char *) memchr(si_string, '\n', SvCUR(si));
20189 assert (si_string != NULL);
20191 remaining = SvPVX(si) + SvCUR(si) - si_string;
20193 while (remaining > 0) {
20195 /* The data consists of just strings defining user-defined
20196 * property names, but in prior incarnations, and perhaps
20197 * somehow from pluggable regex engines, it could still
20198 * hold hex code point definitions, all of which should be
20199 * legal (or it wouldn't have gotten this far). Each
20200 * component of a range would be separated by a tab, and
20201 * each range by a new-line. If these are found, instead
20202 * add them to the inversion list */
20203 I32 grok_flags = PERL_SCAN_SILENT_ILLDIGIT
20204 |PERL_SCAN_SILENT_NON_PORTABLE;
20205 STRLEN len = remaining;
20206 UV cp = grok_hex(si_string, &len, &grok_flags, NULL);
20208 /* If the hex decode routine found something, it should go
20209 * up to the next \n */
20210 if ( *(si_string + len) == '\n') {
20211 if (count) { /* 2nd code point on line */
20212 *output_invlist = _add_range_to_invlist(*output_invlist, prev_cp, cp);
20215 *output_invlist = add_cp_to_invlist(*output_invlist, cp);
20218 goto prepare_for_next_iteration;
20221 /* If the hex decode was instead for the lower range limit,
20222 * save it, and go parse the upper range limit */
20223 if (*(si_string + len) == '\t') {
20224 assert(count == 0);
20228 prepare_for_next_iteration:
20229 si_string += len + 1;
20230 remaining -= len + 1;
20234 /* Here, didn't find a legal hex number. Just add the text
20235 * from here up to the next \n, omitting any trailing
20239 len = strcspn(si_string,
20240 DEFERRED_COULD_BE_OFFICIAL_MARKERs "\n");
20242 if (matches_string) {
20243 sv_catpvn(matches_string, si_string, len);
20246 matches_string = newSVpvn(si_string, len);
20248 sv_catpvs(matches_string, " ");
20252 && UCHARAT(si_string)
20253 == DEFERRED_COULD_BE_OFFICIAL_MARKERc)
20258 if (remaining && UCHARAT(si_string) == '\n') {
20262 } /* end of loop through the text */
20264 assert(matches_string);
20265 if (SvCUR(matches_string)) { /* Get rid of trailing blank */
20266 SvCUR_set(matches_string, SvCUR(matches_string) - 1);
20268 } /* end of has an 'si' */
20271 /* Add the stuff that's already known */
20274 /* Again, if the caller doesn't want the output inversion list, put
20275 * everything in 'matches-string' */
20276 if (! output_invlist) {
20277 if ( ! matches_string) {
20278 matches_string = newSVpvs("\n");
20280 sv_catsv(matches_string, invlist_contents(invlist,
20281 TRUE /* traditional style */
20284 else if (! *output_invlist) {
20285 *output_invlist = invlist_clone(invlist, NULL);
20288 _invlist_union(*output_invlist, invlist, output_invlist);
20292 *listsvp = matches_string;
20298 /* reg_skipcomment()
20300 Absorbs an /x style # comment from the input stream,
20301 returning a pointer to the first character beyond the comment, or if the
20302 comment terminates the pattern without anything following it, this returns
20303 one past the final character of the pattern (in other words, RExC_end) and
20304 sets the REG_RUN_ON_COMMENT_SEEN flag.
20306 Note it's the callers responsibility to ensure that we are
20307 actually in /x mode
20311 PERL_STATIC_INLINE char*
20312 S_reg_skipcomment(RExC_state_t *pRExC_state, char* p)
20314 PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
20318 while (p < RExC_end) {
20319 if (*(++p) == '\n') {
20324 /* we ran off the end of the pattern without ending the comment, so we have
20325 * to add an \n when wrapping */
20326 RExC_seen |= REG_RUN_ON_COMMENT_SEEN;
20331 S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state,
20333 const bool force_to_xmod
20336 /* If the text at the current parse position '*p' is a '(?#...)' comment,
20337 * or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p'
20338 * is /x whitespace, advance '*p' so that on exit it points to the first
20339 * byte past all such white space and comments */
20341 const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED);
20343 PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT;
20345 assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p));
20348 if (RExC_end - (*p) >= 3
20350 && *(*p + 1) == '?'
20351 && *(*p + 2) == '#')
20353 while (*(*p) != ')') {
20354 if ((*p) == RExC_end)
20355 FAIL("Sequence (?#... not terminated");
20363 const char * save_p = *p;
20364 while ((*p) < RExC_end) {
20366 if ((len = is_PATWS_safe((*p), RExC_end, UTF))) {
20369 else if (*(*p) == '#') {
20370 (*p) = reg_skipcomment(pRExC_state, (*p));
20376 if (*p != save_p) {
20389 Advances the parse position by one byte, unless that byte is the beginning
20390 of a '(?#...)' style comment, or is /x whitespace and /x is in effect. In
20391 those two cases, the parse position is advanced beyond all such comments and
20394 This is the UTF, (?#...), and /x friendly way of saying RExC_parse++.
20398 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
20400 PERL_ARGS_ASSERT_NEXTCHAR;
20402 if (RExC_parse < RExC_end) {
20404 || UTF8_IS_INVARIANT(*RExC_parse)
20405 || UTF8_IS_START(*RExC_parse));
20407 RExC_parse += (UTF)
20408 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
20411 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
20412 FALSE /* Don't force /x */ );
20417 S_change_engine_size(pTHX_ RExC_state_t *pRExC_state, const Ptrdiff_t size)
20419 /* 'size' is the delta number of smallest regnode equivalents to add or
20420 * subtract from the current memory allocated to the regex engine being
20423 PERL_ARGS_ASSERT_CHANGE_ENGINE_SIZE;
20428 sizeof(regexp_internal) + (RExC_size + 1) * sizeof(regnode),
20429 /* +1 for REG_MAGIC */
20432 if ( RExC_rxi == NULL )
20433 FAIL("Regexp out of space");
20434 RXi_SET(RExC_rx, RExC_rxi);
20436 RExC_emit_start = RExC_rxi->program;
20438 Zero(REGNODE_p(RExC_emit), size, regnode);
20441 #ifdef RE_TRACK_PATTERN_OFFSETS
20442 Renew(RExC_offsets, 2*RExC_size+1, U32);
20444 Zero(RExC_offsets + 2*(RExC_size - size) + 1, 2 * size, U32);
20446 RExC_offsets[0] = RExC_size;
20450 STATIC regnode_offset
20451 S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name)
20453 /* Allocate a regnode for 'op', with 'extra_size' extra (smallest) regnode
20454 * equivalents space. It aligns and increments RExC_size
20456 * It returns the regnode's offset into the regex engine program */
20458 const regnode_offset ret = RExC_emit;
20460 DECLARE_AND_GET_RE_DEBUG_FLAGS;
20462 PERL_ARGS_ASSERT_REGNODE_GUTS;
20464 SIZE_ALIGN(RExC_size);
20465 change_engine_size(pRExC_state, (Ptrdiff_t) 1 + extra_size);
20466 NODE_ALIGN_FILL(REGNODE_p(ret));
20467 #ifndef RE_TRACK_PATTERN_OFFSETS
20468 PERL_UNUSED_ARG(name);
20469 PERL_UNUSED_ARG(op);
20471 assert(extra_size >= regarglen[op] || PL_regkind[op] == ANYOF);
20473 if (RExC_offsets) { /* MJD */
20475 ("%s:%d: (op %s) %s %" UVuf " (len %" UVuf ") (max %" UVuf ").\n",
20478 (UV)(RExC_emit) > RExC_offsets[0]
20479 ? "Overwriting end of array!\n" : "OK",
20481 (UV)(RExC_parse - RExC_start),
20482 (UV)RExC_offsets[0]));
20483 Set_Node_Offset(REGNODE_p(RExC_emit), RExC_parse + (op == END));
20490 - reg_node - emit a node
20492 STATIC regnode_offset /* Location. */
20493 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
20495 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node");
20496 regnode_offset ptr = ret;
20498 PERL_ARGS_ASSERT_REG_NODE;
20500 assert(regarglen[op] == 0);
20502 FILL_ADVANCE_NODE(ptr, op);
20508 - reganode - emit a node with an argument
20510 STATIC regnode_offset /* Location. */
20511 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
20513 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode");
20514 regnode_offset ptr = ret;
20516 PERL_ARGS_ASSERT_REGANODE;
20518 /* ANYOF are special cased to allow non-length 1 args */
20519 assert(regarglen[op] == 1);
20521 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
20527 - regpnode - emit a temporary node with a SV* argument
20529 STATIC regnode_offset /* Location. */
20530 S_regpnode(pTHX_ RExC_state_t *pRExC_state, U8 op, SV * arg)
20532 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "regpnode");
20533 regnode_offset ptr = ret;
20535 PERL_ARGS_ASSERT_REGPNODE;
20537 FILL_ADVANCE_NODE_ARGp(ptr, op, arg);
20542 STATIC regnode_offset
20543 S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2)
20545 /* emit a node with U32 and I32 arguments */
20547 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode");
20548 regnode_offset ptr = ret;
20550 PERL_ARGS_ASSERT_REG2LANODE;
20552 assert(regarglen[op] == 2);
20554 FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2);
20560 - reginsert - insert an operator in front of already-emitted operand
20562 * That means that on exit 'operand' is the offset of the newly inserted
20563 * operator, and the original operand has been relocated.
20565 * IMPORTANT NOTE - it is the *callers* responsibility to correctly
20566 * set up NEXT_OFF() of the inserted node if needed. Something like this:
20568 * reginsert(pRExC, OPFAIL, orig_emit, depth+1);
20569 * NEXT_OFF(orig_emit) = regarglen[OPFAIL] + NODE_STEP_REGNODE;
20571 * ALSO NOTE - FLAGS(newly-inserted-operator) will be set to 0 as well.
20574 S_reginsert(pTHX_ RExC_state_t *pRExC_state, const U8 op,
20575 const regnode_offset operand, const U32 depth)
20580 const int offset = regarglen[(U8)op];
20581 const int size = NODE_STEP_REGNODE + offset;
20582 DECLARE_AND_GET_RE_DEBUG_FLAGS;
20584 PERL_ARGS_ASSERT_REGINSERT;
20585 PERL_UNUSED_CONTEXT;
20586 PERL_UNUSED_ARG(depth);
20587 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
20588 DEBUG_PARSE_FMT("inst"," - %s", PL_reg_name[op]);
20589 assert(!RExC_study_started); /* I believe we should never use reginsert once we have started
20590 studying. If this is wrong then we need to adjust RExC_recurse
20591 below like we do with RExC_open_parens/RExC_close_parens. */
20592 change_engine_size(pRExC_state, (Ptrdiff_t) size);
20593 src = REGNODE_p(RExC_emit);
20595 dst = REGNODE_p(RExC_emit);
20597 /* If we are in a "count the parentheses" pass, the numbers are unreliable,
20598 * and [perl #133871] shows this can lead to problems, so skip this
20599 * realignment of parens until a later pass when they are reliable */
20600 if (! IN_PARENS_PASS && RExC_open_parens) {
20602 /*DEBUG_PARSE_FMT("inst"," - %" IVdf, (IV)RExC_npar);*/
20603 /* remember that RExC_npar is rex->nparens + 1,
20604 * iow it is 1 more than the number of parens seen in
20605 * the pattern so far. */
20606 for ( paren=0 ; paren < RExC_npar ; paren++ ) {
20607 /* note, RExC_open_parens[0] is the start of the
20608 * regex, it can't move. RExC_close_parens[0] is the end
20609 * of the regex, it *can* move. */
20610 if ( paren && RExC_open_parens[paren] >= operand ) {
20611 /*DEBUG_PARSE_FMT("open"," - %d", size);*/
20612 RExC_open_parens[paren] += size;
20614 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
20616 if ( RExC_close_parens[paren] >= operand ) {
20617 /*DEBUG_PARSE_FMT("close"," - %d", size);*/
20618 RExC_close_parens[paren] += size;
20620 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
20625 RExC_end_op += size;
20627 while (src > REGNODE_p(operand)) {
20628 StructCopy(--src, --dst, regnode);
20629 #ifdef RE_TRACK_PATTERN_OFFSETS
20630 if (RExC_offsets) { /* MJD 20010112 */
20632 ("%s(%d): (op %s) %s copy %" UVuf " -> %" UVuf " (max %" UVuf ").\n",
20636 (UV)(REGNODE_OFFSET(dst)) > RExC_offsets[0]
20637 ? "Overwriting end of array!\n" : "OK",
20638 (UV)REGNODE_OFFSET(src),
20639 (UV)REGNODE_OFFSET(dst),
20640 (UV)RExC_offsets[0]));
20641 Set_Node_Offset_To_R(REGNODE_OFFSET(dst), Node_Offset(src));
20642 Set_Node_Length_To_R(REGNODE_OFFSET(dst), Node_Length(src));
20647 place = REGNODE_p(operand); /* Op node, where operand used to be. */
20648 #ifdef RE_TRACK_PATTERN_OFFSETS
20649 if (RExC_offsets) { /* MJD */
20651 ("%s(%d): (op %s) %s %" UVuf " <- %" UVuf " (max %" UVuf ").\n",
20655 (UV)REGNODE_OFFSET(place) > RExC_offsets[0]
20656 ? "Overwriting end of array!\n" : "OK",
20657 (UV)REGNODE_OFFSET(place),
20658 (UV)(RExC_parse - RExC_start),
20659 (UV)RExC_offsets[0]));
20660 Set_Node_Offset(place, RExC_parse);
20661 Set_Node_Length(place, 1);
20664 src = NEXTOPER(place);
20666 FILL_NODE(operand, op);
20668 /* Zero out any arguments in the new node */
20669 Zero(src, offset, regnode);
20673 - regtail - set the next-pointer at the end of a node chain of p to val. If
20674 that value won't fit in the space available, instead returns FALSE.
20675 (Except asserts if we can't fit in the largest space the regex
20676 engine is designed for.)
20677 - SEE ALSO: regtail_study
20680 S_regtail(pTHX_ RExC_state_t * pRExC_state,
20681 const regnode_offset p,
20682 const regnode_offset val,
20685 regnode_offset scan;
20686 DECLARE_AND_GET_RE_DEBUG_FLAGS;
20688 PERL_ARGS_ASSERT_REGTAIL;
20690 PERL_UNUSED_ARG(depth);
20693 /* The final node in the chain is the first one with a nonzero next pointer
20695 scan = (regnode_offset) p;
20697 regnode * const temp = regnext(REGNODE_p(scan));
20699 DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
20700 regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
20701 Perl_re_printf( aTHX_ "~ %s (%zu) %s %s\n",
20702 SvPV_nolen_const(RExC_mysv), scan,
20703 (temp == NULL ? "->" : ""),
20704 (temp == NULL ? PL_reg_name[OP(REGNODE_p(val))] : "")
20709 scan = REGNODE_OFFSET(temp);
20712 /* Populate this node's next pointer */
20713 assert(val >= scan);
20714 if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
20715 assert((UV) (val - scan) <= U32_MAX);
20716 ARG_SET(REGNODE_p(scan), val - scan);
20719 if (val - scan > U16_MAX) {
20720 /* Populate this with something that won't loop and will likely
20721 * lead to a crash if the caller ignores the failure return, and
20722 * execution continues */
20723 NEXT_OFF(REGNODE_p(scan)) = U16_MAX;
20726 NEXT_OFF(REGNODE_p(scan)) = val - scan;
20734 - regtail_study - set the next-pointer at the end of a node chain of p to val.
20735 - Look for optimizable sequences at the same time.
20736 - currently only looks for EXACT chains.
20738 This is experimental code. The idea is to use this routine to perform
20739 in place optimizations on branches and groups as they are constructed,
20740 with the long term intention of removing optimization from study_chunk so
20741 that it is purely analytical.
20743 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
20744 to control which is which.
20746 This used to return a value that was ignored. It was a problem that it is
20747 #ifdef'd to be another function that didn't return a value. khw has changed it
20748 so both currently return a pass/fail return.
20751 /* TODO: All four parms should be const */
20754 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode_offset p,
20755 const regnode_offset val, U32 depth)
20757 regnode_offset scan;
20759 #ifdef EXPERIMENTAL_INPLACESCAN
20762 DECLARE_AND_GET_RE_DEBUG_FLAGS;
20764 PERL_ARGS_ASSERT_REGTAIL_STUDY;
20767 /* Find last node. */
20771 regnode * const temp = regnext(REGNODE_p(scan));
20772 #ifdef EXPERIMENTAL_INPLACESCAN
20773 if (PL_regkind[OP(REGNODE_p(scan))] == EXACT) {
20774 bool unfolded_multi_char; /* Unexamined in this routine */
20775 if (join_exact(pRExC_state, scan, &min,
20776 &unfolded_multi_char, 1, REGNODE_p(val), depth+1))
20777 return TRUE; /* Was return EXACT */
20781 switch (OP(REGNODE_p(scan))) {
20788 case EXACTFU_S_EDGE:
20789 case EXACTFAA_NO_TRIE:
20796 if( exact == PSEUDO )
20797 exact= OP(REGNODE_p(scan));
20798 else if ( exact != OP(REGNODE_p(scan)) )
20807 DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
20808 regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
20809 Perl_re_printf( aTHX_ "~ %s (%zu) -> %s\n",
20810 SvPV_nolen_const(RExC_mysv),
20812 PL_reg_name[exact]);
20816 scan = REGNODE_OFFSET(temp);
20819 DEBUG_PARSE_MSG("");
20820 regprop(RExC_rx, RExC_mysv, REGNODE_p(val), NULL, pRExC_state);
20821 Perl_re_printf( aTHX_
20822 "~ attach to %s (%" IVdf ") offset to %" IVdf "\n",
20823 SvPV_nolen_const(RExC_mysv),
20828 if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
20829 assert((UV) (val - scan) <= U32_MAX);
20830 ARG_SET(REGNODE_p(scan), val - scan);
20833 if (val - scan > U16_MAX) {
20834 /* Populate this with something that won't loop and will likely
20835 * lead to a crash if the caller ignores the failure return, and
20836 * execution continues */
20837 NEXT_OFF(REGNODE_p(scan)) = U16_MAX;
20840 NEXT_OFF(REGNODE_p(scan)) = val - scan;
20843 return TRUE; /* Was 'return exact' */
20848 S_get_ANYOFM_contents(pTHX_ const regnode * n) {
20850 /* Returns an inversion list of all the code points matched by the
20851 * ANYOFM/NANYOFM node 'n' */
20853 SV * cp_list = _new_invlist(-1);
20854 const U8 lowest = (U8) ARG(n);
20857 U8 needed = 1U << PL_bitcount[ (U8) ~ FLAGS(n)];
20859 PERL_ARGS_ASSERT_GET_ANYOFM_CONTENTS;
20861 /* Starting with the lowest code point, any code point that ANDed with the
20862 * mask yields the lowest code point is in the set */
20863 for (i = lowest; i <= 0xFF; i++) {
20864 if ((i & FLAGS(n)) == ARG(n)) {
20865 cp_list = add_cp_to_invlist(cp_list, i);
20868 /* We know how many code points (a power of two) that are in the
20869 * set. No use looking once we've got that number */
20870 if (count >= needed) break;
20874 if (OP(n) == NANYOFM) {
20875 _invlist_invert(cp_list);
20881 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
20886 S_regdump_intflags(pTHX_ const char *lead, const U32 flags)
20891 ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8);
20893 for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) {
20894 if (flags & (1<<bit)) {
20895 if (!set++ && lead)
20896 Perl_re_printf( aTHX_ "%s", lead);
20897 Perl_re_printf( aTHX_ "%s ", PL_reg_intflags_name[bit]);
20902 Perl_re_printf( aTHX_ "\n");
20904 Perl_re_printf( aTHX_ "%s[none-set]\n", lead);
20909 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
20915 ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8);
20917 for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) {
20918 if (flags & (1<<bit)) {
20919 if ((1<<bit) & RXf_PMf_CHARSET) { /* Output separately, below */
20922 if (!set++ && lead)
20923 Perl_re_printf( aTHX_ "%s", lead);
20924 Perl_re_printf( aTHX_ "%s ", PL_reg_extflags_name[bit]);
20927 if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
20928 if (!set++ && lead) {
20929 Perl_re_printf( aTHX_ "%s", lead);
20932 case REGEX_UNICODE_CHARSET:
20933 Perl_re_printf( aTHX_ "UNICODE");
20935 case REGEX_LOCALE_CHARSET:
20936 Perl_re_printf( aTHX_ "LOCALE");
20938 case REGEX_ASCII_RESTRICTED_CHARSET:
20939 Perl_re_printf( aTHX_ "ASCII-RESTRICTED");
20941 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
20942 Perl_re_printf( aTHX_ "ASCII-MORE_RESTRICTED");
20945 Perl_re_printf( aTHX_ "UNKNOWN CHARACTER SET");
20951 Perl_re_printf( aTHX_ "\n");
20953 Perl_re_printf( aTHX_ "%s[none-set]\n", lead);
20959 Perl_regdump(pTHX_ const regexp *r)
20963 SV * const sv = sv_newmortal();
20964 SV *dsv= sv_newmortal();
20965 RXi_GET_DECL(r, ri);
20966 DECLARE_AND_GET_RE_DEBUG_FLAGS;
20968 PERL_ARGS_ASSERT_REGDUMP;
20970 (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
20972 /* Header fields of interest. */
20973 for (i = 0; i < 2; i++) {
20974 if (r->substrs->data[i].substr) {
20975 RE_PV_QUOTED_DECL(s, 0, dsv,
20976 SvPVX_const(r->substrs->data[i].substr),
20977 RE_SV_DUMPLEN(r->substrs->data[i].substr),
20978 PL_dump_re_max_len);
20979 Perl_re_printf( aTHX_
20980 "%s %s%s at %" IVdf "..%" UVuf " ",
20981 i ? "floating" : "anchored",
20983 RE_SV_TAIL(r->substrs->data[i].substr),
20984 (IV)r->substrs->data[i].min_offset,
20985 (UV)r->substrs->data[i].max_offset);
20987 else if (r->substrs->data[i].utf8_substr) {
20988 RE_PV_QUOTED_DECL(s, 1, dsv,
20989 SvPVX_const(r->substrs->data[i].utf8_substr),
20990 RE_SV_DUMPLEN(r->substrs->data[i].utf8_substr),
20992 Perl_re_printf( aTHX_
20993 "%s utf8 %s%s at %" IVdf "..%" UVuf " ",
20994 i ? "floating" : "anchored",
20996 RE_SV_TAIL(r->substrs->data[i].utf8_substr),
20997 (IV)r->substrs->data[i].min_offset,
20998 (UV)r->substrs->data[i].max_offset);
21002 if (r->check_substr || r->check_utf8)
21003 Perl_re_printf( aTHX_
21005 ( r->check_substr == r->substrs->data[1].substr
21006 && r->check_utf8 == r->substrs->data[1].utf8_substr
21007 ? "(checking floating" : "(checking anchored"));
21008 if (r->intflags & PREGf_NOSCAN)
21009 Perl_re_printf( aTHX_ " noscan");
21010 if (r->extflags & RXf_CHECK_ALL)
21011 Perl_re_printf( aTHX_ " isall");
21012 if (r->check_substr || r->check_utf8)
21013 Perl_re_printf( aTHX_ ") ");
21015 if (ri->regstclass) {
21016 regprop(r, sv, ri->regstclass, NULL, NULL);
21017 Perl_re_printf( aTHX_ "stclass %s ", SvPVX_const(sv));
21019 if (r->intflags & PREGf_ANCH) {
21020 Perl_re_printf( aTHX_ "anchored");
21021 if (r->intflags & PREGf_ANCH_MBOL)
21022 Perl_re_printf( aTHX_ "(MBOL)");
21023 if (r->intflags & PREGf_ANCH_SBOL)
21024 Perl_re_printf( aTHX_ "(SBOL)");
21025 if (r->intflags & PREGf_ANCH_GPOS)
21026 Perl_re_printf( aTHX_ "(GPOS)");
21027 Perl_re_printf( aTHX_ " ");
21029 if (r->intflags & PREGf_GPOS_SEEN)
21030 Perl_re_printf( aTHX_ "GPOS:%" UVuf " ", (UV)r->gofs);
21031 if (r->intflags & PREGf_SKIP)
21032 Perl_re_printf( aTHX_ "plus ");
21033 if (r->intflags & PREGf_IMPLICIT)
21034 Perl_re_printf( aTHX_ "implicit ");
21035 Perl_re_printf( aTHX_ "minlen %" IVdf " ", (IV)r->minlen);
21036 if (r->extflags & RXf_EVAL_SEEN)
21037 Perl_re_printf( aTHX_ "with eval ");
21038 Perl_re_printf( aTHX_ "\n");
21040 regdump_extflags("r->extflags: ", r->extflags);
21041 regdump_intflags("r->intflags: ", r->intflags);
21044 PERL_ARGS_ASSERT_REGDUMP;
21045 PERL_UNUSED_CONTEXT;
21046 PERL_UNUSED_ARG(r);
21047 #endif /* DEBUGGING */
21050 /* Should be synchronized with ANYOF_ #defines in regcomp.h */
21053 # if _CC_WORDCHAR != 0 || _CC_DIGIT != 1 || _CC_ALPHA != 2 \
21054 || _CC_LOWER != 3 || _CC_UPPER != 4 || _CC_PUNCT != 5 \
21055 || _CC_PRINT != 6 || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8 \
21056 || _CC_CASED != 9 || _CC_SPACE != 10 || _CC_BLANK != 11 \
21057 || _CC_XDIGIT != 12 || _CC_CNTRL != 13 || _CC_ASCII != 14 \
21058 || _CC_VERTSPACE != 15
21059 # error Need to adjust order of anyofs[]
21061 static const char * const anyofs[] = {
21098 - regprop - printable representation of opcode, with run time support
21102 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state)
21107 RXi_GET_DECL(prog, progi);
21108 DECLARE_AND_GET_RE_DEBUG_FLAGS;
21110 PERL_ARGS_ASSERT_REGPROP;
21114 if (OP(o) > REGNODE_MAX) { /* regnode.type is unsigned */
21115 if (pRExC_state) { /* This gives more info, if we have it */
21116 FAIL3("panic: corrupted regexp opcode %d > %d",
21117 (int)OP(o), (int)REGNODE_MAX);
21120 Perl_croak(aTHX_ "panic: corrupted regexp opcode %d > %d",
21121 (int)OP(o), (int)REGNODE_MAX);
21124 sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
21126 k = PL_regkind[OP(o)];
21129 sv_catpvs(sv, " ");
21130 /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
21131 * is a crude hack but it may be the best for now since
21132 * we have no flag "this EXACTish node was UTF-8"
21134 pv_pretty(sv, STRING(o), STR_LEN(o), PL_dump_re_max_len,
21135 PL_colors[0], PL_colors[1],
21136 PERL_PV_ESCAPE_UNI_DETECT |
21137 PERL_PV_ESCAPE_NONASCII |
21138 PERL_PV_PRETTY_ELLIPSES |
21139 PERL_PV_PRETTY_LTGT |
21140 PERL_PV_PRETTY_NOCLEAR
21142 } else if (k == TRIE) {
21143 /* print the details of the trie in dumpuntil instead, as
21144 * progi->data isn't available here */
21145 const char op = OP(o);
21146 const U32 n = ARG(o);
21147 const reg_ac_data * const ac = IS_TRIE_AC(op) ?
21148 (reg_ac_data *)progi->data->data[n] :
21150 const reg_trie_data * const trie
21151 = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
21153 Perl_sv_catpvf(aTHX_ sv, "-%s", PL_reg_name[o->flags]);
21154 DEBUG_TRIE_COMPILE_r({
21156 sv_catpvs(sv, "(JUMP)");
21157 Perl_sv_catpvf(aTHX_ sv,
21158 "<S:%" UVuf "/%" IVdf " W:%" UVuf " L:%" UVuf "/%" UVuf " C:%" UVuf "/%" UVuf ">",
21159 (UV)trie->startstate,
21160 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
21161 (UV)trie->wordcount,
21164 (UV)TRIE_CHARCOUNT(trie),
21165 (UV)trie->uniquecharcount
21168 if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
21169 sv_catpvs(sv, "[");
21170 (void) put_charclass_bitmap_innards(sv,
21171 ((IS_ANYOF_TRIE(op))
21173 : TRIE_BITMAP(trie)),
21180 sv_catpvs(sv, "]");
21182 } else if (k == CURLY) {
21183 U32 lo = ARG1(o), hi = ARG2(o);
21184 if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
21185 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
21186 Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo);
21187 if (hi == REG_INFTY)
21188 sv_catpvs(sv, "INFTY");
21190 Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi);
21191 sv_catpvs(sv, "}");
21193 else if (k == WHILEM && o->flags) /* Ordinal/of */
21194 Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
21195 else if (k == REF || k == OPEN || k == CLOSE
21196 || k == GROUPP || OP(o)==ACCEPT)
21198 AV *name_list= NULL;
21199 U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o);
21200 Perl_sv_catpvf(aTHX_ sv, "%" UVuf, (UV)parno); /* Parenth number */
21201 if ( RXp_PAREN_NAMES(prog) ) {
21202 name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
21203 } else if ( pRExC_state ) {
21204 name_list= RExC_paren_name_list;
21207 if ( k != REF || (OP(o) < REFN)) {
21208 SV **name= av_fetch(name_list, parno, 0 );
21210 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
21213 SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]);
21214 I32 *nums=(I32*)SvPVX(sv_dat);
21215 SV **name= av_fetch(name_list, nums[0], 0 );
21218 for ( n=0; n<SvIVX(sv_dat); n++ ) {
21219 Perl_sv_catpvf(aTHX_ sv, "%s%" IVdf,
21220 (n ? "," : ""), (IV)nums[n]);
21222 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
21226 if ( k == REF && reginfo) {
21227 U32 n = ARG(o); /* which paren pair */
21228 I32 ln = prog->offs[n].start;
21229 if (prog->lastparen < n || ln == -1 || prog->offs[n].end == -1)
21230 Perl_sv_catpvf(aTHX_ sv, ": FAIL");
21231 else if (ln == prog->offs[n].end)
21232 Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING");
21234 const char *s = reginfo->strbeg + ln;
21235 Perl_sv_catpvf(aTHX_ sv, ": ");
21236 Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0,
21237 PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE );
21240 } else if (k == GOSUB) {
21241 AV *name_list= NULL;
21242 if ( RXp_PAREN_NAMES(prog) ) {
21243 name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
21244 } else if ( pRExC_state ) {
21245 name_list= RExC_paren_name_list;
21248 /* Paren and offset */
21249 Perl_sv_catpvf(aTHX_ sv, "%d[%+d:%d]", (int)ARG(o),(int)ARG2L(o),
21250 (int)((o + (int)ARG2L(o)) - progi->program) );
21252 SV **name= av_fetch(name_list, ARG(o), 0 );
21254 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
21257 else if (k == LOGICAL)
21258 /* 2: embedded, otherwise 1 */
21259 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);
21260 else if (k == ANYOF || k == ANYOFR) {
21264 bool do_sep = FALSE; /* Do we need to separate various components of
21266 /* Set if there is still an unresolved user-defined property */
21267 SV *unresolved = NULL;
21269 /* Things that are ignored except when the runtime locale is UTF-8 */
21270 SV *only_utf8_locale_invlist = NULL;
21272 /* Code points that don't fit in the bitmap */
21273 SV *nonbitmap_invlist = NULL;
21275 /* And things that aren't in the bitmap, but are small enough to be */
21276 SV* bitmap_range_not_in_bitmap = NULL;
21280 if (inRANGE(OP(o), ANYOFH, ANYOFRb)) {
21286 flags = ANYOF_FLAGS(o);
21287 bitmap = ANYOF_BITMAP(o);
21291 if (OP(o) == ANYOFL || OP(o) == ANYOFPOSIXL) {
21292 if (ANYOFL_UTF8_LOCALE_REQD(flags)) {
21293 sv_catpvs(sv, "{utf8-locale-reqd}");
21295 if (flags & ANYOFL_FOLD) {
21296 sv_catpvs(sv, "{i}");
21300 inverted = flags & ANYOF_INVERT;
21302 /* If there is stuff outside the bitmap, get it */
21303 if (arg != ANYOF_ONLY_HAS_BITMAP) {
21304 if (inRANGE(OP(o), ANYOFR, ANYOFRb)) {
21305 nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
21307 ANYOFRbase(o) + ANYOFRdelta(o));
21310 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
21311 (void) get_regclass_nonbitmap_data(prog, o, FALSE,
21313 &only_utf8_locale_invlist,
21314 &nonbitmap_invlist);
21316 (void) get_re_gclass_nonbitmap_data(prog, o, FALSE,
21318 &only_utf8_locale_invlist,
21319 &nonbitmap_invlist);
21323 /* The non-bitmap data may contain stuff that could fit in the
21324 * bitmap. This could come from a user-defined property being
21325 * finally resolved when this call was done; or much more likely
21326 * because there are matches that require UTF-8 to be valid, and so
21327 * aren't in the bitmap (or ANYOFR). This is teased apart later */
21328 _invlist_intersection(nonbitmap_invlist,
21330 &bitmap_range_not_in_bitmap);
21331 /* Leave just the things that don't fit into the bitmap */
21332 _invlist_subtract(nonbitmap_invlist,
21334 &nonbitmap_invlist);
21337 /* Obey this flag to add all above-the-bitmap code points */
21338 if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
21339 nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
21340 NUM_ANYOF_CODE_POINTS,
21344 /* Ready to start outputting. First, the initial left bracket */
21345 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
21347 /* ANYOFH by definition doesn't have anything that will fit inside the
21348 * bitmap; ANYOFR may or may not. */
21349 if ( ! inRANGE(OP(o), ANYOFH, ANYOFHr)
21350 && ( ! inRANGE(OP(o), ANYOFR, ANYOFRb)
21351 || ANYOFRbase(o) < NUM_ANYOF_CODE_POINTS))
21353 /* Then all the things that could fit in the bitmap */
21354 do_sep = put_charclass_bitmap_innards(sv,
21356 bitmap_range_not_in_bitmap,
21357 only_utf8_locale_invlist,
21361 /* Can't try inverting for a
21362 * better display if there
21363 * are things that haven't
21366 || inRANGE(OP(o), ANYOFR, ANYOFRb));
21367 SvREFCNT_dec(bitmap_range_not_in_bitmap);
21369 /* If there are user-defined properties which haven't been defined
21370 * yet, output them. If the result is not to be inverted, it is
21371 * clearest to output them in a separate [] from the bitmap range
21372 * stuff. If the result is to be complemented, we have to show
21373 * everything in one [], as the inversion applies to the whole
21374 * thing. Use {braces} to separate them from anything in the
21375 * bitmap and anything above the bitmap. */
21378 if (! do_sep) { /* If didn't output anything in the bitmap
21380 sv_catpvs(sv, "^");
21382 sv_catpvs(sv, "{");
21385 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1],
21388 sv_catsv(sv, unresolved);
21390 sv_catpvs(sv, "}");
21392 do_sep = ! inverted;
21396 /* And, finally, add the above-the-bitmap stuff */
21397 if (nonbitmap_invlist && _invlist_len(nonbitmap_invlist)) {
21400 /* See if truncation size is overridden */
21401 const STRLEN dump_len = (PL_dump_re_max_len > 256)
21402 ? PL_dump_re_max_len
21405 /* This is output in a separate [] */
21407 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]);
21410 /* And, for easy of understanding, it is shown in the
21411 * uncomplemented form if possible. The one exception being if
21412 * there are unresolved items, where the inversion has to be
21413 * delayed until runtime */
21414 if (inverted && ! unresolved) {
21415 _invlist_invert(nonbitmap_invlist);
21416 _invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist);
21419 contents = invlist_contents(nonbitmap_invlist,
21420 FALSE /* output suitable for catsv */
21423 /* If the output is shorter than the permissible maximum, just do it. */
21424 if (SvCUR(contents) <= dump_len) {
21425 sv_catsv(sv, contents);
21428 const char * contents_string = SvPVX(contents);
21429 STRLEN i = dump_len;
21431 /* Otherwise, start at the permissible max and work back to the
21432 * first break possibility */
21433 while (i > 0 && contents_string[i] != ' ') {
21436 if (i == 0) { /* Fail-safe. Use the max if we couldn't
21437 find a legal break */
21441 sv_catpvn(sv, contents_string, i);
21442 sv_catpvs(sv, "...");
21445 SvREFCNT_dec_NN(contents);
21446 SvREFCNT_dec_NN(nonbitmap_invlist);
21449 /* And finally the matching, closing ']' */
21450 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
21452 if (OP(o) == ANYOFHs) {
21453 Perl_sv_catpvf(aTHX_ sv, " (Leading UTF-8 bytes=%s", _byte_dump_string((U8 *) ((struct regnode_anyofhs *) o)->string, FLAGS(o), 1));
21455 else if (inRANGE(OP(o), ANYOFH, ANYOFRb)) {
21456 U8 lowest = (OP(o) != ANYOFHr)
21458 : LOWEST_ANYOF_HRx_BYTE(FLAGS(o));
21459 U8 highest = (OP(o) == ANYOFHr)
21460 ? HIGHEST_ANYOF_HRx_BYTE(FLAGS(o))
21461 : (OP(o) == ANYOFH || OP(o) == ANYOFR)
21465 if (OP(o) != ANYOFR || ! isASCII(ANYOFRbase(o) + ANYOFRdelta(o)))
21468 Perl_sv_catpvf(aTHX_ sv, " (First UTF-8 byte=%02X", lowest);
21469 if (lowest != highest) {
21470 Perl_sv_catpvf(aTHX_ sv, "-%02X", highest);
21472 Perl_sv_catpvf(aTHX_ sv, ")");
21476 SvREFCNT_dec(unresolved);
21478 else if (k == ANYOFM) {
21479 SV * cp_list = get_ANYOFM_contents(o);
21481 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
21482 if (OP(o) == NANYOFM) {
21483 _invlist_invert(cp_list);
21486 put_charclass_bitmap_innards(sv, NULL, cp_list, NULL, NULL, 0, TRUE);
21487 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
21489 SvREFCNT_dec(cp_list);
21491 else if (k == POSIXD || k == NPOSIXD) {
21492 U8 index = FLAGS(o) * 2;
21493 if (index < C_ARRAY_LENGTH(anyofs)) {
21494 if (*anyofs[index] != '[') {
21495 sv_catpvs(sv, "[");
21497 sv_catpv(sv, anyofs[index]);
21498 if (*anyofs[index] != '[') {
21499 sv_catpvs(sv, "]");
21503 Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
21506 else if (k == BOUND || k == NBOUND) {
21507 /* Must be synced with order of 'bound_type' in regcomp.h */
21508 const char * const bounds[] = {
21509 "", /* Traditional */
21515 assert(FLAGS(o) < C_ARRAY_LENGTH(bounds));
21516 sv_catpv(sv, bounds[FLAGS(o)]);
21518 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH)) {
21519 Perl_sv_catpvf(aTHX_ sv, "[%d", -(o->flags));
21521 Perl_sv_catpvf(aTHX_ sv, "..-%d", o->flags - o->next_off);
21523 Perl_sv_catpvf(aTHX_ sv, "]");
21525 else if (OP(o) == SBOL)
21526 Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^");
21528 /* add on the verb argument if there is one */
21529 if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) {
21531 Perl_sv_catpvf(aTHX_ sv, ":%" SVf,
21532 SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
21534 sv_catpvs(sv, ":NULL");
21537 PERL_UNUSED_CONTEXT;
21538 PERL_UNUSED_ARG(sv);
21539 PERL_UNUSED_ARG(o);
21540 PERL_UNUSED_ARG(prog);
21541 PERL_UNUSED_ARG(reginfo);
21542 PERL_UNUSED_ARG(pRExC_state);
21543 #endif /* DEBUGGING */
21549 Perl_re_intuit_string(pTHX_ REGEXP * const r)
21550 { /* Assume that RE_INTUIT is set */
21551 /* Returns an SV containing a string that must appear in the target for it
21552 * to match, or NULL if nothing is known that must match.
21554 * CAUTION: the SV can be freed during execution of the regex engine */
21556 struct regexp *const prog = ReANY(r);
21557 DECLARE_AND_GET_RE_DEBUG_FLAGS;
21559 PERL_ARGS_ASSERT_RE_INTUIT_STRING;
21560 PERL_UNUSED_CONTEXT;
21564 if (prog->maxlen > 0) {
21565 const char * const s = SvPV_nolen_const(RX_UTF8(r)
21566 ? prog->check_utf8 : prog->check_substr);
21568 if (!PL_colorset) reginitcolors();
21569 Perl_re_printf( aTHX_
21570 "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
21572 RX_UTF8(r) ? "utf8 " : "",
21573 PL_colors[5], PL_colors[0],
21576 (strlen(s) > PL_dump_re_max_len ? "..." : ""));
21580 /* use UTF8 check substring if regexp pattern itself is in UTF8 */
21581 return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr;
21587 handles refcounting and freeing the perl core regexp structure. When
21588 it is necessary to actually free the structure the first thing it
21589 does is call the 'free' method of the regexp_engine associated to
21590 the regexp, allowing the handling of the void *pprivate; member
21591 first. (This routine is not overridable by extensions, which is why
21592 the extensions free is called first.)
21594 See regdupe and regdupe_internal if you change anything here.
21596 #ifndef PERL_IN_XSUB_RE
21598 Perl_pregfree(pTHX_ REGEXP *r)
21604 Perl_pregfree2(pTHX_ REGEXP *rx)
21606 struct regexp *const r = ReANY(rx);
21607 DECLARE_AND_GET_RE_DEBUG_FLAGS;
21609 PERL_ARGS_ASSERT_PREGFREE2;
21614 if (r->mother_re) {
21615 ReREFCNT_dec(r->mother_re);
21617 CALLREGFREE_PVT(rx); /* free the private data */
21618 SvREFCNT_dec(RXp_PAREN_NAMES(r));
21622 for (i = 0; i < 2; i++) {
21623 SvREFCNT_dec(r->substrs->data[i].substr);
21624 SvREFCNT_dec(r->substrs->data[i].utf8_substr);
21626 Safefree(r->substrs);
21628 RX_MATCH_COPY_FREE(rx);
21629 #ifdef PERL_ANY_COW
21630 SvREFCNT_dec(r->saved_copy);
21633 SvREFCNT_dec(r->qr_anoncv);
21634 if (r->recurse_locinput)
21635 Safefree(r->recurse_locinput);
21641 Copy ssv to dsv, both of which should of type SVt_REGEXP or SVt_PVLV,
21642 except that dsv will be created if NULL.
21644 This function is used in two main ways. First to implement
21645 $r = qr/....; $s = $$r;
21647 Secondly, it is used as a hacky workaround to the structural issue of
21649 being stored in the regexp structure which is in turn stored in
21650 PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
21651 could be PL_curpm in multiple contexts, and could require multiple
21652 result sets being associated with the pattern simultaneously, such
21653 as when doing a recursive match with (??{$qr})
21655 The solution is to make a lightweight copy of the regexp structure
21656 when a qr// is returned from the code executed by (??{$qr}) this
21657 lightweight copy doesn't actually own any of its data except for
21658 the starp/end and the actual regexp structure itself.
21664 Perl_reg_temp_copy(pTHX_ REGEXP *dsv, REGEXP *ssv)
21666 struct regexp *drx;
21667 struct regexp *const srx = ReANY(ssv);
21668 const bool islv = dsv && SvTYPE(dsv) == SVt_PVLV;
21670 PERL_ARGS_ASSERT_REG_TEMP_COPY;
21673 dsv = (REGEXP*) newSV_type(SVt_REGEXP);
21675 assert(SvTYPE(dsv) == SVt_REGEXP || (SvTYPE(dsv) == SVt_PVLV));
21677 /* our only valid caller, sv_setsv_flags(), should have done
21678 * a SV_CHECK_THINKFIRST_COW_DROP() by now */
21679 assert(!SvOOK(dsv));
21680 assert(!SvIsCOW(dsv));
21681 assert(!SvROK(dsv));
21683 if (SvPVX_const(dsv)) {
21685 Safefree(SvPVX(dsv));
21690 SvOK_off((SV *)dsv);
21693 /* For PVLVs, the head (sv_any) points to an XPVLV, while
21694 * the LV's xpvlenu_rx will point to a regexp body, which
21695 * we allocate here */
21696 REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
21697 assert(!SvPVX(dsv));
21698 ((XPV*)SvANY(dsv))->xpv_len_u.xpvlenu_rx = temp->sv_any;
21699 temp->sv_any = NULL;
21700 SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
21701 SvREFCNT_dec_NN(temp);
21702 /* SvCUR still resides in the xpvlv struct, so the regexp copy-
21703 ing below will not set it. */
21704 SvCUR_set(dsv, SvCUR(ssv));
21707 /* This ensures that SvTHINKFIRST(sv) is true, and hence that
21708 sv_force_normal(sv) is called. */
21712 SvFLAGS(dsv) |= SvFLAGS(ssv) & (SVf_POK|SVp_POK|SVf_UTF8);
21713 SvPV_set(dsv, RX_WRAPPED(ssv));
21714 /* We share the same string buffer as the original regexp, on which we
21715 hold a reference count, incremented when mother_re is set below.
21716 The string pointer is copied here, being part of the regexp struct.
21718 memcpy(&(drx->xpv_cur), &(srx->xpv_cur),
21719 sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
21723 const I32 npar = srx->nparens+1;
21724 Newx(drx->offs, npar, regexp_paren_pair);
21725 Copy(srx->offs, drx->offs, npar, regexp_paren_pair);
21727 if (srx->substrs) {
21729 Newx(drx->substrs, 1, struct reg_substr_data);
21730 StructCopy(srx->substrs, drx->substrs, struct reg_substr_data);
21732 for (i = 0; i < 2; i++) {
21733 SvREFCNT_inc_void(drx->substrs->data[i].substr);
21734 SvREFCNT_inc_void(drx->substrs->data[i].utf8_substr);
21737 /* check_substr and check_utf8, if non-NULL, point to either their
21738 anchored or float namesakes, and don't hold a second reference. */
21740 RX_MATCH_COPIED_off(dsv);
21741 #ifdef PERL_ANY_COW
21742 drx->saved_copy = NULL;
21744 drx->mother_re = ReREFCNT_inc(srx->mother_re ? srx->mother_re : ssv);
21745 SvREFCNT_inc_void(drx->qr_anoncv);
21746 if (srx->recurse_locinput)
21747 Newx(drx->recurse_locinput, srx->nparens + 1, char *);
21754 /* regfree_internal()
21756 Free the private data in a regexp. This is overloadable by
21757 extensions. Perl takes care of the regexp structure in pregfree(),
21758 this covers the *pprivate pointer which technically perl doesn't
21759 know about, however of course we have to handle the
21760 regexp_internal structure when no extension is in use.
21762 Note this is called before freeing anything in the regexp
21767 Perl_regfree_internal(pTHX_ REGEXP * const rx)
21769 struct regexp *const r = ReANY(rx);
21770 RXi_GET_DECL(r, ri);
21771 DECLARE_AND_GET_RE_DEBUG_FLAGS;
21773 PERL_ARGS_ASSERT_REGFREE_INTERNAL;
21783 SV *dsv= sv_newmortal();
21784 RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
21785 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), PL_dump_re_max_len);
21786 Perl_re_printf( aTHX_ "%sFreeing REx:%s %s\n",
21787 PL_colors[4], PL_colors[5], s);
21791 #ifdef RE_TRACK_PATTERN_OFFSETS
21793 Safefree(ri->u.offsets); /* 20010421 MJD */
21795 if (ri->code_blocks)
21796 S_free_codeblocks(aTHX_ ri->code_blocks);
21799 int n = ri->data->count;
21802 /* If you add a ->what type here, update the comment in regcomp.h */
21803 switch (ri->data->what[n]) {
21809 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
21812 Safefree(ri->data->data[n]);
21818 { /* Aho Corasick add-on structure for a trie node.
21819 Used in stclass optimization only */
21821 reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
21822 #ifdef USE_ITHREADS
21826 refcount = --aho->refcount;
21829 PerlMemShared_free(aho->states);
21830 PerlMemShared_free(aho->fail);
21831 /* do this last!!!! */
21832 PerlMemShared_free(ri->data->data[n]);
21833 /* we should only ever get called once, so
21834 * assert as much, and also guard the free
21835 * which /might/ happen twice. At the least
21836 * it will make code anlyzers happy and it
21837 * doesn't cost much. - Yves */
21838 assert(ri->regstclass);
21839 if (ri->regstclass) {
21840 PerlMemShared_free(ri->regstclass);
21841 ri->regstclass = 0;
21848 /* trie structure. */
21850 reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
21851 #ifdef USE_ITHREADS
21855 refcount = --trie->refcount;
21858 PerlMemShared_free(trie->charmap);
21859 PerlMemShared_free(trie->states);
21860 PerlMemShared_free(trie->trans);
21862 PerlMemShared_free(trie->bitmap);
21864 PerlMemShared_free(trie->jump);
21865 PerlMemShared_free(trie->wordinfo);
21866 /* do this last!!!! */
21867 PerlMemShared_free(ri->data->data[n]);
21872 Perl_croak(aTHX_ "panic: regfree data code '%c'",
21873 ri->data->what[n]);
21876 Safefree(ri->data->what);
21877 Safefree(ri->data);
21883 #define av_dup_inc(s, t) MUTABLE_AV(sv_dup_inc((const SV *)s, t))
21884 #define hv_dup_inc(s, t) MUTABLE_HV(sv_dup_inc((const SV *)s, t))
21885 #define SAVEPVN(p, n) ((p) ? savepvn(p, n) : NULL)
21888 re_dup_guts - duplicate a regexp.
21890 This routine is expected to clone a given regexp structure. It is only
21891 compiled under USE_ITHREADS.
21893 After all of the core data stored in struct regexp is duplicated
21894 the regexp_engine.dupe method is used to copy any private data
21895 stored in the *pprivate pointer. This allows extensions to handle
21896 any duplication it needs to do.
21898 See pregfree() and regfree_internal() if you change anything here.
21900 #if defined(USE_ITHREADS)
21901 #ifndef PERL_IN_XSUB_RE
21903 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
21907 const struct regexp *r = ReANY(sstr);
21908 struct regexp *ret = ReANY(dstr);
21910 PERL_ARGS_ASSERT_RE_DUP_GUTS;
21912 npar = r->nparens+1;
21913 Newx(ret->offs, npar, regexp_paren_pair);
21914 Copy(r->offs, ret->offs, npar, regexp_paren_pair);
21916 if (ret->substrs) {
21917 /* Do it this way to avoid reading from *r after the StructCopy().
21918 That way, if any of the sv_dup_inc()s dislodge *r from the L1
21919 cache, it doesn't matter. */
21921 const bool anchored = r->check_substr
21922 ? r->check_substr == r->substrs->data[0].substr
21923 : r->check_utf8 == r->substrs->data[0].utf8_substr;
21924 Newx(ret->substrs, 1, struct reg_substr_data);
21925 StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
21927 for (i = 0; i < 2; i++) {
21928 ret->substrs->data[i].substr =
21929 sv_dup_inc(ret->substrs->data[i].substr, param);
21930 ret->substrs->data[i].utf8_substr =
21931 sv_dup_inc(ret->substrs->data[i].utf8_substr, param);
21934 /* check_substr and check_utf8, if non-NULL, point to either their
21935 anchored or float namesakes, and don't hold a second reference. */
21937 if (ret->check_substr) {
21939 assert(r->check_utf8 == r->substrs->data[0].utf8_substr);
21941 ret->check_substr = ret->substrs->data[0].substr;
21942 ret->check_utf8 = ret->substrs->data[0].utf8_substr;
21944 assert(r->check_substr == r->substrs->data[1].substr);
21945 assert(r->check_utf8 == r->substrs->data[1].utf8_substr);
21947 ret->check_substr = ret->substrs->data[1].substr;
21948 ret->check_utf8 = ret->substrs->data[1].utf8_substr;
21950 } else if (ret->check_utf8) {
21952 ret->check_utf8 = ret->substrs->data[0].utf8_substr;
21954 ret->check_utf8 = ret->substrs->data[1].utf8_substr;
21959 RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
21960 ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
21961 if (r->recurse_locinput)
21962 Newx(ret->recurse_locinput, r->nparens + 1, char *);
21965 RXi_SET(ret, CALLREGDUPE_PVT(dstr, param));
21967 if (RX_MATCH_COPIED(dstr))
21968 ret->subbeg = SAVEPVN(ret->subbeg, ret->sublen);
21970 ret->subbeg = NULL;
21971 #ifdef PERL_ANY_COW
21972 ret->saved_copy = NULL;
21975 /* Whether mother_re be set or no, we need to copy the string. We
21976 cannot refrain from copying it when the storage points directly to
21977 our mother regexp, because that's
21978 1: a buffer in a different thread
21979 2: something we no longer hold a reference on
21980 so we need to copy it locally. */
21981 RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED_const(sstr), SvCUR(sstr)+1);
21982 /* set malloced length to a non-zero value so it will be freed
21983 * (otherwise in combination with SVf_FAKE it looks like an alien
21984 * buffer). It doesn't have to be the actual malloced size, since it
21985 * should never be grown */
21986 SvLEN_set(dstr, SvCUR(sstr)+1);
21987 ret->mother_re = NULL;
21989 #endif /* PERL_IN_XSUB_RE */
21994 This is the internal complement to regdupe() which is used to copy
21995 the structure pointed to by the *pprivate pointer in the regexp.
21996 This is the core version of the extension overridable cloning hook.
21997 The regexp structure being duplicated will be copied by perl prior
21998 to this and will be provided as the regexp *r argument, however
21999 with the /old/ structures pprivate pointer value. Thus this routine
22000 may override any copying normally done by perl.
22002 It returns a pointer to the new regexp_internal structure.
22006 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
22009 struct regexp *const r = ReANY(rx);
22010 regexp_internal *reti;
22012 RXi_GET_DECL(r, ri);
22014 PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
22018 Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode),
22019 char, regexp_internal);
22020 Copy(ri->program, reti->program, len+1, regnode);
22023 if (ri->code_blocks) {
22025 Newx(reti->code_blocks, 1, struct reg_code_blocks);
22026 Newx(reti->code_blocks->cb, ri->code_blocks->count,
22027 struct reg_code_block);
22028 Copy(ri->code_blocks->cb, reti->code_blocks->cb,
22029 ri->code_blocks->count, struct reg_code_block);
22030 for (n = 0; n < ri->code_blocks->count; n++)
22031 reti->code_blocks->cb[n].src_regex = (REGEXP*)
22032 sv_dup_inc((SV*)(ri->code_blocks->cb[n].src_regex), param);
22033 reti->code_blocks->count = ri->code_blocks->count;
22034 reti->code_blocks->refcnt = 1;
22037 reti->code_blocks = NULL;
22039 reti->regstclass = NULL;
22042 struct reg_data *d;
22043 const int count = ri->data->count;
22046 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
22047 char, struct reg_data);
22048 Newx(d->what, count, U8);
22051 for (i = 0; i < count; i++) {
22052 d->what[i] = ri->data->what[i];
22053 switch (d->what[i]) {
22054 /* see also regcomp.h and regfree_internal() */
22055 case 'a': /* actually an AV, but the dup function is identical.
22056 values seem to be "plain sv's" generally. */
22057 case 'r': /* a compiled regex (but still just another SV) */
22058 case 's': /* an RV (currently only used for an RV to an AV by the ANYOF code)
22059 this use case should go away, the code could have used
22060 'a' instead - see S_set_ANYOF_arg() for array contents. */
22061 case 'S': /* actually an SV, but the dup function is identical. */
22062 case 'u': /* actually an HV, but the dup function is identical.
22063 values are "plain sv's" */
22064 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
22067 /* Synthetic Start Class - "Fake" charclass we generate to optimize
22068 * patterns which could start with several different things. Pre-TRIE
22069 * this was more important than it is now, however this still helps
22070 * in some places, for instance /x?a+/ might produce a SSC equivalent
22071 * to [xa]. This is used by Perl_re_intuit_start() and S_find_byclass()
22074 /* This is cheating. */
22075 Newx(d->data[i], 1, regnode_ssc);
22076 StructCopy(ri->data->data[i], d->data[i], regnode_ssc);
22077 reti->regstclass = (regnode*)d->data[i];
22080 /* AHO-CORASICK fail table */
22081 /* Trie stclasses are readonly and can thus be shared
22082 * without duplication. We free the stclass in pregfree
22083 * when the corresponding reg_ac_data struct is freed.
22085 reti->regstclass= ri->regstclass;
22088 /* TRIE transition table */
22090 ((reg_trie_data*)ri->data->data[i])->refcount++;
22093 case 'l': /* (?{...}) or (??{ ... }) code (cb->block) */
22094 case 'L': /* same when RExC_pm_flags & PMf_HAS_CV and code
22095 is not from another regexp */
22096 d->data[i] = ri->data->data[i];
22099 Perl_croak(aTHX_ "panic: re_dup_guts unknown data code '%c'",
22100 ri->data->what[i]);
22109 reti->name_list_idx = ri->name_list_idx;
22111 #ifdef RE_TRACK_PATTERN_OFFSETS
22112 if (ri->u.offsets) {
22113 Newx(reti->u.offsets, 2*len+1, U32);
22114 Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
22117 SetProgLen(reti, len);
22120 return (void*)reti;
22123 #endif /* USE_ITHREADS */
22125 #ifndef PERL_IN_XSUB_RE
22128 - regnext - dig the "next" pointer out of a node
22131 Perl_regnext(pTHX_ regnode *p)
22138 if (OP(p) > REGNODE_MAX) { /* regnode.type is unsigned */
22139 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
22140 (int)OP(p), (int)REGNODE_MAX);
22143 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
22153 S_re_croak(pTHX_ bool utf8, const char* pat,...)
22156 STRLEN len = strlen(pat);
22159 const char *message;
22161 PERL_ARGS_ASSERT_RE_CROAK;
22165 Copy(pat, buf, len , char);
22167 buf[len + 1] = '\0';
22168 va_start(args, pat);
22169 msv = vmess(buf, &args);
22171 message = SvPV_const(msv, len);
22174 Copy(message, buf, len , char);
22175 /* len-1 to avoid \n */
22176 Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(utf8, len-1, buf));
22179 /* XXX Here's a total kludge. But we need to re-enter for swash routines. */
22181 #ifndef PERL_IN_XSUB_RE
22183 Perl_save_re_context(pTHX)
22188 /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
22191 const REGEXP * const rx = PM_GETRE(PL_curpm);
22193 nparens = RX_NPARENS(rx);
22196 /* RT #124109. This is a complete hack; in the SWASHNEW case we know
22197 * that PL_curpm will be null, but that utf8.pm and the modules it
22198 * loads will only use $1..$3.
22199 * The t/porting/re_context.t test file checks this assumption.
22204 for (i = 1; i <= nparens; i++) {
22205 char digits[TYPE_CHARS(long)];
22206 const STRLEN len = my_snprintf(digits, sizeof(digits),
22208 GV *const *const gvp
22209 = (GV**)hv_fetch(PL_defstash, digits, len, 0);
22212 GV * const gv = *gvp;
22213 if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
22223 S_put_code_point(pTHX_ SV *sv, UV c)
22225 PERL_ARGS_ASSERT_PUT_CODE_POINT;
22228 Perl_sv_catpvf(aTHX_ sv, "\\x{%04" UVXf "}", c);
22230 else if (isPRINT(c)) {
22231 const char string = (char) c;
22233 /* We use {phrase} as metanotation in the class, so also escape literal
22235 if (isBACKSLASHED_PUNCT(c) || c == '{' || c == '}')
22236 sv_catpvs(sv, "\\");
22237 sv_catpvn(sv, &string, 1);
22239 else if (isMNEMONIC_CNTRL(c)) {
22240 Perl_sv_catpvf(aTHX_ sv, "%s", cntrl_to_mnemonic((U8) c));
22243 Perl_sv_catpvf(aTHX_ sv, "\\x%02X", (U8) c);
22247 #define MAX_PRINT_A MAX_PRINT_A_FOR_USE_ONLY_BY_REGCOMP_DOT_C
22250 S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals)
22252 /* Appends to 'sv' a displayable version of the range of code points from
22253 * 'start' to 'end'. Mnemonics (like '\r') are used for the few controls
22254 * that have them, when they occur at the beginning or end of the range.
22255 * It uses hex to output the remaining code points, unless 'allow_literals'
22256 * is true, in which case the printable ASCII ones are output as-is (though
22257 * some of these will be escaped by put_code_point()).
22259 * NOTE: This is designed only for printing ranges of code points that fit
22260 * inside an ANYOF bitmap. Higher code points are simply suppressed
22263 const unsigned int min_range_count = 3;
22265 assert(start <= end);
22267 PERL_ARGS_ASSERT_PUT_RANGE;
22269 while (start <= end) {
22271 const char * format;
22273 if (end - start < min_range_count) {
22275 /* Output chars individually when they occur in short ranges */
22276 for (; start <= end; start++) {
22277 put_code_point(sv, start);
22282 /* If permitted by the input options, and there is a possibility that
22283 * this range contains a printable literal, look to see if there is
22285 if (allow_literals && start <= MAX_PRINT_A) {
22287 /* If the character at the beginning of the range isn't an ASCII
22288 * printable, effectively split the range into two parts:
22289 * 1) the portion before the first such printable,
22291 * and output them separately. */
22292 if (! isPRINT_A(start)) {
22293 UV temp_end = start + 1;
22295 /* There is no point looking beyond the final possible
22296 * printable, in MAX_PRINT_A */
22297 UV max = MIN(end, MAX_PRINT_A);
22299 while (temp_end <= max && ! isPRINT_A(temp_end)) {
22303 /* Here, temp_end points to one beyond the first printable if
22304 * found, or to one beyond 'max' if not. If none found, make
22305 * sure that we use the entire range */
22306 if (temp_end > MAX_PRINT_A) {
22307 temp_end = end + 1;
22310 /* Output the first part of the split range: the part that
22311 * doesn't have printables, with the parameter set to not look
22312 * for literals (otherwise we would infinitely recurse) */
22313 put_range(sv, start, temp_end - 1, FALSE);
22315 /* The 2nd part of the range (if any) starts here. */
22318 /* We do a continue, instead of dropping down, because even if
22319 * the 2nd part is non-empty, it could be so short that we want
22320 * to output it as individual characters, as tested for at the
22321 * top of this loop. */
22325 /* Here, 'start' is a printable ASCII. If it is an alphanumeric,
22326 * output a sub-range of just the digits or letters, then process
22327 * the remaining portion as usual. */
22328 if (isALPHANUMERIC_A(start)) {
22329 UV mask = (isDIGIT_A(start))
22334 UV temp_end = start + 1;
22336 /* Find the end of the sub-range that includes just the
22337 * characters in the same class as the first character in it */
22338 while (temp_end <= end && _generic_isCC_A(temp_end, mask)) {
22343 /* For short ranges, don't duplicate the code above to output
22344 * them; just call recursively */
22345 if (temp_end - start < min_range_count) {
22346 put_range(sv, start, temp_end, FALSE);
22348 else { /* Output as a range */
22349 put_code_point(sv, start);
22350 sv_catpvs(sv, "-");
22351 put_code_point(sv, temp_end);
22353 start = temp_end + 1;
22357 /* We output any other printables as individual characters */
22358 if (isPUNCT_A(start) || isSPACE_A(start)) {
22359 while (start <= end && (isPUNCT_A(start)
22360 || isSPACE_A(start)))
22362 put_code_point(sv, start);
22367 } /* End of looking for literals */
22369 /* Here is not to output as a literal. Some control characters have
22370 * mnemonic names. Split off any of those at the beginning and end of
22371 * the range to print mnemonically. It isn't possible for many of
22372 * these to be in a row, so this won't overwhelm with output */
22374 && (isMNEMONIC_CNTRL(start) || isMNEMONIC_CNTRL(end)))
22376 while (isMNEMONIC_CNTRL(start) && start <= end) {
22377 put_code_point(sv, start);
22381 /* If this didn't take care of the whole range ... */
22382 if (start <= end) {
22384 /* Look backwards from the end to find the final non-mnemonic
22387 while (isMNEMONIC_CNTRL(temp_end)) {
22391 /* And separately output the interior range that doesn't start
22392 * or end with mnemonics */
22393 put_range(sv, start, temp_end, FALSE);
22395 /* Then output the mnemonic trailing controls */
22396 start = temp_end + 1;
22397 while (start <= end) {
22398 put_code_point(sv, start);
22405 /* As a final resort, output the range or subrange as hex. */
22407 if (start >= NUM_ANYOF_CODE_POINTS) {
22410 else { /* Have to split range at the bitmap boundary */
22411 this_end = (end < NUM_ANYOF_CODE_POINTS)
22413 : NUM_ANYOF_CODE_POINTS - 1;
22415 #if NUM_ANYOF_CODE_POINTS > 256
22416 format = (this_end < 256)
22417 ? "\\x%02" UVXf "-\\x%02" UVXf
22418 : "\\x{%04" UVXf "}-\\x{%04" UVXf "}";
22420 format = "\\x%02" UVXf "-\\x%02" UVXf;
22422 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
22423 Perl_sv_catpvf(aTHX_ sv, format, start, this_end);
22424 GCC_DIAG_RESTORE_STMT;
22430 S_put_charclass_bitmap_innards_invlist(pTHX_ SV *sv, SV* invlist)
22432 /* Concatenate onto the PV in 'sv' a displayable form of the inversion list
22436 bool allow_literals = TRUE;
22438 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_INVLIST;
22440 /* Generally, it is more readable if printable characters are output as
22441 * literals, but if a range (nearly) spans all of them, it's best to output
22442 * it as a single range. This code will use a single range if all but 2
22443 * ASCII printables are in it */
22444 invlist_iterinit(invlist);
22445 while (invlist_iternext(invlist, &start, &end)) {
22447 /* If the range starts beyond the final printable, it doesn't have any
22449 if (start > MAX_PRINT_A) {
22453 /* In both ASCII and EBCDIC, a SPACE is the lowest printable. To span
22454 * all but two, the range must start and end no later than 2 from
22456 if (start < ' ' + 2 && end > MAX_PRINT_A - 2) {
22457 if (end > MAX_PRINT_A) {
22463 if (end - start >= MAX_PRINT_A - ' ' - 2) {
22464 allow_literals = FALSE;
22469 invlist_iterfinish(invlist);
22471 /* Here we have figured things out. Output each range */
22472 invlist_iterinit(invlist);
22473 while (invlist_iternext(invlist, &start, &end)) {
22474 if (start >= NUM_ANYOF_CODE_POINTS) {
22477 put_range(sv, start, end, allow_literals);
22479 invlist_iterfinish(invlist);
22485 S_put_charclass_bitmap_innards_common(pTHX_
22486 SV* invlist, /* The bitmap */
22487 SV* posixes, /* Under /l, things like [:word:], \S */
22488 SV* only_utf8, /* Under /d, matches iff the target is UTF-8 */
22489 SV* not_utf8, /* /d, matches iff the target isn't UTF-8 */
22490 SV* only_utf8_locale, /* Under /l, matches if the locale is UTF-8 */
22491 const bool invert /* Is the result to be inverted? */
22494 /* Create and return an SV containing a displayable version of the bitmap
22495 * and associated information determined by the input parameters. If the
22496 * output would have been only the inversion indicator '^', NULL is instead
22502 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_COMMON;
22505 output = newSVpvs("^");
22508 output = newSVpvs("");
22511 /* First, the code points in the bitmap that are unconditionally there */
22512 put_charclass_bitmap_innards_invlist(output, invlist);
22514 /* Traditionally, these have been placed after the main code points */
22516 sv_catsv(output, posixes);
22519 if (only_utf8 && _invlist_len(only_utf8)) {
22520 Perl_sv_catpvf(aTHX_ output, "%s{utf8}%s", PL_colors[1], PL_colors[0]);
22521 put_charclass_bitmap_innards_invlist(output, only_utf8);
22524 if (not_utf8 && _invlist_len(not_utf8)) {
22525 Perl_sv_catpvf(aTHX_ output, "%s{not utf8}%s", PL_colors[1], PL_colors[0]);
22526 put_charclass_bitmap_innards_invlist(output, not_utf8);
22529 if (only_utf8_locale && _invlist_len(only_utf8_locale)) {
22530 Perl_sv_catpvf(aTHX_ output, "%s{utf8 locale}%s", PL_colors[1], PL_colors[0]);
22531 put_charclass_bitmap_innards_invlist(output, only_utf8_locale);
22533 /* This is the only list in this routine that can legally contain code
22534 * points outside the bitmap range. The call just above to
22535 * 'put_charclass_bitmap_innards_invlist' will simply suppress them, so
22536 * output them here. There's about a half-dozen possible, and none in
22537 * contiguous ranges longer than 2 */
22538 if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
22540 SV* above_bitmap = NULL;
22542 _invlist_subtract(only_utf8_locale, PL_InBitmap, &above_bitmap);
22544 invlist_iterinit(above_bitmap);
22545 while (invlist_iternext(above_bitmap, &start, &end)) {
22548 for (i = start; i <= end; i++) {
22549 put_code_point(output, i);
22552 invlist_iterfinish(above_bitmap);
22553 SvREFCNT_dec_NN(above_bitmap);
22557 if (invert && SvCUR(output) == 1) {
22565 S_put_charclass_bitmap_innards(pTHX_ SV *sv,
22567 SV *nonbitmap_invlist,
22568 SV *only_utf8_locale_invlist,
22569 const regnode * const node,
22571 const bool force_as_is_display)
22573 /* Appends to 'sv' a displayable version of the innards of the bracketed
22574 * character class defined by the other arguments:
22575 * 'bitmap' points to the bitmap, or NULL if to ignore that.
22576 * 'nonbitmap_invlist' is an inversion list of the code points that are in
22577 * the bitmap range, but for some reason aren't in the bitmap; NULL if
22578 * none. The reasons for this could be that they require some
22579 * condition such as the target string being or not being in UTF-8
22580 * (under /d), or because they came from a user-defined property that
22581 * was not resolved at the time of the regex compilation (under /u)
22582 * 'only_utf8_locale_invlist' is an inversion list of the code points that
22583 * are valid only if the runtime locale is a UTF-8 one; NULL if none
22584 * 'node' is the regex pattern ANYOF node. It is needed only when the
22585 * above two parameters are not null, and is passed so that this
22586 * routine can tease apart the various reasons for them.
22587 * 'flags' is the flags field of 'node'
22588 * 'force_as_is_display' is TRUE if this routine should definitely NOT try
22589 * to invert things to see if that leads to a cleaner display. If
22590 * FALSE, this routine is free to use its judgment about doing this.
22592 * It returns TRUE if there was actually something output. (It may be that
22593 * the bitmap, etc is empty.)
22595 * When called for outputting the bitmap of a non-ANYOF node, just pass the
22596 * bitmap, with the succeeding parameters set to NULL, and the final one to
22600 /* In general, it tries to display the 'cleanest' representation of the
22601 * innards, choosing whether to display them inverted or not, regardless of
22602 * whether the class itself is to be inverted. However, there are some
22603 * cases where it can't try inverting, as what actually matches isn't known
22604 * until runtime, and hence the inversion isn't either. */
22607 bool inverting_allowed = ! force_as_is_display;
22610 STRLEN orig_sv_cur = SvCUR(sv);
22612 SV* invlist; /* Inversion list we accumulate of code points that
22613 are unconditionally matched */
22614 SV* only_utf8 = NULL; /* Under /d, list of matches iff the target is
22616 SV* not_utf8 = NULL; /* /d, list of matches iff the target isn't UTF-8
22618 SV* posixes = NULL; /* Under /l, string of things like [:word:], \D */
22619 SV* only_utf8_locale = NULL; /* Under /l, list of matches if the locale
22622 SV* as_is_display; /* The output string when we take the inputs
22624 SV* inverted_display; /* The output string when we invert the inputs */
22626 bool invert = cBOOL(flags & ANYOF_INVERT); /* Is the input to be inverted
22628 /* We are biased in favor of displaying things without them being inverted,
22629 * as that is generally easier to understand */
22630 const int bias = 5;
22632 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS;
22634 /* Start off with whatever code points are passed in. (We clone, so we
22635 * don't change the caller's list) */
22636 if (nonbitmap_invlist) {
22637 assert(invlist_highest(nonbitmap_invlist) < NUM_ANYOF_CODE_POINTS);
22638 invlist = invlist_clone(nonbitmap_invlist, NULL);
22640 else { /* Worst case size is every other code point is matched */
22641 invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2);
22645 if (OP(node) == ANYOFD) {
22647 /* This flag indicates that the code points below 0x100 in the
22648 * nonbitmap list are precisely the ones that match only when the
22649 * target is UTF-8 (they should all be non-ASCII). */
22650 if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
22652 _invlist_intersection(invlist, PL_UpperLatin1, &only_utf8);
22653 _invlist_subtract(invlist, only_utf8, &invlist);
22656 /* And this flag for matching all non-ASCII 0xFF and below */
22657 if (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
22659 not_utf8 = invlist_clone(PL_UpperLatin1, NULL);
22662 else if (OP(node) == ANYOFL || OP(node) == ANYOFPOSIXL) {
22664 /* If either of these flags are set, what matches isn't
22665 * determinable except during execution, so don't know enough here
22667 if (flags & (ANYOFL_FOLD|ANYOF_MATCHES_POSIXL)) {
22668 inverting_allowed = FALSE;
22671 /* What the posix classes match also varies at runtime, so these
22672 * will be output symbolically. */
22673 if (ANYOF_POSIXL_TEST_ANY_SET(node)) {
22676 posixes = newSVpvs("");
22677 for (i = 0; i < ANYOF_POSIXL_MAX; i++) {
22678 if (ANYOF_POSIXL_TEST(node, i)) {
22679 sv_catpv(posixes, anyofs[i]);
22686 /* Accumulate the bit map into the unconditional match list */
22688 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
22689 if (BITMAP_TEST(bitmap, i)) {
22692 i < NUM_ANYOF_CODE_POINTS && BITMAP_TEST(bitmap, i);
22695 invlist = _add_range_to_invlist(invlist, start, i-1);
22700 /* Make sure that the conditional match lists don't have anything in them
22701 * that match unconditionally; otherwise the output is quite confusing.
22702 * This could happen if the code that populates these misses some
22705 _invlist_subtract(only_utf8, invlist, &only_utf8);
22708 _invlist_subtract(not_utf8, invlist, ¬_utf8);
22711 if (only_utf8_locale_invlist) {
22713 /* Since this list is passed in, we have to make a copy before
22715 only_utf8_locale = invlist_clone(only_utf8_locale_invlist, NULL);
22717 _invlist_subtract(only_utf8_locale, invlist, &only_utf8_locale);
22719 /* And, it can get really weird for us to try outputting an inverted
22720 * form of this list when it has things above the bitmap, so don't even
22722 if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
22723 inverting_allowed = FALSE;
22727 /* Calculate what the output would be if we take the input as-is */
22728 as_is_display = put_charclass_bitmap_innards_common(invlist,
22735 /* If have to take the output as-is, just do that */
22736 if (! inverting_allowed) {
22737 if (as_is_display) {
22738 sv_catsv(sv, as_is_display);
22739 SvREFCNT_dec_NN(as_is_display);
22742 else { /* But otherwise, create the output again on the inverted input, and
22743 use whichever version is shorter */
22745 int inverted_bias, as_is_bias;
22747 /* We will apply our bias to whichever of the results doesn't have
22757 inverted_bias = bias;
22760 /* Now invert each of the lists that contribute to the output,
22761 * excluding from the result things outside the possible range */
22763 /* For the unconditional inversion list, we have to add in all the
22764 * conditional code points, so that when inverted, they will be gone
22766 _invlist_union(only_utf8, invlist, &invlist);
22767 _invlist_union(not_utf8, invlist, &invlist);
22768 _invlist_union(only_utf8_locale, invlist, &invlist);
22769 _invlist_invert(invlist);
22770 _invlist_intersection(invlist, PL_InBitmap, &invlist);
22773 _invlist_invert(only_utf8);
22774 _invlist_intersection(only_utf8, PL_UpperLatin1, &only_utf8);
22776 else if (not_utf8) {
22778 /* If a code point matches iff the target string is not in UTF-8,
22779 * then complementing the result has it not match iff not in UTF-8,
22780 * which is the same thing as matching iff it is UTF-8. */
22781 only_utf8 = not_utf8;
22785 if (only_utf8_locale) {
22786 _invlist_invert(only_utf8_locale);
22787 _invlist_intersection(only_utf8_locale,
22789 &only_utf8_locale);
22792 inverted_display = put_charclass_bitmap_innards_common(
22797 only_utf8_locale, invert);
22799 /* Use the shortest representation, taking into account our bias
22800 * against showing it inverted */
22801 if ( inverted_display
22802 && ( ! as_is_display
22803 || ( SvCUR(inverted_display) + inverted_bias
22804 < SvCUR(as_is_display) + as_is_bias)))
22806 sv_catsv(sv, inverted_display);
22808 else if (as_is_display) {
22809 sv_catsv(sv, as_is_display);
22812 SvREFCNT_dec(as_is_display);
22813 SvREFCNT_dec(inverted_display);
22816 SvREFCNT_dec_NN(invlist);
22817 SvREFCNT_dec(only_utf8);
22818 SvREFCNT_dec(not_utf8);
22819 SvREFCNT_dec(posixes);
22820 SvREFCNT_dec(only_utf8_locale);
22822 return SvCUR(sv) > orig_sv_cur;
22825 #define CLEAR_OPTSTART \
22826 if (optstart) STMT_START { \
22827 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ \
22828 " (%" IVdf " nodes)\n", (IV)(node - optstart))); \
22832 #define DUMPUNTIL(b,e) \
22834 node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
22836 STATIC const regnode *
22837 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
22838 const regnode *last, const regnode *plast,
22839 SV* sv, I32 indent, U32 depth)
22841 U8 op = PSEUDO; /* Arbitrary non-END op. */
22842 const regnode *next;
22843 const regnode *optstart= NULL;
22845 RXi_GET_DECL(r, ri);
22846 DECLARE_AND_GET_RE_DEBUG_FLAGS;
22848 PERL_ARGS_ASSERT_DUMPUNTIL;
22850 #ifdef DEBUG_DUMPUNTIL
22851 Perl_re_printf( aTHX_ "--- %d : %d - %d - %d\n", indent, node-start,
22852 last ? last-start : 0, plast ? plast-start : 0);
22855 if (plast && plast < last)
22858 while (PL_regkind[op] != END && (!last || node < last)) {
22860 /* While that wasn't END last time... */
22863 if (op == CLOSE || op == SRCLOSE || op == WHILEM)
22865 next = regnext((regnode *)node);
22868 if (OP(node) == OPTIMIZED) {
22869 if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
22876 regprop(r, sv, node, NULL, NULL);
22877 Perl_re_printf( aTHX_ "%4" IVdf ":%*s%s", (IV)(node - start),
22878 (int)(2*indent + 1), "", SvPVX_const(sv));
22880 if (OP(node) != OPTIMIZED) {
22881 if (next == NULL) /* Next ptr. */
22882 Perl_re_printf( aTHX_ " (0)");
22883 else if (PL_regkind[(U8)op] == BRANCH
22884 && PL_regkind[OP(next)] != BRANCH )
22885 Perl_re_printf( aTHX_ " (FAIL)");
22887 Perl_re_printf( aTHX_ " (%" IVdf ")", (IV)(next - start));
22888 Perl_re_printf( aTHX_ "\n");
22892 if (PL_regkind[(U8)op] == BRANCHJ) {
22895 const regnode *nnode = (OP(next) == LONGJMP
22896 ? regnext((regnode *)next)
22898 if (last && nnode > last)
22900 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
22903 else if (PL_regkind[(U8)op] == BRANCH) {
22905 DUMPUNTIL(NEXTOPER(node), next);
22907 else if ( PL_regkind[(U8)op] == TRIE ) {
22908 const regnode *this_trie = node;
22909 const char op = OP(node);
22910 const U32 n = ARG(node);
22911 const reg_ac_data * const ac = op>=AHOCORASICK ?
22912 (reg_ac_data *)ri->data->data[n] :
22914 const reg_trie_data * const trie =
22915 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
22917 AV *const trie_words
22918 = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
22920 const regnode *nextbranch= NULL;
22923 for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
22924 SV ** const elem_ptr = av_fetch(trie_words, word_idx, 0);
22926 Perl_re_indentf( aTHX_ "%s ",
22929 ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr),
22930 SvCUR(*elem_ptr), PL_dump_re_max_len,
22931 PL_colors[0], PL_colors[1],
22933 ? PERL_PV_ESCAPE_UNI
22935 | PERL_PV_PRETTY_ELLIPSES
22936 | PERL_PV_PRETTY_LTGT
22941 U16 dist= trie->jump[word_idx+1];
22942 Perl_re_printf( aTHX_ "(%" UVuf ")\n",
22943 (UV)((dist ? this_trie + dist : next) - start));
22946 nextbranch= this_trie + trie->jump[0];
22947 DUMPUNTIL(this_trie + dist, nextbranch);
22949 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
22950 nextbranch= regnext((regnode *)nextbranch);
22952 Perl_re_printf( aTHX_ "\n");
22955 if (last && next > last)
22960 else if ( op == CURLY ) { /* "next" might be very big: optimizer */
22961 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
22962 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
22964 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
22966 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
22968 else if ( op == PLUS || op == STAR) {
22969 DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
22971 else if (PL_regkind[(U8)op] == EXACT || op == ANYOFHs) {
22972 /* Literal string, where present. */
22973 node += NODE_SZ_STR(node) - 1;
22974 node = NEXTOPER(node);
22977 node = NEXTOPER(node);
22978 node += regarglen[(U8)op];
22980 if (op == CURLYX || op == OPEN || op == SROPEN)
22984 #ifdef DEBUG_DUMPUNTIL
22985 Perl_re_printf( aTHX_ "--- %d\n", (int)indent);
22990 #endif /* DEBUGGING */
22992 #ifndef PERL_IN_XSUB_RE
22994 # include "uni_keywords.h"
22997 Perl_init_uniprops(pTHX)
23002 char * dump_len_string;
23004 dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN");
23005 if ( ! dump_len_string
23006 || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL))
23008 PL_dump_re_max_len = 60; /* A reasonable default */
23012 PL_user_def_props = newHV();
23014 # ifdef USE_ITHREADS
23016 HvSHAREKEYS_off(PL_user_def_props);
23017 PL_user_def_props_aTHX = aTHX;
23021 /* Set up the inversion list interpreter-level variables */
23023 PL_XPosix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
23024 PL_XPosix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALNUM]);
23025 PL_XPosix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALPHA]);
23026 PL_XPosix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXBLANK]);
23027 PL_XPosix_ptrs[_CC_CASED] = _new_invlist_C_array(uni_prop_ptrs[UNI_CASED]);
23028 PL_XPosix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXCNTRL]);
23029 PL_XPosix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXDIGIT]);
23030 PL_XPosix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXGRAPH]);
23031 PL_XPosix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXLOWER]);
23032 PL_XPosix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPRINT]);
23033 PL_XPosix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPUNCT]);
23034 PL_XPosix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXSPACE]);
23035 PL_XPosix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXUPPER]);
23036 PL_XPosix_ptrs[_CC_VERTSPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_VERTSPACE]);
23037 PL_XPosix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXWORD]);
23038 PL_XPosix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXXDIGIT]);
23040 PL_Posix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
23041 PL_Posix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALNUM]);
23042 PL_Posix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALPHA]);
23043 PL_Posix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXBLANK]);
23044 PL_Posix_ptrs[_CC_CASED] = PL_Posix_ptrs[_CC_ALPHA];
23045 PL_Posix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXCNTRL]);
23046 PL_Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXDIGIT]);
23047 PL_Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXGRAPH]);
23048 PL_Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXLOWER]);
23049 PL_Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPRINT]);
23050 PL_Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPUNCT]);
23051 PL_Posix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXSPACE]);
23052 PL_Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXUPPER]);
23053 PL_Posix_ptrs[_CC_VERTSPACE] = NULL;
23054 PL_Posix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXWORD]);
23055 PL_Posix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXXDIGIT]);
23057 PL_GCB_invlist = _new_invlist_C_array(_Perl_GCB_invlist);
23058 PL_SB_invlist = _new_invlist_C_array(_Perl_SB_invlist);
23059 PL_WB_invlist = _new_invlist_C_array(_Perl_WB_invlist);
23060 PL_LB_invlist = _new_invlist_C_array(_Perl_LB_invlist);
23061 PL_SCX_invlist = _new_invlist_C_array(_Perl_SCX_invlist);
23063 PL_InBitmap = _new_invlist_C_array(InBitmap_invlist);
23064 PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
23065 PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
23066 PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist);
23068 PL_Assigned_invlist = _new_invlist_C_array(uni_prop_ptrs[UNI_ASSIGNED]);
23070 PL_utf8_perl_idstart = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDSTART]);
23071 PL_utf8_perl_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDCONT]);
23073 PL_utf8_charname_begin = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_BEGIN]);
23074 PL_utf8_charname_continue = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_CONTINUE]);
23076 PL_in_some_fold = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_ANY_FOLDS]);
23077 PL_HasMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
23078 UNI__PERL_FOLDS_TO_MULTI_CHAR]);
23079 PL_InMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
23080 UNI__PERL_IS_IN_MULTI_CHAR_FOLD]);
23081 PL_utf8_toupper = _new_invlist_C_array(Uppercase_Mapping_invlist);
23082 PL_utf8_tolower = _new_invlist_C_array(Lowercase_Mapping_invlist);
23083 PL_utf8_totitle = _new_invlist_C_array(Titlecase_Mapping_invlist);
23084 PL_utf8_tofold = _new_invlist_C_array(Case_Folding_invlist);
23085 PL_utf8_tosimplefold = _new_invlist_C_array(Simple_Case_Folding_invlist);
23086 PL_utf8_foldclosures = _new_invlist_C_array(_Perl_IVCF_invlist);
23087 PL_utf8_mark = _new_invlist_C_array(uni_prop_ptrs[UNI_M]);
23088 PL_CCC_non0_non230 = _new_invlist_C_array(_Perl_CCC_non0_non230_invlist);
23089 PL_Private_Use = _new_invlist_C_array(uni_prop_ptrs[UNI_CO]);
23092 /* The below are used only by deprecated functions. They could be removed */
23093 PL_utf8_xidcont = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDC]);
23094 PL_utf8_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI_IDC]);
23095 PL_utf8_xidstart = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDS]);
23099 /* These four functions are compiled only in regcomp.c, where they have access
23100 * to the data they return. They are a way for re_comp.c to get access to that
23101 * data without having to compile the whole data structures. */
23104 Perl_do_uniprop_match(const char * const key, const U16 key_len)
23106 PERL_ARGS_ASSERT_DO_UNIPROP_MATCH;
23108 return match_uniprop((U8 *) key, key_len);
23112 Perl_get_prop_definition(pTHX_ const int table_index)
23114 PERL_ARGS_ASSERT_GET_PROP_DEFINITION;
23116 /* Create and return the inversion list */
23117 return _new_invlist_C_array(uni_prop_ptrs[table_index]);
23120 const char * const *
23121 Perl_get_prop_values(const int table_index)
23123 PERL_ARGS_ASSERT_GET_PROP_VALUES;
23125 return UNI_prop_value_ptrs[table_index];
23129 Perl_get_deprecated_property_msg(const Size_t warning_offset)
23131 PERL_ARGS_ASSERT_GET_DEPRECATED_PROPERTY_MSG;
23133 return deprecated_property_msgs[warning_offset];
23138 This code was mainly added for backcompat to give a warning for non-portable
23139 code points in user-defined properties. But experiments showed that the
23140 warning in earlier perls were only omitted on overflow, which should be an
23141 error, so there really isnt a backcompat issue, and actually adding the
23142 warning when none was present before might cause breakage, for little gain. So
23143 khw left this code in, but not enabled. Tests were never added.
23146 Ei |const char *|get_extended_utf8_msg|const UV cp
23148 PERL_STATIC_INLINE const char *
23149 S_get_extended_utf8_msg(pTHX_ const UV cp)
23151 U8 dummy[UTF8_MAXBYTES + 1];
23155 uvchr_to_utf8_flags_msgs(dummy, cp, UNICODE_WARN_PERL_EXTENDED,
23158 msg = hv_fetchs(msgs, "text", 0);
23161 (void) sv_2mortal((SV *) msgs);
23163 return SvPVX(*msg);
23167 #endif /* end of ! PERL_IN_XSUB_RE */
23170 S_compile_wildcard(pTHX_ const char * subpattern, const STRLEN len,
23171 const bool ignore_case)
23173 /* Pretends that the input subpattern is qr/subpattern/aam, compiling it
23174 * possibly with /i if the 'ignore_case' parameter is true. Use /aa
23175 * because nothing outside of ASCII will match. Use /m because the input
23176 * string may be a bunch of lines strung together.
23178 * Also sets up the debugging info */
23180 U32 flags = PMf_MULTILINE|PMf_WILDCARD;
23182 SV * subpattern_sv = sv_2mortal(newSVpvn(subpattern, len));
23183 REGEXP * subpattern_re;
23184 DECLARE_AND_GET_RE_DEBUG_FLAGS;
23186 PERL_ARGS_ASSERT_COMPILE_WILDCARD;
23191 set_regex_charset(&flags, REGEX_ASCII_MORE_RESTRICTED_CHARSET);
23193 /* Like in op.c, we copy the compile time pm flags to the rx ones */
23194 rx_flags = flags & RXf_PMf_COMPILETIME;
23196 #ifndef PERL_IN_XSUB_RE
23197 /* Use the core engine if this file is regcomp.c. That means no
23198 * 'use re "Debug ..." is in effect, so the core engine is sufficient */
23199 subpattern_re = Perl_re_op_compile(aTHX_ &subpattern_sv, 1, NULL,
23200 &PL_core_reg_engine,
23204 if (isDEBUG_WILDCARD) {
23205 /* Use the special debugging engine if this file is re_comp.c and wants
23206 * to output the wildcard matching. This uses whatever
23207 * 'use re "Debug ..." is in effect */
23208 subpattern_re = Perl_re_op_compile(aTHX_ &subpattern_sv, 1, NULL,
23214 /* Use the special wildcard engine if this file is re_comp.c and
23215 * doesn't want to output the wildcard matching. This uses whatever
23216 * 'use re "Debug ..." is in effect for compilation, but this engine
23217 * structure has been set up so that it uses the core engine for
23218 * execution, so no execution debugging as a result of re.pm will be
23220 subpattern_re = Perl_re_op_compile(aTHX_ &subpattern_sv, 1, NULL,
23224 /* XXX The above has the effect that any user-supplied regex engine
23225 * won't be called for matching wildcards. That might be good, or bad.
23226 * It could be changed in several ways. The reason it is done the
23227 * current way is to avoid having to save and restore
23228 * ^{^RE_DEBUG_FLAGS} around the execution. save_scalar() perhaps
23229 * could be used. Another suggestion is to keep the authoritative
23230 * value of the debug flags in a thread-local variable and add set/get
23231 * magic to ${^RE_DEBUG_FLAGS} to keep the C level variable up to date.
23232 * Still another is to pass a flag, say in the engine's intflags that
23233 * would be checked each time before doing the debug output */
23237 assert(subpattern_re); /* Should have died if didn't compile successfully */
23238 return subpattern_re;
23242 S_execute_wildcard(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
23243 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
23246 DECLARE_AND_GET_RE_DEBUG_FLAGS;
23248 PERL_ARGS_ASSERT_EXECUTE_WILDCARD;
23252 /* The compilation has set things up so that if the program doesn't want to
23253 * see the wildcard matching procedure, it will get the core execution
23254 * engine, which is subject only to -Dr. So we have to turn that off
23255 * around this procedure */
23256 if (! isDEBUG_WILDCARD) {
23257 /* Note! Casts away 'volatile' */
23259 PL_debug &= ~ DEBUG_r_FLAG;
23262 result = CALLREGEXEC(prog, stringarg, strend, strbeg, minend, screamer,
23270 S_handle_user_defined_property(pTHX_
23272 /* Parses the contents of a user-defined property definition; returning the
23273 * expanded definition if possible. If so, the return is an inversion
23276 * If there are subroutines that are part of the expansion and which aren't
23277 * known at the time of the call to this function, this returns what
23278 * parse_uniprop_string() returned for the first one encountered.
23280 * If an error was found, NULL is returned, and 'msg' gets a suitable
23281 * message appended to it. (Appending allows the back trace of how we got
23282 * to the faulty definition to be displayed through nested calls of
23283 * user-defined subs.)
23285 * The caller IS responsible for freeing any returned SV.
23287 * The syntax of the contents is pretty much described in perlunicode.pod,
23288 * but we also allow comments on each line */
23290 const char * name, /* Name of property */
23291 const STRLEN name_len, /* The name's length in bytes */
23292 const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */
23293 const bool to_fold, /* ? Is this under /i */
23294 const bool runtime, /* ? Are we in compile- or run-time */
23295 const bool deferrable, /* Is it ok for this property's full definition
23296 to be deferred until later? */
23297 SV* contents, /* The property's definition */
23298 bool *user_defined_ptr, /* This will be set TRUE as we wouldn't be
23299 getting called unless this is thought to be
23300 a user-defined property */
23301 SV * msg, /* Any error or warning msg(s) are appended to
23303 const STRLEN level) /* Recursion level of this call */
23306 const char * string = SvPV_const(contents, len);
23307 const char * const e = string + len;
23308 const bool is_contents_utf8 = cBOOL(SvUTF8(contents));
23309 const STRLEN msgs_length_on_entry = SvCUR(msg);
23311 const char * s0 = string; /* Points to first byte in the current line
23312 being parsed in 'string' */
23313 const char overflow_msg[] = "Code point too large in \"";
23314 SV* running_definition = NULL;
23316 PERL_ARGS_ASSERT_HANDLE_USER_DEFINED_PROPERTY;
23318 *user_defined_ptr = TRUE;
23320 /* Look at each line */
23322 const char * s; /* Current byte */
23323 char op = '+'; /* Default operation is 'union' */
23324 IV min = 0; /* range begin code point */
23325 IV max = -1; /* and range end */
23326 SV* this_definition;
23328 /* Skip comment lines */
23330 s0 = strchr(s0, '\n');
23338 /* For backcompat, allow an empty first line */
23344 /* First character in the line may optionally be the operation */
23353 /* If the line is one or two hex digits separated by blank space, its
23354 * a range; otherwise it is either another user-defined property or an
23359 if (! isXDIGIT(*s)) {
23360 goto check_if_property;
23363 do { /* Each new hex digit will add 4 bits. */
23364 if (min > ( (IV) MAX_LEGAL_CP >> 4)) {
23365 s = strchr(s, '\n');
23369 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23370 sv_catpv(msg, overflow_msg);
23371 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23372 UTF8fARG(is_contents_utf8, s - s0, s0));
23373 sv_catpvs(msg, "\"");
23374 goto return_failure;
23377 /* Accumulate this digit into the value */
23378 min = (min << 4) + READ_XDIGIT(s);
23379 } while (isXDIGIT(*s));
23381 while (isBLANK(*s)) { s++; }
23383 /* We allow comments at the end of the line */
23385 s = strchr(s, '\n');
23391 else if (s < e && *s != '\n') {
23392 if (! isXDIGIT(*s)) {
23393 goto check_if_property;
23396 /* Look for the high point of the range */
23399 if (max > ( (IV) MAX_LEGAL_CP >> 4)) {
23400 s = strchr(s, '\n');
23404 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23405 sv_catpv(msg, overflow_msg);
23406 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23407 UTF8fARG(is_contents_utf8, s - s0, s0));
23408 sv_catpvs(msg, "\"");
23409 goto return_failure;
23412 max = (max << 4) + READ_XDIGIT(s);
23413 } while (isXDIGIT(*s));
23415 while (isBLANK(*s)) { s++; }
23418 s = strchr(s, '\n');
23423 else if (s < e && *s != '\n') {
23424 goto check_if_property;
23428 if (max == -1) { /* The line only had one entry */
23431 else if (max < min) {
23432 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23433 sv_catpvs(msg, "Illegal range in \"");
23434 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23435 UTF8fARG(is_contents_utf8, s - s0, s0));
23436 sv_catpvs(msg, "\"");
23437 goto return_failure;
23440 # if 0 /* See explanation at definition above of get_extended_utf8_msg() */
23442 if ( UNICODE_IS_PERL_EXTENDED(min)
23443 || UNICODE_IS_PERL_EXTENDED(max))
23445 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23447 /* If both code points are non-portable, warn only on the lower
23449 sv_catpv(msg, get_extended_utf8_msg(
23450 (UNICODE_IS_PERL_EXTENDED(min))
23452 sv_catpvs(msg, " in \"");
23453 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23454 UTF8fARG(is_contents_utf8, s - s0, s0));
23455 sv_catpvs(msg, "\"");
23460 /* Here, this line contains a legal range */
23461 this_definition = sv_2mortal(_new_invlist(2));
23462 this_definition = _add_range_to_invlist(this_definition, min, max);
23467 /* Here it isn't a legal range line. See if it is a legal property
23468 * line. First find the end of the meat of the line */
23469 s = strpbrk(s, "#\n");
23474 /* Ignore trailing blanks in keeping with the requirements of
23475 * parse_uniprop_string() */
23477 while (s > s0 && isBLANK_A(*s)) {
23482 this_definition = parse_uniprop_string(s0, s - s0,
23483 is_utf8, to_fold, runtime,
23486 user_defined_ptr, msg,
23488 ? level /* Don't increase level
23489 if input is empty */
23492 if (this_definition == NULL) {
23493 goto return_failure; /* 'msg' should have had the reason
23494 appended to it by the above call */
23497 if (! is_invlist(this_definition)) { /* Unknown at this time */
23498 return newSVsv(this_definition);
23502 s = strchr(s, '\n');
23512 _invlist_union(running_definition, this_definition,
23513 &running_definition);
23516 _invlist_subtract(running_definition, this_definition,
23517 &running_definition);
23520 _invlist_intersection(running_definition, this_definition,
23521 &running_definition);
23524 _invlist_union_complement_2nd(running_definition,
23525 this_definition, &running_definition);
23528 Perl_croak(aTHX_ "panic: %s: %d: Unexpected operation %d",
23529 __FILE__, __LINE__, op);
23533 /* Position past the '\n' */
23535 } /* End of loop through the lines of 'contents' */
23537 /* Here, we processed all the lines in 'contents' without error. If we
23538 * didn't add any warnings, simply return success */
23539 if (msgs_length_on_entry == SvCUR(msg)) {
23541 /* If the expansion was empty, the answer isn't nothing: its an empty
23542 * inversion list */
23543 if (running_definition == NULL) {
23544 running_definition = _new_invlist(1);
23547 return running_definition;
23550 /* Otherwise, add some explanatory text, but we will return success */
23554 running_definition = NULL;
23558 if (name_len > 0) {
23559 sv_catpvs(msg, " in expansion of ");
23560 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
23563 return running_definition;
23566 /* As explained below, certain operations need to take place in the first
23567 * thread created. These macros switch contexts */
23568 # ifdef USE_ITHREADS
23569 # define DECLARATION_FOR_GLOBAL_CONTEXT \
23570 PerlInterpreter * save_aTHX = aTHX;
23571 # define SWITCH_TO_GLOBAL_CONTEXT \
23572 PERL_SET_CONTEXT((aTHX = PL_user_def_props_aTHX))
23573 # define RESTORE_CONTEXT PERL_SET_CONTEXT((aTHX = save_aTHX));
23574 # define CUR_CONTEXT aTHX
23575 # define ORIGINAL_CONTEXT save_aTHX
23577 # define DECLARATION_FOR_GLOBAL_CONTEXT dNOOP
23578 # define SWITCH_TO_GLOBAL_CONTEXT NOOP
23579 # define RESTORE_CONTEXT NOOP
23580 # define CUR_CONTEXT NULL
23581 # define ORIGINAL_CONTEXT NULL
23585 S_delete_recursion_entry(pTHX_ void *key)
23587 /* Deletes the entry used to detect recursion when expanding user-defined
23588 * properties. This is a function so it can be set up to be called even if
23589 * the program unexpectedly quits */
23592 SV ** current_entry;
23593 const STRLEN key_len = strlen((const char *) key);
23594 DECLARATION_FOR_GLOBAL_CONTEXT;
23596 SWITCH_TO_GLOBAL_CONTEXT;
23598 /* If the entry is one of these types, it is a permanent entry, and not the
23599 * one used to detect recursions. This function should delete only the
23600 * recursion entry */
23601 current_entry = hv_fetch(PL_user_def_props, (const char *) key, key_len, 0);
23603 && ! is_invlist(*current_entry)
23604 && ! SvPOK(*current_entry))
23606 (void) hv_delete(PL_user_def_props, (const char *) key, key_len,
23614 S_get_fq_name(pTHX_
23615 const char * const name, /* The first non-blank in the \p{}, \P{} */
23616 const Size_t name_len, /* Its length in bytes, not including any trailing space */
23617 const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */
23618 const bool has_colon_colon
23621 /* Returns a mortal SV containing the fully qualified version of the input
23626 fq_name = newSVpvs_flags("", SVs_TEMP);
23628 /* Use the current package if it wasn't included in our input */
23629 if (! has_colon_colon) {
23630 const HV * pkg = (IN_PERL_COMPILETIME)
23632 : CopSTASH(PL_curcop);
23633 const char* pkgname = HvNAME(pkg);
23635 Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f,
23636 UTF8fARG(is_utf8, strlen(pkgname), pkgname));
23637 sv_catpvs(fq_name, "::");
23640 Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f,
23641 UTF8fARG(is_utf8, name_len, name));
23646 S_parse_uniprop_string(pTHX_
23648 /* Parse the interior of a \p{}, \P{}. Returns its definition if knowable
23649 * now. If so, the return is an inversion list.
23651 * If the property is user-defined, it is a subroutine, which in turn
23652 * may call other subroutines. This function will call the whole nest of
23653 * them to get the definition they return; if some aren't known at the time
23654 * of the call to this function, the fully qualified name of the highest
23655 * level sub is returned. It is an error to call this function at runtime
23656 * without every sub defined.
23658 * If an error was found, NULL is returned, and 'msg' gets a suitable
23659 * message appended to it. (Appending allows the back trace of how we got
23660 * to the faulty definition to be displayed through nested calls of
23661 * user-defined subs.)
23663 * The caller should NOT try to free any returned inversion list.
23665 * Other parameters will be set on return as described below */
23667 const char * const name, /* The first non-blank in the \p{}, \P{} */
23668 Size_t name_len, /* Its length in bytes, not including any
23670 const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */
23671 const bool to_fold, /* ? Is this under /i */
23672 const bool runtime, /* TRUE if this is being called at run time */
23673 const bool deferrable, /* TRUE if it's ok for the definition to not be
23674 known at this call */
23675 AV ** strings, /* To return string property values, like named
23677 bool *user_defined_ptr, /* Upon return from this function it will be
23678 set to TRUE if any component is a
23679 user-defined property */
23680 SV * msg, /* Any error or warning msg(s) are appended to
23682 const STRLEN level) /* Recursion level of this call */
23685 char* lookup_name; /* normalized name for lookup in our tables */
23686 unsigned lookup_len; /* Its length */
23687 enum { Not_Strict = 0, /* Some properties have stricter name */
23688 Strict, /* normalization rules, which we decide */
23689 As_Is /* upon based on parsing */
23690 } stricter = Not_Strict;
23692 /* nv= or numeric_value=, or possibly one of the cjk numeric properties
23693 * (though it requires extra effort to download them from Unicode and
23694 * compile perl to know about them) */
23695 bool is_nv_type = FALSE;
23697 unsigned int i, j = 0;
23698 int equals_pos = -1; /* Where the '=' is found, or negative if none */
23699 int slash_pos = -1; /* Where the '/' is found, or negative if none */
23700 int table_index = 0; /* The entry number for this property in the table
23701 of all Unicode property names */
23702 bool starts_with_Is = FALSE; /* ? Does the name start with 'Is' */
23703 Size_t lookup_offset = 0; /* Used to ignore the first few characters of
23704 the normalized name in certain situations */
23705 Size_t non_pkg_begin = 0; /* Offset of first byte in 'name' that isn't
23706 part of a package name */
23707 Size_t lun_non_pkg_begin = 0; /* Similarly for 'lookup_name' */
23708 bool could_be_user_defined = TRUE; /* ? Could this be a user-defined
23709 property rather than a Unicode
23711 SV * prop_definition = NULL; /* The returned definition of 'name' or NULL
23712 if an error. If it is an inversion list,
23713 it is the definition. Otherwise it is a
23714 string containing the fully qualified sub
23716 SV * fq_name = NULL; /* For user-defined properties, the fully
23718 bool invert_return = FALSE; /* ? Do we need to complement the result before
23720 bool stripped_utf8_pkg = FALSE; /* Set TRUE if the input includes an
23721 explicit utf8:: package that we strip
23723 /* The expansion of properties that could be either user-defined or
23724 * official unicode ones is deferred until runtime, including a marker for
23725 * those that might be in the latter category. This boolean indicates if
23726 * we've seen that marker. If not, what we're parsing can't be such an
23727 * official Unicode property whose expansion was deferred */
23728 bool could_be_deferred_official = FALSE;
23730 PERL_ARGS_ASSERT_PARSE_UNIPROP_STRING;
23732 /* The input will be normalized into 'lookup_name' */
23733 Newx(lookup_name, name_len, char);
23734 SAVEFREEPV(lookup_name);
23736 /* Parse the input. */
23737 for (i = 0; i < name_len; i++) {
23738 char cur = name[i];
23740 /* Most of the characters in the input will be of this ilk, being parts
23742 if (isIDCONT_A(cur)) {
23744 /* Case differences are ignored. Our lookup routine assumes
23745 * everything is lowercase, so normalize to that */
23746 if (isUPPER_A(cur)) {
23747 lookup_name[j++] = toLOWER_A(cur);
23751 if (cur == '_') { /* Don't include these in the normalized name */
23755 lookup_name[j++] = cur;
23757 /* The first character in a user-defined name must be of this type.
23759 if (i - non_pkg_begin == 0 && ! isIDFIRST_A(cur)) {
23760 could_be_user_defined = FALSE;
23766 /* Here, the character is not something typically in a name, But these
23767 * two types of characters (and the '_' above) can be freely ignored in
23768 * most situations. Later it may turn out we shouldn't have ignored
23769 * them, and we have to reparse, but we don't have enough information
23770 * yet to make that decision */
23771 if (cur == '-' || isSPACE_A(cur)) {
23772 could_be_user_defined = FALSE;
23776 /* An equals sign or single colon mark the end of the first part of
23777 * the property name */
23779 || (cur == ':' && (i >= name_len - 1 || name[i+1] != ':')))
23781 lookup_name[j++] = '='; /* Treat the colon as an '=' */
23782 equals_pos = j; /* Note where it occurred in the input */
23783 could_be_user_defined = FALSE;
23787 /* If this looks like it is a marker we inserted at compile time,
23788 * set a flag and otherwise ignore it. If it isn't in the final
23789 * position, keep it as it would have been user input. */
23790 if ( UNLIKELY(cur == DEFERRED_COULD_BE_OFFICIAL_MARKERc)
23792 && could_be_user_defined
23793 && i == name_len - 1)
23796 could_be_deferred_official = TRUE;
23800 /* Otherwise, this character is part of the name. */
23801 lookup_name[j++] = cur;
23803 /* Here it isn't a single colon, so if it is a colon, it must be a
23807 /* A double colon should be a package qualifier. We note its
23808 * position and continue. Note that one could have
23809 * pkg1::pkg2::...::foo
23810 * so that the position at the end of the loop will be just after
23811 * the final qualifier */
23814 non_pkg_begin = i + 1;
23815 lookup_name[j++] = ':';
23816 lun_non_pkg_begin = j;
23818 else { /* Only word chars (and '::') can be in a user-defined name */
23819 could_be_user_defined = FALSE;
23821 } /* End of parsing through the lhs of the property name (or all of it if
23824 # define STRLENs(s) (sizeof("" s "") - 1)
23826 /* If there is a single package name 'utf8::', it is ambiguous. It could
23827 * be for a user-defined property, or it could be a Unicode property, as
23828 * all of them are considered to be for that package. For the purposes of
23829 * parsing the rest of the property, strip it off */
23830 if (non_pkg_begin == STRLENs("utf8::") && memBEGINPs(name, name_len, "utf8::")) {
23831 lookup_name += STRLENs("utf8::");
23832 j -= STRLENs("utf8::");
23833 equals_pos -= STRLENs("utf8::");
23834 stripped_utf8_pkg = TRUE;
23837 /* Here, we are either done with the whole property name, if it was simple;
23838 * or are positioned just after the '=' if it is compound. */
23840 if (equals_pos >= 0) {
23841 assert(stricter == Not_Strict); /* We shouldn't have set this yet */
23843 /* Space immediately after the '=' is ignored */
23845 for (; i < name_len; i++) {
23846 if (! isSPACE_A(name[i])) {
23851 /* Most punctuation after the equals indicates a subpattern, like
23853 if ( isPUNCT_A(name[i])
23858 /* A backslash means the real delimitter is the next character,
23859 * but it must be punctuation */
23860 && (name[i] != '\\' || (i < name_len && isPUNCT_A(name[i+1]))))
23862 bool special_property = memEQs(lookup_name, j - 1, "name")
23863 || memEQs(lookup_name, j - 1, "na");
23864 if (! special_property) {
23865 /* Find the property. The table includes the equals sign, so
23866 * we use 'j' as-is */
23867 table_index = do_uniprop_match(lookup_name, j);
23869 if (special_property || table_index) {
23870 REGEXP * subpattern_re;
23871 char open = name[i++];
23873 const char * pos_in_brackets;
23874 const char * const * prop_values;
23877 /* Backslash => delimitter is the character following. We
23878 * already checked that it is punctuation */
23879 if (open == '\\') {
23884 /* This data structure is constructed so that the matching
23885 * closing bracket is 3 past its matching opening. The second
23886 * set of closing is so that if the opening is something like
23887 * ']', the closing will be that as well. Something similar is
23888 * done in toke.c */
23889 pos_in_brackets = memCHRs("([<)]>)]>", open);
23890 close = (pos_in_brackets) ? pos_in_brackets[3] : open;
23893 || name[name_len-1] != close
23894 || (escaped && name[name_len-2] != '\\')
23895 /* Also make sure that there are enough characters.
23896 * e.g., '\\\' would show up incorrectly as legal even
23897 * though it is too short */
23898 || (SSize_t) (name_len - i - 1 - escaped) < 0)
23900 sv_catpvs(msg, "Unicode property wildcard not terminated");
23901 goto append_name_to_msg;
23904 Perl_ck_warner_d(aTHX_
23905 packWARN(WARN_EXPERIMENTAL__UNIPROP_WILDCARDS),
23906 "The Unicode property wildcards feature is experimental");
23908 if (special_property) {
23909 const char * error_msg;
23910 const char * revised_name = name + i;
23911 Size_t revised_name_len = name_len - (i + 1 + escaped);
23913 /* Currently, the only 'special_property' is name, which we
23914 * lookup in _charnames.pm */
23916 if (! load_charnames(newSVpvs("placeholder"),
23917 revised_name, revised_name_len,
23920 sv_catpv(msg, error_msg);
23921 goto append_name_to_msg;
23924 /* Farm this out to a function just to make the current
23925 * function less unwieldy */
23926 if (handle_names_wildcard(revised_name, revised_name_len,
23930 return prop_definition;
23936 prop_values = get_prop_values(table_index);
23938 /* Now create and compile the wildcard subpattern. Use /i
23939 * because the property values are supposed to match with case
23941 subpattern_re = compile_wildcard(name + i,
23942 name_len - i - 1 - escaped,
23946 /* For each legal property value, see if the supplied pattern
23948 while (*prop_values) {
23949 const char * const entry = *prop_values;
23950 const Size_t len = strlen(entry);
23951 SV* entry_sv = newSVpvn_flags(entry, len, SVs_TEMP);
23953 if (execute_wildcard(subpattern_re,
23955 (char *) entry + len,
23959 { /* Here, matched. Add to the returned list */
23960 Size_t total_len = j + len;
23961 SV * sub_invlist = NULL;
23962 char * this_string;
23964 /* We know this is a legal \p{property=value}. Call
23965 * the function to return the list of code points that
23967 Newxz(this_string, total_len + 1, char);
23968 Copy(lookup_name, this_string, j, char);
23969 my_strlcat(this_string, entry, total_len + 1);
23970 SAVEFREEPV(this_string);
23971 sub_invlist = parse_uniprop_string(this_string,
23981 _invlist_union(prop_definition, sub_invlist,
23985 prop_values++; /* Next iteration, look at next propvalue */
23986 } /* End of looking through property values; (the data
23987 structure is terminated by a NULL ptr) */
23989 SvREFCNT_dec_NN(subpattern_re);
23991 if (prop_definition) {
23992 return prop_definition;
23995 sv_catpvs(msg, "No Unicode property value wildcard matches:");
23996 goto append_name_to_msg;
23999 /* Here's how khw thinks we should proceed to handle the properties
24000 * not yet done: Bidi Mirroring Glyph can map to ""
24001 Bidi Paired Bracket can map to ""
24002 Case Folding (both full and simple)
24003 Shouldn't /i be good enough for Full
24004 Decomposition Mapping
24005 Equivalent Unified Ideograph can map to ""
24006 Lowercase Mapping (both full and simple)
24007 NFKC Case Fold can map to ""
24008 Titlecase Mapping (both full and simple)
24009 Uppercase Mapping (both full and simple)
24010 * Handle these the same way Name is done, using say, _wild.pm, but
24011 * having both loose and full, like in charclass_invlists.h.
24012 * Perhaps move block and script to that as they are somewhat large
24013 * in charclass_invlists.h.
24014 * For properties where the default is the code point itself, such
24015 * as any of the case changing mappings, the string would otherwise
24016 * consist of all Unicode code points in UTF-8 strung together.
24017 * This would be impractical. So instead, examine their compiled
24018 * pattern, looking at the ssc. If none, reject the pattern as an
24019 * error. Otherwise run the pattern against every code point in
24020 * the ssc. The ssc is kind of like tr18's 3.9 Possible Match Sets
24021 * And it might be good to create an API to return the ssc.
24022 * Or handle them like the algorithmic names are done
24024 } /* End of is a wildcard subppattern */
24026 /* \p{name=...} is handled specially. Instead of using the normal
24027 * mechanism involving charclass_invlists.h, it uses _charnames.pm
24028 * which has the necessary (huge) data accessible to it, and which
24029 * doesn't get loaded unless necessary. The legal syntax for names is
24030 * somewhat different than other properties due both to the vagaries of
24031 * a few outlier official names, and the fact that only a few ASCII
24032 * characters are permitted in them */
24033 if ( memEQs(lookup_name, j - 1, "name")
24034 || memEQs(lookup_name, j - 1, "na"))
24039 const char * error_msg;
24041 SV * character_name;
24042 STRLEN character_len;
24047 /* Since the RHS (after skipping initial space) is passed unchanged
24048 * to charnames, and there are different criteria for what are
24049 * legal characters in the name, just parse it here. A character
24050 * name must begin with an ASCII alphabetic */
24051 if (! isALPHA(name[i])) {
24054 lookup_name[j++] = name[i];
24056 for (++i; i < name_len; i++) {
24057 /* Official names can only be in the ASCII range, and only
24058 * certain characters */
24059 if (! isASCII(name[i]) || ! isCHARNAME_CONT(name[i])) {
24062 lookup_name[j++] = name[i];
24065 /* Finished parsing, save the name into an SV */
24066 character_name = newSVpvn(lookup_name + equals_pos, j - equals_pos);
24068 /* Make sure _charnames is loaded. (The parameters give context
24069 * for any errors generated */
24070 table = load_charnames(character_name, name, name_len, &error_msg);
24071 if (table == NULL) {
24072 sv_catpv(msg, error_msg);
24073 goto append_name_to_msg;
24076 lookup_loose = get_cv("_charnames::_loose_regcomp_lookup", 0);
24077 if (! lookup_loose) {
24079 "panic: Can't find '_charnames::_loose_regcomp_lookup");
24082 PUSHSTACKi(PERLSI_REGCOMP);
24088 XPUSHs(character_name);
24090 call_sv(MUTABLE_SV(lookup_loose), G_SCALAR);
24095 SvREFCNT_inc_simple_void_NN(character);
24102 if (! SvOK(character)) {
24106 cp = valid_utf8_to_uvchr((U8 *) SvPVX(character), &character_len);
24107 if (character_len == SvCUR(character)) {
24108 prop_definition = add_cp_to_invlist(NULL, cp);
24113 /* First of the remaining characters in the string. */
24114 char * remaining = SvPVX(character) + character_len;
24116 if (strings == NULL) {
24117 goto failed; /* XXX Perhaps a specific msg instead, like
24118 'not available here' */
24121 if (*strings == NULL) {
24122 *strings = newAV();
24125 this_string = newAV();
24126 av_push(this_string, newSVuv(cp));
24129 cp = valid_utf8_to_uvchr((U8 *) remaining, &character_len);
24130 av_push(this_string, newSVuv(cp));
24131 remaining += character_len;
24132 } while (remaining < SvEND(character));
24134 av_push(*strings, (SV *) this_string);
24137 return prop_definition;
24140 /* Certain properties whose values are numeric need special handling.
24141 * They may optionally be prefixed by 'is'. Ignore that prefix for the
24142 * purposes of checking if this is one of those properties */
24143 if (memBEGINPs(lookup_name, j, "is")) {
24147 /* Then check if it is one of these specially-handled properties. The
24148 * possibilities are hard-coded because easier this way, and the list
24149 * is unlikely to change.
24151 * All numeric value type properties are of this ilk, and are also
24152 * special in a different way later on. So find those first. There
24153 * are several numeric value type properties in the Unihan DB (which is
24154 * unlikely to be compiled with perl, but we handle it here in case it
24155 * does get compiled). They all end with 'numeric'. The interiors
24156 * aren't checked for the precise property. This would stop working if
24157 * a cjk property were to be created that ended with 'numeric' and
24158 * wasn't a numeric type */
24159 is_nv_type = memEQs(lookup_name + lookup_offset,
24160 j - 1 - lookup_offset, "numericvalue")
24161 || memEQs(lookup_name + lookup_offset,
24162 j - 1 - lookup_offset, "nv")
24163 || ( memENDPs(lookup_name + lookup_offset,
24164 j - 1 - lookup_offset, "numeric")
24165 && ( memBEGINPs(lookup_name + lookup_offset,
24166 j - 1 - lookup_offset, "cjk")
24167 || memBEGINPs(lookup_name + lookup_offset,
24168 j - 1 - lookup_offset, "k")));
24170 || memEQs(lookup_name + lookup_offset,
24171 j - 1 - lookup_offset, "canonicalcombiningclass")
24172 || memEQs(lookup_name + lookup_offset,
24173 j - 1 - lookup_offset, "ccc")
24174 || memEQs(lookup_name + lookup_offset,
24175 j - 1 - lookup_offset, "age")
24176 || memEQs(lookup_name + lookup_offset,
24177 j - 1 - lookup_offset, "in")
24178 || memEQs(lookup_name + lookup_offset,
24179 j - 1 - lookup_offset, "presentin"))
24183 /* Since the stuff after the '=' is a number, we can't throw away
24184 * '-' willy-nilly, as those could be a minus sign. Other stricter
24185 * rules also apply. However, these properties all can have the
24186 * rhs not be a number, in which case they contain at least one
24187 * alphabetic. In those cases, the stricter rules don't apply.
24188 * But the numeric type properties can have the alphas [Ee] to
24189 * signify an exponent, and it is still a number with stricter
24190 * rules. So look for an alpha that signifies not-strict */
24192 for (k = i; k < name_len; k++) {
24193 if ( isALPHA_A(name[k])
24194 && (! is_nv_type || ! isALPHA_FOLD_EQ(name[k], 'E')))
24196 stricter = Not_Strict;
24204 /* A number may have a leading '+' or '-'. The latter is retained
24206 if (name[i] == '+') {
24209 else if (name[i] == '-') {
24210 lookup_name[j++] = '-';
24214 /* Skip leading zeros including single underscores separating the
24215 * zeros, or between the final leading zero and the first other
24217 for (; i < name_len - 1; i++) {
24218 if ( name[i] != '0'
24219 && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
24226 else { /* No '=' */
24228 /* Only a few properties without an '=' should be parsed with stricter
24229 * rules. The list is unlikely to change. */
24230 if ( memBEGINPs(lookup_name, j, "perl")
24231 && memNEs(lookup_name + 4, j - 4, "space")
24232 && memNEs(lookup_name + 4, j - 4, "word"))
24236 /* We set the inputs back to 0 and the code below will reparse,
24242 /* Here, we have either finished the property, or are positioned to parse
24243 * the remainder, and we know if stricter rules apply. Finish out, if not
24245 for (; i < name_len; i++) {
24246 char cur = name[i];
24248 /* In all instances, case differences are ignored, and we normalize to
24250 if (isUPPER_A(cur)) {
24251 lookup_name[j++] = toLOWER(cur);
24255 /* An underscore is skipped, but not under strict rules unless it
24256 * separates two digits */
24259 && ( i == 0 || (int) i == equals_pos || i == name_len- 1
24260 || ! isDIGIT_A(name[i-1]) || ! isDIGIT_A(name[i+1])))
24262 lookup_name[j++] = '_';
24267 /* Hyphens are skipped except under strict */
24268 if (cur == '-' && ! stricter) {
24272 /* XXX Bug in documentation. It says white space skipped adjacent to
24273 * non-word char. Maybe we should, but shouldn't skip it next to a dot
24275 if (isSPACE_A(cur) && ! stricter) {
24279 lookup_name[j++] = cur;
24281 /* Unless this is a non-trailing slash, we are done with it */
24282 if (i >= name_len - 1 || cur != '/') {
24288 /* A slash in the 'numeric value' property indicates that what follows
24289 * is a denominator. It can have a leading '+' and '0's that should be
24290 * skipped. But we have never allowed a negative denominator, so treat
24291 * a minus like every other character. (No need to rule out a second
24292 * '/', as that won't match anything anyway */
24295 if (i < name_len && name[i] == '+') {
24299 /* Skip leading zeros including underscores separating digits */
24300 for (; i < name_len - 1; i++) {
24301 if ( name[i] != '0'
24302 && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
24308 /* Store the first real character in the denominator */
24309 if (i < name_len) {
24310 lookup_name[j++] = name[i];
24315 /* Here are completely done parsing the input 'name', and 'lookup_name'
24316 * contains a copy, normalized.
24318 * This special case is grandfathered in: 'L_' and 'GC=L_' are accepted and
24319 * different from without the underscores. */
24320 if ( ( UNLIKELY(memEQs(lookup_name, j, "l"))
24321 || UNLIKELY(memEQs(lookup_name, j, "gc=l")))
24322 && UNLIKELY(name[name_len-1] == '_'))
24324 lookup_name[j++] = '&';
24327 /* If the original input began with 'In' or 'Is', it could be a subroutine
24328 * call to a user-defined property instead of a Unicode property name. */
24329 if ( name_len - non_pkg_begin > 2
24330 && name[non_pkg_begin+0] == 'I'
24331 && (name[non_pkg_begin+1] == 'n' || name[non_pkg_begin+1] == 's'))
24333 /* Names that start with In have different characterstics than those
24334 * that start with Is */
24335 if (name[non_pkg_begin+1] == 's') {
24336 starts_with_Is = TRUE;
24340 could_be_user_defined = FALSE;
24343 if (could_be_user_defined) {
24346 /* If the user defined property returns the empty string, it could
24347 * easily be because the pattern is being compiled before the data it
24348 * actually needs to compile is available. This could be argued to be
24349 * a bug in the perl code, but this is a change of behavior for Perl,
24350 * so we handle it. This means that intentionally returning nothing
24351 * will not be resolved until runtime */
24352 bool empty_return = FALSE;
24354 /* Here, the name could be for a user defined property, which are
24355 * implemented as subs. */
24356 user_sub = get_cvn_flags(name, name_len, 0);
24359 /* Here, the property name could be a user-defined one, but there
24360 * is no subroutine to handle it (as of now). Defer handling it
24361 * until runtime. Otherwise, a block defined by Unicode in a later
24362 * release would get the synonym InFoo added for it, and existing
24363 * code that used that name would suddenly break if it referred to
24364 * the property before the sub was declared. See [perl #134146] */
24366 goto definition_deferred;
24369 /* Here, we are at runtime, and didn't find the user property. It
24370 * could be an official property, but only if no package was
24371 * specified, or just the utf8:: package. */
24372 if (could_be_deferred_official) {
24373 lookup_name += lun_non_pkg_begin;
24374 j -= lun_non_pkg_begin;
24376 else if (! stripped_utf8_pkg) {
24377 goto unknown_user_defined;
24380 /* Drop down to look up in the official properties */
24383 const char insecure[] = "Insecure user-defined property";
24385 /* Here, there is a sub by the correct name. Normally we call it
24386 * to get the property definition */
24388 SV * user_sub_sv = MUTABLE_SV(user_sub);
24389 SV * error; /* Any error returned by calling 'user_sub' */
24390 SV * key; /* The key into the hash of user defined sub names
24393 SV ** saved_user_prop_ptr; /* Hash entry for this property */
24395 /* How many times to retry when another thread is in the middle of
24396 * expanding the same definition we want */
24397 PERL_INT_FAST8_T retry_countdown = 10;
24399 DECLARATION_FOR_GLOBAL_CONTEXT;
24401 /* If we get here, we know this property is user-defined */
24402 *user_defined_ptr = TRUE;
24404 /* We refuse to call a potentially tainted subroutine; returning an
24407 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24408 sv_catpvn(msg, insecure, sizeof(insecure) - 1);
24409 goto append_name_to_msg;
24412 /* In principal, we only call each subroutine property definition
24413 * once during the life of the program. This guarantees that the
24414 * property definition never changes. The results of the single
24415 * sub call are stored in a hash, which is used instead for future
24416 * references to this property. The property definition is thus
24417 * immutable. But, to allow the user to have a /i-dependent
24418 * definition, we call the sub once for non-/i, and once for /i,
24419 * should the need arise, passing the /i status as a parameter.
24421 * We start by constructing the hash key name, consisting of the
24422 * fully qualified subroutine name, preceded by the /i status, so
24423 * that there is a key for /i and a different key for non-/i */
24424 key = newSVpvn(((to_fold) ? "1" : "0"), 1);
24425 fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8,
24426 non_pkg_begin != 0);
24427 sv_catsv(key, fq_name);
24430 /* We only call the sub once throughout the life of the program
24431 * (with the /i, non-/i exception noted above). That means the
24432 * hash must be global and accessible to all threads. It is
24433 * created at program start-up, before any threads are created, so
24434 * is accessible to all children. But this creates some
24437 * 1) The keys can't be shared, or else problems arise; sharing is
24438 * turned off at hash creation time
24439 * 2) All SVs in it are there for the remainder of the life of the
24440 * program, and must be created in the same interpreter context
24441 * as the hash, or else they will be freed from the wrong pool
24442 * at global destruction time. This is handled by switching to
24443 * the hash's context to create each SV going into it, and then
24444 * immediately switching back
24445 * 3) All accesses to the hash must be controlled by a mutex, to
24446 * prevent two threads from getting an unstable state should
24447 * they simultaneously be accessing it. The code below is
24448 * crafted so that the mutex is locked whenever there is an
24449 * access and unlocked only when the next stable state is
24452 * The hash stores either the definition of the property if it was
24453 * valid, or, if invalid, the error message that was raised. We
24454 * use the type of SV to distinguish.
24456 * There's also the need to guard against the definition expansion
24457 * from infinitely recursing. This is handled by storing the aTHX
24458 * of the expanding thread during the expansion. Again the SV type
24459 * is used to distinguish this from the other two cases. If we
24460 * come to here and the hash entry for this property is our aTHX,
24461 * it means we have recursed, and the code assumes that we would
24462 * infinitely recurse, so instead stops and raises an error.
24463 * (Any recursion has always been treated as infinite recursion in
24466 * If instead, the entry is for a different aTHX, it means that
24467 * that thread has gotten here first, and hasn't finished expanding
24468 * the definition yet. We just have to wait until it is done. We
24469 * sleep and retry a few times, returning an error if the other
24470 * thread doesn't complete. */
24473 USER_PROP_MUTEX_LOCK;
24475 /* If we have an entry for this key, the subroutine has already
24476 * been called once with this /i status. */
24477 saved_user_prop_ptr = hv_fetch(PL_user_def_props,
24478 SvPVX(key), SvCUR(key), 0);
24479 if (saved_user_prop_ptr) {
24481 /* If the saved result is an inversion list, it is the valid
24482 * definition of this property */
24483 if (is_invlist(*saved_user_prop_ptr)) {
24484 prop_definition = *saved_user_prop_ptr;
24486 /* The SV in the hash won't be removed until global
24487 * destruction, so it is stable and we can unlock */
24488 USER_PROP_MUTEX_UNLOCK;
24490 /* The caller shouldn't try to free this SV */
24491 return prop_definition;
24494 /* Otherwise, if it is a string, it is the error message
24495 * that was returned when we first tried to evaluate this
24496 * property. Fail, and append the message */
24497 if (SvPOK(*saved_user_prop_ptr)) {
24498 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24499 sv_catsv(msg, *saved_user_prop_ptr);
24501 /* The SV in the hash won't be removed until global
24502 * destruction, so it is stable and we can unlock */
24503 USER_PROP_MUTEX_UNLOCK;
24508 assert(SvIOK(*saved_user_prop_ptr));
24510 /* Here, we have an unstable entry in the hash. Either another
24511 * thread is in the middle of expanding the property's
24512 * definition, or we are ourselves recursing. We use the aTHX
24513 * in it to distinguish */
24514 if (SvIV(*saved_user_prop_ptr) != PTR2IV(CUR_CONTEXT)) {
24516 /* Here, it's another thread doing the expanding. We've
24517 * looked as much as we are going to at the contents of the
24518 * hash entry. It's safe to unlock. */
24519 USER_PROP_MUTEX_UNLOCK;
24521 /* Retry a few times */
24522 if (retry_countdown-- > 0) {
24527 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24528 sv_catpvs(msg, "Timeout waiting for another thread to "
24530 goto append_name_to_msg;
24533 /* Here, we are recursing; don't dig any deeper */
24534 USER_PROP_MUTEX_UNLOCK;
24536 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24538 "Infinite recursion in user-defined property");
24539 goto append_name_to_msg;
24542 /* Here, this thread has exclusive control, and there is no entry
24543 * for this property in the hash. So we have the go ahead to
24544 * expand the definition ourselves. */
24546 PUSHSTACKi(PERLSI_REGCOMP);
24549 /* Create a temporary placeholder in the hash to detect recursion
24551 SWITCH_TO_GLOBAL_CONTEXT;
24552 placeholder= newSVuv(PTR2IV(ORIGINAL_CONTEXT));
24553 (void) hv_store_ent(PL_user_def_props, key, placeholder, 0);
24556 /* Now that we have a placeholder, we can let other threads
24558 USER_PROP_MUTEX_UNLOCK;
24560 /* Make sure the placeholder always gets destroyed */
24561 SAVEDESTRUCTOR_X(S_delete_recursion_entry, SvPVX(key));
24566 /* Call the user's function, with the /i status as a parameter.
24567 * Note that we have gone to a lot of trouble to keep this call
24568 * from being within the locked mutex region. */
24569 XPUSHs(boolSV(to_fold));
24572 /* The following block was taken from swash_init(). Presumably
24573 * they apply to here as well, though we no longer use a swash --
24577 /* We might get here via a subroutine signature which uses a utf8
24578 * parameter name, at which point PL_subname will have been set
24579 * but not yet used. */
24580 save_item(PL_subname);
24582 /* G_SCALAR guarantees a single return value */
24583 (void) call_sv(user_sub_sv, G_EVAL|G_SCALAR);
24588 if (TAINT_get || SvTRUE(error)) {
24589 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24590 if (SvTRUE(error)) {
24591 sv_catpvs(msg, "Error \"");
24592 sv_catsv(msg, error);
24593 sv_catpvs(msg, "\"");
24596 if (SvTRUE(error)) sv_catpvs(msg, "; ");
24597 sv_catpvn(msg, insecure, sizeof(insecure) - 1);
24600 if (name_len > 0) {
24601 sv_catpvs(msg, " in expansion of ");
24602 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8,
24608 prop_definition = NULL;
24611 SV * contents = POPs;
24613 /* The contents is supposed to be the expansion of the property
24614 * definition. If the definition is deferrable, and we got an
24615 * empty string back, set a flag to later defer it (after clean
24618 && (! SvPOK(contents) || SvCUR(contents) == 0))
24620 empty_return = TRUE;
24622 else { /* Otherwise, call a function to check for valid syntax,
24625 prop_definition = handle_user_defined_property(
24627 is_utf8, to_fold, runtime,
24629 contents, user_defined_ptr,
24635 /* Here, we have the results of the expansion. Delete the
24636 * placeholder, and if the definition is now known, replace it with
24637 * that definition. We need exclusive access to the hash, and we
24638 * can't let anyone else in, between when we delete the placeholder
24639 * and add the permanent entry */
24640 USER_PROP_MUTEX_LOCK;
24642 S_delete_recursion_entry(aTHX_ SvPVX(key));
24644 if ( ! empty_return
24645 && (! prop_definition || is_invlist(prop_definition)))
24647 /* If we got success we use the inversion list defining the
24648 * property; otherwise use the error message */
24649 SWITCH_TO_GLOBAL_CONTEXT;
24650 (void) hv_store_ent(PL_user_def_props,
24653 ? newSVsv(prop_definition)
24659 /* All done, and the hash now has a permanent entry for this
24660 * property. Give up exclusive control */
24661 USER_PROP_MUTEX_UNLOCK;
24667 if (empty_return) {
24668 goto definition_deferred;
24671 if (prop_definition) {
24673 /* If the definition is for something not known at this time,
24674 * we toss it, and go return the main property name, as that's
24675 * the one the user will be aware of */
24676 if (! is_invlist(prop_definition)) {
24677 SvREFCNT_dec_NN(prop_definition);
24678 goto definition_deferred;
24681 sv_2mortal(prop_definition);
24685 return prop_definition;
24687 } /* End of calling the subroutine for the user-defined property */
24688 } /* End of it could be a user-defined property */
24690 /* Here it wasn't a user-defined property that is known at this time. See
24691 * if it is a Unicode property */
24693 lookup_len = j; /* This is a more mnemonic name than 'j' */
24695 /* Get the index into our pointer table of the inversion list corresponding
24696 * to the property */
24697 table_index = do_uniprop_match(lookup_name, lookup_len);
24699 /* If it didn't find the property ... */
24700 if (table_index == 0) {
24702 /* Try again stripping off any initial 'Is'. This is because we
24703 * promise that an initial Is is optional. The same isn't true of
24704 * names that start with 'In'. Those can match only blocks, and the
24705 * lookup table already has those accounted for. */
24706 if (starts_with_Is) {
24712 table_index = do_uniprop_match(lookup_name, lookup_len);
24715 if (table_index == 0) {
24718 /* Here, we didn't find it. If not a numeric type property, and
24719 * can't be a user-defined one, it isn't a legal property */
24720 if (! is_nv_type) {
24721 if (! could_be_user_defined) {
24725 /* Here, the property name is legal as a user-defined one. At
24726 * compile time, it might just be that the subroutine for that
24727 * property hasn't been encountered yet, but at runtime, it's
24728 * an error to try to use an undefined one */
24729 if (! deferrable) {
24730 goto unknown_user_defined;;
24733 goto definition_deferred;
24734 } /* End of isn't a numeric type property */
24736 /* The numeric type properties need more work to decide. What we
24737 * do is make sure we have the number in canonical form and look
24740 if (slash_pos < 0) { /* No slash */
24742 /* When it isn't a rational, take the input, convert it to a
24743 * NV, then create a canonical string representation of that
24747 SSize_t value_len = lookup_len - equals_pos;
24749 /* Get the value */
24750 if ( value_len <= 0
24751 || my_atof3(lookup_name + equals_pos, &value,
24753 != lookup_name + lookup_len)
24758 /* If the value is an integer, the canonical value is integral
24760 if (Perl_ceil(value) == value) {
24761 canonical = Perl_form(aTHX_ "%.*s%.0" NVff,
24762 equals_pos, lookup_name, value);
24764 else { /* Otherwise, it is %e with a known precision */
24767 canonical = Perl_form(aTHX_ "%.*s%.*" NVef,
24768 equals_pos, lookup_name,
24769 PL_E_FORMAT_PRECISION, value);
24771 /* The exponent generated is expecting two digits, whereas
24772 * %e on some systems will generate three. Remove leading
24773 * zeros in excess of 2 from the exponent. We start
24774 * looking for them after the '=' */
24775 exp_ptr = strchr(canonical + equals_pos, 'e');
24777 char * cur_ptr = exp_ptr + 2; /* past the 'e[+-]' */
24778 SSize_t excess_exponent_len = strlen(cur_ptr) - 2;
24780 assert(*(cur_ptr - 1) == '-' || *(cur_ptr - 1) == '+');
24782 if (excess_exponent_len > 0) {
24783 SSize_t leading_zeros = strspn(cur_ptr, "0");
24784 SSize_t excess_leading_zeros
24785 = MIN(leading_zeros, excess_exponent_len);
24786 if (excess_leading_zeros > 0) {
24787 Move(cur_ptr + excess_leading_zeros,
24789 strlen(cur_ptr) - excess_leading_zeros
24790 + 1, /* Copy the NUL as well */
24797 else { /* Has a slash. Create a rational in canonical form */
24798 UV numerator, denominator, gcd, trial;
24799 const char * end_ptr;
24800 const char * sign = "";
24802 /* We can't just find the numerator, denominator, and do the
24803 * division, then use the method above, because that is
24804 * inexact. And the input could be a rational that is within
24805 * epsilon (given our precision) of a valid rational, and would
24806 * then incorrectly compare valid.
24808 * We're only interested in the part after the '=' */
24809 const char * this_lookup_name = lookup_name + equals_pos;
24810 lookup_len -= equals_pos;
24811 slash_pos -= equals_pos;
24813 /* Handle any leading minus */
24814 if (this_lookup_name[0] == '-') {
24816 this_lookup_name++;
24821 /* Convert the numerator to numeric */
24822 end_ptr = this_lookup_name + slash_pos;
24823 if (! grok_atoUV(this_lookup_name, &numerator, &end_ptr)) {
24827 /* It better have included all characters before the slash */
24828 if (*end_ptr != '/') {
24832 /* Set to look at just the denominator */
24833 this_lookup_name += slash_pos;
24834 lookup_len -= slash_pos;
24835 end_ptr = this_lookup_name + lookup_len;
24837 /* Convert the denominator to numeric */
24838 if (! grok_atoUV(this_lookup_name, &denominator, &end_ptr)) {
24842 /* It better be the rest of the characters, and don't divide by
24844 if ( end_ptr != this_lookup_name + lookup_len
24845 || denominator == 0)
24850 /* Get the greatest common denominator using
24851 http://en.wikipedia.org/wiki/Euclidean_algorithm */
24853 trial = denominator;
24854 while (trial != 0) {
24856 trial = gcd % trial;
24860 /* If already in lowest possible terms, we have already tried
24861 * looking this up */
24866 /* Reduce the rational, which should put it in canonical form
24869 denominator /= gcd;
24871 canonical = Perl_form(aTHX_ "%.*s%s%" UVuf "/%" UVuf,
24872 equals_pos, lookup_name, sign, numerator, denominator);
24875 /* Here, we have the number in canonical form. Try that */
24876 table_index = do_uniprop_match(canonical, strlen(canonical));
24877 if (table_index == 0) {
24880 } /* End of still didn't find the property in our table */
24881 } /* End of didn't find the property in our table */
24883 /* Here, we have a non-zero return, which is an index into a table of ptrs.
24884 * A negative return signifies that the real index is the absolute value,
24885 * but the result needs to be inverted */
24886 if (table_index < 0) {
24887 invert_return = TRUE;
24888 table_index = -table_index;
24891 /* Out-of band indices indicate a deprecated property. The proper index is
24892 * modulo it with the table size. And dividing by the table size yields
24893 * an offset into a table constructed by regen/mk_invlists.pl to contain
24894 * the corresponding warning message */
24895 if (table_index > MAX_UNI_KEYWORD_INDEX) {
24896 Size_t warning_offset = table_index / MAX_UNI_KEYWORD_INDEX;
24897 table_index %= MAX_UNI_KEYWORD_INDEX;
24898 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
24899 "Use of '%.*s' in \\p{} or \\P{} is deprecated because: %s",
24900 (int) name_len, name,
24901 get_deprecated_property_msg(warning_offset));
24904 /* In a few properties, a different property is used under /i. These are
24905 * unlikely to change, so are hard-coded here. */
24907 if ( table_index == UNI_XPOSIXUPPER
24908 || table_index == UNI_XPOSIXLOWER
24909 || table_index == UNI_TITLE)
24911 table_index = UNI_CASED;
24913 else if ( table_index == UNI_UPPERCASELETTER
24914 || table_index == UNI_LOWERCASELETTER
24915 # ifdef UNI_TITLECASELETTER /* Missing from early Unicodes */
24916 || table_index == UNI_TITLECASELETTER
24919 table_index = UNI_CASEDLETTER;
24921 else if ( table_index == UNI_POSIXUPPER
24922 || table_index == UNI_POSIXLOWER)
24924 table_index = UNI_POSIXALPHA;
24928 /* Create and return the inversion list */
24929 prop_definition = get_prop_definition(table_index);
24930 sv_2mortal(prop_definition);
24932 /* See if there is a private use override to add to this definition */
24934 COPHH * hinthash = (IN_PERL_COMPILETIME)
24935 ? CopHINTHASH_get(&PL_compiling)
24936 : CopHINTHASH_get(PL_curcop);
24937 SV * pu_overrides = cophh_fetch_pv(hinthash, "private_use", 0, 0);
24939 if (UNLIKELY(pu_overrides && SvPOK(pu_overrides))) {
24941 /* See if there is an element in the hints hash for this table */
24942 SV * pu_lookup = Perl_newSVpvf(aTHX_ "%d=", table_index);
24943 const char * pos = strstr(SvPVX(pu_overrides), SvPVX(pu_lookup));
24947 SV * pu_definition;
24949 SV * expanded_prop_definition =
24950 sv_2mortal(invlist_clone(prop_definition, NULL));
24952 /* If so, it's definition is the string from here to the next
24953 * \a character. And its format is the same as a user-defined
24955 pos += SvCUR(pu_lookup);
24956 pu_definition = newSVpvn(pos, strchr(pos, '\a') - pos);
24957 pu_invlist = handle_user_defined_property(lookup_name,
24960 0, /* Not folded */
24968 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24969 sv_catpvs(msg, "Insecure private-use override");
24970 goto append_name_to_msg;
24973 /* For now, as a safety measure, make sure that it doesn't
24974 * override non-private use code points */
24975 _invlist_intersection(pu_invlist, PL_Private_Use, &pu_invlist);
24977 /* Add it to the list to be returned */
24978 _invlist_union(prop_definition, pu_invlist,
24979 &expanded_prop_definition);
24980 prop_definition = expanded_prop_definition;
24981 Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__PRIVATE_USE), "The private_use feature is experimental");
24986 if (invert_return) {
24987 _invlist_invert(prop_definition);
24989 return prop_definition;
24991 unknown_user_defined:
24992 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24993 sv_catpvs(msg, "Unknown user-defined property name");
24994 goto append_name_to_msg;
24997 if (non_pkg_begin != 0) {
24998 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24999 sv_catpvs(msg, "Illegal user-defined property name");
25002 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
25003 sv_catpvs(msg, "Can't find Unicode property definition");
25007 append_name_to_msg:
25009 const char * prefix = (runtime && level == 0) ? " \\p{" : " \"";
25010 const char * suffix = (runtime && level == 0) ? "}" : "\"";
25012 sv_catpv(msg, prefix);
25013 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
25014 sv_catpv(msg, suffix);
25019 definition_deferred:
25022 bool is_qualified = non_pkg_begin != 0; /* If has "::" */
25024 /* Here it could yet to be defined, so defer evaluation of this until
25025 * its needed at runtime. We need the fully qualified property name to
25026 * avoid ambiguity */
25028 fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8,
25032 /* If it didn't come with a package, or the package is utf8::, this
25033 * actually could be an official Unicode property whose inclusion we
25034 * are deferring until runtime to make sure that it isn't overridden by
25035 * a user-defined property of the same name (which we haven't
25036 * encountered yet). Add a marker to indicate this possibility, for
25037 * use at such time when we first need the definition during pattern
25038 * matching execution */
25039 if (! is_qualified || memBEGINPs(name, non_pkg_begin, "utf8::")) {
25040 sv_catpvs(fq_name, DEFERRED_COULD_BE_OFFICIAL_MARKERs);
25043 /* We also need a trailing newline */
25044 sv_catpvs(fq_name, "\n");
25046 *user_defined_ptr = TRUE;
25052 S_handle_names_wildcard(pTHX_ const char * wname, /* wildcard name to match */
25053 const STRLEN wname_len, /* Its length */
25054 SV ** prop_definition,
25057 /* Deal with Name property wildcard subpatterns; returns TRUE if there were
25058 * any matches, adding them to prop_definition */
25062 CV * get_names_info; /* entry to charnames.pm to get info we need */
25063 SV * names_string; /* Contains all character names, except algo */
25064 SV * algorithmic_names; /* Contains info about algorithmically
25065 generated character names */
25066 REGEXP * subpattern_re; /* The user's pattern to match with */
25067 struct regexp * prog; /* The compiled pattern */
25068 char * all_names_start; /* lib/unicore/Name.pl string of every
25069 (non-algorithmic) character name */
25070 char * cur_pos; /* We match, effectively using /gc; this is
25071 where we are now */
25072 bool found_matches = FALSE; /* Did any name match so far? */
25073 SV * empty; /* For matching zero length names */
25074 SV * must_sv; /* Contains the substring, if any, that must be
25075 in a name for the subpattern to match */
25076 const char * must; /* The PV of 'must' */
25077 STRLEN must_len; /* And its length */
25078 SV * syllable_name = NULL; /* For Hangul syllables */
25079 const char hangul_prefix[] = "HANGUL SYLLABLE ";
25080 const STRLEN hangul_prefix_len = sizeof(hangul_prefix) - 1;
25082 /* By inspection, there are a maximum of 7 bytes in the suffix of a hangul
25083 * syllable name, and these are immutable and guaranteed by the Unicode
25084 * standard to never be extended */
25085 const STRLEN syl_max_len = hangul_prefix_len + 7;
25089 PERL_ARGS_ASSERT_HANDLE_NAMES_WILDCARD;
25091 /* Make sure _charnames is loaded. (The parameters give context
25092 * for any errors generated */
25093 get_names_info = get_cv("_charnames::_get_names_info", 0);
25094 if (! get_names_info) {
25095 Perl_croak(aTHX_ "panic: Can't find '_charnames::_get_names_info");
25098 /* Get the charnames data */
25099 PUSHSTACKi(PERLSI_REGCOMP);
25107 /* Special _charnames entry point that returns the info this routine
25109 call_sv(MUTABLE_SV(get_names_info), G_ARRAY);
25113 /* Data structure for names which end in their very own code points */
25114 algorithmic_names = POPs;
25115 SvREFCNT_inc_simple_void_NN(algorithmic_names);
25117 /* The lib/unicore/Name.pl string */
25118 names_string = POPs;
25119 SvREFCNT_inc_simple_void_NN(names_string);
25126 if ( ! SvROK(names_string)
25127 || ! SvROK(algorithmic_names))
25128 { /* Perhaps should panic instead XXX */
25129 SvREFCNT_dec(names_string);
25130 SvREFCNT_dec(algorithmic_names);
25134 names_string = sv_2mortal(SvRV(names_string));
25135 all_names_start = SvPVX(names_string);
25136 cur_pos = all_names_start;
25138 algorithmic_names= sv_2mortal(SvRV(algorithmic_names));
25140 /* Compile the subpattern consisting of the name being looked for */
25141 subpattern_re = compile_wildcard(wname, wname_len, FALSE /* /-i */ );
25143 must_sv = re_intuit_string(subpattern_re);
25145 /* regexec.c can free the re_intuit_string() return. GH #17734 */
25146 must_sv = sv_2mortal(newSVsv(must_sv));
25147 must = SvPV(must_sv, must_len);
25154 /* (Note: 'must' could contain a NUL. And yet we use strspn() below on it.
25155 * This works because the NUL causes the function to return early, thus
25156 * showing that there are characters in it other than the acceptable ones,
25157 * which is our desired result.) */
25159 prog = ReANY(subpattern_re);
25161 /* If only nothing is matched, skip to where empty names are looked for */
25162 if (prog->maxlen == 0) {
25166 /* And match against the string of all names /gc. Don't even try if it
25167 * must match a character not found in any name. */
25168 if (strspn(must, "\n -0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ()") == must_len)
25170 while (execute_wildcard(subpattern_re,
25172 SvEND(names_string),
25173 all_names_start, 0,
25176 { /* Here, matched. */
25178 /* Note the string entries look like
25179 * 00001\nSTART OF HEADING\n\n
25180 * so we could match anywhere in that string. We have to rule out
25181 * matching a code point line */
25182 char * this_name_start = all_names_start
25183 + RX_OFFS(subpattern_re)->start;
25184 char * this_name_end = all_names_start
25185 + RX_OFFS(subpattern_re)->end;
25188 UV cp = 0; /* Silences some compilers */
25189 AV * this_string = NULL;
25190 bool is_multi = FALSE;
25192 /* If matched nothing, advance to next possible match */
25193 if (this_name_start == this_name_end) {
25194 cur_pos = (char *) memchr(this_name_end + 1, '\n',
25195 SvEND(names_string) - this_name_end);
25196 if (cur_pos == NULL) {
25201 /* Position the next match to start beyond the current returned
25203 cur_pos = (char *) memchr(this_name_end, '\n',
25204 SvEND(names_string) - this_name_end);
25207 /* Back up to the \n just before the beginning of the character. */
25208 cp_end = (char *) my_memrchr(all_names_start,
25210 this_name_start - all_names_start);
25212 /* If we didn't find a \n, it means it matched somewhere in the
25213 * initial '00000' in the string, so isn't a real match */
25214 if (cp_end == NULL) {
25218 this_name_start = cp_end + 1; /* The name starts just after */
25219 cp_end--; /* the \n, and the code point */
25220 /* ends just before it */
25222 /* All code points are 5 digits long */
25223 cp_start = cp_end - 4;
25225 /* This shouldn't happen, as we found a \n, and the first \n is
25226 * further along than what we subtracted */
25227 assert(cp_start >= all_names_start);
25229 if (cp_start == all_names_start) {
25230 *prop_definition = add_cp_to_invlist(*prop_definition, 0);
25234 /* If the character is a blank, we either have a named sequence, or
25235 * something is wrong */
25236 if (*(cp_start - 1) == ' ') {
25237 cp_start = (char *) my_memrchr(all_names_start,
25239 cp_start - all_names_start);
25243 assert(cp_start != NULL && cp_start >= all_names_start + 2);
25245 /* Except for the first line in the string, the sequence before the
25246 * code point is \n\n. If that isn't the case here, we didn't
25247 * match the name of a character. (We could have matched a named
25248 * sequence, not currently handled */
25249 if (*(cp_start - 1) != '\n' || *(cp_start - 2) != '\n') {
25253 /* We matched! Add this to the list */
25254 found_matches = TRUE;
25256 /* Loop through all the code points in the sequence */
25257 while (cp_start < cp_end) {
25259 /* Calculate this code point from its 5 digits */
25260 cp = (XDIGIT_VALUE(cp_start[0]) << 16)
25261 + (XDIGIT_VALUE(cp_start[1]) << 12)
25262 + (XDIGIT_VALUE(cp_start[2]) << 8)
25263 + (XDIGIT_VALUE(cp_start[3]) << 4)
25264 + XDIGIT_VALUE(cp_start[4]);
25266 cp_start += 6; /* Go past any blank */
25268 if (cp_start < cp_end || is_multi) {
25269 if (this_string == NULL) {
25270 this_string = newAV();
25274 av_push(this_string, newSVuv(cp));
25278 if (is_multi) { /* Was more than one code point */
25279 if (*strings == NULL) {
25280 *strings = newAV();
25283 av_push(*strings, (SV *) this_string);
25285 else { /* Only a single code point */
25286 *prop_definition = add_cp_to_invlist(*prop_definition, cp);
25288 } /* End of loop through the non-algorithmic names string */
25291 /* There are also character names not in 'names_string'. These are
25292 * algorithmically generatable. Try this pattern on each possible one.
25293 * (khw originally planned to leave this out given the large number of
25294 * matches attempted; but the speed turned out to be quite acceptable
25296 * There are plenty of opportunities to optimize to skip many of the tests.
25297 * beyond the rudimentary ones already here */
25299 /* First see if the subpattern matches any of the algorithmic generatable
25300 * Hangul syllable names.
25302 * We know none of these syllable names will match if the input pattern
25303 * requires more bytes than any syllable has, or if the input pattern only
25304 * matches an empty name, or if the pattern has something it must match and
25305 * one of the characters in that isn't in any Hangul syllable. */
25306 if ( prog->minlen <= (SSize_t) syl_max_len
25307 && prog->maxlen > 0
25308 && (strspn(must, "\n ABCDEGHIJKLMNOPRSTUWY") == must_len))
25310 /* These constants, names, values, and algorithm are adapted from the
25311 * Unicode standard, version 5.1, section 3.12, and should never
25313 const char * JamoL[] = {
25314 "G", "GG", "N", "D", "DD", "R", "M", "B", "BB",
25315 "S", "SS", "", "J", "JJ", "C", "K", "T", "P", "H"
25317 const int LCount = C_ARRAY_LENGTH(JamoL);
25319 const char * JamoV[] = {
25320 "A", "AE", "YA", "YAE", "EO", "E", "YEO", "YE", "O", "WA",
25321 "WAE", "OE", "YO", "U", "WEO", "WE", "WI", "YU", "EU", "YI",
25324 const int VCount = C_ARRAY_LENGTH(JamoV);
25326 const char * JamoT[] = {
25327 "", "G", "GG", "GS", "N", "NJ", "NH", "D", "L",
25328 "LG", "LM", "LB", "LS", "LT", "LP", "LH", "M", "B",
25329 "BS", "S", "SS", "NG", "J", "C", "K", "T", "P", "H"
25331 const int TCount = C_ARRAY_LENGTH(JamoT);
25335 /* This is the initial Hangul syllable code point; each time through the
25336 * inner loop, it maps to the next higher code point. For more info,
25337 * see the Hangul syllable section of the Unicode standard. */
25340 syllable_name = sv_2mortal(newSV(syl_max_len));
25341 sv_setpvn(syllable_name, hangul_prefix, hangul_prefix_len);
25343 for (L = 0; L < LCount; L++) {
25344 for (V = 0; V < VCount; V++) {
25345 for (T = 0; T < TCount; T++) {
25347 /* Truncate back to the prefix, which is unvarying */
25348 SvCUR_set(syllable_name, hangul_prefix_len);
25350 sv_catpv(syllable_name, JamoL[L]);
25351 sv_catpv(syllable_name, JamoV[V]);
25352 sv_catpv(syllable_name, JamoT[T]);
25354 if (execute_wildcard(subpattern_re,
25355 SvPVX(syllable_name),
25356 SvEND(syllable_name),
25357 SvPVX(syllable_name), 0,
25361 *prop_definition = add_cp_to_invlist(*prop_definition,
25363 found_matches = TRUE;
25372 /* The rest of the algorithmically generatable names are of the form
25373 * "PREFIX-code_point". The prefixes and the code point limits of each
25374 * were returned to us in the array 'algorithmic_names' from data in
25375 * lib/unicore/Name.pm. 'code_point' in the name is expressed in hex. */
25376 for (i = 0; i <= av_top_index((AV *) algorithmic_names); i++) {
25379 /* Each element of the array is a hash, giving the details for the
25380 * series of names it covers. There is the base name of the characters
25381 * in the series, and the low and high code points in the series. And,
25382 * for optimization purposes a string containing all the legal
25383 * characters that could possibly be in a name in this series. */
25384 HV * this_series = (HV *) SvRV(* av_fetch((AV *) algorithmic_names, i, 0));
25385 SV * prefix = * hv_fetchs(this_series, "name", 0);
25386 IV low = SvIV(* hv_fetchs(this_series, "low", 0));
25387 IV high = SvIV(* hv_fetchs(this_series, "high", 0));
25388 char * legal = SvPVX(* hv_fetchs(this_series, "legal", 0));
25390 /* Pre-allocate an SV with enough space */
25391 SV * algo_name = sv_2mortal(Perl_newSVpvf(aTHX_ "%s-0000",
25393 if (high >= 0x10000) {
25394 sv_catpvs(algo_name, "0");
25397 /* This series can be skipped entirely if the pattern requires
25398 * something longer than any name in the series, or can only match an
25399 * empty name, or contains a character not found in any name in the
25401 if ( prog->minlen <= (SSize_t) SvCUR(algo_name)
25402 && prog->maxlen > 0
25403 && (strspn(must, legal) == must_len))
25405 for (j = low; j <= high; j++) { /* For each code point in the series */
25407 /* Get its name, and see if it matches the subpattern */
25408 Perl_sv_setpvf(aTHX_ algo_name, "%s-%X", SvPVX(prefix),
25411 if (execute_wildcard(subpattern_re,
25414 SvPVX(algo_name), 0,
25418 *prop_definition = add_cp_to_invlist(*prop_definition, j);
25419 found_matches = TRUE;
25426 /* Finally, see if the subpattern matches an empty string */
25427 empty = newSVpvs("");
25428 if (execute_wildcard(subpattern_re,
25435 /* Many code points have empty names. Currently these are the \p{GC=C}
25436 * ones, minus CC and CF */
25438 SV * empty_names_ref = get_prop_definition(UNI_C);
25439 SV * empty_names = invlist_clone(empty_names_ref, NULL);
25441 SV * subtract = get_prop_definition(UNI_CC);
25443 _invlist_subtract(empty_names, subtract, &empty_names);
25444 SvREFCNT_dec_NN(empty_names_ref);
25445 SvREFCNT_dec_NN(subtract);
25447 subtract = get_prop_definition(UNI_CF);
25448 _invlist_subtract(empty_names, subtract, &empty_names);
25449 SvREFCNT_dec_NN(subtract);
25451 _invlist_union(*prop_definition, empty_names, prop_definition);
25452 found_matches = TRUE;
25453 SvREFCNT_dec_NN(empty_names);
25455 SvREFCNT_dec_NN(empty);
25458 /* If we ever were to accept aliases for, say private use names, we would
25459 * need to do something fancier to find empty names. The code below works
25460 * (at the time it was written), and is slower than the above */
25461 const char empties_pat[] = "^.";
25462 if (strNE(name, empties_pat)) {
25463 SV * empty = newSVpvs("");
25464 if (execute_wildcard(subpattern_re,
25471 SV * empties = NULL;
25473 (void) handle_names_wildcard(empties_pat, strlen(empties_pat), &empties);
25475 _invlist_union_complement_2nd(*prop_definition, empties, prop_definition);
25476 SvREFCNT_dec_NN(empties);
25478 found_matches = TRUE;
25480 SvREFCNT_dec_NN(empty);
25484 SvREFCNT_dec_NN(subpattern_re);
25485 return found_matches;
25489 * ex: set ts=8 sts=4 sw=4 et: