5 * 'A fair jaw-cracker dwarf-language must be.' --Samwise Gamgee
7 * [p.285 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
10 /* This file contains functions for compiling a regular expression. See
11 * also regexec.c which funnily enough, contains functions for executing
12 * a regular expression.
14 * This file is also copied at build time to ext/re/re_comp.c, where
15 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
16 * This causes the main functions to be compiled under new names and with
17 * debugging support added, which makes "use re 'debug'" work.
20 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
21 * confused with the original package (see point 3 below). Thanks, Henry!
24 /* Additional note: this code is very heavily munged from Henry's version
25 * in places. In some spots I've traded clarity for efficiency, so don't
26 * blame Henry for some of the lack of readability.
29 /* The names of the functions have been changed from regcomp and
30 * regexec to pregcomp and pregexec in order to avoid conflicts
31 * with the POSIX routines of the same names.
34 #ifdef PERL_EXT_RE_BUILD
39 * pregcomp and pregexec -- regsub and regerror are not used in perl
41 * Copyright (c) 1986 by University of Toronto.
42 * Written by Henry Spencer. Not derived from licensed software.
44 * Permission is granted to anyone to use this software for any
45 * purpose on any computer system, and to redistribute it freely,
46 * subject to the following restrictions:
48 * 1. The author is not responsible for the consequences of use of
49 * this software, no matter how awful, even if they arise
52 * 2. The origin of this software must not be misrepresented, either
53 * by explicit claim or by omission.
55 * 3. Altered versions must be plainly marked as such, and must not
56 * be misrepresented as being the original software.
59 **** Alterations to Henry's code are...
61 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
62 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
63 **** by Larry Wall and others
65 **** You may distribute under the terms of either the GNU General Public
66 **** License or the Artistic License, as specified in the README file.
69 * Beware that some of this code is subtly aware of the way operator
70 * precedence is structured in regular expressions. Serious changes in
71 * regular-expression syntax might require a total rethink.
74 #define PERL_IN_REGCOMP_C
77 #ifndef PERL_IN_XSUB_RE
82 #ifdef PERL_IN_XSUB_RE
84 EXTERN_C const struct regexp_engine my_reg_engine;
89 #include "dquote_inline.h"
90 #include "invlist_inline.h"
91 #include "unicode_constants.h"
93 #define HAS_NONLATIN1_FOLD_CLOSURE(i) \
94 _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
95 #define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
96 _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
97 #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
98 #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
101 #define STATIC static
104 /* this is a chain of data about sub patterns we are processing that
105 need to be handled separately/specially in study_chunk. Its so
106 we can simulate recursion without losing state. */
108 typedef struct scan_frame {
109 regnode *last_regnode; /* last node to process in this frame */
110 regnode *next_regnode; /* next node to process when last is reached */
111 U32 prev_recursed_depth;
112 I32 stopparen; /* what stopparen do we use */
114 struct scan_frame *this_prev_frame; /* this previous frame */
115 struct scan_frame *prev_frame; /* previous frame */
116 struct scan_frame *next_frame; /* next frame */
119 /* Certain characters are output as a sequence with the first being a
121 #define isBACKSLASHED_PUNCT(c) strchr("-[]\\^", c)
124 struct RExC_state_t {
125 U32 flags; /* RXf_* are we folding, multilining? */
126 U32 pm_flags; /* PMf_* stuff from the calling PMOP */
127 char *precomp; /* uncompiled string. */
128 char *precomp_end; /* pointer to end of uncompiled string. */
129 REGEXP *rx_sv; /* The SV that is the regexp. */
130 regexp *rx; /* perl core regexp structure */
131 regexp_internal *rxi; /* internal data for regexp object
133 char *start; /* Start of input for compile */
134 char *end; /* End of input for compile */
135 char *parse; /* Input-scan pointer. */
136 char *copy_start; /* start of copy of input within
137 constructed parse string */
138 char *copy_start_in_input; /* Position in input string
139 corresponding to copy_start */
140 SSize_t whilem_seen; /* number of WHILEM in this expr */
141 regnode *emit_start; /* Start of emitted-code area */
142 regnode_offset emit; /* Code-emit pointer */
143 I32 naughty; /* How bad is this pattern? */
144 I32 sawback; /* Did we see \1, ...? */
146 SSize_t size; /* Number of regnode equivalents in
149 /* position beyond 'precomp' of the warning message furthest away from
150 * 'precomp'. During the parse, no warnings are raised for any problems
151 * earlier in the parse than this position. This works if warnings are
152 * raised the first time a given spot is parsed, and if only one
153 * independent warning is raised for any given spot */
154 Size_t latest_warn_offset;
156 I32 npar; /* Capture buffer count so far in the
157 parse, (OPEN) plus one. ("par" 0 is
159 I32 total_par; /* During initial parse, is either 0,
160 or -1; the latter indicating a
161 reparse is needed. After that pass,
162 it is what 'npar' became after the
163 pass. Hence, it being > 0 indicates
164 we are in a reparse situation */
165 I32 nestroot; /* root parens we are in - used by
168 regnode_offset *open_parens; /* offsets to open parens */
169 regnode_offset *close_parens; /* offsets to close parens */
170 regnode *end_op; /* END node in program */
171 I32 utf8; /* whether the pattern is utf8 or not */
172 I32 orig_utf8; /* whether the pattern was originally in utf8 */
173 /* XXX use this for future optimisation of case
174 * where pattern must be upgraded to utf8. */
175 I32 uni_semantics; /* If a d charset modifier should use unicode
176 rules, even if the pattern is not in
178 HV *paren_names; /* Paren names */
180 regnode **recurse; /* Recurse regops */
181 I32 recurse_count; /* Number of recurse regops we have generated */
182 U8 *study_chunk_recursed; /* bitmap of which subs we have moved
184 U32 study_chunk_recursed_bytes; /* bytes in bitmap */
187 I32 override_recoding;
189 I32 recode_x_to_native;
191 I32 in_multi_char_class;
192 struct reg_code_blocks *code_blocks;/* positions of literal (?{})
194 int code_index; /* next code_blocks[] slot */
195 SSize_t maxlen; /* mininum possible number of chars in string to match */
196 scan_frame *frame_head;
197 scan_frame *frame_last;
200 #ifdef ADD_TO_REGEXEC
201 char *starttry; /* -Dr: where regtry was called. */
202 #define RExC_starttry (pRExC_state->starttry)
204 SV *runtime_code_qr; /* qr with the runtime code blocks */
206 const char *lastparse;
208 AV *paren_name_list; /* idx -> name */
209 U32 study_chunk_recursed_count;
213 #define RExC_lastparse (pRExC_state->lastparse)
214 #define RExC_lastnum (pRExC_state->lastnum)
215 #define RExC_paren_name_list (pRExC_state->paren_name_list)
216 #define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count)
217 #define RExC_mysv (pRExC_state->mysv1)
218 #define RExC_mysv1 (pRExC_state->mysv1)
219 #define RExC_mysv2 (pRExC_state->mysv2)
229 #define RExC_flags (pRExC_state->flags)
230 #define RExC_pm_flags (pRExC_state->pm_flags)
231 #define RExC_precomp (pRExC_state->precomp)
232 #define RExC_copy_start_in_input (pRExC_state->copy_start_in_input)
233 #define RExC_copy_start_in_constructed (pRExC_state->copy_start)
234 #define RExC_precomp_end (pRExC_state->precomp_end)
235 #define RExC_rx_sv (pRExC_state->rx_sv)
236 #define RExC_rx (pRExC_state->rx)
237 #define RExC_rxi (pRExC_state->rxi)
238 #define RExC_start (pRExC_state->start)
239 #define RExC_end (pRExC_state->end)
240 #define RExC_parse (pRExC_state->parse)
241 #define RExC_latest_warn_offset (pRExC_state->latest_warn_offset )
242 #define RExC_whilem_seen (pRExC_state->whilem_seen)
243 #define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs
244 under /d from /u ? */
247 #ifdef RE_TRACK_PATTERN_OFFSETS
248 # define RExC_offsets (RExC_rxi->u.offsets) /* I am not like the
251 #define RExC_emit (pRExC_state->emit)
252 #define RExC_emit_start (pRExC_state->emit_start)
253 #define RExC_sawback (pRExC_state->sawback)
254 #define RExC_seen (pRExC_state->seen)
255 #define RExC_size (pRExC_state->size)
256 #define RExC_maxlen (pRExC_state->maxlen)
257 #define RExC_npar (pRExC_state->npar)
258 #define RExC_total_parens (pRExC_state->total_par)
259 #define RExC_nestroot (pRExC_state->nestroot)
260 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
261 #define RExC_utf8 (pRExC_state->utf8)
262 #define RExC_uni_semantics (pRExC_state->uni_semantics)
263 #define RExC_orig_utf8 (pRExC_state->orig_utf8)
264 #define RExC_open_parens (pRExC_state->open_parens)
265 #define RExC_close_parens (pRExC_state->close_parens)
266 #define RExC_end_op (pRExC_state->end_op)
267 #define RExC_paren_names (pRExC_state->paren_names)
268 #define RExC_recurse (pRExC_state->recurse)
269 #define RExC_recurse_count (pRExC_state->recurse_count)
270 #define RExC_study_chunk_recursed (pRExC_state->study_chunk_recursed)
271 #define RExC_study_chunk_recursed_bytes \
272 (pRExC_state->study_chunk_recursed_bytes)
273 #define RExC_in_lookbehind (pRExC_state->in_lookbehind)
274 #define RExC_contains_locale (pRExC_state->contains_locale)
276 # define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
278 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
279 #define RExC_frame_head (pRExC_state->frame_head)
280 #define RExC_frame_last (pRExC_state->frame_last)
281 #define RExC_frame_count (pRExC_state->frame_count)
282 #define RExC_strict (pRExC_state->strict)
283 #define RExC_study_started (pRExC_state->study_started)
284 #define RExC_warn_text (pRExC_state->warn_text)
285 #define RExC_in_script_run (pRExC_state->in_script_run)
286 #define RExC_use_BRANCHJ (pRExC_state->use_BRANCHJ)
288 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
289 * a flag to disable back-off on the fixed/floating substrings - if it's
290 * a high complexity pattern we assume the benefit of avoiding a full match
291 * is worth the cost of checking for the substrings even if they rarely help.
293 #define RExC_naughty (pRExC_state->naughty)
294 #define TOO_NAUGHTY (10)
295 #define MARK_NAUGHTY(add) \
296 if (RExC_naughty < TOO_NAUGHTY) \
297 RExC_naughty += (add)
298 #define MARK_NAUGHTY_EXP(exp, add) \
299 if (RExC_naughty < TOO_NAUGHTY) \
300 RExC_naughty += RExC_naughty / (exp) + (add)
302 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
303 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
304 ((*s) == '{' && regcurly(s)))
307 * Flags to be passed up and down.
309 #define WORST 0 /* Worst case. */
310 #define HASWIDTH 0x01 /* Known to match non-null strings. */
312 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
313 * character. (There needs to be a case: in the switch statement in regexec.c
314 * for any node marked SIMPLE.) Note that this is not the same thing as
317 #define SPSTART 0x04 /* Starts with * or + */
318 #define POSTPONED 0x08 /* (?1),(?&name), (??{...}) or similar */
319 #define TRYAGAIN 0x10 /* Weeded out a declaration. */
320 #define RESTART_PARSE 0x20 /* Need to redo the parse */
321 #define NEED_UTF8 0x40 /* In conjunction with RESTART_PARSE, need to
322 calcuate sizes as UTF-8 */
324 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
326 /* whether trie related optimizations are enabled */
327 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
328 #define TRIE_STUDY_OPT
329 #define FULL_TRIE_STUDY
335 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
336 #define PBITVAL(paren) (1 << ((paren) & 7))
337 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
338 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
339 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
341 #define REQUIRE_UTF8(flagp) STMT_START { \
343 *flagp = RESTART_PARSE|NEED_UTF8; \
348 /* Change from /d into /u rules, and restart the parse. RExC_uni_semantics is
349 * a flag that indicates we've changed to /u during the parse. */
350 #define REQUIRE_UNI_RULES(flagp, restart_retval) \
352 if (DEPENDS_SEMANTICS) { \
353 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); \
354 RExC_uni_semantics = 1; \
355 if (RExC_seen_d_op && LIKELY(RExC_total_parens >= 0)) { \
356 /* No need to restart the parse if we haven't seen \
357 * anything that differs between /u and /d, and no need \
358 * to restart immediately if we're going to reparse \
359 * anyway to count parens */ \
360 *flagp |= RESTART_PARSE; \
361 return restart_retval; \
366 #define BRANCH_MAX_OFFSET U16_MAX
367 #define REQUIRE_BRANCHJ(flagp, restart_retval) \
369 RExC_use_BRANCHJ = 1; \
370 if (LIKELY(RExC_total_parens >= 0)) { \
371 /* No need to restart the parse immediately if we're \
372 * going to reparse anyway to count parens */ \
373 *flagp |= RESTART_PARSE; \
374 return restart_retval; \
378 #define REQUIRE_PARENS_PASS \
380 if (RExC_total_parens == 0) RExC_total_parens = -1; \
383 /* This is used to return failure (zero) early from the calling function if
384 * various flags in 'flags' are set. Two flags always cause a return:
385 * 'RESTART_PARSE' and 'NEED_UTF8'. 'extra' can be used to specify any
386 * additional flags that should cause a return; 0 if none. If the return will
387 * be done, '*flagp' is first set to be all of the flags that caused the
389 #define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra) \
391 if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) { \
392 *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra)); \
397 #define MUST_RESTART(flags) ((flags) & (RESTART_PARSE))
399 #define RETURN_FAIL_ON_RESTART(flags,flagp) \
400 RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0)
401 #define RETURN_FAIL_ON_RESTART_FLAGP(flagp) \
402 if (MUST_RESTART(*(flagp))) return 0
404 /* This converts the named class defined in regcomp.h to its equivalent class
405 * number defined in handy.h. */
406 #define namedclass_to_classnum(class) ((int) ((class) / 2))
407 #define classnum_to_namedclass(classnum) ((classnum) * 2)
409 #define _invlist_union_complement_2nd(a, b, output) \
410 _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
411 #define _invlist_intersection_complement_2nd(a, b, output) \
412 _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
414 /* About scan_data_t.
416 During optimisation we recurse through the regexp program performing
417 various inplace (keyhole style) optimisations. In addition study_chunk
418 and scan_commit populate this data structure with information about
419 what strings MUST appear in the pattern. We look for the longest
420 string that must appear at a fixed location, and we look for the
421 longest string that may appear at a floating location. So for instance
426 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
427 strings (because they follow a .* construct). study_chunk will identify
428 both FOO and BAR as being the longest fixed and floating strings respectively.
430 The strings can be composites, for instance
434 will result in a composite fixed substring 'foo'.
436 For each string some basic information is maintained:
439 This is the position the string must appear at, or not before.
440 It also implicitly (when combined with minlenp) tells us how many
441 characters must match before the string we are searching for.
442 Likewise when combined with minlenp and the length of the string it
443 tells us how many characters must appear after the string we have
447 Only used for floating strings. This is the rightmost point that
448 the string can appear at. If set to SSize_t_MAX it indicates that the
449 string can occur infinitely far to the right.
450 For fixed strings, it is equal to min_offset.
453 A pointer to the minimum number of characters of the pattern that the
454 string was found inside. This is important as in the case of positive
455 lookahead or positive lookbehind we can have multiple patterns
460 The minimum length of the pattern overall is 3, the minimum length
461 of the lookahead part is 3, but the minimum length of the part that
462 will actually match is 1. So 'FOO's minimum length is 3, but the
463 minimum length for the F is 1. This is important as the minimum length
464 is used to determine offsets in front of and behind the string being
465 looked for. Since strings can be composites this is the length of the
466 pattern at the time it was committed with a scan_commit. Note that
467 the length is calculated by study_chunk, so that the minimum lengths
468 are not known until the full pattern has been compiled, thus the
469 pointer to the value.
473 In the case of lookbehind the string being searched for can be
474 offset past the start point of the final matching string.
475 If this value was just blithely removed from the min_offset it would
476 invalidate some of the calculations for how many chars must match
477 before or after (as they are derived from min_offset and minlen and
478 the length of the string being searched for).
479 When the final pattern is compiled and the data is moved from the
480 scan_data_t structure into the regexp structure the information
481 about lookbehind is factored in, with the information that would
482 have been lost precalculated in the end_shift field for the
485 The fields pos_min and pos_delta are used to store the minimum offset
486 and the delta to the maximum offset at the current point in the pattern.
490 struct scan_data_substrs {
491 SV *str; /* longest substring found in pattern */
492 SSize_t min_offset; /* earliest point in string it can appear */
493 SSize_t max_offset; /* latest point in string it can appear */
494 SSize_t *minlenp; /* pointer to the minlen relevant to the string */
495 SSize_t lookbehind; /* is the pos of the string modified by LB */
496 I32 flags; /* per substring SF_* and SCF_* flags */
499 typedef struct scan_data_t {
500 /*I32 len_min; unused */
501 /*I32 len_delta; unused */
505 SSize_t last_end; /* min value, <0 unless valid. */
506 SSize_t last_start_min;
507 SSize_t last_start_max;
508 U8 cur_is_floating; /* whether the last_* values should be set as
509 * the next fixed (0) or floating (1)
512 /* [0] is longest fixed substring so far, [1] is longest float so far */
513 struct scan_data_substrs substrs[2];
515 I32 flags; /* common SF_* and SCF_* flags */
517 SSize_t *last_closep;
518 regnode_ssc *start_class;
522 * Forward declarations for pregcomp()'s friends.
525 static const scan_data_t zero_scan_data = {
526 0, 0, NULL, 0, 0, 0, 0,
528 { NULL, 0, 0, 0, 0, 0 },
529 { NULL, 0, 0, 0, 0, 0 },
536 #define SF_BEFORE_SEOL 0x0001
537 #define SF_BEFORE_MEOL 0x0002
538 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
540 #define SF_IS_INF 0x0040
541 #define SF_HAS_PAR 0x0080
542 #define SF_IN_PAR 0x0100
543 #define SF_HAS_EVAL 0x0200
546 /* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
547 * longest substring in the pattern. When it is not set the optimiser keeps
548 * track of position, but does not keep track of the actual strings seen,
550 * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
553 * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
554 * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
555 * turned off because of the alternation (BRANCH). */
556 #define SCF_DO_SUBSTR 0x0400
558 #define SCF_DO_STCLASS_AND 0x0800
559 #define SCF_DO_STCLASS_OR 0x1000
560 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
561 #define SCF_WHILEM_VISITED_POS 0x2000
563 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
564 #define SCF_SEEN_ACCEPT 0x8000
565 #define SCF_TRIE_DOING_RESTUDY 0x10000
566 #define SCF_IN_DEFINE 0x20000
571 #define UTF cBOOL(RExC_utf8)
573 /* The enums for all these are ordered so things work out correctly */
574 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
575 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) \
576 == REGEX_DEPENDS_CHARSET)
577 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
578 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) \
579 >= REGEX_UNICODE_CHARSET)
580 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
581 == REGEX_ASCII_RESTRICTED_CHARSET)
582 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
583 >= REGEX_ASCII_RESTRICTED_CHARSET)
584 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) \
585 == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
587 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
589 /* For programs that want to be strictly Unicode compatible by dying if any
590 * attempt is made to match a non-Unicode code point against a Unicode
592 #define ALWAYS_WARN_SUPER ckDEAD(packWARN(WARN_NON_UNICODE))
594 #define OOB_NAMEDCLASS -1
596 /* There is no code point that is out-of-bounds, so this is problematic. But
597 * its only current use is to initialize a variable that is always set before
599 #define OOB_UNICODE 0xDEADBEEF
601 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
604 /* length of regex to show in messages that don't mark a position within */
605 #define RegexLengthToShowInErrorMessages 127
608 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
609 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
610 * op/pragma/warn/regcomp.
612 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
613 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
615 #define REPORT_LOCATION " in regex; marked by " MARKER1 \
616 " in m/%" UTF8f MARKER2 "%" UTF8f "/"
618 /* The code in this file in places uses one level of recursion with parsing
619 * rebased to an alternate string constructed by us in memory. This can take
620 * the form of something that is completely different from the input, or
621 * something that uses the input as part of the alternate. In the first case,
622 * there should be no possibility of an error, as we are in complete control of
623 * the alternate string. But in the second case we don't completely control
624 * the input portion, so there may be errors in that. Here's an example:
626 * is handled specially because \x{df} folds to a sequence of more than one
627 * character: 'ss'. What is done is to create and parse an alternate string,
628 * which looks like this:
629 * /(?:\x{DF}|[abc\x{DF}def])/ui
630 * where it uses the input unchanged in the middle of something it constructs,
631 * which is a branch for the DF outside the character class, and clustering
632 * parens around the whole thing. (It knows enough to skip the DF inside the
633 * class while in this substitute parse.) 'abc' and 'def' may have errors that
634 * need to be reported. The general situation looks like this:
636 * |<------- identical ------>|
638 * Input: ---------------------------------------------------------------
639 * Constructed: ---------------------------------------------------
641 * |<------- identical ------>|
643 * sI..eI is the portion of the input pattern we are concerned with here.
644 * sC..EC is the constructed substitute parse string.
645 * sC..tC is constructed by us
646 * tC..eC is an exact duplicate of the portion of the input pattern tI..eI.
647 * In the diagram, these are vertically aligned.
648 * eC..EC is also constructed by us.
649 * xC is the position in the substitute parse string where we found a
651 * xI is the position in the original pattern corresponding to xC.
653 * We want to display a message showing the real input string. Thus we need to
654 * translate from xC to xI. We know that xC >= tC, since the portion of the
655 * string sC..tC has been constructed by us, and so shouldn't have errors. We
657 * xI = tI + (xC - tC)
659 * When the substitute parse is constructed, the code needs to set:
662 * RExC_copy_start_in_input (tI)
663 * RExC_copy_start_in_constructed (tC)
664 * and restore them when done.
666 * During normal processing of the input pattern, both
667 * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to
668 * sI, so that xC equals xI.
671 #define sI RExC_precomp
672 #define eI RExC_precomp_end
673 #define sC RExC_start
675 #define tI RExC_copy_start_in_input
676 #define tC RExC_copy_start_in_constructed
677 #define xI(xC) (tI + (xC - tC))
678 #define xI_offset(xC) (xI(xC) - sI)
680 #define REPORT_LOCATION_ARGS(xC) \
682 (xI(xC) > eI) /* Don't run off end */ \
683 ? eI - sI /* Length before the <--HERE */ \
684 : ((xI_offset(xC) >= 0) \
686 : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %" \
687 IVdf " trying to output message for " \
689 __FILE__, __LINE__, (IV) xI_offset(xC), \
690 ((int) (eC - sC)), sC), 0)), \
691 sI), /* The input pattern printed up to the <--HERE */ \
693 (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */ \
694 (xI(xC) > eI) ? eI : xI(xC)) /* pattern after <--HERE */
696 /* Used to point after bad bytes for an error message, but avoid skipping
697 * past a nul byte. */
698 #define SKIP_IF_CHAR(s) (!*(s) ? 0 : UTF ? UTF8SKIP(s) : 1)
700 /* Set up to clean up after our imminent demise */
701 #define PREPARE_TO_DIE \
704 SAVEFREESV(RExC_rx_sv); \
705 if (RExC_open_parens) \
706 SAVEFREEPV(RExC_open_parens); \
707 if (RExC_close_parens) \
708 SAVEFREEPV(RExC_close_parens); \
712 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
713 * arg. Show regex, up to a maximum length. If it's too long, chop and add
716 #define _FAIL(code) STMT_START { \
717 const char *ellipses = ""; \
718 IV len = RExC_precomp_end - RExC_precomp; \
721 if (len > RegexLengthToShowInErrorMessages) { \
722 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
723 len = RegexLengthToShowInErrorMessages - 10; \
729 #define FAIL(msg) _FAIL( \
730 Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/", \
731 msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
733 #define FAIL2(msg,arg) _FAIL( \
734 Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \
735 arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
738 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
740 #define Simple_vFAIL(m) STMT_START { \
741 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
742 m, REPORT_LOCATION_ARGS(RExC_parse)); \
746 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
748 #define vFAIL(m) STMT_START { \
754 * Like Simple_vFAIL(), but accepts two arguments.
756 #define Simple_vFAIL2(m,a1) STMT_START { \
757 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
758 REPORT_LOCATION_ARGS(RExC_parse)); \
762 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
764 #define vFAIL2(m,a1) STMT_START { \
766 Simple_vFAIL2(m, a1); \
771 * Like Simple_vFAIL(), but accepts three arguments.
773 #define Simple_vFAIL3(m, a1, a2) STMT_START { \
774 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
775 REPORT_LOCATION_ARGS(RExC_parse)); \
779 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
781 #define vFAIL3(m,a1,a2) STMT_START { \
783 Simple_vFAIL3(m, a1, a2); \
787 * Like Simple_vFAIL(), but accepts four arguments.
789 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
790 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3, \
791 REPORT_LOCATION_ARGS(RExC_parse)); \
794 #define vFAIL4(m,a1,a2,a3) STMT_START { \
796 Simple_vFAIL4(m, a1, a2, a3); \
799 /* A specialized version of vFAIL2 that works with UTF8f */
800 #define vFAIL2utf8f(m, a1) STMT_START { \
802 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
803 REPORT_LOCATION_ARGS(RExC_parse)); \
806 #define vFAIL3utf8f(m, a1, a2) STMT_START { \
808 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
809 REPORT_LOCATION_ARGS(RExC_parse)); \
812 /* Setting this to NULL is a signal to not output warnings */
813 #define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE RExC_copy_start_in_constructed = NULL
814 #define RESTORE_WARNINGS RExC_copy_start_in_constructed = RExC_precomp
816 /* Since a warning can be generated multiple times as the input is reparsed, we
817 * output it the first time we come to that point in the parse, but suppress it
818 * otherwise. 'RExC_copy_start_in_constructed' being NULL is a flag to not
819 * generate any warnings */
820 #define TO_OUTPUT_WARNINGS(loc) \
821 ( RExC_copy_start_in_constructed \
822 && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset)
824 /* After we've emitted a warning, we save the position in the input so we don't
826 #define UPDATE_WARNINGS_LOC(loc) \
828 if (TO_OUTPUT_WARNINGS(loc)) { \
829 RExC_latest_warn_offset = (xI(loc)) - RExC_precomp; \
833 /* 'warns' is the output of the packWARNx macro used in 'code' */
834 #define _WARN_HELPER(loc, warns, code) \
836 if (! RExC_copy_start_in_constructed) { \
837 Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none" \
838 " expected at '%s'", \
839 __FILE__, __LINE__, loc); \
841 if (TO_OUTPUT_WARNINGS(loc)) { \
845 UPDATE_WARNINGS_LOC(loc); \
849 /* m is not necessarily a "literal string", in this macro */
850 #define reg_warn_non_literal_string(loc, m) \
851 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
852 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
853 "%s" REPORT_LOCATION, \
854 m, REPORT_LOCATION_ARGS(loc)))
856 #define ckWARNreg(loc,m) \
857 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
858 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
860 REPORT_LOCATION_ARGS(loc)))
862 #define vWARN(loc, m) \
863 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
864 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
866 REPORT_LOCATION_ARGS(loc))) \
868 #define vWARN_dep(loc, m) \
869 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
870 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), \
872 REPORT_LOCATION_ARGS(loc)))
874 #define ckWARNdep(loc,m) \
875 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
876 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
878 REPORT_LOCATION_ARGS(loc)))
880 #define ckWARNregdep(loc,m) \
881 _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
882 Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, \
885 REPORT_LOCATION_ARGS(loc)))
887 #define ckWARN2reg_d(loc,m, a1) \
888 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
889 Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP), \
891 a1, REPORT_LOCATION_ARGS(loc)))
893 #define ckWARN2reg(loc, m, a1) \
894 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
895 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
897 a1, REPORT_LOCATION_ARGS(loc)))
899 #define vWARN3(loc, m, a1, a2) \
900 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
901 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
903 a1, a2, REPORT_LOCATION_ARGS(loc)))
905 #define ckWARN3reg(loc, m, a1, a2) \
906 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
907 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
910 REPORT_LOCATION_ARGS(loc)))
912 #define vWARN4(loc, m, a1, a2, a3) \
913 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
914 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
917 REPORT_LOCATION_ARGS(loc)))
919 #define ckWARN4reg(loc, m, a1, a2, a3) \
920 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
921 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
924 REPORT_LOCATION_ARGS(loc)))
926 #define vWARN5(loc, m, a1, a2, a3, a4) \
927 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
928 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
931 REPORT_LOCATION_ARGS(loc)))
933 #define ckWARNexperimental(loc, class, m) \
934 _WARN_HELPER(loc, packWARN(class), \
935 Perl_ck_warner_d(aTHX_ packWARN(class), \
937 REPORT_LOCATION_ARGS(loc)))
939 /* Convert between a pointer to a node and its offset from the beginning of the
941 #define REGNODE_p(offset) (RExC_emit_start + (offset))
942 #define REGNODE_OFFSET(node) ((node) - RExC_emit_start)
944 /* Macros for recording node offsets. 20001227 mjd@plover.com
945 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
946 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
947 * Element 0 holds the number n.
948 * Position is 1 indexed.
950 #ifndef RE_TRACK_PATTERN_OFFSETS
951 #define Set_Node_Offset_To_R(offset,byte)
952 #define Set_Node_Offset(node,byte)
953 #define Set_Cur_Node_Offset
954 #define Set_Node_Length_To_R(node,len)
955 #define Set_Node_Length(node,len)
956 #define Set_Node_Cur_Length(node,start)
957 #define Node_Offset(n)
958 #define Node_Length(n)
959 #define Set_Node_Offset_Length(node,offset,len)
960 #define ProgLen(ri) ri->u.proglen
961 #define SetProgLen(ri,x) ri->u.proglen = x
962 #define Track_Code(code)
964 #define ProgLen(ri) ri->u.offsets[0]
965 #define SetProgLen(ri,x) ri->u.offsets[0] = x
966 #define Set_Node_Offset_To_R(offset,byte) STMT_START { \
967 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
968 __LINE__, (int)(offset), (int)(byte))); \
970 Perl_croak(aTHX_ "value of node is %d in Offset macro", \
973 RExC_offsets[2*(offset)-1] = (byte); \
977 #define Set_Node_Offset(node,byte) \
978 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start)
979 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
981 #define Set_Node_Length_To_R(node,len) STMT_START { \
982 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
983 __LINE__, (int)(node), (int)(len))); \
985 Perl_croak(aTHX_ "value of node is %d in Length macro", \
988 RExC_offsets[2*(node)] = (len); \
992 #define Set_Node_Length(node,len) \
993 Set_Node_Length_To_R(REGNODE_OFFSET(node), len)
994 #define Set_Node_Cur_Length(node, start) \
995 Set_Node_Length(node, RExC_parse - start)
997 /* Get offsets and lengths */
998 #define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1])
999 #define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))])
1001 #define Set_Node_Offset_Length(node,offset,len) STMT_START { \
1002 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset)); \
1003 Set_Node_Length_To_R(REGNODE_OFFSET(node), (len)); \
1006 #define Track_Code(code) STMT_START { code } STMT_END
1009 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
1010 #define EXPERIMENTAL_INPLACESCAN
1011 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
1015 Perl_re_printf(pTHX_ const char *fmt, ...)
1019 PerlIO *f= Perl_debug_log;
1020 PERL_ARGS_ASSERT_RE_PRINTF;
1022 result = PerlIO_vprintf(f, fmt, ap);
1028 Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
1032 PerlIO *f= Perl_debug_log;
1033 PERL_ARGS_ASSERT_RE_INDENTF;
1034 va_start(ap, depth);
1035 PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
1036 result = PerlIO_vprintf(f, fmt, ap);
1040 #endif /* DEBUGGING */
1042 #define DEBUG_RExC_seen() \
1043 DEBUG_OPTIMISE_MORE_r({ \
1044 Perl_re_printf( aTHX_ "RExC_seen: "); \
1046 if (RExC_seen & REG_ZERO_LEN_SEEN) \
1047 Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN "); \
1049 if (RExC_seen & REG_LOOKBEHIND_SEEN) \
1050 Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN "); \
1052 if (RExC_seen & REG_GPOS_SEEN) \
1053 Perl_re_printf( aTHX_ "REG_GPOS_SEEN "); \
1055 if (RExC_seen & REG_RECURSE_SEEN) \
1056 Perl_re_printf( aTHX_ "REG_RECURSE_SEEN "); \
1058 if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN) \
1059 Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN "); \
1061 if (RExC_seen & REG_VERBARG_SEEN) \
1062 Perl_re_printf( aTHX_ "REG_VERBARG_SEEN "); \
1064 if (RExC_seen & REG_CUTGROUP_SEEN) \
1065 Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN "); \
1067 if (RExC_seen & REG_RUN_ON_COMMENT_SEEN) \
1068 Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN "); \
1070 if (RExC_seen & REG_UNFOLDED_MULTI_SEEN) \
1071 Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN "); \
1073 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) \
1074 Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN "); \
1076 Perl_re_printf( aTHX_ "\n"); \
1079 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
1080 if ((flags) & flag) Perl_re_printf( aTHX_ "%s ", #flag)
1085 S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
1086 const char *close_str)
1091 Perl_re_printf( aTHX_ "%s", open_str);
1092 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
1093 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
1094 DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
1095 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
1096 DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
1097 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
1098 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
1099 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
1100 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
1101 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
1102 DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
1103 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
1104 DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
1105 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
1106 DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
1107 Perl_re_printf( aTHX_ "%s", close_str);
1112 S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
1113 U32 depth, int is_inf)
1115 GET_RE_DEBUG_FLAGS_DECL;
1117 DEBUG_OPTIMISE_MORE_r({
1120 Perl_re_indentf(aTHX_ "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
1124 (IV)data->pos_delta,
1128 S_debug_show_study_flags(aTHX_ data->flags," [","]");
1130 Perl_re_printf( aTHX_
1131 " Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
1133 (IV)(data->last_closep ? *((data)->last_closep) : -1),
1134 is_inf ? "INF " : ""
1137 if (data->last_found) {
1139 Perl_re_printf(aTHX_
1140 "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
1141 SvPVX_const(data->last_found),
1143 (IV)data->last_start_min,
1144 (IV)data->last_start_max
1147 for (i = 0; i < 2; i++) {
1148 Perl_re_printf(aTHX_
1149 " %s%s: '%s' @ %" IVdf "/%" IVdf,
1150 data->cur_is_floating == i ? "*" : "",
1151 i ? "Float" : "Fixed",
1152 SvPVX_const(data->substrs[i].str),
1153 (IV)data->substrs[i].min_offset,
1154 (IV)data->substrs[i].max_offset
1156 S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
1160 Perl_re_printf( aTHX_ "\n");
1166 S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
1167 regnode *scan, U32 depth, U32 flags)
1169 GET_RE_DEBUG_FLAGS_DECL;
1176 Next = regnext(scan);
1177 regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
1178 Perl_re_indentf( aTHX_ "%s>%3d: %s (%d)",
1181 REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
1182 Next ? (REG_NODE_NUM(Next)) : 0 );
1183 S_debug_show_study_flags(aTHX_ flags," [ ","]");
1184 Perl_re_printf( aTHX_ "\n");
1189 # define DEBUG_STUDYDATA(where, data, depth, is_inf) \
1190 S_debug_studydata(aTHX_ where, data, depth, is_inf)
1192 # define DEBUG_PEEP(str, scan, depth, flags) \
1193 S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
1196 # define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
1197 # define DEBUG_PEEP(str, scan, depth, flags) NOOP
1201 /* =========================================================
1202 * BEGIN edit_distance stuff.
1204 * This calculates how many single character changes of any type are needed to
1205 * transform a string into another one. It is taken from version 3.1 of
1207 * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1210 /* Our unsorted dictionary linked list. */
1211 /* Note we use UVs, not chars. */
1216 struct dictionary* next;
1218 typedef struct dictionary item;
1221 PERL_STATIC_INLINE item*
1222 push(UV key, item* curr)
1225 Newx(head, 1, item);
1233 PERL_STATIC_INLINE item*
1234 find(item* head, UV key)
1236 item* iterator = head;
1238 if (iterator->key == key){
1241 iterator = iterator->next;
1247 PERL_STATIC_INLINE item*
1248 uniquePush(item* head, UV key)
1250 item* iterator = head;
1253 if (iterator->key == key) {
1256 iterator = iterator->next;
1259 return push(key, head);
1262 PERL_STATIC_INLINE void
1263 dict_free(item* head)
1265 item* iterator = head;
1268 item* temp = iterator;
1269 iterator = iterator->next;
1276 /* End of Dictionary Stuff */
1278 /* All calculations/work are done here */
1280 S_edit_distance(const UV* src,
1282 const STRLEN x, /* length of src[] */
1283 const STRLEN y, /* length of tgt[] */
1284 const SSize_t maxDistance
1288 UV swapCount, swapScore, targetCharCount, i, j;
1290 UV score_ceil = x + y;
1292 PERL_ARGS_ASSERT_EDIT_DISTANCE;
1294 /* intialize matrix start values */
1295 Newx(scores, ( (x + 2) * (y + 2)), UV);
1296 scores[0] = score_ceil;
1297 scores[1 * (y + 2) + 0] = score_ceil;
1298 scores[0 * (y + 2) + 1] = score_ceil;
1299 scores[1 * (y + 2) + 1] = 0;
1300 head = uniquePush(uniquePush(head, src[0]), tgt[0]);
1305 for (i=1;i<=x;i++) {
1307 head = uniquePush(head, src[i]);
1308 scores[(i+1) * (y + 2) + 1] = i;
1309 scores[(i+1) * (y + 2) + 0] = score_ceil;
1312 for (j=1;j<=y;j++) {
1315 head = uniquePush(head, tgt[j]);
1316 scores[1 * (y + 2) + (j + 1)] = j;
1317 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1320 targetCharCount = find(head, tgt[j-1])->value;
1321 swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1323 if (src[i-1] != tgt[j-1]){
1324 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));
1328 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1332 find(head, src[i-1])->value = i;
1336 IV score = scores[(x+1) * (y + 2) + (y + 1)];
1339 return (maxDistance != 0 && maxDistance < score)?(-1):score;
1343 /* END of edit_distance() stuff
1344 * ========================================================= */
1346 /* is c a control character for which we have a mnemonic? */
1347 #define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
1350 S_cntrl_to_mnemonic(const U8 c)
1352 /* Returns the mnemonic string that represents character 'c', if one
1353 * exists; NULL otherwise. The only ones that exist for the purposes of
1354 * this routine are a few control characters */
1357 case '\a': return "\\a";
1358 case '\b': return "\\b";
1359 case ESC_NATIVE: return "\\e";
1360 case '\f': return "\\f";
1361 case '\n': return "\\n";
1362 case '\r': return "\\r";
1363 case '\t': return "\\t";
1369 /* Mark that we cannot extend a found fixed substring at this point.
1370 Update the longest found anchored substring or the longest found
1371 floating substrings if needed. */
1374 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1375 SSize_t *minlenp, int is_inf)
1377 const STRLEN l = CHR_SVLEN(data->last_found);
1378 SV * const longest_sv = data->substrs[data->cur_is_floating].str;
1379 const STRLEN old_l = CHR_SVLEN(longest_sv);
1380 GET_RE_DEBUG_FLAGS_DECL;
1382 PERL_ARGS_ASSERT_SCAN_COMMIT;
1384 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1385 const U8 i = data->cur_is_floating;
1386 SvSetMagicSV(longest_sv, data->last_found);
1387 data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
1390 data->substrs[0].max_offset = data->substrs[0].min_offset;
1392 data->substrs[1].max_offset = (l
1393 ? data->last_start_max
1394 : (data->pos_delta > SSize_t_MAX - data->pos_min
1396 : data->pos_min + data->pos_delta));
1398 || (STRLEN)data->substrs[1].max_offset > (STRLEN)SSize_t_MAX)
1399 data->substrs[1].max_offset = SSize_t_MAX;
1402 if (data->flags & SF_BEFORE_EOL)
1403 data->substrs[i].flags |= (data->flags & SF_BEFORE_EOL);
1405 data->substrs[i].flags &= ~SF_BEFORE_EOL;
1406 data->substrs[i].minlenp = minlenp;
1407 data->substrs[i].lookbehind = 0;
1410 SvCUR_set(data->last_found, 0);
1412 SV * const sv = data->last_found;
1413 if (SvUTF8(sv) && SvMAGICAL(sv)) {
1414 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1419 data->last_end = -1;
1420 data->flags &= ~SF_BEFORE_EOL;
1421 DEBUG_STUDYDATA("commit", data, 0, is_inf);
1424 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1425 * list that describes which code points it matches */
1428 S_ssc_anything(pTHX_ regnode_ssc *ssc)
1430 /* Set the SSC 'ssc' to match an empty string or any code point */
1432 PERL_ARGS_ASSERT_SSC_ANYTHING;
1434 assert(is_ANYOF_SYNTHETIC(ssc));
1436 /* mortalize so won't leak */
1437 ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
1438 ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING; /* Plus matches empty */
1442 S_ssc_is_anything(const regnode_ssc *ssc)
1444 /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1445 * point; FALSE otherwise. Thus, this is used to see if using 'ssc' buys
1446 * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1447 * in any way, so there's no point in using it */
1452 PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1454 assert(is_ANYOF_SYNTHETIC(ssc));
1456 if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1460 /* See if the list consists solely of the range 0 - Infinity */
1461 invlist_iterinit(ssc->invlist);
1462 ret = invlist_iternext(ssc->invlist, &start, &end)
1466 invlist_iterfinish(ssc->invlist);
1472 /* If e.g., both \w and \W are set, matches everything */
1473 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1475 for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1476 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1486 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1488 /* Initializes the SSC 'ssc'. This includes setting it to match an empty
1489 * string, any code point, or any posix class under locale */
1491 PERL_ARGS_ASSERT_SSC_INIT;
1493 Zero(ssc, 1, regnode_ssc);
1494 set_ANYOF_SYNTHETIC(ssc);
1495 ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1498 /* If any portion of the regex is to operate under locale rules that aren't
1499 * fully known at compile time, initialization includes it. The reason
1500 * this isn't done for all regexes is that the optimizer was written under
1501 * the assumption that locale was all-or-nothing. Given the complexity and
1502 * lack of documentation in the optimizer, and that there are inadequate
1503 * test cases for locale, many parts of it may not work properly, it is
1504 * safest to avoid locale unless necessary. */
1505 if (RExC_contains_locale) {
1506 ANYOF_POSIXL_SETALL(ssc);
1509 ANYOF_POSIXL_ZERO(ssc);
1514 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1515 const regnode_ssc *ssc)
1517 /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1518 * to the list of code points matched, and locale posix classes; hence does
1519 * not check its flags) */
1524 PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1526 assert(is_ANYOF_SYNTHETIC(ssc));
1528 invlist_iterinit(ssc->invlist);
1529 ret = invlist_iternext(ssc->invlist, &start, &end)
1533 invlist_iterfinish(ssc->invlist);
1539 if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1547 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1548 const regnode_charclass* const node)
1550 /* Returns a mortal inversion list defining which code points are matched
1551 * by 'node', which is of type ANYOF. Handles complementing the result if
1552 * appropriate. If some code points aren't knowable at this time, the
1553 * returned list must, and will, contain every code point that is a
1557 SV* only_utf8_locale_invlist = NULL;
1559 const U32 n = ARG(node);
1560 bool new_node_has_latin1 = FALSE;
1562 PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1564 /* Look at the data structure created by S_set_ANYOF_arg() */
1565 if (n != ANYOF_ONLY_HAS_BITMAP) {
1566 SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1567 AV * const av = MUTABLE_AV(SvRV(rv));
1568 SV **const ary = AvARRAY(av);
1569 assert(RExC_rxi->data->what[n] == 's');
1571 if (ary[1] && ary[1] != &PL_sv_undef) { /* Has compile-time swash */
1572 invlist = sv_2mortal(invlist_clone(_get_swash_invlist(ary[1]), NULL));
1574 else if (ary[0] && ary[0] != &PL_sv_undef) {
1576 /* Here, no compile-time swash, and there are things that won't be
1577 * known until runtime -- we have to assume it could be anything */
1578 invlist = sv_2mortal(_new_invlist(1));
1579 return _add_range_to_invlist(invlist, 0, UV_MAX);
1581 else if (ary[3] && ary[3] != &PL_sv_undef) {
1583 /* Here no compile-time swash, and no run-time only data. Use the
1584 * node's inversion list */
1585 invlist = sv_2mortal(invlist_clone(ary[3], NULL));
1588 /* Get the code points valid only under UTF-8 locales */
1589 if ((ANYOF_FLAGS(node) & ANYOFL_FOLD)
1590 && ary[2] && ary[2] != &PL_sv_undef)
1592 only_utf8_locale_invlist = ary[2];
1597 invlist = sv_2mortal(_new_invlist(0));
1600 /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1601 * code points, and an inversion list for the others, but if there are code
1602 * points that should match only conditionally on the target string being
1603 * UTF-8, those are placed in the inversion list, and not the bitmap.
1604 * Since there are circumstances under which they could match, they are
1605 * included in the SSC. But if the ANYOF node is to be inverted, we have
1606 * to exclude them here, so that when we invert below, the end result
1607 * actually does include them. (Think about "\xe0" =~ /[^\xc0]/di;). We
1608 * have to do this here before we add the unconditionally matched code
1610 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1611 _invlist_intersection_complement_2nd(invlist,
1616 /* Add in the points from the bit map */
1617 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1618 if (ANYOF_BITMAP_TEST(node, i)) {
1619 unsigned int start = i++;
1621 for (; i < NUM_ANYOF_CODE_POINTS && ANYOF_BITMAP_TEST(node, i); ++i) {
1624 invlist = _add_range_to_invlist(invlist, start, i-1);
1625 new_node_has_latin1 = TRUE;
1629 /* If this can match all upper Latin1 code points, have to add them
1630 * as well. But don't add them if inverting, as when that gets done below,
1631 * it would exclude all these characters, including the ones it shouldn't
1632 * that were added just above */
1633 if (! (ANYOF_FLAGS(node) & ANYOF_INVERT) && OP(node) == ANYOFD
1634 && (ANYOF_FLAGS(node) & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1636 _invlist_union(invlist, PL_UpperLatin1, &invlist);
1639 /* Similarly for these */
1640 if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1641 _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1644 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1645 _invlist_invert(invlist);
1647 else if (new_node_has_latin1 && ANYOF_FLAGS(node) & ANYOFL_FOLD) {
1649 /* Under /li, any 0-255 could fold to any other 0-255, depending on the
1650 * locale. We can skip this if there are no 0-255 at all. */
1651 _invlist_union(invlist, PL_Latin1, &invlist);
1654 /* Similarly add the UTF-8 locale possible matches. These have to be
1655 * deferred until after the non-UTF-8 locale ones are taken care of just
1656 * above, or it leads to wrong results under ANYOF_INVERT */
1657 if (only_utf8_locale_invlist) {
1658 _invlist_union_maybe_complement_2nd(invlist,
1659 only_utf8_locale_invlist,
1660 ANYOF_FLAGS(node) & ANYOF_INVERT,
1667 /* These two functions currently do the exact same thing */
1668 #define ssc_init_zero ssc_init
1670 #define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp))
1671 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1673 /* 'AND' a given class with another one. Can create false positives. 'ssc'
1674 * should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1675 * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1678 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1679 const regnode_charclass *and_with)
1681 /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1682 * another SSC or a regular ANYOF class. Can create false positives. */
1687 PERL_ARGS_ASSERT_SSC_AND;
1689 assert(is_ANYOF_SYNTHETIC(ssc));
1691 /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1692 * the code point inversion list and just the relevant flags */
1693 if (is_ANYOF_SYNTHETIC(and_with)) {
1694 anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1695 anded_flags = ANYOF_FLAGS(and_with);
1697 /* XXX This is a kludge around what appears to be deficiencies in the
1698 * optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag,
1699 * there are paths through the optimizer where it doesn't get weeded
1700 * out when it should. And if we don't make some extra provision for
1701 * it like the code just below, it doesn't get added when it should.
1702 * This solution is to add it only when AND'ing, which is here, and
1703 * only when what is being AND'ed is the pristine, original node
1704 * matching anything. Thus it is like adding it to ssc_anything() but
1705 * only when the result is to be AND'ed. Probably the same solution
1706 * could be adopted for the same problem we have with /l matching,
1707 * which is solved differently in S_ssc_init(), and that would lead to
1708 * fewer false positives than that solution has. But if this solution
1709 * creates bugs, the consequences are only that a warning isn't raised
1710 * that should be; while the consequences for having /l bugs is
1711 * incorrect matches */
1712 if (ssc_is_anything((regnode_ssc *)and_with)) {
1713 anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1717 anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1718 if (OP(and_with) == ANYOFD) {
1719 anded_flags = ANYOF_FLAGS(and_with) & ANYOF_COMMON_FLAGS;
1722 anded_flags = ANYOF_FLAGS(and_with)
1723 &( ANYOF_COMMON_FLAGS
1724 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1725 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1726 if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(and_with))) {
1728 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1733 ANYOF_FLAGS(ssc) &= anded_flags;
1735 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1736 * C2 is the list of code points in 'and-with'; P2, its posix classes.
1737 * 'and_with' may be inverted. When not inverted, we have the situation of
1739 * (C1 | P1) & (C2 | P2)
1740 * = (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1741 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1742 * <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2))
1743 * <= ((C1 & C2) | P1 | P2)
1744 * Alternatively, the last few steps could be:
1745 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1746 * <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2))
1747 * <= (C1 | C2 | (P1 & P2))
1748 * We favor the second approach if either P1 or P2 is non-empty. This is
1749 * because these components are a barrier to doing optimizations, as what
1750 * they match cannot be known until the moment of matching as they are
1751 * dependent on the current locale, 'AND"ing them likely will reduce or
1753 * But we can do better if we know that C1,P1 are in their initial state (a
1754 * frequent occurrence), each matching everything:
1755 * (<everything>) & (C2 | P2) = C2 | P2
1756 * Similarly, if C2,P2 are in their initial state (again a frequent
1757 * occurrence), the result is a no-op
1758 * (C1 | P1) & (<everything>) = C1 | P1
1761 * (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2)
1762 * = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1763 * <= (C1 & ~C2) | (P1 & ~P2)
1766 if ((ANYOF_FLAGS(and_with) & ANYOF_INVERT)
1767 && ! is_ANYOF_SYNTHETIC(and_with))
1771 ssc_intersection(ssc,
1773 FALSE /* Has already been inverted */
1776 /* If either P1 or P2 is empty, the intersection will be also; can skip
1778 if (! (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL)) {
1779 ANYOF_POSIXL_ZERO(ssc);
1781 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1783 /* Note that the Posix class component P from 'and_with' actually
1785 * P = Pa | Pb | ... | Pn
1786 * where each component is one posix class, such as in [\w\s].
1788 * ~P = ~(Pa | Pb | ... | Pn)
1789 * = ~Pa & ~Pb & ... & ~Pn
1790 * <= ~Pa | ~Pb | ... | ~Pn
1791 * The last is something we can easily calculate, but unfortunately
1792 * is likely to have many false positives. We could do better
1793 * in some (but certainly not all) instances if two classes in
1794 * P have known relationships. For example
1795 * :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1797 * :lower: & :print: = :lower:
1798 * And similarly for classes that must be disjoint. For example,
1799 * since \s and \w can have no elements in common based on rules in
1800 * the POSIX standard,
1801 * \w & ^\S = nothing
1802 * Unfortunately, some vendor locales do not meet the Posix
1803 * standard, in particular almost everything by Microsoft.
1804 * The loop below just changes e.g., \w into \W and vice versa */
1806 regnode_charclass_posixl temp;
1807 int add = 1; /* To calculate the index of the complement */
1809 Zero(&temp, 1, regnode_charclass_posixl);
1810 ANYOF_POSIXL_ZERO(&temp);
1811 for (i = 0; i < ANYOF_MAX; i++) {
1813 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1814 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1816 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1817 ANYOF_POSIXL_SET(&temp, i + add);
1819 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1821 ANYOF_POSIXL_AND(&temp, ssc);
1823 } /* else ssc already has no posixes */
1824 } /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC
1825 in its initial state */
1826 else if (! is_ANYOF_SYNTHETIC(and_with)
1827 || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1829 /* But if 'ssc' is in its initial state, the result is just 'and_with';
1830 * copy it over 'ssc' */
1831 if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1832 if (is_ANYOF_SYNTHETIC(and_with)) {
1833 StructCopy(and_with, ssc, regnode_ssc);
1836 ssc->invlist = anded_cp_list;
1837 ANYOF_POSIXL_ZERO(ssc);
1838 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1839 ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1843 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1844 || (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL))
1846 /* One or the other of P1, P2 is non-empty. */
1847 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1848 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1850 ssc_union(ssc, anded_cp_list, FALSE);
1852 else { /* P1 = P2 = empty */
1853 ssc_intersection(ssc, anded_cp_list, FALSE);
1859 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1860 const regnode_charclass *or_with)
1862 /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1863 * another SSC or a regular ANYOF class. Can create false positives if
1864 * 'or_with' is to be inverted. */
1869 PERL_ARGS_ASSERT_SSC_OR;
1871 assert(is_ANYOF_SYNTHETIC(ssc));
1873 /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1874 * the code point inversion list and just the relevant flags */
1875 if (is_ANYOF_SYNTHETIC(or_with)) {
1876 ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1877 ored_flags = ANYOF_FLAGS(or_with);
1880 ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
1881 ored_flags = ANYOF_FLAGS(or_with) & ANYOF_COMMON_FLAGS;
1882 if (OP(or_with) != ANYOFD) {
1884 |= ANYOF_FLAGS(or_with)
1885 & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1886 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1887 if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(or_with))) {
1889 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1894 ANYOF_FLAGS(ssc) |= ored_flags;
1896 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1897 * C2 is the list of code points in 'or-with'; P2, its posix classes.
1898 * 'or_with' may be inverted. When not inverted, we have the simple
1899 * situation of computing:
1900 * (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2)
1901 * If P1|P2 yields a situation with both a class and its complement are
1902 * set, like having both \w and \W, this matches all code points, and we
1903 * can delete these from the P component of the ssc going forward. XXX We
1904 * might be able to delete all the P components, but I (khw) am not certain
1905 * about this, and it is better to be safe.
1908 * (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2)
1909 * <= (C1 | P1) | ~C2
1910 * <= (C1 | ~C2) | P1
1911 * (which results in actually simpler code than the non-inverted case)
1914 if ((ANYOF_FLAGS(or_with) & ANYOF_INVERT)
1915 && ! is_ANYOF_SYNTHETIC(or_with))
1917 /* We ignore P2, leaving P1 going forward */
1918 } /* else Not inverted */
1919 else if (ANYOF_FLAGS(or_with) & ANYOF_MATCHES_POSIXL) {
1920 ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
1921 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1923 for (i = 0; i < ANYOF_MAX; i += 2) {
1924 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1926 ssc_match_all_cp(ssc);
1927 ANYOF_POSIXL_CLEAR(ssc, i);
1928 ANYOF_POSIXL_CLEAR(ssc, i+1);
1936 FALSE /* Already has been inverted */
1940 PERL_STATIC_INLINE void
1941 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
1943 PERL_ARGS_ASSERT_SSC_UNION;
1945 assert(is_ANYOF_SYNTHETIC(ssc));
1947 _invlist_union_maybe_complement_2nd(ssc->invlist,
1953 PERL_STATIC_INLINE void
1954 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
1956 const bool invert2nd)
1958 PERL_ARGS_ASSERT_SSC_INTERSECTION;
1960 assert(is_ANYOF_SYNTHETIC(ssc));
1962 _invlist_intersection_maybe_complement_2nd(ssc->invlist,
1968 PERL_STATIC_INLINE void
1969 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
1971 PERL_ARGS_ASSERT_SSC_ADD_RANGE;
1973 assert(is_ANYOF_SYNTHETIC(ssc));
1975 ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
1978 PERL_STATIC_INLINE void
1979 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
1981 /* AND just the single code point 'cp' into the SSC 'ssc' */
1983 SV* cp_list = _new_invlist(2);
1985 PERL_ARGS_ASSERT_SSC_CP_AND;
1987 assert(is_ANYOF_SYNTHETIC(ssc));
1989 cp_list = add_cp_to_invlist(cp_list, cp);
1990 ssc_intersection(ssc, cp_list,
1991 FALSE /* Not inverted */
1993 SvREFCNT_dec_NN(cp_list);
1996 PERL_STATIC_INLINE void
1997 S_ssc_clear_locale(regnode_ssc *ssc)
1999 /* Set the SSC 'ssc' to not match any locale things */
2000 PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
2002 assert(is_ANYOF_SYNTHETIC(ssc));
2004 ANYOF_POSIXL_ZERO(ssc);
2005 ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
2008 #define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
2011 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
2013 /* The synthetic start class is used to hopefully quickly winnow down
2014 * places where a pattern could start a match in the target string. If it
2015 * doesn't really narrow things down that much, there isn't much point to
2016 * having the overhead of using it. This function uses some very crude
2017 * heuristics to decide if to use the ssc or not.
2019 * It returns TRUE if 'ssc' rules out more than half what it considers to
2020 * be the "likely" possible matches, but of course it doesn't know what the
2021 * actual things being matched are going to be; these are only guesses
2023 * For /l matches, it assumes that the only likely matches are going to be
2024 * in the 0-255 range, uniformly distributed, so half of that is 127
2025 * For /a and /d matches, it assumes that the likely matches will be just
2026 * the ASCII range, so half of that is 63
2027 * For /u and there isn't anything matching above the Latin1 range, it
2028 * assumes that that is the only range likely to be matched, and uses
2029 * half that as the cut-off: 127. If anything matches above Latin1,
2030 * it assumes that all of Unicode could match (uniformly), except for
2031 * non-Unicode code points and things in the General Category "Other"
2032 * (unassigned, private use, surrogates, controls and formats). This
2033 * is a much large number. */
2035 U32 count = 0; /* Running total of number of code points matched by
2037 UV start, end; /* Start and end points of current range in inversion
2039 const U32 max_code_points = (LOC)
2041 : (( ! UNI_SEMANTICS
2042 || invlist_highest(ssc->invlist) < 256)
2045 const U32 max_match = max_code_points / 2;
2047 PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
2049 invlist_iterinit(ssc->invlist);
2050 while (invlist_iternext(ssc->invlist, &start, &end)) {
2051 if (start >= max_code_points) {
2054 end = MIN(end, max_code_points - 1);
2055 count += end - start + 1;
2056 if (count >= max_match) {
2057 invlist_iterfinish(ssc->invlist);
2067 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
2069 /* The inversion list in the SSC is marked mortal; now we need a more
2070 * permanent copy, which is stored the same way that is done in a regular
2071 * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
2074 SV* invlist = invlist_clone(ssc->invlist, NULL);
2076 PERL_ARGS_ASSERT_SSC_FINALIZE;
2078 assert(is_ANYOF_SYNTHETIC(ssc));
2080 /* The code in this file assumes that all but these flags aren't relevant
2081 * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
2082 * by the time we reach here */
2083 assert(! (ANYOF_FLAGS(ssc)
2084 & ~( ANYOF_COMMON_FLAGS
2085 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2086 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
2088 populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
2090 set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist,
2091 NULL, NULL, NULL, FALSE);
2093 /* Make sure is clone-safe */
2094 ssc->invlist = NULL;
2096 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2097 ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
2098 OP(ssc) = ANYOFPOSIXL;
2100 else if (RExC_contains_locale) {
2104 assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
2107 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
2108 #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
2109 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
2110 #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \
2111 ? (TRIE_LIST_CUR( idx ) - 1) \
2117 dump_trie(trie,widecharmap,revcharmap)
2118 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
2119 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
2121 These routines dump out a trie in a somewhat readable format.
2122 The _interim_ variants are used for debugging the interim
2123 tables that are used to generate the final compressed
2124 representation which is what dump_trie expects.
2126 Part of the reason for their existence is to provide a form
2127 of documentation as to how the different representations function.
2132 Dumps the final compressed table form of the trie to Perl_debug_log.
2133 Used for debugging make_trie().
2137 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
2138 AV *revcharmap, U32 depth)
2141 SV *sv=sv_newmortal();
2142 int colwidth= widecharmap ? 6 : 4;
2144 GET_RE_DEBUG_FLAGS_DECL;
2146 PERL_ARGS_ASSERT_DUMP_TRIE;
2148 Perl_re_indentf( aTHX_ "Char : %-6s%-6s%-4s ",
2149 depth+1, "Match","Base","Ofs" );
2151 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2152 SV ** const tmp = av_fetch( revcharmap, state, 0);
2154 Perl_re_printf( aTHX_ "%*s",
2156 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2157 PL_colors[0], PL_colors[1],
2158 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2159 PERL_PV_ESCAPE_FIRSTCHAR
2164 Perl_re_printf( aTHX_ "\n");
2165 Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
2167 for( state = 0 ; state < trie->uniquecharcount ; state++ )
2168 Perl_re_printf( aTHX_ "%.*s", colwidth, "--------");
2169 Perl_re_printf( aTHX_ "\n");
2171 for( state = 1 ; state < trie->statecount ; state++ ) {
2172 const U32 base = trie->states[ state ].trans.base;
2174 Perl_re_indentf( aTHX_ "#%4" UVXf "|", depth+1, (UV)state);
2176 if ( trie->states[ state ].wordnum ) {
2177 Perl_re_printf( aTHX_ " W%4X", trie->states[ state ].wordnum );
2179 Perl_re_printf( aTHX_ "%6s", "" );
2182 Perl_re_printf( aTHX_ " @%4" UVXf " ", (UV)base );
2187 while( ( base + ofs < trie->uniquecharcount ) ||
2188 ( base + ofs - trie->uniquecharcount < trie->lasttrans
2189 && trie->trans[ base + ofs - trie->uniquecharcount ].check
2193 Perl_re_printf( aTHX_ "+%2" UVXf "[ ", (UV)ofs);
2195 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2196 if ( ( base + ofs >= trie->uniquecharcount )
2197 && ( base + ofs - trie->uniquecharcount
2199 && trie->trans[ base + ofs
2200 - trie->uniquecharcount ].check == state )
2202 Perl_re_printf( aTHX_ "%*" UVXf, colwidth,
2203 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
2206 Perl_re_printf( aTHX_ "%*s", colwidth," ." );
2210 Perl_re_printf( aTHX_ "]");
2213 Perl_re_printf( aTHX_ "\n" );
2215 Perl_re_indentf( aTHX_ "word_info N:(prev,len)=",
2217 for (word=1; word <= trie->wordcount; word++) {
2218 Perl_re_printf( aTHX_ " %d:(%d,%d)",
2219 (int)word, (int)(trie->wordinfo[word].prev),
2220 (int)(trie->wordinfo[word].len));
2222 Perl_re_printf( aTHX_ "\n" );
2225 Dumps a fully constructed but uncompressed trie in list form.
2226 List tries normally only are used for construction when the number of
2227 possible chars (trie->uniquecharcount) is very high.
2228 Used for debugging make_trie().
2231 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2232 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2236 SV *sv=sv_newmortal();
2237 int colwidth= widecharmap ? 6 : 4;
2238 GET_RE_DEBUG_FLAGS_DECL;
2240 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2242 /* print out the table precompression. */
2243 Perl_re_indentf( aTHX_ "State :Word | Transition Data\n",
2245 Perl_re_indentf( aTHX_ "%s",
2246 depth+1, "------:-----+-----------------\n" );
2248 for( state=1 ; state < next_alloc ; state ++ ) {
2251 Perl_re_indentf( aTHX_ " %4" UVXf " :",
2252 depth+1, (UV)state );
2253 if ( ! trie->states[ state ].wordnum ) {
2254 Perl_re_printf( aTHX_ "%5s| ","");
2256 Perl_re_printf( aTHX_ "W%4x| ",
2257 trie->states[ state ].wordnum
2260 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2261 SV ** const tmp = av_fetch( revcharmap,
2262 TRIE_LIST_ITEM(state, charid).forid, 0);
2264 Perl_re_printf( aTHX_ "%*s:%3X=%4" UVXf " | ",
2266 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2268 PL_colors[0], PL_colors[1],
2269 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2270 | PERL_PV_ESCAPE_FIRSTCHAR
2272 TRIE_LIST_ITEM(state, charid).forid,
2273 (UV)TRIE_LIST_ITEM(state, charid).newstate
2276 Perl_re_printf( aTHX_ "\n%*s| ",
2277 (int)((depth * 2) + 14), "");
2280 Perl_re_printf( aTHX_ "\n");
2285 Dumps a fully constructed but uncompressed trie in table form.
2286 This is the normal DFA style state transition table, with a few
2287 twists to facilitate compression later.
2288 Used for debugging make_trie().
2291 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2292 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2297 SV *sv=sv_newmortal();
2298 int colwidth= widecharmap ? 6 : 4;
2299 GET_RE_DEBUG_FLAGS_DECL;
2301 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2304 print out the table precompression so that we can do a visual check
2305 that they are identical.
2308 Perl_re_indentf( aTHX_ "Char : ", depth+1 );
2310 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2311 SV ** const tmp = av_fetch( revcharmap, charid, 0);
2313 Perl_re_printf( aTHX_ "%*s",
2315 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2316 PL_colors[0], PL_colors[1],
2317 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2318 PERL_PV_ESCAPE_FIRSTCHAR
2324 Perl_re_printf( aTHX_ "\n");
2325 Perl_re_indentf( aTHX_ "State+-", depth+1 );
2327 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2328 Perl_re_printf( aTHX_ "%.*s", colwidth,"--------");
2331 Perl_re_printf( aTHX_ "\n" );
2333 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2335 Perl_re_indentf( aTHX_ "%4" UVXf " : ",
2337 (UV)TRIE_NODENUM( state ) );
2339 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2340 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2342 Perl_re_printf( aTHX_ "%*" UVXf, colwidth, v );
2344 Perl_re_printf( aTHX_ "%*s", colwidth, "." );
2346 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2347 Perl_re_printf( aTHX_ " (%4" UVXf ")\n",
2348 (UV)trie->trans[ state ].check );
2350 Perl_re_printf( aTHX_ " (%4" UVXf ") W%4X\n",
2351 (UV)trie->trans[ state ].check,
2352 trie->states[ TRIE_NODENUM( state ) ].wordnum );
2360 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2361 startbranch: the first branch in the whole branch sequence
2362 first : start branch of sequence of branch-exact nodes.
2363 May be the same as startbranch
2364 last : Thing following the last branch.
2365 May be the same as tail.
2366 tail : item following the branch sequence
2367 count : words in the sequence
2368 flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2369 depth : indent depth
2371 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2373 A trie is an N'ary tree where the branches are determined by digital
2374 decomposition of the key. IE, at the root node you look up the 1st character and
2375 follow that branch repeat until you find the end of the branches. Nodes can be
2376 marked as "accepting" meaning they represent a complete word. Eg:
2380 would convert into the following structure. Numbers represent states, letters
2381 following numbers represent valid transitions on the letter from that state, if
2382 the number is in square brackets it represents an accepting state, otherwise it
2383 will be in parenthesis.
2385 +-h->+-e->[3]-+-r->(8)-+-s->[9]
2389 (1) +-i->(6)-+-s->[7]
2391 +-s->(3)-+-h->(4)-+-e->[5]
2393 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2395 This shows that when matching against the string 'hers' we will begin at state 1
2396 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2397 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2398 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2399 single traverse. We store a mapping from accepting to state to which word was
2400 matched, and then when we have multiple possibilities we try to complete the
2401 rest of the regex in the order in which they occurred in the alternation.
2403 The only prior NFA like behaviour that would be changed by the TRIE support is
2404 the silent ignoring of duplicate alternations which are of the form:
2406 / (DUPE|DUPE) X? (?{ ... }) Y /x
2408 Thus EVAL blocks following a trie may be called a different number of times with
2409 and without the optimisation. With the optimisations dupes will be silently
2410 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2411 the following demonstrates:
2413 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2415 which prints out 'word' three times, but
2417 'words'=~/(word|word|word)(?{ print $1 })S/
2419 which doesnt print it out at all. This is due to other optimisations kicking in.
2421 Example of what happens on a structural level:
2423 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2425 1: CURLYM[1] {1,32767}(18)
2436 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2437 and should turn into:
2439 1: CURLYM[1] {1,32767}(18)
2441 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2449 Cases where tail != last would be like /(?foo|bar)baz/:
2459 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2460 and would end up looking like:
2463 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2470 d = uvchr_to_utf8_flags(d, uv, 0);
2472 is the recommended Unicode-aware way of saying
2477 #define TRIE_STORE_REVCHAR(val) \
2480 SV *zlopp = newSV(UTF8_MAXBYTES); \
2481 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
2482 unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
2483 SvCUR_set(zlopp, kapow - flrbbbbb); \
2486 av_push(revcharmap, zlopp); \
2488 char ooooff = (char)val; \
2489 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
2493 /* This gets the next character from the input, folding it if not already
2495 #define TRIE_READ_CHAR STMT_START { \
2498 /* if it is UTF then it is either already folded, or does not need \
2500 uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \
2502 else if (folder == PL_fold_latin1) { \
2503 /* This folder implies Unicode rules, which in the range expressible \
2504 * by not UTF is the lower case, with the two exceptions, one of \
2505 * which should have been taken care of before calling this */ \
2506 assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \
2507 uvc = toLOWER_L1(*uc); \
2508 if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \
2511 /* raw data, will be folded later if needed */ \
2519 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
2520 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
2521 U32 ging = TRIE_LIST_LEN( state ) * 2; \
2522 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2523 TRIE_LIST_LEN( state ) = ging; \
2525 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
2526 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
2527 TRIE_LIST_CUR( state )++; \
2530 #define TRIE_LIST_NEW(state) STMT_START { \
2531 Newx( trie->states[ state ].trans.list, \
2532 4, reg_trie_trans_le ); \
2533 TRIE_LIST_CUR( state ) = 1; \
2534 TRIE_LIST_LEN( state ) = 4; \
2537 #define TRIE_HANDLE_WORD(state) STMT_START { \
2538 U16 dupe= trie->states[ state ].wordnum; \
2539 regnode * const noper_next = regnext( noper ); \
2542 /* store the word for dumping */ \
2544 if (OP(noper) != NOTHING) \
2545 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
2547 tmp = newSVpvn_utf8( "", 0, UTF ); \
2548 av_push( trie_words, tmp ); \
2552 trie->wordinfo[curword].prev = 0; \
2553 trie->wordinfo[curword].len = wordlen; \
2554 trie->wordinfo[curword].accept = state; \
2556 if ( noper_next < tail ) { \
2558 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2560 trie->jump[curword] = (U16)(noper_next - convert); \
2562 jumper = noper_next; \
2564 nextbranch= regnext(cur); \
2568 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
2569 /* chain, so that when the bits of chain are later */\
2570 /* linked together, the dups appear in the chain */\
2571 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2572 trie->wordinfo[dupe].prev = curword; \
2574 /* we haven't inserted this word yet. */ \
2575 trie->states[ state ].wordnum = curword; \
2580 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
2581 ( ( base + charid >= ucharcount \
2582 && base + charid < ubound \
2583 && state == trie->trans[ base - ucharcount + charid ].check \
2584 && trie->trans[ base - ucharcount + charid ].next ) \
2585 ? trie->trans[ base - ucharcount + charid ].next \
2586 : ( state==1 ? special : 0 ) \
2589 #define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder) \
2591 TRIE_BITMAP_SET(trie, uvc); \
2592 /* store the folded codepoint */ \
2594 TRIE_BITMAP_SET(trie, folder[(U8) uvc ]); \
2597 /* store first byte of utf8 representation of */ \
2598 /* variant codepoints */ \
2599 if (! UVCHR_IS_INVARIANT(uvc)) { \
2600 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc)); \
2605 #define MADE_JUMP_TRIE 2
2606 #define MADE_EXACT_TRIE 4
2609 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2610 regnode *first, regnode *last, regnode *tail,
2611 U32 word_count, U32 flags, U32 depth)
2613 /* first pass, loop through and scan words */
2614 reg_trie_data *trie;
2615 HV *widecharmap = NULL;
2616 AV *revcharmap = newAV();
2622 regnode *jumper = NULL;
2623 regnode *nextbranch = NULL;
2624 regnode *convert = NULL;
2625 U32 *prev_states; /* temp array mapping each state to previous one */
2626 /* we just use folder as a flag in utf8 */
2627 const U8 * folder = NULL;
2629 /* in the below add_data call we are storing either 'tu' or 'tuaa'
2630 * which stands for one trie structure, one hash, optionally followed
2633 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
2634 AV *trie_words = NULL;
2635 /* along with revcharmap, this only used during construction but both are
2636 * useful during debugging so we store them in the struct when debugging.
2639 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2640 STRLEN trie_charcount=0;
2642 SV *re_trie_maxbuff;
2643 GET_RE_DEBUG_FLAGS_DECL;
2645 PERL_ARGS_ASSERT_MAKE_TRIE;
2647 PERL_UNUSED_ARG(depth);
2651 case EXACT: case EXACTL: break;
2655 case EXACTFLU8: folder = PL_fold_latin1; break;
2656 case EXACTF: folder = PL_fold; break;
2657 default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2660 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2662 trie->startstate = 1;
2663 trie->wordcount = word_count;
2664 RExC_rxi->data->data[ data_slot ] = (void*)trie;
2665 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2666 if (flags == EXACT || flags == EXACTL)
2667 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2668 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2669 trie->wordcount+1, sizeof(reg_trie_wordinfo));
2672 trie_words = newAV();
2675 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2676 assert(re_trie_maxbuff);
2677 if (!SvIOK(re_trie_maxbuff)) {
2678 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2680 DEBUG_TRIE_COMPILE_r({
2681 Perl_re_indentf( aTHX_
2682 "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2684 REG_NODE_NUM(startbranch), REG_NODE_NUM(first),
2685 REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2688 /* Find the node we are going to overwrite */
2689 if ( first == startbranch && OP( last ) != BRANCH ) {
2690 /* whole branch chain */
2693 /* branch sub-chain */
2694 convert = NEXTOPER( first );
2697 /* -- First loop and Setup --
2699 We first traverse the branches and scan each word to determine if it
2700 contains widechars, and how many unique chars there are, this is
2701 important as we have to build a table with at least as many columns as we
2704 We use an array of integers to represent the character codes 0..255
2705 (trie->charmap) and we use a an HV* to store Unicode characters. We use
2706 the native representation of the character value as the key and IV's for
2709 *TODO* If we keep track of how many times each character is used we can
2710 remap the columns so that the table compression later on is more
2711 efficient in terms of memory by ensuring the most common value is in the
2712 middle and the least common are on the outside. IMO this would be better
2713 than a most to least common mapping as theres a decent chance the most
2714 common letter will share a node with the least common, meaning the node
2715 will not be compressible. With a middle is most common approach the worst
2716 case is when we have the least common nodes twice.
2720 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2721 regnode *noper = NEXTOPER( cur );
2725 U32 wordlen = 0; /* required init */
2726 STRLEN minchars = 0;
2727 STRLEN maxchars = 0;
2728 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2731 if (OP(noper) == NOTHING) {
2732 /* skip past a NOTHING at the start of an alternation
2733 * eg, /(?:)a|(?:b)/ should be the same as /a|b/
2735 regnode *noper_next= regnext(noper);
2736 if (noper_next < tail)
2740 if ( noper < tail &&
2742 OP(noper) == flags ||
2745 OP(noper) == EXACTFU_SS
2749 uc= (U8*)STRING(noper);
2750 e= uc + STR_LEN(noper);
2757 if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2758 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2759 regardless of encoding */
2760 if (OP( noper ) == EXACTFU_SS) {
2761 /* false positives are ok, so just set this */
2762 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2766 for ( ; uc < e ; uc += len ) { /* Look at each char in the current
2768 TRIE_CHARCOUNT(trie)++;
2771 /* TRIE_READ_CHAR returns the current character, or its fold if /i
2772 * is in effect. Under /i, this character can match itself, or
2773 * anything that folds to it. If not under /i, it can match just
2774 * itself. Most folds are 1-1, for example k, K, and KELVIN SIGN
2775 * all fold to k, and all are single characters. But some folds
2776 * expand to more than one character, so for example LATIN SMALL
2777 * LIGATURE FFI folds to the three character sequence 'ffi'. If
2778 * the string beginning at 'uc' is 'ffi', it could be matched by
2779 * three characters, or just by the one ligature character. (It
2780 * could also be matched by two characters: LATIN SMALL LIGATURE FF
2781 * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2782 * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2783 * match.) The trie needs to know the minimum and maximum number
2784 * of characters that could match so that it can use size alone to
2785 * quickly reject many match attempts. The max is simple: it is
2786 * the number of folded characters in this branch (since a fold is
2787 * never shorter than what folds to it. */
2791 /* And the min is equal to the max if not under /i (indicated by
2792 * 'folder' being NULL), or there are no multi-character folds. If
2793 * there is a multi-character fold, the min is incremented just
2794 * once, for the character that folds to the sequence. Each
2795 * character in the sequence needs to be added to the list below of
2796 * characters in the trie, but we count only the first towards the
2797 * min number of characters needed. This is done through the
2798 * variable 'foldlen', which is returned by the macros that look
2799 * for these sequences as the number of bytes the sequence
2800 * occupies. Each time through the loop, we decrement 'foldlen' by
2801 * how many bytes the current char occupies. Only when it reaches
2802 * 0 do we increment 'minchars' or look for another multi-character
2804 if (folder == NULL) {
2807 else if (foldlen > 0) {
2808 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2813 /* See if *uc is the beginning of a multi-character fold. If
2814 * so, we decrement the length remaining to look at, to account
2815 * for the current character this iteration. (We can use 'uc'
2816 * instead of the fold returned by TRIE_READ_CHAR because for
2817 * non-UTF, the latin1_safe macro is smart enough to account
2818 * for all the unfolded characters, and because for UTF, the
2819 * string will already have been folded earlier in the
2820 * compilation process */
2822 if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2823 foldlen -= UTF8SKIP(uc);
2826 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2831 /* The current character (and any potential folds) should be added
2832 * to the possible matching characters for this position in this
2836 U8 folded= folder[ (U8) uvc ];
2837 if ( !trie->charmap[ folded ] ) {
2838 trie->charmap[ folded ]=( ++trie->uniquecharcount );
2839 TRIE_STORE_REVCHAR( folded );
2842 if ( !trie->charmap[ uvc ] ) {
2843 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2844 TRIE_STORE_REVCHAR( uvc );
2847 /* store the codepoint in the bitmap, and its folded
2849 TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
2850 set_bit = 0; /* We've done our bit :-) */
2854 /* XXX We could come up with the list of code points that fold
2855 * to this using PL_utf8_foldclosures, except not for
2856 * multi-char folds, as there may be multiple combinations
2857 * there that could work, which needs to wait until runtime to
2858 * resolve (The comment about LIGATURE FFI above is such an
2863 widecharmap = newHV();
2865 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2868 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
2870 if ( !SvTRUE( *svpp ) ) {
2871 sv_setiv( *svpp, ++trie->uniquecharcount );
2872 TRIE_STORE_REVCHAR(uvc);
2875 } /* end loop through characters in this branch of the trie */
2877 /* We take the min and max for this branch and combine to find the min
2878 * and max for all branches processed so far */
2879 if( cur == first ) {
2880 trie->minlen = minchars;
2881 trie->maxlen = maxchars;
2882 } else if (minchars < trie->minlen) {
2883 trie->minlen = minchars;
2884 } else if (maxchars > trie->maxlen) {
2885 trie->maxlen = maxchars;
2887 } /* end first pass */
2888 DEBUG_TRIE_COMPILE_r(
2889 Perl_re_indentf( aTHX_
2890 "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2892 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
2893 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2894 (int)trie->minlen, (int)trie->maxlen )
2898 We now know what we are dealing with in terms of unique chars and
2899 string sizes so we can calculate how much memory a naive
2900 representation using a flat table will take. If it's over a reasonable
2901 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
2902 conservative but potentially much slower representation using an array
2905 At the end we convert both representations into the same compressed
2906 form that will be used in regexec.c for matching with. The latter
2907 is a form that cannot be used to construct with but has memory
2908 properties similar to the list form and access properties similar
2909 to the table form making it both suitable for fast searches and
2910 small enough that its feasable to store for the duration of a program.
2912 See the comment in the code where the compressed table is produced
2913 inplace from the flat tabe representation for an explanation of how
2914 the compression works.
2919 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2922 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2923 > SvIV(re_trie_maxbuff) )
2926 Second Pass -- Array Of Lists Representation
2928 Each state will be represented by a list of charid:state records
2929 (reg_trie_trans_le) the first such element holds the CUR and LEN
2930 points of the allocated array. (See defines above).
2932 We build the initial structure using the lists, and then convert
2933 it into the compressed table form which allows faster lookups
2934 (but cant be modified once converted).
2937 STRLEN transcount = 1;
2939 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using list compiler\n",
2942 trie->states = (reg_trie_state *)
2943 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2944 sizeof(reg_trie_state) );
2948 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2950 regnode *noper = NEXTOPER( cur );
2951 U32 state = 1; /* required init */
2952 U16 charid = 0; /* sanity init */
2953 U32 wordlen = 0; /* required init */
2955 if (OP(noper) == NOTHING) {
2956 regnode *noper_next= regnext(noper);
2957 if (noper_next < tail)
2961 if ( noper < tail && ( OP(noper) == flags || ( flags == EXACTFU && OP(noper) == EXACTFU_SS ) ) ) {
2962 const U8 *uc= (U8*)STRING(noper);
2963 const U8 *e= uc + STR_LEN(noper);
2965 for ( ; uc < e ; uc += len ) {
2970 charid = trie->charmap[ uvc ];
2972 SV** const svpp = hv_fetch( widecharmap,
2979 charid=(U16)SvIV( *svpp );
2982 /* charid is now 0 if we dont know the char read, or
2983 * nonzero if we do */
2990 if ( !trie->states[ state ].trans.list ) {
2991 TRIE_LIST_NEW( state );
2994 check <= TRIE_LIST_USED( state );
2997 if ( TRIE_LIST_ITEM( state, check ).forid
3000 newstate = TRIE_LIST_ITEM( state, check ).newstate;
3005 newstate = next_alloc++;
3006 prev_states[newstate] = state;
3007 TRIE_LIST_PUSH( state, charid, newstate );
3012 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3016 TRIE_HANDLE_WORD(state);
3018 } /* end second pass */
3020 /* next alloc is the NEXT state to be allocated */
3021 trie->statecount = next_alloc;
3022 trie->states = (reg_trie_state *)
3023 PerlMemShared_realloc( trie->states,
3025 * sizeof(reg_trie_state) );
3027 /* and now dump it out before we compress it */
3028 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
3029 revcharmap, next_alloc,
3033 trie->trans = (reg_trie_trans *)
3034 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
3041 for( state=1 ; state < next_alloc ; state ++ ) {
3045 DEBUG_TRIE_COMPILE_MORE_r(
3046 Perl_re_printf( aTHX_ "tp: %d zp: %d ",tp,zp)
3050 if (trie->states[state].trans.list) {
3051 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
3055 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3056 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
3057 if ( forid < minid ) {
3059 } else if ( forid > maxid ) {
3063 if ( transcount < tp + maxid - minid + 1) {
3065 trie->trans = (reg_trie_trans *)
3066 PerlMemShared_realloc( trie->trans,
3068 * sizeof(reg_trie_trans) );
3069 Zero( trie->trans + (transcount / 2),
3073 base = trie->uniquecharcount + tp - minid;
3074 if ( maxid == minid ) {
3076 for ( ; zp < tp ; zp++ ) {
3077 if ( ! trie->trans[ zp ].next ) {
3078 base = trie->uniquecharcount + zp - minid;
3079 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
3081 trie->trans[ zp ].check = state;
3087 trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
3089 trie->trans[ tp ].check = state;
3094 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3095 const U32 tid = base
3096 - trie->uniquecharcount
3097 + TRIE_LIST_ITEM( state, idx ).forid;
3098 trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
3100 trie->trans[ tid ].check = state;
3102 tp += ( maxid - minid + 1 );
3104 Safefree(trie->states[ state ].trans.list);
3107 DEBUG_TRIE_COMPILE_MORE_r(
3108 Perl_re_printf( aTHX_ " base: %d\n",base);
3111 trie->states[ state ].trans.base=base;
3113 trie->lasttrans = tp + 1;
3117 Second Pass -- Flat Table Representation.
3119 we dont use the 0 slot of either trans[] or states[] so we add 1 to
3120 each. We know that we will need Charcount+1 trans at most to store
3121 the data (one row per char at worst case) So we preallocate both
3122 structures assuming worst case.
3124 We then construct the trie using only the .next slots of the entry
3127 We use the .check field of the first entry of the node temporarily
3128 to make compression both faster and easier by keeping track of how
3129 many non zero fields are in the node.
3131 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
3134 There are two terms at use here: state as a TRIE_NODEIDX() which is
3135 a number representing the first entry of the node, and state as a
3136 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
3137 and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
3138 if there are 2 entrys per node. eg:
3146 The table is internally in the right hand, idx form. However as we
3147 also have to deal with the states array which is indexed by nodenum
3148 we have to use TRIE_NODENUM() to convert.
3151 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using table compiler\n",
3154 trie->trans = (reg_trie_trans *)
3155 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
3156 * trie->uniquecharcount + 1,
3157 sizeof(reg_trie_trans) );
3158 trie->states = (reg_trie_state *)
3159 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3160 sizeof(reg_trie_state) );
3161 next_alloc = trie->uniquecharcount + 1;
3164 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3166 regnode *noper = NEXTOPER( cur );
3168 U32 state = 1; /* required init */
3170 U16 charid = 0; /* sanity init */
3171 U32 accept_state = 0; /* sanity init */
3173 U32 wordlen = 0; /* required init */
3175 if (OP(noper) == NOTHING) {
3176 regnode *noper_next= regnext(noper);
3177 if (noper_next < tail)
3181 if ( noper < tail && ( OP(noper) == flags || ( flags == EXACTFU && OP(noper) == EXACTFU_SS ) ) ) {
3182 const U8 *uc= (U8*)STRING(noper);
3183 const U8 *e= uc + STR_LEN(noper);
3185 for ( ; uc < e ; uc += len ) {
3190 charid = trie->charmap[ uvc ];
3192 SV* const * const svpp = hv_fetch( widecharmap,
3196 charid = svpp ? (U16)SvIV(*svpp) : 0;
3200 if ( !trie->trans[ state + charid ].next ) {
3201 trie->trans[ state + charid ].next = next_alloc;
3202 trie->trans[ state ].check++;
3203 prev_states[TRIE_NODENUM(next_alloc)]
3204 = TRIE_NODENUM(state);
3205 next_alloc += trie->uniquecharcount;
3207 state = trie->trans[ state + charid ].next;
3209 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3211 /* charid is now 0 if we dont know the char read, or
3212 * nonzero if we do */
3215 accept_state = TRIE_NODENUM( state );
3216 TRIE_HANDLE_WORD(accept_state);
3218 } /* end second pass */
3220 /* and now dump it out before we compress it */
3221 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3223 next_alloc, depth+1));
3227 * Inplace compress the table.*
3229 For sparse data sets the table constructed by the trie algorithm will
3230 be mostly 0/FAIL transitions or to put it another way mostly empty.
3231 (Note that leaf nodes will not contain any transitions.)
3233 This algorithm compresses the tables by eliminating most such
3234 transitions, at the cost of a modest bit of extra work during lookup:
3236 - Each states[] entry contains a .base field which indicates the
3237 index in the state[] array wheres its transition data is stored.
3239 - If .base is 0 there are no valid transitions from that node.
3241 - If .base is nonzero then charid is added to it to find an entry in
3244 -If trans[states[state].base+charid].check!=state then the
3245 transition is taken to be a 0/Fail transition. Thus if there are fail
3246 transitions at the front of the node then the .base offset will point
3247 somewhere inside the previous nodes data (or maybe even into a node
3248 even earlier), but the .check field determines if the transition is
3252 The following process inplace converts the table to the compressed
3253 table: We first do not compress the root node 1,and mark all its
3254 .check pointers as 1 and set its .base pointer as 1 as well. This
3255 allows us to do a DFA construction from the compressed table later,
3256 and ensures that any .base pointers we calculate later are greater
3259 - We set 'pos' to indicate the first entry of the second node.
3261 - We then iterate over the columns of the node, finding the first and
3262 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3263 and set the .check pointers accordingly, and advance pos
3264 appropriately and repreat for the next node. Note that when we copy
3265 the next pointers we have to convert them from the original
3266 NODEIDX form to NODENUM form as the former is not valid post
3269 - If a node has no transitions used we mark its base as 0 and do not
3270 advance the pos pointer.
3272 - If a node only has one transition we use a second pointer into the
3273 structure to fill in allocated fail transitions from other states.
3274 This pointer is independent of the main pointer and scans forward
3275 looking for null transitions that are allocated to a state. When it
3276 finds one it writes the single transition into the "hole". If the
3277 pointer doesnt find one the single transition is appended as normal.
3279 - Once compressed we can Renew/realloc the structures to release the
3282 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3283 specifically Fig 3.47 and the associated pseudocode.
3287 const U32 laststate = TRIE_NODENUM( next_alloc );
3290 trie->statecount = laststate;
3292 for ( state = 1 ; state < laststate ; state++ ) {
3294 const U32 stateidx = TRIE_NODEIDX( state );
3295 const U32 o_used = trie->trans[ stateidx ].check;
3296 U32 used = trie->trans[ stateidx ].check;
3297 trie->trans[ stateidx ].check = 0;
3300 used && charid < trie->uniquecharcount;
3303 if ( flag || trie->trans[ stateidx + charid ].next ) {
3304 if ( trie->trans[ stateidx + charid ].next ) {
3306 for ( ; zp < pos ; zp++ ) {
3307 if ( ! trie->trans[ zp ].next ) {
3311 trie->states[ state ].trans.base
3313 + trie->uniquecharcount
3315 trie->trans[ zp ].next
3316 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3318 trie->trans[ zp ].check = state;
3319 if ( ++zp > pos ) pos = zp;
3326 trie->states[ state ].trans.base
3327 = pos + trie->uniquecharcount - charid ;
3329 trie->trans[ pos ].next
3330 = SAFE_TRIE_NODENUM(
3331 trie->trans[ stateidx + charid ].next );
3332 trie->trans[ pos ].check = state;
3337 trie->lasttrans = pos + 1;
3338 trie->states = (reg_trie_state *)
3339 PerlMemShared_realloc( trie->states, laststate
3340 * sizeof(reg_trie_state) );
3341 DEBUG_TRIE_COMPILE_MORE_r(
3342 Perl_re_indentf( aTHX_ "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
3344 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3348 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3351 } /* end table compress */
3353 DEBUG_TRIE_COMPILE_MORE_r(
3354 Perl_re_indentf( aTHX_ "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
3356 (UV)trie->statecount,
3357 (UV)trie->lasttrans)
3359 /* resize the trans array to remove unused space */
3360 trie->trans = (reg_trie_trans *)
3361 PerlMemShared_realloc( trie->trans, trie->lasttrans
3362 * sizeof(reg_trie_trans) );
3364 { /* Modify the program and insert the new TRIE node */
3365 U8 nodetype =(U8)(flags & 0xFF);
3369 regnode *optimize = NULL;
3370 #ifdef RE_TRACK_PATTERN_OFFSETS
3373 U32 mjd_nodelen = 0;
3374 #endif /* RE_TRACK_PATTERN_OFFSETS */
3375 #endif /* DEBUGGING */
3377 This means we convert either the first branch or the first Exact,
3378 depending on whether the thing following (in 'last') is a branch
3379 or not and whther first is the startbranch (ie is it a sub part of
3380 the alternation or is it the whole thing.)
3381 Assuming its a sub part we convert the EXACT otherwise we convert
3382 the whole branch sequence, including the first.
3384 /* Find the node we are going to overwrite */
3385 if ( first != startbranch || OP( last ) == BRANCH ) {
3386 /* branch sub-chain */
3387 NEXT_OFF( first ) = (U16)(last - first);
3388 #ifdef RE_TRACK_PATTERN_OFFSETS
3390 mjd_offset= Node_Offset((convert));
3391 mjd_nodelen= Node_Length((convert));
3394 /* whole branch chain */
3396 #ifdef RE_TRACK_PATTERN_OFFSETS
3399 const regnode *nop = NEXTOPER( convert );
3400 mjd_offset= Node_Offset((nop));
3401 mjd_nodelen= Node_Length((nop));
3405 Perl_re_indentf( aTHX_ "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
3407 (UV)mjd_offset, (UV)mjd_nodelen)
3410 /* But first we check to see if there is a common prefix we can
3411 split out as an EXACT and put in front of the TRIE node. */
3412 trie->startstate= 1;
3413 if ( trie->bitmap && !widecharmap && !trie->jump ) {
3414 /* we want to find the first state that has more than
3415 * one transition, if that state is not the first state
3416 * then we have a common prefix which we can remove.
3419 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3421 I32 first_ofs = -1; /* keeps track of the ofs of the first
3422 transition, -1 means none */
3424 const U32 base = trie->states[ state ].trans.base;
3426 /* does this state terminate an alternation? */
3427 if ( trie->states[state].wordnum )
3430 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3431 if ( ( base + ofs >= trie->uniquecharcount ) &&
3432 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3433 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3435 if ( ++count > 1 ) {
3436 /* we have more than one transition */
3439 /* if this is the first state there is no common prefix
3440 * to extract, so we can exit */
3441 if ( state == 1 ) break;
3442 tmp = av_fetch( revcharmap, ofs, 0);
3443 ch = (U8*)SvPV_nolen_const( *tmp );
3445 /* if we are on count 2 then we need to initialize the
3446 * bitmap, and store the previous char if there was one
3449 /* clear the bitmap */
3450 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3452 Perl_re_indentf( aTHX_ "New Start State=%" UVuf " Class: [",
3455 if (first_ofs >= 0) {
3456 SV ** const tmp = av_fetch( revcharmap, first_ofs, 0);
3457 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3459 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3461 Perl_re_printf( aTHX_ "%s", (char*)ch)
3465 /* store the current firstchar in the bitmap */
3466 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3467 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch));
3473 /* This state has only one transition, its transition is part
3474 * of a common prefix - we need to concatenate the char it
3475 * represents to what we have so far. */
3476 SV **tmp = av_fetch( revcharmap, first_ofs, 0);
3478 char *ch = SvPV( *tmp, len );
3480 SV *sv=sv_newmortal();
3481 Perl_re_indentf( aTHX_ "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n",
3483 (UV)state, (UV)first_ofs,
3484 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3485 PL_colors[0], PL_colors[1],
3486 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3487 PERL_PV_ESCAPE_FIRSTCHAR
3492 OP( convert ) = nodetype;
3493 str=STRING(convert);
3496 STR_LEN(convert) += len;
3502 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n"));
3507 trie->prefixlen = (state-1);
3509 regnode *n = convert+NODE_SZ_STR(convert);
3510 NEXT_OFF(convert) = NODE_SZ_STR(convert);
3511 trie->startstate = state;
3512 trie->minlen -= (state - 1);
3513 trie->maxlen -= (state - 1);
3515 /* At least the UNICOS C compiler choked on this
3516 * being argument to DEBUG_r(), so let's just have
3519 #ifdef PERL_EXT_RE_BUILD
3525 regnode *fix = convert;
3526 U32 word = trie->wordcount;
3527 #ifdef RE_TRACK_PATTERN_OFFSETS
3530 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3531 while( ++fix < n ) {
3532 Set_Node_Offset_Length(fix, 0, 0);
3535 SV ** const tmp = av_fetch( trie_words, word, 0 );
3537 if ( STR_LEN(convert) <= SvCUR(*tmp) )
3538 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3540 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3548 NEXT_OFF(convert) = (U16)(tail - convert);
3549 DEBUG_r(optimize= n);
3555 if ( trie->maxlen ) {
3556 NEXT_OFF( convert ) = (U16)(tail - convert);
3557 ARG_SET( convert, data_slot );
3558 /* Store the offset to the first unabsorbed branch in
3559 jump[0], which is otherwise unused by the jump logic.
3560 We use this when dumping a trie and during optimisation. */
3562 trie->jump[0] = (U16)(nextbranch - convert);
3564 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3565 * and there is a bitmap
3566 * and the first "jump target" node we found leaves enough room
3567 * then convert the TRIE node into a TRIEC node, with the bitmap
3568 * embedded inline in the opcode - this is hypothetically faster.
3570 if ( !trie->states[trie->startstate].wordnum
3572 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3574 OP( convert ) = TRIEC;
3575 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3576 PerlMemShared_free(trie->bitmap);
3579 OP( convert ) = TRIE;
3581 /* store the type in the flags */
3582 convert->flags = nodetype;
3586 + regarglen[ OP( convert ) ];
3588 /* XXX We really should free up the resource in trie now,
3589 as we won't use them - (which resources?) dmq */
3591 /* needed for dumping*/
3592 DEBUG_r(if (optimize) {
3593 regnode *opt = convert;
3595 while ( ++opt < optimize) {
3596 Set_Node_Offset_Length(opt, 0, 0);
3599 Try to clean up some of the debris left after the
3602 while( optimize < jumper ) {
3603 Track_Code( mjd_nodelen += Node_Length((optimize)); );
3604 OP( optimize ) = OPTIMIZED;
3605 Set_Node_Offset_Length(optimize, 0, 0);
3608 Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen);
3610 } /* end node insert */
3612 /* Finish populating the prev field of the wordinfo array. Walk back
3613 * from each accept state until we find another accept state, and if
3614 * so, point the first word's .prev field at the second word. If the
3615 * second already has a .prev field set, stop now. This will be the
3616 * case either if we've already processed that word's accept state,
3617 * or that state had multiple words, and the overspill words were
3618 * already linked up earlier.
3625 for (word=1; word <= trie->wordcount; word++) {
3627 if (trie->wordinfo[word].prev)
3629 state = trie->wordinfo[word].accept;
3631 state = prev_states[state];
3634 prev = trie->states[state].wordnum;
3638 trie->wordinfo[word].prev = prev;
3640 Safefree(prev_states);
3644 /* and now dump out the compressed format */
3645 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3647 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3649 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3650 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3652 SvREFCNT_dec_NN(revcharmap);
3656 : trie->startstate>1
3662 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3664 /* The Trie is constructed and compressed now so we can build a fail array if
3667 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3669 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3673 We find the fail state for each state in the trie, this state is the longest
3674 proper suffix of the current state's 'word' that is also a proper prefix of
3675 another word in our trie. State 1 represents the word '' and is thus the
3676 default fail state. This allows the DFA not to have to restart after its
3677 tried and failed a word at a given point, it simply continues as though it
3678 had been matching the other word in the first place.
3680 'abcdgu'=~/abcdefg|cdgu/
3681 When we get to 'd' we are still matching the first word, we would encounter
3682 'g' which would fail, which would bring us to the state representing 'd' in
3683 the second word where we would try 'g' and succeed, proceeding to match
3686 /* add a fail transition */
3687 const U32 trie_offset = ARG(source);
3688 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3690 const U32 ucharcount = trie->uniquecharcount;
3691 const U32 numstates = trie->statecount;
3692 const U32 ubound = trie->lasttrans + ucharcount;
3696 U32 base = trie->states[ 1 ].trans.base;
3699 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3701 GET_RE_DEBUG_FLAGS_DECL;
3703 PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3704 PERL_UNUSED_CONTEXT;
3706 PERL_UNUSED_ARG(depth);
3709 if ( OP(source) == TRIE ) {
3710 struct regnode_1 *op = (struct regnode_1 *)
3711 PerlMemShared_calloc(1, sizeof(struct regnode_1));
3712 StructCopy(source, op, struct regnode_1);
3713 stclass = (regnode *)op;
3715 struct regnode_charclass *op = (struct regnode_charclass *)
3716 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3717 StructCopy(source, op, struct regnode_charclass);
3718 stclass = (regnode *)op;
3720 OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3722 ARG_SET( stclass, data_slot );
3723 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3724 RExC_rxi->data->data[ data_slot ] = (void*)aho;
3725 aho->trie=trie_offset;
3726 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3727 Copy( trie->states, aho->states, numstates, reg_trie_state );
3728 Newx( q, numstates, U32);
3729 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3732 /* initialize fail[0..1] to be 1 so that we always have
3733 a valid final fail state */
3734 fail[ 0 ] = fail[ 1 ] = 1;
3736 for ( charid = 0; charid < ucharcount ; charid++ ) {
3737 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3739 q[ q_write ] = newstate;
3740 /* set to point at the root */
3741 fail[ q[ q_write++ ] ]=1;
3744 while ( q_read < q_write) {
3745 const U32 cur = q[ q_read++ % numstates ];
3746 base = trie->states[ cur ].trans.base;
3748 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3749 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3751 U32 fail_state = cur;
3754 fail_state = fail[ fail_state ];
3755 fail_base = aho->states[ fail_state ].trans.base;
3756 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3758 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3759 fail[ ch_state ] = fail_state;
3760 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3762 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
3764 q[ q_write++ % numstates] = ch_state;
3768 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3769 when we fail in state 1, this allows us to use the
3770 charclass scan to find a valid start char. This is based on the principle
3771 that theres a good chance the string being searched contains lots of stuff
3772 that cant be a start char.
3774 fail[ 0 ] = fail[ 1 ] = 0;
3775 DEBUG_TRIE_COMPILE_r({
3776 Perl_re_indentf( aTHX_ "Stclass Failtable (%" UVuf " states): 0",
3777 depth, (UV)numstates
3779 for( q_read=1; q_read<numstates; q_read++ ) {
3780 Perl_re_printf( aTHX_ ", %" UVuf, (UV)fail[q_read]);
3782 Perl_re_printf( aTHX_ "\n");
3785 /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3790 /* The below joins as many adjacent EXACTish nodes as possible into a single
3791 * one. The regop may be changed if the node(s) contain certain sequences that
3792 * require special handling. The joining is only done if:
3793 * 1) there is room in the current conglomerated node to entirely contain the
3795 * 2) they are the exact same node type
3797 * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3798 * these get optimized out
3800 * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3801 * as possible, even if that means splitting an existing node so that its first
3802 * part is moved to the preceeding node. This would maximise the efficiency of
3803 * memEQ during matching.
3805 * If a node is to match under /i (folded), the number of characters it matches
3806 * can be different than its character length if it contains a multi-character
3807 * fold. *min_subtract is set to the total delta number of characters of the
3810 * And *unfolded_multi_char is set to indicate whether or not the node contains
3811 * an unfolded multi-char fold. This happens when it won't be known until
3812 * runtime whether the fold is valid or not; namely
3813 * 1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the
3814 * target string being matched against turns out to be UTF-8 is that fold
3816 * 2) for EXACTFL nodes whose folding rules depend on the locale in force at
3818 * (Multi-char folds whose components are all above the Latin1 range are not
3819 * run-time locale dependent, and have already been folded by the time this
3820 * function is called.)
3822 * This is as good a place as any to discuss the design of handling these
3823 * multi-character fold sequences. It's been wrong in Perl for a very long
3824 * time. There are three code points in Unicode whose multi-character folds
3825 * were long ago discovered to mess things up. The previous designs for
3826 * dealing with these involved assigning a special node for them. This
3827 * approach doesn't always work, as evidenced by this example:
3828 * "\xDFs" =~ /s\xDF/ui # Used to fail before these patches
3829 * Both sides fold to "sss", but if the pattern is parsed to create a node that
3830 * would match just the \xDF, it won't be able to handle the case where a
3831 * successful match would have to cross the node's boundary. The new approach
3832 * that hopefully generally solves the problem generates an EXACTFU_SS node
3833 * that is "sss" in this case.
3835 * It turns out that there are problems with all multi-character folds, and not
3836 * just these three. Now the code is general, for all such cases. The
3837 * approach taken is:
3838 * 1) This routine examines each EXACTFish node that could contain multi-
3839 * character folded sequences. Since a single character can fold into
3840 * such a sequence, the minimum match length for this node is less than
3841 * the number of characters in the node. This routine returns in
3842 * *min_subtract how many characters to subtract from the the actual
3843 * length of the string to get a real minimum match length; it is 0 if
3844 * there are no multi-char foldeds. This delta is used by the caller to
3845 * adjust the min length of the match, and the delta between min and max,
3846 * so that the optimizer doesn't reject these possibilities based on size
3848 * 2) For the sequence involving the Sharp s (\xDF), the node type EXACTFU_SS
3849 * is used for an EXACTFU node that contains at least one "ss" sequence in
3850 * it. For non-UTF-8 patterns and strings, this is the only case where
3851 * there is a possible fold length change. That means that a regular
3852 * EXACTFU node without UTF-8 involvement doesn't have to concern itself
3853 * with length changes, and so can be processed faster. regexec.c takes
3854 * advantage of this. Generally, an EXACTFish node that is in UTF-8 is
3855 * pre-folded by regcomp.c (except EXACTFL, some of whose folds aren't
3856 * known until runtime). This saves effort in regex matching. However,
3857 * the pre-folding isn't done for non-UTF8 patterns because the fold of
3858 * the MICRO SIGN requires UTF-8, and we don't want to slow things down by
3859 * forcing the pattern into UTF8 unless necessary. Also what EXACTF (and,
3860 * again, EXACTFL) nodes fold to isn't known until runtime. The fold
3861 * possibilities for the non-UTF8 patterns are quite simple, except for
3862 * the sharp s. All the ones that don't involve a UTF-8 target string are
3863 * members of a fold-pair, and arrays are set up for all of them so that
3864 * the other member of the pair can be found quickly. Code elsewhere in
3865 * this file makes sure that in EXACTFU nodes, the sharp s gets folded to
3866 * 'ss', even if the pattern isn't UTF-8. This avoids the issues
3867 * described in the next item.
3868 * 3) A problem remains for unfolded multi-char folds. (These occur when the
3869 * validity of the fold won't be known until runtime, and so must remain
3870 * unfolded for now. This happens for the sharp s in EXACTF and EXACTFAA
3871 * nodes when the pattern isn't in UTF-8. (Note, BTW, that there cannot
3872 * be an EXACTF node with a UTF-8 pattern.) They also occur for various
3873 * folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
3874 * The reason this is a problem is that the optimizer part of regexec.c
3875 * (probably unwittingly, in Perl_regexec_flags()) makes an assumption
3876 * that a character in the pattern corresponds to at most a single
3877 * character in the target string. (And I do mean character, and not byte
3878 * here, unlike other parts of the documentation that have never been
3879 * updated to account for multibyte Unicode.) sharp s in EXACTF and
3880 * EXACTFL nodes can match the two character string 'ss'; in EXACTFAA
3881 * nodes it can match "\x{17F}\x{17F}". These, along with other ones in
3882 * EXACTFL nodes, violate the assumption, and they are the only instances
3883 * where it is violated. I'm reluctant to try to change the assumption,
3884 * as the code involved is impenetrable to me (khw), so instead the code
3885 * here punts. This routine examines EXACTFL nodes, and (when the pattern
3886 * isn't UTF-8) EXACTF and EXACTFAA for such unfolded folds, and returns a
3887 * boolean indicating whether or not the node contains such a fold. When
3888 * it is true, the caller sets a flag that later causes the optimizer in
3889 * this file to not set values for the floating and fixed string lengths,
3890 * and thus avoids the optimizer code in regexec.c that makes the invalid
3891 * assumption. Thus, there is no optimization based on string lengths for
3892 * EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
3893 * EXACTF and EXACTFAA nodes that contain the sharp s. (The reason the
3894 * assumption is wrong only in these cases is that all other non-UTF-8
3895 * folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
3896 * their expanded versions. (Again, we can't prefold sharp s to 'ss' in
3897 * EXACTF nodes because we don't know at compile time if it actually
3898 * matches 'ss' or not. For EXACTF nodes it will match iff the target
3899 * string is in UTF-8. This is in contrast to EXACTFU nodes, where it
3900 * always matches; and EXACTFAA where it never does. In an EXACTFAA node
3901 * in a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
3902 * problem; but in a non-UTF8 pattern, folding it to that above-Latin1
3903 * string would require the pattern to be forced into UTF-8, the overhead
3904 * of which we want to avoid. Similarly the unfolded multi-char folds in
3905 * EXACTFL nodes will match iff the locale at the time of match is a UTF-8
3908 * Similarly, the code that generates tries doesn't currently handle
3909 * not-already-folded multi-char folds, and it looks like a pain to change
3910 * that. Therefore, trie generation of EXACTFAA nodes with the sharp s
3911 * doesn't work. Instead, such an EXACTFAA is turned into a new regnode,
3912 * EXACTFAA_NO_TRIE, which the trie code knows not to handle. Most people
3913 * using /iaa matching will be doing so almost entirely with ASCII
3914 * strings, so this should rarely be encountered in practice */
3916 #define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
3917 if (PL_regkind[OP(scan)] == EXACT) \
3918 join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags), NULL, depth+1)
3921 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
3922 UV *min_subtract, bool *unfolded_multi_char,
3923 U32 flags, regnode *val, U32 depth)
3925 /* Merge several consecutive EXACTish nodes into one. */
3926 regnode *n = regnext(scan);
3928 regnode *next = scan + NODE_SZ_STR(scan);
3932 regnode *stop = scan;
3933 GET_RE_DEBUG_FLAGS_DECL;
3935 PERL_UNUSED_ARG(depth);
3938 PERL_ARGS_ASSERT_JOIN_EXACT;
3939 #ifndef EXPERIMENTAL_INPLACESCAN
3940 PERL_UNUSED_ARG(flags);
3941 PERL_UNUSED_ARG(val);
3943 DEBUG_PEEP("join", scan, depth, 0);
3945 /* Look through the subsequent nodes in the chain. Skip NOTHING, merge
3946 * EXACT ones that are mergeable to the current one. */
3948 && (PL_regkind[OP(n)] == NOTHING
3949 || (stringok && OP(n) == OP(scan)))
3951 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
3954 if (OP(n) == TAIL || n > next)
3956 if (PL_regkind[OP(n)] == NOTHING) {
3957 DEBUG_PEEP("skip:", n, depth, 0);
3958 NEXT_OFF(scan) += NEXT_OFF(n);
3959 next = n + NODE_STEP_REGNODE;
3966 else if (stringok) {
3967 const unsigned int oldl = STR_LEN(scan);
3968 regnode * const nnext = regnext(n);
3970 /* XXX I (khw) kind of doubt that this works on platforms (should
3971 * Perl ever run on one) where U8_MAX is above 255 because of lots
3972 * of other assumptions */
3973 /* Don't join if the sum can't fit into a single node */
3974 if (oldl + STR_LEN(n) > U8_MAX)
3977 DEBUG_PEEP("merg", n, depth, 0);
3980 NEXT_OFF(scan) += NEXT_OFF(n);
3981 STR_LEN(scan) += STR_LEN(n);
3982 next = n + NODE_SZ_STR(n);
3983 /* Now we can overwrite *n : */
3984 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
3992 #ifdef EXPERIMENTAL_INPLACESCAN
3993 if (flags && !NEXT_OFF(n)) {
3994 DEBUG_PEEP("atch", val, depth, 0);
3995 if (reg_off_by_arg[OP(n)]) {
3996 ARG_SET(n, val - n);
3999 NEXT_OFF(n) = val - n;
4007 *unfolded_multi_char = FALSE;
4009 /* Here, all the adjacent mergeable EXACTish nodes have been merged. We
4010 * can now analyze for sequences of problematic code points. (Prior to
4011 * this final joining, sequences could have been split over boundaries, and
4012 * hence missed). The sequences only happen in folding, hence for any
4013 * non-EXACT EXACTish node */
4014 if (OP(scan) != EXACT && OP(scan) != EXACTL) {
4015 U8* s0 = (U8*) STRING(scan);
4017 U8* s_end = s0 + STR_LEN(scan);
4019 int total_count_delta = 0; /* Total delta number of characters that
4020 multi-char folds expand to */
4022 /* One pass is made over the node's string looking for all the
4023 * possibilities. To avoid some tests in the loop, there are two main
4024 * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
4029 if (OP(scan) == EXACTFL) {
4032 /* An EXACTFL node would already have been changed to another
4033 * node type unless there is at least one character in it that
4034 * is problematic; likely a character whose fold definition
4035 * won't be known until runtime, and so has yet to be folded.
4036 * For all but the UTF-8 locale, folds are 1-1 in length, but
4037 * to handle the UTF-8 case, we need to create a temporary
4038 * folded copy using UTF-8 locale rules in order to analyze it.
4039 * This is because our macros that look to see if a sequence is
4040 * a multi-char fold assume everything is folded (otherwise the
4041 * tests in those macros would be too complicated and slow).
4042 * Note that here, the non-problematic folds will have already
4043 * been done, so we can just copy such characters. We actually
4044 * don't completely fold the EXACTFL string. We skip the
4045 * unfolded multi-char folds, as that would just create work
4046 * below to figure out the size they already are */
4048 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
4051 STRLEN s_len = UTF8SKIP(s);
4052 if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
4053 Copy(s, d, s_len, U8);
4056 else if (is_FOLDS_TO_MULTI_utf8(s)) {
4057 *unfolded_multi_char = TRUE;
4058 Copy(s, d, s_len, U8);
4061 else if (isASCII(*s)) {
4062 *(d++) = toFOLD(*s);
4066 _toFOLD_utf8_flags(s, s_end, d, &len, FOLD_FLAGS_FULL);
4072 /* Point the remainder of the routine to look at our temporary
4076 } /* End of creating folded copy of EXACTFL string */
4078 /* Examine the string for a multi-character fold sequence. UTF-8
4079 * patterns have all characters pre-folded by the time this code is
4081 while (s < s_end - 1) /* Can stop 1 before the end, as minimum
4082 length sequence we are looking for is 2 */
4084 int count = 0; /* How many characters in a multi-char fold */
4085 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
4086 if (! len) { /* Not a multi-char fold: get next char */
4091 /* Nodes with 'ss' require special handling, except for
4092 * EXACTFAA-ish for which there is no multi-char fold to this */
4093 if (len == 2 && *s == 's' && *(s+1) == 's'
4094 && OP(scan) != EXACTFAA
4095 && OP(scan) != EXACTFAA_NO_TRIE)
4098 if (OP(scan) != EXACTFL) {
4099 OP(scan) = EXACTFU_SS;
4103 else { /* Here is a generic multi-char fold. */
4104 U8* multi_end = s + len;
4106 /* Count how many characters are in it. In the case of
4107 * /aa, no folds which contain ASCII code points are
4108 * allowed, so check for those, and skip if found. */
4109 if (OP(scan) != EXACTFAA && OP(scan) != EXACTFAA_NO_TRIE) {
4110 count = utf8_length(s, multi_end);
4114 while (s < multi_end) {
4117 goto next_iteration;
4127 /* The delta is how long the sequence is minus 1 (1 is how long
4128 * the character that folds to the sequence is) */
4129 total_count_delta += count - 1;
4133 /* We created a temporary folded copy of the string in EXACTFL
4134 * nodes. Therefore we need to be sure it doesn't go below zero,
4135 * as the real string could be shorter */
4136 if (OP(scan) == EXACTFL) {
4137 int total_chars = utf8_length((U8*) STRING(scan),
4138 (U8*) STRING(scan) + STR_LEN(scan));
4139 if (total_count_delta > total_chars) {
4140 total_count_delta = total_chars;
4144 *min_subtract += total_count_delta;
4147 else if (OP(scan) == EXACTFAA) {
4149 /* Non-UTF-8 pattern, EXACTFAA node. There can't be a multi-char
4150 * fold to the ASCII range (and there are no existing ones in the
4151 * upper latin1 range). But, as outlined in the comments preceding
4152 * this function, we need to flag any occurrences of the sharp s.
4153 * This character forbids trie formation (because of added
4155 #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
4156 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
4157 || UNICODE_DOT_DOT_VERSION > 0)
4159 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
4160 OP(scan) = EXACTFAA_NO_TRIE;
4161 *unfolded_multi_char = TRUE;
4169 /* Non-UTF-8 pattern, not EXACTFAA node. Look for the multi-char
4170 * folds that are all Latin1. As explained in the comments
4171 * preceding this function, we look also for the sharp s in EXACTF
4172 * and EXACTFL nodes; it can be in the final position. Otherwise
4173 * we can stop looking 1 byte earlier because have to find at least
4174 * two characters for a multi-fold */
4175 const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
4180 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
4181 if (! len) { /* Not a multi-char fold. */
4182 if (*s == LATIN_SMALL_LETTER_SHARP_S
4183 && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
4185 *unfolded_multi_char = TRUE;
4192 && isALPHA_FOLD_EQ(*s, 's')
4193 && isALPHA_FOLD_EQ(*(s+1), 's'))
4196 /* EXACTF nodes need to know that the minimum length
4197 * changed so that a sharp s in the string can match this
4198 * ss in the pattern, but they remain EXACTF nodes, as they
4199 * won't match this unless the target string is is UTF-8,
4200 * which we don't know until runtime. EXACTFL nodes can't
4201 * transform into EXACTFU nodes */
4202 if (OP(scan) != EXACTF && OP(scan) != EXACTFL) {
4203 OP(scan) = EXACTFU_SS;
4207 *min_subtract += len - 1;
4215 /* Allow dumping but overwriting the collection of skipped
4216 * ops and/or strings with fake optimized ops */
4217 n = scan + NODE_SZ_STR(scan);
4225 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl", scan, depth, 0);});
4229 /* REx optimizer. Converts nodes into quicker variants "in place".
4230 Finds fixed substrings. */
4232 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
4233 to the position after last scanned or to NULL. */
4235 #define INIT_AND_WITHP \
4236 assert(!and_withp); \
4237 Newx(and_withp, 1, regnode_ssc); \
4238 SAVEFREEPV(and_withp)
4242 S_unwind_scan_frames(pTHX_ const void *p)
4244 scan_frame *f= (scan_frame *)p;
4246 scan_frame *n= f->next_frame;
4252 /* the return from this sub is the minimum length that could possibly match */
4254 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
4255 SSize_t *minlenp, SSize_t *deltap,
4260 regnode_ssc *and_withp,
4261 U32 flags, U32 depth)
4262 /* scanp: Start here (read-write). */
4263 /* deltap: Write maxlen-minlen here. */
4264 /* last: Stop before this one. */
4265 /* data: string data about the pattern */
4266 /* stopparen: treat close N as END */
4267 /* recursed: which subroutines have we recursed into */
4268 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
4270 /* There must be at least this number of characters to match */
4273 regnode *scan = *scanp, *next;
4275 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
4276 int is_inf_internal = 0; /* The studied chunk is infinite */
4277 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
4278 scan_data_t data_fake;
4279 SV *re_trie_maxbuff = NULL;
4280 regnode *first_non_open = scan;
4281 SSize_t stopmin = SSize_t_MAX;
4282 scan_frame *frame = NULL;
4283 GET_RE_DEBUG_FLAGS_DECL;
4285 PERL_ARGS_ASSERT_STUDY_CHUNK;
4286 RExC_study_started= 1;
4288 Zero(&data_fake, 1, scan_data_t);
4291 while (first_non_open && OP(first_non_open) == OPEN)
4292 first_non_open=regnext(first_non_open);
4298 RExC_study_chunk_recursed_count++;
4300 DEBUG_OPTIMISE_MORE_r(
4302 Perl_re_indentf( aTHX_ "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p",
4303 depth, (long)stopparen,
4304 (unsigned long)RExC_study_chunk_recursed_count,
4305 (unsigned long)depth, (unsigned long)recursed_depth,
4308 if (recursed_depth) {
4311 for ( j = 0 ; j < recursed_depth ; j++ ) {
4312 for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) {
4314 PAREN_TEST(RExC_study_chunk_recursed +
4315 ( j * RExC_study_chunk_recursed_bytes), i )
4318 !PAREN_TEST(RExC_study_chunk_recursed +
4319 (( j - 1 ) * RExC_study_chunk_recursed_bytes), i)
4322 Perl_re_printf( aTHX_ " %d",(int)i);
4326 if ( j + 1 < recursed_depth ) {
4327 Perl_re_printf( aTHX_ ",");
4331 Perl_re_printf( aTHX_ "\n");
4334 while ( scan && OP(scan) != END && scan < last ){
4335 UV min_subtract = 0; /* How mmany chars to subtract from the minimum
4336 node length to get a real minimum (because
4337 the folded version may be shorter) */
4338 bool unfolded_multi_char = FALSE;
4339 /* Peephole optimizer: */
4340 DEBUG_STUDYDATA("Peep", data, depth, is_inf);
4341 DEBUG_PEEP("Peep", scan, depth, flags);
4344 /* The reason we do this here is that we need to deal with things like
4345 * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT
4346 * parsing code, as each (?:..) is handled by a different invocation of
4349 JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);
4351 /* Follow the next-chain of the current node and optimize
4352 away all the NOTHINGs from it. */
4353 if (OP(scan) != CURLYX) {
4354 const int max = (reg_off_by_arg[OP(scan)]
4356 /* I32 may be smaller than U16 on CRAYs! */
4357 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
4358 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
4362 /* Skip NOTHING and LONGJMP. */
4363 while ((n = regnext(n))
4364 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
4365 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
4366 && off + noff < max)
4368 if (reg_off_by_arg[OP(scan)])
4371 NEXT_OFF(scan) = off;
4374 /* The principal pseudo-switch. Cannot be a switch, since we
4375 look into several different things. */
4376 if ( OP(scan) == DEFINEP ) {
4378 SSize_t deltanext = 0;
4379 SSize_t fake_last_close = 0;
4380 I32 f = SCF_IN_DEFINE;
4382 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4383 scan = regnext(scan);
4384 assert( OP(scan) == IFTHEN );
4385 DEBUG_PEEP("expect IFTHEN", scan, depth, flags);
4387 data_fake.last_closep= &fake_last_close;
4389 next = regnext(scan);
4390 scan = NEXTOPER(NEXTOPER(scan));
4391 DEBUG_PEEP("scan", scan, depth, flags);
4392 DEBUG_PEEP("next", next, depth, flags);
4394 /* we suppose the run is continuous, last=next...
4395 * NOTE we dont use the return here! */
4396 /* DEFINEP study_chunk() recursion */
4397 (void)study_chunk(pRExC_state, &scan, &minlen,
4398 &deltanext, next, &data_fake, stopparen,
4399 recursed_depth, NULL, f, depth+1);
4404 OP(scan) == BRANCH ||
4405 OP(scan) == BRANCHJ ||
4408 next = regnext(scan);
4411 /* The op(next)==code check below is to see if we
4412 * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN"
4413 * IFTHEN is special as it might not appear in pairs.
4414 * Not sure whether BRANCH-BRANCHJ is possible, regardless
4415 * we dont handle it cleanly. */
4416 if (OP(next) == code || code == IFTHEN) {
4417 /* NOTE - There is similar code to this block below for
4418 * handling TRIE nodes on a re-study. If you change stuff here
4419 * check there too. */
4420 SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0;
4422 regnode * const startbranch=scan;
4424 if (flags & SCF_DO_SUBSTR) {
4425 /* Cannot merge strings after this. */
4426 scan_commit(pRExC_state, data, minlenp, is_inf);
4429 if (flags & SCF_DO_STCLASS)
4430 ssc_init_zero(pRExC_state, &accum);
4432 while (OP(scan) == code) {
4433 SSize_t deltanext, minnext, fake;
4435 regnode_ssc this_class;
4437 DEBUG_PEEP("Branch", scan, depth, flags);
4440 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4442 data_fake.whilem_c = data->whilem_c;
4443 data_fake.last_closep = data->last_closep;
4446 data_fake.last_closep = &fake;
4448 data_fake.pos_delta = delta;
4449 next = regnext(scan);
4451 scan = NEXTOPER(scan); /* everything */
4452 if (code != BRANCH) /* everything but BRANCH */
4453 scan = NEXTOPER(scan);
4455 if (flags & SCF_DO_STCLASS) {
4456 ssc_init(pRExC_state, &this_class);
4457 data_fake.start_class = &this_class;
4458 f = SCF_DO_STCLASS_AND;
4460 if (flags & SCF_WHILEM_VISITED_POS)
4461 f |= SCF_WHILEM_VISITED_POS;
4463 /* we suppose the run is continuous, last=next...*/
4464 /* recurse study_chunk() for each BRANCH in an alternation */
4465 minnext = study_chunk(pRExC_state, &scan, minlenp,
4466 &deltanext, next, &data_fake, stopparen,
4467 recursed_depth, NULL, f, depth+1);
4471 if (deltanext == SSize_t_MAX) {
4472 is_inf = is_inf_internal = 1;
4474 } else if (max1 < minnext + deltanext)
4475 max1 = minnext + deltanext;
4477 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4479 if (data_fake.flags & SCF_SEEN_ACCEPT) {
4480 if ( stopmin > minnext)
4481 stopmin = min + min1;
4482 flags &= ~SCF_DO_SUBSTR;
4484 data->flags |= SCF_SEEN_ACCEPT;
4487 if (data_fake.flags & SF_HAS_EVAL)
4488 data->flags |= SF_HAS_EVAL;
4489 data->whilem_c = data_fake.whilem_c;
4491 if (flags & SCF_DO_STCLASS)
4492 ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);
4494 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
4496 if (flags & SCF_DO_SUBSTR) {
4497 data->pos_min += min1;
4498 if (data->pos_delta >= SSize_t_MAX - (max1 - min1))
4499 data->pos_delta = SSize_t_MAX;
4501 data->pos_delta += max1 - min1;
4502 if (max1 != min1 || is_inf)
4503 data->cur_is_floating = 1;
4506 if (delta == SSize_t_MAX
4507 || SSize_t_MAX - delta - (max1 - min1) < 0)
4508 delta = SSize_t_MAX;
4510 delta += max1 - min1;
4511 if (flags & SCF_DO_STCLASS_OR) {
4512 ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);
4514 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4515 flags &= ~SCF_DO_STCLASS;
4518 else if (flags & SCF_DO_STCLASS_AND) {
4520 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
4521 flags &= ~SCF_DO_STCLASS;
4524 /* Switch to OR mode: cache the old value of
4525 * data->start_class */
4527 StructCopy(data->start_class, and_withp, regnode_ssc);
4528 flags &= ~SCF_DO_STCLASS_AND;
4529 StructCopy(&accum, data->start_class, regnode_ssc);
4530 flags |= SCF_DO_STCLASS_OR;
4534 if (PERL_ENABLE_TRIE_OPTIMISATION &&
4535 OP( startbranch ) == BRANCH )
4539 Assuming this was/is a branch we are dealing with: 'scan'
4540 now points at the item that follows the branch sequence,
4541 whatever it is. We now start at the beginning of the
4542 sequence and look for subsequences of
4548 which would be constructed from a pattern like
4551 If we can find such a subsequence we need to turn the first
4552 element into a trie and then add the subsequent branch exact
4553 strings to the trie.
4557 1. patterns where the whole set of branches can be
4560 2. patterns where only a subset can be converted.
4562 In case 1 we can replace the whole set with a single regop
4563 for the trie. In case 2 we need to keep the start and end
4566 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
4567 becomes BRANCH TRIE; BRANCH X;
4569 There is an additional case, that being where there is a
4570 common prefix, which gets split out into an EXACT like node
4571 preceding the TRIE node.
4573 If x(1..n)==tail then we can do a simple trie, if not we make
4574 a "jump" trie, such that when we match the appropriate word
4575 we "jump" to the appropriate tail node. Essentially we turn
4576 a nested if into a case structure of sorts.
4581 if (!re_trie_maxbuff) {
4582 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
4583 if (!SvIOK(re_trie_maxbuff))
4584 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
4586 if ( SvIV(re_trie_maxbuff)>=0 ) {
4588 regnode *first = (regnode *)NULL;
4589 regnode *last = (regnode *)NULL;
4590 regnode *tail = scan;
4594 /* var tail is used because there may be a TAIL
4595 regop in the way. Ie, the exacts will point to the
4596 thing following the TAIL, but the last branch will
4597 point at the TAIL. So we advance tail. If we
4598 have nested (?:) we may have to move through several
4602 while ( OP( tail ) == TAIL ) {
4603 /* this is the TAIL generated by (?:) */
4604 tail = regnext( tail );
4608 DEBUG_TRIE_COMPILE_r({
4609 regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);
4610 Perl_re_indentf( aTHX_ "%s %" UVuf ":%s\n",
4612 "Looking for TRIE'able sequences. Tail node is ",
4613 (UV) REGNODE_OFFSET(tail),
4614 SvPV_nolen_const( RExC_mysv )
4620 Step through the branches
4621 cur represents each branch,
4622 noper is the first thing to be matched as part
4624 noper_next is the regnext() of that node.
4626 We normally handle a case like this
4627 /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also
4628 support building with NOJUMPTRIE, which restricts
4629 the trie logic to structures like /FOO|BAR/.
4631 If noper is a trieable nodetype then the branch is
4632 a possible optimization target. If we are building
4633 under NOJUMPTRIE then we require that noper_next is
4634 the same as scan (our current position in the regex
4637 Once we have two or more consecutive such branches
4638 we can create a trie of the EXACT's contents and
4639 stitch it in place into the program.
4641 If the sequence represents all of the branches in
4642 the alternation we replace the entire thing with a
4645 Otherwise when it is a subsequence we need to
4646 stitch it in place and replace only the relevant
4647 branches. This means the first branch has to remain
4648 as it is used by the alternation logic, and its
4649 next pointer, and needs to be repointed at the item
4650 on the branch chain following the last branch we
4651 have optimized away.
4653 This could be either a BRANCH, in which case the
4654 subsequence is internal, or it could be the item
4655 following the branch sequence in which case the
4656 subsequence is at the end (which does not
4657 necessarily mean the first node is the start of the
4660 TRIE_TYPE(X) is a define which maps the optype to a
4664 ----------------+-----------
4668 EXACTFU_SS | EXACTFU
4671 EXACTFLU8 | EXACTFLU8
4675 #define TRIE_TYPE(X) ( ( NOTHING == (X) ) \
4677 : ( EXACT == (X) ) \
4679 : ( EXACTFU == (X) || EXACTFU_SS == (X) ) \
4681 : ( EXACTFAA == (X) ) \
4683 : ( EXACTL == (X) ) \
4685 : ( EXACTFLU8 == (X) ) \
4689 /* dont use tail as the end marker for this traverse */
4690 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
4691 regnode * const noper = NEXTOPER( cur );
4692 U8 noper_type = OP( noper );
4693 U8 noper_trietype = TRIE_TYPE( noper_type );
4694 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
4695 regnode * const noper_next = regnext( noper );
4696 U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
4697 U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0;
4700 DEBUG_TRIE_COMPILE_r({
4701 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4702 Perl_re_indentf( aTHX_ "- %d:%s (%d)",
4704 REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );
4706 regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);
4707 Perl_re_printf( aTHX_ " -> %d:%s",
4708 REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv));
4711 regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);
4712 Perl_re_printf( aTHX_ "\t=> %d:%s\t",
4713 REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv));
4715 Perl_re_printf( aTHX_ "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n",
4716 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
4717 PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]
4721 /* Is noper a trieable nodetype that can be merged
4722 * with the current trie (if there is one)? */
4726 ( noper_trietype == NOTHING )
4727 || ( trietype == NOTHING )
4728 || ( trietype == noper_trietype )
4731 && noper_next >= tail
4735 /* Handle mergable triable node Either we are
4736 * the first node in a new trieable sequence,
4737 * in which case we do some bookkeeping,
4738 * otherwise we update the end pointer. */
4741 if ( noper_trietype == NOTHING ) {
4742 #if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
4743 regnode * const noper_next = regnext( noper );
4744 U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
4745 U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
4748 if ( noper_next_trietype ) {
4749 trietype = noper_next_trietype;
4750 } else if (noper_next_type) {
4751 /* a NOTHING regop is 1 regop wide.
4752 * We need at least two for a trie
4753 * so we can't merge this in */
4757 trietype = noper_trietype;
4760 if ( trietype == NOTHING )
4761 trietype = noper_trietype;
4766 } /* end handle mergable triable node */
4768 /* handle unmergable node -
4769 * noper may either be a triable node which can
4770 * not be tried together with the current trie,
4771 * or a non triable node */
4773 /* If last is set and trietype is not
4774 * NOTHING then we have found at least two
4775 * triable branch sequences in a row of a
4776 * similar trietype so we can turn them
4777 * into a trie. If/when we allow NOTHING to
4778 * start a trie sequence this condition
4779 * will be required, and it isn't expensive
4780 * so we leave it in for now. */
4781 if ( trietype && trietype != NOTHING )
4782 make_trie( pRExC_state,
4783 startbranch, first, cur, tail,
4784 count, trietype, depth+1 );
4785 last = NULL; /* note: we clear/update
4786 first, trietype etc below,
4787 so we dont do it here */
4791 && noper_next >= tail
4794 /* noper is triable, so we can start a new
4798 trietype = noper_trietype;
4800 /* if we already saw a first but the
4801 * current node is not triable then we have
4802 * to reset the first information. */
4807 } /* end handle unmergable node */
4808 } /* loop over branches */
4809 DEBUG_TRIE_COMPILE_r({
4810 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4811 Perl_re_indentf( aTHX_ "- %s (%d) <SCAN FINISHED> ",
4812 depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
4813 Perl_re_printf( aTHX_ "(First==%d, Last==%d, Cur==%d, tt==%s)\n",
4814 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
4815 PL_reg_name[trietype]
4819 if ( last && trietype ) {
4820 if ( trietype != NOTHING ) {
4821 /* the last branch of the sequence was part of
4822 * a trie, so we have to construct it here
4823 * outside of the loop */
4824 made= make_trie( pRExC_state, startbranch,
4825 first, scan, tail, count,
4826 trietype, depth+1 );
4827 #ifdef TRIE_STUDY_OPT
4828 if ( ((made == MADE_EXACT_TRIE &&
4829 startbranch == first)
4830 || ( first_non_open == first )) &&
4832 flags |= SCF_TRIE_RESTUDY;
4833 if ( startbranch == first
4836 RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;
4841 /* at this point we know whatever we have is a
4842 * NOTHING sequence/branch AND if 'startbranch'
4843 * is 'first' then we can turn the whole thing
4846 if ( startbranch == first ) {
4848 /* the entire thing is a NOTHING sequence,
4849 * something like this: (?:|) So we can
4850 * turn it into a plain NOTHING op. */
4851 DEBUG_TRIE_COMPILE_r({
4852 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4853 Perl_re_indentf( aTHX_ "- %s (%d) <NOTHING BRANCH SEQUENCE>\n",
4855 SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
4858 OP(startbranch)= NOTHING;
4859 NEXT_OFF(startbranch)= tail - startbranch;
4860 for ( opt= startbranch + 1; opt < tail ; opt++ )
4864 } /* end if ( last) */
4865 } /* TRIE_MAXBUF is non zero */
4870 else if ( code == BRANCHJ ) { /* single branch is optimized. */
4871 scan = NEXTOPER(NEXTOPER(scan));
4872 } else /* single branch is optimized. */
4873 scan = NEXTOPER(scan);
4875 } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) {
4877 regnode *start = NULL;
4878 regnode *end = NULL;
4879 U32 my_recursed_depth= recursed_depth;
4881 if (OP(scan) != SUSPEND) { /* GOSUB */
4882 /* Do setup, note this code has side effects beyond
4883 * the rest of this block. Specifically setting
4884 * RExC_recurse[] must happen at least once during
4887 RExC_recurse[ARG2L(scan)] = scan;
4888 start = REGNODE_p(RExC_open_parens[paren]);
4889 end = REGNODE_p(RExC_close_parens[paren]);
4891 /* NOTE we MUST always execute the above code, even
4892 * if we do nothing with a GOSUB */
4894 ( flags & SCF_IN_DEFINE )
4897 (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))
4899 ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )
4902 /* no need to do anything here if we are in a define. */
4903 /* or we are after some kind of infinite construct
4904 * so we can skip recursing into this item.
4905 * Since it is infinite we will not change the maxlen
4906 * or delta, and if we miss something that might raise
4907 * the minlen it will merely pessimise a little.
4909 * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/
4910 * might result in a minlen of 1 and not of 4,
4911 * but this doesn't make us mismatch, just try a bit
4912 * harder than we should.
4914 scan= regnext(scan);
4921 !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren)
4923 /* it is quite possible that there are more efficient ways
4924 * to do this. We maintain a bitmap per level of recursion
4925 * of which patterns we have entered so we can detect if a
4926 * pattern creates a possible infinite loop. When we
4927 * recurse down a level we copy the previous levels bitmap
4928 * down. When we are at recursion level 0 we zero the top
4929 * level bitmap. It would be nice to implement a different
4930 * more efficient way of doing this. In particular the top
4931 * level bitmap may be unnecessary.
4933 if (!recursed_depth) {
4934 Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);
4936 Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes),
4937 RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes),
4938 RExC_study_chunk_recursed_bytes, U8);
4940 /* we havent recursed into this paren yet, so recurse into it */
4941 DEBUG_STUDYDATA("gosub-set", data, depth, is_inf);
4942 PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren);
4943 my_recursed_depth= recursed_depth + 1;
4945 DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf);
4946 /* some form of infinite recursion, assume infinite length
4948 if (flags & SCF_DO_SUBSTR) {
4949 scan_commit(pRExC_state, data, minlenp, is_inf);
4950 data->cur_is_floating = 1;
4952 is_inf = is_inf_internal = 1;
4953 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
4954 ssc_anything(data->start_class);
4955 flags &= ~SCF_DO_STCLASS;
4957 start= NULL; /* reset start so we dont recurse later on. */
4962 end = regnext(scan);
4965 scan_frame *newframe;
4967 if (!RExC_frame_last) {
4968 Newxz(newframe, 1, scan_frame);
4969 SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);
4970 RExC_frame_head= newframe;
4972 } else if (!RExC_frame_last->next_frame) {
4973 Newxz(newframe, 1, scan_frame);
4974 RExC_frame_last->next_frame= newframe;
4975 newframe->prev_frame= RExC_frame_last;
4978 newframe= RExC_frame_last->next_frame;
4980 RExC_frame_last= newframe;
4982 newframe->next_regnode = regnext(scan);
4983 newframe->last_regnode = last;
4984 newframe->stopparen = stopparen;
4985 newframe->prev_recursed_depth = recursed_depth;
4986 newframe->this_prev_frame= frame;
4988 DEBUG_STUDYDATA("frame-new", data, depth, is_inf);
4989 DEBUG_PEEP("fnew", scan, depth, flags);
4996 recursed_depth= my_recursed_depth;
5001 else if (OP(scan) == EXACT || OP(scan) == EXACTL) {
5002 SSize_t l = STR_LEN(scan);
5006 const U8 * const s = (U8*)STRING(scan);
5007 uc = utf8_to_uvchr_buf(s, s + l, NULL);
5008 l = utf8_length(s, s + l);
5010 uc = *((U8*)STRING(scan));
5013 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
5014 /* The code below prefers earlier match for fixed
5015 offset, later match for variable offset. */
5016 if (data->last_end == -1) { /* Update the start info. */
5017 data->last_start_min = data->pos_min;
5018 data->last_start_max = is_inf
5019 ? SSize_t_MAX : data->pos_min + data->pos_delta;
5021 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
5023 SvUTF8_on(data->last_found);
5025 SV * const sv = data->last_found;
5026 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5027 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5028 if (mg && mg->mg_len >= 0)
5029 mg->mg_len += utf8_length((U8*)STRING(scan),
5030 (U8*)STRING(scan)+STR_LEN(scan));
5032 data->last_end = data->pos_min + l;
5033 data->pos_min += l; /* As in the first entry. */
5034 data->flags &= ~SF_BEFORE_EOL;
5037 /* ANDing the code point leaves at most it, and not in locale, and
5038 * can't match null string */
5039 if (flags & SCF_DO_STCLASS_AND) {
5040 ssc_cp_and(data->start_class, uc);
5041 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5042 ssc_clear_locale(data->start_class);
5044 else if (flags & SCF_DO_STCLASS_OR) {
5045 ssc_add_cp(data->start_class, uc);
5046 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5048 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5049 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5051 flags &= ~SCF_DO_STCLASS;
5053 else if (PL_regkind[OP(scan)] == EXACT) {
5054 /* But OP != EXACT!, so is EXACTFish */
5055 SSize_t l = STR_LEN(scan);
5056 const U8 * s = (U8*)STRING(scan);
5058 /* Search for fixed substrings supports EXACT only. */
5059 if (flags & SCF_DO_SUBSTR) {
5061 scan_commit(pRExC_state, data, minlenp, is_inf);
5064 l = utf8_length(s, s + l);
5066 if (unfolded_multi_char) {
5067 RExC_seen |= REG_UNFOLDED_MULTI_SEEN;
5069 min += l - min_subtract;
5071 delta += min_subtract;
5072 if (flags & SCF_DO_SUBSTR) {
5073 data->pos_min += l - min_subtract;
5074 if (data->pos_min < 0) {
5077 data->pos_delta += min_subtract;
5079 data->cur_is_floating = 1; /* float */
5083 if (flags & SCF_DO_STCLASS) {
5084 SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan);
5086 assert(EXACTF_invlist);
5087 if (flags & SCF_DO_STCLASS_AND) {
5088 if (OP(scan) != EXACTFL)
5089 ssc_clear_locale(data->start_class);
5090 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5091 ANYOF_POSIXL_ZERO(data->start_class);
5092 ssc_intersection(data->start_class, EXACTF_invlist, FALSE);
5094 else { /* SCF_DO_STCLASS_OR */
5095 ssc_union(data->start_class, EXACTF_invlist, FALSE);
5096 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5098 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5099 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5101 flags &= ~SCF_DO_STCLASS;
5102 SvREFCNT_dec(EXACTF_invlist);
5105 else if (REGNODE_VARIES(OP(scan))) {
5106 SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;
5107 I32 fl = 0, f = flags;
5108 regnode * const oscan = scan;
5109 regnode_ssc this_class;
5110 regnode_ssc *oclass = NULL;
5111 I32 next_is_eval = 0;
5113 switch (PL_regkind[OP(scan)]) {
5114 case WHILEM: /* End of (?:...)* . */
5115 scan = NEXTOPER(scan);
5118 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
5119 next = NEXTOPER(scan);
5120 if (OP(next) == EXACT
5121 || OP(next) == EXACTL
5122 || (flags & SCF_DO_STCLASS))
5125 maxcount = REG_INFTY;
5126 next = regnext(scan);
5127 scan = NEXTOPER(scan);
5131 if (flags & SCF_DO_SUBSTR)
5136 if (flags & SCF_DO_STCLASS) {
5138 maxcount = REG_INFTY;
5139 next = regnext(scan);
5140 scan = NEXTOPER(scan);
5143 if (flags & SCF_DO_SUBSTR) {
5144 scan_commit(pRExC_state, data, minlenp, is_inf);
5145 /* Cannot extend fixed substrings */
5146 data->cur_is_floating = 1; /* float */
5148 is_inf = is_inf_internal = 1;
5149 scan = regnext(scan);
5150 goto optimize_curly_tail;
5152 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
5153 && (scan->flags == stopparen))
5158 mincount = ARG1(scan);
5159 maxcount = ARG2(scan);
5161 next = regnext(scan);
5162 if (OP(scan) == CURLYX) {
5163 I32 lp = (data ? *(data->last_closep) : 0);
5164 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
5166 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
5167 next_is_eval = (OP(scan) == EVAL);
5169 if (flags & SCF_DO_SUBSTR) {
5171 scan_commit(pRExC_state, data, minlenp, is_inf);
5172 /* Cannot extend fixed substrings */
5173 pos_before = data->pos_min;
5177 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
5179 data->flags |= SF_IS_INF;
5181 if (flags & SCF_DO_STCLASS) {
5182 ssc_init(pRExC_state, &this_class);
5183 oclass = data->start_class;
5184 data->start_class = &this_class;
5185 f |= SCF_DO_STCLASS_AND;
5186 f &= ~SCF_DO_STCLASS_OR;
5188 /* Exclude from super-linear cache processing any {n,m}
5189 regops for which the combination of input pos and regex
5190 pos is not enough information to determine if a match
5193 For example, in the regex /foo(bar\s*){4,8}baz/ with the
5194 regex pos at the \s*, the prospects for a match depend not
5195 only on the input position but also on how many (bar\s*)
5196 repeats into the {4,8} we are. */
5197 if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
5198 f &= ~SCF_WHILEM_VISITED_POS;
5200 /* This will finish on WHILEM, setting scan, or on NULL: */
5201 /* recurse study_chunk() on loop bodies */
5202 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
5203 last, data, stopparen, recursed_depth, NULL,
5205 ? (f & ~SCF_DO_SUBSTR)
5209 if (flags & SCF_DO_STCLASS)
5210 data->start_class = oclass;
5211 if (mincount == 0 || minnext == 0) {
5212 if (flags & SCF_DO_STCLASS_OR) {
5213 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5215 else if (flags & SCF_DO_STCLASS_AND) {
5216 /* Switch to OR mode: cache the old value of
5217 * data->start_class */
5219 StructCopy(data->start_class, and_withp, regnode_ssc);
5220 flags &= ~SCF_DO_STCLASS_AND;
5221 StructCopy(&this_class, data->start_class, regnode_ssc);
5222 flags |= SCF_DO_STCLASS_OR;
5223 ANYOF_FLAGS(data->start_class)
5224 |= SSC_MATCHES_EMPTY_STRING;
5226 } else { /* Non-zero len */
5227 if (flags & SCF_DO_STCLASS_OR) {
5228 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5229 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5231 else if (flags & SCF_DO_STCLASS_AND)
5232 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5233 flags &= ~SCF_DO_STCLASS;
5235 if (!scan) /* It was not CURLYX, but CURLY. */
5237 if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR)
5238 /* ? quantifier ok, except for (?{ ... }) */
5239 && (next_is_eval || !(mincount == 0 && maxcount == 1))
5240 && (minnext == 0) && (deltanext == 0)
5241 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
5242 && maxcount <= REG_INFTY/3) /* Complement check for big
5245 _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP),
5246 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
5247 "Quantifier unexpected on zero-length expression "
5248 "in regex m/%" UTF8f "/",
5249 UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,
5253 min += minnext * mincount;
5254 is_inf_internal |= deltanext == SSize_t_MAX
5255 || (maxcount == REG_INFTY && minnext + deltanext > 0);
5256 is_inf |= is_inf_internal;
5258 delta = SSize_t_MAX;
5260 delta += (minnext + deltanext) * maxcount
5261 - minnext * mincount;
5263 /* Try powerful optimization CURLYX => CURLYN. */
5264 if ( OP(oscan) == CURLYX && data
5265 && data->flags & SF_IN_PAR
5266 && !(data->flags & SF_HAS_EVAL)
5267 && !deltanext && minnext == 1 ) {
5268 /* Try to optimize to CURLYN. */
5269 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
5270 regnode * const nxt1 = nxt;
5277 if (!REGNODE_SIMPLE(OP(nxt))
5278 && !(PL_regkind[OP(nxt)] == EXACT
5279 && STR_LEN(nxt) == 1))
5285 if (OP(nxt) != CLOSE)
5287 if (RExC_open_parens) {
5290 RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5293 RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2;
5295 /* Now we know that nxt2 is the only contents: */
5296 oscan->flags = (U8)ARG(nxt);
5298 OP(nxt1) = NOTHING; /* was OPEN. */
5301 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5302 NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
5303 NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
5304 OP(nxt) = OPTIMIZED; /* was CLOSE. */
5305 OP(nxt + 1) = OPTIMIZED; /* was count. */
5306 NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
5311 /* Try optimization CURLYX => CURLYM. */
5312 if ( OP(oscan) == CURLYX && data
5313 && !(data->flags & SF_HAS_PAR)
5314 && !(data->flags & SF_HAS_EVAL)
5315 && !deltanext /* atom is fixed width */
5316 && minnext != 0 /* CURLYM can't handle zero width */
5318 /* Nor characters whose fold at run-time may be
5319 * multi-character */
5320 && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)
5322 /* XXXX How to optimize if data == 0? */
5323 /* Optimize to a simpler form. */
5324 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
5328 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
5329 && (OP(nxt2) != WHILEM))
5331 OP(nxt2) = SUCCEED; /* Whas WHILEM */
5332 /* Need to optimize away parenths. */
5333 if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
5334 /* Set the parenth number. */
5335 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
5337 oscan->flags = (U8)ARG(nxt);
5338 if (RExC_open_parens) {
5340 RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5343 RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2)
5346 OP(nxt1) = OPTIMIZED; /* was OPEN. */
5347 OP(nxt) = OPTIMIZED; /* was CLOSE. */
5350 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5351 OP(nxt + 1) = OPTIMIZED; /* was count. */
5352 NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
5353 NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
5356 while ( nxt1 && (OP(nxt1) != WHILEM)) {
5357 regnode *nnxt = regnext(nxt1);
5359 if (reg_off_by_arg[OP(nxt1)])
5360 ARG_SET(nxt1, nxt2 - nxt1);
5361 else if (nxt2 - nxt1 < U16_MAX)
5362 NEXT_OFF(nxt1) = nxt2 - nxt1;
5364 OP(nxt) = NOTHING; /* Cannot beautify */
5369 /* Optimize again: */
5370 /* recurse study_chunk() on optimised CURLYX => CURLYM */
5371 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
5372 NULL, stopparen, recursed_depth, NULL, 0,
5378 else if ((OP(oscan) == CURLYX)
5379 && (flags & SCF_WHILEM_VISITED_POS)
5380 /* See the comment on a similar expression above.
5381 However, this time it's not a subexpression
5382 we care about, but the expression itself. */
5383 && (maxcount == REG_INFTY)
5385 /* This stays as CURLYX, we can put the count/of pair. */
5386 /* Find WHILEM (as in regexec.c) */
5387 regnode *nxt = oscan + NEXT_OFF(oscan);
5389 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
5391 nxt = PREVOPER(nxt);
5392 if (nxt->flags & 0xf) {
5393 /* we've already set whilem count on this node */
5394 } else if (++data->whilem_c < 16) {
5395 assert(data->whilem_c <= RExC_whilem_seen);
5396 nxt->flags = (U8)(data->whilem_c
5397 | (RExC_whilem_seen << 4)); /* On WHILEM */
5400 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
5402 if (flags & SCF_DO_SUBSTR) {
5403 SV *last_str = NULL;
5404 STRLEN last_chrs = 0;
5405 int counted = mincount != 0;
5407 if (data->last_end > 0 && mincount != 0) { /* Ends with a
5409 SSize_t b = pos_before >= data->last_start_min
5410 ? pos_before : data->last_start_min;
5412 const char * const s = SvPV_const(data->last_found, l);
5413 SSize_t old = b - data->last_start_min;
5416 old = utf8_hop((U8*)s, old) - (U8*)s;
5418 /* Get the added string: */
5419 last_str = newSVpvn_utf8(s + old, l, UTF);
5420 last_chrs = UTF ? utf8_length((U8*)(s + old),
5421 (U8*)(s + old + l)) : l;
5422 if (deltanext == 0 && pos_before == b) {
5423 /* What was added is a constant string */
5426 SvGROW(last_str, (mincount * l) + 1);
5427 repeatcpy(SvPVX(last_str) + l,
5428 SvPVX_const(last_str), l,
5430 SvCUR_set(last_str, SvCUR(last_str) * mincount);
5431 /* Add additional parts. */
5432 SvCUR_set(data->last_found,
5433 SvCUR(data->last_found) - l);
5434 sv_catsv(data->last_found, last_str);
5436 SV * sv = data->last_found;
5438 SvUTF8(sv) && SvMAGICAL(sv) ?
5439 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5440 if (mg && mg->mg_len >= 0)
5441 mg->mg_len += last_chrs * (mincount-1);
5443 last_chrs *= mincount;
5444 data->last_end += l * (mincount - 1);
5447 /* start offset must point into the last copy */
5448 data->last_start_min += minnext * (mincount - 1);
5449 data->last_start_max =
5452 : data->last_start_max +
5453 (maxcount - 1) * (minnext + data->pos_delta);
5456 /* It is counted once already... */
5457 data->pos_min += minnext * (mincount - counted);
5459 Perl_re_printf( aTHX_ "counted=%" UVuf " deltanext=%" UVuf
5460 " SSize_t_MAX=%" UVuf " minnext=%" UVuf
5461 " maxcount=%" UVuf " mincount=%" UVuf "\n",
5462 (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount,
5464 if (deltanext != SSize_t_MAX)
5465 Perl_re_printf( aTHX_ "LHS=%" UVuf " RHS=%" UVuf "\n",
5466 (UV)(-counted * deltanext + (minnext + deltanext) * maxcount
5467 - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta));
5469 if (deltanext == SSize_t_MAX
5470 || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta)
5471 data->pos_delta = SSize_t_MAX;
5473 data->pos_delta += - counted * deltanext +
5474 (minnext + deltanext) * maxcount - minnext * mincount;
5475 if (mincount != maxcount) {
5476 /* Cannot extend fixed substrings found inside
5478 scan_commit(pRExC_state, data, minlenp, is_inf);
5479 if (mincount && last_str) {
5480 SV * const sv = data->last_found;
5481 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5482 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5486 sv_setsv(sv, last_str);
5487 data->last_end = data->pos_min;
5488 data->last_start_min = data->pos_min - last_chrs;
5489 data->last_start_max = is_inf
5491 : data->pos_min + data->pos_delta - last_chrs;
5493 data->cur_is_floating = 1; /* float */
5495 SvREFCNT_dec(last_str);
5497 if (data && (fl & SF_HAS_EVAL))
5498 data->flags |= SF_HAS_EVAL;
5499 optimize_curly_tail:
5500 if (OP(oscan) != CURLYX) {
5501 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
5503 NEXT_OFF(oscan) += NEXT_OFF(next);
5509 Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d",
5514 if (flags & SCF_DO_SUBSTR) {
5515 /* Cannot expect anything... */
5516 scan_commit(pRExC_state, data, minlenp, is_inf);
5517 data->cur_is_floating = 1; /* float */
5519 is_inf = is_inf_internal = 1;
5520 if (flags & SCF_DO_STCLASS_OR) {
5521 if (OP(scan) == CLUMP) {
5522 /* Actually is any start char, but very few code points
5523 * aren't start characters */
5524 ssc_match_all_cp(data->start_class);
5527 ssc_anything(data->start_class);
5530 flags &= ~SCF_DO_STCLASS;
5534 else if (OP(scan) == LNBREAK) {
5535 if (flags & SCF_DO_STCLASS) {
5536 if (flags & SCF_DO_STCLASS_AND) {
5537 ssc_intersection(data->start_class,
5538 PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);
5539 ssc_clear_locale(data->start_class);
5540 ANYOF_FLAGS(data->start_class)
5541 &= ~SSC_MATCHES_EMPTY_STRING;
5543 else if (flags & SCF_DO_STCLASS_OR) {
5544 ssc_union(data->start_class,
5545 PL_XPosix_ptrs[_CC_VERTSPACE],
5547 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5549 /* See commit msg for
5550 * 749e076fceedeb708a624933726e7989f2302f6a */
5551 ANYOF_FLAGS(data->start_class)
5552 &= ~SSC_MATCHES_EMPTY_STRING;
5554 flags &= ~SCF_DO_STCLASS;
5557 if (delta != SSize_t_MAX)
5558 delta++; /* Because of the 2 char string cr-lf */
5559 if (flags & SCF_DO_SUBSTR) {
5560 /* Cannot expect anything... */
5561 scan_commit(pRExC_state, data, minlenp, is_inf);
5563 if (data->pos_delta != SSize_t_MAX) {
5564 data->pos_delta += 1;
5566 data->cur_is_floating = 1; /* float */
5569 else if (REGNODE_SIMPLE(OP(scan))) {
5571 if (flags & SCF_DO_SUBSTR) {
5572 scan_commit(pRExC_state, data, minlenp, is_inf);
5576 if (flags & SCF_DO_STCLASS) {
5578 SV* my_invlist = NULL;
5581 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5582 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5584 /* Some of the logic below assumes that switching
5585 locale on will only add false positives. */
5590 Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d",
5594 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5595 ssc_match_all_cp(data->start_class);
5600 SV* REG_ANY_invlist = _new_invlist(2);
5601 REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,
5603 if (flags & SCF_DO_STCLASS_OR) {
5604 ssc_union(data->start_class,
5606 TRUE /* TRUE => invert, hence all but \n
5610 else if (flags & SCF_DO_STCLASS_AND) {
5611 ssc_intersection(data->start_class,
5613 TRUE /* TRUE => invert */
5615 ssc_clear_locale(data->start_class);
5617 SvREFCNT_dec_NN(REG_ANY_invlist);
5625 if (flags & SCF_DO_STCLASS_AND)
5626 ssc_and(pRExC_state, data->start_class,
5627 (regnode_charclass *) scan);
5629 ssc_or(pRExC_state, data->start_class,
5630 (regnode_charclass *) scan);
5636 SV* cp_list = get_ANYOFM_contents(scan);
5638 if (flags & SCF_DO_STCLASS_OR) {
5639 ssc_union(data->start_class, cp_list, invert);
5641 else if (flags & SCF_DO_STCLASS_AND) {
5642 ssc_intersection(data->start_class, cp_list, invert);
5645 SvREFCNT_dec_NN(cp_list);
5654 namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;
5655 if (flags & SCF_DO_STCLASS_AND) {
5656 bool was_there = cBOOL(
5657 ANYOF_POSIXL_TEST(data->start_class,
5659 ANYOF_POSIXL_ZERO(data->start_class);
5660 if (was_there) { /* Do an AND */
5661 ANYOF_POSIXL_SET(data->start_class, namedclass);
5663 /* No individual code points can now match */
5664 data->start_class->invlist
5665 = sv_2mortal(_new_invlist(0));
5668 int complement = namedclass + ((invert) ? -1 : 1);
5670 assert(flags & SCF_DO_STCLASS_OR);
5672 /* If the complement of this class was already there,
5673 * the result is that they match all code points,
5674 * (\d + \D == everything). Remove the classes from
5675 * future consideration. Locale is not relevant in
5677 if (ANYOF_POSIXL_TEST(data->start_class, complement)) {
5678 ssc_match_all_cp(data->start_class);
5679 ANYOF_POSIXL_CLEAR(data->start_class, namedclass);
5680 ANYOF_POSIXL_CLEAR(data->start_class, complement);
5682 else { /* The usual case; just add this class to the
5684 ANYOF_POSIXL_SET(data->start_class, namedclass);
5693 my_invlist = invlist_clone(PL_Posix_ptrs[_CC_ASCII], NULL);
5695 /* This can be handled as a Posix class */
5696 goto join_posix_and_ascii;
5698 case NPOSIXA: /* For these, we always know the exact set of
5703 assert(FLAGS(scan) != _CC_ASCII);
5704 my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL);
5705 goto join_posix_and_ascii;
5713 my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL);
5715 /* NPOSIXD matches all upper Latin1 code points unless the
5716 * target string being matched is UTF-8, which is
5717 * unknowable until match time. Since we are going to
5718 * invert, we want to get rid of all of them so that the
5719 * inversion will match all */
5720 if (OP(scan) == NPOSIXD) {
5721 _invlist_subtract(my_invlist, PL_UpperLatin1,
5725 join_posix_and_ascii:
5727 if (flags & SCF_DO_STCLASS_AND) {
5728 ssc_intersection(data->start_class, my_invlist, invert);
5729 ssc_clear_locale(data->start_class);
5732 assert(flags & SCF_DO_STCLASS_OR);
5733 ssc_union(data->start_class, my_invlist, invert);
5735 SvREFCNT_dec(my_invlist);
5737 if (flags & SCF_DO_STCLASS_OR)
5738 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5739 flags &= ~SCF_DO_STCLASS;
5742 else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
5743 data->flags |= (OP(scan) == MEOL
5746 scan_commit(pRExC_state, data, minlenp, is_inf);
5749 else if ( PL_regkind[OP(scan)] == BRANCHJ
5750 /* Lookbehind, or need to calculate parens/evals/stclass: */
5751 && (scan->flags || data || (flags & SCF_DO_STCLASS))
5752 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM))
5754 if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
5755 || OP(scan) == UNLESSM )
5757 /* Negative Lookahead/lookbehind
5758 In this case we can't do fixed string optimisation.
5761 SSize_t deltanext, minnext, fake = 0;
5766 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
5768 data_fake.whilem_c = data->whilem_c;
5769 data_fake.last_closep = data->last_closep;
5772 data_fake.last_closep = &fake;
5773 data_fake.pos_delta = delta;
5774 if ( flags & SCF_DO_STCLASS && !scan->flags
5775 && OP(scan) == IFMATCH ) { /* Lookahead */
5776 ssc_init(pRExC_state, &intrnl);
5777 data_fake.start_class = &intrnl;
5778 f |= SCF_DO_STCLASS_AND;
5780 if (flags & SCF_WHILEM_VISITED_POS)
5781 f |= SCF_WHILEM_VISITED_POS;
5782 next = regnext(scan);
5783 nscan = NEXTOPER(NEXTOPER(scan));
5785 /* recurse study_chunk() for lookahead body */
5786 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
5787 last, &data_fake, stopparen,
5788 recursed_depth, NULL, f, depth+1);
5791 FAIL("Variable length lookbehind not implemented");
5793 else if (minnext > (I32)U8_MAX) {
5794 FAIL2("Lookbehind longer than %" UVuf " not implemented",
5797 scan->flags = (U8)minnext;
5800 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
5802 if (data_fake.flags & SF_HAS_EVAL)
5803 data->flags |= SF_HAS_EVAL;
5804 data->whilem_c = data_fake.whilem_c;
5806 if (f & SCF_DO_STCLASS_AND) {
5807 if (flags & SCF_DO_STCLASS_OR) {
5808 /* OR before, AND after: ideally we would recurse with
5809 * data_fake to get the AND applied by study of the
5810 * remainder of the pattern, and then derecurse;
5811 * *** HACK *** for now just treat as "no information".
5812 * See [perl #56690].
5814 ssc_init(pRExC_state, data->start_class);
5816 /* AND before and after: combine and continue. These
5817 * assertions are zero-length, so can match an EMPTY
5819 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
5820 ANYOF_FLAGS(data->start_class)
5821 |= SSC_MATCHES_EMPTY_STRING;
5825 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
5827 /* Positive Lookahead/lookbehind
5828 In this case we can do fixed string optimisation,
5829 but we must be careful about it. Note in the case of
5830 lookbehind the positions will be offset by the minimum
5831 length of the pattern, something we won't know about
5832 until after the recurse.
5834 SSize_t deltanext, fake = 0;
5838 /* We use SAVEFREEPV so that when the full compile
5839 is finished perl will clean up the allocated
5840 minlens when it's all done. This way we don't
5841 have to worry about freeing them when we know
5842 they wont be used, which would be a pain.
5845 Newx( minnextp, 1, SSize_t );
5846 SAVEFREEPV(minnextp);
5849 StructCopy(data, &data_fake, scan_data_t);
5850 if ((flags & SCF_DO_SUBSTR) && data->last_found) {
5853 scan_commit(pRExC_state, &data_fake, minlenp, is_inf);
5854 data_fake.last_found=newSVsv(data->last_found);
5858 data_fake.last_closep = &fake;
5859 data_fake.flags = 0;
5860 data_fake.substrs[0].flags = 0;
5861 data_fake.substrs[1].flags = 0;
5862 data_fake.pos_delta = delta;
5864 data_fake.flags |= SF_IS_INF;
5865 if ( flags & SCF_DO_STCLASS && !scan->flags
5866 && OP(scan) == IFMATCH ) { /* Lookahead */
5867 ssc_init(pRExC_state, &intrnl);
5868 data_fake.start_class = &intrnl;
5869 f |= SCF_DO_STCLASS_AND;
5871 if (flags & SCF_WHILEM_VISITED_POS)
5872 f |= SCF_WHILEM_VISITED_POS;
5873 next = regnext(scan);
5874 nscan = NEXTOPER(NEXTOPER(scan));
5876 /* positive lookahead study_chunk() recursion */
5877 *minnextp = study_chunk(pRExC_state, &nscan, minnextp,
5878 &deltanext, last, &data_fake,
5879 stopparen, recursed_depth, NULL,
5883 FAIL("Variable length lookbehind not implemented");
5885 else if (*minnextp > (I32)U8_MAX) {
5886 FAIL2("Lookbehind longer than %" UVuf " not implemented",
5889 scan->flags = (U8)*minnextp;
5894 if (f & SCF_DO_STCLASS_AND) {
5895 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
5896 ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;
5899 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
5901 if (data_fake.flags & SF_HAS_EVAL)
5902 data->flags |= SF_HAS_EVAL;
5903 data->whilem_c = data_fake.whilem_c;
5904 if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
5906 if (RExC_rx->minlen<*minnextp)
5907 RExC_rx->minlen=*minnextp;
5908 scan_commit(pRExC_state, &data_fake, minnextp, is_inf);
5909 SvREFCNT_dec_NN(data_fake.last_found);
5911 for (i = 0; i < 2; i++) {
5912 if (data_fake.substrs[i].minlenp != minlenp) {
5913 data->substrs[i].min_offset =
5914 data_fake.substrs[i].min_offset;
5915 data->substrs[i].max_offset =
5916 data_fake.substrs[i].max_offset;
5917 data->substrs[i].minlenp =
5918 data_fake.substrs[i].minlenp;
5919 data->substrs[i].lookbehind += scan->flags;
5928 else if (OP(scan) == OPEN) {
5929 if (stopparen != (I32)ARG(scan))
5932 else if (OP(scan) == CLOSE) {
5933 if (stopparen == (I32)ARG(scan)) {
5936 if ((I32)ARG(scan) == is_par) {
5937 next = regnext(scan);
5939 if ( next && (OP(next) != WHILEM) && next < last)
5940 is_par = 0; /* Disable optimization */
5943 *(data->last_closep) = ARG(scan);
5945 else if (OP(scan) == EVAL) {
5947 data->flags |= SF_HAS_EVAL;
5949 else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
5950 if (flags & SCF_DO_SUBSTR) {
5951 scan_commit(pRExC_state, data, minlenp, is_inf);
5952 flags &= ~SCF_DO_SUBSTR;
5954 if (data && OP(scan)==ACCEPT) {
5955 data->flags |= SCF_SEEN_ACCEPT;
5960 else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
5962 if (flags & SCF_DO_SUBSTR) {
5963 scan_commit(pRExC_state, data, minlenp, is_inf);
5964 data->cur_is_floating = 1; /* float */
5966 is_inf = is_inf_internal = 1;
5967 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5968 ssc_anything(data->start_class);
5969 flags &= ~SCF_DO_STCLASS;
5971 else if (OP(scan) == GPOS) {
5972 if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&
5973 !(delta || is_inf || (data && data->pos_delta)))
5975 if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))
5976 RExC_rx->intflags |= PREGf_ANCH_GPOS;
5977 if (RExC_rx->gofs < (STRLEN)min)
5978 RExC_rx->gofs = min;
5980 RExC_rx->intflags |= PREGf_GPOS_FLOAT;
5984 #ifdef TRIE_STUDY_OPT
5985 #ifdef FULL_TRIE_STUDY
5986 else if (PL_regkind[OP(scan)] == TRIE) {
5987 /* NOTE - There is similar code to this block above for handling
5988 BRANCH nodes on the initial study. If you change stuff here
5990 regnode *trie_node= scan;
5991 regnode *tail= regnext(scan);
5992 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
5993 SSize_t max1 = 0, min1 = SSize_t_MAX;
5996 if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */
5997 /* Cannot merge strings after this. */
5998 scan_commit(pRExC_state, data, minlenp, is_inf);
6000 if (flags & SCF_DO_STCLASS)
6001 ssc_init_zero(pRExC_state, &accum);
6007 const regnode *nextbranch= NULL;
6010 for ( word=1 ; word <= trie->wordcount ; word++)
6012 SSize_t deltanext=0, minnext=0, f = 0, fake;
6013 regnode_ssc this_class;
6015 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6017 data_fake.whilem_c = data->whilem_c;
6018 data_fake.last_closep = data->last_closep;
6021 data_fake.last_closep = &fake;
6022 data_fake.pos_delta = delta;
6023 if (flags & SCF_DO_STCLASS) {
6024 ssc_init(pRExC_state, &this_class);
6025 data_fake.start_class = &this_class;
6026 f = SCF_DO_STCLASS_AND;
6028 if (flags & SCF_WHILEM_VISITED_POS)
6029 f |= SCF_WHILEM_VISITED_POS;
6031 if (trie->jump[word]) {
6033 nextbranch = trie_node + trie->jump[0];
6034 scan= trie_node + trie->jump[word];
6035 /* We go from the jump point to the branch that follows
6036 it. Note this means we need the vestigal unused
6037 branches even though they arent otherwise used. */
6038 /* optimise study_chunk() for TRIE */
6039 minnext = study_chunk(pRExC_state, &scan, minlenp,
6040 &deltanext, (regnode *)nextbranch, &data_fake,
6041 stopparen, recursed_depth, NULL, f, depth+1);
6043 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
6044 nextbranch= regnext((regnode*)nextbranch);
6046 if (min1 > (SSize_t)(minnext + trie->minlen))
6047 min1 = minnext + trie->minlen;
6048 if (deltanext == SSize_t_MAX) {
6049 is_inf = is_inf_internal = 1;
6051 } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))
6052 max1 = minnext + deltanext + trie->maxlen;
6054 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6056 if (data_fake.flags & SCF_SEEN_ACCEPT) {
6057 if ( stopmin > min + min1)
6058 stopmin = min + min1;
6059 flags &= ~SCF_DO_SUBSTR;
6061 data->flags |= SCF_SEEN_ACCEPT;
6064 if (data_fake.flags & SF_HAS_EVAL)
6065 data->flags |= SF_HAS_EVAL;
6066 data->whilem_c = data_fake.whilem_c;
6068 if (flags & SCF_DO_STCLASS)
6069 ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);
6072 if (flags & SCF_DO_SUBSTR) {
6073 data->pos_min += min1;
6074 data->pos_delta += max1 - min1;
6075 if (max1 != min1 || is_inf)
6076 data->cur_is_floating = 1; /* float */
6079 if (delta != SSize_t_MAX) {
6080 if (SSize_t_MAX - (max1 - min1) >= delta)
6081 delta += max1 - min1;
6083 delta = SSize_t_MAX;
6085 if (flags & SCF_DO_STCLASS_OR) {
6086 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6088 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6089 flags &= ~SCF_DO_STCLASS;
6092 else if (flags & SCF_DO_STCLASS_AND) {
6094 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6095 flags &= ~SCF_DO_STCLASS;
6098 /* Switch to OR mode: cache the old value of
6099 * data->start_class */
6101 StructCopy(data->start_class, and_withp, regnode_ssc);
6102 flags &= ~SCF_DO_STCLASS_AND;
6103 StructCopy(&accum, data->start_class, regnode_ssc);
6104 flags |= SCF_DO_STCLASS_OR;
6111 else if (PL_regkind[OP(scan)] == TRIE) {
6112 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6115 min += trie->minlen;
6116 delta += (trie->maxlen - trie->minlen);
6117 flags &= ~SCF_DO_STCLASS; /* xxx */
6118 if (flags & SCF_DO_SUBSTR) {
6119 /* Cannot expect anything... */
6120 scan_commit(pRExC_state, data, minlenp, is_inf);
6121 data->pos_min += trie->minlen;
6122 data->pos_delta += (trie->maxlen - trie->minlen);
6123 if (trie->maxlen != trie->minlen)
6124 data->cur_is_floating = 1; /* float */
6126 if (trie->jump) /* no more substrings -- for now /grr*/
6127 flags &= ~SCF_DO_SUBSTR;
6129 #endif /* old or new */
6130 #endif /* TRIE_STUDY_OPT */
6132 /* Else: zero-length, ignore. */
6133 scan = regnext(scan);
6138 /* we need to unwind recursion. */
6141 DEBUG_STUDYDATA("frame-end", data, depth, is_inf);
6142 DEBUG_PEEP("fend", scan, depth, flags);
6144 /* restore previous context */
6145 last = frame->last_regnode;
6146 scan = frame->next_regnode;
6147 stopparen = frame->stopparen;
6148 recursed_depth = frame->prev_recursed_depth;
6150 RExC_frame_last = frame->prev_frame;
6151 frame = frame->this_prev_frame;
6152 goto fake_study_recurse;
6156 DEBUG_STUDYDATA("pre-fin", data, depth, is_inf);
6159 *deltap = is_inf_internal ? SSize_t_MAX : delta;
6161 if (flags & SCF_DO_SUBSTR && is_inf)
6162 data->pos_delta = SSize_t_MAX - data->pos_min;
6163 if (is_par > (I32)U8_MAX)
6165 if (is_par && pars==1 && data) {
6166 data->flags |= SF_IN_PAR;
6167 data->flags &= ~SF_HAS_PAR;
6169 else if (pars && data) {
6170 data->flags |= SF_HAS_PAR;
6171 data->flags &= ~SF_IN_PAR;
6173 if (flags & SCF_DO_STCLASS_OR)
6174 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6175 if (flags & SCF_TRIE_RESTUDY)
6176 data->flags |= SCF_TRIE_RESTUDY;
6178 DEBUG_STUDYDATA("post-fin", data, depth, is_inf);
6181 SSize_t final_minlen= min < stopmin ? min : stopmin;
6183 if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {
6184 if (final_minlen > SSize_t_MAX - delta)
6185 RExC_maxlen = SSize_t_MAX;
6186 else if (RExC_maxlen < final_minlen + delta)
6187 RExC_maxlen = final_minlen + delta;
6189 return final_minlen;
6191 NOT_REACHED; /* NOTREACHED */
6195 S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n)
6197 U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
6199 PERL_ARGS_ASSERT_ADD_DATA;
6201 Renewc(RExC_rxi->data,
6202 sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
6203 char, struct reg_data);
6205 Renew(RExC_rxi->data->what, count + n, U8);
6207 Newx(RExC_rxi->data->what, n, U8);
6208 RExC_rxi->data->count = count + n;
6209 Copy(s, RExC_rxi->data->what + count, n, U8);
6213 /*XXX: todo make this not included in a non debugging perl, but appears to be
6214 * used anyway there, in 'use re' */
6215 #ifndef PERL_IN_XSUB_RE
6217 Perl_reginitcolors(pTHX)
6219 const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
6221 char *t = savepv(s);
6225 t = strchr(t, '\t');
6231 PL_colors[i] = t = (char *)"";
6236 PL_colors[i++] = (char *)"";
6243 #ifdef TRIE_STUDY_OPT
6244 #define CHECK_RESTUDY_GOTO_butfirst(dOsomething) \
6247 (data.flags & SCF_TRIE_RESTUDY) \
6255 #define CHECK_RESTUDY_GOTO_butfirst
6259 * pregcomp - compile a regular expression into internal code
6261 * Decides which engine's compiler to call based on the hint currently in
6265 #ifndef PERL_IN_XSUB_RE
6267 /* return the currently in-scope regex engine (or the default if none) */
6269 regexp_engine const *
6270 Perl_current_re_engine(pTHX)
6272 if (IN_PERL_COMPILETIME) {
6273 HV * const table = GvHV(PL_hintgv);
6276 if (!table || !(PL_hints & HINT_LOCALIZE_HH))
6277 return &PL_core_reg_engine;
6278 ptr = hv_fetchs(table, "regcomp", FALSE);
6279 if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
6280 return &PL_core_reg_engine;
6281 return INT2PTR(regexp_engine*, SvIV(*ptr));
6285 if (!PL_curcop->cop_hints_hash)
6286 return &PL_core_reg_engine;
6287 ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
6288 if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
6289 return &PL_core_reg_engine;
6290 return INT2PTR(regexp_engine*, SvIV(ptr));
6296 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
6298 regexp_engine const *eng = current_re_engine();
6299 GET_RE_DEBUG_FLAGS_DECL;
6301 PERL_ARGS_ASSERT_PREGCOMP;
6303 /* Dispatch a request to compile a regexp to correct regexp engine. */
6305 Perl_re_printf( aTHX_ "Using engine %" UVxf "\n",
6308 return CALLREGCOMP_ENG(eng, pattern, flags);
6312 /* public(ish) entry point for the perl core's own regex compiling code.
6313 * It's actually a wrapper for Perl_re_op_compile that only takes an SV
6314 * pattern rather than a list of OPs, and uses the internal engine rather
6315 * than the current one */
6318 Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
6320 SV *pat = pattern; /* defeat constness! */
6321 PERL_ARGS_ASSERT_RE_COMPILE;
6322 return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
6323 #ifdef PERL_IN_XSUB_RE
6326 &PL_core_reg_engine,
6328 NULL, NULL, rx_flags, 0);
6333 S_free_codeblocks(pTHX_ struct reg_code_blocks *cbs)
6337 if (--cbs->refcnt > 0)
6339 for (n = 0; n < cbs->count; n++) {
6340 REGEXP *rx = cbs->cb[n].src_regex;
6342 cbs->cb[n].src_regex = NULL;
6343 SvREFCNT_dec_NN(rx);
6351 static struct reg_code_blocks *
6352 S_alloc_code_blocks(pTHX_ int ncode)
6354 struct reg_code_blocks *cbs;
6355 Newx(cbs, 1, struct reg_code_blocks);
6358 SAVEDESTRUCTOR_X(S_free_codeblocks, cbs);
6360 Newx(cbs->cb, ncode, struct reg_code_block);
6367 /* upgrade pattern pat_p of length plen_p to UTF8, and if there are code
6368 * blocks, recalculate the indices. Update pat_p and plen_p in-place to
6369 * point to the realloced string and length.
6371 * This is essentially a copy of Perl_bytes_to_utf8() with the code index
6375 S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state,
6376 char **pat_p, STRLEN *plen_p, int num_code_blocks)
6378 U8 *const src = (U8*)*pat_p;
6383 GET_RE_DEBUG_FLAGS_DECL;
6385 DEBUG_PARSE_r(Perl_re_printf( aTHX_
6386 "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
6388 /* 1 for each byte + 1 for each byte that expands to two, + trailing NUL */
6389 Newx(dst, *plen_p + variant_under_utf8_count(src, src + *plen_p) + 1, U8);
6392 while (s < *plen_p) {
6393 append_utf8_from_native_byte(src[s], &d);
6395 if (n < num_code_blocks) {
6396 assert(pRExC_state->code_blocks);
6397 if (!do_end && pRExC_state->code_blocks->cb[n].start == s) {
6398 pRExC_state->code_blocks->cb[n].start = d - dst - 1;
6399 assert(*(d - 1) == '(');
6402 else if (do_end && pRExC_state->code_blocks->cb[n].end == s) {
6403 pRExC_state->code_blocks->cb[n].end = d - dst - 1;
6404 assert(*(d - 1) == ')');
6413 *pat_p = (char*) dst;
6415 RExC_orig_utf8 = RExC_utf8 = 1;
6420 /* S_concat_pat(): concatenate a list of args to the pattern string pat,
6421 * while recording any code block indices, and handling overloading,
6422 * nested qr// objects etc. If pat is null, it will allocate a new
6423 * string, or just return the first arg, if there's only one.
6425 * Returns the malloced/updated pat.
6426 * patternp and pat_count is the array of SVs to be concatted;
6427 * oplist is the optional list of ops that generated the SVs;
6428 * recompile_p is a pointer to a boolean that will be set if
6429 * the regex will need to be recompiled.
6430 * delim, if non-null is an SV that will be inserted between each element
6434 S_concat_pat(pTHX_ RExC_state_t * const pRExC_state,
6435 SV *pat, SV ** const patternp, int pat_count,
6436 OP *oplist, bool *recompile_p, SV *delim)
6440 bool use_delim = FALSE;
6441 bool alloced = FALSE;
6443 /* if we know we have at least two args, create an empty string,
6444 * then concatenate args to that. For no args, return an empty string */
6445 if (!pat && pat_count != 1) {
6451 for (svp = patternp; svp < patternp + pat_count; svp++) {
6454 STRLEN orig_patlen = 0;
6456 SV *msv = use_delim ? delim : *svp;
6457 if (!msv) msv = &PL_sv_undef;
6459 /* if we've got a delimiter, we go round the loop twice for each
6460 * svp slot (except the last), using the delimiter the second
6469 if (SvTYPE(msv) == SVt_PVAV) {
6470 /* we've encountered an interpolated array within
6471 * the pattern, e.g. /...@a..../. Expand the list of elements,
6472 * then recursively append elements.
6473 * The code in this block is based on S_pushav() */
6475 AV *const av = (AV*)msv;
6476 const SSize_t maxarg = AvFILL(av) + 1;
6480 assert(oplist->op_type == OP_PADAV
6481 || oplist->op_type == OP_RV2AV);
6482 oplist = OpSIBLING(oplist);
6485 if (SvRMAGICAL(av)) {
6488 Newx(array, maxarg, SV*);
6490 for (i=0; i < maxarg; i++) {
6491 SV ** const svp = av_fetch(av, i, FALSE);
6492 array[i] = svp ? *svp : &PL_sv_undef;
6496 array = AvARRAY(av);
6498 pat = S_concat_pat(aTHX_ pRExC_state, pat,
6499 array, maxarg, NULL, recompile_p,
6501 GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV))));
6507 /* we make the assumption here that each op in the list of
6508 * op_siblings maps to one SV pushed onto the stack,
6509 * except for code blocks, with have both an OP_NULL and
6511 * This allows us to match up the list of SVs against the
6512 * list of OPs to find the next code block.
6514 * Note that PUSHMARK PADSV PADSV ..
6516 * PADRANGE PADSV PADSV ..
6517 * so the alignment still works. */
6520 if (oplist->op_type == OP_NULL
6521 && (oplist->op_flags & OPf_SPECIAL))
6523 assert(n < pRExC_state->code_blocks->count);
6524 pRExC_state->code_blocks->cb[n].start = pat ? SvCUR(pat) : 0;
6525 pRExC_state->code_blocks->cb[n].block = oplist;
6526 pRExC_state->code_blocks->cb[n].src_regex = NULL;
6529 oplist = OpSIBLING(oplist); /* skip CONST */
6532 oplist = OpSIBLING(oplist);;
6535 /* apply magic and QR overloading to arg */
6538 if (SvROK(msv) && SvAMAGIC(msv)) {
6539 SV *sv = AMG_CALLunary(msv, regexp_amg);
6543 if (SvTYPE(sv) != SVt_REGEXP)
6544 Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
6549 /* try concatenation overload ... */
6550 if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) &&
6551 (sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
6554 /* overloading involved: all bets are off over literal
6555 * code. Pretend we haven't seen it */
6557 pRExC_state->code_blocks->count -= n;
6561 /* ... or failing that, try "" overload */
6562 while (SvAMAGIC(msv)
6563 && (sv = AMG_CALLunary(msv, string_amg))
6567 && SvRV(msv) == SvRV(sv))
6572 if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
6576 /* this is a partially unrolled
6577 * sv_catsv_nomg(pat, msv);
6578 * that allows us to adjust code block indices if
6581 char *dst = SvPV_force_nomg(pat, dlen);
6583 if (SvUTF8(msv) && !SvUTF8(pat)) {
6584 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n);
6585 sv_setpvn(pat, dst, dlen);
6588 sv_catsv_nomg(pat, msv);
6592 /* We have only one SV to process, but we need to verify
6593 * it is properly null terminated or we will fail asserts
6594 * later. In theory we probably shouldn't get such SV's,
6595 * but if we do we should handle it gracefully. */
6596 if ( SvTYPE(msv) != SVt_PV || (SvLEN(msv) > SvCUR(msv) && *(SvEND(msv)) == 0) || SvIsCOW_shared_hash(msv) ) {
6597 /* not a string, or a string with a trailing null */
6600 /* a string with no trailing null, we need to copy it
6601 * so it has a trailing null */
6602 pat = sv_2mortal(newSVsv(msv));
6607 pRExC_state->code_blocks->cb[n-1].end = SvCUR(pat)-1;
6610 /* extract any code blocks within any embedded qr//'s */
6611 if (rx && SvTYPE(rx) == SVt_REGEXP
6612 && RX_ENGINE((REGEXP*)rx)->op_comp)
6615 RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
6616 if (ri->code_blocks && ri->code_blocks->count) {
6618 /* the presence of an embedded qr// with code means
6619 * we should always recompile: the text of the
6620 * qr// may not have changed, but it may be a
6621 * different closure than last time */
6623 if (pRExC_state->code_blocks) {
6624 int new_count = pRExC_state->code_blocks->count
6625 + ri->code_blocks->count;
6626 Renew(pRExC_state->code_blocks->cb,
6627 new_count, struct reg_code_block);
6628 pRExC_state->code_blocks->count = new_count;
6631 pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_
6632 ri->code_blocks->count);
6634 for (i=0; i < ri->code_blocks->count; i++) {
6635 struct reg_code_block *src, *dst;
6636 STRLEN offset = orig_patlen
6637 + ReANY((REGEXP *)rx)->pre_prefix;
6638 assert(n < pRExC_state->code_blocks->count);
6639 src = &ri->code_blocks->cb[i];
6640 dst = &pRExC_state->code_blocks->cb[n];
6641 dst->start = src->start + offset;
6642 dst->end = src->end + offset;
6643 dst->block = src->block;
6644 dst->src_regex = (REGEXP*) SvREFCNT_inc( (SV*)
6653 /* avoid calling magic multiple times on a single element e.g. =~ $qr */
6662 /* see if there are any run-time code blocks in the pattern.
6663 * False positives are allowed */
6666 S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
6667 char *pat, STRLEN plen)
6672 PERL_UNUSED_CONTEXT;
6674 for (s = 0; s < plen; s++) {
6675 if ( pRExC_state->code_blocks
6676 && n < pRExC_state->code_blocks->count
6677 && s == pRExC_state->code_blocks->cb[n].start)
6679 s = pRExC_state->code_blocks->cb[n].end;
6683 /* TODO ideally should handle [..], (#..), /#.../x to reduce false
6685 if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' &&
6687 || (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{'))
6694 /* Handle run-time code blocks. We will already have compiled any direct
6695 * or indirect literal code blocks. Now, take the pattern 'pat' and make a
6696 * copy of it, but with any literal code blocks blanked out and
6697 * appropriate chars escaped; then feed it into
6699 * eval "qr'modified_pattern'"
6703 * a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
6707 * qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
6709 * After eval_sv()-ing that, grab any new code blocks from the returned qr
6710 * and merge them with any code blocks of the original regexp.
6712 * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
6713 * instead, just save the qr and return FALSE; this tells our caller that
6714 * the original pattern needs upgrading to utf8.
6718 S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
6719 char *pat, STRLEN plen)
6723 GET_RE_DEBUG_FLAGS_DECL;
6725 if (pRExC_state->runtime_code_qr) {
6726 /* this is the second time we've been called; this should
6727 * only happen if the main pattern got upgraded to utf8
6728 * during compilation; re-use the qr we compiled first time
6729 * round (which should be utf8 too)
6731 qr = pRExC_state->runtime_code_qr;
6732 pRExC_state->runtime_code_qr = NULL;
6733 assert(RExC_utf8 && SvUTF8(qr));
6739 int newlen = plen + 7; /* allow for "qr''xx\0" extra chars */
6743 /* determine how many extra chars we need for ' and \ escaping */
6744 for (s = 0; s < plen; s++) {
6745 if (pat[s] == '\'' || pat[s] == '\\')
6749 Newx(newpat, newlen, char);
6751 *p++ = 'q'; *p++ = 'r'; *p++ = '\'';
6753 for (s = 0; s < plen; s++) {
6754 if ( pRExC_state->code_blocks
6755 && n < pRExC_state->code_blocks->count
6756 && s == pRExC_state->code_blocks->cb[n].start)
6758 /* blank out literal code block */
6759 assert(pat[s] == '(');
6760 while (s <= pRExC_state->code_blocks->cb[n].end) {
6768 if (pat[s] == '\'' || pat[s] == '\\')
6773 if (pRExC_state->pm_flags & RXf_PMf_EXTENDED) {
6775 if (pRExC_state->pm_flags & RXf_PMf_EXTENDED_MORE) {
6781 Perl_re_printf( aTHX_
6782 "%sre-parsing pattern for runtime code:%s %s\n",
6783 PL_colors[4], PL_colors[5], newpat);
6786 sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
6792 PUSHSTACKi(PERLSI_REQUIRE);
6793 /* G_RE_REPARSING causes the toker to collapse \\ into \ when
6794 * parsing qr''; normally only q'' does this. It also alters
6796 eval_sv(sv, G_SCALAR|G_RE_REPARSING);
6797 SvREFCNT_dec_NN(sv);
6802 SV * const errsv = ERRSV;
6803 if (SvTRUE_NN(errsv))
6804 /* use croak_sv ? */
6805 Perl_croak_nocontext("%" SVf, SVfARG(errsv));
6807 assert(SvROK(qr_ref));
6809 assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
6810 /* the leaving below frees the tmp qr_ref.
6811 * Give qr a life of its own */
6819 if (!RExC_utf8 && SvUTF8(qr)) {
6820 /* first time through; the pattern got upgraded; save the
6821 * qr for the next time through */
6822 assert(!pRExC_state->runtime_code_qr);
6823 pRExC_state->runtime_code_qr = qr;
6828 /* extract any code blocks within the returned qr// */
6831 /* merge the main (r1) and run-time (r2) code blocks into one */
6833 RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
6834 struct reg_code_block *new_block, *dst;
6835 RExC_state_t * const r1 = pRExC_state; /* convenient alias */
6839 if (!r2->code_blocks || !r2->code_blocks->count) /* we guessed wrong */
6841 SvREFCNT_dec_NN(qr);
6845 if (!r1->code_blocks)
6846 r1->code_blocks = S_alloc_code_blocks(aTHX_ 0);
6848 r1c = r1->code_blocks->count;
6849 r2c = r2->code_blocks->count;
6851 Newx(new_block, r1c + r2c, struct reg_code_block);
6855 while (i1 < r1c || i2 < r2c) {
6856 struct reg_code_block *src;
6860 src = &r2->code_blocks->cb[i2++];
6864 src = &r1->code_blocks->cb[i1++];
6865 else if ( r1->code_blocks->cb[i1].start
6866 < r2->code_blocks->cb[i2].start)
6868 src = &r1->code_blocks->cb[i1++];
6869 assert(src->end < r2->code_blocks->cb[i2].start);
6872 assert( r1->code_blocks->cb[i1].start
6873 > r2->code_blocks->cb[i2].start);
6874 src = &r2->code_blocks->cb[i2++];
6876 assert(src->end < r1->code_blocks->cb[i1].start);
6879 assert(pat[src->start] == '(');
6880 assert(pat[src->end] == ')');
6881 dst->start = src->start;
6882 dst->end = src->end;
6883 dst->block = src->block;
6884 dst->src_regex = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
6888 r1->code_blocks->count += r2c;
6889 Safefree(r1->code_blocks->cb);
6890 r1->code_blocks->cb = new_block;
6893 SvREFCNT_dec_NN(qr);
6899 S_setup_longest(pTHX_ RExC_state_t *pRExC_state,
6900 struct reg_substr_datum *rsd,
6901 struct scan_data_substrs *sub,
6902 STRLEN longest_length)
6904 /* This is the common code for setting up the floating and fixed length
6905 * string data extracted from Perl_re_op_compile() below. Returns a boolean
6906 * as to whether succeeded or not */
6910 bool eol = cBOOL(sub->flags & SF_BEFORE_EOL);
6911 bool meol = cBOOL(sub->flags & SF_BEFORE_MEOL);
6913 if (! (longest_length
6914 || (eol /* Can't have SEOL and MULTI */
6915 && (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
6917 /* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */
6918 || (RExC_seen & REG_UNFOLDED_MULTI_SEEN))
6923 /* copy the information about the longest from the reg_scan_data
6924 over to the program. */
6925 if (SvUTF8(sub->str)) {
6927 rsd->utf8_substr = sub->str;
6929 rsd->substr = sub->str;
6930 rsd->utf8_substr = NULL;
6932 /* end_shift is how many chars that must be matched that
6933 follow this item. We calculate it ahead of time as once the
6934 lookbehind offset is added in we lose the ability to correctly
6936 ml = sub->minlenp ? *(sub->minlenp) : (SSize_t)longest_length;
6937 rsd->end_shift = ml - sub->min_offset
6939 /* XXX SvTAIL is always false here - did you mean FBMcf_TAIL
6941 + (SvTAIL(sub->str) != 0)
6945 t = (eol/* Can't have SEOL and MULTI */
6946 && (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
6947 fbm_compile(sub->str, t ? FBMcf_TAIL : 0);
6953 S_set_regex_pv(pTHX_ RExC_state_t *pRExC_state, REGEXP *Rx)
6955 /* Calculates and sets in the compiled pattern 'Rx' the string to compile,
6956 * properly wrapped with the right modifiers */
6958 bool has_p = ((RExC_rx->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
6959 bool has_charset = RExC_utf8 || (get_regex_charset(RExC_rx->extflags)
6960 != REGEX_DEPENDS_CHARSET);
6962 /* The caret is output if there are any defaults: if not all the STD
6963 * flags are set, or if no character set specifier is needed */
6965 (((RExC_rx->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
6967 bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN)
6968 == REG_RUN_ON_COMMENT_SEEN);
6969 U8 reganch = (U8)((RExC_rx->extflags & RXf_PMf_STD_PMMOD)
6970 >> RXf_PMf_STD_PMMOD_SHIFT);
6971 const char *fptr = STD_PAT_MODS; /*"msixxn"*/
6973 STRLEN pat_len = RExC_precomp_end - RExC_precomp;
6975 /* We output all the necessary flags; we never output a minus, as all
6976 * those are defaults, so are
6977 * covered by the caret */
6978 const STRLEN wraplen = pat_len + has_p + has_runon
6979 + has_default /* If needs a caret */
6980 + PL_bitcount[reganch] /* 1 char for each set standard flag */
6982 /* If needs a character set specifier */
6983 + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
6984 + (sizeof("(?:)") - 1);
6986 PERL_ARGS_ASSERT_SET_REGEX_PV;
6988 /* make sure PL_bitcount bounds not exceeded */
6989 assert(sizeof(STD_PAT_MODS) <= 8);
6991 p = sv_grow(MUTABLE_SV(Rx), wraplen + 1); /* +1 for the ending NUL */
6994 SvFLAGS(Rx) |= SVf_UTF8;
6997 /* If a default, cover it using the caret */
6999 *p++= DEFAULT_PAT_MOD;
7005 name = get_regex_charset_name(RExC_rx->extflags, &len);
7006 if strEQ(name, DEPENDS_PAT_MODS) { /* /d under UTF-8 => /u */
7008 name = UNICODE_PAT_MODS;
7009 len = sizeof(UNICODE_PAT_MODS) - 1;
7011 Copy(name, p, len, char);
7015 *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
7018 while((ch = *fptr++)) {
7026 Copy(RExC_precomp, p, pat_len, char);
7027 assert ((RX_WRAPPED(Rx) - p) < 16);
7028 RExC_rx->pre_prefix = p - RX_WRAPPED(Rx);
7031 /* Adding a trailing \n causes this to compile properly:
7032 my $R = qr / A B C # D E/x; /($R)/
7033 Otherwise the parens are considered part of the comment */
7038 SvCUR_set(Rx, p - RX_WRAPPED(Rx));
7042 * Perl_re_op_compile - the perl internal RE engine's function to compile a
7043 * regular expression into internal code.
7044 * The pattern may be passed either as:
7045 * a list of SVs (patternp plus pat_count)
7046 * a list of OPs (expr)
7047 * If both are passed, the SV list is used, but the OP list indicates
7048 * which SVs are actually pre-compiled code blocks
7050 * The SVs in the list have magic and qr overloading applied to them (and
7051 * the list may be modified in-place with replacement SVs in the latter
7054 * If the pattern hasn't changed from old_re, then old_re will be
7057 * eng is the current engine. If that engine has an op_comp method, then
7058 * handle directly (i.e. we assume that op_comp was us); otherwise, just
7059 * do the initial concatenation of arguments and pass on to the external
7062 * If is_bare_re is not null, set it to a boolean indicating whether the
7063 * arg list reduced (after overloading) to a single bare regex which has
7064 * been returned (i.e. /$qr/).
7066 * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
7068 * pm_flags contains the PMf_* flags, typically based on those from the
7069 * pm_flags field of the related PMOP. Currently we're only interested in
7070 * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL.
7072 * For many years this code had an initial sizing pass that calculated
7073 * (sometimes incorrectly, leading to security holes) the size needed for the
7074 * compiled pattern. That was changed by commit
7075 * 7c932d07cab18751bfc7515b4320436273a459e2 in 5.29, which reallocs the size, a
7076 * node at a time, as parsing goes along. Patches welcome to fix any obsolete
7077 * references to this sizing pass.
7079 * Now, an initial crude guess as to the size needed is made, based on the
7080 * length of the pattern. Patches welcome to improve that guess. That amount
7081 * of space is malloc'd and then immediately freed, and then clawed back node
7082 * by node. This design is to minimze, to the extent possible, memory churn
7083 * when doing the the reallocs.
7085 * A separate parentheses counting pass may be needed in some cases.
7086 * (Previously the sizing pass did this.) Patches welcome to reduce the number
7089 * The existence of a sizing pass necessitated design decisions that are no
7090 * longer needed. There are potential areas of simplification.
7092 * Beware that the optimization-preparation code in here knows about some
7093 * of the structure of the compiled regexp. [I'll say.]
7097 Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
7098 OP *expr, const regexp_engine* eng, REGEXP *old_re,
7099 bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags)
7101 REGEXP *Rx; /* Capital 'R' means points to a REGEXP */
7109 SV** new_patternp = patternp;
7111 /* these are all flags - maybe they should be turned
7112 * into a single int with different bit masks */
7113 I32 sawlookahead = 0;
7118 regex_charset initial_charset = get_regex_charset(orig_rx_flags);
7120 bool runtime_code = 0;
7122 RExC_state_t RExC_state;
7123 RExC_state_t * const pRExC_state = &RExC_state;
7124 #ifdef TRIE_STUDY_OPT
7126 RExC_state_t copyRExC_state;
7128 GET_RE_DEBUG_FLAGS_DECL;
7130 PERL_ARGS_ASSERT_RE_OP_COMPILE;
7132 DEBUG_r(if (!PL_colorset) reginitcolors());
7134 /* Initialize these here instead of as-needed, as is quick and avoids
7135 * having to test them each time otherwise */
7136 if (! PL_InBitmap) {
7138 char * dump_len_string;
7141 /* This is calculated here, because the Perl program that generates the
7142 * static global ones doesn't currently have access to
7143 * NUM_ANYOF_CODE_POINTS */
7144 PL_InBitmap = _new_invlist(2);
7145 PL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0,
7146 NUM_ANYOF_CODE_POINTS - 1);
7148 dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN");
7149 if ( ! dump_len_string
7150 || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL))
7152 PL_dump_re_max_len = 60; /* A reasonable default */
7157 pRExC_state->warn_text = NULL;
7158 pRExC_state->code_blocks = NULL;
7161 *is_bare_re = FALSE;
7163 if (expr && (expr->op_type == OP_LIST ||
7164 (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
7165 /* allocate code_blocks if needed */
7169 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o))
7170 if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
7171 ncode++; /* count of DO blocks */
7174 pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode);
7178 /* compile-time pattern with just OP_CONSTs and DO blocks */
7183 /* find how many CONSTs there are */
7186 if (expr->op_type == OP_CONST)
7189 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7190 if (o->op_type == OP_CONST)
7194 /* fake up an SV array */
7196 assert(!new_patternp);
7197 Newx(new_patternp, n, SV*);
7198 SAVEFREEPV(new_patternp);
7202 if (expr->op_type == OP_CONST)
7203 new_patternp[n] = cSVOPx_sv(expr);
7205 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7206 if (o->op_type == OP_CONST)
7207 new_patternp[n++] = cSVOPo_sv;
7212 DEBUG_PARSE_r(Perl_re_printf( aTHX_
7213 "Assembling pattern from %d elements%s\n", pat_count,
7214 orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7216 /* set expr to the first arg op */
7218 if (pRExC_state->code_blocks && pRExC_state->code_blocks->count
7219 && expr->op_type != OP_CONST)
7221 expr = cLISTOPx(expr)->op_first;
7222 assert( expr->op_type == OP_PUSHMARK
7223 || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)
7224 || expr->op_type == OP_PADRANGE);
7225 expr = OpSIBLING(expr);
7228 pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,
7229 expr, &recompile, NULL);
7231 /* handle bare (possibly after overloading) regex: foo =~ $re */
7236 if (SvTYPE(re) == SVt_REGEXP) {
7240 DEBUG_PARSE_r(Perl_re_printf( aTHX_
7241 "Precompiled pattern%s\n",
7242 orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7248 exp = SvPV_nomg(pat, plen);
7250 if (!eng->op_comp) {
7251 if ((SvUTF8(pat) && IN_BYTES)
7252 || SvGMAGICAL(pat) || SvAMAGIC(pat))
7254 /* make a temporary copy; either to convert to bytes,
7255 * or to avoid repeating get-magic / overloaded stringify */
7256 pat = newSVpvn_flags(exp, plen, SVs_TEMP |
7257 (IN_BYTES ? 0 : SvUTF8(pat)));
7259 return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
7262 /* ignore the utf8ness if the pattern is 0 length */
7263 RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
7265 RExC_uni_semantics = RExC_utf8; /* UTF-8 implies unicode semantics;
7266 otherwise we may find later this should
7268 RExC_contains_locale = 0;
7269 RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT);
7270 RExC_in_script_run = 0;
7271 RExC_study_started = 0;
7272 pRExC_state->runtime_code_qr = NULL;
7273 RExC_frame_head= NULL;
7274 RExC_frame_last= NULL;
7275 RExC_frame_count= 0;
7276 RExC_latest_warn_offset = 0;
7277 RExC_use_BRANCHJ = 0;
7278 RExC_total_parens = 0;
7279 RExC_open_parens = NULL;
7280 RExC_close_parens = NULL;
7281 RExC_paren_names = NULL;
7283 RExC_seen_d_op = FALSE;
7285 RExC_paren_name_list = NULL;
7289 RExC_mysv1= sv_newmortal();
7290 RExC_mysv2= sv_newmortal();
7294 SV *dsv= sv_newmortal();
7295 RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7296 Perl_re_printf( aTHX_ "%sCompiling REx%s %s\n",
7297 PL_colors[4], PL_colors[5], s);
7300 /* we jump here if we have to recompile, e.g., from upgrading the pattern
7303 if ((pm_flags & PMf_USE_RE_EVAL)
7304 /* this second condition covers the non-regex literal case,
7305 * i.e. $foo =~ '(?{})'. */
7306 || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))
7308 runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);
7311 /* return old regex if pattern hasn't changed */
7312 /* XXX: note in the below we have to check the flags as well as the
7315 * Things get a touch tricky as we have to compare the utf8 flag
7316 * independently from the compile flags. */
7320 && !!RX_UTF8(old_re) == !!RExC_utf8
7321 && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )
7322 && RX_PRECOMP(old_re)
7323 && RX_PRELEN(old_re) == plen
7324 && memEQ(RX_PRECOMP(old_re), exp, plen)
7325 && !runtime_code /* with runtime code, always recompile */ )
7330 /* Allocate the pattern's SV */
7331 RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP);
7332 RExC_rx = ReANY(Rx);
7333 if ( RExC_rx == NULL )
7334 FAIL("Regexp out of space");
7336 rx_flags = orig_rx_flags;
7338 if (initial_charset == REGEX_DEPENDS_CHARSET && RExC_uni_semantics) {
7340 /* Set to use unicode semantics if the pattern is in utf8 and has the
7341 * 'depends' charset specified, as it means unicode when utf8 */
7342 set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
7345 RExC_pm_flags = pm_flags;
7348 assert(TAINTING_get || !TAINT_get);
7350 Perl_croak(aTHX_ "Eval-group in insecure regular expression");
7352 if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
7353 /* whoops, we have a non-utf8 pattern, whilst run-time code
7354 * got compiled as utf8. Try again with a utf8 pattern */
7355 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7356 pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7360 assert(!pRExC_state->runtime_code_qr);
7366 RExC_in_lookbehind = 0;
7367 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
7369 RExC_recode_x_to_native = 0;
7371 RExC_in_multi_char_class = 0;
7373 RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp;
7374 RExC_precomp_end = RExC_end = exp + plen;
7376 RExC_whilem_seen = 0;
7378 RExC_recurse = NULL;
7379 RExC_study_chunk_recursed = NULL;
7380 RExC_study_chunk_recursed_bytes= 0;
7381 RExC_recurse_count = 0;
7382 pRExC_state->code_index = 0;
7384 /* Initialize the string in the compiled pattern. This is so that there is
7385 * something to output if necessary */
7386 set_regex_pv(pRExC_state, Rx);
7389 Perl_re_printf( aTHX_
7390 "Starting parse and generation\n");
7392 RExC_lastparse=NULL;
7395 /* Allocate space and zero-initialize. Note, the two step process
7396 of zeroing when in debug mode, thus anything assigned has to
7397 happen after that */
7400 /* On the first pass of the parse, we guess how big this will be. Then
7401 * we grow in one operation to that amount and then give it back. As
7402 * we go along, we re-allocate what we need.
7404 * XXX Currently the guess is essentially that the pattern will be an
7405 * EXACT node with one byte input, one byte output. This is crude, and
7406 * better heuristics are welcome.
7408 * On any subsequent passes, we guess what we actually computed in the
7409 * latest earlier pass. Such a pass probably didn't complete so is
7410 * missing stuff. We could improve those guesses by knowing where the
7411 * parse stopped, and use the length so far plus apply the above
7412 * assumption to what's left. */
7413 RExC_size = STR_SZ(RExC_end - RExC_start);
7416 Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal);
7417 if ( RExC_rxi == NULL )
7418 FAIL("Regexp out of space");
7420 Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char);
7421 RXi_SET( RExC_rx, RExC_rxi );
7423 /* We start from 0 (over from 0 in the case this is a reparse. The first
7424 * node parsed will give back any excess memory we have allocated so far).
7428 /* non-zero initialization begins here */
7429 RExC_rx->engine= eng;
7430 RExC_rx->extflags = rx_flags;
7431 RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;
7433 if (pm_flags & PMf_IS_QR) {
7434 RExC_rxi->code_blocks = pRExC_state->code_blocks;
7435 if (RExC_rxi->code_blocks) {
7436 RExC_rxi->code_blocks->refcnt++;
7440 RExC_rx->intflags = 0;
7442 RExC_flags = rx_flags; /* don't let top level (?i) bleed */
7445 /* This NUL is guaranteed because the pattern comes from an SV*, and the sv
7446 * code makes sure the final byte is an uncounted NUL. But should this
7447 * ever not be the case, lots of things could read beyond the end of the
7448 * buffer: loops like
7449 * while(isFOO(*RExC_parse)) RExC_parse++;
7450 * strchr(RExC_parse, "foo");
7451 * etc. So it is worth noting. */
7452 assert(*RExC_end == '\0');
7456 RExC_emit_start = RExC_rxi->program;
7457 pRExC_state->code_index = 0;
7459 *((char*) RExC_emit_start) = (char) REG_MAGIC;
7463 if (reg(pRExC_state, 0, &flags, 1)) {
7465 /* Success!, But if RExC_total_parens < 0, we need to redo the parse
7466 * knowing how many parens there actually are */
7467 if (RExC_total_parens < 0) {
7468 flags |= RESTART_PARSE;
7471 /* We have that number in RExC_npar */
7472 RExC_total_parens = RExC_npar;
7474 else if (! MUST_RESTART(flags)) {
7476 Perl_croak(aTHX_ "panic: reg returned failure to re_op_compile, flags=%#" UVxf, (UV) flags);
7479 /* Here, we either have success, or we have to redo the parse for some reason */
7480 if (MUST_RESTART(flags)) {
7482 /* It's possible to write a regexp in ascii that represents Unicode
7483 codepoints outside of the byte range, such as via \x{100}. If we
7484 detect such a sequence we have to convert the entire pattern to utf8
7485 and then recompile, as our sizing calculation will have been based
7486 on 1 byte == 1 character, but we will need to use utf8 to encode
7487 at least some part of the pattern, and therefore must convert the whole
7490 if (flags & NEED_UTF8) {
7492 /* We have stored the offset of the final warning output so far.
7493 * That must be adjusted. Any variant characters between the start
7494 * of the pattern and this warning count for 2 bytes in the final,
7495 * so just add them again */
7496 if (UNLIKELY(RExC_latest_warn_offset > 0)) {
7497 RExC_latest_warn_offset +=
7498 variant_under_utf8_count((U8 *) exp, (U8 *) exp
7499 + RExC_latest_warn_offset);
7501 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7502 pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7503 DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse after upgrade\n"));
7506 DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse\n"));
7509 if (RExC_total_parens > 0) {
7510 /* Make enough room for all the known parens, and zero it */
7511 Renew(RExC_open_parens, RExC_total_parens, regnode_offset);
7512 Zero(RExC_open_parens, RExC_total_parens, regnode_offset);
7513 RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */
7515 Renew(RExC_close_parens, RExC_total_parens, regnode_offset);
7516 Zero(RExC_close_parens, RExC_total_parens, regnode_offset);
7518 else { /* Parse did not complete. Reinitialize the parentheses
7520 RExC_total_parens = 0;
7521 if (RExC_open_parens) {
7522 Safefree(RExC_open_parens);
7523 RExC_open_parens = NULL;
7525 if (RExC_close_parens) {
7526 Safefree(RExC_close_parens);
7527 RExC_close_parens = NULL;
7531 /* Clean up what we did in this parse */
7532 SvREFCNT_dec_NN(RExC_rx_sv);
7537 /* In a stable state, as here, this must be true */
7538 assert(RExC_size = RExC_emit + 1);
7540 /* Here, we have successfully parsed and generated the pattern's program
7541 * for the regex engine. We are ready to finish things up and look for
7544 /* Update the string to compile, with correct modifiers, etc */
7545 set_regex_pv(pRExC_state, Rx);
7547 RExC_rx->nparens = RExC_total_parens - 1;
7549 /* Uses the upper 4 bits of the FLAGS field, so keep within that size */
7550 if (RExC_whilem_seen > 15)
7551 RExC_whilem_seen = 15;
7554 Perl_re_printf( aTHX_
7555 "Required size %" IVdf " nodes\n", (IV)RExC_size);
7557 RExC_lastparse=NULL;
7560 #ifdef RE_TRACK_PATTERN_OFFSETS
7561 DEBUG_OFFSETS_r(Perl_re_printf( aTHX_
7562 "%s %" UVuf " bytes for offset annotations.\n",
7563 RExC_offsets ? "Got" : "Couldn't get",
7564 (UV)((RExC_offsets[0] * 2 + 1))));
7565 DEBUG_OFFSETS_r(if (RExC_offsets) {
7566 const STRLEN len = RExC_offsets[0];
7568 GET_RE_DEBUG_FLAGS_DECL;
7569 Perl_re_printf( aTHX_
7570 "Offsets: [%" UVuf "]\n\t", (UV)RExC_offsets[0]);
7571 for (i = 1; i <= len; i++) {
7572 if (RExC_offsets[i*2-1] || RExC_offsets[i*2])
7573 Perl_re_printf( aTHX_ "%" UVuf ":%" UVuf "[%" UVuf "] ",
7574 (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]);
7576 Perl_re_printf( aTHX_ "\n");
7580 SetProgLen(RExC_rxi,RExC_size);
7584 Perl_re_printf( aTHX_ "Starting post parse optimization\n");
7587 /* XXXX To minimize changes to RE engine we always allocate
7588 3-units-long substrs field. */
7589 Newx(RExC_rx->substrs, 1, struct reg_substr_data);
7590 if (RExC_recurse_count) {
7591 Newx(RExC_recurse, RExC_recurse_count, regnode *);
7592 SAVEFREEPV(RExC_recurse);
7595 if (RExC_seen & REG_RECURSE_SEEN) {
7596 /* Note, RExC_total_parens is 1 + the number of parens in a pattern.
7597 * So its 1 if there are no parens. */
7598 RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) +
7599 ((RExC_total_parens & 0x07) != 0);
7600 Newx(RExC_study_chunk_recursed,
7601 RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
7602 SAVEFREEPV(RExC_study_chunk_recursed);
7606 RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;
7608 RExC_study_chunk_recursed_count= 0;
7610 Zero(RExC_rx->substrs, 1, struct reg_substr_data);
7611 if (RExC_study_chunk_recursed) {
7612 Zero(RExC_study_chunk_recursed,
7613 RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
7617 #ifdef TRIE_STUDY_OPT
7619 StructCopy(&zero_scan_data, &data, scan_data_t);
7620 copyRExC_state = RExC_state;
7623 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n"));
7625 RExC_state = copyRExC_state;
7626 if (seen & REG_TOP_LEVEL_BRANCHES_SEEN)
7627 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
7629 RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN;
7630 StructCopy(&zero_scan_data, &data, scan_data_t);
7633 StructCopy(&zero_scan_data, &data, scan_data_t);
7636 /* Dig out information for optimizations. */
7637 RExC_rx->extflags = RExC_flags; /* was pm_op */
7638 /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
7641 SvUTF8_on(Rx); /* Unicode in it? */
7642 RExC_rxi->regstclass = NULL;
7643 if (RExC_naughty >= TOO_NAUGHTY) /* Probably an expensive pattern. */
7644 RExC_rx->intflags |= PREGf_NAUGHTY;
7645 scan = RExC_rxi->program + 1; /* First BRANCH. */
7647 /* testing for BRANCH here tells us whether there is "must appear"
7648 data in the pattern. If there is then we can use it for optimisations */
7649 if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice.
7652 STRLEN longest_length[2];
7653 regnode_ssc ch_class; /* pointed to by data */
7655 SSize_t last_close = 0; /* pointed to by data */
7656 regnode *first= scan;
7657 regnode *first_next= regnext(first);
7661 * Skip introductions and multiplicators >= 1
7662 * so that we can extract the 'meat' of the pattern that must
7663 * match in the large if() sequence following.
7664 * NOTE that EXACT is NOT covered here, as it is normally
7665 * picked up by the optimiser separately.
7667 * This is unfortunate as the optimiser isnt handling lookahead
7668 * properly currently.
7671 while ((OP(first) == OPEN && (sawopen = 1)) ||
7672 /* An OR of *one* alternative - should not happen now. */
7673 (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
7674 /* for now we can't handle lookbehind IFMATCH*/
7675 (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
7676 (OP(first) == PLUS) ||
7677 (OP(first) == MINMOD) ||
7678 /* An {n,m} with n>0 */
7679 (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
7680 (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
7683 * the only op that could be a regnode is PLUS, all the rest
7684 * will be regnode_1 or regnode_2.
7686 * (yves doesn't think this is true)
7688 if (OP(first) == PLUS)
7691 if (OP(first) == MINMOD)
7693 first += regarglen[OP(first)];
7695 first = NEXTOPER(first);
7696 first_next= regnext(first);
7699 /* Starting-point info. */
7701 DEBUG_PEEP("first:", first, 0, 0);
7702 /* Ignore EXACT as we deal with it later. */
7703 if (PL_regkind[OP(first)] == EXACT) {
7704 if (OP(first) == EXACT || OP(first) == EXACTL)
7705 NOOP; /* Empty, get anchored substr later. */
7707 RExC_rxi->regstclass = first;
7710 else if (PL_regkind[OP(first)] == TRIE &&
7711 ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0)
7713 /* this can happen only on restudy */
7714 RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0);
7717 else if (REGNODE_SIMPLE(OP(first)))
7718 RExC_rxi->regstclass = first;
7719 else if (PL_regkind[OP(first)] == BOUND ||
7720 PL_regkind[OP(first)] == NBOUND)
7721 RExC_rxi->regstclass = first;
7722 else if (PL_regkind[OP(first)] == BOL) {
7723 RExC_rx->intflags |= (OP(first) == MBOL
7726 first = NEXTOPER(first);
7729 else if (OP(first) == GPOS) {
7730 RExC_rx->intflags |= PREGf_ANCH_GPOS;
7731 first = NEXTOPER(first);
7734 else if ((!sawopen || !RExC_sawback) &&
7736 (OP(first) == STAR &&
7737 PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
7738 !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks)
7740 /* turn .* into ^.* with an implied $*=1 */
7742 (OP(NEXTOPER(first)) == REG_ANY)
7745 RExC_rx->intflags |= (type | PREGf_IMPLICIT);
7746 first = NEXTOPER(first);
7749 if (sawplus && !sawminmod && !sawlookahead
7750 && (!sawopen || !RExC_sawback)
7751 && !pRExC_state->code_blocks) /* May examine pos and $& */
7752 /* x+ must match at the 1st pos of run of x's */
7753 RExC_rx->intflags |= PREGf_SKIP;
7755 /* Scan is after the zeroth branch, first is atomic matcher. */
7756 #ifdef TRIE_STUDY_OPT
7759 Perl_re_printf( aTHX_ "first at %" IVdf "\n",
7760 (IV)(first - scan + 1))
7764 Perl_re_printf( aTHX_ "first at %" IVdf "\n",
7765 (IV)(first - scan + 1))
7771 * If there's something expensive in the r.e., find the
7772 * longest literal string that must appear and make it the
7773 * regmust. Resolve ties in favor of later strings, since
7774 * the regstart check works with the beginning of the r.e.
7775 * and avoiding duplication strengthens checking. Not a
7776 * strong reason, but sufficient in the absence of others.
7777 * [Now we resolve ties in favor of the earlier string if
7778 * it happens that c_offset_min has been invalidated, since the
7779 * earlier string may buy us something the later one won't.]
7782 data.substrs[0].str = newSVpvs("");
7783 data.substrs[1].str = newSVpvs("");
7784 data.last_found = newSVpvs("");
7785 data.cur_is_floating = 0; /* initially any found substring is fixed */
7786 ENTER_with_name("study_chunk");
7787 SAVEFREESV(data.substrs[0].str);
7788 SAVEFREESV(data.substrs[1].str);
7789 SAVEFREESV(data.last_found);
7791 if (!RExC_rxi->regstclass) {
7792 ssc_init(pRExC_state, &ch_class);
7793 data.start_class = &ch_class;
7794 stclass_flag = SCF_DO_STCLASS_AND;
7795 } else /* XXXX Check for BOUND? */
7797 data.last_closep = &last_close;
7801 * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/
7802 * (NO top level branches)
7804 minlen = study_chunk(pRExC_state, &first, &minlen, &fake,
7805 scan + RExC_size, /* Up to end */
7807 SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
7808 | (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
7812 CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
7815 if ( RExC_total_parens == 1 && !data.cur_is_floating
7816 && data.last_start_min == 0 && data.last_end > 0
7817 && !RExC_seen_zerolen
7818 && !(RExC_seen & REG_VERBARG_SEEN)
7819 && !(RExC_seen & REG_GPOS_SEEN)
7821 RExC_rx->extflags |= RXf_CHECK_ALL;
7823 scan_commit(pRExC_state, &data,&minlen, 0);
7826 /* XXX this is done in reverse order because that's the way the
7827 * code was before it was parameterised. Don't know whether it
7828 * actually needs doing in reverse order. DAPM */
7829 for (i = 1; i >= 0; i--) {
7830 longest_length[i] = CHR_SVLEN(data.substrs[i].str);
7833 && SvCUR(data.substrs[0].str) /* ok to leave SvCUR */
7834 && data.substrs[0].min_offset
7835 == data.substrs[1].min_offset
7836 && SvCUR(data.substrs[0].str)
7837 == SvCUR(data.substrs[1].str)
7839 && S_setup_longest (aTHX_ pRExC_state,
7840 &(RExC_rx->substrs->data[i]),
7844 RExC_rx->substrs->data[i].min_offset =
7845 data.substrs[i].min_offset - data.substrs[i].lookbehind;
7847 RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset;
7848 /* Don't offset infinity */
7849 if (data.substrs[i].max_offset < SSize_t_MAX)
7850 RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind;
7851 SvREFCNT_inc_simple_void_NN(data.substrs[i].str);
7854 RExC_rx->substrs->data[i].substr = NULL;
7855 RExC_rx->substrs->data[i].utf8_substr = NULL;
7856 longest_length[i] = 0;
7860 LEAVE_with_name("study_chunk");
7862 if (RExC_rxi->regstclass
7863 && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY))
7864 RExC_rxi->regstclass = NULL;
7866 if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr)
7867 || RExC_rx->substrs->data[0].min_offset)
7869 && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
7870 && is_ssc_worth_it(pRExC_state, data.start_class))
7872 const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
7874 ssc_finalize(pRExC_state, data.start_class);
7876 Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
7877 StructCopy(data.start_class,
7878 (regnode_ssc*)RExC_rxi->data->data[n],
7880 RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
7881 RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
7882 DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
7883 regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
7884 Perl_re_printf( aTHX_
7885 "synthetic stclass \"%s\".\n",
7886 SvPVX_const(sv));});
7887 data.start_class = NULL;
7890 /* A temporary algorithm prefers floated substr to fixed one of
7891 * same length to dig more info. */
7892 i = (longest_length[0] <= longest_length[1]);
7893 RExC_rx->substrs->check_ix = i;
7894 RExC_rx->check_end_shift = RExC_rx->substrs->data[i].end_shift;
7895 RExC_rx->check_substr = RExC_rx->substrs->data[i].substr;
7896 RExC_rx->check_utf8 = RExC_rx->substrs->data[i].utf8_substr;
7897 RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset;
7898 RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset;
7899 if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS)))
7900 RExC_rx->intflags |= PREGf_NOSCAN;
7902 if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) {
7903 RExC_rx->extflags |= RXf_USE_INTUIT;
7904 if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8))
7905 RExC_rx->extflags |= RXf_INTUIT_TAIL;
7908 /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
7909 if ( (STRLEN)minlen < longest_length[1] )
7910 minlen= longest_length[1];
7911 if ( (STRLEN)minlen < longest_length[0] )
7912 minlen= longest_length[0];
7916 /* Several toplevels. Best we can is to set minlen. */
7918 regnode_ssc ch_class;
7919 SSize_t last_close = 0;
7921 DEBUG_PARSE_r(Perl_re_printf( aTHX_ "\nMulti Top Level\n"));
7923 scan = RExC_rxi->program + 1;
7924 ssc_init(pRExC_state, &ch_class);
7925 data.start_class = &ch_class;
7926 data.last_closep = &last_close;
7930 * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../
7931 * (patterns WITH top level branches)
7933 minlen = study_chunk(pRExC_state,
7934 &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL,
7935 SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied
7936 ? SCF_TRIE_DOING_RESTUDY
7940 CHECK_RESTUDY_GOTO_butfirst(NOOP);
7942 RExC_rx->check_substr = NULL;
7943 RExC_rx->check_utf8 = NULL;
7944 RExC_rx->substrs->data[0].substr = NULL;
7945 RExC_rx->substrs->data[0].utf8_substr = NULL;
7946 RExC_rx->substrs->data[1].substr = NULL;
7947 RExC_rx->substrs->data[1].utf8_substr = NULL;
7949 if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
7950 && is_ssc_worth_it(pRExC_state, data.start_class))
7952 const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
7954 ssc_finalize(pRExC_state, data.start_class);
7956 Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
7957 StructCopy(data.start_class,
7958 (regnode_ssc*)RExC_rxi->data->data[n],
7960 RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
7961 RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
7962 DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
7963 regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
7964 Perl_re_printf( aTHX_
7965 "synthetic stclass \"%s\".\n",
7966 SvPVX_const(sv));});
7967 data.start_class = NULL;
7971 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) {
7972 RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN;
7973 RExC_rx->maxlen = REG_INFTY;
7976 RExC_rx->maxlen = RExC_maxlen;
7979 /* Guard against an embedded (?=) or (?<=) with a longer minlen than
7980 the "real" pattern. */
7982 Perl_re_printf( aTHX_ "minlen: %" IVdf " RExC_rx->minlen:%" IVdf " maxlen:%" IVdf "\n",
7983 (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen);
7985 RExC_rx->minlenret = minlen;
7986 if (RExC_rx->minlen < minlen)
7987 RExC_rx->minlen = minlen;
7989 if (RExC_seen & REG_RECURSE_SEEN ) {
7990 RExC_rx->intflags |= PREGf_RECURSE_SEEN;
7991 Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *);
7993 if (RExC_seen & REG_GPOS_SEEN)
7994 RExC_rx->intflags |= PREGf_GPOS_SEEN;
7995 if (RExC_seen & REG_LOOKBEHIND_SEEN)
7996 RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the
7998 if (pRExC_state->code_blocks)
7999 RExC_rx->extflags |= RXf_EVAL_SEEN;
8000 if (RExC_seen & REG_VERBARG_SEEN)
8002 RExC_rx->intflags |= PREGf_VERBARG_SEEN;
8003 RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */
8005 if (RExC_seen & REG_CUTGROUP_SEEN)
8006 RExC_rx->intflags |= PREGf_CUTGROUP_SEEN;
8007 if (pm_flags & PMf_USE_RE_EVAL)
8008 RExC_rx->intflags |= PREGf_USE_RE_EVAL;
8009 if (RExC_paren_names)
8010 RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
8012 RXp_PAREN_NAMES(RExC_rx) = NULL;
8014 /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED
8015 * so it can be used in pp.c */
8016 if (RExC_rx->intflags & PREGf_ANCH)
8017 RExC_rx->extflags |= RXf_IS_ANCHORED;
8021 /* this is used to identify "special" patterns that might result
8022 * in Perl NOT calling the regex engine and instead doing the match "itself",
8023 * particularly special cases in split//. By having the regex compiler
8024 * do this pattern matching at a regop level (instead of by inspecting the pattern)
8025 * we avoid weird issues with equivalent patterns resulting in different behavior,
8026 * AND we allow non Perl engines to get the same optimizations by the setting the
8027 * flags appropriately - Yves */
8028 regnode *first = RExC_rxi->program + 1;
8030 regnode *next = regnext(first);
8033 if (PL_regkind[fop] == NOTHING && nop == END)
8034 RExC_rx->extflags |= RXf_NULL;
8035 else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END)
8036 /* when fop is SBOL first->flags will be true only when it was
8037 * produced by parsing /\A/, and not when parsing /^/. This is
8038 * very important for the split code as there we want to
8039 * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m.
8040 * See rt #122761 for more details. -- Yves */
8041 RExC_rx->extflags |= RXf_START_ONLY;
8042 else if (fop == PLUS
8043 && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE
8045 RExC_rx->extflags |= RXf_WHITE;
8046 else if ( RExC_rx->extflags & RXf_SPLIT
8047 && (fop == EXACT || fop == EXACTL)
8048 && STR_LEN(first) == 1
8049 && *(STRING(first)) == ' '
8051 RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
8055 if (RExC_contains_locale) {
8056 RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED;
8060 if (RExC_paren_names) {
8061 RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a"));
8062 RExC_rxi->data->data[RExC_rxi->name_list_idx]
8063 = (void*)SvREFCNT_inc(RExC_paren_name_list);
8066 RExC_rxi->name_list_idx = 0;
8068 while ( RExC_recurse_count > 0 ) {
8069 const regnode *scan = RExC_recurse[ --RExC_recurse_count ];
8071 * This data structure is set up in study_chunk() and is used
8072 * to calculate the distance between a GOSUB regopcode and
8073 * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's)
8076 * If for some reason someone writes code that optimises
8077 * away a GOSUB opcode then the assert should be changed to
8078 * an if(scan) to guard the ARG2L_SET() - Yves
8081 assert(scan && OP(scan) == GOSUB);
8082 ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan));
8085 Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair);
8086 /* assume we don't need to swap parens around before we match */
8088 Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n",
8089 (unsigned long)RExC_study_chunk_recursed_count);
8093 Perl_re_printf( aTHX_ "Final program:\n");
8097 if (RExC_open_parens) {
8098 Safefree(RExC_open_parens);
8099 RExC_open_parens = NULL;
8101 if (RExC_close_parens) {
8102 Safefree(RExC_close_parens);
8103 RExC_close_parens = NULL;
8107 /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated
8108 * by setting the regexp SV to readonly-only instead. If the
8109 * pattern's been recompiled, the USEDness should remain. */
8110 if (old_re && SvREADONLY(old_re))
8118 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
8121 PERL_ARGS_ASSERT_REG_NAMED_BUFF;
8123 PERL_UNUSED_ARG(value);
8125 if (flags & RXapif_FETCH) {
8126 return reg_named_buff_fetch(rx, key, flags);
8127 } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
8128 Perl_croak_no_modify();
8130 } else if (flags & RXapif_EXISTS) {
8131 return reg_named_buff_exists(rx, key, flags)
8134 } else if (flags & RXapif_REGNAMES) {
8135 return reg_named_buff_all(rx, flags);
8136 } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
8137 return reg_named_buff_scalar(rx, flags);
8139 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
8145 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
8148 PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
8149 PERL_UNUSED_ARG(lastkey);
8151 if (flags & RXapif_FIRSTKEY)
8152 return reg_named_buff_firstkey(rx, flags);
8153 else if (flags & RXapif_NEXTKEY)
8154 return reg_named_buff_nextkey(rx, flags);
8156 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter",
8163 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
8167 struct regexp *const rx = ReANY(r);
8169 PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
8171 if (rx && RXp_PAREN_NAMES(rx)) {
8172 HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
8175 SV* sv_dat=HeVAL(he_str);
8176 I32 *nums=(I32*)SvPVX(sv_dat);
8177 AV * const retarray = (flags & RXapif_ALL) ? newAV() : NULL;
8178 for ( i=0; i<SvIVX(sv_dat); i++ ) {
8179 if ((I32)(rx->nparens) >= nums[i]
8180 && rx->offs[nums[i]].start != -1
8181 && rx->offs[nums[i]].end != -1)
8184 CALLREG_NUMBUF_FETCH(r, nums[i], ret);
8189 ret = newSVsv(&PL_sv_undef);
8192 av_push(retarray, ret);
8195 return newRV_noinc(MUTABLE_SV(retarray));
8202 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
8205 struct regexp *const rx = ReANY(r);
8207 PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
8209 if (rx && RXp_PAREN_NAMES(rx)) {
8210 if (flags & RXapif_ALL) {
8211 return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
8213 SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
8215 SvREFCNT_dec_NN(sv);
8227 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
8229 struct regexp *const rx = ReANY(r);
8231 PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
8233 if ( rx && RXp_PAREN_NAMES(rx) ) {
8234 (void)hv_iterinit(RXp_PAREN_NAMES(rx));
8236 return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
8243 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
8245 struct regexp *const rx = ReANY(r);
8246 GET_RE_DEBUG_FLAGS_DECL;
8248 PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
8250 if (rx && RXp_PAREN_NAMES(rx)) {
8251 HV *hv = RXp_PAREN_NAMES(rx);
8253 while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8256 SV* sv_dat = HeVAL(temphe);
8257 I32 *nums = (I32*)SvPVX(sv_dat);
8258 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8259 if ((I32)(rx->lastparen) >= nums[i] &&
8260 rx->offs[nums[i]].start != -1 &&
8261 rx->offs[nums[i]].end != -1)
8267 if (parno || flags & RXapif_ALL) {
8268 return newSVhek(HeKEY_hek(temphe));
8276 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
8281 struct regexp *const rx = ReANY(r);
8283 PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
8285 if (rx && RXp_PAREN_NAMES(rx)) {
8286 if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
8287 return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
8288 } else if (flags & RXapif_ONE) {
8289 ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
8290 av = MUTABLE_AV(SvRV(ret));
8291 length = av_tindex(av);
8292 SvREFCNT_dec_NN(ret);
8293 return newSViv(length + 1);
8295 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar",
8300 return &PL_sv_undef;
8304 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
8306 struct regexp *const rx = ReANY(r);
8309 PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
8311 if (rx && RXp_PAREN_NAMES(rx)) {
8312 HV *hv= RXp_PAREN_NAMES(rx);
8314 (void)hv_iterinit(hv);
8315 while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8318 SV* sv_dat = HeVAL(temphe);
8319 I32 *nums = (I32*)SvPVX(sv_dat);
8320 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8321 if ((I32)(rx->lastparen) >= nums[i] &&
8322 rx->offs[nums[i]].start != -1 &&
8323 rx->offs[nums[i]].end != -1)
8329 if (parno || flags & RXapif_ALL) {
8330 av_push(av, newSVhek(HeKEY_hek(temphe)));
8335 return newRV_noinc(MUTABLE_SV(av));
8339 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
8342 struct regexp *const rx = ReANY(r);
8348 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
8350 if ( n == RX_BUFF_IDX_CARET_PREMATCH
8351 || n == RX_BUFF_IDX_CARET_FULLMATCH
8352 || n == RX_BUFF_IDX_CARET_POSTMATCH
8355 bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8357 /* on something like
8360 * the KEEPCOPY is set on the PMOP rather than the regex */
8361 if (PL_curpm && r == PM_GETRE(PL_curpm))
8362 keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8371 if (n == RX_BUFF_IDX_CARET_FULLMATCH)
8372 /* no need to distinguish between them any more */
8373 n = RX_BUFF_IDX_FULLMATCH;
8375 if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
8376 && rx->offs[0].start != -1)
8378 /* $`, ${^PREMATCH} */
8379 i = rx->offs[0].start;
8383 if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
8384 && rx->offs[0].end != -1)
8386 /* $', ${^POSTMATCH} */
8387 s = rx->subbeg - rx->suboffset + rx->offs[0].end;
8388 i = rx->sublen + rx->suboffset - rx->offs[0].end;
8391 if ( 0 <= n && n <= (I32)rx->nparens &&
8392 (s1 = rx->offs[n].start) != -1 &&
8393 (t1 = rx->offs[n].end) != -1)
8395 /* $&, ${^MATCH}, $1 ... */
8397 s = rx->subbeg + s1 - rx->suboffset;
8402 assert(s >= rx->subbeg);
8403 assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) );
8405 #ifdef NO_TAINT_SUPPORT
8406 sv_setpvn(sv, s, i);
8408 const int oldtainted = TAINT_get;
8410 sv_setpvn(sv, s, i);
8411 TAINT_set(oldtainted);
8413 if (RXp_MATCH_UTF8(rx))
8418 if (RXp_MATCH_TAINTED(rx)) {
8419 if (SvTYPE(sv) >= SVt_PVMG) {
8420 MAGIC* const mg = SvMAGIC(sv);
8423 SvMAGIC_set(sv, mg->mg_moremagic);
8425 if ((mgt = SvMAGIC(sv))) {
8426 mg->mg_moremagic = mgt;
8427 SvMAGIC_set(sv, mg);
8444 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
8445 SV const * const value)
8447 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
8449 PERL_UNUSED_ARG(rx);
8450 PERL_UNUSED_ARG(paren);
8451 PERL_UNUSED_ARG(value);
8454 Perl_croak_no_modify();
8458 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
8461 struct regexp *const rx = ReANY(r);
8465 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
8467 if ( paren == RX_BUFF_IDX_CARET_PREMATCH
8468 || paren == RX_BUFF_IDX_CARET_FULLMATCH
8469 || paren == RX_BUFF_IDX_CARET_POSTMATCH
8472 bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8474 /* on something like
8477 * the KEEPCOPY is set on the PMOP rather than the regex */
8478 if (PL_curpm && r == PM_GETRE(PL_curpm))
8479 keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8485 /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
8487 case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
8488 case RX_BUFF_IDX_PREMATCH: /* $` */
8489 if (rx->offs[0].start != -1) {
8490 i = rx->offs[0].start;
8499 case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
8500 case RX_BUFF_IDX_POSTMATCH: /* $' */
8501 if (rx->offs[0].end != -1) {
8502 i = rx->sublen - rx->offs[0].end;
8504 s1 = rx->offs[0].end;
8511 default: /* $& / ${^MATCH}, $1, $2, ... */
8512 if (paren <= (I32)rx->nparens &&
8513 (s1 = rx->offs[paren].start) != -1 &&
8514 (t1 = rx->offs[paren].end) != -1)
8520 if (ckWARN(WARN_UNINITIALIZED))
8521 report_uninit((const SV *)sv);
8526 if (i > 0 && RXp_MATCH_UTF8(rx)) {
8527 const char * const s = rx->subbeg - rx->suboffset + s1;
8532 if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
8539 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
8541 PERL_ARGS_ASSERT_REG_QR_PACKAGE;
8542 PERL_UNUSED_ARG(rx);
8546 return newSVpvs("Regexp");
8549 /* Scans the name of a named buffer from the pattern.
8550 * If flags is REG_RSN_RETURN_NULL returns null.
8551 * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
8552 * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
8553 * to the parsed name as looked up in the RExC_paren_names hash.
8554 * If there is an error throws a vFAIL().. type exception.
8557 #define REG_RSN_RETURN_NULL 0
8558 #define REG_RSN_RETURN_NAME 1
8559 #define REG_RSN_RETURN_DATA 2
8562 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
8564 char *name_start = RExC_parse;
8567 PERL_ARGS_ASSERT_REG_SCAN_NAME;
8569 assert (RExC_parse <= RExC_end);
8570 if (RExC_parse == RExC_end) NOOP;
8571 else if (isIDFIRST_lazy_if_safe(RExC_parse, RExC_end, UTF)) {
8572 /* Note that the code here assumes well-formed UTF-8. Skip IDFIRST by
8573 * using do...while */
8576 RExC_parse += UTF8SKIP(RExC_parse);
8577 } while ( RExC_parse < RExC_end
8578 && isWORDCHAR_utf8_safe((U8*)RExC_parse, (U8*) RExC_end));
8582 } while (RExC_parse < RExC_end && isWORDCHAR(*RExC_parse));
8584 RExC_parse++; /* so the <- from the vFAIL is after the offending
8586 vFAIL("Group name must start with a non-digit word character");
8588 sv_name = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
8589 SVs_TEMP | (UTF ? SVf_UTF8 : 0));
8590 if ( flags == REG_RSN_RETURN_NAME)
8592 else if (flags==REG_RSN_RETURN_DATA) {
8595 if ( ! sv_name ) /* should not happen*/
8596 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
8597 if (RExC_paren_names)
8598 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
8600 sv_dat = HeVAL(he_str);
8601 if ( ! sv_dat ) { /* Didn't find group */
8603 /* It might be a forward reference; we can't fail until we
8604 * know, by completing the parse to get all the groups, and
8606 if (RExC_total_parens > 0) {
8607 vFAIL("Reference to nonexistent named group");
8610 REQUIRE_PARENS_PASS;
8616 Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
8617 (unsigned long) flags);
8620 #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
8622 if (RExC_lastparse!=RExC_parse) { \
8623 Perl_re_printf( aTHX_ "%s", \
8624 Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse, \
8625 RExC_end - RExC_parse, 16, \
8627 PERL_PV_ESCAPE_UNI_DETECT | \
8628 PERL_PV_PRETTY_ELLIPSES | \
8629 PERL_PV_PRETTY_LTGT | \
8630 PERL_PV_ESCAPE_RE | \
8631 PERL_PV_PRETTY_EXACTSIZE \
8635 Perl_re_printf( aTHX_ "%16s",""); \
8637 num=REG_NODE_NUM(REGNODE_p(RExC_emit)); \
8638 if (RExC_lastnum!=num) \
8639 Perl_re_printf( aTHX_ "|%4d", num); \
8641 Perl_re_printf( aTHX_ "|%4s",""); \
8642 Perl_re_printf( aTHX_ "|%*s%-4s", \
8643 (int)((depth*2)), "", \
8647 RExC_lastparse=RExC_parse; \
8652 #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
8653 DEBUG_PARSE_MSG((funcname)); \
8654 Perl_re_printf( aTHX_ "%4s","\n"); \
8656 #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({\
8657 DEBUG_PARSE_MSG((funcname)); \
8658 Perl_re_printf( aTHX_ fmt "\n",args); \
8661 /* This section of code defines the inversion list object and its methods. The
8662 * interfaces are highly subject to change, so as much as possible is static to
8663 * this file. An inversion list is here implemented as a malloc'd C UV array
8664 * as an SVt_INVLIST scalar.
8666 * An inversion list for Unicode is an array of code points, sorted by ordinal
8667 * number. Each element gives the code point that begins a range that extends
8668 * up-to but not including the code point given by the next element. The final
8669 * element gives the first code point of a range that extends to the platform's
8670 * infinity. The even-numbered elements (invlist[0], invlist[2], invlist[4],
8671 * ...) give ranges whose code points are all in the inversion list. We say
8672 * that those ranges are in the set. The odd-numbered elements give ranges
8673 * whose code points are not in the inversion list, and hence not in the set.
8674 * Thus, element [0] is the first code point in the list. Element [1]
8675 * is the first code point beyond that not in the list; and element [2] is the
8676 * first code point beyond that that is in the list. In other words, the first
8677 * range is invlist[0]..(invlist[1]-1), and all code points in that range are
8678 * in the inversion list. The second range is invlist[1]..(invlist[2]-1), and
8679 * all code points in that range are not in the inversion list. The third
8680 * range invlist[2]..(invlist[3]-1) gives code points that are in the inversion
8681 * list, and so forth. Thus every element whose index is divisible by two
8682 * gives the beginning of a range that is in the list, and every element whose
8683 * index is not divisible by two gives the beginning of a range not in the
8684 * list. If the final element's index is divisible by two, the inversion list
8685 * extends to the platform's infinity; otherwise the highest code point in the
8686 * inversion list is the contents of that element minus 1.
8688 * A range that contains just a single code point N will look like
8690 * invlist[i+1] == N+1
8692 * If N is UV_MAX (the highest representable code point on the machine), N+1 is
8693 * impossible to represent, so element [i+1] is omitted. The single element
8695 * invlist[0] == UV_MAX
8696 * contains just UV_MAX, but is interpreted as matching to infinity.
8698 * Taking the complement (inverting) an inversion list is quite simple, if the
8699 * first element is 0, remove it; otherwise add a 0 element at the beginning.
8700 * This implementation reserves an element at the beginning of each inversion
8701 * list to always contain 0; there is an additional flag in the header which
8702 * indicates if the list begins at the 0, or is offset to begin at the next
8703 * element. This means that the inversion list can be inverted without any
8704 * copying; just flip the flag.
8706 * More about inversion lists can be found in "Unicode Demystified"
8707 * Chapter 13 by Richard Gillam, published by Addison-Wesley.
8709 * The inversion list data structure is currently implemented as an SV pointing
8710 * to an array of UVs that the SV thinks are bytes. This allows us to have an
8711 * array of UV whose memory management is automatically handled by the existing
8712 * facilities for SV's.
8714 * Some of the methods should always be private to the implementation, and some
8715 * should eventually be made public */
8717 /* The header definitions are in F<invlist_inline.h> */
8719 #ifndef PERL_IN_XSUB_RE
8721 PERL_STATIC_INLINE UV*
8722 S__invlist_array_init(SV* const invlist, const bool will_have_0)
8724 /* Returns a pointer to the first element in the inversion list's array.
8725 * This is called upon initialization of an inversion list. Where the
8726 * array begins depends on whether the list has the code point U+0000 in it
8727 * or not. The other parameter tells it whether the code that follows this
8728 * call is about to put a 0 in the inversion list or not. The first
8729 * element is either the element reserved for 0, if TRUE, or the element
8730 * after it, if FALSE */
8732 bool* offset = get_invlist_offset_addr(invlist);
8733 UV* zero_addr = (UV *) SvPVX(invlist);
8735 PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
8738 assert(! _invlist_len(invlist));
8742 /* 1^1 = 0; 1^0 = 1 */
8743 *offset = 1 ^ will_have_0;
8744 return zero_addr + *offset;
8747 PERL_STATIC_INLINE void
8748 S_invlist_set_len(pTHX_ SV* const invlist, const UV len, const bool offset)
8750 /* Sets the current number of elements stored in the inversion list.
8751 * Updates SvCUR correspondingly */
8752 PERL_UNUSED_CONTEXT;
8753 PERL_ARGS_ASSERT_INVLIST_SET_LEN;
8755 assert(is_invlist(invlist));
8760 : TO_INTERNAL_SIZE(len + offset));
8761 assert(SvLEN(invlist) == 0 || SvCUR(invlist) <= SvLEN(invlist));
8765 S_invlist_replace_list_destroys_src(pTHX_ SV * dest, SV * src)
8767 /* Replaces the inversion list in 'dest' with the one from 'src'. It
8768 * steals the list from 'src', so 'src' is made to have a NULL list. This
8769 * is similar to what SvSetMagicSV() would do, if it were implemented on
8770 * inversion lists, though this routine avoids a copy */
8772 const UV src_len = _invlist_len(src);
8773 const bool src_offset = *get_invlist_offset_addr(src);
8774 const STRLEN src_byte_len = SvLEN(src);
8775 char * array = SvPVX(src);
8777 const int oldtainted = TAINT_get;
8779 PERL_ARGS_ASSERT_INVLIST_REPLACE_LIST_DESTROYS_SRC;
8781 assert(is_invlist(src));
8782 assert(is_invlist(dest));
8783 assert(! invlist_is_iterating(src));
8784 assert(SvCUR(src) == 0 || SvCUR(src) < SvLEN(src));
8786 /* Make sure it ends in the right place with a NUL, as our inversion list
8787 * manipulations aren't careful to keep this true, but sv_usepvn_flags()
8789 array[src_byte_len - 1] = '\0';
8791 TAINT_NOT; /* Otherwise it breaks */
8792 sv_usepvn_flags(dest,
8796 /* This flag is documented to cause a copy to be avoided */
8797 SV_HAS_TRAILING_NUL);
8798 TAINT_set(oldtainted);
8803 /* Finish up copying over the other fields in an inversion list */
8804 *get_invlist_offset_addr(dest) = src_offset;
8805 invlist_set_len(dest, src_len, src_offset);
8806 *get_invlist_previous_index_addr(dest) = 0;
8807 invlist_iterfinish(dest);
8810 PERL_STATIC_INLINE IV*
8811 S_get_invlist_previous_index_addr(SV* invlist)
8813 /* Return the address of the IV that is reserved to hold the cached index
8815 PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
8817 assert(is_invlist(invlist));
8819 return &(((XINVLIST*) SvANY(invlist))->prev_index);
8822 PERL_STATIC_INLINE IV
8823 S_invlist_previous_index(SV* const invlist)
8825 /* Returns cached index of previous search */
8827 PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
8829 return *get_invlist_previous_index_addr(invlist);
8832 PERL_STATIC_INLINE void
8833 S_invlist_set_previous_index(SV* const invlist, const IV index)
8835 /* Caches <index> for later retrieval */
8837 PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
8839 assert(index == 0 || index < (int) _invlist_len(invlist));
8841 *get_invlist_previous_index_addr(invlist) = index;
8844 PERL_STATIC_INLINE void
8845 S_invlist_trim(SV* invlist)
8847 /* Free the not currently-being-used space in an inversion list */
8849 /* But don't free up the space needed for the 0 UV that is always at the
8850 * beginning of the list, nor the trailing NUL */
8851 const UV min_size = TO_INTERNAL_SIZE(1) + 1;
8853 PERL_ARGS_ASSERT_INVLIST_TRIM;
8855 assert(is_invlist(invlist));
8857 SvPV_renew(invlist, MAX(min_size, SvCUR(invlist) + 1));
8860 PERL_STATIC_INLINE void
8861 S_invlist_clear(pTHX_ SV* invlist) /* Empty the inversion list */
8863 PERL_ARGS_ASSERT_INVLIST_CLEAR;
8865 assert(is_invlist(invlist));
8867 invlist_set_len(invlist, 0, 0);
8868 invlist_trim(invlist);
8871 #endif /* ifndef PERL_IN_XSUB_RE */
8873 PERL_STATIC_INLINE bool
8874 S_invlist_is_iterating(SV* const invlist)
8876 PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
8878 return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX;
8881 #ifndef PERL_IN_XSUB_RE
8883 PERL_STATIC_INLINE UV
8884 S_invlist_max(SV* const invlist)
8886 /* Returns the maximum number of elements storable in the inversion list's
8887 * array, without having to realloc() */
8889 PERL_ARGS_ASSERT_INVLIST_MAX;
8891 assert(is_invlist(invlist));
8893 /* Assumes worst case, in which the 0 element is not counted in the
8894 * inversion list, so subtracts 1 for that */
8895 return SvLEN(invlist) == 0 /* This happens under _new_invlist_C_array */
8896 ? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1
8897 : FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1;
8901 S_initialize_invlist_guts(pTHX_ SV* invlist, const Size_t initial_size)
8903 PERL_ARGS_ASSERT_INITIALIZE_INVLIST_GUTS;
8905 /* First 1 is in case the zero element isn't in the list; second 1 is for
8907 SvGROW(invlist, TO_INTERNAL_SIZE(initial_size + 1) + 1);
8908 invlist_set_len(invlist, 0, 0);
8910 /* Force iterinit() to be used to get iteration to work */
8911 invlist_iterfinish(invlist);
8913 *get_invlist_previous_index_addr(invlist) = 0;
8917 Perl__new_invlist(pTHX_ IV initial_size)
8920 /* Return a pointer to a newly constructed inversion list, with enough
8921 * space to store 'initial_size' elements. If that number is negative, a
8922 * system default is used instead */
8926 if (initial_size < 0) {
8930 /* Allocate the initial space */
8931 new_list = newSV_type(SVt_INVLIST);
8933 initialize_invlist_guts(new_list, initial_size);
8939 Perl__new_invlist_C_array(pTHX_ const UV* const list)
8941 /* Return a pointer to a newly constructed inversion list, initialized to
8942 * point to <list>, which has to be in the exact correct inversion list
8943 * form, including internal fields. Thus this is a dangerous routine that
8944 * should not be used in the wrong hands. The passed in 'list' contains
8945 * several header fields at the beginning that are not part of the
8946 * inversion list body proper */
8948 const STRLEN length = (STRLEN) list[0];
8949 const UV version_id = list[1];
8950 const bool offset = cBOOL(list[2]);
8951 #define HEADER_LENGTH 3
8952 /* If any of the above changes in any way, you must change HEADER_LENGTH
8953 * (if appropriate) and regenerate INVLIST_VERSION_ID by running
8954 * perl -E 'say int(rand 2**31-1)'
8956 #define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and
8957 data structure type, so that one being
8958 passed in can be validated to be an
8959 inversion list of the correct vintage.
8962 SV* invlist = newSV_type(SVt_INVLIST);
8964 PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
8966 if (version_id != INVLIST_VERSION_ID) {
8967 Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
8970 /* The generated array passed in includes header elements that aren't part
8971 * of the list proper, so start it just after them */
8972 SvPV_set(invlist, (char *) (list + HEADER_LENGTH));
8974 SvLEN_set(invlist, 0); /* Means we own the contents, and the system
8975 shouldn't touch it */
8977 *(get_invlist_offset_addr(invlist)) = offset;
8979 /* The 'length' passed to us is the physical number of elements in the
8980 * inversion list. But if there is an offset the logical number is one
8982 invlist_set_len(invlist, length - offset, offset);
8984 invlist_set_previous_index(invlist, 0);
8986 /* Initialize the iteration pointer. */
8987 invlist_iterfinish(invlist);
8989 SvREADONLY_on(invlist);
8995 S_invlist_extend(pTHX_ SV* const invlist, const UV new_max)
8997 /* Grow the maximum size of an inversion list */
8999 PERL_ARGS_ASSERT_INVLIST_EXTEND;
9001 assert(is_invlist(invlist));
9003 /* Add one to account for the zero element at the beginning which may not
9004 * be counted by the calling parameters */
9005 SvGROW((SV *)invlist, TO_INTERNAL_SIZE(new_max + 1));
9009 S__append_range_to_invlist(pTHX_ SV* const invlist,
9010 const UV start, const UV end)
9012 /* Subject to change or removal. Append the range from 'start' to 'end' at
9013 * the end of the inversion list. The range must be above any existing
9017 UV max = invlist_max(invlist);
9018 UV len = _invlist_len(invlist);
9021 PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
9023 if (len == 0) { /* Empty lists must be initialized */
9024 offset = start != 0;
9025 array = _invlist_array_init(invlist, ! offset);
9028 /* Here, the existing list is non-empty. The current max entry in the
9029 * list is generally the first value not in the set, except when the
9030 * set extends to the end of permissible values, in which case it is
9031 * the first entry in that final set, and so this call is an attempt to
9032 * append out-of-order */
9034 UV final_element = len - 1;
9035 array = invlist_array(invlist);
9036 if ( array[final_element] > start
9037 || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
9039 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",
9040 array[final_element], start,
9041 ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
9044 /* Here, it is a legal append. If the new range begins 1 above the end
9045 * of the range below it, it is extending the range below it, so the
9046 * new first value not in the set is one greater than the newly
9047 * extended range. */
9048 offset = *get_invlist_offset_addr(invlist);
9049 if (array[final_element] == start) {
9050 if (end != UV_MAX) {
9051 array[final_element] = end + 1;
9054 /* But if the end is the maximum representable on the machine,
9055 * assume that infinity was actually what was meant. Just let
9056 * the range that this would extend to have no end */
9057 invlist_set_len(invlist, len - 1, offset);
9063 /* Here the new range doesn't extend any existing set. Add it */
9065 len += 2; /* Includes an element each for the start and end of range */
9067 /* If wll overflow the existing space, extend, which may cause the array to
9070 invlist_extend(invlist, len);
9072 /* Have to set len here to avoid assert failure in invlist_array() */
9073 invlist_set_len(invlist, len, offset);
9075 array = invlist_array(invlist);
9078 invlist_set_len(invlist, len, offset);
9081 /* The next item on the list starts the range, the one after that is
9082 * one past the new range. */
9083 array[len - 2] = start;
9084 if (end != UV_MAX) {
9085 array[len - 1] = end + 1;
9088 /* But if the end is the maximum representable on the machine, just let
9089 * the range have no end */
9090 invlist_set_len(invlist, len - 1, offset);
9095 Perl__invlist_search(SV* const invlist, const UV cp)
9097 /* Searches the inversion list for the entry that contains the input code
9098 * point <cp>. If <cp> is not in the list, -1 is returned. Otherwise, the
9099 * return value is the index into the list's array of the range that
9100 * contains <cp>, that is, 'i' such that
9101 * array[i] <= cp < array[i+1]
9106 IV high = _invlist_len(invlist);
9107 const IV highest_element = high - 1;
9110 PERL_ARGS_ASSERT__INVLIST_SEARCH;
9112 /* If list is empty, return failure. */
9117 /* (We can't get the array unless we know the list is non-empty) */
9118 array = invlist_array(invlist);
9120 mid = invlist_previous_index(invlist);
9122 if (mid > highest_element) {
9123 mid = highest_element;
9126 /* <mid> contains the cache of the result of the previous call to this
9127 * function (0 the first time). See if this call is for the same result,
9128 * or if it is for mid-1. This is under the theory that calls to this
9129 * function will often be for related code points that are near each other.
9130 * And benchmarks show that caching gives better results. We also test
9131 * here if the code point is within the bounds of the list. These tests
9132 * replace others that would have had to be made anyway to make sure that
9133 * the array bounds were not exceeded, and these give us extra information
9134 * at the same time */
9135 if (cp >= array[mid]) {
9136 if (cp >= array[highest_element]) {
9137 return highest_element;
9140 /* Here, array[mid] <= cp < array[highest_element]. This means that
9141 * the final element is not the answer, so can exclude it; it also
9142 * means that <mid> is not the final element, so can refer to 'mid + 1'
9144 if (cp < array[mid + 1]) {
9150 else { /* cp < aray[mid] */
9151 if (cp < array[0]) { /* Fail if outside the array */
9155 if (cp >= array[mid - 1]) {
9160 /* Binary search. What we are looking for is <i> such that
9161 * array[i] <= cp < array[i+1]
9162 * The loop below converges on the i+1. Note that there may not be an
9163 * (i+1)th element in the array, and things work nonetheless */
9164 while (low < high) {
9165 mid = (low + high) / 2;
9166 assert(mid <= highest_element);
9167 if (array[mid] <= cp) { /* cp >= array[mid] */
9170 /* We could do this extra test to exit the loop early.
9171 if (cp < array[low]) {
9176 else { /* cp < array[mid] */
9183 invlist_set_previous_index(invlist, high);
9188 Perl__invlist_populate_swatch(SV* const invlist,
9189 const UV start, const UV end, U8* swatch)
9191 /* populates a swatch of a swash the same way swatch_get() does in utf8.c,
9192 * but is used when the swash has an inversion list. This makes this much
9193 * faster, as it uses a binary search instead of a linear one. This is
9194 * intimately tied to that function, and perhaps should be in utf8.c,
9195 * except it is intimately tied to inversion lists as well. It assumes
9196 * that <swatch> is all 0's on input */
9199 const IV len = _invlist_len(invlist);
9203 PERL_ARGS_ASSERT__INVLIST_POPULATE_SWATCH;
9205 if (len == 0) { /* Empty inversion list */
9209 array = invlist_array(invlist);
9211 /* Find which element it is */
9212 i = _invlist_search(invlist, start);
9214 /* We populate from <start> to <end> */
9215 while (current < end) {
9218 /* The inversion list gives the results for every possible code point
9219 * after the first one in the list. Only those ranges whose index is
9220 * even are ones that the inversion list matches. For the odd ones,
9221 * and if the initial code point is not in the list, we have to skip
9222 * forward to the next element */
9223 if (i == -1 || ! ELEMENT_RANGE_MATCHES_INVLIST(i)) {
9225 if (i >= len) { /* Finished if beyond the end of the array */
9229 if (current >= end) { /* Finished if beyond the end of what we
9231 if (LIKELY(end < UV_MAX)) {
9235 /* We get here when the upper bound is the maximum
9236 * representable on the machine, and we are looking for just
9237 * that code point. Have to special case it */
9239 goto join_end_of_list;
9242 assert(current >= start);
9244 /* The current range ends one below the next one, except don't go past
9247 upper = (i < len && array[i] < end) ? array[i] : end;
9249 /* Here we are in a range that matches. Populate a bit in the 3-bit U8
9250 * for each code point in it */
9251 for (; current < upper; current++) {
9252 const STRLEN offset = (STRLEN)(current - start);
9253 swatch[offset >> 3] |= 1 << (offset & 7);
9258 /* Quit if at the end of the list */
9261 /* But first, have to deal with the highest possible code point on
9262 * the platform. The previous code assumes that <end> is one
9263 * beyond where we want to populate, but that is impossible at the
9264 * platform's infinity, so have to handle it specially */
9265 if (UNLIKELY(end == UV_MAX && ELEMENT_RANGE_MATCHES_INVLIST(len-1)))
9267 const STRLEN offset = (STRLEN)(end - start);
9268 swatch[offset >> 3] |= 1 << (offset & 7);
9273 /* Advance to the next range, which will be for code points not in the
9282 Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9283 const bool complement_b, SV** output)
9285 /* Take the union of two inversion lists and point '*output' to it. On
9286 * input, '*output' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9287 * even 'a' or 'b'). If to an inversion list, the contents of the original
9288 * list will be replaced by the union. The first list, 'a', may be
9289 * NULL, in which case a copy of the second list is placed in '*output'.
9290 * If 'complement_b' is TRUE, the union is taken of the complement
9291 * (inversion) of 'b' instead of b itself.
9293 * The basis for this comes from "Unicode Demystified" Chapter 13 by
9294 * Richard Gillam, published by Addison-Wesley, and explained at some
9295 * length there. The preface says to incorporate its examples into your
9296 * code at your own risk.
9298 * The algorithm is like a merge sort. */
9300 const UV* array_a; /* a's array */
9302 UV len_a; /* length of a's array */
9305 SV* u; /* the resulting union */
9309 UV i_a = 0; /* current index into a's array */
9313 /* running count, as explained in the algorithm source book; items are
9314 * stopped accumulating and are output when the count changes to/from 0.
9315 * The count is incremented when we start a range that's in an input's set,
9316 * and decremented when we start a range that's not in a set. So this
9317 * variable can be 0, 1, or 2. When it is 0 neither input is in their set,
9318 * and hence nothing goes into the union; 1, just one of the inputs is in
9319 * its set (and its current range gets added to the union); and 2 when both
9320 * inputs are in their sets. */
9323 PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
9325 assert(*output == NULL || is_invlist(*output));
9327 len_b = _invlist_len(b);
9330 /* Here, 'b' is empty, hence it's complement is all possible code
9331 * points. So if the union includes the complement of 'b', it includes
9332 * everything, and we need not even look at 'a'. It's easiest to
9333 * create a new inversion list that matches everything. */
9335 SV* everything = _add_range_to_invlist(NULL, 0, UV_MAX);
9337 if (*output == NULL) { /* If the output didn't exist, just point it
9339 *output = everything;
9341 else { /* Otherwise, replace its contents with the new list */
9342 invlist_replace_list_destroys_src(*output, everything);
9343 SvREFCNT_dec_NN(everything);
9349 /* Here, we don't want the complement of 'b', and since 'b' is empty,
9350 * the union will come entirely from 'a'. If 'a' is NULL or empty, the
9351 * output will be empty */
9353 if (a == NULL || _invlist_len(a) == 0) {
9354 if (*output == NULL) {
9355 *output = _new_invlist(0);
9358 invlist_clear(*output);
9363 /* Here, 'a' is not empty, but 'b' is, so 'a' entirely determines the
9364 * union. We can just return a copy of 'a' if '*output' doesn't point
9365 * to an existing list */
9366 if (*output == NULL) {
9367 *output = invlist_clone(a, NULL);
9371 /* If the output is to overwrite 'a', we have a no-op, as it's
9377 /* Here, '*output' is to be overwritten by 'a' */
9378 u = invlist_clone(a, NULL);
9379 invlist_replace_list_destroys_src(*output, u);
9385 /* Here 'b' is not empty. See about 'a' */
9387 if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
9389 /* Here, 'a' is empty (and b is not). That means the union will come
9390 * entirely from 'b'. If '*output' is NULL, we can directly return a
9391 * clone of 'b'. Otherwise, we replace the contents of '*output' with
9394 SV ** dest = (*output == NULL) ? output : &u;
9395 *dest = invlist_clone(b, NULL);
9397 _invlist_invert(*dest);
9401 invlist_replace_list_destroys_src(*output, u);
9408 /* Here both lists exist and are non-empty */
9409 array_a = invlist_array(a);
9410 array_b = invlist_array(b);
9412 /* If are to take the union of 'a' with the complement of b, set it
9413 * up so are looking at b's complement. */
9416 /* To complement, we invert: if the first element is 0, remove it. To
9417 * do this, we just pretend the array starts one later */
9418 if (array_b[0] == 0) {
9424 /* But if the first element is not zero, we pretend the list starts
9425 * at the 0 that is always stored immediately before the array. */
9431 /* Size the union for the worst case: that the sets are completely
9433 u = _new_invlist(len_a + len_b);
9435 /* Will contain U+0000 if either component does */
9436 array_u = _invlist_array_init(u, ( len_a > 0 && array_a[0] == 0)
9437 || (len_b > 0 && array_b[0] == 0));
9439 /* Go through each input list item by item, stopping when have exhausted
9441 while (i_a < len_a && i_b < len_b) {
9442 UV cp; /* The element to potentially add to the union's array */
9443 bool cp_in_set; /* is it in the the input list's set or not */
9445 /* We need to take one or the other of the two inputs for the union.
9446 * Since we are merging two sorted lists, we take the smaller of the
9447 * next items. In case of a tie, we take first the one that is in its
9448 * set. If we first took the one not in its set, it would decrement
9449 * the count, possibly to 0 which would cause it to be output as ending
9450 * the range, and the next time through we would take the same number,
9451 * and output it again as beginning the next range. By doing it the
9452 * opposite way, there is no possibility that the count will be
9453 * momentarily decremented to 0, and thus the two adjoining ranges will
9454 * be seamlessly merged. (In a tie and both are in the set or both not
9455 * in the set, it doesn't matter which we take first.) */
9456 if ( array_a[i_a] < array_b[i_b]
9457 || ( array_a[i_a] == array_b[i_b]
9458 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9460 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9461 cp = array_a[i_a++];
9464 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9465 cp = array_b[i_b++];
9468 /* Here, have chosen which of the two inputs to look at. Only output
9469 * if the running count changes to/from 0, which marks the
9470 * beginning/end of a range that's in the set */
9473 array_u[i_u++] = cp;
9480 array_u[i_u++] = cp;
9486 /* The loop above increments the index into exactly one of the input lists
9487 * each iteration, and ends when either index gets to its list end. That
9488 * means the other index is lower than its end, and so something is
9489 * remaining in that one. We decrement 'count', as explained below, if
9490 * that list is in its set. (i_a and i_b each currently index the element
9491 * beyond the one we care about.) */
9492 if ( (i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9493 || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9498 /* Above we decremented 'count' if the list that had unexamined elements in
9499 * it was in its set. This has made it so that 'count' being non-zero
9500 * means there isn't anything left to output; and 'count' equal to 0 means
9501 * that what is left to output is precisely that which is left in the
9502 * non-exhausted input list.
9504 * To see why, note first that the exhausted input obviously has nothing
9505 * left to add to the union. If it was in its set at its end, that means
9506 * the set extends from here to the platform's infinity, and hence so does
9507 * the union and the non-exhausted set is irrelevant. The exhausted set
9508 * also contributed 1 to 'count'. If 'count' was 2, it got decremented to
9509 * 1, but if it was 1, the non-exhausted set wasn't in its set, and so
9510 * 'count' remains at 1. This is consistent with the decremented 'count'
9511 * != 0 meaning there's nothing left to add to the union.
9513 * But if the exhausted input wasn't in its set, it contributed 0 to
9514 * 'count', and the rest of the union will be whatever the other input is.
9515 * If 'count' was 0, neither list was in its set, and 'count' remains 0;
9516 * otherwise it gets decremented to 0. This is consistent with 'count'
9517 * == 0 meaning the remainder of the union is whatever is left in the
9518 * non-exhausted list. */
9523 IV copy_count = len_a - i_a;
9524 if (copy_count > 0) { /* The non-exhausted input is 'a' */
9525 Copy(array_a + i_a, array_u + i_u, copy_count, UV);
9527 else { /* The non-exhausted input is b */
9528 copy_count = len_b - i_b;
9529 Copy(array_b + i_b, array_u + i_u, copy_count, UV);
9531 len_u = i_u + copy_count;
9534 /* Set the result to the final length, which can change the pointer to
9535 * array_u, so re-find it. (Note that it is unlikely that this will
9536 * change, as we are shrinking the space, not enlarging it) */
9537 if (len_u != _invlist_len(u)) {
9538 invlist_set_len(u, len_u, *get_invlist_offset_addr(u));
9540 array_u = invlist_array(u);
9543 if (*output == NULL) { /* Simply return the new inversion list */
9547 /* Otherwise, overwrite the inversion list that was in '*output'. We
9548 * could instead free '*output', and then set it to 'u', but experience
9549 * has shown [perl #127392] that if the input is a mortal, we can get a
9550 * huge build-up of these during regex compilation before they get
9552 invlist_replace_list_destroys_src(*output, u);
9560 Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9561 const bool complement_b, SV** i)
9563 /* Take the intersection of two inversion lists and point '*i' to it. On
9564 * input, '*i' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9565 * even 'a' or 'b'). If to an inversion list, the contents of the original
9566 * list will be replaced by the intersection. The first list, 'a', may be
9567 * NULL, in which case '*i' will be an empty list. If 'complement_b' is
9568 * TRUE, the result will be the intersection of 'a' and the complement (or
9569 * inversion) of 'b' instead of 'b' directly.
9571 * The basis for this comes from "Unicode Demystified" Chapter 13 by
9572 * Richard Gillam, published by Addison-Wesley, and explained at some
9573 * length there. The preface says to incorporate its examples into your
9574 * code at your own risk. In fact, it had bugs
9576 * The algorithm is like a merge sort, and is essentially the same as the
9580 const UV* array_a; /* a's array */
9582 UV len_a; /* length of a's array */
9585 SV* r; /* the resulting intersection */
9589 UV i_a = 0; /* current index into a's array */
9593 /* running count of how many of the two inputs are postitioned at ranges
9594 * that are in their sets. As explained in the algorithm source book,
9595 * items are stopped accumulating and are output when the count changes
9596 * to/from 2. The count is incremented when we start a range that's in an
9597 * input's set, and decremented when we start a range that's not in a set.
9598 * Only when it is 2 are we in the intersection. */
9601 PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
9603 assert(*i == NULL || is_invlist(*i));
9605 /* Special case if either one is empty */
9606 len_a = (a == NULL) ? 0 : _invlist_len(a);
9607 if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
9608 if (len_a != 0 && complement_b) {
9610 /* Here, 'a' is not empty, therefore from the enclosing 'if', 'b'
9611 * must be empty. Here, also we are using 'b's complement, which
9612 * hence must be every possible code point. Thus the intersection
9615 if (*i == a) { /* No-op */
9620 *i = invlist_clone(a, NULL);
9624 r = invlist_clone(a, NULL);
9625 invlist_replace_list_destroys_src(*i, r);
9630 /* Here, 'a' or 'b' is empty and not using the complement of 'b'. The
9631 * intersection must be empty */
9633 *i = _new_invlist(0);
9641 /* Here both lists exist and are non-empty */
9642 array_a = invlist_array(a);
9643 array_b = invlist_array(b);
9645 /* If are to take the intersection of 'a' with the complement of b, set it
9646 * up so are looking at b's complement. */
9649 /* To complement, we invert: if the first element is 0, remove it. To
9650 * do this, we just pretend the array starts one later */
9651 if (array_b[0] == 0) {
9657 /* But if the first element is not zero, we pretend the list starts
9658 * at the 0 that is always stored immediately before the array. */
9664 /* Size the intersection for the worst case: that the intersection ends up
9665 * fragmenting everything to be completely disjoint */
9666 r= _new_invlist(len_a + len_b);
9668 /* Will contain U+0000 iff both components do */
9669 array_r = _invlist_array_init(r, len_a > 0 && array_a[0] == 0
9670 && len_b > 0 && array_b[0] == 0);
9672 /* Go through each list item by item, stopping when have exhausted one of
9674 while (i_a < len_a && i_b < len_b) {
9675 UV cp; /* The element to potentially add to the intersection's
9677 bool cp_in_set; /* Is it in the input list's set or not */
9679 /* We need to take one or the other of the two inputs for the
9680 * intersection. Since we are merging two sorted lists, we take the
9681 * smaller of the next items. In case of a tie, we take first the one
9682 * that is not in its set (a difference from the union algorithm). If
9683 * we first took the one in its set, it would increment the count,
9684 * possibly to 2 which would cause it to be output as starting a range
9685 * in the intersection, and the next time through we would take that
9686 * same number, and output it again as ending the set. By doing the
9687 * opposite of this, there is no possibility that the count will be
9688 * momentarily incremented to 2. (In a tie and both are in the set or
9689 * both not in the set, it doesn't matter which we take first.) */
9690 if ( array_a[i_a] < array_b[i_b]
9691 || ( array_a[i_a] == array_b[i_b]
9692 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9694 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9695 cp = array_a[i_a++];
9698 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9702 /* Here, have chosen which of the two inputs to look at. Only output
9703 * if the running count changes to/from 2, which marks the
9704 * beginning/end of a range that's in the intersection */
9708 array_r[i_r++] = cp;
9713 array_r[i_r++] = cp;
9720 /* The loop above increments the index into exactly one of the input lists
9721 * each iteration, and ends when either index gets to its list end. That
9722 * means the other index is lower than its end, and so something is
9723 * remaining in that one. We increment 'count', as explained below, if the
9724 * exhausted list was in its set. (i_a and i_b each currently index the
9725 * element beyond the one we care about.) */
9726 if ( (i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9727 || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9732 /* Above we incremented 'count' if the exhausted list was in its set. This
9733 * has made it so that 'count' being below 2 means there is nothing left to
9734 * output; otheriwse what's left to add to the intersection is precisely
9735 * that which is left in the non-exhausted input list.
9737 * To see why, note first that the exhausted input obviously has nothing
9738 * left to affect the intersection. If it was in its set at its end, that
9739 * means the set extends from here to the platform's infinity, and hence
9740 * anything in the non-exhausted's list will be in the intersection, and
9741 * anything not in it won't be. Hence, the rest of the intersection is
9742 * precisely what's in the non-exhausted list The exhausted set also
9743 * contributed 1 to 'count', meaning 'count' was at least 1. Incrementing
9744 * it means 'count' is now at least 2. This is consistent with the
9745 * incremented 'count' being >= 2 means to add the non-exhausted list to
9748 * But if the exhausted input wasn't in its set, it contributed 0 to
9749 * 'count', and the intersection can't include anything further; the
9750 * non-exhausted set is irrelevant. 'count' was at most 1, and doesn't get
9751 * incremented. This is consistent with 'count' being < 2 meaning nothing
9752 * further to add to the intersection. */
9753 if (count < 2) { /* Nothing left to put in the intersection. */
9756 else { /* copy the non-exhausted list, unchanged. */
9757 IV copy_count = len_a - i_a;
9758 if (copy_count > 0) { /* a is the one with stuff left */
9759 Copy(array_a + i_a, array_r + i_r, copy_count, UV);
9761 else { /* b is the one with stuff left */
9762 copy_count = len_b - i_b;
9763 Copy(array_b + i_b, array_r + i_r, copy_count, UV);
9765 len_r = i_r + copy_count;
9768 /* Set the result to the final length, which can change the pointer to
9769 * array_r, so re-find it. (Note that it is unlikely that this will
9770 * change, as we are shrinking the space, not enlarging it) */
9771 if (len_r != _invlist_len(r)) {
9772 invlist_set_len(r, len_r, *get_invlist_offset_addr(r));
9774 array_r = invlist_array(r);
9777 if (*i == NULL) { /* Simply return the calculated intersection */
9780 else { /* Otherwise, replace the existing inversion list in '*i'. We could
9781 instead free '*i', and then set it to 'r', but experience has
9782 shown [perl #127392] that if the input is a mortal, we can get a
9783 huge build-up of these during regex compilation before they get
9786 invlist_replace_list_destroys_src(*i, r);
9798 Perl__add_range_to_invlist(pTHX_ SV* invlist, UV start, UV end)
9800 /* Add the range from 'start' to 'end' inclusive to the inversion list's
9801 * set. A pointer to the inversion list is returned. This may actually be
9802 * a new list, in which case the passed in one has been destroyed. The
9803 * passed-in inversion list can be NULL, in which case a new one is created
9804 * with just the one range in it. The new list is not necessarily
9805 * NUL-terminated. Space is not freed if the inversion list shrinks as a
9806 * result of this function. The gain would not be large, and in many
9807 * cases, this is called multiple times on a single inversion list, so
9808 * anything freed may almost immediately be needed again.
9810 * This used to mostly call the 'union' routine, but that is much more
9811 * heavyweight than really needed for a single range addition */
9813 UV* array; /* The array implementing the inversion list */
9814 UV len; /* How many elements in 'array' */
9815 SSize_t i_s; /* index into the invlist array where 'start'
9817 SSize_t i_e = 0; /* And the index where 'end' should go */
9818 UV cur_highest; /* The highest code point in the inversion list
9819 upon entry to this function */
9821 /* This range becomes the whole inversion list if none already existed */
9822 if (invlist == NULL) {
9823 invlist = _new_invlist(2);
9824 _append_range_to_invlist(invlist, start, end);
9828 /* Likewise, if the inversion list is currently empty */
9829 len = _invlist_len(invlist);
9831 _append_range_to_invlist(invlist, start, end);
9835 /* Starting here, we have to know the internals of the list */
9836 array = invlist_array(invlist);
9838 /* If the new range ends higher than the current highest ... */
9839 cur_highest = invlist_highest(invlist);
9840 if (end > cur_highest) {
9842 /* If the whole range is higher, we can just append it */
9843 if (start > cur_highest) {
9844 _append_range_to_invlist(invlist, start, end);
9848 /* Otherwise, add the portion that is higher ... */
9849 _append_range_to_invlist(invlist, cur_highest + 1, end);
9851 /* ... and continue on below to handle the rest. As a result of the
9852 * above append, we know that the index of the end of the range is the
9853 * final even numbered one of the array. Recall that the final element
9854 * always starts a range that extends to infinity. If that range is in
9855 * the set (meaning the set goes from here to infinity), it will be an
9856 * even index, but if it isn't in the set, it's odd, and the final
9857 * range in the set is one less, which is even. */
9858 if (end == UV_MAX) {
9866 /* We have dealt with appending, now see about prepending. If the new
9867 * range starts lower than the current lowest ... */
9868 if (start < array[0]) {
9870 /* Adding something which has 0 in it is somewhat tricky, and uncommon.
9871 * Let the union code handle it, rather than having to know the
9872 * trickiness in two code places. */
9873 if (UNLIKELY(start == 0)) {
9876 range_invlist = _new_invlist(2);
9877 _append_range_to_invlist(range_invlist, start, end);
9879 _invlist_union(invlist, range_invlist, &invlist);
9881 SvREFCNT_dec_NN(range_invlist);
9886 /* If the whole new range comes before the first entry, and doesn't
9887 * extend it, we have to insert it as an additional range */
9888 if (end < array[0] - 1) {
9890 goto splice_in_new_range;
9893 /* Here the new range adjoins the existing first range, extending it
9897 /* And continue on below to handle the rest. We know that the index of
9898 * the beginning of the range is the first one of the array */
9901 else { /* Not prepending any part of the new range to the existing list.
9902 * Find where in the list it should go. This finds i_s, such that:
9903 * invlist[i_s] <= start < array[i_s+1]
9905 i_s = _invlist_search(invlist, start);
9908 /* At this point, any extending before the beginning of the inversion list
9909 * and/or after the end has been done. This has made it so that, in the
9910 * code below, each endpoint of the new range is either in a range that is
9911 * in the set, or is in a gap between two ranges that are. This means we
9912 * don't have to worry about exceeding the array bounds.
9914 * Find where in the list the new range ends (but we can skip this if we
9915 * have already determined what it is, or if it will be the same as i_s,
9916 * which we already have computed) */
9918 i_e = (start == end)
9920 : _invlist_search(invlist, end);
9923 /* Here generally invlist[i_e] <= end < array[i_e+1]. But if invlist[i_e]
9924 * is a range that goes to infinity there is no element at invlist[i_e+1],
9925 * so only the first relation holds. */
9927 if ( ! ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
9929 /* Here, the ranges on either side of the beginning of the new range
9930 * are in the set, and this range starts in the gap between them.
9932 * The new range extends the range above it downwards if the new range
9933 * ends at or above that range's start */
9934 const bool extends_the_range_above = ( end == UV_MAX
9935 || end + 1 >= array[i_s+1]);
9937 /* The new range extends the range below it upwards if it begins just
9938 * after where that range ends */
9939 if (start == array[i_s]) {
9941 /* If the new range fills the entire gap between the other ranges,
9942 * they will get merged together. Other ranges may also get
9943 * merged, depending on how many of them the new range spans. In
9944 * the general case, we do the merge later, just once, after we
9945 * figure out how many to merge. But in the case where the new
9946 * range exactly spans just this one gap (possibly extending into
9947 * the one above), we do the merge here, and an early exit. This
9948 * is done here to avoid having to special case later. */
9949 if (i_e - i_s <= 1) {
9951 /* If i_e - i_s == 1, it means that the new range terminates
9952 * within the range above, and hence 'extends_the_range_above'
9953 * must be true. (If the range above it extends to infinity,
9954 * 'i_s+2' will be above the array's limit, but 'len-i_s-2'
9955 * will be 0, so no harm done.) */
9956 if (extends_the_range_above) {
9957 Move(array + i_s + 2, array + i_s, len - i_s - 2, UV);
9958 invlist_set_len(invlist,
9960 *(get_invlist_offset_addr(invlist)));
9964 /* Here, i_e must == i_s. We keep them in sync, as they apply
9965 * to the same range, and below we are about to decrement i_s
9970 /* Here, the new range is adjacent to the one below. (It may also
9971 * span beyond the range above, but that will get resolved later.)
9972 * Extend the range below to include this one. */
9973 array[i_s] = (end == UV_MAX) ? UV_MAX : end + 1;
9977 else if (extends_the_range_above) {
9979 /* Here the new range only extends the range above it, but not the
9980 * one below. It merges with the one above. Again, we keep i_e
9981 * and i_s in sync if they point to the same range */
9990 /* Here, we've dealt with the new range start extending any adjoining
9993 * If the new range extends to infinity, it is now the final one,
9994 * regardless of what was there before */
9995 if (UNLIKELY(end == UV_MAX)) {
9996 invlist_set_len(invlist, i_s + 1, *(get_invlist_offset_addr(invlist)));
10000 /* If i_e started as == i_s, it has also been dealt with,
10001 * and been updated to the new i_s, which will fail the following if */
10002 if (! ELEMENT_RANGE_MATCHES_INVLIST(i_e)) {
10004 /* Here, the ranges on either side of the end of the new range are in
10005 * the set, and this range ends in the gap between them.
10007 * If this range is adjacent to (hence extends) the range above it, it
10008 * becomes part of that range; likewise if it extends the range below,
10009 * it becomes part of that range */
10010 if (end + 1 == array[i_e+1]) {
10012 array[i_e] = start;
10014 else if (start <= array[i_e]) {
10015 array[i_e] = end + 1;
10022 /* If the range fits entirely in an existing range (as possibly already
10023 * extended above), it doesn't add anything new */
10024 if (ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10028 /* Here, no part of the range is in the list. Must add it. It will
10029 * occupy 2 more slots */
10030 splice_in_new_range:
10032 invlist_extend(invlist, len + 2);
10033 array = invlist_array(invlist);
10034 /* Move the rest of the array down two slots. Don't include any
10036 Move(array + i_e + 1, array + i_e + 3, len - i_e - 1, UV);
10038 /* Do the actual splice */
10039 array[i_e+1] = start;
10040 array[i_e+2] = end + 1;
10041 invlist_set_len(invlist, len + 2, *(get_invlist_offset_addr(invlist)));
10045 /* Here the new range crossed the boundaries of a pre-existing range. The
10046 * code above has adjusted things so that both ends are in ranges that are
10047 * in the set. This means everything in between must also be in the set.
10048 * Just squash things together */
10049 Move(array + i_e + 1, array + i_s + 1, len - i_e - 1, UV);
10050 invlist_set_len(invlist,
10052 *(get_invlist_offset_addr(invlist)));
10058 Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0,
10059 UV** other_elements_ptr)
10061 /* Create and return an inversion list whose contents are to be populated
10062 * by the caller. The caller gives the number of elements (in 'size') and
10063 * the very first element ('element0'). This function will set
10064 * '*other_elements_ptr' to an array of UVs, where the remaining elements
10065 * are to be placed.
10067 * Obviously there is some trust involved that the caller will properly
10068 * fill in the other elements of the array.
10070 * (The first element needs to be passed in, as the underlying code does
10071 * things differently depending on whether it is zero or non-zero) */
10073 SV* invlist = _new_invlist(size);
10076 PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST;
10078 invlist = add_cp_to_invlist(invlist, element0);
10079 offset = *get_invlist_offset_addr(invlist);
10081 invlist_set_len(invlist, size, offset);
10082 *other_elements_ptr = invlist_array(invlist) + 1;
10088 PERL_STATIC_INLINE SV*
10089 S_add_cp_to_invlist(pTHX_ SV* invlist, const UV cp) {
10090 return _add_range_to_invlist(invlist, cp, cp);
10093 #ifndef PERL_IN_XSUB_RE
10095 Perl__invlist_invert(pTHX_ SV* const invlist)
10097 /* Complement the input inversion list. This adds a 0 if the list didn't
10098 * have a zero; removes it otherwise. As described above, the data
10099 * structure is set up so that this is very efficient */
10101 PERL_ARGS_ASSERT__INVLIST_INVERT;
10103 assert(! invlist_is_iterating(invlist));
10105 /* The inverse of matching nothing is matching everything */
10106 if (_invlist_len(invlist) == 0) {
10107 _append_range_to_invlist(invlist, 0, UV_MAX);
10111 *get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist);
10115 Perl_invlist_clone(pTHX_ SV* const invlist, SV* new_invlist)
10118 /* Return a new inversion list that is a copy of the input one, which is
10119 * unchanged. The new list will not be mortal even if the old one was. */
10121 const STRLEN nominal_length = _invlist_len(invlist); /* Why not +1 XXX */
10122 const STRLEN physical_length = SvCUR(invlist);
10123 const bool offset = *(get_invlist_offset_addr(invlist));
10125 PERL_ARGS_ASSERT_INVLIST_CLONE;
10127 /* Need to allocate extra space to accommodate Perl's addition of a
10128 * trailing NUL to SvPV's, since it thinks they are always strings */
10129 if (new_invlist == NULL) {
10130 new_invlist = _new_invlist(nominal_length);
10133 sv_upgrade(new_invlist, SVt_INVLIST);
10134 initialize_invlist_guts(new_invlist, nominal_length);
10137 *(get_invlist_offset_addr(new_invlist)) = offset;
10138 invlist_set_len(new_invlist, nominal_length, offset);
10139 Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char);
10141 return new_invlist;
10146 PERL_STATIC_INLINE STRLEN*
10147 S_get_invlist_iter_addr(SV* invlist)
10149 /* Return the address of the UV that contains the current iteration
10152 PERL_ARGS_ASSERT_GET_INVLIST_ITER_ADDR;
10154 assert(is_invlist(invlist));
10156 return &(((XINVLIST*) SvANY(invlist))->iterator);
10159 PERL_STATIC_INLINE void
10160 S_invlist_iterinit(SV* invlist) /* Initialize iterator for invlist */
10162 PERL_ARGS_ASSERT_INVLIST_ITERINIT;
10164 *get_invlist_iter_addr(invlist) = 0;
10167 PERL_STATIC_INLINE void
10168 S_invlist_iterfinish(SV* invlist)
10170 /* Terminate iterator for invlist. This is to catch development errors.
10171 * Any iteration that is interrupted before completed should call this
10172 * function. Functions that add code points anywhere else but to the end
10173 * of an inversion list assert that they are not in the middle of an
10174 * iteration. If they were, the addition would make the iteration
10175 * problematical: if the iteration hadn't reached the place where things
10176 * were being added, it would be ok */
10178 PERL_ARGS_ASSERT_INVLIST_ITERFINISH;
10180 *get_invlist_iter_addr(invlist) = (STRLEN) UV_MAX;
10184 S_invlist_iternext(SV* invlist, UV* start, UV* end)
10186 /* An C<invlist_iterinit> call on <invlist> must be used to set this up.
10187 * This call sets in <*start> and <*end>, the next range in <invlist>.
10188 * Returns <TRUE> if successful and the next call will return the next
10189 * range; <FALSE> if was already at the end of the list. If the latter,
10190 * <*start> and <*end> are unchanged, and the next call to this function
10191 * will start over at the beginning of the list */
10193 STRLEN* pos = get_invlist_iter_addr(invlist);
10194 UV len = _invlist_len(invlist);
10197 PERL_ARGS_ASSERT_INVLIST_ITERNEXT;
10200 *pos = (STRLEN) UV_MAX; /* Force iterinit() to be required next time */
10204 array = invlist_array(invlist);
10206 *start = array[(*pos)++];
10212 *end = array[(*pos)++] - 1;
10218 PERL_STATIC_INLINE UV
10219 S_invlist_highest(SV* const invlist)
10221 /* Returns the highest code point that matches an inversion list. This API
10222 * has an ambiguity, as it returns 0 under either the highest is actually
10223 * 0, or if the list is empty. If this distinction matters to you, check
10224 * for emptiness before calling this function */
10226 UV len = _invlist_len(invlist);
10229 PERL_ARGS_ASSERT_INVLIST_HIGHEST;
10235 array = invlist_array(invlist);
10237 /* The last element in the array in the inversion list always starts a
10238 * range that goes to infinity. That range may be for code points that are
10239 * matched in the inversion list, or it may be for ones that aren't
10240 * matched. In the latter case, the highest code point in the set is one
10241 * less than the beginning of this range; otherwise it is the final element
10242 * of this range: infinity */
10243 return (ELEMENT_RANGE_MATCHES_INVLIST(len - 1))
10245 : array[len - 1] - 1;
10249 S_invlist_contents(pTHX_ SV* const invlist, const bool traditional_style)
10251 /* Get the contents of an inversion list into a string SV so that they can
10252 * be printed out. If 'traditional_style' is TRUE, it uses the format
10253 * traditionally done for debug tracing; otherwise it uses a format
10254 * suitable for just copying to the output, with blanks between ranges and
10255 * a dash between range components */
10259 const char intra_range_delimiter = (traditional_style ? '\t' : '-');
10260 const char inter_range_delimiter = (traditional_style ? '\n' : ' ');
10262 if (traditional_style) {
10263 output = newSVpvs("\n");
10266 output = newSVpvs("");
10269 PERL_ARGS_ASSERT_INVLIST_CONTENTS;
10271 assert(! invlist_is_iterating(invlist));
10273 invlist_iterinit(invlist);
10274 while (invlist_iternext(invlist, &start, &end)) {
10275 if (end == UV_MAX) {
10276 Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%cINFINITY%c",
10277 start, intra_range_delimiter,
10278 inter_range_delimiter);
10280 else if (end != start) {
10281 Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c%04" UVXf "%c",
10283 intra_range_delimiter,
10284 end, inter_range_delimiter);
10287 Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c",
10288 start, inter_range_delimiter);
10292 if (SvCUR(output) && ! traditional_style) {/* Get rid of trailing blank */
10293 SvCUR_set(output, SvCUR(output) - 1);
10299 #ifndef PERL_IN_XSUB_RE
10301 Perl__invlist_dump(pTHX_ PerlIO *file, I32 level,
10302 const char * const indent, SV* const invlist)
10304 /* Designed to be called only by do_sv_dump(). Dumps out the ranges of the
10305 * inversion list 'invlist' to 'file' at 'level' Each line is prefixed by
10306 * the string 'indent'. The output looks like this:
10307 [0] 0x000A .. 0x000D
10309 [4] 0x2028 .. 0x2029
10310 [6] 0x3104 .. INFINITY
10311 * This means that the first range of code points matched by the list are
10312 * 0xA through 0xD; the second range contains only the single code point
10313 * 0x85, etc. An inversion list is an array of UVs. Two array elements
10314 * are used to define each range (except if the final range extends to
10315 * infinity, only a single element is needed). The array index of the
10316 * first element for the corresponding range is given in brackets. */
10321 PERL_ARGS_ASSERT__INVLIST_DUMP;
10323 if (invlist_is_iterating(invlist)) {
10324 Perl_dump_indent(aTHX_ level, file,
10325 "%sCan't dump inversion list because is in middle of iterating\n",
10330 invlist_iterinit(invlist);
10331 while (invlist_iternext(invlist, &start, &end)) {
10332 if (end == UV_MAX) {
10333 Perl_dump_indent(aTHX_ level, file,
10334 "%s[%" UVuf "] 0x%04" UVXf " .. INFINITY\n",
10335 indent, (UV)count, start);
10337 else if (end != start) {
10338 Perl_dump_indent(aTHX_ level, file,
10339 "%s[%" UVuf "] 0x%04" UVXf " .. 0x%04" UVXf "\n",
10340 indent, (UV)count, start, end);
10343 Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf "\n",
10344 indent, (UV)count, start);
10352 #if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE)
10354 Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b)
10356 /* Return a boolean as to if the two passed in inversion lists are
10357 * identical. The final argument, if TRUE, says to take the complement of
10358 * the second inversion list before doing the comparison */
10360 const UV* array_a = invlist_array(a);
10361 const UV* array_b = invlist_array(b);
10362 UV len_a = _invlist_len(a);
10363 UV len_b = _invlist_len(b);
10365 PERL_ARGS_ASSERT__INVLISTEQ;
10367 /* If are to compare 'a' with the complement of b, set it
10368 * up so are looking at b's complement. */
10369 if (complement_b) {
10371 /* The complement of nothing is everything, so <a> would have to have
10372 * just one element, starting at zero (ending at infinity) */
10374 return (len_a == 1 && array_a[0] == 0);
10376 else if (array_b[0] == 0) {
10378 /* Otherwise, to complement, we invert. Here, the first element is
10379 * 0, just remove it. To do this, we just pretend the array starts
10387 /* But if the first element is not zero, we pretend the list starts
10388 * at the 0 that is always stored immediately before the array. */
10394 return len_a == len_b
10395 && memEQ(array_a, array_b, len_a * sizeof(array_a[0]));
10401 * As best we can, determine the characters that can match the start of
10402 * the given EXACTF-ish node.
10404 * Returns the invlist as a new SV*; it is the caller's responsibility to
10405 * call SvREFCNT_dec() when done with it.
10408 S__make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node)
10410 const U8 * s = (U8*)STRING(node);
10411 SSize_t bytelen = STR_LEN(node);
10413 /* Start out big enough for 2 separate code points */
10414 SV* invlist = _new_invlist(4);
10416 PERL_ARGS_ASSERT__MAKE_EXACTF_INVLIST;
10421 /* We punt and assume can match anything if the node begins
10422 * with a multi-character fold. Things are complicated. For
10423 * example, /ffi/i could match any of:
10424 * "\N{LATIN SMALL LIGATURE FFI}"
10425 * "\N{LATIN SMALL LIGATURE FF}I"
10426 * "F\N{LATIN SMALL LIGATURE FI}"
10427 * plus several other things; and making sure we have all the
10428 * possibilities is hard. */
10429 if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) {
10430 invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10433 /* Any Latin1 range character can potentially match any
10434 * other depending on the locale */
10435 if (OP(node) == EXACTFL) {
10436 _invlist_union(invlist, PL_Latin1, &invlist);
10439 /* But otherwise, it matches at least itself. We can
10440 * quickly tell if it has a distinct fold, and if so,
10441 * it matches that as well */
10442 invlist = add_cp_to_invlist(invlist, uc);
10443 if (IS_IN_SOME_FOLD_L1(uc))
10444 invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]);
10447 /* Some characters match above-Latin1 ones under /i. This
10448 * is true of EXACTFL ones when the locale is UTF-8 */
10449 if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc)
10450 && (! isASCII(uc) || (OP(node) != EXACTFAA
10451 && OP(node) != EXACTFAA_NO_TRIE)))
10453 add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist);
10457 else { /* Pattern is UTF-8 */
10458 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
10459 const U8* e = s + bytelen;
10462 fc = uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
10464 /* The only code points that aren't folded in a UTF EXACTFish
10465 * node are are the problematic ones in EXACTFL nodes */
10466 if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) {
10467 /* We need to check for the possibility that this EXACTFL
10468 * node begins with a multi-char fold. Therefore we fold
10469 * the first few characters of it so that we can make that
10475 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) {
10477 *(d++) = (U8) toFOLD(*s);
10478 if (fc < 0) { /* Save the first fold */
10485 UV fold = toFOLD_utf8_safe(s, e, d, &len);
10486 if (fc < 0) { /* Save the first fold */
10494 /* And set up so the code below that looks in this folded
10495 * buffer instead of the node's string */
10500 /* When we reach here 's' points to the fold of the first
10501 * character(s) of the node; and 'e' points to far enough along
10502 * the folded string to be just past any possible multi-char
10505 * Unlike the non-UTF-8 case, the macro for determining if a
10506 * string is a multi-char fold requires all the characters to
10507 * already be folded. This is because of all the complications
10508 * if not. Note that they are folded anyway, except in EXACTFL
10509 * nodes. Like the non-UTF case above, we punt if the node
10510 * begins with a multi-char fold */
10512 if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) {
10513 invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10515 else { /* Single char fold */
10517 unsigned int first_folds_to;
10518 const unsigned int * remaining_folds_to_list;
10519 Size_t folds_to_count;
10521 /* It matches itself */
10522 invlist = add_cp_to_invlist(invlist, fc);
10524 /* ... plus all the things that fold to it, which are found in
10525 * PL_utf8_foldclosures */
10526 folds_to_count = _inverse_folds(fc, &first_folds_to,
10527 &remaining_folds_to_list);
10528 for (k = 0; k < folds_to_count; k++) {
10529 UV c = (k == 0) ? first_folds_to : remaining_folds_to_list[k-1];
10531 /* /aa doesn't allow folds between ASCII and non- */
10532 if ( (OP(node) == EXACTFAA || OP(node) == EXACTFAA_NO_TRIE)
10533 && isASCII(c) != isASCII(fc))
10538 invlist = add_cp_to_invlist(invlist, c);
10546 #undef HEADER_LENGTH
10547 #undef TO_INTERNAL_SIZE
10548 #undef FROM_INTERNAL_SIZE
10549 #undef INVLIST_VERSION_ID
10551 /* End of inversion list object */
10554 S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state)
10556 /* This parses the flags that are in either the '(?foo)' or '(?foo:bar)'
10557 * constructs, and updates RExC_flags with them. On input, RExC_parse
10558 * should point to the first flag; it is updated on output to point to the
10559 * final ')' or ':'. There needs to be at least one flag, or this will
10562 /* for (?g), (?gc), and (?o) warnings; warning
10563 about (?c) will warn about (?g) -- japhy */
10565 #define WASTED_O 0x01
10566 #define WASTED_G 0x02
10567 #define WASTED_C 0x04
10568 #define WASTED_GC (WASTED_G|WASTED_C)
10569 I32 wastedflags = 0x00;
10570 U32 posflags = 0, negflags = 0;
10571 U32 *flagsp = &posflags;
10572 char has_charset_modifier = '\0';
10574 bool has_use_defaults = FALSE;
10575 const char* const seqstart = RExC_parse - 1; /* Point to the '?' */
10576 int x_mod_count = 0;
10578 PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS;
10580 /* '^' as an initial flag sets certain defaults */
10581 if (UCHARAT(RExC_parse) == '^') {
10583 has_use_defaults = TRUE;
10584 STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
10585 set_regex_charset(&RExC_flags, (RExC_uni_semantics)
10586 ? REGEX_UNICODE_CHARSET
10587 : REGEX_DEPENDS_CHARSET);
10590 cs = get_regex_charset(RExC_flags);
10591 if (cs == REGEX_DEPENDS_CHARSET
10592 && (RExC_uni_semantics))
10594 cs = REGEX_UNICODE_CHARSET;
10597 while (RExC_parse < RExC_end) {
10598 /* && strchr("iogcmsx", *RExC_parse) */
10599 /* (?g), (?gc) and (?o) are useless here
10600 and must be globally applied -- japhy */
10601 switch (*RExC_parse) {
10603 /* Code for the imsxn flags */
10604 CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count);
10606 case LOCALE_PAT_MOD:
10607 if (has_charset_modifier) {
10608 goto excess_modifier;
10610 else if (flagsp == &negflags) {
10613 cs = REGEX_LOCALE_CHARSET;
10614 has_charset_modifier = LOCALE_PAT_MOD;
10616 case UNICODE_PAT_MOD:
10617 if (has_charset_modifier) {
10618 goto excess_modifier;
10620 else if (flagsp == &negflags) {
10623 cs = REGEX_UNICODE_CHARSET;
10624 has_charset_modifier = UNICODE_PAT_MOD;
10626 case ASCII_RESTRICT_PAT_MOD:
10627 if (flagsp == &negflags) {
10630 if (has_charset_modifier) {
10631 if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
10632 goto excess_modifier;
10634 /* Doubled modifier implies more restricted */
10635 cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
10638 cs = REGEX_ASCII_RESTRICTED_CHARSET;
10640 has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
10642 case DEPENDS_PAT_MOD:
10643 if (has_use_defaults) {
10644 goto fail_modifiers;
10646 else if (flagsp == &negflags) {
10649 else if (has_charset_modifier) {
10650 goto excess_modifier;
10653 /* The dual charset means unicode semantics if the
10654 * pattern (or target, not known until runtime) are
10655 * utf8, or something in the pattern indicates unicode
10657 cs = (RExC_uni_semantics)
10658 ? REGEX_UNICODE_CHARSET
10659 : REGEX_DEPENDS_CHARSET;
10660 has_charset_modifier = DEPENDS_PAT_MOD;
10664 if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
10665 vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
10667 else if (has_charset_modifier == *(RExC_parse - 1)) {
10668 vFAIL2("Regexp modifier \"%c\" may not appear twice",
10669 *(RExC_parse - 1));
10672 vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
10674 NOT_REACHED; /*NOTREACHED*/
10677 vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"",
10678 *(RExC_parse - 1));
10679 NOT_REACHED; /*NOTREACHED*/
10680 case ONCE_PAT_MOD: /* 'o' */
10681 case GLOBAL_PAT_MOD: /* 'g' */
10682 if (ckWARN(WARN_REGEXP)) {
10683 const I32 wflagbit = *RExC_parse == 'o'
10686 if (! (wastedflags & wflagbit) ) {
10687 wastedflags |= wflagbit;
10688 /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10691 "Useless (%s%c) - %suse /%c modifier",
10692 flagsp == &negflags ? "?-" : "?",
10694 flagsp == &negflags ? "don't " : "",
10701 case CONTINUE_PAT_MOD: /* 'c' */
10702 if (ckWARN(WARN_REGEXP)) {
10703 if (! (wastedflags & WASTED_C) ) {
10704 wastedflags |= WASTED_GC;
10705 /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10708 "Useless (%sc) - %suse /gc modifier",
10709 flagsp == &negflags ? "?-" : "?",
10710 flagsp == &negflags ? "don't " : ""
10715 case KEEPCOPY_PAT_MOD: /* 'p' */
10716 if (flagsp == &negflags) {
10717 ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
10719 *flagsp |= RXf_PMf_KEEPCOPY;
10723 /* A flag is a default iff it is following a minus, so
10724 * if there is a minus, it means will be trying to
10725 * re-specify a default which is an error */
10726 if (has_use_defaults || flagsp == &negflags) {
10727 goto fail_modifiers;
10729 flagsp = &negflags;
10730 wastedflags = 0; /* reset so (?g-c) warns twice */
10736 if ((posflags & (RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE)) == RXf_PMf_EXTENDED) {
10737 negflags |= RXf_PMf_EXTENDED_MORE;
10739 RExC_flags |= posflags;
10741 if (negflags & RXf_PMf_EXTENDED) {
10742 negflags |= RXf_PMf_EXTENDED_MORE;
10744 RExC_flags &= ~negflags;
10745 set_regex_charset(&RExC_flags, cs);
10750 RExC_parse += SKIP_IF_CHAR(RExC_parse);
10751 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
10752 vFAIL2utf8f("Sequence (%" UTF8f "...) not recognized",
10753 UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
10754 NOT_REACHED; /*NOTREACHED*/
10757 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10760 vFAIL("Sequence (?... not terminated");
10764 - reg - regular expression, i.e. main body or parenthesized thing
10766 * Caller must absorb opening parenthesis.
10768 * Combining parenthesis handling with the base level of regular expression
10769 * is a trifle forced, but the need to tie the tails of the branches to what
10770 * follows makes it hard to avoid.
10772 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
10774 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
10776 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
10779 PERL_STATIC_INLINE regnode_offset
10780 S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state,
10782 char * parse_start,
10786 regnode_offset ret;
10787 char* name_start = RExC_parse;
10789 SV *sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
10790 GET_RE_DEBUG_FLAGS_DECL;
10792 PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF;
10794 if (RExC_parse == name_start || *RExC_parse != ch) {
10795 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
10796 vFAIL2("Sequence %.3s... not terminated", parse_start);
10800 num = add_data( pRExC_state, STR_WITH_LEN("S"));
10801 RExC_rxi->data->data[num]=(void*)sv_dat;
10802 SvREFCNT_inc_simple_void_NN(sv_dat);
10805 ret = reganode(pRExC_state,
10808 : (ASCII_FOLD_RESTRICTED)
10810 : (AT_LEAST_UNI_SEMANTICS)
10816 *flagp |= HASWIDTH;
10818 Set_Node_Offset(REGNODE_p(ret), parse_start+1);
10819 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
10821 nextchar(pRExC_state);
10825 /* On success, returns the offset at which any next node should be placed into
10826 * the regex engine program being compiled.
10828 * Returns 0 otherwise, with *flagp set to indicate why:
10829 * TRYAGAIN at the end of (?) that only sets flags.
10830 * RESTART_PARSE if the parse needs to be restarted, or'd with
10831 * NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
10832 * Otherwise would only return 0 if regbranch() returns 0, which cannot
10834 STATIC regnode_offset
10835 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp, U32 depth)
10836 /* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter.
10837 * 2 is like 1, but indicates that nextchar() has been called to advance
10838 * RExC_parse beyond the '('. Things like '(?' are indivisible tokens, and
10839 * this flag alerts us to the need to check for that */
10841 regnode_offset ret = 0; /* Will be the head of the group. */
10843 regnode_offset lastbr;
10844 regnode_offset ender = 0;
10847 U32 oregflags = RExC_flags;
10848 bool have_branch = 0;
10850 I32 freeze_paren = 0;
10851 I32 after_freeze = 0;
10852 I32 num; /* numeric backreferences */
10854 char * parse_start = RExC_parse; /* MJD */
10855 char * const oregcomp_parse = RExC_parse;
10857 GET_RE_DEBUG_FLAGS_DECL;
10859 PERL_ARGS_ASSERT_REG;
10860 DEBUG_PARSE("reg ");
10862 *flagp = 0; /* Tentatively. */
10864 /* Having this true makes it feasible to have a lot fewer tests for the
10865 * parse pointer being in scope. For example, we can write
10866 * while(isFOO(*RExC_parse)) RExC_parse++;
10868 * while(RExC_parse < RExC_end && isFOO(*RExC_parse)) RExC_parse++;
10870 assert(*RExC_end == '\0');
10872 /* Make an OPEN node, if parenthesized. */
10875 /* Under /x, space and comments can be gobbled up between the '(' and
10876 * here (if paren ==2). The forms '(*VERB' and '(?...' disallow such
10877 * intervening space, as the sequence is a token, and a token should be
10879 bool has_intervening_patws = (paren == 2)
10880 && *(RExC_parse - 1) != '(';
10882 if (RExC_parse >= RExC_end) {
10883 vFAIL("Unmatched (");
10886 if (paren == 'r') { /* Atomic script run */
10890 else if ( *RExC_parse == '*') { /* (*VERB:ARG), (*construct:...) */
10891 char *start_verb = RExC_parse + 1;
10893 char *start_arg = NULL;
10894 unsigned char op = 0;
10895 int arg_required = 0;
10896 int internal_argval = -1; /* if >-1 we are not allowed an argument*/
10897 bool has_upper = FALSE;
10899 if (has_intervening_patws) {
10900 RExC_parse++; /* past the '*' */
10902 /* For strict backwards compatibility, don't change the message
10903 * now that we also have lowercase operands */
10904 if (isUPPER(*RExC_parse)) {
10905 vFAIL("In '(*VERB...)', the '(' and '*' must be adjacent");
10908 vFAIL("In '(*...)', the '(' and '*' must be adjacent");
10911 while (RExC_parse < RExC_end && *RExC_parse != ')' ) {
10912 if ( *RExC_parse == ':' ) {
10913 start_arg = RExC_parse + 1;
10917 if (isUPPER(*RExC_parse)) {
10923 RExC_parse += UTF8SKIP(RExC_parse);
10926 verb_len = RExC_parse - start_verb;
10928 if (RExC_parse >= RExC_end) {
10929 goto unterminated_verb_pattern;
10932 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10933 while ( RExC_parse < RExC_end && *RExC_parse != ')' ) {
10934 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10936 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
10937 unterminated_verb_pattern:
10939 vFAIL("Unterminated verb pattern argument");
10942 vFAIL("Unterminated '(*...' argument");
10946 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
10948 vFAIL("Unterminated verb pattern");
10951 vFAIL("Unterminated '(*...' construct");
10956 /* Here, we know that RExC_parse < RExC_end */
10958 switch ( *start_verb ) {
10959 case 'A': /* (*ACCEPT) */
10960 if ( memEQs(start_verb, verb_len,"ACCEPT") ) {
10962 internal_argval = RExC_nestroot;
10965 case 'C': /* (*COMMIT) */
10966 if ( memEQs(start_verb, verb_len,"COMMIT") )
10969 case 'F': /* (*FAIL) */
10970 if ( verb_len==1 || memEQs(start_verb, verb_len,"FAIL") ) {
10974 case ':': /* (*:NAME) */
10975 case 'M': /* (*MARK:NAME) */
10976 if ( verb_len==0 || memEQs(start_verb, verb_len,"MARK") ) {
10981 case 'P': /* (*PRUNE) */
10982 if ( memEQs(start_verb, verb_len,"PRUNE") )
10985 case 'S': /* (*SKIP) */
10986 if ( memEQs(start_verb, verb_len,"SKIP") )
10989 case 'T': /* (*THEN) */
10990 /* [19:06] <TimToady> :: is then */
10991 if ( memEQs(start_verb, verb_len,"THEN") ) {
10993 RExC_seen |= REG_CUTGROUP_SEEN;
10997 if ( memEQs(start_verb, verb_len, "asr")
10998 || memEQs(start_verb, verb_len, "atomic_script_run"))
11000 paren = 'r'; /* Mnemonic: recursed run */
11003 else if (memEQs(start_verb, verb_len, "atomic")) {
11004 paren = 't'; /* AtOMIC */
11005 goto alpha_assertions;
11009 if ( memEQs(start_verb, verb_len, "plb")
11010 || memEQs(start_verb, verb_len, "positive_lookbehind"))
11013 goto lookbehind_alpha_assertions;
11015 else if ( memEQs(start_verb, verb_len, "pla")
11016 || memEQs(start_verb, verb_len, "positive_lookahead"))
11019 goto alpha_assertions;
11023 if ( memEQs(start_verb, verb_len, "nlb")
11024 || memEQs(start_verb, verb_len, "negative_lookbehind"))
11027 goto lookbehind_alpha_assertions;
11029 else if ( memEQs(start_verb, verb_len, "nla")
11030 || memEQs(start_verb, verb_len, "negative_lookahead"))
11033 goto alpha_assertions;
11037 if ( memEQs(start_verb, verb_len, "sr")
11038 || memEQs(start_verb, verb_len, "script_run"))
11040 regnode_offset atomic;
11046 /* This indicates Unicode rules. */
11047 REQUIRE_UNI_RULES(flagp, 0);
11053 RExC_parse = start_arg;
11055 if (RExC_in_script_run) {
11057 /* Nested script runs are treated as no-ops, because
11058 * if the nested one fails, the outer one must as
11059 * well. It could fail sooner, and avoid (??{} with
11060 * side effects, but that is explicitly documented as
11061 * undefined behavior. */
11065 if (paren == 's') {
11070 /* But, the atomic part of a nested atomic script run
11071 * isn't a no-op, but can be treated just like a '(?>'
11077 /* By doing this here, we avoid extra warnings for nested
11079 ckWARNexperimental(RExC_parse,
11080 WARN_EXPERIMENTAL__SCRIPT_RUN,
11081 "The script_run feature is experimental");
11083 if (paren == 's') {
11084 /* Here, we're starting a new regular script run */
11085 ret = reg_node(pRExC_state, SROPEN);
11086 RExC_in_script_run = 1;
11091 /* Here, we are starting an atomic script run. This is
11092 * handled by recursing to deal with the atomic portion
11093 * separately, enclosed in SROPEN ... SRCLOSE nodes */
11095 ret = reg_node(pRExC_state, SROPEN);
11097 RExC_in_script_run = 1;
11099 atomic = reg(pRExC_state, 'r', &flags, depth);
11100 if (flags & (RESTART_PARSE|NEED_UTF8)) {
11101 *flagp = flags & (RESTART_PARSE|NEED_UTF8);
11105 REGTAIL(pRExC_state, ret, atomic);
11107 REGTAIL(pRExC_state, atomic,
11108 reg_node(pRExC_state, SRCLOSE));
11110 RExC_in_script_run = 0;
11116 lookbehind_alpha_assertions:
11117 RExC_seen |= REG_LOOKBEHIND_SEEN;
11118 RExC_in_lookbehind++;
11122 ckWARNexperimental(RExC_parse,
11123 WARN_EXPERIMENTAL__ALPHA_ASSERTIONS,
11124 "The alpha_assertions feature is experimental");
11126 RExC_seen_zerolen++;
11132 /* An empty negative lookahead assertion simply is failure */
11133 if (paren == 'A' && RExC_parse == start_arg) {
11134 ret=reganode(pRExC_state, OPFAIL, 0);
11135 nextchar(pRExC_state);
11139 RExC_parse = start_arg;
11144 "'(*%" UTF8f "' requires a terminating ':'",
11145 UTF8fARG(UTF, verb_len, start_verb));
11146 NOT_REACHED; /*NOTREACHED*/
11148 } /* End of switch */
11150 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11151 if (has_upper || verb_len == 0) {
11153 "Unknown verb pattern '%" UTF8f "'",
11154 UTF8fARG(UTF, verb_len, start_verb));
11158 "Unknown '(*...)' construct '%" UTF8f "'",
11159 UTF8fARG(UTF, verb_len, start_verb));
11162 if ( RExC_parse == start_arg ) {
11165 if ( arg_required && !start_arg ) {
11166 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
11167 verb_len, start_verb);
11169 if (internal_argval == -1) {
11170 ret = reganode(pRExC_state, op, 0);
11172 ret = reg2Lanode(pRExC_state, op, 0, internal_argval);
11174 RExC_seen |= REG_VERBARG_SEEN;
11176 SV *sv = newSVpvn( start_arg,
11177 RExC_parse - start_arg);
11178 ARG(REGNODE_p(ret)) = add_data( pRExC_state,
11179 STR_WITH_LEN("S"));
11180 RExC_rxi->data->data[ARG(REGNODE_p(ret))]=(void*)sv;
11181 FLAGS(REGNODE_p(ret)) = 1;
11183 FLAGS(REGNODE_p(ret)) = 0;
11185 if ( internal_argval != -1 )
11186 ARG2L_SET(REGNODE_p(ret), internal_argval);
11187 nextchar(pRExC_state);
11190 else if (*RExC_parse == '?') { /* (?...) */
11191 bool is_logical = 0;
11192 const char * const seqstart = RExC_parse;
11193 const char * endptr;
11194 if (has_intervening_patws) {
11196 vFAIL("In '(?...)', the '(' and '?' must be adjacent");
11199 RExC_parse++; /* past the '?' */
11200 paren = *RExC_parse; /* might be a trailing NUL, if not
11202 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11203 if (RExC_parse > RExC_end) {
11206 ret = 0; /* For look-ahead/behind. */
11209 case 'P': /* (?P...) variants for those used to PCRE/Python */
11210 paren = *RExC_parse;
11211 if ( paren == '<') { /* (?P<...>) named capture */
11213 if (RExC_parse >= RExC_end) {
11214 vFAIL("Sequence (?P<... not terminated");
11216 goto named_capture;
11218 else if (paren == '>') { /* (?P>name) named recursion */
11220 if (RExC_parse >= RExC_end) {
11221 vFAIL("Sequence (?P>... not terminated");
11223 goto named_recursion;
11225 else if (paren == '=') { /* (?P=...) named backref */
11227 return handle_named_backref(pRExC_state, flagp,
11230 RExC_parse += SKIP_IF_CHAR(RExC_parse);
11231 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11232 vFAIL3("Sequence (%.*s...) not recognized",
11233 RExC_parse-seqstart, seqstart);
11234 NOT_REACHED; /*NOTREACHED*/
11235 case '<': /* (?<...) */
11236 if (*RExC_parse == '!')
11238 else if (*RExC_parse != '=')
11245 case '\'': /* (?'...') */
11246 name_start = RExC_parse;
11247 svname = reg_scan_name(pRExC_state, REG_RSN_RETURN_NAME);
11248 if ( RExC_parse == name_start
11249 || RExC_parse >= RExC_end
11250 || *RExC_parse != paren)
11252 vFAIL2("Sequence (?%c... not terminated",
11253 paren=='>' ? '<' : paren);
11258 if (!svname) /* shouldn't happen */
11260 "panic: reg_scan_name returned NULL");
11261 if (!RExC_paren_names) {
11262 RExC_paren_names= newHV();
11263 sv_2mortal(MUTABLE_SV(RExC_paren_names));
11265 RExC_paren_name_list= newAV();
11266 sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
11269 he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
11271 sv_dat = HeVAL(he_str);
11273 /* croak baby croak */
11275 "panic: paren_name hash element allocation failed");
11276 } else if ( SvPOK(sv_dat) ) {
11277 /* (?|...) can mean we have dupes so scan to check
11278 its already been stored. Maybe a flag indicating
11279 we are inside such a construct would be useful,
11280 but the arrays are likely to be quite small, so
11281 for now we punt -- dmq */
11282 IV count = SvIV(sv_dat);
11283 I32 *pv = (I32*)SvPVX(sv_dat);
11285 for ( i = 0 ; i < count ; i++ ) {
11286 if ( pv[i] == RExC_npar ) {
11292 pv = (I32*)SvGROW(sv_dat,
11293 SvCUR(sv_dat) + sizeof(I32)+1);
11294 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
11295 pv[count] = RExC_npar;
11296 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
11299 (void)SvUPGRADE(sv_dat, SVt_PVNV);
11300 sv_setpvn(sv_dat, (char *)&(RExC_npar),
11303 SvIV_set(sv_dat, 1);
11306 /* Yes this does cause a memory leak in debugging Perls
11308 if (!av_store(RExC_paren_name_list,
11309 RExC_npar, SvREFCNT_inc_NN(svname)))
11310 SvREFCNT_dec_NN(svname);
11313 /*sv_dump(sv_dat);*/
11315 nextchar(pRExC_state);
11317 goto capturing_parens;
11320 RExC_seen |= REG_LOOKBEHIND_SEEN;
11321 RExC_in_lookbehind++;
11323 if (RExC_parse >= RExC_end) {
11324 vFAIL("Sequence (?... not terminated");
11328 case '=': /* (?=...) */
11329 RExC_seen_zerolen++;
11331 case '!': /* (?!...) */
11332 RExC_seen_zerolen++;
11333 /* check if we're really just a "FAIL" assertion */
11334 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
11335 FALSE /* Don't force to /x */ );
11336 if (*RExC_parse == ')') {
11337 ret=reganode(pRExC_state, OPFAIL, 0);
11338 nextchar(pRExC_state);
11342 case '|': /* (?|...) */
11343 /* branch reset, behave like a (?:...) except that
11344 buffers in alternations share the same numbers */
11346 after_freeze = freeze_paren = RExC_npar;
11348 /* XXX This construct currently requires an extra pass.
11349 * Investigation would be required to see if that could be
11351 REQUIRE_PARENS_PASS;
11353 case ':': /* (?:...) */
11354 case '>': /* (?>...) */
11356 case '$': /* (?$...) */
11357 case '@': /* (?@...) */
11358 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
11360 case '0' : /* (?0) */
11361 case 'R' : /* (?R) */
11362 if (RExC_parse == RExC_end || *RExC_parse != ')')
11363 FAIL("Sequence (?R) not terminated");
11365 RExC_seen |= REG_RECURSE_SEEN;
11367 /* XXX These constructs currently require an extra pass.
11368 * It probably could be changed */
11369 REQUIRE_PARENS_PASS;
11371 *flagp |= POSTPONED;
11372 goto gen_recurse_regop;
11374 /* named and numeric backreferences */
11375 case '&': /* (?&NAME) */
11376 parse_start = RExC_parse - 1;
11379 SV *sv_dat = reg_scan_name(pRExC_state,
11380 REG_RSN_RETURN_DATA);
11381 num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
11383 if (RExC_parse >= RExC_end || *RExC_parse != ')')
11384 vFAIL("Sequence (?&... not terminated");
11385 goto gen_recurse_regop;
11388 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
11390 vFAIL("Illegal pattern");
11392 goto parse_recursion;
11394 case '-': /* (?-1) */
11395 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
11396 RExC_parse--; /* rewind to let it be handled later */
11400 case '1': case '2': case '3': case '4': /* (?1) */
11401 case '5': case '6': case '7': case '8': case '9':
11402 RExC_parse = (char *) seqstart + 1; /* Point to the digit */
11405 bool is_neg = FALSE;
11407 parse_start = RExC_parse - 1; /* MJD */
11408 if (*RExC_parse == '-') {
11413 if (grok_atoUV(RExC_parse, &unum, &endptr)
11417 RExC_parse = (char*)endptr;
11421 /* Some limit for num? */
11425 if (*RExC_parse!=')')
11426 vFAIL("Expecting close bracket");
11429 if ( paren == '-' ) {
11431 Diagram of capture buffer numbering.
11432 Top line is the normal capture buffer numbers
11433 Bottom line is the negative indexing as from
11437 /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
11441 num = RExC_npar + num;
11444 /* It might be a forward reference; we can't fail until
11445 * we know, by completing the parse to get all the
11446 * groups, and then reparsing */
11447 if (RExC_total_parens > 0) {
11449 vFAIL("Reference to nonexistent group");
11452 REQUIRE_PARENS_PASS;
11455 } else if ( paren == '+' ) {
11456 num = RExC_npar + num - 1;
11458 /* We keep track how many GOSUB items we have produced.
11459 To start off the ARG2L() of the GOSUB holds its "id",
11460 which is used later in conjunction with RExC_recurse
11461 to calculate the offset we need to jump for the GOSUB,
11462 which it will store in the final representation.
11463 We have to defer the actual calculation until much later
11464 as the regop may move.
11467 ret = reg2Lanode(pRExC_state, GOSUB, num, RExC_recurse_count);
11468 if (num >= RExC_npar) {
11470 /* It might be a forward reference; we can't fail until we
11471 * know, by completing the parse to get all the groups, and
11472 * then reparsing */
11473 if (RExC_total_parens > 0) {
11474 if (num >= RExC_total_parens) {
11476 vFAIL("Reference to nonexistent group");
11480 REQUIRE_PARENS_PASS;
11483 RExC_recurse_count++;
11484 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11485 "%*s%*s Recurse #%" UVuf " to %" IVdf "\n",
11486 22, "| |", (int)(depth * 2 + 1), "",
11487 (UV)ARG(REGNODE_p(ret)),
11488 (IV)ARG2L(REGNODE_p(ret))));
11489 RExC_seen |= REG_RECURSE_SEEN;
11491 Set_Node_Length(REGNODE_p(ret),
11492 1 + regarglen[OP(REGNODE_p(ret))]); /* MJD */
11493 Set_Node_Offset(REGNODE_p(ret), parse_start); /* MJD */
11495 *flagp |= POSTPONED;
11496 assert(*RExC_parse == ')');
11497 nextchar(pRExC_state);
11502 case '?': /* (??...) */
11504 if (*RExC_parse != '{') {
11505 RExC_parse += SKIP_IF_CHAR(RExC_parse);
11506 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11508 "Sequence (%" UTF8f "...) not recognized",
11509 UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
11510 NOT_REACHED; /*NOTREACHED*/
11512 *flagp |= POSTPONED;
11516 case '{': /* (?{...}) */
11519 struct reg_code_block *cb;
11522 RExC_seen_zerolen++;
11524 if ( !pRExC_state->code_blocks
11525 || pRExC_state->code_index
11526 >= pRExC_state->code_blocks->count
11527 || pRExC_state->code_blocks->cb[pRExC_state->code_index].start
11528 != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
11531 if (RExC_pm_flags & PMf_USE_RE_EVAL)
11532 FAIL("panic: Sequence (?{...}): no code block found\n");
11533 FAIL("Eval-group not allowed at runtime, use re 'eval'");
11535 /* this is a pre-compiled code block (?{...}) */
11536 cb = &pRExC_state->code_blocks->cb[pRExC_state->code_index];
11537 RExC_parse = RExC_start + cb->end;
11539 if (cb->src_regex) {
11540 n = add_data(pRExC_state, STR_WITH_LEN("rl"));
11541 RExC_rxi->data->data[n] =
11542 (void*)SvREFCNT_inc((SV*)cb->src_regex);
11543 RExC_rxi->data->data[n+1] = (void*)o;
11546 n = add_data(pRExC_state,
11547 (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l", 1);
11548 RExC_rxi->data->data[n] = (void*)o;
11550 pRExC_state->code_index++;
11551 nextchar(pRExC_state);
11554 regnode_offset eval;
11555 ret = reg_node(pRExC_state, LOGICAL);
11557 eval = reg2Lanode(pRExC_state, EVAL,
11560 /* for later propagation into (??{})
11562 RExC_flags & RXf_PMf_COMPILETIME
11564 FLAGS(REGNODE_p(ret)) = 2;
11565 REGTAIL(pRExC_state, ret, eval);
11566 /* deal with the length of this later - MJD */
11569 ret = reg2Lanode(pRExC_state, EVAL, n, 0);
11570 Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1);
11571 Set_Node_Offset(REGNODE_p(ret), parse_start);
11574 case '(': /* (?(?{...})...) and (?(?=...)...) */
11577 const int DEFINE_len = sizeof("DEFINE") - 1;
11578 if ( RExC_parse < RExC_end - 1
11579 && ( ( RExC_parse[0] == '?' /* (?(?...)) */
11580 && ( RExC_parse[1] == '='
11581 || RExC_parse[1] == '!'
11582 || RExC_parse[1] == '<'
11583 || RExC_parse[1] == '{'))
11584 || ( RExC_parse[0] == '*' /* (?(*...)) */
11585 && ( memBEGINs(RExC_parse + 1,
11586 (Size_t) (RExC_end - (RExC_parse + 1)),
11588 || memBEGINs(RExC_parse + 1,
11589 (Size_t) (RExC_end - (RExC_parse + 1)),
11591 || memBEGINs(RExC_parse + 1,
11592 (Size_t) (RExC_end - (RExC_parse + 1)),
11594 || memBEGINs(RExC_parse + 1,
11595 (Size_t) (RExC_end - (RExC_parse + 1)),
11597 || memBEGINs(RExC_parse + 1,
11598 (Size_t) (RExC_end - (RExC_parse + 1)),
11599 "positive_lookahead:")
11600 || memBEGINs(RExC_parse + 1,
11601 (Size_t) (RExC_end - (RExC_parse + 1)),
11602 "positive_lookbehind:")
11603 || memBEGINs(RExC_parse + 1,
11604 (Size_t) (RExC_end - (RExC_parse + 1)),
11605 "negative_lookahead:")
11606 || memBEGINs(RExC_parse + 1,
11607 (Size_t) (RExC_end - (RExC_parse + 1)),
11608 "negative_lookbehind:"))))
11609 ) { /* Lookahead or eval. */
11611 regnode_offset tail;
11613 ret = reg_node(pRExC_state, LOGICAL);
11614 FLAGS(REGNODE_p(ret)) = 1;
11616 tail = reg(pRExC_state, 1, &flag, depth+1);
11617 RETURN_FAIL_ON_RESTART(flag, flagp);
11618 REGTAIL(pRExC_state, ret, tail);
11621 else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
11622 || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
11624 char ch = RExC_parse[0] == '<' ? '>' : '\'';
11625 char *name_start= RExC_parse++;
11627 SV *sv_dat=reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
11628 if ( RExC_parse == name_start
11629 || RExC_parse >= RExC_end
11630 || *RExC_parse != ch)
11632 vFAIL2("Sequence (?(%c... not terminated",
11633 (ch == '>' ? '<' : ch));
11637 num = add_data( pRExC_state, STR_WITH_LEN("S"));
11638 RExC_rxi->data->data[num]=(void*)sv_dat;
11639 SvREFCNT_inc_simple_void_NN(sv_dat);
11641 ret = reganode(pRExC_state, NGROUPP, num);
11642 goto insert_if_check_paren;
11644 else if (memBEGINs(RExC_parse,
11645 (STRLEN) (RExC_end - RExC_parse),
11648 ret = reganode(pRExC_state, DEFINEP, 0);
11649 RExC_parse += DEFINE_len;
11651 goto insert_if_check_paren;
11653 else if (RExC_parse[0] == 'R') {
11655 /* parno == 0 => /(?(R)YES|NO)/ "in any form of recursion OR eval"
11656 * parno == 1 => /(?(R0)YES|NO)/ "in GOSUB (?0) / (?R)"
11657 * parno == 2 => /(?(R1)YES|NO)/ "in GOSUB (?1) (parno-1)"
11660 if (RExC_parse[0] == '0') {
11664 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
11667 if (grok_atoUV(RExC_parse, &uv, &endptr)
11670 parno = (I32)uv + 1;
11671 RExC_parse = (char*)endptr;
11673 /* else "Switch condition not recognized" below */
11674 } else if (RExC_parse[0] == '&') {
11677 sv_dat = reg_scan_name(pRExC_state,
11678 REG_RSN_RETURN_DATA);
11680 parno = 1 + *((I32 *)SvPVX(sv_dat));
11682 ret = reganode(pRExC_state, INSUBP, parno);
11683 goto insert_if_check_paren;
11685 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
11690 if (grok_atoUV(RExC_parse, &uv, &endptr)
11694 RExC_parse = (char*)endptr;
11697 vFAIL("panic: grok_atoUV returned FALSE");
11699 ret = reganode(pRExC_state, GROUPP, parno);
11701 insert_if_check_paren:
11702 if (UCHARAT(RExC_parse) != ')') {
11703 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11704 vFAIL("Switch condition not recognized");
11706 nextchar(pRExC_state);
11708 REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
11709 br = regbranch(pRExC_state, &flags, 1, depth+1);
11711 RETURN_FAIL_ON_RESTART(flags,flagp);
11712 FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
11715 REGTAIL(pRExC_state, br, reganode(pRExC_state,
11717 c = UCHARAT(RExC_parse);
11718 nextchar(pRExC_state);
11719 if (flags&HASWIDTH)
11720 *flagp |= HASWIDTH;
11723 vFAIL("(?(DEFINE)....) does not allow branches");
11725 /* Fake one for optimizer. */
11726 lastbr = reganode(pRExC_state, IFTHEN, 0);
11728 if (!regbranch(pRExC_state, &flags, 1, depth+1)) {
11729 RETURN_FAIL_ON_RESTART(flags, flagp);
11730 FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
11733 REGTAIL(pRExC_state, ret, lastbr);
11734 if (flags&HASWIDTH)
11735 *flagp |= HASWIDTH;
11736 c = UCHARAT(RExC_parse);
11737 nextchar(pRExC_state);
11742 if (RExC_parse >= RExC_end)
11743 vFAIL("Switch (?(condition)... not terminated");
11745 vFAIL("Switch (?(condition)... contains too many branches");
11747 ender = reg_node(pRExC_state, TAIL);
11748 REGTAIL(pRExC_state, br, ender);
11750 REGTAIL(pRExC_state, lastbr, ender);
11751 REGTAIL(pRExC_state, REGNODE_OFFSET(
11753 NEXTOPER(REGNODE_p(lastbr)))),
11757 REGTAIL(pRExC_state, ret, ender);
11758 #if 0 /* Removing this doesn't cause failures in the test suite -- khw */
11759 RExC_size++; /* XXX WHY do we need this?!!
11760 For large programs it seems to be required
11761 but I can't figure out why. -- dmq*/
11765 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11766 vFAIL("Unknown switch condition (?(...))");
11768 case '[': /* (?[ ... ]) */
11769 return handle_regex_sets(pRExC_state, NULL, flagp, depth+1,
11771 case 0: /* A NUL */
11772 RExC_parse--; /* for vFAIL to print correctly */
11773 vFAIL("Sequence (? incomplete");
11775 default: /* e.g., (?i) */
11776 RExC_parse = (char *) seqstart + 1;
11778 parse_lparen_question_flags(pRExC_state);
11779 if (UCHARAT(RExC_parse) != ':') {
11780 if (RExC_parse < RExC_end)
11781 nextchar(pRExC_state);
11786 nextchar(pRExC_state);
11792 if (*RExC_parse == '{') {
11793 ckWARNregdep(RExC_parse + 1,
11794 "Unescaped left brace in regex is "
11795 "deprecated here (and will be fatal "
11796 "in Perl 5.32), passed through");
11798 /* Not bothering to indent here, as the above 'else' is temporary
11800 if (!(RExC_flags & RXf_PMf_NOCAPTURE)) { /* (...) */
11804 if (RExC_total_parens <= 0) {
11805 /* If we are in our first pass through (and maybe only pass),
11806 * we need to allocate memory for the capturing parentheses
11807 * data structures. Since we start at npar=1, when it reaches
11808 * 2, for the first time it has something to put in it. Above
11809 * 2 means we extend what we already have */
11810 if (RExC_npar == 2) {
11811 /* setup RExC_open_parens, which holds the address of each
11812 * OPEN tag, and to make things simpler for the 0 index the
11813 * start of the program - this is used later for offsets */
11814 Newxz(RExC_open_parens, RExC_npar, regnode_offset);
11815 RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */
11817 /* setup RExC_close_parens, which holds the address of each
11818 * CLOSE tag, and to make things simpler for the 0 index
11819 * the end of the program - this is used later for offsets
11821 Newxz(RExC_close_parens, RExC_npar, regnode_offset);
11822 /* we dont know where end op starts yet, so we dont need to
11823 * set RExC_close_parens[0] like we do RExC_open_parens[0]
11827 Renew(RExC_open_parens, RExC_npar, regnode_offset);
11828 Zero(RExC_open_parens + RExC_npar - 1, 1, regnode_offset);
11830 Renew(RExC_close_parens, RExC_npar, regnode_offset);
11831 Zero(RExC_close_parens + RExC_npar - 1, 1, regnode_offset);
11835 ret = reganode(pRExC_state, OPEN, parno);
11836 if (!RExC_nestroot)
11837 RExC_nestroot = parno;
11838 if (RExC_open_parens && !RExC_open_parens[parno])
11840 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11841 "%*s%*s Setting open paren #%" IVdf " to %d\n",
11842 22, "| |", (int)(depth * 2 + 1), "",
11843 (IV)parno, REG_NODE_NUM(REGNODE_p(ret))));
11844 RExC_open_parens[parno]= ret;
11847 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
11848 Set_Node_Offset(REGNODE_p(ret), RExC_parse); /* MJD */
11851 /* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */
11861 /* Pick up the branches, linking them together. */
11862 parse_start = RExC_parse; /* MJD */
11863 br = regbranch(pRExC_state, &flags, 1, depth+1);
11865 /* branch_len = (paren != 0); */
11868 RETURN_FAIL_ON_RESTART(flags, flagp);
11869 FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
11871 if (*RExC_parse == '|') {
11872 if (RExC_use_BRANCHJ) {
11873 reginsert(pRExC_state, BRANCHJ, br, depth+1);
11876 reginsert(pRExC_state, BRANCH, br, depth+1);
11877 Set_Node_Length(REGNODE_p(br), paren != 0);
11878 Set_Node_Offset_To_R(br, parse_start-RExC_start);
11882 else if (paren == ':') {
11883 *flagp |= flags&SIMPLE;
11885 if (is_open) { /* Starts with OPEN. */
11886 REGTAIL(pRExC_state, ret, br); /* OPEN -> first. */
11888 else if (paren != '?') /* Not Conditional */
11890 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
11892 while (*RExC_parse == '|') {
11893 if (RExC_use_BRANCHJ) {
11894 ender = reganode(pRExC_state, LONGJMP, 0);
11896 /* Append to the previous. */
11897 REGTAIL(pRExC_state,
11898 REGNODE_OFFSET(NEXTOPER(NEXTOPER(REGNODE_p(lastbr)))),
11901 nextchar(pRExC_state);
11902 if (freeze_paren) {
11903 if (RExC_npar > after_freeze)
11904 after_freeze = RExC_npar;
11905 RExC_npar = freeze_paren;
11907 br = regbranch(pRExC_state, &flags, 0, depth+1);
11910 RETURN_FAIL_ON_RESTART(flags, flagp);
11911 FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
11913 REGTAIL(pRExC_state, lastbr, br); /* BRANCH -> BRANCH. */
11915 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
11918 if (have_branch || paren != ':') {
11921 /* Make a closing node, and hook it on the end. */
11924 ender = reg_node(pRExC_state, TAIL);
11927 ender = reganode(pRExC_state, CLOSE, parno);
11928 if ( RExC_close_parens ) {
11929 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11930 "%*s%*s Setting close paren #%" IVdf " to %d\n",
11931 22, "| |", (int)(depth * 2 + 1), "",
11932 (IV)parno, REG_NODE_NUM(REGNODE_p(ender))));
11933 RExC_close_parens[parno]= ender;
11934 if (RExC_nestroot == parno)
11937 Set_Node_Offset(REGNODE_p(ender), RExC_parse+1); /* MJD */
11938 Set_Node_Length(REGNODE_p(ender), 1); /* MJD */
11941 ender = reg_node(pRExC_state, SRCLOSE);
11942 RExC_in_script_run = 0;
11952 *flagp &= ~HASWIDTH;
11954 case 't': /* aTomic */
11956 ender = reg_node(pRExC_state, SUCCEED);
11959 ender = reg_node(pRExC_state, END);
11960 assert(!RExC_end_op); /* there can only be one! */
11961 RExC_end_op = REGNODE_p(ender);
11962 if (RExC_close_parens) {
11963 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11964 "%*s%*s Setting close paren #0 (END) to %d\n",
11965 22, "| |", (int)(depth * 2 + 1), "",
11966 REG_NODE_NUM(REGNODE_p(ender))));
11968 RExC_close_parens[0]= ender;
11973 DEBUG_PARSE_MSG("lsbr");
11974 regprop(RExC_rx, RExC_mysv1, REGNODE_p(lastbr), NULL, pRExC_state);
11975 regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender), NULL, pRExC_state);
11976 Perl_re_printf( aTHX_ "~ tying lastbr %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
11977 SvPV_nolen_const(RExC_mysv1),
11978 (IV)REG_NODE_NUM(REGNODE_p(lastbr)),
11979 SvPV_nolen_const(RExC_mysv2),
11980 (IV)REG_NODE_NUM(REGNODE_p(ender)),
11981 (IV)(ender - lastbr)
11984 REGTAIL(pRExC_state, lastbr, ender);
11987 char is_nothing= 1;
11989 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
11991 /* Hook the tails of the branches to the closing node. */
11992 for (br = REGNODE_p(ret); br; br = regnext(br)) {
11993 const U8 op = PL_regkind[OP(br)];
11994 if (op == BRANCH) {
11995 REGTAIL_STUDY(pRExC_state,
11996 REGNODE_OFFSET(NEXTOPER(br)),
11998 if ( OP(NEXTOPER(br)) != NOTHING
11999 || regnext(NEXTOPER(br)) != REGNODE_p(ender))
12002 else if (op == BRANCHJ) {
12003 REGTAIL_STUDY(pRExC_state,
12004 REGNODE_OFFSET(NEXTOPER(NEXTOPER(br))),
12006 /* for now we always disable this optimisation * /
12007 if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING
12008 || regnext(NEXTOPER(NEXTOPER(br))) != REGNODE_p(ender))
12014 regnode * ret_as_regnode = REGNODE_p(ret);
12015 br= PL_regkind[OP(ret_as_regnode)] != BRANCH
12016 ? regnext(ret_as_regnode)
12019 DEBUG_PARSE_MSG("NADA");
12020 regprop(RExC_rx, RExC_mysv1, ret_as_regnode,
12021 NULL, pRExC_state);
12022 regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender),
12023 NULL, pRExC_state);
12024 Perl_re_printf( aTHX_ "~ converting ret %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12025 SvPV_nolen_const(RExC_mysv1),
12026 (IV)REG_NODE_NUM(ret_as_regnode),
12027 SvPV_nolen_const(RExC_mysv2),
12028 (IV)REG_NODE_NUM(REGNODE_p(ender)),
12033 if (OP(REGNODE_p(ender)) == TAIL) {
12035 RExC_emit= REGNODE_OFFSET(br) + 1;
12038 for ( opt= br + 1; opt < REGNODE_p(ender) ; opt++ )
12039 OP(opt)= OPTIMIZED;
12040 NEXT_OFF(br)= REGNODE_p(ender) - br;
12048 /* Even/odd or x=don't care: 010101x10x */
12049 static const char parens[] = "=!aA<,>Bbt";
12050 /* flag below is set to 0 up through 'A'; 1 for larger */
12052 if (paren && (p = strchr(parens, paren))) {
12053 U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
12054 int flag = (p - parens) > 3;
12056 if (paren == '>' || paren == 't') {
12057 node = SUSPEND, flag = 0;
12060 reginsert(pRExC_state, node, ret, depth+1);
12061 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12062 Set_Node_Offset(REGNODE_p(ret), parse_start + 1);
12063 FLAGS(REGNODE_p(ret)) = flag;
12064 REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
12068 /* Check for proper termination. */
12070 /* restore original flags, but keep (?p) and, if we've changed from /d
12071 * rules to /u, keep the /u */
12072 RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY);
12073 if (DEPENDS_SEMANTICS && RExC_uni_semantics) {
12074 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
12076 if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') {
12077 RExC_parse = oregcomp_parse;
12078 vFAIL("Unmatched (");
12080 nextchar(pRExC_state);
12082 else if (!paren && RExC_parse < RExC_end) {
12083 if (*RExC_parse == ')') {
12085 vFAIL("Unmatched )");
12088 FAIL("Junk on end of regexp"); /* "Can't happen". */
12089 NOT_REACHED; /* NOTREACHED */
12092 if (RExC_in_lookbehind) {
12093 RExC_in_lookbehind--;
12095 if (after_freeze > RExC_npar)
12096 RExC_npar = after_freeze;
12101 - regbranch - one alternative of an | operator
12103 * Implements the concatenation operator.
12105 * On success, returns the offset at which any next node should be placed into
12106 * the regex engine program being compiled.
12108 * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
12109 * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
12112 STATIC regnode_offset
12113 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
12115 regnode_offset ret;
12116 regnode_offset chain = 0;
12117 regnode_offset latest;
12118 I32 flags = 0, c = 0;
12119 GET_RE_DEBUG_FLAGS_DECL;
12121 PERL_ARGS_ASSERT_REGBRANCH;
12123 DEBUG_PARSE("brnc");
12128 if (RExC_use_BRANCHJ)
12129 ret = reganode(pRExC_state, BRANCHJ, 0);
12131 ret = reg_node(pRExC_state, BRANCH);
12132 Set_Node_Length(REGNODE_p(ret), 1);
12136 *flagp = WORST; /* Tentatively. */
12138 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
12139 FALSE /* Don't force to /x */ );
12140 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
12141 flags &= ~TRYAGAIN;
12142 latest = regpiece(pRExC_state, &flags, depth+1);
12144 if (flags & TRYAGAIN)
12146 RETURN_FAIL_ON_RESTART(flags, flagp);
12147 FAIL2("panic: regpiece returned failure, flags=%#" UVxf, (UV) flags);
12151 *flagp |= flags&(HASWIDTH|POSTPONED);
12152 if (chain == 0) /* First piece. */
12153 *flagp |= flags&SPSTART;
12155 /* FIXME adding one for every branch after the first is probably
12156 * excessive now we have TRIE support. (hv) */
12158 if ( chain > (SSize_t) BRANCH_MAX_OFFSET
12159 && ! RExC_use_BRANCHJ)
12161 /* XXX We could just redo this branch, but figuring out what
12162 * bookkeeping needs to be reset is a pain */
12163 REQUIRE_BRANCHJ(flagp, 0);
12165 REGTAIL(pRExC_state, chain, latest);
12170 if (chain == 0) { /* Loop ran zero times. */
12171 chain = reg_node(pRExC_state, NOTHING);
12176 *flagp |= flags&SIMPLE;
12183 - regpiece - something followed by possible quantifier * + ? {n,m}
12185 * Note that the branching code sequences used for ? and the general cases
12186 * of * and + are somewhat optimized: they use the same NOTHING node as
12187 * both the endmarker for their branch list and the body of the last branch.
12188 * It might seem that this node could be dispensed with entirely, but the
12189 * endmarker role is not redundant.
12191 * On success, returns the offset at which any next node should be placed into
12192 * the regex engine program being compiled.
12194 * Returns 0 otherwise, with *flagp set to indicate why:
12195 * TRYAGAIN if regatom() returns 0 with TRYAGAIN.
12196 * RESTART_PARSE if the parse needs to be restarted, or'd with
12197 * NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
12199 STATIC regnode_offset
12200 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
12202 regnode_offset ret;
12206 const char * const origparse = RExC_parse;
12208 I32 max = REG_INFTY;
12209 #ifdef RE_TRACK_PATTERN_OFFSETS
12212 const char *maxpos = NULL;
12215 /* Save the original in case we change the emitted regop to a FAIL. */
12216 const regnode_offset orig_emit = RExC_emit;
12218 GET_RE_DEBUG_FLAGS_DECL;
12220 PERL_ARGS_ASSERT_REGPIECE;
12222 DEBUG_PARSE("piec");
12224 ret = regatom(pRExC_state, &flags, depth+1);
12226 RETURN_FAIL_ON_RESTART_OR_FLAGS(flags, flagp, TRYAGAIN);
12227 FAIL2("panic: regatom returned failure, flags=%#" UVxf, (UV) flags);
12232 if (op == '{' && regcurly(RExC_parse)) {
12234 #ifdef RE_TRACK_PATTERN_OFFSETS
12235 parse_start = RExC_parse; /* MJD */
12237 next = RExC_parse + 1;
12238 while (isDIGIT(*next) || *next == ',') {
12239 if (*next == ',') {
12247 if (*next == '}') { /* got one */
12248 const char* endptr;
12252 if (isDIGIT(*RExC_parse)) {
12254 if (!grok_atoUV(RExC_parse, &uv, &endptr))
12255 vFAIL("Invalid quantifier in {,}");
12256 if (uv >= REG_INFTY)
12257 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12262 if (*maxpos == ',')
12265 maxpos = RExC_parse;
12266 if (isDIGIT(*maxpos)) {
12268 if (!grok_atoUV(maxpos, &uv, &endptr))
12269 vFAIL("Invalid quantifier in {,}");
12270 if (uv >= REG_INFTY)
12271 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12274 max = REG_INFTY; /* meaning "infinity" */
12277 nextchar(pRExC_state);
12278 if (max < min) { /* If can't match, warn and optimize to fail
12280 reginsert(pRExC_state, OPFAIL, orig_emit, depth+1);
12281 ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
12282 NEXT_OFF(REGNODE_p(orig_emit)) =
12283 regarglen[OPFAIL] + NODE_STEP_REGNODE;
12286 else if (min == max && *RExC_parse == '?')
12288 ckWARN2reg(RExC_parse + 1,
12289 "Useless use of greediness modifier '%c'",
12294 if ((flags&SIMPLE)) {
12295 if (min == 0 && max == REG_INFTY) {
12296 reginsert(pRExC_state, STAR, ret, depth+1);
12298 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12301 if (min == 1 && max == REG_INFTY) {
12302 reginsert(pRExC_state, PLUS, ret, depth+1);
12304 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12307 MARK_NAUGHTY_EXP(2, 2);
12308 reginsert(pRExC_state, CURLY, ret, depth+1);
12309 Set_Node_Offset(REGNODE_p(ret), parse_start+1); /* MJD */
12310 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12313 const regnode_offset w = reg_node(pRExC_state, WHILEM);
12315 FLAGS(REGNODE_p(w)) = 0;
12316 REGTAIL(pRExC_state, ret, w);
12317 if (RExC_use_BRANCHJ) {
12318 reginsert(pRExC_state, LONGJMP, ret, depth+1);
12319 reginsert(pRExC_state, NOTHING, ret, depth+1);
12320 NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over LONGJMP. */
12322 reginsert(pRExC_state, CURLYX, ret, depth+1);
12324 Set_Node_Offset(REGNODE_p(ret), parse_start+1);
12325 Set_Node_Length(REGNODE_p(ret),
12326 op == '{' ? (RExC_parse - parse_start) : 1);
12328 if (RExC_use_BRANCHJ)
12329 NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over NOTHING to
12331 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
12332 RExC_whilem_seen++;
12333 MARK_NAUGHTY_EXP(1, 4); /* compound interest */
12335 FLAGS(REGNODE_p(ret)) = 0;
12340 *flagp |= HASWIDTH;
12341 ARG1_SET(REGNODE_p(ret), (U16)min);
12342 ARG2_SET(REGNODE_p(ret), (U16)max);
12343 if (max == REG_INFTY)
12344 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12350 if (!ISMULT1(op)) {
12355 #if 0 /* Now runtime fix should be reliable. */
12357 /* if this is reinstated, don't forget to put this back into perldiag:
12359 =item Regexp *+ operand could be empty at {#} in regex m/%s/
12361 (F) The part of the regexp subject to either the * or + quantifier
12362 could match an empty string. The {#} shows in the regular
12363 expression about where the problem was discovered.
12367 if (!(flags&HASWIDTH) && op != '?')
12368 vFAIL("Regexp *+ operand could be empty");
12371 #ifdef RE_TRACK_PATTERN_OFFSETS
12372 parse_start = RExC_parse;
12374 nextchar(pRExC_state);
12376 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
12382 else if (op == '+') {
12386 else if (op == '?') {
12391 if (!(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
12392 ckWARN2reg(RExC_parse,
12393 "%" UTF8f " matches null string many times",
12394 UTF8fARG(UTF, (RExC_parse >= origparse
12395 ? RExC_parse - origparse
12400 if (*RExC_parse == '?') {
12401 nextchar(pRExC_state);
12402 reginsert(pRExC_state, MINMOD, ret, depth+1);
12403 REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
12405 else if (*RExC_parse == '+') {
12406 regnode_offset ender;
12407 nextchar(pRExC_state);
12408 ender = reg_node(pRExC_state, SUCCEED);
12409 REGTAIL(pRExC_state, ret, ender);
12410 reginsert(pRExC_state, SUSPEND, ret, depth+1);
12411 ender = reg_node(pRExC_state, TAIL);
12412 REGTAIL(pRExC_state, ret, ender);
12415 if (ISMULT2(RExC_parse)) {
12417 vFAIL("Nested quantifiers");
12424 S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state,
12425 regnode_offset * node_p,
12433 /* This routine teases apart the various meanings of \N and returns
12434 * accordingly. The input parameters constrain which meaning(s) is/are valid
12435 * in the current context.
12437 * Exactly one of <node_p> and <code_point_p> must be non-NULL.
12439 * If <code_point_p> is not NULL, the context is expecting the result to be a
12440 * single code point. If this \N instance turns out to a single code point,
12441 * the function returns TRUE and sets *code_point_p to that code point.
12443 * If <node_p> is not NULL, the context is expecting the result to be one of
12444 * the things representable by a regnode. If this \N instance turns out to be
12445 * one such, the function generates the regnode, returns TRUE and sets *node_p
12446 * to point to the offset of that regnode into the regex engine program being
12449 * If this instance of \N isn't legal in any context, this function will
12450 * generate a fatal error and not return.
12452 * On input, RExC_parse should point to the first char following the \N at the
12453 * time of the call. On successful return, RExC_parse will have been updated
12454 * to point to just after the sequence identified by this routine. Also
12455 * *flagp has been updated as needed.
12457 * When there is some problem with the current context and this \N instance,
12458 * the function returns FALSE, without advancing RExC_parse, nor setting
12459 * *node_p, nor *code_point_p, nor *flagp.
12461 * If <cp_count> is not NULL, the caller wants to know the length (in code
12462 * points) that this \N sequence matches. This is set, and the input is
12463 * parsed for errors, even if the function returns FALSE, as detailed below.
12465 * There are 5 possibilities here, as detailed in the next 5 paragraphs.
12467 * Probably the most common case is for the \N to specify a single code point.
12468 * *cp_count will be set to 1, and *code_point_p will be set to that code
12471 * Another possibility is for the input to be an empty \N{}, which for
12472 * backwards compatibility we accept. *cp_count will be set to 0. *node_p
12473 * will be set to a generated NOTHING node.
12475 * Still another possibility is for the \N to mean [^\n]. *cp_count will be
12476 * set to 0. *node_p will be set to a generated REG_ANY node.
12478 * The fourth possibility is that \N resolves to a sequence of more than one
12479 * code points. *cp_count will be set to the number of code points in the
12480 * sequence. *node_p will be set to a generated node returned by this
12481 * function calling S_reg().
12483 * The final possibility is that it is premature to be calling this function;
12484 * the parse needs to be restarted. This can happen when this changes from
12485 * /d to /u rules, or when the pattern needs to be upgraded to UTF-8. The
12486 * latter occurs only when the fourth possibility would otherwise be in
12487 * effect, and is because one of those code points requires the pattern to be
12488 * recompiled as UTF-8. The function returns FALSE, and sets the
12489 * RESTART_PARSE and NEED_UTF8 flags in *flagp, as appropriate. When this
12490 * happens, the caller needs to desist from continuing parsing, and return
12491 * this information to its caller. This is not set for when there is only one
12492 * code point, as this can be called as part of an ANYOF node, and they can
12493 * store above-Latin1 code points without the pattern having to be in UTF-8.
12495 * For non-single-quoted regexes, the tokenizer has resolved character and
12496 * sequence names inside \N{...} into their Unicode values, normalizing the
12497 * result into what we should see here: '\N{U+c1.c2...}', where c1... are the
12498 * hex-represented code points in the sequence. This is done there because
12499 * the names can vary based on what charnames pragma is in scope at the time,
12500 * so we need a way to take a snapshot of what they resolve to at the time of
12501 * the original parse. [perl #56444].
12503 * That parsing is skipped for single-quoted regexes, so we may here get
12504 * '\N{NAME}'. This is a fatal error. These names have to be resolved by the
12505 * parser. But if the single-quoted regex is something like '\N{U+41}', that
12506 * is legal and handled here. The code point is Unicode, and has to be
12507 * translated into the native character set for non-ASCII platforms.
12510 char * endbrace; /* points to '}' following the name */
12511 char* p = RExC_parse; /* Temporary */
12513 SV * substitute_parse = NULL;
12517 Size_t count = 0; /* code point count kept internally by this function */
12519 GET_RE_DEBUG_FLAGS_DECL;
12521 PERL_ARGS_ASSERT_GROK_BSLASH_N;
12523 GET_RE_DEBUG_FLAGS;
12525 assert(cBOOL(node_p) ^ cBOOL(code_point_p)); /* Exactly one should be set */
12526 assert(! (node_p && cp_count)); /* At most 1 should be set */
12528 if (cp_count) { /* Initialize return for the most common case */
12532 /* The [^\n] meaning of \N ignores spaces and comments under the /x
12533 * modifier. The other meanings do not, so use a temporary until we find
12534 * out which we are being called with */
12535 skip_to_be_ignored_text(pRExC_state, &p,
12536 FALSE /* Don't force to /x */ );
12538 /* Disambiguate between \N meaning a named character versus \N meaning
12539 * [^\n]. The latter is assumed when the {...} following the \N is a legal
12540 * quantifier, or there is no '{' at all */
12541 if (*p != '{' || regcurly(p)) {
12551 *node_p = reg_node(pRExC_state, REG_ANY);
12552 *flagp |= HASWIDTH|SIMPLE;
12554 Set_Node_Length(REGNODE_p(*(node_p)), 1); /* MJD */
12558 /* The test above made sure that the next real character is a '{', but
12559 * under the /x modifier, it could be separated by space (or a comment and
12560 * \n) and this is not allowed (for consistency with \x{...} and the
12561 * tokenizer handling of \N{NAME}). */
12562 if (*RExC_parse != '{') {
12563 vFAIL("Missing braces on \\N{}");
12566 RExC_parse++; /* Skip past the '{' */
12568 endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
12569 if (! endbrace) { /* no trailing brace */
12570 vFAIL2("Missing right brace on \\%c{}", 'N');
12573 /* Here, we have decided it should be a named character or sequence */
12574 REQUIRE_UNI_RULES(flagp, FALSE); /* Unicode named chars imply Unicode
12577 if (endbrace == RExC_parse) { /* empty: \N{} */
12579 RExC_parse++; /* Position after the "}" */
12580 vFAIL("Zero length \\N{}");
12585 nextchar(pRExC_state);
12590 *node_p = reg_node(pRExC_state, NOTHING);
12594 /* If we haven't got something that begins with 'U+', then it didn't get lexed. */
12595 if ( endbrace - RExC_parse < 2
12596 || strnNE(RExC_parse, "U+", 2))
12598 RExC_parse = endbrace; /* position msg's '<--HERE' */
12599 vFAIL("\\N{NAME} must be resolved by the lexer");
12602 /* This code purposely indented below because of future changes coming */
12604 /* We can get to here when the input is \N{U+...} or when toke.c has
12605 * converted a name to the \N{U+...} form. This include changing a
12606 * name that evaluates to multiple code points to \N{U+c1.c2.c3 ...} */
12608 RExC_parse += 2; /* Skip past the 'U+' */
12610 /* Code points are separated by dots. The '}' terminates the whole
12613 do { /* Loop until the ending brace */
12615 char * start_digit; /* The first of the current code point */
12616 if (! isXDIGIT(*RExC_parse)) {
12618 vFAIL("Invalid hexadecimal number in \\N{U+...}");
12621 start_digit = RExC_parse;
12624 /* Loop through the hex digits of the current code point */
12626 /* Adding this digit will shift the result 4 bits. If that
12627 * result would be above the legal max, it's overflow */
12628 if (cp > MAX_LEGAL_CP >> 4) {
12630 /* Find the end of the code point */
12633 } while (isXDIGIT(*RExC_parse) || *RExC_parse == '_');
12635 /* Be sure to synchronize this message with the similar one
12637 vFAIL4("Use of code point 0x%.*s is not allowed; the"
12638 " permissible max is 0x%" UVxf,
12639 (int) (RExC_parse - start_digit), start_digit,
12643 /* Accumulate this (valid) digit into the running total */
12644 cp = (cp << 4) + READ_XDIGIT(RExC_parse);
12646 /* READ_XDIGIT advanced the input pointer. Ignore a single
12647 * underscore separator */
12648 if (*RExC_parse == '_' && isXDIGIT(RExC_parse[1])) {
12651 } while (isXDIGIT(*RExC_parse));
12653 /* Here, have accumulated the next code point */
12654 if (RExC_parse >= endbrace) { /* If done ... */
12659 /* Here, is a single code point; fail if doesn't want that */
12660 if (! code_point_p) {
12665 /* A single code point is easy to handle; just return it */
12666 *code_point_p = UNI_TO_NATIVE(cp);
12667 RExC_parse = endbrace;
12668 nextchar(pRExC_state);
12672 /* Here, the only legal thing would be a multiple character
12673 * sequence (of the form "\N{U+c1.c2. ... }". So the next
12674 * character must be a dot (and the one after that can't be the
12675 * endbrace, or we'd have something like \N{U+100.} ) */
12676 if (*RExC_parse != '.' || RExC_parse + 1 >= endbrace) {
12677 RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */
12678 ? UTF8SKIP(RExC_parse)
12680 if (RExC_parse >= endbrace) { /* Guard against malformed utf8 */
12681 RExC_parse = endbrace;
12683 vFAIL("Invalid hexadecimal number in \\N{U+...}");
12686 /* Here, looks like its really a multiple character sequence. Fail
12687 * if that's not what the caller wants. But continue with counting
12688 * and error checking if they still want a count */
12689 if (! node_p && ! cp_count) {
12693 /* What is done here is to convert this to a sub-pattern of the
12694 * form \x{char1}\x{char2}... and then call reg recursively to
12695 * parse it (enclosing in "(?: ... )" ). That way, it retains its
12696 * atomicness, while not having to worry about special handling
12697 * that some code points may have. We don't create a subpattern,
12698 * but go through the motions of code point counting and error
12699 * checking, if the caller doesn't want a node returned. */
12701 if (node_p && count == 1) {
12702 substitute_parse = newSVpvs("?:");
12708 /* Convert to notation the rest of the code understands */
12709 sv_catpvs(substitute_parse, "\\x{");
12710 sv_catpvn(substitute_parse, start_digit,
12711 RExC_parse - start_digit);
12712 sv_catpvs(substitute_parse, "}");
12715 /* Move to after the dot (or ending brace the final time through.)
12720 } while (RExC_parse < endbrace);
12722 if (! node_p) { /* Doesn't want the node */
12729 sv_catpvs(substitute_parse, ")");
12732 /* The values are Unicode, and therefore have to be converted to native
12733 * on a non-Unicode (meaning non-ASCII) platform. */
12734 RExC_recode_x_to_native = 1;
12737 /* Here, we have the string the name evaluates to, ready to be parsed,
12738 * stored in 'substitute_parse' as a series of valid "\x{...}\x{...}"
12739 * constructs. This can be called from within a substitute parse already.
12740 * The error reporting mechanism doesn't work for 2 levels of this, but the
12741 * code above has validated this new construct, so there should be no
12742 * errors generated by the below. And this isn' an exact copy, so the
12743 * mechanism to seamlessly deal with this won't work, so turn off warnings
12745 save_start = RExC_start;
12746 orig_end = RExC_end;
12748 RExC_parse = RExC_start = SvPVX(substitute_parse);
12749 RExC_end = RExC_parse + SvCUR(substitute_parse);
12750 TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
12752 *node_p = reg(pRExC_state, 1, &flags, depth+1);
12754 /* Restore the saved values */
12756 RExC_start = save_start;
12757 RExC_parse = endbrace;
12758 RExC_end = orig_end;
12760 RExC_recode_x_to_native = 0;
12763 SvREFCNT_dec_NN(substitute_parse);
12766 RETURN_FAIL_ON_RESTART(flags, flagp);
12767 FAIL2("panic: reg returned failure to grok_bslash_N, flags=%#" UVxf,
12770 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
12772 nextchar(pRExC_state);
12778 PERL_STATIC_INLINE U8
12779 S_compute_EXACTish(RExC_state_t *pRExC_state)
12783 PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
12791 op = get_regex_charset(RExC_flags);
12792 if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
12793 op--; /* /a is same as /u, and map /aa's offset to what /a's would have
12794 been, so there is no hole */
12797 return op + EXACTF;
12800 PERL_STATIC_INLINE void
12801 S_alloc_maybe_populate_EXACT(pTHX_ RExC_state_t *pRExC_state,
12802 regnode_offset node, I32* flagp, STRLEN len,
12803 UV code_point, bool downgradable)
12805 /* This knows the details about sizing an EXACTish node, setting flags for
12806 * it (by setting <*flagp>, and potentially populating it with a single
12809 * If <len> (the length in bytes) is non-zero, this function assumes that
12810 * the node has already been populated, and just does the sizing. In this
12811 * case <code_point> should be the final code point that has already been
12812 * placed into the node. This value will be ignored except that under some
12813 * circumstances <*flagp> is set based on it.
12815 * If <len> is zero, the function assumes that the node is to contain only
12816 * the single character given by <code_point> and calculates what <len>
12817 * should be. It populates the node's STRING with <code_point> or its
12820 * In both cases <*flagp> is appropriately set
12822 * It knows that under FOLD, the Latin Sharp S and UTF characters above
12823 * 255, must be folded (the former only when the rules indicate it can
12826 * When it does the populating, it looks at the flag 'downgradable'. If
12827 * true with a node that folds, it checks if the single code point
12828 * participates in a fold, and if not downgrades the node to an EXACT.
12829 * This helps the optimizer */
12831 bool len_passed_in = cBOOL(len != 0);
12832 U8 character[UTF8_MAXBYTES_CASE+1];
12834 PERL_ARGS_ASSERT_ALLOC_MAYBE_POPULATE_EXACT;
12836 if (! len_passed_in) {
12838 if (UVCHR_IS_INVARIANT(code_point)) {
12839 if (LOC || ! FOLD) { /* /l defers folding until runtime */
12840 *character = (U8) code_point;
12842 else { /* Here is /i and not /l. */
12843 *character = toFOLD((U8) code_point);
12845 /* We can downgrade to an EXACT node if this character
12846 * isn't a folding one. Note that this assumes that
12847 * nothing above Latin1 folds to some other invariant than
12848 * one of these alphabetics; otherwise we would also have
12850 * && (! HAS_NONLATIN1_FOLD_CLOSURE(code_point)
12851 * || ASCII_FOLD_RESTRICTED))
12853 if (downgradable && PL_fold[code_point] == code_point) {
12854 OP(REGNODE_p(node)) = EXACT;
12859 else if (FOLD && ( ! LOC
12860 || ! is_PROBLEMATIC_LOCALE_FOLD_cp(code_point)))
12861 { /* Folding, and ok to do so now */
12862 UV folded = _to_uni_fold_flags(
12866 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
12867 ? FOLD_FLAGS_NOMIX_ASCII
12870 && folded == code_point /* This quickly rules out many
12871 cases, avoiding the
12872 _invlist_contains_cp() overhead
12874 && ! _invlist_contains_cp(PL_utf8_foldable, code_point))
12876 OP(REGNODE_p(node)) = (LOC)
12881 else if (code_point <= MAX_UTF8_TWO_BYTE) {
12883 /* Not folding this cp, and can output it directly */
12884 *character = UTF8_TWO_BYTE_HI(code_point);
12885 *(character + 1) = UTF8_TWO_BYTE_LO(code_point);
12889 uvchr_to_utf8( character, code_point);
12890 len = UTF8SKIP(character);
12892 } /* Else pattern isn't UTF8. */
12894 *character = (U8) code_point;
12896 } /* Else is folded non-UTF8 */
12897 #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
12898 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
12899 || UNICODE_DOT_DOT_VERSION > 0)
12900 else if (LIKELY(code_point != LATIN_SMALL_LETTER_SHARP_S)) {
12904 /* We don't fold any non-UTF8 except possibly the Sharp s (see
12905 * comments at join_exact()); */
12906 *character = (U8) code_point;
12909 /* Can turn into an EXACT node if we know the fold at compile time,
12910 * and it folds to itself and doesn't particpate in other folds */
12913 && PL_fold_latin1[code_point] == code_point
12914 && (! HAS_NONLATIN1_FOLD_CLOSURE(code_point)
12915 || (isASCII(code_point) && ASCII_FOLD_RESTRICTED)))
12917 OP(REGNODE_p(node)) = EXACT;
12919 } /* else is Sharp s. May need to fold it */
12920 else if (AT_LEAST_UNI_SEMANTICS && ! ASCII_FOLD_RESTRICTED) {
12922 *(character + 1) = 's';
12926 *character = LATIN_SMALL_LETTER_SHARP_S;
12931 if (downgradable) {
12932 change_engine_size(pRExC_state, STR_SZ(len));
12935 RExC_emit += STR_SZ(len);
12936 STR_LEN(REGNODE_p(node)) = len;
12937 if (! len_passed_in) {
12938 Copy((char *) character, STRING(REGNODE_p(node)), len, char);
12941 *flagp |= HASWIDTH;
12943 /* A single character node is SIMPLE, except for the special-cased SHARP S
12945 if ((len == 1 || (UTF && len == UVCHR_SKIP(code_point)))
12946 #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
12947 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
12948 || UNICODE_DOT_DOT_VERSION > 0)
12949 && ( code_point != LATIN_SMALL_LETTER_SHARP_S
12950 || ! FOLD || ! DEPENDS_SEMANTICS)
12956 if (OP(REGNODE_p(node)) == EXACTFL) {
12957 RExC_contains_locale = 1;
12962 S_new_regcurly(const char *s, const char *e)
12964 /* This is a temporary function designed to match the most lenient form of
12965 * a {m,n} quantifier we ever envision, with either number omitted, and
12966 * spaces anywhere between/before/after them.
12968 * If this function fails, then the string it matches is very unlikely to
12969 * ever be considered a valid quantifier, so we can allow the '{' that
12970 * begins it to be considered as a literal */
12972 bool has_min = FALSE;
12973 bool has_max = FALSE;
12975 PERL_ARGS_ASSERT_NEW_REGCURLY;
12977 if (s >= e || *s++ != '{')
12980 while (s < e && isSPACE(*s)) {
12983 while (s < e && isDIGIT(*s)) {
12987 while (s < e && isSPACE(*s)) {
12993 while (s < e && isSPACE(*s)) {
12996 while (s < e && isDIGIT(*s)) {
13000 while (s < e && isSPACE(*s)) {
13005 return s < e && *s == '}' && (has_min || has_max);
13008 /* Parse backref decimal value, unless it's too big to sensibly be a backref,
13009 * in which case return I32_MAX (rather than possibly 32-bit wrapping) */
13012 S_backref_value(char *p, char *e)
13014 const char* endptr = e;
13016 if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX)
13023 - regatom - the lowest level
13025 Try to identify anything special at the start of the current parse position.
13026 If there is, then handle it as required. This may involve generating a
13027 single regop, such as for an assertion; or it may involve recursing, such as
13028 to handle a () structure.
13030 If the string doesn't start with something special then we gobble up
13031 as much literal text as we can. If we encounter a quantifier, we have to
13032 back off the final literal character, as that quantifier applies to just it
13033 and not to the whole string of literals.
13035 Once we have been able to handle whatever type of thing started the
13036 sequence, we return the offset into the regex engine program being compiled
13037 at which any next regnode should be placed.
13039 Returns 0, setting *flagp to TRYAGAIN if reg() returns 0 with TRYAGAIN.
13040 Returns 0, setting *flagp to RESTART_PARSE if the parse needs to be
13041 restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
13042 Otherwise does not return 0.
13044 Note: we have to be careful with escapes, as they can be both literal
13045 and special, and in the case of \10 and friends, context determines which.
13047 A summary of the code structure is:
13049 switch (first_byte) {
13050 cases for each special:
13051 handle this special;
13054 switch (2nd byte) {
13055 cases for each unambiguous special:
13056 handle this special;
13058 cases for each ambigous special/literal:
13060 if (special) handle here
13062 default: // unambiguously literal:
13065 default: // is a literal char
13068 create EXACTish node for literal;
13069 while (more input and node isn't full) {
13070 switch (input_byte) {
13071 cases for each special;
13072 make sure parse pointer is set so that the next call to
13073 regatom will see this special first
13074 goto loopdone; // EXACTish node terminated by prev. char
13076 append char to EXACTISH node;
13078 get next input byte;
13082 return the generated node;
13084 Specifically there are two separate switches for handling
13085 escape sequences, with the one for handling literal escapes requiring
13086 a dummy entry for all of the special escapes that are actually handled
13091 STATIC regnode_offset
13092 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
13094 regnode_offset ret = 0;
13101 GET_RE_DEBUG_FLAGS_DECL;
13103 *flagp = WORST; /* Tentatively. */
13105 DEBUG_PARSE("atom");
13107 PERL_ARGS_ASSERT_REGATOM;
13110 parse_start = RExC_parse;
13111 assert(RExC_parse < RExC_end);
13112 switch ((U8)*RExC_parse) {
13114 RExC_seen_zerolen++;
13115 nextchar(pRExC_state);
13116 if (RExC_flags & RXf_PMf_MULTILINE)
13117 ret = reg_node(pRExC_state, MBOL);
13119 ret = reg_node(pRExC_state, SBOL);
13120 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13123 nextchar(pRExC_state);
13125 RExC_seen_zerolen++;
13126 if (RExC_flags & RXf_PMf_MULTILINE)
13127 ret = reg_node(pRExC_state, MEOL);
13129 ret = reg_node(pRExC_state, SEOL);
13130 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13133 nextchar(pRExC_state);
13134 if (RExC_flags & RXf_PMf_SINGLELINE)
13135 ret = reg_node(pRExC_state, SANY);
13137 ret = reg_node(pRExC_state, REG_ANY);
13138 *flagp |= HASWIDTH|SIMPLE;
13140 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13144 char * const oregcomp_parse = ++RExC_parse;
13145 ret = regclass(pRExC_state, flagp, depth+1,
13146 FALSE, /* means parse the whole char class */
13147 TRUE, /* allow multi-char folds */
13148 FALSE, /* don't silence non-portable warnings. */
13149 (bool) RExC_strict,
13150 TRUE, /* Allow an optimized regnode result */
13153 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13154 FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13157 if (*RExC_parse != ']') {
13158 RExC_parse = oregcomp_parse;
13159 vFAIL("Unmatched [");
13161 nextchar(pRExC_state);
13162 Set_Node_Length(REGNODE_p(ret), RExC_parse - oregcomp_parse + 1); /* MJD */
13166 nextchar(pRExC_state);
13167 ret = reg(pRExC_state, 2, &flags, depth+1);
13169 if (flags & TRYAGAIN) {
13170 if (RExC_parse >= RExC_end) {
13171 /* Make parent create an empty node if needed. */
13172 *flagp |= TRYAGAIN;
13177 RETURN_FAIL_ON_RESTART(flags, flagp);
13178 FAIL2("panic: reg returned failure to regatom, flags=%#" UVxf,
13181 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
13185 if (flags & TRYAGAIN) {
13186 *flagp |= TRYAGAIN;
13189 vFAIL("Internal urp");
13190 /* Supposed to be caught earlier. */
13196 vFAIL("Quantifier follows nothing");
13201 This switch handles escape sequences that resolve to some kind
13202 of special regop and not to literal text. Escape sequences that
13203 resolve to literal text are handled below in the switch marked
13206 Every entry in this switch *must* have a corresponding entry
13207 in the literal escape switch. However, the opposite is not
13208 required, as the default for this switch is to jump to the
13209 literal text handling code.
13212 switch ((U8)*RExC_parse) {
13213 /* Special Escapes */
13215 RExC_seen_zerolen++;
13216 ret = reg_node(pRExC_state, SBOL);
13217 /* SBOL is shared with /^/ so we set the flags so we can tell
13218 * /\A/ from /^/ in split. */
13219 FLAGS(REGNODE_p(ret)) = 1;
13221 goto finish_meta_pat;
13223 ret = reg_node(pRExC_state, GPOS);
13224 RExC_seen |= REG_GPOS_SEEN;
13226 goto finish_meta_pat;
13228 RExC_seen_zerolen++;
13229 ret = reg_node(pRExC_state, KEEPS);
13231 /* XXX:dmq : disabling in-place substitution seems to
13232 * be necessary here to avoid cases of memory corruption, as
13233 * with: C<$_="x" x 80; s/x\K/y/> -- rgs
13235 RExC_seen |= REG_LOOKBEHIND_SEEN;
13236 goto finish_meta_pat;
13238 ret = reg_node(pRExC_state, SEOL);
13240 RExC_seen_zerolen++; /* Do not optimize RE away */
13241 goto finish_meta_pat;
13243 ret = reg_node(pRExC_state, EOS);
13245 RExC_seen_zerolen++; /* Do not optimize RE away */
13246 goto finish_meta_pat;
13248 vFAIL("\\C no longer supported");
13250 ret = reg_node(pRExC_state, CLUMP);
13251 *flagp |= HASWIDTH;
13252 goto finish_meta_pat;
13258 arg = ANYOF_WORDCHAR;
13266 regex_charset charset = get_regex_charset(RExC_flags);
13268 RExC_seen_zerolen++;
13269 RExC_seen |= REG_LOOKBEHIND_SEEN;
13270 op = BOUND + charset;
13273 RExC_seen_d_op = TRUE;
13275 else if (op == BOUNDL) {
13276 RExC_contains_locale = 1;
13279 ret = reg_node(pRExC_state, op);
13281 if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') {
13282 FLAGS(REGNODE_p(ret)) = TRADITIONAL_BOUND;
13283 if (op > BOUNDA) { /* /aa is same as /a */
13284 OP(REGNODE_p(ret)) = BOUNDA;
13289 char name = *RExC_parse;
13290 char * endbrace = NULL;
13292 if (RExC_parse < RExC_end) {
13293 endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
13297 vFAIL2("Missing right brace on \\%c{}", name);
13299 /* XXX Need to decide whether to take spaces or not. Should be
13300 * consistent with \p{}, but that currently is SPACE, which
13301 * means vertical too, which seems wrong
13302 * while (isBLANK(*RExC_parse)) {
13305 if (endbrace == RExC_parse) {
13306 RExC_parse++; /* After the '}' */
13307 vFAIL2("Empty \\%c{}", name);
13309 length = endbrace - RExC_parse;
13310 /*while (isBLANK(*(RExC_parse + length - 1))) {
13313 switch (*RExC_parse) {
13316 && (memNEs(RExC_parse + 1, length - 1, "cb")))
13318 goto bad_bound_type;
13320 FLAGS(REGNODE_p(ret)) = GCB_BOUND;
13323 if (length != 2 || *(RExC_parse + 1) != 'b') {
13324 goto bad_bound_type;
13326 FLAGS(REGNODE_p(ret)) = LB_BOUND;
13329 if (length != 2 || *(RExC_parse + 1) != 'b') {
13330 goto bad_bound_type;
13332 FLAGS(REGNODE_p(ret)) = SB_BOUND;
13335 if (length != 2 || *(RExC_parse + 1) != 'b') {
13336 goto bad_bound_type;
13338 FLAGS(REGNODE_p(ret)) = WB_BOUND;
13342 RExC_parse = endbrace;
13344 "'%" UTF8f "' is an unknown bound type",
13345 UTF8fARG(UTF, length, endbrace - length));
13346 NOT_REACHED; /*NOTREACHED*/
13348 RExC_parse = endbrace;
13349 REQUIRE_UNI_RULES(flagp, 0);
13351 if (op >= BOUNDA) { /* /aa is same as /a */
13352 OP(REGNODE_p(ret)) = BOUNDU;
13355 /* Don't have to worry about UTF-8, in this message because
13356 * to get here the contents of the \b must be ASCII */
13357 ckWARN4reg(RExC_parse + 1, /* Include the '}' in msg */
13358 "Using /u for '%.*s' instead of /%s",
13360 endbrace - length + 1,
13361 (charset == REGEX_ASCII_RESTRICTED_CHARSET)
13362 ? ASCII_RESTRICT_PAT_MODS
13363 : ASCII_MORE_RESTRICT_PAT_MODS);
13368 OP(REGNODE_p(ret)) += NBOUND - BOUND;
13370 goto finish_meta_pat;
13378 if (! DEPENDS_SEMANTICS) {
13382 /* \d doesn't have any matches in the upper Latin1 range, hence /d
13383 * is equivalent to /u. Changing to /u saves some branches at
13386 goto join_posix_op_known;
13389 ret = reg_node(pRExC_state, LNBREAK);
13390 *flagp |= HASWIDTH|SIMPLE;
13391 goto finish_meta_pat;
13399 goto join_posix_op_known;
13405 arg = ANYOF_VERTWS;
13407 goto join_posix_op_known;
13417 op = POSIXD + get_regex_charset(RExC_flags);
13418 if (op > POSIXA) { /* /aa is same as /a */
13421 else if (op == POSIXL) {
13422 RExC_contains_locale = 1;
13424 else if (op == POSIXD) {
13425 RExC_seen_d_op = TRUE;
13428 join_posix_op_known:
13431 op += NPOSIXD - POSIXD;
13434 ret = reg_node(pRExC_state, op);
13435 FLAGS(REGNODE_p(ret)) = namedclass_to_classnum(arg);
13437 *flagp |= HASWIDTH|SIMPLE;
13441 if ( UCHARAT(RExC_parse + 1) == '{'
13442 && UNLIKELY(! new_regcurly(RExC_parse + 1, RExC_end)))
13445 vFAIL("Unescaped left brace in regex is illegal here");
13447 nextchar(pRExC_state);
13448 Set_Node_Length(REGNODE_p(ret), 2); /* MJD */
13454 ret = regclass(pRExC_state, flagp, depth+1,
13455 TRUE, /* means just parse this element */
13456 FALSE, /* don't allow multi-char folds */
13457 FALSE, /* don't silence non-portable warnings. It
13458 would be a bug if these returned
13460 (bool) RExC_strict,
13461 TRUE, /* Allow an optimized regnode result */
13463 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13464 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
13465 * multi-char folds are allowed. */
13467 FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13472 Set_Node_Offset(REGNODE_p(ret), parse_start);
13473 Set_Node_Cur_Length(REGNODE_p(ret), parse_start - 2);
13474 nextchar(pRExC_state);
13477 /* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the
13478 * \N{...} evaluates to a sequence of more than one code points).
13479 * The function call below returns a regnode, which is our result.
13480 * The parameters cause it to fail if the \N{} evaluates to a
13481 * single code point; we handle those like any other literal. The
13482 * reason that the multicharacter case is handled here and not as
13483 * part of the EXACtish code is because of quantifiers. In
13484 * /\N{BLAH}+/, the '+' applies to the whole thing, and doing it
13485 * this way makes that Just Happen. dmq.
13486 * join_exact() will join this up with adjacent EXACTish nodes
13487 * later on, if appropriate. */
13489 if (grok_bslash_N(pRExC_state,
13490 &ret, /* Want a regnode returned */
13491 NULL, /* Fail if evaluates to a single code
13493 NULL, /* Don't need a count of how many code
13502 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13504 /* Here, evaluates to a single code point. Go get that */
13505 RExC_parse = parse_start;
13508 case 'k': /* Handle \k<NAME> and \k'NAME' */
13512 if ( RExC_parse >= RExC_end - 1
13513 || (( ch = RExC_parse[1]) != '<'
13518 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
13519 vFAIL2("Sequence %.2s... not terminated", parse_start);
13522 ret = handle_named_backref(pRExC_state,
13534 case '1': case '2': case '3': case '4':
13535 case '5': case '6': case '7': case '8': case '9':
13540 if (*RExC_parse == 'g') {
13544 if (*RExC_parse == '{') {
13548 if (*RExC_parse == '-') {
13552 if (hasbrace && !isDIGIT(*RExC_parse)) {
13553 if (isrel) RExC_parse--;
13555 goto parse_named_seq;
13558 if (RExC_parse >= RExC_end) {
13559 goto unterminated_g;
13561 num = S_backref_value(RExC_parse, RExC_end);
13563 vFAIL("Reference to invalid group 0");
13564 else if (num == I32_MAX) {
13565 if (isDIGIT(*RExC_parse))
13566 vFAIL("Reference to nonexistent group");
13569 vFAIL("Unterminated \\g... pattern");
13573 num = RExC_npar - num;
13575 vFAIL("Reference to nonexistent or unclosed group");
13579 num = S_backref_value(RExC_parse, RExC_end);
13580 /* bare \NNN might be backref or octal - if it is larger
13581 * than or equal RExC_npar then it is assumed to be an
13582 * octal escape. Note RExC_npar is +1 from the actual
13583 * number of parens. */
13584 /* Note we do NOT check if num == I32_MAX here, as that is
13585 * handled by the RExC_npar check */
13588 /* any numeric escape < 10 is always a backref */
13590 /* any numeric escape < RExC_npar is a backref */
13591 && num >= RExC_npar
13592 /* cannot be an octal escape if it starts with 8 */
13593 && *RExC_parse != '8'
13594 /* cannot be an octal escape it it starts with 9 */
13595 && *RExC_parse != '9'
13597 /* Probably not meant to be a backref, instead likely
13598 * to be an octal character escape, e.g. \35 or \777.
13599 * The above logic should make it obvious why using
13600 * octal escapes in patterns is problematic. - Yves */
13601 RExC_parse = parse_start;
13606 /* At this point RExC_parse points at a numeric escape like
13607 * \12 or \88 or something similar, which we should NOT treat
13608 * as an octal escape. It may or may not be a valid backref
13609 * escape. For instance \88888888 is unlikely to be a valid
13611 while (isDIGIT(*RExC_parse))
13614 if (*RExC_parse != '}')
13615 vFAIL("Unterminated \\g{...} pattern");
13618 if (num >= (I32)RExC_npar) {
13620 /* It might be a forward reference; we can't fail until we
13621 * know, by completing the parse to get all the groups, and
13622 * then reparsing */
13623 if (RExC_total_parens > 0) {
13624 if (num >= RExC_total_parens) {
13625 vFAIL("Reference to nonexistent group");
13629 REQUIRE_PARENS_PASS;
13633 ret = reganode(pRExC_state,
13636 : (ASCII_FOLD_RESTRICTED)
13638 : (AT_LEAST_UNI_SEMANTICS)
13644 if (OP(REGNODE_p(ret)) == REFF) {
13645 RExC_seen_d_op = TRUE;
13647 *flagp |= HASWIDTH;
13649 /* override incorrect value set in reganode MJD */
13650 Set_Node_Offset(REGNODE_p(ret), parse_start);
13651 Set_Node_Cur_Length(REGNODE_p(ret), parse_start-1);
13652 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
13653 FALSE /* Don't force to /x */ );
13657 if (RExC_parse >= RExC_end)
13658 FAIL("Trailing \\");
13661 /* Do not generate "unrecognized" warnings here, we fall
13662 back into the quick-grab loop below */
13663 RExC_parse = parse_start;
13665 } /* end of switch on a \foo sequence */
13670 /* '#' comments should have been spaced over before this function was
13672 assert((RExC_flags & RXf_PMf_EXTENDED) == 0);
13674 if (RExC_flags & RXf_PMf_EXTENDED) {
13675 RExC_parse = reg_skipcomment( pRExC_state, RExC_parse );
13676 if (RExC_parse < RExC_end)
13686 /* Here, we have determined that the next thing is probably a
13687 * literal character. RExC_parse points to the first byte of its
13688 * definition. (It still may be an escape sequence that evaluates
13689 * to a single character) */
13696 /* This allows us to fill a node with just enough spare so that if the final
13697 * character folds, its expansion is guaranteed to fit */
13698 #define MAX_NODE_STRING_SIZE (255-UTF8_MAXBYTES_CASE)
13701 U8 upper_parse = MAX_NODE_STRING_SIZE;
13703 /* We start out as an EXACT node, even if under /i, until we find a
13704 * character which is in a fold. The algorithm now segregates into
13705 * separate nodes, characters that fold from those that don't under
13706 * /i. (This hopefully will create nodes that are fixed strings
13707 * even under /i, giving the optimizer something to grab on to.)
13708 * So, if a node has something in it and the next character is in
13709 * the opposite category, that node is closed up, and the function
13710 * returns. Then regatom is called again, and a new node is
13711 * created for the new category. */
13712 U8 node_type = EXACT;
13714 /* Assume the node will be fully used; the excess is given back at
13715 * the end. We can't make any other length assumptions, as a byte
13716 * input sequence could shrink down. */
13717 Ptrdiff_t initial_size = STR_SZ(256);
13719 bool next_is_quantifier;
13720 char * oldp = NULL;
13722 /* We can convert EXACTF nodes to EXACTFU if they contain only
13723 * characters that match identically regardless of the target
13724 * string's UTF8ness. The reason to do this is that EXACTF is not
13725 * trie-able, EXACTFU is.
13727 * Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they
13728 * contain only above-Latin1 characters (hence must be in UTF8),
13729 * which don't participate in folds with Latin1-range characters,
13730 * as the latter's folds aren't known until runtime. */
13731 bool maybe_exactfu = TRUE;
13733 /* Allocate an EXACT node. The node_type may change below to
13734 * another EXACTish node, but since the size of the node doesn't
13735 * change, it works */
13736 ret = regnode_guts(pRExC_state, node_type, initial_size, "exact");
13737 FILL_NODE(ret, node_type);
13740 s = STRING(REGNODE_p(ret));
13746 /* This breaks under rare circumstances. If folding, we do not
13747 * want to split a node at a character that is a non-final in a
13748 * multi-char fold, as an input string could just happen to want to
13749 * match across the node boundary. The code at the end of the loop
13750 * looks for this, and backs off until it finds not such a
13751 * character, but it is possible (though extremely, extremely
13752 * unlikely) for all characters in the node to be non-final fold
13753 * ones, in which case we just leave the node fully filled, and
13754 * hope that it doesn't match the string in just the wrong place */
13756 assert( ! UTF /* Is at the beginning of a character */
13757 || UTF8_IS_INVARIANT(UCHARAT(RExC_parse))
13758 || UTF8_IS_START(UCHARAT(RExC_parse)));
13761 /* Here, we have a literal character. Find the maximal string of
13762 * them in the input that we can fit into a single EXACTish node.
13763 * We quit at the first non-literal or when the node gets full, or
13764 * under /i the categorization of folding/non-folding character
13766 for (p = RExC_parse; len < upper_parse && p < RExC_end; ) {
13768 /* In most cases each iteration adds one byte to the output.
13769 * The exceptions override this */
13770 Size_t added_len = 1;
13774 /* White space has already been ignored */
13775 assert( (RExC_flags & RXf_PMf_EXTENDED) == 0
13776 || ! is_PATWS_safe((p), RExC_end, UTF));
13788 /* Literal Escapes Switch
13790 This switch is meant to handle escape sequences that
13791 resolve to a literal character.
13793 Every escape sequence that represents something
13794 else, like an assertion or a char class, is handled
13795 in the switch marked 'Special Escapes' above in this
13796 routine, but also has an entry here as anything that
13797 isn't explicitly mentioned here will be treated as
13798 an unescaped equivalent literal.
13801 switch ((U8)*++p) {
13803 /* These are all the special escapes. */
13804 case 'A': /* Start assertion */
13805 case 'b': case 'B': /* Word-boundary assertion*/
13806 case 'C': /* Single char !DANGEROUS! */
13807 case 'd': case 'D': /* digit class */
13808 case 'g': case 'G': /* generic-backref, pos assertion */
13809 case 'h': case 'H': /* HORIZWS */
13810 case 'k': case 'K': /* named backref, keep marker */
13811 case 'p': case 'P': /* Unicode property */
13812 case 'R': /* LNBREAK */
13813 case 's': case 'S': /* space class */
13814 case 'v': case 'V': /* VERTWS */
13815 case 'w': case 'W': /* word class */
13816 case 'X': /* eXtended Unicode "combining
13817 character sequence" */
13818 case 'z': case 'Z': /* End of line/string assertion */
13822 /* Anything after here is an escape that resolves to a
13823 literal. (Except digits, which may or may not)
13829 case 'N': /* Handle a single-code point named character. */
13830 RExC_parse = p + 1;
13831 if (! grok_bslash_N(pRExC_state,
13832 NULL, /* Fail if evaluates to
13833 anything other than a
13834 single code point */
13835 &ender, /* The returned single code
13837 NULL, /* Don't need a count of
13838 how many code points */
13843 if (*flagp & NEED_UTF8)
13844 FAIL("panic: grok_bslash_N set NEED_UTF8");
13845 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13847 /* Here, it wasn't a single code point. Go close
13848 * up this EXACTish node. The switch() prior to
13849 * this switch handles the other cases */
13850 RExC_parse = p = oldp;
13854 RExC_parse = parse_start;
13855 if (ender > 0xff) {
13856 REQUIRE_UTF8(flagp);
13859 /* The \N{} means the pattern, if previously /d,
13860 * becomes /u. That means it can't be an EXACTF node,
13861 * but an EXACTFU */
13862 if (node_type == EXACTF) {
13863 node_type = EXACTFU;
13865 /* If the node already contains something that
13866 * differs between EXACTF and EXACTFU, reparse it
13868 if (! maybe_exactfu) {
13871 maybe_exactfu = TRUE; /* Prob. unnecessary */
13890 ender = ESC_NATIVE;
13900 const char* error_msg;
13902 bool valid = grok_bslash_o(&p,
13906 TO_OUTPUT_WARNINGS(p),
13907 (bool) RExC_strict,
13908 TRUE, /* Output warnings
13913 RExC_parse = p; /* going to die anyway; point
13914 to exact spot of failure */
13917 UPDATE_WARNINGS_LOC(p - 1);
13919 if (ender > 0xff) {
13920 REQUIRE_UTF8(flagp);
13926 UV result = UV_MAX; /* initialize to erroneous
13928 const char* error_msg;
13930 bool valid = grok_bslash_x(&p,
13934 TO_OUTPUT_WARNINGS(p),
13935 (bool) RExC_strict,
13936 TRUE, /* Silence warnings
13941 RExC_parse = p; /* going to die anyway; point
13942 to exact spot of failure */
13945 UPDATE_WARNINGS_LOC(p - 1);
13948 if (ender < 0x100) {
13950 if (RExC_recode_x_to_native) {
13951 ender = LATIN1_TO_NATIVE(ender);
13956 REQUIRE_UTF8(flagp);
13962 ender = grok_bslash_c(*p, TO_OUTPUT_WARNINGS(p));
13963 UPDATE_WARNINGS_LOC(p);
13966 case '8': case '9': /* must be a backreference */
13968 /* we have an escape like \8 which cannot be an octal escape
13969 * so we exit the loop, and let the outer loop handle this
13970 * escape which may or may not be a legitimate backref. */
13972 case '1': case '2': case '3':case '4':
13973 case '5': case '6': case '7':
13974 /* When we parse backslash escapes there is ambiguity
13975 * between backreferences and octal escapes. Any escape
13976 * from \1 - \9 is a backreference, any multi-digit
13977 * escape which does not start with 0 and which when
13978 * evaluated as decimal could refer to an already
13979 * parsed capture buffer is a back reference. Anything
13982 * Note this implies that \118 could be interpreted as
13983 * 118 OR as "\11" . "8" depending on whether there
13984 * were 118 capture buffers defined already in the
13987 /* NOTE, RExC_npar is 1 more than the actual number of
13988 * parens we have seen so far, hence the "<" as opposed
13990 if ( !isDIGIT(p[1]) || S_backref_value(p, RExC_end) < RExC_npar)
13991 { /* Not to be treated as an octal constant, go
13999 I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
14001 ender = grok_oct(p, &numlen, &flags, NULL);
14002 if (ender > 0xff) {
14003 REQUIRE_UTF8(flagp);
14006 if ( isDIGIT(*p) /* like \08, \178 */
14007 && ckWARN(WARN_REGEXP)
14010 reg_warn_non_literal_string(
14012 form_short_octal_warning(p, numlen));
14018 FAIL("Trailing \\");
14021 if (isALPHANUMERIC(*p)) {
14022 /* An alpha followed by '{' is going to fail next
14023 * iteration, so don't output this warning in that
14025 if (! isALPHA(*p) || *(p + 1) != '{') {
14026 ckWARN2reg(p + 1, "Unrecognized escape \\%.1s"
14027 " passed through", p);
14030 goto normal_default;
14031 } /* End of switch on '\' */
14034 /* Trying to gain new uses for '{' without breaking too
14035 * much existing code is hard. The solution currently
14037 * 1) If there is no ambiguity that a '{' should always
14038 * be taken literally, at the start of a construct, we
14040 * 2) If the literal '{' conflicts with our desired use
14041 * of it as a metacharacter, we die. The deprecation
14042 * cycles for this have come and gone.
14043 * 3) If there is ambiguity, we raise a simple warning.
14044 * This could happen, for example, if the user
14045 * intended it to introduce a quantifier, but slightly
14046 * misspelled the quantifier. Without this warning,
14047 * the quantifier would silently be taken as a literal
14048 * string of characters instead of a meta construct */
14049 if (len || (p > RExC_start && isALPHA_A(*(p - 1)))) {
14051 || ( p > parse_start + 1
14052 && isALPHA_A(*(p - 1))
14053 && *(p - 2) == '\\')
14054 || new_regcurly(p, RExC_end))
14056 RExC_parse = p + 1;
14057 vFAIL("Unescaped left brace in regex is "
14060 ckWARNreg(p + 1, "Unescaped left brace in regex is"
14061 " passed through");
14063 goto normal_default;
14066 if (p > RExC_parse && RExC_strict) {
14067 ckWARN2reg(p + 1, "Unescaped literal '%c'", *p);
14070 default: /* A literal character */
14072 if (! UTF8_IS_INVARIANT(*p) && UTF) {
14074 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
14075 &numlen, UTF8_ALLOW_DEFAULT);
14081 } /* End of switch on the literal */
14083 /* Here, have looked at the literal character, and <ender>
14084 * contains its ordinal; <p> points to the character after it.
14085 * We need to check if the next non-ignored thing is a
14086 * quantifier. Move <p> to after anything that should be
14087 * ignored, which, as a side effect, positions <p> for the next
14088 * loop iteration */
14089 skip_to_be_ignored_text(pRExC_state, &p,
14090 FALSE /* Don't force to /x */ );
14092 /* If the next thing is a quantifier, it applies to this
14093 * character only, which means that this character has to be in
14094 * its own node and can't just be appended to the string in an
14095 * existing node, so if there are already other characters in
14096 * the node, close the node with just them, and set up to do
14097 * this character again next time through, when it will be the
14098 * only thing in its new node */
14100 next_is_quantifier = LIKELY(p < RExC_end)
14101 && UNLIKELY(ISMULT2(p));
14103 if (next_is_quantifier && LIKELY(len)) {
14108 /* Ready to add 'ender' to the node */
14110 if (! FOLD) { /* The simple case, just append the literal */
14113 if (UVCHR_IS_INVARIANT(ender) || ! UTF) {
14114 *(s++) = (char) ender;
14117 U8 * new_s = uvchr_to_utf8((U8*)s, ender);
14118 added_len = (char *) new_s - s;
14119 s = (char *) new_s;
14122 else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) {
14124 /* Here are folding under /l, and the code point is
14125 * problematic. If this is the first character in the
14126 * node, change the node type to folding. Otherwise, if
14127 * this is the first problematic character, close up the
14128 * existing node, so can start a new node with this one */
14130 node_type = EXACTFL;
14132 else if (node_type == EXACT) {
14137 /* This code point means we can't simplify things */
14138 maybe_exactfu = FALSE;
14140 /* Here, we are adding a problematic fold character.
14141 * "Problematic" in this context means that its fold isn't
14142 * known until runtime. (The non-problematic code points
14143 * are the above-Latin1 ones that fold to also all
14144 * above-Latin1. Their folds don't vary no matter what the
14145 * locale is.) But here we have characters whose fold
14146 * depends on the locale. We just add in the unfolded
14147 * character, and wait until runtime to fold it */
14148 goto not_fold_common;
14150 else /* regular fold; see if actually is in a fold */
14151 if ( (ender < 256 && ! IS_IN_SOME_FOLD_L1(ender))
14153 && ! _invlist_contains_cp(PL_utf8_foldable, ender)))
14155 /* Here, folding, but the character isn't in a fold.
14157 * Start a new node if previous characters in the node were
14159 if (len && node_type != EXACT) {
14164 /* Here, continuing a node with non-folded characters. Add
14167 if (UVCHR_IS_INVARIANT(ender) || ! UTF) {
14168 *(s++) = (char) ender;
14171 s = (char *) uvchr_to_utf8((U8 *) s, ender);
14172 added_len = UVCHR_SKIP(ender);
14175 else { /* Here, does participate in some fold */
14177 /* If this is the first character in the node, change its
14178 * type to folding. Otherwise, if this is the first
14179 * folding character in the node, close up the existing
14180 * node, so can start a new node with this one. */
14182 node_type = compute_EXACTish(pRExC_state);
14184 else if (node_type == EXACT) {
14189 if (UTF) { /* For UTF-8, we add the folded value */
14190 if (UVCHR_IS_INVARIANT(ender)) {
14191 *(s)++ = (U8) toFOLD(ender);
14194 ender = _to_uni_fold_flags(
14198 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
14199 ? FOLD_FLAGS_NOMIX_ASCII
14206 /* Here is non-UTF8; we don't normally store the folded
14207 * value. First, see if the character's fold differs
14208 * between /d and /u. */
14209 if (PL_fold[ender] != PL_fold_latin1[ender]) {
14210 maybe_exactfu = FALSE;
14213 #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
14214 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
14215 || UNICODE_DOT_DOT_VERSION > 0)
14217 /* On non-ancient Unicode versions, this includes the
14218 * multi-char fold SHARP S to 'ss' */
14220 else if (UNLIKELY( ender == LATIN_SMALL_LETTER_SHARP_S
14222 && isALPHA_FOLD_EQ(ender, 's')
14223 && isALPHA_FOLD_EQ(*(s-1), 's'))))
14226 if (node_type == EXACTFU) {
14227 /* See comments for join_exact() as to why we
14228 * fold this non-UTF at compile time */
14229 if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) {
14232 /* Let the code below add in the extra 's' */
14238 maybe_exactfu = FALSE;
14243 /* Even when folding, we store just the input
14244 * character, as we have an array that finds its fold
14246 *(s++) = (char) ender;
14248 } /* End of adding current character to the node */
14252 if (next_is_quantifier) {
14254 /* Here, the next input is a quantifier, and to get here,
14255 * the current character is the only one in the node. */
14259 } /* End of loop through literal characters */
14261 /* Here we have either exhausted the input or ran out of room in
14262 * the node. (If we encountered a character that can't be in the
14263 * node, transfer is made directly to <loopdone>, and so we
14264 * wouldn't have fallen off the end of the loop.) In the latter
14265 * case, we artificially have to split the node into two, because
14266 * we just don't have enough space to hold everything. This
14267 * creates a problem if the final character participates in a
14268 * multi-character fold in the non-final position, as a match that
14269 * should have occurred won't, due to the way nodes are matched,
14270 * and our artificial boundary. So back off until we find a non-
14271 * problematic character -- one that isn't at the beginning or
14272 * middle of such a fold. (Either it doesn't participate in any
14273 * folds, or appears only in the final position of all the folds it
14274 * does participate in.) A better solution with far fewer false
14275 * positives, and that would fill the nodes more completely, would
14276 * be to actually have available all the multi-character folds to
14277 * test against, and to back-off only far enough to be sure that
14278 * this node isn't ending with a partial one. <upper_parse> is set
14279 * further below (if we need to reparse the node) to include just
14280 * up through that final non-problematic character that this code
14281 * identifies, so when it is set to less than the full node, we can
14282 * skip the rest of this */
14283 if (FOLD && p < RExC_end && upper_parse == MAX_NODE_STRING_SIZE) {
14285 const STRLEN full_len = len;
14287 assert(len >= MAX_NODE_STRING_SIZE);
14289 /* Here, <s> points to the final byte of the final character.
14290 * Look backwards through the string until find a non-
14291 * problematic character */
14295 /* This has no multi-char folds to non-UTF characters */
14296 if (ASCII_FOLD_RESTRICTED) {
14300 while (--s >= s0 && IS_NON_FINAL_FOLD(*s)) { }
14305 /* Point to the first byte of the final character */
14306 s = (char *) utf8_hop((U8 *) s, -1);
14308 while (s >= s0) { /* Search backwards until find
14309 a non-problematic char */
14310 if (UTF8_IS_INVARIANT(*s)) {
14312 /* There are no ascii characters that participate
14313 * in multi-char folds under /aa. In EBCDIC, the
14314 * non-ascii invariants are all control characters,
14315 * so don't ever participate in any folds. */
14316 if (ASCII_FOLD_RESTRICTED
14317 || ! IS_NON_FINAL_FOLD(*s))
14322 else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
14323 if (! IS_NON_FINAL_FOLD(EIGHT_BIT_UTF8_TO_NATIVE(
14329 else if (! _invlist_contains_cp(
14330 PL_NonL1NonFinalFold,
14331 valid_utf8_to_uvchr((U8 *) s, NULL)))
14336 /* Here, the current character is problematic in that
14337 * it does occur in the non-final position of some
14338 * fold, so try the character before it, but have to
14339 * special case the very first byte in the string, so
14340 * we don't read outside the string */
14341 s = (s == s0) ? s -1 : (char *) utf8_hop((U8 *) s, -1);
14342 } /* End of loop backwards through the string */
14344 /* If there were only problematic characters in the string,
14345 * <s> will point to before s0, in which case the length
14346 * should be 0, otherwise include the length of the
14347 * non-problematic character just found */
14348 len = (s < s0) ? 0 : s - s0 + UTF8SKIP(s);
14351 /* Here, have found the final character, if any, that is
14352 * non-problematic as far as ending the node without splitting
14353 * it across a potential multi-char fold. <len> contains the
14354 * number of bytes in the node up-to and including that
14355 * character, or is 0 if there is no such character, meaning
14356 * the whole node contains only problematic characters. In
14357 * this case, give up and just take the node as-is. We can't
14362 /* If the node ends in an 's' we make sure it stays EXACTF,
14363 * as if it turns into an EXACTFU, it could later get
14364 * joined with another 's' that would then wrongly match
14366 if (maybe_exactfu && isALPHA_FOLD_EQ(ender, 's'))
14368 maybe_exactfu = FALSE;
14372 /* Here, the node does contain some characters that aren't
14373 * problematic. If one such is the final character in the
14374 * node, we are done */
14375 if (len == full_len) {
14378 else if (len + ((UTF) ? UTF8SKIP(s) : 1) == full_len) {
14380 /* If the final character is problematic, but the
14381 * penultimate is not, back-off that last character to
14382 * later start a new node with it */
14387 /* Here, the final non-problematic character is earlier
14388 * in the input than the penultimate character. What we do
14389 * is reparse from the beginning, going up only as far as
14390 * this final ok one, thus guaranteeing that the node ends
14391 * in an acceptable character. The reason we reparse is
14392 * that we know how far in the character is, but we don't
14393 * know how to correlate its position with the input parse.
14394 * An alternate implementation would be to build that
14395 * correlation as we go along during the original parse,
14396 * but that would entail extra work for every node, whereas
14397 * this code gets executed only when the string is too
14398 * large for the node, and the final two characters are
14399 * problematic, an infrequent occurrence. Yet another
14400 * possible strategy would be to save the tail of the
14401 * string, and the next time regatom is called, initialize
14402 * with that. The problem with this is that unless you
14403 * back off one more character, you won't be guaranteed
14404 * regatom will get called again, unless regbranch,
14405 * regpiece ... are also changed. If you do back off that
14406 * extra character, so that there is input guaranteed to
14407 * force calling regatom, you can't handle the case where
14408 * just the first character in the node is acceptable. I
14409 * (khw) decided to try this method which doesn't have that
14410 * pitfall; if performance issues are found, we can do a
14411 * combination of the current approach plus that one */
14417 } /* End of verifying node ends with an appropriate char */
14419 loopdone: /* Jumped to when encounters something that shouldn't be
14422 /* Free up any over-allocated space */
14423 change_engine_size(pRExC_state, - (initial_size - STR_SZ(len)));
14425 /* I (khw) don't know if you can get here with zero length, but the
14426 * old code handled this situation by creating a zero-length EXACT
14427 * node. Might as well be NOTHING instead */
14429 OP(REGNODE_p(ret)) = NOTHING;
14432 OP(REGNODE_p(ret)) = node_type;
14434 /* If the node type is EXACT here, check to see if it
14435 * should be EXACTL. */
14436 if (node_type == EXACT) {
14438 OP(REGNODE_p(ret)) = EXACTL;
14443 /* If 'maybe_exactfu' is set, then there are no code points
14444 * that match differently depending on UTF8ness of the
14445 * target string (for /u), or depending on locale for /l */
14446 if (maybe_exactfu) {
14447 if (node_type == EXACTF) {
14448 OP(REGNODE_p(ret)) = EXACTFU;
14450 else if (node_type == EXACTFL) {
14451 OP(REGNODE_p(ret)) = EXACTFLU8;
14454 else if (node_type == EXACTF) {
14455 RExC_seen_d_op = TRUE;
14459 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, len, ender,
14460 FALSE /* Don't look to see if could
14461 be turned into an EXACT
14462 node, as we have already
14467 RExC_parse = p - 1;
14468 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
14471 /* len is STRLEN which is unsigned, need to copy to signed */
14474 vFAIL("Internal disaster");
14477 } /* End of label 'defchar:' */
14479 } /* End of giant switch on input character */
14481 /* Position parse to next real character */
14482 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
14483 FALSE /* Don't force to /x */ );
14484 if ( *RExC_parse == '{'
14485 && OP(REGNODE_p(ret)) != SBOL && ! regcurly(RExC_parse))
14487 if (RExC_strict || new_regcurly(RExC_parse, RExC_end)) {
14489 vFAIL("Unescaped left brace in regex is illegal here");
14491 ckWARNreg(RExC_parse + 1, "Unescaped left brace in regex is"
14492 " passed through");
14500 S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr)
14502 /* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'. It
14503 * sets up the bitmap and any flags, removing those code points from the
14504 * inversion list, setting it to NULL should it become completely empty */
14506 PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST;
14507 assert(PL_regkind[OP(node)] == ANYOF);
14509 ANYOF_BITMAP_ZERO(node);
14510 if (*invlist_ptr) {
14512 /* This gets set if we actually need to modify things */
14513 bool change_invlist = FALSE;
14517 /* Start looking through *invlist_ptr */
14518 invlist_iterinit(*invlist_ptr);
14519 while (invlist_iternext(*invlist_ptr, &start, &end)) {
14523 if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) {
14524 ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP;
14527 /* Quit if are above what we should change */
14528 if (start >= NUM_ANYOF_CODE_POINTS) {
14532 change_invlist = TRUE;
14534 /* Set all the bits in the range, up to the max that we are doing */
14535 high = (end < NUM_ANYOF_CODE_POINTS - 1)
14537 : NUM_ANYOF_CODE_POINTS - 1;
14538 for (i = start; i <= (int) high; i++) {
14539 if (! ANYOF_BITMAP_TEST(node, i)) {
14540 ANYOF_BITMAP_SET(node, i);
14544 invlist_iterfinish(*invlist_ptr);
14546 /* Done with loop; remove any code points that are in the bitmap from
14547 * *invlist_ptr; similarly for code points above the bitmap if we have
14548 * a flag to match all of them anyways */
14549 if (change_invlist) {
14550 _invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr);
14552 if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
14553 _invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr);
14556 /* If have completely emptied it, remove it completely */
14557 if (_invlist_len(*invlist_ptr) == 0) {
14558 SvREFCNT_dec_NN(*invlist_ptr);
14559 *invlist_ptr = NULL;
14564 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
14565 Character classes ([:foo:]) can also be negated ([:^foo:]).
14566 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
14567 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
14568 but trigger failures because they are currently unimplemented. */
14570 #define POSIXCC_DONE(c) ((c) == ':')
14571 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
14572 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
14573 #define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';')
14575 #define WARNING_PREFIX "Assuming NOT a POSIX class since "
14576 #define NO_BLANKS_POSIX_WARNING "no blanks are allowed in one"
14577 #define SEMI_COLON_POSIX_WARNING "a semi-colon was found instead of a colon"
14579 #define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1)
14581 /* 'posix_warnings' and 'warn_text' are names of variables in the following
14583 #define ADD_POSIX_WARNING(p, text) STMT_START { \
14584 if (posix_warnings) { \
14585 if (! RExC_warn_text ) RExC_warn_text = \
14586 (AV *) sv_2mortal((SV *) newAV()); \
14587 av_push(RExC_warn_text, Perl_newSVpvf(aTHX_ \
14591 REPORT_LOCATION_ARGS(p))); \
14594 #define CLEAR_POSIX_WARNINGS() \
14596 if (posix_warnings && RExC_warn_text) \
14597 av_clear(RExC_warn_text); \
14600 #define CLEAR_POSIX_WARNINGS_AND_RETURN(ret) \
14602 CLEAR_POSIX_WARNINGS(); \
14607 S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state,
14609 const char * const s, /* Where the putative posix class begins.
14610 Normally, this is one past the '['. This
14611 parameter exists so it can be somewhere
14612 besides RExC_parse. */
14613 char ** updated_parse_ptr, /* Where to set the updated parse pointer, or
14615 AV ** posix_warnings, /* Where to place any generated warnings, or
14617 const bool check_only /* Don't die if error */
14620 /* This parses what the caller thinks may be one of the three POSIX
14622 * 1) a character class, like [:blank:]
14623 * 2) a collating symbol, like [. .]
14624 * 3) an equivalence class, like [= =]
14625 * In the latter two cases, it croaks if it finds a syntactically legal
14626 * one, as these are not handled by Perl.
14628 * The main purpose is to look for a POSIX character class. It returns:
14629 * a) the class number
14630 * if it is a completely syntactically and semantically legal class.
14631 * 'updated_parse_ptr', if not NULL, is set to point to just after the
14632 * closing ']' of the class
14633 * b) OOB_NAMEDCLASS
14634 * if it appears that one of the three POSIX constructs was meant, but
14635 * its specification was somehow defective. 'updated_parse_ptr', if
14636 * not NULL, is set to point to the character just after the end
14637 * character of the class. See below for handling of warnings.
14638 * c) NOT_MEANT_TO_BE_A_POSIX_CLASS
14639 * if it doesn't appear that a POSIX construct was intended.
14640 * 'updated_parse_ptr' is not changed. No warnings nor errors are
14643 * In b) there may be errors or warnings generated. If 'check_only' is
14644 * TRUE, then any errors are discarded. Warnings are returned to the
14645 * caller via an AV* created into '*posix_warnings' if it is not NULL. If
14646 * instead it is NULL, warnings are suppressed.
14648 * The reason for this function, and its complexity is that a bracketed
14649 * character class can contain just about anything. But it's easy to
14650 * mistype the very specific posix class syntax but yielding a valid
14651 * regular bracketed class, so it silently gets compiled into something
14652 * quite unintended.
14654 * The solution adopted here maintains backward compatibility except that
14655 * it adds a warning if it looks like a posix class was intended but
14656 * improperly specified. The warning is not raised unless what is input
14657 * very closely resembles one of the 14 legal posix classes. To do this,
14658 * it uses fuzzy parsing. It calculates how many single-character edits it
14659 * would take to transform what was input into a legal posix class. Only
14660 * if that number is quite small does it think that the intention was a
14661 * posix class. Obviously these are heuristics, and there will be cases
14662 * where it errs on one side or another, and they can be tweaked as
14663 * experience informs.
14665 * The syntax for a legal posix class is:
14667 * qr/(?xa: \[ : \^? [[:lower:]]{4,6} : \] )/
14669 * What this routine considers syntactically to be an intended posix class
14670 * is this (the comments indicate some restrictions that the pattern
14673 * qr/(?x: \[? # The left bracket, possibly
14675 * \h* # possibly followed by blanks
14676 * (?: \^ \h* )? # possibly a misplaced caret
14677 * [:;]? # The opening class character,
14678 * # possibly omitted. A typo
14679 * # semi-colon can also be used.
14681 * \^? # possibly a correctly placed
14682 * # caret, but not if there was also
14683 * # a misplaced one
14685 * .{3,15} # The class name. If there are
14686 * # deviations from the legal syntax,
14687 * # its edit distance must be close
14688 * # to a real class name in order
14689 * # for it to be considered to be
14690 * # an intended posix class.
14692 * [[:punct:]]? # The closing class character,
14693 * # possibly omitted. If not a colon
14694 * # nor semi colon, the class name
14695 * # must be even closer to a valid
14698 * \]? # The right bracket, possibly
14702 * In the above, \h must be ASCII-only.
14704 * These are heuristics, and can be tweaked as field experience dictates.
14705 * There will be cases when someone didn't intend to specify a posix class
14706 * that this warns as being so. The goal is to minimize these, while
14707 * maximizing the catching of things intended to be a posix class that
14708 * aren't parsed as such.
14712 const char * const e = RExC_end;
14713 unsigned complement = 0; /* If to complement the class */
14714 bool found_problem = FALSE; /* Assume OK until proven otherwise */
14715 bool has_opening_bracket = FALSE;
14716 bool has_opening_colon = FALSE;
14717 int class_number = OOB_NAMEDCLASS; /* Out-of-bounds until find
14719 const char * possible_end = NULL; /* used for a 2nd parse pass */
14720 const char* name_start; /* ptr to class name first char */
14722 /* If the number of single-character typos the input name is away from a
14723 * legal name is no more than this number, it is considered to have meant
14724 * the legal name */
14725 int max_distance = 2;
14727 /* to store the name. The size determines the maximum length before we
14728 * decide that no posix class was intended. Should be at least
14729 * sizeof("alphanumeric") */
14731 STATIC_ASSERT_DECL(C_ARRAY_LENGTH(input_text) >= sizeof "alphanumeric");
14733 PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX;
14735 CLEAR_POSIX_WARNINGS();
14738 return NOT_MEANT_TO_BE_A_POSIX_CLASS;
14741 if (*(p - 1) != '[') {
14742 ADD_POSIX_WARNING(p, "it doesn't start with a '['");
14743 found_problem = TRUE;
14746 has_opening_bracket = TRUE;
14749 /* They could be confused and think you can put spaces between the
14752 found_problem = TRUE;
14756 } while (p < e && isBLANK(*p));
14758 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14761 /* For [. .] and [= =]. These are quite different internally from [: :],
14762 * so they are handled separately. */
14763 if (POSIXCC_NOTYET(*p) && p < e - 3) /* 1 for the close, and 1 for the ']'
14764 and 1 for at least one char in it
14767 const char open_char = *p;
14768 const char * temp_ptr = p + 1;
14770 /* These two constructs are not handled by perl, and if we find a
14771 * syntactically valid one, we croak. khw, who wrote this code, finds
14772 * this explanation of them very unclear:
14773 * http://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html
14774 * And searching the rest of the internet wasn't very helpful either.
14775 * It looks like just about any byte can be in these constructs,
14776 * depending on the locale. But unless the pattern is being compiled
14777 * under /l, which is very rare, Perl runs under the C or POSIX locale.
14778 * In that case, it looks like [= =] isn't allowed at all, and that
14779 * [. .] could be any single code point, but for longer strings the
14780 * constituent characters would have to be the ASCII alphabetics plus
14781 * the minus-hyphen. Any sensible locale definition would limit itself
14782 * to these. And any portable one definitely should. Trying to parse
14783 * the general case is a nightmare (see [perl #127604]). So, this code
14784 * looks only for interiors of these constructs that match:
14786 * Using \w relaxes the apparent rules a little, without adding much
14787 * danger of mistaking something else for one of these constructs.
14789 * [. .] in some implementations described on the internet is usable to
14790 * escape a character that otherwise is special in bracketed character
14791 * classes. For example [.].] means a literal right bracket instead of
14792 * the ending of the class
14794 * [= =] can legitimately contain a [. .] construct, but we don't
14795 * handle this case, as that [. .] construct will later get parsed
14796 * itself and croak then. And [= =] is checked for even when not under
14797 * /l, as Perl has long done so.
14799 * The code below relies on there being a trailing NUL, so it doesn't
14800 * have to keep checking if the parse ptr < e.
14802 if (temp_ptr[1] == open_char) {
14805 else while ( temp_ptr < e
14806 && (isWORDCHAR(*temp_ptr) || *temp_ptr == '-'))
14811 if (*temp_ptr == open_char) {
14813 if (*temp_ptr == ']') {
14815 if (! found_problem && ! check_only) {
14816 RExC_parse = (char *) temp_ptr;
14817 vFAIL3("POSIX syntax [%c %c] is reserved for future "
14818 "extensions", open_char, open_char);
14821 /* Here, the syntax wasn't completely valid, or else the call
14822 * is to check-only */
14823 if (updated_parse_ptr) {
14824 *updated_parse_ptr = (char *) temp_ptr;
14827 CLEAR_POSIX_WARNINGS_AND_RETURN(OOB_NAMEDCLASS);
14831 /* If we find something that started out to look like one of these
14832 * constructs, but isn't, we continue below so that it can be checked
14833 * for being a class name with a typo of '.' or '=' instead of a colon.
14837 /* Here, we think there is a possibility that a [: :] class was meant, and
14838 * we have the first real character. It could be they think the '^' comes
14841 found_problem = TRUE;
14842 ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon");
14847 found_problem = TRUE;
14851 } while (p < e && isBLANK(*p));
14853 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14857 /* But the first character should be a colon, which they could have easily
14858 * mistyped on a qwerty keyboard as a semi-colon (and which may be hard to
14859 * distinguish from a colon, so treat that as a colon). */
14862 has_opening_colon = TRUE;
14864 else if (*p == ';') {
14865 found_problem = TRUE;
14867 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
14868 has_opening_colon = TRUE;
14871 found_problem = TRUE;
14872 ADD_POSIX_WARNING(p, "there must be a starting ':'");
14874 /* Consider an initial punctuation (not one of the recognized ones) to
14875 * be a left terminator */
14876 if (*p != '^' && *p != ']' && isPUNCT(*p)) {
14881 /* They may think that you can put spaces between the components */
14883 found_problem = TRUE;
14887 } while (p < e && isBLANK(*p));
14889 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14894 /* We consider something like [^:^alnum:]] to not have been intended to
14895 * be a posix class, but XXX maybe we should */
14897 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
14904 /* Again, they may think that you can put spaces between the components */
14906 found_problem = TRUE;
14910 } while (p < e && isBLANK(*p));
14912 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14917 /* XXX This ']' may be a typo, and something else was meant. But
14918 * treating it as such creates enough complications, that that
14919 * possibility isn't currently considered here. So we assume that the
14920 * ']' is what is intended, and if we've already found an initial '[',
14921 * this leaves this construct looking like [:] or [:^], which almost
14922 * certainly weren't intended to be posix classes */
14923 if (has_opening_bracket) {
14924 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
14927 /* But this function can be called when we parse the colon for
14928 * something like qr/[alpha:]]/, so we back up to look for the
14933 found_problem = TRUE;
14934 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
14936 else if (*p != ':') {
14938 /* XXX We are currently very restrictive here, so this code doesn't
14939 * consider the possibility that, say, /[alpha.]]/ was intended to
14940 * be a posix class. */
14941 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
14944 /* Here we have something like 'foo:]'. There was no initial colon,
14945 * and we back up over 'foo. XXX Unlike the going forward case, we
14946 * don't handle typos of non-word chars in the middle */
14947 has_opening_colon = FALSE;
14950 while (p > RExC_start && isWORDCHAR(*p)) {
14955 /* Here, we have positioned ourselves to where we think the first
14956 * character in the potential class is */
14959 /* Now the interior really starts. There are certain key characters that
14960 * can end the interior, or these could just be typos. To catch both
14961 * cases, we may have to do two passes. In the first pass, we keep on
14962 * going unless we come to a sequence that matches
14963 * qr/ [[:punct:]] [[:blank:]]* \] /xa
14964 * This means it takes a sequence to end the pass, so two typos in a row if
14965 * that wasn't what was intended. If the class is perfectly formed, just
14966 * this one pass is needed. We also stop if there are too many characters
14967 * being accumulated, but this number is deliberately set higher than any
14968 * real class. It is set high enough so that someone who thinks that
14969 * 'alphanumeric' is a correct name would get warned that it wasn't.
14970 * While doing the pass, we keep track of where the key characters were in
14971 * it. If we don't find an end to the class, and one of the key characters
14972 * was found, we redo the pass, but stop when we get to that character.
14973 * Thus the key character was considered a typo in the first pass, but a
14974 * terminator in the second. If two key characters are found, we stop at
14975 * the second one in the first pass. Again this can miss two typos, but
14976 * catches a single one
14978 * In the first pass, 'possible_end' starts as NULL, and then gets set to
14979 * point to the first key character. For the second pass, it starts as -1.
14985 bool has_blank = FALSE;
14986 bool has_upper = FALSE;
14987 bool has_terminating_colon = FALSE;
14988 bool has_terminating_bracket = FALSE;
14989 bool has_semi_colon = FALSE;
14990 unsigned int name_len = 0;
14991 int punct_count = 0;
14995 /* Squeeze out blanks when looking up the class name below */
14996 if (isBLANK(*p) ) {
14998 found_problem = TRUE;
15003 /* The name will end with a punctuation */
15005 const char * peek = p + 1;
15007 /* Treat any non-']' punctuation followed by a ']' (possibly
15008 * with intervening blanks) as trying to terminate the class.
15009 * ']]' is very likely to mean a class was intended (but
15010 * missing the colon), but the warning message that gets
15011 * generated shows the error position better if we exit the
15012 * loop at the bottom (eventually), so skip it here. */
15014 if (peek < e && isBLANK(*peek)) {
15016 found_problem = TRUE;
15019 } while (peek < e && isBLANK(*peek));
15022 if (peek < e && *peek == ']') {
15023 has_terminating_bracket = TRUE;
15025 has_terminating_colon = TRUE;
15027 else if (*p == ';') {
15028 has_semi_colon = TRUE;
15029 has_terminating_colon = TRUE;
15032 found_problem = TRUE;
15039 /* Here we have punctuation we thought didn't end the class.
15040 * Keep track of the position of the key characters that are
15041 * more likely to have been class-enders */
15042 if (*p == ']' || *p == '[' || *p == ':' || *p == ';') {
15044 /* Allow just one such possible class-ender not actually
15045 * ending the class. */
15046 if (possible_end) {
15052 /* If we have too many punctuation characters, no use in
15054 if (++punct_count > max_distance) {
15058 /* Treat the punctuation as a typo. */
15059 input_text[name_len++] = *p;
15062 else if (isUPPER(*p)) { /* Use lowercase for lookup */
15063 input_text[name_len++] = toLOWER(*p);
15065 found_problem = TRUE;
15067 } else if (! UTF || UTF8_IS_INVARIANT(*p)) {
15068 input_text[name_len++] = *p;
15072 input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL);
15076 /* The declaration of 'input_text' is how long we allow a potential
15077 * class name to be, before saying they didn't mean a class name at
15079 if (name_len >= C_ARRAY_LENGTH(input_text)) {
15084 /* We get to here when the possible class name hasn't been properly
15085 * terminated before:
15086 * 1) we ran off the end of the pattern; or
15087 * 2) found two characters, each of which might have been intended to
15088 * be the name's terminator
15089 * 3) found so many punctuation characters in the purported name,
15090 * that the edit distance to a valid one is exceeded
15091 * 4) we decided it was more characters than anyone could have
15092 * intended to be one. */
15094 found_problem = TRUE;
15096 /* In the final two cases, we know that looking up what we've
15097 * accumulated won't lead to a match, even a fuzzy one. */
15098 if ( name_len >= C_ARRAY_LENGTH(input_text)
15099 || punct_count > max_distance)
15101 /* If there was an intermediate key character that could have been
15102 * an intended end, redo the parse, but stop there */
15103 if (possible_end && possible_end != (char *) -1) {
15104 possible_end = (char *) -1; /* Special signal value to say
15105 we've done a first pass */
15110 /* Otherwise, it can't have meant to have been a class */
15111 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15114 /* If we ran off the end, and the final character was a punctuation
15115 * one, back up one, to look at that final one just below. Later, we
15116 * will restore the parse pointer if appropriate */
15117 if (name_len && p == e && isPUNCT(*(p-1))) {
15122 if (p < e && isPUNCT(*p)) {
15124 has_terminating_bracket = TRUE;
15126 /* If this is a 2nd ']', and the first one is just below this
15127 * one, consider that to be the real terminator. This gives a
15128 * uniform and better positioning for the warning message */
15130 && possible_end != (char *) -1
15131 && *possible_end == ']'
15132 && name_len && input_text[name_len - 1] == ']')
15137 /* And this is actually equivalent to having done the 2nd
15138 * pass now, so set it to not try again */
15139 possible_end = (char *) -1;
15144 has_terminating_colon = TRUE;
15146 else if (*p == ';') {
15147 has_semi_colon = TRUE;
15148 has_terminating_colon = TRUE;
15156 /* Here, we have a class name to look up. We can short circuit the
15157 * stuff below for short names that can't possibly be meant to be a
15158 * class name. (We can do this on the first pass, as any second pass
15159 * will yield an even shorter name) */
15160 if (name_len < 3) {
15161 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15164 /* Find which class it is. Initially switch on the length of the name.
15166 switch (name_len) {
15168 if (memEQs(name_start, 4, "word")) {
15169 /* this is not POSIX, this is the Perl \w */
15170 class_number = ANYOF_WORDCHAR;
15174 /* Names all of length 5: alnum alpha ascii blank cntrl digit
15175 * graph lower print punct space upper
15176 * Offset 4 gives the best switch position. */
15177 switch (name_start[4]) {
15179 if (memBEGINs(name_start, 5, "alph")) /* alpha */
15180 class_number = ANYOF_ALPHA;
15183 if (memBEGINs(name_start, 5, "spac")) /* space */
15184 class_number = ANYOF_SPACE;
15187 if (memBEGINs(name_start, 5, "grap")) /* graph */
15188 class_number = ANYOF_GRAPH;
15191 if (memBEGINs(name_start, 5, "asci")) /* ascii */
15192 class_number = ANYOF_ASCII;
15195 if (memBEGINs(name_start, 5, "blan")) /* blank */
15196 class_number = ANYOF_BLANK;
15199 if (memBEGINs(name_start, 5, "cntr")) /* cntrl */
15200 class_number = ANYOF_CNTRL;
15203 if (memBEGINs(name_start, 5, "alnu")) /* alnum */
15204 class_number = ANYOF_ALPHANUMERIC;
15207 if (memBEGINs(name_start, 5, "lowe")) /* lower */
15208 class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER;
15209 else if (memBEGINs(name_start, 5, "uppe")) /* upper */
15210 class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER;
15213 if (memBEGINs(name_start, 5, "digi")) /* digit */
15214 class_number = ANYOF_DIGIT;
15215 else if (memBEGINs(name_start, 5, "prin")) /* print */
15216 class_number = ANYOF_PRINT;
15217 else if (memBEGINs(name_start, 5, "punc")) /* punct */
15218 class_number = ANYOF_PUNCT;
15223 if (memEQs(name_start, 6, "xdigit"))
15224 class_number = ANYOF_XDIGIT;
15228 /* If the name exactly matches a posix class name the class number will
15229 * here be set to it, and the input almost certainly was meant to be a
15230 * posix class, so we can skip further checking. If instead the syntax
15231 * is exactly correct, but the name isn't one of the legal ones, we
15232 * will return that as an error below. But if neither of these apply,
15233 * it could be that no posix class was intended at all, or that one
15234 * was, but there was a typo. We tease these apart by doing fuzzy
15235 * matching on the name */
15236 if (class_number == OOB_NAMEDCLASS && found_problem) {
15237 const UV posix_names[][6] = {
15238 { 'a', 'l', 'n', 'u', 'm' },
15239 { 'a', 'l', 'p', 'h', 'a' },
15240 { 'a', 's', 'c', 'i', 'i' },
15241 { 'b', 'l', 'a', 'n', 'k' },
15242 { 'c', 'n', 't', 'r', 'l' },
15243 { 'd', 'i', 'g', 'i', 't' },
15244 { 'g', 'r', 'a', 'p', 'h' },
15245 { 'l', 'o', 'w', 'e', 'r' },
15246 { 'p', 'r', 'i', 'n', 't' },
15247 { 'p', 'u', 'n', 'c', 't' },
15248 { 's', 'p', 'a', 'c', 'e' },
15249 { 'u', 'p', 'p', 'e', 'r' },
15250 { 'w', 'o', 'r', 'd' },
15251 { 'x', 'd', 'i', 'g', 'i', 't' }
15253 /* The names of the above all have added NULs to make them the same
15254 * size, so we need to also have the real lengths */
15255 const UV posix_name_lengths[] = {
15256 sizeof("alnum") - 1,
15257 sizeof("alpha") - 1,
15258 sizeof("ascii") - 1,
15259 sizeof("blank") - 1,
15260 sizeof("cntrl") - 1,
15261 sizeof("digit") - 1,
15262 sizeof("graph") - 1,
15263 sizeof("lower") - 1,
15264 sizeof("print") - 1,
15265 sizeof("punct") - 1,
15266 sizeof("space") - 1,
15267 sizeof("upper") - 1,
15268 sizeof("word") - 1,
15269 sizeof("xdigit")- 1
15272 int temp_max = max_distance; /* Use a temporary, so if we
15273 reparse, we haven't changed the
15276 /* Use a smaller max edit distance if we are missing one of the
15278 if ( has_opening_bracket + has_opening_colon < 2
15279 || has_terminating_bracket + has_terminating_colon < 2)
15284 /* See if the input name is close to a legal one */
15285 for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) {
15287 /* Short circuit call if the lengths are too far apart to be
15289 if (abs( (int) (name_len - posix_name_lengths[i]))
15295 if (edit_distance(input_text,
15298 posix_name_lengths[i],
15302 { /* If it is close, it probably was intended to be a class */
15303 goto probably_meant_to_be;
15307 /* Here the input name is not close enough to a valid class name
15308 * for us to consider it to be intended to be a posix class. If
15309 * we haven't already done so, and the parse found a character that
15310 * could have been terminators for the name, but which we absorbed
15311 * as typos during the first pass, repeat the parse, signalling it
15312 * to stop at that character */
15313 if (possible_end && possible_end != (char *) -1) {
15314 possible_end = (char *) -1;
15319 /* Here neither pass found a close-enough class name */
15320 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15323 probably_meant_to_be:
15325 /* Here we think that a posix specification was intended. Update any
15327 if (updated_parse_ptr) {
15328 *updated_parse_ptr = (char *) p;
15331 /* If a posix class name was intended but incorrectly specified, we
15332 * output or return the warnings */
15333 if (found_problem) {
15335 /* We set flags for these issues in the parse loop above instead of
15336 * adding them to the list of warnings, because we can parse it
15337 * twice, and we only want one warning instance */
15339 ADD_POSIX_WARNING(p, "the name must be all lowercase letters");
15342 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15344 if (has_semi_colon) {
15345 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15347 else if (! has_terminating_colon) {
15348 ADD_POSIX_WARNING(p, "there is no terminating ':'");
15350 if (! has_terminating_bracket) {
15351 ADD_POSIX_WARNING(p, "there is no terminating ']'");
15354 if ( posix_warnings
15356 && av_top_index(RExC_warn_text) > -1)
15358 *posix_warnings = RExC_warn_text;
15361 else if (class_number != OOB_NAMEDCLASS) {
15362 /* If it is a known class, return the class. The class number
15363 * #defines are structured so each complement is +1 to the normal
15365 CLEAR_POSIX_WARNINGS_AND_RETURN(class_number + complement);
15367 else if (! check_only) {
15369 /* Here, it is an unrecognized class. This is an error (unless the
15370 * call is to check only, which we've already handled above) */
15371 const char * const complement_string = (complement)
15374 RExC_parse = (char *) p;
15375 vFAIL3utf8f("POSIX class [:%s%" UTF8f ":] unknown",
15377 UTF8fARG(UTF, RExC_parse - name_start - 2, name_start));
15381 return OOB_NAMEDCLASS;
15383 #undef ADD_POSIX_WARNING
15385 STATIC unsigned int
15386 S_regex_set_precedence(const U8 my_operator) {
15388 /* Returns the precedence in the (?[...]) construct of the input operator,
15389 * specified by its character representation. The precedence follows
15390 * general Perl rules, but it extends this so that ')' and ']' have (low)
15391 * precedence even though they aren't really operators */
15393 switch (my_operator) {
15409 NOT_REACHED; /* NOTREACHED */
15410 return 0; /* Silence compiler warning */
15413 STATIC regnode_offset
15414 S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist,
15415 I32 *flagp, U32 depth,
15416 char * const oregcomp_parse)
15418 /* Handle the (?[...]) construct to do set operations */
15420 U8 curchar; /* Current character being parsed */
15421 UV start, end; /* End points of code point ranges */
15422 SV* final = NULL; /* The end result inversion list */
15423 SV* result_string; /* 'final' stringified */
15424 AV* stack; /* stack of operators and operands not yet
15426 AV* fence_stack = NULL; /* A stack containing the positions in
15427 'stack' of where the undealt-with left
15428 parens would be if they were actually
15430 /* The 'volatile' is a workaround for an optimiser bug
15431 * in Solaris Studio 12.3. See RT #127455 */
15432 volatile IV fence = 0; /* Position of where most recent undealt-
15433 with left paren in stack is; -1 if none.
15435 STRLEN len; /* Temporary */
15436 regnode_offset node; /* Temporary, and final regnode returned by
15438 const bool save_fold = FOLD; /* Temporary */
15439 char *save_end, *save_parse; /* Temporaries */
15440 const bool in_locale = LOC; /* we turn off /l during processing */
15442 GET_RE_DEBUG_FLAGS_DECL;
15444 PERL_ARGS_ASSERT_HANDLE_REGEX_SETS;
15446 DEBUG_PARSE("xcls");
15449 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
15452 /* The use of this operator implies /u. This is required so that the
15453 * compile time values are valid in all runtime cases */
15454 REQUIRE_UNI_RULES(flagp, 0);
15456 ckWARNexperimental(RExC_parse,
15457 WARN_EXPERIMENTAL__REGEX_SETS,
15458 "The regex_sets feature is experimental");
15460 /* Everything in this construct is a metacharacter. Operands begin with
15461 * either a '\' (for an escape sequence), or a '[' for a bracketed
15462 * character class. Any other character should be an operator, or
15463 * parenthesis for grouping. Both types of operands are handled by calling
15464 * regclass() to parse them. It is called with a parameter to indicate to
15465 * return the computed inversion list. The parsing here is implemented via
15466 * a stack. Each entry on the stack is a single character representing one
15467 * of the operators; or else a pointer to an operand inversion list. */
15469 #define IS_OPERATOR(a) SvIOK(a)
15470 #define IS_OPERAND(a) (! IS_OPERATOR(a))
15472 /* The stack is kept in Łukasiewicz order. (That's pronounced similar
15473 * to luke-a-shave-itch (or -itz), but people who didn't want to bother
15474 * with pronouncing it called it Reverse Polish instead, but now that YOU
15475 * know how to pronounce it you can use the correct term, thus giving due
15476 * credit to the person who invented it, and impressing your geek friends.
15477 * Wikipedia says that the pronounciation of "Ł" has been changing so that
15478 * it is now more like an English initial W (as in wonk) than an L.)
15480 * This means that, for example, 'a | b & c' is stored on the stack as
15488 * where the numbers in brackets give the stack [array] element number.
15489 * In this implementation, parentheses are not stored on the stack.
15490 * Instead a '(' creates a "fence" so that the part of the stack below the
15491 * fence is invisible except to the corresponding ')' (this allows us to
15492 * replace testing for parens, by using instead subtraction of the fence
15493 * position). As new operands are processed they are pushed onto the stack
15494 * (except as noted in the next paragraph). New operators of higher
15495 * precedence than the current final one are inserted on the stack before
15496 * the lhs operand (so that when the rhs is pushed next, everything will be
15497 * in the correct positions shown above. When an operator of equal or
15498 * lower precedence is encountered in parsing, all the stacked operations
15499 * of equal or higher precedence are evaluated, leaving the result as the
15500 * top entry on the stack. This makes higher precedence operations
15501 * evaluate before lower precedence ones, and causes operations of equal
15502 * precedence to left associate.
15504 * The only unary operator '!' is immediately pushed onto the stack when
15505 * encountered. When an operand is encountered, if the top of the stack is
15506 * a '!", the complement is immediately performed, and the '!' popped. The
15507 * resulting value is treated as a new operand, and the logic in the
15508 * previous paragraph is executed. Thus in the expression
15510 * the stack looks like
15516 * as 'b' gets parsed, the latter gets evaluated to '!b', and the stack
15523 * A ')' is treated as an operator with lower precedence than all the
15524 * aforementioned ones, which causes all operations on the stack above the
15525 * corresponding '(' to be evaluated down to a single resultant operand.
15526 * Then the fence for the '(' is removed, and the operand goes through the
15527 * algorithm above, without the fence.
15529 * A separate stack is kept of the fence positions, so that the position of
15530 * the latest so-far unbalanced '(' is at the top of it.
15532 * The ']' ending the construct is treated as the lowest operator of all,
15533 * so that everything gets evaluated down to a single operand, which is the
15536 sv_2mortal((SV *)(stack = newAV()));
15537 sv_2mortal((SV *)(fence_stack = newAV()));
15539 while (RExC_parse < RExC_end) {
15540 I32 top_index; /* Index of top-most element in 'stack' */
15541 SV** top_ptr; /* Pointer to top 'stack' element */
15542 SV* current = NULL; /* To contain the current inversion list
15544 SV* only_to_avoid_leaks;
15546 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
15547 TRUE /* Force /x */ );
15548 if (RExC_parse >= RExC_end) { /* Fail */
15552 curchar = UCHARAT(RExC_parse);
15556 #ifdef ENABLE_REGEX_SETS_DEBUGGING
15557 /* Enable with -Accflags=-DENABLE_REGEX_SETS_DEBUGGING */
15558 DEBUG_U(dump_regex_sets_structures(pRExC_state,
15559 stack, fence, fence_stack));
15562 top_index = av_tindex_skip_len_mg(stack);
15565 SV** stacked_ptr; /* Ptr to something already on 'stack' */
15566 char stacked_operator; /* The topmost operator on the 'stack'. */
15567 SV* lhs; /* Operand to the left of the operator */
15568 SV* rhs; /* Operand to the right of the operator */
15569 SV* fence_ptr; /* Pointer to top element of the fence
15574 if ( RExC_parse < RExC_end - 1
15575 && (UCHARAT(RExC_parse + 1) == '?'))
15577 /* If is a '(?', could be an embedded '(?flags:(?[...])'.
15578 * This happens when we have some thing like
15580 * my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
15582 * qr/(?[ \p{Digit} & $thai_or_lao ])/;
15584 * Here we would be handling the interpolated
15585 * '$thai_or_lao'. We handle this by a recursive call to
15586 * ourselves which returns the inversion list the
15587 * interpolated expression evaluates to. We use the flags
15588 * from the interpolated pattern. */
15589 U32 save_flags = RExC_flags;
15590 const char * save_parse;
15592 RExC_parse += 2; /* Skip past the '(?' */
15593 save_parse = RExC_parse;
15595 /* Parse any flags for the '(?' */
15596 parse_lparen_question_flags(pRExC_state);
15598 if (RExC_parse == save_parse /* Makes sure there was at
15599 least one flag (or else
15600 this embedding wasn't
15602 || RExC_parse >= RExC_end - 4
15603 || UCHARAT(RExC_parse) != ':'
15604 || UCHARAT(++RExC_parse) != '('
15605 || UCHARAT(++RExC_parse) != '?'
15606 || UCHARAT(++RExC_parse) != '[')
15609 /* In combination with the above, this moves the
15610 * pointer to the point just after the first erroneous
15611 * character (or if there are no flags, to where they
15612 * should have been) */
15613 if (RExC_parse >= RExC_end - 4) {
15614 RExC_parse = RExC_end;
15616 else if (RExC_parse != save_parse) {
15617 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
15619 vFAIL("Expecting '(?flags:(?[...'");
15622 /* Recurse, with the meat of the embedded expression */
15624 (void) handle_regex_sets(pRExC_state, ¤t, flagp,
15625 depth+1, oregcomp_parse);
15627 /* Here, 'current' contains the embedded expression's
15628 * inversion list, and RExC_parse points to the trailing
15629 * ']'; the next character should be the ')' */
15631 if (UCHARAT(RExC_parse) != ')')
15632 vFAIL("Expecting close paren for nested extended charclass");
15634 /* Then the ')' matching the original '(' handled by this
15635 * case: statement */
15637 if (UCHARAT(RExC_parse) != ')')
15638 vFAIL("Expecting close paren for wrapper for nested extended charclass");
15641 RExC_flags = save_flags;
15642 goto handle_operand;
15645 /* A regular '('. Look behind for illegal syntax */
15646 if (top_index - fence >= 0) {
15647 /* If the top entry on the stack is an operator, it had
15648 * better be a '!', otherwise the entry below the top
15649 * operand should be an operator */
15650 if ( ! (top_ptr = av_fetch(stack, top_index, FALSE))
15651 || (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!')
15652 || ( IS_OPERAND(*top_ptr)
15653 && ( top_index - fence < 1
15654 || ! (stacked_ptr = av_fetch(stack,
15657 || ! IS_OPERATOR(*stacked_ptr))))
15660 vFAIL("Unexpected '(' with no preceding operator");
15664 /* Stack the position of this undealt-with left paren */
15665 av_push(fence_stack, newSViv(fence));
15666 fence = top_index + 1;
15670 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
15671 * multi-char folds are allowed. */
15672 if (!regclass(pRExC_state, flagp, depth+1,
15673 TRUE, /* means parse just the next thing */
15674 FALSE, /* don't allow multi-char folds */
15675 FALSE, /* don't silence non-portable warnings. */
15677 FALSE, /* Require return to be an ANYOF */
15680 FAIL2("panic: regclass returned failure to handle_sets, "
15681 "flags=%#" UVxf, (UV) *flagp);
15684 /* regclass() will return with parsing just the \ sequence,
15685 * leaving the parse pointer at the next thing to parse */
15687 goto handle_operand;
15689 case '[': /* Is a bracketed character class */
15691 /* See if this is a [:posix:] class. */
15692 bool is_posix_class = (OOB_NAMEDCLASS
15693 < handle_possible_posix(pRExC_state,
15697 TRUE /* checking only */));
15698 /* If it is a posix class, leave the parse pointer at the '['
15699 * to fool regclass() into thinking it is part of a
15700 * '[[:posix:]]'. */
15701 if (! is_posix_class) {
15705 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
15706 * multi-char folds are allowed. */
15707 if (!regclass(pRExC_state, flagp, depth+1,
15708 is_posix_class, /* parse the whole char
15709 class only if not a
15711 FALSE, /* don't allow multi-char folds */
15712 TRUE, /* silence non-portable warnings. */
15714 FALSE, /* Require return to be an ANYOF */
15717 FAIL2("panic: regclass returned failure to handle_sets, "
15718 "flags=%#" UVxf, (UV) *flagp);
15725 /* function call leaves parse pointing to the ']', except if we
15727 if (is_posix_class) {
15731 goto handle_operand;
15735 if (top_index >= 1) {
15736 goto join_operators;
15739 /* Only a single operand on the stack: are done */
15743 if (av_tindex_skip_len_mg(fence_stack) < 0) {
15744 if (UCHARAT(RExC_parse - 1) == ']') {
15748 vFAIL("Unexpected ')'");
15751 /* If nothing after the fence, is missing an operand */
15752 if (top_index - fence < 0) {
15756 /* If at least two things on the stack, treat this as an
15758 if (top_index - fence >= 1) {
15759 goto join_operators;
15762 /* Here only a single thing on the fenced stack, and there is a
15763 * fence. Get rid of it */
15764 fence_ptr = av_pop(fence_stack);
15766 fence = SvIV(fence_ptr);
15767 SvREFCNT_dec_NN(fence_ptr);
15774 /* Having gotten rid of the fence, we pop the operand at the
15775 * stack top and process it as a newly encountered operand */
15776 current = av_pop(stack);
15777 if (IS_OPERAND(current)) {
15778 goto handle_operand;
15790 /* These binary operators should have a left operand already
15792 if ( top_index - fence < 0
15793 || top_index - fence == 1
15794 || ( ! (top_ptr = av_fetch(stack, top_index, FALSE)))
15795 || ! IS_OPERAND(*top_ptr))
15797 goto unexpected_binary;
15800 /* If only the one operand is on the part of the stack visible
15801 * to us, we just place this operator in the proper position */
15802 if (top_index - fence < 2) {
15804 /* Place the operator before the operand */
15806 SV* lhs = av_pop(stack);
15807 av_push(stack, newSVuv(curchar));
15808 av_push(stack, lhs);
15812 /* But if there is something else on the stack, we need to
15813 * process it before this new operator if and only if the
15814 * stacked operation has equal or higher precedence than the
15819 /* The operator on the stack is supposed to be below both its
15821 if ( ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE))
15822 || IS_OPERAND(*stacked_ptr))
15824 /* But if not, it's legal and indicates we are completely
15825 * done if and only if we're currently processing a ']',
15826 * which should be the final thing in the expression */
15827 if (curchar == ']') {
15833 vFAIL2("Unexpected binary operator '%c' with no "
15834 "preceding operand", curchar);
15836 stacked_operator = (char) SvUV(*stacked_ptr);
15838 if (regex_set_precedence(curchar)
15839 > regex_set_precedence(stacked_operator))
15841 /* Here, the new operator has higher precedence than the
15842 * stacked one. This means we need to add the new one to
15843 * the stack to await its rhs operand (and maybe more
15844 * stuff). We put it before the lhs operand, leaving
15845 * untouched the stacked operator and everything below it
15847 lhs = av_pop(stack);
15848 assert(IS_OPERAND(lhs));
15850 av_push(stack, newSVuv(curchar));
15851 av_push(stack, lhs);
15855 /* Here, the new operator has equal or lower precedence than
15856 * what's already there. This means the operation already
15857 * there should be performed now, before the new one. */
15859 rhs = av_pop(stack);
15860 if (! IS_OPERAND(rhs)) {
15862 /* This can happen when a ! is not followed by an operand,
15863 * like in /(?[\t &!])/ */
15867 lhs = av_pop(stack);
15869 if (! IS_OPERAND(lhs)) {
15871 /* This can happen when there is an empty (), like in
15872 * /(?[[0]+()+])/ */
15876 switch (stacked_operator) {
15878 _invlist_intersection(lhs, rhs, &rhs);
15883 _invlist_union(lhs, rhs, &rhs);
15887 _invlist_subtract(lhs, rhs, &rhs);
15890 case '^': /* The union minus the intersection */
15895 _invlist_union(lhs, rhs, &u);
15896 _invlist_intersection(lhs, rhs, &i);
15897 _invlist_subtract(u, i, &rhs);
15898 SvREFCNT_dec_NN(i);
15899 SvREFCNT_dec_NN(u);
15905 /* Here, the higher precedence operation has been done, and the
15906 * result is in 'rhs'. We overwrite the stacked operator with
15907 * the result. Then we redo this code to either push the new
15908 * operator onto the stack or perform any higher precedence
15909 * stacked operation */
15910 only_to_avoid_leaks = av_pop(stack);
15911 SvREFCNT_dec(only_to_avoid_leaks);
15912 av_push(stack, rhs);
15915 case '!': /* Highest priority, right associative */
15917 /* If what's already at the top of the stack is another '!",
15918 * they just cancel each other out */
15919 if ( (top_ptr = av_fetch(stack, top_index, FALSE))
15920 && (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!'))
15922 only_to_avoid_leaks = av_pop(stack);
15923 SvREFCNT_dec(only_to_avoid_leaks);
15925 else { /* Otherwise, since it's right associative, just push
15927 av_push(stack, newSVuv(curchar));
15932 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
15933 if (RExC_parse >= RExC_end) {
15936 vFAIL("Unexpected character");
15940 /* Here 'current' is the operand. If something is already on the
15941 * stack, we have to check if it is a !. But first, the code above
15942 * may have altered the stack in the time since we earlier set
15945 top_index = av_tindex_skip_len_mg(stack);
15946 if (top_index - fence >= 0) {
15947 /* If the top entry on the stack is an operator, it had better
15948 * be a '!', otherwise the entry below the top operand should
15949 * be an operator */
15950 top_ptr = av_fetch(stack, top_index, FALSE);
15952 if (IS_OPERATOR(*top_ptr)) {
15954 /* The only permissible operator at the top of the stack is
15955 * '!', which is applied immediately to this operand. */
15956 curchar = (char) SvUV(*top_ptr);
15957 if (curchar != '!') {
15958 SvREFCNT_dec(current);
15959 vFAIL2("Unexpected binary operator '%c' with no "
15960 "preceding operand", curchar);
15963 _invlist_invert(current);
15965 only_to_avoid_leaks = av_pop(stack);
15966 SvREFCNT_dec(only_to_avoid_leaks);
15968 /* And we redo with the inverted operand. This allows
15969 * handling multiple ! in a row */
15970 goto handle_operand;
15972 /* Single operand is ok only for the non-binary ')'
15974 else if ((top_index - fence == 0 && curchar != ')')
15975 || (top_index - fence > 0
15976 && (! (stacked_ptr = av_fetch(stack,
15979 || IS_OPERAND(*stacked_ptr))))
15981 SvREFCNT_dec(current);
15982 vFAIL("Operand with no preceding operator");
15986 /* Here there was nothing on the stack or the top element was
15987 * another operand. Just add this new one */
15988 av_push(stack, current);
15990 } /* End of switch on next parse token */
15992 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
15993 } /* End of loop parsing through the construct */
15995 vFAIL("Syntax error in (?[...])");
15999 if (RExC_parse >= RExC_end || RExC_parse[1] != ')') {
16000 if (RExC_parse < RExC_end) {
16004 vFAIL("Unexpected ']' with no following ')' in (?[...");
16007 if (av_tindex_skip_len_mg(fence_stack) >= 0) {
16008 vFAIL("Unmatched (");
16011 if (av_tindex_skip_len_mg(stack) < 0 /* Was empty */
16012 || ((final = av_pop(stack)) == NULL)
16013 || ! IS_OPERAND(final)
16014 || ! is_invlist(final)
16015 || av_tindex_skip_len_mg(stack) >= 0) /* More left on stack */
16018 SvREFCNT_dec(final);
16019 vFAIL("Incomplete expression within '(?[ ])'");
16022 /* Here, 'final' is the resultant inversion list from evaluating the
16023 * expression. Return it if so requested */
16024 if (return_invlist) {
16025 *return_invlist = final;
16029 /* Otherwise generate a resultant node, based on 'final'. regclass() is
16030 * expecting a string of ranges and individual code points */
16031 invlist_iterinit(final);
16032 result_string = newSVpvs("");
16033 while (invlist_iternext(final, &start, &end)) {
16034 if (start == end) {
16035 Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}", start);
16038 Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}-\\x{%" UVXf "}",
16043 /* About to generate an ANYOF (or similar) node from the inversion list we
16044 * have calculated */
16045 save_parse = RExC_parse;
16046 RExC_parse = SvPV(result_string, len);
16047 save_end = RExC_end;
16048 RExC_end = RExC_parse + len;
16049 TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
16051 /* We turn off folding around the call, as the class we have constructed
16052 * already has all folding taken into consideration, and we don't want
16053 * regclass() to add to that */
16054 RExC_flags &= ~RXf_PMf_FOLD;
16055 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if multi-char
16056 * folds are allowed. */
16057 node = regclass(pRExC_state, flagp, depth+1,
16058 FALSE, /* means parse the whole char class */
16059 FALSE, /* don't allow multi-char folds */
16060 TRUE, /* silence non-portable warnings. The above may very
16061 well have generated non-portable code points, but
16062 they're valid on this machine */
16063 FALSE, /* similarly, no need for strict */
16064 FALSE, /* Require return to be an ANYOF */
16069 RExC_parse = save_parse + 1;
16070 RExC_end = save_end;
16071 SvREFCNT_dec_NN(final);
16072 SvREFCNT_dec_NN(result_string);
16075 RExC_flags |= RXf_PMf_FOLD;
16079 FAIL2("panic: regclass returned failure to handle_sets, flags=%#" UVxf,
16082 /* Fix up the node type if we are in locale. (We have pretended we are
16083 * under /u for the purposes of regclass(), as this construct will only
16084 * work under UTF-8 locales. But now we change the opcode to be ANYOFL (so
16085 * as to cause any warnings about bad locales to be output in regexec.c),
16086 * and add the flag that indicates to check if not in a UTF-8 locale. The
16087 * reason we above forbid optimization into something other than an ANYOF
16088 * node is simply to minimize the number of code changes in regexec.c.
16089 * Otherwise we would have to create new EXACTish node types and deal with
16090 * them. This decision could be revisited should this construct become
16093 * (One might think we could look at the resulting ANYOF node and suppress
16094 * the flag if everything is above 255, as those would be UTF-8 only,
16095 * but this isn't true, as the components that led to that result could
16096 * have been locale-affected, and just happen to cancel each other out
16097 * under UTF-8 locales.) */
16099 set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
16101 assert(OP(REGNODE_p(node)) == ANYOF);
16103 OP(REGNODE_p(node)) = ANYOFL;
16104 ANYOF_FLAGS(REGNODE_p(node))
16105 |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
16108 nextchar(pRExC_state);
16109 Set_Node_Length(REGNODE_p(node), RExC_parse - oregcomp_parse + 1); /* MJD */
16113 #ifdef ENABLE_REGEX_SETS_DEBUGGING
16116 S_dump_regex_sets_structures(pTHX_ RExC_state_t *pRExC_state,
16117 AV * stack, const IV fence, AV * fence_stack)
16118 { /* Dumps the stacks in handle_regex_sets() */
16120 const SSize_t stack_top = av_tindex_skip_len_mg(stack);
16121 const SSize_t fence_stack_top = av_tindex_skip_len_mg(fence_stack);
16124 PERL_ARGS_ASSERT_DUMP_REGEX_SETS_STRUCTURES;
16126 PerlIO_printf(Perl_debug_log, "\nParse position is:%s\n", RExC_parse);
16128 if (stack_top < 0) {
16129 PerlIO_printf(Perl_debug_log, "Nothing on stack\n");
16132 PerlIO_printf(Perl_debug_log, "Stack: (fence=%d)\n", (int) fence);
16133 for (i = stack_top; i >= 0; i--) {
16134 SV ** element_ptr = av_fetch(stack, i, FALSE);
16135 if (! element_ptr) {
16138 if (IS_OPERATOR(*element_ptr)) {
16139 PerlIO_printf(Perl_debug_log, "[%d]: %c\n",
16140 (int) i, (int) SvIV(*element_ptr));
16143 PerlIO_printf(Perl_debug_log, "[%d] ", (int) i);
16144 sv_dump(*element_ptr);
16149 if (fence_stack_top < 0) {
16150 PerlIO_printf(Perl_debug_log, "Nothing on fence_stack\n");
16153 PerlIO_printf(Perl_debug_log, "Fence_stack: \n");
16154 for (i = fence_stack_top; i >= 0; i--) {
16155 SV ** element_ptr = av_fetch(fence_stack, i, FALSE);
16156 if (! element_ptr) {
16159 PerlIO_printf(Perl_debug_log, "[%d]: %d\n",
16160 (int) i, (int) SvIV(*element_ptr));
16171 S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist)
16173 /* This adds the Latin1/above-Latin1 folding rules.
16175 * This should be called only for a Latin1-range code points, cp, which is
16176 * known to be involved in a simple fold with other code points above
16177 * Latin1. It would give false results if /aa has been specified.
16178 * Multi-char folds are outside the scope of this, and must be handled
16181 PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS;
16183 assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp));
16185 /* The rules that are valid for all Unicode versions are hard-coded in */
16190 add_cp_to_invlist(*invlist, KELVIN_SIGN);
16194 *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S);
16197 *invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU);
16198 *invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU);
16200 case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
16201 case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
16202 *invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN);
16204 case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
16205 *invlist = add_cp_to_invlist(*invlist,
16206 LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
16209 default: /* Other code points are checked against the data for the
16210 current Unicode version */
16212 Size_t folds_to_count;
16213 unsigned int first_folds_to;
16214 const unsigned int * remaining_folds_to_list;
16218 folded_cp = toFOLD(cp);
16221 U8 dummy_fold[UTF8_MAXBYTES_CASE+1];
16223 folded_cp = _to_fold_latin1(cp, dummy_fold, &dummy_len, 0);
16226 if (folded_cp > 255) {
16227 *invlist = add_cp_to_invlist(*invlist, folded_cp);
16230 folds_to_count = _inverse_folds(folded_cp, &first_folds_to,
16231 &remaining_folds_to_list);
16232 if (folds_to_count == 0) {
16234 /* Use deprecated warning to increase the chances of this being
16236 ckWARN2reg_d(RExC_parse,
16237 "Perl folding rules are not up-to-date for 0x%02X;"
16238 " please use the perlbug utility to report;", cp);
16243 if (first_folds_to > 255) {
16244 *invlist = add_cp_to_invlist(*invlist, first_folds_to);
16246 for (i = 0; i < folds_to_count - 1; i++) {
16247 if (remaining_folds_to_list[i] > 255) {
16248 *invlist = add_cp_to_invlist(*invlist,
16249 remaining_folds_to_list[i]);
16259 S_output_posix_warnings(pTHX_ RExC_state_t *pRExC_state, AV* posix_warnings)
16261 /* Output the elements of the array given by '*posix_warnings' as REGEXP
16265 const bool first_is_fatal = ckDEAD(packWARN(WARN_REGEXP));
16267 PERL_ARGS_ASSERT_OUTPUT_POSIX_WARNINGS;
16269 if (! TO_OUTPUT_WARNINGS(RExC_parse)) {
16273 while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) {
16274 if (first_is_fatal) { /* Avoid leaking this */
16275 av_undef(posix_warnings); /* This isn't necessary if the
16276 array is mortal, but is a
16278 (void) sv_2mortal(msg);
16281 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg));
16282 SvREFCNT_dec_NN(msg);
16285 UPDATE_WARNINGS_LOC(RExC_parse);
16289 S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count)
16291 /* This adds the string scalar <multi_string> to the array
16292 * <multi_char_matches>. <multi_string> is known to have exactly
16293 * <cp_count> code points in it. This is used when constructing a
16294 * bracketed character class and we find something that needs to match more
16295 * than a single character.
16297 * <multi_char_matches> is actually an array of arrays. Each top-level
16298 * element is an array that contains all the strings known so far that are
16299 * the same length. And that length (in number of code points) is the same
16300 * as the index of the top-level array. Hence, the [2] element is an
16301 * array, each element thereof is a string containing TWO code points;
16302 * while element [3] is for strings of THREE characters, and so on. Since
16303 * this is for multi-char strings there can never be a [0] nor [1] element.
16305 * When we rewrite the character class below, we will do so such that the
16306 * longest strings are written first, so that it prefers the longest
16307 * matching strings first. This is done even if it turns out that any
16308 * quantifier is non-greedy, out of this programmer's (khw) laziness. Tom
16309 * Christiansen has agreed that this is ok. This makes the test for the
16310 * ligature 'ffi' come before the test for 'ff', for example */
16313 AV** this_array_ptr;
16315 PERL_ARGS_ASSERT_ADD_MULTI_MATCH;
16317 if (! multi_char_matches) {
16318 multi_char_matches = newAV();
16321 if (av_exists(multi_char_matches, cp_count)) {
16322 this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE);
16323 this_array = *this_array_ptr;
16326 this_array = newAV();
16327 av_store(multi_char_matches, cp_count,
16330 av_push(this_array, multi_string);
16332 return multi_char_matches;
16335 /* The names of properties whose definitions are not known at compile time are
16336 * stored in this SV, after a constant heading. So if the length has been
16337 * changed since initialization, then there is a run-time definition. */
16338 #define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION \
16339 (SvCUR(listsv) != initial_listsv_len)
16341 /* There is a restricted set of white space characters that are legal when
16342 * ignoring white space in a bracketed character class. This generates the
16343 * code to skip them.
16345 * There is a line below that uses the same white space criteria but is outside
16346 * this macro. Both here and there must use the same definition */
16347 #define SKIP_BRACKETED_WHITE_SPACE(do_skip, p) \
16350 while (isBLANK_A(UCHARAT(p))) \
16357 STATIC regnode_offset
16358 S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth,
16359 const bool stop_at_1, /* Just parse the next thing, don't
16360 look for a full character class */
16361 bool allow_multi_folds,
16362 const bool silence_non_portable, /* Don't output warnings
16366 bool optimizable, /* ? Allow a non-ANYOF return
16368 SV** ret_invlist /* Return an inversion list, not a node */
16371 /* parse a bracketed class specification. Most of these will produce an
16372 * ANYOF node; but something like [a] will produce an EXACT node; [aA], an
16373 * EXACTFish node; [[:ascii:]], a POSIXA node; etc. It is more complex
16374 * under /i with multi-character folds: it will be rewritten following the
16375 * paradigm of this example, where the <multi-fold>s are characters which
16376 * fold to multiple character sequences:
16377 * /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
16378 * gets effectively rewritten as:
16379 * /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
16380 * reg() gets called (recursively) on the rewritten version, and this
16381 * function will return what it constructs. (Actually the <multi-fold>s
16382 * aren't physically removed from the [abcdefghi], it's just that they are
16383 * ignored in the recursion by means of a flag:
16384 * <RExC_in_multi_char_class>.)
16386 * ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS
16387 * characters, with the corresponding bit set if that character is in the
16388 * list. For characters above this, a range list or swash is used. There
16389 * are extra bits for \w, etc. in locale ANYOFs, as what these match is not
16390 * determinable at compile time
16392 * On success, returns the offset at which any next node should be placed
16393 * into the regex engine program being compiled.
16395 * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
16396 * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
16400 UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
16402 UV value = OOB_UNICODE, save_value = OOB_UNICODE;
16403 regnode_offset ret;
16405 int namedclass = OOB_NAMEDCLASS;
16406 char *rangebegin = NULL;
16407 bool need_class = 0;
16409 STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
16410 than just initialized. */
16411 SV* properties = NULL; /* Code points that match \p{} \P{} */
16412 SV* posixes = NULL; /* Code points that match classes like [:word:],
16413 extended beyond the Latin1 range. These have to
16414 be kept separate from other code points for much
16415 of this function because their handling is
16416 different under /i, and for most classes under
16418 SV* nposixes = NULL; /* Similarly for [:^word:]. These are kept
16419 separate for a while from the non-complemented
16420 versions because of complications with /d
16422 SV* simple_posixes = NULL; /* But under some conditions, the classes can be
16423 treated more simply than the general case,
16424 leading to less compilation and execution
16426 UV element_count = 0; /* Number of distinct elements in the class.
16427 Optimizations may be possible if this is tiny */
16428 AV * multi_char_matches = NULL; /* Code points that fold to more than one
16429 character; used under /i */
16431 char * stop_ptr = RExC_end; /* where to stop parsing */
16433 /* ignore unescaped whitespace? */
16434 const bool skip_white = cBOOL( ret_invlist
16435 || (RExC_flags & RXf_PMf_EXTENDED_MORE));
16437 /* Unicode properties are stored in a swash; this holds the current one
16438 * being parsed. If this swash is the only above-latin1 component of the
16439 * character class, an optimization is to pass it directly on to the
16440 * execution engine. Otherwise, it is set to NULL to indicate that there
16441 * are other things in the class that have to be dealt with at execution
16443 SV* swash = NULL; /* Code points that match \p{} \P{} */
16445 /* Set if a component of this character class is user-defined; just passed
16446 * on to the engine */
16447 bool has_user_defined_property = FALSE;
16449 /* inversion list of code points this node matches only when the target
16450 * string is in UTF-8. These are all non-ASCII, < 256. (Because is under
16452 SV* has_upper_latin1_only_utf8_matches = NULL;
16454 /* Inversion list of code points this node matches regardless of things
16455 * like locale, folding, utf8ness of the target string */
16456 SV* cp_list = NULL;
16458 /* Like cp_list, but code points on this list need to be checked for things
16459 * that fold to/from them under /i */
16460 SV* cp_foldable_list = NULL;
16462 /* Like cp_list, but code points on this list are valid only when the
16463 * runtime locale is UTF-8 */
16464 SV* only_utf8_locale_list = NULL;
16466 /* In a range, if one of the endpoints is non-character-set portable,
16467 * meaning that it hard-codes a code point that may mean a different
16468 * charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a
16469 * mnemonic '\t' which each mean the same character no matter which
16470 * character set the platform is on. */
16471 unsigned int non_portable_endpoint = 0;
16473 /* Is the range unicode? which means on a platform that isn't 1-1 native
16474 * to Unicode (i.e. non-ASCII), each code point in it should be considered
16475 * to be a Unicode value. */
16476 bool unicode_range = FALSE;
16477 bool invert = FALSE; /* Is this class to be complemented */
16479 bool warn_super = ALWAYS_WARN_SUPER;
16481 const regnode_offset orig_emit = RExC_emit; /* Save the original RExC_emit in
16482 case we need to change the emitted regop to an EXACT. */
16483 const char * orig_parse = RExC_parse;
16484 bool posixl_matches_all = FALSE; /* Does /l class have both e.g. \W,\w ? */
16486 /* This variable is used to mark where the end in the input is of something
16487 * that looks like a POSIX construct but isn't. During the parse, when
16488 * something looks like it could be such a construct is encountered, it is
16489 * checked for being one, but not if we've already checked this area of the
16490 * input. Only after this position is reached do we check again */
16491 char *not_posix_region_end = RExC_parse - 1;
16493 AV* posix_warnings = NULL;
16494 const bool do_posix_warnings = ckWARN(WARN_REGEXP);
16495 U8 op = END; /* The returned node-type, initialized to an impossible
16497 U8 anyof_flags = 0; /* flag bits if the node is an ANYOF-type */
16498 U32 posixl = 0; /* bit field of posix classes matched under /l */
16499 bool use_anyofd = FALSE; /* ? Is this to be an ANYOFD node */
16501 GET_RE_DEBUG_FLAGS_DECL;
16503 PERL_ARGS_ASSERT_REGCLASS;
16505 PERL_UNUSED_ARG(depth);
16509 /* If wants an inversion list returned, we can't optimize to something
16512 optimizable = FALSE;
16515 DEBUG_PARSE("clas");
16517 #if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */ \
16518 || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0 \
16519 && UNICODE_DOT_DOT_VERSION == 0)
16520 allow_multi_folds = FALSE;
16523 listsv = newSVpvs_flags("# comment\n", SVs_TEMP);
16524 initial_listsv_len = SvCUR(listsv);
16525 SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated. */
16527 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
16529 assert(RExC_parse <= RExC_end);
16531 if (UCHARAT(RExC_parse) == '^') { /* Complement the class */
16534 allow_multi_folds = FALSE;
16536 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
16539 /* Check that they didn't say [:posix:] instead of [[:posix:]] */
16540 if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) {
16541 int maybe_class = handle_possible_posix(pRExC_state,
16543 ¬_posix_region_end,
16545 TRUE /* checking only */);
16546 if (maybe_class >= OOB_NAMEDCLASS && do_posix_warnings) {
16547 ckWARN4reg(not_posix_region_end,
16548 "POSIX syntax [%c %c] belongs inside character classes%s",
16549 *RExC_parse, *RExC_parse,
16550 (maybe_class == OOB_NAMEDCLASS)
16551 ? ((POSIXCC_NOTYET(*RExC_parse))
16552 ? " (but this one isn't implemented)"
16553 : " (but this one isn't fully valid)")
16559 /* If the caller wants us to just parse a single element, accomplish this
16560 * by faking the loop ending condition */
16561 if (stop_at_1 && RExC_end > RExC_parse) {
16562 stop_ptr = RExC_parse + 1;
16565 /* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */
16566 if (UCHARAT(RExC_parse) == ']')
16567 goto charclassloop;
16571 if ( posix_warnings
16572 && av_tindex_skip_len_mg(posix_warnings) >= 0
16573 && RExC_parse > not_posix_region_end)
16575 /* Warnings about posix class issues are considered tentative until
16576 * we are far enough along in the parse that we can no longer
16577 * change our mind, at which point we output them. This is done
16578 * each time through the loop so that a later class won't zap them
16579 * before they have been dealt with. */
16580 output_posix_warnings(pRExC_state, posix_warnings);
16583 if (RExC_parse >= stop_ptr) {
16587 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
16589 if (UCHARAT(RExC_parse) == ']') {
16595 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
16596 save_value = value;
16597 save_prevvalue = prevvalue;
16600 rangebegin = RExC_parse;
16602 non_portable_endpoint = 0;
16604 if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) {
16605 value = utf8n_to_uvchr((U8*)RExC_parse,
16606 RExC_end - RExC_parse,
16607 &numlen, UTF8_ALLOW_DEFAULT);
16608 RExC_parse += numlen;
16611 value = UCHARAT(RExC_parse++);
16613 if (value == '[') {
16614 char * posix_class_end;
16615 namedclass = handle_possible_posix(pRExC_state,
16618 do_posix_warnings ? &posix_warnings : NULL,
16619 FALSE /* die if error */);
16620 if (namedclass > OOB_NAMEDCLASS) {
16622 /* If there was an earlier attempt to parse this particular
16623 * posix class, and it failed, it was a false alarm, as this
16624 * successful one proves */
16625 if ( posix_warnings
16626 && av_tindex_skip_len_mg(posix_warnings) >= 0
16627 && not_posix_region_end >= RExC_parse
16628 && not_posix_region_end <= posix_class_end)
16630 av_undef(posix_warnings);
16633 RExC_parse = posix_class_end;
16635 else if (namedclass == OOB_NAMEDCLASS) {
16636 not_posix_region_end = posix_class_end;
16639 namedclass = OOB_NAMEDCLASS;
16642 else if ( RExC_parse - 1 > not_posix_region_end
16643 && MAYBE_POSIXCC(value))
16645 (void) handle_possible_posix(
16647 RExC_parse - 1, /* -1 because parse has already been
16649 ¬_posix_region_end,
16650 do_posix_warnings ? &posix_warnings : NULL,
16651 TRUE /* checking only */);
16653 else if ( strict && ! skip_white
16654 && ( _generic_isCC(value, _CC_VERTSPACE)
16655 || is_VERTWS_cp_high(value)))
16657 vFAIL("Literal vertical space in [] is illegal except under /x");
16659 else if (value == '\\') {
16660 /* Is a backslash; get the code point of the char after it */
16662 if (RExC_parse >= RExC_end) {
16663 vFAIL("Unmatched [");
16666 if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) {
16667 value = utf8n_to_uvchr((U8*)RExC_parse,
16668 RExC_end - RExC_parse,
16669 &numlen, UTF8_ALLOW_DEFAULT);
16670 RExC_parse += numlen;
16673 value = UCHARAT(RExC_parse++);
16675 /* Some compilers cannot handle switching on 64-bit integer
16676 * values, therefore value cannot be an UV. Yes, this will
16677 * be a problem later if we want switch on Unicode.
16678 * A similar issue a little bit later when switching on
16679 * namedclass. --jhi */
16681 /* If the \ is escaping white space when white space is being
16682 * skipped, it means that that white space is wanted literally, and
16683 * is already in 'value'. Otherwise, need to translate the escape
16684 * into what it signifies. */
16685 if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) {
16687 case 'w': namedclass = ANYOF_WORDCHAR; break;
16688 case 'W': namedclass = ANYOF_NWORDCHAR; break;
16689 case 's': namedclass = ANYOF_SPACE; break;
16690 case 'S': namedclass = ANYOF_NSPACE; break;
16691 case 'd': namedclass = ANYOF_DIGIT; break;
16692 case 'D': namedclass = ANYOF_NDIGIT; break;
16693 case 'v': namedclass = ANYOF_VERTWS; break;
16694 case 'V': namedclass = ANYOF_NVERTWS; break;
16695 case 'h': namedclass = ANYOF_HORIZWS; break;
16696 case 'H': namedclass = ANYOF_NHORIZWS; break;
16697 case 'N': /* Handle \N{NAME} in class */
16699 const char * const backslash_N_beg = RExC_parse - 2;
16702 if (! grok_bslash_N(pRExC_state,
16703 NULL, /* No regnode */
16704 &value, /* Yes single value */
16705 &cp_count, /* Multiple code pt count */
16711 if (*flagp & NEED_UTF8)
16712 FAIL("panic: grok_bslash_N set NEED_UTF8");
16714 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
16716 if (cp_count < 0) {
16717 vFAIL("\\N in a character class must be a named character: \\N{...}");
16719 else if (cp_count == 0) {
16720 ckWARNreg(RExC_parse,
16721 "Ignoring zero length \\N{} in character class");
16723 else { /* cp_count > 1 */
16724 if (! RExC_in_multi_char_class) {
16725 if (invert || range || *RExC_parse == '-') {
16728 vFAIL("\\N{} in inverted character class or as a range end-point is restricted to one character");
16730 ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class");
16731 break; /* <value> contains the first code
16732 point. Drop out of the switch to
16736 SV * multi_char_N = newSVpvn(backslash_N_beg,
16737 RExC_parse - backslash_N_beg);
16739 = add_multi_match(multi_char_matches,
16744 } /* End of cp_count != 1 */
16746 /* This element should not be processed further in this
16749 value = save_value;
16750 prevvalue = save_prevvalue;
16751 continue; /* Back to top of loop to get next char */
16754 /* Here, is a single code point, and <value> contains it */
16755 unicode_range = TRUE; /* \N{} are Unicode */
16764 /* We will handle any undefined properties ourselves */
16765 U8 swash_init_flags = _CORE_SWASH_INIT_RETURN_IF_UNDEF
16766 /* And we actually would prefer to get
16767 * the straight inversion list of the
16768 * swash, since we will be accessing it
16769 * anyway, to save a little time */
16770 |_CORE_SWASH_INIT_ACCEPT_INVLIST;
16772 SvREFCNT_dec(swash); /* Free any left-overs */
16774 /* \p means they want Unicode semantics */
16775 REQUIRE_UNI_RULES(flagp, 0);
16777 if (RExC_parse >= RExC_end)
16778 vFAIL2("Empty \\%c", (U8)value);
16779 if (*RExC_parse == '{') {
16780 const U8 c = (U8)value;
16781 e = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
16784 vFAIL2("Missing right brace on \\%c{}", c);
16789 /* White space is allowed adjacent to the braces and after
16790 * any '^', even when not under /x */
16791 while (isSPACE(*RExC_parse)) {
16795 if (UCHARAT(RExC_parse) == '^') {
16797 /* toggle. (The rhs xor gets the single bit that
16798 * differs between P and p; the other xor inverts just
16800 value ^= 'P' ^ 'p';
16803 while (isSPACE(*RExC_parse)) {
16808 if (e == RExC_parse)
16809 vFAIL2("Empty \\%c{}", c);
16811 n = e - RExC_parse;
16812 while (isSPACE(*(RExC_parse + n - 1)))
16815 } /* The \p isn't immediately followed by a '{' */
16816 else if (! isALPHA(*RExC_parse)) {
16817 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16818 vFAIL2("Character following \\%c must be '{' or a "
16819 "single-character Unicode property name",
16827 char* name = RExC_parse;
16828 char* base_name; /* name after any packages are stripped */
16829 char* lookup_name = NULL;
16830 const char * const colon_colon = "::";
16835 /* Temporary workaround for [perl #133136]. For this
16836 * precise input that is in the .t that is failing, load
16837 * utf8.pm, which is what the test wants, so that that
16839 if ( memEQs(RExC_start, e + 1 - RExC_start,
16841 && ! hv_common(GvHVn(PL_incgv),
16843 "utf8.pm", sizeof("utf8.pm") - 1,
16844 0, HV_FETCH_ISEXISTS, NULL, 0))
16846 require_pv("utf8.pm");
16848 invlist = parse_uniprop_string(name, n, FOLD, &invert);
16851 value ^= 'P' ^ 'p';
16856 /* Try to get the definition of the property into
16857 * <invlist>. If /i is in effect, the effective property
16858 * will have its name be <__NAME_i>. The design is
16859 * discussed in commit
16860 * 2f833f5208e26b208886e51e09e2c072b5eabb46 */
16861 name = savepv(Perl_form(aTHX_ "%.*s", (int)n, RExC_parse));
16864 for (i = RExC_parse; i < RExC_parse + n; i++) {
16865 if (isCNTRL(*i) && *i != '\t') {
16866 RExC_parse = e + 1;
16867 vFAIL2("Can't find Unicode property definition \"%s\"", name);
16872 lookup_name = savepv(Perl_form(aTHX_ "__%s_i", name));
16874 /* The function call just below that uses this can fail
16875 * to return, leaking memory if we don't do this */
16876 SAVEFREEPV(lookup_name);
16879 /* Look up the property name, and get its swash and
16880 * inversion list, if the property is found */
16881 swash = _core_swash_init("utf8",
16888 NULL, /* No inversion list */
16891 if (! swash || ! (invlist = _get_swash_invlist(swash))) {
16892 HV* curpkg = (IN_PERL_COMPILETIME)
16894 : CopSTASH(PL_curcop);
16898 if (swash) { /* Got a swash but no inversion list.
16899 Something is likely wrong that will
16900 be sorted-out later */
16901 SvREFCNT_dec_NN(swash);
16905 /* Here didn't find it. It could be a an error (like a
16906 * typo) in specifying a Unicode property, or it could
16907 * be a user-defined property that will be available at
16908 * run-time. The names of these must begin with 'In'
16909 * or 'Is' (after any packages are stripped off). So
16910 * if not one of those, or if we accept only
16911 * compile-time properties, is an error; otherwise add
16912 * it to the list for run-time look up. */
16913 if ((base_name = rninstr(name, name + n,
16914 colon_colon, colon_colon + 2)))
16915 { /* Has ::. We know this must be a user-defined
16918 final_n -= base_name - name;
16927 || base_name[0] != 'I'
16928 || (base_name[1] != 's' && base_name[1] != 'n')
16931 const char * const msg
16933 ? "Illegal user-defined property name"
16934 : "Can't find Unicode property definition";
16935 RExC_parse = e + 1;
16937 /* diag_listed_as: Can't find Unicode property definition "%s" */
16938 vFAIL3utf8f("%s \"%" UTF8f "\"",
16939 msg, UTF8fARG(UTF, n, name));
16942 /* If the property name doesn't already have a package
16943 * name, add the current one to it so that it can be
16944 * referred to outside it. [perl #121777] */
16945 if (! has_pkg && curpkg) {
16946 char* pkgname = HvNAME(curpkg);
16947 if (memNEs(pkgname, HvNAMELEN(curpkg), "main")) {
16948 char* full_name = Perl_form(aTHX_
16952 n = strlen(full_name);
16953 name = savepvn(full_name, n);
16957 Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%s%" UTF8f "%s\n",
16958 (value == 'p' ? '+' : '!'),
16959 (FOLD) ? "__" : "",
16960 UTF8fARG(UTF, n, name),
16961 (FOLD) ? "_i" : "");
16962 has_user_defined_property = TRUE;
16963 optimizable = FALSE; /* Will have to leave this an
16966 /* We don't know yet what this matches, so have to flag
16968 anyof_flags |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
16972 /* Here, did get the swash and its inversion list. If
16973 * the swash is from a user-defined property, then this
16974 * whole character class should be regarded as such */
16975 if (swash_init_flags
16976 & _CORE_SWASH_INIT_USER_DEFINED_PROPERTY)
16978 has_user_defined_property = TRUE;
16983 if (! has_user_defined_property &&
16984 /* We warn on matching an above-Unicode code point
16985 * if the match would return true, except don't
16986 * warn for \p{All}, which has exactly one element
16988 (_invlist_contains_cp(invlist, 0x110000)
16989 && (! (_invlist_len(invlist) == 1
16990 && *invlist_array(invlist) == 0))))
16995 /* Invert if asking for the complement */
16996 if (value == 'P') {
16997 _invlist_union_complement_2nd(properties,
17001 /* The swash can't be used as-is, because we've
17002 * inverted things; delay removing it to here after
17003 * have copied its invlist above */
17005 SvREFCNT_dec_NN(invlist);
17007 SvREFCNT_dec(swash);
17011 _invlist_union(properties, invlist, &properties);
17013 SvREFCNT_dec_NN(invlist);
17019 RExC_parse = e + 1;
17020 namedclass = ANYOF_UNIPROP; /* no official name, but it's
17024 case 'n': value = '\n'; break;
17025 case 'r': value = '\r'; break;
17026 case 't': value = '\t'; break;
17027 case 'f': value = '\f'; break;
17028 case 'b': value = '\b'; break;
17029 case 'e': value = ESC_NATIVE; break;
17030 case 'a': value = '\a'; break;
17032 RExC_parse--; /* function expects to be pointed at the 'o' */
17034 const char* error_msg;
17035 bool valid = grok_bslash_o(&RExC_parse,
17039 TO_OUTPUT_WARNINGS(RExC_parse),
17041 silence_non_portable,
17046 UPDATE_WARNINGS_LOC(RExC_parse - 1);
17048 non_portable_endpoint++;
17051 RExC_parse--; /* function expects to be pointed at the 'x' */
17053 const char* error_msg;
17054 bool valid = grok_bslash_x(&RExC_parse,
17058 TO_OUTPUT_WARNINGS(RExC_parse),
17060 silence_non_portable,
17065 UPDATE_WARNINGS_LOC(RExC_parse - 1);
17067 non_portable_endpoint++;
17070 value = grok_bslash_c(*RExC_parse, TO_OUTPUT_WARNINGS(RExC_parse));
17071 UPDATE_WARNINGS_LOC(RExC_parse);
17073 non_portable_endpoint++;
17075 case '0': case '1': case '2': case '3': case '4':
17076 case '5': case '6': case '7':
17078 /* Take 1-3 octal digits */
17079 I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
17080 numlen = (strict) ? 4 : 3;
17081 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
17082 RExC_parse += numlen;
17085 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
17086 vFAIL("Need exactly 3 octal digits");
17088 else if ( numlen < 3 /* like \08, \178 */
17089 && RExC_parse < RExC_end
17090 && isDIGIT(*RExC_parse)
17091 && ckWARN(WARN_REGEXP))
17093 reg_warn_non_literal_string(
17095 form_short_octal_warning(RExC_parse, numlen));
17098 non_portable_endpoint++;
17102 /* Allow \_ to not give an error */
17103 if (isWORDCHAR(value) && value != '_') {
17105 vFAIL2("Unrecognized escape \\%c in character class",
17109 ckWARN2reg(RExC_parse,
17110 "Unrecognized escape \\%c in character class passed through",
17115 } /* End of switch on char following backslash */
17116 } /* end of handling backslash escape sequences */
17118 /* Here, we have the current token in 'value' */
17120 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
17123 /* a bad range like a-\d, a-[:digit:]. The '-' is taken as a
17124 * literal, as is the character that began the false range, i.e.
17125 * the 'a' in the examples */
17127 const int w = (RExC_parse >= rangebegin)
17128 ? RExC_parse - rangebegin
17132 "False [] range \"%" UTF8f "\"",
17133 UTF8fARG(UTF, w, rangebegin));
17136 ckWARN2reg(RExC_parse,
17137 "False [] range \"%" UTF8f "\"",
17138 UTF8fARG(UTF, w, rangebegin));
17139 cp_list = add_cp_to_invlist(cp_list, '-');
17140 cp_foldable_list = add_cp_to_invlist(cp_foldable_list,
17144 range = 0; /* this was not a true range */
17145 element_count += 2; /* So counts for three values */
17148 classnum = namedclass_to_classnum(namedclass);
17150 if (LOC && namedclass < ANYOF_POSIXL_MAX
17151 #ifndef HAS_ISASCII
17152 && classnum != _CC_ASCII
17155 SV* scratch_list = NULL;
17157 /* What the Posix classes (like \w, [:space:]) match in locale
17158 * isn't knowable under locale until actual match time. Room
17159 * must be reserved (one time per outer bracketed class) to
17160 * store such classes. The space will contain a bit for each
17161 * named class that is to be matched against. This isn't
17162 * needed for \p{} and pseudo-classes, as they are not affected
17163 * by locale, and hence are dealt with separately */
17164 if (! need_class) {
17166 anyof_flags |= ANYOF_MATCHES_POSIXL;
17168 /* We can't change this into some other type of node
17169 * (unless this is the only element, in which case there
17170 * are nodes that mean exactly this) as has runtime
17172 optimizable = FALSE;
17175 /* Coverity thinks it is possible for this to be negative; both
17176 * jhi and khw think it's not, but be safer */
17177 assert(! (anyof_flags & ANYOF_MATCHES_POSIXL)
17178 || (namedclass + ((namedclass % 2) ? -1 : 1)) >= 0);
17180 /* See if it already matches the complement of this POSIX
17182 if ( (anyof_flags & ANYOF_MATCHES_POSIXL)
17183 && POSIXL_TEST(posixl, namedclass + ((namedclass % 2)
17187 posixl_matches_all = TRUE;
17188 break; /* No need to continue. Since it matches both
17189 e.g., \w and \W, it matches everything, and the
17190 bracketed class can be optimized into qr/./s */
17193 /* Add this class to those that should be checked at runtime */
17194 POSIXL_SET(posixl, namedclass);
17196 /* The above-Latin1 characters are not subject to locale rules.
17197 * Just add them to the unconditionally-matched list */
17199 /* Get the list of the above-Latin1 code points this matches */
17200 _invlist_intersection_maybe_complement_2nd(PL_AboveLatin1,
17201 PL_XPosix_ptrs[classnum],
17203 /* Odd numbers are complements, like
17204 * NDIGIT, NASCII, ... */
17205 namedclass % 2 != 0,
17207 /* Checking if 'cp_list' is NULL first saves an extra clone.
17208 * Its reference count will be decremented at the next union,
17209 * etc, or if this is the only instance, at the end of the
17212 cp_list = scratch_list;
17215 _invlist_union(cp_list, scratch_list, &cp_list);
17216 SvREFCNT_dec_NN(scratch_list);
17218 continue; /* Go get next character */
17222 /* Here, is not /l, or is a POSIX class for which /l doesn't
17223 * matter (or is a Unicode property, which is skipped here). */
17224 if (namedclass >= ANYOF_POSIXL_MAX) { /* If a special class */
17225 if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */
17227 /* Here, should be \h, \H, \v, or \V. None of /d, /i
17228 * nor /l make a difference in what these match,
17229 * therefore we just add what they match to cp_list. */
17230 if (classnum != _CC_VERTSPACE) {
17231 assert( namedclass == ANYOF_HORIZWS
17232 || namedclass == ANYOF_NHORIZWS);
17234 /* It turns out that \h is just a synonym for
17236 classnum = _CC_BLANK;
17239 _invlist_union_maybe_complement_2nd(
17241 PL_XPosix_ptrs[classnum],
17242 namedclass % 2 != 0, /* Complement if odd
17243 (NHORIZWS, NVERTWS)
17248 else if ( UNI_SEMANTICS
17249 || AT_LEAST_ASCII_RESTRICTED
17250 || classnum == _CC_ASCII
17251 || (DEPENDS_SEMANTICS && ( classnum == _CC_DIGIT
17252 || classnum == _CC_XDIGIT)))
17254 /* We usually have to worry about /d affecting what POSIX
17255 * classes match, with special code needed because we won't
17256 * know until runtime what all matches. But there is no
17257 * extra work needed under /u and /a; and [:ascii:] is
17258 * unaffected by /d; and :digit: and :xdigit: don't have
17259 * runtime differences under /d. So we can special case
17260 * these, and avoid some extra work below, and at runtime.
17262 _invlist_union_maybe_complement_2nd(
17264 ((AT_LEAST_ASCII_RESTRICTED)
17265 ? PL_Posix_ptrs[classnum]
17266 : PL_XPosix_ptrs[classnum]),
17267 namedclass % 2 != 0,
17270 else { /* Garden variety class. If is NUPPER, NALPHA, ...
17271 complement and use nposixes */
17272 SV** posixes_ptr = namedclass % 2 == 0
17275 _invlist_union_maybe_complement_2nd(
17277 PL_XPosix_ptrs[classnum],
17278 namedclass % 2 != 0,
17282 } /* end of namedclass \blah */
17284 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17286 /* If 'range' is set, 'value' is the ending of a range--check its
17287 * validity. (If value isn't a single code point in the case of a
17288 * range, we should have figured that out above in the code that
17289 * catches false ranges). Later, we will handle each individual code
17290 * point in the range. If 'range' isn't set, this could be the
17291 * beginning of a range, so check for that by looking ahead to see if
17292 * the next real character to be processed is the range indicator--the
17297 /* For unicode ranges, we have to test that the Unicode as opposed
17298 * to the native values are not decreasing. (Above 255, there is
17299 * no difference between native and Unicode) */
17300 if (unicode_range && prevvalue < 255 && value < 255) {
17301 if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) {
17302 goto backwards_range;
17307 if (prevvalue > value) /* b-a */ {
17312 w = RExC_parse - rangebegin;
17314 "Invalid [] range \"%" UTF8f "\"",
17315 UTF8fARG(UTF, w, rangebegin));
17316 NOT_REACHED; /* NOTREACHED */
17320 prevvalue = value; /* save the beginning of the potential range */
17321 if (! stop_at_1 /* Can't be a range if parsing just one thing */
17322 && *RExC_parse == '-')
17324 char* next_char_ptr = RExC_parse + 1;
17326 /* Get the next real char after the '-' */
17327 SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr);
17329 /* If the '-' is at the end of the class (just before the ']',
17330 * it is a literal minus; otherwise it is a range */
17331 if (next_char_ptr < RExC_end && *next_char_ptr != ']') {
17332 RExC_parse = next_char_ptr;
17334 /* a bad range like \w-, [:word:]- ? */
17335 if (namedclass > OOB_NAMEDCLASS) {
17336 if (strict || ckWARN(WARN_REGEXP)) {
17337 const int w = RExC_parse >= rangebegin
17338 ? RExC_parse - rangebegin
17341 vFAIL4("False [] range \"%*.*s\"",
17346 "False [] range \"%*.*s\"",
17350 cp_list = add_cp_to_invlist(cp_list, '-');
17353 range = 1; /* yeah, it's a range! */
17354 continue; /* but do it the next time */
17359 if (namedclass > OOB_NAMEDCLASS) {
17363 /* Here, we have a single value this time through the loop, and
17364 * <prevvalue> is the beginning of the range, if any; or <value> if
17367 /* non-Latin1 code point implies unicode semantics. */
17369 REQUIRE_UNI_RULES(flagp, 0);
17372 /* Ready to process either the single value, or the completed range.
17373 * For single-valued non-inverted ranges, we consider the possibility
17374 * of multi-char folds. (We made a conscious decision to not do this
17375 * for the other cases because it can often lead to non-intuitive
17376 * results. For example, you have the peculiar case that:
17377 * "s s" =~ /^[^\xDF]+$/i => Y
17378 * "ss" =~ /^[^\xDF]+$/i => N
17380 * See [perl #89750] */
17381 if (FOLD && allow_multi_folds && value == prevvalue) {
17382 if (value == LATIN_SMALL_LETTER_SHARP_S
17383 || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
17386 /* Here <value> is indeed a multi-char fold. Get what it is */
17388 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
17391 UV folded = _to_uni_fold_flags(
17395 FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED
17396 ? FOLD_FLAGS_NOMIX_ASCII
17400 /* Here, <folded> should be the first character of the
17401 * multi-char fold of <value>, with <foldbuf> containing the
17402 * whole thing. But, if this fold is not allowed (because of
17403 * the flags), <fold> will be the same as <value>, and should
17404 * be processed like any other character, so skip the special
17406 if (folded != value) {
17408 /* Skip if we are recursed, currently parsing the class
17409 * again. Otherwise add this character to the list of
17410 * multi-char folds. */
17411 if (! RExC_in_multi_char_class) {
17412 STRLEN cp_count = utf8_length(foldbuf,
17413 foldbuf + foldlen);
17414 SV* multi_fold = sv_2mortal(newSVpvs(""));
17416 Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%" UVXf "}", value);
17419 = add_multi_match(multi_char_matches,
17425 /* This element should not be processed further in this
17428 value = save_value;
17429 prevvalue = save_prevvalue;
17435 if (strict && ckWARN(WARN_REGEXP)) {
17438 /* If the range starts above 255, everything is portable and
17439 * likely to be so for any forseeable character set, so don't
17441 if (unicode_range && non_portable_endpoint && prevvalue < 256) {
17442 vWARN(RExC_parse, "Both or neither range ends should be Unicode");
17444 else if (prevvalue != value) {
17446 /* Under strict, ranges that stop and/or end in an ASCII
17447 * printable should have each end point be a portable value
17448 * for it (preferably like 'A', but we don't warn if it is
17449 * a (portable) Unicode name or code point), and the range
17450 * must be be all digits or all letters of the same case.
17451 * Otherwise, the range is non-portable and unclear as to
17452 * what it contains */
17453 if ( (isPRINT_A(prevvalue) || isPRINT_A(value))
17454 && ( non_portable_endpoint
17455 || ! ( (isDIGIT_A(prevvalue) && isDIGIT_A(value))
17456 || (isLOWER_A(prevvalue) && isLOWER_A(value))
17457 || (isUPPER_A(prevvalue) && isUPPER_A(value))
17459 vWARN(RExC_parse, "Ranges of ASCII printables should"
17460 " be some subset of \"0-9\","
17461 " \"A-Z\", or \"a-z\"");
17463 else if (prevvalue >= FIRST_NON_ASCII_DECIMAL_DIGIT) {
17464 SSize_t index_start;
17465 SSize_t index_final;
17467 /* But the nature of Unicode and languages mean we
17468 * can't do the same checks for above-ASCII ranges,
17469 * except in the case of digit ones. These should
17470 * contain only digits from the same group of 10. The
17471 * ASCII case is handled just above. Hence here, the
17472 * range could be a range of digits. First some
17473 * unlikely special cases. Grandfather in that a range
17474 * ending in 19DA (NEW TAI LUE THAM DIGIT ONE) is bad
17475 * if its starting value is one of the 10 digits prior
17476 * to it. This is because it is an alternate way of
17477 * writing 19D1, and some people may expect it to be in
17478 * that group. But it is bad, because it won't give
17479 * the expected results. In Unicode 5.2 it was
17480 * considered to be in that group (of 11, hence), but
17481 * this was fixed in the next version */
17483 if (UNLIKELY(value == 0x19DA && prevvalue >= 0x19D0)) {
17484 goto warn_bad_digit_range;
17486 else if (UNLIKELY( prevvalue >= 0x1D7CE
17487 && value <= 0x1D7FF))
17489 /* This is the only other case currently in Unicode
17490 * where the algorithm below fails. The code
17491 * points just above are the end points of a single
17492 * range containing only decimal digits. It is 5
17493 * different series of 0-9. All other ranges of
17494 * digits currently in Unicode are just a single
17495 * series. (And mktables will notify us if a later
17496 * Unicode version breaks this.)
17498 * If the range being checked is at most 9 long,
17499 * and the digit values represented are in
17500 * numerical order, they are from the same series.
17502 if ( value - prevvalue > 9
17503 || ((( value - 0x1D7CE) % 10)
17504 <= (prevvalue - 0x1D7CE) % 10))
17506 goto warn_bad_digit_range;
17511 /* For all other ranges of digits in Unicode, the
17512 * algorithm is just to check if both end points
17513 * are in the same series, which is the same range.
17515 index_start = _invlist_search(
17516 PL_XPosix_ptrs[_CC_DIGIT],
17519 /* Warn if the range starts and ends with a digit,
17520 * and they are not in the same group of 10. */
17521 if ( index_start >= 0
17522 && ELEMENT_RANGE_MATCHES_INVLIST(index_start)
17524 _invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
17525 value)) != index_start
17526 && index_final >= 0
17527 && ELEMENT_RANGE_MATCHES_INVLIST(index_final))
17529 warn_bad_digit_range:
17530 vWARN(RExC_parse, "Ranges of digits should be"
17531 " from the same group of"
17538 if ((! range || prevvalue == value) && non_portable_endpoint) {
17539 if (isPRINT_A(value)) {
17542 if (isBACKSLASHED_PUNCT(value)) {
17543 literal[d++] = '\\';
17545 literal[d++] = (char) value;
17546 literal[d++] = '\0';
17549 "\"%.*s\" is more clearly written simply as \"%s\"",
17550 (int) (RExC_parse - rangebegin),
17555 else if isMNEMONIC_CNTRL(value) {
17557 "\"%.*s\" is more clearly written simply as \"%s\"",
17558 (int) (RExC_parse - rangebegin),
17560 cntrl_to_mnemonic((U8) value)
17566 /* Deal with this element of the class */
17569 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
17572 /* On non-ASCII platforms, for ranges that span all of 0..255, and ones
17573 * that don't require special handling, we can just add the range like
17574 * we do for ASCII platforms */
17575 if ((UNLIKELY(prevvalue == 0) && value >= 255)
17576 || ! (prevvalue < 256
17578 || (! non_portable_endpoint
17579 && ((isLOWER_A(prevvalue) && isLOWER_A(value))
17580 || (isUPPER_A(prevvalue)
17581 && isUPPER_A(value)))))))
17583 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
17587 /* Here, requires special handling. This can be because it is a
17588 * range whose code points are considered to be Unicode, and so
17589 * must be individually translated into native, or because its a
17590 * subrange of 'A-Z' or 'a-z' which each aren't contiguous in
17591 * EBCDIC, but we have defined them to include only the "expected"
17592 * upper or lower case ASCII alphabetics. Subranges above 255 are
17593 * the same in native and Unicode, so can be added as a range */
17594 U8 start = NATIVE_TO_LATIN1(prevvalue);
17596 U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255;
17597 for (j = start; j <= end; j++) {
17598 cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j));
17601 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
17607 range = 0; /* this range (if it was one) is done now */
17608 } /* End of loop through all the text within the brackets */
17610 if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) {
17611 output_posix_warnings(pRExC_state, posix_warnings);
17614 /* If anything in the class expands to more than one character, we have to
17615 * deal with them by building up a substitute parse string, and recursively
17616 * calling reg() on it, instead of proceeding */
17617 if (multi_char_matches) {
17618 SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
17621 char *save_end = RExC_end;
17622 char *save_parse = RExC_parse;
17623 char *save_start = RExC_start;
17624 Size_t constructed_prefix_len = 0; /* This gives the length of the
17625 constructed portion of the
17626 substitute parse. */
17627 bool first_time = TRUE; /* First multi-char occurrence doesn't get
17632 /* Only one level of recursion allowed */
17633 assert(RExC_copy_start_in_constructed == RExC_precomp);
17635 #if 0 /* Have decided not to deal with multi-char folds in inverted classes,
17636 because too confusing */
17638 sv_catpvs(substitute_parse, "(?:");
17642 /* Look at the longest folds first */
17643 for (cp_count = av_tindex_skip_len_mg(multi_char_matches);
17648 if (av_exists(multi_char_matches, cp_count)) {
17649 AV** this_array_ptr;
17652 this_array_ptr = (AV**) av_fetch(multi_char_matches,
17654 while ((this_sequence = av_pop(*this_array_ptr)) !=
17657 if (! first_time) {
17658 sv_catpvs(substitute_parse, "|");
17660 first_time = FALSE;
17662 sv_catpv(substitute_parse, SvPVX(this_sequence));
17667 /* If the character class contains anything else besides these
17668 * multi-character folds, have to include it in recursive parsing */
17669 if (element_count) {
17670 sv_catpvs(substitute_parse, "|[");
17671 constructed_prefix_len = SvCUR(substitute_parse);
17672 sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
17674 /* Put in a closing ']' only if not going off the end, as otherwise
17675 * we are adding something that really isn't there */
17676 if (RExC_parse < RExC_end) {
17677 sv_catpvs(substitute_parse, "]");
17681 sv_catpvs(substitute_parse, ")");
17684 /* This is a way to get the parse to skip forward a whole named
17685 * sequence instead of matching the 2nd character when it fails the
17687 sv_catpvs(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
17691 /* Set up the data structure so that any errors will be properly
17692 * reported. See the comments at the definition of
17693 * REPORT_LOCATION_ARGS for details */
17694 RExC_copy_start_in_input = (char *) orig_parse;
17695 RExC_start = RExC_parse = SvPV(substitute_parse, len);
17696 RExC_copy_start_in_constructed = RExC_start + constructed_prefix_len;
17697 RExC_end = RExC_parse + len;
17698 RExC_in_multi_char_class = 1;
17700 ret = reg(pRExC_state, 1, ®_flags, depth+1);
17702 *flagp |= reg_flags & (HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PARSE|NEED_UTF8);
17704 /* And restore so can parse the rest of the pattern */
17705 RExC_parse = save_parse;
17706 RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = save_start;
17707 RExC_end = save_end;
17708 RExC_in_multi_char_class = 0;
17709 SvREFCNT_dec_NN(multi_char_matches);
17713 /* If folding, we calculate all characters that could fold to or from the
17714 * ones already on the list */
17715 if (cp_foldable_list) {
17717 UV start, end; /* End points of code point ranges */
17719 SV* fold_intersection = NULL;
17722 /* Our calculated list will be for Unicode rules. For locale
17723 * matching, we have to keep a separate list that is consulted at
17724 * runtime only when the locale indicates Unicode rules. For
17725 * non-locale, we just use the general list */
17727 use_list = &only_utf8_locale_list;
17730 use_list = &cp_list;
17733 /* Only the characters in this class that participate in folds need
17734 * be checked. Get the intersection of this class and all the
17735 * possible characters that are foldable. This can quickly narrow
17736 * down a large class */
17737 _invlist_intersection(PL_utf8_foldable, cp_foldable_list,
17738 &fold_intersection);
17740 /* Now look at the foldable characters in this class individually */
17741 invlist_iterinit(fold_intersection);
17742 while (invlist_iternext(fold_intersection, &start, &end)) {
17746 /* Look at every character in the range */
17747 for (j = start; j <= end; j++) {
17748 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
17751 Size_t folds_to_count;
17752 unsigned int first_folds_to;
17753 const unsigned int * remaining_folds_to_list;
17757 if (IS_IN_SOME_FOLD_L1(j)) {
17759 /* ASCII is always matched; non-ASCII is matched
17760 * only under Unicode rules (which could happen
17761 * under /l if the locale is a UTF-8 one */
17762 if (isASCII(j) || ! DEPENDS_SEMANTICS) {
17763 *use_list = add_cp_to_invlist(*use_list,
17764 PL_fold_latin1[j]);
17767 has_upper_latin1_only_utf8_matches
17768 = add_cp_to_invlist(
17769 has_upper_latin1_only_utf8_matches,
17770 PL_fold_latin1[j]);
17774 if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j)
17775 && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
17777 add_above_Latin1_folds(pRExC_state,
17784 /* Here is an above Latin1 character. We don't have the
17785 * rules hard-coded for it. First, get its fold. This is
17786 * the simple fold, as the multi-character folds have been
17787 * handled earlier and separated out */
17788 folded = _to_uni_fold_flags(j, foldbuf, &foldlen,
17789 (ASCII_FOLD_RESTRICTED)
17790 ? FOLD_FLAGS_NOMIX_ASCII
17793 /* Single character fold of above Latin1. Add everything
17794 * in its fold closure to the list that this node should
17796 folds_to_count = _inverse_folds(folded, &first_folds_to,
17797 &remaining_folds_to_list);
17798 for (k = 0; k <= folds_to_count; k++) {
17799 UV c = (k == 0) /* First time through use itself */
17801 : (k == 1) /* 2nd time use, the first fold */
17804 /* Then the remaining ones */
17805 : remaining_folds_to_list[k-2];
17807 /* /aa doesn't allow folds between ASCII and non- */
17808 if (( ASCII_FOLD_RESTRICTED
17809 && (isASCII(c) != isASCII(j))))
17814 /* Folds under /l which cross the 255/256 boundary are
17815 * added to a separate list. (These are valid only
17816 * when the locale is UTF-8.) */
17817 if (c < 256 && LOC) {
17818 *use_list = add_cp_to_invlist(*use_list, c);
17822 if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
17824 cp_list = add_cp_to_invlist(cp_list, c);
17827 /* Similarly folds involving non-ascii Latin1
17828 * characters under /d are added to their list */
17829 has_upper_latin1_only_utf8_matches
17830 = add_cp_to_invlist(
17831 has_upper_latin1_only_utf8_matches,
17837 SvREFCNT_dec_NN(fold_intersection);
17840 /* Now that we have finished adding all the folds, there is no reason
17841 * to keep the foldable list separate */
17842 _invlist_union(cp_list, cp_foldable_list, &cp_list);
17843 SvREFCNT_dec_NN(cp_foldable_list);
17846 /* And combine the result (if any) with any inversion lists from posix
17847 * classes. The lists are kept separate up to now because we don't want to
17848 * fold the classes (folding of those is automatically handled by the swash
17849 * fetching code) */
17850 if (simple_posixes) { /* These are the classes known to be unaffected by
17853 _invlist_union(cp_list, simple_posixes, &cp_list);
17854 SvREFCNT_dec_NN(simple_posixes);
17857 cp_list = simple_posixes;
17860 if (posixes || nposixes) {
17861 if (! DEPENDS_SEMANTICS) {
17863 /* For everything but /d, we can just add the current 'posixes' and
17864 * 'nposixes' to the main list */
17867 _invlist_union(cp_list, posixes, &cp_list);
17868 SvREFCNT_dec_NN(posixes);
17876 _invlist_union(cp_list, nposixes, &cp_list);
17877 SvREFCNT_dec_NN(nposixes);
17880 cp_list = nposixes;
17885 /* Under /d, things like \w match upper Latin1 characters only if
17886 * the target string is in UTF-8. But things like \W match all the
17887 * upper Latin1 characters if the target string is not in UTF-8.
17889 * Handle the case where there something like \W separately */
17891 SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1, NULL);
17893 /* A complemented posix class matches all upper Latin1
17894 * characters if not in UTF-8. And it matches just certain
17895 * ones when in UTF-8. That means those certain ones are
17896 * matched regardless, so can just be added to the
17897 * unconditional list */
17899 _invlist_union(cp_list, nposixes, &cp_list);
17900 SvREFCNT_dec_NN(nposixes);
17904 cp_list = nposixes;
17907 /* Likewise for 'posixes' */
17908 _invlist_union(posixes, cp_list, &cp_list);
17910 /* Likewise for anything else in the range that matched only
17912 if (has_upper_latin1_only_utf8_matches) {
17913 _invlist_union(cp_list,
17914 has_upper_latin1_only_utf8_matches,
17916 SvREFCNT_dec_NN(has_upper_latin1_only_utf8_matches);
17917 has_upper_latin1_only_utf8_matches = NULL;
17920 /* If we don't match all the upper Latin1 characters regardless
17921 * of UTF-8ness, we have to set a flag to match the rest when
17923 _invlist_subtract(only_non_utf8_list, cp_list,
17924 &only_non_utf8_list);
17925 if (_invlist_len(only_non_utf8_list) != 0) {
17926 anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
17928 SvREFCNT_dec_NN(only_non_utf8_list);
17931 /* Here there were no complemented posix classes. That means
17932 * the upper Latin1 characters in 'posixes' match only when the
17933 * target string is in UTF-8. So we have to add them to the
17934 * list of those types of code points, while adding the
17935 * remainder to the unconditional list.
17937 * First calculate what they are */
17938 SV* nonascii_but_latin1_properties = NULL;
17939 _invlist_intersection(posixes, PL_UpperLatin1,
17940 &nonascii_but_latin1_properties);
17942 /* And add them to the final list of such characters. */
17943 _invlist_union(has_upper_latin1_only_utf8_matches,
17944 nonascii_but_latin1_properties,
17945 &has_upper_latin1_only_utf8_matches);
17947 /* Remove them from what now becomes the unconditional list */
17948 _invlist_subtract(posixes, nonascii_but_latin1_properties,
17951 /* And add those unconditional ones to the final list */
17953 _invlist_union(cp_list, posixes, &cp_list);
17954 SvREFCNT_dec_NN(posixes);
17961 SvREFCNT_dec(nonascii_but_latin1_properties);
17963 /* Get rid of any characters that we now know are matched
17964 * unconditionally from the conditional list, which may make
17965 * that list empty */
17966 _invlist_subtract(has_upper_latin1_only_utf8_matches,
17968 &has_upper_latin1_only_utf8_matches);
17969 if (_invlist_len(has_upper_latin1_only_utf8_matches) == 0) {
17970 SvREFCNT_dec_NN(has_upper_latin1_only_utf8_matches);
17971 has_upper_latin1_only_utf8_matches = NULL;
17977 /* And combine the result (if any) with any inversion list from properties.
17978 * The lists are kept separate up to now so that we can distinguish the two
17979 * in regards to matching above-Unicode. A run-time warning is generated
17980 * if a Unicode property is matched against a non-Unicode code point. But,
17981 * we allow user-defined properties to match anything, without any warning,
17982 * and we also suppress the warning if there is a portion of the character
17983 * class that isn't a Unicode property, and which matches above Unicode, \W
17984 * or [\x{110000}] for example.
17985 * (Note that in this case, unlike the Posix one above, there is no
17986 * <has_upper_latin1_only_utf8_matches>, because having a Unicode property
17987 * forces Unicode semantics */
17991 /* If it matters to the final outcome, see if a non-property
17992 * component of the class matches above Unicode. If so, the
17993 * warning gets suppressed. This is true even if just a single
17994 * such code point is specified, as, though not strictly correct if
17995 * another such code point is matched against, the fact that they
17996 * are using above-Unicode code points indicates they should know
17997 * the issues involved */
17999 warn_super = ! (invert
18000 ^ (invlist_highest(cp_list) > PERL_UNICODE_MAX));
18003 _invlist_union(properties, cp_list, &cp_list);
18004 SvREFCNT_dec_NN(properties);
18007 cp_list = properties;
18012 |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
18014 /* Because an ANYOF node is the only one that warns, this node
18015 * can't be optimized into something else */
18016 optimizable = FALSE;
18020 /* Here, we have calculated what code points should be in the character
18023 * Now we can see about various optimizations. Fold calculation (which we
18024 * did above) needs to take place before inversion. Otherwise /[^k]/i
18025 * would invert to include K, which under /i would match k, which it
18026 * shouldn't. Therefore we can't invert folded locale now, as it won't be
18027 * folded until runtime */
18029 /* If we didn't do folding, it's because some information isn't available
18030 * until runtime; set the run-time fold flag for these. (We don't have to
18031 * worry about properties folding, as that is taken care of by the swash
18032 * fetching). We know to set the flag if we have a non-NULL list for UTF-8
18033 * locales, or the class matches at least one 0-255 range code point */
18036 /* Some things on the list might be unconditionally included because of
18037 * other components. Remove them, and clean up the list if it goes to
18039 if (only_utf8_locale_list && cp_list) {
18040 _invlist_subtract(only_utf8_locale_list, cp_list,
18041 &only_utf8_locale_list);
18043 if (_invlist_len(only_utf8_locale_list) == 0) {
18044 SvREFCNT_dec_NN(only_utf8_locale_list);
18045 only_utf8_locale_list = NULL;
18048 if (only_utf8_locale_list) {
18051 | ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
18053 else if (cp_list) { /* Look to see if a 0-255 code point is in list */
18055 invlist_iterinit(cp_list);
18056 if (invlist_iternext(cp_list, &start, &end) && start < 256) {
18057 anyof_flags |= ANYOFL_FOLD;
18059 invlist_iterfinish(cp_list);
18062 else if ( DEPENDS_SEMANTICS
18063 && ( has_upper_latin1_only_utf8_matches
18064 || (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)))
18067 RExC_seen_d_op = TRUE;
18068 optimizable = FALSE;
18071 /* Optimize inverted simple patterns (e.g. [^a-z]) when everything is known
18072 * at compile time. Besides not inverting folded locale now, we can't
18073 * invert if there are things such as \w, which aren't known until runtime
18078 && ! (anyof_flags & (ANYOF_LOCALE_FLAGS))
18079 && ! HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
18081 _invlist_invert(cp_list);
18083 /* Any swash can't be used as-is, because we've inverted things */
18085 SvREFCNT_dec_NN(swash);
18089 /* Clear the invert flag since have just done it here */
18094 *ret_invlist = cp_list;
18095 SvREFCNT_dec(swash);
18100 /* Some character classes are equivalent to other nodes. Such nodes take
18101 * up less room and generally fewer operations to execute than ANYOF nodes.
18105 int posix_class = -1; /* Illegal value */
18106 const char * cur_parse= RExC_parse;
18107 U8 ANYOFM_mask = 0xFF;
18111 if (UNLIKELY(posixl_matches_all)) {
18114 else if (cp_list && ! invert) {
18116 invlist_iterinit(cp_list);
18117 if (! invlist_iternext(cp_list, &start, &end)) {
18119 /* Here, the list is empty. This happens, for example, when a
18120 * Unicode property that doesn't match anything is the only
18121 * element in the character class (perluniprops.pod notes such
18124 *flagp |= HASWIDTH|SIMPLE;
18126 else if (start == end) { /* The range is a single code point */
18127 if (! invlist_iternext(cp_list, &start, &end)
18129 /* Don't do this optimization if it would require
18130 * changing the pattern to UTF-8 */
18131 && (start < 256 || UTF))
18133 /* Here, the list contains a single code point. Can
18134 * optimize into an EXACTish node */
18145 /* A locale node under folding with one code point can
18146 * be an EXACTFL, as its fold won't be calculated until
18152 /* Here, we are generally folding, but there is only
18153 * one code point to match. If we have to, we use an
18154 * EXACT node, but it would be better for joining with
18155 * adjacent nodes in the optimization phase if we used
18156 * the same EXACTFish node that any such are likely to
18157 * be. We can do this iff the code point doesn't
18158 * participate in any folds. For example, an EXACTF of
18159 * a colon is the same as an EXACT one, since nothing
18160 * folds to or from a colon. */
18162 if (IS_IN_SOME_FOLD_L1(value)) {
18167 if (_invlist_contains_cp(PL_utf8_foldable, value)) {
18172 /* If we haven't found the node type, above, it means
18173 * we can use the prevailing one */
18175 op = compute_EXACTish(pRExC_state);
18179 } /* End of first range contains just a single code point */
18180 else if (start == 0) {
18181 if (end == UV_MAX) {
18183 *flagp |= HASWIDTH|SIMPLE;
18186 else if (end == '\n' - 1
18187 && invlist_iternext(cp_list, &start, &end)
18188 && start == '\n' + 1 && end == UV_MAX)
18191 *flagp |= HASWIDTH|SIMPLE;
18195 invlist_iterfinish(cp_list);
18199 /* Here, didn't find an optimization. See if this matches any
18200 * of the POSIX classes. First try ASCII */
18202 if (_invlistEQ(cp_list, PL_XPosix_ptrs[_CC_ASCII], 0)) {
18204 *flagp |= HASWIDTH|SIMPLE;
18206 else if (_invlistEQ(cp_list, PL_XPosix_ptrs[_CC_ASCII], 1)) {
18208 *flagp |= HASWIDTH|SIMPLE;
18212 /* Then try the other POSIX classes. The POSIXA ones are
18213 * about the same speed as ANYOF ops, but take less room;
18214 * the ones that have above-Latin1 code point matches are
18215 * somewhat faster than ANYOF. */
18217 for (posix_class = 0;
18218 posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC;
18223 for (try_inverted = 0; try_inverted < 2; try_inverted++)
18226 /* Check if matches POSIXA, normal or inverted */
18227 if (PL_Posix_ptrs[posix_class]) {
18228 if (_invlistEQ(cp_list,
18229 PL_Posix_ptrs[posix_class],
18232 op = (try_inverted)
18235 *flagp |= HASWIDTH|SIMPLE;
18240 /* Check if matches POSIXU, normal or inverted */
18241 if (_invlistEQ(cp_list,
18242 PL_XPosix_ptrs[posix_class],
18245 op = (try_inverted)
18248 *flagp |= HASWIDTH|SIMPLE;
18256 /* If it didn't match a POSIX class, it might be able to be
18257 * turned into an ANYOFM node. Compare two different bytes,
18258 * bit-by-bit. In some positions, the bits in each will be 1;
18259 * and in other positions both will be 0; and in some positions
18260 * the bit will be 1 in one byte, and 0 in the other. Let 'n'
18261 * be the number of positions where the bits differ. We create
18262 * a mask which has exactly 'n' 0 bits, each in a position
18263 * where the two bytes differ. Now take the set of all bytes
18264 * that when ANDed with the mask yield the same result. That
18265 * set has 2**n elements, and is representable by just two 8
18266 * bit numbers: the result and the mask. Importantly, matching
18267 * the set can be vectorized by creating a word full of the
18268 * result bytes, and a word full of the mask bytes, yielding a
18269 * significant speed up. Here, see if this node matches such a
18270 * set. As a concrete example consider [01], and the byte
18271 * representing '0' which is 0x30 on ASCII machines. It has
18272 * the bits 0011 0000. Take the mask 1111 1110. If we AND
18273 * 0x31 and 0x30 with that mask we get 0x30. Any other bytes
18274 * ANDed yield something else. So [01], which is a common
18275 * usage, is optimizable into ANYOFM, and can benefit from the
18276 * speed up. We can only do this on UTF-8 invariant bytes,
18277 * because the variance would throw this off. */
18279 PERL_UINT_FAST8_T inverted = 0;
18281 const PERL_UINT_FAST8_T max_permissible = 0xFF;
18283 const PERL_UINT_FAST8_T max_permissible = 0x7F;
18285 if (invlist_highest(cp_list) > max_permissible) {
18286 _invlist_invert(cp_list);
18290 if (invlist_highest(cp_list) <= max_permissible) {
18291 Size_t cp_count = 0;
18292 bool first_time = TRUE;
18293 unsigned int lowest_cp = 0xFF;
18294 U8 bits_differing = 0;
18296 /* Only needed on EBCDIC, as there, variants and non- are mixed
18297 * together. Could #ifdef it out on ASCII, but probably the
18298 * compiler will optimize it out */
18299 bool has_variant = FALSE;
18301 /* Go through the bytes and find the bit positions that differ */
18302 invlist_iterinit(cp_list);
18303 while (invlist_iternext(cp_list, &start, &end)) {
18304 unsigned int i = start;
18306 cp_count += end - start + 1;
18309 if (! UVCHR_IS_INVARIANT(i)) {
18310 has_variant = TRUE;
18314 first_time = FALSE;
18320 /* Find the bit positions that differ from the lowest
18321 * code point in the node. Keep track of all such
18322 * positions by OR'ing */
18323 for (; i <= end; i++) {
18324 if (! UVCHR_IS_INVARIANT(i)) {
18325 has_variant = TRUE;
18329 bits_differing |= i ^ lowest_cp;
18332 invlist_iterfinish(cp_list);
18334 /* At the end of the loop, we count how many bits differ
18335 * from the bits in lowest code point, call the count 'd'.
18336 * If the set we found contains 2**d elements, it is the
18337 * closure of all code points that differ only in those bit
18338 * positions. To convince yourself of that, first note
18339 * that the number in the closure must be a power of 2,
18340 * which we test for. The only way we could have that
18341 * count and it be some differing set, is if we got some
18342 * code points that don't differ from the lowest code point
18343 * in any position, but do differ from each other in some
18344 * other position. That means one code point has a 1 in
18345 * that position, and another has a 0. But that would mean
18346 * that one of them differs from the lowest code point in
18347 * that position, which possibility we've already excluded.
18350 && cp_count == 1U << PL_bitcount[bits_differing])
18352 assert(inverted || cp_count > 1);
18353 op = ANYOFM + inverted;;
18355 /* We need to make the bits that differ be 0's */
18356 ANYOFM_mask = ~ bits_differing; /* This goes into FLAGS
18359 /* The argument is the lowest code point */
18360 anode_arg = lowest_cp;
18361 *flagp |= HASWIDTH|SIMPLE;
18365 _invlist_invert(cp_list);
18372 RExC_parse = (char *)orig_parse;
18373 RExC_emit = orig_emit;
18375 if (regarglen[op]) {
18376 ret = reganode(pRExC_state, op, anode_arg);
18378 ret = reg_node(pRExC_state, op);
18381 RExC_parse = (char *)cur_parse;
18383 if (PL_regkind[op] == EXACT) {
18384 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, 0, value,
18385 TRUE /* downgradable to EXACT */
18388 else if (PL_regkind[op] == POSIXD || PL_regkind[op] == NPOSIXD) {
18389 FLAGS(REGNODE_p(ret)) = posix_class;
18391 else if (PL_regkind[op] == ANYOFM) {
18392 FLAGS(REGNODE_p(ret)) = ANYOFM_mask;
18395 SvREFCNT_dec_NN(cp_list);
18398 } /* End of seeing if can optimize it into a different node */
18400 /* It's going to be an ANYOF node. */
18408 ret = regnode_guts(pRExC_state, op, regarglen[op], "anyof");
18409 FILL_NODE(ret, op); /* We set the argument later */
18410 RExC_emit += 1 + regarglen[op];
18411 ANYOF_FLAGS(REGNODE_p(ret)) = anyof_flags;
18413 /* Here, <cp_list> contains all the code points we can determine at
18414 * compile time that match under all conditions. Go through it, and
18415 * for things that belong in the bitmap, put them there, and delete from
18416 * <cp_list>. While we are at it, see if everything above 255 is in the
18417 * list, and if so, set a flag to speed up execution */
18419 populate_ANYOF_from_invlist(REGNODE_p(ret), &cp_list);
18422 ANYOF_POSIXL_SET_TO_BITMAP(REGNODE_p(ret), posixl);
18426 ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_INVERT;
18429 /* Here, the bitmap has been populated with all the Latin1 code points that
18430 * always match. Can now add to the overall list those that match only
18431 * when the target string is UTF-8 (<has_upper_latin1_only_utf8_matches>).
18433 if (has_upper_latin1_only_utf8_matches) {
18435 _invlist_union(cp_list,
18436 has_upper_latin1_only_utf8_matches,
18438 SvREFCNT_dec_NN(has_upper_latin1_only_utf8_matches);
18441 cp_list = has_upper_latin1_only_utf8_matches;
18443 ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
18446 /* If there is a swash and more than one element, we can't use the swash in
18447 * the optimization below. */
18448 if (swash && element_count > 1) {
18449 SvREFCNT_dec_NN(swash);
18453 /* Note that the optimization of using 'swash' if it is the only thing in
18454 * the class doesn't have us change swash at all, so it can include things
18455 * that are also in the bitmap; otherwise we have purposely deleted that
18456 * duplicate information */
18457 set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
18458 (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
18460 only_utf8_locale_list,
18461 swash, has_user_defined_property);
18463 *flagp |= HASWIDTH|SIMPLE;
18465 if (ANYOF_FLAGS(REGNODE_p(ret)) & ANYOF_LOCALE_FLAGS) {
18466 RExC_contains_locale = 1;
18472 #undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
18475 S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state,
18476 regnode* const node,
18478 SV* const runtime_defns,
18479 SV* const only_utf8_locale_list,
18481 const bool has_user_defined_property)
18483 /* Sets the arg field of an ANYOF-type node 'node', using information about
18484 * the node passed-in. If there is nothing outside the node's bitmap, the
18485 * arg is set to ANYOF_ONLY_HAS_BITMAP. Otherwise, it sets the argument to
18486 * the count returned by add_data(), having allocated and stored an array,
18487 * av, that that count references, as follows:
18488 * av[0] stores the character class description in its textual form.
18489 * This is used later (regexec.c:Perl_regclass_swash()) to
18490 * initialize the appropriate swash, and is also useful for dumping
18491 * the regnode. This is set to &PL_sv_undef if the textual
18492 * description is not needed at run-time (as happens if the other
18493 * elements completely define the class)
18494 * av[1] if &PL_sv_undef, is a placeholder to later contain the swash
18495 * computed from av[0]. But if no further computation need be done,
18496 * the swash is stored here now (and av[0] is &PL_sv_undef).
18497 * av[2] stores the inversion list of code points that match only if the
18498 * current locale is UTF-8
18499 * av[3] stores the cp_list inversion list for use in addition or instead
18500 * of av[0]; used only if cp_list exists and av[1] is &PL_sv_undef.
18501 * (Otherwise everything needed is already in av[0] and av[1])
18502 * av[4] is set if any component of the class is from a user-defined
18503 * property; used only if av[3] exists */
18507 PERL_ARGS_ASSERT_SET_ANYOF_ARG;
18509 if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) {
18510 assert(! (ANYOF_FLAGS(node)
18511 & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP));
18512 ARG_SET(node, ANYOF_ONLY_HAS_BITMAP);
18515 AV * const av = newAV();
18518 av_store(av, 0, (runtime_defns)
18519 ? SvREFCNT_inc(runtime_defns) : &PL_sv_undef);
18522 av_store(av, 1, swash);
18523 SvREFCNT_dec_NN(cp_list);
18526 av_store(av, 1, &PL_sv_undef);
18528 av_store(av, 3, cp_list);
18529 av_store(av, 4, newSVuv(has_user_defined_property));
18533 if (only_utf8_locale_list) {
18534 av_store(av, 2, only_utf8_locale_list);
18537 av_store(av, 2, &PL_sv_undef);
18540 rv = newRV_noinc(MUTABLE_SV(av));
18541 n = add_data(pRExC_state, STR_WITH_LEN("s"));
18542 RExC_rxi->data->data[n] = (void*)rv;
18547 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
18549 Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog,
18550 const regnode* node,
18553 SV** only_utf8_locale_ptr,
18554 SV** output_invlist)
18557 /* For internal core use only.
18558 * Returns the swash for the input 'node' in the regex 'prog'.
18559 * If <doinit> is 'true', will attempt to create the swash if not already
18561 * If <listsvp> is non-null, will return the printable contents of the
18562 * swash. This can be used to get debugging information even before the
18563 * swash exists, by calling this function with 'doinit' set to false, in
18564 * which case the components that will be used to eventually create the
18565 * swash are returned (in a printable form).
18566 * If <only_utf8_locale_ptr> is not NULL, it is where this routine is to
18567 * store an inversion list of code points that should match only if the
18568 * execution-time locale is a UTF-8 one.
18569 * If <output_invlist> is not NULL, it is where this routine is to store an
18570 * inversion list of the code points that would be instead returned in
18571 * <listsvp> if this were NULL. Thus, what gets output in <listsvp>
18572 * when this parameter is used, is just the non-code point data that
18573 * will go into creating the swash. This currently should be just
18574 * user-defined properties whose definitions were not known at compile
18575 * time. Using this parameter allows for easier manipulation of the
18576 * swash's data by the caller. It is illegal to call this function with
18577 * this parameter set, but not <listsvp>
18579 * Tied intimately to how S_set_ANYOF_arg sets up the data structure. Note
18580 * that, in spite of this function's name, the swash it returns may include
18581 * the bitmap data as well */
18584 SV *si = NULL; /* Input swash initialization string */
18585 SV* invlist = NULL;
18587 RXi_GET_DECL(prog, progi);
18588 const struct reg_data * const data = prog ? progi->data : NULL;
18590 PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA;
18591 assert(! output_invlist || listsvp);
18593 if (data && data->count) {
18594 const U32 n = ARG(node);
18596 if (data->what[n] == 's') {
18597 SV * const rv = MUTABLE_SV(data->data[n]);
18598 AV * const av = MUTABLE_AV(SvRV(rv));
18599 SV **const ary = AvARRAY(av);
18600 U8 swash_init_flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
18602 si = *ary; /* ary[0] = the string to initialize the swash with */
18604 if (av_tindex_skip_len_mg(av) >= 2) {
18605 if (only_utf8_locale_ptr
18607 && ary[2] != &PL_sv_undef)
18609 *only_utf8_locale_ptr = ary[2];
18612 assert(only_utf8_locale_ptr);
18613 *only_utf8_locale_ptr = NULL;
18616 /* Elements 3 and 4 are either both present or both absent. [3]
18617 * is any inversion list generated at compile time; [4]
18618 * indicates if that inversion list has any user-defined
18619 * properties in it. */
18620 if (av_tindex_skip_len_mg(av) >= 3) {
18622 if (SvUV(ary[4])) {
18623 swash_init_flags |= _CORE_SWASH_INIT_USER_DEFINED_PROPERTY;
18631 /* Element [1] is reserved for the set-up swash. If already there,
18632 * return it; if not, create it and store it there */
18633 if (ary[1] && SvROK(ary[1])) {
18636 else if (doinit && ((si && si != &PL_sv_undef)
18637 || (invlist && invlist != &PL_sv_undef))) {
18639 sw = _core_swash_init("utf8", /* the utf8 package */
18643 0, /* not from tr/// */
18645 &swash_init_flags);
18646 (void)av_store(av, 1, sw);
18651 /* If requested, return a printable version of what this swash matches */
18653 SV* matches_string = NULL;
18655 /* The swash should be used, if possible, to get the data, as it
18656 * contains the resolved data. But this function can be called at
18657 * compile-time, before everything gets resolved, in which case we
18658 * return the currently best available information, which is the string
18659 * that will eventually be used to do that resolving, 'si' */
18660 if ((! sw || (invlist = _get_swash_invlist(sw)) == NULL)
18661 && (si && si != &PL_sv_undef))
18663 /* Here, we only have 'si' (and possibly some passed-in data in
18664 * 'invlist', which is handled below) If the caller only wants
18665 * 'si', use that. */
18666 if (! output_invlist) {
18667 matches_string = newSVsv(si);
18670 /* But if the caller wants an inversion list of the node, we
18671 * need to parse 'si' and place as much as possible in the
18672 * desired output inversion list, making 'matches_string' only
18673 * contain the currently unresolvable things */
18674 const char *si_string = SvPVX(si);
18675 STRLEN remaining = SvCUR(si);
18679 /* Ignore everything before the first new-line */
18680 while (*si_string != '\n' && remaining > 0) {
18684 assert(remaining > 0);
18689 while (remaining > 0) {
18691 /* The data consists of just strings defining user-defined
18692 * property names, but in prior incarnations, and perhaps
18693 * somehow from pluggable regex engines, it could still
18694 * hold hex code point definitions. Each component of a
18695 * range would be separated by a tab, and each range by a
18696 * new-line. If these are found, instead add them to the
18697 * inversion list */
18698 I32 grok_flags = PERL_SCAN_SILENT_ILLDIGIT
18699 |PERL_SCAN_SILENT_NON_PORTABLE;
18700 STRLEN len = remaining;
18701 UV cp = grok_hex(si_string, &len, &grok_flags, NULL);
18703 /* If the hex decode routine found something, it should go
18704 * up to the next \n */
18705 if ( *(si_string + len) == '\n') {
18706 if (count) { /* 2nd code point on line */
18707 *output_invlist = _add_range_to_invlist(*output_invlist, prev_cp, cp);
18710 *output_invlist = add_cp_to_invlist(*output_invlist, cp);
18713 goto prepare_for_next_iteration;
18716 /* If the hex decode was instead for the lower range limit,
18717 * save it, and go parse the upper range limit */
18718 if (*(si_string + len) == '\t') {
18719 assert(count == 0);
18723 prepare_for_next_iteration:
18724 si_string += len + 1;
18725 remaining -= len + 1;
18729 /* Here, didn't find a legal hex number. Just add it from
18730 * here to the next \n */
18733 while (*(si_string + len) != '\n' && remaining > 0) {
18737 if (*(si_string + len) == '\n') {
18741 if (matches_string) {
18742 sv_catpvn(matches_string, si_string, len - 1);
18745 matches_string = newSVpvn(si_string, len - 1);
18748 sv_catpvs(matches_string, " ");
18749 } /* end of loop through the text */
18751 assert(matches_string);
18752 if (SvCUR(matches_string)) { /* Get rid of trailing blank */
18753 SvCUR_set(matches_string, SvCUR(matches_string) - 1);
18755 } /* end of has an 'si' but no swash */
18758 /* If we have a swash in place, its equivalent inversion list was above
18759 * placed into 'invlist'. If not, this variable may contain a stored
18760 * inversion list which is information beyond what is in 'si' */
18763 /* Again, if the caller doesn't want the output inversion list, put
18764 * everything in 'matches-string' */
18765 if (! output_invlist) {
18766 if ( ! matches_string) {
18767 matches_string = newSVpvs("\n");
18769 sv_catsv(matches_string, invlist_contents(invlist,
18770 TRUE /* traditional style */
18773 else if (! *output_invlist) {
18774 *output_invlist = invlist_clone(invlist, NULL);
18777 _invlist_union(*output_invlist, invlist, output_invlist);
18781 *listsvp = matches_string;
18786 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
18788 /* reg_skipcomment()
18790 Absorbs an /x style # comment from the input stream,
18791 returning a pointer to the first character beyond the comment, or if the
18792 comment terminates the pattern without anything following it, this returns
18793 one past the final character of the pattern (in other words, RExC_end) and
18794 sets the REG_RUN_ON_COMMENT_SEEN flag.
18796 Note it's the callers responsibility to ensure that we are
18797 actually in /x mode
18801 PERL_STATIC_INLINE char*
18802 S_reg_skipcomment(RExC_state_t *pRExC_state, char* p)
18804 PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
18808 while (p < RExC_end) {
18809 if (*(++p) == '\n') {
18814 /* we ran off the end of the pattern without ending the comment, so we have
18815 * to add an \n when wrapping */
18816 RExC_seen |= REG_RUN_ON_COMMENT_SEEN;
18821 S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state,
18823 const bool force_to_xmod
18826 /* If the text at the current parse position '*p' is a '(?#...)' comment,
18827 * or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p'
18828 * is /x whitespace, advance '*p' so that on exit it points to the first
18829 * byte past all such white space and comments */
18831 const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED);
18833 PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT;
18835 assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p));
18838 if (RExC_end - (*p) >= 3
18840 && *(*p + 1) == '?'
18841 && *(*p + 2) == '#')
18843 while (*(*p) != ')') {
18844 if ((*p) == RExC_end)
18845 FAIL("Sequence (?#... not terminated");
18853 const char * save_p = *p;
18854 while ((*p) < RExC_end) {
18856 if ((len = is_PATWS_safe((*p), RExC_end, UTF))) {
18859 else if (*(*p) == '#') {
18860 (*p) = reg_skipcomment(pRExC_state, (*p));
18866 if (*p != save_p) {
18879 Advances the parse position by one byte, unless that byte is the beginning
18880 of a '(?#...)' style comment, or is /x whitespace and /x is in effect. In
18881 those two cases, the parse position is advanced beyond all such comments and
18884 This is the UTF, (?#...), and /x friendly way of saying RExC_parse++.
18888 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
18890 PERL_ARGS_ASSERT_NEXTCHAR;
18892 if (RExC_parse < RExC_end) {
18894 || UTF8_IS_INVARIANT(*RExC_parse)
18895 || UTF8_IS_START(*RExC_parse));
18897 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
18899 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
18900 FALSE /* Don't force /x */ );
18905 S_change_engine_size(pTHX_ RExC_state_t *pRExC_state, const Ptrdiff_t size)
18907 PERL_ARGS_ASSERT_CHANGE_ENGINE_SIZE;
18912 sizeof(regexp_internal) + (RExC_size + 1) * sizeof(regnode),
18913 /* +1 for REG_MAGIC */
18916 if ( RExC_rxi == NULL )
18917 FAIL("Regexp out of space");
18918 RXi_SET(RExC_rx, RExC_rxi);
18920 RExC_emit_start = RExC_rxi->program;
18922 Zero(REGNODE_p(RExC_emit), size, regnode);
18925 #ifdef RE_TRACK_PATTERN_OFFSETS
18926 Renew(RExC_offsets, 2*RExC_size+1, U32);
18928 Zero(RExC_offsets + 2*(RExC_size - size) + 1, 2 * size, U32);
18930 RExC_offsets[0] = RExC_size;
18934 STATIC regnode_offset
18935 S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name)
18937 /* Allocate a regnode for 'op', with 'extra_size' extra space. It aligns
18938 * and increments RExC_size and RExC_emit
18940 * It returns the regnode's offset into the regex engine program */
18942 const regnode_offset ret = RExC_emit;
18944 GET_RE_DEBUG_FLAGS_DECL;
18946 PERL_ARGS_ASSERT_REGNODE_GUTS;
18948 SIZE_ALIGN(RExC_size);
18949 change_engine_size(pRExC_state, (Ptrdiff_t) 1 + extra_size);
18950 NODE_ALIGN_FILL(REGNODE_p(ret));
18951 #ifndef RE_TRACK_PATTERN_OFFSETS
18952 PERL_UNUSED_ARG(name);
18953 PERL_UNUSED_ARG(op);
18955 assert(extra_size >= regarglen[op] || PL_regkind[op] == ANYOF);
18957 if (RExC_offsets) { /* MJD */
18959 ("%s:%d: (op %s) %s %" UVuf " (len %" UVuf ") (max %" UVuf ").\n",
18962 (UV)(RExC_emit) > RExC_offsets[0]
18963 ? "Overwriting end of array!\n" : "OK",
18965 (UV)(RExC_parse - RExC_start),
18966 (UV)RExC_offsets[0]));
18967 Set_Node_Offset(REGNODE_p(RExC_emit), RExC_parse + (op == END));
18974 - reg_node - emit a node
18976 STATIC regnode_offset /* Location. */
18977 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
18979 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node");
18980 regnode_offset ptr = ret;
18982 PERL_ARGS_ASSERT_REG_NODE;
18984 assert(regarglen[op] == 0);
18986 FILL_ADVANCE_NODE(ptr, op);
18992 - reganode - emit a node with an argument
18994 STATIC regnode_offset /* Location. */
18995 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
18997 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode");
18998 regnode_offset ptr = ret;
19000 PERL_ARGS_ASSERT_REGANODE;
19002 /* ANYOF are special cased to allow non-length 1 args */
19003 assert(regarglen[op] == 1);
19005 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
19010 STATIC regnode_offset
19011 S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2)
19013 /* emit a node with U32 and I32 arguments */
19015 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode");
19016 regnode_offset ptr = ret;
19018 PERL_ARGS_ASSERT_REG2LANODE;
19020 assert(regarglen[op] == 2);
19022 FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2);
19028 - reginsert - insert an operator in front of already-emitted operand
19030 * That means that on exit 'operand' is the offset of the newly inserted
19031 * operator, and the original operand has been relocated.
19033 * IMPORTANT NOTE - it is the *callers* responsibility to correctly
19034 * set up NEXT_OFF() of the inserted node if needed. Something like this:
19036 * reginsert(pRExC, OPFAIL, orig_emit, depth+1);
19037 * NEXT_OFF(orig_emit) = regarglen[OPFAIL] + NODE_STEP_REGNODE;
19039 * ALSO NOTE - FLAGS(newly-inserted-operator) will be set to 0 as well.
19042 S_reginsert(pTHX_ RExC_state_t *pRExC_state, const U8 op,
19043 const regnode_offset operand, const U32 depth)
19048 const int offset = regarglen[(U8)op];
19049 const int size = NODE_STEP_REGNODE + offset;
19050 GET_RE_DEBUG_FLAGS_DECL;
19052 PERL_ARGS_ASSERT_REGINSERT;
19053 PERL_UNUSED_CONTEXT;
19054 PERL_UNUSED_ARG(depth);
19055 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
19056 DEBUG_PARSE_FMT("inst"," - %s", PL_reg_name[op]);
19057 assert(!RExC_study_started); /* I believe we should never use reginsert once we have started
19058 studying. If this is wrong then we need to adjust RExC_recurse
19059 below like we do with RExC_open_parens/RExC_close_parens. */
19060 change_engine_size(pRExC_state, (Ptrdiff_t) size);
19061 src = REGNODE_p(RExC_emit);
19063 dst = REGNODE_p(RExC_emit);
19064 if (RExC_open_parens) {
19066 /*DEBUG_PARSE_FMT("inst"," - %" IVdf, (IV)RExC_npar);*/
19067 /* remember that RExC_npar is rex->nparens + 1,
19068 * iow it is 1 more than the number of parens seen in
19069 * the pattern so far. */
19070 for ( paren=0 ; paren < RExC_npar ; paren++ ) {
19071 /* note, RExC_open_parens[0] is the start of the
19072 * regex, it can't move. RExC_close_parens[0] is the end
19073 * of the regex, it *can* move. */
19074 if ( paren && RExC_open_parens[paren] >= operand ) {
19075 /*DEBUG_PARSE_FMT("open"," - %d", size);*/
19076 RExC_open_parens[paren] += size;
19078 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
19080 if ( RExC_close_parens[paren] >= operand ) {
19081 /*DEBUG_PARSE_FMT("close"," - %d", size);*/
19082 RExC_close_parens[paren] += size;
19084 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
19089 RExC_end_op += size;
19091 while (src > REGNODE_p(operand)) {
19092 StructCopy(--src, --dst, regnode);
19093 #ifdef RE_TRACK_PATTERN_OFFSETS
19094 if (RExC_offsets) { /* MJD 20010112 */
19096 ("%s(%d): (op %s) %s copy %" UVuf " -> %" UVuf " (max %" UVuf ").\n",
19100 (UV)(REGNODE_OFFSET(dst)) > RExC_offsets[0]
19101 ? "Overwriting end of array!\n" : "OK",
19102 (UV)REGNODE_OFFSET(src),
19103 (UV)REGNODE_OFFSET(dst),
19104 (UV)RExC_offsets[0]));
19105 Set_Node_Offset_To_R(REGNODE_OFFSET(dst), Node_Offset(src));
19106 Set_Node_Length_To_R(REGNODE_OFFSET(dst), Node_Length(src));
19111 place = REGNODE_p(operand); /* Op node, where operand used to be. */
19112 #ifdef RE_TRACK_PATTERN_OFFSETS
19113 if (RExC_offsets) { /* MJD */
19115 ("%s(%d): (op %s) %s %" UVuf " <- %" UVuf " (max %" UVuf ").\n",
19119 (UV)REGNODE_OFFSET(place) > RExC_offsets[0]
19120 ? "Overwriting end of array!\n" : "OK",
19121 (UV)REGNODE_OFFSET(place),
19122 (UV)(RExC_parse - RExC_start),
19123 (UV)RExC_offsets[0]));
19124 Set_Node_Offset(place, RExC_parse);
19125 Set_Node_Length(place, 1);
19128 src = NEXTOPER(place);
19130 FILL_NODE(operand, op);
19132 /* Zero out any arguments in the new node */
19133 Zero(src, offset, regnode);
19137 - regtail - set the next-pointer at the end of a node chain of p to val.
19138 - SEE ALSO: regtail_study
19141 S_regtail(pTHX_ RExC_state_t * pRExC_state,
19142 const regnode_offset p,
19143 const regnode_offset val,
19146 regnode_offset scan;
19147 GET_RE_DEBUG_FLAGS_DECL;
19149 PERL_ARGS_ASSERT_REGTAIL;
19151 PERL_UNUSED_ARG(depth);
19154 /* Find last node. */
19155 scan = (regnode_offset) p;
19157 regnode * const temp = regnext(REGNODE_p(scan));
19159 DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
19160 regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
19161 Perl_re_printf( aTHX_ "~ %s (%d) %s %s\n",
19162 SvPV_nolen_const(RExC_mysv), REG_NODE_NUM(REGNODE_p(scan)),
19163 (temp == NULL ? "->" : ""),
19164 (temp == NULL ? PL_reg_name[OP(REGNODE_p(val))] : "")
19169 scan = REGNODE_OFFSET(temp);
19172 if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
19173 ARG_SET(REGNODE_p(scan), val - scan);
19176 NEXT_OFF(REGNODE_p(scan)) = val - scan;
19182 - regtail_study - set the next-pointer at the end of a node chain of p to val.
19183 - Look for optimizable sequences at the same time.
19184 - currently only looks for EXACT chains.
19186 This is experimental code. The idea is to use this routine to perform
19187 in place optimizations on branches and groups as they are constructed,
19188 with the long term intention of removing optimization from study_chunk so
19189 that it is purely analytical.
19191 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
19192 to control which is which.
19195 /* TODO: All four parms should be const */
19198 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode_offset p,
19199 const regnode_offset val, U32 depth)
19201 regnode_offset scan;
19203 #ifdef EXPERIMENTAL_INPLACESCAN
19206 GET_RE_DEBUG_FLAGS_DECL;
19208 PERL_ARGS_ASSERT_REGTAIL_STUDY;
19211 /* Find last node. */
19215 regnode * const temp = regnext(REGNODE_p(scan));
19216 #ifdef EXPERIMENTAL_INPLACESCAN
19217 if (PL_regkind[OP(REGNODE_p(scan))] == EXACT) {
19218 bool unfolded_multi_char; /* Unexamined in this routine */
19219 if (join_exact(pRExC_state, scan, &min,
19220 &unfolded_multi_char, 1, REGNODE_p(val), depth+1))
19225 switch (OP(REGNODE_p(scan))) {
19229 case EXACTFAA_NO_TRIE:
19235 if( exact == PSEUDO )
19236 exact= OP(REGNODE_p(scan));
19237 else if ( exact != OP(REGNODE_p(scan)) )
19246 DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
19247 regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
19248 Perl_re_printf( aTHX_ "~ %s (%d) -> %s\n",
19249 SvPV_nolen_const(RExC_mysv),
19250 REG_NODE_NUM(REGNODE_p(scan)),
19251 PL_reg_name[exact]);
19255 scan = REGNODE_OFFSET(temp);
19258 DEBUG_PARSE_MSG("");
19259 regprop(RExC_rx, RExC_mysv, REGNODE_p(val), NULL, pRExC_state);
19260 Perl_re_printf( aTHX_
19261 "~ attach to %s (%" IVdf ") offset to %" IVdf "\n",
19262 SvPV_nolen_const(RExC_mysv),
19263 (IV)REG_NODE_NUM(REGNODE_p(val)),
19267 if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
19268 ARG_SET(REGNODE_p(scan), val - scan);
19271 NEXT_OFF(REGNODE_p(scan)) = val - scan;
19279 S_get_ANYOFM_contents(pTHX_ const regnode * n) {
19281 /* Returns an inversion list of all the code points matched by the
19282 * ANYOFM/NANYOFM node 'n' */
19284 SV * cp_list = _new_invlist(-1);
19285 const U8 lowest = (U8) ARG(n);
19288 U8 needed = 1U << PL_bitcount[ (U8) ~ FLAGS(n)];
19290 PERL_ARGS_ASSERT_GET_ANYOFM_CONTENTS;
19292 /* Starting with the lowest code point, any code point that ANDed with the
19293 * mask yields the lowest code point is in the set */
19294 for (i = lowest; i <= 0xFF; i++) {
19295 if ((i & FLAGS(n)) == ARG(n)) {
19296 cp_list = add_cp_to_invlist(cp_list, i);
19299 /* We know how many code points (a power of two) that are in the
19300 * set. No use looking once we've got that number */
19301 if (count >= needed) break;
19305 if (OP(n) == NANYOFM) {
19306 _invlist_invert(cp_list);
19312 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
19317 S_regdump_intflags(pTHX_ const char *lead, const U32 flags)
19322 ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8);
19324 for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) {
19325 if (flags & (1<<bit)) {
19326 if (!set++ && lead)
19327 Perl_re_printf( aTHX_ "%s", lead);
19328 Perl_re_printf( aTHX_ "%s ", PL_reg_intflags_name[bit]);
19333 Perl_re_printf( aTHX_ "\n");
19335 Perl_re_printf( aTHX_ "%s[none-set]\n", lead);
19340 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
19346 ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8);
19348 for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) {
19349 if (flags & (1<<bit)) {
19350 if ((1<<bit) & RXf_PMf_CHARSET) { /* Output separately, below */
19353 if (!set++ && lead)
19354 Perl_re_printf( aTHX_ "%s", lead);
19355 Perl_re_printf( aTHX_ "%s ", PL_reg_extflags_name[bit]);
19358 if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
19359 if (!set++ && lead) {
19360 Perl_re_printf( aTHX_ "%s", lead);
19363 case REGEX_UNICODE_CHARSET:
19364 Perl_re_printf( aTHX_ "UNICODE");
19366 case REGEX_LOCALE_CHARSET:
19367 Perl_re_printf( aTHX_ "LOCALE");
19369 case REGEX_ASCII_RESTRICTED_CHARSET:
19370 Perl_re_printf( aTHX_ "ASCII-RESTRICTED");
19372 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
19373 Perl_re_printf( aTHX_ "ASCII-MORE_RESTRICTED");
19376 Perl_re_printf( aTHX_ "UNKNOWN CHARACTER SET");
19382 Perl_re_printf( aTHX_ "\n");
19384 Perl_re_printf( aTHX_ "%s[none-set]\n", lead);
19390 Perl_regdump(pTHX_ const regexp *r)
19394 SV * const sv = sv_newmortal();
19395 SV *dsv= sv_newmortal();
19396 RXi_GET_DECL(r, ri);
19397 GET_RE_DEBUG_FLAGS_DECL;
19399 PERL_ARGS_ASSERT_REGDUMP;
19401 (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
19403 /* Header fields of interest. */
19404 for (i = 0; i < 2; i++) {
19405 if (r->substrs->data[i].substr) {
19406 RE_PV_QUOTED_DECL(s, 0, dsv,
19407 SvPVX_const(r->substrs->data[i].substr),
19408 RE_SV_DUMPLEN(r->substrs->data[i].substr),
19409 PL_dump_re_max_len);
19410 Perl_re_printf( aTHX_
19411 "%s %s%s at %" IVdf "..%" UVuf " ",
19412 i ? "floating" : "anchored",
19414 RE_SV_TAIL(r->substrs->data[i].substr),
19415 (IV)r->substrs->data[i].min_offset,
19416 (UV)r->substrs->data[i].max_offset);
19418 else if (r->substrs->data[i].utf8_substr) {
19419 RE_PV_QUOTED_DECL(s, 1, dsv,
19420 SvPVX_const(r->substrs->data[i].utf8_substr),
19421 RE_SV_DUMPLEN(r->substrs->data[i].utf8_substr),
19423 Perl_re_printf( aTHX_
19424 "%s utf8 %s%s at %" IVdf "..%" UVuf " ",
19425 i ? "floating" : "anchored",
19427 RE_SV_TAIL(r->substrs->data[i].utf8_substr),
19428 (IV)r->substrs->data[i].min_offset,
19429 (UV)r->substrs->data[i].max_offset);
19433 if (r->check_substr || r->check_utf8)
19434 Perl_re_printf( aTHX_
19436 ( r->check_substr == r->substrs->data[1].substr
19437 && r->check_utf8 == r->substrs->data[1].utf8_substr
19438 ? "(checking floating" : "(checking anchored"));
19439 if (r->intflags & PREGf_NOSCAN)
19440 Perl_re_printf( aTHX_ " noscan");
19441 if (r->extflags & RXf_CHECK_ALL)
19442 Perl_re_printf( aTHX_ " isall");
19443 if (r->check_substr || r->check_utf8)
19444 Perl_re_printf( aTHX_ ") ");
19446 if (ri->regstclass) {
19447 regprop(r, sv, ri->regstclass, NULL, NULL);
19448 Perl_re_printf( aTHX_ "stclass %s ", SvPVX_const(sv));
19450 if (r->intflags & PREGf_ANCH) {
19451 Perl_re_printf( aTHX_ "anchored");
19452 if (r->intflags & PREGf_ANCH_MBOL)
19453 Perl_re_printf( aTHX_ "(MBOL)");
19454 if (r->intflags & PREGf_ANCH_SBOL)
19455 Perl_re_printf( aTHX_ "(SBOL)");
19456 if (r->intflags & PREGf_ANCH_GPOS)
19457 Perl_re_printf( aTHX_ "(GPOS)");
19458 Perl_re_printf( aTHX_ " ");
19460 if (r->intflags & PREGf_GPOS_SEEN)
19461 Perl_re_printf( aTHX_ "GPOS:%" UVuf " ", (UV)r->gofs);
19462 if (r->intflags & PREGf_SKIP)
19463 Perl_re_printf( aTHX_ "plus ");
19464 if (r->intflags & PREGf_IMPLICIT)
19465 Perl_re_printf( aTHX_ "implicit ");
19466 Perl_re_printf( aTHX_ "minlen %" IVdf " ", (IV)r->minlen);
19467 if (r->extflags & RXf_EVAL_SEEN)
19468 Perl_re_printf( aTHX_ "with eval ");
19469 Perl_re_printf( aTHX_ "\n");
19471 regdump_extflags("r->extflags: ", r->extflags);
19472 regdump_intflags("r->intflags: ", r->intflags);
19475 PERL_ARGS_ASSERT_REGDUMP;
19476 PERL_UNUSED_CONTEXT;
19477 PERL_UNUSED_ARG(r);
19478 #endif /* DEBUGGING */
19481 /* Should be synchronized with ANYOF_ #defines in regcomp.h */
19484 # if _CC_WORDCHAR != 0 || _CC_DIGIT != 1 || _CC_ALPHA != 2 \
19485 || _CC_LOWER != 3 || _CC_UPPER != 4 || _CC_PUNCT != 5 \
19486 || _CC_PRINT != 6 || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8 \
19487 || _CC_CASED != 9 || _CC_SPACE != 10 || _CC_BLANK != 11 \
19488 || _CC_XDIGIT != 12 || _CC_CNTRL != 13 || _CC_ASCII != 14 \
19489 || _CC_VERTSPACE != 15
19490 # error Need to adjust order of anyofs[]
19492 static const char * const anyofs[] = {
19529 - regprop - printable representation of opcode, with run time support
19533 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state)
19537 RXi_GET_DECL(prog, progi);
19538 GET_RE_DEBUG_FLAGS_DECL;
19540 PERL_ARGS_ASSERT_REGPROP;
19544 if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */
19545 /* It would be nice to FAIL() here, but this may be called from
19546 regexec.c, and it would be hard to supply pRExC_state. */
19547 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
19548 (int)OP(o), (int)REGNODE_MAX);
19549 sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
19551 k = PL_regkind[OP(o)];
19554 sv_catpvs(sv, " ");
19555 /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
19556 * is a crude hack but it may be the best for now since
19557 * we have no flag "this EXACTish node was UTF-8"
19559 pv_pretty(sv, STRING(o), STR_LEN(o), PL_dump_re_max_len,
19560 PL_colors[0], PL_colors[1],
19561 PERL_PV_ESCAPE_UNI_DETECT |
19562 PERL_PV_ESCAPE_NONASCII |
19563 PERL_PV_PRETTY_ELLIPSES |
19564 PERL_PV_PRETTY_LTGT |
19565 PERL_PV_PRETTY_NOCLEAR
19567 } else if (k == TRIE) {
19568 /* print the details of the trie in dumpuntil instead, as
19569 * progi->data isn't available here */
19570 const char op = OP(o);
19571 const U32 n = ARG(o);
19572 const reg_ac_data * const ac = IS_TRIE_AC(op) ?
19573 (reg_ac_data *)progi->data->data[n] :
19575 const reg_trie_data * const trie
19576 = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
19578 Perl_sv_catpvf(aTHX_ sv, "-%s", PL_reg_name[o->flags]);
19579 DEBUG_TRIE_COMPILE_r({
19581 sv_catpvs(sv, "(JUMP)");
19582 Perl_sv_catpvf(aTHX_ sv,
19583 "<S:%" UVuf "/%" IVdf " W:%" UVuf " L:%" UVuf "/%" UVuf " C:%" UVuf "/%" UVuf ">",
19584 (UV)trie->startstate,
19585 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
19586 (UV)trie->wordcount,
19589 (UV)TRIE_CHARCOUNT(trie),
19590 (UV)trie->uniquecharcount
19593 if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
19594 sv_catpvs(sv, "[");
19595 (void) put_charclass_bitmap_innards(sv,
19596 ((IS_ANYOF_TRIE(op))
19598 : TRIE_BITMAP(trie)),
19604 sv_catpvs(sv, "]");
19606 } else if (k == CURLY) {
19607 U32 lo = ARG1(o), hi = ARG2(o);
19608 if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
19609 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
19610 Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo);
19611 if (hi == REG_INFTY)
19612 sv_catpvs(sv, "INFTY");
19614 Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi);
19615 sv_catpvs(sv, "}");
19617 else if (k == WHILEM && o->flags) /* Ordinal/of */
19618 Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
19619 else if (k == REF || k == OPEN || k == CLOSE
19620 || k == GROUPP || OP(o)==ACCEPT)
19622 AV *name_list= NULL;
19623 U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o);
19624 Perl_sv_catpvf(aTHX_ sv, "%" UVuf, (UV)parno); /* Parenth number */
19625 if ( RXp_PAREN_NAMES(prog) ) {
19626 name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
19627 } else if ( pRExC_state ) {
19628 name_list= RExC_paren_name_list;
19631 if ( k != REF || (OP(o) < NREF)) {
19632 SV **name= av_fetch(name_list, parno, 0 );
19634 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
19637 SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]);
19638 I32 *nums=(I32*)SvPVX(sv_dat);
19639 SV **name= av_fetch(name_list, nums[0], 0 );
19642 for ( n=0; n<SvIVX(sv_dat); n++ ) {
19643 Perl_sv_catpvf(aTHX_ sv, "%s%" IVdf,
19644 (n ? "," : ""), (IV)nums[n]);
19646 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
19650 if ( k == REF && reginfo) {
19651 U32 n = ARG(o); /* which paren pair */
19652 I32 ln = prog->offs[n].start;
19653 if (prog->lastparen < n || ln == -1 || prog->offs[n].end == -1)
19654 Perl_sv_catpvf(aTHX_ sv, ": FAIL");
19655 else if (ln == prog->offs[n].end)
19656 Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING");
19658 const char *s = reginfo->strbeg + ln;
19659 Perl_sv_catpvf(aTHX_ sv, ": ");
19660 Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0,
19661 PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE );
19664 } else if (k == GOSUB) {
19665 AV *name_list= NULL;
19666 if ( RXp_PAREN_NAMES(prog) ) {
19667 name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
19668 } else if ( pRExC_state ) {
19669 name_list= RExC_paren_name_list;
19672 /* Paren and offset */
19673 Perl_sv_catpvf(aTHX_ sv, "%d[%+d:%d]", (int)ARG(o),(int)ARG2L(o),
19674 (int)((o + (int)ARG2L(o)) - progi->program) );
19676 SV **name= av_fetch(name_list, ARG(o), 0 );
19678 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
19681 else if (k == LOGICAL)
19682 /* 2: embedded, otherwise 1 */
19683 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);
19684 else if (k == ANYOF) {
19685 const U8 flags = ANYOF_FLAGS(o);
19686 bool do_sep = FALSE; /* Do we need to separate various components of
19688 /* Set if there is still an unresolved user-defined property */
19689 SV *unresolved = NULL;
19691 /* Things that are ignored except when the runtime locale is UTF-8 */
19692 SV *only_utf8_locale_invlist = NULL;
19694 /* Code points that don't fit in the bitmap */
19695 SV *nonbitmap_invlist = NULL;
19697 /* And things that aren't in the bitmap, but are small enough to be */
19698 SV* bitmap_range_not_in_bitmap = NULL;
19700 const bool inverted = flags & ANYOF_INVERT;
19702 if (OP(o) == ANYOFL || OP(o) == ANYOFPOSIXL) {
19703 if (ANYOFL_UTF8_LOCALE_REQD(flags)) {
19704 sv_catpvs(sv, "{utf8-locale-reqd}");
19706 if (flags & ANYOFL_FOLD) {
19707 sv_catpvs(sv, "{i}");
19711 /* If there is stuff outside the bitmap, get it */
19712 if (ARG(o) != ANYOF_ONLY_HAS_BITMAP) {
19713 (void) _get_regclass_nonbitmap_data(prog, o, FALSE,
19715 &only_utf8_locale_invlist,
19716 &nonbitmap_invlist);
19717 /* The non-bitmap data may contain stuff that could fit in the
19718 * bitmap. This could come from a user-defined property being
19719 * finally resolved when this call was done; or much more likely
19720 * because there are matches that require UTF-8 to be valid, and so
19721 * aren't in the bitmap. This is teased apart later */
19722 _invlist_intersection(nonbitmap_invlist,
19724 &bitmap_range_not_in_bitmap);
19725 /* Leave just the things that don't fit into the bitmap */
19726 _invlist_subtract(nonbitmap_invlist,
19728 &nonbitmap_invlist);
19731 /* Obey this flag to add all above-the-bitmap code points */
19732 if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
19733 nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
19734 NUM_ANYOF_CODE_POINTS,
19738 /* Ready to start outputting. First, the initial left bracket */
19739 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
19741 /* Then all the things that could fit in the bitmap */
19742 do_sep = put_charclass_bitmap_innards(sv,
19744 bitmap_range_not_in_bitmap,
19745 only_utf8_locale_invlist,
19748 /* Can't try inverting for a
19749 * better display if there are
19750 * things that haven't been
19752 unresolved != NULL);
19753 SvREFCNT_dec(bitmap_range_not_in_bitmap);
19755 /* If there are user-defined properties which haven't been defined yet,
19756 * output them. If the result is not to be inverted, it is clearest to
19757 * output them in a separate [] from the bitmap range stuff. If the
19758 * result is to be complemented, we have to show everything in one [],
19759 * as the inversion applies to the whole thing. Use {braces} to
19760 * separate them from anything in the bitmap and anything above the
19764 if (! do_sep) { /* If didn't output anything in the bitmap */
19765 sv_catpvs(sv, "^");
19767 sv_catpvs(sv, "{");
19770 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]);
19772 sv_catsv(sv, unresolved);
19774 sv_catpvs(sv, "}");
19776 do_sep = ! inverted;
19779 /* And, finally, add the above-the-bitmap stuff */
19780 if (nonbitmap_invlist && _invlist_len(nonbitmap_invlist)) {
19783 /* See if truncation size is overridden */
19784 const STRLEN dump_len = (PL_dump_re_max_len > 256)
19785 ? PL_dump_re_max_len
19788 /* This is output in a separate [] */
19790 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]);
19793 /* And, for easy of understanding, it is shown in the
19794 * uncomplemented form if possible. The one exception being if
19795 * there are unresolved items, where the inversion has to be
19796 * delayed until runtime */
19797 if (inverted && ! unresolved) {
19798 _invlist_invert(nonbitmap_invlist);
19799 _invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist);
19802 contents = invlist_contents(nonbitmap_invlist,
19803 FALSE /* output suitable for catsv */
19806 /* If the output is shorter than the permissible maximum, just do it. */
19807 if (SvCUR(contents) <= dump_len) {
19808 sv_catsv(sv, contents);
19811 const char * contents_string = SvPVX(contents);
19812 STRLEN i = dump_len;
19814 /* Otherwise, start at the permissible max and work back to the
19815 * first break possibility */
19816 while (i > 0 && contents_string[i] != ' ') {
19819 if (i == 0) { /* Fail-safe. Use the max if we couldn't
19820 find a legal break */
19824 sv_catpvn(sv, contents_string, i);
19825 sv_catpvs(sv, "...");
19828 SvREFCNT_dec_NN(contents);
19829 SvREFCNT_dec_NN(nonbitmap_invlist);
19832 /* And finally the matching, closing ']' */
19833 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
19835 SvREFCNT_dec(unresolved);
19837 else if (k == ANYOFM) {
19838 SV * cp_list = get_ANYOFM_contents(o);
19840 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
19841 if (OP(o) == NANYOFM) {
19842 _invlist_invert(cp_list);
19845 put_charclass_bitmap_innards(sv, NULL, cp_list, NULL, NULL, TRUE);
19846 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
19848 SvREFCNT_dec(cp_list);
19850 else if (k == POSIXD || k == NPOSIXD) {
19851 U8 index = FLAGS(o) * 2;
19852 if (index < C_ARRAY_LENGTH(anyofs)) {
19853 if (*anyofs[index] != '[') {
19854 sv_catpvs(sv, "[");
19856 sv_catpv(sv, anyofs[index]);
19857 if (*anyofs[index] != '[') {
19858 sv_catpvs(sv, "]");
19862 Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
19865 else if (k == BOUND || k == NBOUND) {
19866 /* Must be synced with order of 'bound_type' in regcomp.h */
19867 const char * const bounds[] = {
19868 "", /* Traditional */
19874 assert(FLAGS(o) < C_ARRAY_LENGTH(bounds));
19875 sv_catpv(sv, bounds[FLAGS(o)]);
19877 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
19878 Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
19879 else if (OP(o) == SBOL)
19880 Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^");
19882 /* add on the verb argument if there is one */
19883 if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) {
19885 Perl_sv_catpvf(aTHX_ sv, ":%" SVf,
19886 SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
19888 sv_catpvs(sv, ":NULL");
19891 PERL_UNUSED_CONTEXT;
19892 PERL_UNUSED_ARG(sv);
19893 PERL_UNUSED_ARG(o);
19894 PERL_UNUSED_ARG(prog);
19895 PERL_UNUSED_ARG(reginfo);
19896 PERL_UNUSED_ARG(pRExC_state);
19897 #endif /* DEBUGGING */
19903 Perl_re_intuit_string(pTHX_ REGEXP * const r)
19904 { /* Assume that RE_INTUIT is set */
19905 struct regexp *const prog = ReANY(r);
19906 GET_RE_DEBUG_FLAGS_DECL;
19908 PERL_ARGS_ASSERT_RE_INTUIT_STRING;
19909 PERL_UNUSED_CONTEXT;
19913 const char * const s = SvPV_nolen_const(RX_UTF8(r)
19914 ? prog->check_utf8 : prog->check_substr);
19916 if (!PL_colorset) reginitcolors();
19917 Perl_re_printf( aTHX_
19918 "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
19920 RX_UTF8(r) ? "utf8 " : "",
19921 PL_colors[5], PL_colors[0],
19924 (strlen(s) > PL_dump_re_max_len ? "..." : ""));
19927 /* use UTF8 check substring if regexp pattern itself is in UTF8 */
19928 return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr;
19934 handles refcounting and freeing the perl core regexp structure. When
19935 it is necessary to actually free the structure the first thing it
19936 does is call the 'free' method of the regexp_engine associated to
19937 the regexp, allowing the handling of the void *pprivate; member
19938 first. (This routine is not overridable by extensions, which is why
19939 the extensions free is called first.)
19941 See regdupe and regdupe_internal if you change anything here.
19943 #ifndef PERL_IN_XSUB_RE
19945 Perl_pregfree(pTHX_ REGEXP *r)
19951 Perl_pregfree2(pTHX_ REGEXP *rx)
19953 struct regexp *const r = ReANY(rx);
19954 GET_RE_DEBUG_FLAGS_DECL;
19956 PERL_ARGS_ASSERT_PREGFREE2;
19961 if (r->mother_re) {
19962 ReREFCNT_dec(r->mother_re);
19964 CALLREGFREE_PVT(rx); /* free the private data */
19965 SvREFCNT_dec(RXp_PAREN_NAMES(r));
19969 for (i = 0; i < 2; i++) {
19970 SvREFCNT_dec(r->substrs->data[i].substr);
19971 SvREFCNT_dec(r->substrs->data[i].utf8_substr);
19973 Safefree(r->substrs);
19975 RX_MATCH_COPY_FREE(rx);
19976 #ifdef PERL_ANY_COW
19977 SvREFCNT_dec(r->saved_copy);
19980 SvREFCNT_dec(r->qr_anoncv);
19981 if (r->recurse_locinput)
19982 Safefree(r->recurse_locinput);
19988 Copy ssv to dsv, both of which should of type SVt_REGEXP or SVt_PVLV,
19989 except that dsv will be created if NULL.
19991 This function is used in two main ways. First to implement
19992 $r = qr/....; $s = $$r;
19994 Secondly, it is used as a hacky workaround to the structural issue of
19996 being stored in the regexp structure which is in turn stored in
19997 PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
19998 could be PL_curpm in multiple contexts, and could require multiple
19999 result sets being associated with the pattern simultaneously, such
20000 as when doing a recursive match with (??{$qr})
20002 The solution is to make a lightweight copy of the regexp structure
20003 when a qr// is returned from the code executed by (??{$qr}) this
20004 lightweight copy doesn't actually own any of its data except for
20005 the starp/end and the actual regexp structure itself.
20011 Perl_reg_temp_copy(pTHX_ REGEXP *dsv, REGEXP *ssv)
20013 struct regexp *drx;
20014 struct regexp *const srx = ReANY(ssv);
20015 const bool islv = dsv && SvTYPE(dsv) == SVt_PVLV;
20017 PERL_ARGS_ASSERT_REG_TEMP_COPY;
20020 dsv = (REGEXP*) newSV_type(SVt_REGEXP);
20022 SvOK_off((SV *)dsv);
20024 /* For PVLVs, the head (sv_any) points to an XPVLV, while
20025 * the LV's xpvlenu_rx will point to a regexp body, which
20026 * we allocate here */
20027 REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
20028 assert(!SvPVX(dsv));
20029 ((XPV*)SvANY(dsv))->xpv_len_u.xpvlenu_rx = temp->sv_any;
20030 temp->sv_any = NULL;
20031 SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
20032 SvREFCNT_dec_NN(temp);
20033 /* SvCUR still resides in the xpvlv struct, so the regexp copy-
20034 ing below will not set it. */
20035 SvCUR_set(dsv, SvCUR(ssv));
20038 /* This ensures that SvTHINKFIRST(sv) is true, and hence that
20039 sv_force_normal(sv) is called. */
20043 SvFLAGS(dsv) |= SvFLAGS(ssv) & (SVf_POK|SVp_POK|SVf_UTF8);
20044 SvPV_set(dsv, RX_WRAPPED(ssv));
20045 /* We share the same string buffer as the original regexp, on which we
20046 hold a reference count, incremented when mother_re is set below.
20047 The string pointer is copied here, being part of the regexp struct.
20049 memcpy(&(drx->xpv_cur), &(srx->xpv_cur),
20050 sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
20054 const I32 npar = srx->nparens+1;
20055 Newx(drx->offs, npar, regexp_paren_pair);
20056 Copy(srx->offs, drx->offs, npar, regexp_paren_pair);
20058 if (srx->substrs) {
20060 Newx(drx->substrs, 1, struct reg_substr_data);
20061 StructCopy(srx->substrs, drx->substrs, struct reg_substr_data);
20063 for (i = 0; i < 2; i++) {
20064 SvREFCNT_inc_void(drx->substrs->data[i].substr);
20065 SvREFCNT_inc_void(drx->substrs->data[i].utf8_substr);
20068 /* check_substr and check_utf8, if non-NULL, point to either their
20069 anchored or float namesakes, and don't hold a second reference. */
20071 RX_MATCH_COPIED_off(dsv);
20072 #ifdef PERL_ANY_COW
20073 drx->saved_copy = NULL;
20075 drx->mother_re = ReREFCNT_inc(srx->mother_re ? srx->mother_re : ssv);
20076 SvREFCNT_inc_void(drx->qr_anoncv);
20077 if (srx->recurse_locinput)
20078 Newx(drx->recurse_locinput, srx->nparens + 1, char *);
20085 /* regfree_internal()
20087 Free the private data in a regexp. This is overloadable by
20088 extensions. Perl takes care of the regexp structure in pregfree(),
20089 this covers the *pprivate pointer which technically perl doesn't
20090 know about, however of course we have to handle the
20091 regexp_internal structure when no extension is in use.
20093 Note this is called before freeing anything in the regexp
20098 Perl_regfree_internal(pTHX_ REGEXP * const rx)
20100 struct regexp *const r = ReANY(rx);
20101 RXi_GET_DECL(r, ri);
20102 GET_RE_DEBUG_FLAGS_DECL;
20104 PERL_ARGS_ASSERT_REGFREE_INTERNAL;
20114 SV *dsv= sv_newmortal();
20115 RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
20116 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), PL_dump_re_max_len);
20117 Perl_re_printf( aTHX_ "%sFreeing REx:%s %s\n",
20118 PL_colors[4], PL_colors[5], s);
20122 #ifdef RE_TRACK_PATTERN_OFFSETS
20124 Safefree(ri->u.offsets); /* 20010421 MJD */
20126 if (ri->code_blocks)
20127 S_free_codeblocks(aTHX_ ri->code_blocks);
20130 int n = ri->data->count;
20133 /* If you add a ->what type here, update the comment in regcomp.h */
20134 switch (ri->data->what[n]) {
20140 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
20143 Safefree(ri->data->data[n]);
20149 { /* Aho Corasick add-on structure for a trie node.
20150 Used in stclass optimization only */
20152 reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
20153 #ifdef USE_ITHREADS
20157 refcount = --aho->refcount;
20160 PerlMemShared_free(aho->states);
20161 PerlMemShared_free(aho->fail);
20162 /* do this last!!!! */
20163 PerlMemShared_free(ri->data->data[n]);
20164 /* we should only ever get called once, so
20165 * assert as much, and also guard the free
20166 * which /might/ happen twice. At the least
20167 * it will make code anlyzers happy and it
20168 * doesn't cost much. - Yves */
20169 assert(ri->regstclass);
20170 if (ri->regstclass) {
20171 PerlMemShared_free(ri->regstclass);
20172 ri->regstclass = 0;
20179 /* trie structure. */
20181 reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
20182 #ifdef USE_ITHREADS
20186 refcount = --trie->refcount;
20189 PerlMemShared_free(trie->charmap);
20190 PerlMemShared_free(trie->states);
20191 PerlMemShared_free(trie->trans);
20193 PerlMemShared_free(trie->bitmap);
20195 PerlMemShared_free(trie->jump);
20196 PerlMemShared_free(trie->wordinfo);
20197 /* do this last!!!! */
20198 PerlMemShared_free(ri->data->data[n]);
20203 Perl_croak(aTHX_ "panic: regfree data code '%c'",
20204 ri->data->what[n]);
20207 Safefree(ri->data->what);
20208 Safefree(ri->data);
20214 #define av_dup_inc(s, t) MUTABLE_AV(sv_dup_inc((const SV *)s, t))
20215 #define hv_dup_inc(s, t) MUTABLE_HV(sv_dup_inc((const SV *)s, t))
20216 #define SAVEPVN(p, n) ((p) ? savepvn(p, n) : NULL)
20219 re_dup_guts - duplicate a regexp.
20221 This routine is expected to clone a given regexp structure. It is only
20222 compiled under USE_ITHREADS.
20224 After all of the core data stored in struct regexp is duplicated
20225 the regexp_engine.dupe method is used to copy any private data
20226 stored in the *pprivate pointer. This allows extensions to handle
20227 any duplication it needs to do.
20229 See pregfree() and regfree_internal() if you change anything here.
20231 #if defined(USE_ITHREADS)
20232 #ifndef PERL_IN_XSUB_RE
20234 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
20238 const struct regexp *r = ReANY(sstr);
20239 struct regexp *ret = ReANY(dstr);
20241 PERL_ARGS_ASSERT_RE_DUP_GUTS;
20243 npar = r->nparens+1;
20244 Newx(ret->offs, npar, regexp_paren_pair);
20245 Copy(r->offs, ret->offs, npar, regexp_paren_pair);
20247 if (ret->substrs) {
20248 /* Do it this way to avoid reading from *r after the StructCopy().
20249 That way, if any of the sv_dup_inc()s dislodge *r from the L1
20250 cache, it doesn't matter. */
20252 const bool anchored = r->check_substr
20253 ? r->check_substr == r->substrs->data[0].substr
20254 : r->check_utf8 == r->substrs->data[0].utf8_substr;
20255 Newx(ret->substrs, 1, struct reg_substr_data);
20256 StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
20258 for (i = 0; i < 2; i++) {
20259 ret->substrs->data[i].substr =
20260 sv_dup_inc(ret->substrs->data[i].substr, param);
20261 ret->substrs->data[i].utf8_substr =
20262 sv_dup_inc(ret->substrs->data[i].utf8_substr, param);
20265 /* check_substr and check_utf8, if non-NULL, point to either their
20266 anchored or float namesakes, and don't hold a second reference. */
20268 if (ret->check_substr) {
20270 assert(r->check_utf8 == r->substrs->data[0].utf8_substr);
20272 ret->check_substr = ret->substrs->data[0].substr;
20273 ret->check_utf8 = ret->substrs->data[0].utf8_substr;
20275 assert(r->check_substr == r->substrs->data[1].substr);
20276 assert(r->check_utf8 == r->substrs->data[1].utf8_substr);
20278 ret->check_substr = ret->substrs->data[1].substr;
20279 ret->check_utf8 = ret->substrs->data[1].utf8_substr;
20281 } else if (ret->check_utf8) {
20283 ret->check_utf8 = ret->substrs->data[0].utf8_substr;
20285 ret->check_utf8 = ret->substrs->data[1].utf8_substr;
20290 RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
20291 ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
20292 if (r->recurse_locinput)
20293 Newx(ret->recurse_locinput, r->nparens + 1, char *);
20296 RXi_SET(ret, CALLREGDUPE_PVT(dstr, param));
20298 if (RX_MATCH_COPIED(dstr))
20299 ret->subbeg = SAVEPVN(ret->subbeg, ret->sublen);
20301 ret->subbeg = NULL;
20302 #ifdef PERL_ANY_COW
20303 ret->saved_copy = NULL;
20306 /* Whether mother_re be set or no, we need to copy the string. We
20307 cannot refrain from copying it when the storage points directly to
20308 our mother regexp, because that's
20309 1: a buffer in a different thread
20310 2: something we no longer hold a reference on
20311 so we need to copy it locally. */
20312 RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED_const(sstr), SvCUR(sstr)+1);
20313 ret->mother_re = NULL;
20315 #endif /* PERL_IN_XSUB_RE */
20320 This is the internal complement to regdupe() which is used to copy
20321 the structure pointed to by the *pprivate pointer in the regexp.
20322 This is the core version of the extension overridable cloning hook.
20323 The regexp structure being duplicated will be copied by perl prior
20324 to this and will be provided as the regexp *r argument, however
20325 with the /old/ structures pprivate pointer value. Thus this routine
20326 may override any copying normally done by perl.
20328 It returns a pointer to the new regexp_internal structure.
20332 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
20335 struct regexp *const r = ReANY(rx);
20336 regexp_internal *reti;
20338 RXi_GET_DECL(r, ri);
20340 PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
20344 Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode),
20345 char, regexp_internal);
20346 Copy(ri->program, reti->program, len+1, regnode);
20349 if (ri->code_blocks) {
20351 Newx(reti->code_blocks, 1, struct reg_code_blocks);
20352 Newx(reti->code_blocks->cb, ri->code_blocks->count,
20353 struct reg_code_block);
20354 Copy(ri->code_blocks->cb, reti->code_blocks->cb,
20355 ri->code_blocks->count, struct reg_code_block);
20356 for (n = 0; n < ri->code_blocks->count; n++)
20357 reti->code_blocks->cb[n].src_regex = (REGEXP*)
20358 sv_dup_inc((SV*)(ri->code_blocks->cb[n].src_regex), param);
20359 reti->code_blocks->count = ri->code_blocks->count;
20360 reti->code_blocks->refcnt = 1;
20363 reti->code_blocks = NULL;
20365 reti->regstclass = NULL;
20368 struct reg_data *d;
20369 const int count = ri->data->count;
20372 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
20373 char, struct reg_data);
20374 Newx(d->what, count, U8);
20377 for (i = 0; i < count; i++) {
20378 d->what[i] = ri->data->what[i];
20379 switch (d->what[i]) {
20380 /* see also regcomp.h and regfree_internal() */
20381 case 'a': /* actually an AV, but the dup function is identical.
20382 values seem to be "plain sv's" generally. */
20383 case 'r': /* a compiled regex (but still just another SV) */
20384 case 's': /* an RV (currently only used for an RV to an AV by the ANYOF code)
20385 this use case should go away, the code could have used
20386 'a' instead - see S_set_ANYOF_arg() for array contents. */
20387 case 'S': /* actually an SV, but the dup function is identical. */
20388 case 'u': /* actually an HV, but the dup function is identical.
20389 values are "plain sv's" */
20390 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
20393 /* Synthetic Start Class - "Fake" charclass we generate to optimize
20394 * patterns which could start with several different things. Pre-TRIE
20395 * this was more important than it is now, however this still helps
20396 * in some places, for instance /x?a+/ might produce a SSC equivalent
20397 * to [xa]. This is used by Perl_re_intuit_start() and S_find_byclass()
20400 /* This is cheating. */
20401 Newx(d->data[i], 1, regnode_ssc);
20402 StructCopy(ri->data->data[i], d->data[i], regnode_ssc);
20403 reti->regstclass = (regnode*)d->data[i];
20406 /* AHO-CORASICK fail table */
20407 /* Trie stclasses are readonly and can thus be shared
20408 * without duplication. We free the stclass in pregfree
20409 * when the corresponding reg_ac_data struct is freed.
20411 reti->regstclass= ri->regstclass;
20414 /* TRIE transition table */
20416 ((reg_trie_data*)ri->data->data[i])->refcount++;
20419 case 'l': /* (?{...}) or (??{ ... }) code (cb->block) */
20420 case 'L': /* same when RExC_pm_flags & PMf_HAS_CV and code
20421 is not from another regexp */
20422 d->data[i] = ri->data->data[i];
20425 Perl_croak(aTHX_ "panic: re_dup_guts unknown data code '%c'",
20426 ri->data->what[i]);
20435 reti->name_list_idx = ri->name_list_idx;
20437 #ifdef RE_TRACK_PATTERN_OFFSETS
20438 if (ri->u.offsets) {
20439 Newx(reti->u.offsets, 2*len+1, U32);
20440 Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
20443 SetProgLen(reti, len);
20446 return (void*)reti;
20449 #endif /* USE_ITHREADS */
20451 #ifndef PERL_IN_XSUB_RE
20454 - regnext - dig the "next" pointer out of a node
20457 Perl_regnext(pTHX_ regnode *p)
20464 if (OP(p) > REGNODE_MAX) { /* regnode.type is unsigned */
20465 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
20466 (int)OP(p), (int)REGNODE_MAX);
20469 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
20479 S_re_croak2(pTHX_ bool utf8, const char* pat1, const char* pat2,...)
20482 STRLEN l1 = strlen(pat1);
20483 STRLEN l2 = strlen(pat2);
20486 const char *message;
20488 PERL_ARGS_ASSERT_RE_CROAK2;
20494 Copy(pat1, buf, l1 , char);
20495 Copy(pat2, buf + l1, l2 , char);
20496 buf[l1 + l2] = '\n';
20497 buf[l1 + l2 + 1] = '\0';
20498 va_start(args, pat2);
20499 msv = vmess(buf, &args);
20501 message = SvPV_const(msv, l1);
20504 Copy(message, buf, l1 , char);
20505 /* l1-1 to avoid \n */
20506 Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(utf8, l1-1, buf));
20509 /* XXX Here's a total kludge. But we need to re-enter for swash routines. */
20511 #ifndef PERL_IN_XSUB_RE
20513 Perl_save_re_context(pTHX)
20518 /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
20521 const REGEXP * const rx = PM_GETRE(PL_curpm);
20523 nparens = RX_NPARENS(rx);
20526 /* RT #124109. This is a complete hack; in the SWASHNEW case we know
20527 * that PL_curpm will be null, but that utf8.pm and the modules it
20528 * loads will only use $1..$3.
20529 * The t/porting/re_context.t test file checks this assumption.
20534 for (i = 1; i <= nparens; i++) {
20535 char digits[TYPE_CHARS(long)];
20536 const STRLEN len = my_snprintf(digits, sizeof(digits),
20538 GV *const *const gvp
20539 = (GV**)hv_fetch(PL_defstash, digits, len, 0);
20542 GV * const gv = *gvp;
20543 if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
20553 S_put_code_point(pTHX_ SV *sv, UV c)
20555 PERL_ARGS_ASSERT_PUT_CODE_POINT;
20558 Perl_sv_catpvf(aTHX_ sv, "\\x{%04" UVXf "}", c);
20560 else if (isPRINT(c)) {
20561 const char string = (char) c;
20563 /* We use {phrase} as metanotation in the class, so also escape literal
20565 if (isBACKSLASHED_PUNCT(c) || c == '{' || c == '}')
20566 sv_catpvs(sv, "\\");
20567 sv_catpvn(sv, &string, 1);
20569 else if (isMNEMONIC_CNTRL(c)) {
20570 Perl_sv_catpvf(aTHX_ sv, "%s", cntrl_to_mnemonic((U8) c));
20573 Perl_sv_catpvf(aTHX_ sv, "\\x%02X", (U8) c);
20577 #define MAX_PRINT_A MAX_PRINT_A_FOR_USE_ONLY_BY_REGCOMP_DOT_C
20580 S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals)
20582 /* Appends to 'sv' a displayable version of the range of code points from
20583 * 'start' to 'end'. Mnemonics (like '\r') are used for the few controls
20584 * that have them, when they occur at the beginning or end of the range.
20585 * It uses hex to output the remaining code points, unless 'allow_literals'
20586 * is true, in which case the printable ASCII ones are output as-is (though
20587 * some of these will be escaped by put_code_point()).
20589 * NOTE: This is designed only for printing ranges of code points that fit
20590 * inside an ANYOF bitmap. Higher code points are simply suppressed
20593 const unsigned int min_range_count = 3;
20595 assert(start <= end);
20597 PERL_ARGS_ASSERT_PUT_RANGE;
20599 while (start <= end) {
20601 const char * format;
20603 if (end - start < min_range_count) {
20605 /* Output chars individually when they occur in short ranges */
20606 for (; start <= end; start++) {
20607 put_code_point(sv, start);
20612 /* If permitted by the input options, and there is a possibility that
20613 * this range contains a printable literal, look to see if there is
20615 if (allow_literals && start <= MAX_PRINT_A) {
20617 /* If the character at the beginning of the range isn't an ASCII
20618 * printable, effectively split the range into two parts:
20619 * 1) the portion before the first such printable,
20621 * and output them separately. */
20622 if (! isPRINT_A(start)) {
20623 UV temp_end = start + 1;
20625 /* There is no point looking beyond the final possible
20626 * printable, in MAX_PRINT_A */
20627 UV max = MIN(end, MAX_PRINT_A);
20629 while (temp_end <= max && ! isPRINT_A(temp_end)) {
20633 /* Here, temp_end points to one beyond the first printable if
20634 * found, or to one beyond 'max' if not. If none found, make
20635 * sure that we use the entire range */
20636 if (temp_end > MAX_PRINT_A) {
20637 temp_end = end + 1;
20640 /* Output the first part of the split range: the part that
20641 * doesn't have printables, with the parameter set to not look
20642 * for literals (otherwise we would infinitely recurse) */
20643 put_range(sv, start, temp_end - 1, FALSE);
20645 /* The 2nd part of the range (if any) starts here. */
20648 /* We do a continue, instead of dropping down, because even if
20649 * the 2nd part is non-empty, it could be so short that we want
20650 * to output it as individual characters, as tested for at the
20651 * top of this loop. */
20655 /* Here, 'start' is a printable ASCII. If it is an alphanumeric,
20656 * output a sub-range of just the digits or letters, then process
20657 * the remaining portion as usual. */
20658 if (isALPHANUMERIC_A(start)) {
20659 UV mask = (isDIGIT_A(start))
20664 UV temp_end = start + 1;
20666 /* Find the end of the sub-range that includes just the
20667 * characters in the same class as the first character in it */
20668 while (temp_end <= end && _generic_isCC_A(temp_end, mask)) {
20673 /* For short ranges, don't duplicate the code above to output
20674 * them; just call recursively */
20675 if (temp_end - start < min_range_count) {
20676 put_range(sv, start, temp_end, FALSE);
20678 else { /* Output as a range */
20679 put_code_point(sv, start);
20680 sv_catpvs(sv, "-");
20681 put_code_point(sv, temp_end);
20683 start = temp_end + 1;
20687 /* We output any other printables as individual characters */
20688 if (isPUNCT_A(start) || isSPACE_A(start)) {
20689 while (start <= end && (isPUNCT_A(start)
20690 || isSPACE_A(start)))
20692 put_code_point(sv, start);
20697 } /* End of looking for literals */
20699 /* Here is not to output as a literal. Some control characters have
20700 * mnemonic names. Split off any of those at the beginning and end of
20701 * the range to print mnemonically. It isn't possible for many of
20702 * these to be in a row, so this won't overwhelm with output */
20704 && (isMNEMONIC_CNTRL(start) || isMNEMONIC_CNTRL(end)))
20706 while (isMNEMONIC_CNTRL(start) && start <= end) {
20707 put_code_point(sv, start);
20711 /* If this didn't take care of the whole range ... */
20712 if (start <= end) {
20714 /* Look backwards from the end to find the final non-mnemonic
20717 while (isMNEMONIC_CNTRL(temp_end)) {
20721 /* And separately output the interior range that doesn't start
20722 * or end with mnemonics */
20723 put_range(sv, start, temp_end, FALSE);
20725 /* Then output the mnemonic trailing controls */
20726 start = temp_end + 1;
20727 while (start <= end) {
20728 put_code_point(sv, start);
20735 /* As a final resort, output the range or subrange as hex. */
20737 this_end = (end < NUM_ANYOF_CODE_POINTS)
20739 : NUM_ANYOF_CODE_POINTS - 1;
20740 #if NUM_ANYOF_CODE_POINTS > 256
20741 format = (this_end < 256)
20742 ? "\\x%02" UVXf "-\\x%02" UVXf
20743 : "\\x{%04" UVXf "}-\\x{%04" UVXf "}";
20745 format = "\\x%02" UVXf "-\\x%02" UVXf;
20747 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
20748 Perl_sv_catpvf(aTHX_ sv, format, start, this_end);
20749 GCC_DIAG_RESTORE_STMT;
20755 S_put_charclass_bitmap_innards_invlist(pTHX_ SV *sv, SV* invlist)
20757 /* Concatenate onto the PV in 'sv' a displayable form of the inversion list
20761 bool allow_literals = TRUE;
20763 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_INVLIST;
20765 /* Generally, it is more readable if printable characters are output as
20766 * literals, but if a range (nearly) spans all of them, it's best to output
20767 * it as a single range. This code will use a single range if all but 2
20768 * ASCII printables are in it */
20769 invlist_iterinit(invlist);
20770 while (invlist_iternext(invlist, &start, &end)) {
20772 /* If the range starts beyond the final printable, it doesn't have any
20774 if (start > MAX_PRINT_A) {
20778 /* In both ASCII and EBCDIC, a SPACE is the lowest printable. To span
20779 * all but two, the range must start and end no later than 2 from
20781 if (start < ' ' + 2 && end > MAX_PRINT_A - 2) {
20782 if (end > MAX_PRINT_A) {
20788 if (end - start >= MAX_PRINT_A - ' ' - 2) {
20789 allow_literals = FALSE;
20794 invlist_iterfinish(invlist);
20796 /* Here we have figured things out. Output each range */
20797 invlist_iterinit(invlist);
20798 while (invlist_iternext(invlist, &start, &end)) {
20799 if (start >= NUM_ANYOF_CODE_POINTS) {
20802 put_range(sv, start, end, allow_literals);
20804 invlist_iterfinish(invlist);
20810 S_put_charclass_bitmap_innards_common(pTHX_
20811 SV* invlist, /* The bitmap */
20812 SV* posixes, /* Under /l, things like [:word:], \S */
20813 SV* only_utf8, /* Under /d, matches iff the target is UTF-8 */
20814 SV* not_utf8, /* /d, matches iff the target isn't UTF-8 */
20815 SV* only_utf8_locale, /* Under /l, matches if the locale is UTF-8 */
20816 const bool invert /* Is the result to be inverted? */
20819 /* Create and return an SV containing a displayable version of the bitmap
20820 * and associated information determined by the input parameters. If the
20821 * output would have been only the inversion indicator '^', NULL is instead
20826 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_COMMON;
20829 output = newSVpvs("^");
20832 output = newSVpvs("");
20835 /* First, the code points in the bitmap that are unconditionally there */
20836 put_charclass_bitmap_innards_invlist(output, invlist);
20838 /* Traditionally, these have been placed after the main code points */
20840 sv_catsv(output, posixes);
20843 if (only_utf8 && _invlist_len(only_utf8)) {
20844 Perl_sv_catpvf(aTHX_ output, "%s{utf8}%s", PL_colors[1], PL_colors[0]);
20845 put_charclass_bitmap_innards_invlist(output, only_utf8);
20848 if (not_utf8 && _invlist_len(not_utf8)) {
20849 Perl_sv_catpvf(aTHX_ output, "%s{not utf8}%s", PL_colors[1], PL_colors[0]);
20850 put_charclass_bitmap_innards_invlist(output, not_utf8);
20853 if (only_utf8_locale && _invlist_len(only_utf8_locale)) {
20854 Perl_sv_catpvf(aTHX_ output, "%s{utf8 locale}%s", PL_colors[1], PL_colors[0]);
20855 put_charclass_bitmap_innards_invlist(output, only_utf8_locale);
20857 /* This is the only list in this routine that can legally contain code
20858 * points outside the bitmap range. The call just above to
20859 * 'put_charclass_bitmap_innards_invlist' will simply suppress them, so
20860 * output them here. There's about a half-dozen possible, and none in
20861 * contiguous ranges longer than 2 */
20862 if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
20864 SV* above_bitmap = NULL;
20866 _invlist_subtract(only_utf8_locale, PL_InBitmap, &above_bitmap);
20868 invlist_iterinit(above_bitmap);
20869 while (invlist_iternext(above_bitmap, &start, &end)) {
20872 for (i = start; i <= end; i++) {
20873 put_code_point(output, i);
20876 invlist_iterfinish(above_bitmap);
20877 SvREFCNT_dec_NN(above_bitmap);
20881 if (invert && SvCUR(output) == 1) {
20889 S_put_charclass_bitmap_innards(pTHX_ SV *sv,
20891 SV *nonbitmap_invlist,
20892 SV *only_utf8_locale_invlist,
20893 const regnode * const node,
20894 const bool force_as_is_display)
20896 /* Appends to 'sv' a displayable version of the innards of the bracketed
20897 * character class defined by the other arguments:
20898 * 'bitmap' points to the bitmap, or NULL if to ignore that.
20899 * 'nonbitmap_invlist' is an inversion list of the code points that are in
20900 * the bitmap range, but for some reason aren't in the bitmap; NULL if
20901 * none. The reasons for this could be that they require some
20902 * condition such as the target string being or not being in UTF-8
20903 * (under /d), or because they came from a user-defined property that
20904 * was not resolved at the time of the regex compilation (under /u)
20905 * 'only_utf8_locale_invlist' is an inversion list of the code points that
20906 * are valid only if the runtime locale is a UTF-8 one; NULL if none
20907 * 'node' is the regex pattern ANYOF node. It is needed only when the
20908 * above two parameters are not null, and is passed so that this
20909 * routine can tease apart the various reasons for them.
20910 * 'force_as_is_display' is TRUE if this routine should definitely NOT try
20911 * to invert things to see if that leads to a cleaner display. If
20912 * FALSE, this routine is free to use its judgment about doing this.
20914 * It returns TRUE if there was actually something output. (It may be that
20915 * the bitmap, etc is empty.)
20917 * When called for outputting the bitmap of a non-ANYOF node, just pass the
20918 * bitmap, with the succeeding parameters set to NULL, and the final one to
20922 /* In general, it tries to display the 'cleanest' representation of the
20923 * innards, choosing whether to display them inverted or not, regardless of
20924 * whether the class itself is to be inverted. However, there are some
20925 * cases where it can't try inverting, as what actually matches isn't known
20926 * until runtime, and hence the inversion isn't either. */
20927 bool inverting_allowed = ! force_as_is_display;
20930 STRLEN orig_sv_cur = SvCUR(sv);
20932 SV* invlist; /* Inversion list we accumulate of code points that
20933 are unconditionally matched */
20934 SV* only_utf8 = NULL; /* Under /d, list of matches iff the target is
20936 SV* not_utf8 = NULL; /* /d, list of matches iff the target isn't UTF-8
20938 SV* posixes = NULL; /* Under /l, string of things like [:word:], \D */
20939 SV* only_utf8_locale = NULL; /* Under /l, list of matches if the locale
20942 SV* as_is_display; /* The output string when we take the inputs
20944 SV* inverted_display; /* The output string when we invert the inputs */
20946 U8 flags = (node) ? ANYOF_FLAGS(node) : 0;
20948 bool invert = cBOOL(flags & ANYOF_INVERT); /* Is the input to be inverted
20950 /* We are biased in favor of displaying things without them being inverted,
20951 * as that is generally easier to understand */
20952 const int bias = 5;
20954 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS;
20956 /* Start off with whatever code points are passed in. (We clone, so we
20957 * don't change the caller's list) */
20958 if (nonbitmap_invlist) {
20959 assert(invlist_highest(nonbitmap_invlist) < NUM_ANYOF_CODE_POINTS);
20960 invlist = invlist_clone(nonbitmap_invlist, NULL);
20962 else { /* Worst case size is every other code point is matched */
20963 invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2);
20967 if (OP(node) == ANYOFD) {
20969 /* This flag indicates that the code points below 0x100 in the
20970 * nonbitmap list are precisely the ones that match only when the
20971 * target is UTF-8 (they should all be non-ASCII). */
20972 if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
20974 _invlist_intersection(invlist, PL_UpperLatin1, &only_utf8);
20975 _invlist_subtract(invlist, only_utf8, &invlist);
20978 /* And this flag for matching all non-ASCII 0xFF and below */
20979 if (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
20981 not_utf8 = invlist_clone(PL_UpperLatin1, NULL);
20984 else if (OP(node) == ANYOFL || OP(node) == ANYOFPOSIXL) {
20986 /* If either of these flags are set, what matches isn't
20987 * determinable except during execution, so don't know enough here
20989 if (flags & (ANYOFL_FOLD|ANYOF_MATCHES_POSIXL)) {
20990 inverting_allowed = FALSE;
20993 /* What the posix classes match also varies at runtime, so these
20994 * will be output symbolically. */
20995 if (ANYOF_POSIXL_TEST_ANY_SET(node)) {
20998 posixes = newSVpvs("");
20999 for (i = 0; i < ANYOF_POSIXL_MAX; i++) {
21000 if (ANYOF_POSIXL_TEST(node, i)) {
21001 sv_catpv(posixes, anyofs[i]);
21008 /* Accumulate the bit map into the unconditional match list */
21010 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
21011 if (BITMAP_TEST(bitmap, i)) {
21014 i < NUM_ANYOF_CODE_POINTS && BITMAP_TEST(bitmap, i);
21017 invlist = _add_range_to_invlist(invlist, start, i-1);
21022 /* Make sure that the conditional match lists don't have anything in them
21023 * that match unconditionally; otherwise the output is quite confusing.
21024 * This could happen if the code that populates these misses some
21027 _invlist_subtract(only_utf8, invlist, &only_utf8);
21030 _invlist_subtract(not_utf8, invlist, ¬_utf8);
21033 if (only_utf8_locale_invlist) {
21035 /* Since this list is passed in, we have to make a copy before
21037 only_utf8_locale = invlist_clone(only_utf8_locale_invlist, NULL);
21039 _invlist_subtract(only_utf8_locale, invlist, &only_utf8_locale);
21041 /* And, it can get really weird for us to try outputting an inverted
21042 * form of this list when it has things above the bitmap, so don't even
21044 if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
21045 inverting_allowed = FALSE;
21049 /* Calculate what the output would be if we take the input as-is */
21050 as_is_display = put_charclass_bitmap_innards_common(invlist,
21057 /* If have to take the output as-is, just do that */
21058 if (! inverting_allowed) {
21059 if (as_is_display) {
21060 sv_catsv(sv, as_is_display);
21061 SvREFCNT_dec_NN(as_is_display);
21064 else { /* But otherwise, create the output again on the inverted input, and
21065 use whichever version is shorter */
21067 int inverted_bias, as_is_bias;
21069 /* We will apply our bias to whichever of the the results doesn't have
21079 inverted_bias = bias;
21082 /* Now invert each of the lists that contribute to the output,
21083 * excluding from the result things outside the possible range */
21085 /* For the unconditional inversion list, we have to add in all the
21086 * conditional code points, so that when inverted, they will be gone
21088 _invlist_union(only_utf8, invlist, &invlist);
21089 _invlist_union(not_utf8, invlist, &invlist);
21090 _invlist_union(only_utf8_locale, invlist, &invlist);
21091 _invlist_invert(invlist);
21092 _invlist_intersection(invlist, PL_InBitmap, &invlist);
21095 _invlist_invert(only_utf8);
21096 _invlist_intersection(only_utf8, PL_UpperLatin1, &only_utf8);
21098 else if (not_utf8) {
21100 /* If a code point matches iff the target string is not in UTF-8,
21101 * then complementing the result has it not match iff not in UTF-8,
21102 * which is the same thing as matching iff it is UTF-8. */
21103 only_utf8 = not_utf8;
21107 if (only_utf8_locale) {
21108 _invlist_invert(only_utf8_locale);
21109 _invlist_intersection(only_utf8_locale,
21111 &only_utf8_locale);
21114 inverted_display = put_charclass_bitmap_innards_common(
21119 only_utf8_locale, invert);
21121 /* Use the shortest representation, taking into account our bias
21122 * against showing it inverted */
21123 if ( inverted_display
21124 && ( ! as_is_display
21125 || ( SvCUR(inverted_display) + inverted_bias
21126 < SvCUR(as_is_display) + as_is_bias)))
21128 sv_catsv(sv, inverted_display);
21130 else if (as_is_display) {
21131 sv_catsv(sv, as_is_display);
21134 SvREFCNT_dec(as_is_display);
21135 SvREFCNT_dec(inverted_display);
21138 SvREFCNT_dec_NN(invlist);
21139 SvREFCNT_dec(only_utf8);
21140 SvREFCNT_dec(not_utf8);
21141 SvREFCNT_dec(posixes);
21142 SvREFCNT_dec(only_utf8_locale);
21144 return SvCUR(sv) > orig_sv_cur;
21147 #define CLEAR_OPTSTART \
21148 if (optstart) STMT_START { \
21149 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ \
21150 " (%" IVdf " nodes)\n", (IV)(node - optstart))); \
21154 #define DUMPUNTIL(b,e) \
21156 node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
21158 STATIC const regnode *
21159 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
21160 const regnode *last, const regnode *plast,
21161 SV* sv, I32 indent, U32 depth)
21163 U8 op = PSEUDO; /* Arbitrary non-END op. */
21164 const regnode *next;
21165 const regnode *optstart= NULL;
21167 RXi_GET_DECL(r, ri);
21168 GET_RE_DEBUG_FLAGS_DECL;
21170 PERL_ARGS_ASSERT_DUMPUNTIL;
21172 #ifdef DEBUG_DUMPUNTIL
21173 Perl_re_printf( aTHX_ "--- %d : %d - %d - %d\n", indent, node-start,
21174 last ? last-start : 0, plast ? plast-start : 0);
21177 if (plast && plast < last)
21180 while (PL_regkind[op] != END && (!last || node < last)) {
21182 /* While that wasn't END last time... */
21185 if (op == CLOSE || op == SRCLOSE || op == WHILEM)
21187 next = regnext((regnode *)node);
21190 if (OP(node) == OPTIMIZED) {
21191 if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
21198 regprop(r, sv, node, NULL, NULL);
21199 Perl_re_printf( aTHX_ "%4" IVdf ":%*s%s", (IV)(node - start),
21200 (int)(2*indent + 1), "", SvPVX_const(sv));
21202 if (OP(node) != OPTIMIZED) {
21203 if (next == NULL) /* Next ptr. */
21204 Perl_re_printf( aTHX_ " (0)");
21205 else if (PL_regkind[(U8)op] == BRANCH
21206 && PL_regkind[OP(next)] != BRANCH )
21207 Perl_re_printf( aTHX_ " (FAIL)");
21209 Perl_re_printf( aTHX_ " (%" IVdf ")", (IV)(next - start));
21210 Perl_re_printf( aTHX_ "\n");
21214 if (PL_regkind[(U8)op] == BRANCHJ) {
21217 const regnode *nnode = (OP(next) == LONGJMP
21218 ? regnext((regnode *)next)
21220 if (last && nnode > last)
21222 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
21225 else if (PL_regkind[(U8)op] == BRANCH) {
21227 DUMPUNTIL(NEXTOPER(node), next);
21229 else if ( PL_regkind[(U8)op] == TRIE ) {
21230 const regnode *this_trie = node;
21231 const char op = OP(node);
21232 const U32 n = ARG(node);
21233 const reg_ac_data * const ac = op>=AHOCORASICK ?
21234 (reg_ac_data *)ri->data->data[n] :
21236 const reg_trie_data * const trie =
21237 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
21239 AV *const trie_words
21240 = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
21242 const regnode *nextbranch= NULL;
21245 for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
21246 SV ** const elem_ptr = av_fetch(trie_words, word_idx, 0);
21248 Perl_re_indentf( aTHX_ "%s ",
21251 ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr),
21252 SvCUR(*elem_ptr), PL_dump_re_max_len,
21253 PL_colors[0], PL_colors[1],
21255 ? PERL_PV_ESCAPE_UNI
21257 | PERL_PV_PRETTY_ELLIPSES
21258 | PERL_PV_PRETTY_LTGT
21263 U16 dist= trie->jump[word_idx+1];
21264 Perl_re_printf( aTHX_ "(%" UVuf ")\n",
21265 (UV)((dist ? this_trie + dist : next) - start));
21268 nextbranch= this_trie + trie->jump[0];
21269 DUMPUNTIL(this_trie + dist, nextbranch);
21271 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
21272 nextbranch= regnext((regnode *)nextbranch);
21274 Perl_re_printf( aTHX_ "\n");
21277 if (last && next > last)
21282 else if ( op == CURLY ) { /* "next" might be very big: optimizer */
21283 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
21284 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
21286 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
21288 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
21290 else if ( op == PLUS || op == STAR) {
21291 DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
21293 else if (PL_regkind[(U8)op] == EXACT) {
21294 /* Literal string, where present. */
21295 node += NODE_SZ_STR(node) - 1;
21296 node = NEXTOPER(node);
21299 node = NEXTOPER(node);
21300 node += regarglen[(U8)op];
21302 if (op == CURLYX || op == OPEN || op == SROPEN)
21306 #ifdef DEBUG_DUMPUNTIL
21307 Perl_re_printf( aTHX_ "--- %d\n", (int)indent);
21312 #endif /* DEBUGGING */
21314 #ifndef PERL_IN_XSUB_RE
21316 #include "uni_keywords.h"
21319 Perl_init_uniprops(pTHX)
21321 /* Set up the inversion list global variables */
21323 PL_XPosix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
21324 PL_XPosix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALNUM]);
21325 PL_XPosix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALPHA]);
21326 PL_XPosix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXBLANK]);
21327 PL_XPosix_ptrs[_CC_CASED] = _new_invlist_C_array(uni_prop_ptrs[UNI_CASED]);
21328 PL_XPosix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXCNTRL]);
21329 PL_XPosix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXDIGIT]);
21330 PL_XPosix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXGRAPH]);
21331 PL_XPosix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXLOWER]);
21332 PL_XPosix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPRINT]);
21333 PL_XPosix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPUNCT]);
21334 PL_XPosix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXSPACE]);
21335 PL_XPosix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXUPPER]);
21336 PL_XPosix_ptrs[_CC_VERTSPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_VERTSPACE]);
21337 PL_XPosix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXWORD]);
21338 PL_XPosix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXXDIGIT]);
21340 PL_Posix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
21341 PL_Posix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALNUM]);
21342 PL_Posix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALPHA]);
21343 PL_Posix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXBLANK]);
21344 PL_Posix_ptrs[_CC_CASED] = PL_Posix_ptrs[_CC_ALPHA];
21345 PL_Posix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXCNTRL]);
21346 PL_Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXDIGIT]);
21347 PL_Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXGRAPH]);
21348 PL_Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXLOWER]);
21349 PL_Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPRINT]);
21350 PL_Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPUNCT]);
21351 PL_Posix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXSPACE]);
21352 PL_Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXUPPER]);
21353 PL_Posix_ptrs[_CC_VERTSPACE] = NULL;
21354 PL_Posix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXWORD]);
21355 PL_Posix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXXDIGIT]);
21357 PL_GCB_invlist = _new_invlist_C_array(_Perl_GCB_invlist);
21358 PL_SB_invlist = _new_invlist_C_array(_Perl_SB_invlist);
21359 PL_WB_invlist = _new_invlist_C_array(_Perl_WB_invlist);
21360 PL_LB_invlist = _new_invlist_C_array(_Perl_LB_invlist);
21361 PL_SCX_invlist = _new_invlist_C_array(_Perl_SCX_invlist);
21363 PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
21364 PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
21365 PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist);
21367 PL_Assigned_invlist = _new_invlist_C_array(uni_prop_ptrs[UNI_ASSIGNED]);
21369 PL_utf8_perl_idstart = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDSTART]);
21370 PL_utf8_perl_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDCONT]);
21372 PL_utf8_charname_begin = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_BEGIN]);
21373 PL_utf8_charname_continue = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_CONTINUE]);
21375 PL_utf8_foldable = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_ANY_FOLDS]);
21376 PL_HasMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
21377 UNI__PERL_FOLDS_TO_MULTI_CHAR]);
21378 PL_NonL1NonFinalFold = _new_invlist_C_array(
21379 NonL1_Perl_Non_Final_Folds_invlist);
21381 PL_utf8_toupper = _new_invlist_C_array(Uppercase_Mapping_invlist);
21382 PL_utf8_tolower = _new_invlist_C_array(Lowercase_Mapping_invlist);
21383 PL_utf8_totitle = _new_invlist_C_array(Titlecase_Mapping_invlist);
21384 PL_utf8_tofold = _new_invlist_C_array(Case_Folding_invlist);
21385 PL_utf8_tosimplefold = _new_invlist_C_array(Simple_Case_Folding_invlist);
21386 PL_utf8_foldclosures = _new_invlist_C_array(_Perl_IVCF_invlist);
21387 PL_utf8_mark = _new_invlist_C_array(uni_prop_ptrs[UNI_M]);
21389 /* The below are used only by deprecated functions. They could be removed */
21390 PL_utf8_xidcont = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDC]);
21391 PL_utf8_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI_IDC]);
21392 PL_utf8_xidstart = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDS]);
21396 Perl_parse_uniprop_string(pTHX_ const char * const name, const Size_t name_len,
21397 const bool to_fold, bool * invert)
21399 /* Parse the interior meat of \p{} passed to this in 'name' with length
21400 * 'name_len', and return an inversion list if a property with 'name' is
21401 * found, or NULL if not. 'name' point to the input with leading and
21402 * trailing space trimmed. 'to_fold' indicates if /i is in effect.
21404 * When the return is an inversion list, '*invert' will be set to a boolean
21405 * indicating if it should be inverted or not
21407 * This currently doesn't handle all cases. A NULL return indicates the
21408 * caller should try a different approach
21412 bool stricter = FALSE;
21413 bool is_nv_type = FALSE; /* nv= or numeric_value=, or possibly one
21414 of the cjk numeric properties (though
21415 it requires extra effort to compile
21418 unsigned int j = 0, lookup_len;
21419 int equals_pos = -1; /* Where the '=' is found, or negative if none */
21420 int slash_pos = -1; /* Where the '/' is found, or negative if none */
21421 int table_index = 0;
21422 bool starts_with_In_or_Is = FALSE;
21423 Size_t lookup_offset = 0;
21425 PERL_ARGS_ASSERT_PARSE_UNIPROP_STRING;
21427 /* The input will be modified into 'lookup_name' */
21428 Newx(lookup_name, name_len, char);
21429 SAVEFREEPV(lookup_name);
21431 /* Parse the input. */
21432 for (i = 0; i < name_len; i++) {
21433 char cur = name[i];
21435 /* These characters can be freely ignored in most situations. Later it
21436 * may turn out we shouldn't have ignored them, and we have to reparse,
21437 * but we don't have enough information yet to make that decision */
21438 if (cur == '-' || cur == '_' || isSPACE_A(cur)) {
21442 /* Case differences are also ignored. Our lookup routine assumes
21443 * everything is lowercase */
21444 if (isUPPER_A(cur)) {
21445 lookup_name[j++] = toLOWER(cur);
21449 /* A double colon is either an error, or a package qualifier to a
21450 * subroutine user-defined property; neither of which do we currently
21453 * But a single colon is a synonym for '=' */
21455 if (i < name_len - 1 && name[i+1] == ':') {
21461 /* Otherwise, this character is part of the name. */
21462 lookup_name[j++] = cur;
21464 /* Only the equals sign needs further processing */
21466 equals_pos = j; /* Note where it occurred in the input */
21471 /* Here, we are either done with the whole property name, if it was simple;
21472 * or are positioned just after the '=' if it is compound. */
21474 if (equals_pos >= 0) {
21475 assert(! stricter); /* We shouldn't have set this yet */
21477 /* Space immediately after the '=' is ignored */
21479 for (; i < name_len; i++) {
21480 if (! isSPACE_A(name[i])) {
21485 /* Certain properties need special handling. They may optionally be
21486 * prefixed by 'is'. Ignore that prefix for the purposes of checking
21487 * if this is one of those properties */
21488 if (memBEGINPs(lookup_name, name_len, "is")) {
21492 /* Then check if it is one of these properties. This is hard-coded
21493 * because easier this way, and the list is unlikely to change. There
21494 * are several properties like this in the Unihan DB, which is unlikely
21495 * to be compiled, and they all end with 'numeric'. The interiors
21496 * aren't checked for the precise property. This would stop working if
21497 * a cjk property were to be created that ended with 'numeric' and
21498 * wasn't a numeric type */
21499 is_nv_type = memEQs(lookup_name + lookup_offset,
21500 j - 1 - lookup_offset, "numericvalue")
21501 || memEQs(lookup_name + lookup_offset,
21502 j - 1 - lookup_offset, "nv")
21503 || ( memENDPs(lookup_name + lookup_offset,
21504 j - 1 - lookup_offset, "numeric")
21505 && ( memBEGINPs(lookup_name + lookup_offset,
21506 j - 1 - lookup_offset, "cjk")
21507 || memBEGINPs(lookup_name + lookup_offset,
21508 j - 1 - lookup_offset, "k")));
21510 || memEQs(lookup_name + lookup_offset,
21511 j - 1 - lookup_offset, "canonicalcombiningclass")
21512 || memEQs(lookup_name + lookup_offset,
21513 j - 1 - lookup_offset, "ccc")
21514 || memEQs(lookup_name + lookup_offset,
21515 j - 1 - lookup_offset, "age")
21516 || memEQs(lookup_name + lookup_offset,
21517 j - 1 - lookup_offset, "in")
21518 || memEQs(lookup_name + lookup_offset,
21519 j - 1 - lookup_offset, "presentin"))
21523 /* What makes these properties special is that the stuff after the
21524 * '=' is a number. Therefore, we can't throw away '-'
21525 * willy-nilly, as those could be a minus sign. Other stricter
21526 * rules also apply. However, these properties all can have the
21527 * rhs not be a number, in which case they contain at least one
21528 * alphabetic. In those cases, the stricter rules don't apply.
21529 * But the numeric type properties can have the alphas [Ee] to
21530 * signify an exponent, and it is still a number with stricter
21531 * rules. So look for an alpha that signifys not-strict */
21533 for (k = i; k < name_len; k++) {
21534 if ( isALPHA_A(name[k])
21535 && (! is_nv_type || ! isALPHA_FOLD_EQ(name[k], 'E')))
21545 /* A number may have a leading '+' or '-'. The latter is retained
21547 if (name[i] == '+') {
21550 else if (name[i] == '-') {
21551 lookup_name[j++] = '-';
21555 /* Skip leading zeros including single underscores separating the
21556 * zeros, or between the final leading zero and the first other
21558 for (; i < name_len - 1; i++) {
21559 if ( name[i] != '0'
21560 && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
21567 else { /* No '=' */
21569 /* We are now in a position to determine if this property should have
21570 * been parsed using stricter rules. Only a few are like that, and
21571 * unlikely to change. */
21572 if ( memBEGINPs(lookup_name, j, "perl")
21573 && memNEs(lookup_name + 4, j - 4, "space")
21574 && memNEs(lookup_name + 4, j - 4, "word"))
21578 /* We set the inputs back to 0 and the code below will reparse,
21584 /* Here, we have either finished the property, or are positioned to parse
21585 * the remainder, and we know if stricter rules apply. Finish out, if not
21587 for (; i < name_len; i++) {
21588 char cur = name[i];
21590 /* In all instances, case differences are ignored, and we normalize to
21592 if (isUPPER_A(cur)) {
21593 lookup_name[j++] = toLOWER(cur);
21597 /* An underscore is skipped, but not under strict rules unless it
21598 * separates two digits */
21601 && ( i == 0 || (int) i == equals_pos || i == name_len- 1
21602 || ! isDIGIT_A(name[i-1]) || ! isDIGIT_A(name[i+1])))
21604 lookup_name[j++] = '_';
21609 /* Hyphens are skipped except under strict */
21610 if (cur == '-' && ! stricter) {
21614 /* XXX Bug in documentation. It says white space skipped adjacent to
21615 * non-word char. Maybe we should, but shouldn't skip it next to a dot
21617 if (isSPACE_A(cur) && ! stricter) {
21621 lookup_name[j++] = cur;
21623 /* Unless this is a non-trailing slash, we are done with it */
21624 if (i >= name_len - 1 || cur != '/') {
21630 /* A slash in the 'numeric value' property indicates that what follows
21631 * is a denominator. It can have a leading '+' and '0's that should be
21632 * skipped. But we have never allowed a negative denominator, so treat
21633 * a minus like every other character. (No need to rule out a second
21634 * '/', as that won't match anything anyway */
21637 if (i < name_len && name[i] == '+') {
21641 /* Skip leading zeros including underscores separating digits */
21642 for (; i < name_len - 1; i++) {
21643 if ( name[i] != '0'
21644 && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
21650 /* Store the first real character in the denominator */
21651 lookup_name[j++] = name[i];
21655 /* Here are completely done parsing the input 'name', and 'lookup_name'
21656 * contains a copy, normalized.
21658 * This special case is grandfathered in: 'L_' and 'GC=L_' are accepted and
21659 * different from without the underscores. */
21660 if ( ( UNLIKELY(memEQs(lookup_name, j, "l"))
21661 || UNLIKELY(memEQs(lookup_name, j, "gc=l")))
21662 && UNLIKELY(name[name_len-1] == '_'))
21664 lookup_name[j++] = '&';
21666 else if (name_len > 2 && name[0] == 'I' && ( name[1] == 'n'
21667 || name[1] == 's'))
21670 /* Also, if the original input began with 'In' or 'Is', it could be a
21671 * subroutine call instead of a property names, which currently isn't
21672 * handled by this function. Subroutine calls can't happen if there is
21673 * an '=' in the name */
21674 if (equals_pos < 0 && get_cvn_flags(name, name_len, GV_NOTQUAL) != NULL)
21679 starts_with_In_or_Is = TRUE;
21682 lookup_len = j; /* Use a more mnemonic name starting here */
21684 /* Get the index into our pointer table of the inversion list corresponding
21685 * to the property */
21686 table_index = match_uniprop((U8 *) lookup_name, lookup_len);
21688 /* If it didn't find the property */
21689 if (table_index == 0) {
21691 /* If didn't find the property, we try again stripping off any initial
21693 if (starts_with_In_or_Is) {
21699 table_index = match_uniprop((U8 *) lookup_name, lookup_len);
21702 if (table_index == 0) {
21705 /* If not found, and not a numeric type property, isn't a legal
21707 if (! is_nv_type) {
21711 /* But the numeric type properties need more work to decide. What
21712 * we do is make sure we have the number in canonical form and look
21715 if (slash_pos < 0) { /* No slash */
21717 /* When it isn't a rational, take the input, convert it to a
21718 * NV, then create a canonical string representation of that
21723 /* Get the value */
21724 if (my_atof3(lookup_name + equals_pos, &value,
21725 lookup_len - equals_pos)
21726 != lookup_name + lookup_len)
21731 /* If the value is an integer, the canonical value is integral */
21732 if (Perl_ceil(value) == value) {
21733 canonical = Perl_form(aTHX_ "%.*s%.0" NVff,
21734 equals_pos, lookup_name, value);
21736 else { /* Otherwise, it is %e with a known precision */
21739 canonical = Perl_form(aTHX_ "%.*s%.*" NVef,
21740 equals_pos, lookup_name,
21741 PL_E_FORMAT_PRECISION, value);
21743 /* The exponent generated is expecting two digits, whereas
21744 * %e on some systems will generate three. Remove leading
21745 * zeros in excess of 2 from the exponent. We start
21746 * looking for them after the '=' */
21747 exp_ptr = strchr(canonical + equals_pos, 'e');
21749 char * cur_ptr = exp_ptr + 2; /* past the 'e[+-]' */
21750 SSize_t excess_exponent_len = strlen(cur_ptr) - 2;
21752 assert(*(cur_ptr - 1) == '-' || *(cur_ptr - 1) == '+');
21754 if (excess_exponent_len > 0) {
21755 SSize_t leading_zeros = strspn(cur_ptr, "0");
21756 SSize_t excess_leading_zeros
21757 = MIN(leading_zeros, excess_exponent_len);
21758 if (excess_leading_zeros > 0) {
21759 Move(cur_ptr + excess_leading_zeros,
21761 strlen(cur_ptr) - excess_leading_zeros
21762 + 1, /* Copy the NUL as well */
21769 else { /* Has a slash. Create a rational in canonical form */
21770 UV numerator, denominator, gcd, trial;
21771 const char * end_ptr;
21772 const char * sign = "";
21774 /* We can't just find the numerator, denominator, and do the
21775 * division, then use the method above, because that is
21776 * inexact. And the input could be a rational that is within
21777 * epsilon (given our precision) of a valid rational, and would
21778 * then incorrectly compare valid.
21780 * We're only interested in the part after the '=' */
21781 const char * this_lookup_name = lookup_name + equals_pos;
21782 lookup_len -= equals_pos;
21783 slash_pos -= equals_pos;
21785 /* Handle any leading minus */
21786 if (this_lookup_name[0] == '-') {
21788 this_lookup_name++;
21793 /* Convert the numerator to numeric */
21794 end_ptr = this_lookup_name + slash_pos;
21795 if (! grok_atoUV(this_lookup_name, &numerator, &end_ptr)) {
21799 /* It better have included all characters before the slash */
21800 if (*end_ptr != '/') {
21804 /* Set to look at just the denominator */
21805 this_lookup_name += slash_pos;
21806 lookup_len -= slash_pos;
21807 end_ptr = this_lookup_name + lookup_len;
21809 /* Convert the denominator to numeric */
21810 if (! grok_atoUV(this_lookup_name, &denominator, &end_ptr)) {
21814 /* It better be the rest of the characters, and don't divide by
21816 if ( end_ptr != this_lookup_name + lookup_len
21817 || denominator == 0)
21822 /* Get the greatest common denominator using
21823 http://en.wikipedia.org/wiki/Euclidean_algorithm */
21825 trial = denominator;
21826 while (trial != 0) {
21828 trial = gcd % trial;
21832 /* If already in lowest possible terms, we have already tried
21833 * looking this up */
21838 /* Reduce the rational, which should put it in canonical form.
21839 * Then look it up */
21841 denominator /= gcd;
21843 canonical = Perl_form(aTHX_ "%.*s%s%" UVuf "/%" UVuf,
21844 equals_pos, lookup_name, sign, numerator, denominator);
21847 /* Here, we have the number in canonical form. Try that */
21848 table_index = match_uniprop((U8 *) canonical, strlen(canonical));
21849 if (table_index == 0) {
21855 /* The return is an index into a table of ptrs. A negative return
21856 * signifies that the real index is the absolute value, but the result
21857 * needs to be inverted */
21858 if (table_index < 0) {
21860 table_index = -table_index;
21866 /* Out-of band indices indicate a deprecated property. The proper index is
21867 * modulo it with the table size. And dividing by the table size yields
21868 * an offset into a table constructed to contain the corresponding warning
21870 if (table_index > MAX_UNI_KEYWORD_INDEX) {
21871 Size_t warning_offset = table_index / MAX_UNI_KEYWORD_INDEX;
21872 table_index %= MAX_UNI_KEYWORD_INDEX;
21873 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
21874 "Use of '%.*s' in \\p{} or \\P{} is deprecated because: %s",
21875 (int) name_len, name, deprecated_property_msgs[warning_offset]);
21878 /* In a few properties, a different property is used under /i. These are
21879 * unlikely to change, so are hard-coded here. */
21881 if ( table_index == UNI_XPOSIXUPPER
21882 || table_index == UNI_XPOSIXLOWER
21883 || table_index == UNI_TITLE)
21885 table_index = UNI_CASED;
21887 else if ( table_index == UNI_UPPERCASELETTER
21888 || table_index == UNI_LOWERCASELETTER
21889 # ifdef UNI_TITLECASELETTER /* Missing from early Unicodes */
21890 || table_index == UNI_TITLECASELETTER
21893 table_index = UNI_CASEDLETTER;
21895 else if ( table_index == UNI_POSIXUPPER
21896 || table_index == UNI_POSIXLOWER)
21898 table_index = UNI_POSIXALPHA;
21902 /* Create and return the inversion list */
21903 return _new_invlist_C_array(uni_prop_ptrs[table_index]);
21909 * ex: set ts=8 sts=4 sw=4 et: