This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
makedef.pl: Add comment
[perl5.git] / regcomp.c
... / ...
CommitLineData
1/* regcomp.c
2 */
3
4/*
5 * 'A fair jaw-cracker dwarf-language must be.' --Samwise Gamgee
6 *
7 * [p.285 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
8 */
9
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.
13 *
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.
18 */
19
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!
22 */
23
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.
27 */
28
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.
32*/
33
34#ifdef PERL_EXT_RE_BUILD
35#include "re_top.h"
36#endif
37
38/*
39 * pregcomp and pregexec -- regsub and regerror are not used in perl
40 *
41 * Copyright (c) 1986 by University of Toronto.
42 * Written by Henry Spencer. Not derived from licensed software.
43 *
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:
47 *
48 * 1. The author is not responsible for the consequences of use of
49 * this software, no matter how awful, even if they arise
50 * from defects in it.
51 *
52 * 2. The origin of this software must not be misrepresented, either
53 * by explicit claim or by omission.
54 *
55 * 3. Altered versions must be plainly marked as such, and must not
56 * be misrepresented as being the original software.
57 *
58 *
59 **** Alterations to Henry's code are...
60 ****
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
64 ****
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.
67
68 *
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.
72 */
73#include "EXTERN.h"
74#define PERL_IN_REGCOMP_C
75#include "perl.h"
76
77#define REG_COMP_C
78#ifdef PERL_IN_XSUB_RE
79# include "re_comp.h"
80EXTERN_C const struct regexp_engine my_reg_engine;
81#else
82# include "regcomp.h"
83#endif
84
85#include "invlist_inline.h"
86#include "unicode_constants.h"
87
88#define HAS_NONLATIN1_FOLD_CLOSURE(i) \
89 _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
90#define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
91 _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
92#define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
93#define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
94
95#ifndef STATIC
96#define STATIC static
97#endif
98
99/* this is a chain of data about sub patterns we are processing that
100 need to be handled separately/specially in study_chunk. Its so
101 we can simulate recursion without losing state. */
102struct scan_frame;
103typedef struct scan_frame {
104 regnode *last_regnode; /* last node to process in this frame */
105 regnode *next_regnode; /* next node to process when last is reached */
106 U32 prev_recursed_depth;
107 I32 stopparen; /* what stopparen do we use */
108
109 struct scan_frame *this_prev_frame; /* this previous frame */
110 struct scan_frame *prev_frame; /* previous frame */
111 struct scan_frame *next_frame; /* next frame */
112} scan_frame;
113
114/* Certain characters are output as a sequence with the first being a
115 * backslash. */
116#define isBACKSLASHED_PUNCT(c) memCHRs("-[]\\^", c)
117
118
119struct RExC_state_t {
120 U32 flags; /* RXf_* are we folding, multilining? */
121 U32 pm_flags; /* PMf_* stuff from the calling PMOP */
122 char *precomp; /* uncompiled string. */
123 char *precomp_end; /* pointer to end of uncompiled string. */
124 REGEXP *rx_sv; /* The SV that is the regexp. */
125 regexp *rx; /* perl core regexp structure */
126 regexp_internal *rxi; /* internal data for regexp object
127 pprivate field */
128 char *start; /* Start of input for compile */
129 char *end; /* End of input for compile */
130 char *parse; /* Input-scan pointer. */
131 char *copy_start; /* start of copy of input within
132 constructed parse string */
133 char *save_copy_start; /* Provides one level of saving
134 and restoring 'copy_start' */
135 char *copy_start_in_input; /* Position in input string
136 corresponding to copy_start */
137 SSize_t whilem_seen; /* number of WHILEM in this expr */
138 regnode *emit_start; /* Start of emitted-code area */
139 regnode_offset emit; /* Code-emit pointer */
140 I32 naughty; /* How bad is this pattern? */
141 I32 sawback; /* Did we see \1, ...? */
142 SSize_t size; /* Number of regnode equivalents in
143 pattern */
144 Size_t sets_depth; /* Counts recursion depth of already-
145 compiled regex set patterns */
146 U32 seen;
147
148 I32 parens_buf_size; /* #slots malloced open/close_parens */
149 regnode_offset *open_parens; /* offsets to open parens */
150 regnode_offset *close_parens; /* offsets to close parens */
151 HV *paren_names; /* Paren names */
152
153 /* position beyond 'precomp' of the warning message furthest away from
154 * 'precomp'. During the parse, no warnings are raised for any problems
155 * earlier in the parse than this position. This works if warnings are
156 * raised the first time a given spot is parsed, and if only one
157 * independent warning is raised for any given spot */
158 Size_t latest_warn_offset;
159
160 I32 npar; /* Capture buffer count so far in the
161 parse, (OPEN) plus one. ("par" 0 is
162 the whole pattern)*/
163 I32 total_par; /* During initial parse, is either 0,
164 or -1; the latter indicating a
165 reparse is needed. After that pass,
166 it is what 'npar' became after the
167 pass. Hence, it being > 0 indicates
168 we are in a reparse situation */
169 I32 nestroot; /* root parens we are in - used by
170 accept */
171 I32 seen_zerolen;
172 regnode *end_op; /* END node in program */
173 I32 utf8; /* whether the pattern is utf8 or not */
174 I32 orig_utf8; /* whether the pattern was originally in utf8 */
175 /* XXX use this for future optimisation of case
176 * where pattern must be upgraded to utf8. */
177 I32 uni_semantics; /* If a d charset modifier should use unicode
178 rules, even if the pattern is not in
179 utf8 */
180
181 I32 recurse_count; /* Number of recurse regops we have generated */
182 regnode **recurse; /* Recurse regops */
183 U8 *study_chunk_recursed; /* bitmap of which subs we have moved
184 through */
185 U32 study_chunk_recursed_bytes; /* bytes in bitmap */
186 I32 in_lookbehind;
187 I32 in_lookahead;
188 I32 contains_locale;
189 I32 override_recoding;
190 I32 recode_x_to_native;
191 I32 in_multi_char_class;
192 int code_index; /* next code_blocks[] slot */
193 struct reg_code_blocks *code_blocks;/* positions of literal (?{})
194 within pattern */
195 SSize_t maxlen; /* mininum possible number of chars in string to match */
196 scan_frame *frame_head;
197 scan_frame *frame_last;
198 U32 frame_count;
199 AV *warn_text;
200 HV *unlexed_names;
201 SV *runtime_code_qr; /* qr with the runtime code blocks */
202#ifdef DEBUGGING
203 const char *lastparse;
204 I32 lastnum;
205 U32 study_chunk_recursed_count;
206 AV *paren_name_list; /* idx -> name */
207 SV *mysv1;
208 SV *mysv2;
209
210#define RExC_lastparse (pRExC_state->lastparse)
211#define RExC_lastnum (pRExC_state->lastnum)
212#define RExC_paren_name_list (pRExC_state->paren_name_list)
213#define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count)
214#define RExC_mysv (pRExC_state->mysv1)
215#define RExC_mysv1 (pRExC_state->mysv1)
216#define RExC_mysv2 (pRExC_state->mysv2)
217
218#endif
219 bool seen_d_op;
220 bool strict;
221 bool study_started;
222 bool in_script_run;
223 bool use_BRANCHJ;
224 bool sWARN_EXPERIMENTAL__VLB;
225 bool sWARN_EXPERIMENTAL__REGEX_SETS;
226};
227
228#define RExC_flags (pRExC_state->flags)
229#define RExC_pm_flags (pRExC_state->pm_flags)
230#define RExC_precomp (pRExC_state->precomp)
231#define RExC_copy_start_in_input (pRExC_state->copy_start_in_input)
232#define RExC_copy_start_in_constructed (pRExC_state->copy_start)
233#define RExC_save_copy_start_in_constructed (pRExC_state->save_copy_start)
234#define RExC_precomp_end (pRExC_state->precomp_end)
235#define RExC_rx_sv (pRExC_state->rx_sv)
236#define RExC_rx (pRExC_state->rx)
237#define RExC_rxi (pRExC_state->rxi)
238#define RExC_start (pRExC_state->start)
239#define RExC_end (pRExC_state->end)
240#define RExC_parse (pRExC_state->parse)
241#define RExC_latest_warn_offset (pRExC_state->latest_warn_offset )
242#define RExC_whilem_seen (pRExC_state->whilem_seen)
243#define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs
244 under /d from /u ? */
245
246#ifdef RE_TRACK_PATTERN_OFFSETS
247# define RExC_offsets (RExC_rxi->u.offsets) /* I am not like the
248 others */
249#endif
250#define RExC_emit (pRExC_state->emit)
251#define RExC_emit_start (pRExC_state->emit_start)
252#define RExC_sawback (pRExC_state->sawback)
253#define RExC_seen (pRExC_state->seen)
254#define RExC_size (pRExC_state->size)
255#define RExC_maxlen (pRExC_state->maxlen)
256#define RExC_npar (pRExC_state->npar)
257#define RExC_total_parens (pRExC_state->total_par)
258#define RExC_parens_buf_size (pRExC_state->parens_buf_size)
259#define RExC_nestroot (pRExC_state->nestroot)
260#define RExC_seen_zerolen (pRExC_state->seen_zerolen)
261#define RExC_utf8 (pRExC_state->utf8)
262#define RExC_uni_semantics (pRExC_state->uni_semantics)
263#define RExC_orig_utf8 (pRExC_state->orig_utf8)
264#define RExC_open_parens (pRExC_state->open_parens)
265#define RExC_close_parens (pRExC_state->close_parens)
266#define RExC_end_op (pRExC_state->end_op)
267#define RExC_paren_names (pRExC_state->paren_names)
268#define RExC_recurse (pRExC_state->recurse)
269#define RExC_recurse_count (pRExC_state->recurse_count)
270#define RExC_sets_depth (pRExC_state->sets_depth)
271#define RExC_study_chunk_recursed (pRExC_state->study_chunk_recursed)
272#define RExC_study_chunk_recursed_bytes \
273 (pRExC_state->study_chunk_recursed_bytes)
274#define RExC_in_lookbehind (pRExC_state->in_lookbehind)
275#define RExC_in_lookahead (pRExC_state->in_lookahead)
276#define RExC_contains_locale (pRExC_state->contains_locale)
277#define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
278
279#ifdef EBCDIC
280# define SET_recode_x_to_native(x) \
281 STMT_START { RExC_recode_x_to_native = (x); } STMT_END
282#else
283# define SET_recode_x_to_native(x) NOOP
284#endif
285
286#define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
287#define RExC_frame_head (pRExC_state->frame_head)
288#define RExC_frame_last (pRExC_state->frame_last)
289#define RExC_frame_count (pRExC_state->frame_count)
290#define RExC_strict (pRExC_state->strict)
291#define RExC_study_started (pRExC_state->study_started)
292#define RExC_warn_text (pRExC_state->warn_text)
293#define RExC_in_script_run (pRExC_state->in_script_run)
294#define RExC_use_BRANCHJ (pRExC_state->use_BRANCHJ)
295#define RExC_warned_WARN_EXPERIMENTAL__VLB (pRExC_state->sWARN_EXPERIMENTAL__VLB)
296#define RExC_warned_WARN_EXPERIMENTAL__REGEX_SETS (pRExC_state->sWARN_EXPERIMENTAL__REGEX_SETS)
297#define RExC_unlexed_names (pRExC_state->unlexed_names)
298
299/* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
300 * a flag to disable back-off on the fixed/floating substrings - if it's
301 * a high complexity pattern we assume the benefit of avoiding a full match
302 * is worth the cost of checking for the substrings even if they rarely help.
303 */
304#define RExC_naughty (pRExC_state->naughty)
305#define TOO_NAUGHTY (10)
306#define MARK_NAUGHTY(add) \
307 if (RExC_naughty < TOO_NAUGHTY) \
308 RExC_naughty += (add)
309#define MARK_NAUGHTY_EXP(exp, add) \
310 if (RExC_naughty < TOO_NAUGHTY) \
311 RExC_naughty += RExC_naughty / (exp) + (add)
312
313#define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
314#define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
315 ((*s) == '{' && regcurly(s)))
316
317/*
318 * Flags to be passed up and down.
319 */
320#define WORST 0 /* Worst case. */
321#define HASWIDTH 0x01 /* Known to not match null strings, could match
322 non-null ones. */
323
324/* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
325 * character. (There needs to be a case: in the switch statement in regexec.c
326 * for any node marked SIMPLE.) Note that this is not the same thing as
327 * REGNODE_SIMPLE */
328#define SIMPLE 0x02
329#define SPSTART 0x04 /* Starts with * or + */
330#define POSTPONED 0x08 /* (?1),(?&name), (??{...}) or similar */
331#define TRYAGAIN 0x10 /* Weeded out a declaration. */
332#define RESTART_PARSE 0x20 /* Need to redo the parse */
333#define NEED_UTF8 0x40 /* In conjunction with RESTART_PARSE, need to
334 calcuate sizes as UTF-8 */
335
336#define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
337
338/* whether trie related optimizations are enabled */
339#if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
340#define TRIE_STUDY_OPT
341#define FULL_TRIE_STUDY
342#define TRIE_STCLASS
343#endif
344
345
346
347#define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
348#define PBITVAL(paren) (1 << ((paren) & 7))
349#define PAREN_OFFSET(depth) \
350 (RExC_study_chunk_recursed + (depth) * RExC_study_chunk_recursed_bytes)
351#define PAREN_TEST(depth, paren) \
352 (PBYTE(PAREN_OFFSET(depth), paren) & PBITVAL(paren))
353#define PAREN_SET(depth, paren) \
354 (PBYTE(PAREN_OFFSET(depth), paren) |= PBITVAL(paren))
355#define PAREN_UNSET(depth, paren) \
356 (PBYTE(PAREN_OFFSET(depth), paren) &= ~PBITVAL(paren))
357
358#define REQUIRE_UTF8(flagp) STMT_START { \
359 if (!UTF) { \
360 *flagp = RESTART_PARSE|NEED_UTF8; \
361 return 0; \
362 } \
363 } STMT_END
364
365/* Change from /d into /u rules, and restart the parse. RExC_uni_semantics is
366 * a flag that indicates we need to override /d with /u as a result of
367 * something in the pattern. It should only be used in regards to calling
368 * set_regex_charset() or get_regex_charset() */
369#define REQUIRE_UNI_RULES(flagp, restart_retval) \
370 STMT_START { \
371 if (DEPENDS_SEMANTICS) { \
372 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); \
373 RExC_uni_semantics = 1; \
374 if (RExC_seen_d_op && LIKELY(! IN_PARENS_PASS)) { \
375 /* No need to restart the parse if we haven't seen \
376 * anything that differs between /u and /d, and no need \
377 * to restart immediately if we're going to reparse \
378 * anyway to count parens */ \
379 *flagp |= RESTART_PARSE; \
380 return restart_retval; \
381 } \
382 } \
383 } STMT_END
384
385#define REQUIRE_BRANCHJ(flagp, restart_retval) \
386 STMT_START { \
387 RExC_use_BRANCHJ = 1; \
388 *flagp |= RESTART_PARSE; \
389 return restart_retval; \
390 } STMT_END
391
392/* Until we have completed the parse, we leave RExC_total_parens at 0 or
393 * less. After that, it must always be positive, because the whole re is
394 * considered to be surrounded by virtual parens. Setting it to negative
395 * indicates there is some construct that needs to know the actual number of
396 * parens to be properly handled. And that means an extra pass will be
397 * required after we've counted them all */
398#define ALL_PARENS_COUNTED (RExC_total_parens > 0)
399#define REQUIRE_PARENS_PASS \
400 STMT_START { /* No-op if have completed a pass */ \
401 if (! ALL_PARENS_COUNTED) RExC_total_parens = -1; \
402 } STMT_END
403#define IN_PARENS_PASS (RExC_total_parens < 0)
404
405
406/* This is used to return failure (zero) early from the calling function if
407 * various flags in 'flags' are set. Two flags always cause a return:
408 * 'RESTART_PARSE' and 'NEED_UTF8'. 'extra' can be used to specify any
409 * additional flags that should cause a return; 0 if none. If the return will
410 * be done, '*flagp' is first set to be all of the flags that caused the
411 * return. */
412#define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra) \
413 STMT_START { \
414 if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) { \
415 *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra)); \
416 return 0; \
417 } \
418 } STMT_END
419
420#define MUST_RESTART(flags) ((flags) & (RESTART_PARSE))
421
422#define RETURN_FAIL_ON_RESTART(flags,flagp) \
423 RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0)
424#define RETURN_FAIL_ON_RESTART_FLAGP(flagp) \
425 if (MUST_RESTART(*(flagp))) return 0
426
427/* This converts the named class defined in regcomp.h to its equivalent class
428 * number defined in handy.h. */
429#define namedclass_to_classnum(class) ((int) ((class) / 2))
430#define classnum_to_namedclass(classnum) ((classnum) * 2)
431
432#define _invlist_union_complement_2nd(a, b, output) \
433 _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
434#define _invlist_intersection_complement_2nd(a, b, output) \
435 _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
436
437/* We add a marker if we are deferring expansion of a property that is both
438 * 1) potentiallly user-defined; and
439 * 2) could also be an official Unicode property.
440 *
441 * Without this marker, any deferred expansion can only be for a user-defined
442 * one. This marker shouldn't conflict with any that could be in a legal name,
443 * and is appended to its name to indicate this. There is a string and
444 * character form */
445#define DEFERRED_COULD_BE_OFFICIAL_MARKERs "~"
446#define DEFERRED_COULD_BE_OFFICIAL_MARKERc '~'
447
448/* What is infinity for optimization purposes */
449#define OPTIMIZE_INFTY SSize_t_MAX
450
451/* About scan_data_t.
452
453 During optimisation we recurse through the regexp program performing
454 various inplace (keyhole style) optimisations. In addition study_chunk
455 and scan_commit populate this data structure with information about
456 what strings MUST appear in the pattern. We look for the longest
457 string that must appear at a fixed location, and we look for the
458 longest string that may appear at a floating location. So for instance
459 in the pattern:
460
461 /FOO[xX]A.*B[xX]BAR/
462
463 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
464 strings (because they follow a .* construct). study_chunk will identify
465 both FOO and BAR as being the longest fixed and floating strings respectively.
466
467 The strings can be composites, for instance
468
469 /(f)(o)(o)/
470
471 will result in a composite fixed substring 'foo'.
472
473 For each string some basic information is maintained:
474
475 - min_offset
476 This is the position the string must appear at, or not before.
477 It also implicitly (when combined with minlenp) tells us how many
478 characters must match before the string we are searching for.
479 Likewise when combined with minlenp and the length of the string it
480 tells us how many characters must appear after the string we have
481 found.
482
483 - max_offset
484 Only used for floating strings. This is the rightmost point that
485 the string can appear at. If set to OPTIMIZE_INFTY it indicates that the
486 string can occur infinitely far to the right.
487 For fixed strings, it is equal to min_offset.
488
489 - minlenp
490 A pointer to the minimum number of characters of the pattern that the
491 string was found inside. This is important as in the case of positive
492 lookahead or positive lookbehind we can have multiple patterns
493 involved. Consider
494
495 /(?=FOO).*F/
496
497 The minimum length of the pattern overall is 3, the minimum length
498 of the lookahead part is 3, but the minimum length of the part that
499 will actually match is 1. So 'FOO's minimum length is 3, but the
500 minimum length for the F is 1. This is important as the minimum length
501 is used to determine offsets in front of and behind the string being
502 looked for. Since strings can be composites this is the length of the
503 pattern at the time it was committed with a scan_commit. Note that
504 the length is calculated by study_chunk, so that the minimum lengths
505 are not known until the full pattern has been compiled, thus the
506 pointer to the value.
507
508 - lookbehind
509
510 In the case of lookbehind the string being searched for can be
511 offset past the start point of the final matching string.
512 If this value was just blithely removed from the min_offset it would
513 invalidate some of the calculations for how many chars must match
514 before or after (as they are derived from min_offset and minlen and
515 the length of the string being searched for).
516 When the final pattern is compiled and the data is moved from the
517 scan_data_t structure into the regexp structure the information
518 about lookbehind is factored in, with the information that would
519 have been lost precalculated in the end_shift field for the
520 associated string.
521
522 The fields pos_min and pos_delta are used to store the minimum offset
523 and the delta to the maximum offset at the current point in the pattern.
524
525*/
526
527struct scan_data_substrs {
528 SV *str; /* longest substring found in pattern */
529 SSize_t min_offset; /* earliest point in string it can appear */
530 SSize_t max_offset; /* latest point in string it can appear */
531 SSize_t *minlenp; /* pointer to the minlen relevant to the string */
532 SSize_t lookbehind; /* is the pos of the string modified by LB */
533 I32 flags; /* per substring SF_* and SCF_* flags */
534};
535
536typedef struct scan_data_t {
537 /*I32 len_min; unused */
538 /*I32 len_delta; unused */
539 SSize_t pos_min;
540 SSize_t pos_delta;
541 SV *last_found;
542 SSize_t last_end; /* min value, <0 unless valid. */
543 SSize_t last_start_min;
544 SSize_t last_start_max;
545 U8 cur_is_floating; /* whether the last_* values should be set as
546 * the next fixed (0) or floating (1)
547 * substring */
548
549 /* [0] is longest fixed substring so far, [1] is longest float so far */
550 struct scan_data_substrs substrs[2];
551
552 I32 flags; /* common SF_* and SCF_* flags */
553 I32 whilem_c;
554 SSize_t *last_closep;
555 regnode_ssc *start_class;
556} scan_data_t;
557
558/*
559 * Forward declarations for pregcomp()'s friends.
560 */
561
562static const scan_data_t zero_scan_data = {
563 0, 0, NULL, 0, 0, 0, 0,
564 {
565 { NULL, 0, 0, 0, 0, 0 },
566 { NULL, 0, 0, 0, 0, 0 },
567 },
568 0, 0, NULL, NULL
569};
570
571/* study flags */
572
573#define SF_BEFORE_SEOL 0x0001
574#define SF_BEFORE_MEOL 0x0002
575#define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
576
577#define SF_IS_INF 0x0040
578#define SF_HAS_PAR 0x0080
579#define SF_IN_PAR 0x0100
580#define SF_HAS_EVAL 0x0200
581
582
583/* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
584 * longest substring in the pattern. When it is not set the optimiser keeps
585 * track of position, but does not keep track of the actual strings seen,
586 *
587 * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
588 * /foo/i will not.
589 *
590 * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
591 * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
592 * turned off because of the alternation (BRANCH). */
593#define SCF_DO_SUBSTR 0x0400
594
595#define SCF_DO_STCLASS_AND 0x0800
596#define SCF_DO_STCLASS_OR 0x1000
597#define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
598#define SCF_WHILEM_VISITED_POS 0x2000
599
600#define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
601#define SCF_SEEN_ACCEPT 0x8000
602#define SCF_TRIE_DOING_RESTUDY 0x10000
603#define SCF_IN_DEFINE 0x20000
604
605
606
607
608#define UTF cBOOL(RExC_utf8)
609
610/* The enums for all these are ordered so things work out correctly */
611#define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
612#define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) \
613 == REGEX_DEPENDS_CHARSET)
614#define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
615#define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) \
616 >= REGEX_UNICODE_CHARSET)
617#define ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
618 == REGEX_ASCII_RESTRICTED_CHARSET)
619#define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
620 >= REGEX_ASCII_RESTRICTED_CHARSET)
621#define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) \
622 == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
623
624#define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
625
626/* For programs that want to be strictly Unicode compatible by dying if any
627 * attempt is made to match a non-Unicode code point against a Unicode
628 * property. */
629#define ALWAYS_WARN_SUPER ckDEAD(packWARN(WARN_NON_UNICODE))
630
631#define OOB_NAMEDCLASS -1
632
633/* There is no code point that is out-of-bounds, so this is problematic. But
634 * its only current use is to initialize a variable that is always set before
635 * looked at. */
636#define OOB_UNICODE 0xDEADBEEF
637
638#define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
639
640
641/* length of regex to show in messages that don't mark a position within */
642#define RegexLengthToShowInErrorMessages 127
643
644/*
645 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
646 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
647 * op/pragma/warn/regcomp.
648 */
649#define MARKER1 "<-- HERE" /* marker as it appears in the description */
650#define MARKER2 " <-- HERE " /* marker as it appears within the regex */
651
652#define REPORT_LOCATION " in regex; marked by " MARKER1 \
653 " in m/%" UTF8f MARKER2 "%" UTF8f "/"
654
655/* The code in this file in places uses one level of recursion with parsing
656 * rebased to an alternate string constructed by us in memory. This can take
657 * the form of something that is completely different from the input, or
658 * something that uses the input as part of the alternate. In the first case,
659 * there should be no possibility of an error, as we are in complete control of
660 * the alternate string. But in the second case we don't completely control
661 * the input portion, so there may be errors in that. Here's an example:
662 * /[abc\x{DF}def]/ui
663 * is handled specially because \x{df} folds to a sequence of more than one
664 * character: 'ss'. What is done is to create and parse an alternate string,
665 * which looks like this:
666 * /(?:\x{DF}|[abc\x{DF}def])/ui
667 * where it uses the input unchanged in the middle of something it constructs,
668 * which is a branch for the DF outside the character class, and clustering
669 * parens around the whole thing. (It knows enough to skip the DF inside the
670 * class while in this substitute parse.) 'abc' and 'def' may have errors that
671 * need to be reported. The general situation looks like this:
672 *
673 * |<------- identical ------>|
674 * sI tI xI eI
675 * Input: ---------------------------------------------------------------
676 * Constructed: ---------------------------------------------------
677 * sC tC xC eC EC
678 * |<------- identical ------>|
679 *
680 * sI..eI is the portion of the input pattern we are concerned with here.
681 * sC..EC is the constructed substitute parse string.
682 * sC..tC is constructed by us
683 * tC..eC is an exact duplicate of the portion of the input pattern tI..eI.
684 * In the diagram, these are vertically aligned.
685 * eC..EC is also constructed by us.
686 * xC is the position in the substitute parse string where we found a
687 * problem.
688 * xI is the position in the original pattern corresponding to xC.
689 *
690 * We want to display a message showing the real input string. Thus we need to
691 * translate from xC to xI. We know that xC >= tC, since the portion of the
692 * string sC..tC has been constructed by us, and so shouldn't have errors. We
693 * get:
694 * xI = tI + (xC - tC)
695 *
696 * When the substitute parse is constructed, the code needs to set:
697 * RExC_start (sC)
698 * RExC_end (eC)
699 * RExC_copy_start_in_input (tI)
700 * RExC_copy_start_in_constructed (tC)
701 * and restore them when done.
702 *
703 * During normal processing of the input pattern, both
704 * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to
705 * sI, so that xC equals xI.
706 */
707
708#define sI RExC_precomp
709#define eI RExC_precomp_end
710#define sC RExC_start
711#define eC RExC_end
712#define tI RExC_copy_start_in_input
713#define tC RExC_copy_start_in_constructed
714#define xI(xC) (tI + (xC - tC))
715#define xI_offset(xC) (xI(xC) - sI)
716
717#define REPORT_LOCATION_ARGS(xC) \
718 UTF8fARG(UTF, \
719 (xI(xC) > eI) /* Don't run off end */ \
720 ? eI - sI /* Length before the <--HERE */ \
721 : ((xI_offset(xC) >= 0) \
722 ? xI_offset(xC) \
723 : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %" \
724 IVdf " trying to output message for " \
725 " pattern %.*s", \
726 __FILE__, __LINE__, (IV) xI_offset(xC), \
727 ((int) (eC - sC)), sC), 0)), \
728 sI), /* The input pattern printed up to the <--HERE */ \
729 UTF8fARG(UTF, \
730 (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */ \
731 (xI(xC) > eI) ? eI : xI(xC)) /* pattern after <--HERE */
732
733/* Used to point after bad bytes for an error message, but avoid skipping
734 * past a nul byte. */
735#define SKIP_IF_CHAR(s, e) (!*(s) ? 0 : UTF ? UTF8_SAFE_SKIP(s, e) : 1)
736
737/* Set up to clean up after our imminent demise */
738#define PREPARE_TO_DIE \
739 STMT_START { \
740 if (RExC_rx_sv) \
741 SAVEFREESV(RExC_rx_sv); \
742 if (RExC_open_parens) \
743 SAVEFREEPV(RExC_open_parens); \
744 if (RExC_close_parens) \
745 SAVEFREEPV(RExC_close_parens); \
746 } STMT_END
747
748/*
749 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
750 * arg. Show regex, up to a maximum length. If it's too long, chop and add
751 * "...".
752 */
753#define _FAIL(code) STMT_START { \
754 const char *ellipses = ""; \
755 IV len = RExC_precomp_end - RExC_precomp; \
756 \
757 PREPARE_TO_DIE; \
758 if (len > RegexLengthToShowInErrorMessages) { \
759 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
760 len = RegexLengthToShowInErrorMessages - 10; \
761 ellipses = "..."; \
762 } \
763 code; \
764} STMT_END
765
766#define FAIL(msg) _FAIL( \
767 Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/", \
768 msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
769
770#define FAIL2(msg,arg) _FAIL( \
771 Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \
772 arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
773
774#define FAIL3(msg,arg1,arg2) _FAIL( \
775 Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \
776 arg1, arg2, UTF8fARG(UTF, len, RExC_precomp), ellipses))
777
778/*
779 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
780 */
781#define Simple_vFAIL(m) STMT_START { \
782 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
783 m, REPORT_LOCATION_ARGS(RExC_parse)); \
784} STMT_END
785
786/*
787 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
788 */
789#define vFAIL(m) STMT_START { \
790 PREPARE_TO_DIE; \
791 Simple_vFAIL(m); \
792} STMT_END
793
794/*
795 * Like Simple_vFAIL(), but accepts two arguments.
796 */
797#define Simple_vFAIL2(m,a1) STMT_START { \
798 S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, \
799 REPORT_LOCATION_ARGS(RExC_parse)); \
800} STMT_END
801
802/*
803 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
804 */
805#define vFAIL2(m,a1) STMT_START { \
806 PREPARE_TO_DIE; \
807 Simple_vFAIL2(m, a1); \
808} STMT_END
809
810
811/*
812 * Like Simple_vFAIL(), but accepts three arguments.
813 */
814#define Simple_vFAIL3(m, a1, a2) STMT_START { \
815 S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, a2, \
816 REPORT_LOCATION_ARGS(RExC_parse)); \
817} STMT_END
818
819/*
820 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
821 */
822#define vFAIL3(m,a1,a2) STMT_START { \
823 PREPARE_TO_DIE; \
824 Simple_vFAIL3(m, a1, a2); \
825} STMT_END
826
827/*
828 * Like Simple_vFAIL(), but accepts four arguments.
829 */
830#define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
831 S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, a2, a3, \
832 REPORT_LOCATION_ARGS(RExC_parse)); \
833} STMT_END
834
835#define vFAIL4(m,a1,a2,a3) STMT_START { \
836 PREPARE_TO_DIE; \
837 Simple_vFAIL4(m, a1, a2, a3); \
838} STMT_END
839
840/* A specialized version of vFAIL2 that works with UTF8f */
841#define vFAIL2utf8f(m, a1) STMT_START { \
842 PREPARE_TO_DIE; \
843 S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, \
844 REPORT_LOCATION_ARGS(RExC_parse)); \
845} STMT_END
846
847#define vFAIL3utf8f(m, a1, a2) STMT_START { \
848 PREPARE_TO_DIE; \
849 S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, a2, \
850 REPORT_LOCATION_ARGS(RExC_parse)); \
851} STMT_END
852
853/* Setting this to NULL is a signal to not output warnings */
854#define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE \
855 STMT_START { \
856 RExC_save_copy_start_in_constructed = RExC_copy_start_in_constructed;\
857 RExC_copy_start_in_constructed = NULL; \
858 } STMT_END
859#define RESTORE_WARNINGS \
860 RExC_copy_start_in_constructed = RExC_save_copy_start_in_constructed
861
862/* Since a warning can be generated multiple times as the input is reparsed, we
863 * output it the first time we come to that point in the parse, but suppress it
864 * otherwise. 'RExC_copy_start_in_constructed' being NULL is a flag to not
865 * generate any warnings */
866#define TO_OUTPUT_WARNINGS(loc) \
867 ( RExC_copy_start_in_constructed \
868 && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset)
869
870/* After we've emitted a warning, we save the position in the input so we don't
871 * output it again */
872#define UPDATE_WARNINGS_LOC(loc) \
873 STMT_START { \
874 if (TO_OUTPUT_WARNINGS(loc)) { \
875 RExC_latest_warn_offset = MAX(sI, MIN(eI, xI(loc))) \
876 - RExC_precomp; \
877 } \
878 } STMT_END
879
880/* 'warns' is the output of the packWARNx macro used in 'code' */
881#define _WARN_HELPER(loc, warns, code) \
882 STMT_START { \
883 if (! RExC_copy_start_in_constructed) { \
884 Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none" \
885 " expected at '%s'", \
886 __FILE__, __LINE__, loc); \
887 } \
888 if (TO_OUTPUT_WARNINGS(loc)) { \
889 if (ckDEAD(warns)) \
890 PREPARE_TO_DIE; \
891 code; \
892 UPDATE_WARNINGS_LOC(loc); \
893 } \
894 } STMT_END
895
896/* m is not necessarily a "literal string", in this macro */
897#define warn_non_literal_string(loc, packed_warn, m) \
898 _WARN_HELPER(loc, packed_warn, \
899 Perl_warner(aTHX_ packed_warn, \
900 "%s" REPORT_LOCATION, \
901 m, REPORT_LOCATION_ARGS(loc)))
902#define reg_warn_non_literal_string(loc, m) \
903 warn_non_literal_string(loc, packWARN(WARN_REGEXP), m)
904
905#define ckWARN2_non_literal_string(loc, packwarn, m, a1) \
906 STMT_START { \
907 char * format; \
908 Size_t format_size = strlen(m) + strlen(REPORT_LOCATION)+ 1;\
909 Newx(format, format_size, char); \
910 my_strlcpy(format, m, format_size); \
911 my_strlcat(format, REPORT_LOCATION, format_size); \
912 SAVEFREEPV(format); \
913 _WARN_HELPER(loc, packwarn, \
914 Perl_ck_warner(aTHX_ packwarn, \
915 format, \
916 a1, REPORT_LOCATION_ARGS(loc))); \
917 } STMT_END
918
919#define ckWARNreg(loc,m) \
920 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
921 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
922 m REPORT_LOCATION, \
923 REPORT_LOCATION_ARGS(loc)))
924
925#define vWARN(loc, m) \
926 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
927 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
928 m REPORT_LOCATION, \
929 REPORT_LOCATION_ARGS(loc))) \
930
931#define vWARN_dep(loc, m) \
932 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
933 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), \
934 m REPORT_LOCATION, \
935 REPORT_LOCATION_ARGS(loc)))
936
937#define ckWARNdep(loc,m) \
938 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
939 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
940 m REPORT_LOCATION, \
941 REPORT_LOCATION_ARGS(loc)))
942
943#define ckWARNregdep(loc,m) \
944 _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
945 Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, \
946 WARN_REGEXP), \
947 m REPORT_LOCATION, \
948 REPORT_LOCATION_ARGS(loc)))
949
950#define ckWARN2reg_d(loc,m, a1) \
951 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
952 Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP), \
953 m REPORT_LOCATION, \
954 a1, REPORT_LOCATION_ARGS(loc)))
955
956#define ckWARN2reg(loc, m, a1) \
957 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
958 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
959 m REPORT_LOCATION, \
960 a1, REPORT_LOCATION_ARGS(loc)))
961
962#define vWARN3(loc, m, a1, a2) \
963 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
964 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
965 m REPORT_LOCATION, \
966 a1, a2, REPORT_LOCATION_ARGS(loc)))
967
968#define ckWARN3reg(loc, m, a1, a2) \
969 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
970 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
971 m REPORT_LOCATION, \
972 a1, a2, \
973 REPORT_LOCATION_ARGS(loc)))
974
975#define vWARN4(loc, m, a1, a2, a3) \
976 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
977 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
978 m REPORT_LOCATION, \
979 a1, a2, a3, \
980 REPORT_LOCATION_ARGS(loc)))
981
982#define ckWARN4reg(loc, m, a1, a2, a3) \
983 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
984 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
985 m REPORT_LOCATION, \
986 a1, a2, a3, \
987 REPORT_LOCATION_ARGS(loc)))
988
989#define vWARN5(loc, m, a1, a2, a3, a4) \
990 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
991 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
992 m REPORT_LOCATION, \
993 a1, a2, a3, a4, \
994 REPORT_LOCATION_ARGS(loc)))
995
996#define ckWARNexperimental(loc, class, m) \
997 STMT_START { \
998 if (! RExC_warned_ ## class) { /* warn once per compilation */ \
999 RExC_warned_ ## class = 1; \
1000 _WARN_HELPER(loc, packWARN(class), \
1001 Perl_ck_warner_d(aTHX_ packWARN(class), \
1002 m REPORT_LOCATION, \
1003 REPORT_LOCATION_ARGS(loc)));\
1004 } \
1005 } STMT_END
1006
1007/* Convert between a pointer to a node and its offset from the beginning of the
1008 * program */
1009#define REGNODE_p(offset) (RExC_emit_start + (offset))
1010#define REGNODE_OFFSET(node) ((node) - RExC_emit_start)
1011
1012/* Macros for recording node offsets. 20001227 mjd@plover.com
1013 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
1014 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
1015 * Element 0 holds the number n.
1016 * Position is 1 indexed.
1017 */
1018#ifndef RE_TRACK_PATTERN_OFFSETS
1019#define Set_Node_Offset_To_R(offset,byte)
1020#define Set_Node_Offset(node,byte)
1021#define Set_Cur_Node_Offset
1022#define Set_Node_Length_To_R(node,len)
1023#define Set_Node_Length(node,len)
1024#define Set_Node_Cur_Length(node,start)
1025#define Node_Offset(n)
1026#define Node_Length(n)
1027#define Set_Node_Offset_Length(node,offset,len)
1028#define ProgLen(ri) ri->u.proglen
1029#define SetProgLen(ri,x) ri->u.proglen = x
1030#define Track_Code(code)
1031#else
1032#define ProgLen(ri) ri->u.offsets[0]
1033#define SetProgLen(ri,x) ri->u.offsets[0] = x
1034#define Set_Node_Offset_To_R(offset,byte) STMT_START { \
1035 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
1036 __LINE__, (int)(offset), (int)(byte))); \
1037 if((offset) < 0) { \
1038 Perl_croak(aTHX_ "value of node is %d in Offset macro", \
1039 (int)(offset)); \
1040 } else { \
1041 RExC_offsets[2*(offset)-1] = (byte); \
1042 } \
1043} STMT_END
1044
1045#define Set_Node_Offset(node,byte) \
1046 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start)
1047#define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
1048
1049#define Set_Node_Length_To_R(node,len) STMT_START { \
1050 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
1051 __LINE__, (int)(node), (int)(len))); \
1052 if((node) < 0) { \
1053 Perl_croak(aTHX_ "value of node is %d in Length macro", \
1054 (int)(node)); \
1055 } else { \
1056 RExC_offsets[2*(node)] = (len); \
1057 } \
1058} STMT_END
1059
1060#define Set_Node_Length(node,len) \
1061 Set_Node_Length_To_R(REGNODE_OFFSET(node), len)
1062#define Set_Node_Cur_Length(node, start) \
1063 Set_Node_Length(node, RExC_parse - start)
1064
1065/* Get offsets and lengths */
1066#define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1])
1067#define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))])
1068
1069#define Set_Node_Offset_Length(node,offset,len) STMT_START { \
1070 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset)); \
1071 Set_Node_Length_To_R(REGNODE_OFFSET(node), (len)); \
1072} STMT_END
1073
1074#define Track_Code(code) STMT_START { code } STMT_END
1075#endif
1076
1077#if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
1078#define EXPERIMENTAL_INPLACESCAN
1079#endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
1080
1081#ifdef DEBUGGING
1082int
1083Perl_re_printf(pTHX_ const char *fmt, ...)
1084{
1085 va_list ap;
1086 int result;
1087 PerlIO *f= Perl_debug_log;
1088 PERL_ARGS_ASSERT_RE_PRINTF;
1089 va_start(ap, fmt);
1090 result = PerlIO_vprintf(f, fmt, ap);
1091 va_end(ap);
1092 return result;
1093}
1094
1095int
1096Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
1097{
1098 va_list ap;
1099 int result;
1100 PerlIO *f= Perl_debug_log;
1101 PERL_ARGS_ASSERT_RE_INDENTF;
1102 va_start(ap, depth);
1103 PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
1104 result = PerlIO_vprintf(f, fmt, ap);
1105 va_end(ap);
1106 return result;
1107}
1108#endif /* DEBUGGING */
1109
1110#define DEBUG_RExC_seen() \
1111 DEBUG_OPTIMISE_MORE_r({ \
1112 Perl_re_printf( aTHX_ "RExC_seen: "); \
1113 \
1114 if (RExC_seen & REG_ZERO_LEN_SEEN) \
1115 Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN "); \
1116 \
1117 if (RExC_seen & REG_LOOKBEHIND_SEEN) \
1118 Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN "); \
1119 \
1120 if (RExC_seen & REG_GPOS_SEEN) \
1121 Perl_re_printf( aTHX_ "REG_GPOS_SEEN "); \
1122 \
1123 if (RExC_seen & REG_RECURSE_SEEN) \
1124 Perl_re_printf( aTHX_ "REG_RECURSE_SEEN "); \
1125 \
1126 if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN) \
1127 Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN "); \
1128 \
1129 if (RExC_seen & REG_VERBARG_SEEN) \
1130 Perl_re_printf( aTHX_ "REG_VERBARG_SEEN "); \
1131 \
1132 if (RExC_seen & REG_CUTGROUP_SEEN) \
1133 Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN "); \
1134 \
1135 if (RExC_seen & REG_RUN_ON_COMMENT_SEEN) \
1136 Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN "); \
1137 \
1138 if (RExC_seen & REG_UNFOLDED_MULTI_SEEN) \
1139 Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN "); \
1140 \
1141 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) \
1142 Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN "); \
1143 \
1144 Perl_re_printf( aTHX_ "\n"); \
1145 });
1146
1147#define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
1148 if ((flags) & flag) Perl_re_printf( aTHX_ "%s ", #flag)
1149
1150
1151#ifdef DEBUGGING
1152static void
1153S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
1154 const char *close_str)
1155{
1156 if (!flags)
1157 return;
1158
1159 Perl_re_printf( aTHX_ "%s", open_str);
1160 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
1161 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
1162 DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
1163 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
1164 DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
1165 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
1166 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
1167 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
1168 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
1169 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
1170 DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
1171 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
1172 DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
1173 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
1174 DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
1175 Perl_re_printf( aTHX_ "%s", close_str);
1176}
1177
1178
1179static void
1180S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
1181 U32 depth, int is_inf)
1182{
1183 GET_RE_DEBUG_FLAGS_DECL;
1184
1185 DEBUG_OPTIMISE_MORE_r({
1186 if (!data)
1187 return;
1188 Perl_re_indentf(aTHX_ "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
1189 depth,
1190 where,
1191 (IV)data->pos_min,
1192 (IV)data->pos_delta,
1193 (UV)data->flags
1194 );
1195
1196 S_debug_show_study_flags(aTHX_ data->flags," [","]");
1197
1198 Perl_re_printf( aTHX_
1199 " Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
1200 (IV)data->whilem_c,
1201 (IV)(data->last_closep ? *((data)->last_closep) : -1),
1202 is_inf ? "INF " : ""
1203 );
1204
1205 if (data->last_found) {
1206 int i;
1207 Perl_re_printf(aTHX_
1208 "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
1209 SvPVX_const(data->last_found),
1210 (IV)data->last_end,
1211 (IV)data->last_start_min,
1212 (IV)data->last_start_max
1213 );
1214
1215 for (i = 0; i < 2; i++) {
1216 Perl_re_printf(aTHX_
1217 " %s%s: '%s' @ %" IVdf "/%" IVdf,
1218 data->cur_is_floating == i ? "*" : "",
1219 i ? "Float" : "Fixed",
1220 SvPVX_const(data->substrs[i].str),
1221 (IV)data->substrs[i].min_offset,
1222 (IV)data->substrs[i].max_offset
1223 );
1224 S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
1225 }
1226 }
1227
1228 Perl_re_printf( aTHX_ "\n");
1229 });
1230}
1231
1232
1233static void
1234S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
1235 regnode *scan, U32 depth, U32 flags)
1236{
1237 GET_RE_DEBUG_FLAGS_DECL;
1238
1239 DEBUG_OPTIMISE_r({
1240 regnode *Next;
1241
1242 if (!scan)
1243 return;
1244 Next = regnext(scan);
1245 regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
1246 Perl_re_indentf( aTHX_ "%s>%3d: %s (%d)",
1247 depth,
1248 str,
1249 REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
1250 Next ? (REG_NODE_NUM(Next)) : 0 );
1251 S_debug_show_study_flags(aTHX_ flags," [ ","]");
1252 Perl_re_printf( aTHX_ "\n");
1253 });
1254}
1255
1256
1257# define DEBUG_STUDYDATA(where, data, depth, is_inf) \
1258 S_debug_studydata(aTHX_ where, data, depth, is_inf)
1259
1260# define DEBUG_PEEP(str, scan, depth, flags) \
1261 S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
1262
1263#else
1264# define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
1265# define DEBUG_PEEP(str, scan, depth, flags) NOOP
1266#endif
1267
1268
1269/* =========================================================
1270 * BEGIN edit_distance stuff.
1271 *
1272 * This calculates how many single character changes of any type are needed to
1273 * transform a string into another one. It is taken from version 3.1 of
1274 *
1275 * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1276 */
1277
1278/* Our unsorted dictionary linked list. */
1279/* Note we use UVs, not chars. */
1280
1281struct dictionary{
1282 UV key;
1283 UV value;
1284 struct dictionary* next;
1285};
1286typedef struct dictionary item;
1287
1288
1289PERL_STATIC_INLINE item*
1290push(UV key, item* curr)
1291{
1292 item* head;
1293 Newx(head, 1, item);
1294 head->key = key;
1295 head->value = 0;
1296 head->next = curr;
1297 return head;
1298}
1299
1300
1301PERL_STATIC_INLINE item*
1302find(item* head, UV key)
1303{
1304 item* iterator = head;
1305 while (iterator){
1306 if (iterator->key == key){
1307 return iterator;
1308 }
1309 iterator = iterator->next;
1310 }
1311
1312 return NULL;
1313}
1314
1315PERL_STATIC_INLINE item*
1316uniquePush(item* head, UV key)
1317{
1318 item* iterator = head;
1319
1320 while (iterator){
1321 if (iterator->key == key) {
1322 return head;
1323 }
1324 iterator = iterator->next;
1325 }
1326
1327 return push(key, head);
1328}
1329
1330PERL_STATIC_INLINE void
1331dict_free(item* head)
1332{
1333 item* iterator = head;
1334
1335 while (iterator) {
1336 item* temp = iterator;
1337 iterator = iterator->next;
1338 Safefree(temp);
1339 }
1340
1341 head = NULL;
1342}
1343
1344/* End of Dictionary Stuff */
1345
1346/* All calculations/work are done here */
1347STATIC int
1348S_edit_distance(const UV* src,
1349 const UV* tgt,
1350 const STRLEN x, /* length of src[] */
1351 const STRLEN y, /* length of tgt[] */
1352 const SSize_t maxDistance
1353)
1354{
1355 item *head = NULL;
1356 UV swapCount, swapScore, targetCharCount, i, j;
1357 UV *scores;
1358 UV score_ceil = x + y;
1359
1360 PERL_ARGS_ASSERT_EDIT_DISTANCE;
1361
1362 /* intialize matrix start values */
1363 Newx(scores, ( (x + 2) * (y + 2)), UV);
1364 scores[0] = score_ceil;
1365 scores[1 * (y + 2) + 0] = score_ceil;
1366 scores[0 * (y + 2) + 1] = score_ceil;
1367 scores[1 * (y + 2) + 1] = 0;
1368 head = uniquePush(uniquePush(head, src[0]), tgt[0]);
1369
1370 /* work loops */
1371 /* i = src index */
1372 /* j = tgt index */
1373 for (i=1;i<=x;i++) {
1374 if (i < x)
1375 head = uniquePush(head, src[i]);
1376 scores[(i+1) * (y + 2) + 1] = i;
1377 scores[(i+1) * (y + 2) + 0] = score_ceil;
1378 swapCount = 0;
1379
1380 for (j=1;j<=y;j++) {
1381 if (i == 1) {
1382 if(j < y)
1383 head = uniquePush(head, tgt[j]);
1384 scores[1 * (y + 2) + (j + 1)] = j;
1385 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1386 }
1387
1388 targetCharCount = find(head, tgt[j-1])->value;
1389 swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1390
1391 if (src[i-1] != tgt[j-1]){
1392 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));
1393 }
1394 else {
1395 swapCount = j;
1396 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1397 }
1398 }
1399
1400 find(head, src[i-1])->value = i;
1401 }
1402
1403 {
1404 IV score = scores[(x+1) * (y + 2) + (y + 1)];
1405 dict_free(head);
1406 Safefree(scores);
1407 return (maxDistance != 0 && maxDistance < score)?(-1):score;
1408 }
1409}
1410
1411/* END of edit_distance() stuff
1412 * ========================================================= */
1413
1414/* Mark that we cannot extend a found fixed substring at this point.
1415 Update the longest found anchored substring or the longest found
1416 floating substrings if needed. */
1417
1418STATIC void
1419S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1420 SSize_t *minlenp, int is_inf)
1421{
1422 const STRLEN l = CHR_SVLEN(data->last_found);
1423 SV * const longest_sv = data->substrs[data->cur_is_floating].str;
1424 const STRLEN old_l = CHR_SVLEN(longest_sv);
1425 GET_RE_DEBUG_FLAGS_DECL;
1426
1427 PERL_ARGS_ASSERT_SCAN_COMMIT;
1428
1429 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1430 const U8 i = data->cur_is_floating;
1431 SvSetMagicSV(longest_sv, data->last_found);
1432 data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
1433
1434 if (!i) /* fixed */
1435 data->substrs[0].max_offset = data->substrs[0].min_offset;
1436 else { /* float */
1437 data->substrs[1].max_offset = (l
1438 ? data->last_start_max
1439 : (data->pos_delta > OPTIMIZE_INFTY - data->pos_min
1440 ? OPTIMIZE_INFTY
1441 : data->pos_min + data->pos_delta));
1442 if (is_inf
1443 || (STRLEN)data->substrs[1].max_offset > (STRLEN)OPTIMIZE_INFTY)
1444 data->substrs[1].max_offset = OPTIMIZE_INFTY;
1445 }
1446
1447 if (data->flags & SF_BEFORE_EOL)
1448 data->substrs[i].flags |= (data->flags & SF_BEFORE_EOL);
1449 else
1450 data->substrs[i].flags &= ~SF_BEFORE_EOL;
1451 data->substrs[i].minlenp = minlenp;
1452 data->substrs[i].lookbehind = 0;
1453 }
1454
1455 SvCUR_set(data->last_found, 0);
1456 {
1457 SV * const sv = data->last_found;
1458 if (SvUTF8(sv) && SvMAGICAL(sv)) {
1459 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1460 if (mg)
1461 mg->mg_len = 0;
1462 }
1463 }
1464 data->last_end = -1;
1465 data->flags &= ~SF_BEFORE_EOL;
1466 DEBUG_STUDYDATA("commit", data, 0, is_inf);
1467}
1468
1469/* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1470 * list that describes which code points it matches */
1471
1472STATIC void
1473S_ssc_anything(pTHX_ regnode_ssc *ssc)
1474{
1475 /* Set the SSC 'ssc' to match an empty string or any code point */
1476
1477 PERL_ARGS_ASSERT_SSC_ANYTHING;
1478
1479 assert(is_ANYOF_SYNTHETIC(ssc));
1480
1481 /* mortalize so won't leak */
1482 ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
1483 ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING; /* Plus matches empty */
1484}
1485
1486STATIC int
1487S_ssc_is_anything(const regnode_ssc *ssc)
1488{
1489 /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1490 * point; FALSE otherwise. Thus, this is used to see if using 'ssc' buys
1491 * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1492 * in any way, so there's no point in using it */
1493
1494 UV start, end;
1495 bool ret;
1496
1497 PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1498
1499 assert(is_ANYOF_SYNTHETIC(ssc));
1500
1501 if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1502 return FALSE;
1503 }
1504
1505 /* See if the list consists solely of the range 0 - Infinity */
1506 invlist_iterinit(ssc->invlist);
1507 ret = invlist_iternext(ssc->invlist, &start, &end)
1508 && start == 0
1509 && end == UV_MAX;
1510
1511 invlist_iterfinish(ssc->invlist);
1512
1513 if (ret) {
1514 return TRUE;
1515 }
1516
1517 /* If e.g., both \w and \W are set, matches everything */
1518 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1519 int i;
1520 for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1521 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1522 return TRUE;
1523 }
1524 }
1525 }
1526
1527 return FALSE;
1528}
1529
1530STATIC void
1531S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1532{
1533 /* Initializes the SSC 'ssc'. This includes setting it to match an empty
1534 * string, any code point, or any posix class under locale */
1535
1536 PERL_ARGS_ASSERT_SSC_INIT;
1537
1538 Zero(ssc, 1, regnode_ssc);
1539 set_ANYOF_SYNTHETIC(ssc);
1540 ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1541 ssc_anything(ssc);
1542
1543 /* If any portion of the regex is to operate under locale rules that aren't
1544 * fully known at compile time, initialization includes it. The reason
1545 * this isn't done for all regexes is that the optimizer was written under
1546 * the assumption that locale was all-or-nothing. Given the complexity and
1547 * lack of documentation in the optimizer, and that there are inadequate
1548 * test cases for locale, many parts of it may not work properly, it is
1549 * safest to avoid locale unless necessary. */
1550 if (RExC_contains_locale) {
1551 ANYOF_POSIXL_SETALL(ssc);
1552 }
1553 else {
1554 ANYOF_POSIXL_ZERO(ssc);
1555 }
1556}
1557
1558STATIC int
1559S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1560 const regnode_ssc *ssc)
1561{
1562 /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1563 * to the list of code points matched, and locale posix classes; hence does
1564 * not check its flags) */
1565
1566 UV start, end;
1567 bool ret;
1568
1569 PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1570
1571 assert(is_ANYOF_SYNTHETIC(ssc));
1572
1573 invlist_iterinit(ssc->invlist);
1574 ret = invlist_iternext(ssc->invlist, &start, &end)
1575 && start == 0
1576 && end == UV_MAX;
1577
1578 invlist_iterfinish(ssc->invlist);
1579
1580 if (! ret) {
1581 return FALSE;
1582 }
1583
1584 if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1585 return FALSE;
1586 }
1587
1588 return TRUE;
1589}
1590
1591#define INVLIST_INDEX 0
1592#define ONLY_LOCALE_MATCHES_INDEX 1
1593#define DEFERRED_USER_DEFINED_INDEX 2
1594
1595STATIC SV*
1596S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1597 const regnode_charclass* const node)
1598{
1599 /* Returns a mortal inversion list defining which code points are matched
1600 * by 'node', which is of type ANYOF. Handles complementing the result if
1601 * appropriate. If some code points aren't knowable at this time, the
1602 * returned list must, and will, contain every code point that is a
1603 * possibility. */
1604
1605 dVAR;
1606 SV* invlist = NULL;
1607 SV* only_utf8_locale_invlist = NULL;
1608 unsigned int i;
1609 const U32 n = ARG(node);
1610 bool new_node_has_latin1 = FALSE;
1611 const U8 flags = (inRANGE(OP(node), ANYOFH, ANYOFRb))
1612 ? 0
1613 : ANYOF_FLAGS(node);
1614
1615 PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1616
1617 /* Look at the data structure created by S_set_ANYOF_arg() */
1618 if (n != ANYOF_ONLY_HAS_BITMAP) {
1619 SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1620 AV * const av = MUTABLE_AV(SvRV(rv));
1621 SV **const ary = AvARRAY(av);
1622 assert(RExC_rxi->data->what[n] == 's');
1623
1624 if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
1625
1626 /* Here there are things that won't be known until runtime -- we
1627 * have to assume it could be anything */
1628 invlist = sv_2mortal(_new_invlist(1));
1629 return _add_range_to_invlist(invlist, 0, UV_MAX);
1630 }
1631 else if (ary[INVLIST_INDEX]) {
1632
1633 /* Use the node's inversion list */
1634 invlist = sv_2mortal(invlist_clone(ary[INVLIST_INDEX], NULL));
1635 }
1636
1637 /* Get the code points valid only under UTF-8 locales */
1638 if ( (flags & ANYOFL_FOLD)
1639 && av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX)
1640 {
1641 only_utf8_locale_invlist = ary[ONLY_LOCALE_MATCHES_INDEX];
1642 }
1643 }
1644
1645 if (! invlist) {
1646 invlist = sv_2mortal(_new_invlist(0));
1647 }
1648
1649 /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1650 * code points, and an inversion list for the others, but if there are code
1651 * points that should match only conditionally on the target string being
1652 * UTF-8, those are placed in the inversion list, and not the bitmap.
1653 * Since there are circumstances under which they could match, they are
1654 * included in the SSC. But if the ANYOF node is to be inverted, we have
1655 * to exclude them here, so that when we invert below, the end result
1656 * actually does include them. (Think about "\xe0" =~ /[^\xc0]/di;). We
1657 * have to do this here before we add the unconditionally matched code
1658 * points */
1659 if (flags & ANYOF_INVERT) {
1660 _invlist_intersection_complement_2nd(invlist,
1661 PL_UpperLatin1,
1662 &invlist);
1663 }
1664
1665 /* Add in the points from the bit map */
1666 if (! inRANGE(OP(node), ANYOFH, ANYOFRb)) {
1667 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1668 if (ANYOF_BITMAP_TEST(node, i)) {
1669 unsigned int start = i++;
1670
1671 for (; i < NUM_ANYOF_CODE_POINTS
1672 && ANYOF_BITMAP_TEST(node, i); ++i)
1673 {
1674 /* empty */
1675 }
1676 invlist = _add_range_to_invlist(invlist, start, i-1);
1677 new_node_has_latin1 = TRUE;
1678 }
1679 }
1680 }
1681
1682 /* If this can match all upper Latin1 code points, have to add them
1683 * as well. But don't add them if inverting, as when that gets done below,
1684 * it would exclude all these characters, including the ones it shouldn't
1685 * that were added just above */
1686 if (! (flags & ANYOF_INVERT) && OP(node) == ANYOFD
1687 && (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1688 {
1689 _invlist_union(invlist, PL_UpperLatin1, &invlist);
1690 }
1691
1692 /* Similarly for these */
1693 if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1694 _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1695 }
1696
1697 if (flags & ANYOF_INVERT) {
1698 _invlist_invert(invlist);
1699 }
1700 else if (flags & ANYOFL_FOLD) {
1701 if (new_node_has_latin1) {
1702
1703 /* Under /li, any 0-255 could fold to any other 0-255, depending on
1704 * the locale. We can skip this if there are no 0-255 at all. */
1705 _invlist_union(invlist, PL_Latin1, &invlist);
1706
1707 invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I);
1708 invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
1709 }
1710 else {
1711 if (_invlist_contains_cp(invlist, LATIN_SMALL_LETTER_DOTLESS_I)) {
1712 invlist = add_cp_to_invlist(invlist, 'I');
1713 }
1714 if (_invlist_contains_cp(invlist,
1715 LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE))
1716 {
1717 invlist = add_cp_to_invlist(invlist, 'i');
1718 }
1719 }
1720 }
1721
1722 /* Similarly add the UTF-8 locale possible matches. These have to be
1723 * deferred until after the non-UTF-8 locale ones are taken care of just
1724 * above, or it leads to wrong results under ANYOF_INVERT */
1725 if (only_utf8_locale_invlist) {
1726 _invlist_union_maybe_complement_2nd(invlist,
1727 only_utf8_locale_invlist,
1728 flags & ANYOF_INVERT,
1729 &invlist);
1730 }
1731
1732 return invlist;
1733}
1734
1735/* These two functions currently do the exact same thing */
1736#define ssc_init_zero ssc_init
1737
1738#define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp))
1739#define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1740
1741/* 'AND' a given class with another one. Can create false positives. 'ssc'
1742 * should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1743 * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1744
1745STATIC void
1746S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1747 const regnode_charclass *and_with)
1748{
1749 /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1750 * another SSC or a regular ANYOF class. Can create false positives. */
1751
1752 SV* anded_cp_list;
1753 U8 and_with_flags = inRANGE(OP(and_with), ANYOFH, ANYOFRb)
1754 ? 0
1755 : ANYOF_FLAGS(and_with);
1756 U8 anded_flags;
1757
1758 PERL_ARGS_ASSERT_SSC_AND;
1759
1760 assert(is_ANYOF_SYNTHETIC(ssc));
1761
1762 /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1763 * the code point inversion list and just the relevant flags */
1764 if (is_ANYOF_SYNTHETIC(and_with)) {
1765 anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1766 anded_flags = and_with_flags;
1767
1768 /* XXX This is a kludge around what appears to be deficiencies in the
1769 * optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag,
1770 * there are paths through the optimizer where it doesn't get weeded
1771 * out when it should. And if we don't make some extra provision for
1772 * it like the code just below, it doesn't get added when it should.
1773 * This solution is to add it only when AND'ing, which is here, and
1774 * only when what is being AND'ed is the pristine, original node
1775 * matching anything. Thus it is like adding it to ssc_anything() but
1776 * only when the result is to be AND'ed. Probably the same solution
1777 * could be adopted for the same problem we have with /l matching,
1778 * which is solved differently in S_ssc_init(), and that would lead to
1779 * fewer false positives than that solution has. But if this solution
1780 * creates bugs, the consequences are only that a warning isn't raised
1781 * that should be; while the consequences for having /l bugs is
1782 * incorrect matches */
1783 if (ssc_is_anything((regnode_ssc *)and_with)) {
1784 anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1785 }
1786 }
1787 else {
1788 anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1789 if (OP(and_with) == ANYOFD) {
1790 anded_flags = and_with_flags & ANYOF_COMMON_FLAGS;
1791 }
1792 else {
1793 anded_flags = and_with_flags
1794 &( ANYOF_COMMON_FLAGS
1795 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1796 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1797 if (ANYOFL_UTF8_LOCALE_REQD(and_with_flags)) {
1798 anded_flags &=
1799 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1800 }
1801 }
1802 }
1803
1804 ANYOF_FLAGS(ssc) &= anded_flags;
1805
1806 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1807 * C2 is the list of code points in 'and-with'; P2, its posix classes.
1808 * 'and_with' may be inverted. When not inverted, we have the situation of
1809 * computing:
1810 * (C1 | P1) & (C2 | P2)
1811 * = (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1812 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1813 * <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2))
1814 * <= ((C1 & C2) | P1 | P2)
1815 * Alternatively, the last few steps could be:
1816 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1817 * <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2))
1818 * <= (C1 | C2 | (P1 & P2))
1819 * We favor the second approach if either P1 or P2 is non-empty. This is
1820 * because these components are a barrier to doing optimizations, as what
1821 * they match cannot be known until the moment of matching as they are
1822 * dependent on the current locale, 'AND"ing them likely will reduce or
1823 * eliminate them.
1824 * But we can do better if we know that C1,P1 are in their initial state (a
1825 * frequent occurrence), each matching everything:
1826 * (<everything>) & (C2 | P2) = C2 | P2
1827 * Similarly, if C2,P2 are in their initial state (again a frequent
1828 * occurrence), the result is a no-op
1829 * (C1 | P1) & (<everything>) = C1 | P1
1830 *
1831 * Inverted, we have
1832 * (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2)
1833 * = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1834 * <= (C1 & ~C2) | (P1 & ~P2)
1835 * */
1836
1837 if ((and_with_flags & ANYOF_INVERT)
1838 && ! is_ANYOF_SYNTHETIC(and_with))
1839 {
1840 unsigned int i;
1841
1842 ssc_intersection(ssc,
1843 anded_cp_list,
1844 FALSE /* Has already been inverted */
1845 );
1846
1847 /* If either P1 or P2 is empty, the intersection will be also; can skip
1848 * the loop */
1849 if (! (and_with_flags & ANYOF_MATCHES_POSIXL)) {
1850 ANYOF_POSIXL_ZERO(ssc);
1851 }
1852 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1853
1854 /* Note that the Posix class component P from 'and_with' actually
1855 * looks like:
1856 * P = Pa | Pb | ... | Pn
1857 * where each component is one posix class, such as in [\w\s].
1858 * Thus
1859 * ~P = ~(Pa | Pb | ... | Pn)
1860 * = ~Pa & ~Pb & ... & ~Pn
1861 * <= ~Pa | ~Pb | ... | ~Pn
1862 * The last is something we can easily calculate, but unfortunately
1863 * is likely to have many false positives. We could do better
1864 * in some (but certainly not all) instances if two classes in
1865 * P have known relationships. For example
1866 * :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1867 * So
1868 * :lower: & :print: = :lower:
1869 * And similarly for classes that must be disjoint. For example,
1870 * since \s and \w can have no elements in common based on rules in
1871 * the POSIX standard,
1872 * \w & ^\S = nothing
1873 * Unfortunately, some vendor locales do not meet the Posix
1874 * standard, in particular almost everything by Microsoft.
1875 * The loop below just changes e.g., \w into \W and vice versa */
1876
1877 regnode_charclass_posixl temp;
1878 int add = 1; /* To calculate the index of the complement */
1879
1880 Zero(&temp, 1, regnode_charclass_posixl);
1881 ANYOF_POSIXL_ZERO(&temp);
1882 for (i = 0; i < ANYOF_MAX; i++) {
1883 assert(i % 2 != 0
1884 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1885 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1886
1887 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1888 ANYOF_POSIXL_SET(&temp, i + add);
1889 }
1890 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1891 }
1892 ANYOF_POSIXL_AND(&temp, ssc);
1893
1894 } /* else ssc already has no posixes */
1895 } /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC
1896 in its initial state */
1897 else if (! is_ANYOF_SYNTHETIC(and_with)
1898 || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1899 {
1900 /* But if 'ssc' is in its initial state, the result is just 'and_with';
1901 * copy it over 'ssc' */
1902 if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1903 if (is_ANYOF_SYNTHETIC(and_with)) {
1904 StructCopy(and_with, ssc, regnode_ssc);
1905 }
1906 else {
1907 ssc->invlist = anded_cp_list;
1908 ANYOF_POSIXL_ZERO(ssc);
1909 if (and_with_flags & ANYOF_MATCHES_POSIXL) {
1910 ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1911 }
1912 }
1913 }
1914 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1915 || (and_with_flags & ANYOF_MATCHES_POSIXL))
1916 {
1917 /* One or the other of P1, P2 is non-empty. */
1918 if (and_with_flags & ANYOF_MATCHES_POSIXL) {
1919 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1920 }
1921 ssc_union(ssc, anded_cp_list, FALSE);
1922 }
1923 else { /* P1 = P2 = empty */
1924 ssc_intersection(ssc, anded_cp_list, FALSE);
1925 }
1926 }
1927}
1928
1929STATIC void
1930S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1931 const regnode_charclass *or_with)
1932{
1933 /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1934 * another SSC or a regular ANYOF class. Can create false positives if
1935 * 'or_with' is to be inverted. */
1936
1937 SV* ored_cp_list;
1938 U8 ored_flags;
1939 U8 or_with_flags = inRANGE(OP(or_with), ANYOFH, ANYOFRb)
1940 ? 0
1941 : ANYOF_FLAGS(or_with);
1942
1943 PERL_ARGS_ASSERT_SSC_OR;
1944
1945 assert(is_ANYOF_SYNTHETIC(ssc));
1946
1947 /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1948 * the code point inversion list and just the relevant flags */
1949 if (is_ANYOF_SYNTHETIC(or_with)) {
1950 ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1951 ored_flags = or_with_flags;
1952 }
1953 else {
1954 ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
1955 ored_flags = or_with_flags & ANYOF_COMMON_FLAGS;
1956 if (OP(or_with) != ANYOFD) {
1957 ored_flags
1958 |= or_with_flags
1959 & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1960 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1961 if (ANYOFL_UTF8_LOCALE_REQD(or_with_flags)) {
1962 ored_flags |=
1963 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1964 }
1965 }
1966 }
1967
1968 ANYOF_FLAGS(ssc) |= ored_flags;
1969
1970 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1971 * C2 is the list of code points in 'or-with'; P2, its posix classes.
1972 * 'or_with' may be inverted. When not inverted, we have the simple
1973 * situation of computing:
1974 * (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2)
1975 * If P1|P2 yields a situation with both a class and its complement are
1976 * set, like having both \w and \W, this matches all code points, and we
1977 * can delete these from the P component of the ssc going forward. XXX We
1978 * might be able to delete all the P components, but I (khw) am not certain
1979 * about this, and it is better to be safe.
1980 *
1981 * Inverted, we have
1982 * (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2)
1983 * <= (C1 | P1) | ~C2
1984 * <= (C1 | ~C2) | P1
1985 * (which results in actually simpler code than the non-inverted case)
1986 * */
1987
1988 if ((or_with_flags & ANYOF_INVERT)
1989 && ! is_ANYOF_SYNTHETIC(or_with))
1990 {
1991 /* We ignore P2, leaving P1 going forward */
1992 } /* else Not inverted */
1993 else if (or_with_flags & ANYOF_MATCHES_POSIXL) {
1994 ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
1995 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1996 unsigned int i;
1997 for (i = 0; i < ANYOF_MAX; i += 2) {
1998 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1999 {
2000 ssc_match_all_cp(ssc);
2001 ANYOF_POSIXL_CLEAR(ssc, i);
2002 ANYOF_POSIXL_CLEAR(ssc, i+1);
2003 }
2004 }
2005 }
2006 }
2007
2008 ssc_union(ssc,
2009 ored_cp_list,
2010 FALSE /* Already has been inverted */
2011 );
2012}
2013
2014PERL_STATIC_INLINE void
2015S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
2016{
2017 PERL_ARGS_ASSERT_SSC_UNION;
2018
2019 assert(is_ANYOF_SYNTHETIC(ssc));
2020
2021 _invlist_union_maybe_complement_2nd(ssc->invlist,
2022 invlist,
2023 invert2nd,
2024 &ssc->invlist);
2025}
2026
2027PERL_STATIC_INLINE void
2028S_ssc_intersection(pTHX_ regnode_ssc *ssc,
2029 SV* const invlist,
2030 const bool invert2nd)
2031{
2032 PERL_ARGS_ASSERT_SSC_INTERSECTION;
2033
2034 assert(is_ANYOF_SYNTHETIC(ssc));
2035
2036 _invlist_intersection_maybe_complement_2nd(ssc->invlist,
2037 invlist,
2038 invert2nd,
2039 &ssc->invlist);
2040}
2041
2042PERL_STATIC_INLINE void
2043S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
2044{
2045 PERL_ARGS_ASSERT_SSC_ADD_RANGE;
2046
2047 assert(is_ANYOF_SYNTHETIC(ssc));
2048
2049 ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
2050}
2051
2052PERL_STATIC_INLINE void
2053S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
2054{
2055 /* AND just the single code point 'cp' into the SSC 'ssc' */
2056
2057 SV* cp_list = _new_invlist(2);
2058
2059 PERL_ARGS_ASSERT_SSC_CP_AND;
2060
2061 assert(is_ANYOF_SYNTHETIC(ssc));
2062
2063 cp_list = add_cp_to_invlist(cp_list, cp);
2064 ssc_intersection(ssc, cp_list,
2065 FALSE /* Not inverted */
2066 );
2067 SvREFCNT_dec_NN(cp_list);
2068}
2069
2070PERL_STATIC_INLINE void
2071S_ssc_clear_locale(regnode_ssc *ssc)
2072{
2073 /* Set the SSC 'ssc' to not match any locale things */
2074 PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
2075
2076 assert(is_ANYOF_SYNTHETIC(ssc));
2077
2078 ANYOF_POSIXL_ZERO(ssc);
2079 ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
2080}
2081
2082#define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
2083
2084STATIC bool
2085S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
2086{
2087 /* The synthetic start class is used to hopefully quickly winnow down
2088 * places where a pattern could start a match in the target string. If it
2089 * doesn't really narrow things down that much, there isn't much point to
2090 * having the overhead of using it. This function uses some very crude
2091 * heuristics to decide if to use the ssc or not.
2092 *
2093 * It returns TRUE if 'ssc' rules out more than half what it considers to
2094 * be the "likely" possible matches, but of course it doesn't know what the
2095 * actual things being matched are going to be; these are only guesses
2096 *
2097 * For /l matches, it assumes that the only likely matches are going to be
2098 * in the 0-255 range, uniformly distributed, so half of that is 127
2099 * For /a and /d matches, it assumes that the likely matches will be just
2100 * the ASCII range, so half of that is 63
2101 * For /u and there isn't anything matching above the Latin1 range, it
2102 * assumes that that is the only range likely to be matched, and uses
2103 * half that as the cut-off: 127. If anything matches above Latin1,
2104 * it assumes that all of Unicode could match (uniformly), except for
2105 * non-Unicode code points and things in the General Category "Other"
2106 * (unassigned, private use, surrogates, controls and formats). This
2107 * is a much large number. */
2108
2109 U32 count = 0; /* Running total of number of code points matched by
2110 'ssc' */
2111 UV start, end; /* Start and end points of current range in inversion
2112 XXX outdated. UTF-8 locales are common, what about invert? list */
2113 const U32 max_code_points = (LOC)
2114 ? 256
2115 : (( ! UNI_SEMANTICS
2116 || invlist_highest(ssc->invlist) < 256)
2117 ? 128
2118 : NON_OTHER_COUNT);
2119 const U32 max_match = max_code_points / 2;
2120
2121 PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
2122
2123 invlist_iterinit(ssc->invlist);
2124 while (invlist_iternext(ssc->invlist, &start, &end)) {
2125 if (start >= max_code_points) {
2126 break;
2127 }
2128 end = MIN(end, max_code_points - 1);
2129 count += end - start + 1;
2130 if (count >= max_match) {
2131 invlist_iterfinish(ssc->invlist);
2132 return FALSE;
2133 }
2134 }
2135
2136 return TRUE;
2137}
2138
2139
2140STATIC void
2141S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
2142{
2143 /* The inversion list in the SSC is marked mortal; now we need a more
2144 * permanent copy, which is stored the same way that is done in a regular
2145 * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
2146 * map */
2147
2148 SV* invlist = invlist_clone(ssc->invlist, NULL);
2149
2150 PERL_ARGS_ASSERT_SSC_FINALIZE;
2151
2152 assert(is_ANYOF_SYNTHETIC(ssc));
2153
2154 /* The code in this file assumes that all but these flags aren't relevant
2155 * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
2156 * by the time we reach here */
2157 assert(! (ANYOF_FLAGS(ssc)
2158 & ~( ANYOF_COMMON_FLAGS
2159 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2160 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
2161
2162 populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
2163
2164 set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist, NULL, NULL);
2165 SvREFCNT_dec(invlist);
2166
2167 /* Make sure is clone-safe */
2168 ssc->invlist = NULL;
2169
2170 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2171 ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
2172 OP(ssc) = ANYOFPOSIXL;
2173 }
2174 else if (RExC_contains_locale) {
2175 OP(ssc) = ANYOFL;
2176 }
2177
2178 assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
2179}
2180
2181#define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
2182#define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
2183#define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
2184#define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \
2185 ? (TRIE_LIST_CUR( idx ) - 1) \
2186 : 0 )
2187
2188
2189#ifdef DEBUGGING
2190/*
2191 dump_trie(trie,widecharmap,revcharmap)
2192 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
2193 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
2194
2195 These routines dump out a trie in a somewhat readable format.
2196 The _interim_ variants are used for debugging the interim
2197 tables that are used to generate the final compressed
2198 representation which is what dump_trie expects.
2199
2200 Part of the reason for their existence is to provide a form
2201 of documentation as to how the different representations function.
2202
2203*/
2204
2205/*
2206 Dumps the final compressed table form of the trie to Perl_debug_log.
2207 Used for debugging make_trie().
2208*/
2209
2210STATIC void
2211S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
2212 AV *revcharmap, U32 depth)
2213{
2214 U32 state;
2215 SV *sv=sv_newmortal();
2216 int colwidth= widecharmap ? 6 : 4;
2217 U16 word;
2218 GET_RE_DEBUG_FLAGS_DECL;
2219
2220 PERL_ARGS_ASSERT_DUMP_TRIE;
2221
2222 Perl_re_indentf( aTHX_ "Char : %-6s%-6s%-4s ",
2223 depth+1, "Match","Base","Ofs" );
2224
2225 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2226 SV ** const tmp = av_fetch( revcharmap, state, 0);
2227 if ( tmp ) {
2228 Perl_re_printf( aTHX_ "%*s",
2229 colwidth,
2230 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2231 PL_colors[0], PL_colors[1],
2232 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2233 PERL_PV_ESCAPE_FIRSTCHAR
2234 )
2235 );
2236 }
2237 }
2238 Perl_re_printf( aTHX_ "\n");
2239 Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
2240
2241 for( state = 0 ; state < trie->uniquecharcount ; state++ )
2242 Perl_re_printf( aTHX_ "%.*s", colwidth, "--------");
2243 Perl_re_printf( aTHX_ "\n");
2244
2245 for( state = 1 ; state < trie->statecount ; state++ ) {
2246 const U32 base = trie->states[ state ].trans.base;
2247
2248 Perl_re_indentf( aTHX_ "#%4" UVXf "|", depth+1, (UV)state);
2249
2250 if ( trie->states[ state ].wordnum ) {
2251 Perl_re_printf( aTHX_ " W%4X", trie->states[ state ].wordnum );
2252 } else {
2253 Perl_re_printf( aTHX_ "%6s", "" );
2254 }
2255
2256 Perl_re_printf( aTHX_ " @%4" UVXf " ", (UV)base );
2257
2258 if ( base ) {
2259 U32 ofs = 0;
2260
2261 while( ( base + ofs < trie->uniquecharcount ) ||
2262 ( base + ofs - trie->uniquecharcount < trie->lasttrans
2263 && trie->trans[ base + ofs - trie->uniquecharcount ].check
2264 != state))
2265 ofs++;
2266
2267 Perl_re_printf( aTHX_ "+%2" UVXf "[ ", (UV)ofs);
2268
2269 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2270 if ( ( base + ofs >= trie->uniquecharcount )
2271 && ( base + ofs - trie->uniquecharcount
2272 < trie->lasttrans )
2273 && trie->trans[ base + ofs
2274 - trie->uniquecharcount ].check == state )
2275 {
2276 Perl_re_printf( aTHX_ "%*" UVXf, colwidth,
2277 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
2278 );
2279 } else {
2280 Perl_re_printf( aTHX_ "%*s", colwidth," ." );
2281 }
2282 }
2283
2284 Perl_re_printf( aTHX_ "]");
2285
2286 }
2287 Perl_re_printf( aTHX_ "\n" );
2288 }
2289 Perl_re_indentf( aTHX_ "word_info N:(prev,len)=",
2290 depth);
2291 for (word=1; word <= trie->wordcount; word++) {
2292 Perl_re_printf( aTHX_ " %d:(%d,%d)",
2293 (int)word, (int)(trie->wordinfo[word].prev),
2294 (int)(trie->wordinfo[word].len));
2295 }
2296 Perl_re_printf( aTHX_ "\n" );
2297}
2298/*
2299 Dumps a fully constructed but uncompressed trie in list form.
2300 List tries normally only are used for construction when the number of
2301 possible chars (trie->uniquecharcount) is very high.
2302 Used for debugging make_trie().
2303*/
2304STATIC void
2305S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2306 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2307 U32 depth)
2308{
2309 U32 state;
2310 SV *sv=sv_newmortal();
2311 int colwidth= widecharmap ? 6 : 4;
2312 GET_RE_DEBUG_FLAGS_DECL;
2313
2314 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2315
2316 /* print out the table precompression. */
2317 Perl_re_indentf( aTHX_ "State :Word | Transition Data\n",
2318 depth+1 );
2319 Perl_re_indentf( aTHX_ "%s",
2320 depth+1, "------:-----+-----------------\n" );
2321
2322 for( state=1 ; state < next_alloc ; state ++ ) {
2323 U16 charid;
2324
2325 Perl_re_indentf( aTHX_ " %4" UVXf " :",
2326 depth+1, (UV)state );
2327 if ( ! trie->states[ state ].wordnum ) {
2328 Perl_re_printf( aTHX_ "%5s| ","");
2329 } else {
2330 Perl_re_printf( aTHX_ "W%4x| ",
2331 trie->states[ state ].wordnum
2332 );
2333 }
2334 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2335 SV ** const tmp = av_fetch( revcharmap,
2336 TRIE_LIST_ITEM(state, charid).forid, 0);
2337 if ( tmp ) {
2338 Perl_re_printf( aTHX_ "%*s:%3X=%4" UVXf " | ",
2339 colwidth,
2340 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2341 colwidth,
2342 PL_colors[0], PL_colors[1],
2343 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2344 | PERL_PV_ESCAPE_FIRSTCHAR
2345 ) ,
2346 TRIE_LIST_ITEM(state, charid).forid,
2347 (UV)TRIE_LIST_ITEM(state, charid).newstate
2348 );
2349 if (!(charid % 10))
2350 Perl_re_printf( aTHX_ "\n%*s| ",
2351 (int)((depth * 2) + 14), "");
2352 }
2353 }
2354 Perl_re_printf( aTHX_ "\n");
2355 }
2356}
2357
2358/*
2359 Dumps a fully constructed but uncompressed trie in table form.
2360 This is the normal DFA style state transition table, with a few
2361 twists to facilitate compression later.
2362 Used for debugging make_trie().
2363*/
2364STATIC void
2365S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2366 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2367 U32 depth)
2368{
2369 U32 state;
2370 U16 charid;
2371 SV *sv=sv_newmortal();
2372 int colwidth= widecharmap ? 6 : 4;
2373 GET_RE_DEBUG_FLAGS_DECL;
2374
2375 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2376
2377 /*
2378 print out the table precompression so that we can do a visual check
2379 that they are identical.
2380 */
2381
2382 Perl_re_indentf( aTHX_ "Char : ", depth+1 );
2383
2384 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2385 SV ** const tmp = av_fetch( revcharmap, charid, 0);
2386 if ( tmp ) {
2387 Perl_re_printf( aTHX_ "%*s",
2388 colwidth,
2389 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2390 PL_colors[0], PL_colors[1],
2391 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2392 PERL_PV_ESCAPE_FIRSTCHAR
2393 )
2394 );
2395 }
2396 }
2397
2398 Perl_re_printf( aTHX_ "\n");
2399 Perl_re_indentf( aTHX_ "State+-", depth+1 );
2400
2401 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2402 Perl_re_printf( aTHX_ "%.*s", colwidth,"--------");
2403 }
2404
2405 Perl_re_printf( aTHX_ "\n" );
2406
2407 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2408
2409 Perl_re_indentf( aTHX_ "%4" UVXf " : ",
2410 depth+1,
2411 (UV)TRIE_NODENUM( state ) );
2412
2413 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2414 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2415 if (v)
2416 Perl_re_printf( aTHX_ "%*" UVXf, colwidth, v );
2417 else
2418 Perl_re_printf( aTHX_ "%*s", colwidth, "." );
2419 }
2420 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2421 Perl_re_printf( aTHX_ " (%4" UVXf ")\n",
2422 (UV)trie->trans[ state ].check );
2423 } else {
2424 Perl_re_printf( aTHX_ " (%4" UVXf ") W%4X\n",
2425 (UV)trie->trans[ state ].check,
2426 trie->states[ TRIE_NODENUM( state ) ].wordnum );
2427 }
2428 }
2429}
2430
2431#endif
2432
2433
2434/* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2435 startbranch: the first branch in the whole branch sequence
2436 first : start branch of sequence of branch-exact nodes.
2437 May be the same as startbranch
2438 last : Thing following the last branch.
2439 May be the same as tail.
2440 tail : item following the branch sequence
2441 count : words in the sequence
2442 flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2443 depth : indent depth
2444
2445Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2446
2447A trie is an N'ary tree where the branches are determined by digital
2448decomposition of the key. IE, at the root node you look up the 1st character and
2449follow that branch repeat until you find the end of the branches. Nodes can be
2450marked as "accepting" meaning they represent a complete word. Eg:
2451
2452 /he|she|his|hers/
2453
2454would convert into the following structure. Numbers represent states, letters
2455following numbers represent valid transitions on the letter from that state, if
2456the number is in square brackets it represents an accepting state, otherwise it
2457will be in parenthesis.
2458
2459 +-h->+-e->[3]-+-r->(8)-+-s->[9]
2460 | |
2461 | (2)
2462 | |
2463 (1) +-i->(6)-+-s->[7]
2464 |
2465 +-s->(3)-+-h->(4)-+-e->[5]
2466
2467 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2468
2469This shows that when matching against the string 'hers' we will begin at state 1
2470read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2471then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2472is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2473single traverse. We store a mapping from accepting to state to which word was
2474matched, and then when we have multiple possibilities we try to complete the
2475rest of the regex in the order in which they occurred in the alternation.
2476
2477The only prior NFA like behaviour that would be changed by the TRIE support is
2478the silent ignoring of duplicate alternations which are of the form:
2479
2480 / (DUPE|DUPE) X? (?{ ... }) Y /x
2481
2482Thus EVAL blocks following a trie may be called a different number of times with
2483and without the optimisation. With the optimisations dupes will be silently
2484ignored. This inconsistent behaviour of EVAL type nodes is well established as
2485the following demonstrates:
2486
2487 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2488
2489which prints out 'word' three times, but
2490
2491 'words'=~/(word|word|word)(?{ print $1 })S/
2492
2493which doesnt print it out at all. This is due to other optimisations kicking in.
2494
2495Example of what happens on a structural level:
2496
2497The regexp /(ac|ad|ab)+/ will produce the following debug output:
2498
2499 1: CURLYM[1] {1,32767}(18)
2500 5: BRANCH(8)
2501 6: EXACT <ac>(16)
2502 8: BRANCH(11)
2503 9: EXACT <ad>(16)
2504 11: BRANCH(14)
2505 12: EXACT <ab>(16)
2506 16: SUCCEED(0)
2507 17: NOTHING(18)
2508 18: END(0)
2509
2510This would be optimizable with startbranch=5, first=5, last=16, tail=16
2511and should turn into:
2512
2513 1: CURLYM[1] {1,32767}(18)
2514 5: TRIE(16)
2515 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2516 <ac>
2517 <ad>
2518 <ab>
2519 16: SUCCEED(0)
2520 17: NOTHING(18)
2521 18: END(0)
2522
2523Cases where tail != last would be like /(?foo|bar)baz/:
2524
2525 1: BRANCH(4)
2526 2: EXACT <foo>(8)
2527 4: BRANCH(7)
2528 5: EXACT <bar>(8)
2529 7: TAIL(8)
2530 8: EXACT <baz>(10)
2531 10: END(0)
2532
2533which would be optimizable with startbranch=1, first=1, last=7, tail=8
2534and would end up looking like:
2535
2536 1: TRIE(8)
2537 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2538 <foo>
2539 <bar>
2540 7: TAIL(8)
2541 8: EXACT <baz>(10)
2542 10: END(0)
2543
2544 d = uvchr_to_utf8_flags(d, uv, 0);
2545
2546is the recommended Unicode-aware way of saying
2547
2548 *(d++) = uv;
2549*/
2550
2551#define TRIE_STORE_REVCHAR(val) \
2552 STMT_START { \
2553 if (UTF) { \
2554 SV *zlopp = newSV(UTF8_MAXBYTES); \
2555 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
2556 unsigned char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
2557 *kapow = '\0'; \
2558 SvCUR_set(zlopp, kapow - flrbbbbb); \
2559 SvPOK_on(zlopp); \
2560 SvUTF8_on(zlopp); \
2561 av_push(revcharmap, zlopp); \
2562 } else { \
2563 char ooooff = (char)val; \
2564 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
2565 } \
2566 } STMT_END
2567
2568/* This gets the next character from the input, folding it if not already
2569 * folded. */
2570#define TRIE_READ_CHAR STMT_START { \
2571 wordlen++; \
2572 if ( UTF ) { \
2573 /* if it is UTF then it is either already folded, or does not need \
2574 * folding */ \
2575 uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \
2576 } \
2577 else if (folder == PL_fold_latin1) { \
2578 /* This folder implies Unicode rules, which in the range expressible \
2579 * by not UTF is the lower case, with the two exceptions, one of \
2580 * which should have been taken care of before calling this */ \
2581 assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \
2582 uvc = toLOWER_L1(*uc); \
2583 if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \
2584 len = 1; \
2585 } else { \
2586 /* raw data, will be folded later if needed */ \
2587 uvc = (U32)*uc; \
2588 len = 1; \
2589 } \
2590} STMT_END
2591
2592
2593
2594#define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
2595 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
2596 U32 ging = TRIE_LIST_LEN( state ) * 2; \
2597 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2598 TRIE_LIST_LEN( state ) = ging; \
2599 } \
2600 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
2601 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
2602 TRIE_LIST_CUR( state )++; \
2603} STMT_END
2604
2605#define TRIE_LIST_NEW(state) STMT_START { \
2606 Newx( trie->states[ state ].trans.list, \
2607 4, reg_trie_trans_le ); \
2608 TRIE_LIST_CUR( state ) = 1; \
2609 TRIE_LIST_LEN( state ) = 4; \
2610} STMT_END
2611
2612#define TRIE_HANDLE_WORD(state) STMT_START { \
2613 U16 dupe= trie->states[ state ].wordnum; \
2614 regnode * const noper_next = regnext( noper ); \
2615 \
2616 DEBUG_r({ \
2617 /* store the word for dumping */ \
2618 SV* tmp; \
2619 if (OP(noper) != NOTHING) \
2620 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
2621 else \
2622 tmp = newSVpvn_utf8( "", 0, UTF ); \
2623 av_push( trie_words, tmp ); \
2624 }); \
2625 \
2626 curword++; \
2627 trie->wordinfo[curword].prev = 0; \
2628 trie->wordinfo[curword].len = wordlen; \
2629 trie->wordinfo[curword].accept = state; \
2630 \
2631 if ( noper_next < tail ) { \
2632 if (!trie->jump) \
2633 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2634 sizeof(U16) ); \
2635 trie->jump[curword] = (U16)(noper_next - convert); \
2636 if (!jumper) \
2637 jumper = noper_next; \
2638 if (!nextbranch) \
2639 nextbranch= regnext(cur); \
2640 } \
2641 \
2642 if ( dupe ) { \
2643 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
2644 /* chain, so that when the bits of chain are later */\
2645 /* linked together, the dups appear in the chain */\
2646 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2647 trie->wordinfo[dupe].prev = curword; \
2648 } else { \
2649 /* we haven't inserted this word yet. */ \
2650 trie->states[ state ].wordnum = curword; \
2651 } \
2652} STMT_END
2653
2654
2655#define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
2656 ( ( base + charid >= ucharcount \
2657 && base + charid < ubound \
2658 && state == trie->trans[ base - ucharcount + charid ].check \
2659 && trie->trans[ base - ucharcount + charid ].next ) \
2660 ? trie->trans[ base - ucharcount + charid ].next \
2661 : ( state==1 ? special : 0 ) \
2662 )
2663
2664#define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder) \
2665STMT_START { \
2666 TRIE_BITMAP_SET(trie, uvc); \
2667 /* store the folded codepoint */ \
2668 if ( folder ) \
2669 TRIE_BITMAP_SET(trie, folder[(U8) uvc ]); \
2670 \
2671 if ( !UTF ) { \
2672 /* store first byte of utf8 representation of */ \
2673 /* variant codepoints */ \
2674 if (! UVCHR_IS_INVARIANT(uvc)) { \
2675 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc)); \
2676 } \
2677 } \
2678} STMT_END
2679#define MADE_TRIE 1
2680#define MADE_JUMP_TRIE 2
2681#define MADE_EXACT_TRIE 4
2682
2683STATIC I32
2684S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2685 regnode *first, regnode *last, regnode *tail,
2686 U32 word_count, U32 flags, U32 depth)
2687{
2688 /* first pass, loop through and scan words */
2689 reg_trie_data *trie;
2690 HV *widecharmap = NULL;
2691 AV *revcharmap = newAV();
2692 regnode *cur;
2693 STRLEN len = 0;
2694 UV uvc = 0;
2695 U16 curword = 0;
2696 U32 next_alloc = 0;
2697 regnode *jumper = NULL;
2698 regnode *nextbranch = NULL;
2699 regnode *convert = NULL;
2700 U32 *prev_states; /* temp array mapping each state to previous one */
2701 /* we just use folder as a flag in utf8 */
2702 const U8 * folder = NULL;
2703
2704 /* in the below add_data call we are storing either 'tu' or 'tuaa'
2705 * which stands for one trie structure, one hash, optionally followed
2706 * by two arrays */
2707#ifdef DEBUGGING
2708 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
2709 AV *trie_words = NULL;
2710 /* along with revcharmap, this only used during construction but both are
2711 * useful during debugging so we store them in the struct when debugging.
2712 */
2713#else
2714 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2715 STRLEN trie_charcount=0;
2716#endif
2717 SV *re_trie_maxbuff;
2718 GET_RE_DEBUG_FLAGS_DECL;
2719
2720 PERL_ARGS_ASSERT_MAKE_TRIE;
2721#ifndef DEBUGGING
2722 PERL_UNUSED_ARG(depth);
2723#endif
2724
2725 switch (flags) {
2726 case EXACT: case EXACT_REQ8: case EXACTL: break;
2727 case EXACTFAA:
2728 case EXACTFUP:
2729 case EXACTFU:
2730 case EXACTFLU8: folder = PL_fold_latin1; break;
2731 case EXACTF: folder = PL_fold; break;
2732 default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2733 }
2734
2735 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2736 trie->refcount = 1;
2737 trie->startstate = 1;
2738 trie->wordcount = word_count;
2739 RExC_rxi->data->data[ data_slot ] = (void*)trie;
2740 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2741 if (flags == EXACT || flags == EXACT_REQ8 || flags == EXACTL)
2742 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2743 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2744 trie->wordcount+1, sizeof(reg_trie_wordinfo));
2745
2746 DEBUG_r({
2747 trie_words = newAV();
2748 });
2749
2750 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, GV_ADD);
2751 assert(re_trie_maxbuff);
2752 if (!SvIOK(re_trie_maxbuff)) {
2753 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2754 }
2755 DEBUG_TRIE_COMPILE_r({
2756 Perl_re_indentf( aTHX_
2757 "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2758 depth+1,
2759 REG_NODE_NUM(startbranch), REG_NODE_NUM(first),
2760 REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2761 });
2762
2763 /* Find the node we are going to overwrite */
2764 if ( first == startbranch && OP( last ) != BRANCH ) {
2765 /* whole branch chain */
2766 convert = first;
2767 } else {
2768 /* branch sub-chain */
2769 convert = NEXTOPER( first );
2770 }
2771
2772 /* -- First loop and Setup --
2773
2774 We first traverse the branches and scan each word to determine if it
2775 contains widechars, and how many unique chars there are, this is
2776 important as we have to build a table with at least as many columns as we
2777 have unique chars.
2778
2779 We use an array of integers to represent the character codes 0..255
2780 (trie->charmap) and we use a an HV* to store Unicode characters. We use
2781 the native representation of the character value as the key and IV's for
2782 the coded index.
2783
2784 *TODO* If we keep track of how many times each character is used we can
2785 remap the columns so that the table compression later on is more
2786 efficient in terms of memory by ensuring the most common value is in the
2787 middle and the least common are on the outside. IMO this would be better
2788 than a most to least common mapping as theres a decent chance the most
2789 common letter will share a node with the least common, meaning the node
2790 will not be compressible. With a middle is most common approach the worst
2791 case is when we have the least common nodes twice.
2792
2793 */
2794
2795 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2796 regnode *noper = NEXTOPER( cur );
2797 const U8 *uc;
2798 const U8 *e;
2799 int foldlen = 0;
2800 U32 wordlen = 0; /* required init */
2801 STRLEN minchars = 0;
2802 STRLEN maxchars = 0;
2803 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2804 bitmap?*/
2805
2806 if (OP(noper) == NOTHING) {
2807 /* skip past a NOTHING at the start of an alternation
2808 * eg, /(?:)a|(?:b)/ should be the same as /a|b/
2809 *
2810 * If the next node is not something we are supposed to process
2811 * we will just ignore it due to the condition guarding the
2812 * next block.
2813 */
2814
2815 regnode *noper_next= regnext(noper);
2816 if (noper_next < tail)
2817 noper= noper_next;
2818 }
2819
2820 if ( noper < tail
2821 && ( OP(noper) == flags
2822 || (flags == EXACT && OP(noper) == EXACT_REQ8)
2823 || (flags == EXACTFU && ( OP(noper) == EXACTFU_REQ8
2824 || OP(noper) == EXACTFUP))))
2825 {
2826 uc= (U8*)STRING(noper);
2827 e= uc + STR_LEN(noper);
2828 } else {
2829 trie->minlen= 0;
2830 continue;
2831 }
2832
2833
2834 if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2835 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2836 regardless of encoding */
2837 if (OP( noper ) == EXACTFUP) {
2838 /* false positives are ok, so just set this */
2839 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2840 }
2841 }
2842
2843 for ( ; uc < e ; uc += len ) { /* Look at each char in the current
2844 branch */
2845 TRIE_CHARCOUNT(trie)++;
2846 TRIE_READ_CHAR;
2847
2848 /* TRIE_READ_CHAR returns the current character, or its fold if /i
2849 * is in effect. Under /i, this character can match itself, or
2850 * anything that folds to it. If not under /i, it can match just
2851 * itself. Most folds are 1-1, for example k, K, and KELVIN SIGN
2852 * all fold to k, and all are single characters. But some folds
2853 * expand to more than one character, so for example LATIN SMALL
2854 * LIGATURE FFI folds to the three character sequence 'ffi'. If
2855 * the string beginning at 'uc' is 'ffi', it could be matched by
2856 * three characters, or just by the one ligature character. (It
2857 * could also be matched by two characters: LATIN SMALL LIGATURE FF
2858 * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2859 * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2860 * match.) The trie needs to know the minimum and maximum number
2861 * of characters that could match so that it can use size alone to
2862 * quickly reject many match attempts. The max is simple: it is
2863 * the number of folded characters in this branch (since a fold is
2864 * never shorter than what folds to it. */
2865
2866 maxchars++;
2867
2868 /* And the min is equal to the max if not under /i (indicated by
2869 * 'folder' being NULL), or there are no multi-character folds. If
2870 * there is a multi-character fold, the min is incremented just
2871 * once, for the character that folds to the sequence. Each
2872 * character in the sequence needs to be added to the list below of
2873 * characters in the trie, but we count only the first towards the
2874 * min number of characters needed. This is done through the
2875 * variable 'foldlen', which is returned by the macros that look
2876 * for these sequences as the number of bytes the sequence
2877 * occupies. Each time through the loop, we decrement 'foldlen' by
2878 * how many bytes the current char occupies. Only when it reaches
2879 * 0 do we increment 'minchars' or look for another multi-character
2880 * sequence. */
2881 if (folder == NULL) {
2882 minchars++;
2883 }
2884 else if (foldlen > 0) {
2885 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2886 }
2887 else {
2888 minchars++;
2889
2890 /* See if *uc is the beginning of a multi-character fold. If
2891 * so, we decrement the length remaining to look at, to account
2892 * for the current character this iteration. (We can use 'uc'
2893 * instead of the fold returned by TRIE_READ_CHAR because for
2894 * non-UTF, the latin1_safe macro is smart enough to account
2895 * for all the unfolded characters, and because for UTF, the
2896 * string will already have been folded earlier in the
2897 * compilation process */
2898 if (UTF) {
2899 if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2900 foldlen -= UTF8SKIP(uc);
2901 }
2902 }
2903 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2904 foldlen--;
2905 }
2906 }
2907
2908 /* The current character (and any potential folds) should be added
2909 * to the possible matching characters for this position in this
2910 * branch */
2911 if ( uvc < 256 ) {
2912 if ( folder ) {
2913 U8 folded= folder[ (U8) uvc ];
2914 if ( !trie->charmap[ folded ] ) {
2915 trie->charmap[ folded ]=( ++trie->uniquecharcount );
2916 TRIE_STORE_REVCHAR( folded );
2917 }
2918 }
2919 if ( !trie->charmap[ uvc ] ) {
2920 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2921 TRIE_STORE_REVCHAR( uvc );
2922 }
2923 if ( set_bit ) {
2924 /* store the codepoint in the bitmap, and its folded
2925 * equivalent. */
2926 TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
2927 set_bit = 0; /* We've done our bit :-) */
2928 }
2929 } else {
2930
2931 /* XXX We could come up with the list of code points that fold
2932 * to this using PL_utf8_foldclosures, except not for
2933 * multi-char folds, as there may be multiple combinations
2934 * there that could work, which needs to wait until runtime to
2935 * resolve (The comment about LIGATURE FFI above is such an
2936 * example */
2937
2938 SV** svpp;
2939 if ( !widecharmap )
2940 widecharmap = newHV();
2941
2942 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2943
2944 if ( !svpp )
2945 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
2946
2947 if ( !SvTRUE( *svpp ) ) {
2948 sv_setiv( *svpp, ++trie->uniquecharcount );
2949 TRIE_STORE_REVCHAR(uvc);
2950 }
2951 }
2952 } /* end loop through characters in this branch of the trie */
2953
2954 /* We take the min and max for this branch and combine to find the min
2955 * and max for all branches processed so far */
2956 if( cur == first ) {
2957 trie->minlen = minchars;
2958 trie->maxlen = maxchars;
2959 } else if (minchars < trie->minlen) {
2960 trie->minlen = minchars;
2961 } else if (maxchars > trie->maxlen) {
2962 trie->maxlen = maxchars;
2963 }
2964 } /* end first pass */
2965 DEBUG_TRIE_COMPILE_r(
2966 Perl_re_indentf( aTHX_
2967 "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2968 depth+1,
2969 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
2970 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2971 (int)trie->minlen, (int)trie->maxlen )
2972 );
2973
2974 /*
2975 We now know what we are dealing with in terms of unique chars and
2976 string sizes so we can calculate how much memory a naive
2977 representation using a flat table will take. If it's over a reasonable
2978 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
2979 conservative but potentially much slower representation using an array
2980 of lists.
2981
2982 At the end we convert both representations into the same compressed
2983 form that will be used in regexec.c for matching with. The latter
2984 is a form that cannot be used to construct with but has memory
2985 properties similar to the list form and access properties similar
2986 to the table form making it both suitable for fast searches and
2987 small enough that its feasable to store for the duration of a program.
2988
2989 See the comment in the code where the compressed table is produced
2990 inplace from the flat tabe representation for an explanation of how
2991 the compression works.
2992
2993 */
2994
2995
2996 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2997 prev_states[1] = 0;
2998
2999 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
3000 > SvIV(re_trie_maxbuff) )
3001 {
3002 /*
3003 Second Pass -- Array Of Lists Representation
3004
3005 Each state will be represented by a list of charid:state records
3006 (reg_trie_trans_le) the first such element holds the CUR and LEN
3007 points of the allocated array. (See defines above).
3008
3009 We build the initial structure using the lists, and then convert
3010 it into the compressed table form which allows faster lookups
3011 (but cant be modified once converted).
3012 */
3013
3014 STRLEN transcount = 1;
3015
3016 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using list compiler\n",
3017 depth+1));
3018
3019 trie->states = (reg_trie_state *)
3020 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3021 sizeof(reg_trie_state) );
3022 TRIE_LIST_NEW(1);
3023 next_alloc = 2;
3024
3025 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3026
3027 regnode *noper = NEXTOPER( cur );
3028 U32 state = 1; /* required init */
3029 U16 charid = 0; /* sanity init */
3030 U32 wordlen = 0; /* required init */
3031
3032 if (OP(noper) == NOTHING) {
3033 regnode *noper_next= regnext(noper);
3034 if (noper_next < tail)
3035 noper= noper_next;
3036 /* we will undo this assignment if noper does not
3037 * point at a trieable type in the else clause of
3038 * the following statement. */
3039 }
3040
3041 if ( noper < tail
3042 && ( OP(noper) == flags
3043 || (flags == EXACT && OP(noper) == EXACT_REQ8)
3044 || (flags == EXACTFU && ( OP(noper) == EXACTFU_REQ8
3045 || OP(noper) == EXACTFUP))))
3046 {
3047 const U8 *uc= (U8*)STRING(noper);
3048 const U8 *e= uc + STR_LEN(noper);
3049
3050 for ( ; uc < e ; uc += len ) {
3051
3052 TRIE_READ_CHAR;
3053
3054 if ( uvc < 256 ) {
3055 charid = trie->charmap[ uvc ];
3056 } else {
3057 SV** const svpp = hv_fetch( widecharmap,
3058 (char*)&uvc,
3059 sizeof( UV ),
3060 0);
3061 if ( !svpp ) {
3062 charid = 0;
3063 } else {
3064 charid=(U16)SvIV( *svpp );
3065 }
3066 }
3067 /* charid is now 0 if we dont know the char read, or
3068 * nonzero if we do */
3069 if ( charid ) {
3070
3071 U16 check;
3072 U32 newstate = 0;
3073
3074 charid--;
3075 if ( !trie->states[ state ].trans.list ) {
3076 TRIE_LIST_NEW( state );
3077 }
3078 for ( check = 1;
3079 check <= TRIE_LIST_USED( state );
3080 check++ )
3081 {
3082 if ( TRIE_LIST_ITEM( state, check ).forid
3083 == charid )
3084 {
3085 newstate = TRIE_LIST_ITEM( state, check ).newstate;
3086 break;
3087 }
3088 }
3089 if ( ! newstate ) {
3090 newstate = next_alloc++;
3091 prev_states[newstate] = state;
3092 TRIE_LIST_PUSH( state, charid, newstate );
3093 transcount++;
3094 }
3095 state = newstate;
3096 } else {
3097 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3098 }
3099 }
3100 } else {
3101 /* If we end up here it is because we skipped past a NOTHING, but did not end up
3102 * on a trieable type. So we need to reset noper back to point at the first regop
3103 * in the branch before we call TRIE_HANDLE_WORD()
3104 */
3105 noper= NEXTOPER(cur);
3106 }
3107 TRIE_HANDLE_WORD(state);
3108
3109 } /* end second pass */
3110
3111 /* next alloc is the NEXT state to be allocated */
3112 trie->statecount = next_alloc;
3113 trie->states = (reg_trie_state *)
3114 PerlMemShared_realloc( trie->states,
3115 next_alloc
3116 * sizeof(reg_trie_state) );
3117
3118 /* and now dump it out before we compress it */
3119 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
3120 revcharmap, next_alloc,
3121 depth+1)
3122 );
3123
3124 trie->trans = (reg_trie_trans *)
3125 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
3126 {
3127 U32 state;
3128 U32 tp = 0;
3129 U32 zp = 0;
3130
3131
3132 for( state=1 ; state < next_alloc ; state ++ ) {
3133 U32 base=0;
3134
3135 /*
3136 DEBUG_TRIE_COMPILE_MORE_r(
3137 Perl_re_printf( aTHX_ "tp: %d zp: %d ",tp,zp)
3138 );
3139 */
3140
3141 if (trie->states[state].trans.list) {
3142 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
3143 U16 maxid=minid;
3144 U16 idx;
3145
3146 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3147 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
3148 if ( forid < minid ) {
3149 minid=forid;
3150 } else if ( forid > maxid ) {
3151 maxid=forid;
3152 }
3153 }
3154 if ( transcount < tp + maxid - minid + 1) {
3155 transcount *= 2;
3156 trie->trans = (reg_trie_trans *)
3157 PerlMemShared_realloc( trie->trans,
3158 transcount
3159 * sizeof(reg_trie_trans) );
3160 Zero( trie->trans + (transcount / 2),
3161 transcount / 2,
3162 reg_trie_trans );
3163 }
3164 base = trie->uniquecharcount + tp - minid;
3165 if ( maxid == minid ) {
3166 U32 set = 0;
3167 for ( ; zp < tp ; zp++ ) {
3168 if ( ! trie->trans[ zp ].next ) {
3169 base = trie->uniquecharcount + zp - minid;
3170 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
3171 1).newstate;
3172 trie->trans[ zp ].check = state;
3173 set = 1;
3174 break;
3175 }
3176 }
3177 if ( !set ) {
3178 trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
3179 1).newstate;
3180 trie->trans[ tp ].check = state;
3181 tp++;
3182 zp = tp;
3183 }
3184 } else {
3185 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3186 const U32 tid = base
3187 - trie->uniquecharcount
3188 + TRIE_LIST_ITEM( state, idx ).forid;
3189 trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
3190 idx ).newstate;
3191 trie->trans[ tid ].check = state;
3192 }
3193 tp += ( maxid - minid + 1 );
3194 }
3195 Safefree(trie->states[ state ].trans.list);
3196 }
3197 /*
3198 DEBUG_TRIE_COMPILE_MORE_r(
3199 Perl_re_printf( aTHX_ " base: %d\n",base);
3200 );
3201 */
3202 trie->states[ state ].trans.base=base;
3203 }
3204 trie->lasttrans = tp + 1;
3205 }
3206 } else {
3207 /*
3208 Second Pass -- Flat Table Representation.
3209
3210 we dont use the 0 slot of either trans[] or states[] so we add 1 to
3211 each. We know that we will need Charcount+1 trans at most to store
3212 the data (one row per char at worst case) So we preallocate both
3213 structures assuming worst case.
3214
3215 We then construct the trie using only the .next slots of the entry
3216 structs.
3217
3218 We use the .check field of the first entry of the node temporarily
3219 to make compression both faster and easier by keeping track of how
3220 many non zero fields are in the node.
3221
3222 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
3223 transition.
3224
3225 There are two terms at use here: state as a TRIE_NODEIDX() which is
3226 a number representing the first entry of the node, and state as a
3227 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
3228 and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
3229 if there are 2 entrys per node. eg:
3230
3231 A B A B
3232 1. 2 4 1. 3 7
3233 2. 0 3 3. 0 5
3234 3. 0 0 5. 0 0
3235 4. 0 0 7. 0 0
3236
3237 The table is internally in the right hand, idx form. However as we
3238 also have to deal with the states array which is indexed by nodenum
3239 we have to use TRIE_NODENUM() to convert.
3240
3241 */
3242 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using table compiler\n",
3243 depth+1));
3244
3245 trie->trans = (reg_trie_trans *)
3246 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
3247 * trie->uniquecharcount + 1,
3248 sizeof(reg_trie_trans) );
3249 trie->states = (reg_trie_state *)
3250 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3251 sizeof(reg_trie_state) );
3252 next_alloc = trie->uniquecharcount + 1;
3253
3254
3255 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3256
3257 regnode *noper = NEXTOPER( cur );
3258
3259 U32 state = 1; /* required init */
3260
3261 U16 charid = 0; /* sanity init */
3262 U32 accept_state = 0; /* sanity init */
3263
3264 U32 wordlen = 0; /* required init */
3265
3266 if (OP(noper) == NOTHING) {
3267 regnode *noper_next= regnext(noper);
3268 if (noper_next < tail)
3269 noper= noper_next;
3270 /* we will undo this assignment if noper does not
3271 * point at a trieable type in the else clause of
3272 * the following statement. */
3273 }
3274
3275 if ( noper < tail
3276 && ( OP(noper) == flags
3277 || (flags == EXACT && OP(noper) == EXACT_REQ8)
3278 || (flags == EXACTFU && ( OP(noper) == EXACTFU_REQ8
3279 || OP(noper) == EXACTFUP))))
3280 {
3281 const U8 *uc= (U8*)STRING(noper);
3282 const U8 *e= uc + STR_LEN(noper);
3283
3284 for ( ; uc < e ; uc += len ) {
3285
3286 TRIE_READ_CHAR;
3287
3288 if ( uvc < 256 ) {
3289 charid = trie->charmap[ uvc ];
3290 } else {
3291 SV* const * const svpp = hv_fetch( widecharmap,
3292 (char*)&uvc,
3293 sizeof( UV ),
3294 0);
3295 charid = svpp ? (U16)SvIV(*svpp) : 0;
3296 }
3297 if ( charid ) {
3298 charid--;
3299 if ( !trie->trans[ state + charid ].next ) {
3300 trie->trans[ state + charid ].next = next_alloc;
3301 trie->trans[ state ].check++;
3302 prev_states[TRIE_NODENUM(next_alloc)]
3303 = TRIE_NODENUM(state);
3304 next_alloc += trie->uniquecharcount;
3305 }
3306 state = trie->trans[ state + charid ].next;
3307 } else {
3308 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3309 }
3310 /* charid is now 0 if we dont know the char read, or
3311 * nonzero if we do */
3312 }
3313 } else {
3314 /* If we end up here it is because we skipped past a NOTHING, but did not end up
3315 * on a trieable type. So we need to reset noper back to point at the first regop
3316 * in the branch before we call TRIE_HANDLE_WORD().
3317 */
3318 noper= NEXTOPER(cur);
3319 }
3320 accept_state = TRIE_NODENUM( state );
3321 TRIE_HANDLE_WORD(accept_state);
3322
3323 } /* end second pass */
3324
3325 /* and now dump it out before we compress it */
3326 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3327 revcharmap,
3328 next_alloc, depth+1));
3329
3330 {
3331 /*
3332 * Inplace compress the table.*
3333
3334 For sparse data sets the table constructed by the trie algorithm will
3335 be mostly 0/FAIL transitions or to put it another way mostly empty.
3336 (Note that leaf nodes will not contain any transitions.)
3337
3338 This algorithm compresses the tables by eliminating most such
3339 transitions, at the cost of a modest bit of extra work during lookup:
3340
3341 - Each states[] entry contains a .base field which indicates the
3342 index in the state[] array wheres its transition data is stored.
3343
3344 - If .base is 0 there are no valid transitions from that node.
3345
3346 - If .base is nonzero then charid is added to it to find an entry in
3347 the trans array.
3348
3349 -If trans[states[state].base+charid].check!=state then the
3350 transition is taken to be a 0/Fail transition. Thus if there are fail
3351 transitions at the front of the node then the .base offset will point
3352 somewhere inside the previous nodes data (or maybe even into a node
3353 even earlier), but the .check field determines if the transition is
3354 valid.
3355
3356 XXX - wrong maybe?
3357 The following process inplace converts the table to the compressed
3358 table: We first do not compress the root node 1,and mark all its
3359 .check pointers as 1 and set its .base pointer as 1 as well. This
3360 allows us to do a DFA construction from the compressed table later,
3361 and ensures that any .base pointers we calculate later are greater
3362 than 0.
3363
3364 - We set 'pos' to indicate the first entry of the second node.
3365
3366 - We then iterate over the columns of the node, finding the first and
3367 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3368 and set the .check pointers accordingly, and advance pos
3369 appropriately and repreat for the next node. Note that when we copy
3370 the next pointers we have to convert them from the original
3371 NODEIDX form to NODENUM form as the former is not valid post
3372 compression.
3373
3374 - If a node has no transitions used we mark its base as 0 and do not
3375 advance the pos pointer.
3376
3377 - If a node only has one transition we use a second pointer into the
3378 structure to fill in allocated fail transitions from other states.
3379 This pointer is independent of the main pointer and scans forward
3380 looking for null transitions that are allocated to a state. When it
3381 finds one it writes the single transition into the "hole". If the
3382 pointer doesnt find one the single transition is appended as normal.
3383
3384 - Once compressed we can Renew/realloc the structures to release the
3385 excess space.
3386
3387 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3388 specifically Fig 3.47 and the associated pseudocode.
3389
3390 demq
3391 */
3392 const U32 laststate = TRIE_NODENUM( next_alloc );
3393 U32 state, charid;
3394 U32 pos = 0, zp=0;
3395 trie->statecount = laststate;
3396
3397 for ( state = 1 ; state < laststate ; state++ ) {
3398 U8 flag = 0;
3399 const U32 stateidx = TRIE_NODEIDX( state );
3400 const U32 o_used = trie->trans[ stateidx ].check;
3401 U32 used = trie->trans[ stateidx ].check;
3402 trie->trans[ stateidx ].check = 0;
3403
3404 for ( charid = 0;
3405 used && charid < trie->uniquecharcount;
3406 charid++ )
3407 {
3408 if ( flag || trie->trans[ stateidx + charid ].next ) {
3409 if ( trie->trans[ stateidx + charid ].next ) {
3410 if (o_used == 1) {
3411 for ( ; zp < pos ; zp++ ) {
3412 if ( ! trie->trans[ zp ].next ) {
3413 break;
3414 }
3415 }
3416 trie->states[ state ].trans.base
3417 = zp
3418 + trie->uniquecharcount
3419 - charid ;
3420 trie->trans[ zp ].next
3421 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3422 + charid ].next );
3423 trie->trans[ zp ].check = state;
3424 if ( ++zp > pos ) pos = zp;
3425 break;
3426 }
3427 used--;
3428 }
3429 if ( !flag ) {
3430 flag = 1;
3431 trie->states[ state ].trans.base
3432 = pos + trie->uniquecharcount - charid ;
3433 }
3434 trie->trans[ pos ].next
3435 = SAFE_TRIE_NODENUM(
3436 trie->trans[ stateidx + charid ].next );
3437 trie->trans[ pos ].check = state;
3438 pos++;
3439 }
3440 }
3441 }
3442 trie->lasttrans = pos + 1;
3443 trie->states = (reg_trie_state *)
3444 PerlMemShared_realloc( trie->states, laststate
3445 * sizeof(reg_trie_state) );
3446 DEBUG_TRIE_COMPILE_MORE_r(
3447 Perl_re_indentf( aTHX_ "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
3448 depth+1,
3449 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3450 + 1 ),
3451 (IV)next_alloc,
3452 (IV)pos,
3453 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3454 );
3455
3456 } /* end table compress */
3457 }
3458 DEBUG_TRIE_COMPILE_MORE_r(
3459 Perl_re_indentf( aTHX_ "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
3460 depth+1,
3461 (UV)trie->statecount,
3462 (UV)trie->lasttrans)
3463 );
3464 /* resize the trans array to remove unused space */
3465 trie->trans = (reg_trie_trans *)
3466 PerlMemShared_realloc( trie->trans, trie->lasttrans
3467 * sizeof(reg_trie_trans) );
3468
3469 { /* Modify the program and insert the new TRIE node */
3470 U8 nodetype =(U8)(flags & 0xFF);
3471 char *str=NULL;
3472
3473#ifdef DEBUGGING
3474 regnode *optimize = NULL;
3475#ifdef RE_TRACK_PATTERN_OFFSETS
3476
3477 U32 mjd_offset = 0;
3478 U32 mjd_nodelen = 0;
3479#endif /* RE_TRACK_PATTERN_OFFSETS */
3480#endif /* DEBUGGING */
3481 /*
3482 This means we convert either the first branch or the first Exact,
3483 depending on whether the thing following (in 'last') is a branch
3484 or not and whther first is the startbranch (ie is it a sub part of
3485 the alternation or is it the whole thing.)
3486 Assuming its a sub part we convert the EXACT otherwise we convert
3487 the whole branch sequence, including the first.
3488 */
3489 /* Find the node we are going to overwrite */
3490 if ( first != startbranch || OP( last ) == BRANCH ) {
3491 /* branch sub-chain */
3492 NEXT_OFF( first ) = (U16)(last - first);
3493#ifdef RE_TRACK_PATTERN_OFFSETS
3494 DEBUG_r({
3495 mjd_offset= Node_Offset((convert));
3496 mjd_nodelen= Node_Length((convert));
3497 });
3498#endif
3499 /* whole branch chain */
3500 }
3501#ifdef RE_TRACK_PATTERN_OFFSETS
3502 else {
3503 DEBUG_r({
3504 const regnode *nop = NEXTOPER( convert );
3505 mjd_offset= Node_Offset((nop));
3506 mjd_nodelen= Node_Length((nop));
3507 });
3508 }
3509 DEBUG_OPTIMISE_r(
3510 Perl_re_indentf( aTHX_ "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
3511 depth+1,
3512 (UV)mjd_offset, (UV)mjd_nodelen)
3513 );
3514#endif
3515 /* But first we check to see if there is a common prefix we can
3516 split out as an EXACT and put in front of the TRIE node. */
3517 trie->startstate= 1;
3518 if ( trie->bitmap && !widecharmap && !trie->jump ) {
3519 /* we want to find the first state that has more than
3520 * one transition, if that state is not the first state
3521 * then we have a common prefix which we can remove.
3522 */
3523 U32 state;
3524 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3525 U32 ofs = 0;
3526 I32 first_ofs = -1; /* keeps track of the ofs of the first
3527 transition, -1 means none */
3528 U32 count = 0;
3529 const U32 base = trie->states[ state ].trans.base;
3530
3531 /* does this state terminate an alternation? */
3532 if ( trie->states[state].wordnum )
3533 count = 1;
3534
3535 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3536 if ( ( base + ofs >= trie->uniquecharcount ) &&
3537 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3538 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3539 {
3540 if ( ++count > 1 ) {
3541 /* we have more than one transition */
3542 SV **tmp;
3543 U8 *ch;
3544 /* if this is the first state there is no common prefix
3545 * to extract, so we can exit */
3546 if ( state == 1 ) break;
3547 tmp = av_fetch( revcharmap, ofs, 0);
3548 ch = (U8*)SvPV_nolen_const( *tmp );
3549
3550 /* if we are on count 2 then we need to initialize the
3551 * bitmap, and store the previous char if there was one
3552 * in it*/
3553 if ( count == 2 ) {
3554 /* clear the bitmap */
3555 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3556 DEBUG_OPTIMISE_r(
3557 Perl_re_indentf( aTHX_ "New Start State=%" UVuf " Class: [",
3558 depth+1,
3559 (UV)state));
3560 if (first_ofs >= 0) {
3561 SV ** const tmp = av_fetch( revcharmap, first_ofs, 0);
3562 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3563
3564 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3565 DEBUG_OPTIMISE_r(
3566 Perl_re_printf( aTHX_ "%s", (char*)ch)
3567 );
3568 }
3569 }
3570 /* store the current firstchar in the bitmap */
3571 TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3572 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch));
3573 }
3574 first_ofs = ofs;
3575 }
3576 }
3577 if ( count == 1 ) {
3578 /* This state has only one transition, its transition is part
3579 * of a common prefix - we need to concatenate the char it
3580 * represents to what we have so far. */
3581 SV **tmp = av_fetch( revcharmap, first_ofs, 0);
3582 STRLEN len;
3583 char *ch = SvPV( *tmp, len );
3584 DEBUG_OPTIMISE_r({
3585 SV *sv=sv_newmortal();
3586 Perl_re_indentf( aTHX_ "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n",
3587 depth+1,
3588 (UV)state, (UV)first_ofs,
3589 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3590 PL_colors[0], PL_colors[1],
3591 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3592 PERL_PV_ESCAPE_FIRSTCHAR
3593 )
3594 );
3595 });
3596 if ( state==1 ) {
3597 OP( convert ) = nodetype;
3598 str=STRING(convert);
3599 setSTR_LEN(convert, 0);
3600 }
3601 assert( ( STR_LEN(convert) + len ) < 256 );
3602 setSTR_LEN(convert, (U8)(STR_LEN(convert) + len));
3603 while (len--)
3604 *str++ = *ch++;
3605 } else {
3606#ifdef DEBUGGING
3607 if (state>1)
3608 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n"));
3609#endif
3610 break;
3611 }
3612 }
3613 trie->prefixlen = (state-1);
3614 if (str) {
3615 regnode *n = convert+NODE_SZ_STR(convert);
3616 assert( NODE_SZ_STR(convert) <= U16_MAX );
3617 NEXT_OFF(convert) = (U16)(NODE_SZ_STR(convert));
3618 trie->startstate = state;
3619 trie->minlen -= (state - 1);
3620 trie->maxlen -= (state - 1);
3621#ifdef DEBUGGING
3622 /* At least the UNICOS C compiler choked on this
3623 * being argument to DEBUG_r(), so let's just have
3624 * it right here. */
3625 if (
3626#ifdef PERL_EXT_RE_BUILD
3627 1
3628#else
3629 DEBUG_r_TEST
3630#endif
3631 ) {
3632 regnode *fix = convert;
3633 U32 word = trie->wordcount;
3634#ifdef RE_TRACK_PATTERN_OFFSETS
3635 mjd_nodelen++;
3636#endif
3637 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3638 while( ++fix < n ) {
3639 Set_Node_Offset_Length(fix, 0, 0);
3640 }
3641 while (word--) {
3642 SV ** const tmp = av_fetch( trie_words, word, 0 );
3643 if (tmp) {
3644 if ( STR_LEN(convert) <= SvCUR(*tmp) )
3645 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3646 else
3647 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3648 }
3649 }
3650 }
3651#endif
3652 if (trie->maxlen) {
3653 convert = n;
3654 } else {
3655 NEXT_OFF(convert) = (U16)(tail - convert);
3656 DEBUG_r(optimize= n);
3657 }
3658 }
3659 }
3660 if (!jumper)
3661 jumper = last;
3662 if ( trie->maxlen ) {
3663 NEXT_OFF( convert ) = (U16)(tail - convert);
3664 ARG_SET( convert, data_slot );
3665 /* Store the offset to the first unabsorbed branch in
3666 jump[0], which is otherwise unused by the jump logic.
3667 We use this when dumping a trie and during optimisation. */
3668 if (trie->jump)
3669 trie->jump[0] = (U16)(nextbranch - convert);
3670
3671 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3672 * and there is a bitmap
3673 * and the first "jump target" node we found leaves enough room
3674 * then convert the TRIE node into a TRIEC node, with the bitmap
3675 * embedded inline in the opcode - this is hypothetically faster.
3676 */
3677 if ( !trie->states[trie->startstate].wordnum
3678 && trie->bitmap
3679 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3680 {
3681 OP( convert ) = TRIEC;
3682 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3683 PerlMemShared_free(trie->bitmap);
3684 trie->bitmap= NULL;
3685 } else
3686 OP( convert ) = TRIE;
3687
3688 /* store the type in the flags */
3689 convert->flags = nodetype;
3690 DEBUG_r({
3691 optimize = convert
3692 + NODE_STEP_REGNODE
3693 + regarglen[ OP( convert ) ];
3694 });
3695 /* XXX We really should free up the resource in trie now,
3696 as we won't use them - (which resources?) dmq */
3697 }
3698 /* needed for dumping*/
3699 DEBUG_r(if (optimize) {
3700 regnode *opt = convert;
3701
3702 while ( ++opt < optimize) {
3703 Set_Node_Offset_Length(opt, 0, 0);
3704 }
3705 /*
3706 Try to clean up some of the debris left after the
3707 optimisation.
3708 */
3709 while( optimize < jumper ) {
3710 Track_Code( mjd_nodelen += Node_Length((optimize)); );
3711 OP( optimize ) = OPTIMIZED;
3712 Set_Node_Offset_Length(optimize, 0, 0);
3713 optimize++;
3714 }
3715 Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen);
3716 });
3717 } /* end node insert */
3718
3719 /* Finish populating the prev field of the wordinfo array. Walk back
3720 * from each accept state until we find another accept state, and if
3721 * so, point the first word's .prev field at the second word. If the
3722 * second already has a .prev field set, stop now. This will be the
3723 * case either if we've already processed that word's accept state,
3724 * or that state had multiple words, and the overspill words were
3725 * already linked up earlier.
3726 */
3727 {
3728 U16 word;
3729 U32 state;
3730 U16 prev;
3731
3732 for (word=1; word <= trie->wordcount; word++) {
3733 prev = 0;
3734 if (trie->wordinfo[word].prev)
3735 continue;
3736 state = trie->wordinfo[word].accept;
3737 while (state) {
3738 state = prev_states[state];
3739 if (!state)
3740 break;
3741 prev = trie->states[state].wordnum;
3742 if (prev)
3743 break;
3744 }
3745 trie->wordinfo[word].prev = prev;
3746 }
3747 Safefree(prev_states);
3748 }
3749
3750
3751 /* and now dump out the compressed format */
3752 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3753
3754 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3755#ifdef DEBUGGING
3756 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3757 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3758#else
3759 SvREFCNT_dec_NN(revcharmap);
3760#endif
3761 return trie->jump
3762 ? MADE_JUMP_TRIE
3763 : trie->startstate>1
3764 ? MADE_EXACT_TRIE
3765 : MADE_TRIE;
3766}
3767
3768STATIC regnode *
3769S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3770{
3771/* The Trie is constructed and compressed now so we can build a fail array if
3772 * it's needed
3773
3774 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3775 3.32 in the
3776 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3777 Ullman 1985/88
3778 ISBN 0-201-10088-6
3779
3780 We find the fail state for each state in the trie, this state is the longest
3781 proper suffix of the current state's 'word' that is also a proper prefix of
3782 another word in our trie. State 1 represents the word '' and is thus the
3783 default fail state. This allows the DFA not to have to restart after its
3784 tried and failed a word at a given point, it simply continues as though it
3785 had been matching the other word in the first place.
3786 Consider
3787 'abcdgu'=~/abcdefg|cdgu/
3788 When we get to 'd' we are still matching the first word, we would encounter
3789 'g' which would fail, which would bring us to the state representing 'd' in
3790 the second word where we would try 'g' and succeed, proceeding to match
3791 'cdgu'.
3792 */
3793 /* add a fail transition */
3794 const U32 trie_offset = ARG(source);
3795 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3796 U32 *q;
3797 const U32 ucharcount = trie->uniquecharcount;
3798 const U32 numstates = trie->statecount;
3799 const U32 ubound = trie->lasttrans + ucharcount;
3800 U32 q_read = 0;
3801 U32 q_write = 0;
3802 U32 charid;
3803 U32 base = trie->states[ 1 ].trans.base;
3804 U32 *fail;
3805 reg_ac_data *aho;
3806 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3807 regnode *stclass;
3808 GET_RE_DEBUG_FLAGS_DECL;
3809
3810 PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3811 PERL_UNUSED_CONTEXT;
3812#ifndef DEBUGGING
3813 PERL_UNUSED_ARG(depth);
3814#endif
3815
3816 if ( OP(source) == TRIE ) {
3817 struct regnode_1 *op = (struct regnode_1 *)
3818 PerlMemShared_calloc(1, sizeof(struct regnode_1));
3819 StructCopy(source, op, struct regnode_1);
3820 stclass = (regnode *)op;
3821 } else {
3822 struct regnode_charclass *op = (struct regnode_charclass *)
3823 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3824 StructCopy(source, op, struct regnode_charclass);
3825 stclass = (regnode *)op;
3826 }
3827 OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3828
3829 ARG_SET( stclass, data_slot );
3830 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3831 RExC_rxi->data->data[ data_slot ] = (void*)aho;
3832 aho->trie=trie_offset;
3833 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3834 Copy( trie->states, aho->states, numstates, reg_trie_state );
3835 Newx( q, numstates, U32);
3836 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3837 aho->refcount = 1;
3838 fail = aho->fail;
3839 /* initialize fail[0..1] to be 1 so that we always have
3840 a valid final fail state */
3841 fail[ 0 ] = fail[ 1 ] = 1;
3842
3843 for ( charid = 0; charid < ucharcount ; charid++ ) {
3844 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3845 if ( newstate ) {
3846 q[ q_write ] = newstate;
3847 /* set to point at the root */
3848 fail[ q[ q_write++ ] ]=1;
3849 }
3850 }
3851 while ( q_read < q_write) {
3852 const U32 cur = q[ q_read++ % numstates ];
3853 base = trie->states[ cur ].trans.base;
3854
3855 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3856 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3857 if (ch_state) {
3858 U32 fail_state = cur;
3859 U32 fail_base;
3860 do {
3861 fail_state = fail[ fail_state ];
3862 fail_base = aho->states[ fail_state ].trans.base;
3863 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3864
3865 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3866 fail[ ch_state ] = fail_state;
3867 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3868 {
3869 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
3870 }
3871 q[ q_write++ % numstates] = ch_state;
3872 }
3873 }
3874 }
3875 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3876 when we fail in state 1, this allows us to use the
3877 charclass scan to find a valid start char. This is based on the principle
3878 that theres a good chance the string being searched contains lots of stuff
3879 that cant be a start char.
3880 */
3881 fail[ 0 ] = fail[ 1 ] = 0;
3882 DEBUG_TRIE_COMPILE_r({
3883 Perl_re_indentf( aTHX_ "Stclass Failtable (%" UVuf " states): 0",
3884 depth, (UV)numstates
3885 );
3886 for( q_read=1; q_read<numstates; q_read++ ) {
3887 Perl_re_printf( aTHX_ ", %" UVuf, (UV)fail[q_read]);
3888 }
3889 Perl_re_printf( aTHX_ "\n");
3890 });
3891 Safefree(q);
3892 /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3893 return stclass;
3894}
3895
3896
3897/* The below joins as many adjacent EXACTish nodes as possible into a single
3898 * one. The regop may be changed if the node(s) contain certain sequences that
3899 * require special handling. The joining is only done if:
3900 * 1) there is room in the current conglomerated node to entirely contain the
3901 * next one.
3902 * 2) they are compatible node types
3903 *
3904 * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3905 * these get optimized out
3906 *
3907 * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3908 * as possible, even if that means splitting an existing node so that its first
3909 * part is moved to the preceeding node. This would maximise the efficiency of
3910 * memEQ during matching.
3911 *
3912 * If a node is to match under /i (folded), the number of characters it matches
3913 * can be different than its character length if it contains a multi-character
3914 * fold. *min_subtract is set to the total delta number of characters of the
3915 * input nodes.
3916 *
3917 * And *unfolded_multi_char is set to indicate whether or not the node contains
3918 * an unfolded multi-char fold. This happens when it won't be known until
3919 * runtime whether the fold is valid or not; namely
3920 * 1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the
3921 * target string being matched against turns out to be UTF-8 is that fold
3922 * valid; or
3923 * 2) for EXACTFL nodes whose folding rules depend on the locale in force at
3924 * runtime.
3925 * (Multi-char folds whose components are all above the Latin1 range are not
3926 * run-time locale dependent, and have already been folded by the time this
3927 * function is called.)
3928 *
3929 * This is as good a place as any to discuss the design of handling these
3930 * multi-character fold sequences. It's been wrong in Perl for a very long
3931 * time. There are three code points in Unicode whose multi-character folds
3932 * were long ago discovered to mess things up. The previous designs for
3933 * dealing with these involved assigning a special node for them. This
3934 * approach doesn't always work, as evidenced by this example:
3935 * "\xDFs" =~ /s\xDF/ui # Used to fail before these patches
3936 * Both sides fold to "sss", but if the pattern is parsed to create a node that
3937 * would match just the \xDF, it won't be able to handle the case where a
3938 * successful match would have to cross the node's boundary. The new approach
3939 * that hopefully generally solves the problem generates an EXACTFUP node
3940 * that is "sss" in this case.
3941 *
3942 * It turns out that there are problems with all multi-character folds, and not
3943 * just these three. Now the code is general, for all such cases. The
3944 * approach taken is:
3945 * 1) This routine examines each EXACTFish node that could contain multi-
3946 * character folded sequences. Since a single character can fold into
3947 * such a sequence, the minimum match length for this node is less than
3948 * the number of characters in the node. This routine returns in
3949 * *min_subtract how many characters to subtract from the the actual
3950 * length of the string to get a real minimum match length; it is 0 if
3951 * there are no multi-char foldeds. This delta is used by the caller to
3952 * adjust the min length of the match, and the delta between min and max,
3953 * so that the optimizer doesn't reject these possibilities based on size
3954 * constraints.
3955 *
3956 * 2) For the sequence involving the LATIN SMALL LETTER SHARP S (U+00DF)
3957 * under /u, we fold it to 'ss' in regatom(), and in this routine, after
3958 * joining, we scan for occurrences of the sequence 'ss' in non-UTF-8
3959 * EXACTFU nodes. The node type of such nodes is then changed to
3960 * EXACTFUP, indicating it is problematic, and needs careful handling.
3961 * (The procedures in step 1) above are sufficient to handle this case in
3962 * UTF-8 encoded nodes.) The reason this is problematic is that this is
3963 * the only case where there is a possible fold length change in non-UTF-8
3964 * patterns. By reserving a special node type for problematic cases, the
3965 * far more common regular EXACTFU nodes can be processed faster.
3966 * regexec.c takes advantage of this.
3967 *
3968 * EXACTFUP has been created as a grab-bag for (hopefully uncommon)
3969 * problematic cases. These all only occur when the pattern is not
3970 * UTF-8. In addition to the 'ss' sequence where there is a possible fold
3971 * length change, it handles the situation where the string cannot be
3972 * entirely folded. The strings in an EXACTFish node are folded as much
3973 * as possible during compilation in regcomp.c. This saves effort in
3974 * regex matching. By using an EXACTFUP node when it is not possible to
3975 * fully fold at compile time, regexec.c can know that everything in an
3976 * EXACTFU node is folded, so folding can be skipped at runtime. The only
3977 * case where folding in EXACTFU nodes can't be done at compile time is
3978 * the presumably uncommon MICRO SIGN, when the pattern isn't UTF-8. This
3979 * is because its fold requires UTF-8 to represent. Thus EXACTFUP nodes
3980 * handle two very different cases. Alternatively, there could have been
3981 * a node type where there are length changes, one for unfolded, and one
3982 * for both. If yet another special case needed to be created, the number
3983 * of required node types would have to go to 7. khw figures that even
3984 * though there are plenty of node types to spare, that the maintenance
3985 * cost wasn't worth the small speedup of doing it that way, especially
3986 * since he thinks the MICRO SIGN is rarely encountered in practice.
3987 *
3988 * There are other cases where folding isn't done at compile time, but
3989 * none of them are under /u, and hence not for EXACTFU nodes. The folds
3990 * in EXACTFL nodes aren't known until runtime, and vary as the locale
3991 * changes. Some folds in EXACTF depend on if the runtime target string
3992 * is UTF-8 or not. (regatom() will create an EXACTFU node even under /di
3993 * when no fold in it depends on the UTF-8ness of the target string.)
3994 *
3995 * 3) A problem remains for unfolded multi-char folds. (These occur when the
3996 * validity of the fold won't be known until runtime, and so must remain
3997 * unfolded for now. This happens for the sharp s in EXACTF and EXACTFAA
3998 * nodes when the pattern isn't in UTF-8. (Note, BTW, that there cannot
3999 * be an EXACTF node with a UTF-8 pattern.) They also occur for various
4000 * folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
4001 * The reason this is a problem is that the optimizer part of regexec.c
4002 * (probably unwittingly, in Perl_regexec_flags()) makes an assumption
4003 * that a character in the pattern corresponds to at most a single
4004 * character in the target string. (And I do mean character, and not byte
4005 * here, unlike other parts of the documentation that have never been
4006 * updated to account for multibyte Unicode.) Sharp s in EXACTF and
4007 * EXACTFL nodes can match the two character string 'ss'; in EXACTFAA
4008 * nodes it can match "\x{17F}\x{17F}". These, along with other ones in
4009 * EXACTFL nodes, violate the assumption, and they are the only instances
4010 * where it is violated. I'm reluctant to try to change the assumption,
4011 * as the code involved is impenetrable to me (khw), so instead the code
4012 * here punts. This routine examines EXACTFL nodes, and (when the pattern
4013 * isn't UTF-8) EXACTF and EXACTFAA for such unfolded folds, and returns a
4014 * boolean indicating whether or not the node contains such a fold. When
4015 * it is true, the caller sets a flag that later causes the optimizer in
4016 * this file to not set values for the floating and fixed string lengths,
4017 * and thus avoids the optimizer code in regexec.c that makes the invalid
4018 * assumption. Thus, there is no optimization based on string lengths for
4019 * EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
4020 * EXACTF and EXACTFAA nodes that contain the sharp s. (The reason the
4021 * assumption is wrong only in these cases is that all other non-UTF-8
4022 * folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
4023 * their expanded versions. (Again, we can't prefold sharp s to 'ss' in
4024 * EXACTF nodes because we don't know at compile time if it actually
4025 * matches 'ss' or not. For EXACTF nodes it will match iff the target
4026 * string is in UTF-8. This is in contrast to EXACTFU nodes, where it
4027 * always matches; and EXACTFAA where it never does. In an EXACTFAA node
4028 * in a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
4029 * problem; but in a non-UTF8 pattern, folding it to that above-Latin1
4030 * string would require the pattern to be forced into UTF-8, the overhead
4031 * of which we want to avoid. Similarly the unfolded multi-char folds in
4032 * EXACTFL nodes will match iff the locale at the time of match is a UTF-8
4033 * locale.)
4034 *
4035 * Similarly, the code that generates tries doesn't currently handle
4036 * not-already-folded multi-char folds, and it looks like a pain to change
4037 * that. Therefore, trie generation of EXACTFAA nodes with the sharp s
4038 * doesn't work. Instead, such an EXACTFAA is turned into a new regnode,
4039 * EXACTFAA_NO_TRIE, which the trie code knows not to handle. Most people
4040 * using /iaa matching will be doing so almost entirely with ASCII
4041 * strings, so this should rarely be encountered in practice */
4042
4043STATIC U32
4044S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
4045 UV *min_subtract, bool *unfolded_multi_char,
4046 U32 flags, regnode *val, U32 depth)
4047{
4048 /* Merge several consecutive EXACTish nodes into one. */
4049
4050 regnode *n = regnext(scan);
4051 U32 stringok = 1;
4052 regnode *next = scan + NODE_SZ_STR(scan);
4053 U32 merged = 0;
4054 U32 stopnow = 0;
4055#ifdef DEBUGGING
4056 regnode *stop = scan;
4057 GET_RE_DEBUG_FLAGS_DECL;
4058#else
4059 PERL_UNUSED_ARG(depth);
4060#endif
4061
4062 PERL_ARGS_ASSERT_JOIN_EXACT;
4063#ifndef EXPERIMENTAL_INPLACESCAN
4064 PERL_UNUSED_ARG(flags);
4065 PERL_UNUSED_ARG(val);
4066#endif
4067 DEBUG_PEEP("join", scan, depth, 0);
4068
4069 assert(PL_regkind[OP(scan)] == EXACT);
4070
4071 /* Look through the subsequent nodes in the chain. Skip NOTHING, merge
4072 * EXACT ones that are mergeable to the current one. */
4073 while ( n
4074 && ( PL_regkind[OP(n)] == NOTHING
4075 || (stringok && PL_regkind[OP(n)] == EXACT))
4076 && NEXT_OFF(n)
4077 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
4078 {
4079
4080 if (OP(n) == TAIL || n > next)
4081 stringok = 0;
4082 if (PL_regkind[OP(n)] == NOTHING) {
4083 DEBUG_PEEP("skip:", n, depth, 0);
4084 NEXT_OFF(scan) += NEXT_OFF(n);
4085 next = n + NODE_STEP_REGNODE;
4086#ifdef DEBUGGING
4087 if (stringok)
4088 stop = n;
4089#endif
4090 n = regnext(n);
4091 }
4092 else if (stringok) {
4093 const unsigned int oldl = STR_LEN(scan);
4094 regnode * const nnext = regnext(n);
4095
4096 /* XXX I (khw) kind of doubt that this works on platforms (should
4097 * Perl ever run on one) where U8_MAX is above 255 because of lots
4098 * of other assumptions */
4099 /* Don't join if the sum can't fit into a single node */
4100 if (oldl + STR_LEN(n) > U8_MAX)
4101 break;
4102
4103 /* Joining something that requires UTF-8 with something that
4104 * doesn't, means the result requires UTF-8. */
4105 if (OP(scan) == EXACT && (OP(n) == EXACT_REQ8)) {
4106 OP(scan) = EXACT_REQ8;
4107 }
4108 else if (OP(scan) == EXACT_REQ8 && (OP(n) == EXACT)) {
4109 ; /* join is compatible, no need to change OP */
4110 }
4111 else if ((OP(scan) == EXACTFU) && (OP(n) == EXACTFU_REQ8)) {
4112 OP(scan) = EXACTFU_REQ8;
4113 }
4114 else if ((OP(scan) == EXACTFU_REQ8) && (OP(n) == EXACTFU)) {
4115 ; /* join is compatible, no need to change OP */
4116 }
4117 else if (OP(scan) == EXACTFU && OP(n) == EXACTFU) {
4118 ; /* join is compatible, no need to change OP */
4119 }
4120 else if (OP(scan) == EXACTFU && OP(n) == EXACTFU_S_EDGE) {
4121
4122 /* Under /di, temporary EXACTFU_S_EDGE nodes are generated,
4123 * which can join with EXACTFU ones. We check for this case
4124 * here. These need to be resolved to either EXACTFU or
4125 * EXACTF at joining time. They have nothing in them that
4126 * would forbid them from being the more desirable EXACTFU
4127 * nodes except that they begin and/or end with a single [Ss].
4128 * The reason this is problematic is because they could be
4129 * joined in this loop with an adjacent node that ends and/or
4130 * begins with [Ss] which would then form the sequence 'ss',
4131 * which matches differently under /di than /ui, in which case
4132 * EXACTFU can't be used. If the 'ss' sequence doesn't get
4133 * formed, the nodes get absorbed into any adjacent EXACTFU
4134 * node. And if the only adjacent node is EXACTF, they get
4135 * absorbed into that, under the theory that a longer node is
4136 * better than two shorter ones, even if one is EXACTFU. Note
4137 * that EXACTFU_REQ8 is generated only for UTF-8 patterns,
4138 * and the EXACTFU_S_EDGE ones only for non-UTF-8. */
4139
4140 if (STRING(n)[STR_LEN(n)-1] == 's') {
4141
4142 /* Here the joined node would end with 's'. If the node
4143 * following the combination is an EXACTF one, it's better to
4144 * join this trailing edge 's' node with that one, leaving the
4145 * current one in 'scan' be the more desirable EXACTFU */
4146 if (OP(nnext) == EXACTF) {
4147 break;
4148 }
4149
4150 OP(scan) = EXACTFU_S_EDGE;
4151
4152 } /* Otherwise, the beginning 's' of the 2nd node just
4153 becomes an interior 's' in 'scan' */
4154 }
4155 else if (OP(scan) == EXACTF && OP(n) == EXACTF) {
4156 ; /* join is compatible, no need to change OP */
4157 }
4158 else if (OP(scan) == EXACTF && OP(n) == EXACTFU_S_EDGE) {
4159
4160 /* EXACTF nodes are compatible for joining with EXACTFU_S_EDGE
4161 * nodes. But the latter nodes can be also joined with EXACTFU
4162 * ones, and that is a better outcome, so if the node following
4163 * 'n' is EXACTFU, quit now so that those two can be joined
4164 * later */
4165 if (OP(nnext) == EXACTFU) {
4166 break;
4167 }
4168
4169 /* The join is compatible, and the combined node will be
4170 * EXACTF. (These don't care if they begin or end with 's' */
4171 }
4172 else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU_S_EDGE) {
4173 if ( STRING(scan)[STR_LEN(scan)-1] == 's'
4174 && STRING(n)[0] == 's')
4175 {
4176 /* When combined, we have the sequence 'ss', which means we
4177 * have to remain /di */
4178 OP(scan) = EXACTF;
4179 }
4180 }
4181 else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU) {
4182 if (STRING(n)[0] == 's') {
4183 ; /* Here the join is compatible and the combined node
4184 starts with 's', no need to change OP */
4185 }
4186 else { /* Now the trailing 's' is in the interior */
4187 OP(scan) = EXACTFU;
4188 }
4189 }
4190 else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTF) {
4191
4192 /* The join is compatible, and the combined node will be
4193 * EXACTF. (These don't care if they begin or end with 's' */
4194 OP(scan) = EXACTF;
4195 }
4196 else if (OP(scan) != OP(n)) {
4197
4198 /* The only other compatible joinings are the same node type */
4199 break;
4200 }
4201
4202 DEBUG_PEEP("merg", n, depth, 0);
4203 merged++;
4204
4205 NEXT_OFF(scan) += NEXT_OFF(n);
4206 assert( ( STR_LEN(scan) + STR_LEN(n) ) < 256 );
4207 setSTR_LEN(scan, (U8)(STR_LEN(scan) + STR_LEN(n)));
4208 next = n + NODE_SZ_STR(n);
4209 /* Now we can overwrite *n : */
4210 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
4211#ifdef DEBUGGING
4212 stop = next - 1;
4213#endif
4214 n = nnext;
4215 if (stopnow) break;
4216 }
4217
4218#ifdef EXPERIMENTAL_INPLACESCAN
4219 if (flags && !NEXT_OFF(n)) {
4220 DEBUG_PEEP("atch", val, depth, 0);
4221 if (reg_off_by_arg[OP(n)]) {
4222 ARG_SET(n, val - n);
4223 }
4224 else {
4225 NEXT_OFF(n) = val - n;
4226 }
4227 stopnow = 1;
4228 }
4229#endif
4230 }
4231
4232 /* This temporary node can now be turned into EXACTFU, and must, as
4233 * regexec.c doesn't handle it */
4234 if (OP(scan) == EXACTFU_S_EDGE) {
4235 OP(scan) = EXACTFU;
4236 }
4237
4238 *min_subtract = 0;
4239 *unfolded_multi_char = FALSE;
4240
4241 /* Here, all the adjacent mergeable EXACTish nodes have been merged. We
4242 * can now analyze for sequences of problematic code points. (Prior to
4243 * this final joining, sequences could have been split over boundaries, and
4244 * hence missed). The sequences only happen in folding, hence for any
4245 * non-EXACT EXACTish node */
4246 if (OP(scan) != EXACT && OP(scan) != EXACT_REQ8 && OP(scan) != EXACTL) {
4247 U8* s0 = (U8*) STRING(scan);
4248 U8* s = s0;
4249 U8* s_end = s0 + STR_LEN(scan);
4250
4251 int total_count_delta = 0; /* Total delta number of characters that
4252 multi-char folds expand to */
4253
4254 /* One pass is made over the node's string looking for all the
4255 * possibilities. To avoid some tests in the loop, there are two main
4256 * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
4257 * non-UTF-8 */
4258 if (UTF) {
4259 U8* folded = NULL;
4260
4261 if (OP(scan) == EXACTFL) {
4262 U8 *d;
4263
4264 /* An EXACTFL node would already have been changed to another
4265 * node type unless there is at least one character in it that
4266 * is problematic; likely a character whose fold definition
4267 * won't be known until runtime, and so has yet to be folded.
4268 * For all but the UTF-8 locale, folds are 1-1 in length, but
4269 * to handle the UTF-8 case, we need to create a temporary
4270 * folded copy using UTF-8 locale rules in order to analyze it.
4271 * This is because our macros that look to see if a sequence is
4272 * a multi-char fold assume everything is folded (otherwise the
4273 * tests in those macros would be too complicated and slow).
4274 * Note that here, the non-problematic folds will have already
4275 * been done, so we can just copy such characters. We actually
4276 * don't completely fold the EXACTFL string. We skip the
4277 * unfolded multi-char folds, as that would just create work
4278 * below to figure out the size they already are */
4279
4280 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
4281 d = folded;
4282 while (s < s_end) {
4283 STRLEN s_len = UTF8SKIP(s);
4284 if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
4285 Copy(s, d, s_len, U8);
4286 d += s_len;
4287 }
4288 else if (is_FOLDS_TO_MULTI_utf8(s)) {
4289 *unfolded_multi_char = TRUE;
4290 Copy(s, d, s_len, U8);
4291 d += s_len;
4292 }
4293 else if (isASCII(*s)) {
4294 *(d++) = toFOLD(*s);
4295 }
4296 else {
4297 STRLEN len;
4298 _toFOLD_utf8_flags(s, s_end, d, &len, FOLD_FLAGS_FULL);
4299 d += len;
4300 }
4301 s += s_len;
4302 }
4303
4304 /* Point the remainder of the routine to look at our temporary
4305 * folded copy */
4306 s = folded;
4307 s_end = d;
4308 } /* End of creating folded copy of EXACTFL string */
4309
4310 /* Examine the string for a multi-character fold sequence. UTF-8
4311 * patterns have all characters pre-folded by the time this code is
4312 * executed */
4313 while (s < s_end - 1) /* Can stop 1 before the end, as minimum
4314 length sequence we are looking for is 2 */
4315 {
4316 int count = 0; /* How many characters in a multi-char fold */
4317 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
4318 if (! len) { /* Not a multi-char fold: get next char */
4319 s += UTF8SKIP(s);
4320 continue;
4321 }
4322
4323 { /* Here is a generic multi-char fold. */
4324 U8* multi_end = s + len;
4325
4326 /* Count how many characters are in it. In the case of
4327 * /aa, no folds which contain ASCII code points are
4328 * allowed, so check for those, and skip if found. */
4329 if (OP(scan) != EXACTFAA && OP(scan) != EXACTFAA_NO_TRIE) {
4330 count = utf8_length(s, multi_end);
4331 s = multi_end;
4332 }
4333 else {
4334 while (s < multi_end) {
4335 if (isASCII(*s)) {
4336 s++;
4337 goto next_iteration;
4338 }
4339 else {
4340 s += UTF8SKIP(s);
4341 }
4342 count++;
4343 }
4344 }
4345 }
4346
4347 /* The delta is how long the sequence is minus 1 (1 is how long
4348 * the character that folds to the sequence is) */
4349 total_count_delta += count - 1;
4350 next_iteration: ;
4351 }
4352
4353 /* We created a temporary folded copy of the string in EXACTFL
4354 * nodes. Therefore we need to be sure it doesn't go below zero,
4355 * as the real string could be shorter */
4356 if (OP(scan) == EXACTFL) {
4357 int total_chars = utf8_length((U8*) STRING(scan),
4358 (U8*) STRING(scan) + STR_LEN(scan));
4359 if (total_count_delta > total_chars) {
4360 total_count_delta = total_chars;
4361 }
4362 }
4363
4364 *min_subtract += total_count_delta;
4365 Safefree(folded);
4366 }
4367 else if (OP(scan) == EXACTFAA) {
4368
4369 /* Non-UTF-8 pattern, EXACTFAA node. There can't be a multi-char
4370 * fold to the ASCII range (and there are no existing ones in the
4371 * upper latin1 range). But, as outlined in the comments preceding
4372 * this function, we need to flag any occurrences of the sharp s.
4373 * This character forbids trie formation (because of added
4374 * complexity) */
4375#if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
4376 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
4377 || UNICODE_DOT_DOT_VERSION > 0)
4378 while (s < s_end) {
4379 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
4380 OP(scan) = EXACTFAA_NO_TRIE;
4381 *unfolded_multi_char = TRUE;
4382 break;
4383 }
4384 s++;
4385 }
4386 }
4387 else {
4388
4389 /* Non-UTF-8 pattern, not EXACTFAA node. Look for the multi-char
4390 * folds that are all Latin1. As explained in the comments
4391 * preceding this function, we look also for the sharp s in EXACTF
4392 * and EXACTFL nodes; it can be in the final position. Otherwise
4393 * we can stop looking 1 byte earlier because have to find at least
4394 * two characters for a multi-fold */
4395 const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
4396 ? s_end
4397 : s_end -1;
4398
4399 while (s < upper) {
4400 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
4401 if (! len) { /* Not a multi-char fold. */
4402 if (*s == LATIN_SMALL_LETTER_SHARP_S
4403 && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
4404 {
4405 *unfolded_multi_char = TRUE;
4406 }
4407 s++;
4408 continue;
4409 }
4410
4411 if (len == 2
4412 && isALPHA_FOLD_EQ(*s, 's')
4413 && isALPHA_FOLD_EQ(*(s+1), 's'))
4414 {
4415
4416 /* EXACTF nodes need to know that the minimum length
4417 * changed so that a sharp s in the string can match this
4418 * ss in the pattern, but they remain EXACTF nodes, as they
4419 * won't match this unless the target string is is UTF-8,
4420 * which we don't know until runtime. EXACTFL nodes can't
4421 * transform into EXACTFU nodes */
4422 if (OP(scan) != EXACTF && OP(scan) != EXACTFL) {
4423 OP(scan) = EXACTFUP;
4424 }
4425 }
4426
4427 *min_subtract += len - 1;
4428 s += len;
4429 }
4430#endif
4431 }
4432 }
4433
4434#ifdef DEBUGGING
4435 /* Allow dumping but overwriting the collection of skipped
4436 * ops and/or strings with fake optimized ops */
4437 n = scan + NODE_SZ_STR(scan);
4438 while (n <= stop) {
4439 OP(n) = OPTIMIZED;
4440 FLAGS(n) = 0;
4441 NEXT_OFF(n) = 0;
4442 n++;
4443 }
4444#endif
4445 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl", scan, depth, 0);});
4446 return stopnow;
4447}
4448
4449/* REx optimizer. Converts nodes into quicker variants "in place".
4450 Finds fixed substrings. */
4451
4452/* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
4453 to the position after last scanned or to NULL. */
4454
4455#define INIT_AND_WITHP \
4456 assert(!and_withp); \
4457 Newx(and_withp, 1, regnode_ssc); \
4458 SAVEFREEPV(and_withp)
4459
4460
4461static void
4462S_unwind_scan_frames(pTHX_ const void *p)
4463{
4464 scan_frame *f= (scan_frame *)p;
4465 do {
4466 scan_frame *n= f->next_frame;
4467 Safefree(f);
4468 f= n;
4469 } while (f);
4470}
4471
4472/* the return from this sub is the minimum length that could possibly match */
4473STATIC SSize_t
4474S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
4475 SSize_t *minlenp, SSize_t *deltap,
4476 regnode *last,
4477 scan_data_t *data,
4478 I32 stopparen,
4479 U32 recursed_depth,
4480 regnode_ssc *and_withp,
4481 U32 flags, U32 depth)
4482 /* scanp: Start here (read-write). */
4483 /* deltap: Write maxlen-minlen here. */
4484 /* last: Stop before this one. */
4485 /* data: string data about the pattern */
4486 /* stopparen: treat close N as END */
4487 /* recursed: which subroutines have we recursed into */
4488 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
4489{
4490 dVAR;
4491 SSize_t final_minlen;
4492 /* There must be at least this number of characters to match */
4493 SSize_t min = 0;
4494 I32 pars = 0, code;
4495 regnode *scan = *scanp, *next;
4496 SSize_t delta = 0;
4497 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
4498 int is_inf_internal = 0; /* The studied chunk is infinite */
4499 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
4500 scan_data_t data_fake;
4501 SV *re_trie_maxbuff = NULL;
4502 regnode *first_non_open = scan;
4503 SSize_t stopmin = OPTIMIZE_INFTY;
4504 scan_frame *frame = NULL;
4505 GET_RE_DEBUG_FLAGS_DECL;
4506
4507 PERL_ARGS_ASSERT_STUDY_CHUNK;
4508 RExC_study_started= 1;
4509
4510 Zero(&data_fake, 1, scan_data_t);
4511
4512 if ( depth == 0 ) {
4513 while (first_non_open && OP(first_non_open) == OPEN)
4514 first_non_open=regnext(first_non_open);
4515 }
4516
4517
4518 fake_study_recurse:
4519 DEBUG_r(
4520 RExC_study_chunk_recursed_count++;
4521 );
4522 DEBUG_OPTIMISE_MORE_r(
4523 {
4524 Perl_re_indentf( aTHX_ "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p",
4525 depth, (long)stopparen,
4526 (unsigned long)RExC_study_chunk_recursed_count,
4527 (unsigned long)depth, (unsigned long)recursed_depth,
4528 scan,
4529 last);
4530 if (recursed_depth) {
4531 U32 i;
4532 U32 j;
4533 for ( j = 0 ; j < recursed_depth ; j++ ) {
4534 for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) {
4535 if (PAREN_TEST(j, i) && (!j || !PAREN_TEST(j - 1, i))) {
4536 Perl_re_printf( aTHX_ " %d",(int)i);
4537 break;
4538 }
4539 }
4540 if ( j + 1 < recursed_depth ) {
4541 Perl_re_printf( aTHX_ ",");
4542 }
4543 }
4544 }
4545 Perl_re_printf( aTHX_ "\n");
4546 }
4547 );
4548 while ( scan && OP(scan) != END && scan < last ){
4549 UV min_subtract = 0; /* How mmany chars to subtract from the minimum
4550 node length to get a real minimum (because
4551 the folded version may be shorter) */
4552 bool unfolded_multi_char = FALSE;
4553 /* Peephole optimizer: */
4554 DEBUG_STUDYDATA("Peep", data, depth, is_inf);
4555 DEBUG_PEEP("Peep", scan, depth, flags);
4556
4557
4558 /* The reason we do this here is that we need to deal with things like
4559 * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT
4560 * parsing code, as each (?:..) is handled by a different invocation of
4561 * reg() -- Yves
4562 */
4563 if (PL_regkind[OP(scan)] == EXACT && OP(scan) != LEXACT
4564 && OP(scan) != LEXACT_REQ8)
4565 join_exact(pRExC_state, scan, &min_subtract, &unfolded_multi_char,
4566 0, NULL, depth + 1);
4567
4568 /* Follow the next-chain of the current node and optimize
4569 away all the NOTHINGs from it. */
4570 if (OP(scan) != CURLYX) {
4571 const int max = (reg_off_by_arg[OP(scan)]
4572 ? I32_MAX
4573 /* I32 may be smaller than U16 on CRAYs! */
4574 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
4575 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
4576 int noff;
4577 regnode *n = scan;
4578
4579 /* Skip NOTHING and LONGJMP. */
4580 while ( (n = regnext(n))
4581 && ( (PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
4582 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
4583 && off + noff < max)
4584 off += noff;
4585 if (reg_off_by_arg[OP(scan)])
4586 ARG(scan) = off;
4587 else
4588 NEXT_OFF(scan) = off;
4589 }
4590
4591 /* The principal pseudo-switch. Cannot be a switch, since we look into
4592 * several different things. */
4593 if ( OP(scan) == DEFINEP ) {
4594 SSize_t minlen = 0;
4595 SSize_t deltanext = 0;
4596 SSize_t fake_last_close = 0;
4597 I32 f = SCF_IN_DEFINE;
4598
4599 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4600 scan = regnext(scan);
4601 assert( OP(scan) == IFTHEN );
4602 DEBUG_PEEP("expect IFTHEN", scan, depth, flags);
4603
4604 data_fake.last_closep= &fake_last_close;
4605 minlen = *minlenp;
4606 next = regnext(scan);
4607 scan = NEXTOPER(NEXTOPER(scan));
4608 DEBUG_PEEP("scan", scan, depth, flags);
4609 DEBUG_PEEP("next", next, depth, flags);
4610
4611 /* we suppose the run is continuous, last=next...
4612 * NOTE we dont use the return here! */
4613 /* DEFINEP study_chunk() recursion */
4614 (void)study_chunk(pRExC_state, &scan, &minlen,
4615 &deltanext, next, &data_fake, stopparen,
4616 recursed_depth, NULL, f, depth+1);
4617
4618 scan = next;
4619 } else
4620 if (
4621 OP(scan) == BRANCH ||
4622 OP(scan) == BRANCHJ ||
4623 OP(scan) == IFTHEN
4624 ) {
4625 next = regnext(scan);
4626 code = OP(scan);
4627
4628 /* The op(next)==code check below is to see if we
4629 * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN"
4630 * IFTHEN is special as it might not appear in pairs.
4631 * Not sure whether BRANCH-BRANCHJ is possible, regardless
4632 * we dont handle it cleanly. */
4633 if (OP(next) == code || code == IFTHEN) {
4634 /* NOTE - There is similar code to this block below for
4635 * handling TRIE nodes on a re-study. If you change stuff here
4636 * check there too. */
4637 SSize_t max1 = 0, min1 = OPTIMIZE_INFTY, num = 0;
4638 regnode_ssc accum;
4639 regnode * const startbranch=scan;
4640
4641 if (flags & SCF_DO_SUBSTR) {
4642 /* Cannot merge strings after this. */
4643 scan_commit(pRExC_state, data, minlenp, is_inf);
4644 }
4645
4646 if (flags & SCF_DO_STCLASS)
4647 ssc_init_zero(pRExC_state, &accum);
4648
4649 while (OP(scan) == code) {
4650 SSize_t deltanext, minnext, fake;
4651 I32 f = 0;
4652 regnode_ssc this_class;
4653
4654 DEBUG_PEEP("Branch", scan, depth, flags);
4655
4656 num++;
4657 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4658 if (data) {
4659 data_fake.whilem_c = data->whilem_c;
4660 data_fake.last_closep = data->last_closep;
4661 }
4662 else
4663 data_fake.last_closep = &fake;
4664
4665 data_fake.pos_delta = delta;
4666 next = regnext(scan);
4667
4668 scan = NEXTOPER(scan); /* everything */
4669 if (code != BRANCH) /* everything but BRANCH */
4670 scan = NEXTOPER(scan);
4671
4672 if (flags & SCF_DO_STCLASS) {
4673 ssc_init(pRExC_state, &this_class);
4674 data_fake.start_class = &this_class;
4675 f = SCF_DO_STCLASS_AND;
4676 }
4677 if (flags & SCF_WHILEM_VISITED_POS)
4678 f |= SCF_WHILEM_VISITED_POS;
4679
4680 /* we suppose the run is continuous, last=next...*/
4681 /* recurse study_chunk() for each BRANCH in an alternation */
4682 minnext = study_chunk(pRExC_state, &scan, minlenp,
4683 &deltanext, next, &data_fake, stopparen,
4684 recursed_depth, NULL, f, depth+1);
4685
4686 if (min1 > minnext)
4687 min1 = minnext;
4688 if (deltanext == OPTIMIZE_INFTY) {
4689 is_inf = is_inf_internal = 1;
4690 max1 = OPTIMIZE_INFTY;
4691 } else if (max1 < minnext + deltanext)
4692 max1 = minnext + deltanext;
4693 scan = next;
4694 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4695 pars++;
4696 if (data_fake.flags & SCF_SEEN_ACCEPT) {
4697 if ( stopmin > minnext)
4698 stopmin = min + min1;
4699 flags &= ~SCF_DO_SUBSTR;
4700 if (data)
4701 data->flags |= SCF_SEEN_ACCEPT;
4702 }
4703 if (data) {
4704 if (data_fake.flags & SF_HAS_EVAL)
4705 data->flags |= SF_HAS_EVAL;
4706 data->whilem_c = data_fake.whilem_c;
4707 }
4708 if (flags & SCF_DO_STCLASS)
4709 ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);
4710 }
4711 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
4712 min1 = 0;
4713 if (flags & SCF_DO_SUBSTR) {
4714 data->pos_min += min1;
4715 if (data->pos_delta >= OPTIMIZE_INFTY - (max1 - min1))
4716 data->pos_delta = OPTIMIZE_INFTY;
4717 else
4718 data->pos_delta += max1 - min1;
4719 if (max1 != min1 || is_inf)
4720 data->cur_is_floating = 1;
4721 }
4722 min += min1;
4723 if (delta == OPTIMIZE_INFTY
4724 || OPTIMIZE_INFTY - delta - (max1 - min1) < 0)
4725 delta = OPTIMIZE_INFTY;
4726 else
4727 delta += max1 - min1;
4728 if (flags & SCF_DO_STCLASS_OR) {
4729 ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);
4730 if (min1) {
4731 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4732 flags &= ~SCF_DO_STCLASS;
4733 }
4734 }
4735 else if (flags & SCF_DO_STCLASS_AND) {
4736 if (min1) {
4737 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
4738 flags &= ~SCF_DO_STCLASS;
4739 }
4740 else {
4741 /* Switch to OR mode: cache the old value of
4742 * data->start_class */
4743 INIT_AND_WITHP;
4744 StructCopy(data->start_class, and_withp, regnode_ssc);
4745 flags &= ~SCF_DO_STCLASS_AND;
4746 StructCopy(&accum, data->start_class, regnode_ssc);
4747 flags |= SCF_DO_STCLASS_OR;
4748 }
4749 }
4750
4751 if (PERL_ENABLE_TRIE_OPTIMISATION &&
4752 OP( startbranch ) == BRANCH )
4753 {
4754 /* demq.
4755
4756 Assuming this was/is a branch we are dealing with: 'scan'
4757 now points at the item that follows the branch sequence,
4758 whatever it is. We now start at the beginning of the
4759 sequence and look for subsequences of
4760
4761 BRANCH->EXACT=>x1
4762 BRANCH->EXACT=>x2
4763 tail
4764
4765 which would be constructed from a pattern like
4766 /A|LIST|OF|WORDS/
4767
4768 If we can find such a subsequence we need to turn the first
4769 element into a trie and then add the subsequent branch exact
4770 strings to the trie.
4771
4772 We have two cases
4773
4774 1. patterns where the whole set of branches can be
4775 converted.
4776
4777 2. patterns where only a subset can be converted.
4778
4779 In case 1 we can replace the whole set with a single regop
4780 for the trie. In case 2 we need to keep the start and end
4781 branches so
4782
4783 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
4784 becomes BRANCH TRIE; BRANCH X;
4785
4786 There is an additional case, that being where there is a
4787 common prefix, which gets split out into an EXACT like node
4788 preceding the TRIE node.
4789
4790 If x(1..n)==tail then we can do a simple trie, if not we make
4791 a "jump" trie, such that when we match the appropriate word
4792 we "jump" to the appropriate tail node. Essentially we turn
4793 a nested if into a case structure of sorts.
4794
4795 */
4796
4797 int made=0;
4798 if (!re_trie_maxbuff) {
4799 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
4800 if (!SvIOK(re_trie_maxbuff))
4801 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
4802 }
4803 if ( SvIV(re_trie_maxbuff)>=0 ) {
4804 regnode *cur;
4805 regnode *first = (regnode *)NULL;
4806 regnode *prev = (regnode *)NULL;
4807 regnode *tail = scan;
4808 U8 trietype = 0;
4809 U32 count=0;
4810
4811 /* var tail is used because there may be a TAIL
4812 regop in the way. Ie, the exacts will point to the
4813 thing following the TAIL, but the last branch will
4814 point at the TAIL. So we advance tail. If we
4815 have nested (?:) we may have to move through several
4816 tails.
4817 */
4818
4819 while ( OP( tail ) == TAIL ) {
4820 /* this is the TAIL generated by (?:) */
4821 tail = regnext( tail );
4822 }
4823
4824
4825 DEBUG_TRIE_COMPILE_r({
4826 regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);
4827 Perl_re_indentf( aTHX_ "%s %" UVuf ":%s\n",
4828 depth+1,
4829 "Looking for TRIE'able sequences. Tail node is ",
4830 (UV) REGNODE_OFFSET(tail),
4831 SvPV_nolen_const( RExC_mysv )
4832 );
4833 });
4834
4835 /*
4836
4837 Step through the branches
4838 cur represents each branch,
4839 noper is the first thing to be matched as part
4840 of that branch
4841 noper_next is the regnext() of that node.
4842
4843 We normally handle a case like this
4844 /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also
4845 support building with NOJUMPTRIE, which restricts
4846 the trie logic to structures like /FOO|BAR/.
4847
4848 If noper is a trieable nodetype then the branch is
4849 a possible optimization target. If we are building
4850 under NOJUMPTRIE then we require that noper_next is
4851 the same as scan (our current position in the regex
4852 program).
4853
4854 Once we have two or more consecutive such branches
4855 we can create a trie of the EXACT's contents and
4856 stitch it in place into the program.
4857
4858 If the sequence represents all of the branches in
4859 the alternation we replace the entire thing with a
4860 single TRIE node.
4861
4862 Otherwise when it is a subsequence we need to
4863 stitch it in place and replace only the relevant
4864 branches. This means the first branch has to remain
4865 as it is used by the alternation logic, and its
4866 next pointer, and needs to be repointed at the item
4867 on the branch chain following the last branch we
4868 have optimized away.
4869
4870 This could be either a BRANCH, in which case the
4871 subsequence is internal, or it could be the item
4872 following the branch sequence in which case the
4873 subsequence is at the end (which does not
4874 necessarily mean the first node is the start of the
4875 alternation).
4876
4877 TRIE_TYPE(X) is a define which maps the optype to a
4878 trietype.
4879
4880 optype | trietype
4881 ----------------+-----------
4882 NOTHING | NOTHING
4883 EXACT | EXACT
4884 EXACT_REQ8 | EXACT
4885 EXACTFU | EXACTFU
4886 EXACTFU_REQ8 | EXACTFU
4887 EXACTFUP | EXACTFU
4888 EXACTFAA | EXACTFAA
4889 EXACTL | EXACTL
4890 EXACTFLU8 | EXACTFLU8
4891
4892
4893 */
4894#define TRIE_TYPE(X) ( ( NOTHING == (X) ) \
4895 ? NOTHING \
4896 : ( EXACT == (X) || EXACT_REQ8 == (X) ) \
4897 ? EXACT \
4898 : ( EXACTFU == (X) \
4899 || EXACTFU_REQ8 == (X) \
4900 || EXACTFUP == (X) ) \
4901 ? EXACTFU \
4902 : ( EXACTFAA == (X) ) \
4903 ? EXACTFAA \
4904 : ( EXACTL == (X) ) \
4905 ? EXACTL \
4906 : ( EXACTFLU8 == (X) ) \
4907 ? EXACTFLU8 \
4908 : 0 )
4909
4910 /* dont use tail as the end marker for this traverse */
4911 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
4912 regnode * const noper = NEXTOPER( cur );
4913 U8 noper_type = OP( noper );
4914 U8 noper_trietype = TRIE_TYPE( noper_type );
4915#if defined(DEBUGGING) || defined(NOJUMPTRIE)
4916 regnode * const noper_next = regnext( noper );
4917 U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
4918 U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0;
4919#endif
4920
4921 DEBUG_TRIE_COMPILE_r({
4922 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4923 Perl_re_indentf( aTHX_ "- %d:%s (%d)",
4924 depth+1,
4925 REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );
4926
4927 regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);
4928 Perl_re_printf( aTHX_ " -> %d:%s",
4929 REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv));
4930
4931 if ( noper_next ) {
4932 regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);
4933 Perl_re_printf( aTHX_ "\t=> %d:%s\t",
4934 REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv));
4935 }
4936 Perl_re_printf( aTHX_ "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n",
4937 REG_NODE_NUM(first), REG_NODE_NUM(prev), REG_NODE_NUM(cur),
4938 PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]
4939 );
4940 });
4941
4942 /* Is noper a trieable nodetype that can be merged
4943 * with the current trie (if there is one)? */
4944 if ( noper_trietype
4945 &&
4946 (
4947 ( noper_trietype == NOTHING )
4948 || ( trietype == NOTHING )
4949 || ( trietype == noper_trietype )
4950 )
4951#ifdef NOJUMPTRIE
4952 && noper_next >= tail
4953#endif
4954 && count < U16_MAX)
4955 {
4956 /* Handle mergable triable node Either we are
4957 * the first node in a new trieable sequence,
4958 * in which case we do some bookkeeping,
4959 * otherwise we update the end pointer. */
4960 if ( !first ) {
4961 first = cur;
4962 if ( noper_trietype == NOTHING ) {
4963#if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
4964 regnode * const noper_next = regnext( noper );
4965 U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
4966 U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
4967#endif
4968
4969 if ( noper_next_trietype ) {
4970 trietype = noper_next_trietype;
4971 } else if (noper_next_type) {
4972 /* a NOTHING regop is 1 regop wide.
4973 * We need at least two for a trie
4974 * so we can't merge this in */
4975 first = NULL;
4976 }
4977 } else {
4978 trietype = noper_trietype;
4979 }
4980 } else {
4981 if ( trietype == NOTHING )
4982 trietype = noper_trietype;
4983 prev = cur;
4984 }
4985 if (first)
4986 count++;
4987 } /* end handle mergable triable node */
4988 else {
4989 /* handle unmergable node -
4990 * noper may either be a triable node which can
4991 * not be tried together with the current trie,
4992 * or a non triable node */
4993 if ( prev ) {
4994 /* If last is set and trietype is not
4995 * NOTHING then we have found at least two
4996 * triable branch sequences in a row of a
4997 * similar trietype so we can turn them
4998 * into a trie. If/when we allow NOTHING to
4999 * start a trie sequence this condition
5000 * will be required, and it isn't expensive
5001 * so we leave it in for now. */
5002 if ( trietype && trietype != NOTHING )
5003 make_trie( pRExC_state,
5004 startbranch, first, cur, tail,
5005 count, trietype, depth+1 );
5006 prev = NULL; /* note: we clear/update
5007 first, trietype etc below,
5008 so we dont do it here */
5009 }
5010 if ( noper_trietype
5011#ifdef NOJUMPTRIE
5012 && noper_next >= tail
5013#endif
5014 ){
5015 /* noper is triable, so we can start a new
5016 * trie sequence */
5017 count = 1;
5018 first = cur;
5019 trietype = noper_trietype;
5020 } else if (first) {
5021 /* if we already saw a first but the
5022 * current node is not triable then we have
5023 * to reset the first information. */
5024 count = 0;
5025 first = NULL;
5026 trietype = 0;
5027 }
5028 } /* end handle unmergable node */
5029 } /* loop over branches */
5030 DEBUG_TRIE_COMPILE_r({
5031 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5032 Perl_re_indentf( aTHX_ "- %s (%d) <SCAN FINISHED> ",
5033 depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
5034 Perl_re_printf( aTHX_ "(First==%d, Last==%d, Cur==%d, tt==%s)\n",
5035 REG_NODE_NUM(first), REG_NODE_NUM(prev), REG_NODE_NUM(cur),
5036 PL_reg_name[trietype]
5037 );
5038
5039 });
5040 if ( prev && trietype ) {
5041 if ( trietype != NOTHING ) {
5042 /* the last branch of the sequence was part of
5043 * a trie, so we have to construct it here
5044 * outside of the loop */
5045 made= make_trie( pRExC_state, startbranch,
5046 first, scan, tail, count,
5047 trietype, depth+1 );
5048#ifdef TRIE_STUDY_OPT
5049 if ( ((made == MADE_EXACT_TRIE &&
5050 startbranch == first)
5051 || ( first_non_open == first )) &&
5052 depth==0 ) {
5053 flags |= SCF_TRIE_RESTUDY;
5054 if ( startbranch == first
5055 && scan >= tail )
5056 {
5057 RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;
5058 }
5059 }
5060#endif
5061 } else {
5062 /* at this point we know whatever we have is a
5063 * NOTHING sequence/branch AND if 'startbranch'
5064 * is 'first' then we can turn the whole thing
5065 * into a NOTHING
5066 */
5067 if ( startbranch == first ) {
5068 regnode *opt;
5069 /* the entire thing is a NOTHING sequence,
5070 * something like this: (?:|) So we can
5071 * turn it into a plain NOTHING op. */
5072 DEBUG_TRIE_COMPILE_r({
5073 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5074 Perl_re_indentf( aTHX_ "- %s (%d) <NOTHING BRANCH SEQUENCE>\n",
5075 depth+1,
5076 SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
5077
5078 });
5079 OP(startbranch)= NOTHING;
5080 NEXT_OFF(startbranch)= tail - startbranch;
5081 for ( opt= startbranch + 1; opt < tail ; opt++ )
5082 OP(opt)= OPTIMIZED;
5083 }
5084 }
5085 } /* end if ( prev) */
5086 } /* TRIE_MAXBUF is non zero */
5087 } /* do trie */
5088
5089 }
5090 else if ( code == BRANCHJ ) { /* single branch is optimized. */
5091 scan = NEXTOPER(NEXTOPER(scan));
5092 } else /* single branch is optimized. */
5093 scan = NEXTOPER(scan);
5094 continue;
5095 } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) {
5096 I32 paren = 0;
5097 regnode *start = NULL;
5098 regnode *end = NULL;
5099 U32 my_recursed_depth= recursed_depth;
5100
5101 if (OP(scan) != SUSPEND) { /* GOSUB */
5102 /* Do setup, note this code has side effects beyond
5103 * the rest of this block. Specifically setting
5104 * RExC_recurse[] must happen at least once during
5105 * study_chunk(). */
5106 paren = ARG(scan);
5107 RExC_recurse[ARG2L(scan)] = scan;
5108 start = REGNODE_p(RExC_open_parens[paren]);
5109 end = REGNODE_p(RExC_close_parens[paren]);
5110
5111 /* NOTE we MUST always execute the above code, even
5112 * if we do nothing with a GOSUB */
5113 if (
5114 ( flags & SCF_IN_DEFINE )
5115 ||
5116 (
5117 (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))
5118 &&
5119 ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )
5120 )
5121 ) {
5122 /* no need to do anything here if we are in a define. */
5123 /* or we are after some kind of infinite construct
5124 * so we can skip recursing into this item.
5125 * Since it is infinite we will not change the maxlen
5126 * or delta, and if we miss something that might raise
5127 * the minlen it will merely pessimise a little.
5128 *
5129 * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/
5130 * might result in a minlen of 1 and not of 4,
5131 * but this doesn't make us mismatch, just try a bit
5132 * harder than we should.
5133 * */
5134 scan= regnext(scan);
5135 continue;
5136 }
5137
5138 if (
5139 !recursed_depth
5140 || !PAREN_TEST(recursed_depth - 1, paren)
5141 ) {
5142 /* it is quite possible that there are more efficient ways
5143 * to do this. We maintain a bitmap per level of recursion
5144 * of which patterns we have entered so we can detect if a
5145 * pattern creates a possible infinite loop. When we
5146 * recurse down a level we copy the previous levels bitmap
5147 * down. When we are at recursion level 0 we zero the top
5148 * level bitmap. It would be nice to implement a different
5149 * more efficient way of doing this. In particular the top
5150 * level bitmap may be unnecessary.
5151 */
5152 if (!recursed_depth) {
5153 Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);
5154 } else {
5155 Copy(PAREN_OFFSET(recursed_depth - 1),
5156 PAREN_OFFSET(recursed_depth),
5157 RExC_study_chunk_recursed_bytes, U8);
5158 }
5159 /* we havent recursed into this paren yet, so recurse into it */
5160 DEBUG_STUDYDATA("gosub-set", data, depth, is_inf);
5161 PAREN_SET(recursed_depth, paren);
5162 my_recursed_depth= recursed_depth + 1;
5163 } else {
5164 DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf);
5165 /* some form of infinite recursion, assume infinite length
5166 * */
5167 if (flags & SCF_DO_SUBSTR) {
5168 scan_commit(pRExC_state, data, minlenp, is_inf);
5169 data->cur_is_floating = 1;
5170 }
5171 is_inf = is_inf_internal = 1;
5172 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5173 ssc_anything(data->start_class);
5174 flags &= ~SCF_DO_STCLASS;
5175
5176 start= NULL; /* reset start so we dont recurse later on. */
5177 }
5178 } else {
5179 paren = stopparen;
5180 start = scan + 2;
5181 end = regnext(scan);
5182 }
5183 if (start) {
5184 scan_frame *newframe;
5185 assert(end);
5186 if (!RExC_frame_last) {
5187 Newxz(newframe, 1, scan_frame);
5188 SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);
5189 RExC_frame_head= newframe;
5190 RExC_frame_count++;
5191 } else if (!RExC_frame_last->next_frame) {
5192 Newxz(newframe, 1, scan_frame);
5193 RExC_frame_last->next_frame= newframe;
5194 newframe->prev_frame= RExC_frame_last;
5195 RExC_frame_count++;
5196 } else {
5197 newframe= RExC_frame_last->next_frame;
5198 }
5199 RExC_frame_last= newframe;
5200
5201 newframe->next_regnode = regnext(scan);
5202 newframe->last_regnode = last;
5203 newframe->stopparen = stopparen;
5204 newframe->prev_recursed_depth = recursed_depth;
5205 newframe->this_prev_frame= frame;
5206
5207 DEBUG_STUDYDATA("frame-new", data, depth, is_inf);
5208 DEBUG_PEEP("fnew", scan, depth, flags);
5209
5210 frame = newframe;
5211 scan = start;
5212 stopparen = paren;
5213 last = end;
5214 depth = depth + 1;
5215 recursed_depth= my_recursed_depth;
5216
5217 continue;
5218 }
5219 }
5220 else if ( OP(scan) == EXACT
5221 || OP(scan) == LEXACT
5222 || OP(scan) == EXACT_REQ8
5223 || OP(scan) == LEXACT_REQ8
5224 || OP(scan) == EXACTL)
5225 {
5226 SSize_t bytelen = STR_LEN(scan), charlen;
5227 UV uc;
5228 assert(bytelen);
5229 if (UTF) {
5230 const U8 * const s = (U8*)STRING(scan);
5231 uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
5232 charlen = utf8_length(s, s + bytelen);
5233 } else {
5234 uc = *((U8*)STRING(scan));
5235 charlen = bytelen;
5236 }
5237 min += charlen;
5238 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
5239 /* The code below prefers earlier match for fixed
5240 offset, later match for variable offset. */
5241 if (data->last_end == -1) { /* Update the start info. */
5242 data->last_start_min = data->pos_min;
5243 data->last_start_max = is_inf
5244 ? OPTIMIZE_INFTY : data->pos_min + data->pos_delta;
5245 }
5246 sv_catpvn(data->last_found, STRING(scan), bytelen);
5247 if (UTF)
5248 SvUTF8_on(data->last_found);
5249 {
5250 SV * const sv = data->last_found;
5251 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5252 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5253 if (mg && mg->mg_len >= 0)
5254 mg->mg_len += charlen;
5255 }
5256 data->last_end = data->pos_min + charlen;
5257 data->pos_min += charlen; /* As in the first entry. */
5258 data->flags &= ~SF_BEFORE_EOL;
5259 }
5260
5261 /* ANDing the code point leaves at most it, and not in locale, and
5262 * can't match null string */
5263 if (flags & SCF_DO_STCLASS_AND) {
5264 ssc_cp_and(data->start_class, uc);
5265 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5266 ssc_clear_locale(data->start_class);
5267 }
5268 else if (flags & SCF_DO_STCLASS_OR) {
5269 ssc_add_cp(data->start_class, uc);
5270 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5271
5272 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5273 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5274 }
5275 flags &= ~SCF_DO_STCLASS;
5276 }
5277 else if (PL_regkind[OP(scan)] == EXACT) {
5278 /* But OP != EXACT!, so is EXACTFish */
5279 SSize_t bytelen = STR_LEN(scan), charlen;
5280 const U8 * s = (U8*)STRING(scan);
5281
5282 /* Replace a length 1 ASCII fold pair node with an ANYOFM node,
5283 * with the mask set to the complement of the bit that differs
5284 * between upper and lower case, and the lowest code point of the
5285 * pair (which the '&' forces) */
5286 if ( bytelen == 1
5287 && isALPHA_A(*s)
5288 && ( OP(scan) == EXACTFAA
5289 || ( OP(scan) == EXACTFU
5290 && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(*s))))
5291 {
5292 U8 mask = ~ ('A' ^ 'a'); /* These differ in just one bit */
5293
5294 OP(scan) = ANYOFM;
5295 ARG_SET(scan, *s & mask);
5296 FLAGS(scan) = mask;
5297 /* we're not EXACTFish any more, so restudy */
5298 continue;
5299 }
5300
5301 /* Search for fixed substrings supports EXACT only. */
5302 if (flags & SCF_DO_SUBSTR) {
5303 assert(data);
5304 scan_commit(pRExC_state, data, minlenp, is_inf);
5305 }
5306 charlen = UTF ? (SSize_t) utf8_length(s, s + bytelen) : bytelen;
5307 if (unfolded_multi_char) {
5308 RExC_seen |= REG_UNFOLDED_MULTI_SEEN;
5309 }
5310 min += charlen - min_subtract;
5311 assert (min >= 0);
5312 delta += min_subtract;
5313 if (flags & SCF_DO_SUBSTR) {
5314 data->pos_min += charlen - min_subtract;
5315 if (data->pos_min < 0) {
5316 data->pos_min = 0;
5317 }
5318 data->pos_delta += min_subtract;
5319 if (min_subtract) {
5320 data->cur_is_floating = 1; /* float */
5321 }
5322 }
5323
5324 if (flags & SCF_DO_STCLASS) {
5325 SV* EXACTF_invlist = make_exactf_invlist(pRExC_state, scan);
5326
5327 assert(EXACTF_invlist);
5328 if (flags & SCF_DO_STCLASS_AND) {
5329 if (OP(scan) != EXACTFL)
5330 ssc_clear_locale(data->start_class);
5331 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5332 ANYOF_POSIXL_ZERO(data->start_class);
5333 ssc_intersection(data->start_class, EXACTF_invlist, FALSE);
5334 }
5335 else { /* SCF_DO_STCLASS_OR */
5336 ssc_union(data->start_class, EXACTF_invlist, FALSE);
5337 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5338
5339 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5340 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5341 }
5342 flags &= ~SCF_DO_STCLASS;
5343 SvREFCNT_dec(EXACTF_invlist);
5344 }
5345 }
5346 else if (REGNODE_VARIES(OP(scan))) {
5347 SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;
5348 I32 fl = 0, f = flags;
5349 regnode * const oscan = scan;
5350 regnode_ssc this_class;
5351 regnode_ssc *oclass = NULL;
5352 I32 next_is_eval = 0;
5353
5354 switch (PL_regkind[OP(scan)]) {
5355 case WHILEM: /* End of (?:...)* . */
5356 scan = NEXTOPER(scan);
5357 goto finish;
5358 case PLUS:
5359 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
5360 next = NEXTOPER(scan);
5361 if ( OP(next) == EXACT
5362 || OP(next) == LEXACT
5363 || OP(next) == EXACT_REQ8
5364 || OP(next) == LEXACT_REQ8
5365 || OP(next) == EXACTL
5366 || (flags & SCF_DO_STCLASS))
5367 {
5368 mincount = 1;
5369 maxcount = REG_INFTY;
5370 next = regnext(scan);
5371 scan = NEXTOPER(scan);
5372 goto do_curly;
5373 }
5374 }
5375 if (flags & SCF_DO_SUBSTR)
5376 data->pos_min++;
5377 min++;
5378 /* FALLTHROUGH */
5379 case STAR:
5380 next = NEXTOPER(scan);
5381
5382 /* This temporary node can now be turned into EXACTFU, and
5383 * must, as regexec.c doesn't handle it */
5384 if (OP(next) == EXACTFU_S_EDGE) {
5385 OP(next) = EXACTFU;
5386 }
5387
5388 if ( STR_LEN(next) == 1
5389 && isALPHA_A(* STRING(next))
5390 && ( OP(next) == EXACTFAA
5391 || ( OP(next) == EXACTFU
5392 && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next)))))
5393 {
5394 /* These differ in just one bit */
5395 U8 mask = ~ ('A' ^ 'a');
5396
5397 assert(isALPHA_A(* STRING(next)));
5398
5399 /* Then replace it by an ANYOFM node, with
5400 * the mask set to the complement of the
5401 * bit that differs between upper and lower
5402 * case, and the lowest code point of the
5403 * pair (which the '&' forces) */
5404 OP(next) = ANYOFM;
5405 ARG_SET(next, *STRING(next) & mask);
5406 FLAGS(next) = mask;
5407 }
5408
5409 if (flags & SCF_DO_STCLASS) {
5410 mincount = 0;
5411 maxcount = REG_INFTY;
5412 next = regnext(scan);
5413 scan = NEXTOPER(scan);
5414 goto do_curly;
5415 }
5416 if (flags & SCF_DO_SUBSTR) {
5417 scan_commit(pRExC_state, data, minlenp, is_inf);
5418 /* Cannot extend fixed substrings */
5419 data->cur_is_floating = 1; /* float */
5420 }
5421 is_inf = is_inf_internal = 1;
5422 scan = regnext(scan);
5423 goto optimize_curly_tail;
5424 case CURLY:
5425 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
5426 && (scan->flags == stopparen))
5427 {
5428 mincount = 1;
5429 maxcount = 1;
5430 } else {
5431 mincount = ARG1(scan);
5432 maxcount = ARG2(scan);
5433 }
5434 next = regnext(scan);
5435 if (OP(scan) == CURLYX) {
5436 I32 lp = (data ? *(data->last_closep) : 0);
5437 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
5438 }
5439 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
5440 next_is_eval = (OP(scan) == EVAL);
5441 do_curly:
5442 if (flags & SCF_DO_SUBSTR) {
5443 if (mincount == 0)
5444 scan_commit(pRExC_state, data, minlenp, is_inf);
5445 /* Cannot extend fixed substrings */
5446 pos_before = data->pos_min;
5447 }
5448 if (data) {
5449 fl = data->flags;
5450 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
5451 if (is_inf)
5452 data->flags |= SF_IS_INF;
5453 }
5454 if (flags & SCF_DO_STCLASS) {
5455 ssc_init(pRExC_state, &this_class);
5456 oclass = data->start_class;
5457 data->start_class = &this_class;
5458 f |= SCF_DO_STCLASS_AND;
5459 f &= ~SCF_DO_STCLASS_OR;
5460 }
5461 /* Exclude from super-linear cache processing any {n,m}
5462 regops for which the combination of input pos and regex
5463 pos is not enough information to determine if a match
5464 will be possible.
5465
5466 For example, in the regex /foo(bar\s*){4,8}baz/ with the
5467 regex pos at the \s*, the prospects for a match depend not
5468 only on the input position but also on how many (bar\s*)
5469 repeats into the {4,8} we are. */
5470 if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
5471 f &= ~SCF_WHILEM_VISITED_POS;
5472
5473 /* This will finish on WHILEM, setting scan, or on NULL: */
5474 /* recurse study_chunk() on loop bodies */
5475 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
5476 last, data, stopparen, recursed_depth, NULL,
5477 (mincount == 0
5478 ? (f & ~SCF_DO_SUBSTR)
5479 : f)
5480 ,depth+1);
5481
5482 if (flags & SCF_DO_STCLASS)
5483 data->start_class = oclass;
5484 if (mincount == 0 || minnext == 0) {
5485 if (flags & SCF_DO_STCLASS_OR) {
5486 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5487 }
5488 else if (flags & SCF_DO_STCLASS_AND) {
5489 /* Switch to OR mode: cache the old value of
5490 * data->start_class */
5491 INIT_AND_WITHP;
5492 StructCopy(data->start_class, and_withp, regnode_ssc);
5493 flags &= ~SCF_DO_STCLASS_AND;
5494 StructCopy(&this_class, data->start_class, regnode_ssc);
5495 flags |= SCF_DO_STCLASS_OR;
5496 ANYOF_FLAGS(data->start_class)
5497 |= SSC_MATCHES_EMPTY_STRING;
5498 }
5499 } else { /* Non-zero len */
5500 if (flags & SCF_DO_STCLASS_OR) {
5501 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5502 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5503 }
5504 else if (flags & SCF_DO_STCLASS_AND)
5505 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5506 flags &= ~SCF_DO_STCLASS;
5507 }
5508 if (!scan) /* It was not CURLYX, but CURLY. */
5509 scan = next;
5510 if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR)
5511 /* ? quantifier ok, except for (?{ ... }) */
5512 && (next_is_eval || !(mincount == 0 && maxcount == 1))
5513 && (minnext == 0) && (deltanext == 0)
5514 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
5515 && maxcount <= REG_INFTY/3) /* Complement check for big
5516 count */
5517 {
5518 _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP),
5519 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
5520 "Quantifier unexpected on zero-length expression "
5521 "in regex m/%" UTF8f "/",
5522 UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,
5523 RExC_precomp)));
5524 }
5525
5526 min += minnext * mincount;
5527 is_inf_internal |= deltanext == OPTIMIZE_INFTY
5528 || (maxcount == REG_INFTY && minnext + deltanext > 0);
5529 is_inf |= is_inf_internal;
5530 if (is_inf) {
5531 delta = OPTIMIZE_INFTY;
5532 } else {
5533 delta += (minnext + deltanext) * maxcount
5534 - minnext * mincount;
5535 }
5536 /* Try powerful optimization CURLYX => CURLYN. */
5537 if ( OP(oscan) == CURLYX && data
5538 && data->flags & SF_IN_PAR
5539 && !(data->flags & SF_HAS_EVAL)
5540 && !deltanext && minnext == 1 ) {
5541 /* Try to optimize to CURLYN. */
5542 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
5543 regnode * const nxt1 = nxt;
5544#ifdef DEBUGGING
5545 regnode *nxt2;
5546#endif
5547
5548 /* Skip open. */
5549 nxt = regnext(nxt);
5550 if (!REGNODE_SIMPLE(OP(nxt))
5551 && !(PL_regkind[OP(nxt)] == EXACT
5552 && STR_LEN(nxt) == 1))
5553 goto nogo;
5554#ifdef DEBUGGING
5555 nxt2 = nxt;
5556#endif
5557 nxt = regnext(nxt);
5558 if (OP(nxt) != CLOSE)
5559 goto nogo;
5560 if (RExC_open_parens) {
5561
5562 /*open->CURLYM*/
5563 RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5564
5565 /*close->while*/
5566 RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2;
5567 }
5568 /* Now we know that nxt2 is the only contents: */
5569 oscan->flags = (U8)ARG(nxt);
5570 OP(oscan) = CURLYN;
5571 OP(nxt1) = NOTHING; /* was OPEN. */
5572
5573#ifdef DEBUGGING
5574 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5575 NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
5576 NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
5577 OP(nxt) = OPTIMIZED; /* was CLOSE. */
5578 OP(nxt + 1) = OPTIMIZED; /* was count. */
5579 NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
5580#endif
5581 }
5582 nogo:
5583
5584 /* Try optimization CURLYX => CURLYM. */
5585 if ( OP(oscan) == CURLYX && data
5586 && !(data->flags & SF_HAS_PAR)
5587 && !(data->flags & SF_HAS_EVAL)
5588 && !deltanext /* atom is fixed width */
5589 && minnext != 0 /* CURLYM can't handle zero width */
5590
5591 /* Nor characters whose fold at run-time may be
5592 * multi-character */
5593 && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)
5594 ) {
5595 /* XXXX How to optimize if data == 0? */
5596 /* Optimize to a simpler form. */
5597 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
5598 regnode *nxt2;
5599
5600 OP(oscan) = CURLYM;
5601 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
5602 && (OP(nxt2) != WHILEM))
5603 nxt = nxt2;
5604 OP(nxt2) = SUCCEED; /* Whas WHILEM */
5605 /* Need to optimize away parenths. */
5606 if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
5607 /* Set the parenth number. */
5608 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
5609
5610 oscan->flags = (U8)ARG(nxt);
5611 if (RExC_open_parens) {
5612 /*open->CURLYM*/
5613 RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5614
5615 /*close->NOTHING*/
5616 RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2)
5617 + 1;
5618 }
5619 OP(nxt1) = OPTIMIZED; /* was OPEN. */
5620 OP(nxt) = OPTIMIZED; /* was CLOSE. */
5621
5622#ifdef DEBUGGING
5623 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5624 OP(nxt + 1) = OPTIMIZED; /* was count. */
5625 NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
5626 NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
5627#endif
5628#if 0
5629 while ( nxt1 && (OP(nxt1) != WHILEM)) {
5630 regnode *nnxt = regnext(nxt1);
5631 if (nnxt == nxt) {
5632 if (reg_off_by_arg[OP(nxt1)])
5633 ARG_SET(nxt1, nxt2 - nxt1);
5634 else if (nxt2 - nxt1 < U16_MAX)
5635 NEXT_OFF(nxt1) = nxt2 - nxt1;
5636 else
5637 OP(nxt) = NOTHING; /* Cannot beautify */
5638 }
5639 nxt1 = nnxt;
5640 }
5641#endif
5642 /* Optimize again: */
5643 /* recurse study_chunk() on optimised CURLYX => CURLYM */
5644 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
5645 NULL, stopparen, recursed_depth, NULL, 0,
5646 depth+1);
5647 }
5648 else
5649 oscan->flags = 0;
5650 }
5651 else if ((OP(oscan) == CURLYX)
5652 && (flags & SCF_WHILEM_VISITED_POS)
5653 /* See the comment on a similar expression above.
5654 However, this time it's not a subexpression
5655 we care about, but the expression itself. */
5656 && (maxcount == REG_INFTY)
5657 && data) {
5658 /* This stays as CURLYX, we can put the count/of pair. */
5659 /* Find WHILEM (as in regexec.c) */
5660 regnode *nxt = oscan + NEXT_OFF(oscan);
5661
5662 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
5663 nxt += ARG(nxt);
5664 nxt = PREVOPER(nxt);
5665 if (nxt->flags & 0xf) {
5666 /* we've already set whilem count on this node */
5667 } else if (++data->whilem_c < 16) {
5668 assert(data->whilem_c <= RExC_whilem_seen);
5669 nxt->flags = (U8)(data->whilem_c
5670 | (RExC_whilem_seen << 4)); /* On WHILEM */
5671 }
5672 }
5673 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
5674 pars++;
5675 if (flags & SCF_DO_SUBSTR) {
5676 SV *last_str = NULL;
5677 STRLEN last_chrs = 0;
5678 int counted = mincount != 0;
5679
5680 if (data->last_end > 0 && mincount != 0) { /* Ends with a
5681 string. */
5682 SSize_t b = pos_before >= data->last_start_min
5683 ? pos_before : data->last_start_min;
5684 STRLEN l;
5685 const char * const s = SvPV_const(data->last_found, l);
5686 SSize_t old = b - data->last_start_min;
5687 assert(old >= 0);
5688
5689 if (UTF)
5690 old = utf8_hop_forward((U8*)s, old,
5691 (U8 *) SvEND(data->last_found))
5692 - (U8*)s;
5693 l -= old;
5694 /* Get the added string: */
5695 last_str = newSVpvn_utf8(s + old, l, UTF);
5696 last_chrs = UTF ? utf8_length((U8*)(s + old),
5697 (U8*)(s + old + l)) : l;
5698 if (deltanext == 0 && pos_before == b) {
5699 /* What was added is a constant string */
5700 if (mincount > 1) {
5701
5702 SvGROW(last_str, (mincount * l) + 1);
5703 repeatcpy(SvPVX(last_str) + l,
5704 SvPVX_const(last_str), l,
5705 mincount - 1);
5706 SvCUR_set(last_str, SvCUR(last_str) * mincount);
5707 /* Add additional parts. */
5708 SvCUR_set(data->last_found,
5709 SvCUR(data->last_found) - l);
5710 sv_catsv(data->last_found, last_str);
5711 {
5712 SV * sv = data->last_found;
5713 MAGIC *mg =
5714 SvUTF8(sv) && SvMAGICAL(sv) ?
5715 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5716 if (mg && mg->mg_len >= 0)
5717 mg->mg_len += last_chrs * (mincount-1);
5718 }
5719 last_chrs *= mincount;
5720 data->last_end += l * (mincount - 1);
5721 }
5722 } else {
5723 /* start offset must point into the last copy */
5724 data->last_start_min += minnext * (mincount - 1);
5725 data->last_start_max =
5726 is_inf
5727 ? OPTIMIZE_INFTY
5728 : data->last_start_max +
5729 (maxcount - 1) * (minnext + data->pos_delta);
5730 }
5731 }
5732 /* It is counted once already... */
5733 data->pos_min += minnext * (mincount - counted);
5734#if 0
5735Perl_re_printf( aTHX_ "counted=%" UVuf " deltanext=%" UVuf
5736 " OPTIMIZE_INFTY=%" UVuf " minnext=%" UVuf
5737 " maxcount=%" UVuf " mincount=%" UVuf "\n",
5738 (UV)counted, (UV)deltanext, (UV)OPTIMIZE_INFTY, (UV)minnext, (UV)maxcount,
5739 (UV)mincount);
5740if (deltanext != OPTIMIZE_INFTY)
5741Perl_re_printf( aTHX_ "LHS=%" UVuf " RHS=%" UVuf "\n",
5742 (UV)(-counted * deltanext + (minnext + deltanext) * maxcount
5743 - minnext * mincount), (UV)(OPTIMIZE_INFTY - data->pos_delta));
5744#endif
5745 if (deltanext == OPTIMIZE_INFTY
5746 || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= OPTIMIZE_INFTY - data->pos_delta)
5747 data->pos_delta = OPTIMIZE_INFTY;
5748 else
5749 data->pos_delta += - counted * deltanext +
5750 (minnext + deltanext) * maxcount - minnext * mincount;
5751 if (mincount != maxcount) {
5752 /* Cannot extend fixed substrings found inside
5753 the group. */
5754 scan_commit(pRExC_state, data, minlenp, is_inf);
5755 if (mincount && last_str) {
5756 SV * const sv = data->last_found;
5757 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5758 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5759
5760 if (mg)
5761 mg->mg_len = -1;
5762 sv_setsv(sv, last_str);
5763 data->last_end = data->pos_min;
5764 data->last_start_min = data->pos_min - last_chrs;
5765 data->last_start_max = is_inf
5766 ? OPTIMIZE_INFTY
5767 : data->pos_min + data->pos_delta - last_chrs;
5768 }
5769 data->cur_is_floating = 1; /* float */
5770 }
5771 SvREFCNT_dec(last_str);
5772 }
5773 if (data && (fl & SF_HAS_EVAL))
5774 data->flags |= SF_HAS_EVAL;
5775 optimize_curly_tail:
5776 if (OP(oscan) != CURLYX) {
5777 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
5778 && NEXT_OFF(next))
5779 NEXT_OFF(oscan) += NEXT_OFF(next);
5780 }
5781 continue;
5782
5783 default:
5784 Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d",
5785 OP(scan));
5786 case REF:
5787 case CLUMP:
5788 if (flags & SCF_DO_SUBSTR) {
5789 /* Cannot expect anything... */
5790 scan_commit(pRExC_state, data, minlenp, is_inf);
5791 data->cur_is_floating = 1; /* float */
5792 }
5793 is_inf = is_inf_internal = 1;
5794 if (flags & SCF_DO_STCLASS_OR) {
5795 if (OP(scan) == CLUMP) {
5796 /* Actually is any start char, but very few code points
5797 * aren't start characters */
5798 ssc_match_all_cp(data->start_class);
5799 }
5800 else {
5801 ssc_anything(data->start_class);
5802 }
5803 }
5804 flags &= ~SCF_DO_STCLASS;
5805 break;
5806 }
5807 }
5808 else if (OP(scan) == LNBREAK) {
5809 if (flags & SCF_DO_STCLASS) {
5810 if (flags & SCF_DO_STCLASS_AND) {
5811 ssc_intersection(data->start_class,
5812 PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);
5813 ssc_clear_locale(data->start_class);
5814 ANYOF_FLAGS(data->start_class)
5815 &= ~SSC_MATCHES_EMPTY_STRING;
5816 }
5817 else if (flags & SCF_DO_STCLASS_OR) {
5818 ssc_union(data->start_class,
5819 PL_XPosix_ptrs[_CC_VERTSPACE],
5820 FALSE);
5821 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5822
5823 /* See commit msg for
5824 * 749e076fceedeb708a624933726e7989f2302f6a */
5825 ANYOF_FLAGS(data->start_class)
5826 &= ~SSC_MATCHES_EMPTY_STRING;
5827 }
5828 flags &= ~SCF_DO_STCLASS;
5829 }
5830 min++;
5831 if (delta != OPTIMIZE_INFTY)
5832 delta++; /* Because of the 2 char string cr-lf */
5833 if (flags & SCF_DO_SUBSTR) {
5834 /* Cannot expect anything... */
5835 scan_commit(pRExC_state, data, minlenp, is_inf);
5836 data->pos_min += 1;
5837 if (data->pos_delta != OPTIMIZE_INFTY) {
5838 data->pos_delta += 1;
5839 }
5840 data->cur_is_floating = 1; /* float */
5841 }
5842 }
5843 else if (REGNODE_SIMPLE(OP(scan))) {
5844
5845 if (flags & SCF_DO_SUBSTR) {
5846 scan_commit(pRExC_state, data, minlenp, is_inf);
5847 data->pos_min++;
5848 }
5849 min++;
5850 if (flags & SCF_DO_STCLASS) {
5851 bool invert = 0;
5852 SV* my_invlist = NULL;
5853 U8 namedclass;
5854
5855 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5856 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5857
5858 /* Some of the logic below assumes that switching
5859 locale on will only add false positives. */
5860 switch (OP(scan)) {
5861
5862 default:
5863#ifdef DEBUGGING
5864 Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d",
5865 OP(scan));
5866#endif
5867 case SANY:
5868 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5869 ssc_match_all_cp(data->start_class);
5870 break;
5871
5872 case REG_ANY:
5873 {
5874 SV* REG_ANY_invlist = _new_invlist(2);
5875 REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,
5876 '\n');
5877 if (flags & SCF_DO_STCLASS_OR) {
5878 ssc_union(data->start_class,
5879 REG_ANY_invlist,
5880 TRUE /* TRUE => invert, hence all but \n
5881 */
5882 );
5883 }
5884 else if (flags & SCF_DO_STCLASS_AND) {
5885 ssc_intersection(data->start_class,
5886 REG_ANY_invlist,
5887 TRUE /* TRUE => invert */
5888 );
5889 ssc_clear_locale(data->start_class);
5890 }
5891 SvREFCNT_dec_NN(REG_ANY_invlist);
5892 }
5893 break;
5894
5895 case ANYOFD:
5896 case ANYOFL:
5897 case ANYOFPOSIXL:
5898 case ANYOFH:
5899 case ANYOFHb:
5900 case ANYOFHr:
5901 case ANYOFHs:
5902 case ANYOF:
5903 if (flags & SCF_DO_STCLASS_AND)
5904 ssc_and(pRExC_state, data->start_class,
5905 (regnode_charclass *) scan);
5906 else
5907 ssc_or(pRExC_state, data->start_class,
5908 (regnode_charclass *) scan);
5909 break;
5910
5911 case NANYOFM:
5912 case ANYOFM:
5913 {
5914 SV* cp_list = get_ANYOFM_contents(scan);
5915
5916 if (flags & SCF_DO_STCLASS_OR) {
5917 ssc_union(data->start_class, cp_list, invert);
5918 }
5919 else if (flags & SCF_DO_STCLASS_AND) {
5920 ssc_intersection(data->start_class, cp_list, invert);
5921 }
5922
5923 SvREFCNT_dec_NN(cp_list);
5924 break;
5925 }
5926
5927 case ANYOFR:
5928 case ANYOFRb:
5929 {
5930 SV* cp_list = NULL;
5931
5932 cp_list = _add_range_to_invlist(cp_list,
5933 ANYOFRbase(scan),
5934 ANYOFRbase(scan) + ANYOFRdelta(scan));
5935
5936 if (flags & SCF_DO_STCLASS_OR) {
5937 ssc_union(data->start_class, cp_list, invert);
5938 }
5939 else if (flags & SCF_DO_STCLASS_AND) {
5940 ssc_intersection(data->start_class, cp_list, invert);
5941 }
5942
5943 SvREFCNT_dec_NN(cp_list);
5944 break;
5945 }
5946
5947 case NPOSIXL:
5948 invert = 1;
5949 /* FALLTHROUGH */
5950
5951 case POSIXL:
5952 namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;
5953 if (flags & SCF_DO_STCLASS_AND) {
5954 bool was_there = cBOOL(
5955 ANYOF_POSIXL_TEST(data->start_class,
5956 namedclass));
5957 ANYOF_POSIXL_ZERO(data->start_class);
5958 if (was_there) { /* Do an AND */
5959 ANYOF_POSIXL_SET(data->start_class, namedclass);
5960 }
5961 /* No individual code points can now match */
5962 data->start_class->invlist
5963 = sv_2mortal(_new_invlist(0));
5964 }
5965 else {
5966 int complement = namedclass + ((invert) ? -1 : 1);
5967
5968 assert(flags & SCF_DO_STCLASS_OR);
5969
5970 /* If the complement of this class was already there,
5971 * the result is that they match all code points,
5972 * (\d + \D == everything). Remove the classes from
5973 * future consideration. Locale is not relevant in
5974 * this case */
5975 if (ANYOF_POSIXL_TEST(data->start_class, complement)) {
5976 ssc_match_all_cp(data->start_class);
5977 ANYOF_POSIXL_CLEAR(data->start_class, namedclass);
5978 ANYOF_POSIXL_CLEAR(data->start_class, complement);
5979 }
5980 else { /* The usual case; just add this class to the
5981 existing set */
5982 ANYOF_POSIXL_SET(data->start_class, namedclass);
5983 }
5984 }
5985 break;
5986
5987 case NPOSIXA: /* For these, we always know the exact set of
5988 what's matched */
5989 invert = 1;
5990 /* FALLTHROUGH */
5991 case POSIXA:
5992 my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL);
5993 goto join_posix_and_ascii;
5994
5995 case NPOSIXD:
5996 case NPOSIXU:
5997 invert = 1;
5998 /* FALLTHROUGH */
5999 case POSIXD:
6000 case POSIXU:
6001 my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL);
6002
6003 /* NPOSIXD matches all upper Latin1 code points unless the
6004 * target string being matched is UTF-8, which is
6005 * unknowable until match time. Since we are going to
6006 * invert, we want to get rid of all of them so that the
6007 * inversion will match all */
6008 if (OP(scan) == NPOSIXD) {
6009 _invlist_subtract(my_invlist, PL_UpperLatin1,
6010 &my_invlist);
6011 }
6012
6013 join_posix_and_ascii:
6014
6015 if (flags & SCF_DO_STCLASS_AND) {
6016 ssc_intersection(data->start_class, my_invlist, invert);
6017 ssc_clear_locale(data->start_class);
6018 }
6019 else {
6020 assert(flags & SCF_DO_STCLASS_OR);
6021 ssc_union(data->start_class, my_invlist, invert);
6022 }
6023 SvREFCNT_dec(my_invlist);
6024 }
6025 if (flags & SCF_DO_STCLASS_OR)
6026 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6027 flags &= ~SCF_DO_STCLASS;
6028 }
6029 }
6030 else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
6031 data->flags |= (OP(scan) == MEOL
6032 ? SF_BEFORE_MEOL
6033 : SF_BEFORE_SEOL);
6034 scan_commit(pRExC_state, data, minlenp, is_inf);
6035
6036 }
6037 else if ( PL_regkind[OP(scan)] == BRANCHJ
6038 /* Lookbehind, or need to calculate parens/evals/stclass: */
6039 && (scan->flags || data || (flags & SCF_DO_STCLASS))
6040 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM))
6041 {
6042 if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
6043 || OP(scan) == UNLESSM )
6044 {
6045 /* Negative Lookahead/lookbehind
6046 In this case we can't do fixed string optimisation.
6047 */
6048
6049 SSize_t deltanext, minnext, fake = 0;
6050 regnode *nscan;
6051 regnode_ssc intrnl;
6052 int f = 0;
6053
6054 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6055 if (data) {
6056 data_fake.whilem_c = data->whilem_c;
6057 data_fake.last_closep = data->last_closep;
6058 }
6059 else
6060 data_fake.last_closep = &fake;
6061 data_fake.pos_delta = delta;
6062 if ( flags & SCF_DO_STCLASS && !scan->flags
6063 && OP(scan) == IFMATCH ) { /* Lookahead */
6064 ssc_init(pRExC_state, &intrnl);
6065 data_fake.start_class = &intrnl;
6066 f |= SCF_DO_STCLASS_AND;
6067 }
6068 if (flags & SCF_WHILEM_VISITED_POS)
6069 f |= SCF_WHILEM_VISITED_POS;
6070 next = regnext(scan);
6071 nscan = NEXTOPER(NEXTOPER(scan));
6072
6073 /* recurse study_chunk() for lookahead body */
6074 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
6075 last, &data_fake, stopparen,
6076 recursed_depth, NULL, f, depth+1);
6077 if (scan->flags) {
6078 if ( deltanext < 0
6079 || deltanext > (I32) U8_MAX
6080 || minnext > (I32)U8_MAX
6081 || minnext + deltanext > (I32)U8_MAX)
6082 {
6083 FAIL2("Lookbehind longer than %" UVuf " not implemented",
6084 (UV)U8_MAX);
6085 }
6086
6087 /* The 'next_off' field has been repurposed to count the
6088 * additional starting positions to try beyond the initial
6089 * one. (This leaves it at 0 for non-variable length
6090 * matches to avoid breakage for those not using this
6091 * extension) */
6092 if (deltanext) {
6093 scan->next_off = deltanext;
6094 ckWARNexperimental(RExC_parse,
6095 WARN_EXPERIMENTAL__VLB,
6096 "Variable length lookbehind is experimental");
6097 }
6098 scan->flags = (U8)minnext + deltanext;
6099 }
6100 if (data) {
6101 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6102 pars++;
6103 if (data_fake.flags & SF_HAS_EVAL)
6104 data->flags |= SF_HAS_EVAL;
6105 data->whilem_c = data_fake.whilem_c;
6106 }
6107 if (f & SCF_DO_STCLASS_AND) {
6108 if (flags & SCF_DO_STCLASS_OR) {
6109 /* OR before, AND after: ideally we would recurse with
6110 * data_fake to get the AND applied by study of the
6111 * remainder of the pattern, and then derecurse;
6112 * *** HACK *** for now just treat as "no information".
6113 * See [perl #56690].
6114 */
6115 ssc_init(pRExC_state, data->start_class);
6116 } else {
6117 /* AND before and after: combine and continue. These
6118 * assertions are zero-length, so can match an EMPTY
6119 * string */
6120 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6121 ANYOF_FLAGS(data->start_class)
6122 |= SSC_MATCHES_EMPTY_STRING;
6123 }
6124 }
6125 }
6126#if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
6127 else {
6128 /* Positive Lookahead/lookbehind
6129 In this case we can do fixed string optimisation,
6130 but we must be careful about it. Note in the case of
6131 lookbehind the positions will be offset by the minimum
6132 length of the pattern, something we won't know about
6133 until after the recurse.
6134 */
6135 SSize_t deltanext, fake = 0;
6136 regnode *nscan;
6137 regnode_ssc intrnl;
6138 int f = 0;
6139 /* We use SAVEFREEPV so that when the full compile
6140 is finished perl will clean up the allocated
6141 minlens when it's all done. This way we don't
6142 have to worry about freeing them when we know
6143 they wont be used, which would be a pain.
6144 */
6145 SSize_t *minnextp;
6146 Newx( minnextp, 1, SSize_t );
6147 SAVEFREEPV(minnextp);
6148
6149 if (data) {
6150 StructCopy(data, &data_fake, scan_data_t);
6151 if ((flags & SCF_DO_SUBSTR) && data->last_found) {
6152 f |= SCF_DO_SUBSTR;
6153 if (scan->flags)
6154 scan_commit(pRExC_state, &data_fake, minlenp, is_inf);
6155 data_fake.last_found=newSVsv(data->last_found);
6156 }
6157 }
6158 else
6159 data_fake.last_closep = &fake;
6160 data_fake.flags = 0;
6161 data_fake.substrs[0].flags = 0;
6162 data_fake.substrs[1].flags = 0;
6163 data_fake.pos_delta = delta;
6164 if (is_inf)
6165 data_fake.flags |= SF_IS_INF;
6166 if ( flags & SCF_DO_STCLASS && !scan->flags
6167 && OP(scan) == IFMATCH ) { /* Lookahead */
6168 ssc_init(pRExC_state, &intrnl);
6169 data_fake.start_class = &intrnl;
6170 f |= SCF_DO_STCLASS_AND;
6171 }
6172 if (flags & SCF_WHILEM_VISITED_POS)
6173 f |= SCF_WHILEM_VISITED_POS;
6174 next = regnext(scan);
6175 nscan = NEXTOPER(NEXTOPER(scan));
6176
6177 /* positive lookahead study_chunk() recursion */
6178 *minnextp = study_chunk(pRExC_state, &nscan, minnextp,
6179 &deltanext, last, &data_fake,
6180 stopparen, recursed_depth, NULL,
6181 f, depth+1);
6182 if (scan->flags) {
6183 assert(0); /* This code has never been tested since this
6184 is normally not compiled */
6185 if ( deltanext < 0
6186 || deltanext > (I32) U8_MAX
6187 || *minnextp > (I32)U8_MAX
6188 || *minnextp + deltanext > (I32)U8_MAX)
6189 {
6190 FAIL2("Lookbehind longer than %" UVuf " not implemented",
6191 (UV)U8_MAX);
6192 }
6193
6194 if (deltanext) {
6195 scan->next_off = deltanext;
6196 }
6197 scan->flags = (U8)*minnextp + deltanext;
6198 }
6199
6200 *minnextp += min;
6201
6202 if (f & SCF_DO_STCLASS_AND) {
6203 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6204 ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;
6205 }
6206 if (data) {
6207 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6208 pars++;
6209 if (data_fake.flags & SF_HAS_EVAL)
6210 data->flags |= SF_HAS_EVAL;
6211 data->whilem_c = data_fake.whilem_c;
6212 if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
6213 int i;
6214 if (RExC_rx->minlen<*minnextp)
6215 RExC_rx->minlen=*minnextp;
6216 scan_commit(pRExC_state, &data_fake, minnextp, is_inf);
6217 SvREFCNT_dec_NN(data_fake.last_found);
6218
6219 for (i = 0; i < 2; i++) {
6220 if (data_fake.substrs[i].minlenp != minlenp) {
6221 data->substrs[i].min_offset =
6222 data_fake.substrs[i].min_offset;
6223 data->substrs[i].max_offset =
6224 data_fake.substrs[i].max_offset;
6225 data->substrs[i].minlenp =
6226 data_fake.substrs[i].minlenp;
6227 data->substrs[i].lookbehind += scan->flags;
6228 }
6229 }
6230 }
6231 }
6232 }
6233#endif
6234 }
6235 else if (OP(scan) == OPEN) {
6236 if (stopparen != (I32)ARG(scan))
6237 pars++;
6238 }
6239 else if (OP(scan) == CLOSE) {
6240 if (stopparen == (I32)ARG(scan)) {
6241 break;
6242 }
6243 if ((I32)ARG(scan) == is_par) {
6244 next = regnext(scan);
6245
6246 if ( next && (OP(next) != WHILEM) && next < last)
6247 is_par = 0; /* Disable optimization */
6248 }
6249 if (data)
6250 *(data->last_closep) = ARG(scan);
6251 }
6252 else if (OP(scan) == EVAL) {
6253 if (data)
6254 data->flags |= SF_HAS_EVAL;
6255 }
6256 else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
6257 if (flags & SCF_DO_SUBSTR) {
6258 scan_commit(pRExC_state, data, minlenp, is_inf);
6259 flags &= ~SCF_DO_SUBSTR;
6260 }
6261 if (data && OP(scan)==ACCEPT) {
6262 data->flags |= SCF_SEEN_ACCEPT;
6263 if (stopmin > min)
6264 stopmin = min;
6265 }
6266 }
6267 else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
6268 {
6269 if (flags & SCF_DO_SUBSTR) {
6270 scan_commit(pRExC_state, data, minlenp, is_inf);
6271 data->cur_is_floating = 1; /* float */
6272 }
6273 is_inf = is_inf_internal = 1;
6274 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
6275 ssc_anything(data->start_class);
6276 flags &= ~SCF_DO_STCLASS;
6277 }
6278 else if (OP(scan) == GPOS) {
6279 if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&
6280 !(delta || is_inf || (data && data->pos_delta)))
6281 {
6282 if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))
6283 RExC_rx->intflags |= PREGf_ANCH_GPOS;
6284 if (RExC_rx->gofs < (STRLEN)min)
6285 RExC_rx->gofs = min;
6286 } else {
6287 RExC_rx->intflags |= PREGf_GPOS_FLOAT;
6288 RExC_rx->gofs = 0;
6289 }
6290 }
6291#ifdef TRIE_STUDY_OPT
6292#ifdef FULL_TRIE_STUDY
6293 else if (PL_regkind[OP(scan)] == TRIE) {
6294 /* NOTE - There is similar code to this block above for handling
6295 BRANCH nodes on the initial study. If you change stuff here
6296 check there too. */
6297 regnode *trie_node= scan;
6298 regnode *tail= regnext(scan);
6299 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6300 SSize_t max1 = 0, min1 = OPTIMIZE_INFTY;
6301 regnode_ssc accum;
6302
6303 if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */
6304 /* Cannot merge strings after this. */
6305 scan_commit(pRExC_state, data, minlenp, is_inf);
6306 }
6307 if (flags & SCF_DO_STCLASS)
6308 ssc_init_zero(pRExC_state, &accum);
6309
6310 if (!trie->jump) {
6311 min1= trie->minlen;
6312 max1= trie->maxlen;
6313 } else {
6314 const regnode *nextbranch= NULL;
6315 U32 word;
6316
6317 for ( word=1 ; word <= trie->wordcount ; word++)
6318 {
6319 SSize_t deltanext=0, minnext=0, f = 0, fake;
6320 regnode_ssc this_class;
6321
6322 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6323 if (data) {
6324 data_fake.whilem_c = data->whilem_c;
6325 data_fake.last_closep = data->last_closep;
6326 }
6327 else
6328 data_fake.last_closep = &fake;
6329 data_fake.pos_delta = delta;
6330 if (flags & SCF_DO_STCLASS) {
6331 ssc_init(pRExC_state, &this_class);
6332 data_fake.start_class = &this_class;
6333 f = SCF_DO_STCLASS_AND;
6334 }
6335 if (flags & SCF_WHILEM_VISITED_POS)
6336 f |= SCF_WHILEM_VISITED_POS;
6337
6338 if (trie->jump[word]) {
6339 if (!nextbranch)
6340 nextbranch = trie_node + trie->jump[0];
6341 scan= trie_node + trie->jump[word];
6342 /* We go from the jump point to the branch that follows
6343 it. Note this means we need the vestigal unused
6344 branches even though they arent otherwise used. */
6345 /* optimise study_chunk() for TRIE */
6346 minnext = study_chunk(pRExC_state, &scan, minlenp,
6347 &deltanext, (regnode *)nextbranch, &data_fake,
6348 stopparen, recursed_depth, NULL, f, depth+1);
6349 }
6350 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
6351 nextbranch= regnext((regnode*)nextbranch);
6352
6353 if (min1 > (SSize_t)(minnext + trie->minlen))
6354 min1 = minnext + trie->minlen;
6355 if (deltanext == OPTIMIZE_INFTY) {
6356 is_inf = is_inf_internal = 1;
6357 max1 = OPTIMIZE_INFTY;
6358 } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))
6359 max1 = minnext + deltanext + trie->maxlen;
6360
6361 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6362 pars++;
6363 if (data_fake.flags & SCF_SEEN_ACCEPT) {
6364 if ( stopmin > min + min1)
6365 stopmin = min + min1;
6366 flags &= ~SCF_DO_SUBSTR;
6367 if (data)
6368 data->flags |= SCF_SEEN_ACCEPT;
6369 }
6370 if (data) {
6371 if (data_fake.flags & SF_HAS_EVAL)
6372 data->flags |= SF_HAS_EVAL;
6373 data->whilem_c = data_fake.whilem_c;
6374 }
6375 if (flags & SCF_DO_STCLASS)
6376 ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);
6377 }
6378 }
6379 if (flags & SCF_DO_SUBSTR) {
6380 data->pos_min += min1;
6381 data->pos_delta += max1 - min1;
6382 if (max1 != min1 || is_inf)
6383 data->cur_is_floating = 1; /* float */
6384 }
6385 min += min1;
6386 if (delta != OPTIMIZE_INFTY) {
6387 if (OPTIMIZE_INFTY - (max1 - min1) >= delta)
6388 delta += max1 - min1;
6389 else
6390 delta = OPTIMIZE_INFTY;
6391 }
6392 if (flags & SCF_DO_STCLASS_OR) {
6393 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6394 if (min1) {
6395 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6396 flags &= ~SCF_DO_STCLASS;
6397 }
6398 }
6399 else if (flags & SCF_DO_STCLASS_AND) {
6400 if (min1) {
6401 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6402 flags &= ~SCF_DO_STCLASS;
6403 }
6404 else {
6405 /* Switch to OR mode: cache the old value of
6406 * data->start_class */
6407 INIT_AND_WITHP;
6408 StructCopy(data->start_class, and_withp, regnode_ssc);
6409 flags &= ~SCF_DO_STCLASS_AND;
6410 StructCopy(&accum, data->start_class, regnode_ssc);
6411 flags |= SCF_DO_STCLASS_OR;
6412 }
6413 }
6414 scan= tail;
6415 continue;
6416 }
6417#else
6418 else if (PL_regkind[OP(scan)] == TRIE) {
6419 reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6420 U8*bang=NULL;
6421
6422 min += trie->minlen;
6423 delta += (trie->maxlen - trie->minlen);
6424 flags &= ~SCF_DO_STCLASS; /* xxx */
6425 if (flags & SCF_DO_SUBSTR) {
6426 /* Cannot expect anything... */
6427 scan_commit(pRExC_state, data, minlenp, is_inf);
6428 data->pos_min += trie->minlen;
6429 data->pos_delta += (trie->maxlen - trie->minlen);
6430 if (trie->maxlen != trie->minlen)
6431 data->cur_is_floating = 1; /* float */
6432 }
6433 if (trie->jump) /* no more substrings -- for now /grr*/
6434 flags &= ~SCF_DO_SUBSTR;
6435 }
6436 else if (OP(scan) == REGEX_SET) {
6437 Perl_croak(aTHX_ "panic: %s regnode should be resolved"
6438 " before optimization", reg_name[REGEX_SET]);
6439 }
6440
6441#endif /* old or new */
6442#endif /* TRIE_STUDY_OPT */
6443
6444 /* Else: zero-length, ignore. */
6445 scan = regnext(scan);
6446 }
6447
6448 finish:
6449 if (frame) {
6450 /* we need to unwind recursion. */
6451 depth = depth - 1;
6452
6453 DEBUG_STUDYDATA("frame-end", data, depth, is_inf);
6454 DEBUG_PEEP("fend", scan, depth, flags);
6455
6456 /* restore previous context */
6457 last = frame->last_regnode;
6458 scan = frame->next_regnode;
6459 stopparen = frame->stopparen;
6460 recursed_depth = frame->prev_recursed_depth;
6461
6462 RExC_frame_last = frame->prev_frame;
6463 frame = frame->this_prev_frame;
6464 goto fake_study_recurse;
6465 }
6466
6467 assert(!frame);
6468 DEBUG_STUDYDATA("pre-fin", data, depth, is_inf);
6469
6470 *scanp = scan;
6471 *deltap = is_inf_internal ? OPTIMIZE_INFTY : delta;
6472
6473 if (flags & SCF_DO_SUBSTR && is_inf)
6474 data->pos_delta = OPTIMIZE_INFTY - data->pos_min;
6475 if (is_par > (I32)U8_MAX)
6476 is_par = 0;
6477 if (is_par && pars==1 && data) {
6478 data->flags |= SF_IN_PAR;
6479 data->flags &= ~SF_HAS_PAR;
6480 }
6481 else if (pars && data) {
6482 data->flags |= SF_HAS_PAR;
6483 data->flags &= ~SF_IN_PAR;
6484 }
6485 if (flags & SCF_DO_STCLASS_OR)
6486 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6487 if (flags & SCF_TRIE_RESTUDY)
6488 data->flags |= SCF_TRIE_RESTUDY;
6489
6490 DEBUG_STUDYDATA("post-fin", data, depth, is_inf);
6491
6492 final_minlen = min < stopmin
6493 ? min : stopmin;
6494
6495 if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {
6496 if (final_minlen > OPTIMIZE_INFTY - delta)
6497 RExC_maxlen = OPTIMIZE_INFTY;
6498 else if (RExC_maxlen < final_minlen + delta)
6499 RExC_maxlen = final_minlen + delta;
6500 }
6501 return final_minlen;
6502}
6503
6504STATIC U32
6505S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n)
6506{
6507 U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
6508
6509 PERL_ARGS_ASSERT_ADD_DATA;
6510
6511 Renewc(RExC_rxi->data,
6512 sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
6513 char, struct reg_data);
6514 if(count)
6515 Renew(RExC_rxi->data->what, count + n, U8);
6516 else
6517 Newx(RExC_rxi->data->what, n, U8);
6518 RExC_rxi->data->count = count + n;
6519 Copy(s, RExC_rxi->data->what + count, n, U8);
6520 return count;
6521}
6522
6523/*XXX: todo make this not included in a non debugging perl, but appears to be
6524 * used anyway there, in 'use re' */
6525#ifndef PERL_IN_XSUB_RE
6526void
6527Perl_reginitcolors(pTHX)
6528{
6529 const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
6530 if (s) {
6531 char *t = savepv(s);
6532 int i = 0;
6533 PL_colors[0] = t;
6534 while (++i < 6) {
6535 t = strchr(t, '\t');
6536 if (t) {
6537 *t = '\0';
6538 PL_colors[i] = ++t;
6539 }
6540 else
6541 PL_colors[i] = t = (char *)"";
6542 }
6543 } else {
6544 int i = 0;
6545 while (i < 6)
6546 PL_colors[i++] = (char *)"";
6547 }
6548 PL_colorset = 1;
6549}
6550#endif
6551
6552
6553#ifdef TRIE_STUDY_OPT
6554#define CHECK_RESTUDY_GOTO_butfirst(dOsomething) \
6555 STMT_START { \
6556 if ( \
6557 (data.flags & SCF_TRIE_RESTUDY) \
6558 && ! restudied++ \
6559 ) { \
6560 dOsomething; \
6561 goto reStudy; \
6562 } \
6563 } STMT_END
6564#else
6565#define CHECK_RESTUDY_GOTO_butfirst
6566#endif
6567
6568/*
6569 * pregcomp - compile a regular expression into internal code
6570 *
6571 * Decides which engine's compiler to call based on the hint currently in
6572 * scope
6573 */
6574
6575#ifndef PERL_IN_XSUB_RE
6576
6577/* return the currently in-scope regex engine (or the default if none) */
6578
6579regexp_engine const *
6580Perl_current_re_engine(pTHX)
6581{
6582 if (IN_PERL_COMPILETIME) {
6583 HV * const table = GvHV(PL_hintgv);
6584 SV **ptr;
6585
6586 if (!table || !(PL_hints & HINT_LOCALIZE_HH))
6587 return &PL_core_reg_engine;
6588 ptr = hv_fetchs(table, "regcomp", FALSE);
6589 if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
6590 return &PL_core_reg_engine;
6591 return INT2PTR(regexp_engine*, SvIV(*ptr));
6592 }
6593 else {
6594 SV *ptr;
6595 if (!PL_curcop->cop_hints_hash)
6596 return &PL_core_reg_engine;
6597 ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
6598 if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
6599 return &PL_core_reg_engine;
6600 return INT2PTR(regexp_engine*, SvIV(ptr));
6601 }
6602}
6603
6604
6605REGEXP *
6606Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
6607{
6608 regexp_engine const *eng = current_re_engine();
6609 GET_RE_DEBUG_FLAGS_DECL;
6610
6611 PERL_ARGS_ASSERT_PREGCOMP;
6612
6613 /* Dispatch a request to compile a regexp to correct regexp engine. */
6614 DEBUG_COMPILE_r({
6615 Perl_re_printf( aTHX_ "Using engine %" UVxf "\n",
6616 PTR2UV(eng));
6617 });
6618 return CALLREGCOMP_ENG(eng, pattern, flags);
6619}
6620#endif
6621
6622/* public(ish) entry point for the perl core's own regex compiling code.
6623 * It's actually a wrapper for Perl_re_op_compile that only takes an SV
6624 * pattern rather than a list of OPs, and uses the internal engine rather
6625 * than the current one */
6626
6627REGEXP *
6628Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
6629{
6630 PERL_ARGS_ASSERT_RE_COMPILE;
6631 return re_op_compile_wrapper(pattern, rx_flags, 0);
6632}
6633
6634REGEXP *
6635S_re_op_compile_wrapper(pTHX_ SV * const pattern, U32 rx_flags, const U32 pm_flags)
6636{
6637 SV *pat = pattern; /* defeat constness! */
6638
6639 PERL_ARGS_ASSERT_RE_OP_COMPILE_WRAPPER;
6640
6641 return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
6642#ifdef PERL_IN_XSUB_RE
6643 &my_reg_engine,
6644#else
6645 &PL_core_reg_engine,
6646#endif
6647 NULL, NULL, rx_flags, pm_flags);
6648}
6649
6650
6651static void
6652S_free_codeblocks(pTHX_ struct reg_code_blocks *cbs)
6653{
6654 int n;
6655
6656 if (--cbs->refcnt > 0)
6657 return;
6658 for (n = 0; n < cbs->count; n++) {
6659 REGEXP *rx = cbs->cb[n].src_regex;
6660 if (rx) {
6661 cbs->cb[n].src_regex = NULL;
6662 SvREFCNT_dec_NN(rx);
6663 }
6664 }
6665 Safefree(cbs->cb);
6666 Safefree(cbs);
6667}
6668
6669
6670static struct reg_code_blocks *
6671S_alloc_code_blocks(pTHX_ int ncode)
6672{
6673 struct reg_code_blocks *cbs;
6674 Newx(cbs, 1, struct reg_code_blocks);
6675 cbs->count = ncode;
6676 cbs->refcnt = 1;
6677 SAVEDESTRUCTOR_X(S_free_codeblocks, cbs);
6678 if (ncode)
6679 Newx(cbs->cb, ncode, struct reg_code_block);
6680 else
6681 cbs->cb = NULL;
6682 return cbs;
6683}
6684
6685
6686/* upgrade pattern pat_p of length plen_p to UTF8, and if there are code
6687 * blocks, recalculate the indices. Update pat_p and plen_p in-place to
6688 * point to the realloced string and length.
6689 *
6690 * This is essentially a copy of Perl_bytes_to_utf8() with the code index
6691 * stuff added */
6692
6693static void
6694S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state,
6695 char **pat_p, STRLEN *plen_p, int num_code_blocks)
6696{
6697 U8 *const src = (U8*)*pat_p;
6698 U8 *dst, *d;
6699 int n=0;
6700 STRLEN s = 0;
6701 bool do_end = 0;
6702 GET_RE_DEBUG_FLAGS_DECL;
6703
6704 DEBUG_PARSE_r(Perl_re_printf( aTHX_
6705 "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
6706
6707 /* 1 for each byte + 1 for each byte that expands to two, + trailing NUL */
6708 Newx(dst, *plen_p + variant_under_utf8_count(src, src + *plen_p) + 1, U8);
6709 d = dst;
6710
6711 while (s < *plen_p) {
6712 append_utf8_from_native_byte(src[s], &d);
6713
6714 if (n < num_code_blocks) {
6715 assert(pRExC_state->code_blocks);
6716 if (!do_end && pRExC_state->code_blocks->cb[n].start == s) {
6717 pRExC_state->code_blocks->cb[n].start = d - dst - 1;
6718 assert(*(d - 1) == '(');
6719 do_end = 1;
6720 }
6721 else if (do_end && pRExC_state->code_blocks->cb[n].end == s) {
6722 pRExC_state->code_blocks->cb[n].end = d - dst - 1;
6723 assert(*(d - 1) == ')');
6724 do_end = 0;
6725 n++;
6726 }
6727 }
6728 s++;
6729 }
6730 *d = '\0';
6731 *plen_p = d - dst;
6732 *pat_p = (char*) dst;
6733 SAVEFREEPV(*pat_p);
6734 RExC_orig_utf8 = RExC_utf8 = 1;
6735}
6736
6737
6738
6739/* S_concat_pat(): concatenate a list of args to the pattern string pat,
6740 * while recording any code block indices, and handling overloading,
6741 * nested qr// objects etc. If pat is null, it will allocate a new
6742 * string, or just return the first arg, if there's only one.
6743 *
6744 * Returns the malloced/updated pat.
6745 * patternp and pat_count is the array of SVs to be concatted;
6746 * oplist is the optional list of ops that generated the SVs;
6747 * recompile_p is a pointer to a boolean that will be set if
6748 * the regex will need to be recompiled.
6749 * delim, if non-null is an SV that will be inserted between each element
6750 */
6751
6752static SV*
6753S_concat_pat(pTHX_ RExC_state_t * const pRExC_state,
6754 SV *pat, SV ** const patternp, int pat_count,
6755 OP *oplist, bool *recompile_p, SV *delim)
6756{
6757 SV **svp;
6758 int n = 0;
6759 bool use_delim = FALSE;
6760 bool alloced = FALSE;
6761
6762 /* if we know we have at least two args, create an empty string,
6763 * then concatenate args to that. For no args, return an empty string */
6764 if (!pat && pat_count != 1) {
6765 pat = newSVpvs("");
6766 SAVEFREESV(pat);
6767 alloced = TRUE;
6768 }
6769
6770 for (svp = patternp; svp < patternp + pat_count; svp++) {
6771 SV *sv;
6772 SV *rx = NULL;
6773 STRLEN orig_patlen = 0;
6774 bool code = 0;
6775 SV *msv = use_delim ? delim : *svp;
6776 if (!msv) msv = &PL_sv_undef;
6777
6778 /* if we've got a delimiter, we go round the loop twice for each
6779 * svp slot (except the last), using the delimiter the second
6780 * time round */
6781 if (use_delim) {
6782 svp--;
6783 use_delim = FALSE;
6784 }
6785 else if (delim)
6786 use_delim = TRUE;
6787
6788 if (SvTYPE(msv) == SVt_PVAV) {
6789 /* we've encountered an interpolated array within
6790 * the pattern, e.g. /...@a..../. Expand the list of elements,
6791 * then recursively append elements.
6792 * The code in this block is based on S_pushav() */
6793
6794 AV *const av = (AV*)msv;
6795 const SSize_t maxarg = AvFILL(av) + 1;
6796 SV **array;
6797
6798 if (oplist) {
6799 assert(oplist->op_type == OP_PADAV
6800 || oplist->op_type == OP_RV2AV);
6801 oplist = OpSIBLING(oplist);
6802 }
6803
6804 if (SvRMAGICAL(av)) {
6805 SSize_t i;
6806
6807 Newx(array, maxarg, SV*);
6808 SAVEFREEPV(array);
6809 for (i=0; i < maxarg; i++) {
6810 SV ** const svp = av_fetch(av, i, FALSE);
6811 array[i] = svp ? *svp : &PL_sv_undef;
6812 }
6813 }
6814 else
6815 array = AvARRAY(av);
6816
6817 pat = S_concat_pat(aTHX_ pRExC_state, pat,
6818 array, maxarg, NULL, recompile_p,
6819 /* $" */
6820 GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV))));
6821
6822 continue;
6823 }
6824
6825
6826 /* we make the assumption here that each op in the list of
6827 * op_siblings maps to one SV pushed onto the stack,
6828 * except for code blocks, with have both an OP_NULL and
6829 * and OP_CONST.
6830 * This allows us to match up the list of SVs against the
6831 * list of OPs to find the next code block.
6832 *
6833 * Note that PUSHMARK PADSV PADSV ..
6834 * is optimised to
6835 * PADRANGE PADSV PADSV ..
6836 * so the alignment still works. */
6837
6838 if (oplist) {
6839 if (oplist->op_type == OP_NULL
6840 && (oplist->op_flags & OPf_SPECIAL))
6841 {
6842 assert(n < pRExC_state->code_blocks->count);
6843 pRExC_state->code_blocks->cb[n].start = pat ? SvCUR(pat) : 0;
6844 pRExC_state->code_blocks->cb[n].block = oplist;
6845 pRExC_state->code_blocks->cb[n].src_regex = NULL;
6846 n++;
6847 code = 1;
6848 oplist = OpSIBLING(oplist); /* skip CONST */
6849 assert(oplist);
6850 }
6851 oplist = OpSIBLING(oplist);;
6852 }
6853
6854 /* apply magic and QR overloading to arg */
6855
6856 SvGETMAGIC(msv);
6857 if (SvROK(msv) && SvAMAGIC(msv)) {
6858 SV *sv = AMG_CALLunary(msv, regexp_amg);
6859 if (sv) {
6860 if (SvROK(sv))
6861 sv = SvRV(sv);
6862 if (SvTYPE(sv) != SVt_REGEXP)
6863 Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
6864 msv = sv;
6865 }
6866 }
6867
6868 /* try concatenation overload ... */
6869 if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) &&
6870 (sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
6871 {
6872 sv_setsv(pat, sv);
6873 /* overloading involved: all bets are off over literal
6874 * code. Pretend we haven't seen it */
6875 if (n)
6876 pRExC_state->code_blocks->count -= n;
6877 n = 0;
6878 }
6879 else {
6880 /* ... or failing that, try "" overload */
6881 while (SvAMAGIC(msv)
6882 && (sv = AMG_CALLunary(msv, string_amg))
6883 && sv != msv
6884 && !( SvROK(msv)
6885 && SvROK(sv)
6886 && SvRV(msv) == SvRV(sv))
6887 ) {
6888 msv = sv;
6889 SvGETMAGIC(msv);
6890 }
6891 if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
6892 msv = SvRV(msv);
6893
6894 if (pat) {
6895 /* this is a partially unrolled
6896 * sv_catsv_nomg(pat, msv);
6897 * that allows us to adjust code block indices if
6898 * needed */
6899 STRLEN dlen;
6900 char *dst = SvPV_force_nomg(pat, dlen);
6901 orig_patlen = dlen;
6902 if (SvUTF8(msv) && !SvUTF8(pat)) {
6903 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n);
6904 sv_setpvn(pat, dst, dlen);
6905 SvUTF8_on(pat);
6906 }
6907 sv_catsv_nomg(pat, msv);
6908 rx = msv;
6909 }
6910 else {
6911 /* We have only one SV to process, but we need to verify
6912 * it is properly null terminated or we will fail asserts
6913 * later. In theory we probably shouldn't get such SV's,
6914 * but if we do we should handle it gracefully. */
6915 if ( SvTYPE(msv) != SVt_PV || (SvLEN(msv) > SvCUR(msv) && *(SvEND(msv)) == 0) || SvIsCOW_shared_hash(msv) ) {
6916 /* not a string, or a string with a trailing null */
6917 pat = msv;
6918 } else {
6919 /* a string with no trailing null, we need to copy it
6920 * so it has a trailing null */
6921 pat = sv_2mortal(newSVsv(msv));
6922 }
6923 }
6924
6925 if (code)
6926 pRExC_state->code_blocks->cb[n-1].end = SvCUR(pat)-1;
6927 }
6928
6929 /* extract any code blocks within any embedded qr//'s */
6930 if (rx && SvTYPE(rx) == SVt_REGEXP
6931 && RX_ENGINE((REGEXP*)rx)->op_comp)
6932 {
6933
6934 RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
6935 if (ri->code_blocks && ri->code_blocks->count) {
6936 int i;
6937 /* the presence of an embedded qr// with code means
6938 * we should always recompile: the text of the
6939 * qr// may not have changed, but it may be a
6940 * different closure than last time */
6941 *recompile_p = 1;
6942 if (pRExC_state->code_blocks) {
6943 int new_count = pRExC_state->code_blocks->count
6944 + ri->code_blocks->count;
6945 Renew(pRExC_state->code_blocks->cb,
6946 new_count, struct reg_code_block);
6947 pRExC_state->code_blocks->count = new_count;
6948 }
6949 else
6950 pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_
6951 ri->code_blocks->count);
6952
6953 for (i=0; i < ri->code_blocks->count; i++) {
6954 struct reg_code_block *src, *dst;
6955 STRLEN offset = orig_patlen
6956 + ReANY((REGEXP *)rx)->pre_prefix;
6957 assert(n < pRExC_state->code_blocks->count);
6958 src = &ri->code_blocks->cb[i];
6959 dst = &pRExC_state->code_blocks->cb[n];
6960 dst->start = src->start + offset;
6961 dst->end = src->end + offset;
6962 dst->block = src->block;
6963 dst->src_regex = (REGEXP*) SvREFCNT_inc( (SV*)
6964 src->src_regex
6965 ? src->src_regex
6966 : (REGEXP*)rx);
6967 n++;
6968 }
6969 }
6970 }
6971 }
6972 /* avoid calling magic multiple times on a single element e.g. =~ $qr */
6973 if (alloced)
6974 SvSETMAGIC(pat);
6975
6976 return pat;
6977}
6978
6979
6980
6981/* see if there are any run-time code blocks in the pattern.
6982 * False positives are allowed */
6983
6984static bool
6985S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
6986 char *pat, STRLEN plen)
6987{
6988 int n = 0;
6989 STRLEN s;
6990
6991 PERL_UNUSED_CONTEXT;
6992
6993 for (s = 0; s < plen; s++) {
6994 if ( pRExC_state->code_blocks
6995 && n < pRExC_state->code_blocks->count
6996 && s == pRExC_state->code_blocks->cb[n].start)
6997 {
6998 s = pRExC_state->code_blocks->cb[n].end;
6999 n++;
7000 continue;
7001 }
7002 /* TODO ideally should handle [..], (#..), /#.../x to reduce false
7003 * positives here */
7004 if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' &&
7005 (pat[s+2] == '{'
7006 || (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{'))
7007 )
7008 return 1;
7009 }
7010 return 0;
7011}
7012
7013/* Handle run-time code blocks. We will already have compiled any direct
7014 * or indirect literal code blocks. Now, take the pattern 'pat' and make a
7015 * copy of it, but with any literal code blocks blanked out and
7016 * appropriate chars escaped; then feed it into
7017 *
7018 * eval "qr'modified_pattern'"
7019 *
7020 * For example,
7021 *
7022 * a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
7023 *
7024 * becomes
7025 *
7026 * qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
7027 *
7028 * After eval_sv()-ing that, grab any new code blocks from the returned qr
7029 * and merge them with any code blocks of the original regexp.
7030 *
7031 * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
7032 * instead, just save the qr and return FALSE; this tells our caller that
7033 * the original pattern needs upgrading to utf8.
7034 */
7035
7036static bool
7037S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
7038 char *pat, STRLEN plen)
7039{
7040 SV *qr;
7041
7042 GET_RE_DEBUG_FLAGS_DECL;
7043
7044 if (pRExC_state->runtime_code_qr) {
7045 /* this is the second time we've been called; this should
7046 * only happen if the main pattern got upgraded to utf8
7047 * during compilation; re-use the qr we compiled first time
7048 * round (which should be utf8 too)
7049 */
7050 qr = pRExC_state->runtime_code_qr;
7051 pRExC_state->runtime_code_qr = NULL;
7052 assert(RExC_utf8 && SvUTF8(qr));
7053 }
7054 else {
7055 int n = 0;
7056 STRLEN s;
7057 char *p, *newpat;
7058 int newlen = plen + 7; /* allow for "qr''xx\0" extra chars */
7059 SV *sv, *qr_ref;
7060 dSP;
7061
7062 /* determine how many extra chars we need for ' and \ escaping */
7063 for (s = 0; s < plen; s++) {
7064 if (pat[s] == '\'' || pat[s] == '\\')
7065 newlen++;
7066 }
7067
7068 Newx(newpat, newlen, char);
7069 p = newpat;
7070 *p++ = 'q'; *p++ = 'r'; *p++ = '\'';
7071
7072 for (s = 0; s < plen; s++) {
7073 if ( pRExC_state->code_blocks
7074 && n < pRExC_state->code_blocks->count
7075 && s == pRExC_state->code_blocks->cb[n].start)
7076 {
7077 /* blank out literal code block so that they aren't
7078 * recompiled: eg change from/to:
7079 * /(?{xyz})/
7080 * /(?=====)/
7081 * and
7082 * /(??{xyz})/
7083 * /(?======)/
7084 * and
7085 * /(?(?{xyz}))/
7086 * /(?(?=====))/
7087 */
7088 assert(pat[s] == '(');
7089 assert(pat[s+1] == '?');
7090 *p++ = '(';
7091 *p++ = '?';
7092 s += 2;
7093 while (s < pRExC_state->code_blocks->cb[n].end) {
7094 *p++ = '=';
7095 s++;
7096 }
7097 *p++ = ')';
7098 n++;
7099 continue;
7100 }
7101 if (pat[s] == '\'' || pat[s] == '\\')
7102 *p++ = '\\';
7103 *p++ = pat[s];
7104 }
7105 *p++ = '\'';
7106 if (pRExC_state->pm_flags & RXf_PMf_EXTENDED) {
7107 *p++ = 'x';
7108 if (pRExC_state->pm_flags & RXf_PMf_EXTENDED_MORE) {
7109 *p++ = 'x';
7110 }
7111 }
7112 *p++ = '\0';
7113 DEBUG_COMPILE_r({
7114 Perl_re_printf( aTHX_
7115 "%sre-parsing pattern for runtime code:%s %s\n",
7116 PL_colors[4], PL_colors[5], newpat);
7117 });
7118
7119 sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
7120 Safefree(newpat);
7121
7122 ENTER;
7123 SAVETMPS;
7124 save_re_context();
7125 PUSHSTACKi(PERLSI_REQUIRE);
7126 /* G_RE_REPARSING causes the toker to collapse \\ into \ when
7127 * parsing qr''; normally only q'' does this. It also alters
7128 * hints handling */
7129 eval_sv(sv, G_SCALAR|G_RE_REPARSING);
7130 SvREFCNT_dec_NN(sv);
7131 SPAGAIN;
7132 qr_ref = POPs;
7133 PUTBACK;
7134 {
7135 SV * const errsv = ERRSV;
7136 if (SvTRUE_NN(errsv))
7137 /* use croak_sv ? */
7138 Perl_croak_nocontext("%" SVf, SVfARG(errsv));
7139 }
7140 assert(SvROK(qr_ref));
7141 qr = SvRV(qr_ref);
7142 assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
7143 /* the leaving below frees the tmp qr_ref.
7144 * Give qr a life of its own */
7145 SvREFCNT_inc(qr);
7146 POPSTACK;
7147 FREETMPS;
7148 LEAVE;
7149
7150 }
7151
7152 if (!RExC_utf8 && SvUTF8(qr)) {
7153 /* first time through; the pattern got upgraded; save the
7154 * qr for the next time through */
7155 assert(!pRExC_state->runtime_code_qr);
7156 pRExC_state->runtime_code_qr = qr;
7157 return 0;
7158 }
7159
7160
7161 /* extract any code blocks within the returned qr// */
7162
7163
7164 /* merge the main (r1) and run-time (r2) code blocks into one */
7165 {
7166 RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
7167 struct reg_code_block *new_block, *dst;
7168 RExC_state_t * const r1 = pRExC_state; /* convenient alias */
7169 int i1 = 0, i2 = 0;
7170 int r1c, r2c;
7171
7172 if (!r2->code_blocks || !r2->code_blocks->count) /* we guessed wrong */
7173 {
7174 SvREFCNT_dec_NN(qr);
7175 return 1;
7176 }
7177
7178 if (!r1->code_blocks)
7179 r1->code_blocks = S_alloc_code_blocks(aTHX_ 0);
7180
7181 r1c = r1->code_blocks->count;
7182 r2c = r2->code_blocks->count;
7183
7184 Newx(new_block, r1c + r2c, struct reg_code_block);
7185
7186 dst = new_block;
7187
7188 while (i1 < r1c || i2 < r2c) {
7189 struct reg_code_block *src;
7190 bool is_qr = 0;
7191
7192 if (i1 == r1c) {
7193 src = &r2->code_blocks->cb[i2++];
7194 is_qr = 1;
7195 }
7196 else if (i2 == r2c)
7197 src = &r1->code_blocks->cb[i1++];
7198 else if ( r1->code_blocks->cb[i1].start
7199 < r2->code_blocks->cb[i2].start)
7200 {
7201 src = &r1->code_blocks->cb[i1++];
7202 assert(src->end < r2->code_blocks->cb[i2].start);
7203 }
7204 else {
7205 assert( r1->code_blocks->cb[i1].start
7206 > r2->code_blocks->cb[i2].start);
7207 src = &r2->code_blocks->cb[i2++];
7208 is_qr = 1;
7209 assert(src->end < r1->code_blocks->cb[i1].start);
7210 }
7211
7212 assert(pat[src->start] == '(');
7213 assert(pat[src->end] == ')');
7214 dst->start = src->start;
7215 dst->end = src->end;
7216 dst->block = src->block;
7217 dst->src_regex = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
7218 : src->src_regex;
7219 dst++;
7220 }
7221 r1->code_blocks->count += r2c;
7222 Safefree(r1->code_blocks->cb);
7223 r1->code_blocks->cb = new_block;
7224 }
7225
7226 SvREFCNT_dec_NN(qr);
7227 return 1;
7228}
7229
7230
7231STATIC bool
7232S_setup_longest(pTHX_ RExC_state_t *pRExC_state,
7233 struct reg_substr_datum *rsd,
7234 struct scan_data_substrs *sub,
7235 STRLEN longest_length)
7236{
7237 /* This is the common code for setting up the floating and fixed length
7238 * string data extracted from Perl_re_op_compile() below. Returns a boolean
7239 * as to whether succeeded or not */
7240
7241 I32 t;
7242 SSize_t ml;
7243 bool eol = cBOOL(sub->flags & SF_BEFORE_EOL);
7244 bool meol = cBOOL(sub->flags & SF_BEFORE_MEOL);
7245
7246 if (! (longest_length
7247 || (eol /* Can't have SEOL and MULTI */
7248 && (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
7249 )
7250 /* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */
7251 || (RExC_seen & REG_UNFOLDED_MULTI_SEEN))
7252 {
7253 return FALSE;
7254 }
7255
7256 /* copy the information about the longest from the reg_scan_data
7257 over to the program. */
7258 if (SvUTF8(sub->str)) {
7259 rsd->substr = NULL;
7260 rsd->utf8_substr = sub->str;
7261 } else {
7262 rsd->substr = sub->str;
7263 rsd->utf8_substr = NULL;
7264 }
7265 /* end_shift is how many chars that must be matched that
7266 follow this item. We calculate it ahead of time as once the
7267 lookbehind offset is added in we lose the ability to correctly
7268 calculate it.*/
7269 ml = sub->minlenp ? *(sub->minlenp) : (SSize_t)longest_length;
7270 rsd->end_shift = ml - sub->min_offset
7271 - longest_length
7272 /* XXX SvTAIL is always false here - did you mean FBMcf_TAIL
7273 * intead? - DAPM
7274 + (SvTAIL(sub->str) != 0)
7275 */
7276 + sub->lookbehind;
7277
7278 t = (eol/* Can't have SEOL and MULTI */
7279 && (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
7280 fbm_compile(sub->str, t ? FBMcf_TAIL : 0);
7281
7282 return TRUE;
7283}
7284
7285STATIC void
7286S_set_regex_pv(pTHX_ RExC_state_t *pRExC_state, REGEXP *Rx)
7287{
7288 /* Calculates and sets in the compiled pattern 'Rx' the string to compile,
7289 * properly wrapped with the right modifiers */
7290
7291 bool has_p = ((RExC_rx->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
7292 bool has_charset = RExC_utf8 || (get_regex_charset(RExC_rx->extflags)
7293 != REGEX_DEPENDS_CHARSET);
7294
7295 /* The caret is output if there are any defaults: if not all the STD
7296 * flags are set, or if no character set specifier is needed */
7297 bool has_default =
7298 (((RExC_rx->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
7299 || ! has_charset);
7300 bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN)
7301 == REG_RUN_ON_COMMENT_SEEN);
7302 U8 reganch = (U8)((RExC_rx->extflags & RXf_PMf_STD_PMMOD)
7303 >> RXf_PMf_STD_PMMOD_SHIFT);
7304 const char *fptr = STD_PAT_MODS; /*"msixxn"*/
7305 char *p;
7306 STRLEN pat_len = RExC_precomp_end - RExC_precomp;
7307
7308 /* We output all the necessary flags; we never output a minus, as all
7309 * those are defaults, so are
7310 * covered by the caret */
7311 const STRLEN wraplen = pat_len + has_p + has_runon
7312 + has_default /* If needs a caret */
7313 + PL_bitcount[reganch] /* 1 char for each set standard flag */
7314
7315 /* If needs a character set specifier */
7316 + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
7317 + (sizeof("(?:)") - 1);
7318
7319 PERL_ARGS_ASSERT_SET_REGEX_PV;
7320
7321 /* make sure PL_bitcount bounds not exceeded */
7322 assert(sizeof(STD_PAT_MODS) <= 8);
7323
7324 p = sv_grow(MUTABLE_SV(Rx), wraplen + 1); /* +1 for the ending NUL */
7325 SvPOK_on(Rx);
7326 if (RExC_utf8)
7327 SvFLAGS(Rx) |= SVf_UTF8;
7328 *p++='('; *p++='?';
7329
7330 /* If a default, cover it using the caret */
7331 if (has_default) {
7332 *p++= DEFAULT_PAT_MOD;
7333 }
7334 if (has_charset) {
7335 STRLEN len;
7336 const char* name;
7337
7338 name = get_regex_charset_name(RExC_rx->extflags, &len);
7339 if (strEQ(name, DEPENDS_PAT_MODS)) { /* /d under UTF-8 => /u */
7340 assert(RExC_utf8);
7341 name = UNICODE_PAT_MODS;
7342 len = sizeof(UNICODE_PAT_MODS) - 1;
7343 }
7344 Copy(name, p, len, char);
7345 p += len;
7346 }
7347 if (has_p)
7348 *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
7349 {
7350 char ch;
7351 while((ch = *fptr++)) {
7352 if(reganch & 1)
7353 *p++ = ch;
7354 reganch >>= 1;
7355 }
7356 }
7357
7358 *p++ = ':';
7359 Copy(RExC_precomp, p, pat_len, char);
7360 assert ((RX_WRAPPED(Rx) - p) < 16);
7361 RExC_rx->pre_prefix = p - RX_WRAPPED(Rx);
7362 p += pat_len;
7363
7364 /* Adding a trailing \n causes this to compile properly:
7365 my $R = qr / A B C # D E/x; /($R)/
7366 Otherwise the parens are considered part of the comment */
7367 if (has_runon)
7368 *p++ = '\n';
7369 *p++ = ')';
7370 *p = 0;
7371 SvCUR_set(Rx, p - RX_WRAPPED(Rx));
7372}
7373
7374/*
7375 * Perl_re_op_compile - the perl internal RE engine's function to compile a
7376 * regular expression into internal code.
7377 * The pattern may be passed either as:
7378 * a list of SVs (patternp plus pat_count)
7379 * a list of OPs (expr)
7380 * If both are passed, the SV list is used, but the OP list indicates
7381 * which SVs are actually pre-compiled code blocks
7382 *
7383 * The SVs in the list have magic and qr overloading applied to them (and
7384 * the list may be modified in-place with replacement SVs in the latter
7385 * case).
7386 *
7387 * If the pattern hasn't changed from old_re, then old_re will be
7388 * returned.
7389 *
7390 * eng is the current engine. If that engine has an op_comp method, then
7391 * handle directly (i.e. we assume that op_comp was us); otherwise, just
7392 * do the initial concatenation of arguments and pass on to the external
7393 * engine.
7394 *
7395 * If is_bare_re is not null, set it to a boolean indicating whether the
7396 * arg list reduced (after overloading) to a single bare regex which has
7397 * been returned (i.e. /$qr/).
7398 *
7399 * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
7400 *
7401 * pm_flags contains the PMf_* flags, typically based on those from the
7402 * pm_flags field of the related PMOP. Currently we're only interested in
7403 * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL, PMf_WILDCARD.
7404 *
7405 * For many years this code had an initial sizing pass that calculated
7406 * (sometimes incorrectly, leading to security holes) the size needed for the
7407 * compiled pattern. That was changed by commit
7408 * 7c932d07cab18751bfc7515b4320436273a459e2 in 5.29, which reallocs the size, a
7409 * node at a time, as parsing goes along. Patches welcome to fix any obsolete
7410 * references to this sizing pass.
7411 *
7412 * Now, an initial crude guess as to the size needed is made, based on the
7413 * length of the pattern. Patches welcome to improve that guess. That amount
7414 * of space is malloc'd and then immediately freed, and then clawed back node
7415 * by node. This design is to minimze, to the extent possible, memory churn
7416 * when doing the the reallocs.
7417 *
7418 * A separate parentheses counting pass may be needed in some cases.
7419 * (Previously the sizing pass did this.) Patches welcome to reduce the number
7420 * of these cases.
7421 *
7422 * The existence of a sizing pass necessitated design decisions that are no
7423 * longer needed. There are potential areas of simplification.
7424 *
7425 * Beware that the optimization-preparation code in here knows about some
7426 * of the structure of the compiled regexp. [I'll say.]
7427 */
7428
7429REGEXP *
7430Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
7431 OP *expr, const regexp_engine* eng, REGEXP *old_re,
7432 bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags)
7433{
7434 dVAR;
7435 REGEXP *Rx; /* Capital 'R' means points to a REGEXP */
7436 STRLEN plen;
7437 char *exp;
7438 regnode *scan;
7439 I32 flags;
7440 SSize_t minlen = 0;
7441 U32 rx_flags;
7442 SV *pat;
7443 SV** new_patternp = patternp;
7444
7445 /* these are all flags - maybe they should be turned
7446 * into a single int with different bit masks */
7447 I32 sawlookahead = 0;
7448 I32 sawplus = 0;
7449 I32 sawopen = 0;
7450 I32 sawminmod = 0;
7451
7452 regex_charset initial_charset = get_regex_charset(orig_rx_flags);
7453 bool recompile = 0;
7454 bool runtime_code = 0;
7455 scan_data_t data;
7456 RExC_state_t RExC_state;
7457 RExC_state_t * const pRExC_state = &RExC_state;
7458#ifdef TRIE_STUDY_OPT
7459 int restudied = 0;
7460 RExC_state_t copyRExC_state;
7461#endif
7462 GET_RE_DEBUG_FLAGS_DECL;
7463
7464 PERL_ARGS_ASSERT_RE_OP_COMPILE;
7465
7466 DEBUG_r(if (!PL_colorset) reginitcolors());
7467
7468
7469 pRExC_state->warn_text = NULL;
7470 pRExC_state->unlexed_names = NULL;
7471 pRExC_state->code_blocks = NULL;
7472
7473 if (is_bare_re)
7474 *is_bare_re = FALSE;
7475
7476 if (expr && (expr->op_type == OP_LIST ||
7477 (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
7478 /* allocate code_blocks if needed */
7479 OP *o;
7480 int ncode = 0;
7481
7482 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o))
7483 if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
7484 ncode++; /* count of DO blocks */
7485
7486 if (ncode)
7487 pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode);
7488 }
7489
7490 if (!pat_count) {
7491 /* compile-time pattern with just OP_CONSTs and DO blocks */
7492
7493 int n;
7494 OP *o;
7495
7496 /* find how many CONSTs there are */
7497 assert(expr);
7498 n = 0;
7499 if (expr->op_type == OP_CONST)
7500 n = 1;
7501 else
7502 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7503 if (o->op_type == OP_CONST)
7504 n++;
7505 }
7506
7507 /* fake up an SV array */
7508
7509 assert(!new_patternp);
7510 Newx(new_patternp, n, SV*);
7511 SAVEFREEPV(new_patternp);
7512 pat_count = n;
7513
7514 n = 0;
7515 if (expr->op_type == OP_CONST)
7516 new_patternp[n] = cSVOPx_sv(expr);
7517 else
7518 for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7519 if (o->op_type == OP_CONST)
7520 new_patternp[n++] = cSVOPo_sv;
7521 }
7522
7523 }
7524
7525 DEBUG_PARSE_r(Perl_re_printf( aTHX_
7526 "Assembling pattern from %d elements%s\n", pat_count,
7527 orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7528
7529 /* set expr to the first arg op */
7530
7531 if (pRExC_state->code_blocks && pRExC_state->code_blocks->count
7532 && expr->op_type != OP_CONST)
7533 {
7534 expr = cLISTOPx(expr)->op_first;
7535 assert( expr->op_type == OP_PUSHMARK
7536 || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)
7537 || expr->op_type == OP_PADRANGE);
7538 expr = OpSIBLING(expr);
7539 }
7540
7541 pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,
7542 expr, &recompile, NULL);
7543
7544 /* handle bare (possibly after overloading) regex: foo =~ $re */
7545 {
7546 SV *re = pat;
7547 if (SvROK(re))
7548 re = SvRV(re);
7549 if (SvTYPE(re) == SVt_REGEXP) {
7550 if (is_bare_re)
7551 *is_bare_re = TRUE;
7552 SvREFCNT_inc(re);
7553 DEBUG_PARSE_r(Perl_re_printf( aTHX_
7554 "Precompiled pattern%s\n",
7555 orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7556
7557 return (REGEXP*)re;
7558 }
7559 }
7560
7561 exp = SvPV_nomg(pat, plen);
7562
7563 if (!eng->op_comp) {
7564 if ((SvUTF8(pat) && IN_BYTES)
7565 || SvGMAGICAL(pat) || SvAMAGIC(pat))
7566 {
7567 /* make a temporary copy; either to convert to bytes,
7568 * or to avoid repeating get-magic / overloaded stringify */
7569 pat = newSVpvn_flags(exp, plen, SVs_TEMP |
7570 (IN_BYTES ? 0 : SvUTF8(pat)));
7571 }
7572 return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
7573 }
7574
7575 /* ignore the utf8ness if the pattern is 0 length */
7576 RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
7577 RExC_uni_semantics = 0;
7578 RExC_contains_locale = 0;
7579 RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT);
7580 RExC_in_script_run = 0;
7581 RExC_study_started = 0;
7582 pRExC_state->runtime_code_qr = NULL;
7583 RExC_frame_head= NULL;
7584 RExC_frame_last= NULL;
7585 RExC_frame_count= 0;
7586 RExC_latest_warn_offset = 0;
7587 RExC_use_BRANCHJ = 0;
7588 RExC_warned_WARN_EXPERIMENTAL__VLB = 0;
7589 RExC_warned_WARN_EXPERIMENTAL__REGEX_SETS = 0;
7590 RExC_total_parens = 0;
7591 RExC_open_parens = NULL;
7592 RExC_close_parens = NULL;
7593 RExC_paren_names = NULL;
7594 RExC_size = 0;
7595 RExC_seen_d_op = FALSE;
7596#ifdef DEBUGGING
7597 RExC_paren_name_list = NULL;
7598#endif
7599
7600 DEBUG_r({
7601 RExC_mysv1= sv_newmortal();
7602 RExC_mysv2= sv_newmortal();
7603 });
7604
7605 DEBUG_COMPILE_r({
7606 SV *dsv= sv_newmortal();
7607 RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7608 Perl_re_printf( aTHX_ "%sCompiling REx%s %s\n",
7609 PL_colors[4], PL_colors[5], s);
7610 });
7611
7612 /* we jump here if we have to recompile, e.g., from upgrading the pattern
7613 * to utf8 */
7614
7615 if ((pm_flags & PMf_USE_RE_EVAL)
7616 /* this second condition covers the non-regex literal case,
7617 * i.e. $foo =~ '(?{})'. */
7618 || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))
7619 )
7620 runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);
7621
7622 redo_parse:
7623 /* return old regex if pattern hasn't changed */
7624 /* XXX: note in the below we have to check the flags as well as the
7625 * pattern.
7626 *
7627 * Things get a touch tricky as we have to compare the utf8 flag
7628 * independently from the compile flags. */
7629
7630 if ( old_re
7631 && !recompile
7632 && !!RX_UTF8(old_re) == !!RExC_utf8
7633 && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )
7634 && RX_PRECOMP(old_re)
7635 && RX_PRELEN(old_re) == plen
7636 && memEQ(RX_PRECOMP(old_re), exp, plen)
7637 && !runtime_code /* with runtime code, always recompile */ )
7638 {
7639 DEBUG_COMPILE_r({
7640 SV *dsv= sv_newmortal();
7641 RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7642 Perl_re_printf( aTHX_ "%sSkipping recompilation of unchanged REx%s %s\n",
7643 PL_colors[4], PL_colors[5], s);
7644 });
7645 return old_re;
7646 }
7647
7648 /* Allocate the pattern's SV */
7649 RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP);
7650 RExC_rx = ReANY(Rx);
7651 if ( RExC_rx == NULL )
7652 FAIL("Regexp out of space");
7653
7654 rx_flags = orig_rx_flags;
7655
7656 if ( (UTF || RExC_uni_semantics)
7657 && initial_charset == REGEX_DEPENDS_CHARSET)
7658 {
7659
7660 /* Set to use unicode semantics if the pattern is in utf8 and has the
7661 * 'depends' charset specified, as it means unicode when utf8 */
7662 set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
7663 RExC_uni_semantics = 1;
7664 }
7665
7666 RExC_pm_flags = pm_flags;
7667
7668 if (runtime_code) {
7669 assert(TAINTING_get || !TAINT_get);
7670 if (TAINT_get)
7671 Perl_croak(aTHX_ "Eval-group in insecure regular expression");
7672
7673 if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
7674 /* whoops, we have a non-utf8 pattern, whilst run-time code
7675 * got compiled as utf8. Try again with a utf8 pattern */
7676 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7677 pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7678 goto redo_parse;
7679 }
7680 }
7681 assert(!pRExC_state->runtime_code_qr);
7682
7683 RExC_sawback = 0;
7684
7685 RExC_seen = 0;
7686 RExC_maxlen = 0;
7687 RExC_in_lookbehind = 0;
7688 RExC_in_lookahead = 0;
7689 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
7690 RExC_recode_x_to_native = 0;
7691 RExC_in_multi_char_class = 0;
7692
7693 RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp;
7694 RExC_precomp_end = RExC_end = exp + plen;
7695 RExC_nestroot = 0;
7696 RExC_whilem_seen = 0;
7697 RExC_end_op = NULL;
7698 RExC_recurse = NULL;
7699 RExC_study_chunk_recursed = NULL;
7700 RExC_study_chunk_recursed_bytes= 0;
7701 RExC_recurse_count = 0;
7702 RExC_sets_depth = 0;
7703 pRExC_state->code_index = 0;
7704
7705 /* Initialize the string in the compiled pattern. This is so that there is
7706 * something to output if necessary */
7707 set_regex_pv(pRExC_state, Rx);
7708
7709 DEBUG_PARSE_r({
7710 Perl_re_printf( aTHX_
7711 "Starting parse and generation\n");
7712 RExC_lastnum=0;
7713 RExC_lastparse=NULL;
7714 });
7715
7716 /* Allocate space and zero-initialize. Note, the two step process
7717 of zeroing when in debug mode, thus anything assigned has to
7718 happen after that */
7719 if (! RExC_size) {
7720
7721 /* On the first pass of the parse, we guess how big this will be. Then
7722 * we grow in one operation to that amount and then give it back. As
7723 * we go along, we re-allocate what we need.
7724 *
7725 * XXX Currently the guess is essentially that the pattern will be an
7726 * EXACT node with one byte input, one byte output. This is crude, and
7727 * better heuristics are welcome.
7728 *
7729 * On any subsequent passes, we guess what we actually computed in the
7730 * latest earlier pass. Such a pass probably didn't complete so is
7731 * missing stuff. We could improve those guesses by knowing where the
7732 * parse stopped, and use the length so far plus apply the above
7733 * assumption to what's left. */
7734 RExC_size = STR_SZ(RExC_end - RExC_start);
7735 }
7736
7737 Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal);
7738 if ( RExC_rxi == NULL )
7739 FAIL("Regexp out of space");
7740
7741 Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char);
7742 RXi_SET( RExC_rx, RExC_rxi );
7743
7744 /* We start from 0 (over from 0 in the case this is a reparse. The first
7745 * node parsed will give back any excess memory we have allocated so far).
7746 * */
7747 RExC_size = 0;
7748
7749 /* non-zero initialization begins here */
7750 RExC_rx->engine= eng;
7751 RExC_rx->extflags = rx_flags;
7752 RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;
7753
7754 if (pm_flags & PMf_IS_QR) {
7755 RExC_rxi->code_blocks = pRExC_state->code_blocks;
7756 if (RExC_rxi->code_blocks) {
7757 RExC_rxi->code_blocks->refcnt++;
7758 }
7759 }
7760
7761 RExC_rx->intflags = 0;
7762
7763 RExC_flags = rx_flags; /* don't let top level (?i) bleed */
7764 RExC_parse = exp;
7765
7766 /* This NUL is guaranteed because the pattern comes from an SV*, and the sv
7767 * code makes sure the final byte is an uncounted NUL. But should this
7768 * ever not be the case, lots of things could read beyond the end of the
7769 * buffer: loops like
7770 * while(isFOO(*RExC_parse)) RExC_parse++;
7771 * strchr(RExC_parse, "foo");
7772 * etc. So it is worth noting. */
7773 assert(*RExC_end == '\0');
7774
7775 RExC_naughty = 0;
7776 RExC_npar = 1;
7777 RExC_parens_buf_size = 0;
7778 RExC_emit_start = RExC_rxi->program;
7779 pRExC_state->code_index = 0;
7780
7781 *((char*) RExC_emit_start) = (char) REG_MAGIC;
7782 RExC_emit = 1;
7783
7784 /* Do the parse */
7785 if (reg(pRExC_state, 0, &flags, 1)) {
7786
7787 /* Success!, But we may need to redo the parse knowing how many parens
7788 * there actually are */
7789 if (IN_PARENS_PASS) {
7790 flags |= RESTART_PARSE;
7791 }
7792
7793 /* We have that number in RExC_npar */
7794 RExC_total_parens = RExC_npar;
7795 }
7796 else if (! MUST_RESTART(flags)) {
7797 ReREFCNT_dec(Rx);
7798 Perl_croak(aTHX_ "panic: reg returned failure to re_op_compile, flags=%#" UVxf, (UV) flags);
7799 }
7800
7801 /* Here, we either have success, or we have to redo the parse for some reason */
7802 if (MUST_RESTART(flags)) {
7803
7804 /* It's possible to write a regexp in ascii that represents Unicode
7805 codepoints outside of the byte range, such as via \x{100}. If we
7806 detect such a sequence we have to convert the entire pattern to utf8
7807 and then recompile, as our sizing calculation will have been based
7808 on 1 byte == 1 character, but we will need to use utf8 to encode
7809 at least some part of the pattern, and therefore must convert the whole
7810 thing.
7811 -- dmq */
7812 if (flags & NEED_UTF8) {
7813
7814 /* We have stored the offset of the final warning output so far.
7815 * That must be adjusted. Any variant characters between the start
7816 * of the pattern and this warning count for 2 bytes in the final,
7817 * so just add them again */
7818 if (UNLIKELY(RExC_latest_warn_offset > 0)) {
7819 RExC_latest_warn_offset +=
7820 variant_under_utf8_count((U8 *) exp, (U8 *) exp
7821 + RExC_latest_warn_offset);
7822 }
7823 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7824 pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7825 DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse after upgrade\n"));
7826 }
7827 else {
7828 DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse\n"));
7829 }
7830
7831 if (ALL_PARENS_COUNTED) {
7832 /* Make enough room for all the known parens, and zero it */
7833 Renew(RExC_open_parens, RExC_total_parens, regnode_offset);
7834 Zero(RExC_open_parens, RExC_total_parens, regnode_offset);
7835 RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */
7836
7837 Renew(RExC_close_parens, RExC_total_parens, regnode_offset);
7838 Zero(RExC_close_parens, RExC_total_parens, regnode_offset);
7839 }
7840 else { /* Parse did not complete. Reinitialize the parentheses
7841 structures */
7842 RExC_total_parens = 0;
7843 if (RExC_open_parens) {
7844 Safefree(RExC_open_parens);
7845 RExC_open_parens = NULL;
7846 }
7847 if (RExC_close_parens) {
7848 Safefree(RExC_close_parens);
7849 RExC_close_parens = NULL;
7850 }
7851 }
7852
7853 /* Clean up what we did in this parse */
7854 SvREFCNT_dec_NN(RExC_rx_sv);
7855
7856 goto redo_parse;
7857 }
7858
7859 /* Here, we have successfully parsed and generated the pattern's program
7860 * for the regex engine. We are ready to finish things up and look for
7861 * optimizations. */
7862
7863 /* Update the string to compile, with correct modifiers, etc */
7864 set_regex_pv(pRExC_state, Rx);
7865
7866 RExC_rx->nparens = RExC_total_parens - 1;
7867
7868 /* Uses the upper 4 bits of the FLAGS field, so keep within that size */
7869 if (RExC_whilem_seen > 15)
7870 RExC_whilem_seen = 15;
7871
7872 DEBUG_PARSE_r({
7873 Perl_re_printf( aTHX_
7874 "Required size %" IVdf " nodes\n", (IV)RExC_size);
7875 RExC_lastnum=0;
7876 RExC_lastparse=NULL;
7877 });
7878
7879#ifdef RE_TRACK_PATTERN_OFFSETS
7880 DEBUG_OFFSETS_r(Perl_re_printf( aTHX_
7881 "%s %" UVuf " bytes for offset annotations.\n",
7882 RExC_offsets ? "Got" : "Couldn't get",
7883 (UV)((RExC_offsets[0] * 2 + 1))));
7884 DEBUG_OFFSETS_r(if (RExC_offsets) {
7885 const STRLEN len = RExC_offsets[0];
7886 STRLEN i;
7887 GET_RE_DEBUG_FLAGS_DECL;
7888 Perl_re_printf( aTHX_
7889 "Offsets: [%" UVuf "]\n\t", (UV)RExC_offsets[0]);
7890 for (i = 1; i <= len; i++) {
7891 if (RExC_offsets[i*2-1] || RExC_offsets[i*2])
7892 Perl_re_printf( aTHX_ "%" UVuf ":%" UVuf "[%" UVuf "] ",
7893 (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]);
7894 }
7895 Perl_re_printf( aTHX_ "\n");
7896 });
7897
7898#else
7899 SetProgLen(RExC_rxi,RExC_size);
7900#endif
7901
7902 DEBUG_DUMP_PRE_OPTIMIZE_r({
7903 SV * const sv = sv_newmortal();
7904 RXi_GET_DECL(RExC_rx, ri);
7905 DEBUG_RExC_seen();
7906 Perl_re_printf( aTHX_ "Program before optimization:\n");
7907
7908 (void)dumpuntil(RExC_rx, ri->program, ri->program + 1, NULL, NULL,
7909 sv, 0, 0);
7910 });
7911
7912 DEBUG_OPTIMISE_r(
7913 Perl_re_printf( aTHX_ "Starting post parse optimization\n");
7914 );
7915
7916 /* XXXX To minimize changes to RE engine we always allocate
7917 3-units-long substrs field. */
7918 Newx(RExC_rx->substrs, 1, struct reg_substr_data);
7919 if (RExC_recurse_count) {
7920 Newx(RExC_recurse, RExC_recurse_count, regnode *);
7921 SAVEFREEPV(RExC_recurse);
7922 }
7923
7924 if (RExC_seen & REG_RECURSE_SEEN) {
7925 /* Note, RExC_total_parens is 1 + the number of parens in a pattern.
7926 * So its 1 if there are no parens. */
7927 RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) +
7928 ((RExC_total_parens & 0x07) != 0);
7929 Newx(RExC_study_chunk_recursed,
7930 RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
7931 SAVEFREEPV(RExC_study_chunk_recursed);
7932 }
7933
7934 reStudy:
7935 RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;
7936 DEBUG_r(
7937 RExC_study_chunk_recursed_count= 0;
7938 );
7939 Zero(RExC_rx->substrs, 1, struct reg_substr_data);
7940 if (RExC_study_chunk_recursed) {
7941 Zero(RExC_study_chunk_recursed,
7942 RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
7943 }
7944
7945
7946#ifdef TRIE_STUDY_OPT
7947 if (!restudied) {
7948 StructCopy(&zero_scan_data, &data, scan_data_t);
7949 copyRExC_state = RExC_state;
7950 } else {
7951 U32 seen=RExC_seen;
7952 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n"));
7953
7954 RExC_state = copyRExC_state;
7955 if (seen & REG_TOP_LEVEL_BRANCHES_SEEN)
7956 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
7957 else
7958 RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN;
7959 StructCopy(&zero_scan_data, &data, scan_data_t);
7960 }
7961#else
7962 StructCopy(&zero_scan_data, &data, scan_data_t);
7963#endif
7964
7965 /* Dig out information for optimizations. */
7966 RExC_rx->extflags = RExC_flags; /* was pm_op */
7967 /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
7968
7969 if (UTF)
7970 SvUTF8_on(Rx); /* Unicode in it? */
7971 RExC_rxi->regstclass = NULL;
7972 if (RExC_naughty >= TOO_NAUGHTY) /* Probably an expensive pattern. */
7973 RExC_rx->intflags |= PREGf_NAUGHTY;
7974 scan = RExC_rxi->program + 1; /* First BRANCH. */
7975
7976 /* testing for BRANCH here tells us whether there is "must appear"
7977 data in the pattern. If there is then we can use it for optimisations */
7978 if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice.
7979 */
7980 SSize_t fake;
7981 STRLEN longest_length[2];
7982 regnode_ssc ch_class; /* pointed to by data */
7983 int stclass_flag;
7984 SSize_t last_close = 0; /* pointed to by data */
7985 regnode *first= scan;
7986 regnode *first_next= regnext(first);
7987 int i;
7988
7989 /*
7990 * Skip introductions and multiplicators >= 1
7991 * so that we can extract the 'meat' of the pattern that must
7992 * match in the large if() sequence following.
7993 * NOTE that EXACT is NOT covered here, as it is normally
7994 * picked up by the optimiser separately.
7995 *
7996 * This is unfortunate as the optimiser isnt handling lookahead
7997 * properly currently.
7998 *
7999 */
8000 while ((OP(first) == OPEN && (sawopen = 1)) ||
8001 /* An OR of *one* alternative - should not happen now. */
8002 (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
8003 /* for now we can't handle lookbehind IFMATCH*/
8004 (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
8005 (OP(first) == PLUS) ||
8006 (OP(first) == MINMOD) ||
8007 /* An {n,m} with n>0 */
8008 (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
8009 (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
8010 {
8011 /*
8012 * the only op that could be a regnode is PLUS, all the rest
8013 * will be regnode_1 or regnode_2.
8014 *
8015 * (yves doesn't think this is true)
8016 */
8017 if (OP(first) == PLUS)
8018 sawplus = 1;
8019 else {
8020 if (OP(first) == MINMOD)
8021 sawminmod = 1;
8022 first += regarglen[OP(first)];
8023 }
8024 first = NEXTOPER(first);
8025 first_next= regnext(first);
8026 }
8027
8028 /* Starting-point info. */
8029 again:
8030 DEBUG_PEEP("first:", first, 0, 0);
8031 /* Ignore EXACT as we deal with it later. */
8032 if (PL_regkind[OP(first)] == EXACT) {
8033 if ( OP(first) == EXACT
8034 || OP(first) == LEXACT
8035 || OP(first) == EXACT_REQ8
8036 || OP(first) == LEXACT_REQ8
8037 || OP(first) == EXACTL)
8038 {
8039 NOOP; /* Empty, get anchored substr later. */
8040 }
8041 else
8042 RExC_rxi->regstclass = first;
8043 }
8044#ifdef TRIE_STCLASS
8045 else if (PL_regkind[OP(first)] == TRIE &&
8046 ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0)
8047 {
8048 /* this can happen only on restudy */
8049 RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0);
8050 }
8051#endif
8052 else if (REGNODE_SIMPLE(OP(first)))
8053 RExC_rxi->regstclass = first;
8054 else if (PL_regkind[OP(first)] == BOUND ||
8055 PL_regkind[OP(first)] == NBOUND)
8056 RExC_rxi->regstclass = first;
8057 else if (PL_regkind[OP(first)] == BOL) {
8058 RExC_rx->intflags |= (OP(first) == MBOL
8059 ? PREGf_ANCH_MBOL
8060 : PREGf_ANCH_SBOL);
8061 first = NEXTOPER(first);
8062 goto again;
8063 }
8064 else if (OP(first) == GPOS) {
8065 RExC_rx->intflags |= PREGf_ANCH_GPOS;
8066 first = NEXTOPER(first);
8067 goto again;
8068 }
8069 else if ((!sawopen || !RExC_sawback) &&
8070 !sawlookahead &&
8071 (OP(first) == STAR &&
8072 PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
8073 !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks)
8074 {
8075 /* turn .* into ^.* with an implied $*=1 */
8076 const int type =
8077 (OP(NEXTOPER(first)) == REG_ANY)
8078 ? PREGf_ANCH_MBOL
8079 : PREGf_ANCH_SBOL;
8080 RExC_rx->intflags |= (type | PREGf_IMPLICIT);
8081 first = NEXTOPER(first);
8082 goto again;
8083 }
8084 if (sawplus && !sawminmod && !sawlookahead
8085 && (!sawopen || !RExC_sawback)
8086 && !pRExC_state->code_blocks) /* May examine pos and $& */
8087 /* x+ must match at the 1st pos of run of x's */
8088 RExC_rx->intflags |= PREGf_SKIP;
8089
8090 /* Scan is after the zeroth branch, first is atomic matcher. */
8091#ifdef TRIE_STUDY_OPT
8092 DEBUG_PARSE_r(
8093 if (!restudied)
8094 Perl_re_printf( aTHX_ "first at %" IVdf "\n",
8095 (IV)(first - scan + 1))
8096 );
8097#else
8098 DEBUG_PARSE_r(
8099 Perl_re_printf( aTHX_ "first at %" IVdf "\n",
8100 (IV)(first - scan + 1))
8101 );
8102#endif
8103
8104
8105 /*
8106 * If there's something expensive in the r.e., find the
8107 * longest literal string that must appear and make it the
8108 * regmust. Resolve ties in favor of later strings, since
8109 * the regstart check works with the beginning of the r.e.
8110 * and avoiding duplication strengthens checking. Not a
8111 * strong reason, but sufficient in the absence of others.
8112 * [Now we resolve ties in favor of the earlier string if
8113 * it happens that c_offset_min has been invalidated, since the
8114 * earlier string may buy us something the later one won't.]
8115 */
8116
8117 data.substrs[0].str = newSVpvs("");
8118 data.substrs[1].str = newSVpvs("");
8119 data.last_found = newSVpvs("");
8120 data.cur_is_floating = 0; /* initially any found substring is fixed */
8121 ENTER_with_name("study_chunk");
8122 SAVEFREESV(data.substrs[0].str);
8123 SAVEFREESV(data.substrs[1].str);
8124 SAVEFREESV(data.last_found);
8125 first = scan;
8126 if (!RExC_rxi->regstclass) {
8127 ssc_init(pRExC_state, &ch_class);
8128 data.start_class = &ch_class;
8129 stclass_flag = SCF_DO_STCLASS_AND;
8130 } else /* XXXX Check for BOUND? */
8131 stclass_flag = 0;
8132 data.last_closep = &last_close;
8133
8134 DEBUG_RExC_seen();
8135 /*
8136 * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/
8137 * (NO top level branches)
8138 */
8139 minlen = study_chunk(pRExC_state, &first, &minlen, &fake,
8140 scan + RExC_size, /* Up to end */
8141 &data, -1, 0, NULL,
8142 SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
8143 | (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
8144 0);
8145
8146
8147 CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
8148
8149
8150 if ( RExC_total_parens == 1 && !data.cur_is_floating
8151 && data.last_start_min == 0 && data.last_end > 0
8152 && !RExC_seen_zerolen
8153 && !(RExC_seen & REG_VERBARG_SEEN)
8154 && !(RExC_seen & REG_GPOS_SEEN)
8155 ){
8156 RExC_rx->extflags |= RXf_CHECK_ALL;
8157 }
8158 scan_commit(pRExC_state, &data,&minlen, 0);
8159
8160
8161 /* XXX this is done in reverse order because that's the way the
8162 * code was before it was parameterised. Don't know whether it
8163 * actually needs doing in reverse order. DAPM */
8164 for (i = 1; i >= 0; i--) {
8165 longest_length[i] = CHR_SVLEN(data.substrs[i].str);
8166
8167 if ( !( i
8168 && SvCUR(data.substrs[0].str) /* ok to leave SvCUR */
8169 && data.substrs[0].min_offset
8170 == data.substrs[1].min_offset
8171 && SvCUR(data.substrs[0].str)
8172 == SvCUR(data.substrs[1].str)
8173 )
8174 && S_setup_longest (aTHX_ pRExC_state,
8175 &(RExC_rx->substrs->data[i]),
8176 &(data.substrs[i]),
8177 longest_length[i]))
8178 {
8179 RExC_rx->substrs->data[i].min_offset =
8180 data.substrs[i].min_offset - data.substrs[i].lookbehind;
8181
8182 RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset;
8183 /* Don't offset infinity */
8184 if (data.substrs[i].max_offset < OPTIMIZE_INFTY)
8185 RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind;
8186 SvREFCNT_inc_simple_void_NN(data.substrs[i].str);
8187 }
8188 else {
8189 RExC_rx->substrs->data[i].substr = NULL;
8190 RExC_rx->substrs->data[i].utf8_substr = NULL;
8191 longest_length[i] = 0;
8192 }
8193 }
8194
8195 LEAVE_with_name("study_chunk");
8196
8197 if (RExC_rxi->regstclass
8198 && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY))
8199 RExC_rxi->regstclass = NULL;
8200
8201 if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr)
8202 || RExC_rx->substrs->data[0].min_offset)
8203 && stclass_flag
8204 && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8205 && is_ssc_worth_it(pRExC_state, data.start_class))
8206 {
8207 const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8208
8209 ssc_finalize(pRExC_state, data.start_class);
8210
8211 Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8212 StructCopy(data.start_class,
8213 (regnode_ssc*)RExC_rxi->data->data[n],
8214 regnode_ssc);
8215 RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8216 RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
8217 DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
8218 regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8219 Perl_re_printf( aTHX_
8220 "synthetic stclass \"%s\".\n",
8221 SvPVX_const(sv));});
8222 data.start_class = NULL;
8223 }
8224
8225 /* A temporary algorithm prefers floated substr to fixed one of
8226 * same length to dig more info. */
8227 i = (longest_length[0] <= longest_length[1]);
8228 RExC_rx->substrs->check_ix = i;
8229 RExC_rx->check_end_shift = RExC_rx->substrs->data[i].end_shift;
8230 RExC_rx->check_substr = RExC_rx->substrs->data[i].substr;
8231 RExC_rx->check_utf8 = RExC_rx->substrs->data[i].utf8_substr;
8232 RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset;
8233 RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset;
8234 if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS)))
8235 RExC_rx->intflags |= PREGf_NOSCAN;
8236
8237 if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) {
8238 RExC_rx->extflags |= RXf_USE_INTUIT;
8239 if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8))
8240 RExC_rx->extflags |= RXf_INTUIT_TAIL;
8241 }
8242
8243 /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
8244 if ( (STRLEN)minlen < longest_length[1] )
8245 minlen= longest_length[1];
8246 if ( (STRLEN)minlen < longest_length[0] )
8247 minlen= longest_length[0];
8248 */
8249 }
8250 else {
8251 /* Several toplevels. Best we can is to set minlen. */
8252 SSize_t fake;
8253 regnode_ssc ch_class;
8254 SSize_t last_close = 0;
8255
8256 DEBUG_PARSE_r(Perl_re_printf( aTHX_ "\nMulti Top Level\n"));
8257
8258 scan = RExC_rxi->program + 1;
8259 ssc_init(pRExC_state, &ch_class);
8260 data.start_class = &ch_class;
8261 data.last_closep = &last_close;
8262
8263 DEBUG_RExC_seen();
8264 /*
8265 * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../
8266 * (patterns WITH top level branches)
8267 */
8268 minlen = study_chunk(pRExC_state,
8269 &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL,
8270 SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied
8271 ? SCF_TRIE_DOING_RESTUDY
8272 : 0),
8273 0);
8274
8275 CHECK_RESTUDY_GOTO_butfirst(NOOP);
8276
8277 RExC_rx->check_substr = NULL;
8278 RExC_rx->check_utf8 = NULL;
8279 RExC_rx->substrs->data[0].substr = NULL;
8280 RExC_rx->substrs->data[0].utf8_substr = NULL;
8281 RExC_rx->substrs->data[1].substr = NULL;
8282 RExC_rx->substrs->data[1].utf8_substr = NULL;
8283
8284 if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8285 && is_ssc_worth_it(pRExC_state, data.start_class))
8286 {
8287 const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8288
8289 ssc_finalize(pRExC_state, data.start_class);
8290
8291 Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8292 StructCopy(data.start_class,
8293 (regnode_ssc*)RExC_rxi->data->data[n],
8294 regnode_ssc);
8295 RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8296 RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
8297 DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
8298 regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8299 Perl_re_printf( aTHX_
8300 "synthetic stclass \"%s\".\n",
8301 SvPVX_const(sv));});
8302 data.start_class = NULL;
8303 }
8304 }
8305
8306 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) {
8307 RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN;
8308 RExC_rx->maxlen = REG_INFTY;
8309 }
8310 else {
8311 RExC_rx->maxlen = RExC_maxlen;
8312 }
8313
8314 /* Guard against an embedded (?=) or (?<=) with a longer minlen than
8315 the "real" pattern. */
8316 DEBUG_OPTIMISE_r({
8317 Perl_re_printf( aTHX_ "minlen: %" IVdf " RExC_rx->minlen:%" IVdf " maxlen:%" IVdf "\n",
8318 (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen);
8319 });
8320 RExC_rx->minlenret = minlen;
8321 if (RExC_rx->minlen < minlen)
8322 RExC_rx->minlen = minlen;
8323
8324 if (RExC_seen & REG_RECURSE_SEEN ) {
8325 RExC_rx->intflags |= PREGf_RECURSE_SEEN;
8326 Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *);
8327 }
8328 if (RExC_seen & REG_GPOS_SEEN)
8329 RExC_rx->intflags |= PREGf_GPOS_SEEN;
8330 if (RExC_seen & REG_LOOKBEHIND_SEEN)
8331 RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the
8332 lookbehind */
8333 if (pRExC_state->code_blocks)
8334 RExC_rx->extflags |= RXf_EVAL_SEEN;
8335 if (RExC_seen & REG_VERBARG_SEEN)
8336 {
8337 RExC_rx->intflags |= PREGf_VERBARG_SEEN;
8338 RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */
8339 }
8340 if (RExC_seen & REG_CUTGROUP_SEEN)
8341 RExC_rx->intflags |= PREGf_CUTGROUP_SEEN;
8342 if (pm_flags & PMf_USE_RE_EVAL)
8343 RExC_rx->intflags |= PREGf_USE_RE_EVAL;
8344 if (RExC_paren_names)
8345 RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
8346 else
8347 RXp_PAREN_NAMES(RExC_rx) = NULL;
8348
8349 /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED
8350 * so it can be used in pp.c */
8351 if (RExC_rx->intflags & PREGf_ANCH)
8352 RExC_rx->extflags |= RXf_IS_ANCHORED;
8353
8354
8355 {
8356 /* this is used to identify "special" patterns that might result
8357 * in Perl NOT calling the regex engine and instead doing the match "itself",
8358 * particularly special cases in split//. By having the regex compiler
8359 * do this pattern matching at a regop level (instead of by inspecting the pattern)
8360 * we avoid weird issues with equivalent patterns resulting in different behavior,
8361 * AND we allow non Perl engines to get the same optimizations by the setting the
8362 * flags appropriately - Yves */
8363 regnode *first = RExC_rxi->program + 1;
8364 U8 fop = OP(first);
8365 regnode *next = regnext(first);
8366 U8 nop = OP(next);
8367
8368 if (PL_regkind[fop] == NOTHING && nop == END)
8369 RExC_rx->extflags |= RXf_NULL;
8370 else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END)
8371 /* when fop is SBOL first->flags will be true only when it was
8372 * produced by parsing /\A/, and not when parsing /^/. This is
8373 * very important for the split code as there we want to
8374 * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m.
8375 * See rt #122761 for more details. -- Yves */
8376 RExC_rx->extflags |= RXf_START_ONLY;
8377 else if (fop == PLUS
8378 && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE
8379 && nop == END)
8380 RExC_rx->extflags |= RXf_WHITE;
8381 else if ( RExC_rx->extflags & RXf_SPLIT
8382 && ( fop == EXACT || fop == LEXACT
8383 || fop == EXACT_REQ8 || fop == LEXACT_REQ8
8384 || fop == EXACTL)
8385 && STR_LEN(first) == 1
8386 && *(STRING(first)) == ' '
8387 && nop == END )
8388 RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
8389
8390 }
8391
8392 if (RExC_contains_locale) {
8393 RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED;
8394 }
8395
8396#ifdef DEBUGGING
8397 if (RExC_paren_names) {
8398 RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a"));
8399 RExC_rxi->data->data[RExC_rxi->name_list_idx]
8400 = (void*)SvREFCNT_inc(RExC_paren_name_list);
8401 } else
8402#endif
8403 RExC_rxi->name_list_idx = 0;
8404
8405 while ( RExC_recurse_count > 0 ) {
8406 const regnode *scan = RExC_recurse[ --RExC_recurse_count ];
8407 /*
8408 * This data structure is set up in study_chunk() and is used
8409 * to calculate the distance between a GOSUB regopcode and
8410 * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's)
8411 * it refers to.
8412 *
8413 * If for some reason someone writes code that optimises
8414 * away a GOSUB opcode then the assert should be changed to
8415 * an if(scan) to guard the ARG2L_SET() - Yves
8416 *
8417 */
8418 assert(scan && OP(scan) == GOSUB);
8419 ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan));
8420 }
8421
8422 Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair);
8423 /* assume we don't need to swap parens around before we match */
8424 DEBUG_TEST_r({
8425 Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n",
8426 (unsigned long)RExC_study_chunk_recursed_count);
8427 });
8428 DEBUG_DUMP_r({
8429 DEBUG_RExC_seen();
8430 Perl_re_printf( aTHX_ "Final program:\n");
8431 regdump(RExC_rx);
8432 });
8433
8434 if (RExC_open_parens) {
8435 Safefree(RExC_open_parens);
8436 RExC_open_parens = NULL;
8437 }
8438 if (RExC_close_parens) {
8439 Safefree(RExC_close_parens);
8440 RExC_close_parens = NULL;
8441 }
8442
8443#ifdef USE_ITHREADS
8444 /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated
8445 * by setting the regexp SV to readonly-only instead. If the
8446 * pattern's been recompiled, the USEDness should remain. */
8447 if (old_re && SvREADONLY(old_re))
8448 SvREADONLY_on(Rx);
8449#endif
8450 return Rx;
8451}
8452
8453
8454SV*
8455Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
8456 const U32 flags)
8457{
8458 PERL_ARGS_ASSERT_REG_NAMED_BUFF;
8459
8460 PERL_UNUSED_ARG(value);
8461
8462 if (flags & RXapif_FETCH) {
8463 return reg_named_buff_fetch(rx, key, flags);
8464 } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
8465 Perl_croak_no_modify();
8466 return NULL;
8467 } else if (flags & RXapif_EXISTS) {
8468 return reg_named_buff_exists(rx, key, flags)
8469 ? &PL_sv_yes
8470 : &PL_sv_no;
8471 } else if (flags & RXapif_REGNAMES) {
8472 return reg_named_buff_all(rx, flags);
8473 } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
8474 return reg_named_buff_scalar(rx, flags);
8475 } else {
8476 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
8477 return NULL;
8478 }
8479}
8480
8481SV*
8482Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
8483 const U32 flags)
8484{
8485 PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
8486 PERL_UNUSED_ARG(lastkey);
8487
8488 if (flags & RXapif_FIRSTKEY)
8489 return reg_named_buff_firstkey(rx, flags);
8490 else if (flags & RXapif_NEXTKEY)
8491 return reg_named_buff_nextkey(rx, flags);
8492 else {
8493 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter",
8494 (int)flags);
8495 return NULL;
8496 }
8497}
8498
8499SV*
8500Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
8501 const U32 flags)
8502{
8503 SV *ret;
8504 struct regexp *const rx = ReANY(r);
8505
8506 PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
8507
8508 if (rx && RXp_PAREN_NAMES(rx)) {
8509 HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
8510 if (he_str) {
8511 IV i;
8512 SV* sv_dat=HeVAL(he_str);
8513 I32 *nums=(I32*)SvPVX(sv_dat);
8514 AV * const retarray = (flags & RXapif_ALL) ? newAV() : NULL;
8515 for ( i=0; i<SvIVX(sv_dat); i++ ) {
8516 if ((I32)(rx->nparens) >= nums[i]
8517 && rx->offs[nums[i]].start != -1
8518 && rx->offs[nums[i]].end != -1)
8519 {
8520 ret = newSVpvs("");
8521 CALLREG_NUMBUF_FETCH(r, nums[i], ret);
8522 if (!retarray)
8523 return ret;
8524 } else {
8525 if (retarray)
8526 ret = newSVsv(&PL_sv_undef);
8527 }
8528 if (retarray)
8529 av_push(retarray, ret);
8530 }
8531 if (retarray)
8532 return newRV_noinc(MUTABLE_SV(retarray));
8533 }
8534 }
8535 return NULL;
8536}
8537
8538bool
8539Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
8540 const U32 flags)
8541{
8542 struct regexp *const rx = ReANY(r);
8543
8544 PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
8545
8546 if (rx && RXp_PAREN_NAMES(rx)) {
8547 if (flags & RXapif_ALL) {
8548 return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
8549 } else {
8550 SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
8551 if (sv) {
8552 SvREFCNT_dec_NN(sv);
8553 return TRUE;
8554 } else {
8555 return FALSE;
8556 }
8557 }
8558 } else {
8559 return FALSE;
8560 }
8561}
8562
8563SV*
8564Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
8565{
8566 struct regexp *const rx = ReANY(r);
8567
8568 PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
8569
8570 if ( rx && RXp_PAREN_NAMES(rx) ) {
8571 (void)hv_iterinit(RXp_PAREN_NAMES(rx));
8572
8573 return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
8574 } else {
8575 return FALSE;
8576 }
8577}
8578
8579SV*
8580Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
8581{
8582 struct regexp *const rx = ReANY(r);
8583 GET_RE_DEBUG_FLAGS_DECL;
8584
8585 PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
8586
8587 if (rx && RXp_PAREN_NAMES(rx)) {
8588 HV *hv = RXp_PAREN_NAMES(rx);
8589 HE *temphe;
8590 while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8591 IV i;
8592 IV parno = 0;
8593 SV* sv_dat = HeVAL(temphe);
8594 I32 *nums = (I32*)SvPVX(sv_dat);
8595 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8596 if ((I32)(rx->lastparen) >= nums[i] &&
8597 rx->offs[nums[i]].start != -1 &&
8598 rx->offs[nums[i]].end != -1)
8599 {
8600 parno = nums[i];
8601 break;
8602 }
8603 }
8604 if (parno || flags & RXapif_ALL) {
8605 return newSVhek(HeKEY_hek(temphe));
8606 }
8607 }
8608 }
8609 return NULL;
8610}
8611
8612SV*
8613Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
8614{
8615 SV *ret;
8616 AV *av;
8617 SSize_t length;
8618 struct regexp *const rx = ReANY(r);
8619
8620 PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
8621
8622 if (rx && RXp_PAREN_NAMES(rx)) {
8623 if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
8624 return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
8625 } else if (flags & RXapif_ONE) {
8626 ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
8627 av = MUTABLE_AV(SvRV(ret));
8628 length = av_tindex(av);
8629 SvREFCNT_dec_NN(ret);
8630 return newSViv(length + 1);
8631 } else {
8632 Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar",
8633 (int)flags);
8634 return NULL;
8635 }
8636 }
8637 return &PL_sv_undef;
8638}
8639
8640SV*
8641Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
8642{
8643 struct regexp *const rx = ReANY(r);
8644 AV *av = newAV();
8645
8646 PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
8647
8648 if (rx && RXp_PAREN_NAMES(rx)) {
8649 HV *hv= RXp_PAREN_NAMES(rx);
8650 HE *temphe;
8651 (void)hv_iterinit(hv);
8652 while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8653 IV i;
8654 IV parno = 0;
8655 SV* sv_dat = HeVAL(temphe);
8656 I32 *nums = (I32*)SvPVX(sv_dat);
8657 for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8658 if ((I32)(rx->lastparen) >= nums[i] &&
8659 rx->offs[nums[i]].start != -1 &&
8660 rx->offs[nums[i]].end != -1)
8661 {
8662 parno = nums[i];
8663 break;
8664 }
8665 }
8666 if (parno || flags & RXapif_ALL) {
8667 av_push(av, newSVhek(HeKEY_hek(temphe)));
8668 }
8669 }
8670 }
8671
8672 return newRV_noinc(MUTABLE_SV(av));
8673}
8674
8675void
8676Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
8677 SV * const sv)
8678{
8679 struct regexp *const rx = ReANY(r);
8680 char *s = NULL;
8681 SSize_t i = 0;
8682 SSize_t s1, t1;
8683 I32 n = paren;
8684
8685 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
8686
8687 if ( n == RX_BUFF_IDX_CARET_PREMATCH
8688 || n == RX_BUFF_IDX_CARET_FULLMATCH
8689 || n == RX_BUFF_IDX_CARET_POSTMATCH
8690 )
8691 {
8692 bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8693 if (!keepcopy) {
8694 /* on something like
8695 * $r = qr/.../;
8696 * /$qr/p;
8697 * the KEEPCOPY is set on the PMOP rather than the regex */
8698 if (PL_curpm && r == PM_GETRE(PL_curpm))
8699 keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8700 }
8701 if (!keepcopy)
8702 goto ret_undef;
8703 }
8704
8705 if (!rx->subbeg)
8706 goto ret_undef;
8707
8708 if (n == RX_BUFF_IDX_CARET_FULLMATCH)
8709 /* no need to distinguish between them any more */
8710 n = RX_BUFF_IDX_FULLMATCH;
8711
8712 if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
8713 && rx->offs[0].start != -1)
8714 {
8715 /* $`, ${^PREMATCH} */
8716 i = rx->offs[0].start;
8717 s = rx->subbeg;
8718 }
8719 else
8720 if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
8721 && rx->offs[0].end != -1)
8722 {
8723 /* $', ${^POSTMATCH} */
8724 s = rx->subbeg - rx->suboffset + rx->offs[0].end;
8725 i = rx->sublen + rx->suboffset - rx->offs[0].end;
8726 }
8727 else
8728 if (inRANGE(n, 0, (I32)rx->nparens) &&
8729 (s1 = rx->offs[n].start) != -1 &&
8730 (t1 = rx->offs[n].end) != -1)
8731 {
8732 /* $&, ${^MATCH}, $1 ... */
8733 i = t1 - s1;
8734 s = rx->subbeg + s1 - rx->suboffset;
8735 } else {
8736 goto ret_undef;
8737 }
8738
8739 assert(s >= rx->subbeg);
8740 assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) );
8741 if (i >= 0) {
8742#ifdef NO_TAINT_SUPPORT
8743 sv_setpvn(sv, s, i);
8744#else
8745 const int oldtainted = TAINT_get;
8746 TAINT_NOT;
8747 sv_setpvn(sv, s, i);
8748 TAINT_set(oldtainted);
8749#endif
8750 if (RXp_MATCH_UTF8(rx))
8751 SvUTF8_on(sv);
8752 else
8753 SvUTF8_off(sv);
8754 if (TAINTING_get) {
8755 if (RXp_MATCH_TAINTED(rx)) {
8756 if (SvTYPE(sv) >= SVt_PVMG) {
8757 MAGIC* const mg = SvMAGIC(sv);
8758 MAGIC* mgt;
8759 TAINT;
8760 SvMAGIC_set(sv, mg->mg_moremagic);
8761 SvTAINT(sv);
8762 if ((mgt = SvMAGIC(sv))) {
8763 mg->mg_moremagic = mgt;
8764 SvMAGIC_set(sv, mg);
8765 }
8766 } else {
8767 TAINT;
8768 SvTAINT(sv);
8769 }
8770 } else
8771 SvTAINTED_off(sv);
8772 }
8773 } else {
8774 ret_undef:
8775 sv_set_undef(sv);
8776 return;
8777 }
8778}
8779
8780void
8781Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
8782 SV const * const value)
8783{
8784 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
8785
8786 PERL_UNUSED_ARG(rx);
8787 PERL_UNUSED_ARG(paren);
8788 PERL_UNUSED_ARG(value);
8789
8790 if (!PL_localizing)
8791 Perl_croak_no_modify();
8792}
8793
8794I32
8795Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
8796 const I32 paren)
8797{
8798 struct regexp *const rx = ReANY(r);
8799 I32 i;
8800 I32 s1, t1;
8801
8802 PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
8803
8804 if ( paren == RX_BUFF_IDX_CARET_PREMATCH
8805 || paren == RX_BUFF_IDX_CARET_FULLMATCH
8806 || paren == RX_BUFF_IDX_CARET_POSTMATCH
8807 )
8808 {
8809 bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8810 if (!keepcopy) {
8811 /* on something like
8812 * $r = qr/.../;
8813 * /$qr/p;
8814 * the KEEPCOPY is set on the PMOP rather than the regex */
8815 if (PL_curpm && r == PM_GETRE(PL_curpm))
8816 keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8817 }
8818 if (!keepcopy)
8819 goto warn_undef;
8820 }
8821
8822 /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
8823 switch (paren) {
8824 case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
8825 case RX_BUFF_IDX_PREMATCH: /* $` */
8826 if (rx->offs[0].start != -1) {
8827 i = rx->offs[0].start;
8828 if (i > 0) {
8829 s1 = 0;
8830 t1 = i;
8831 goto getlen;
8832 }
8833 }
8834 return 0;
8835
8836 case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
8837 case RX_BUFF_IDX_POSTMATCH: /* $' */
8838 if (rx->offs[0].end != -1) {
8839 i = rx->sublen - rx->offs[0].end;
8840 if (i > 0) {
8841 s1 = rx->offs[0].end;
8842 t1 = rx->sublen;
8843 goto getlen;
8844 }
8845 }
8846 return 0;
8847
8848 default: /* $& / ${^MATCH}, $1, $2, ... */
8849 if (paren <= (I32)rx->nparens &&
8850 (s1 = rx->offs[paren].start) != -1 &&
8851 (t1 = rx->offs[paren].end) != -1)
8852 {
8853 i = t1 - s1;
8854 goto getlen;
8855 } else {
8856 warn_undef:
8857 if (ckWARN(WARN_UNINITIALIZED))
8858 report_uninit((const SV *)sv);
8859 return 0;
8860 }
8861 }
8862 getlen:
8863 if (i > 0 && RXp_MATCH_UTF8(rx)) {
8864 const char * const s = rx->subbeg - rx->suboffset + s1;
8865 const U8 *ep;
8866 STRLEN el;
8867
8868 i = t1 - s1;
8869 if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
8870 i = el;
8871 }
8872 return i;
8873}
8874
8875SV*
8876Perl_reg_qr_package(pTHX_ REGEXP * const rx)
8877{
8878 PERL_ARGS_ASSERT_REG_QR_PACKAGE;
8879 PERL_UNUSED_ARG(rx);
8880 if (0)
8881 return NULL;
8882 else
8883 return newSVpvs("Regexp");
8884}
8885
8886/* Scans the name of a named buffer from the pattern.
8887 * If flags is REG_RSN_RETURN_NULL returns null.
8888 * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
8889 * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
8890 * to the parsed name as looked up in the RExC_paren_names hash.
8891 * If there is an error throws a vFAIL().. type exception.
8892 */
8893
8894#define REG_RSN_RETURN_NULL 0
8895#define REG_RSN_RETURN_NAME 1
8896#define REG_RSN_RETURN_DATA 2
8897
8898STATIC SV*
8899S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
8900{
8901 char *name_start = RExC_parse;
8902 SV* sv_name;
8903
8904 PERL_ARGS_ASSERT_REG_SCAN_NAME;
8905
8906 assert (RExC_parse <= RExC_end);
8907 if (RExC_parse == RExC_end) NOOP;
8908 else if (isIDFIRST_lazy_if_safe(RExC_parse, RExC_end, UTF)) {
8909 /* Note that the code here assumes well-formed UTF-8. Skip IDFIRST by
8910 * using do...while */
8911 if (UTF)
8912 do {
8913 RExC_parse += UTF8SKIP(RExC_parse);
8914 } while ( RExC_parse < RExC_end
8915 && isWORDCHAR_utf8_safe((U8*)RExC_parse, (U8*) RExC_end));
8916 else
8917 do {
8918 RExC_parse++;
8919 } while (RExC_parse < RExC_end && isWORDCHAR(*RExC_parse));
8920 } else {
8921 RExC_parse++; /* so the <- from the vFAIL is after the offending
8922 character */
8923 vFAIL("Group name must start with a non-digit word character");
8924 }
8925 sv_name = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
8926 SVs_TEMP | (UTF ? SVf_UTF8 : 0));
8927 if ( flags == REG_RSN_RETURN_NAME)
8928 return sv_name;
8929 else if (flags==REG_RSN_RETURN_DATA) {
8930 HE *he_str = NULL;
8931 SV *sv_dat = NULL;
8932 if ( ! sv_name ) /* should not happen*/
8933 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
8934 if (RExC_paren_names)
8935 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
8936 if ( he_str )
8937 sv_dat = HeVAL(he_str);
8938 if ( ! sv_dat ) { /* Didn't find group */
8939
8940 /* It might be a forward reference; we can't fail until we
8941 * know, by completing the parse to get all the groups, and
8942 * then reparsing */
8943 if (ALL_PARENS_COUNTED) {
8944 vFAIL("Reference to nonexistent named group");
8945 }
8946 else {
8947 REQUIRE_PARENS_PASS;
8948 }
8949 }
8950 return sv_dat;
8951 }
8952
8953 Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
8954 (unsigned long) flags);
8955}
8956
8957#define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
8958 if (RExC_lastparse!=RExC_parse) { \
8959 Perl_re_printf( aTHX_ "%s", \
8960 Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse, \
8961 RExC_end - RExC_parse, 16, \
8962 "", "", \
8963 PERL_PV_ESCAPE_UNI_DETECT | \
8964 PERL_PV_PRETTY_ELLIPSES | \
8965 PERL_PV_PRETTY_LTGT | \
8966 PERL_PV_ESCAPE_RE | \
8967 PERL_PV_PRETTY_EXACTSIZE \
8968 ) \
8969 ); \
8970 } else \
8971 Perl_re_printf( aTHX_ "%16s",""); \
8972 \
8973 if (RExC_lastnum!=RExC_emit) \
8974 Perl_re_printf( aTHX_ "|%4zu", RExC_emit); \
8975 else \
8976 Perl_re_printf( aTHX_ "|%4s",""); \
8977 Perl_re_printf( aTHX_ "|%*s%-4s", \
8978 (int)((depth*2)), "", \
8979 (funcname) \
8980 ); \
8981 RExC_lastnum=RExC_emit; \
8982 RExC_lastparse=RExC_parse; \
8983})
8984
8985
8986
8987#define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
8988 DEBUG_PARSE_MSG((funcname)); \
8989 Perl_re_printf( aTHX_ "%4s","\n"); \
8990})
8991#define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({\
8992 DEBUG_PARSE_MSG((funcname)); \
8993 Perl_re_printf( aTHX_ fmt "\n",args); \
8994})
8995
8996/* This section of code defines the inversion list object and its methods. The
8997 * interfaces are highly subject to change, so as much as possible is static to
8998 * this file. An inversion list is here implemented as a malloc'd C UV array
8999 * as an SVt_INVLIST scalar.
9000 *
9001 * An inversion list for Unicode is an array of code points, sorted by ordinal
9002 * number. Each element gives the code point that begins a range that extends
9003 * up-to but not including the code point given by the next element. The final
9004 * element gives the first code point of a range that extends to the platform's
9005 * infinity. The even-numbered elements (invlist[0], invlist[2], invlist[4],
9006 * ...) give ranges whose code points are all in the inversion list. We say
9007 * that those ranges are in the set. The odd-numbered elements give ranges
9008 * whose code points are not in the inversion list, and hence not in the set.
9009 * Thus, element [0] is the first code point in the list. Element [1]
9010 * is the first code point beyond that not in the list; and element [2] is the
9011 * first code point beyond that that is in the list. In other words, the first
9012 * range is invlist[0]..(invlist[1]-1), and all code points in that range are
9013 * in the inversion list. The second range is invlist[1]..(invlist[2]-1), and
9014 * all code points in that range are not in the inversion list. The third
9015 * range invlist[2]..(invlist[3]-1) gives code points that are in the inversion
9016 * list, and so forth. Thus every element whose index is divisible by two
9017 * gives the beginning of a range that is in the list, and every element whose
9018 * index is not divisible by two gives the beginning of a range not in the
9019 * list. If the final element's index is divisible by two, the inversion list
9020 * extends to the platform's infinity; otherwise the highest code point in the
9021 * inversion list is the contents of that element minus 1.
9022 *
9023 * A range that contains just a single code point N will look like
9024 * invlist[i] == N
9025 * invlist[i+1] == N+1
9026 *
9027 * If N is UV_MAX (the highest representable code point on the machine), N+1 is
9028 * impossible to represent, so element [i+1] is omitted. The single element
9029 * inversion list
9030 * invlist[0] == UV_MAX
9031 * contains just UV_MAX, but is interpreted as matching to infinity.
9032 *
9033 * Taking the complement (inverting) an inversion list is quite simple, if the
9034 * first element is 0, remove it; otherwise add a 0 element at the beginning.
9035 * This implementation reserves an element at the beginning of each inversion
9036 * list to always contain 0; there is an additional flag in the header which
9037 * indicates if the list begins at the 0, or is offset to begin at the next
9038 * element. This means that the inversion list can be inverted without any
9039 * copying; just flip the flag.
9040 *
9041 * More about inversion lists can be found in "Unicode Demystified"
9042 * Chapter 13 by Richard Gillam, published by Addison-Wesley.
9043 *
9044 * The inversion list data structure is currently implemented as an SV pointing
9045 * to an array of UVs that the SV thinks are bytes. This allows us to have an
9046 * array of UV whose memory management is automatically handled by the existing
9047 * facilities for SV's.
9048 *
9049 * Some of the methods should always be private to the implementation, and some
9050 * should eventually be made public */
9051
9052/* The header definitions are in F<invlist_inline.h> */
9053
9054#ifndef PERL_IN_XSUB_RE
9055
9056PERL_STATIC_INLINE UV*
9057S__invlist_array_init(SV* const invlist, const bool will_have_0)
9058{
9059 /* Returns a pointer to the first element in the inversion list's array.
9060 * This is called upon initialization of an inversion list. Where the
9061 * array begins depends on whether the list has the code point U+0000 in it
9062 * or not. The other parameter tells it whether the code that follows this
9063 * call is about to put a 0 in the inversion list or not. The first
9064 * element is either the element reserved for 0, if TRUE, or the element
9065 * after it, if FALSE */
9066
9067 bool* offset = get_invlist_offset_addr(invlist);
9068 UV* zero_addr = (UV *) SvPVX(invlist);
9069
9070 PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
9071
9072 /* Must be empty */
9073 assert(! _invlist_len(invlist));
9074
9075 *zero_addr = 0;
9076
9077 /* 1^1 = 0; 1^0 = 1 */
9078 *offset = 1 ^ will_have_0;
9079 return zero_addr + *offset;
9080}
9081
9082STATIC void
9083S_invlist_replace_list_destroys_src(pTHX_ SV * dest, SV * src)
9084{
9085 /* Replaces the inversion list in 'dest' with the one from 'src'. It
9086 * steals the list from 'src', so 'src' is made to have a NULL list. This
9087 * is similar to what SvSetMagicSV() would do, if it were implemented on
9088 * inversion lists, though this routine avoids a copy */
9089
9090 const UV src_len = _invlist_len(src);
9091 const bool src_offset = *get_invlist_offset_addr(src);
9092 const STRLEN src_byte_len = SvLEN(src);
9093 char * array = SvPVX(src);
9094
9095 const int oldtainted = TAINT_get;
9096
9097 PERL_ARGS_ASSERT_INVLIST_REPLACE_LIST_DESTROYS_SRC;
9098
9099 assert(is_invlist(src));
9100 assert(is_invlist(dest));
9101 assert(! invlist_is_iterating(src));
9102 assert(SvCUR(src) == 0 || SvCUR(src) < SvLEN(src));
9103
9104 /* Make sure it ends in the right place with a NUL, as our inversion list
9105 * manipulations aren't careful to keep this true, but sv_usepvn_flags()
9106 * asserts it */
9107 array[src_byte_len - 1] = '\0';
9108
9109 TAINT_NOT; /* Otherwise it breaks */
9110 sv_usepvn_flags(dest,
9111 (char *) array,
9112 src_byte_len - 1,
9113
9114 /* This flag is documented to cause a copy to be avoided */
9115 SV_HAS_TRAILING_NUL);
9116 TAINT_set(oldtainted);
9117 SvPV_set(src, 0);
9118 SvLEN_set(src, 0);
9119 SvCUR_set(src, 0);
9120
9121 /* Finish up copying over the other fields in an inversion list */
9122 *get_invlist_offset_addr(dest) = src_offset;
9123 invlist_set_len(dest, src_len, src_offset);
9124 *get_invlist_previous_index_addr(dest) = 0;
9125 invlist_iterfinish(dest);
9126}
9127
9128PERL_STATIC_INLINE IV*
9129S_get_invlist_previous_index_addr(SV* invlist)
9130{
9131 /* Return the address of the IV that is reserved to hold the cached index
9132 * */
9133 PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
9134
9135 assert(is_invlist(invlist));
9136
9137 return &(((XINVLIST*) SvANY(invlist))->prev_index);
9138}
9139
9140PERL_STATIC_INLINE IV
9141S_invlist_previous_index(SV* const invlist)
9142{
9143 /* Returns cached index of previous search */
9144
9145 PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
9146
9147 return *get_invlist_previous_index_addr(invlist);
9148}
9149
9150PERL_STATIC_INLINE void
9151S_invlist_set_previous_index(SV* const invlist, const IV index)
9152{
9153 /* Caches <index> for later retrieval */
9154
9155 PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
9156
9157 assert(index == 0 || index < (int) _invlist_len(invlist));
9158
9159 *get_invlist_previous_index_addr(invlist) = index;
9160}
9161
9162PERL_STATIC_INLINE void
9163S_invlist_trim(SV* invlist)
9164{
9165 /* Free the not currently-being-used space in an inversion list */
9166
9167 /* But don't free up the space needed for the 0 UV that is always at the
9168 * beginning of the list, nor the trailing NUL */
9169 const UV min_size = TO_INTERNAL_SIZE(1) + 1;
9170
9171 PERL_ARGS_ASSERT_INVLIST_TRIM;
9172
9173 assert(is_invlist(invlist));
9174
9175 SvPV_renew(invlist, MAX(min_size, SvCUR(invlist) + 1));
9176}
9177
9178PERL_STATIC_INLINE void
9179S_invlist_clear(pTHX_ SV* invlist) /* Empty the inversion list */
9180{
9181 PERL_ARGS_ASSERT_INVLIST_CLEAR;
9182
9183 assert(is_invlist(invlist));
9184
9185 invlist_set_len(invlist, 0, 0);
9186 invlist_trim(invlist);
9187}
9188
9189#endif /* ifndef PERL_IN_XSUB_RE */
9190
9191PERL_STATIC_INLINE bool
9192S_invlist_is_iterating(SV* const invlist)
9193{
9194 PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
9195
9196 return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX;
9197}
9198
9199#ifndef PERL_IN_XSUB_RE
9200
9201PERL_STATIC_INLINE UV
9202S_invlist_max(SV* const invlist)
9203{
9204 /* Returns the maximum number of elements storable in the inversion list's
9205 * array, without having to realloc() */
9206
9207 PERL_ARGS_ASSERT_INVLIST_MAX;
9208
9209 assert(is_invlist(invlist));
9210
9211 /* Assumes worst case, in which the 0 element is not counted in the
9212 * inversion list, so subtracts 1 for that */
9213 return SvLEN(invlist) == 0 /* This happens under _new_invlist_C_array */
9214 ? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1
9215 : FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1;
9216}
9217
9218STATIC void
9219S_initialize_invlist_guts(pTHX_ SV* invlist, const Size_t initial_size)
9220{
9221 PERL_ARGS_ASSERT_INITIALIZE_INVLIST_GUTS;
9222
9223 /* First 1 is in case the zero element isn't in the list; second 1 is for
9224 * trailing NUL */
9225 SvGROW(invlist, TO_INTERNAL_SIZE(initial_size + 1) + 1);
9226 invlist_set_len(invlist, 0, 0);
9227
9228 /* Force iterinit() to be used to get iteration to work */
9229 invlist_iterfinish(invlist);
9230
9231 *get_invlist_previous_index_addr(invlist) = 0;
9232 SvPOK_on(invlist); /* This allows B to extract the PV */
9233}
9234
9235SV*
9236Perl__new_invlist(pTHX_ IV initial_size)
9237{
9238
9239 /* Return a pointer to a newly constructed inversion list, with enough
9240 * space to store 'initial_size' elements. If that number is negative, a
9241 * system default is used instead */
9242
9243 SV* new_list;
9244
9245 if (initial_size < 0) {
9246 initial_size = 10;
9247 }
9248
9249 new_list = newSV_type(SVt_INVLIST);
9250 initialize_invlist_guts(new_list, initial_size);
9251
9252 return new_list;
9253}
9254
9255SV*
9256Perl__new_invlist_C_array(pTHX_ const UV* const list)
9257{
9258 /* Return a pointer to a newly constructed inversion list, initialized to
9259 * point to <list>, which has to be in the exact correct inversion list
9260 * form, including internal fields. Thus this is a dangerous routine that
9261 * should not be used in the wrong hands. The passed in 'list' contains
9262 * several header fields at the beginning that are not part of the
9263 * inversion list body proper */
9264
9265 const STRLEN length = (STRLEN) list[0];
9266 const UV version_id = list[1];
9267 const bool offset = cBOOL(list[2]);
9268#define HEADER_LENGTH 3
9269 /* If any of the above changes in any way, you must change HEADER_LENGTH
9270 * (if appropriate) and regenerate INVLIST_VERSION_ID by running
9271 * perl -E 'say int(rand 2**31-1)'
9272 */
9273#define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and
9274 data structure type, so that one being
9275 passed in can be validated to be an
9276 inversion list of the correct vintage.
9277 */
9278
9279 SV* invlist = newSV_type(SVt_INVLIST);
9280
9281 PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
9282
9283 if (version_id != INVLIST_VERSION_ID) {
9284 Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
9285 }
9286
9287 /* The generated array passed in includes header elements that aren't part
9288 * of the list proper, so start it just after them */
9289 SvPV_set(invlist, (char *) (list + HEADER_LENGTH));
9290
9291 SvLEN_set(invlist, 0); /* Means we own the contents, and the system
9292 shouldn't touch it */
9293
9294 *(get_invlist_offset_addr(invlist)) = offset;
9295
9296 /* The 'length' passed to us is the physical number of elements in the
9297 * inversion list. But if there is an offset the logical number is one
9298 * less than that */
9299 invlist_set_len(invlist, length - offset, offset);
9300
9301 invlist_set_previous_index(invlist, 0);
9302
9303 /* Initialize the iteration pointer. */
9304 invlist_iterfinish(invlist);
9305
9306 SvREADONLY_on(invlist);
9307 SvPOK_on(invlist);
9308
9309 return invlist;
9310}
9311
9312STATIC void
9313S__append_range_to_invlist(pTHX_ SV* const invlist,
9314 const UV start, const UV end)
9315{
9316 /* Subject to change or removal. Append the range from 'start' to 'end' at
9317 * the end of the inversion list. The range must be above any existing
9318 * ones. */
9319
9320 UV* array;
9321 UV max = invlist_max(invlist);
9322 UV len = _invlist_len(invlist);
9323 bool offset;
9324
9325 PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
9326
9327 if (len == 0) { /* Empty lists must be initialized */
9328 offset = start != 0;
9329 array = _invlist_array_init(invlist, ! offset);
9330 }
9331 else {
9332 /* Here, the existing list is non-empty. The current max entry in the
9333 * list is generally the first value not in the set, except when the
9334 * set extends to the end of permissible values, in which case it is
9335 * the first entry in that final set, and so this call is an attempt to
9336 * append out-of-order */
9337
9338 UV final_element = len - 1;
9339 array = invlist_array(invlist);
9340 if ( array[final_element] > start
9341 || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
9342 {
9343 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",
9344 array[final_element], start,
9345 ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
9346 }
9347
9348 /* Here, it is a legal append. If the new range begins 1 above the end
9349 * of the range below it, it is extending the range below it, so the
9350 * new first value not in the set is one greater than the newly
9351 * extended range. */
9352 offset = *get_invlist_offset_addr(invlist);
9353 if (array[final_element] == start) {
9354 if (end != UV_MAX) {
9355 array[final_element] = end + 1;
9356 }
9357 else {
9358 /* But if the end is the maximum representable on the machine,
9359 * assume that infinity was actually what was meant. Just let
9360 * the range that this would extend to have no end */
9361 invlist_set_len(invlist, len - 1, offset);
9362 }
9363 return;
9364 }
9365 }
9366
9367 /* Here the new range doesn't extend any existing set. Add it */
9368
9369 len += 2; /* Includes an element each for the start and end of range */
9370
9371 /* If wll overflow the existing space, extend, which may cause the array to
9372 * be moved */
9373 if (max < len) {
9374 invlist_extend(invlist, len);
9375
9376 /* Have to set len here to avoid assert failure in invlist_array() */
9377 invlist_set_len(invlist, len, offset);
9378
9379 array = invlist_array(invlist);
9380 }
9381 else {
9382 invlist_set_len(invlist, len, offset);
9383 }
9384
9385 /* The next item on the list starts the range, the one after that is
9386 * one past the new range. */
9387 array[len - 2] = start;
9388 if (end != UV_MAX) {
9389 array[len - 1] = end + 1;
9390 }
9391 else {
9392 /* But if the end is the maximum representable on the machine, just let
9393 * the range have no end */
9394 invlist_set_len(invlist, len - 1, offset);
9395 }
9396}
9397
9398SSize_t
9399Perl__invlist_search(SV* const invlist, const UV cp)
9400{
9401 /* Searches the inversion list for the entry that contains the input code
9402 * point <cp>. If <cp> is not in the list, -1 is returned. Otherwise, the
9403 * return value is the index into the list's array of the range that
9404 * contains <cp>, that is, 'i' such that
9405 * array[i] <= cp < array[i+1]
9406 */
9407
9408 IV low = 0;
9409 IV mid;
9410 IV high = _invlist_len(invlist);
9411 const IV highest_element = high - 1;
9412 const UV* array;
9413
9414 PERL_ARGS_ASSERT__INVLIST_SEARCH;
9415
9416 /* If list is empty, return failure. */
9417 if (high == 0) {
9418 return -1;
9419 }
9420
9421 /* (We can't get the array unless we know the list is non-empty) */
9422 array = invlist_array(invlist);
9423
9424 mid = invlist_previous_index(invlist);
9425 assert(mid >=0);
9426 if (mid > highest_element) {
9427 mid = highest_element;
9428 }
9429
9430 /* <mid> contains the cache of the result of the previous call to this
9431 * function (0 the first time). See if this call is for the same result,
9432 * or if it is for mid-1. This is under the theory that calls to this
9433 * function will often be for related code points that are near each other.
9434 * And benchmarks show that caching gives better results. We also test
9435 * here if the code point is within the bounds of the list. These tests
9436 * replace others that would have had to be made anyway to make sure that
9437 * the array bounds were not exceeded, and these give us extra information
9438 * at the same time */
9439 if (cp >= array[mid]) {
9440 if (cp >= array[highest_element]) {
9441 return highest_element;
9442 }
9443
9444 /* Here, array[mid] <= cp < array[highest_element]. This means that
9445 * the final element is not the answer, so can exclude it; it also
9446 * means that <mid> is not the final element, so can refer to 'mid + 1'
9447 * safely */
9448 if (cp < array[mid + 1]) {
9449 return mid;
9450 }
9451 high--;
9452 low = mid + 1;
9453 }
9454 else { /* cp < aray[mid] */
9455 if (cp < array[0]) { /* Fail if outside the array */
9456 return -1;
9457 }
9458 high = mid;
9459 if (cp >= array[mid - 1]) {
9460 goto found_entry;
9461 }
9462 }
9463
9464 /* Binary search. What we are looking for is <i> such that
9465 * array[i] <= cp < array[i+1]
9466 * The loop below converges on the i+1. Note that there may not be an
9467 * (i+1)th element in the array, and things work nonetheless */
9468 while (low < high) {
9469 mid = (low + high) / 2;
9470 assert(mid <= highest_element);
9471 if (array[mid] <= cp) { /* cp >= array[mid] */
9472 low = mid + 1;
9473
9474 /* We could do this extra test to exit the loop early.
9475 if (cp < array[low]) {
9476 return mid;
9477 }
9478 */
9479 }
9480 else { /* cp < array[mid] */
9481 high = mid;
9482 }
9483 }
9484
9485 found_entry:
9486 high--;
9487 invlist_set_previous_index(invlist, high);
9488 return high;
9489}
9490
9491void
9492Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9493 const bool complement_b, SV** output)
9494{
9495 /* Take the union of two inversion lists and point '*output' to it. On
9496 * input, '*output' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9497 * even 'a' or 'b'). If to an inversion list, the contents of the original
9498 * list will be replaced by the union. The first list, 'a', may be
9499 * NULL, in which case a copy of the second list is placed in '*output'.
9500 * If 'complement_b' is TRUE, the union is taken of the complement
9501 * (inversion) of 'b' instead of b itself.
9502 *
9503 * The basis for this comes from "Unicode Demystified" Chapter 13 by
9504 * Richard Gillam, published by Addison-Wesley, and explained at some
9505 * length there. The preface says to incorporate its examples into your
9506 * code at your own risk.
9507 *
9508 * The algorithm is like a merge sort. */
9509
9510 const UV* array_a; /* a's array */
9511 const UV* array_b;
9512 UV len_a; /* length of a's array */
9513 UV len_b;
9514
9515 SV* u; /* the resulting union */
9516 UV* array_u;
9517 UV len_u = 0;
9518
9519 UV i_a = 0; /* current index into a's array */
9520 UV i_b = 0;
9521 UV i_u = 0;
9522
9523 /* running count, as explained in the algorithm source book; items are
9524 * stopped accumulating and are output when the count changes to/from 0.
9525 * The count is incremented when we start a range that's in an input's set,
9526 * and decremented when we start a range that's not in a set. So this
9527 * variable can be 0, 1, or 2. When it is 0 neither input is in their set,
9528 * and hence nothing goes into the union; 1, just one of the inputs is in
9529 * its set (and its current range gets added to the union); and 2 when both
9530 * inputs are in their sets. */
9531 UV count = 0;
9532
9533 PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
9534 assert(a != b);
9535 assert(*output == NULL || is_invlist(*output));
9536
9537 len_b = _invlist_len(b);
9538 if (len_b == 0) {
9539
9540 /* Here, 'b' is empty, hence it's complement is all possible code
9541 * points. So if the union includes the complement of 'b', it includes
9542 * everything, and we need not even look at 'a'. It's easiest to
9543 * create a new inversion list that matches everything. */
9544 if (complement_b) {
9545 SV* everything = _add_range_to_invlist(NULL, 0, UV_MAX);
9546
9547 if (*output == NULL) { /* If the output didn't exist, just point it
9548 at the new list */
9549 *output = everything;
9550 }
9551 else { /* Otherwise, replace its contents with the new list */
9552 invlist_replace_list_destroys_src(*output, everything);
9553 SvREFCNT_dec_NN(everything);
9554 }
9555
9556 return;
9557 }
9558
9559 /* Here, we don't want the complement of 'b', and since 'b' is empty,
9560 * the union will come entirely from 'a'. If 'a' is NULL or empty, the
9561 * output will be empty */
9562
9563 if (a == NULL || _invlist_len(a) == 0) {
9564 if (*output == NULL) {
9565 *output = _new_invlist(0);
9566 }
9567 else {
9568 invlist_clear(*output);
9569 }
9570 return;
9571 }
9572
9573 /* Here, 'a' is not empty, but 'b' is, so 'a' entirely determines the
9574 * union. We can just return a copy of 'a' if '*output' doesn't point
9575 * to an existing list */
9576 if (*output == NULL) {
9577 *output = invlist_clone(a, NULL);
9578 return;
9579 }
9580
9581 /* If the output is to overwrite 'a', we have a no-op, as it's
9582 * already in 'a' */
9583 if (*output == a) {
9584 return;
9585 }
9586
9587 /* Here, '*output' is to be overwritten by 'a' */
9588 u = invlist_clone(a, NULL);
9589 invlist_replace_list_destroys_src(*output, u);
9590 SvREFCNT_dec_NN(u);
9591
9592 return;
9593 }
9594
9595 /* Here 'b' is not empty. See about 'a' */
9596
9597 if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
9598
9599 /* Here, 'a' is empty (and b is not). That means the union will come
9600 * entirely from 'b'. If '*output' is NULL, we can directly return a
9601 * clone of 'b'. Otherwise, we replace the contents of '*output' with
9602 * the clone */
9603
9604 SV ** dest = (*output == NULL) ? output : &u;
9605 *dest = invlist_clone(b, NULL);
9606 if (complement_b) {
9607 _invlist_invert(*dest);
9608 }
9609
9610 if (dest == &u) {
9611 invlist_replace_list_destroys_src(*output, u);
9612 SvREFCNT_dec_NN(u);
9613 }
9614
9615 return;
9616 }
9617
9618 /* Here both lists exist and are non-empty */
9619 array_a = invlist_array(a);
9620 array_b = invlist_array(b);
9621
9622 /* If are to take the union of 'a' with the complement of b, set it
9623 * up so are looking at b's complement. */
9624 if (complement_b) {
9625
9626 /* To complement, we invert: if the first element is 0, remove it. To
9627 * do this, we just pretend the array starts one later */
9628 if (array_b[0] == 0) {
9629 array_b++;
9630 len_b--;
9631 }
9632 else {
9633
9634 /* But if the first element is not zero, we pretend the list starts
9635 * at the 0 that is always stored immediately before the array. */
9636 array_b--;
9637 len_b++;
9638 }
9639 }
9640
9641 /* Size the union for the worst case: that the sets are completely
9642 * disjoint */
9643 u = _new_invlist(len_a + len_b);
9644
9645 /* Will contain U+0000 if either component does */
9646 array_u = _invlist_array_init(u, ( len_a > 0 && array_a[0] == 0)
9647 || (len_b > 0 && array_b[0] == 0));
9648
9649 /* Go through each input list item by item, stopping when have exhausted
9650 * one of them */
9651 while (i_a < len_a && i_b < len_b) {
9652 UV cp; /* The element to potentially add to the union's array */
9653 bool cp_in_set; /* is it in the the input list's set or not */
9654
9655 /* We need to take one or the other of the two inputs for the union.
9656 * Since we are merging two sorted lists, we take the smaller of the
9657 * next items. In case of a tie, we take first the one that is in its
9658 * set. If we first took the one not in its set, it would decrement
9659 * the count, possibly to 0 which would cause it to be output as ending
9660 * the range, and the next time through we would take the same number,
9661 * and output it again as beginning the next range. By doing it the
9662 * opposite way, there is no possibility that the count will be
9663 * momentarily decremented to 0, and thus the two adjoining ranges will
9664 * be seamlessly merged. (In a tie and both are in the set or both not
9665 * in the set, it doesn't matter which we take first.) */
9666 if ( array_a[i_a] < array_b[i_b]
9667 || ( array_a[i_a] == array_b[i_b]
9668 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9669 {
9670 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9671 cp = array_a[i_a++];
9672 }
9673 else {
9674 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9675 cp = array_b[i_b++];
9676 }
9677
9678 /* Here, have chosen which of the two inputs to look at. Only output
9679 * if the running count changes to/from 0, which marks the
9680 * beginning/end of a range that's in the set */
9681 if (cp_in_set) {
9682 if (count == 0) {
9683 array_u[i_u++] = cp;
9684 }
9685 count++;
9686 }
9687 else {
9688 count--;
9689 if (count == 0) {
9690 array_u[i_u++] = cp;
9691 }
9692 }
9693 }
9694
9695
9696 /* The loop above increments the index into exactly one of the input lists
9697 * each iteration, and ends when either index gets to its list end. That
9698 * means the other index is lower than its end, and so something is
9699 * remaining in that one. We decrement 'count', as explained below, if
9700 * that list is in its set. (i_a and i_b each currently index the element
9701 * beyond the one we care about.) */
9702 if ( (i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9703 || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9704 {
9705 count--;
9706 }
9707
9708 /* Above we decremented 'count' if the list that had unexamined elements in
9709 * it was in its set. This has made it so that 'count' being non-zero
9710 * means there isn't anything left to output; and 'count' equal to 0 means
9711 * that what is left to output is precisely that which is left in the
9712 * non-exhausted input list.
9713 *
9714 * To see why, note first that the exhausted input obviously has nothing
9715 * left to add to the union. If it was in its set at its end, that means
9716 * the set extends from here to the platform's infinity, and hence so does
9717 * the union and the non-exhausted set is irrelevant. The exhausted set
9718 * also contributed 1 to 'count'. If 'count' was 2, it got decremented to
9719 * 1, but if it was 1, the non-exhausted set wasn't in its set, and so
9720 * 'count' remains at 1. This is consistent with the decremented 'count'
9721 * != 0 meaning there's nothing left to add to the union.
9722 *
9723 * But if the exhausted input wasn't in its set, it contributed 0 to
9724 * 'count', and the rest of the union will be whatever the other input is.
9725 * If 'count' was 0, neither list was in its set, and 'count' remains 0;
9726 * otherwise it gets decremented to 0. This is consistent with 'count'
9727 * == 0 meaning the remainder of the union is whatever is left in the
9728 * non-exhausted list. */
9729 if (count != 0) {
9730 len_u = i_u;
9731 }
9732 else {
9733 IV copy_count = len_a - i_a;
9734 if (copy_count > 0) { /* The non-exhausted input is 'a' */
9735 Copy(array_a + i_a, array_u + i_u, copy_count, UV);
9736 }
9737 else { /* The non-exhausted input is b */
9738 copy_count = len_b - i_b;
9739 Copy(array_b + i_b, array_u + i_u, copy_count, UV);
9740 }
9741 len_u = i_u + copy_count;
9742 }
9743
9744 /* Set the result to the final length, which can change the pointer to
9745 * array_u, so re-find it. (Note that it is unlikely that this will
9746 * change, as we are shrinking the space, not enlarging it) */
9747 if (len_u != _invlist_len(u)) {
9748 invlist_set_len(u, len_u, *get_invlist_offset_addr(u));
9749 invlist_trim(u);
9750 array_u = invlist_array(u);
9751 }
9752
9753 if (*output == NULL) { /* Simply return the new inversion list */
9754 *output = u;
9755 }
9756 else {
9757 /* Otherwise, overwrite the inversion list that was in '*output'. We
9758 * could instead free '*output', and then set it to 'u', but experience
9759 * has shown [perl #127392] that if the input is a mortal, we can get a
9760 * huge build-up of these during regex compilation before they get
9761 * freed. */
9762 invlist_replace_list_destroys_src(*output, u);
9763 SvREFCNT_dec_NN(u);
9764 }
9765
9766 return;
9767}
9768
9769void
9770Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9771 const bool complement_b, SV** i)
9772{
9773 /* Take the intersection of two inversion lists and point '*i' to it. On
9774 * input, '*i' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9775 * even 'a' or 'b'). If to an inversion list, the contents of the original
9776 * list will be replaced by the intersection. The first list, 'a', may be
9777 * NULL, in which case '*i' will be an empty list. If 'complement_b' is
9778 * TRUE, the result will be the intersection of 'a' and the complement (or
9779 * inversion) of 'b' instead of 'b' directly.
9780 *
9781 * The basis for this comes from "Unicode Demystified" Chapter 13 by
9782 * Richard Gillam, published by Addison-Wesley, and explained at some
9783 * length there. The preface says to incorporate its examples into your
9784 * code at your own risk. In fact, it had bugs
9785 *
9786 * The algorithm is like a merge sort, and is essentially the same as the
9787 * union above
9788 */
9789
9790 const UV* array_a; /* a's array */
9791 const UV* array_b;
9792 UV len_a; /* length of a's array */
9793 UV len_b;
9794
9795 SV* r; /* the resulting intersection */
9796 UV* array_r;
9797 UV len_r = 0;
9798
9799 UV i_a = 0; /* current index into a's array */
9800 UV i_b = 0;
9801 UV i_r = 0;
9802
9803 /* running count of how many of the two inputs are postitioned at ranges
9804 * that are in their sets. As explained in the algorithm source book,
9805 * items are stopped accumulating and are output when the count changes
9806 * to/from 2. The count is incremented when we start a range that's in an
9807 * input's set, and decremented when we start a range that's not in a set.
9808 * Only when it is 2 are we in the intersection. */
9809 UV count = 0;
9810
9811 PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
9812 assert(a != b);
9813 assert(*i == NULL || is_invlist(*i));
9814
9815 /* Special case if either one is empty */
9816 len_a = (a == NULL) ? 0 : _invlist_len(a);
9817 if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
9818 if (len_a != 0 && complement_b) {
9819
9820 /* Here, 'a' is not empty, therefore from the enclosing 'if', 'b'
9821 * must be empty. Here, also we are using 'b's complement, which
9822 * hence must be every possible code point. Thus the intersection
9823 * is simply 'a'. */
9824
9825 if (*i == a) { /* No-op */
9826 return;
9827 }
9828
9829 if (*i == NULL) {
9830 *i = invlist_clone(a, NULL);
9831 return;
9832 }
9833
9834 r = invlist_clone(a, NULL);
9835 invlist_replace_list_destroys_src(*i, r);
9836 SvREFCNT_dec_NN(r);
9837 return;
9838 }
9839
9840 /* Here, 'a' or 'b' is empty and not using the complement of 'b'. The
9841 * intersection must be empty */
9842 if (*i == NULL) {
9843 *i = _new_invlist(0);
9844 return;
9845 }
9846
9847 invlist_clear(*i);
9848 return;
9849 }
9850
9851 /* Here both lists exist and are non-empty */
9852 array_a = invlist_array(a);
9853 array_b = invlist_array(b);
9854
9855 /* If are to take the intersection of 'a' with the complement of b, set it
9856 * up so are looking at b's complement. */
9857 if (complement_b) {
9858
9859 /* To complement, we invert: if the first element is 0, remove it. To
9860 * do this, we just pretend the array starts one later */
9861 if (array_b[0] == 0) {
9862 array_b++;
9863 len_b--;
9864 }
9865 else {
9866
9867 /* But if the first element is not zero, we pretend the list starts
9868 * at the 0 that is always stored immediately before the array. */
9869 array_b--;
9870 len_b++;
9871 }
9872 }
9873
9874 /* Size the intersection for the worst case: that the intersection ends up
9875 * fragmenting everything to be completely disjoint */
9876 r= _new_invlist(len_a + len_b);
9877
9878 /* Will contain U+0000 iff both components do */
9879 array_r = _invlist_array_init(r, len_a > 0 && array_a[0] == 0
9880 && len_b > 0 && array_b[0] == 0);
9881
9882 /* Go through each list item by item, stopping when have exhausted one of
9883 * them */
9884 while (i_a < len_a && i_b < len_b) {
9885 UV cp; /* The element to potentially add to the intersection's
9886 array */
9887 bool cp_in_set; /* Is it in the input list's set or not */
9888
9889 /* We need to take one or the other of the two inputs for the
9890 * intersection. Since we are merging two sorted lists, we take the
9891 * smaller of the next items. In case of a tie, we take first the one
9892 * that is not in its set (a difference from the union algorithm). If
9893 * we first took the one in its set, it would increment the count,
9894 * possibly to 2 which would cause it to be output as starting a range
9895 * in the intersection, and the next time through we would take that
9896 * same number, and output it again as ending the set. By doing the
9897 * opposite of this, there is no possibility that the count will be
9898 * momentarily incremented to 2. (In a tie and both are in the set or
9899 * both not in the set, it doesn't matter which we take first.) */
9900 if ( array_a[i_a] < array_b[i_b]
9901 || ( array_a[i_a] == array_b[i_b]
9902 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9903 {
9904 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9905 cp = array_a[i_a++];
9906 }
9907 else {
9908 cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9909 cp= array_b[i_b++];
9910 }
9911
9912 /* Here, have chosen which of the two inputs to look at. Only output
9913 * if the running count changes to/from 2, which marks the
9914 * beginning/end of a range that's in the intersection */
9915 if (cp_in_set) {
9916 count++;
9917 if (count == 2) {
9918 array_r[i_r++] = cp;
9919 }
9920 }
9921 else {
9922 if (count == 2) {
9923 array_r[i_r++] = cp;
9924 }
9925 count--;
9926 }
9927
9928 }
9929
9930 /* The loop above increments the index into exactly one of the input lists
9931 * each iteration, and ends when either index gets to its list end. That
9932 * means the other index is lower than its end, and so something is
9933 * remaining in that one. We increment 'count', as explained below, if the
9934 * exhausted list was in its set. (i_a and i_b each currently index the
9935 * element beyond the one we care about.) */
9936 if ( (i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9937 || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9938 {
9939 count++;
9940 }
9941
9942 /* Above we incremented 'count' if the exhausted list was in its set. This
9943 * has made it so that 'count' being below 2 means there is nothing left to
9944 * output; otheriwse what's left to add to the intersection is precisely
9945 * that which is left in the non-exhausted input list.
9946 *
9947 * To see why, note first that the exhausted input obviously has nothing
9948 * left to affect the intersection. If it was in its set at its end, that
9949 * means the set extends from here to the platform's infinity, and hence
9950 * anything in the non-exhausted's list will be in the intersection, and
9951 * anything not in it won't be. Hence, the rest of the intersection is
9952 * precisely what's in the non-exhausted list The exhausted set also
9953 * contributed 1 to 'count', meaning 'count' was at least 1. Incrementing
9954 * it means 'count' is now at least 2. This is consistent with the
9955 * incremented 'count' being >= 2 means to add the non-exhausted list to
9956 * the intersection.
9957 *
9958 * But if the exhausted input wasn't in its set, it contributed 0 to
9959 * 'count', and the intersection can't include anything further; the
9960 * non-exhausted set is irrelevant. 'count' was at most 1, and doesn't get
9961 * incremented. This is consistent with 'count' being < 2 meaning nothing
9962 * further to add to the intersection. */
9963 if (count < 2) { /* Nothing left to put in the intersection. */
9964 len_r = i_r;
9965 }
9966 else { /* copy the non-exhausted list, unchanged. */
9967 IV copy_count = len_a - i_a;
9968 if (copy_count > 0) { /* a is the one with stuff left */
9969 Copy(array_a + i_a, array_r + i_r, copy_count, UV);
9970 }
9971 else { /* b is the one with stuff left */
9972 copy_count = len_b - i_b;
9973 Copy(array_b + i_b, array_r + i_r, copy_count, UV);
9974 }
9975 len_r = i_r + copy_count;
9976 }
9977
9978 /* Set the result to the final length, which can change the pointer to
9979 * array_r, so re-find it. (Note that it is unlikely that this will
9980 * change, as we are shrinking the space, not enlarging it) */
9981 if (len_r != _invlist_len(r)) {
9982 invlist_set_len(r, len_r, *get_invlist_offset_addr(r));
9983 invlist_trim(r);
9984 array_r = invlist_array(r);
9985 }
9986
9987 if (*i == NULL) { /* Simply return the calculated intersection */
9988 *i = r;
9989 }
9990 else { /* Otherwise, replace the existing inversion list in '*i'. We could
9991 instead free '*i', and then set it to 'r', but experience has
9992 shown [perl #127392] that if the input is a mortal, we can get a
9993 huge build-up of these during regex compilation before they get
9994 freed. */
9995 if (len_r) {
9996 invlist_replace_list_destroys_src(*i, r);
9997 }
9998 else {
9999 invlist_clear(*i);
10000 }
10001 SvREFCNT_dec_NN(r);
10002 }
10003
10004 return;
10005}
10006
10007SV*
10008Perl__add_range_to_invlist(pTHX_ SV* invlist, UV start, UV end)
10009{
10010 /* Add the range from 'start' to 'end' inclusive to the inversion list's
10011 * set. A pointer to the inversion list is returned. This may actually be
10012 * a new list, in which case the passed in one has been destroyed. The
10013 * passed-in inversion list can be NULL, in which case a new one is created
10014 * with just the one range in it. The new list is not necessarily
10015 * NUL-terminated. Space is not freed if the inversion list shrinks as a
10016 * result of this function. The gain would not be large, and in many
10017 * cases, this is called multiple times on a single inversion list, so
10018 * anything freed may almost immediately be needed again.
10019 *
10020 * This used to mostly call the 'union' routine, but that is much more
10021 * heavyweight than really needed for a single range addition */
10022
10023 UV* array; /* The array implementing the inversion list */
10024 UV len; /* How many elements in 'array' */
10025 SSize_t i_s; /* index into the invlist array where 'start'
10026 should go */
10027 SSize_t i_e = 0; /* And the index where 'end' should go */
10028 UV cur_highest; /* The highest code point in the inversion list
10029 upon entry to this function */
10030
10031 /* This range becomes the whole inversion list if none already existed */
10032 if (invlist == NULL) {
10033 invlist = _new_invlist(2);
10034 _append_range_to_invlist(invlist, start, end);
10035 return invlist;
10036 }
10037
10038 /* Likewise, if the inversion list is currently empty */
10039 len = _invlist_len(invlist);
10040 if (len == 0) {
10041 _append_range_to_invlist(invlist, start, end);
10042 return invlist;
10043 }
10044
10045 /* Starting here, we have to know the internals of the list */
10046 array = invlist_array(invlist);
10047
10048 /* If the new range ends higher than the current highest ... */
10049 cur_highest = invlist_highest(invlist);
10050 if (end > cur_highest) {
10051
10052 /* If the whole range is higher, we can just append it */
10053 if (start > cur_highest) {
10054 _append_range_to_invlist(invlist, start, end);
10055 return invlist;
10056 }
10057
10058 /* Otherwise, add the portion that is higher ... */
10059 _append_range_to_invlist(invlist, cur_highest + 1, end);
10060
10061 /* ... and continue on below to handle the rest. As a result of the
10062 * above append, we know that the index of the end of the range is the
10063 * final even numbered one of the array. Recall that the final element
10064 * always starts a range that extends to infinity. If that range is in
10065 * the set (meaning the set goes from here to infinity), it will be an
10066 * even index, but if it isn't in the set, it's odd, and the final
10067 * range in the set is one less, which is even. */
10068 if (end == UV_MAX) {
10069 i_e = len;
10070 }
10071 else {
10072 i_e = len - 2;
10073 }
10074 }
10075
10076 /* We have dealt with appending, now see about prepending. If the new
10077 * range starts lower than the current lowest ... */
10078 if (start < array[0]) {
10079
10080 /* Adding something which has 0 in it is somewhat tricky, and uncommon.
10081 * Let the union code handle it, rather than having to know the
10082 * trickiness in two code places. */
10083 if (UNLIKELY(start == 0)) {
10084 SV* range_invlist;
10085
10086 range_invlist = _new_invlist(2);
10087 _append_range_to_invlist(range_invlist, start, end);
10088
10089 _invlist_union(invlist, range_invlist, &invlist);
10090
10091 SvREFCNT_dec_NN(range_invlist);
10092
10093 return invlist;
10094 }
10095
10096 /* If the whole new range comes before the first entry, and doesn't
10097 * extend it, we have to insert it as an additional range */
10098 if (end < array[0] - 1) {
10099 i_s = i_e = -1;
10100 goto splice_in_new_range;
10101 }
10102
10103 /* Here the new range adjoins the existing first range, extending it
10104 * downwards. */
10105 array[0] = start;
10106
10107 /* And continue on below to handle the rest. We know that the index of
10108 * the beginning of the range is the first one of the array */
10109 i_s = 0;
10110 }
10111 else { /* Not prepending any part of the new range to the existing list.
10112 * Find where in the list it should go. This finds i_s, such that:
10113 * invlist[i_s] <= start < array[i_s+1]
10114 */
10115 i_s = _invlist_search(invlist, start);
10116 }
10117
10118 /* At this point, any extending before the beginning of the inversion list
10119 * and/or after the end has been done. This has made it so that, in the
10120 * code below, each endpoint of the new range is either in a range that is
10121 * in the set, or is in a gap between two ranges that are. This means we
10122 * don't have to worry about exceeding the array bounds.
10123 *
10124 * Find where in the list the new range ends (but we can skip this if we
10125 * have already determined what it is, or if it will be the same as i_s,
10126 * which we already have computed) */
10127 if (i_e == 0) {
10128 i_e = (start == end)
10129 ? i_s
10130 : _invlist_search(invlist, end);
10131 }
10132
10133 /* Here generally invlist[i_e] <= end < array[i_e+1]. But if invlist[i_e]
10134 * is a range that goes to infinity there is no element at invlist[i_e+1],
10135 * so only the first relation holds. */
10136
10137 if ( ! ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10138
10139 /* Here, the ranges on either side of the beginning of the new range
10140 * are in the set, and this range starts in the gap between them.
10141 *
10142 * The new range extends the range above it downwards if the new range
10143 * ends at or above that range's start */
10144 const bool extends_the_range_above = ( end == UV_MAX
10145 || end + 1 >= array[i_s+1]);
10146
10147 /* The new range extends the range below it upwards if it begins just
10148 * after where that range ends */
10149 if (start == array[i_s]) {
10150
10151 /* If the new range fills the entire gap between the other ranges,
10152 * they will get merged together. Other ranges may also get
10153 * merged, depending on how many of them the new range spans. In
10154 * the general case, we do the merge later, just once, after we
10155 * figure out how many to merge. But in the case where the new
10156 * range exactly spans just this one gap (possibly extending into
10157 * the one above), we do the merge here, and an early exit. This
10158 * is done here to avoid having to special case later. */
10159 if (i_e - i_s <= 1) {
10160
10161 /* If i_e - i_s == 1, it means that the new range terminates
10162 * within the range above, and hence 'extends_the_range_above'
10163 * must be true. (If the range above it extends to infinity,
10164 * 'i_s+2' will be above the array's limit, but 'len-i_s-2'
10165 * will be 0, so no harm done.) */
10166 if (extends_the_range_above) {
10167 Move(array + i_s + 2, array + i_s, len - i_s - 2, UV);
10168 invlist_set_len(invlist,
10169 len - 2,
10170 *(get_invlist_offset_addr(invlist)));
10171 return invlist;
10172 }
10173
10174 /* Here, i_e must == i_s. We keep them in sync, as they apply
10175 * to the same range, and below we are about to decrement i_s
10176 * */
10177 i_e--;
10178 }
10179
10180 /* Here, the new range is adjacent to the one below. (It may also
10181 * span beyond the range above, but that will get resolved later.)
10182 * Extend the range below to include this one. */
10183 array[i_s] = (end == UV_MAX) ? UV_MAX : end + 1;
10184 i_s--;
10185 start = array[i_s];
10186 }
10187 else if (extends_the_range_above) {
10188
10189 /* Here the new range only extends the range above it, but not the
10190 * one below. It merges with the one above. Again, we keep i_e
10191 * and i_s in sync if they point to the same range */
10192 if (i_e == i_s) {
10193 i_e++;
10194 }
10195 i_s++;
10196 array[i_s] = start;
10197 }
10198 }
10199
10200 /* Here, we've dealt with the new range start extending any adjoining
10201 * existing ranges.
10202 *
10203 * If the new range extends to infinity, it is now the final one,
10204 * regardless of what was there before */
10205 if (UNLIKELY(end == UV_MAX)) {
10206 invlist_set_len(invlist, i_s + 1, *(get_invlist_offset_addr(invlist)));
10207 return invlist;
10208 }
10209
10210 /* If i_e started as == i_s, it has also been dealt with,
10211 * and been updated to the new i_s, which will fail the following if */
10212 if (! ELEMENT_RANGE_MATCHES_INVLIST(i_e)) {
10213
10214 /* Here, the ranges on either side of the end of the new range are in
10215 * the set, and this range ends in the gap between them.
10216 *
10217 * If this range is adjacent to (hence extends) the range above it, it
10218 * becomes part of that range; likewise if it extends the range below,
10219 * it becomes part of that range */
10220 if (end + 1 == array[i_e+1]) {
10221 i_e++;
10222 array[i_e] = start;
10223 }
10224 else if (start <= array[i_e]) {
10225 array[i_e] = end + 1;
10226 i_e--;
10227 }
10228 }
10229
10230 if (i_s == i_e) {
10231
10232 /* If the range fits entirely in an existing range (as possibly already
10233 * extended above), it doesn't add anything new */
10234 if (ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10235 return invlist;
10236 }
10237
10238 /* Here, no part of the range is in the list. Must add it. It will
10239 * occupy 2 more slots */
10240 splice_in_new_range:
10241
10242 invlist_extend(invlist, len + 2);
10243 array = invlist_array(invlist);
10244 /* Move the rest of the array down two slots. Don't include any
10245 * trailing NUL */
10246 Move(array + i_e + 1, array + i_e + 3, len - i_e - 1, UV);
10247
10248 /* Do the actual splice */
10249 array[i_e+1] = start;
10250 array[i_e+2] = end + 1;
10251 invlist_set_len(invlist, len + 2, *(get_invlist_offset_addr(invlist)));
10252 return invlist;
10253 }
10254
10255 /* Here the new range crossed the boundaries of a pre-existing range. The
10256 * code above has adjusted things so that both ends are in ranges that are
10257 * in the set. This means everything in between must also be in the set.
10258 * Just squash things together */
10259 Move(array + i_e + 1, array + i_s + 1, len - i_e - 1, UV);
10260 invlist_set_len(invlist,
10261 len - i_e + i_s,
10262 *(get_invlist_offset_addr(invlist)));
10263
10264 return invlist;
10265}
10266
10267SV*
10268Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0,
10269 UV** other_elements_ptr)
10270{
10271 /* Create and return an inversion list whose contents are to be populated
10272 * by the caller. The caller gives the number of elements (in 'size') and
10273 * the very first element ('element0'). This function will set
10274 * '*other_elements_ptr' to an array of UVs, where the remaining elements
10275 * are to be placed.
10276 *
10277 * Obviously there is some trust involved that the caller will properly
10278 * fill in the other elements of the array.
10279 *
10280 * (The first element needs to be passed in, as the underlying code does
10281 * things differently depending on whether it is zero or non-zero) */
10282
10283 SV* invlist = _new_invlist(size);
10284 bool offset;
10285
10286 PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST;
10287
10288 invlist = add_cp_to_invlist(invlist, element0);
10289 offset = *get_invlist_offset_addr(invlist);
10290
10291 invlist_set_len(invlist, size, offset);
10292 *other_elements_ptr = invlist_array(invlist) + 1;
10293 return invlist;
10294}
10295
10296#endif
10297
10298#ifndef PERL_IN_XSUB_RE
10299void
10300Perl__invlist_invert(pTHX_ SV* const invlist)
10301{
10302 /* Complement the input inversion list. This adds a 0 if the list didn't
10303 * have a zero; removes it otherwise. As described above, the data
10304 * structure is set up so that this is very efficient */
10305
10306 PERL_ARGS_ASSERT__INVLIST_INVERT;
10307
10308 assert(! invlist_is_iterating(invlist));
10309
10310 /* The inverse of matching nothing is matching everything */
10311 if (_invlist_len(invlist) == 0) {
10312 _append_range_to_invlist(invlist, 0, UV_MAX);
10313 return;
10314 }
10315
10316 *get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist);
10317}
10318
10319SV*
10320Perl_invlist_clone(pTHX_ SV* const invlist, SV* new_invlist)
10321{
10322 /* Return a new inversion list that is a copy of the input one, which is
10323 * unchanged. The new list will not be mortal even if the old one was. */
10324
10325 const STRLEN nominal_length = _invlist_len(invlist);
10326 const STRLEN physical_length = SvCUR(invlist);
10327 const bool offset = *(get_invlist_offset_addr(invlist));
10328
10329 PERL_ARGS_ASSERT_INVLIST_CLONE;
10330
10331 if (new_invlist == NULL) {
10332 new_invlist = _new_invlist(nominal_length);
10333 }
10334 else {
10335 sv_upgrade(new_invlist, SVt_INVLIST);
10336 initialize_invlist_guts(new_invlist, nominal_length);
10337 }
10338
10339 *(get_invlist_offset_addr(new_invlist)) = offset;
10340 invlist_set_len(new_invlist, nominal_length, offset);
10341 Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char);
10342
10343 return new_invlist;
10344}
10345
10346#endif
10347
10348PERL_STATIC_INLINE UV
10349S_invlist_lowest(SV* const invlist)
10350{
10351 /* Returns the lowest code point that matches an inversion list. This API
10352 * has an ambiguity, as it returns 0 under either the lowest is actually
10353 * 0, or if the list is empty. If this distinction matters to you, check
10354 * for emptiness before calling this function */
10355
10356 UV len = _invlist_len(invlist);
10357 UV *array;
10358
10359 PERL_ARGS_ASSERT_INVLIST_LOWEST;
10360
10361 if (len == 0) {
10362 return 0;
10363 }
10364
10365 array = invlist_array(invlist);
10366
10367 return array[0];
10368}
10369
10370STATIC SV *
10371S_invlist_contents(pTHX_ SV* const invlist, const bool traditional_style)
10372{
10373 /* Get the contents of an inversion list into a string SV so that they can
10374 * be printed out. If 'traditional_style' is TRUE, it uses the format
10375 * traditionally done for debug tracing; otherwise it uses a format
10376 * suitable for just copying to the output, with blanks between ranges and
10377 * a dash between range components */
10378
10379 UV start, end;
10380 SV* output;
10381 const char intra_range_delimiter = (traditional_style ? '\t' : '-');
10382 const char inter_range_delimiter = (traditional_style ? '\n' : ' ');
10383
10384 if (traditional_style) {
10385 output = newSVpvs("\n");
10386 }
10387 else {
10388 output = newSVpvs("");
10389 }
10390
10391 PERL_ARGS_ASSERT_INVLIST_CONTENTS;
10392
10393 assert(! invlist_is_iterating(invlist));
10394
10395 invlist_iterinit(invlist);
10396 while (invlist_iternext(invlist, &start, &end)) {
10397 if (end == UV_MAX) {
10398 Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%cINFTY%c",
10399 start, intra_range_delimiter,
10400 inter_range_delimiter);
10401 }
10402 else if (end != start) {
10403 Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c%04" UVXf "%c",
10404 start,
10405 intra_range_delimiter,
10406 end, inter_range_delimiter);
10407 }
10408 else {
10409 Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c",
10410 start, inter_range_delimiter);
10411 }
10412 }
10413
10414 if (SvCUR(output) && ! traditional_style) {/* Get rid of trailing blank */
10415 SvCUR_set(output, SvCUR(output) - 1);
10416 }
10417
10418 return output;
10419}
10420
10421#ifndef PERL_IN_XSUB_RE
10422void
10423Perl__invlist_dump(pTHX_ PerlIO *file, I32 level,
10424 const char * const indent, SV* const invlist)
10425{
10426 /* Designed to be called only by do_sv_dump(). Dumps out the ranges of the
10427 * inversion list 'invlist' to 'file' at 'level' Each line is prefixed by
10428 * the string 'indent'. The output looks like this:
10429 [0] 0x000A .. 0x000D
10430 [2] 0x0085
10431 [4] 0x2028 .. 0x2029
10432 [6] 0x3104 .. INFTY
10433 * This means that the first range of code points matched by the list are
10434 * 0xA through 0xD; the second range contains only the single code point
10435 * 0x85, etc. An inversion list is an array of UVs. Two array elements
10436 * are used to define each range (except if the final range extends to
10437 * infinity, only a single element is needed). The array index of the
10438 * first element for the corresponding range is given in brackets. */
10439
10440 UV start, end;
10441 STRLEN count = 0;
10442
10443 PERL_ARGS_ASSERT__INVLIST_DUMP;
10444
10445 if (invlist_is_iterating(invlist)) {
10446 Perl_dump_indent(aTHX_ level, file,
10447 "%sCan't dump inversion list because is in middle of iterating\n",
10448 indent);
10449 return;
10450 }
10451
10452 invlist_iterinit(invlist);
10453 while (invlist_iternext(invlist, &start, &end)) {
10454 if (end == UV_MAX) {
10455 Perl_dump_indent(aTHX_ level, file,
10456 "%s[%" UVuf "] 0x%04" UVXf " .. INFTY\n",
10457 indent, (UV)count, start);
10458 }
10459 else if (end != start) {
10460 Perl_dump_indent(aTHX_ level, file,
10461 "%s[%" UVuf "] 0x%04" UVXf " .. 0x%04" UVXf "\n",
10462 indent, (UV)count, start, end);
10463 }
10464 else {
10465 Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf "\n",
10466 indent, (UV)count, start);
10467 }
10468 count += 2;
10469 }
10470}
10471
10472#endif
10473
10474#if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE)
10475bool
10476Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b)
10477{
10478 /* Return a boolean as to if the two passed in inversion lists are
10479 * identical. The final argument, if TRUE, says to take the complement of
10480 * the second inversion list before doing the comparison */
10481
10482 const UV len_a = _invlist_len(a);
10483 UV len_b = _invlist_len(b);
10484
10485 const UV* array_a = NULL;
10486 const UV* array_b = NULL;
10487
10488 PERL_ARGS_ASSERT__INVLISTEQ;
10489
10490 /* This code avoids accessing the arrays unless it knows the length is
10491 * non-zero */
10492
10493 if (len_a == 0) {
10494 if (len_b == 0) {
10495 return ! complement_b;
10496 }
10497 }
10498 else {
10499 array_a = invlist_array(a);
10500 }
10501
10502 if (len_b != 0) {
10503 array_b = invlist_array(b);
10504 }
10505
10506 /* If are to compare 'a' with the complement of b, set it
10507 * up so are looking at b's complement. */
10508 if (complement_b) {
10509
10510 /* The complement of nothing is everything, so <a> would have to have
10511 * just one element, starting at zero (ending at infinity) */
10512 if (len_b == 0) {
10513 return (len_a == 1 && array_a[0] == 0);
10514 }
10515 if (array_b[0] == 0) {
10516
10517 /* Otherwise, to complement, we invert. Here, the first element is
10518 * 0, just remove it. To do this, we just pretend the array starts
10519 * one later */
10520
10521 array_b++;
10522 len_b--;
10523 }
10524 else {
10525
10526 /* But if the first element is not zero, we pretend the list starts
10527 * at the 0 that is always stored immediately before the array. */
10528 array_b--;
10529 len_b++;
10530 }
10531 }
10532
10533 return len_a == len_b
10534 && memEQ(array_a, array_b, len_a * sizeof(array_a[0]));
10535
10536}
10537#endif
10538
10539/*
10540 * As best we can, determine the characters that can match the start of
10541 * the given EXACTF-ish node. This is for use in creating ssc nodes, so there
10542 * can be false positive matches
10543 *
10544 * Returns the invlist as a new SV*; it is the caller's responsibility to
10545 * call SvREFCNT_dec() when done with it.
10546 */
10547STATIC SV*
10548S_make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node)
10549{
10550 dVAR;
10551 const U8 * s = (U8*)STRING(node);
10552 SSize_t bytelen = STR_LEN(node);
10553 UV uc;
10554 /* Start out big enough for 2 separate code points */
10555 SV* invlist = _new_invlist(4);
10556
10557 PERL_ARGS_ASSERT_MAKE_EXACTF_INVLIST;
10558
10559 if (! UTF) {
10560 uc = *s;
10561
10562 /* We punt and assume can match anything if the node begins
10563 * with a multi-character fold. Things are complicated. For
10564 * example, /ffi/i could match any of:
10565 * "\N{LATIN SMALL LIGATURE FFI}"
10566 * "\N{LATIN SMALL LIGATURE FF}I"
10567 * "F\N{LATIN SMALL LIGATURE FI}"
10568 * plus several other things; and making sure we have all the
10569 * possibilities is hard. */
10570 if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) {
10571 invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10572 }
10573 else {
10574 /* Any Latin1 range character can potentially match any
10575 * other depending on the locale, and in Turkic locales, U+130 and
10576 * U+131 */
10577 if (OP(node) == EXACTFL) {
10578 _invlist_union(invlist, PL_Latin1, &invlist);
10579 invlist = add_cp_to_invlist(invlist,
10580 LATIN_SMALL_LETTER_DOTLESS_I);
10581 invlist = add_cp_to_invlist(invlist,
10582 LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10583 }
10584 else {
10585 /* But otherwise, it matches at least itself. We can
10586 * quickly tell if it has a distinct fold, and if so,
10587 * it matches that as well */
10588 invlist = add_cp_to_invlist(invlist, uc);
10589 if (IS_IN_SOME_FOLD_L1(uc))
10590 invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]);
10591 }
10592
10593 /* Some characters match above-Latin1 ones under /i. This
10594 * is true of EXACTFL ones when the locale is UTF-8 */
10595 if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc)
10596 && (! isASCII(uc) || (OP(node) != EXACTFAA
10597 && OP(node) != EXACTFAA_NO_TRIE)))
10598 {
10599 add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist);
10600 }
10601 }
10602 }
10603 else { /* Pattern is UTF-8 */
10604 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
10605 const U8* e = s + bytelen;
10606 IV fc;
10607
10608 fc = uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
10609
10610 /* The only code points that aren't folded in a UTF EXACTFish
10611 * node are are the problematic ones in EXACTFL nodes */
10612 if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) {
10613 /* We need to check for the possibility that this EXACTFL
10614 * node begins with a multi-char fold. Therefore we fold
10615 * the first few characters of it so that we can make that
10616 * check */
10617 U8 *d = folded;
10618 int i;
10619
10620 fc = -1;
10621 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) {
10622 if (isASCII(*s)) {
10623 *(d++) = (U8) toFOLD(*s);
10624 if (fc < 0) { /* Save the first fold */
10625 fc = *(d-1);
10626 }
10627 s++;
10628 }
10629 else {
10630 STRLEN len;
10631 UV fold = toFOLD_utf8_safe(s, e, d, &len);
10632 if (fc < 0) { /* Save the first fold */
10633 fc = fold;
10634 }
10635 d += len;
10636 s += UTF8SKIP(s);
10637 }
10638 }
10639
10640 /* And set up so the code below that looks in this folded
10641 * buffer instead of the node's string */
10642 e = d;
10643 s = folded;
10644 }
10645
10646 /* When we reach here 's' points to the fold of the first
10647 * character(s) of the node; and 'e' points to far enough along
10648 * the folded string to be just past any possible multi-char
10649 * fold.
10650 *
10651 * Unlike the non-UTF-8 case, the macro for determining if a
10652 * string is a multi-char fold requires all the characters to
10653 * already be folded. This is because of all the complications
10654 * if not. Note that they are folded anyway, except in EXACTFL
10655 * nodes. Like the non-UTF case above, we punt if the node
10656 * begins with a multi-char fold */
10657
10658 if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) {
10659 invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10660 }
10661 else { /* Single char fold */
10662 unsigned int k;
10663 U32 first_fold;
10664 const U32 * remaining_folds;
10665 Size_t folds_count;
10666
10667 /* It matches itself */
10668 invlist = add_cp_to_invlist(invlist, fc);
10669
10670 /* ... plus all the things that fold to it, which are found in
10671 * PL_utf8_foldclosures */
10672 folds_count = _inverse_folds(fc, &first_fold,
10673 &remaining_folds);
10674 for (k = 0; k < folds_count; k++) {
10675 UV c = (k == 0) ? first_fold : remaining_folds[k-1];
10676
10677 /* /aa doesn't allow folds between ASCII and non- */
10678 if ( (OP(node) == EXACTFAA || OP(node) == EXACTFAA_NO_TRIE)
10679 && isASCII(c) != isASCII(fc))
10680 {
10681 continue;
10682 }
10683
10684 invlist = add_cp_to_invlist(invlist, c);
10685 }
10686
10687 if (OP(node) == EXACTFL) {
10688
10689 /* If either [iI] are present in an EXACTFL node the above code
10690 * should have added its normal case pair, but under a Turkish
10691 * locale they could match instead the case pairs from it. Add
10692 * those as potential matches as well */
10693 if (isALPHA_FOLD_EQ(fc, 'I')) {
10694 invlist = add_cp_to_invlist(invlist,
10695 LATIN_SMALL_LETTER_DOTLESS_I);
10696 invlist = add_cp_to_invlist(invlist,
10697 LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10698 }
10699 else if (fc == LATIN_SMALL_LETTER_DOTLESS_I) {
10700 invlist = add_cp_to_invlist(invlist, 'I');
10701 }
10702 else if (fc == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) {
10703 invlist = add_cp_to_invlist(invlist, 'i');
10704 }
10705 }
10706 }
10707 }
10708
10709 return invlist;
10710}
10711
10712#undef HEADER_LENGTH
10713#undef TO_INTERNAL_SIZE
10714#undef FROM_INTERNAL_SIZE
10715#undef INVLIST_VERSION_ID
10716
10717/* End of inversion list object */
10718
10719STATIC void
10720S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state)
10721{
10722 /* This parses the flags that are in either the '(?foo)' or '(?foo:bar)'
10723 * constructs, and updates RExC_flags with them. On input, RExC_parse
10724 * should point to the first flag; it is updated on output to point to the
10725 * final ')' or ':'. There needs to be at least one flag, or this will
10726 * abort */
10727
10728 /* for (?g), (?gc), and (?o) warnings; warning
10729 about (?c) will warn about (?g) -- japhy */
10730
10731#define WASTED_O 0x01
10732#define WASTED_G 0x02
10733#define WASTED_C 0x04
10734#define WASTED_GC (WASTED_G|WASTED_C)
10735 I32 wastedflags = 0x00;
10736 U32 posflags = 0, negflags = 0;
10737 U32 *flagsp = &posflags;
10738 char has_charset_modifier = '\0';
10739 regex_charset cs;
10740 bool has_use_defaults = FALSE;
10741 const char* const seqstart = RExC_parse - 1; /* Point to the '?' */
10742 int x_mod_count = 0;
10743
10744 PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS;
10745
10746 /* '^' as an initial flag sets certain defaults */
10747 if (UCHARAT(RExC_parse) == '^') {
10748 RExC_parse++;
10749 has_use_defaults = TRUE;
10750 STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
10751 cs = (RExC_uni_semantics)
10752 ? REGEX_UNICODE_CHARSET
10753 : REGEX_DEPENDS_CHARSET;
10754 set_regex_charset(&RExC_flags, cs);
10755 }
10756 else {
10757 cs = get_regex_charset(RExC_flags);
10758 if ( cs == REGEX_DEPENDS_CHARSET
10759 && RExC_uni_semantics)
10760 {
10761 cs = REGEX_UNICODE_CHARSET;
10762 }
10763 }
10764
10765 while (RExC_parse < RExC_end) {
10766 /* && memCHRs("iogcmsx", *RExC_parse) */
10767 /* (?g), (?gc) and (?o) are useless here
10768 and must be globally applied -- japhy */
10769 if ((RExC_pm_flags & PMf_WILDCARD)) {
10770 if (flagsp == & negflags) {
10771 if (*RExC_parse == 'm') {
10772 RExC_parse++;
10773 /* diag_listed_as: Use of %s is not allowed in Unicode
10774 property wildcard subpatterns in regex; marked by <--
10775 HERE in m/%s/ */
10776 vFAIL("Use of modifier '-m' is not allowed in Unicode"
10777 " property wildcard subpatterns");
10778 }
10779 }
10780 else {
10781 if (*RExC_parse == 's') {
10782 goto modifier_illegal_in_wildcard;
10783 }
10784 }
10785 }
10786
10787 switch (*RExC_parse) {
10788
10789 /* Code for the imsxn flags */
10790 CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count);
10791
10792 case LOCALE_PAT_MOD:
10793 if (has_charset_modifier) {
10794 goto excess_modifier;
10795 }
10796 else if (flagsp == &negflags) {
10797 goto neg_modifier;
10798 }
10799 cs = REGEX_LOCALE_CHARSET;
10800 has_charset_modifier = LOCALE_PAT_MOD;
10801 break;
10802 case UNICODE_PAT_MOD:
10803 if (has_charset_modifier) {
10804 goto excess_modifier;
10805 }
10806 else if (flagsp == &negflags) {
10807 goto neg_modifier;
10808 }
10809 cs = REGEX_UNICODE_CHARSET;
10810 has_charset_modifier = UNICODE_PAT_MOD;
10811 break;
10812 case ASCII_RESTRICT_PAT_MOD:
10813 if (flagsp == &negflags) {
10814 goto neg_modifier;
10815 }
10816 if (has_charset_modifier) {
10817 if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
10818 goto excess_modifier;
10819 }
10820 /* Doubled modifier implies more restricted */
10821 cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
10822 }
10823 else {
10824 cs = REGEX_ASCII_RESTRICTED_CHARSET;
10825 }
10826 has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
10827 break;
10828 case DEPENDS_PAT_MOD:
10829 if (has_use_defaults) {
10830 goto fail_modifiers;
10831 }
10832 else if (flagsp == &negflags) {
10833 goto neg_modifier;
10834 }
10835 else if (has_charset_modifier) {
10836 goto excess_modifier;
10837 }
10838
10839 /* The dual charset means unicode semantics if the
10840 * pattern (or target, not known until runtime) are
10841 * utf8, or something in the pattern indicates unicode
10842 * semantics */
10843 cs = (RExC_uni_semantics)
10844 ? REGEX_UNICODE_CHARSET
10845 : REGEX_DEPENDS_CHARSET;
10846 has_charset_modifier = DEPENDS_PAT_MOD;
10847 break;
10848 excess_modifier:
10849 RExC_parse++;
10850 if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
10851 vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
10852 }
10853 else if (has_charset_modifier == *(RExC_parse - 1)) {
10854 vFAIL2("Regexp modifier \"%c\" may not appear twice",
10855 *(RExC_parse - 1));
10856 }
10857 else {
10858 vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
10859 }
10860 NOT_REACHED; /*NOTREACHED*/
10861 neg_modifier:
10862 RExC_parse++;
10863 vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"",
10864 *(RExC_parse - 1));
10865 NOT_REACHED; /*NOTREACHED*/
10866 case GLOBAL_PAT_MOD: /* 'g' */
10867 if (RExC_pm_flags & PMf_WILDCARD) {
10868 goto modifier_illegal_in_wildcard;
10869 }
10870 /*FALLTHROUGH*/
10871 case ONCE_PAT_MOD: /* 'o' */
10872 if (ckWARN(WARN_REGEXP)) {
10873 const I32 wflagbit = *RExC_parse == 'o'
10874 ? WASTED_O
10875 : WASTED_G;
10876 if (! (wastedflags & wflagbit) ) {
10877 wastedflags |= wflagbit;
10878 /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10879 vWARN5(
10880 RExC_parse + 1,
10881 "Useless (%s%c) - %suse /%c modifier",
10882 flagsp == &negflags ? "?-" : "?",
10883 *RExC_parse,
10884 flagsp == &negflags ? "don't " : "",
10885 *RExC_parse
10886 );
10887 }
10888 }
10889 break;
10890
10891 case CONTINUE_PAT_MOD: /* 'c' */
10892 if (RExC_pm_flags & PMf_WILDCARD) {
10893 goto modifier_illegal_in_wildcard;
10894 }
10895 if (ckWARN(WARN_REGEXP)) {
10896 if (! (wastedflags & WASTED_C) ) {
10897 wastedflags |= WASTED_GC;
10898 /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10899 vWARN3(
10900 RExC_parse + 1,
10901 "Useless (%sc) - %suse /gc modifier",
10902 flagsp == &negflags ? "?-" : "?",
10903 flagsp == &negflags ? "don't " : ""
10904 );
10905 }
10906 }
10907 break;
10908 case KEEPCOPY_PAT_MOD: /* 'p' */
10909 if (RExC_pm_flags & PMf_WILDCARD) {
10910 goto modifier_illegal_in_wildcard;
10911 }
10912 if (flagsp == &negflags) {
10913 ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
10914 } else {
10915 *flagsp |= RXf_PMf_KEEPCOPY;
10916 }
10917 break;
10918 case '-':
10919 /* A flag is a default iff it is following a minus, so
10920 * if there is a minus, it means will be trying to
10921 * re-specify a default which is an error */
10922 if (has_use_defaults || flagsp == &negflags) {
10923 goto fail_modifiers;
10924 }
10925 flagsp = &negflags;
10926 wastedflags = 0; /* reset so (?g-c) warns twice */
10927 x_mod_count = 0;
10928 break;
10929 case ':':
10930 case ')':
10931
10932 if ( (RExC_pm_flags & PMf_WILDCARD)
10933 && cs != REGEX_ASCII_MORE_RESTRICTED_CHARSET)
10934 {
10935 RExC_parse++;
10936 /* diag_listed_as: Use of %s is not allowed in Unicode
10937 property wildcard subpatterns in regex; marked by <--
10938 HERE in m/%s/ */
10939 vFAIL2("Use of modifier '%c' is not allowed in Unicode"
10940 " property wildcard subpatterns",
10941 has_charset_modifier);
10942 }
10943
10944 if ((posflags & (RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE)) == RXf_PMf_EXTENDED) {
10945 negflags |= RXf_PMf_EXTENDED_MORE;
10946 }
10947 RExC_flags |= posflags;
10948
10949 if (negflags & RXf_PMf_EXTENDED) {
10950 negflags |= RXf_PMf_EXTENDED_MORE;
10951 }
10952 RExC_flags &= ~negflags;
10953 set_regex_charset(&RExC_flags, cs);
10954
10955 return;
10956 default:
10957 fail_modifiers:
10958 RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
10959 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
10960 vFAIL2utf8f("Sequence (%" UTF8f "...) not recognized",
10961 UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
10962 NOT_REACHED; /*NOTREACHED*/
10963 }
10964
10965 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10966 }
10967
10968 vFAIL("Sequence (?... not terminated");
10969
10970 modifier_illegal_in_wildcard:
10971 RExC_parse++;
10972 /* diag_listed_as: Use of %s is not allowed in Unicode property wildcard
10973 subpatterns in regex; marked by <-- HERE in m/%s/ */
10974 vFAIL2("Use of modifier '%c' is not allowed in Unicode property wildcard"
10975 " subpatterns", *(RExC_parse - 1));
10976}
10977
10978/*
10979 - reg - regular expression, i.e. main body or parenthesized thing
10980 *
10981 * Caller must absorb opening parenthesis.
10982 *
10983 * Combining parenthesis handling with the base level of regular expression
10984 * is a trifle forced, but the need to tie the tails of the branches to what
10985 * follows makes it hard to avoid.
10986 */
10987#define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
10988#ifdef DEBUGGING
10989#define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
10990#else
10991#define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
10992#endif
10993
10994PERL_STATIC_INLINE regnode_offset
10995S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state,
10996 I32 *flagp,
10997 char * parse_start,
10998 char ch
10999 )
11000{
11001 regnode_offset ret;
11002 char* name_start = RExC_parse;
11003 U32 num = 0;
11004 SV *sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
11005 GET_RE_DEBUG_FLAGS_DECL;
11006
11007 PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF;
11008
11009 if (RExC_parse == name_start || *RExC_parse != ch) {
11010 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
11011 vFAIL2("Sequence %.3s... not terminated", parse_start);
11012 }
11013
11014 if (sv_dat) {
11015 num = add_data( pRExC_state, STR_WITH_LEN("S"));
11016 RExC_rxi->data->data[num]=(void*)sv_dat;
11017 SvREFCNT_inc_simple_void_NN(sv_dat);
11018 }
11019 RExC_sawback = 1;
11020 ret = reganode(pRExC_state,
11021 ((! FOLD)
11022 ? REFN
11023 : (ASCII_FOLD_RESTRICTED)
11024 ? REFFAN
11025 : (AT_LEAST_UNI_SEMANTICS)
11026 ? REFFUN
11027 : (LOC)
11028 ? REFFLN
11029 : REFFN),
11030 num);
11031 *flagp |= HASWIDTH;
11032
11033 Set_Node_Offset(REGNODE_p(ret), parse_start+1);
11034 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
11035
11036 nextchar(pRExC_state);
11037 return ret;
11038}
11039
11040/* On success, returns the offset at which any next node should be placed into
11041 * the regex engine program being compiled.
11042 *
11043 * Returns 0 otherwise, with *flagp set to indicate why:
11044 * TRYAGAIN at the end of (?) that only sets flags.
11045 * RESTART_PARSE if the parse needs to be restarted, or'd with
11046 * NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
11047 * Otherwise would only return 0 if regbranch() returns 0, which cannot
11048 * happen. */
11049STATIC regnode_offset
11050S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp, U32 depth)
11051 /* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter.
11052 * 2 is like 1, but indicates that nextchar() has been called to advance
11053 * RExC_parse beyond the '('. Things like '(?' are indivisible tokens, and
11054 * this flag alerts us to the need to check for that */
11055{
11056 regnode_offset ret = 0; /* Will be the head of the group. */
11057 regnode_offset br;
11058 regnode_offset lastbr;
11059 regnode_offset ender = 0;
11060 I32 parno = 0;
11061 I32 flags;
11062 U32 oregflags = RExC_flags;
11063 bool have_branch = 0;
11064 bool is_open = 0;
11065 I32 freeze_paren = 0;
11066 I32 after_freeze = 0;
11067 I32 num; /* numeric backreferences */
11068 SV * max_open; /* Max number of unclosed parens */
11069
11070 char * parse_start = RExC_parse; /* MJD */
11071 char * const oregcomp_parse = RExC_parse;
11072
11073 GET_RE_DEBUG_FLAGS_DECL;
11074
11075 PERL_ARGS_ASSERT_REG;
11076 DEBUG_PARSE("reg ");
11077
11078 max_open = get_sv(RE_COMPILE_RECURSION_LIMIT, GV_ADD);
11079 assert(max_open);
11080 if (!SvIOK(max_open)) {
11081 sv_setiv(max_open, RE_COMPILE_RECURSION_INIT);
11082 }
11083 if (depth > 4 * (UV) SvIV(max_open)) { /* We increase depth by 4 for each
11084 open paren */
11085 vFAIL("Too many nested open parens");
11086 }
11087
11088 *flagp = 0; /* Tentatively. */
11089
11090 if (RExC_in_lookbehind) {
11091 RExC_in_lookbehind++;
11092 }
11093 if (RExC_in_lookahead) {
11094 RExC_in_lookahead++;
11095 }
11096
11097 /* Having this true makes it feasible to have a lot fewer tests for the
11098 * parse pointer being in scope. For example, we can write
11099 * while(isFOO(*RExC_parse)) RExC_parse++;
11100 * instead of
11101 * while(RExC_parse < RExC_end && isFOO(*RExC_parse)) RExC_parse++;
11102 */
11103 assert(*RExC_end == '\0');
11104
11105 /* Make an OPEN node, if parenthesized. */
11106 if (paren) {
11107
11108 /* Under /x, space and comments can be gobbled up between the '(' and
11109 * here (if paren ==2). The forms '(*VERB' and '(?...' disallow such
11110 * intervening space, as the sequence is a token, and a token should be
11111 * indivisible */
11112 bool has_intervening_patws = (paren == 2)
11113 && *(RExC_parse - 1) != '(';
11114
11115 if (RExC_parse >= RExC_end) {
11116 vFAIL("Unmatched (");
11117 }
11118
11119 if (paren == 'r') { /* Atomic script run */
11120 paren = '>';
11121 goto parse_rest;
11122 }
11123 else if ( *RExC_parse == '*') { /* (*VERB:ARG), (*construct:...) */
11124 char *start_verb = RExC_parse + 1;
11125 STRLEN verb_len;
11126 char *start_arg = NULL;
11127 unsigned char op = 0;
11128 int arg_required = 0;
11129 int internal_argval = -1; /* if >-1 we are not allowed an argument*/
11130 bool has_upper = FALSE;
11131
11132 if (has_intervening_patws) {
11133 RExC_parse++; /* past the '*' */
11134
11135 /* For strict backwards compatibility, don't change the message
11136 * now that we also have lowercase operands */
11137 if (isUPPER(*RExC_parse)) {
11138 vFAIL("In '(*VERB...)', the '(' and '*' must be adjacent");
11139 }
11140 else {
11141 vFAIL("In '(*...)', the '(' and '*' must be adjacent");
11142 }
11143 }
11144 while (RExC_parse < RExC_end && *RExC_parse != ')' ) {
11145 if ( *RExC_parse == ':' ) {
11146 start_arg = RExC_parse + 1;
11147 break;
11148 }
11149 else if (! UTF) {
11150 if (isUPPER(*RExC_parse)) {
11151 has_upper = TRUE;
11152 }
11153 RExC_parse++;
11154 }
11155 else {
11156 RExC_parse += UTF8SKIP(RExC_parse);
11157 }
11158 }
11159 verb_len = RExC_parse - start_verb;
11160 if ( start_arg ) {
11161 if (RExC_parse >= RExC_end) {
11162 goto unterminated_verb_pattern;
11163 }
11164
11165 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11166 while ( RExC_parse < RExC_end && *RExC_parse != ')' ) {
11167 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11168 }
11169 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
11170 unterminated_verb_pattern:
11171 if (has_upper) {
11172 vFAIL("Unterminated verb pattern argument");
11173 }
11174 else {
11175 vFAIL("Unterminated '(*...' argument");
11176 }
11177 }
11178 } else {
11179 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
11180 if (has_upper) {
11181 vFAIL("Unterminated verb pattern");
11182 }
11183 else {
11184 vFAIL("Unterminated '(*...' construct");
11185 }
11186 }
11187 }
11188
11189 /* Here, we know that RExC_parse < RExC_end */
11190
11191 switch ( *start_verb ) {
11192 case 'A': /* (*ACCEPT) */
11193 if ( memEQs(start_verb, verb_len,"ACCEPT") ) {
11194 op = ACCEPT;
11195 internal_argval = RExC_nestroot;
11196 }
11197 break;
11198 case 'C': /* (*COMMIT) */
11199 if ( memEQs(start_verb, verb_len,"COMMIT") )
11200 op = COMMIT;
11201 break;
11202 case 'F': /* (*FAIL) */
11203 if ( verb_len==1 || memEQs(start_verb, verb_len,"FAIL") ) {
11204 op = OPFAIL;
11205 }
11206 break;
11207 case ':': /* (*:NAME) */
11208 case 'M': /* (*MARK:NAME) */
11209 if ( verb_len==0 || memEQs(start_verb, verb_len,"MARK") ) {
11210 op = MARKPOINT;
11211 arg_required = 1;
11212 }
11213 break;
11214 case 'P': /* (*PRUNE) */
11215 if ( memEQs(start_verb, verb_len,"PRUNE") )
11216 op = PRUNE;
11217 break;
11218 case 'S': /* (*SKIP) */
11219 if ( memEQs(start_verb, verb_len,"SKIP") )
11220 op = SKIP;
11221 break;
11222 case 'T': /* (*THEN) */
11223 /* [19:06] <TimToady> :: is then */
11224 if ( memEQs(start_verb, verb_len,"THEN") ) {
11225 op = CUTGROUP;
11226 RExC_seen |= REG_CUTGROUP_SEEN;
11227 }
11228 break;
11229 case 'a':
11230 if ( memEQs(start_verb, verb_len, "asr")
11231 || memEQs(start_verb, verb_len, "atomic_script_run"))
11232 {
11233 paren = 'r'; /* Mnemonic: recursed run */
11234 goto script_run;
11235 }
11236 else if (memEQs(start_verb, verb_len, "atomic")) {
11237 paren = 't'; /* AtOMIC */
11238 goto alpha_assertions;
11239 }
11240 break;
11241 case 'p':
11242 if ( memEQs(start_verb, verb_len, "plb")
11243 || memEQs(start_verb, verb_len, "positive_lookbehind"))
11244 {
11245 paren = 'b';
11246 goto lookbehind_alpha_assertions;
11247 }
11248 else if ( memEQs(start_verb, verb_len, "pla")
11249 || memEQs(start_verb, verb_len, "positive_lookahead"))
11250 {
11251 paren = 'a';
11252 goto alpha_assertions;
11253 }
11254 break;
11255 case 'n':
11256 if ( memEQs(start_verb, verb_len, "nlb")
11257 || memEQs(start_verb, verb_len, "negative_lookbehind"))
11258 {
11259 paren = 'B';
11260 goto lookbehind_alpha_assertions;
11261 }
11262 else if ( memEQs(start_verb, verb_len, "nla")
11263 || memEQs(start_verb, verb_len, "negative_lookahead"))
11264 {
11265 paren = 'A';
11266 goto alpha_assertions;
11267 }
11268 break;
11269 case 's':
11270 if ( memEQs(start_verb, verb_len, "sr")
11271 || memEQs(start_verb, verb_len, "script_run"))
11272 {
11273 regnode_offset atomic;
11274
11275 paren = 's';
11276
11277 script_run:
11278
11279 /* This indicates Unicode rules. */
11280 REQUIRE_UNI_RULES(flagp, 0);
11281
11282 if (! start_arg) {
11283 goto no_colon;
11284 }
11285
11286 RExC_parse = start_arg;
11287
11288 if (RExC_in_script_run) {
11289
11290 /* Nested script runs are treated as no-ops, because
11291 * if the nested one fails, the outer one must as
11292 * well. It could fail sooner, and avoid (??{} with
11293 * side effects, but that is explicitly documented as
11294 * undefined behavior. */
11295
11296 ret = 0;
11297
11298 if (paren == 's') {
11299 paren = ':';
11300 goto parse_rest;
11301 }
11302
11303 /* But, the atomic part of a nested atomic script run
11304 * isn't a no-op, but can be treated just like a '(?>'
11305 * */
11306 paren = '>';
11307 goto parse_rest;
11308 }
11309
11310 if (paren == 's') {
11311 /* Here, we're starting a new regular script run */
11312 ret = reg_node(pRExC_state, SROPEN);
11313 RExC_in_script_run = 1;
11314 is_open = 1;
11315 goto parse_rest;
11316 }
11317
11318 /* Here, we are starting an atomic script run. This is
11319 * handled by recursing to deal with the atomic portion
11320 * separately, enclosed in SROPEN ... SRCLOSE nodes */
11321
11322 ret = reg_node(pRExC_state, SROPEN);
11323
11324 RExC_in_script_run = 1;
11325
11326 atomic = reg(pRExC_state, 'r', &flags, depth);
11327 if (flags & (RESTART_PARSE|NEED_UTF8)) {
11328 *flagp = flags & (RESTART_PARSE|NEED_UTF8);
11329 return 0;
11330 }
11331
11332 if (! REGTAIL(pRExC_state, ret, atomic)) {
11333 REQUIRE_BRANCHJ(flagp, 0);
11334 }
11335
11336 if (! REGTAIL(pRExC_state, atomic, reg_node(pRExC_state,
11337 SRCLOSE)))
11338 {
11339 REQUIRE_BRANCHJ(flagp, 0);
11340 }
11341
11342 RExC_in_script_run = 0;
11343 return ret;
11344 }
11345
11346 break;
11347
11348 lookbehind_alpha_assertions:
11349 RExC_seen |= REG_LOOKBEHIND_SEEN;
11350 RExC_in_lookbehind++;
11351 /*FALLTHROUGH*/
11352
11353 alpha_assertions:
11354
11355 RExC_seen_zerolen++;
11356
11357 if (! start_arg) {
11358 goto no_colon;
11359 }
11360
11361 /* An empty negative lookahead assertion simply is failure */
11362 if (paren == 'A' && RExC_parse == start_arg) {
11363 ret=reganode(pRExC_state, OPFAIL, 0);
11364 nextchar(pRExC_state);
11365 return ret;
11366 }
11367
11368 RExC_parse = start_arg;
11369 goto parse_rest;
11370
11371 no_colon:
11372 vFAIL2utf8f(
11373 "'(*%" UTF8f "' requires a terminating ':'",
11374 UTF8fARG(UTF, verb_len, start_verb));
11375 NOT_REACHED; /*NOTREACHED*/
11376
11377 } /* End of switch */
11378 if ( ! op ) {
11379 RExC_parse += UTF
11380 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
11381 : 1;
11382 if (has_upper || verb_len == 0) {
11383 vFAIL2utf8f(
11384 "Unknown verb pattern '%" UTF8f "'",
11385 UTF8fARG(UTF, verb_len, start_verb));
11386 }
11387 else {
11388 vFAIL2utf8f(
11389 "Unknown '(*...)' construct '%" UTF8f "'",
11390 UTF8fARG(UTF, verb_len, start_verb));
11391 }
11392 }
11393 if ( RExC_parse == start_arg ) {
11394 start_arg = NULL;
11395 }
11396 if ( arg_required && !start_arg ) {
11397 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
11398 (int) verb_len, start_verb);
11399 }
11400 if (internal_argval == -1) {
11401 ret = reganode(pRExC_state, op, 0);
11402 } else {
11403 ret = reg2Lanode(pRExC_state, op, 0, internal_argval);
11404 }
11405 RExC_seen |= REG_VERBARG_SEEN;
11406 if (start_arg) {
11407 SV *sv = newSVpvn( start_arg,
11408 RExC_parse - start_arg);
11409 ARG(REGNODE_p(ret)) = add_data( pRExC_state,
11410 STR_WITH_LEN("S"));
11411 RExC_rxi->data->data[ARG(REGNODE_p(ret))]=(void*)sv;
11412 FLAGS(REGNODE_p(ret)) = 1;
11413 } else {
11414 FLAGS(REGNODE_p(ret)) = 0;
11415 }
11416 if ( internal_argval != -1 )
11417 ARG2L_SET(REGNODE_p(ret), internal_argval);
11418 nextchar(pRExC_state);
11419 return ret;
11420 }
11421 else if (*RExC_parse == '?') { /* (?...) */
11422 bool is_logical = 0;
11423 const char * const seqstart = RExC_parse;
11424 const char * endptr;
11425 if (has_intervening_patws) {
11426 RExC_parse++;
11427 vFAIL("In '(?...)', the '(' and '?' must be adjacent");
11428 }
11429
11430 RExC_parse++; /* past the '?' */
11431 paren = *RExC_parse; /* might be a trailing NUL, if not
11432 well-formed */
11433 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11434 if (RExC_parse > RExC_end) {
11435 paren = '\0';
11436 }
11437 ret = 0; /* For look-ahead/behind. */
11438 switch (paren) {
11439
11440 case 'P': /* (?P...) variants for those used to PCRE/Python */
11441 paren = *RExC_parse;
11442 if ( paren == '<') { /* (?P<...>) named capture */
11443 RExC_parse++;
11444 if (RExC_parse >= RExC_end) {
11445 vFAIL("Sequence (?P<... not terminated");
11446 }
11447 goto named_capture;
11448 }
11449 else if (paren == '>') { /* (?P>name) named recursion */
11450 RExC_parse++;
11451 if (RExC_parse >= RExC_end) {
11452 vFAIL("Sequence (?P>... not terminated");
11453 }
11454 goto named_recursion;
11455 }
11456 else if (paren == '=') { /* (?P=...) named backref */
11457 RExC_parse++;
11458 return handle_named_backref(pRExC_state, flagp,
11459 parse_start, ')');
11460 }
11461 RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
11462 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11463 vFAIL3("Sequence (%.*s...) not recognized",
11464 (int) (RExC_parse - seqstart), seqstart);
11465 NOT_REACHED; /*NOTREACHED*/
11466 case '<': /* (?<...) */
11467 /* If you want to support (?<*...), first reconcile with GH #17363 */
11468 if (*RExC_parse == '!')
11469 paren = ',';
11470 else if (*RExC_parse != '=')
11471 named_capture:
11472 { /* (?<...>) */
11473 char *name_start;
11474 SV *svname;
11475 paren= '>';
11476 /* FALLTHROUGH */
11477 case '\'': /* (?'...') */
11478 name_start = RExC_parse;
11479 svname = reg_scan_name(pRExC_state, REG_RSN_RETURN_NAME);
11480 if ( RExC_parse == name_start
11481 || RExC_parse >= RExC_end
11482 || *RExC_parse != paren)
11483 {
11484 vFAIL2("Sequence (?%c... not terminated",
11485 paren=='>' ? '<' : (char) paren);
11486 }
11487 {
11488 HE *he_str;
11489 SV *sv_dat = NULL;
11490 if (!svname) /* shouldn't happen */
11491 Perl_croak(aTHX_
11492 "panic: reg_scan_name returned NULL");
11493 if (!RExC_paren_names) {
11494 RExC_paren_names= newHV();
11495 sv_2mortal(MUTABLE_SV(RExC_paren_names));
11496#ifdef DEBUGGING
11497 RExC_paren_name_list= newAV();
11498 sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
11499#endif
11500 }
11501 he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
11502 if ( he_str )
11503 sv_dat = HeVAL(he_str);
11504 if ( ! sv_dat ) {
11505 /* croak baby croak */
11506 Perl_croak(aTHX_
11507 "panic: paren_name hash element allocation failed");
11508 } else if ( SvPOK(sv_dat) ) {
11509 /* (?|...) can mean we have dupes so scan to check
11510 its already been stored. Maybe a flag indicating
11511 we are inside such a construct would be useful,
11512 but the arrays are likely to be quite small, so
11513 for now we punt -- dmq */
11514 IV count = SvIV(sv_dat);
11515 I32 *pv = (I32*)SvPVX(sv_dat);
11516 IV i;
11517 for ( i = 0 ; i < count ; i++ ) {
11518 if ( pv[i] == RExC_npar ) {
11519 count = 0;
11520 break;
11521 }
11522 }
11523 if ( count ) {
11524 pv = (I32*)SvGROW(sv_dat,
11525 SvCUR(sv_dat) + sizeof(I32)+1);
11526 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
11527 pv[count] = RExC_npar;
11528 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
11529 }
11530 } else {
11531 (void)SvUPGRADE(sv_dat, SVt_PVNV);
11532 sv_setpvn(sv_dat, (char *)&(RExC_npar),
11533 sizeof(I32));
11534 SvIOK_on(sv_dat);
11535 SvIV_set(sv_dat, 1);
11536 }
11537#ifdef DEBUGGING
11538 /* Yes this does cause a memory leak in debugging Perls
11539 * */
11540 if (!av_store(RExC_paren_name_list,
11541 RExC_npar, SvREFCNT_inc_NN(svname)))
11542 SvREFCNT_dec_NN(svname);
11543#endif
11544
11545 /*sv_dump(sv_dat);*/
11546 }
11547 nextchar(pRExC_state);
11548 paren = 1;
11549 goto capturing_parens;
11550 }
11551
11552 RExC_seen |= REG_LOOKBEHIND_SEEN;
11553 RExC_in_lookbehind++;
11554 RExC_parse++;
11555 if (RExC_parse >= RExC_end) {
11556 vFAIL("Sequence (?... not terminated");
11557 }
11558 RExC_seen_zerolen++;
11559 break;
11560 case '=': /* (?=...) */
11561 RExC_seen_zerolen++;
11562 RExC_in_lookahead++;
11563 break;
11564 case '!': /* (?!...) */
11565 RExC_seen_zerolen++;
11566 /* check if we're really just a "FAIL" assertion */
11567 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
11568 FALSE /* Don't force to /x */ );
11569 if (*RExC_parse == ')') {
11570 ret=reganode(pRExC_state, OPFAIL, 0);
11571 nextchar(pRExC_state);
11572 return ret;
11573 }
11574 break;
11575 case '|': /* (?|...) */
11576 /* branch reset, behave like a (?:...) except that
11577 buffers in alternations share the same numbers */
11578 paren = ':';
11579 after_freeze = freeze_paren = RExC_npar;
11580
11581 /* XXX This construct currently requires an extra pass.
11582 * Investigation would be required to see if that could be
11583 * changed */
11584 REQUIRE_PARENS_PASS;
11585 break;
11586 case ':': /* (?:...) */
11587 case '>': /* (?>...) */
11588 break;
11589 case '$': /* (?$...) */
11590 case '@': /* (?@...) */
11591 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
11592 break;
11593 case '0' : /* (?0) */
11594 case 'R' : /* (?R) */
11595 if (RExC_parse == RExC_end || *RExC_parse != ')')
11596 FAIL("Sequence (?R) not terminated");
11597 num = 0;
11598 RExC_seen |= REG_RECURSE_SEEN;
11599
11600 /* XXX These constructs currently require an extra pass.
11601 * It probably could be changed */
11602 REQUIRE_PARENS_PASS;
11603
11604 *flagp |= POSTPONED;
11605 goto gen_recurse_regop;
11606 /*notreached*/
11607 /* named and numeric backreferences */
11608 case '&': /* (?&NAME) */
11609 parse_start = RExC_parse - 1;
11610 named_recursion:
11611 {
11612 SV *sv_dat = reg_scan_name(pRExC_state,
11613 REG_RSN_RETURN_DATA);
11614 num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
11615 }
11616 if (RExC_parse >= RExC_end || *RExC_parse != ')')
11617 vFAIL("Sequence (?&... not terminated");
11618 goto gen_recurse_regop;
11619 /* NOTREACHED */
11620 case '+':
11621 if (! inRANGE(RExC_parse[0], '1', '9')) {
11622 RExC_parse++;
11623 vFAIL("Illegal pattern");
11624 }
11625 goto parse_recursion;
11626 /* NOTREACHED*/
11627 case '-': /* (?-1) */
11628 if (! inRANGE(RExC_parse[0], '1', '9')) {
11629 RExC_parse--; /* rewind to let it be handled later */
11630 goto parse_flags;
11631 }
11632 /* FALLTHROUGH */
11633 case '1': case '2': case '3': case '4': /* (?1) */
11634 case '5': case '6': case '7': case '8': case '9':
11635 RExC_parse = (char *) seqstart + 1; /* Point to the digit */
11636 parse_recursion:
11637 {
11638 bool is_neg = FALSE;
11639 UV unum;
11640 parse_start = RExC_parse - 1; /* MJD */
11641 if (*RExC_parse == '-') {
11642 RExC_parse++;
11643 is_neg = TRUE;
11644 }
11645 endptr = RExC_end;
11646 if (grok_atoUV(RExC_parse, &unum, &endptr)
11647 && unum <= I32_MAX
11648 ) {
11649 num = (I32)unum;
11650 RExC_parse = (char*)endptr;
11651 } else
11652 num = I32_MAX;
11653 if (is_neg) {
11654 /* Some limit for num? */
11655 num = -num;
11656 }
11657 }
11658 if (*RExC_parse!=')')
11659 vFAIL("Expecting close bracket");
11660
11661 gen_recurse_regop:
11662 if ( paren == '-' ) {
11663 /*
11664 Diagram of capture buffer numbering.
11665 Top line is the normal capture buffer numbers
11666 Bottom line is the negative indexing as from
11667 the X (the (?-2))
11668
11669 + 1 2 3 4 5 X 6 7
11670 /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
11671 - 5 4 3 2 1 X x x
11672
11673 */
11674 num = RExC_npar + num;
11675 if (num < 1) {
11676
11677 /* It might be a forward reference; we can't fail until
11678 * we know, by completing the parse to get all the
11679 * groups, and then reparsing */
11680 if (ALL_PARENS_COUNTED) {
11681 RExC_parse++;
11682 vFAIL("Reference to nonexistent group");
11683 }
11684 else {
11685 REQUIRE_PARENS_PASS;
11686 }
11687 }
11688 } else if ( paren == '+' ) {
11689 num = RExC_npar + num - 1;
11690 }
11691 /* We keep track how many GOSUB items we have produced.
11692 To start off the ARG2L() of the GOSUB holds its "id",
11693 which is used later in conjunction with RExC_recurse
11694 to calculate the offset we need to jump for the GOSUB,
11695 which it will store in the final representation.
11696 We have to defer the actual calculation until much later
11697 as the regop may move.
11698 */
11699
11700 ret = reg2Lanode(pRExC_state, GOSUB, num, RExC_recurse_count);
11701 if (num >= RExC_npar) {
11702
11703 /* It might be a forward reference; we can't fail until we
11704 * know, by completing the parse to get all the groups, and
11705 * then reparsing */
11706 if (ALL_PARENS_COUNTED) {
11707 if (num >= RExC_total_parens) {
11708 RExC_parse++;
11709 vFAIL("Reference to nonexistent group");
11710 }
11711 }
11712 else {
11713 REQUIRE_PARENS_PASS;
11714 }
11715 }
11716 RExC_recurse_count++;
11717 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11718 "%*s%*s Recurse #%" UVuf " to %" IVdf "\n",
11719 22, "| |", (int)(depth * 2 + 1), "",
11720 (UV)ARG(REGNODE_p(ret)),
11721 (IV)ARG2L(REGNODE_p(ret))));
11722 RExC_seen |= REG_RECURSE_SEEN;
11723
11724 Set_Node_Length(REGNODE_p(ret),
11725 1 + regarglen[OP(REGNODE_p(ret))]); /* MJD */
11726 Set_Node_Offset(REGNODE_p(ret), parse_start); /* MJD */
11727
11728 *flagp |= POSTPONED;
11729 assert(*RExC_parse == ')');
11730 nextchar(pRExC_state);
11731 return ret;
11732
11733 /* NOTREACHED */
11734
11735 case '?': /* (??...) */
11736 is_logical = 1;
11737 if (*RExC_parse != '{') {
11738 RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
11739 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11740 vFAIL2utf8f(
11741 "Sequence (%" UTF8f "...) not recognized",
11742 UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
11743 NOT_REACHED; /*NOTREACHED*/
11744 }
11745 *flagp |= POSTPONED;
11746 paren = '{';
11747 RExC_parse++;
11748 /* FALLTHROUGH */
11749 case '{': /* (?{...}) */
11750 {
11751 U32 n = 0;
11752 struct reg_code_block *cb;
11753 OP * o;
11754
11755 RExC_seen_zerolen++;
11756
11757 if ( !pRExC_state->code_blocks
11758 || pRExC_state->code_index
11759 >= pRExC_state->code_blocks->count
11760 || pRExC_state->code_blocks->cb[pRExC_state->code_index].start
11761 != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
11762 - RExC_start)
11763 ) {
11764 if (RExC_pm_flags & PMf_USE_RE_EVAL)
11765 FAIL("panic: Sequence (?{...}): no code block found\n");
11766 FAIL("Eval-group not allowed at runtime, use re 'eval'");
11767 }
11768 /* this is a pre-compiled code block (?{...}) */
11769 cb = &pRExC_state->code_blocks->cb[pRExC_state->code_index];
11770 RExC_parse = RExC_start + cb->end;
11771 o = cb->block;
11772 if (cb->src_regex) {
11773 n = add_data(pRExC_state, STR_WITH_LEN("rl"));
11774 RExC_rxi->data->data[n] =
11775 (void*)SvREFCNT_inc((SV*)cb->src_regex);
11776 RExC_rxi->data->data[n+1] = (void*)o;
11777 }
11778 else {
11779 n = add_data(pRExC_state,
11780 (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l", 1);
11781 RExC_rxi->data->data[n] = (void*)o;
11782 }
11783 pRExC_state->code_index++;
11784 nextchar(pRExC_state);
11785
11786 if (is_logical) {
11787 regnode_offset eval;
11788 ret = reg_node(pRExC_state, LOGICAL);
11789
11790 eval = reg2Lanode(pRExC_state, EVAL,
11791 n,
11792
11793 /* for later propagation into (??{})
11794 * return value */
11795 RExC_flags & RXf_PMf_COMPILETIME
11796 );
11797 FLAGS(REGNODE_p(ret)) = 2;
11798 if (! REGTAIL(pRExC_state, ret, eval)) {
11799 REQUIRE_BRANCHJ(flagp, 0);
11800 }
11801 /* deal with the length of this later - MJD */
11802 return ret;
11803 }
11804 ret = reg2Lanode(pRExC_state, EVAL, n, 0);
11805 Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1);
11806 Set_Node_Offset(REGNODE_p(ret), parse_start);
11807 return ret;
11808 }
11809 case '(': /* (?(?{...})...) and (?(?=...)...) */
11810 {
11811 int is_define= 0;
11812 const int DEFINE_len = sizeof("DEFINE") - 1;
11813 if ( RExC_parse < RExC_end - 1
11814 && ( ( RExC_parse[0] == '?' /* (?(?...)) */
11815 && ( RExC_parse[1] == '='
11816 || RExC_parse[1] == '!'
11817 || RExC_parse[1] == '<'
11818 || RExC_parse[1] == '{'))
11819 || ( RExC_parse[0] == '*' /* (?(*...)) */
11820 && ( memBEGINs(RExC_parse + 1,
11821 (Size_t) (RExC_end - (RExC_parse + 1)),
11822 "pla:")
11823 || memBEGINs(RExC_parse + 1,
11824 (Size_t) (RExC_end - (RExC_parse + 1)),
11825 "plb:")
11826 || memBEGINs(RExC_parse + 1,
11827 (Size_t) (RExC_end - (RExC_parse + 1)),
11828 "nla:")
11829 || memBEGINs(RExC_parse + 1,
11830 (Size_t) (RExC_end - (RExC_parse + 1)),
11831 "nlb:")
11832 || memBEGINs(RExC_parse + 1,
11833 (Size_t) (RExC_end - (RExC_parse + 1)),
11834 "positive_lookahead:")
11835 || memBEGINs(RExC_parse + 1,
11836 (Size_t) (RExC_end - (RExC_parse + 1)),
11837 "positive_lookbehind:")
11838 || memBEGINs(RExC_parse + 1,
11839 (Size_t) (RExC_end - (RExC_parse + 1)),
11840 "negative_lookahead:")
11841 || memBEGINs(RExC_parse + 1,
11842 (Size_t) (RExC_end - (RExC_parse + 1)),
11843 "negative_lookbehind:"))))
11844 ) { /* Lookahead or eval. */
11845 I32 flag;
11846 regnode_offset tail;
11847
11848 ret = reg_node(pRExC_state, LOGICAL);
11849 FLAGS(REGNODE_p(ret)) = 1;
11850
11851 tail = reg(pRExC_state, 1, &flag, depth+1);
11852 RETURN_FAIL_ON_RESTART(flag, flagp);
11853 if (! REGTAIL(pRExC_state, ret, tail)) {
11854 REQUIRE_BRANCHJ(flagp, 0);
11855 }
11856 goto insert_if;
11857 }
11858 else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
11859 || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
11860 {
11861 char ch = RExC_parse[0] == '<' ? '>' : '\'';
11862 char *name_start= RExC_parse++;
11863 U32 num = 0;
11864 SV *sv_dat=reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
11865 if ( RExC_parse == name_start
11866 || RExC_parse >= RExC_end
11867 || *RExC_parse != ch)
11868 {
11869 vFAIL2("Sequence (?(%c... not terminated",
11870 (ch == '>' ? '<' : ch));
11871 }
11872 RExC_parse++;
11873 if (sv_dat) {
11874 num = add_data( pRExC_state, STR_WITH_LEN("S"));
11875 RExC_rxi->data->data[num]=(void*)sv_dat;
11876 SvREFCNT_inc_simple_void_NN(sv_dat);
11877 }
11878 ret = reganode(pRExC_state, GROUPPN, num);
11879 goto insert_if_check_paren;
11880 }
11881 else if (memBEGINs(RExC_parse,
11882 (STRLEN) (RExC_end - RExC_parse),
11883 "DEFINE"))
11884 {
11885 ret = reganode(pRExC_state, DEFINEP, 0);
11886 RExC_parse += DEFINE_len;
11887 is_define = 1;
11888 goto insert_if_check_paren;
11889 }
11890 else if (RExC_parse[0] == 'R') {
11891 RExC_parse++;
11892 /* parno == 0 => /(?(R)YES|NO)/ "in any form of recursion OR eval"
11893 * parno == 1 => /(?(R0)YES|NO)/ "in GOSUB (?0) / (?R)"
11894 * parno == 2 => /(?(R1)YES|NO)/ "in GOSUB (?1) (parno-1)"
11895 */
11896 parno = 0;
11897 if (RExC_parse[0] == '0') {
11898 parno = 1;
11899 RExC_parse++;
11900 }
11901 else if (inRANGE(RExC_parse[0], '1', '9')) {
11902 UV uv;
11903 endptr = RExC_end;
11904 if (grok_atoUV(RExC_parse, &uv, &endptr)
11905 && uv <= I32_MAX
11906 ) {
11907 parno = (I32)uv + 1;
11908 RExC_parse = (char*)endptr;
11909 }
11910 /* else "Switch condition not recognized" below */
11911 } else if (RExC_parse[0] == '&') {
11912 SV *sv_dat;
11913 RExC_parse++;
11914 sv_dat = reg_scan_name(pRExC_state,
11915 REG_RSN_RETURN_DATA);
11916 if (sv_dat)
11917 parno = 1 + *((I32 *)SvPVX(sv_dat));
11918 }
11919 ret = reganode(pRExC_state, INSUBP, parno);
11920 goto insert_if_check_paren;
11921 }
11922 else if (inRANGE(RExC_parse[0], '1', '9')) {
11923 /* (?(1)...) */
11924 char c;
11925 UV uv;
11926 endptr = RExC_end;
11927 if (grok_atoUV(RExC_parse, &uv, &endptr)
11928 && uv <= I32_MAX
11929 ) {
11930 parno = (I32)uv;
11931 RExC_parse = (char*)endptr;
11932 }
11933 else {
11934 vFAIL("panic: grok_atoUV returned FALSE");
11935 }
11936 ret = reganode(pRExC_state, GROUPP, parno);
11937
11938 insert_if_check_paren:
11939 if (UCHARAT(RExC_parse) != ')') {
11940 RExC_parse += UTF
11941 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
11942 : 1;
11943 vFAIL("Switch condition not recognized");
11944 }
11945 nextchar(pRExC_state);
11946 insert_if:
11947 if (! REGTAIL(pRExC_state, ret, reganode(pRExC_state,
11948 IFTHEN, 0)))
11949 {
11950 REQUIRE_BRANCHJ(flagp, 0);
11951 }
11952 br = regbranch(pRExC_state, &flags, 1, depth+1);
11953 if (br == 0) {
11954 RETURN_FAIL_ON_RESTART(flags,flagp);
11955 FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
11956 (UV) flags);
11957 } else
11958 if (! REGTAIL(pRExC_state, br, reganode(pRExC_state,
11959 LONGJMP, 0)))
11960 {
11961 REQUIRE_BRANCHJ(flagp, 0);
11962 }
11963 c = UCHARAT(RExC_parse);
11964 nextchar(pRExC_state);
11965 if (flags&HASWIDTH)
11966 *flagp |= HASWIDTH;
11967 if (c == '|') {
11968 if (is_define)
11969 vFAIL("(?(DEFINE)....) does not allow branches");
11970
11971 /* Fake one for optimizer. */
11972 lastbr = reganode(pRExC_state, IFTHEN, 0);
11973
11974 if (!regbranch(pRExC_state, &flags, 1, depth+1)) {
11975 RETURN_FAIL_ON_RESTART(flags, flagp);
11976 FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
11977 (UV) flags);
11978 }
11979 if (! REGTAIL(pRExC_state, ret, lastbr)) {
11980 REQUIRE_BRANCHJ(flagp, 0);
11981 }
11982 if (flags&HASWIDTH)
11983 *flagp |= HASWIDTH;
11984 c = UCHARAT(RExC_parse);
11985 nextchar(pRExC_state);
11986 }
11987 else
11988 lastbr = 0;
11989 if (c != ')') {
11990 if (RExC_parse >= RExC_end)
11991 vFAIL("Switch (?(condition)... not terminated");
11992 else
11993 vFAIL("Switch (?(condition)... contains too many branches");
11994 }
11995 ender = reg_node(pRExC_state, TAIL);
11996 if (! REGTAIL(pRExC_state, br, ender)) {
11997 REQUIRE_BRANCHJ(flagp, 0);
11998 }
11999 if (lastbr) {
12000 if (! REGTAIL(pRExC_state, lastbr, ender)) {
12001 REQUIRE_BRANCHJ(flagp, 0);
12002 }
12003 if (! REGTAIL(pRExC_state,
12004 REGNODE_OFFSET(
12005 NEXTOPER(
12006 NEXTOPER(REGNODE_p(lastbr)))),
12007 ender))
12008 {
12009 REQUIRE_BRANCHJ(flagp, 0);
12010 }
12011 }
12012 else
12013 if (! REGTAIL(pRExC_state, ret, ender)) {
12014 REQUIRE_BRANCHJ(flagp, 0);
12015 }
12016#if 0 /* Removing this doesn't cause failures in the test suite -- khw */
12017 RExC_size++; /* XXX WHY do we need this?!!
12018 For large programs it seems to be required
12019 but I can't figure out why. -- dmq*/
12020#endif
12021 return ret;
12022 }
12023 RExC_parse += UTF
12024 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
12025 : 1;
12026 vFAIL("Unknown switch condition (?(...))");
12027 }
12028 case '[': /* (?[ ... ]) */
12029 return handle_regex_sets(pRExC_state, NULL, flagp, depth+1,
12030 oregcomp_parse);
12031 case 0: /* A NUL */
12032 RExC_parse--; /* for vFAIL to print correctly */
12033 vFAIL("Sequence (? incomplete");
12034 break;
12035
12036 case ')':
12037 if (RExC_strict) { /* [perl #132851] */
12038 ckWARNreg(RExC_parse, "Empty (?) without any modifiers");
12039 }
12040 /* FALLTHROUGH */
12041 case '*': /* If you want to support (?*...), first reconcile with GH #17363 */
12042 /* FALLTHROUGH */
12043 default: /* e.g., (?i) */
12044 RExC_parse = (char *) seqstart + 1;
12045 parse_flags:
12046 parse_lparen_question_flags(pRExC_state);
12047 if (UCHARAT(RExC_parse) != ':') {
12048 if (RExC_parse < RExC_end)
12049 nextchar(pRExC_state);
12050 *flagp = TRYAGAIN;
12051 return 0;
12052 }
12053 paren = ':';
12054 nextchar(pRExC_state);
12055 ret = 0;
12056 goto parse_rest;
12057 } /* end switch */
12058 }
12059 else if (!(RExC_flags & RXf_PMf_NOCAPTURE)) { /* (...) */
12060 capturing_parens:
12061 parno = RExC_npar;
12062 RExC_npar++;
12063 if (! ALL_PARENS_COUNTED) {
12064 /* If we are in our first pass through (and maybe only pass),
12065 * we need to allocate memory for the capturing parentheses
12066 * data structures.
12067 */
12068
12069 if (!RExC_parens_buf_size) {
12070 /* first guess at number of parens we might encounter */
12071 RExC_parens_buf_size = 10;
12072
12073 /* setup RExC_open_parens, which holds the address of each
12074 * OPEN tag, and to make things simpler for the 0 index the
12075 * start of the program - this is used later for offsets */
12076 Newxz(RExC_open_parens, RExC_parens_buf_size,
12077 regnode_offset);
12078 RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */
12079
12080 /* setup RExC_close_parens, which holds the address of each
12081 * CLOSE tag, and to make things simpler for the 0 index
12082 * the end of the program - this is used later for offsets
12083 * */
12084 Newxz(RExC_close_parens, RExC_parens_buf_size,
12085 regnode_offset);
12086 /* we dont know where end op starts yet, so we dont need to
12087 * set RExC_close_parens[0] like we do RExC_open_parens[0]
12088 * above */
12089 }
12090 else if (RExC_npar > RExC_parens_buf_size) {
12091 I32 old_size = RExC_parens_buf_size;
12092
12093 RExC_parens_buf_size *= 2;
12094
12095 Renew(RExC_open_parens, RExC_parens_buf_size,
12096 regnode_offset);
12097 Zero(RExC_open_parens + old_size,
12098 RExC_parens_buf_size - old_size, regnode_offset);
12099
12100 Renew(RExC_close_parens, RExC_parens_buf_size,
12101 regnode_offset);
12102 Zero(RExC_close_parens + old_size,
12103 RExC_parens_buf_size - old_size, regnode_offset);
12104 }
12105 }
12106
12107 ret = reganode(pRExC_state, OPEN, parno);
12108 if (!RExC_nestroot)
12109 RExC_nestroot = parno;
12110 if (RExC_open_parens && !RExC_open_parens[parno])
12111 {
12112 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12113 "%*s%*s Setting open paren #%" IVdf " to %zu\n",
12114 22, "| |", (int)(depth * 2 + 1), "",
12115 (IV)parno, ret));
12116 RExC_open_parens[parno]= ret;
12117 }
12118
12119 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
12120 Set_Node_Offset(REGNODE_p(ret), RExC_parse); /* MJD */
12121 is_open = 1;
12122 } else {
12123 /* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */
12124 paren = ':';
12125 ret = 0;
12126 }
12127 }
12128 else /* ! paren */
12129 ret = 0;
12130
12131 parse_rest:
12132 /* Pick up the branches, linking them together. */
12133 parse_start = RExC_parse; /* MJD */
12134 br = regbranch(pRExC_state, &flags, 1, depth+1);
12135
12136 /* branch_len = (paren != 0); */
12137
12138 if (br == 0) {
12139 RETURN_FAIL_ON_RESTART(flags, flagp);
12140 FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12141 }
12142 if (*RExC_parse == '|') {
12143 if (RExC_use_BRANCHJ) {
12144 reginsert(pRExC_state, BRANCHJ, br, depth+1);
12145 }
12146 else { /* MJD */
12147 reginsert(pRExC_state, BRANCH, br, depth+1);
12148 Set_Node_Length(REGNODE_p(br), paren != 0);
12149 Set_Node_Offset_To_R(br, parse_start-RExC_start);
12150 }
12151 have_branch = 1;
12152 }
12153 else if (paren == ':') {
12154 *flagp |= flags&SIMPLE;
12155 }
12156 if (is_open) { /* Starts with OPEN. */
12157 if (! REGTAIL(pRExC_state, ret, br)) { /* OPEN -> first. */
12158 REQUIRE_BRANCHJ(flagp, 0);
12159 }
12160 }
12161 else if (paren != '?') /* Not Conditional */
12162 ret = br;
12163 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
12164 lastbr = br;
12165 while (*RExC_parse == '|') {
12166 if (RExC_use_BRANCHJ) {
12167 bool shut_gcc_up;
12168
12169 ender = reganode(pRExC_state, LONGJMP, 0);
12170
12171 /* Append to the previous. */
12172 shut_gcc_up = REGTAIL(pRExC_state,
12173 REGNODE_OFFSET(NEXTOPER(NEXTOPER(REGNODE_p(lastbr)))),
12174 ender);
12175 PERL_UNUSED_VAR(shut_gcc_up);
12176 }
12177 nextchar(pRExC_state);
12178 if (freeze_paren) {
12179 if (RExC_npar > after_freeze)
12180 after_freeze = RExC_npar;
12181 RExC_npar = freeze_paren;
12182 }
12183 br = regbranch(pRExC_state, &flags, 0, depth+1);
12184
12185 if (br == 0) {
12186 RETURN_FAIL_ON_RESTART(flags, flagp);
12187 FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12188 }
12189 if (! REGTAIL(pRExC_state, lastbr, br)) { /* BRANCH -> BRANCH. */
12190 REQUIRE_BRANCHJ(flagp, 0);
12191 }
12192 lastbr = br;
12193 *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
12194 }
12195
12196 if (have_branch || paren != ':') {
12197 regnode * br;
12198
12199 /* Make a closing node, and hook it on the end. */
12200 switch (paren) {
12201 case ':':
12202 ender = reg_node(pRExC_state, TAIL);
12203 break;
12204 case 1: case 2:
12205 ender = reganode(pRExC_state, CLOSE, parno);
12206 if ( RExC_close_parens ) {
12207 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12208 "%*s%*s Setting close paren #%" IVdf " to %zu\n",
12209 22, "| |", (int)(depth * 2 + 1), "",
12210 (IV)parno, ender));
12211 RExC_close_parens[parno]= ender;
12212 if (RExC_nestroot == parno)
12213 RExC_nestroot = 0;
12214 }
12215 Set_Node_Offset(REGNODE_p(ender), RExC_parse+1); /* MJD */
12216 Set_Node_Length(REGNODE_p(ender), 1); /* MJD */
12217 break;
12218 case 's':
12219 ender = reg_node(pRExC_state, SRCLOSE);
12220 RExC_in_script_run = 0;
12221 break;
12222 case '<':
12223 case 'a':
12224 case 'A':
12225 case 'b':
12226 case 'B':
12227 case ',':
12228 case '=':
12229 case '!':
12230 *flagp &= ~HASWIDTH;
12231 /* FALLTHROUGH */
12232 case 't': /* aTomic */
12233 case '>':
12234 ender = reg_node(pRExC_state, SUCCEED);
12235 break;
12236 case 0:
12237 ender = reg_node(pRExC_state, END);
12238 assert(!RExC_end_op); /* there can only be one! */
12239 RExC_end_op = REGNODE_p(ender);
12240 if (RExC_close_parens) {
12241 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12242 "%*s%*s Setting close paren #0 (END) to %zu\n",
12243 22, "| |", (int)(depth * 2 + 1), "",
12244 ender));
12245
12246 RExC_close_parens[0]= ender;
12247 }
12248 break;
12249 }
12250 DEBUG_PARSE_r({
12251 DEBUG_PARSE_MSG("lsbr");
12252 regprop(RExC_rx, RExC_mysv1, REGNODE_p(lastbr), NULL, pRExC_state);
12253 regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender), NULL, pRExC_state);
12254 Perl_re_printf( aTHX_ "~ tying lastbr %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12255 SvPV_nolen_const(RExC_mysv1),
12256 (IV)lastbr,
12257 SvPV_nolen_const(RExC_mysv2),
12258 (IV)ender,
12259 (IV)(ender - lastbr)
12260 );
12261 });
12262 if (! REGTAIL(pRExC_state, lastbr, ender)) {
12263 REQUIRE_BRANCHJ(flagp, 0);
12264 }
12265
12266 if (have_branch) {
12267 char is_nothing= 1;
12268 if (depth==1)
12269 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
12270
12271 /* Hook the tails of the branches to the closing node. */
12272 for (br = REGNODE_p(ret); br; br = regnext(br)) {
12273 const U8 op = PL_regkind[OP(br)];
12274 if (op == BRANCH) {
12275 if (! REGTAIL_STUDY(pRExC_state,
12276 REGNODE_OFFSET(NEXTOPER(br)),
12277 ender))
12278 {
12279 REQUIRE_BRANCHJ(flagp, 0);
12280 }
12281 if ( OP(NEXTOPER(br)) != NOTHING
12282 || regnext(NEXTOPER(br)) != REGNODE_p(ender))
12283 is_nothing= 0;
12284 }
12285 else if (op == BRANCHJ) {
12286 bool shut_gcc_up = REGTAIL_STUDY(pRExC_state,
12287 REGNODE_OFFSET(NEXTOPER(NEXTOPER(br))),
12288 ender);
12289 PERL_UNUSED_VAR(shut_gcc_up);
12290 /* for now we always disable this optimisation * /
12291 if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING
12292 || regnext(NEXTOPER(NEXTOPER(br))) != REGNODE_p(ender))
12293 */
12294 is_nothing= 0;
12295 }
12296 }
12297 if (is_nothing) {
12298 regnode * ret_as_regnode = REGNODE_p(ret);
12299 br= PL_regkind[OP(ret_as_regnode)] != BRANCH
12300 ? regnext(ret_as_regnode)
12301 : ret_as_regnode;
12302 DEBUG_PARSE_r({
12303 DEBUG_PARSE_MSG("NADA");
12304 regprop(RExC_rx, RExC_mysv1, ret_as_regnode,
12305 NULL, pRExC_state);
12306 regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender),
12307 NULL, pRExC_state);
12308 Perl_re_printf( aTHX_ "~ converting ret %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12309 SvPV_nolen_const(RExC_mysv1),
12310 (IV)REG_NODE_NUM(ret_as_regnode),
12311 SvPV_nolen_const(RExC_mysv2),
12312 (IV)ender,
12313 (IV)(ender - ret)
12314 );
12315 });
12316 OP(br)= NOTHING;
12317 if (OP(REGNODE_p(ender)) == TAIL) {
12318 NEXT_OFF(br)= 0;
12319 RExC_emit= REGNODE_OFFSET(br) + 1;
12320 } else {
12321 regnode *opt;
12322 for ( opt= br + 1; opt < REGNODE_p(ender) ; opt++ )
12323 OP(opt)= OPTIMIZED;
12324 NEXT_OFF(br)= REGNODE_p(ender) - br;
12325 }
12326 }
12327 }
12328 }
12329
12330 {
12331 const char *p;
12332 /* Even/odd or x=don't care: 010101x10x */
12333 static const char parens[] = "=!aA<,>Bbt";
12334 /* flag below is set to 0 up through 'A'; 1 for larger */
12335
12336 if (paren && (p = strchr(parens, paren))) {
12337 U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
12338 int flag = (p - parens) > 3;
12339
12340 if (paren == '>' || paren == 't') {
12341 node = SUSPEND, flag = 0;
12342 }
12343
12344 reginsert(pRExC_state, node, ret, depth+1);
12345 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12346 Set_Node_Offset(REGNODE_p(ret), parse_start + 1);
12347 FLAGS(REGNODE_p(ret)) = flag;
12348 if (! REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL)))
12349 {
12350 REQUIRE_BRANCHJ(flagp, 0);
12351 }
12352 }
12353 }
12354
12355 /* Check for proper termination. */
12356 if (paren) {
12357 /* restore original flags, but keep (?p) and, if we've encountered
12358 * something in the parse that changes /d rules into /u, keep the /u */
12359 RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY);
12360 if (DEPENDS_SEMANTICS && RExC_uni_semantics) {
12361 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
12362 }
12363 if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') {
12364 RExC_parse = oregcomp_parse;
12365 vFAIL("Unmatched (");
12366 }
12367 nextchar(pRExC_state);
12368 }
12369 else if (!paren && RExC_parse < RExC_end) {
12370 if (*RExC_parse == ')') {
12371 RExC_parse++;
12372 vFAIL("Unmatched )");
12373 }
12374 else
12375 FAIL("Junk on end of regexp"); /* "Can't happen". */
12376 NOT_REACHED; /* NOTREACHED */
12377 }
12378
12379 if (RExC_in_lookbehind) {
12380 RExC_in_lookbehind--;
12381 }
12382 if (RExC_in_lookahead) {
12383 RExC_in_lookahead--;
12384 }
12385 if (after_freeze > RExC_npar)
12386 RExC_npar = after_freeze;
12387 return(ret);
12388}
12389
12390/*
12391 - regbranch - one alternative of an | operator
12392 *
12393 * Implements the concatenation operator.
12394 *
12395 * On success, returns the offset at which any next node should be placed into
12396 * the regex engine program being compiled.
12397 *
12398 * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
12399 * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
12400 * UTF-8
12401 */
12402STATIC regnode_offset
12403S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
12404{
12405 regnode_offset ret;
12406 regnode_offset chain = 0;
12407 regnode_offset latest;
12408 I32 flags = 0, c = 0;
12409 GET_RE_DEBUG_FLAGS_DECL;
12410
12411 PERL_ARGS_ASSERT_REGBRANCH;
12412
12413 DEBUG_PARSE("brnc");
12414
12415 if (first)
12416 ret = 0;
12417 else {
12418 if (RExC_use_BRANCHJ)
12419 ret = reganode(pRExC_state, BRANCHJ, 0);
12420 else {
12421 ret = reg_node(pRExC_state, BRANCH);
12422 Set_Node_Length(REGNODE_p(ret), 1);
12423 }
12424 }
12425
12426 *flagp = WORST; /* Tentatively. */
12427
12428 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
12429 FALSE /* Don't force to /x */ );
12430 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
12431 flags &= ~TRYAGAIN;
12432 latest = regpiece(pRExC_state, &flags, depth+1);
12433 if (latest == 0) {
12434 if (flags & TRYAGAIN)
12435 continue;
12436 RETURN_FAIL_ON_RESTART(flags, flagp);
12437 FAIL2("panic: regpiece returned failure, flags=%#" UVxf, (UV) flags);
12438 }
12439 else if (ret == 0)
12440 ret = latest;
12441 *flagp |= flags&(HASWIDTH|POSTPONED);
12442 if (chain == 0) /* First piece. */
12443 *flagp |= flags&SPSTART;
12444 else {
12445 /* FIXME adding one for every branch after the first is probably
12446 * excessive now we have TRIE support. (hv) */
12447 MARK_NAUGHTY(1);
12448 if (! REGTAIL(pRExC_state, chain, latest)) {
12449 /* XXX We could just redo this branch, but figuring out what
12450 * bookkeeping needs to be reset is a pain, and it's likely
12451 * that other branches that goto END will also be too large */
12452 REQUIRE_BRANCHJ(flagp, 0);
12453 }
12454 }
12455 chain = latest;
12456 c++;
12457 }
12458 if (chain == 0) { /* Loop ran zero times. */
12459 chain = reg_node(pRExC_state, NOTHING);
12460 if (ret == 0)
12461 ret = chain;
12462 }
12463 if (c == 1) {
12464 *flagp |= flags&SIMPLE;
12465 }
12466
12467 return ret;
12468}
12469
12470/*
12471 - regpiece - something followed by possible quantifier * + ? {n,m}
12472 *
12473 * Note that the branching code sequences used for ? and the general cases
12474 * of * and + are somewhat optimized: they use the same NOTHING node as
12475 * both the endmarker for their branch list and the body of the last branch.
12476 * It might seem that this node could be dispensed with entirely, but the
12477 * endmarker role is not redundant.
12478 *
12479 * On success, returns the offset at which any next node should be placed into
12480 * the regex engine program being compiled.
12481 *
12482 * Returns 0 otherwise, with *flagp set to indicate why:
12483 * TRYAGAIN if regatom() returns 0 with TRYAGAIN.
12484 * RESTART_PARSE if the parse needs to be restarted, or'd with
12485 * NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
12486 */
12487STATIC regnode_offset
12488S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
12489{
12490 regnode_offset ret;
12491 char op;
12492 char *next;
12493 I32 flags;
12494 const char * const origparse = RExC_parse;
12495 I32 min;
12496 I32 max = REG_INFTY;
12497#ifdef RE_TRACK_PATTERN_OFFSETS
12498 char *parse_start;
12499#endif
12500 const char *maxpos = NULL;
12501 UV uv;
12502
12503 /* Save the original in case we change the emitted regop to a FAIL. */
12504 const regnode_offset orig_emit = RExC_emit;
12505
12506 GET_RE_DEBUG_FLAGS_DECL;
12507
12508 PERL_ARGS_ASSERT_REGPIECE;
12509
12510 DEBUG_PARSE("piec");
12511
12512 ret = regatom(pRExC_state, &flags, depth+1);
12513 if (ret == 0) {
12514 RETURN_FAIL_ON_RESTART_OR_FLAGS(flags, flagp, TRYAGAIN);
12515 FAIL2("panic: regatom returned failure, flags=%#" UVxf, (UV) flags);
12516 }
12517
12518 op = *RExC_parse;
12519
12520 if (op == '{' && regcurly(RExC_parse)) {
12521 maxpos = NULL;
12522#ifdef RE_TRACK_PATTERN_OFFSETS
12523 parse_start = RExC_parse; /* MJD */
12524#endif
12525 next = RExC_parse + 1;
12526 while (isDIGIT(*next) || *next == ',') {
12527 if (*next == ',') {
12528 if (maxpos)
12529 break;
12530 else
12531 maxpos = next;
12532 }
12533 next++;
12534 }
12535 if (*next == '}') { /* got one */
12536 const char* endptr;
12537 if (!maxpos)
12538 maxpos = next;
12539 RExC_parse++;
12540 if (isDIGIT(*RExC_parse)) {
12541 endptr = RExC_end;
12542 if (!grok_atoUV(RExC_parse, &uv, &endptr))
12543 vFAIL("Invalid quantifier in {,}");
12544 if (uv >= REG_INFTY)
12545 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12546 min = (I32)uv;
12547 } else {
12548 min = 0;
12549 }
12550 if (*maxpos == ',')
12551 maxpos++;
12552 else
12553 maxpos = RExC_parse;
12554 if (isDIGIT(*maxpos)) {
12555 endptr = RExC_end;
12556 if (!grok_atoUV(maxpos, &uv, &endptr))
12557 vFAIL("Invalid quantifier in {,}");
12558 if (uv >= REG_INFTY)
12559 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12560 max = (I32)uv;
12561 } else {
12562 max = REG_INFTY; /* meaning "infinity" */
12563 }
12564 RExC_parse = next;
12565 nextchar(pRExC_state);
12566 if (max < min) { /* If can't match, warn and optimize to fail
12567 unconditionally */
12568 reginsert(pRExC_state, OPFAIL, orig_emit, depth+1);
12569 ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
12570 NEXT_OFF(REGNODE_p(orig_emit)) =
12571 regarglen[OPFAIL] + NODE_STEP_REGNODE;
12572 return ret;
12573 }
12574 else if (min == max && *RExC_parse == '?')
12575 {
12576 ckWARN2reg(RExC_parse + 1,
12577 "Useless use of greediness modifier '%c'",
12578 *RExC_parse);
12579 }
12580
12581 do_curly:
12582 if ((flags&SIMPLE)) {
12583 if (min == 0 && max == REG_INFTY) {
12584
12585 /* Going from 0..inf is currently forbidden in wildcard
12586 * subpatterns. The only reason is to make it harder to
12587 * write patterns that take a long long time to halt, and
12588 * because the use of this construct isn't necessary in
12589 * matching Unicode property values */
12590 if (RExC_pm_flags & PMf_WILDCARD) {
12591 RExC_parse++;
12592 /* diag_listed_as: Use of %s is not allowed in Unicode
12593 property wildcard subpatterns in regex; marked by
12594 <-- HERE in m/%s/ */
12595 vFAIL("Use of quantifier '*' is not allowed in"
12596 " Unicode property wildcard subpatterns");
12597 /* Note, don't need to worry about {0,}, as a '}' isn't
12598 * legal at all in wildcards, so wouldn't get this far
12599 * */
12600 }
12601 reginsert(pRExC_state, STAR, ret, depth+1);
12602 MARK_NAUGHTY(4);
12603 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12604 goto nest_check;
12605 }
12606 if (min == 1 && max == REG_INFTY) {
12607 reginsert(pRExC_state, PLUS, ret, depth+1);
12608 MARK_NAUGHTY(3);
12609 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12610 goto nest_check;
12611 }
12612 MARK_NAUGHTY_EXP(2, 2);
12613 reginsert(pRExC_state, CURLY, ret, depth+1);
12614 Set_Node_Offset(REGNODE_p(ret), parse_start+1); /* MJD */
12615 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12616 }
12617 else {
12618 const regnode_offset w = reg_node(pRExC_state, WHILEM);
12619
12620 FLAGS(REGNODE_p(w)) = 0;
12621 if (! REGTAIL(pRExC_state, ret, w)) {
12622 REQUIRE_BRANCHJ(flagp, 0);
12623 }
12624 if (RExC_use_BRANCHJ) {
12625 reginsert(pRExC_state, LONGJMP, ret, depth+1);
12626 reginsert(pRExC_state, NOTHING, ret, depth+1);
12627 NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over LONGJMP. */
12628 }
12629 reginsert(pRExC_state, CURLYX, ret, depth+1);
12630 /* MJD hk */
12631 Set_Node_Offset(REGNODE_p(ret), parse_start+1);
12632 Set_Node_Length(REGNODE_p(ret),
12633 op == '{' ? (RExC_parse - parse_start) : 1);
12634
12635 if (RExC_use_BRANCHJ)
12636 NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over NOTHING to
12637 LONGJMP. */
12638 if (! REGTAIL(pRExC_state, ret, reg_node(pRExC_state,
12639 NOTHING)))
12640 {
12641 REQUIRE_BRANCHJ(flagp, 0);
12642 }
12643 RExC_whilem_seen++;
12644 MARK_NAUGHTY_EXP(1, 4); /* compound interest */
12645 }
12646 FLAGS(REGNODE_p(ret)) = 0;
12647
12648 if (min > 0)
12649 *flagp = WORST;
12650 if (max > 0)
12651 *flagp |= HASWIDTH;
12652 ARG1_SET(REGNODE_p(ret), (U16)min);
12653 ARG2_SET(REGNODE_p(ret), (U16)max);
12654 if (max == REG_INFTY)
12655 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12656
12657 goto nest_check;
12658 }
12659 }
12660
12661 if (!ISMULT1(op)) {
12662 *flagp = flags;
12663 return(ret);
12664 }
12665
12666#if 0 /* Now runtime fix should be reliable. */
12667
12668 /* if this is reinstated, don't forget to put this back into perldiag:
12669
12670 =item Regexp *+ operand could be empty at {#} in regex m/%s/
12671
12672 (F) The part of the regexp subject to either the * or + quantifier
12673 could match an empty string. The {#} shows in the regular
12674 expression about where the problem was discovered.
12675
12676 */
12677
12678 if (!(flags&HASWIDTH) && op != '?')
12679 vFAIL("Regexp *+ operand could be empty");
12680#endif
12681
12682#ifdef RE_TRACK_PATTERN_OFFSETS
12683 parse_start = RExC_parse;
12684#endif
12685 nextchar(pRExC_state);
12686
12687 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
12688
12689 if (op == '*') {
12690 min = 0;
12691 goto do_curly;
12692 }
12693 else if (op == '+') {
12694 min = 1;
12695 goto do_curly;
12696 }
12697 else if (op == '?') {
12698 min = 0; max = 1;
12699 goto do_curly;
12700 }
12701 nest_check:
12702 if (!(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
12703 if (origparse[0] == '\\' && origparse[1] == 'K') {
12704 vFAIL2utf8f(
12705 "%" UTF8f " is forbidden - matches null string many times",
12706 UTF8fARG(UTF, (RExC_parse >= origparse
12707 ? RExC_parse - origparse
12708 : 0),
12709 origparse));
12710 /* NOT-REACHED */
12711 } else {
12712 ckWARN2reg(RExC_parse,
12713 "%" UTF8f " matches null string many times",
12714 UTF8fARG(UTF, (RExC_parse >= origparse
12715 ? RExC_parse - origparse
12716 : 0),
12717 origparse));
12718 }
12719 }
12720
12721 if (*RExC_parse == '?') {
12722 nextchar(pRExC_state);
12723 reginsert(pRExC_state, MINMOD, ret, depth+1);
12724 if (! REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE)) {
12725 REQUIRE_BRANCHJ(flagp, 0);
12726 }
12727 }
12728 else if (*RExC_parse == '+') {
12729 regnode_offset ender;
12730 nextchar(pRExC_state);
12731 ender = reg_node(pRExC_state, SUCCEED);
12732 if (! REGTAIL(pRExC_state, ret, ender)) {
12733 REQUIRE_BRANCHJ(flagp, 0);
12734 }
12735 reginsert(pRExC_state, SUSPEND, ret, depth+1);
12736 ender = reg_node(pRExC_state, TAIL);
12737 if (! REGTAIL(pRExC_state, ret, ender)) {
12738 REQUIRE_BRANCHJ(flagp, 0);
12739 }
12740 }
12741
12742 if (ISMULT2(RExC_parse)) {
12743 RExC_parse++;
12744 vFAIL("Nested quantifiers");
12745 }
12746
12747 return(ret);
12748}
12749
12750STATIC bool
12751S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state,
12752 regnode_offset * node_p,
12753 UV * code_point_p,
12754 int * cp_count,
12755 I32 * flagp,
12756 const bool strict,
12757 const U32 depth
12758 )
12759{
12760 /* This routine teases apart the various meanings of \N and returns
12761 * accordingly. The input parameters constrain which meaning(s) is/are valid
12762 * in the current context.
12763 *
12764 * Exactly one of <node_p> and <code_point_p> must be non-NULL.
12765 *
12766 * If <code_point_p> is not NULL, the context is expecting the result to be a
12767 * single code point. If this \N instance turns out to a single code point,
12768 * the function returns TRUE and sets *code_point_p to that code point.
12769 *
12770 * If <node_p> is not NULL, the context is expecting the result to be one of
12771 * the things representable by a regnode. If this \N instance turns out to be
12772 * one such, the function generates the regnode, returns TRUE and sets *node_p
12773 * to point to the offset of that regnode into the regex engine program being
12774 * compiled.
12775 *
12776 * If this instance of \N isn't legal in any context, this function will
12777 * generate a fatal error and not return.
12778 *
12779 * On input, RExC_parse should point to the first char following the \N at the
12780 * time of the call. On successful return, RExC_parse will have been updated
12781 * to point to just after the sequence identified by this routine. Also
12782 * *flagp has been updated as needed.
12783 *
12784 * When there is some problem with the current context and this \N instance,
12785 * the function returns FALSE, without advancing RExC_parse, nor setting
12786 * *node_p, nor *code_point_p, nor *flagp.
12787 *
12788 * If <cp_count> is not NULL, the caller wants to know the length (in code
12789 * points) that this \N sequence matches. This is set, and the input is
12790 * parsed for errors, even if the function returns FALSE, as detailed below.
12791 *
12792 * There are 6 possibilities here, as detailed in the next 6 paragraphs.
12793 *
12794 * Probably the most common case is for the \N to specify a single code point.
12795 * *cp_count will be set to 1, and *code_point_p will be set to that code
12796 * point.
12797 *
12798 * Another possibility is for the input to be an empty \N{}. This is no
12799 * longer accepted, and will generate a fatal error.
12800 *
12801 * Another possibility is for a custom charnames handler to be in effect which
12802 * translates the input name to an empty string. *cp_count will be set to 0.
12803 * *node_p will be set to a generated NOTHING node.
12804 *
12805 * Still another possibility is for the \N to mean [^\n]. *cp_count will be
12806 * set to 0. *node_p will be set to a generated REG_ANY node.
12807 *
12808 * The fifth possibility is that \N resolves to a sequence of more than one
12809 * code points. *cp_count will be set to the number of code points in the
12810 * sequence. *node_p will be set to a generated node returned by this
12811 * function calling S_reg().
12812 *
12813 * The final possibility is that it is premature to be calling this function;
12814 * the parse needs to be restarted. This can happen when this changes from
12815 * /d to /u rules, or when the pattern needs to be upgraded to UTF-8. The
12816 * latter occurs only when the fifth possibility would otherwise be in
12817 * effect, and is because one of those code points requires the pattern to be
12818 * recompiled as UTF-8. The function returns FALSE, and sets the
12819 * RESTART_PARSE and NEED_UTF8 flags in *flagp, as appropriate. When this
12820 * happens, the caller needs to desist from continuing parsing, and return
12821 * this information to its caller. This is not set for when there is only one
12822 * code point, as this can be called as part of an ANYOF node, and they can
12823 * store above-Latin1 code points without the pattern having to be in UTF-8.
12824 *
12825 * For non-single-quoted regexes, the tokenizer has resolved character and
12826 * sequence names inside \N{...} into their Unicode values, normalizing the
12827 * result into what we should see here: '\N{U+c1.c2...}', where c1... are the
12828 * hex-represented code points in the sequence. This is done there because
12829 * the names can vary based on what charnames pragma is in scope at the time,
12830 * so we need a way to take a snapshot of what they resolve to at the time of
12831 * the original parse. [perl #56444].
12832 *
12833 * That parsing is skipped for single-quoted regexes, so here we may get
12834 * '\N{NAME}', which is parsed now. If the single-quoted regex is something
12835 * like '\N{U+41}', that code point is Unicode, and has to be translated into
12836 * the native character set for non-ASCII platforms. The other possibilities
12837 * are already native, so no translation is done. */
12838
12839 char * endbrace; /* points to '}' following the name */
12840 char* p = RExC_parse; /* Temporary */
12841
12842 SV * substitute_parse = NULL;
12843 char *orig_end;
12844 char *save_start;
12845 I32 flags;
12846
12847 GET_RE_DEBUG_FLAGS_DECL;
12848
12849 PERL_ARGS_ASSERT_GROK_BSLASH_N;
12850
12851 GET_RE_DEBUG_FLAGS;
12852
12853 assert(cBOOL(node_p) ^ cBOOL(code_point_p)); /* Exactly one should be set */
12854 assert(! (node_p && cp_count)); /* At most 1 should be set */
12855
12856 if (cp_count) { /* Initialize return for the most common case */
12857 *cp_count = 1;
12858 }
12859
12860 /* The [^\n] meaning of \N ignores spaces and comments under the /x
12861 * modifier. The other meanings do not, so use a temporary until we find
12862 * out which we are being called with */
12863 skip_to_be_ignored_text(pRExC_state, &p,
12864 FALSE /* Don't force to /x */ );
12865
12866 /* Disambiguate between \N meaning a named character versus \N meaning
12867 * [^\n]. The latter is assumed when the {...} following the \N is a legal
12868 * quantifier, or if there is no '{' at all */
12869 if (*p != '{' || regcurly(p)) {
12870 RExC_parse = p;
12871 if (cp_count) {
12872 *cp_count = -1;
12873 }
12874
12875 if (! node_p) {
12876 return FALSE;
12877 }
12878
12879 *node_p = reg_node(pRExC_state, REG_ANY);
12880 *flagp |= HASWIDTH|SIMPLE;
12881 MARK_NAUGHTY(1);
12882 Set_Node_Length(REGNODE_p(*(node_p)), 1); /* MJD */
12883 return TRUE;
12884 }
12885
12886 /* The test above made sure that the next real character is a '{', but
12887 * under the /x modifier, it could be separated by space (or a comment and
12888 * \n) and this is not allowed (for consistency with \x{...} and the
12889 * tokenizer handling of \N{NAME}). */
12890 if (*RExC_parse != '{') {
12891 vFAIL("Missing braces on \\N{}");
12892 }
12893
12894 RExC_parse++; /* Skip past the '{' */
12895
12896 endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
12897 if (! endbrace) { /* no trailing brace */
12898 vFAIL2("Missing right brace on \\%c{}", 'N');
12899 }
12900
12901 /* Here, we have decided it should be a named character or sequence. These
12902 * imply Unicode semantics */
12903 REQUIRE_UNI_RULES(flagp, FALSE);
12904
12905 /* \N{_} is what toke.c returns to us to indicate a name that evaluates to
12906 * nothing at all (not allowed under strict) */
12907 if (endbrace - RExC_parse == 1 && *RExC_parse == '_') {
12908 RExC_parse = endbrace;
12909 if (strict) {
12910 RExC_parse++; /* Position after the "}" */
12911 vFAIL("Zero length \\N{}");
12912 }
12913
12914 if (cp_count) {
12915 *cp_count = 0;
12916 }
12917 nextchar(pRExC_state);
12918 if (! node_p) {
12919 return FALSE;
12920 }
12921
12922 *node_p = reg_node(pRExC_state, NOTHING);
12923 return TRUE;
12924 }
12925
12926 if (endbrace - RExC_parse < 2 || ! strBEGINs(RExC_parse, "U+")) {
12927
12928 /* Here, the name isn't of the form U+.... This can happen if the
12929 * pattern is single-quoted, so didn't get evaluated in toke.c. Now
12930 * is the time to find out what the name means */
12931
12932 const STRLEN name_len = endbrace - RExC_parse;
12933 SV * value_sv; /* What does this name evaluate to */
12934 SV ** value_svp;
12935 const U8 * value; /* string of name's value */
12936 STRLEN value_len; /* and its length */
12937
12938 /* RExC_unlexed_names is a hash of names that weren't evaluated by
12939 * toke.c, and their values. Make sure is initialized */
12940 if (! RExC_unlexed_names) {
12941 RExC_unlexed_names = newHV();
12942 }
12943
12944 /* If we have already seen this name in this pattern, use that. This
12945 * allows us to only call the charnames handler once per name per
12946 * pattern. A broken or malicious handler could return something
12947 * different each time, which could cause the results to vary depending
12948 * on if something gets added or subtracted from the pattern that
12949 * causes the number of passes to change, for example */
12950 if ((value_svp = hv_fetch(RExC_unlexed_names, RExC_parse,
12951 name_len, 0)))
12952 {
12953 value_sv = *value_svp;
12954 }
12955 else { /* Otherwise we have to go out and get the name */
12956 const char * error_msg = NULL;
12957 value_sv = get_and_check_backslash_N_name(RExC_parse, endbrace,
12958 UTF,
12959 &error_msg);
12960 if (error_msg) {
12961 RExC_parse = endbrace;
12962 vFAIL(error_msg);
12963 }
12964
12965 /* If no error message, should have gotten a valid return */
12966 assert (value_sv);
12967
12968 /* Save the name's meaning for later use */
12969 if (! hv_store(RExC_unlexed_names, RExC_parse, name_len,
12970 value_sv, 0))
12971 {
12972 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
12973 }
12974 }
12975
12976 /* Here, we have the value the name evaluates to in 'value_sv' */
12977 value = (U8 *) SvPV(value_sv, value_len);
12978
12979 /* See if the result is one code point vs 0 or multiple */
12980 if (inRANGE(value_len, 1, ((UV) SvUTF8(value_sv)
12981 ? UTF8SKIP(value)
12982 : 1)))
12983 {
12984 /* Here, exactly one code point. If that isn't what is wanted,
12985 * fail */
12986 if (! code_point_p) {
12987 RExC_parse = p;
12988 return FALSE;
12989 }
12990
12991 /* Convert from string to numeric code point */
12992 *code_point_p = (SvUTF8(value_sv))
12993 ? valid_utf8_to_uvchr(value, NULL)
12994 : *value;
12995
12996 /* Have parsed this entire single code point \N{...}. *cp_count
12997 * has already been set to 1, so don't do it again. */
12998 RExC_parse = endbrace;
12999 nextchar(pRExC_state);
13000 return TRUE;
13001 } /* End of is a single code point */
13002
13003 /* Count the code points, if caller desires. The API says to do this
13004 * even if we will later return FALSE */
13005 if (cp_count) {
13006 *cp_count = 0;
13007
13008 *cp_count = (SvUTF8(value_sv))
13009 ? utf8_length(value, value + value_len)
13010 : value_len;
13011 }
13012
13013 /* Fail if caller doesn't want to handle a multi-code-point sequence.
13014 * But don't back the pointer up if the caller wants to know how many
13015 * code points there are (they need to handle it themselves in this
13016 * case). */
13017 if (! node_p) {
13018 if (! cp_count) {
13019 RExC_parse = p;
13020 }
13021 return FALSE;
13022 }
13023
13024 /* Convert this to a sub-pattern of the form "(?: ... )", and then call
13025 * reg recursively to parse it. That way, it retains its atomicness,
13026 * while not having to worry about any special handling that some code
13027 * points may have. */
13028
13029 substitute_parse = newSVpvs("?:");
13030 sv_catsv(substitute_parse, value_sv);
13031 sv_catpv(substitute_parse, ")");
13032
13033 /* The value should already be native, so no need to convert on EBCDIC
13034 * platforms.*/
13035 assert(! RExC_recode_x_to_native);
13036
13037 }
13038 else { /* \N{U+...} */
13039 Size_t count = 0; /* code point count kept internally */
13040
13041 /* We can get to here when the input is \N{U+...} or when toke.c has
13042 * converted a name to the \N{U+...} form. This include changing a
13043 * name that evaluates to multiple code points to \N{U+c1.c2.c3 ...} */
13044
13045 RExC_parse += 2; /* Skip past the 'U+' */
13046
13047 /* Code points are separated by dots. The '}' terminates the whole
13048 * thing. */
13049
13050 do { /* Loop until the ending brace */
13051 I32 flags = PERL_SCAN_SILENT_OVERFLOW
13052 | PERL_SCAN_SILENT_ILLDIGIT
13053 | PERL_SCAN_NOTIFY_ILLDIGIT
13054 | PERL_SCAN_ALLOW_MEDIAL_UNDERSCORES
13055 | PERL_SCAN_DISALLOW_PREFIX;
13056 STRLEN len = endbrace - RExC_parse;
13057 NV overflow_value;
13058 char * start_digit = RExC_parse;
13059 UV cp = grok_hex(RExC_parse, &len, &flags, &overflow_value);
13060
13061 if (len == 0) {
13062 RExC_parse++;
13063 bad_NU:
13064 vFAIL("Invalid hexadecimal number in \\N{U+...}");
13065 }
13066
13067 RExC_parse += len;
13068
13069 if (cp > MAX_LEGAL_CP) {
13070 vFAIL(form_cp_too_large_msg(16, start_digit, len, 0));
13071 }
13072
13073 if (RExC_parse >= endbrace) { /* Got to the closing '}' */
13074 if (count) {
13075 goto do_concat;
13076 }
13077
13078 /* Here, is a single code point; fail if doesn't want that */
13079 if (! code_point_p) {
13080 RExC_parse = p;
13081 return FALSE;
13082 }
13083
13084 /* A single code point is easy to handle; just return it */
13085 *code_point_p = UNI_TO_NATIVE(cp);
13086 RExC_parse = endbrace;
13087 nextchar(pRExC_state);
13088 return TRUE;
13089 }
13090
13091 /* Here, the parse stopped bfore the ending brace. This is legal
13092 * only if that character is a dot separating code points, like a
13093 * multiple character sequence (of the form "\N{U+c1.c2. ... }".
13094 * So the next character must be a dot (and the one after that
13095 * can't be the endbrace, or we'd have something like \N{U+100.} )
13096 * */
13097 if (*RExC_parse != '.' || RExC_parse + 1 >= endbrace) {
13098 RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */
13099 ? UTF8SKIP(RExC_parse)
13100 : 1;
13101 RExC_parse = MIN(endbrace, RExC_parse);/* Guard against
13102 malformed utf8 */
13103 goto bad_NU;
13104 }
13105
13106 /* Here, looks like its really a multiple character sequence. Fail
13107 * if that's not what the caller wants. But continue with counting
13108 * and error checking if they still want a count */
13109 if (! node_p && ! cp_count) {
13110 return FALSE;
13111 }
13112
13113 /* What is done here is to convert this to a sub-pattern of the
13114 * form \x{char1}\x{char2}... and then call reg recursively to
13115 * parse it (enclosing in "(?: ... )" ). That way, it retains its
13116 * atomicness, while not having to worry about special handling
13117 * that some code points may have. We don't create a subpattern,
13118 * but go through the motions of code point counting and error
13119 * checking, if the caller doesn't want a node returned. */
13120
13121 if (node_p && ! substitute_parse) {
13122 substitute_parse = newSVpvs("?:");
13123 }
13124
13125 do_concat:
13126
13127 if (node_p) {
13128 /* Convert to notation the rest of the code understands */
13129 sv_catpvs(substitute_parse, "\\x{");
13130 sv_catpvn(substitute_parse, start_digit,
13131 RExC_parse - start_digit);
13132 sv_catpvs(substitute_parse, "}");
13133 }
13134
13135 /* Move to after the dot (or ending brace the final time through.)
13136 * */
13137 RExC_parse++;
13138 count++;
13139
13140 } while (RExC_parse < endbrace);
13141
13142 if (! node_p) { /* Doesn't want the node */
13143 assert (cp_count);
13144
13145 *cp_count = count;
13146 return FALSE;
13147 }
13148
13149 sv_catpvs(substitute_parse, ")");
13150
13151 /* The values are Unicode, and therefore have to be converted to native
13152 * on a non-Unicode (meaning non-ASCII) platform. */
13153 SET_recode_x_to_native(1);
13154 }
13155
13156 /* Here, we have the string the name evaluates to, ready to be parsed,
13157 * stored in 'substitute_parse' as a series of valid "\x{...}\x{...}"
13158 * constructs. This can be called from within a substitute parse already.
13159 * The error reporting mechanism doesn't work for 2 levels of this, but the
13160 * code above has validated this new construct, so there should be no
13161 * errors generated by the below. And this isn' an exact copy, so the
13162 * mechanism to seamlessly deal with this won't work, so turn off warnings
13163 * during it */
13164 save_start = RExC_start;
13165 orig_end = RExC_end;
13166
13167 RExC_parse = RExC_start = SvPVX(substitute_parse);
13168 RExC_end = RExC_parse + SvCUR(substitute_parse);
13169 TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
13170
13171 *node_p = reg(pRExC_state, 1, &flags, depth+1);
13172
13173 /* Restore the saved values */
13174 RESTORE_WARNINGS;
13175 RExC_start = save_start;
13176 RExC_parse = endbrace;
13177 RExC_end = orig_end;
13178 SET_recode_x_to_native(0);
13179
13180 SvREFCNT_dec_NN(substitute_parse);
13181
13182 if (! *node_p) {
13183 RETURN_FAIL_ON_RESTART(flags, flagp);
13184 FAIL2("panic: reg returned failure to grok_bslash_N, flags=%#" UVxf,
13185 (UV) flags);
13186 }
13187 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
13188
13189 nextchar(pRExC_state);
13190
13191 return TRUE;
13192}
13193
13194
13195PERL_STATIC_INLINE U8
13196S_compute_EXACTish(RExC_state_t *pRExC_state)
13197{
13198 U8 op;
13199
13200 PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
13201
13202 if (! FOLD) {
13203 return (LOC)
13204 ? EXACTL
13205 : EXACT;
13206 }
13207
13208 op = get_regex_charset(RExC_flags);
13209 if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
13210 op--; /* /a is same as /u, and map /aa's offset to what /a's would have
13211 been, so there is no hole */
13212 }
13213
13214 return op + EXACTF;
13215}
13216
13217STATIC bool
13218S_new_regcurly(const char *s, const char *e)
13219{
13220 /* This is a temporary function designed to match the most lenient form of
13221 * a {m,n} quantifier we ever envision, with either number omitted, and
13222 * spaces anywhere between/before/after them.
13223 *
13224 * If this function fails, then the string it matches is very unlikely to
13225 * ever be considered a valid quantifier, so we can allow the '{' that
13226 * begins it to be considered as a literal */
13227
13228 bool has_min = FALSE;
13229 bool has_max = FALSE;
13230
13231 PERL_ARGS_ASSERT_NEW_REGCURLY;
13232
13233 if (s >= e || *s++ != '{')
13234 return FALSE;
13235
13236 while (s < e && isSPACE(*s)) {
13237 s++;
13238 }
13239 while (s < e && isDIGIT(*s)) {
13240 has_min = TRUE;
13241 s++;
13242 }
13243 while (s < e && isSPACE(*s)) {
13244 s++;
13245 }
13246
13247 if (*s == ',') {
13248 s++;
13249 while (s < e && isSPACE(*s)) {
13250 s++;
13251 }
13252 while (s < e && isDIGIT(*s)) {
13253 has_max = TRUE;
13254 s++;
13255 }
13256 while (s < e && isSPACE(*s)) {
13257 s++;
13258 }
13259 }
13260
13261 return s < e && *s == '}' && (has_min || has_max);
13262}
13263
13264/* Parse backref decimal value, unless it's too big to sensibly be a backref,
13265 * in which case return I32_MAX (rather than possibly 32-bit wrapping) */
13266
13267static I32
13268S_backref_value(char *p, char *e)
13269{
13270 const char* endptr = e;
13271 UV val;
13272 if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX)
13273 return (I32)val;
13274 return I32_MAX;
13275}
13276
13277
13278/*
13279 - regatom - the lowest level
13280
13281 Try to identify anything special at the start of the current parse position.
13282 If there is, then handle it as required. This may involve generating a
13283 single regop, such as for an assertion; or it may involve recursing, such as
13284 to handle a () structure.
13285
13286 If the string doesn't start with something special then we gobble up
13287 as much literal text as we can. If we encounter a quantifier, we have to
13288 back off the final literal character, as that quantifier applies to just it
13289 and not to the whole string of literals.
13290
13291 Once we have been able to handle whatever type of thing started the
13292 sequence, we return the offset into the regex engine program being compiled
13293 at which any next regnode should be placed.
13294
13295 Returns 0, setting *flagp to TRYAGAIN if reg() returns 0 with TRYAGAIN.
13296 Returns 0, setting *flagp to RESTART_PARSE if the parse needs to be
13297 restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
13298 Otherwise does not return 0.
13299
13300 Note: we have to be careful with escapes, as they can be both literal
13301 and special, and in the case of \10 and friends, context determines which.
13302
13303 A summary of the code structure is:
13304
13305 switch (first_byte) {
13306 cases for each special:
13307 handle this special;
13308 break;
13309 case '\\':
13310 switch (2nd byte) {
13311 cases for each unambiguous special:
13312 handle this special;
13313 break;
13314 cases for each ambigous special/literal:
13315 disambiguate;
13316 if (special) handle here
13317 else goto defchar;
13318 default: // unambiguously literal:
13319 goto defchar;
13320 }
13321 default: // is a literal char
13322 // FALL THROUGH
13323 defchar:
13324 create EXACTish node for literal;
13325 while (more input and node isn't full) {
13326 switch (input_byte) {
13327 cases for each special;
13328 make sure parse pointer is set so that the next call to
13329 regatom will see this special first
13330 goto loopdone; // EXACTish node terminated by prev. char
13331 default:
13332 append char to EXACTISH node;
13333 }
13334 get next input byte;
13335 }
13336 loopdone:
13337 }
13338 return the generated node;
13339
13340 Specifically there are two separate switches for handling
13341 escape sequences, with the one for handling literal escapes requiring
13342 a dummy entry for all of the special escapes that are actually handled
13343 by the other.
13344
13345*/
13346
13347STATIC regnode_offset
13348S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
13349{
13350 dVAR;
13351 regnode_offset ret = 0;
13352 I32 flags = 0;
13353 char *parse_start;
13354 U8 op;
13355 int invert = 0;
13356
13357 GET_RE_DEBUG_FLAGS_DECL;
13358
13359 *flagp = WORST; /* Tentatively. */
13360
13361 DEBUG_PARSE("atom");
13362
13363 PERL_ARGS_ASSERT_REGATOM;
13364
13365 tryagain:
13366 parse_start = RExC_parse;
13367 assert(RExC_parse < RExC_end);
13368 switch ((U8)*RExC_parse) {
13369 case '^':
13370 RExC_seen_zerolen++;
13371 nextchar(pRExC_state);
13372 if (RExC_flags & RXf_PMf_MULTILINE)
13373 ret = reg_node(pRExC_state, MBOL);
13374 else
13375 ret = reg_node(pRExC_state, SBOL);
13376 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13377 break;
13378 case '$':
13379 nextchar(pRExC_state);
13380 if (*RExC_parse)
13381 RExC_seen_zerolen++;
13382 if (RExC_flags & RXf_PMf_MULTILINE)
13383 ret = reg_node(pRExC_state, MEOL);
13384 else
13385 ret = reg_node(pRExC_state, SEOL);
13386 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13387 break;
13388 case '.':
13389 nextchar(pRExC_state);
13390 if (RExC_flags & RXf_PMf_SINGLELINE)
13391 ret = reg_node(pRExC_state, SANY);
13392 else
13393 ret = reg_node(pRExC_state, REG_ANY);
13394 *flagp |= HASWIDTH|SIMPLE;
13395 MARK_NAUGHTY(1);
13396 Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13397 break;
13398 case '[':
13399 {
13400 char * const oregcomp_parse = ++RExC_parse;
13401 ret = regclass(pRExC_state, flagp, depth+1,
13402 FALSE, /* means parse the whole char class */
13403 TRUE, /* allow multi-char folds */
13404 FALSE, /* don't silence non-portable warnings. */
13405 (bool) RExC_strict,
13406 TRUE, /* Allow an optimized regnode result */
13407 NULL);
13408 if (ret == 0) {
13409 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13410 FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13411 (UV) *flagp);
13412 }
13413 if (*RExC_parse != ']') {
13414 RExC_parse = oregcomp_parse;
13415 vFAIL("Unmatched [");
13416 }
13417 nextchar(pRExC_state);
13418 Set_Node_Length(REGNODE_p(ret), RExC_parse - oregcomp_parse + 1); /* MJD */
13419 break;
13420 }
13421 case '(':
13422 nextchar(pRExC_state);
13423 ret = reg(pRExC_state, 2, &flags, depth+1);
13424 if (ret == 0) {
13425 if (flags & TRYAGAIN) {
13426 if (RExC_parse >= RExC_end) {
13427 /* Make parent create an empty node if needed. */
13428 *flagp |= TRYAGAIN;
13429 return(0);
13430 }
13431 goto tryagain;
13432 }
13433 RETURN_FAIL_ON_RESTART(flags, flagp);
13434 FAIL2("panic: reg returned failure to regatom, flags=%#" UVxf,
13435 (UV) flags);
13436 }
13437 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
13438 break;
13439 case '|':
13440 case ')':
13441 if (flags & TRYAGAIN) {
13442 *flagp |= TRYAGAIN;
13443 return 0;
13444 }
13445 vFAIL("Internal urp");
13446 /* Supposed to be caught earlier. */
13447 break;
13448 case '?':
13449 case '+':
13450 case '*':
13451 RExC_parse++;
13452 vFAIL("Quantifier follows nothing");
13453 break;
13454 case '\\':
13455 /* Special Escapes
13456
13457 This switch handles escape sequences that resolve to some kind
13458 of special regop and not to literal text. Escape sequences that
13459 resolve to literal text are handled below in the switch marked
13460 "Literal Escapes".
13461
13462 Every entry in this switch *must* have a corresponding entry
13463 in the literal escape switch. However, the opposite is not
13464 required, as the default for this switch is to jump to the
13465 literal text handling code.
13466 */
13467 RExC_parse++;
13468 switch ((U8)*RExC_parse) {
13469 /* Special Escapes */
13470 case 'A':
13471 RExC_seen_zerolen++;
13472 /* Under wildcards, this is changed to match \n; should be
13473 * invisible to the user, as they have to compile under /m */
13474 if (RExC_pm_flags & PMf_WILDCARD) {
13475 ret = reg_node(pRExC_state, MBOL);
13476 }
13477 else {
13478 ret = reg_node(pRExC_state, SBOL);
13479 /* SBOL is shared with /^/ so we set the flags so we can tell
13480 * /\A/ from /^/ in split. */
13481 FLAGS(REGNODE_p(ret)) = 1;
13482 }
13483 *flagp |= SIMPLE;
13484 goto finish_meta_pat;
13485 case 'G':
13486 if (RExC_pm_flags & PMf_WILDCARD) {
13487 RExC_parse++;
13488 /* diag_listed_as: Use of %s is not allowed in Unicode property
13489 wildcard subpatterns in regex; marked by <-- HERE in m/%s/
13490 */
13491 vFAIL("Use of '\\G' is not allowed in Unicode property"
13492 " wildcard subpatterns");
13493 }
13494 ret = reg_node(pRExC_state, GPOS);
13495 RExC_seen |= REG_GPOS_SEEN;
13496 *flagp |= SIMPLE;
13497 goto finish_meta_pat;
13498 case 'K':
13499 if (!RExC_in_lookbehind && !RExC_in_lookahead) {
13500 RExC_seen_zerolen++;
13501 ret = reg_node(pRExC_state, KEEPS);
13502 *flagp |= SIMPLE;
13503 /* XXX:dmq : disabling in-place substitution seems to
13504 * be necessary here to avoid cases of memory corruption, as
13505 * with: C<$_="x" x 80; s/x\K/y/> -- rgs
13506 */
13507 RExC_seen |= REG_LOOKBEHIND_SEEN;
13508 goto finish_meta_pat;
13509 }
13510 else {
13511 ++RExC_parse; /* advance past the 'K' */
13512 vFAIL("\\K not permitted in lookahead/lookbehind");
13513 }
13514 case 'Z':
13515 if (RExC_pm_flags & PMf_WILDCARD) {
13516 /* See comment under \A above */
13517 ret = reg_node(pRExC_state, MEOL);
13518 }
13519 else {
13520 ret = reg_node(pRExC_state, SEOL);
13521 }
13522 *flagp |= SIMPLE;
13523 RExC_seen_zerolen++; /* Do not optimize RE away */
13524 goto finish_meta_pat;
13525 case 'z':
13526 if (RExC_pm_flags & PMf_WILDCARD) {
13527 /* See comment under \A above */
13528 ret = reg_node(pRExC_state, MEOL);
13529 }
13530 else {
13531 ret = reg_node(pRExC_state, EOS);
13532 }
13533 *flagp |= SIMPLE;
13534 RExC_seen_zerolen++; /* Do not optimize RE away */
13535 goto finish_meta_pat;
13536 case 'C':
13537 vFAIL("\\C no longer supported");
13538 case 'X':
13539 ret = reg_node(pRExC_state, CLUMP);
13540 *flagp |= HASWIDTH;
13541 goto finish_meta_pat;
13542
13543 case 'B':
13544 invert = 1;
13545 /* FALLTHROUGH */
13546 case 'b':
13547 {
13548 U8 flags = 0;
13549 regex_charset charset = get_regex_charset(RExC_flags);
13550
13551 RExC_seen_zerolen++;
13552 RExC_seen |= REG_LOOKBEHIND_SEEN;
13553 op = BOUND + charset;
13554
13555 if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') {
13556 flags = TRADITIONAL_BOUND;
13557 if (op > BOUNDA) { /* /aa is same as /a */
13558 op = BOUNDA;
13559 }
13560 }
13561 else {
13562 STRLEN length;
13563 char name = *RExC_parse;
13564 char * endbrace = NULL;
13565 RExC_parse += 2;
13566 endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
13567
13568 if (! endbrace) {
13569 vFAIL2("Missing right brace on \\%c{}", name);
13570 }
13571 /* XXX Need to decide whether to take spaces or not. Should be
13572 * consistent with \p{}, but that currently is SPACE, which
13573 * means vertical too, which seems wrong
13574 * while (isBLANK(*RExC_parse)) {
13575 RExC_parse++;
13576 }*/
13577 if (endbrace == RExC_parse) {
13578 RExC_parse++; /* After the '}' */
13579 vFAIL2("Empty \\%c{}", name);
13580 }
13581 length = endbrace - RExC_parse;
13582 /*while (isBLANK(*(RExC_parse + length - 1))) {
13583 length--;
13584 }*/
13585 switch (*RExC_parse) {
13586 case 'g':
13587 if ( length != 1
13588 && (memNEs(RExC_parse + 1, length - 1, "cb")))
13589 {
13590 goto bad_bound_type;
13591 }
13592 flags = GCB_BOUND;
13593 break;
13594 case 'l':
13595 if (length != 2 || *(RExC_parse + 1) != 'b') {
13596 goto bad_bound_type;
13597 }
13598 flags = LB_BOUND;
13599 break;
13600 case 's':
13601 if (length != 2 || *(RExC_parse + 1) != 'b') {
13602 goto bad_bound_type;
13603 }
13604 flags = SB_BOUND;
13605 break;
13606 case 'w':
13607 if (length != 2 || *(RExC_parse + 1) != 'b') {
13608 goto bad_bound_type;
13609 }
13610 flags = WB_BOUND;
13611 break;
13612 default:
13613 bad_bound_type:
13614 RExC_parse = endbrace;
13615 vFAIL2utf8f(
13616 "'%" UTF8f "' is an unknown bound type",
13617 UTF8fARG(UTF, length, endbrace - length));
13618 NOT_REACHED; /*NOTREACHED*/
13619 }
13620 RExC_parse = endbrace;
13621 REQUIRE_UNI_RULES(flagp, 0);
13622
13623 if (op == BOUND) {
13624 op = BOUNDU;
13625 }
13626 else if (op >= BOUNDA) { /* /aa is same as /a */
13627 op = BOUNDU;
13628 length += 4;
13629
13630 /* Don't have to worry about UTF-8, in this message because
13631 * to get here the contents of the \b must be ASCII */
13632 ckWARN4reg(RExC_parse + 1, /* Include the '}' in msg */
13633 "Using /u for '%.*s' instead of /%s",
13634 (unsigned) length,
13635 endbrace - length + 1,
13636 (charset == REGEX_ASCII_RESTRICTED_CHARSET)
13637 ? ASCII_RESTRICT_PAT_MODS
13638 : ASCII_MORE_RESTRICT_PAT_MODS);
13639 }
13640 }
13641
13642 if (op == BOUND) {
13643 RExC_seen_d_op = TRUE;
13644 }
13645 else if (op == BOUNDL) {
13646 RExC_contains_locale = 1;
13647 }
13648
13649 if (invert) {
13650 op += NBOUND - BOUND;
13651 }
13652
13653 ret = reg_node(pRExC_state, op);
13654 FLAGS(REGNODE_p(ret)) = flags;
13655
13656 *flagp |= SIMPLE;
13657
13658 goto finish_meta_pat;
13659 }
13660
13661 case 'R':
13662 ret = reg_node(pRExC_state, LNBREAK);
13663 *flagp |= HASWIDTH|SIMPLE;
13664 goto finish_meta_pat;
13665
13666 case 'd':
13667 case 'D':
13668 case 'h':
13669 case 'H':
13670 case 'p':
13671 case 'P':
13672 case 's':
13673 case 'S':
13674 case 'v':
13675 case 'V':
13676 case 'w':
13677 case 'W':
13678 /* These all have the same meaning inside [brackets], and it knows
13679 * how to do the best optimizations for them. So, pretend we found
13680 * these within brackets, and let it do the work */
13681 RExC_parse--;
13682
13683 ret = regclass(pRExC_state, flagp, depth+1,
13684 TRUE, /* means just parse this element */
13685 FALSE, /* don't allow multi-char folds */
13686 FALSE, /* don't silence non-portable warnings. It
13687 would be a bug if these returned
13688 non-portables */
13689 (bool) RExC_strict,
13690 TRUE, /* Allow an optimized regnode result */
13691 NULL);
13692 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13693 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
13694 * multi-char folds are allowed. */
13695 if (!ret)
13696 FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13697 (UV) *flagp);
13698
13699 RExC_parse--; /* regclass() leaves this one too far ahead */
13700
13701 finish_meta_pat:
13702 /* The escapes above that don't take a parameter can't be
13703 * followed by a '{'. But 'pX', 'p{foo}' and
13704 * correspondingly 'P' can be */
13705 if ( RExC_parse - parse_start == 1
13706 && UCHARAT(RExC_parse + 1) == '{'
13707 && UNLIKELY(! new_regcurly(RExC_parse + 1, RExC_end)))
13708 {
13709 RExC_parse += 2;
13710 vFAIL("Unescaped left brace in regex is illegal here");
13711 }
13712 Set_Node_Offset(REGNODE_p(ret), parse_start);
13713 Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1); /* MJD */
13714 nextchar(pRExC_state);
13715 break;
13716 case 'N':
13717 /* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the
13718 * \N{...} evaluates to a sequence of more than one code points).
13719 * The function call below returns a regnode, which is our result.
13720 * The parameters cause it to fail if the \N{} evaluates to a
13721 * single code point; we handle those like any other literal. The
13722 * reason that the multicharacter case is handled here and not as
13723 * part of the EXACtish code is because of quantifiers. In
13724 * /\N{BLAH}+/, the '+' applies to the whole thing, and doing it
13725 * this way makes that Just Happen. dmq.
13726 * join_exact() will join this up with adjacent EXACTish nodes
13727 * later on, if appropriate. */
13728 ++RExC_parse;
13729 if (grok_bslash_N(pRExC_state,
13730 &ret, /* Want a regnode returned */
13731 NULL, /* Fail if evaluates to a single code
13732 point */
13733 NULL, /* Don't need a count of how many code
13734 points */
13735 flagp,
13736 RExC_strict,
13737 depth)
13738 ) {
13739 break;
13740 }
13741
13742 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13743
13744 /* Here, evaluates to a single code point. Go get that */
13745 RExC_parse = parse_start;
13746 goto defchar;
13747
13748 case 'k': /* Handle \k<NAME> and \k'NAME' */
13749 parse_named_seq:
13750 {
13751 char ch;
13752 if ( RExC_parse >= RExC_end - 1
13753 || (( ch = RExC_parse[1]) != '<'
13754 && ch != '\''
13755 && ch != '{'))
13756 {
13757 RExC_parse++;
13758 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
13759 vFAIL2("Sequence %.2s... not terminated", parse_start);
13760 } else {
13761 RExC_parse += 2;
13762 ret = handle_named_backref(pRExC_state,
13763 flagp,
13764 parse_start,
13765 (ch == '<')
13766 ? '>'
13767 : (ch == '{')
13768 ? '}'
13769 : '\'');
13770 }
13771 break;
13772 }
13773 case 'g':
13774 case '1': case '2': case '3': case '4':
13775 case '5': case '6': case '7': case '8': case '9':
13776 {
13777 I32 num;
13778 bool hasbrace = 0;
13779
13780 if (*RExC_parse == 'g') {
13781 bool isrel = 0;
13782
13783 RExC_parse++;
13784 if (*RExC_parse == '{') {
13785 RExC_parse++;
13786 hasbrace = 1;
13787 }
13788 if (*RExC_parse == '-') {
13789 RExC_parse++;
13790 isrel = 1;
13791 }
13792 if (hasbrace && !isDIGIT(*RExC_parse)) {
13793 if (isrel) RExC_parse--;
13794 RExC_parse -= 2;
13795 goto parse_named_seq;
13796 }
13797
13798 if (RExC_parse >= RExC_end) {
13799 goto unterminated_g;
13800 }
13801 num = S_backref_value(RExC_parse, RExC_end);
13802 if (num == 0)
13803 vFAIL("Reference to invalid group 0");
13804 else if (num == I32_MAX) {
13805 if (isDIGIT(*RExC_parse))
13806 vFAIL("Reference to nonexistent group");
13807 else
13808 unterminated_g:
13809 vFAIL("Unterminated \\g... pattern");
13810 }
13811
13812 if (isrel) {
13813 num = RExC_npar - num;
13814 if (num < 1)
13815 vFAIL("Reference to nonexistent or unclosed group");
13816 }
13817 }
13818 else {
13819 num = S_backref_value(RExC_parse, RExC_end);
13820 /* bare \NNN might be backref or octal - if it is larger
13821 * than or equal RExC_npar then it is assumed to be an
13822 * octal escape. Note RExC_npar is +1 from the actual
13823 * number of parens. */
13824 /* Note we do NOT check if num == I32_MAX here, as that is
13825 * handled by the RExC_npar check */
13826
13827 if (
13828 /* any numeric escape < 10 is always a backref */
13829 num > 9
13830 /* any numeric escape < RExC_npar is a backref */
13831 && num >= RExC_npar
13832 /* cannot be an octal escape if it starts with 8 */
13833 && *RExC_parse != '8'
13834 /* cannot be an octal escape if it starts with 9 */
13835 && *RExC_parse != '9'
13836 ) {
13837 /* Probably not meant to be a backref, instead likely
13838 * to be an octal character escape, e.g. \35 or \777.
13839 * The above logic should make it obvious why using
13840 * octal escapes in patterns is problematic. - Yves */
13841 RExC_parse = parse_start;
13842 goto defchar;
13843 }
13844 }
13845
13846 /* At this point RExC_parse points at a numeric escape like
13847 * \12 or \88 or something similar, which we should NOT treat
13848 * as an octal escape. It may or may not be a valid backref
13849 * escape. For instance \88888888 is unlikely to be a valid
13850 * backref. */
13851 while (isDIGIT(*RExC_parse))
13852 RExC_parse++;
13853 if (hasbrace) {
13854 if (*RExC_parse != '}')
13855 vFAIL("Unterminated \\g{...} pattern");
13856 RExC_parse++;
13857 }
13858 if (num >= (I32)RExC_npar) {
13859
13860 /* It might be a forward reference; we can't fail until we
13861 * know, by completing the parse to get all the groups, and
13862 * then reparsing */
13863 if (ALL_PARENS_COUNTED) {
13864 if (num >= RExC_total_parens) {
13865 vFAIL("Reference to nonexistent group");
13866 }
13867 }
13868 else {
13869 REQUIRE_PARENS_PASS;
13870 }
13871 }
13872 RExC_sawback = 1;
13873 ret = reganode(pRExC_state,
13874 ((! FOLD)
13875 ? REF
13876 : (ASCII_FOLD_RESTRICTED)
13877 ? REFFA
13878 : (AT_LEAST_UNI_SEMANTICS)
13879 ? REFFU
13880 : (LOC)
13881 ? REFFL
13882 : REFF),
13883 num);
13884 if (OP(REGNODE_p(ret)) == REFF) {
13885 RExC_seen_d_op = TRUE;
13886 }
13887 *flagp |= HASWIDTH;
13888
13889 /* override incorrect value set in reganode MJD */
13890 Set_Node_Offset(REGNODE_p(ret), parse_start);
13891 Set_Node_Cur_Length(REGNODE_p(ret), parse_start-1);
13892 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
13893 FALSE /* Don't force to /x */ );
13894 }
13895 break;
13896 case '\0':
13897 if (RExC_parse >= RExC_end)
13898 FAIL("Trailing \\");
13899 /* FALLTHROUGH */
13900 default:
13901 /* Do not generate "unrecognized" warnings here, we fall
13902 back into the quick-grab loop below */
13903 RExC_parse = parse_start;
13904 goto defchar;
13905 } /* end of switch on a \foo sequence */
13906 break;
13907
13908 case '#':
13909
13910 /* '#' comments should have been spaced over before this function was
13911 * called */
13912 assert((RExC_flags & RXf_PMf_EXTENDED) == 0);
13913 /*
13914 if (RExC_flags & RXf_PMf_EXTENDED) {
13915 RExC_parse = reg_skipcomment( pRExC_state, RExC_parse );
13916 if (RExC_parse < RExC_end)
13917 goto tryagain;
13918 }
13919 */
13920
13921 /* FALLTHROUGH */
13922
13923 default:
13924 defchar: {
13925
13926 /* Here, we have determined that the next thing is probably a
13927 * literal character. RExC_parse points to the first byte of its
13928 * definition. (It still may be an escape sequence that evaluates
13929 * to a single character) */
13930
13931 STRLEN len = 0;
13932 UV ender = 0;
13933 char *p;
13934 char *s, *old_s = NULL, *old_old_s = NULL;
13935 char *s0;
13936 U32 max_string_len = 255;
13937
13938 /* We may have to reparse the node, artificially stopping filling
13939 * it early, based on info gleaned in the first parse. This
13940 * variable gives where we stop. Make it above the normal stopping
13941 * place first time through; otherwise it would stop too early */
13942 U32 upper_fill = max_string_len + 1;
13943
13944 /* We start out as an EXACT node, even if under /i, until we find a
13945 * character which is in a fold. The algorithm now segregates into
13946 * separate nodes, characters that fold from those that don't under
13947 * /i. (This hopefully will create nodes that are fixed strings
13948 * even under /i, giving the optimizer something to grab on to.)
13949 * So, if a node has something in it and the next character is in
13950 * the opposite category, that node is closed up, and the function
13951 * returns. Then regatom is called again, and a new node is
13952 * created for the new category. */
13953 U8 node_type = EXACT;
13954
13955 /* Assume the node will be fully used; the excess is given back at
13956 * the end. Under /i, we may need to temporarily add the fold of
13957 * an extra character or two at the end to check for splitting
13958 * multi-char folds, so allocate extra space for that. We can't
13959 * make any other length assumptions, as a byte input sequence
13960 * could shrink down. */
13961 Ptrdiff_t current_string_nodes = STR_SZ(max_string_len
13962 + ((! FOLD)
13963 ? 0
13964 : 2 * ((UTF)
13965 ? UTF8_MAXBYTES_CASE
13966 /* Max non-UTF-8 expansion is 2 */ : 2)));
13967
13968 bool next_is_quantifier;
13969 char * oldp = NULL;
13970
13971 /* We can convert EXACTF nodes to EXACTFU if they contain only
13972 * characters that match identically regardless of the target
13973 * string's UTF8ness. The reason to do this is that EXACTF is not
13974 * trie-able, EXACTFU is, and EXACTFU requires fewer operations at
13975 * runtime.
13976 *
13977 * Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they
13978 * contain only above-Latin1 characters (hence must be in UTF8),
13979 * which don't participate in folds with Latin1-range characters,
13980 * as the latter's folds aren't known until runtime. */
13981 bool maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC);
13982
13983 /* Single-character EXACTish nodes are almost always SIMPLE. This
13984 * allows us to override this as encountered */
13985 U8 maybe_SIMPLE = SIMPLE;
13986
13987 /* Does this node contain something that can't match unless the
13988 * target string is (also) in UTF-8 */
13989 bool requires_utf8_target = FALSE;
13990
13991 /* The sequence 'ss' is problematic in non-UTF-8 patterns. */
13992 bool has_ss = FALSE;
13993
13994 /* So is the MICRO SIGN */
13995 bool has_micro_sign = FALSE;
13996
13997 /* Set when we fill up the current node and there is still more
13998 * text to process */
13999 bool overflowed;
14000
14001 /* Allocate an EXACT node. The node_type may change below to
14002 * another EXACTish node, but since the size of the node doesn't
14003 * change, it works */
14004 ret = regnode_guts(pRExC_state, node_type, current_string_nodes,
14005 "exact");
14006 FILL_NODE(ret, node_type);
14007 RExC_emit++;
14008
14009 s = STRING(REGNODE_p(ret));
14010
14011 s0 = s;
14012
14013 reparse:
14014
14015 p = RExC_parse;
14016 len = 0;
14017 s = s0;
14018 node_type = EXACT;
14019 oldp = NULL;
14020 maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC);
14021 maybe_SIMPLE = SIMPLE;
14022 requires_utf8_target = FALSE;
14023 has_ss = FALSE;
14024 has_micro_sign = FALSE;
14025
14026 continue_parse:
14027
14028 /* This breaks under rare circumstances. If folding, we do not
14029 * want to split a node at a character that is a non-final in a
14030 * multi-char fold, as an input string could just happen to want to
14031 * match across the node boundary. The code at the end of the loop
14032 * looks for this, and backs off until it finds not such a
14033 * character, but it is possible (though extremely, extremely
14034 * unlikely) for all characters in the node to be non-final fold
14035 * ones, in which case we just leave the node fully filled, and
14036 * hope that it doesn't match the string in just the wrong place */
14037
14038 assert( ! UTF /* Is at the beginning of a character */
14039 || UTF8_IS_INVARIANT(UCHARAT(RExC_parse))
14040 || UTF8_IS_START(UCHARAT(RExC_parse)));
14041
14042 overflowed = FALSE;
14043
14044 /* Here, we have a literal character. Find the maximal string of
14045 * them in the input that we can fit into a single EXACTish node.
14046 * We quit at the first non-literal or when the node gets full, or
14047 * under /i the categorization of folding/non-folding character
14048 * changes */
14049 while (p < RExC_end && len < upper_fill) {
14050
14051 /* In most cases each iteration adds one byte to the output.
14052 * The exceptions override this */
14053 Size_t added_len = 1;
14054
14055 oldp = p;
14056 old_old_s = old_s;
14057 old_s = s;
14058
14059 /* White space has already been ignored */
14060 assert( (RExC_flags & RXf_PMf_EXTENDED) == 0
14061 || ! is_PATWS_safe((p), RExC_end, UTF));
14062
14063 switch ((U8)*p) {
14064 const char* message;
14065 U32 packed_warn;
14066 U8 grok_c_char;
14067
14068 case '^':
14069 case '$':
14070 case '.':
14071 case '[':
14072 case '(':
14073 case ')':
14074 case '|':
14075 goto loopdone;
14076 case '\\':
14077 /* Literal Escapes Switch
14078
14079 This switch is meant to handle escape sequences that
14080 resolve to a literal character.
14081
14082 Every escape sequence that represents something
14083 else, like an assertion or a char class, is handled
14084 in the switch marked 'Special Escapes' above in this
14085 routine, but also has an entry here as anything that
14086 isn't explicitly mentioned here will be treated as
14087 an unescaped equivalent literal.
14088 */
14089
14090 switch ((U8)*++p) {
14091
14092 /* These are all the special escapes. */
14093 case 'A': /* Start assertion */
14094 case 'b': case 'B': /* Word-boundary assertion*/
14095 case 'C': /* Single char !DANGEROUS! */
14096 case 'd': case 'D': /* digit class */
14097 case 'g': case 'G': /* generic-backref, pos assertion */
14098 case 'h': case 'H': /* HORIZWS */
14099 case 'k': case 'K': /* named backref, keep marker */
14100 case 'p': case 'P': /* Unicode property */
14101 case 'R': /* LNBREAK */
14102 case 's': case 'S': /* space class */
14103 case 'v': case 'V': /* VERTWS */
14104 case 'w': case 'W': /* word class */
14105 case 'X': /* eXtended Unicode "combining
14106 character sequence" */
14107 case 'z': case 'Z': /* End of line/string assertion */
14108 --p;
14109 goto loopdone;
14110
14111 /* Anything after here is an escape that resolves to a
14112 literal. (Except digits, which may or may not)
14113 */
14114 case 'n':
14115 ender = '\n';
14116 p++;
14117 break;
14118 case 'N': /* Handle a single-code point named character. */
14119 RExC_parse = p + 1;
14120 if (! grok_bslash_N(pRExC_state,
14121 NULL, /* Fail if evaluates to
14122 anything other than a
14123 single code point */
14124 &ender, /* The returned single code
14125 point */
14126 NULL, /* Don't need a count of
14127 how many code points */
14128 flagp,
14129 RExC_strict,
14130 depth)
14131 ) {
14132 if (*flagp & NEED_UTF8)
14133 FAIL("panic: grok_bslash_N set NEED_UTF8");
14134 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
14135
14136 /* Here, it wasn't a single code point. Go close
14137 * up this EXACTish node. The switch() prior to
14138 * this switch handles the other cases */
14139 RExC_parse = p = oldp;
14140 goto loopdone;
14141 }
14142 p = RExC_parse;
14143 RExC_parse = parse_start;
14144
14145 /* The \N{} means the pattern, if previously /d,
14146 * becomes /u. That means it can't be an EXACTF node,
14147 * but an EXACTFU */
14148 if (node_type == EXACTF) {
14149 node_type = EXACTFU;
14150
14151 /* If the node already contains something that
14152 * differs between EXACTF and EXACTFU, reparse it
14153 * as EXACTFU */
14154 if (! maybe_exactfu) {
14155 len = 0;
14156 s = s0;
14157 goto reparse;
14158 }
14159 }
14160
14161 break;
14162 case 'r':
14163 ender = '\r';
14164 p++;
14165 break;
14166 case 't':
14167 ender = '\t';
14168 p++;
14169 break;
14170 case 'f':
14171 ender = '\f';
14172 p++;
14173 break;
14174 case 'e':
14175 ender = ESC_NATIVE;
14176 p++;
14177 break;
14178 case 'a':
14179 ender = '\a';
14180 p++;
14181 break;
14182 case 'o':
14183 if (! grok_bslash_o(&p,
14184 RExC_end,
14185 &ender,
14186 &message,
14187 &packed_warn,
14188 (bool) RExC_strict,
14189 FALSE, /* No illegal cp's */
14190 UTF))
14191 {
14192 RExC_parse = p; /* going to die anyway; point to
14193 exact spot of failure */
14194 vFAIL(message);
14195 }
14196
14197 if (message && TO_OUTPUT_WARNINGS(p)) {
14198 warn_non_literal_string(p, packed_warn, message);
14199 }
14200 break;
14201 case 'x':
14202 if (! grok_bslash_x(&p,
14203 RExC_end,
14204 &ender,
14205 &message,
14206 &packed_warn,
14207 (bool) RExC_strict,
14208 FALSE, /* No illegal cp's */
14209 UTF))
14210 {
14211 RExC_parse = p; /* going to die anyway; point
14212 to exact spot of failure */
14213 vFAIL(message);
14214 }
14215
14216 if (message && TO_OUTPUT_WARNINGS(p)) {
14217 warn_non_literal_string(p, packed_warn, message);
14218 }
14219
14220#ifdef EBCDIC
14221 if (ender < 0x100) {
14222 if (RExC_recode_x_to_native) {
14223 ender = LATIN1_TO_NATIVE(ender);
14224 }
14225 }
14226#endif
14227 break;
14228 case 'c':
14229 p++;
14230 if (! grok_bslash_c(*p, &grok_c_char,
14231 &message, &packed_warn))
14232 {
14233 /* going to die anyway; point to exact spot of
14234 * failure */
14235 RExC_parse = p + ((UTF)
14236 ? UTF8_SAFE_SKIP(p, RExC_end)
14237 : 1);
14238 vFAIL(message);
14239 }
14240
14241 ender = grok_c_char;
14242 p++;
14243 if (message && TO_OUTPUT_WARNINGS(p)) {
14244 warn_non_literal_string(p, packed_warn, message);
14245 }
14246
14247 break;
14248 case '8': case '9': /* must be a backreference */
14249 --p;
14250 /* we have an escape like \8 which cannot be an octal escape
14251 * so we exit the loop, and let the outer loop handle this
14252 * escape which may or may not be a legitimate backref. */
14253 goto loopdone;
14254 case '1': case '2': case '3':case '4':
14255 case '5': case '6': case '7':
14256 /* When we parse backslash escapes there is ambiguity
14257 * between backreferences and octal escapes. Any escape
14258 * from \1 - \9 is a backreference, any multi-digit
14259 * escape which does not start with 0 and which when
14260 * evaluated as decimal could refer to an already
14261 * parsed capture buffer is a back reference. Anything
14262 * else is octal.
14263 *
14264 * Note this implies that \118 could be interpreted as
14265 * 118 OR as "\11" . "8" depending on whether there
14266 * were 118 capture buffers defined already in the
14267 * pattern. */
14268
14269 /* NOTE, RExC_npar is 1 more than the actual number of
14270 * parens we have seen so far, hence the "<" as opposed
14271 * to "<=" */
14272 if ( !isDIGIT(p[1]) || S_backref_value(p, RExC_end) < RExC_npar)
14273 { /* Not to be treated as an octal constant, go
14274 find backref */
14275 --p;
14276 goto loopdone;
14277 }
14278 /* FALLTHROUGH */
14279 case '0':
14280 {
14281 I32 flags = PERL_SCAN_SILENT_ILLDIGIT
14282 | PERL_SCAN_NOTIFY_ILLDIGIT;
14283 STRLEN numlen = 3;
14284 ender = grok_oct(p, &numlen, &flags, NULL);
14285 p += numlen;
14286 if ( (flags & PERL_SCAN_NOTIFY_ILLDIGIT)
14287 && isDIGIT(*p) /* like \08, \178 */
14288 && ckWARN(WARN_REGEXP))
14289 {
14290 reg_warn_non_literal_string(
14291 p + 1,
14292 form_alien_digit_msg(8, numlen, p,
14293 RExC_end, UTF, FALSE));
14294 }
14295 }
14296 break;
14297 case '\0':
14298 if (p >= RExC_end)
14299 FAIL("Trailing \\");
14300 /* FALLTHROUGH */
14301 default:
14302 if (isALPHANUMERIC(*p)) {
14303 /* An alpha followed by '{' is going to fail next
14304 * iteration, so don't output this warning in that
14305 * case */
14306 if (! isALPHA(*p) || *(p + 1) != '{') {
14307 ckWARN2reg(p + 1, "Unrecognized escape \\%.1s"
14308 " passed through", p);
14309 }
14310 }
14311 goto normal_default;
14312 } /* End of switch on '\' */
14313 break;
14314 case '{':
14315 /* Trying to gain new uses for '{' without breaking too
14316 * much existing code is hard. The solution currently
14317 * adopted is:
14318 * 1) If there is no ambiguity that a '{' should always
14319 * be taken literally, at the start of a construct, we
14320 * just do so.
14321 * 2) If the literal '{' conflicts with our desired use
14322 * of it as a metacharacter, we die. The deprecation
14323 * cycles for this have come and gone.
14324 * 3) If there is ambiguity, we raise a simple warning.
14325 * This could happen, for example, if the user
14326 * intended it to introduce a quantifier, but slightly
14327 * misspelled the quantifier. Without this warning,
14328 * the quantifier would silently be taken as a literal
14329 * string of characters instead of a meta construct */
14330 if (len || (p > RExC_start && isALPHA_A(*(p - 1)))) {
14331 if ( RExC_strict
14332 || ( p > parse_start + 1
14333 && isALPHA_A(*(p - 1))
14334 && *(p - 2) == '\\')
14335 || new_regcurly(p, RExC_end))
14336 {
14337 RExC_parse = p + 1;
14338 vFAIL("Unescaped left brace in regex is "
14339 "illegal here");
14340 }
14341 ckWARNreg(p + 1, "Unescaped left brace in regex is"
14342 " passed through");
14343 }
14344 goto normal_default;
14345 case '}':
14346 case ']':
14347 if (p > RExC_parse && RExC_strict) {
14348 ckWARN2reg(p + 1, "Unescaped literal '%c'", *p);
14349 }
14350 /*FALLTHROUGH*/
14351 default: /* A literal character */
14352 normal_default:
14353 if (! UTF8_IS_INVARIANT(*p) && UTF) {
14354 STRLEN numlen;
14355 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
14356 &numlen, UTF8_ALLOW_DEFAULT);
14357 p += numlen;
14358 }
14359 else
14360 ender = (U8) *p++;
14361 break;
14362 } /* End of switch on the literal */
14363
14364 /* Here, have looked at the literal character, and <ender>
14365 * contains its ordinal; <p> points to the character after it.
14366 * */
14367
14368 if (ender > 255) {
14369 REQUIRE_UTF8(flagp);
14370 if ( UNICODE_IS_PERL_EXTENDED(ender)
14371 && TO_OUTPUT_WARNINGS(p))
14372 {
14373 ckWARN2_non_literal_string(p,
14374 packWARN(WARN_PORTABLE),
14375 PL_extended_cp_format,
14376 ender);
14377 }
14378 }
14379
14380 /* We need to check if the next non-ignored thing is a
14381 * quantifier. Move <p> to after anything that should be
14382 * ignored, which, as a side effect, positions <p> for the next
14383 * loop iteration */
14384 skip_to_be_ignored_text(pRExC_state, &p,
14385 FALSE /* Don't force to /x */ );
14386
14387 /* If the next thing is a quantifier, it applies to this
14388 * character only, which means that this character has to be in
14389 * its own node and can't just be appended to the string in an
14390 * existing node, so if there are already other characters in
14391 * the node, close the node with just them, and set up to do
14392 * this character again next time through, when it will be the
14393 * only thing in its new node */
14394
14395 next_is_quantifier = LIKELY(p < RExC_end)
14396 && UNLIKELY(ISMULT2(p));
14397
14398 if (next_is_quantifier && LIKELY(len)) {
14399 p = oldp;
14400 goto loopdone;
14401 }
14402
14403 /* Ready to add 'ender' to the node */
14404
14405 if (! FOLD) { /* The simple case, just append the literal */
14406 not_fold_common:
14407
14408 /* Don't output if it would overflow */
14409 if (UNLIKELY(len > max_string_len - ((UTF)
14410 ? UVCHR_SKIP(ender)
14411 : 1)))
14412 {
14413 overflowed = TRUE;
14414 break;
14415 }
14416
14417 if (UVCHR_IS_INVARIANT(ender) || ! UTF) {
14418 *(s++) = (char) ender;
14419 }
14420 else {
14421 U8 * new_s = uvchr_to_utf8((U8*)s, ender);
14422 added_len = (char *) new_s - s;
14423 s = (char *) new_s;
14424
14425 if (ender > 255) {
14426 requires_utf8_target = TRUE;
14427 }
14428 }
14429 }
14430 else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) {
14431
14432 /* Here are folding under /l, and the code point is
14433 * problematic. If this is the first character in the
14434 * node, change the node type to folding. Otherwise, if
14435 * this is the first problematic character, close up the
14436 * existing node, so can start a new node with this one */
14437 if (! len) {
14438 node_type = EXACTFL;
14439 RExC_contains_locale = 1;
14440 }
14441 else if (node_type == EXACT) {
14442 p = oldp;
14443 goto loopdone;
14444 }
14445
14446 /* This problematic code point means we can't simplify
14447 * things */
14448 maybe_exactfu = FALSE;
14449
14450 /* Here, we are adding a problematic fold character.
14451 * "Problematic" in this context means that its fold isn't
14452 * known until runtime. (The non-problematic code points
14453 * are the above-Latin1 ones that fold to also all
14454 * above-Latin1. Their folds don't vary no matter what the
14455 * locale is.) But here we have characters whose fold
14456 * depends on the locale. We just add in the unfolded
14457 * character, and wait until runtime to fold it */
14458 goto not_fold_common;
14459 }
14460 else /* regular fold; see if actually is in a fold */
14461 if ( (ender < 256 && ! IS_IN_SOME_FOLD_L1(ender))
14462 || (ender > 255
14463 && ! _invlist_contains_cp(PL_in_some_fold, ender)))
14464 {
14465 /* Here, folding, but the character isn't in a fold.
14466 *
14467 * Start a new node if previous characters in the node were
14468 * folded */
14469 if (len && node_type != EXACT) {
14470 p = oldp;
14471 goto loopdone;
14472 }
14473
14474 /* Here, continuing a node with non-folded characters. Add
14475 * this one */
14476 goto not_fold_common;
14477 }
14478 else { /* Here, does participate in some fold */
14479
14480 /* If this is the first character in the node, change its
14481 * type to folding. Otherwise, if this is the first
14482 * folding character in the node, close up the existing
14483 * node, so can start a new node with this one. */
14484 if (! len) {
14485 node_type = compute_EXACTish(pRExC_state);
14486 }
14487 else if (node_type == EXACT) {
14488 p = oldp;
14489 goto loopdone;
14490 }
14491
14492 if (UTF) { /* Alway use the folded value for UTF-8
14493 patterns */
14494 if (UVCHR_IS_INVARIANT(ender)) {
14495 if (UNLIKELY(len + 1 > max_string_len)) {
14496 overflowed = TRUE;
14497 break;
14498 }
14499
14500 *(s)++ = (U8) toFOLD(ender);
14501 }
14502 else {
14503 UV folded = _to_uni_fold_flags(
14504 ender,
14505 (U8 *) s, /* We have allocated extra space
14506 in 's' so can't run off the
14507 end */
14508 &added_len,
14509 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
14510 ? FOLD_FLAGS_NOMIX_ASCII
14511 : 0));
14512 if (UNLIKELY(len + added_len > max_string_len)) {
14513 overflowed = TRUE;
14514 break;
14515 }
14516
14517 s += added_len;
14518
14519 if ( folded > 255
14520 && LIKELY(folded != GREEK_SMALL_LETTER_MU))
14521 {
14522 /* U+B5 folds to the MU, so its possible for a
14523 * non-UTF-8 target to match it */
14524 requires_utf8_target = TRUE;
14525 }
14526 }
14527 }
14528 else { /* Here is non-UTF8. */
14529
14530 /* The fold will be one or (rarely) two characters.
14531 * Check that there's room for at least a single one
14532 * before setting any flags, etc. Because otherwise an
14533 * overflowing character could cause a flag to be set
14534 * even though it doesn't end up in this node. (For
14535 * the two character fold, we check again, before
14536 * setting any flags) */
14537 if (UNLIKELY(len + 1 > max_string_len)) {
14538 overflowed = TRUE;
14539 break;
14540 }
14541
14542#if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
14543 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
14544 || UNICODE_DOT_DOT_VERSION > 0)
14545
14546 /* On non-ancient Unicodes, check for the only possible
14547 * multi-char fold */
14548 if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) {
14549
14550 /* This potential multi-char fold means the node
14551 * can't be simple (because it could match more
14552 * than a single char). And in some cases it will
14553 * match 'ss', so set that flag */
14554 maybe_SIMPLE = 0;
14555 has_ss = TRUE;
14556
14557 /* It can't change to be an EXACTFU (unless already
14558 * is one). We fold it iff under /u rules. */
14559 if (node_type != EXACTFU) {
14560 maybe_exactfu = FALSE;
14561 }
14562 else {
14563 if (UNLIKELY(len + 2 > max_string_len)) {
14564 overflowed = TRUE;
14565 break;
14566 }
14567
14568 *(s++) = 's';
14569 *(s++) = 's';
14570 added_len = 2;
14571
14572 goto done_with_this_char;
14573 }
14574 }
14575 else if ( UNLIKELY(isALPHA_FOLD_EQ(ender, 's'))
14576 && LIKELY(len > 0)
14577 && UNLIKELY(isALPHA_FOLD_EQ(*(s-1), 's')))
14578 {
14579 /* Also, the sequence 'ss' is special when not
14580 * under /u. If the target string is UTF-8, it
14581 * should match SHARP S; otherwise it won't. So,
14582 * here we have to exclude the possibility of this
14583 * node moving to /u.*/
14584 has_ss = TRUE;
14585 maybe_exactfu = FALSE;
14586 }
14587#endif
14588 /* Here, the fold will be a single character */
14589
14590 if (UNLIKELY(ender == MICRO_SIGN)) {
14591 has_micro_sign = TRUE;
14592 }
14593 else if (PL_fold[ender] != PL_fold_latin1[ender]) {
14594
14595 /* If the character's fold differs between /d and
14596 * /u, this can't change to be an EXACTFU node */
14597 maybe_exactfu = FALSE;
14598 }
14599
14600 *(s++) = (DEPENDS_SEMANTICS)
14601 ? (char) toFOLD(ender)
14602
14603 /* Under /u, the fold of any character in
14604 * the 0-255 range happens to be its
14605 * lowercase equivalent, except for LATIN
14606 * SMALL LETTER SHARP S, which was handled
14607 * above, and the MICRO SIGN, whose fold
14608 * requires UTF-8 to represent. */
14609 : (char) toLOWER_L1(ender);
14610 }
14611 } /* End of adding current character to the node */
14612
14613 done_with_this_char:
14614
14615 len += added_len;
14616
14617 if (next_is_quantifier) {
14618
14619 /* Here, the next input is a quantifier, and to get here,
14620 * the current character is the only one in the node. */
14621 goto loopdone;
14622 }
14623
14624 } /* End of loop through literal characters */
14625
14626 /* Here we have either exhausted the input or run out of room in
14627 * the node. If the former, we are done. (If we encountered a
14628 * character that can't be in the node, transfer is made directly
14629 * to <loopdone>, and so we wouldn't have fallen off the end of the
14630 * loop.) */
14631 if (LIKELY(! overflowed)) {
14632 goto loopdone;
14633 }
14634
14635 /* Here we have run out of room. We can grow plain EXACT and
14636 * LEXACT nodes. If the pattern is gigantic enough, though,
14637 * eventually we'll have to artificially chunk the pattern into
14638 * multiple nodes. */
14639 if (! LOC && (node_type == EXACT || node_type == LEXACT)) {
14640 Size_t overhead = 1 + regarglen[OP(REGNODE_p(ret))];
14641 Size_t overhead_expansion = 0;
14642 char temp[256];
14643 Size_t max_nodes_for_string;
14644 Size_t achievable;
14645 SSize_t delta;
14646
14647 /* Here we couldn't fit the final character in the current
14648 * node, so it will have to be reparsed, no matter what else we
14649 * do */
14650 p = oldp;
14651
14652 /* If would have overflowed a regular EXACT node, switch
14653 * instead to an LEXACT. The code below is structured so that
14654 * the actual growing code is common to changing from an EXACT
14655 * or just increasing the LEXACT size. This means that we have
14656 * to save the string in the EXACT case before growing, and
14657 * then copy it afterwards to its new location */
14658 if (node_type == EXACT) {
14659 overhead_expansion = regarglen[LEXACT] - regarglen[EXACT];
14660 RExC_emit += overhead_expansion;
14661 Copy(s0, temp, len, char);
14662 }
14663
14664 /* Ready to grow. If it was a plain EXACT, the string was
14665 * saved, and the first few bytes of it overwritten by adding
14666 * an argument field. We assume, as we do elsewhere in this
14667 * file, that one byte of remaining input will translate into
14668 * one byte of output, and if that's too small, we grow again,
14669 * if too large the excess memory is freed at the end */
14670
14671 max_nodes_for_string = U16_MAX - overhead - overhead_expansion;
14672 achievable = MIN(max_nodes_for_string,
14673 current_string_nodes + STR_SZ(RExC_end - p));
14674 delta = achievable - current_string_nodes;
14675
14676 /* If there is just no more room, go finish up this chunk of
14677 * the pattern. */
14678 if (delta <= 0) {
14679 goto loopdone;
14680 }
14681
14682 change_engine_size(pRExC_state, delta + overhead_expansion);
14683 current_string_nodes += delta;
14684 max_string_len
14685 = sizeof(struct regnode) * current_string_nodes;
14686 upper_fill = max_string_len + 1;
14687
14688 /* If the length was small, we know this was originally an
14689 * EXACT node now converted to LEXACT, and the string has to be
14690 * restored. Otherwise the string was untouched. 260 is just
14691 * a number safely above 255 so don't have to worry about
14692 * getting it precise */
14693 if (len < 260) {
14694 node_type = LEXACT;
14695 FILL_NODE(ret, node_type);
14696 s0 = STRING(REGNODE_p(ret));
14697 Copy(temp, s0, len, char);
14698 s = s0 + len;
14699 }
14700
14701 goto continue_parse;
14702 }
14703 else if (FOLD) {
14704 bool splittable = FALSE;
14705 bool backed_up = FALSE;
14706 char * e; /* should this be U8? */
14707 char * s_start; /* should this be U8? */
14708
14709 /* Here is /i. Running out of room creates a problem if we are
14710 * folding, and the split happens in the middle of a
14711 * multi-character fold, as a match that should have occurred,
14712 * won't, due to the way nodes are matched, and our artificial
14713 * boundary. So back off until we aren't splitting such a
14714 * fold. If there is no such place to back off to, we end up
14715 * taking the entire node as-is. This can happen if the node
14716 * consists entirely of 'f' or entirely of 's' characters (or
14717 * things that fold to them) as 'ff' and 'ss' are
14718 * multi-character folds.
14719 *
14720 * The Unicode standard says that multi character folds consist
14721 * of either two or three characters. That means we would be
14722 * splitting one if the final character in the node is at the
14723 * beginning of either type, or is the second of a three
14724 * character fold.
14725 *
14726 * At this point:
14727 * ender is the code point of the character that won't fit
14728 * in the node
14729 * s points to just beyond the final byte in the node.
14730 * It's where we would place ender if there were
14731 * room, and where in fact we do place ender's fold
14732 * in the code below, as we've over-allocated space
14733 * for s0 (hence s) to allow for this
14734 * e starts at 's' and advances as we append things.
14735 * old_s is the same as 's'. (If ender had fit, 's' would
14736 * have been advanced to beyond it).
14737 * old_old_s points to the beginning byte of the final
14738 * character in the node
14739 * p points to the beginning byte in the input of the
14740 * character beyond 'ender'.
14741 * oldp points to the beginning byte in the input of
14742 * 'ender'.
14743 *
14744 * In the case of /il, we haven't folded anything that could be
14745 * affected by the locale. That means only above-Latin1
14746 * characters that fold to other above-latin1 characters get
14747 * folded at compile time. To check where a good place to
14748 * split nodes is, everything in it will have to be folded.
14749 * The boolean 'maybe_exactfu' keeps track in /il if there are
14750 * any unfolded characters in the node. */
14751 bool need_to_fold_loc = LOC && ! maybe_exactfu;
14752
14753 /* If we do need to fold the node, we need a place to store the
14754 * folded copy, and a way to map back to the unfolded original
14755 * */
14756 char * locfold_buf = NULL;
14757 Size_t * loc_correspondence = NULL;
14758
14759 if (! need_to_fold_loc) { /* The normal case. Just
14760 initialize to the actual node */
14761 e = s;
14762 s_start = s0;
14763 s = old_old_s; /* Point to the beginning of the final char
14764 that fits in the node */
14765 }
14766 else {
14767
14768 /* Here, we have filled a /il node, and there are unfolded
14769 * characters in it. If the runtime locale turns out to be
14770 * UTF-8, there are possible multi-character folds, just
14771 * like when not under /l. The node hence can't terminate
14772 * in the middle of such a fold. To determine this, we
14773 * have to create a folded copy of this node. That means
14774 * reparsing the node, folding everything assuming a UTF-8
14775 * locale. (If at runtime it isn't such a locale, the
14776 * actions here wouldn't have been necessary, but we have
14777 * to assume the worst case.) If we find we need to back
14778 * off the folded string, we do so, and then map that
14779 * position back to the original unfolded node, which then
14780 * gets output, truncated at that spot */
14781
14782 char * redo_p = RExC_parse;
14783 char * redo_e;
14784 char * old_redo_e;
14785
14786 /* Allow enough space assuming a single byte input folds to
14787 * a single byte output, plus assume that the two unparsed
14788 * characters (that we may need) fold to the largest number
14789 * of bytes possible, plus extra for one more worst case
14790 * scenario. In the loop below, if we start eating into
14791 * that final spare space, we enlarge this initial space */
14792 Size_t size = max_string_len + (3 * UTF8_MAXBYTES_CASE) + 1;
14793
14794 Newxz(locfold_buf, size, char);
14795 Newxz(loc_correspondence, size, Size_t);
14796
14797 /* Redo this node's parse, folding into 'locfold_buf' */
14798 redo_p = RExC_parse;
14799 old_redo_e = redo_e = locfold_buf;
14800 while (redo_p <= oldp) {
14801
14802 old_redo_e = redo_e;
14803 loc_correspondence[redo_e - locfold_buf]
14804 = redo_p - RExC_parse;
14805
14806 if (UTF) {
14807 Size_t added_len;
14808
14809 (void) _to_utf8_fold_flags((U8 *) redo_p,
14810 (U8 *) RExC_end,
14811 (U8 *) redo_e,
14812 &added_len,
14813 FOLD_FLAGS_FULL);
14814 redo_e += added_len;
14815 redo_p += UTF8SKIP(redo_p);
14816 }
14817 else {
14818
14819 /* Note that if this code is run on some ancient
14820 * Unicode versions, SHARP S doesn't fold to 'ss',
14821 * but rather than clutter the code with #ifdef's,
14822 * as is done above, we ignore that possibility.
14823 * This is ok because this code doesn't affect what
14824 * gets matched, but merely where the node gets
14825 * split */
14826 if (UCHARAT(redo_p) != LATIN_SMALL_LETTER_SHARP_S) {
14827 *redo_e++ = toLOWER_L1(UCHARAT(redo_p));
14828 }
14829 else {
14830 *redo_e++ = 's';
14831 *redo_e++ = 's';
14832 }
14833 redo_p++;
14834 }
14835
14836
14837 /* If we're getting so close to the end that a
14838 * worst-case fold in the next character would cause us
14839 * to overflow, increase, assuming one byte output byte
14840 * per one byte input one, plus room for another worst
14841 * case fold */
14842 if ( redo_p <= oldp
14843 && redo_e > locfold_buf + size
14844 - (UTF8_MAXBYTES_CASE + 1))
14845 {
14846 Size_t new_size = size
14847 + (oldp - redo_p)
14848 + UTF8_MAXBYTES_CASE + 1;
14849 Ptrdiff_t e_offset = redo_e - locfold_buf;
14850
14851 Renew(locfold_buf, new_size, char);
14852 Renew(loc_correspondence, new_size, Size_t);
14853 size = new_size;
14854
14855 redo_e = locfold_buf + e_offset;
14856 }
14857 }
14858
14859 /* Set so that things are in terms of the folded, temporary
14860 * string */
14861 s = old_redo_e;
14862 s_start = locfold_buf;
14863 e = redo_e;
14864
14865 }
14866
14867 /* Here, we have 's', 's_start' and 'e' set up to point to the
14868 * input that goes into the node, folded.
14869 *
14870 * If the final character of the node and the fold of ender
14871 * form the first two characters of a three character fold, we
14872 * need to peek ahead at the next (unparsed) character in the
14873 * input to determine if the three actually do form such a
14874 * fold. Just looking at that character is not generally
14875 * sufficient, as it could be, for example, an escape sequence
14876 * that evaluates to something else, and it needs to be folded.
14877 *
14878 * khw originally thought to just go through the parse loop one
14879 * extra time, but that doesn't work easily as that iteration
14880 * could cause things to think that the parse is over and to
14881 * goto loopdone. The character could be a '$' for example, or
14882 * the character beyond could be a quantifier, and other
14883 * glitches as well.
14884 *
14885 * The solution used here for peeking ahead is to look at that
14886 * next character. If it isn't ASCII punctuation, then it will
14887 * be something that continues in an EXACTish node if there
14888 * were space. We append the fold of it to s, having reserved
14889 * enough room in s0 for the purpose. If we can't reasonably
14890 * peek ahead, we instead assume the worst case: that it is
14891 * something that would form the completion of a multi-char
14892 * fold.
14893 *
14894 * If we can't split between s and ender, we work backwards
14895 * character-by-character down to s0. At each current point
14896 * see if we are at the beginning of a multi-char fold. If so,
14897 * that means we would be splitting the fold across nodes, and
14898 * so we back up one and try again.
14899 *
14900 * If we're not at the beginning, we still could be at the
14901 * final two characters of a (rare) three character fold. We
14902 * check if the sequence starting at the character before the
14903 * current position (and including the current and next
14904 * characters) is a three character fold. If not, the node can
14905 * be split here. If it is, we have to backup two characters
14906 * and try again.
14907 *
14908 * Otherwise, the node can be split at the current position.
14909 *
14910 * The same logic is used for UTF-8 patterns and not */
14911 if (UTF) {
14912 Size_t added_len;
14913
14914 /* Append the fold of ender */
14915 (void) _to_uni_fold_flags(
14916 ender,
14917 (U8 *) e,
14918 &added_len,
14919 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
14920 ? FOLD_FLAGS_NOMIX_ASCII
14921 : 0));
14922 e += added_len;
14923
14924 /* 's' and the character folded to by ender may be the
14925 * first two of a three-character fold, in which case the
14926 * node should not be split here. That may mean examining
14927 * the so-far unparsed character starting at 'p'. But if
14928 * ender folded to more than one character, we already have
14929 * three characters to look at. Also, we first check if
14930 * the sequence consisting of s and the next character form
14931 * the first two of some three character fold. If not,
14932 * there's no need to peek ahead. */
14933 if ( added_len <= UTF8SKIP(e - added_len)
14934 && UNLIKELY(is_THREE_CHAR_FOLD_HEAD_utf8_safe(s, e)))
14935 {
14936 /* Here, the two do form the beginning of a potential
14937 * three character fold. The unexamined character may
14938 * or may not complete it. Peek at it. It might be
14939 * something that ends the node or an escape sequence,
14940 * in which case we don't know without a lot of work
14941 * what it evaluates to, so we have to assume the worst
14942 * case: that it does complete the fold, and so we
14943 * can't split here. All such instances will have
14944 * that character be an ASCII punctuation character,
14945 * like a backslash. So, for that case, backup one and
14946 * drop down to try at that position */
14947 if (isPUNCT(*p)) {
14948 s = (char *) utf8_hop_back((U8 *) s, -1,
14949 (U8 *) s_start);
14950 backed_up = TRUE;
14951 }
14952 else {
14953 /* Here, since it's not punctuation, it must be a
14954 * real character, and we can append its fold to
14955 * 'e' (having deliberately reserved enough space
14956 * for this eventuality) and drop down to check if
14957 * the three actually do form a folded sequence */
14958 (void) _to_utf8_fold_flags(
14959 (U8 *) p, (U8 *) RExC_end,
14960 (U8 *) e,
14961 &added_len,
14962 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
14963 ? FOLD_FLAGS_NOMIX_ASCII
14964 : 0));
14965 e += added_len;
14966 }
14967 }
14968
14969 /* Here, we either have three characters available in
14970 * sequence starting at 's', or we have two characters and
14971 * know that the following one can't possibly be part of a
14972 * three character fold. We go through the node backwards
14973 * until we find a place where we can split it without
14974 * breaking apart a multi-character fold. At any given
14975 * point we have to worry about if such a fold begins at
14976 * the current 's', and also if a three-character fold
14977 * begins at s-1, (containing s and s+1). Splitting in
14978 * either case would break apart a fold */
14979 do {
14980 char *prev_s = (char *) utf8_hop_back((U8 *) s, -1,
14981 (U8 *) s_start);
14982
14983 /* If is a multi-char fold, can't split here. Backup
14984 * one char and try again */
14985 if (UNLIKELY(is_MULTI_CHAR_FOLD_utf8_safe(s, e))) {
14986 s = prev_s;
14987 backed_up = TRUE;
14988 continue;
14989 }
14990
14991 /* If the two characters beginning at 's' are part of a
14992 * three character fold starting at the character
14993 * before s, we can't split either before or after s.
14994 * Backup two chars and try again */
14995 if ( LIKELY(s > s_start)
14996 && UNLIKELY(is_THREE_CHAR_FOLD_utf8_safe(prev_s, e)))
14997 {
14998 s = prev_s;
14999 s = (char *) utf8_hop_back((U8 *) s, -1, (U8 *) s_start);
15000 backed_up = TRUE;
15001 continue;
15002 }
15003
15004 /* Here there's no multi-char fold between s and the
15005 * next character following it. We can split */
15006 splittable = TRUE;
15007 break;
15008
15009 } while (s > s_start); /* End of loops backing up through the node */
15010
15011 /* Here we either couldn't find a place to split the node,
15012 * or else we broke out of the loop setting 'splittable' to
15013 * true. In the latter case, the place to split is between
15014 * the first and second characters in the sequence starting
15015 * at 's' */
15016 if (splittable) {
15017 s += UTF8SKIP(s);
15018 }
15019 }
15020 else { /* Pattern not UTF-8 */
15021 if ( ender != LATIN_SMALL_LETTER_SHARP_S
15022 || ASCII_FOLD_RESTRICTED)
15023 {
15024 assert( toLOWER_L1(ender) < 256 );
15025 *e++ = (char)(toLOWER_L1(ender)); /* should e and the cast be U8? */
15026 }
15027 else {
15028 *e++ = 's';
15029 *e++ = 's';
15030 }
15031
15032 if ( e - s <= 1
15033 && UNLIKELY(is_THREE_CHAR_FOLD_HEAD_latin1_safe(s, e)))
15034 {
15035 if (isPUNCT(*p)) {
15036 s--;
15037 backed_up = TRUE;
15038 }
15039 else {
15040 if ( UCHARAT(p) != LATIN_SMALL_LETTER_SHARP_S
15041 || ASCII_FOLD_RESTRICTED)
15042 {
15043 assert( toLOWER_L1(ender) < 256 );
15044 *e++ = (char)(toLOWER_L1(ender)); /* should e and the cast be U8? */
15045 }
15046 else {
15047 *e++ = 's';
15048 *e++ = 's';
15049 }
15050 }
15051 }
15052
15053 do {
15054 if (UNLIKELY(is_MULTI_CHAR_FOLD_latin1_safe(s, e))) {
15055 s--;
15056 backed_up = TRUE;
15057 continue;
15058 }
15059
15060 if ( LIKELY(s > s_start)
15061 && UNLIKELY(is_THREE_CHAR_FOLD_latin1_safe(s - 1, e)))
15062 {
15063 s -= 2;
15064 backed_up = TRUE;
15065 continue;
15066 }
15067
15068 splittable = TRUE;
15069 break;
15070
15071 } while (s > s_start);
15072
15073 if (splittable) {
15074 s++;
15075 }
15076 }
15077
15078 /* Here, we are done backing up. If we didn't backup at all
15079 * (the likely case), just proceed */
15080 if (backed_up) {
15081
15082 /* If we did find a place to split, reparse the entire node
15083 * stopping where we have calculated. */
15084 if (splittable) {
15085
15086 /* If we created a temporary folded string under /l, we
15087 * have to map that back to the original */
15088 if (need_to_fold_loc) {
15089 upper_fill = loc_correspondence[s - s_start];
15090 Safefree(locfold_buf);
15091 Safefree(loc_correspondence);
15092
15093 if (upper_fill == 0) {
15094 FAIL2("panic: loc_correspondence[%d] is 0",
15095 (int) (s - s_start));
15096 }
15097 }
15098 else {
15099 upper_fill = s - s0;
15100 }
15101 goto reparse;
15102 }
15103 else if (need_to_fold_loc) {
15104 Safefree(locfold_buf);
15105 Safefree(loc_correspondence);
15106 }
15107
15108 /* Here the node consists entirely of non-final multi-char
15109 * folds. (Likely it is all 'f's or all 's's.) There's no
15110 * decent place to split it, so give up and just take the
15111 * whole thing */
15112 len = old_s - s0;
15113 }
15114 } /* End of verifying node ends with an appropriate char */
15115
15116 /* We need to start the next node at the character that didn't fit
15117 * in this one */
15118 p = oldp;
15119
15120 loopdone: /* Jumped to when encounters something that shouldn't be
15121 in the node */
15122
15123 /* Free up any over-allocated space; cast is to silence bogus
15124 * warning in MS VC */
15125 change_engine_size(pRExC_state,
15126 - (Ptrdiff_t) (current_string_nodes - STR_SZ(len)));
15127
15128 /* I (khw) don't know if you can get here with zero length, but the
15129 * old code handled this situation by creating a zero-length EXACT
15130 * node. Might as well be NOTHING instead */
15131 if (len == 0) {
15132 OP(REGNODE_p(ret)) = NOTHING;
15133 }
15134 else {
15135
15136 /* If the node type is EXACT here, check to see if it
15137 * should be EXACTL, or EXACT_REQ8. */
15138 if (node_type == EXACT) {
15139 if (LOC) {
15140 node_type = EXACTL;
15141 }
15142 else if (requires_utf8_target) {
15143 node_type = EXACT_REQ8;
15144 }
15145 }
15146 else if (node_type == LEXACT) {
15147 if (requires_utf8_target) {
15148 node_type = LEXACT_REQ8;
15149 }
15150 }
15151 else if (FOLD) {
15152 if ( UNLIKELY(has_micro_sign || has_ss)
15153 && (node_type == EXACTFU || ( node_type == EXACTF
15154 && maybe_exactfu)))
15155 { /* These two conditions are problematic in non-UTF-8
15156 EXACTFU nodes. */
15157 assert(! UTF);
15158 node_type = EXACTFUP;
15159 }
15160 else if (node_type == EXACTFL) {
15161
15162 /* 'maybe_exactfu' is deliberately set above to
15163 * indicate this node type, where all code points in it
15164 * are above 255 */
15165 if (maybe_exactfu) {
15166 node_type = EXACTFLU8;
15167 }
15168 else if (UNLIKELY(
15169 _invlist_contains_cp(PL_HasMultiCharFold, ender)))
15170 {
15171 /* A character that folds to more than one will
15172 * match multiple characters, so can't be SIMPLE.
15173 * We don't have to worry about this with EXACTFLU8
15174 * nodes just above, as they have already been
15175 * folded (since the fold doesn't vary at run
15176 * time). Here, if the final character in the node
15177 * folds to multiple, it can't be simple. (This
15178 * only has an effect if the node has only a single
15179 * character, hence the final one, as elsewhere we
15180 * turn off simple for nodes whose length > 1 */
15181 maybe_SIMPLE = 0;
15182 }
15183 }
15184 else if (node_type == EXACTF) { /* Means is /di */
15185
15186 /* This intermediate variable is needed solely because
15187 * the asserts in the macro where used exceed Win32's
15188 * literal string capacity */
15189 char first_char = * STRING(REGNODE_p(ret));
15190
15191 /* If 'maybe_exactfu' is clear, then we need to stay
15192 * /di. If it is set, it means there are no code
15193 * points that match differently depending on UTF8ness
15194 * of the target string, so it can become an EXACTFU
15195 * node */
15196 if (! maybe_exactfu) {
15197 RExC_seen_d_op = TRUE;
15198 }
15199 else if ( isALPHA_FOLD_EQ(first_char, 's')
15200 || isALPHA_FOLD_EQ(ender, 's'))
15201 {
15202 /* But, if the node begins or ends in an 's' we
15203 * have to defer changing it into an EXACTFU, as
15204 * the node could later get joined with another one
15205 * that ends or begins with 's' creating an 'ss'
15206 * sequence which would then wrongly match the
15207 * sharp s without the target being UTF-8. We
15208 * create a special node that we resolve later when
15209 * we join nodes together */
15210
15211 node_type = EXACTFU_S_EDGE;
15212 }
15213 else {
15214 node_type = EXACTFU;
15215 }
15216 }
15217
15218 if (requires_utf8_target && node_type == EXACTFU) {
15219 node_type = EXACTFU_REQ8;
15220 }
15221 }
15222
15223 OP(REGNODE_p(ret)) = node_type;
15224 setSTR_LEN(REGNODE_p(ret), len);
15225 RExC_emit += STR_SZ(len);
15226
15227 /* If the node isn't a single character, it can't be SIMPLE */
15228 if (len > (Size_t) ((UTF) ? UTF8SKIP(STRING(REGNODE_p(ret))) : 1)) {
15229 maybe_SIMPLE = 0;
15230 }
15231
15232 *flagp |= HASWIDTH | maybe_SIMPLE;
15233 }
15234
15235 Set_Node_Length(REGNODE_p(ret), p - parse_start - 1);
15236 RExC_parse = p;
15237
15238 {
15239 /* len is STRLEN which is unsigned, need to copy to signed */
15240 IV iv = len;
15241 if (iv < 0)
15242 vFAIL("Internal disaster");
15243 }
15244
15245 } /* End of label 'defchar:' */
15246 break;
15247 } /* End of giant switch on input character */
15248
15249 /* Position parse to next real character */
15250 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
15251 FALSE /* Don't force to /x */ );
15252 if ( *RExC_parse == '{'
15253 && OP(REGNODE_p(ret)) != SBOL && ! regcurly(RExC_parse))
15254 {
15255 if (RExC_strict || new_regcurly(RExC_parse, RExC_end)) {
15256 RExC_parse++;
15257 vFAIL("Unescaped left brace in regex is illegal here");
15258 }
15259 ckWARNreg(RExC_parse + 1, "Unescaped left brace in regex is"
15260 " passed through");
15261 }
15262
15263 return(ret);
15264}
15265
15266
15267STATIC void
15268S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr)
15269{
15270 /* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'. It
15271 * sets up the bitmap and any flags, removing those code points from the
15272 * inversion list, setting it to NULL should it become completely empty */
15273
15274 dVAR;
15275
15276 PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST;
15277 assert(PL_regkind[OP(node)] == ANYOF);
15278
15279 /* There is no bitmap for this node type */
15280 if (inRANGE(OP(node), ANYOFH, ANYOFRb)) {
15281 return;
15282 }
15283
15284 ANYOF_BITMAP_ZERO(node);
15285 if (*invlist_ptr) {
15286
15287 /* This gets set if we actually need to modify things */
15288 bool change_invlist = FALSE;
15289
15290 UV start, end;
15291
15292 /* Start looking through *invlist_ptr */
15293 invlist_iterinit(*invlist_ptr);
15294 while (invlist_iternext(*invlist_ptr, &start, &end)) {
15295 UV high;
15296 int i;
15297
15298 if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) {
15299 ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP;
15300 }
15301
15302 /* Quit if are above what we should change */
15303 if (start >= NUM_ANYOF_CODE_POINTS) {
15304 break;
15305 }
15306
15307 change_invlist = TRUE;
15308
15309 /* Set all the bits in the range, up to the max that we are doing */
15310 high = (end < NUM_ANYOF_CODE_POINTS - 1)
15311 ? end
15312 : NUM_ANYOF_CODE_POINTS - 1;
15313 for (i = start; i <= (int) high; i++) {
15314 if (! ANYOF_BITMAP_TEST(node, i)) {
15315 ANYOF_BITMAP_SET(node, i);
15316 }
15317 }
15318 }
15319 invlist_iterfinish(*invlist_ptr);
15320
15321 /* Done with loop; remove any code points that are in the bitmap from
15322 * *invlist_ptr; similarly for code points above the bitmap if we have
15323 * a flag to match all of them anyways */
15324 if (change_invlist) {
15325 _invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr);
15326 }
15327 if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
15328 _invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr);
15329 }
15330
15331 /* If have completely emptied it, remove it completely */
15332 if (_invlist_len(*invlist_ptr) == 0) {
15333 SvREFCNT_dec_NN(*invlist_ptr);
15334 *invlist_ptr = NULL;
15335 }
15336 }
15337}
15338
15339/* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
15340 Character classes ([:foo:]) can also be negated ([:^foo:]).
15341 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
15342 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
15343 but trigger failures because they are currently unimplemented. */
15344
15345#define POSIXCC_DONE(c) ((c) == ':')
15346#define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
15347#define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
15348#define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';')
15349
15350#define WARNING_PREFIX "Assuming NOT a POSIX class since "
15351#define NO_BLANKS_POSIX_WARNING "no blanks are allowed in one"
15352#define SEMI_COLON_POSIX_WARNING "a semi-colon was found instead of a colon"
15353
15354#define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1)
15355
15356/* 'posix_warnings' and 'warn_text' are names of variables in the following
15357 * routine. q.v. */
15358#define ADD_POSIX_WARNING(p, text) STMT_START { \
15359 if (posix_warnings) { \
15360 if (! RExC_warn_text ) RExC_warn_text = \
15361 (AV *) sv_2mortal((SV *) newAV()); \
15362 av_push(RExC_warn_text, Perl_newSVpvf(aTHX_ \
15363 WARNING_PREFIX \
15364 text \
15365 REPORT_LOCATION, \
15366 REPORT_LOCATION_ARGS(p))); \
15367 } \
15368 } STMT_END
15369#define CLEAR_POSIX_WARNINGS() \
15370 STMT_START { \
15371 if (posix_warnings && RExC_warn_text) \
15372 av_clear(RExC_warn_text); \
15373 } STMT_END
15374
15375#define CLEAR_POSIX_WARNINGS_AND_RETURN(ret) \
15376 STMT_START { \
15377 CLEAR_POSIX_WARNINGS(); \
15378 return ret; \
15379 } STMT_END
15380
15381STATIC int
15382S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state,
15383
15384 const char * const s, /* Where the putative posix class begins.
15385 Normally, this is one past the '['. This
15386 parameter exists so it can be somewhere
15387 besides RExC_parse. */
15388 char ** updated_parse_ptr, /* Where to set the updated parse pointer, or
15389 NULL */
15390 AV ** posix_warnings, /* Where to place any generated warnings, or
15391 NULL */
15392 const bool check_only /* Don't die if error */
15393)
15394{
15395 /* This parses what the caller thinks may be one of the three POSIX
15396 * constructs:
15397 * 1) a character class, like [:blank:]
15398 * 2) a collating symbol, like [. .]
15399 * 3) an equivalence class, like [= =]
15400 * In the latter two cases, it croaks if it finds a syntactically legal
15401 * one, as these are not handled by Perl.
15402 *
15403 * The main purpose is to look for a POSIX character class. It returns:
15404 * a) the class number
15405 * if it is a completely syntactically and semantically legal class.
15406 * 'updated_parse_ptr', if not NULL, is set to point to just after the
15407 * closing ']' of the class
15408 * b) OOB_NAMEDCLASS
15409 * if it appears that one of the three POSIX constructs was meant, but
15410 * its specification was somehow defective. 'updated_parse_ptr', if
15411 * not NULL, is set to point to the character just after the end
15412 * character of the class. See below for handling of warnings.
15413 * c) NOT_MEANT_TO_BE_A_POSIX_CLASS
15414 * if it doesn't appear that a POSIX construct was intended.
15415 * 'updated_parse_ptr' is not changed. No warnings nor errors are
15416 * raised.
15417 *
15418 * In b) there may be errors or warnings generated. If 'check_only' is
15419 * TRUE, then any errors are discarded. Warnings are returned to the
15420 * caller via an AV* created into '*posix_warnings' if it is not NULL. If
15421 * instead it is NULL, warnings are suppressed.
15422 *
15423 * The reason for this function, and its complexity is that a bracketed
15424 * character class can contain just about anything. But it's easy to
15425 * mistype the very specific posix class syntax but yielding a valid
15426 * regular bracketed class, so it silently gets compiled into something
15427 * quite unintended.
15428 *
15429 * The solution adopted here maintains backward compatibility except that
15430 * it adds a warning if it looks like a posix class was intended but
15431 * improperly specified. The warning is not raised unless what is input
15432 * very closely resembles one of the 14 legal posix classes. To do this,
15433 * it uses fuzzy parsing. It calculates how many single-character edits it
15434 * would take to transform what was input into a legal posix class. Only
15435 * if that number is quite small does it think that the intention was a
15436 * posix class. Obviously these are heuristics, and there will be cases
15437 * where it errs on one side or another, and they can be tweaked as
15438 * experience informs.
15439 *
15440 * The syntax for a legal posix class is:
15441 *
15442 * qr/(?xa: \[ : \^? [[:lower:]]{4,6} : \] )/
15443 *
15444 * What this routine considers syntactically to be an intended posix class
15445 * is this (the comments indicate some restrictions that the pattern
15446 * doesn't show):
15447 *
15448 * qr/(?x: \[? # The left bracket, possibly
15449 * # omitted
15450 * \h* # possibly followed by blanks
15451 * (?: \^ \h* )? # possibly a misplaced caret
15452 * [:;]? # The opening class character,
15453 * # possibly omitted. A typo
15454 * # semi-colon can also be used.
15455 * \h*
15456 * \^? # possibly a correctly placed
15457 * # caret, but not if there was also
15458 * # a misplaced one
15459 * \h*
15460 * .{3,15} # The class name. If there are
15461 * # deviations from the legal syntax,
15462 * # its edit distance must be close
15463 * # to a real class name in order
15464 * # for it to be considered to be
15465 * # an intended posix class.
15466 * \h*
15467 * [[:punct:]]? # The closing class character,
15468 * # possibly omitted. If not a colon
15469 * # nor semi colon, the class name
15470 * # must be even closer to a valid
15471 * # one
15472 * \h*
15473 * \]? # The right bracket, possibly
15474 * # omitted.
15475 * )/
15476 *
15477 * In the above, \h must be ASCII-only.
15478 *
15479 * These are heuristics, and can be tweaked as field experience dictates.
15480 * There will be cases when someone didn't intend to specify a posix class
15481 * that this warns as being so. The goal is to minimize these, while
15482 * maximizing the catching of things intended to be a posix class that
15483 * aren't parsed as such.
15484 */
15485
15486 const char* p = s;
15487 const char * const e = RExC_end;
15488 unsigned complement = 0; /* If to complement the class */
15489 bool found_problem = FALSE; /* Assume OK until proven otherwise */
15490 bool has_opening_bracket = FALSE;
15491 bool has_opening_colon = FALSE;
15492 int class_number = OOB_NAMEDCLASS; /* Out-of-bounds until find
15493 valid class */
15494 const char * possible_end = NULL; /* used for a 2nd parse pass */
15495 const char* name_start; /* ptr to class name first char */
15496
15497 /* If the number of single-character typos the input name is away from a
15498 * legal name is no more than this number, it is considered to have meant
15499 * the legal name */
15500 int max_distance = 2;
15501
15502 /* to store the name. The size determines the maximum length before we
15503 * decide that no posix class was intended. Should be at least
15504 * sizeof("alphanumeric") */
15505 UV input_text[15];
15506 STATIC_ASSERT_DECL(C_ARRAY_LENGTH(input_text) >= sizeof "alphanumeric");
15507
15508 PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX;
15509
15510 CLEAR_POSIX_WARNINGS();
15511
15512 if (p >= e) {
15513 return NOT_MEANT_TO_BE_A_POSIX_CLASS;
15514 }
15515
15516 if (*(p - 1) != '[') {
15517 ADD_POSIX_WARNING(p, "it doesn't start with a '['");
15518 found_problem = TRUE;
15519 }
15520 else {
15521 has_opening_bracket = TRUE;
15522 }
15523
15524 /* They could be confused and think you can put spaces between the
15525 * components */
15526 if (isBLANK(*p)) {
15527 found_problem = TRUE;
15528
15529 do {
15530 p++;
15531 } while (p < e && isBLANK(*p));
15532
15533 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15534 }
15535
15536 /* For [. .] and [= =]. These are quite different internally from [: :],
15537 * so they are handled separately. */
15538 if (POSIXCC_NOTYET(*p) && p < e - 3) /* 1 for the close, and 1 for the ']'
15539 and 1 for at least one char in it
15540 */
15541 {
15542 const char open_char = *p;
15543 const char * temp_ptr = p + 1;
15544
15545 /* These two constructs are not handled by perl, and if we find a
15546 * syntactically valid one, we croak. khw, who wrote this code, finds
15547 * this explanation of them very unclear:
15548 * http://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html
15549 * And searching the rest of the internet wasn't very helpful either.
15550 * It looks like just about any byte can be in these constructs,
15551 * depending on the locale. But unless the pattern is being compiled
15552 * under /l, which is very rare, Perl runs under the C or POSIX locale.
15553 * In that case, it looks like [= =] isn't allowed at all, and that
15554 * [. .] could be any single code point, but for longer strings the
15555 * constituent characters would have to be the ASCII alphabetics plus
15556 * the minus-hyphen. Any sensible locale definition would limit itself
15557 * to these. And any portable one definitely should. Trying to parse
15558 * the general case is a nightmare (see [perl #127604]). So, this code
15559 * looks only for interiors of these constructs that match:
15560 * qr/.|[-\w]{2,}/
15561 * Using \w relaxes the apparent rules a little, without adding much
15562 * danger of mistaking something else for one of these constructs.
15563 *
15564 * [. .] in some implementations described on the internet is usable to
15565 * escape a character that otherwise is special in bracketed character
15566 * classes. For example [.].] means a literal right bracket instead of
15567 * the ending of the class
15568 *
15569 * [= =] can legitimately contain a [. .] construct, but we don't
15570 * handle this case, as that [. .] construct will later get parsed
15571 * itself and croak then. And [= =] is checked for even when not under
15572 * /l, as Perl has long done so.
15573 *
15574 * The code below relies on there being a trailing NUL, so it doesn't
15575 * have to keep checking if the parse ptr < e.
15576 */
15577 if (temp_ptr[1] == open_char) {
15578 temp_ptr++;
15579 }
15580 else while ( temp_ptr < e
15581 && (isWORDCHAR(*temp_ptr) || *temp_ptr == '-'))
15582 {
15583 temp_ptr++;
15584 }
15585
15586 if (*temp_ptr == open_char) {
15587 temp_ptr++;
15588 if (*temp_ptr == ']') {
15589 temp_ptr++;
15590 if (! found_problem && ! check_only) {
15591 RExC_parse = (char *) temp_ptr;
15592 vFAIL3("POSIX syntax [%c %c] is reserved for future "
15593 "extensions", open_char, open_char);
15594 }
15595
15596 /* Here, the syntax wasn't completely valid, or else the call
15597 * is to check-only */
15598 if (updated_parse_ptr) {
15599 *updated_parse_ptr = (char *) temp_ptr;
15600 }
15601
15602 CLEAR_POSIX_WARNINGS_AND_RETURN(OOB_NAMEDCLASS);
15603 }
15604 }
15605
15606 /* If we find something that started out to look like one of these
15607 * constructs, but isn't, we continue below so that it can be checked
15608 * for being a class name with a typo of '.' or '=' instead of a colon.
15609 * */
15610 }
15611
15612 /* Here, we think there is a possibility that a [: :] class was meant, and
15613 * we have the first real character. It could be they think the '^' comes
15614 * first */
15615 if (*p == '^') {
15616 found_problem = TRUE;
15617 ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon");
15618 complement = 1;
15619 p++;
15620
15621 if (isBLANK(*p)) {
15622 found_problem = TRUE;
15623
15624 do {
15625 p++;
15626 } while (p < e && isBLANK(*p));
15627
15628 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15629 }
15630 }
15631
15632 /* But the first character should be a colon, which they could have easily
15633 * mistyped on a qwerty keyboard as a semi-colon (and which may be hard to
15634 * distinguish from a colon, so treat that as a colon). */
15635 if (*p == ':') {
15636 p++;
15637 has_opening_colon = TRUE;
15638 }
15639 else if (*p == ';') {
15640 found_problem = TRUE;
15641 p++;
15642 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15643 has_opening_colon = TRUE;
15644 }
15645 else {
15646 found_problem = TRUE;
15647 ADD_POSIX_WARNING(p, "there must be a starting ':'");
15648
15649 /* Consider an initial punctuation (not one of the recognized ones) to
15650 * be a left terminator */
15651 if (*p != '^' && *p != ']' && isPUNCT(*p)) {
15652 p++;
15653 }
15654 }
15655
15656 /* They may think that you can put spaces between the components */
15657 if (isBLANK(*p)) {
15658 found_problem = TRUE;
15659
15660 do {
15661 p++;
15662 } while (p < e && isBLANK(*p));
15663
15664 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15665 }
15666
15667 if (*p == '^') {
15668
15669 /* We consider something like [^:^alnum:]] to not have been intended to
15670 * be a posix class, but XXX maybe we should */
15671 if (complement) {
15672 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15673 }
15674
15675 complement = 1;
15676 p++;
15677 }
15678
15679 /* Again, they may think that you can put spaces between the components */
15680 if (isBLANK(*p)) {
15681 found_problem = TRUE;
15682
15683 do {
15684 p++;
15685 } while (p < e && isBLANK(*p));
15686
15687 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15688 }
15689
15690 if (*p == ']') {
15691
15692 /* XXX This ']' may be a typo, and something else was meant. But
15693 * treating it as such creates enough complications, that that
15694 * possibility isn't currently considered here. So we assume that the
15695 * ']' is what is intended, and if we've already found an initial '[',
15696 * this leaves this construct looking like [:] or [:^], which almost
15697 * certainly weren't intended to be posix classes */
15698 if (has_opening_bracket) {
15699 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15700 }
15701
15702 /* But this function can be called when we parse the colon for
15703 * something like qr/[alpha:]]/, so we back up to look for the
15704 * beginning */
15705 p--;
15706
15707 if (*p == ';') {
15708 found_problem = TRUE;
15709 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15710 }
15711 else if (*p != ':') {
15712
15713 /* XXX We are currently very restrictive here, so this code doesn't
15714 * consider the possibility that, say, /[alpha.]]/ was intended to
15715 * be a posix class. */
15716 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15717 }
15718
15719 /* Here we have something like 'foo:]'. There was no initial colon,
15720 * and we back up over 'foo. XXX Unlike the going forward case, we
15721 * don't handle typos of non-word chars in the middle */
15722 has_opening_colon = FALSE;
15723 p--;
15724
15725 while (p > RExC_start && isWORDCHAR(*p)) {
15726 p--;
15727 }
15728 p++;
15729
15730 /* Here, we have positioned ourselves to where we think the first
15731 * character in the potential class is */
15732 }
15733
15734 /* Now the interior really starts. There are certain key characters that
15735 * can end the interior, or these could just be typos. To catch both
15736 * cases, we may have to do two passes. In the first pass, we keep on
15737 * going unless we come to a sequence that matches
15738 * qr/ [[:punct:]] [[:blank:]]* \] /xa
15739 * This means it takes a sequence to end the pass, so two typos in a row if
15740 * that wasn't what was intended. If the class is perfectly formed, just
15741 * this one pass is needed. We also stop if there are too many characters
15742 * being accumulated, but this number is deliberately set higher than any
15743 * real class. It is set high enough so that someone who thinks that
15744 * 'alphanumeric' is a correct name would get warned that it wasn't.
15745 * While doing the pass, we keep track of where the key characters were in
15746 * it. If we don't find an end to the class, and one of the key characters
15747 * was found, we redo the pass, but stop when we get to that character.
15748 * Thus the key character was considered a typo in the first pass, but a
15749 * terminator in the second. If two key characters are found, we stop at
15750 * the second one in the first pass. Again this can miss two typos, but
15751 * catches a single one
15752 *
15753 * In the first pass, 'possible_end' starts as NULL, and then gets set to
15754 * point to the first key character. For the second pass, it starts as -1.
15755 * */
15756
15757 name_start = p;
15758 parse_name:
15759 {
15760 bool has_blank = FALSE;
15761 bool has_upper = FALSE;
15762 bool has_terminating_colon = FALSE;
15763 bool has_terminating_bracket = FALSE;
15764 bool has_semi_colon = FALSE;
15765 unsigned int name_len = 0;
15766 int punct_count = 0;
15767
15768 while (p < e) {
15769
15770 /* Squeeze out blanks when looking up the class name below */
15771 if (isBLANK(*p) ) {
15772 has_blank = TRUE;
15773 found_problem = TRUE;
15774 p++;
15775 continue;
15776 }
15777
15778 /* The name will end with a punctuation */
15779 if (isPUNCT(*p)) {
15780 const char * peek = p + 1;
15781
15782 /* Treat any non-']' punctuation followed by a ']' (possibly
15783 * with intervening blanks) as trying to terminate the class.
15784 * ']]' is very likely to mean a class was intended (but
15785 * missing the colon), but the warning message that gets
15786 * generated shows the error position better if we exit the
15787 * loop at the bottom (eventually), so skip it here. */
15788 if (*p != ']') {
15789 if (peek < e && isBLANK(*peek)) {
15790 has_blank = TRUE;
15791 found_problem = TRUE;
15792 do {
15793 peek++;
15794 } while (peek < e && isBLANK(*peek));
15795 }
15796
15797 if (peek < e && *peek == ']') {
15798 has_terminating_bracket = TRUE;
15799 if (*p == ':') {
15800 has_terminating_colon = TRUE;
15801 }
15802 else if (*p == ';') {
15803 has_semi_colon = TRUE;
15804 has_terminating_colon = TRUE;
15805 }
15806 else {
15807 found_problem = TRUE;
15808 }
15809 p = peek + 1;
15810 goto try_posix;
15811 }
15812 }
15813
15814 /* Here we have punctuation we thought didn't end the class.
15815 * Keep track of the position of the key characters that are
15816 * more likely to have been class-enders */
15817 if (*p == ']' || *p == '[' || *p == ':' || *p == ';') {
15818
15819 /* Allow just one such possible class-ender not actually
15820 * ending the class. */
15821 if (possible_end) {
15822 break;
15823 }
15824 possible_end = p;
15825 }
15826
15827 /* If we have too many punctuation characters, no use in
15828 * keeping going */
15829 if (++punct_count > max_distance) {
15830 break;
15831 }
15832
15833 /* Treat the punctuation as a typo. */
15834 input_text[name_len++] = *p;
15835 p++;
15836 }
15837 else if (isUPPER(*p)) { /* Use lowercase for lookup */
15838 input_text[name_len++] = toLOWER(*p);
15839 has_upper = TRUE;
15840 found_problem = TRUE;
15841 p++;
15842 } else if (! UTF || UTF8_IS_INVARIANT(*p)) {
15843 input_text[name_len++] = *p;
15844 p++;
15845 }
15846 else {
15847 input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL);
15848 p+= UTF8SKIP(p);
15849 }
15850
15851 /* The declaration of 'input_text' is how long we allow a potential
15852 * class name to be, before saying they didn't mean a class name at
15853 * all */
15854 if (name_len >= C_ARRAY_LENGTH(input_text)) {
15855 break;
15856 }
15857 }
15858
15859 /* We get to here when the possible class name hasn't been properly
15860 * terminated before:
15861 * 1) we ran off the end of the pattern; or
15862 * 2) found two characters, each of which might have been intended to
15863 * be the name's terminator
15864 * 3) found so many punctuation characters in the purported name,
15865 * that the edit distance to a valid one is exceeded
15866 * 4) we decided it was more characters than anyone could have
15867 * intended to be one. */
15868
15869 found_problem = TRUE;
15870
15871 /* In the final two cases, we know that looking up what we've
15872 * accumulated won't lead to a match, even a fuzzy one. */
15873 if ( name_len >= C_ARRAY_LENGTH(input_text)
15874 || punct_count > max_distance)
15875 {
15876 /* If there was an intermediate key character that could have been
15877 * an intended end, redo the parse, but stop there */
15878 if (possible_end && possible_end != (char *) -1) {
15879 possible_end = (char *) -1; /* Special signal value to say
15880 we've done a first pass */
15881 p = name_start;
15882 goto parse_name;
15883 }
15884
15885 /* Otherwise, it can't have meant to have been a class */
15886 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15887 }
15888
15889 /* If we ran off the end, and the final character was a punctuation
15890 * one, back up one, to look at that final one just below. Later, we
15891 * will restore the parse pointer if appropriate */
15892 if (name_len && p == e && isPUNCT(*(p-1))) {
15893 p--;
15894 name_len--;
15895 }
15896
15897 if (p < e && isPUNCT(*p)) {
15898 if (*p == ']') {
15899 has_terminating_bracket = TRUE;
15900
15901 /* If this is a 2nd ']', and the first one is just below this
15902 * one, consider that to be the real terminator. This gives a
15903 * uniform and better positioning for the warning message */
15904 if ( possible_end
15905 && possible_end != (char *) -1
15906 && *possible_end == ']'
15907 && name_len && input_text[name_len - 1] == ']')
15908 {
15909 name_len--;
15910 p = possible_end;
15911
15912 /* And this is actually equivalent to having done the 2nd
15913 * pass now, so set it to not try again */
15914 possible_end = (char *) -1;
15915 }
15916 }
15917 else {
15918 if (*p == ':') {
15919 has_terminating_colon = TRUE;
15920 }
15921 else if (*p == ';') {
15922 has_semi_colon = TRUE;
15923 has_terminating_colon = TRUE;
15924 }
15925 p++;
15926 }
15927 }
15928
15929 try_posix:
15930
15931 /* Here, we have a class name to look up. We can short circuit the
15932 * stuff below for short names that can't possibly be meant to be a
15933 * class name. (We can do this on the first pass, as any second pass
15934 * will yield an even shorter name) */
15935 if (name_len < 3) {
15936 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15937 }
15938
15939 /* Find which class it is. Initially switch on the length of the name.
15940 * */
15941 switch (name_len) {
15942 case 4:
15943 if (memEQs(name_start, 4, "word")) {
15944 /* this is not POSIX, this is the Perl \w */
15945 class_number = ANYOF_WORDCHAR;
15946 }
15947 break;
15948 case 5:
15949 /* Names all of length 5: alnum alpha ascii blank cntrl digit
15950 * graph lower print punct space upper
15951 * Offset 4 gives the best switch position. */
15952 switch (name_start[4]) {
15953 case 'a':
15954 if (memBEGINs(name_start, 5, "alph")) /* alpha */
15955 class_number = ANYOF_ALPHA;
15956 break;
15957 case 'e':
15958 if (memBEGINs(name_start, 5, "spac")) /* space */
15959 class_number = ANYOF_SPACE;
15960 break;
15961 case 'h':
15962 if (memBEGINs(name_start, 5, "grap")) /* graph */
15963 class_number = ANYOF_GRAPH;
15964 break;
15965 case 'i':
15966 if (memBEGINs(name_start, 5, "asci")) /* ascii */
15967 class_number = ANYOF_ASCII;
15968 break;
15969 case 'k':
15970 if (memBEGINs(name_start, 5, "blan")) /* blank */
15971 class_number = ANYOF_BLANK;
15972 break;
15973 case 'l':
15974 if (memBEGINs(name_start, 5, "cntr")) /* cntrl */
15975 class_number = ANYOF_CNTRL;
15976 break;
15977 case 'm':
15978 if (memBEGINs(name_start, 5, "alnu")) /* alnum */
15979 class_number = ANYOF_ALPHANUMERIC;
15980 break;
15981 case 'r':
15982 if (memBEGINs(name_start, 5, "lowe")) /* lower */
15983 class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER;
15984 else if (memBEGINs(name_start, 5, "uppe")) /* upper */
15985 class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER;
15986 break;
15987 case 't':
15988 if (memBEGINs(name_start, 5, "digi")) /* digit */
15989 class_number = ANYOF_DIGIT;
15990 else if (memBEGINs(name_start, 5, "prin")) /* print */
15991 class_number = ANYOF_PRINT;
15992 else if (memBEGINs(name_start, 5, "punc")) /* punct */
15993 class_number = ANYOF_PUNCT;
15994 break;
15995 }
15996 break;
15997 case 6:
15998 if (memEQs(name_start, 6, "xdigit"))
15999 class_number = ANYOF_XDIGIT;
16000 break;
16001 }
16002
16003 /* If the name exactly matches a posix class name the class number will
16004 * here be set to it, and the input almost certainly was meant to be a
16005 * posix class, so we can skip further checking. If instead the syntax
16006 * is exactly correct, but the name isn't one of the legal ones, we
16007 * will return that as an error below. But if neither of these apply,
16008 * it could be that no posix class was intended at all, or that one
16009 * was, but there was a typo. We tease these apart by doing fuzzy
16010 * matching on the name */
16011 if (class_number == OOB_NAMEDCLASS && found_problem) {
16012 const UV posix_names[][6] = {
16013 { 'a', 'l', 'n', 'u', 'm' },
16014 { 'a', 'l', 'p', 'h', 'a' },
16015 { 'a', 's', 'c', 'i', 'i' },
16016 { 'b', 'l', 'a', 'n', 'k' },
16017 { 'c', 'n', 't', 'r', 'l' },
16018 { 'd', 'i', 'g', 'i', 't' },
16019 { 'g', 'r', 'a', 'p', 'h' },
16020 { 'l', 'o', 'w', 'e', 'r' },
16021 { 'p', 'r', 'i', 'n', 't' },
16022 { 'p', 'u', 'n', 'c', 't' },
16023 { 's', 'p', 'a', 'c', 'e' },
16024 { 'u', 'p', 'p', 'e', 'r' },
16025 { 'w', 'o', 'r', 'd' },
16026 { 'x', 'd', 'i', 'g', 'i', 't' }
16027 };
16028 /* The names of the above all have added NULs to make them the same
16029 * size, so we need to also have the real lengths */
16030 const UV posix_name_lengths[] = {
16031 sizeof("alnum") - 1,
16032 sizeof("alpha") - 1,
16033 sizeof("ascii") - 1,
16034 sizeof("blank") - 1,
16035 sizeof("cntrl") - 1,
16036 sizeof("digit") - 1,
16037 sizeof("graph") - 1,
16038 sizeof("lower") - 1,
16039 sizeof("print") - 1,
16040 sizeof("punct") - 1,
16041 sizeof("space") - 1,
16042 sizeof("upper") - 1,
16043 sizeof("word") - 1,
16044 sizeof("xdigit")- 1
16045 };
16046 unsigned int i;
16047 int temp_max = max_distance; /* Use a temporary, so if we
16048 reparse, we haven't changed the
16049 outer one */
16050
16051 /* Use a smaller max edit distance if we are missing one of the
16052 * delimiters */
16053 if ( has_opening_bracket + has_opening_colon < 2
16054 || has_terminating_bracket + has_terminating_colon < 2)
16055 {
16056 temp_max--;
16057 }
16058
16059 /* See if the input name is close to a legal one */
16060 for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) {
16061
16062 /* Short circuit call if the lengths are too far apart to be
16063 * able to match */
16064 if (abs( (int) (name_len - posix_name_lengths[i]))
16065 > temp_max)
16066 {
16067 continue;
16068 }
16069
16070 if (edit_distance(input_text,
16071 posix_names[i],
16072 name_len,
16073 posix_name_lengths[i],
16074 temp_max
16075 )
16076 > -1)
16077 { /* If it is close, it probably was intended to be a class */
16078 goto probably_meant_to_be;
16079 }
16080 }
16081
16082 /* Here the input name is not close enough to a valid class name
16083 * for us to consider it to be intended to be a posix class. If
16084 * we haven't already done so, and the parse found a character that
16085 * could have been terminators for the name, but which we absorbed
16086 * as typos during the first pass, repeat the parse, signalling it
16087 * to stop at that character */
16088 if (possible_end && possible_end != (char *) -1) {
16089 possible_end = (char *) -1;
16090 p = name_start;
16091 goto parse_name;
16092 }
16093
16094 /* Here neither pass found a close-enough class name */
16095 CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
16096 }
16097
16098 probably_meant_to_be:
16099
16100 /* Here we think that a posix specification was intended. Update any
16101 * parse pointer */
16102 if (updated_parse_ptr) {
16103 *updated_parse_ptr = (char *) p;
16104 }
16105
16106 /* If a posix class name was intended but incorrectly specified, we
16107 * output or return the warnings */
16108 if (found_problem) {
16109
16110 /* We set flags for these issues in the parse loop above instead of
16111 * adding them to the list of warnings, because we can parse it
16112 * twice, and we only want one warning instance */
16113 if (has_upper) {
16114 ADD_POSIX_WARNING(p, "the name must be all lowercase letters");
16115 }
16116 if (has_blank) {
16117 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
16118 }
16119 if (has_semi_colon) {
16120 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
16121 }
16122 else if (! has_terminating_colon) {
16123 ADD_POSIX_WARNING(p, "there is no terminating ':'");
16124 }
16125 if (! has_terminating_bracket) {
16126 ADD_POSIX_WARNING(p, "there is no terminating ']'");
16127 }
16128
16129 if ( posix_warnings
16130 && RExC_warn_text
16131 && av_top_index(RExC_warn_text) > -1)
16132 {
16133 *posix_warnings = RExC_warn_text;
16134 }
16135 }
16136 else if (class_number != OOB_NAMEDCLASS) {
16137 /* If it is a known class, return the class. The class number
16138 * #defines are structured so each complement is +1 to the normal
16139 * one */
16140 CLEAR_POSIX_WARNINGS_AND_RETURN(class_number + complement);
16141 }
16142 else if (! check_only) {
16143
16144 /* Here, it is an unrecognized class. This is an error (unless the
16145 * call is to check only, which we've already handled above) */
16146 const char * const complement_string = (complement)
16147 ? "^"
16148 : "";
16149 RExC_parse = (char *) p;
16150 vFAIL3utf8f("POSIX class [:%s%" UTF8f ":] unknown",
16151 complement_string,
16152 UTF8fARG(UTF, RExC_parse - name_start - 2, name_start));
16153 }
16154 }
16155
16156 return OOB_NAMEDCLASS;
16157}
16158#undef ADD_POSIX_WARNING
16159
16160STATIC unsigned int
16161S_regex_set_precedence(const U8 my_operator) {
16162
16163 /* Returns the precedence in the (?[...]) construct of the input operator,
16164 * specified by its character representation. The precedence follows
16165 * general Perl rules, but it extends this so that ')' and ']' have (low)
16166 * precedence even though they aren't really operators */
16167
16168 switch (my_operator) {
16169 case '!':
16170 return 5;
16171 case '&':
16172 return 4;
16173 case '^':
16174 case '|':
16175 case '+':
16176 case '-':
16177 return 3;
16178 case ')':
16179 return 2;
16180 case ']':
16181 return 1;
16182 }
16183
16184 NOT_REACHED; /* NOTREACHED */
16185 return 0; /* Silence compiler warning */
16186}
16187
16188STATIC regnode_offset
16189S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist,
16190 I32 *flagp, U32 depth,
16191 char * const oregcomp_parse)
16192{
16193 /* Handle the (?[...]) construct to do set operations */
16194
16195 U8 curchar; /* Current character being parsed */
16196 UV start, end; /* End points of code point ranges */
16197 SV* final = NULL; /* The end result inversion list */
16198 SV* result_string; /* 'final' stringified */
16199 AV* stack; /* stack of operators and operands not yet
16200 resolved */
16201 AV* fence_stack = NULL; /* A stack containing the positions in
16202 'stack' of where the undealt-with left
16203 parens would be if they were actually
16204 put there */
16205 /* The 'volatile' is a workaround for an optimiser bug
16206 * in Solaris Studio 12.3. See RT #127455 */
16207 volatile IV fence = 0; /* Position of where most recent undealt-
16208 with left paren in stack is; -1 if none.
16209 */
16210 STRLEN len; /* Temporary */
16211 regnode_offset node; /* Temporary, and final regnode returned by
16212 this function */
16213 const bool save_fold = FOLD; /* Temporary */
16214 char *save_end, *save_parse; /* Temporaries */
16215 const bool in_locale = LOC; /* we turn off /l during processing */
16216
16217 GET_RE_DEBUG_FLAGS_DECL;
16218
16219 PERL_ARGS_ASSERT_HANDLE_REGEX_SETS;
16220 PERL_UNUSED_ARG(oregcomp_parse); /* Only for Set_Node_Length */
16221
16222 DEBUG_PARSE("xcls");
16223
16224 if (in_locale) {
16225 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
16226 }
16227
16228 /* The use of this operator implies /u. This is required so that the
16229 * compile time values are valid in all runtime cases */
16230 REQUIRE_UNI_RULES(flagp, 0);
16231
16232 ckWARNexperimental(RExC_parse,
16233 WARN_EXPERIMENTAL__REGEX_SETS,
16234 "The regex_sets feature is experimental");
16235
16236 /* Everything in this construct is a metacharacter. Operands begin with
16237 * either a '\' (for an escape sequence), or a '[' for a bracketed
16238 * character class. Any other character should be an operator, or
16239 * parenthesis for grouping. Both types of operands are handled by calling
16240 * regclass() to parse them. It is called with a parameter to indicate to
16241 * return the computed inversion list. The parsing here is implemented via
16242 * a stack. Each entry on the stack is a single character representing one
16243 * of the operators; or else a pointer to an operand inversion list. */
16244
16245#define IS_OPERATOR(a) SvIOK(a)
16246#define IS_OPERAND(a) (! IS_OPERATOR(a))
16247
16248 /* The stack is kept in Łukasiewicz order. (That's pronounced similar
16249 * to luke-a-shave-itch (or -itz), but people who didn't want to bother
16250 * with pronouncing it called it Reverse Polish instead, but now that YOU
16251 * know how to pronounce it you can use the correct term, thus giving due
16252 * credit to the person who invented it, and impressing your geek friends.
16253 * Wikipedia says that the pronounciation of "Ł" has been changing so that
16254 * it is now more like an English initial W (as in wonk) than an L.)
16255 *
16256 * This means that, for example, 'a | b & c' is stored on the stack as
16257 *
16258 * c [4]
16259 * b [3]
16260 * & [2]
16261 * a [1]
16262 * | [0]
16263 *
16264 * where the numbers in brackets give the stack [array] element number.
16265 * In this implementation, parentheses are not stored on the stack.
16266 * Instead a '(' creates a "fence" so that the part of the stack below the
16267 * fence is invisible except to the corresponding ')' (this allows us to
16268 * replace testing for parens, by using instead subtraction of the fence
16269 * position). As new operands are processed they are pushed onto the stack
16270 * (except as noted in the next paragraph). New operators of higher
16271 * precedence than the current final one are inserted on the stack before
16272 * the lhs operand (so that when the rhs is pushed next, everything will be
16273 * in the correct positions shown above. When an operator of equal or
16274 * lower precedence is encountered in parsing, all the stacked operations
16275 * of equal or higher precedence are evaluated, leaving the result as the
16276 * top entry on the stack. This makes higher precedence operations
16277 * evaluate before lower precedence ones, and causes operations of equal
16278 * precedence to left associate.
16279 *
16280 * The only unary operator '!' is immediately pushed onto the stack when
16281 * encountered. When an operand is encountered, if the top of the stack is
16282 * a '!", the complement is immediately performed, and the '!' popped. The
16283 * resulting value is treated as a new operand, and the logic in the
16284 * previous paragraph is executed. Thus in the expression
16285 * [a] + ! [b]
16286 * the stack looks like
16287 *
16288 * !
16289 * a
16290 * +
16291 *
16292 * as 'b' gets parsed, the latter gets evaluated to '!b', and the stack
16293 * becomes
16294 *
16295 * !b
16296 * a
16297 * +
16298 *
16299 * A ')' is treated as an operator with lower precedence than all the
16300 * aforementioned ones, which causes all operations on the stack above the
16301 * corresponding '(' to be evaluated down to a single resultant operand.
16302 * Then the fence for the '(' is removed, and the operand goes through the
16303 * algorithm above, without the fence.
16304 *
16305 * A separate stack is kept of the fence positions, so that the position of
16306 * the latest so-far unbalanced '(' is at the top of it.
16307 *
16308 * The ']' ending the construct is treated as the lowest operator of all,
16309 * so that everything gets evaluated down to a single operand, which is the
16310 * result */
16311
16312 sv_2mortal((SV *)(stack = newAV()));
16313 sv_2mortal((SV *)(fence_stack = newAV()));
16314
16315 while (RExC_parse < RExC_end) {
16316 I32 top_index; /* Index of top-most element in 'stack' */
16317 SV** top_ptr; /* Pointer to top 'stack' element */
16318 SV* current = NULL; /* To contain the current inversion list
16319 operand */
16320 SV* only_to_avoid_leaks;
16321
16322 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
16323 TRUE /* Force /x */ );
16324 if (RExC_parse >= RExC_end) { /* Fail */
16325 break;
16326 }
16327
16328 curchar = UCHARAT(RExC_parse);
16329
16330redo_curchar:
16331
16332#ifdef ENABLE_REGEX_SETS_DEBUGGING
16333 /* Enable with -Accflags=-DENABLE_REGEX_SETS_DEBUGGING */
16334 DEBUG_U(dump_regex_sets_structures(pRExC_state,
16335 stack, fence, fence_stack));
16336#endif
16337
16338 top_index = av_tindex_skip_len_mg(stack);
16339
16340 switch (curchar) {
16341 SV** stacked_ptr; /* Ptr to something already on 'stack' */
16342 char stacked_operator; /* The topmost operator on the 'stack'. */
16343 SV* lhs; /* Operand to the left of the operator */
16344 SV* rhs; /* Operand to the right of the operator */
16345 SV* fence_ptr; /* Pointer to top element of the fence
16346 stack */
16347 case '(':
16348
16349 if ( RExC_parse < RExC_end - 2
16350 && UCHARAT(RExC_parse + 1) == '?'
16351 && UCHARAT(RExC_parse + 2) == '^')
16352 {
16353 const regnode_offset orig_emit = RExC_emit;
16354 SV * resultant_invlist;
16355
16356 /* If is a '(?^', could be an embedded '(?^flags:(?[...])'.
16357 * This happens when we have some thing like
16358 *
16359 * my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
16360 * ...
16361 * qr/(?[ \p{Digit} & $thai_or_lao ])/;
16362 *
16363 * Here we would be handling the interpolated
16364 * '$thai_or_lao'. We handle this by a recursive call to
16365 * reg which returns the inversion list the
16366 * interpolated expression evaluates to. Actually, the
16367 * return is a special regnode containing a pointer to that
16368 * inversion list. If the return isn't that regnode alone,
16369 * we know that this wasn't such an interpolation, which is
16370 * an error: we need to get a single inversion list back
16371 * from the recursion */
16372
16373 RExC_parse++;
16374 RExC_sets_depth++;
16375
16376 node = reg(pRExC_state, 2, flagp, depth+1);
16377 RETURN_FAIL_ON_RESTART(*flagp, flagp);
16378
16379 if ( OP(REGNODE_p(node)) != REGEX_SET
16380 /* If more than a single node returned, the nested
16381 * parens evaluated to more than just a (?[...]),
16382 * which isn't legal */
16383 || node != 1) {
16384 vFAIL("Expecting interpolated extended charclass");
16385 }
16386 resultant_invlist = (SV *) ARGp(REGNODE_p(node));
16387 current = invlist_clone(resultant_invlist, NULL);
16388 SvREFCNT_dec(resultant_invlist);
16389
16390 RExC_sets_depth--;
16391 RExC_emit = orig_emit;
16392 goto handle_operand;
16393 }
16394
16395 /* A regular '('. Look behind for illegal syntax */
16396 if (top_index - fence >= 0) {
16397 /* If the top entry on the stack is an operator, it had
16398 * better be a '!', otherwise the entry below the top
16399 * operand should be an operator */
16400 if ( ! (top_ptr = av_fetch(stack, top_index, FALSE))
16401 || (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!')
16402 || ( IS_OPERAND(*top_ptr)
16403 && ( top_index - fence < 1
16404 || ! (stacked_ptr = av_fetch(stack,
16405 top_index - 1,
16406 FALSE))
16407 || ! IS_OPERATOR(*stacked_ptr))))
16408 {
16409 RExC_parse++;
16410 vFAIL("Unexpected '(' with no preceding operator");
16411 }
16412 }
16413
16414 /* Stack the position of this undealt-with left paren */
16415 av_push(fence_stack, newSViv(fence));
16416 fence = top_index + 1;
16417 break;
16418
16419 case '\\':
16420 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
16421 * multi-char folds are allowed. */
16422 if (!regclass(pRExC_state, flagp, depth+1,
16423 TRUE, /* means parse just the next thing */
16424 FALSE, /* don't allow multi-char folds */
16425 FALSE, /* don't silence non-portable warnings. */
16426 TRUE, /* strict */
16427 FALSE, /* Require return to be an ANYOF */
16428 &current))
16429 {
16430 RETURN_FAIL_ON_RESTART(*flagp, flagp);
16431 goto regclass_failed;
16432 }
16433
16434 /* regclass() will return with parsing just the \ sequence,
16435 * leaving the parse pointer at the next thing to parse */
16436 RExC_parse--;
16437 goto handle_operand;
16438
16439 case '[': /* Is a bracketed character class */
16440 {
16441 /* See if this is a [:posix:] class. */
16442 bool is_posix_class = (OOB_NAMEDCLASS
16443 < handle_possible_posix(pRExC_state,
16444 RExC_parse + 1,
16445 NULL,
16446 NULL,
16447 TRUE /* checking only */));
16448 /* If it is a posix class, leave the parse pointer at the '['
16449 * to fool regclass() into thinking it is part of a
16450 * '[[:posix:]]'. */
16451 if (! is_posix_class) {
16452 RExC_parse++;
16453 }
16454
16455 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
16456 * multi-char folds are allowed. */
16457 if (!regclass(pRExC_state, flagp, depth+1,
16458 is_posix_class, /* parse the whole char
16459 class only if not a
16460 posix class */
16461 FALSE, /* don't allow multi-char folds */
16462 TRUE, /* silence non-portable warnings. */
16463 TRUE, /* strict */
16464 FALSE, /* Require return to be an ANYOF */
16465 &current))
16466 {
16467 RETURN_FAIL_ON_RESTART(*flagp, flagp);
16468 goto regclass_failed;
16469 }
16470
16471 if (! current) {
16472 break;
16473 }
16474
16475 /* function call leaves parse pointing to the ']', except if we
16476 * faked it */
16477 if (is_posix_class) {
16478 RExC_parse--;
16479 }
16480
16481 goto handle_operand;
16482 }
16483
16484 case ']':
16485 if (top_index >= 1) {
16486 goto join_operators;
16487 }
16488
16489 /* Only a single operand on the stack: are done */
16490 goto done;
16491
16492 case ')':
16493 if (av_tindex_skip_len_mg(fence_stack) < 0) {
16494 if (UCHARAT(RExC_parse - 1) == ']') {
16495 break;
16496 }
16497 RExC_parse++;
16498 vFAIL("Unexpected ')'");
16499 }
16500
16501 /* If nothing after the fence, is missing an operand */
16502 if (top_index - fence < 0) {
16503 RExC_parse++;
16504 goto bad_syntax;
16505 }
16506 /* If at least two things on the stack, treat this as an
16507 * operator */
16508 if (top_index - fence >= 1) {
16509 goto join_operators;
16510 }
16511
16512 /* Here only a single thing on the fenced stack, and there is a
16513 * fence. Get rid of it */
16514 fence_ptr = av_pop(fence_stack);
16515 assert(fence_ptr);
16516 fence = SvIV(fence_ptr);
16517 SvREFCNT_dec_NN(fence_ptr);
16518 fence_ptr = NULL;
16519
16520 if (fence < 0) {
16521 fence = 0;
16522 }
16523
16524 /* Having gotten rid of the fence, we pop the operand at the
16525 * stack top and process it as a newly encountered operand */
16526 current = av_pop(stack);
16527 if (IS_OPERAND(current)) {
16528 goto handle_operand;
16529 }
16530
16531 RExC_parse++;
16532 goto bad_syntax;
16533
16534 case '&':
16535 case '|':
16536 case '+':
16537 case '-':
16538 case '^':
16539
16540 /* These binary operators should have a left operand already
16541 * parsed */
16542 if ( top_index - fence < 0
16543 || top_index - fence == 1
16544 || ( ! (top_ptr = av_fetch(stack, top_index, FALSE)))
16545 || ! IS_OPERAND(*top_ptr))
16546 {
16547 goto unexpected_binary;
16548 }
16549
16550 /* If only the one operand is on the part of the stack visible
16551 * to us, we just place this operator in the proper position */
16552 if (top_index - fence < 2) {
16553
16554 /* Place the operator before the operand */
16555
16556 SV* lhs = av_pop(stack);
16557 av_push(stack, newSVuv(curchar));
16558 av_push(stack, lhs);
16559 break;
16560 }
16561
16562 /* But if there is something else on the stack, we need to
16563 * process it before this new operator if and only if the
16564 * stacked operation has equal or higher precedence than the
16565 * new one */
16566
16567 join_operators:
16568
16569 /* The operator on the stack is supposed to be below both its
16570 * operands */
16571 if ( ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE))
16572 || IS_OPERAND(*stacked_ptr))
16573 {
16574 /* But if not, it's legal and indicates we are completely
16575 * done if and only if we're currently processing a ']',
16576 * which should be the final thing in the expression */
16577 if (curchar == ']') {
16578 goto done;
16579 }
16580
16581 unexpected_binary:
16582 RExC_parse++;
16583 vFAIL2("Unexpected binary operator '%c' with no "
16584 "preceding operand", curchar);
16585 }
16586 stacked_operator = (char) SvUV(*stacked_ptr);
16587
16588 if (regex_set_precedence(curchar)
16589 > regex_set_precedence(stacked_operator))
16590 {
16591 /* Here, the new operator has higher precedence than the
16592 * stacked one. This means we need to add the new one to
16593 * the stack to await its rhs operand (and maybe more
16594 * stuff). We put it before the lhs operand, leaving
16595 * untouched the stacked operator and everything below it
16596 * */
16597 lhs = av_pop(stack);
16598 assert(IS_OPERAND(lhs));
16599
16600 av_push(stack, newSVuv(curchar));
16601 av_push(stack, lhs);
16602 break;
16603 }
16604
16605 /* Here, the new operator has equal or lower precedence than
16606 * what's already there. This means the operation already
16607 * there should be performed now, before the new one. */
16608
16609 rhs = av_pop(stack);
16610 if (! IS_OPERAND(rhs)) {
16611
16612 /* This can happen when a ! is not followed by an operand,
16613 * like in /(?[\t &!])/ */
16614 goto bad_syntax;
16615 }
16616
16617 lhs = av_pop(stack);
16618
16619 if (! IS_OPERAND(lhs)) {
16620
16621 /* This can happen when there is an empty (), like in
16622 * /(?[[0]+()+])/ */
16623 goto bad_syntax;
16624 }
16625
16626 switch (stacked_operator) {
16627 case '&':
16628 _invlist_intersection(lhs, rhs, &rhs);
16629 break;
16630
16631 case '|':
16632 case '+':
16633 _invlist_union(lhs, rhs, &rhs);
16634 break;
16635
16636 case '-':
16637 _invlist_subtract(lhs, rhs, &rhs);
16638 break;
16639
16640 case '^': /* The union minus the intersection */
16641 {
16642 SV* i = NULL;
16643 SV* u = NULL;
16644
16645 _invlist_union(lhs, rhs, &u);
16646 _invlist_intersection(lhs, rhs, &i);
16647 _invlist_subtract(u, i, &rhs);
16648 SvREFCNT_dec_NN(i);
16649 SvREFCNT_dec_NN(u);
16650 break;
16651 }
16652 }
16653 SvREFCNT_dec(lhs);
16654
16655 /* Here, the higher precedence operation has been done, and the
16656 * result is in 'rhs'. We overwrite the stacked operator with
16657 * the result. Then we redo this code to either push the new
16658 * operator onto the stack or perform any higher precedence
16659 * stacked operation */
16660 only_to_avoid_leaks = av_pop(stack);
16661 SvREFCNT_dec(only_to_avoid_leaks);
16662 av_push(stack, rhs);
16663 goto redo_curchar;
16664
16665 case '!': /* Highest priority, right associative */
16666
16667 /* If what's already at the top of the stack is another '!",
16668 * they just cancel each other out */
16669 if ( (top_ptr = av_fetch(stack, top_index, FALSE))
16670 && (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!'))
16671 {
16672 only_to_avoid_leaks = av_pop(stack);
16673 SvREFCNT_dec(only_to_avoid_leaks);
16674 }
16675 else { /* Otherwise, since it's right associative, just push
16676 onto the stack */
16677 av_push(stack, newSVuv(curchar));
16678 }
16679 break;
16680
16681 default:
16682 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16683 if (RExC_parse >= RExC_end) {
16684 break;
16685 }
16686 vFAIL("Unexpected character");
16687
16688 handle_operand:
16689
16690 /* Here 'current' is the operand. If something is already on the
16691 * stack, we have to check if it is a !. But first, the code above
16692 * may have altered the stack in the time since we earlier set
16693 * 'top_index'. */
16694
16695 top_index = av_tindex_skip_len_mg(stack);
16696 if (top_index - fence >= 0) {
16697 /* If the top entry on the stack is an operator, it had better
16698 * be a '!', otherwise the entry below the top operand should
16699 * be an operator */
16700 top_ptr = av_fetch(stack, top_index, FALSE);
16701 assert(top_ptr);
16702 if (IS_OPERATOR(*top_ptr)) {
16703
16704 /* The only permissible operator at the top of the stack is
16705 * '!', which is applied immediately to this operand. */
16706 curchar = (char) SvUV(*top_ptr);
16707 if (curchar != '!') {
16708 SvREFCNT_dec(current);
16709 vFAIL2("Unexpected binary operator '%c' with no "
16710 "preceding operand", curchar);
16711 }
16712
16713 _invlist_invert(current);
16714
16715 only_to_avoid_leaks = av_pop(stack);
16716 SvREFCNT_dec(only_to_avoid_leaks);
16717
16718 /* And we redo with the inverted operand. This allows
16719 * handling multiple ! in a row */
16720 goto handle_operand;
16721 }
16722 /* Single operand is ok only for the non-binary ')'
16723 * operator */
16724 else if ((top_index - fence == 0 && curchar != ')')
16725 || (top_index - fence > 0
16726 && (! (stacked_ptr = av_fetch(stack,
16727 top_index - 1,
16728 FALSE))
16729 || IS_OPERAND(*stacked_ptr))))
16730 {
16731 SvREFCNT_dec(current);
16732 vFAIL("Operand with no preceding operator");
16733 }
16734 }
16735
16736 /* Here there was nothing on the stack or the top element was
16737 * another operand. Just add this new one */
16738 av_push(stack, current);
16739
16740 } /* End of switch on next parse token */
16741
16742 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16743 } /* End of loop parsing through the construct */
16744
16745 vFAIL("Syntax error in (?[...])");
16746
16747 done:
16748
16749 if (RExC_parse >= RExC_end || RExC_parse[1] != ')') {
16750 if (RExC_parse < RExC_end) {
16751 RExC_parse++;
16752 }
16753
16754 vFAIL("Unexpected ']' with no following ')' in (?[...");
16755 }
16756
16757 if (av_tindex_skip_len_mg(fence_stack) >= 0) {
16758 vFAIL("Unmatched (");
16759 }
16760
16761 if (av_tindex_skip_len_mg(stack) < 0 /* Was empty */
16762 || ((final = av_pop(stack)) == NULL)
16763 || ! IS_OPERAND(final)
16764 || ! is_invlist(final)
16765 || av_tindex_skip_len_mg(stack) >= 0) /* More left on stack */
16766 {
16767 bad_syntax:
16768 SvREFCNT_dec(final);
16769 vFAIL("Incomplete expression within '(?[ ])'");
16770 }
16771
16772 /* Here, 'final' is the resultant inversion list from evaluating the
16773 * expression. Return it if so requested */
16774 if (return_invlist) {
16775 *return_invlist = final;
16776 return END;
16777 }
16778
16779 if (RExC_sets_depth) { /* If within a recursive call, return in a special
16780 regnode */
16781 RExC_parse++;
16782 node = regpnode(pRExC_state, REGEX_SET, (void *) final);
16783 }
16784 else {
16785
16786 /* Otherwise generate a resultant node, based on 'final'. regclass()
16787 * is expecting a string of ranges and individual code points */
16788 invlist_iterinit(final);
16789 result_string = newSVpvs("");
16790 while (invlist_iternext(final, &start, &end)) {
16791 if (start == end) {
16792 Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}", start);
16793 }
16794 else {
16795 Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}-\\x{%"
16796 UVXf "}", start, end);
16797 }
16798 }
16799
16800 /* About to generate an ANYOF (or similar) node from the inversion list
16801 * we have calculated */
16802 save_parse = RExC_parse;
16803 RExC_parse = SvPV(result_string, len);
16804 save_end = RExC_end;
16805 RExC_end = RExC_parse + len;
16806 TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
16807
16808 /* We turn off folding around the call, as the class we have
16809 * constructed already has all folding taken into consideration, and we
16810 * don't want regclass() to add to that */
16811 RExC_flags &= ~RXf_PMf_FOLD;
16812 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if multi-char
16813 * folds are allowed. */
16814 node = regclass(pRExC_state, flagp, depth+1,
16815 FALSE, /* means parse the whole char class */
16816 FALSE, /* don't allow multi-char folds */
16817 TRUE, /* silence non-portable warnings. The above may
16818 very well have generated non-portable code
16819 points, but they're valid on this machine */
16820 FALSE, /* similarly, no need for strict */
16821
16822 /* We can optimize into something besides an ANYOF,
16823 * except under /l, which needs to be ANYOF because of
16824 * runtime checks for locale sanity, etc */
16825 ! in_locale,
16826 NULL
16827 );
16828
16829 RESTORE_WARNINGS;
16830 RExC_parse = save_parse + 1;
16831 RExC_end = save_end;
16832 SvREFCNT_dec_NN(final);
16833 SvREFCNT_dec_NN(result_string);
16834
16835 if (save_fold) {
16836 RExC_flags |= RXf_PMf_FOLD;
16837 }
16838
16839 if (!node) {
16840 RETURN_FAIL_ON_RESTART(*flagp, flagp);
16841 goto regclass_failed;
16842 }
16843
16844 /* Fix up the node type if we are in locale. (We have pretended we are
16845 * under /u for the purposes of regclass(), as this construct will only
16846 * work under UTF-8 locales. But now we change the opcode to be ANYOFL
16847 * (so as to cause any warnings about bad locales to be output in
16848 * regexec.c), and add the flag that indicates to check if not in a
16849 * UTF-8 locale. The reason we above forbid optimization into
16850 * something other than an ANYOF node is simply to minimize the number
16851 * of code changes in regexec.c. Otherwise we would have to create new
16852 * EXACTish node types and deal with them. This decision could be
16853 * revisited should this construct become popular.
16854 *
16855 * (One might think we could look at the resulting ANYOF node and
16856 * suppress the flag if everything is above 255, as those would be
16857 * UTF-8 only, but this isn't true, as the components that led to that
16858 * result could have been locale-affected, and just happen to cancel
16859 * each other out under UTF-8 locales.) */
16860 if (in_locale) {
16861 set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
16862
16863 assert(OP(REGNODE_p(node)) == ANYOF);
16864
16865 OP(REGNODE_p(node)) = ANYOFL;
16866 ANYOF_FLAGS(REGNODE_p(node))
16867 |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
16868 }
16869 }
16870
16871 nextchar(pRExC_state);
16872 Set_Node_Length(REGNODE_p(node), RExC_parse - oregcomp_parse + 1); /* MJD */
16873 return node;
16874
16875 regclass_failed:
16876 FAIL2("panic: regclass returned failure to handle_sets, " "flags=%#" UVxf,
16877 (UV) *flagp);
16878}
16879
16880#ifdef ENABLE_REGEX_SETS_DEBUGGING
16881
16882STATIC void
16883S_dump_regex_sets_structures(pTHX_ RExC_state_t *pRExC_state,
16884 AV * stack, const IV fence, AV * fence_stack)
16885{ /* Dumps the stacks in handle_regex_sets() */
16886
16887 const SSize_t stack_top = av_tindex_skip_len_mg(stack);
16888 const SSize_t fence_stack_top = av_tindex_skip_len_mg(fence_stack);
16889 SSize_t i;
16890
16891 PERL_ARGS_ASSERT_DUMP_REGEX_SETS_STRUCTURES;
16892
16893 PerlIO_printf(Perl_debug_log, "\nParse position is:%s\n", RExC_parse);
16894
16895 if (stack_top < 0) {
16896 PerlIO_printf(Perl_debug_log, "Nothing on stack\n");
16897 }
16898 else {
16899 PerlIO_printf(Perl_debug_log, "Stack: (fence=%d)\n", (int) fence);
16900 for (i = stack_top; i >= 0; i--) {
16901 SV ** element_ptr = av_fetch(stack, i, FALSE);
16902 if (! element_ptr) {
16903 }
16904
16905 if (IS_OPERATOR(*element_ptr)) {
16906 PerlIO_printf(Perl_debug_log, "[%d]: %c\n",
16907 (int) i, (int) SvIV(*element_ptr));
16908 }
16909 else {
16910 PerlIO_printf(Perl_debug_log, "[%d] ", (int) i);
16911 sv_dump(*element_ptr);
16912 }
16913 }
16914 }
16915
16916 if (fence_stack_top < 0) {
16917 PerlIO_printf(Perl_debug_log, "Nothing on fence_stack\n");
16918 }
16919 else {
16920 PerlIO_printf(Perl_debug_log, "Fence_stack: \n");
16921 for (i = fence_stack_top; i >= 0; i--) {
16922 SV ** element_ptr = av_fetch(fence_stack, i, FALSE);
16923 if (! element_ptr) {
16924 }
16925
16926 PerlIO_printf(Perl_debug_log, "[%d]: %d\n",
16927 (int) i, (int) SvIV(*element_ptr));
16928 }
16929 }
16930}
16931
16932#endif
16933
16934#undef IS_OPERATOR
16935#undef IS_OPERAND
16936
16937STATIC void
16938S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist)
16939{
16940 /* This adds the Latin1/above-Latin1 folding rules.
16941 *
16942 * This should be called only for a Latin1-range code points, cp, which is
16943 * known to be involved in a simple fold with other code points above
16944 * Latin1. It would give false results if /aa has been specified.
16945 * Multi-char folds are outside the scope of this, and must be handled
16946 * specially. */
16947
16948 PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS;
16949
16950 assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp));
16951
16952 /* The rules that are valid for all Unicode versions are hard-coded in */
16953 switch (cp) {
16954 case 'k':
16955 case 'K':
16956 *invlist =
16957 add_cp_to_invlist(*invlist, KELVIN_SIGN);
16958 break;
16959 case 's':
16960 case 'S':
16961 *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S);
16962 break;
16963 case MICRO_SIGN:
16964 *invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU);
16965 *invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU);
16966 break;
16967 case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
16968 case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
16969 *invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN);
16970 break;
16971 case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
16972 *invlist = add_cp_to_invlist(*invlist,
16973 LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
16974 break;
16975
16976 default: /* Other code points are checked against the data for the
16977 current Unicode version */
16978 {
16979 Size_t folds_count;
16980 U32 first_fold;
16981 const U32 * remaining_folds;
16982 UV folded_cp;
16983
16984 if (isASCII(cp)) {
16985 folded_cp = toFOLD(cp);
16986 }
16987 else {
16988 U8 dummy_fold[UTF8_MAXBYTES_CASE+1];
16989 Size_t dummy_len;
16990 folded_cp = _to_fold_latin1(cp, dummy_fold, &dummy_len, 0);
16991 }
16992
16993 if (folded_cp > 255) {
16994 *invlist = add_cp_to_invlist(*invlist, folded_cp);
16995 }
16996
16997 folds_count = _inverse_folds(folded_cp, &first_fold,
16998 &remaining_folds);
16999 if (folds_count == 0) {
17000
17001 /* Use deprecated warning to increase the chances of this being
17002 * output */
17003 ckWARN2reg_d(RExC_parse,
17004 "Perl folding rules are not up-to-date for 0x%02X;"
17005 " please use the perlbug utility to report;", cp);
17006 }
17007 else {
17008 unsigned int i;
17009
17010 if (first_fold > 255) {
17011 *invlist = add_cp_to_invlist(*invlist, first_fold);
17012 }
17013 for (i = 0; i < folds_count - 1; i++) {
17014 if (remaining_folds[i] > 255) {
17015 *invlist = add_cp_to_invlist(*invlist,
17016 remaining_folds[i]);
17017 }
17018 }
17019 }
17020 break;
17021 }
17022 }
17023}
17024
17025STATIC void
17026S_output_posix_warnings(pTHX_ RExC_state_t *pRExC_state, AV* posix_warnings)
17027{
17028 /* Output the elements of the array given by '*posix_warnings' as REGEXP
17029 * warnings. */
17030
17031 SV * msg;
17032 const bool first_is_fatal = ckDEAD(packWARN(WARN_REGEXP));
17033
17034 PERL_ARGS_ASSERT_OUTPUT_POSIX_WARNINGS;
17035
17036 if (! TO_OUTPUT_WARNINGS(RExC_parse)) {
17037 CLEAR_POSIX_WARNINGS();
17038 return;
17039 }
17040
17041 while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) {
17042 if (first_is_fatal) { /* Avoid leaking this */
17043 av_undef(posix_warnings); /* This isn't necessary if the
17044 array is mortal, but is a
17045 fail-safe */
17046 (void) sv_2mortal(msg);
17047 PREPARE_TO_DIE;
17048 }
17049 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg));
17050 SvREFCNT_dec_NN(msg);
17051 }
17052
17053 UPDATE_WARNINGS_LOC(RExC_parse);
17054}
17055
17056PERL_STATIC_INLINE Size_t
17057S_find_first_differing_byte_pos(const U8 * s1, const U8 * s2, const Size_t max)
17058{
17059 const U8 * const start = s1;
17060 const U8 * const send = start + max;
17061
17062 PERL_ARGS_ASSERT_FIND_FIRST_DIFFERING_BYTE_POS;
17063
17064 while (s1 < send && *s1 == *s2) {
17065 s1++; s2++;
17066 }
17067
17068 return s1 - start;
17069}
17070
17071
17072STATIC AV *
17073S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count)
17074{
17075 /* This adds the string scalar <multi_string> to the array
17076 * <multi_char_matches>. <multi_string> is known to have exactly
17077 * <cp_count> code points in it. This is used when constructing a
17078 * bracketed character class and we find something that needs to match more
17079 * than a single character.
17080 *
17081 * <multi_char_matches> is actually an array of arrays. Each top-level
17082 * element is an array that contains all the strings known so far that are
17083 * the same length. And that length (in number of code points) is the same
17084 * as the index of the top-level array. Hence, the [2] element is an
17085 * array, each element thereof is a string containing TWO code points;
17086 * while element [3] is for strings of THREE characters, and so on. Since
17087 * this is for multi-char strings there can never be a [0] nor [1] element.
17088 *
17089 * When we rewrite the character class below, we will do so such that the
17090 * longest strings are written first, so that it prefers the longest
17091 * matching strings first. This is done even if it turns out that any
17092 * quantifier is non-greedy, out of this programmer's (khw) laziness. Tom
17093 * Christiansen has agreed that this is ok. This makes the test for the
17094 * ligature 'ffi' come before the test for 'ff', for example */
17095
17096 AV* this_array;
17097 AV** this_array_ptr;
17098
17099 PERL_ARGS_ASSERT_ADD_MULTI_MATCH;
17100
17101 if (! multi_char_matches) {
17102 multi_char_matches = newAV();
17103 }
17104
17105 if (av_exists(multi_char_matches, cp_count)) {
17106 this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE);
17107 this_array = *this_array_ptr;
17108 }
17109 else {
17110 this_array = newAV();
17111 av_store(multi_char_matches, cp_count,
17112 (SV*) this_array);
17113 }
17114 av_push(this_array, multi_string);
17115
17116 return multi_char_matches;
17117}
17118
17119/* The names of properties whose definitions are not known at compile time are
17120 * stored in this SV, after a constant heading. So if the length has been
17121 * changed since initialization, then there is a run-time definition. */
17122#define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION \
17123 (SvCUR(listsv) != initial_listsv_len)
17124
17125/* There is a restricted set of white space characters that are legal when
17126 * ignoring white space in a bracketed character class. This generates the
17127 * code to skip them.
17128 *
17129 * There is a line below that uses the same white space criteria but is outside
17130 * this macro. Both here and there must use the same definition */
17131#define SKIP_BRACKETED_WHITE_SPACE(do_skip, p) \
17132 STMT_START { \
17133 if (do_skip) { \
17134 while (isBLANK_A(UCHARAT(p))) \
17135 { \
17136 p++; \
17137 } \
17138 } \
17139 } STMT_END
17140
17141STATIC regnode_offset
17142S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth,
17143 const bool stop_at_1, /* Just parse the next thing, don't
17144 look for a full character class */
17145 bool allow_mutiple_chars,
17146 const bool silence_non_portable, /* Don't output warnings
17147 about too large
17148 characters */
17149 const bool strict,
17150 bool optimizable, /* ? Allow a non-ANYOF return
17151 node */
17152 SV** ret_invlist /* Return an inversion list, not a node */
17153 )
17154{
17155 /* parse a bracketed class specification. Most of these will produce an
17156 * ANYOF node; but something like [a] will produce an EXACT node; [aA], an
17157 * EXACTFish node; [[:ascii:]], a POSIXA node; etc. It is more complex
17158 * under /i with multi-character folds: it will be rewritten following the
17159 * paradigm of this example, where the <multi-fold>s are characters which
17160 * fold to multiple character sequences:
17161 * /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
17162 * gets effectively rewritten as:
17163 * /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
17164 * reg() gets called (recursively) on the rewritten version, and this
17165 * function will return what it constructs. (Actually the <multi-fold>s
17166 * aren't physically removed from the [abcdefghi], it's just that they are
17167 * ignored in the recursion by means of a flag:
17168 * <RExC_in_multi_char_class>.)
17169 *
17170 * ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS
17171 * characters, with the corresponding bit set if that character is in the
17172 * list. For characters above this, an inversion list is used. There
17173 * are extra bits for \w, etc. in locale ANYOFs, as what these match is not
17174 * determinable at compile time
17175 *
17176 * On success, returns the offset at which any next node should be placed
17177 * into the regex engine program being compiled.
17178 *
17179 * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
17180 * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
17181 * UTF-8
17182 */
17183
17184 dVAR;
17185 UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
17186 IV range = 0;
17187 UV value = OOB_UNICODE, save_value = OOB_UNICODE;
17188 regnode_offset ret = -1; /* Initialized to an illegal value */
17189 STRLEN numlen;
17190 int namedclass = OOB_NAMEDCLASS;
17191 char *rangebegin = NULL;
17192 SV *listsv = NULL; /* List of \p{user-defined} whose definitions
17193 aren't available at the time this was called */
17194 STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
17195 than just initialized. */
17196 SV* properties = NULL; /* Code points that match \p{} \P{} */
17197 SV* posixes = NULL; /* Code points that match classes like [:word:],
17198 extended beyond the Latin1 range. These have to
17199 be kept separate from other code points for much
17200 of this function because their handling is
17201 different under /i, and for most classes under
17202 /d as well */
17203 SV* nposixes = NULL; /* Similarly for [:^word:]. These are kept
17204 separate for a while from the non-complemented
17205 versions because of complications with /d
17206 matching */
17207 SV* simple_posixes = NULL; /* But under some conditions, the classes can be
17208 treated more simply than the general case,
17209 leading to less compilation and execution
17210 work */
17211 UV element_count = 0; /* Number of distinct elements in the class.
17212 Optimizations may be possible if this is tiny */
17213 AV * multi_char_matches = NULL; /* Code points that fold to more than one
17214 character; used under /i */
17215 UV n;
17216 char * stop_ptr = RExC_end; /* where to stop parsing */
17217
17218 /* ignore unescaped whitespace? */
17219 const bool skip_white = cBOOL( ret_invlist
17220 || (RExC_flags & RXf_PMf_EXTENDED_MORE));
17221
17222 /* inversion list of code points this node matches only when the target
17223 * string is in UTF-8. These are all non-ASCII, < 256. (Because is under
17224 * /d) */
17225 SV* upper_latin1_only_utf8_matches = NULL;
17226
17227 /* Inversion list of code points this node matches regardless of things
17228 * like locale, folding, utf8ness of the target string */
17229 SV* cp_list = NULL;
17230
17231 /* Like cp_list, but code points on this list need to be checked for things
17232 * that fold to/from them under /i */
17233 SV* cp_foldable_list = NULL;
17234
17235 /* Like cp_list, but code points on this list are valid only when the
17236 * runtime locale is UTF-8 */
17237 SV* only_utf8_locale_list = NULL;
17238
17239 /* In a range, if one of the endpoints is non-character-set portable,
17240 * meaning that it hard-codes a code point that may mean a different
17241 * charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a
17242 * mnemonic '\t' which each mean the same character no matter which
17243 * character set the platform is on. */
17244 unsigned int non_portable_endpoint = 0;
17245
17246 /* Is the range unicode? which means on a platform that isn't 1-1 native
17247 * to Unicode (i.e. non-ASCII), each code point in it should be considered
17248 * to be a Unicode value. */
17249 bool unicode_range = FALSE;
17250 bool invert = FALSE; /* Is this class to be complemented */
17251
17252 bool warn_super = ALWAYS_WARN_SUPER;
17253
17254 const char * orig_parse = RExC_parse;
17255
17256 /* This variable is used to mark where the end in the input is of something
17257 * that looks like a POSIX construct but isn't. During the parse, when
17258 * something looks like it could be such a construct is encountered, it is
17259 * checked for being one, but not if we've already checked this area of the
17260 * input. Only after this position is reached do we check again */
17261 char *not_posix_region_end = RExC_parse - 1;
17262
17263 AV* posix_warnings = NULL;
17264 const bool do_posix_warnings = ckWARN(WARN_REGEXP);
17265 U8 op = END; /* The returned node-type, initialized to an impossible
17266 one. */
17267 U8 anyof_flags = 0; /* flag bits if the node is an ANYOF-type */
17268 U32 posixl = 0; /* bit field of posix classes matched under /l */
17269
17270
17271/* Flags as to what things aren't knowable until runtime. (Note that these are
17272 * mutually exclusive.) */
17273#define HAS_USER_DEFINED_PROPERTY 0x01 /* /u any user-defined properties that
17274 haven't been defined as of yet */
17275#define HAS_D_RUNTIME_DEPENDENCY 0x02 /* /d if the target being matched is
17276 UTF-8 or not */
17277#define HAS_L_RUNTIME_DEPENDENCY 0x04 /* /l what the posix classes match and
17278 what gets folded */
17279 U32 has_runtime_dependency = 0; /* OR of the above flags */
17280
17281 GET_RE_DEBUG_FLAGS_DECL;
17282
17283 PERL_ARGS_ASSERT_REGCLASS;
17284#ifndef DEBUGGING
17285 PERL_UNUSED_ARG(depth);
17286#endif
17287
17288
17289 /* If wants an inversion list returned, we can't optimize to something
17290 * else. */
17291 if (ret_invlist) {
17292 optimizable = FALSE;
17293 }
17294
17295 DEBUG_PARSE("clas");
17296
17297#if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */ \
17298 || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0 \
17299 && UNICODE_DOT_DOT_VERSION == 0)
17300 allow_mutiple_chars = FALSE;
17301#endif
17302
17303 /* We include the /i status at the beginning of this so that we can
17304 * know it at runtime */
17305 listsv = sv_2mortal(Perl_newSVpvf(aTHX_ "#%d\n", cBOOL(FOLD)));
17306 initial_listsv_len = SvCUR(listsv);
17307 SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated. */
17308
17309 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17310
17311 assert(RExC_parse <= RExC_end);
17312
17313 if (UCHARAT(RExC_parse) == '^') { /* Complement the class */
17314 RExC_parse++;
17315 invert = TRUE;
17316 allow_mutiple_chars = FALSE;
17317 MARK_NAUGHTY(1);
17318 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17319 }
17320
17321 /* Check that they didn't say [:posix:] instead of [[:posix:]] */
17322 if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) {
17323 int maybe_class = handle_possible_posix(pRExC_state,
17324 RExC_parse,
17325 &not_posix_region_end,
17326 NULL,
17327 TRUE /* checking only */);
17328 if (maybe_class >= OOB_NAMEDCLASS && do_posix_warnings) {
17329 ckWARN4reg(not_posix_region_end,
17330 "POSIX syntax [%c %c] belongs inside character classes%s",
17331 *RExC_parse, *RExC_parse,
17332 (maybe_class == OOB_NAMEDCLASS)
17333 ? ((POSIXCC_NOTYET(*RExC_parse))
17334 ? " (but this one isn't implemented)"
17335 : " (but this one isn't fully valid)")
17336 : ""
17337 );
17338 }
17339 }
17340
17341 /* If the caller wants us to just parse a single element, accomplish this
17342 * by faking the loop ending condition */
17343 if (stop_at_1 && RExC_end > RExC_parse) {
17344 stop_ptr = RExC_parse + 1;
17345 }
17346
17347 /* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */
17348 if (UCHARAT(RExC_parse) == ']')
17349 goto charclassloop;
17350
17351 while (1) {
17352
17353 if ( posix_warnings
17354 && av_tindex_skip_len_mg(posix_warnings) >= 0
17355 && RExC_parse > not_posix_region_end)
17356 {
17357 /* Warnings about posix class issues are considered tentative until
17358 * we are far enough along in the parse that we can no longer
17359 * change our mind, at which point we output them. This is done
17360 * each time through the loop so that a later class won't zap them
17361 * before they have been dealt with. */
17362 output_posix_warnings(pRExC_state, posix_warnings);
17363 }
17364
17365 if (RExC_parse >= stop_ptr) {
17366 break;
17367 }
17368
17369 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17370
17371 if (UCHARAT(RExC_parse) == ']') {
17372 break;
17373 }
17374
17375 charclassloop:
17376
17377 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
17378 save_value = value;
17379 save_prevvalue = prevvalue;
17380
17381 if (!range) {
17382 rangebegin = RExC_parse;
17383 element_count++;
17384 non_portable_endpoint = 0;
17385 }
17386 if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) {
17387 value = utf8n_to_uvchr((U8*)RExC_parse,
17388 RExC_end - RExC_parse,
17389 &numlen, UTF8_ALLOW_DEFAULT);
17390 RExC_parse += numlen;
17391 }
17392 else
17393 value = UCHARAT(RExC_parse++);
17394
17395 if (value == '[') {
17396 char * posix_class_end;
17397 namedclass = handle_possible_posix(pRExC_state,
17398 RExC_parse,
17399 &posix_class_end,
17400 do_posix_warnings ? &posix_warnings : NULL,
17401 FALSE /* die if error */);
17402 if (namedclass > OOB_NAMEDCLASS) {
17403
17404 /* If there was an earlier attempt to parse this particular
17405 * posix class, and it failed, it was a false alarm, as this
17406 * successful one proves */
17407 if ( posix_warnings
17408 && av_tindex_skip_len_mg(posix_warnings) >= 0
17409 && not_posix_region_end >= RExC_parse
17410 && not_posix_region_end <= posix_class_end)
17411 {
17412 av_undef(posix_warnings);
17413 }
17414
17415 RExC_parse = posix_class_end;
17416 }
17417 else if (namedclass == OOB_NAMEDCLASS) {
17418 not_posix_region_end = posix_class_end;
17419 }
17420 else {
17421 namedclass = OOB_NAMEDCLASS;
17422 }
17423 }
17424 else if ( RExC_parse - 1 > not_posix_region_end
17425 && MAYBE_POSIXCC(value))
17426 {
17427 (void) handle_possible_posix(
17428 pRExC_state,
17429 RExC_parse - 1, /* -1 because parse has already been
17430 advanced */
17431 &not_posix_region_end,
17432 do_posix_warnings ? &posix_warnings : NULL,
17433 TRUE /* checking only */);
17434 }
17435 else if ( strict && ! skip_white
17436 && ( _generic_isCC(value, _CC_VERTSPACE)
17437 || is_VERTWS_cp_high(value)))
17438 {
17439 vFAIL("Literal vertical space in [] is illegal except under /x");
17440 }
17441 else if (value == '\\') {
17442 /* Is a backslash; get the code point of the char after it */
17443
17444 if (RExC_parse >= RExC_end) {
17445 vFAIL("Unmatched [");
17446 }
17447
17448 if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) {
17449 value = utf8n_to_uvchr((U8*)RExC_parse,
17450 RExC_end - RExC_parse,
17451 &numlen, UTF8_ALLOW_DEFAULT);
17452 RExC_parse += numlen;
17453 }
17454 else
17455 value = UCHARAT(RExC_parse++);
17456
17457 /* Some compilers cannot handle switching on 64-bit integer
17458 * values, therefore value cannot be an UV. Yes, this will
17459 * be a problem later if we want switch on Unicode.
17460 * A similar issue a little bit later when switching on
17461 * namedclass. --jhi */
17462
17463 /* If the \ is escaping white space when white space is being
17464 * skipped, it means that that white space is wanted literally, and
17465 * is already in 'value'. Otherwise, need to translate the escape
17466 * into what it signifies. */
17467 if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) {
17468 const char * message;
17469 U32 packed_warn;
17470 U8 grok_c_char;
17471
17472 case 'w': namedclass = ANYOF_WORDCHAR; break;
17473 case 'W': namedclass = ANYOF_NWORDCHAR; break;
17474 case 's': namedclass = ANYOF_SPACE; break;
17475 case 'S': namedclass = ANYOF_NSPACE; break;
17476 case 'd': namedclass = ANYOF_DIGIT; break;
17477 case 'D': namedclass = ANYOF_NDIGIT; break;
17478 case 'v': namedclass = ANYOF_VERTWS; break;
17479 case 'V': namedclass = ANYOF_NVERTWS; break;
17480 case 'h': namedclass = ANYOF_HORIZWS; break;
17481 case 'H': namedclass = ANYOF_NHORIZWS; break;
17482 case 'N': /* Handle \N{NAME} in class */
17483 {
17484 const char * const backslash_N_beg = RExC_parse - 2;
17485 int cp_count;
17486
17487 if (! grok_bslash_N(pRExC_state,
17488 NULL, /* No regnode */
17489 &value, /* Yes single value */
17490 &cp_count, /* Multiple code pt count */
17491 flagp,
17492 strict,
17493 depth)
17494 ) {
17495
17496 if (*flagp & NEED_UTF8)
17497 FAIL("panic: grok_bslash_N set NEED_UTF8");
17498
17499 RETURN_FAIL_ON_RESTART_FLAGP(flagp);
17500
17501 if (cp_count < 0) {
17502 vFAIL("\\N in a character class must be a named character: \\N{...}");
17503 }
17504 else if (cp_count == 0) {
17505 ckWARNreg(RExC_parse,
17506 "Ignoring zero length \\N{} in character class");
17507 }
17508 else { /* cp_count > 1 */
17509 assert(cp_count > 1);
17510 if (! RExC_in_multi_char_class) {
17511 if ( ! allow_mutiple_chars
17512 || invert
17513 || range
17514 || *RExC_parse == '-')
17515 {
17516 if (strict) {
17517 RExC_parse--;
17518 vFAIL("\\N{} here is restricted to one character");
17519 }
17520 ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class");
17521 break; /* <value> contains the first code
17522 point. Drop out of the switch to
17523 process it */
17524 }
17525 else {
17526 SV * multi_char_N = newSVpvn(backslash_N_beg,
17527 RExC_parse - backslash_N_beg);
17528 multi_char_matches
17529 = add_multi_match(multi_char_matches,
17530 multi_char_N,
17531 cp_count);
17532 }
17533 }
17534 } /* End of cp_count != 1 */
17535
17536 /* This element should not be processed further in this
17537 * class */
17538 element_count--;
17539 value = save_value;
17540 prevvalue = save_prevvalue;
17541 continue; /* Back to top of loop to get next char */
17542 }
17543
17544 /* Here, is a single code point, and <value> contains it */
17545 unicode_range = TRUE; /* \N{} are Unicode */
17546 }
17547 break;
17548 case 'p':
17549 case 'P':
17550 {
17551 char *e;
17552
17553 if (RExC_pm_flags & PMf_WILDCARD) {
17554 RExC_parse++;
17555 /* diag_listed_as: Use of %s is not allowed in Unicode
17556 property wildcard subpatterns in regex; marked by <--
17557 HERE in m/%s/ */
17558 vFAIL3("Use of '\\%c%c' is not allowed in Unicode property"
17559 " wildcard subpatterns", (char) value, *(RExC_parse - 1));
17560 }
17561
17562 /* \p means they want Unicode semantics */
17563 REQUIRE_UNI_RULES(flagp, 0);
17564
17565 if (RExC_parse >= RExC_end)
17566 vFAIL2("Empty \\%c", (U8)value);
17567 if (*RExC_parse == '{') {
17568 const U8 c = (U8)value;
17569 e = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
17570 if (!e) {
17571 RExC_parse++;
17572 vFAIL2("Missing right brace on \\%c{}", c);
17573 }
17574
17575 RExC_parse++;
17576
17577 /* White space is allowed adjacent to the braces and after
17578 * any '^', even when not under /x */
17579 while (isSPACE(*RExC_parse)) {
17580 RExC_parse++;
17581 }
17582
17583 if (UCHARAT(RExC_parse) == '^') {
17584
17585 /* toggle. (The rhs xor gets the single bit that
17586 * differs between P and p; the other xor inverts just
17587 * that bit) */
17588 value ^= 'P' ^ 'p';
17589
17590 RExC_parse++;
17591 while (isSPACE(*RExC_parse)) {
17592 RExC_parse++;
17593 }
17594 }
17595
17596 if (e == RExC_parse)
17597 vFAIL2("Empty \\%c{}", c);
17598
17599 n = e - RExC_parse;
17600 while (isSPACE(*(RExC_parse + n - 1)))
17601 n--;
17602
17603 } /* The \p isn't immediately followed by a '{' */
17604 else if (! isALPHA(*RExC_parse)) {
17605 RExC_parse += (UTF)
17606 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
17607 : 1;
17608 vFAIL2("Character following \\%c must be '{' or a "
17609 "single-character Unicode property name",
17610 (U8) value);
17611 }
17612 else {
17613 e = RExC_parse;
17614 n = 1;
17615 }
17616 {
17617 char* name = RExC_parse;
17618
17619 /* Any message returned about expanding the definition */
17620 SV* msg = newSVpvs_flags("", SVs_TEMP);
17621
17622 /* If set TRUE, the property is user-defined as opposed to
17623 * official Unicode */
17624 bool user_defined = FALSE;
17625
17626 SV * prop_definition = parse_uniprop_string(
17627 name, n, UTF, FOLD,
17628 FALSE, /* This is compile-time */
17629
17630 /* We can't defer this defn when
17631 * the full result is required in
17632 * this call */
17633 ! cBOOL(ret_invlist),
17634
17635 &user_defined,
17636 msg,
17637 0 /* Base level */
17638 );
17639 if (SvCUR(msg)) { /* Assumes any error causes a msg */
17640 assert(prop_definition == NULL);
17641 RExC_parse = e + 1;
17642 if (SvUTF8(msg)) { /* msg being UTF-8 makes the whole
17643 thing so, or else the display is
17644 mojibake */
17645 RExC_utf8 = TRUE;
17646 }
17647 /* diag_listed_as: Can't find Unicode property definition "%s" in regex; marked by <-- HERE in m/%s/ */
17648 vFAIL2utf8f("%" UTF8f, UTF8fARG(SvUTF8(msg),
17649 SvCUR(msg), SvPVX(msg)));
17650 }
17651
17652 if (! is_invlist(prop_definition)) {
17653
17654 /* Here, the definition isn't known, so we have gotten
17655 * returned a string that will be evaluated if and when
17656 * encountered at runtime. We add it to the list of
17657 * such properties, along with whether it should be
17658 * complemented or not */
17659 if (value == 'P') {
17660 sv_catpvs(listsv, "!");
17661 }
17662 else {
17663 sv_catpvs(listsv, "+");
17664 }
17665 sv_catsv(listsv, prop_definition);
17666
17667 has_runtime_dependency |= HAS_USER_DEFINED_PROPERTY;
17668
17669 /* We don't know yet what this matches, so have to flag
17670 * it */
17671 anyof_flags |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
17672 }
17673 else {
17674 assert (prop_definition && is_invlist(prop_definition));
17675
17676 /* Here we do have the complete property definition
17677 *
17678 * Temporary workaround for [perl #133136]. For this
17679 * precise input that is in the .t that is failing,
17680 * load utf8.pm, which is what the test wants, so that
17681 * that .t passes */
17682 if ( memEQs(RExC_start, e + 1 - RExC_start,
17683 "foo\\p{Alnum}")
17684 && ! hv_common(GvHVn(PL_incgv),
17685 NULL,
17686 "utf8.pm", sizeof("utf8.pm") - 1,
17687 0, HV_FETCH_ISEXISTS, NULL, 0))
17688 {
17689 require_pv("utf8.pm");
17690 }
17691
17692 if (! user_defined &&
17693 /* We warn on matching an above-Unicode code point
17694 * if the match would return true, except don't
17695 * warn for \p{All}, which has exactly one element
17696 * = 0 */
17697 (_invlist_contains_cp(prop_definition, 0x110000)
17698 && (! (_invlist_len(prop_definition) == 1
17699 && *invlist_array(prop_definition) == 0))))
17700 {
17701 warn_super = TRUE;
17702 }
17703
17704 /* Invert if asking for the complement */
17705 if (value == 'P') {
17706 _invlist_union_complement_2nd(properties,
17707 prop_definition,
17708 &properties);
17709 }
17710 else {
17711 _invlist_union(properties, prop_definition, &properties);
17712 }
17713 }
17714 }
17715
17716 RExC_parse = e + 1;
17717 namedclass = ANYOF_UNIPROP; /* no official name, but it's
17718 named */
17719 }
17720 break;
17721 case 'n': value = '\n'; break;
17722 case 'r': value = '\r'; break;
17723 case 't': value = '\t'; break;
17724 case 'f': value = '\f'; break;
17725 case 'b': value = '\b'; break;
17726 case 'e': value = ESC_NATIVE; break;
17727 case 'a': value = '\a'; break;
17728 case 'o':
17729 RExC_parse--; /* function expects to be pointed at the 'o' */
17730 if (! grok_bslash_o(&RExC_parse,
17731 RExC_end,
17732 &value,
17733 &message,
17734 &packed_warn,
17735 strict,
17736 cBOOL(range), /* MAX_UV allowed for range
17737 upper limit */
17738 UTF))
17739 {
17740 vFAIL(message);
17741 }
17742 else if (message && TO_OUTPUT_WARNINGS(RExC_parse)) {
17743 warn_non_literal_string(RExC_parse, packed_warn, message);
17744 }
17745
17746 if (value < 256) {
17747 non_portable_endpoint++;
17748 }
17749 break;
17750 case 'x':
17751 RExC_parse--; /* function expects to be pointed at the 'x' */
17752 if (! grok_bslash_x(&RExC_parse,
17753 RExC_end,
17754 &value,
17755 &message,
17756 &packed_warn,
17757 strict,
17758 cBOOL(range), /* MAX_UV allowed for range
17759 upper limit */
17760 UTF))
17761 {
17762 vFAIL(message);
17763 }
17764 else if (message && TO_OUTPUT_WARNINGS(RExC_parse)) {
17765 warn_non_literal_string(RExC_parse, packed_warn, message);
17766 }
17767
17768 if (value < 256) {
17769 non_portable_endpoint++;
17770 }
17771 break;
17772 case 'c':
17773 if (! grok_bslash_c(*RExC_parse, &grok_c_char, &message,
17774 &packed_warn))
17775 {
17776 /* going to die anyway; point to exact spot of
17777 * failure */
17778 RExC_parse += (UTF)
17779 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
17780 : 1;
17781 vFAIL(message);
17782 }
17783
17784 value = grok_c_char;
17785 RExC_parse++;
17786 if (message && TO_OUTPUT_WARNINGS(RExC_parse)) {
17787 warn_non_literal_string(RExC_parse, packed_warn, message);
17788 }
17789
17790 non_portable_endpoint++;
17791 break;
17792 case '0': case '1': case '2': case '3': case '4':
17793 case '5': case '6': case '7':
17794 {
17795 /* Take 1-3 octal digits */
17796 I32 flags = PERL_SCAN_SILENT_ILLDIGIT
17797 | PERL_SCAN_NOTIFY_ILLDIGIT;
17798 numlen = (strict) ? 4 : 3;
17799 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
17800 RExC_parse += numlen;
17801 if (numlen != 3) {
17802 if (strict) {
17803 RExC_parse += (UTF)
17804 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
17805 : 1;
17806 vFAIL("Need exactly 3 octal digits");
17807 }
17808 else if ( (flags & PERL_SCAN_NOTIFY_ILLDIGIT)
17809 && RExC_parse < RExC_end
17810 && isDIGIT(*RExC_parse)
17811 && ckWARN(WARN_REGEXP))
17812 {
17813 reg_warn_non_literal_string(
17814 RExC_parse + 1,
17815 form_alien_digit_msg(8, numlen, RExC_parse,
17816 RExC_end, UTF, FALSE));
17817 }
17818 }
17819 if (value < 256) {
17820 non_portable_endpoint++;
17821 }
17822 break;
17823 }
17824 default:
17825 /* Allow \_ to not give an error */
17826 if (isWORDCHAR(value) && value != '_') {
17827 if (strict) {
17828 vFAIL2("Unrecognized escape \\%c in character class",
17829 (int)value);
17830 }
17831 else {
17832 ckWARN2reg(RExC_parse,
17833 "Unrecognized escape \\%c in character class passed through",
17834 (int)value);
17835 }
17836 }
17837 break;
17838 } /* End of switch on char following backslash */
17839 } /* end of handling backslash escape sequences */
17840
17841 /* Here, we have the current token in 'value' */
17842
17843 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
17844 U8 classnum;
17845
17846 /* a bad range like a-\d, a-[:digit:]. The '-' is taken as a
17847 * literal, as is the character that began the false range, i.e.
17848 * the 'a' in the examples */
17849 if (range) {
17850 const int w = (RExC_parse >= rangebegin)
17851 ? RExC_parse - rangebegin
17852 : 0;
17853 if (strict) {
17854 vFAIL2utf8f(
17855 "False [] range \"%" UTF8f "\"",
17856 UTF8fARG(UTF, w, rangebegin));
17857 }
17858 else {
17859 ckWARN2reg(RExC_parse,
17860 "False [] range \"%" UTF8f "\"",
17861 UTF8fARG(UTF, w, rangebegin));
17862 cp_list = add_cp_to_invlist(cp_list, '-');
17863 cp_foldable_list = add_cp_to_invlist(cp_foldable_list,
17864 prevvalue);
17865 }
17866
17867 range = 0; /* this was not a true range */
17868 element_count += 2; /* So counts for three values */
17869 }
17870
17871 classnum = namedclass_to_classnum(namedclass);
17872
17873 if (LOC && namedclass < ANYOF_POSIXL_MAX
17874#ifndef HAS_ISASCII
17875 && classnum != _CC_ASCII
17876#endif
17877 ) {
17878 SV* scratch_list = NULL;
17879
17880 /* What the Posix classes (like \w, [:space:]) match isn't
17881 * generally knowable under locale until actual match time. A
17882 * special node is used for these which has extra space for a
17883 * bitmap, with a bit reserved for each named class that is to
17884 * be matched against. (This isn't needed for \p{} and
17885 * pseudo-classes, as they are not affected by locale, and
17886 * hence are dealt with separately.) However, if a named class
17887 * and its complement are both present, then it matches
17888 * everything, and there is no runtime dependency. Odd numbers
17889 * are the complements of the next lower number, so xor works.
17890 * (Note that something like [\w\D] should match everything,
17891 * because \d should be a proper subset of \w. But rather than
17892 * trust that the locale is well behaved, we leave this to
17893 * runtime to sort out) */
17894 if (POSIXL_TEST(posixl, namedclass ^ 1)) {
17895 cp_list = _add_range_to_invlist(cp_list, 0, UV_MAX);
17896 POSIXL_ZERO(posixl);
17897 has_runtime_dependency &= ~HAS_L_RUNTIME_DEPENDENCY;
17898 anyof_flags &= ~ANYOF_MATCHES_POSIXL;
17899 continue; /* We could ignore the rest of the class, but
17900 best to parse it for any errors */
17901 }
17902 else { /* Here, isn't the complement of any already parsed
17903 class */
17904 POSIXL_SET(posixl, namedclass);
17905 has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
17906 anyof_flags |= ANYOF_MATCHES_POSIXL;
17907
17908 /* The above-Latin1 characters are not subject to locale
17909 * rules. Just add them to the unconditionally-matched
17910 * list */
17911
17912 /* Get the list of the above-Latin1 code points this
17913 * matches */
17914 _invlist_intersection_maybe_complement_2nd(PL_AboveLatin1,
17915 PL_XPosix_ptrs[classnum],
17916
17917 /* Odd numbers are complements,
17918 * like NDIGIT, NASCII, ... */
17919 namedclass % 2 != 0,
17920 &scratch_list);
17921 /* Checking if 'cp_list' is NULL first saves an extra
17922 * clone. Its reference count will be decremented at the
17923 * next union, etc, or if this is the only instance, at the
17924 * end of the routine */
17925 if (! cp_list) {
17926 cp_list = scratch_list;
17927 }
17928 else {
17929 _invlist_union(cp_list, scratch_list, &cp_list);
17930 SvREFCNT_dec_NN(scratch_list);
17931 }
17932 continue; /* Go get next character */
17933 }
17934 }
17935 else {
17936
17937 /* Here, is not /l, or is a POSIX class for which /l doesn't
17938 * matter (or is a Unicode property, which is skipped here). */
17939 if (namedclass >= ANYOF_POSIXL_MAX) { /* If a special class */
17940 if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */
17941
17942 /* Here, should be \h, \H, \v, or \V. None of /d, /i
17943 * nor /l make a difference in what these match,
17944 * therefore we just add what they match to cp_list. */
17945 if (classnum != _CC_VERTSPACE) {
17946 assert( namedclass == ANYOF_HORIZWS
17947 || namedclass == ANYOF_NHORIZWS);
17948
17949 /* It turns out that \h is just a synonym for
17950 * XPosixBlank */
17951 classnum = _CC_BLANK;
17952 }
17953
17954 _invlist_union_maybe_complement_2nd(
17955 cp_list,
17956 PL_XPosix_ptrs[classnum],
17957 namedclass % 2 != 0, /* Complement if odd
17958 (NHORIZWS, NVERTWS)
17959 */
17960 &cp_list);
17961 }
17962 }
17963 else if ( AT_LEAST_UNI_SEMANTICS
17964 || classnum == _CC_ASCII
17965 || (DEPENDS_SEMANTICS && ( classnum == _CC_DIGIT
17966 || classnum == _CC_XDIGIT)))
17967 {
17968 /* We usually have to worry about /d affecting what POSIX
17969 * classes match, with special code needed because we won't
17970 * know until runtime what all matches. But there is no
17971 * extra work needed under /u and /a; and [:ascii:] is
17972 * unaffected by /d; and :digit: and :xdigit: don't have
17973 * runtime differences under /d. So we can special case
17974 * these, and avoid some extra work below, and at runtime.
17975 * */
17976 _invlist_union_maybe_complement_2nd(
17977 simple_posixes,
17978 ((AT_LEAST_ASCII_RESTRICTED)
17979 ? PL_Posix_ptrs[classnum]
17980 : PL_XPosix_ptrs[classnum]),
17981 namedclass % 2 != 0,
17982 &simple_posixes);
17983 }
17984 else { /* Garden variety class. If is NUPPER, NALPHA, ...
17985 complement and use nposixes */
17986 SV** posixes_ptr = namedclass % 2 == 0
17987 ? &posixes
17988 : &nposixes;
17989 _invlist_union_maybe_complement_2nd(
17990 *posixes_ptr,
17991 PL_XPosix_ptrs[classnum],
17992 namedclass % 2 != 0,
17993 posixes_ptr);
17994 }
17995 }
17996 } /* end of namedclass \blah */
17997
17998 SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17999
18000 /* If 'range' is set, 'value' is the ending of a range--check its
18001 * validity. (If value isn't a single code point in the case of a
18002 * range, we should have figured that out above in the code that
18003 * catches false ranges). Later, we will handle each individual code
18004 * point in the range. If 'range' isn't set, this could be the
18005 * beginning of a range, so check for that by looking ahead to see if
18006 * the next real character to be processed is the range indicator--the
18007 * minus sign */
18008
18009 if (range) {
18010#ifdef EBCDIC
18011 /* For unicode ranges, we have to test that the Unicode as opposed
18012 * to the native values are not decreasing. (Above 255, there is
18013 * no difference between native and Unicode) */
18014 if (unicode_range && prevvalue < 255 && value < 255) {
18015 if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) {
18016 goto backwards_range;
18017 }
18018 }
18019 else
18020#endif
18021 if (prevvalue > value) /* b-a */ {
18022 int w;
18023#ifdef EBCDIC
18024 backwards_range:
18025#endif
18026 w = RExC_parse - rangebegin;
18027 vFAIL2utf8f(
18028 "Invalid [] range \"%" UTF8f "\"",
18029 UTF8fARG(UTF, w, rangebegin));
18030 NOT_REACHED; /* NOTREACHED */
18031 }
18032 }
18033 else {
18034 prevvalue = value; /* save the beginning of the potential range */
18035 if (! stop_at_1 /* Can't be a range if parsing just one thing */
18036 && *RExC_parse == '-')
18037 {
18038 char* next_char_ptr = RExC_parse + 1;
18039
18040 /* Get the next real char after the '-' */
18041 SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr);
18042
18043 /* If the '-' is at the end of the class (just before the ']',
18044 * it is a literal minus; otherwise it is a range */
18045 if (next_char_ptr < RExC_end && *next_char_ptr != ']') {
18046 RExC_parse = next_char_ptr;
18047
18048 /* a bad range like \w-, [:word:]- ? */
18049 if (namedclass > OOB_NAMEDCLASS) {
18050 if (strict || ckWARN(WARN_REGEXP)) {
18051 const int w = RExC_parse >= rangebegin
18052 ? RExC_parse - rangebegin
18053 : 0;
18054 if (strict) {
18055 vFAIL4("False [] range \"%*.*s\"",
18056 w, w, rangebegin);
18057 }
18058 else {
18059 vWARN4(RExC_parse,
18060 "False [] range \"%*.*s\"",
18061 w, w, rangebegin);
18062 }
18063 }
18064 cp_list = add_cp_to_invlist(cp_list, '-');
18065 element_count++;
18066 } else
18067 range = 1; /* yeah, it's a range! */
18068 continue; /* but do it the next time */
18069 }
18070 }
18071 }
18072
18073 if (namedclass > OOB_NAMEDCLASS) {
18074 continue;
18075 }
18076
18077 /* Here, we have a single value this time through the loop, and
18078 * <prevvalue> is the beginning of the range, if any; or <value> if
18079 * not. */
18080
18081 /* non-Latin1 code point implies unicode semantics. */
18082 if (value > 255) {
18083 if (value > MAX_LEGAL_CP && ( value != UV_MAX
18084 || prevvalue > MAX_LEGAL_CP))
18085 {
18086 vFAIL(form_cp_too_large_msg(16, NULL, 0, value));
18087 }
18088 REQUIRE_UNI_RULES(flagp, 0);
18089 if ( ! silence_non_portable
18090 && UNICODE_IS_PERL_EXTENDED(value)
18091 && TO_OUTPUT_WARNINGS(RExC_parse))
18092 {
18093 ckWARN2_non_literal_string(RExC_parse,
18094 packWARN(WARN_PORTABLE),
18095 PL_extended_cp_format,
18096 value);
18097 }
18098 }
18099
18100 /* Ready to process either the single value, or the completed range.
18101 * For single-valued non-inverted ranges, we consider the possibility
18102 * of multi-char folds. (We made a conscious decision to not do this
18103 * for the other cases because it can often lead to non-intuitive
18104 * results. For example, you have the peculiar case that:
18105 * "s s" =~ /^[^\xDF]+$/i => Y
18106 * "ss" =~ /^[^\xDF]+$/i => N
18107 *
18108 * See [perl #89750] */
18109 if (FOLD && allow_mutiple_chars && value == prevvalue) {
18110 if ( value == LATIN_SMALL_LETTER_SHARP_S
18111 || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
18112 value)))
18113 {
18114 /* Here <value> is indeed a multi-char fold. Get what it is */
18115
18116 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
18117 STRLEN foldlen;
18118
18119 UV folded = _to_uni_fold_flags(
18120 value,
18121 foldbuf,
18122 &foldlen,
18123 FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED
18124 ? FOLD_FLAGS_NOMIX_ASCII
18125 : 0)
18126 );
18127
18128 /* Here, <folded> should be the first character of the
18129 * multi-char fold of <value>, with <foldbuf> containing the
18130 * whole thing. But, if this fold is not allowed (because of
18131 * the flags), <fold> will be the same as <value>, and should
18132 * be processed like any other character, so skip the special
18133 * handling */
18134 if (folded != value) {
18135
18136 /* Skip if we are recursed, currently parsing the class
18137 * again. Otherwise add this character to the list of
18138 * multi-char folds. */
18139 if (! RExC_in_multi_char_class) {
18140 STRLEN cp_count = utf8_length(foldbuf,
18141 foldbuf + foldlen);
18142 SV* multi_fold = sv_2mortal(newSVpvs(""));
18143
18144 Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%" UVXf "}", value);
18145
18146 multi_char_matches
18147 = add_multi_match(multi_char_matches,
18148 multi_fold,
18149 cp_count);
18150
18151 }
18152
18153 /* This element should not be processed further in this
18154 * class */
18155 element_count--;
18156 value = save_value;
18157 prevvalue = save_prevvalue;
18158 continue;
18159 }
18160 }
18161 }
18162
18163 if (strict && ckWARN(WARN_REGEXP)) {
18164 if (range) {
18165
18166 /* If the range starts above 255, everything is portable and
18167 * likely to be so for any forseeable character set, so don't
18168 * warn. */
18169 if (unicode_range && non_portable_endpoint && prevvalue < 256) {
18170 vWARN(RExC_parse, "Both or neither range ends should be Unicode");
18171 }
18172 else if (prevvalue != value) {
18173
18174 /* Under strict, ranges that stop and/or end in an ASCII
18175 * printable should have each end point be a portable value
18176 * for it (preferably like 'A', but we don't warn if it is
18177 * a (portable) Unicode name or code point), and the range
18178 * must be be all digits or all letters of the same case.
18179 * Otherwise, the range is non-portable and unclear as to
18180 * what it contains */
18181 if ( (isPRINT_A(prevvalue) || isPRINT_A(value))
18182 && ( non_portable_endpoint
18183 || ! ( (isDIGIT_A(prevvalue) && isDIGIT_A(value))
18184 || (isLOWER_A(prevvalue) && isLOWER_A(value))
18185 || (isUPPER_A(prevvalue) && isUPPER_A(value))
18186 ))) {
18187 vWARN(RExC_parse, "Ranges of ASCII printables should"
18188 " be some subset of \"0-9\","
18189 " \"A-Z\", or \"a-z\"");
18190 }
18191 else if (prevvalue >= FIRST_NON_ASCII_DECIMAL_DIGIT) {
18192 SSize_t index_start;
18193 SSize_t index_final;
18194
18195 /* But the nature of Unicode and languages mean we
18196 * can't do the same checks for above-ASCII ranges,
18197 * except in the case of digit ones. These should
18198 * contain only digits from the same group of 10. The
18199 * ASCII case is handled just above. Hence here, the
18200 * range could be a range of digits. First some
18201 * unlikely special cases. Grandfather in that a range
18202 * ending in 19DA (NEW TAI LUE THAM DIGIT ONE) is bad
18203 * if its starting value is one of the 10 digits prior
18204 * to it. This is because it is an alternate way of
18205 * writing 19D1, and some people may expect it to be in
18206 * that group. But it is bad, because it won't give
18207 * the expected results. In Unicode 5.2 it was
18208 * considered to be in that group (of 11, hence), but
18209 * this was fixed in the next version */
18210
18211 if (UNLIKELY(value == 0x19DA && prevvalue >= 0x19D0)) {
18212 goto warn_bad_digit_range;
18213 }
18214 else if (UNLIKELY( prevvalue >= 0x1D7CE
18215 && value <= 0x1D7FF))
18216 {
18217 /* This is the only other case currently in Unicode
18218 * where the algorithm below fails. The code
18219 * points just above are the end points of a single
18220 * range containing only decimal digits. It is 5
18221 * different series of 0-9. All other ranges of
18222 * digits currently in Unicode are just a single
18223 * series. (And mktables will notify us if a later
18224 * Unicode version breaks this.)
18225 *
18226 * If the range being checked is at most 9 long,
18227 * and the digit values represented are in
18228 * numerical order, they are from the same series.
18229 * */
18230 if ( value - prevvalue > 9
18231 || ((( value - 0x1D7CE) % 10)
18232 <= (prevvalue - 0x1D7CE) % 10))
18233 {
18234 goto warn_bad_digit_range;
18235 }
18236 }
18237 else {
18238
18239 /* For all other ranges of digits in Unicode, the
18240 * algorithm is just to check if both end points
18241 * are in the same series, which is the same range.
18242 * */
18243 index_start = _invlist_search(
18244 PL_XPosix_ptrs[_CC_DIGIT],
18245 prevvalue);
18246
18247 /* Warn if the range starts and ends with a digit,
18248 * and they are not in the same group of 10. */
18249 if ( index_start >= 0
18250 && ELEMENT_RANGE_MATCHES_INVLIST(index_start)
18251 && (index_final =
18252 _invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
18253 value)) != index_start
18254 && index_final >= 0
18255 && ELEMENT_RANGE_MATCHES_INVLIST(index_final))
18256 {
18257 warn_bad_digit_range:
18258 vWARN(RExC_parse, "Ranges of digits should be"
18259 " from the same group of"
18260 " 10");
18261 }
18262 }
18263 }
18264 }
18265 }
18266 if ((! range || prevvalue == value) && non_portable_endpoint) {
18267 if (isPRINT_A(value)) {
18268 char literal[3];
18269 unsigned d = 0;
18270 if (isBACKSLASHED_PUNCT(value)) {
18271 literal[d++] = '\\';
18272 }
18273 literal[d++] = (char) value;
18274 literal[d++] = '\0';
18275
18276 vWARN4(RExC_parse,
18277 "\"%.*s\" is more clearly written simply as \"%s\"",
18278 (int) (RExC_parse - rangebegin),
18279 rangebegin,
18280 literal
18281 );
18282 }
18283 else if (isMNEMONIC_CNTRL(value)) {
18284 vWARN4(RExC_parse,
18285 "\"%.*s\" is more clearly written simply as \"%s\"",
18286 (int) (RExC_parse - rangebegin),
18287 rangebegin,
18288 cntrl_to_mnemonic((U8) value)
18289 );
18290 }
18291 }
18292 }
18293
18294 /* Deal with this element of the class */
18295
18296#ifndef EBCDIC
18297 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18298 prevvalue, value);
18299#else
18300 /* On non-ASCII platforms, for ranges that span all of 0..255, and ones
18301 * that don't require special handling, we can just add the range like
18302 * we do for ASCII platforms */
18303 if ((UNLIKELY(prevvalue == 0) && value >= 255)
18304 || ! (prevvalue < 256
18305 && (unicode_range
18306 || (! non_portable_endpoint
18307 && ((isLOWER_A(prevvalue) && isLOWER_A(value))
18308 || (isUPPER_A(prevvalue)
18309 && isUPPER_A(value)))))))
18310 {
18311 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18312 prevvalue, value);
18313 }
18314 else {
18315 /* Here, requires special handling. This can be because it is a
18316 * range whose code points are considered to be Unicode, and so
18317 * must be individually translated into native, or because its a
18318 * subrange of 'A-Z' or 'a-z' which each aren't contiguous in
18319 * EBCDIC, but we have defined them to include only the "expected"
18320 * upper or lower case ASCII alphabetics. Subranges above 255 are
18321 * the same in native and Unicode, so can be added as a range */
18322 U8 start = NATIVE_TO_LATIN1(prevvalue);
18323 unsigned j;
18324 U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255;
18325 for (j = start; j <= end; j++) {
18326 cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j));
18327 }
18328 if (value > 255) {
18329 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18330 256, value);
18331 }
18332 }
18333#endif
18334
18335 range = 0; /* this range (if it was one) is done now */
18336 } /* End of loop through all the text within the brackets */
18337
18338 if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) {
18339 output_posix_warnings(pRExC_state, posix_warnings);
18340 }
18341
18342 /* If anything in the class expands to more than one character, we have to
18343 * deal with them by building up a substitute parse string, and recursively
18344 * calling reg() on it, instead of proceeding */
18345 if (multi_char_matches) {
18346 SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
18347 I32 cp_count;
18348 STRLEN len;
18349 char *save_end = RExC_end;
18350 char *save_parse = RExC_parse;
18351 char *save_start = RExC_start;
18352 Size_t constructed_prefix_len = 0; /* This gives the length of the
18353 constructed portion of the
18354 substitute parse. */
18355 bool first_time = TRUE; /* First multi-char occurrence doesn't get
18356 a "|" */
18357 I32 reg_flags;
18358
18359 assert(! invert);
18360 /* Only one level of recursion allowed */
18361 assert(RExC_copy_start_in_constructed == RExC_precomp);
18362
18363#if 0 /* Have decided not to deal with multi-char folds in inverted classes,
18364 because too confusing */
18365 if (invert) {
18366 sv_catpvs(substitute_parse, "(?:");
18367 }
18368#endif
18369
18370 /* Look at the longest folds first */
18371 for (cp_count = av_tindex_skip_len_mg(multi_char_matches);
18372 cp_count > 0;
18373 cp_count--)
18374 {
18375
18376 if (av_exists(multi_char_matches, cp_count)) {
18377 AV** this_array_ptr;
18378 SV* this_sequence;
18379
18380 this_array_ptr = (AV**) av_fetch(multi_char_matches,
18381 cp_count, FALSE);
18382 while ((this_sequence = av_pop(*this_array_ptr)) !=
18383 &PL_sv_undef)
18384 {
18385 if (! first_time) {
18386 sv_catpvs(substitute_parse, "|");
18387 }
18388 first_time = FALSE;
18389
18390 sv_catpv(substitute_parse, SvPVX(this_sequence));
18391 }
18392 }
18393 }
18394
18395 /* If the character class contains anything else besides these
18396 * multi-character folds, have to include it in recursive parsing */
18397 if (element_count) {
18398 sv_catpvs(substitute_parse, "|[");
18399 constructed_prefix_len = SvCUR(substitute_parse);
18400 sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
18401
18402 /* Put in a closing ']' only if not going off the end, as otherwise
18403 * we are adding something that really isn't there */
18404 if (RExC_parse < RExC_end) {
18405 sv_catpvs(substitute_parse, "]");
18406 }
18407 }
18408
18409 sv_catpvs(substitute_parse, ")");
18410#if 0
18411 if (invert) {
18412 /* This is a way to get the parse to skip forward a whole named
18413 * sequence instead of matching the 2nd character when it fails the
18414 * first */
18415 sv_catpvs(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
18416 }
18417#endif
18418
18419 /* Set up the data structure so that any errors will be properly
18420 * reported. See the comments at the definition of
18421 * REPORT_LOCATION_ARGS for details */
18422 RExC_copy_start_in_input = (char *) orig_parse;
18423 RExC_start = RExC_parse = SvPV(substitute_parse, len);
18424 RExC_copy_start_in_constructed = RExC_start + constructed_prefix_len;
18425 RExC_end = RExC_parse + len;
18426 RExC_in_multi_char_class = 1;
18427
18428 ret = reg(pRExC_state, 1, &reg_flags, depth+1);
18429
18430 *flagp |= reg_flags & (HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PARSE|NEED_UTF8);
18431
18432 /* And restore so can parse the rest of the pattern */
18433 RExC_parse = save_parse;
18434 RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = save_start;
18435 RExC_end = save_end;
18436 RExC_in_multi_char_class = 0;
18437 SvREFCNT_dec_NN(multi_char_matches);
18438 return ret;
18439 }
18440
18441 /* If folding, we calculate all characters that could fold to or from the
18442 * ones already on the list */
18443 if (cp_foldable_list) {
18444 if (FOLD) {
18445 UV start, end; /* End points of code point ranges */
18446
18447 SV* fold_intersection = NULL;
18448 SV** use_list;
18449
18450 /* Our calculated list will be for Unicode rules. For locale
18451 * matching, we have to keep a separate list that is consulted at
18452 * runtime only when the locale indicates Unicode rules (and we
18453 * don't include potential matches in the ASCII/Latin1 range, as
18454 * any code point could fold to any other, based on the run-time
18455 * locale). For non-locale, we just use the general list */
18456 if (LOC) {
18457 use_list = &only_utf8_locale_list;
18458 }
18459 else {
18460 use_list = &cp_list;
18461 }
18462
18463 /* Only the characters in this class that participate in folds need
18464 * be checked. Get the intersection of this class and all the
18465 * possible characters that are foldable. This can quickly narrow
18466 * down a large class */
18467 _invlist_intersection(PL_in_some_fold, cp_foldable_list,
18468 &fold_intersection);
18469
18470 /* Now look at the foldable characters in this class individually */
18471 invlist_iterinit(fold_intersection);
18472 while (invlist_iternext(fold_intersection, &start, &end)) {
18473 UV j;
18474 UV folded;
18475
18476 /* Look at every character in the range */
18477 for (j = start; j <= end; j++) {
18478 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
18479 STRLEN foldlen;
18480 unsigned int k;
18481 Size_t folds_count;
18482 U32 first_fold;
18483 const U32 * remaining_folds;
18484
18485 if (j < 256) {
18486
18487 /* Under /l, we don't know what code points below 256
18488 * fold to, except we do know the MICRO SIGN folds to
18489 * an above-255 character if the locale is UTF-8, so we
18490 * add it to the special list (in *use_list) Otherwise
18491 * we know now what things can match, though some folds
18492 * are valid under /d only if the target is UTF-8.
18493 * Those go in a separate list */
18494 if ( IS_IN_SOME_FOLD_L1(j)
18495 && ! (LOC && j != MICRO_SIGN))
18496 {
18497
18498 /* ASCII is always matched; non-ASCII is matched
18499 * only under Unicode rules (which could happen
18500 * under /l if the locale is a UTF-8 one */
18501 if (isASCII(j) || ! DEPENDS_SEMANTICS) {
18502 *use_list = add_cp_to_invlist(*use_list,
18503 PL_fold_latin1[j]);
18504 }
18505 else if (j != PL_fold_latin1[j]) {
18506 upper_latin1_only_utf8_matches
18507 = add_cp_to_invlist(
18508 upper_latin1_only_utf8_matches,
18509 PL_fold_latin1[j]);
18510 }
18511 }
18512
18513 if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j)
18514 && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
18515 {
18516 add_above_Latin1_folds(pRExC_state,
18517 (U8) j,
18518 use_list);
18519 }
18520 continue;
18521 }
18522
18523 /* Here is an above Latin1 character. We don't have the
18524 * rules hard-coded for it. First, get its fold. This is
18525 * the simple fold, as the multi-character folds have been
18526 * handled earlier and separated out */
18527 folded = _to_uni_fold_flags(j, foldbuf, &foldlen,
18528 (ASCII_FOLD_RESTRICTED)
18529 ? FOLD_FLAGS_NOMIX_ASCII
18530 : 0);
18531
18532 /* Single character fold of above Latin1. Add everything
18533 * in its fold closure to the list that this node should
18534 * match. */
18535 folds_count = _inverse_folds(folded, &first_fold,
18536 &remaining_folds);
18537 for (k = 0; k <= folds_count; k++) {
18538 UV c = (k == 0) /* First time through use itself */
18539 ? folded
18540 : (k == 1) /* 2nd time use, the first fold */
18541 ? first_fold
18542
18543 /* Then the remaining ones */
18544 : remaining_folds[k-2];
18545
18546 /* /aa doesn't allow folds between ASCII and non- */
18547 if (( ASCII_FOLD_RESTRICTED
18548 && (isASCII(c) != isASCII(j))))
18549 {
18550 continue;
18551 }
18552
18553 /* Folds under /l which cross the 255/256 boundary are
18554 * added to a separate list. (These are valid only
18555 * when the locale is UTF-8.) */
18556 if (c < 256 && LOC) {
18557 *use_list = add_cp_to_invlist(*use_list, c);
18558 continue;
18559 }
18560
18561 if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
18562 {
18563 cp_list = add_cp_to_invlist(cp_list, c);
18564 }
18565 else {
18566 /* Similarly folds involving non-ascii Latin1
18567 * characters under /d are added to their list */
18568 upper_latin1_only_utf8_matches
18569 = add_cp_to_invlist(
18570 upper_latin1_only_utf8_matches,
18571 c);
18572 }
18573 }
18574 }
18575 }
18576 SvREFCNT_dec_NN(fold_intersection);
18577 }
18578
18579 /* Now that we have finished adding all the folds, there is no reason
18580 * to keep the foldable list separate */
18581 _invlist_union(cp_list, cp_foldable_list, &cp_list);
18582 SvREFCNT_dec_NN(cp_foldable_list);
18583 }
18584
18585 /* And combine the result (if any) with any inversion lists from posix
18586 * classes. The lists are kept separate up to now because we don't want to
18587 * fold the classes */
18588 if (simple_posixes) { /* These are the classes known to be unaffected by
18589 /a, /aa, and /d */
18590 if (cp_list) {
18591 _invlist_union(cp_list, simple_posixes, &cp_list);
18592 SvREFCNT_dec_NN(simple_posixes);
18593 }
18594 else {
18595 cp_list = simple_posixes;
18596 }
18597 }
18598 if (posixes || nposixes) {
18599 if (! DEPENDS_SEMANTICS) {
18600
18601 /* For everything but /d, we can just add the current 'posixes' and
18602 * 'nposixes' to the main list */
18603 if (posixes) {
18604 if (cp_list) {
18605 _invlist_union(cp_list, posixes, &cp_list);
18606 SvREFCNT_dec_NN(posixes);
18607 }
18608 else {
18609 cp_list = posixes;
18610 }
18611 }
18612 if (nposixes) {
18613 if (cp_list) {
18614 _invlist_union(cp_list, nposixes, &cp_list);
18615 SvREFCNT_dec_NN(nposixes);
18616 }
18617 else {
18618 cp_list = nposixes;
18619 }
18620 }
18621 }
18622 else {
18623 /* Under /d, things like \w match upper Latin1 characters only if
18624 * the target string is in UTF-8. But things like \W match all the
18625 * upper Latin1 characters if the target string is not in UTF-8.
18626 *
18627 * Handle the case with something like \W separately */
18628 if (nposixes) {
18629 SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1, NULL);
18630
18631 /* A complemented posix class matches all upper Latin1
18632 * characters if not in UTF-8. And it matches just certain
18633 * ones when in UTF-8. That means those certain ones are
18634 * matched regardless, so can just be added to the
18635 * unconditional list */
18636 if (cp_list) {
18637 _invlist_union(cp_list, nposixes, &cp_list);
18638 SvREFCNT_dec_NN(nposixes);
18639 nposixes = NULL;
18640 }
18641 else {
18642 cp_list = nposixes;
18643 }
18644
18645 /* Likewise for 'posixes' */
18646 _invlist_union(posixes, cp_list, &cp_list);
18647 SvREFCNT_dec(posixes);
18648
18649 /* Likewise for anything else in the range that matched only
18650 * under UTF-8 */
18651 if (upper_latin1_only_utf8_matches) {
18652 _invlist_union(cp_list,
18653 upper_latin1_only_utf8_matches,
18654 &cp_list);
18655 SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
18656 upper_latin1_only_utf8_matches = NULL;
18657 }
18658
18659 /* If we don't match all the upper Latin1 characters regardless
18660 * of UTF-8ness, we have to set a flag to match the rest when
18661 * not in UTF-8 */
18662 _invlist_subtract(only_non_utf8_list, cp_list,
18663 &only_non_utf8_list);
18664 if (_invlist_len(only_non_utf8_list) != 0) {
18665 anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
18666 }
18667 SvREFCNT_dec_NN(only_non_utf8_list);
18668 }
18669 else {
18670 /* Here there were no complemented posix classes. That means
18671 * the upper Latin1 characters in 'posixes' match only when the
18672 * target string is in UTF-8. So we have to add them to the
18673 * list of those types of code points, while adding the
18674 * remainder to the unconditional list.
18675 *
18676 * First calculate what they are */
18677 SV* nonascii_but_latin1_properties = NULL;
18678 _invlist_intersection(posixes, PL_UpperLatin1,
18679 &nonascii_but_latin1_properties);
18680
18681 /* And add them to the final list of such characters. */
18682 _invlist_union(upper_latin1_only_utf8_matches,
18683 nonascii_but_latin1_properties,
18684 &upper_latin1_only_utf8_matches);
18685
18686 /* Remove them from what now becomes the unconditional list */
18687 _invlist_subtract(posixes, nonascii_but_latin1_properties,
18688 &posixes);
18689
18690 /* And add those unconditional ones to the final list */
18691 if (cp_list) {
18692 _invlist_union(cp_list, posixes, &cp_list);
18693 SvREFCNT_dec_NN(posixes);
18694 posixes = NULL;
18695 }
18696 else {
18697 cp_list = posixes;
18698 }
18699
18700 SvREFCNT_dec(nonascii_but_latin1_properties);
18701
18702 /* Get rid of any characters from the conditional list that we
18703 * now know are matched unconditionally, which may make that
18704 * list empty */
18705 _invlist_subtract(upper_latin1_only_utf8_matches,
18706 cp_list,
18707 &upper_latin1_only_utf8_matches);
18708 if (_invlist_len(upper_latin1_only_utf8_matches) == 0) {
18709 SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
18710 upper_latin1_only_utf8_matches = NULL;
18711 }
18712 }
18713 }
18714 }
18715
18716 /* And combine the result (if any) with any inversion list from properties.
18717 * The lists are kept separate up to now so that we can distinguish the two
18718 * in regards to matching above-Unicode. A run-time warning is generated
18719 * if a Unicode property is matched against a non-Unicode code point. But,
18720 * we allow user-defined properties to match anything, without any warning,
18721 * and we also suppress the warning if there is a portion of the character
18722 * class that isn't a Unicode property, and which matches above Unicode, \W
18723 * or [\x{110000}] for example.
18724 * (Note that in this case, unlike the Posix one above, there is no
18725 * <upper_latin1_only_utf8_matches>, because having a Unicode property
18726 * forces Unicode semantics */
18727 if (properties) {
18728 if (cp_list) {
18729
18730 /* If it matters to the final outcome, see if a non-property
18731 * component of the class matches above Unicode. If so, the
18732 * warning gets suppressed. This is true even if just a single
18733 * such code point is specified, as, though not strictly correct if
18734 * another such code point is matched against, the fact that they
18735 * are using above-Unicode code points indicates they should know
18736 * the issues involved */
18737 if (warn_super) {
18738 warn_super = ! (invert
18739 ^ (invlist_highest(cp_list) > PERL_UNICODE_MAX));
18740 }
18741
18742 _invlist_union(properties, cp_list, &cp_list);
18743 SvREFCNT_dec_NN(properties);
18744 }
18745 else {
18746 cp_list = properties;
18747 }
18748
18749 if (warn_super) {
18750 anyof_flags
18751 |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
18752
18753 /* Because an ANYOF node is the only one that warns, this node
18754 * can't be optimized into something else */
18755 optimizable = FALSE;
18756 }
18757 }
18758
18759 /* Here, we have calculated what code points should be in the character
18760 * class.
18761 *
18762 * Now we can see about various optimizations. Fold calculation (which we
18763 * did above) needs to take place before inversion. Otherwise /[^k]/i
18764 * would invert to include K, which under /i would match k, which it
18765 * shouldn't. Therefore we can't invert folded locale now, as it won't be
18766 * folded until runtime */
18767
18768 /* If we didn't do folding, it's because some information isn't available
18769 * until runtime; set the run-time fold flag for these We know to set the
18770 * flag if we have a non-NULL list for UTF-8 locales, or the class matches
18771 * at least one 0-255 range code point */
18772 if (LOC && FOLD) {
18773
18774 /* Some things on the list might be unconditionally included because of
18775 * other components. Remove them, and clean up the list if it goes to
18776 * 0 elements */
18777 if (only_utf8_locale_list && cp_list) {
18778 _invlist_subtract(only_utf8_locale_list, cp_list,
18779 &only_utf8_locale_list);
18780
18781 if (_invlist_len(only_utf8_locale_list) == 0) {
18782 SvREFCNT_dec_NN(only_utf8_locale_list);
18783 only_utf8_locale_list = NULL;
18784 }
18785 }
18786 if ( only_utf8_locale_list
18787 || (cp_list && ( _invlist_contains_cp(cp_list, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE)
18788 || _invlist_contains_cp(cp_list, LATIN_SMALL_LETTER_DOTLESS_I))))
18789 {
18790 has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18791 anyof_flags
18792 |= ANYOFL_FOLD
18793 | ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
18794 }
18795 else if (cp_list && invlist_lowest(cp_list) < 256) {
18796 /* If nothing is below 256, has no locale dependency; otherwise it
18797 * does */
18798 anyof_flags |= ANYOFL_FOLD;
18799 has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18800 }
18801 }
18802 else if ( DEPENDS_SEMANTICS
18803 && ( upper_latin1_only_utf8_matches
18804 || (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)))
18805 {
18806 RExC_seen_d_op = TRUE;
18807 has_runtime_dependency |= HAS_D_RUNTIME_DEPENDENCY;
18808 }
18809
18810 /* Optimize inverted patterns (e.g. [^a-z]) when everything is known at
18811 * compile time. */
18812 if ( cp_list
18813 && invert
18814 && ! has_runtime_dependency)
18815 {
18816 _invlist_invert(cp_list);
18817
18818 /* Clear the invert flag since have just done it here */
18819 invert = FALSE;
18820 }
18821
18822 /* All possible optimizations below still have these characteristics.
18823 * (Multi-char folds aren't SIMPLE, but they don't get this far in this
18824 * routine) */
18825 *flagp |= HASWIDTH|SIMPLE;
18826
18827 if (ret_invlist) {
18828 *ret_invlist = cp_list;
18829
18830 return RExC_emit;
18831 }
18832
18833 if (anyof_flags & ANYOF_LOCALE_FLAGS) {
18834 RExC_contains_locale = 1;
18835 }
18836
18837 /* Some character classes are equivalent to other nodes. Such nodes take
18838 * up less room, and some nodes require fewer operations to execute, than
18839 * ANYOF nodes. EXACTish nodes may be joinable with adjacent nodes to
18840 * improve efficiency. */
18841
18842 if (optimizable) {
18843 PERL_UINT_FAST8_T i;
18844 UV partial_cp_count = 0;
18845 UV start[MAX_FOLD_FROMS+1] = { 0 }; /* +1 for the folded-to char */
18846 UV end[MAX_FOLD_FROMS+1] = { 0 };
18847 bool single_range = FALSE;
18848
18849 if (cp_list) { /* Count the code points in enough ranges that we would
18850 see all the ones possible in any fold in this version
18851 of Unicode */
18852
18853 invlist_iterinit(cp_list);
18854 for (i = 0; i <= MAX_FOLD_FROMS; i++) {
18855 if (! invlist_iternext(cp_list, &start[i], &end[i])) {
18856 break;
18857 }
18858 partial_cp_count += end[i] - start[i] + 1;
18859 }
18860
18861 if (i == 1) {
18862 single_range = TRUE;
18863 }
18864 invlist_iterfinish(cp_list);
18865 }
18866
18867 /* If we know at compile time that this matches every possible code
18868 * point, any run-time dependencies don't matter */
18869 if (start[0] == 0 && end[0] == UV_MAX) {
18870 if (invert) {
18871 ret = reganode(pRExC_state, OPFAIL, 0);
18872 }
18873 else {
18874 ret = reg_node(pRExC_state, SANY);
18875 MARK_NAUGHTY(1);
18876 }
18877 goto not_anyof;
18878 }
18879
18880 /* Similarly, for /l posix classes, if both a class and its
18881 * complement match, any run-time dependencies don't matter */
18882 if (posixl) {
18883 for (namedclass = 0; namedclass < ANYOF_POSIXL_MAX;
18884 namedclass += 2)
18885 {
18886 if ( POSIXL_TEST(posixl, namedclass) /* class */
18887 && POSIXL_TEST(posixl, namedclass + 1)) /* its complement */
18888 {
18889 if (invert) {
18890 ret = reganode(pRExC_state, OPFAIL, 0);
18891 }
18892 else {
18893 ret = reg_node(pRExC_state, SANY);
18894 MARK_NAUGHTY(1);
18895 }
18896 goto not_anyof;
18897 }
18898 }
18899
18900 /* For well-behaved locales, some classes are subsets of others,
18901 * so complementing the subset and including the non-complemented
18902 * superset should match everything, like [\D[:alnum:]], and
18903 * [[:^alpha:][:alnum:]], but some implementations of locales are
18904 * buggy, and khw thinks its a bad idea to have optimization change
18905 * behavior, even if it avoids an OS bug in a given case */
18906
18907#define isSINGLE_BIT_SET(n) isPOWER_OF_2(n)
18908
18909 /* If is a single posix /l class, can optimize to just that op.
18910 * Such a node will not match anything in the Latin1 range, as that
18911 * is not determinable until runtime, but will match whatever the
18912 * class does outside that range. (Note that some classes won't
18913 * match anything outside the range, like [:ascii:]) */
18914 if ( isSINGLE_BIT_SET(posixl)
18915 && (partial_cp_count == 0 || start[0] > 255))
18916 {
18917 U8 classnum;
18918 SV * class_above_latin1 = NULL;
18919 bool already_inverted;
18920 bool are_equivalent;
18921
18922 /* Compute which bit is set, which is the same thing as, e.g.,
18923 * ANYOF_CNTRL. From
18924 * https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn
18925 * */
18926 static const int MultiplyDeBruijnBitPosition2[32] =
18927 {
18928 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
18929 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
18930 };
18931
18932 namedclass = MultiplyDeBruijnBitPosition2[(posixl
18933 * 0x077CB531U) >> 27];
18934 classnum = namedclass_to_classnum(namedclass);
18935
18936 /* The named classes are such that the inverted number is one
18937 * larger than the non-inverted one */
18938 already_inverted = namedclass
18939 - classnum_to_namedclass(classnum);
18940
18941 /* Create an inversion list of the official property, inverted
18942 * if the constructed node list is inverted, and restricted to
18943 * only the above latin1 code points, which are the only ones
18944 * known at compile time */
18945 _invlist_intersection_maybe_complement_2nd(
18946 PL_AboveLatin1,
18947 PL_XPosix_ptrs[classnum],
18948 already_inverted,
18949 &class_above_latin1);
18950 are_equivalent = _invlistEQ(class_above_latin1, cp_list,
18951 FALSE);
18952 SvREFCNT_dec_NN(class_above_latin1);
18953
18954 if (are_equivalent) {
18955
18956 /* Resolve the run-time inversion flag with this possibly
18957 * inverted class */
18958 invert = invert ^ already_inverted;
18959
18960 ret = reg_node(pRExC_state,
18961 POSIXL + invert * (NPOSIXL - POSIXL));
18962 FLAGS(REGNODE_p(ret)) = classnum;
18963 goto not_anyof;
18964 }
18965 }
18966 }
18967
18968 /* khw can't think of any other possible transformation involving
18969 * these. */
18970 if (has_runtime_dependency & HAS_USER_DEFINED_PROPERTY) {
18971 goto is_anyof;
18972 }
18973
18974 if (! has_runtime_dependency) {
18975
18976 /* If the list is empty, nothing matches. This happens, for
18977 * example, when a Unicode property that doesn't match anything is
18978 * the only element in the character class (perluniprops.pod notes
18979 * such properties). */
18980 if (partial_cp_count == 0) {
18981 if (invert) {
18982 ret = reg_node(pRExC_state, SANY);
18983 }
18984 else {
18985 ret = reganode(pRExC_state, OPFAIL, 0);
18986 }
18987
18988 goto not_anyof;
18989 }
18990
18991 /* If matches everything but \n */
18992 if ( start[0] == 0 && end[0] == '\n' - 1
18993 && start[1] == '\n' + 1 && end[1] == UV_MAX)
18994 {
18995 assert (! invert);
18996 ret = reg_node(pRExC_state, REG_ANY);
18997 MARK_NAUGHTY(1);
18998 goto not_anyof;
18999 }
19000 }
19001
19002 /* Next see if can optimize classes that contain just a few code points
19003 * into an EXACTish node. The reason to do this is to let the
19004 * optimizer join this node with adjacent EXACTish ones, and ANYOF
19005 * nodes require conversion to code point from UTF-8.
19006 *
19007 * An EXACTFish node can be generated even if not under /i, and vice
19008 * versa. But care must be taken. An EXACTFish node has to be such
19009 * that it only matches precisely the code points in the class, but we
19010 * want to generate the least restrictive one that does that, to
19011 * increase the odds of being able to join with an adjacent node. For
19012 * example, if the class contains [kK], we have to make it an EXACTFAA
19013 * node to prevent the KELVIN SIGN from matching. Whether we are under
19014 * /i or not is irrelevant in this case. Less obvious is the pattern
19015 * qr/[\x{02BC}]n/i. U+02BC is MODIFIER LETTER APOSTROPHE. That is
19016 * supposed to match the single character U+0149 LATIN SMALL LETTER N
19017 * PRECEDED BY APOSTROPHE. And so even though there is no simple fold
19018 * that includes \X{02BC}, there is a multi-char fold that does, and so
19019 * the node generated for it must be an EXACTFish one. On the other
19020 * hand qr/:/i should generate a plain EXACT node since the colon
19021 * participates in no fold whatsoever, and having it EXACT tells the
19022 * optimizer the target string cannot match unless it has a colon in
19023 * it.
19024 */
19025 if ( ! posixl
19026 && ! invert
19027
19028 /* Only try if there are no more code points in the class than
19029 * in the max possible fold */
19030 && inRANGE(partial_cp_count, 1, MAX_FOLD_FROMS + 1))
19031 {
19032 if (partial_cp_count == 1 && ! upper_latin1_only_utf8_matches)
19033 {
19034 /* We can always make a single code point class into an
19035 * EXACTish node. */
19036
19037 if (LOC) {
19038
19039 /* Here is /l: Use EXACTL, except if there is a fold not
19040 * known until runtime so shows as only a single code point
19041 * here. For code points above 255, we know which can
19042 * cause problems by having a potential fold to the Latin1
19043 * range. */
19044 if ( ! FOLD
19045 || ( start[0] > 255
19046 && ! is_PROBLEMATIC_LOCALE_FOLD_cp(start[0])))
19047 {
19048 op = EXACTL;
19049 }
19050 else {
19051 op = EXACTFL;
19052 }
19053 }
19054 else if (! FOLD) { /* Not /l and not /i */
19055 op = (start[0] < 256) ? EXACT : EXACT_REQ8;
19056 }
19057 else if (start[0] < 256) { /* /i, not /l, and the code point is
19058 small */
19059
19060 /* Under /i, it gets a little tricky. A code point that
19061 * doesn't participate in a fold should be an EXACT node.
19062 * We know this one isn't the result of a simple fold, or
19063 * there'd be more than one code point in the list, but it
19064 * could be part of a multi- character fold. In that case
19065 * we better not create an EXACT node, as we would wrongly
19066 * be telling the optimizer that this code point must be in
19067 * the target string, and that is wrong. This is because
19068 * if the sequence around this code point forms a
19069 * multi-char fold, what needs to be in the string could be
19070 * the code point that folds to the sequence.
19071 *
19072 * This handles the case of below-255 code points, as we
19073 * have an easy look up for those. The next clause handles
19074 * the above-256 one */
19075 op = IS_IN_SOME_FOLD_L1(start[0])
19076 ? EXACTFU
19077 : EXACT;
19078 }
19079 else { /* /i, larger code point. Since we are under /i, and
19080 have just this code point, we know that it can't
19081 fold to something else, so PL_InMultiCharFold
19082 applies to it */
19083 op = _invlist_contains_cp(PL_InMultiCharFold,
19084 start[0])
19085 ? EXACTFU_REQ8
19086 : EXACT_REQ8;
19087 }
19088
19089 value = start[0];
19090 }
19091 else if ( ! (has_runtime_dependency & ~HAS_D_RUNTIME_DEPENDENCY)
19092 && _invlist_contains_cp(PL_in_some_fold, start[0]))
19093 {
19094 /* Here, the only runtime dependency, if any, is from /d, and
19095 * the class matches more than one code point, and the lowest
19096 * code point participates in some fold. It might be that the
19097 * other code points are /i equivalent to this one, and hence
19098 * they would representable by an EXACTFish node. Above, we
19099 * eliminated classes that contain too many code points to be
19100 * EXACTFish, with the test for MAX_FOLD_FROMS
19101 *
19102 * First, special case the ASCII fold pairs, like 'B' and 'b'.
19103 * We do this because we have EXACTFAA at our disposal for the
19104 * ASCII range */
19105 if (partial_cp_count == 2 && isASCII(start[0])) {
19106
19107 /* The only ASCII characters that participate in folds are
19108 * alphabetics */
19109 assert(isALPHA(start[0]));
19110 if ( end[0] == start[0] /* First range is a single
19111 character, so 2nd exists */
19112 && isALPHA_FOLD_EQ(start[0], start[1]))
19113 {
19114
19115 /* Here, is part of an ASCII fold pair */
19116
19117 if ( ASCII_FOLD_RESTRICTED
19118 || HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(start[0]))
19119 {
19120 /* If the second clause just above was true, it
19121 * means we can't be under /i, or else the list
19122 * would have included more than this fold pair.
19123 * Therefore we have to exclude the possibility of
19124 * whatever else it is that folds to these, by
19125 * using EXACTFAA */
19126 op = EXACTFAA;
19127 }
19128 else if (HAS_NONLATIN1_FOLD_CLOSURE(start[0])) {
19129
19130 /* Here, there's no simple fold that start[0] is part
19131 * of, but there is a multi-character one. If we
19132 * are not under /i, we want to exclude that
19133 * possibility; if under /i, we want to include it
19134 * */
19135 op = (FOLD) ? EXACTFU : EXACTFAA;
19136 }
19137 else {
19138
19139 /* Here, the only possible fold start[0] particpates in
19140 * is with start[1]. /i or not isn't relevant */
19141 op = EXACTFU;
19142 }
19143
19144 value = toFOLD(start[0]);
19145 }
19146 }
19147 else if ( ! upper_latin1_only_utf8_matches
19148 || ( _invlist_len(upper_latin1_only_utf8_matches)
19149 == 2
19150 && PL_fold_latin1[
19151 invlist_highest(upper_latin1_only_utf8_matches)]
19152 == start[0]))
19153 {
19154 /* Here, the smallest character is non-ascii or there are
19155 * more than 2 code points matched by this node. Also, we
19156 * either don't have /d UTF-8 dependent matches, or if we
19157 * do, they look like they could be a single character that
19158 * is the fold of the lowest one in the always-match list.
19159 * This test quickly excludes most of the false positives
19160 * when there are /d UTF-8 depdendent matches. These are
19161 * like LATIN CAPITAL LETTER A WITH GRAVE matching LATIN
19162 * SMALL LETTER A WITH GRAVE iff the target string is
19163 * UTF-8. (We don't have to worry above about exceeding
19164 * the array bounds of PL_fold_latin1[] because any code
19165 * point in 'upper_latin1_only_utf8_matches' is below 256.)
19166 *
19167 * EXACTFAA would apply only to pairs (hence exactly 2 code
19168 * points) in the ASCII range, so we can't use it here to
19169 * artificially restrict the fold domain, so we check if
19170 * the class does or does not match some EXACTFish node.
19171 * Further, if we aren't under /i, and and the folded-to
19172 * character is part of a multi-character fold, we can't do
19173 * this optimization, as the sequence around it could be
19174 * that multi-character fold, and we don't here know the
19175 * context, so we have to assume it is that multi-char
19176 * fold, to prevent potential bugs.
19177 *
19178 * To do the general case, we first find the fold of the
19179 * lowest code point (which may be higher than the lowest
19180 * one), then find everything that folds to it. (The data
19181 * structure we have only maps from the folded code points,
19182 * so we have to do the earlier step.) */
19183
19184 Size_t foldlen;
19185 U8 foldbuf[UTF8_MAXBYTES_CASE];
19186 UV folded = _to_uni_fold_flags(start[0],
19187 foldbuf, &foldlen, 0);
19188 U32 first_fold;
19189 const U32 * remaining_folds;
19190 Size_t folds_to_this_cp_count = _inverse_folds(
19191 folded,
19192 &first_fold,
19193 &remaining_folds);
19194 Size_t folds_count = folds_to_this_cp_count + 1;
19195 SV * fold_list = _new_invlist(folds_count);
19196 unsigned int i;
19197
19198 /* If there are UTF-8 dependent matches, create a temporary
19199 * list of what this node matches, including them. */
19200 SV * all_cp_list = NULL;
19201 SV ** use_this_list = &cp_list;
19202
19203 if (upper_latin1_only_utf8_matches) {
19204 all_cp_list = _new_invlist(0);
19205 use_this_list = &all_cp_list;
19206 _invlist_union(cp_list,
19207 upper_latin1_only_utf8_matches,
19208 use_this_list);
19209 }
19210
19211 /* Having gotten everything that participates in the fold
19212 * containing the lowest code point, we turn that into an
19213 * inversion list, making sure everything is included. */
19214 fold_list = add_cp_to_invlist(fold_list, start[0]);
19215 fold_list = add_cp_to_invlist(fold_list, folded);
19216 if (folds_to_this_cp_count > 0) {
19217 fold_list = add_cp_to_invlist(fold_list, first_fold);
19218 for (i = 0; i + 1 < folds_to_this_cp_count; i++) {
19219 fold_list = add_cp_to_invlist(fold_list,
19220 remaining_folds[i]);
19221 }
19222 }
19223
19224 /* If the fold list is identical to what's in this ANYOF
19225 * node, the node can be represented by an EXACTFish one
19226 * instead */
19227 if (_invlistEQ(*use_this_list, fold_list,
19228 0 /* Don't complement */ )
19229 ) {
19230
19231 /* But, we have to be careful, as mentioned above.
19232 * Just the right sequence of characters could match
19233 * this if it is part of a multi-character fold. That
19234 * IS what we want if we are under /i. But it ISN'T
19235 * what we want if not under /i, as it could match when
19236 * it shouldn't. So, when we aren't under /i and this
19237 * character participates in a multi-char fold, we
19238 * don't optimize into an EXACTFish node. So, for each
19239 * case below we have to check if we are folding
19240 * and if not, if it is not part of a multi-char fold.
19241 * */
19242 if (start[0] > 255) { /* Highish code point */
19243 if (FOLD || ! _invlist_contains_cp(
19244 PL_InMultiCharFold, folded))
19245 {
19246 op = (LOC)
19247 ? EXACTFLU8
19248 : (ASCII_FOLD_RESTRICTED)
19249 ? EXACTFAA
19250 : EXACTFU_REQ8;
19251 value = folded;
19252 }
19253 } /* Below, the lowest code point < 256 */
19254 else if ( FOLD
19255 && folded == 's'
19256 && DEPENDS_SEMANTICS)
19257 { /* An EXACTF node containing a single character
19258 's', can be an EXACTFU if it doesn't get
19259 joined with an adjacent 's' */
19260 op = EXACTFU_S_EDGE;
19261 value = folded;
19262 }
19263 else if ( FOLD
19264 || ! HAS_NONLATIN1_FOLD_CLOSURE(start[0]))
19265 {
19266 if (upper_latin1_only_utf8_matches) {
19267 op = EXACTF;
19268
19269 /* We can't use the fold, as that only matches
19270 * under UTF-8 */
19271 value = start[0];
19272 }
19273 else if ( UNLIKELY(start[0] == MICRO_SIGN)
19274 && ! UTF)
19275 { /* EXACTFUP is a special node for this
19276 character */
19277 op = (ASCII_FOLD_RESTRICTED)
19278 ? EXACTFAA
19279 : EXACTFUP;
19280 value = MICRO_SIGN;
19281 }
19282 else if ( ASCII_FOLD_RESTRICTED
19283 && ! isASCII(start[0]))
19284 { /* For ASCII under /iaa, we can use EXACTFU
19285 below */
19286 op = EXACTFAA;
19287 value = folded;
19288 }
19289 else {
19290 op = EXACTFU;
19291 value = folded;
19292 }
19293 }
19294 }
19295
19296 SvREFCNT_dec_NN(fold_list);
19297 SvREFCNT_dec(all_cp_list);
19298 }
19299 }
19300
19301 if (op != END) {
19302 U8 len;
19303
19304 /* Here, we have calculated what EXACTish node to use. Have to
19305 * convert to UTF-8 if not already there */
19306 if (value > 255) {
19307 if (! UTF) {
19308 SvREFCNT_dec(cp_list);;
19309 REQUIRE_UTF8(flagp);
19310 }
19311
19312 /* This is a kludge to the special casing issues with this
19313 * ligature under /aa. FB05 should fold to FB06, but the
19314 * call above to _to_uni_fold_flags() didn't find this, as
19315 * it didn't use the /aa restriction in order to not miss
19316 * other folds that would be affected. This is the only
19317 * instance likely to ever be a problem in all of Unicode.
19318 * So special case it. */
19319 if ( value == LATIN_SMALL_LIGATURE_LONG_S_T
19320 && ASCII_FOLD_RESTRICTED)
19321 {
19322 value = LATIN_SMALL_LIGATURE_ST;
19323 }
19324 }
19325
19326 len = (UTF) ? UVCHR_SKIP(value) : 1;
19327
19328 ret = regnode_guts(pRExC_state, op, len, "exact");
19329 FILL_NODE(ret, op);
19330 RExC_emit += 1 + STR_SZ(len);
19331 setSTR_LEN(REGNODE_p(ret), len);
19332 if (len == 1) {
19333 *STRINGs(REGNODE_p(ret)) = (U8) value;
19334 }
19335 else {
19336 uvchr_to_utf8((U8 *) STRINGs(REGNODE_p(ret)), value);
19337 }
19338 goto not_anyof;
19339 }
19340 }
19341
19342 if (! has_runtime_dependency) {
19343
19344 /* See if this can be turned into an ANYOFM node. Think about the
19345 * bit patterns in two different bytes. In some positions, the
19346 * bits in each will be 1; and in other positions both will be 0;
19347 * and in some positions the bit will be 1 in one byte, and 0 in
19348 * the other. Let 'n' be the number of positions where the bits
19349 * differ. We create a mask which has exactly 'n' 0 bits, each in
19350 * a position where the two bytes differ. Now take the set of all
19351 * bytes that when ANDed with the mask yield the same result. That
19352 * set has 2**n elements, and is representable by just two 8 bit
19353 * numbers: the result and the mask. Importantly, matching the set
19354 * can be vectorized by creating a word full of the result bytes,
19355 * and a word full of the mask bytes, yielding a significant speed
19356 * up. Here, see if this node matches such a set. As a concrete
19357 * example consider [01], and the byte representing '0' which is
19358 * 0x30 on ASCII machines. It has the bits 0011 0000. Take the
19359 * mask 1111 1110. If we AND 0x31 and 0x30 with that mask we get
19360 * 0x30. Any other bytes ANDed yield something else. So [01],
19361 * which is a common usage, is optimizable into ANYOFM, and can
19362 * benefit from the speed up. We can only do this on UTF-8
19363 * invariant bytes, because they have the same bit patterns under
19364 * UTF-8 as not. */
19365 PERL_UINT_FAST8_T inverted = 0;
19366#ifdef EBCDIC
19367 const PERL_UINT_FAST8_T max_permissible = 0xFF;
19368#else
19369 const PERL_UINT_FAST8_T max_permissible = 0x7F;
19370#endif
19371 /* If doesn't fit the criteria for ANYOFM, invert and try again.
19372 * If that works we will instead later generate an NANYOFM, and
19373 * invert back when through */
19374 if (invlist_highest(cp_list) > max_permissible) {
19375 _invlist_invert(cp_list);
19376 inverted = 1;
19377 }
19378
19379 if (invlist_highest(cp_list) <= max_permissible) {
19380 UV this_start, this_end;
19381 UV lowest_cp = UV_MAX; /* init'ed to suppress compiler warn */
19382 U8 bits_differing = 0;
19383 Size_t full_cp_count = 0;
19384 bool first_time = TRUE;
19385
19386 /* Go through the bytes and find the bit positions that differ
19387 * */
19388 invlist_iterinit(cp_list);
19389 while (invlist_iternext(cp_list, &this_start, &this_end)) {
19390 unsigned int i = this_start;
19391
19392 if (first_time) {
19393 if (! UVCHR_IS_INVARIANT(i)) {
19394 goto done_anyofm;
19395 }
19396
19397 first_time = FALSE;
19398 lowest_cp = this_start;
19399
19400 /* We have set up the code point to compare with.
19401 * Don't compare it with itself */
19402 i++;
19403 }
19404
19405 /* Find the bit positions that differ from the lowest code
19406 * point in the node. Keep track of all such positions by
19407 * OR'ing */
19408 for (; i <= this_end; i++) {
19409 if (! UVCHR_IS_INVARIANT(i)) {
19410 goto done_anyofm;
19411 }
19412
19413 bits_differing |= i ^ lowest_cp;
19414 }
19415
19416 full_cp_count += this_end - this_start + 1;
19417 }
19418
19419 /* At the end of the loop, we count how many bits differ from
19420 * the bits in lowest code point, call the count 'd'. If the
19421 * set we found contains 2**d elements, it is the closure of
19422 * all code points that differ only in those bit positions. To
19423 * convince yourself of that, first note that the number in the
19424 * closure must be a power of 2, which we test for. The only
19425 * way we could have that count and it be some differing set,
19426 * is if we got some code points that don't differ from the
19427 * lowest code point in any position, but do differ from each
19428 * other in some other position. That means one code point has
19429 * a 1 in that position, and another has a 0. But that would
19430 * mean that one of them differs from the lowest code point in
19431 * that position, which possibility we've already excluded. */
19432 if ( (inverted || full_cp_count > 1)
19433 && full_cp_count == 1U << PL_bitcount[bits_differing])
19434 {
19435 U8 ANYOFM_mask;
19436
19437 op = ANYOFM + inverted;;
19438
19439 /* We need to make the bits that differ be 0's */
19440 ANYOFM_mask = ~ bits_differing; /* This goes into FLAGS */
19441
19442 /* The argument is the lowest code point */
19443 ret = reganode(pRExC_state, op, lowest_cp);
19444 FLAGS(REGNODE_p(ret)) = ANYOFM_mask;
19445 }
19446
19447 done_anyofm:
19448 invlist_iterfinish(cp_list);
19449 }
19450
19451 if (inverted) {
19452 _invlist_invert(cp_list);
19453 }
19454
19455 if (op != END) {
19456 goto not_anyof;
19457 }
19458
19459 /* XXX We could create an ANYOFR_LOW node here if we saved above if
19460 * all were invariants, it wasn't inverted, and there is a single
19461 * range. This would be faster than some of the posix nodes we
19462 * create below like /\d/a, but would be twice the size. Without
19463 * having actually measured the gain, khw doesn't think the
19464 * tradeoff is really worth it */
19465 }
19466
19467 if (! (anyof_flags & ANYOF_LOCALE_FLAGS)) {
19468 PERL_UINT_FAST8_T type;
19469 SV * intersection = NULL;
19470 SV* d_invlist = NULL;
19471
19472 /* See if this matches any of the POSIX classes. The POSIXA and
19473 * POSIXD ones are about the same speed as ANYOF ops, but take less
19474 * room; the ones that have above-Latin1 code point matches are
19475 * somewhat faster than ANYOF. */
19476
19477 for (type = POSIXA; type >= POSIXD; type--) {
19478 int posix_class;
19479
19480 if (type == POSIXL) { /* But not /l posix classes */
19481 continue;
19482 }
19483
19484 for (posix_class = 0;
19485 posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC;
19486 posix_class++)
19487 {
19488 SV** our_code_points = &cp_list;
19489 SV** official_code_points;
19490 int try_inverted;
19491
19492 if (type == POSIXA) {
19493 official_code_points = &PL_Posix_ptrs[posix_class];
19494 }
19495 else {
19496 official_code_points = &PL_XPosix_ptrs[posix_class];
19497 }
19498
19499 /* Skip non-existent classes of this type. e.g. \v only
19500 * has an entry in PL_XPosix_ptrs */
19501 if (! *official_code_points) {
19502 continue;
19503 }
19504
19505 /* Try both the regular class, and its inversion */
19506 for (try_inverted = 0; try_inverted < 2; try_inverted++) {
19507 bool this_inverted = invert ^ try_inverted;
19508
19509 if (type != POSIXD) {
19510
19511 /* This class that isn't /d can't match if we have
19512 * /d dependencies */
19513 if (has_runtime_dependency
19514 & HAS_D_RUNTIME_DEPENDENCY)
19515 {
19516 continue;
19517 }
19518 }
19519 else /* is /d */ if (! this_inverted) {
19520
19521 /* /d classes don't match anything non-ASCII below
19522 * 256 unconditionally (which cp_list contains) */
19523 _invlist_intersection(cp_list, PL_UpperLatin1,
19524 &intersection);
19525 if (_invlist_len(intersection) != 0) {
19526 continue;
19527 }
19528
19529 SvREFCNT_dec(d_invlist);
19530 d_invlist = invlist_clone(cp_list, NULL);
19531
19532 /* But under UTF-8 it turns into using /u rules.
19533 * Add the things it matches under these conditions
19534 * so that we check below that these are identical
19535 * to what the tested class should match */
19536 if (upper_latin1_only_utf8_matches) {
19537 _invlist_union(
19538 d_invlist,
19539 upper_latin1_only_utf8_matches,
19540 &d_invlist);
19541 }
19542 our_code_points = &d_invlist;
19543 }
19544 else { /* POSIXD, inverted. If this doesn't have this
19545 flag set, it isn't /d. */
19546 if (! (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
19547 {
19548 continue;
19549 }
19550 our_code_points = &cp_list;
19551 }
19552
19553 /* Here, have weeded out some things. We want to see
19554 * if the list of characters this node contains
19555 * ('*our_code_points') precisely matches those of the
19556 * class we are currently checking against
19557 * ('*official_code_points'). */
19558 if (_invlistEQ(*our_code_points,
19559 *official_code_points,
19560 try_inverted))
19561 {
19562 /* Here, they precisely match. Optimize this ANYOF
19563 * node into its equivalent POSIX one of the
19564 * correct type, possibly inverted */
19565 ret = reg_node(pRExC_state, (try_inverted)
19566 ? type + NPOSIXA
19567 - POSIXA
19568 : type);
19569 FLAGS(REGNODE_p(ret)) = posix_class;
19570 SvREFCNT_dec(d_invlist);
19571 SvREFCNT_dec(intersection);
19572 goto not_anyof;
19573 }
19574 }
19575 }
19576 }
19577 SvREFCNT_dec(d_invlist);
19578 SvREFCNT_dec(intersection);
19579 }
19580
19581 /* If it is a single contiguous range, ANYOFR is an efficient regnode,
19582 * both in size and speed. Currently, a 20 bit range base (smallest
19583 * code point in the range), and a 12 bit maximum delta are packed into
19584 * a 32 bit word. This allows for using it on all of the Unicode code
19585 * points except for the highest plane, which is only for private use
19586 * code points. khw doubts that a bigger delta is likely in real world
19587 * applications */
19588 if ( single_range
19589 && ! has_runtime_dependency
19590 && anyof_flags == 0
19591 && start[0] < (1 << ANYOFR_BASE_BITS)
19592 && end[0] - start[0]
19593 < ((1U << (sizeof(((struct regnode_1 *)NULL)->arg1)
19594 * CHARBITS - ANYOFR_BASE_BITS))))
19595
19596 {
19597 U8 low_utf8[UTF8_MAXBYTES+1];
19598 U8 high_utf8[UTF8_MAXBYTES+1];
19599
19600 ret = reganode(pRExC_state, ANYOFR,
19601 (start[0] | (end[0] - start[0]) << ANYOFR_BASE_BITS));
19602
19603 /* Place the lowest UTF-8 start byte in the flags field, so as to
19604 * allow efficient ruling out at run time of many possible inputs.
19605 * */
19606 (void) uvchr_to_utf8(low_utf8, start[0]);
19607 (void) uvchr_to_utf8(high_utf8, end[0]);
19608
19609 /* If all code points share the same first byte, this can be an
19610 * ANYOFRb. Otherwise store the lowest UTF-8 start byte which can
19611 * quickly rule out many inputs at run-time without having to
19612 * compute the code point from UTF-8. For EBCDIC, we use I8, as
19613 * not doing that transformation would not rule out nearly so many
19614 * things */
19615 if (low_utf8[0] == high_utf8[0]) {
19616 OP(REGNODE_p(ret)) = ANYOFRb;
19617 ANYOF_FLAGS(REGNODE_p(ret)) = low_utf8[0];
19618 }
19619 else {
19620 ANYOF_FLAGS(REGNODE_p(ret))
19621 = NATIVE_UTF8_TO_I8(low_utf8[0]);
19622 }
19623
19624 goto not_anyof;
19625 }
19626
19627 /* If didn't find an optimization and there is no need for a bitmap,
19628 * optimize to indicate that */
19629 if ( start[0] >= NUM_ANYOF_CODE_POINTS
19630 && ! LOC
19631 && ! upper_latin1_only_utf8_matches
19632 && anyof_flags == 0)
19633 {
19634 U8 low_utf8[UTF8_MAXBYTES+1];
19635 UV highest_cp = invlist_highest(cp_list);
19636
19637 /* Currently the maximum allowed code point by the system is
19638 * IV_MAX. Higher ones are reserved for future internal use. This
19639 * particular regnode can be used for higher ones, but we can't
19640 * calculate the code point of those. IV_MAX suffices though, as
19641 * it will be a large first byte */
19642 Size_t low_len = uvchr_to_utf8(low_utf8, MIN(start[0], IV_MAX))
19643 - low_utf8;
19644
19645 /* We store the lowest possible first byte of the UTF-8
19646 * representation, using the flags field. This allows for quick
19647 * ruling out of some inputs without having to convert from UTF-8
19648 * to code point. For EBCDIC, we use I8, as not doing that
19649 * transformation would not rule out nearly so many things */
19650 anyof_flags = NATIVE_UTF8_TO_I8(low_utf8[0]);
19651
19652 op = ANYOFH;
19653
19654 /* If the first UTF-8 start byte for the highest code point in the
19655 * range is suitably small, we may be able to get an upper bound as
19656 * well */
19657 if (highest_cp <= IV_MAX) {
19658 U8 high_utf8[UTF8_MAXBYTES+1];
19659 Size_t high_len = uvchr_to_utf8(high_utf8, highest_cp)
19660 - high_utf8;
19661
19662 /* If the lowest and highest are the same, we can get an exact
19663 * first byte instead of a just minimum or even a sequence of
19664 * exact leading bytes. We signal these with different
19665 * regnodes */
19666 if (low_utf8[0] == high_utf8[0]) {
19667 Size_t len = find_first_differing_byte_pos(low_utf8,
19668 high_utf8,
19669 MIN(low_len, high_len));
19670
19671 if (len == 1) {
19672
19673 /* No need to convert to I8 for EBCDIC as this is an
19674 * exact match */
19675 anyof_flags = low_utf8[0];
19676 op = ANYOFHb;
19677 }
19678 else {
19679 op = ANYOFHs;
19680 ret = regnode_guts(pRExC_state, op,
19681 regarglen[op] + STR_SZ(len),
19682 "anyofhs");
19683 FILL_NODE(ret, op);
19684 ((struct regnode_anyofhs *) REGNODE_p(ret))->str_len
19685 = len;
19686 Copy(low_utf8, /* Add the common bytes */
19687 ((struct regnode_anyofhs *) REGNODE_p(ret))->string,
19688 len, U8);
19689 RExC_emit += NODE_SZ_STR(REGNODE_p(ret));
19690 set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
19691 NULL, only_utf8_locale_list);
19692 goto not_anyof;
19693 }
19694 }
19695 else if (NATIVE_UTF8_TO_I8(high_utf8[0]) <= MAX_ANYOF_HRx_BYTE)
19696 {
19697
19698 /* Here, the high byte is not the same as the low, but is
19699 * small enough that its reasonable to have a loose upper
19700 * bound, which is packed in with the strict lower bound.
19701 * See comments at the definition of MAX_ANYOF_HRx_BYTE.
19702 * On EBCDIC platforms, I8 is used. On ASCII platforms I8
19703 * is the same thing as UTF-8 */
19704
19705 U8 bits = 0;
19706 U8 max_range_diff = MAX_ANYOF_HRx_BYTE - anyof_flags;
19707 U8 range_diff = NATIVE_UTF8_TO_I8(high_utf8[0])
19708 - anyof_flags;
19709
19710 if (range_diff <= max_range_diff / 8) {
19711 bits = 3;
19712 }
19713 else if (range_diff <= max_range_diff / 4) {
19714 bits = 2;
19715 }
19716 else if (range_diff <= max_range_diff / 2) {
19717 bits = 1;
19718 }
19719 anyof_flags = (anyof_flags - 0xC0) << 2 | bits;
19720 op = ANYOFHr;
19721 }
19722 }
19723
19724 goto done_finding_op;
19725 }
19726 } /* End of seeing if can optimize it into a different node */
19727
19728 is_anyof: /* It's going to be an ANYOF node. */
19729 op = (has_runtime_dependency & HAS_D_RUNTIME_DEPENDENCY)
19730 ? ANYOFD
19731 : ((posixl)
19732 ? ANYOFPOSIXL
19733 : ((LOC)
19734 ? ANYOFL
19735 : ANYOF));
19736
19737 done_finding_op:
19738
19739 ret = regnode_guts(pRExC_state, op, regarglen[op], "anyof");
19740 FILL_NODE(ret, op); /* We set the argument later */
19741 RExC_emit += 1 + regarglen[op];
19742 ANYOF_FLAGS(REGNODE_p(ret)) = anyof_flags;
19743
19744 /* Here, <cp_list> contains all the code points we can determine at
19745 * compile time that match under all conditions. Go through it, and
19746 * for things that belong in the bitmap, put them there, and delete from
19747 * <cp_list>. While we are at it, see if everything above 255 is in the
19748 * list, and if so, set a flag to speed up execution */
19749
19750 populate_ANYOF_from_invlist(REGNODE_p(ret), &cp_list);
19751
19752 if (posixl) {
19753 ANYOF_POSIXL_SET_TO_BITMAP(REGNODE_p(ret), posixl);
19754 }
19755
19756 if (invert) {
19757 ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_INVERT;
19758 }
19759
19760 /* Here, the bitmap has been populated with all the Latin1 code points that
19761 * always match. Can now add to the overall list those that match only
19762 * when the target string is UTF-8 (<upper_latin1_only_utf8_matches>).
19763 * */
19764 if (upper_latin1_only_utf8_matches) {
19765 if (cp_list) {
19766 _invlist_union(cp_list,
19767 upper_latin1_only_utf8_matches,
19768 &cp_list);
19769 SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
19770 }
19771 else {
19772 cp_list = upper_latin1_only_utf8_matches;
19773 }
19774 ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
19775 }
19776
19777 set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
19778 (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
19779 ? listsv
19780 : NULL,
19781 only_utf8_locale_list);
19782 SvREFCNT_dec(cp_list);;
19783 SvREFCNT_dec(only_utf8_locale_list);
19784 return ret;
19785
19786 not_anyof:
19787
19788 /* Here, the node is getting optimized into something that's not an ANYOF
19789 * one. Finish up. */
19790
19791 Set_Node_Offset_Length(REGNODE_p(ret), orig_parse - RExC_start,
19792 RExC_parse - orig_parse);;
19793 SvREFCNT_dec(cp_list);;
19794 SvREFCNT_dec(only_utf8_locale_list);
19795 return ret;
19796}
19797
19798#undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
19799
19800STATIC void
19801S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state,
19802 regnode* const node,
19803 SV* const cp_list,
19804 SV* const runtime_defns,
19805 SV* const only_utf8_locale_list)
19806{
19807 /* Sets the arg field of an ANYOF-type node 'node', using information about
19808 * the node passed-in. If there is nothing outside the node's bitmap, the
19809 * arg is set to ANYOF_ONLY_HAS_BITMAP. Otherwise, it sets the argument to
19810 * the count returned by add_data(), having allocated and stored an array,
19811 * av, as follows:
19812 *
19813 * av[0] stores the inversion list defining this class as far as known at
19814 * this time, or PL_sv_undef if nothing definite is now known.
19815 * av[1] stores the inversion list of code points that match only if the
19816 * current locale is UTF-8, or if none, PL_sv_undef if there is an
19817 * av[2], or no entry otherwise.
19818 * av[2] stores the list of user-defined properties whose subroutine
19819 * definitions aren't known at this time, or no entry if none. */
19820
19821 UV n;
19822
19823 PERL_ARGS_ASSERT_SET_ANYOF_ARG;
19824
19825 if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) {
19826 assert(! (ANYOF_FLAGS(node)
19827 & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP));
19828 ARG_SET(node, ANYOF_ONLY_HAS_BITMAP);
19829 }
19830 else {
19831 AV * const av = newAV();
19832 SV *rv;
19833
19834 if (cp_list) {
19835 av_store(av, INVLIST_INDEX, SvREFCNT_inc_NN(cp_list));
19836 }
19837
19838 if (only_utf8_locale_list) {
19839 av_store(av, ONLY_LOCALE_MATCHES_INDEX,
19840 SvREFCNT_inc_NN(only_utf8_locale_list));
19841 }
19842
19843 if (runtime_defns) {
19844 av_store(av, DEFERRED_USER_DEFINED_INDEX,
19845 SvREFCNT_inc_NN(runtime_defns));
19846 }
19847
19848 rv = newRV_noinc(MUTABLE_SV(av));
19849 n = add_data(pRExC_state, STR_WITH_LEN("s"));
19850 RExC_rxi->data->data[n] = (void*)rv;
19851 ARG_SET(node, n);
19852 }
19853}
19854
19855#if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
19856SV *
19857Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog,
19858 const regnode* node,
19859 bool doinit,
19860 SV** listsvp,
19861 SV** only_utf8_locale_ptr,
19862 SV** output_invlist)
19863
19864{
19865 /* For internal core use only.
19866 * Returns the inversion list for the input 'node' in the regex 'prog'.
19867 * If <doinit> is 'true', will attempt to create the inversion list if not
19868 * already done.
19869 * If <listsvp> is non-null, will return the printable contents of the
19870 * property definition. This can be used to get debugging information
19871 * even before the inversion list exists, by calling this function with
19872 * 'doinit' set to false, in which case the components that will be used
19873 * to eventually create the inversion list are returned (in a printable
19874 * form).
19875 * If <only_utf8_locale_ptr> is not NULL, it is where this routine is to
19876 * store an inversion list of code points that should match only if the
19877 * execution-time locale is a UTF-8 one.
19878 * If <output_invlist> is not NULL, it is where this routine is to store an
19879 * inversion list of the code points that would be instead returned in
19880 * <listsvp> if this were NULL. Thus, what gets output in <listsvp>
19881 * when this parameter is used, is just the non-code point data that
19882 * will go into creating the inversion list. This currently should be just
19883 * user-defined properties whose definitions were not known at compile
19884 * time. Using this parameter allows for easier manipulation of the
19885 * inversion list's data by the caller. It is illegal to call this
19886 * function with this parameter set, but not <listsvp>
19887 *
19888 * Tied intimately to how S_set_ANYOF_arg sets up the data structure. Note
19889 * that, in spite of this function's name, the inversion list it returns
19890 * may include the bitmap data as well */
19891
19892 SV *si = NULL; /* Input initialization string */
19893 SV* invlist = NULL;
19894
19895 RXi_GET_DECL(prog, progi);
19896 const struct reg_data * const data = prog ? progi->data : NULL;
19897
19898 PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA;
19899 assert(! output_invlist || listsvp);
19900
19901 if (data && data->count) {
19902 const U32 n = ARG(node);
19903
19904 if (data->what[n] == 's') {
19905 SV * const rv = MUTABLE_SV(data->data[n]);
19906 AV * const av = MUTABLE_AV(SvRV(rv));
19907 SV **const ary = AvARRAY(av);
19908
19909 invlist = ary[INVLIST_INDEX];
19910
19911 if (av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX) {
19912 *only_utf8_locale_ptr = ary[ONLY_LOCALE_MATCHES_INDEX];
19913 }
19914
19915 if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
19916 si = ary[DEFERRED_USER_DEFINED_INDEX];
19917 }
19918
19919 if (doinit && (si || invlist)) {
19920 if (si) {
19921 bool user_defined;
19922 SV * msg = newSVpvs_flags("", SVs_TEMP);
19923
19924 SV * prop_definition = handle_user_defined_property(
19925 "", 0, FALSE, /* There is no \p{}, \P{} */
19926 SvPVX_const(si)[1] - '0', /* /i or not has been
19927 stored here for just
19928 this occasion */
19929 TRUE, /* run time */
19930 FALSE, /* This call must find the defn */
19931 si, /* The property definition */
19932 &user_defined,
19933 msg,
19934 0 /* base level call */
19935 );
19936
19937 if (SvCUR(msg)) {
19938 assert(prop_definition == NULL);
19939
19940 Perl_croak(aTHX_ "%" UTF8f,
19941 UTF8fARG(SvUTF8(msg), SvCUR(msg), SvPVX(msg)));
19942 }
19943
19944 if (invlist) {
19945 _invlist_union(invlist, prop_definition, &invlist);
19946 SvREFCNT_dec_NN(prop_definition);
19947 }
19948 else {
19949 invlist = prop_definition;
19950 }
19951
19952 STATIC_ASSERT_STMT(ONLY_LOCALE_MATCHES_INDEX == 1 + INVLIST_INDEX);
19953 STATIC_ASSERT_STMT(DEFERRED_USER_DEFINED_INDEX == 1 + ONLY_LOCALE_MATCHES_INDEX);
19954
19955 ary[INVLIST_INDEX] = invlist;
19956 av_fill(av, (ary[ONLY_LOCALE_MATCHES_INDEX])
19957 ? ONLY_LOCALE_MATCHES_INDEX
19958 : INVLIST_INDEX);
19959 si = NULL;
19960 }
19961 }
19962 }
19963 }
19964
19965 /* If requested, return a printable version of what this ANYOF node matches
19966 * */
19967 if (listsvp) {
19968 SV* matches_string = NULL;
19969
19970 /* This function can be called at compile-time, before everything gets
19971 * resolved, in which case we return the currently best available
19972 * information, which is the string that will eventually be used to do
19973 * that resolving, 'si' */
19974 if (si) {
19975 /* Here, we only have 'si' (and possibly some passed-in data in
19976 * 'invlist', which is handled below) If the caller only wants
19977 * 'si', use that. */
19978 if (! output_invlist) {
19979 matches_string = newSVsv(si);
19980 }
19981 else {
19982 /* But if the caller wants an inversion list of the node, we
19983 * need to parse 'si' and place as much as possible in the
19984 * desired output inversion list, making 'matches_string' only
19985 * contain the currently unresolvable things */
19986 const char *si_string = SvPVX(si);
19987 STRLEN remaining = SvCUR(si);
19988 UV prev_cp = 0;
19989 U8 count = 0;
19990
19991 /* Ignore everything before and including the first new-line */
19992 si_string = (const char *) memchr(si_string, '\n', SvCUR(si));
19993 assert (si_string != NULL);
19994 si_string++;
19995 remaining = SvPVX(si) + SvCUR(si) - si_string;
19996
19997 while (remaining > 0) {
19998
19999 /* The data consists of just strings defining user-defined
20000 * property names, but in prior incarnations, and perhaps
20001 * somehow from pluggable regex engines, it could still
20002 * hold hex code point definitions, all of which should be
20003 * legal (or it wouldn't have gotten this far). Each
20004 * component of a range would be separated by a tab, and
20005 * each range by a new-line. If these are found, instead
20006 * add them to the inversion list */
20007 I32 grok_flags = PERL_SCAN_SILENT_ILLDIGIT
20008 |PERL_SCAN_SILENT_NON_PORTABLE;
20009 STRLEN len = remaining;
20010 UV cp = grok_hex(si_string, &len, &grok_flags, NULL);
20011
20012 /* If the hex decode routine found something, it should go
20013 * up to the next \n */
20014 if ( *(si_string + len) == '\n') {
20015 if (count) { /* 2nd code point on line */
20016 *output_invlist = _add_range_to_invlist(*output_invlist, prev_cp, cp);
20017 }
20018 else {
20019 *output_invlist = add_cp_to_invlist(*output_invlist, cp);
20020 }
20021 count = 0;
20022 goto prepare_for_next_iteration;
20023 }
20024
20025 /* If the hex decode was instead for the lower range limit,
20026 * save it, and go parse the upper range limit */
20027 if (*(si_string + len) == '\t') {
20028 assert(count == 0);
20029
20030 prev_cp = cp;
20031 count = 1;
20032 prepare_for_next_iteration:
20033 si_string += len + 1;
20034 remaining -= len + 1;
20035 continue;
20036 }
20037
20038 /* Here, didn't find a legal hex number. Just add the text
20039 * from here up to the next \n, omitting any trailing
20040 * markers. */
20041
20042 remaining -= len;
20043 len = strcspn(si_string,
20044 DEFERRED_COULD_BE_OFFICIAL_MARKERs "\n");
20045 remaining -= len;
20046 if (matches_string) {
20047 sv_catpvn(matches_string, si_string, len);
20048 }
20049 else {
20050 matches_string = newSVpvn(si_string, len);
20051 }
20052 sv_catpvs(matches_string, " ");
20053
20054 si_string += len;
20055 if ( remaining
20056 && UCHARAT(si_string)
20057 == DEFERRED_COULD_BE_OFFICIAL_MARKERc)
20058 {
20059 si_string++;
20060 remaining--;
20061 }
20062 if (remaining && UCHARAT(si_string) == '\n') {
20063 si_string++;
20064 remaining--;
20065 }
20066 } /* end of loop through the text */
20067
20068 assert(matches_string);
20069 if (SvCUR(matches_string)) { /* Get rid of trailing blank */
20070 SvCUR_set(matches_string, SvCUR(matches_string) - 1);
20071 }
20072 } /* end of has an 'si' */
20073 }
20074
20075 /* Add the stuff that's already known */
20076 if (invlist) {
20077
20078 /* Again, if the caller doesn't want the output inversion list, put
20079 * everything in 'matches-string' */
20080 if (! output_invlist) {
20081 if ( ! matches_string) {
20082 matches_string = newSVpvs("\n");
20083 }
20084 sv_catsv(matches_string, invlist_contents(invlist,
20085 TRUE /* traditional style */
20086 ));
20087 }
20088 else if (! *output_invlist) {
20089 *output_invlist = invlist_clone(invlist, NULL);
20090 }
20091 else {
20092 _invlist_union(*output_invlist, invlist, output_invlist);
20093 }
20094 }
20095
20096 *listsvp = matches_string;
20097 }
20098
20099 return invlist;
20100}
20101#endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
20102
20103/* reg_skipcomment()
20104
20105 Absorbs an /x style # comment from the input stream,
20106 returning a pointer to the first character beyond the comment, or if the
20107 comment terminates the pattern without anything following it, this returns
20108 one past the final character of the pattern (in other words, RExC_end) and
20109 sets the REG_RUN_ON_COMMENT_SEEN flag.
20110
20111 Note it's the callers responsibility to ensure that we are
20112 actually in /x mode
20113
20114*/
20115
20116PERL_STATIC_INLINE char*
20117S_reg_skipcomment(RExC_state_t *pRExC_state, char* p)
20118{
20119 PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
20120
20121 assert(*p == '#');
20122
20123 while (p < RExC_end) {
20124 if (*(++p) == '\n') {
20125 return p+1;
20126 }
20127 }
20128
20129 /* we ran off the end of the pattern without ending the comment, so we have
20130 * to add an \n when wrapping */
20131 RExC_seen |= REG_RUN_ON_COMMENT_SEEN;
20132 return p;
20133}
20134
20135STATIC void
20136S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state,
20137 char ** p,
20138 const bool force_to_xmod
20139 )
20140{
20141 /* If the text at the current parse position '*p' is a '(?#...)' comment,
20142 * or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p'
20143 * is /x whitespace, advance '*p' so that on exit it points to the first
20144 * byte past all such white space and comments */
20145
20146 const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED);
20147
20148 PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT;
20149
20150 assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p));
20151
20152 for (;;) {
20153 if (RExC_end - (*p) >= 3
20154 && *(*p) == '('
20155 && *(*p + 1) == '?'
20156 && *(*p + 2) == '#')
20157 {
20158 while (*(*p) != ')') {
20159 if ((*p) == RExC_end)
20160 FAIL("Sequence (?#... not terminated");
20161 (*p)++;
20162 }
20163 (*p)++;
20164 continue;
20165 }
20166
20167 if (use_xmod) {
20168 const char * save_p = *p;
20169 while ((*p) < RExC_end) {
20170 STRLEN len;
20171 if ((len = is_PATWS_safe((*p), RExC_end, UTF))) {
20172 (*p) += len;
20173 }
20174 else if (*(*p) == '#') {
20175 (*p) = reg_skipcomment(pRExC_state, (*p));
20176 }
20177 else {
20178 break;
20179 }
20180 }
20181 if (*p != save_p) {
20182 continue;
20183 }
20184 }
20185
20186 break;
20187 }
20188
20189 return;
20190}
20191
20192/* nextchar()
20193
20194 Advances the parse position by one byte, unless that byte is the beginning
20195 of a '(?#...)' style comment, or is /x whitespace and /x is in effect. In
20196 those two cases, the parse position is advanced beyond all such comments and
20197 white space.
20198
20199 This is the UTF, (?#...), and /x friendly way of saying RExC_parse++.
20200*/
20201
20202STATIC void
20203S_nextchar(pTHX_ RExC_state_t *pRExC_state)
20204{
20205 PERL_ARGS_ASSERT_NEXTCHAR;
20206
20207 if (RExC_parse < RExC_end) {
20208 assert( ! UTF
20209 || UTF8_IS_INVARIANT(*RExC_parse)
20210 || UTF8_IS_START(*RExC_parse));
20211
20212 RExC_parse += (UTF)
20213 ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
20214 : 1;
20215
20216 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
20217 FALSE /* Don't force /x */ );
20218 }
20219}
20220
20221STATIC void
20222S_change_engine_size(pTHX_ RExC_state_t *pRExC_state, const Ptrdiff_t size)
20223{
20224 /* 'size' is the delta number of smallest regnode equivalents to add or
20225 * subtract from the current memory allocated to the regex engine being
20226 * constructed. */
20227
20228 PERL_ARGS_ASSERT_CHANGE_ENGINE_SIZE;
20229
20230 RExC_size += size;
20231
20232 Renewc(RExC_rxi,
20233 sizeof(regexp_internal) + (RExC_size + 1) * sizeof(regnode),
20234 /* +1 for REG_MAGIC */
20235 char,
20236 regexp_internal);
20237 if ( RExC_rxi == NULL )
20238 FAIL("Regexp out of space");
20239 RXi_SET(RExC_rx, RExC_rxi);
20240
20241 RExC_emit_start = RExC_rxi->program;
20242 if (size > 0) {
20243 Zero(REGNODE_p(RExC_emit), size, regnode);
20244 }
20245
20246#ifdef RE_TRACK_PATTERN_OFFSETS
20247 Renew(RExC_offsets, 2*RExC_size+1, U32);
20248 if (size > 0) {
20249 Zero(RExC_offsets + 2*(RExC_size - size) + 1, 2 * size, U32);
20250 }
20251 RExC_offsets[0] = RExC_size;
20252#endif
20253}
20254
20255STATIC regnode_offset
20256S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name)
20257{
20258 /* Allocate a regnode for 'op', with 'extra_size' extra (smallest) regnode
20259 * equivalents space. It aligns and increments RExC_size
20260 *
20261 * It returns the regnode's offset into the regex engine program */
20262
20263 const regnode_offset ret = RExC_emit;
20264
20265 GET_RE_DEBUG_FLAGS_DECL;
20266
20267 PERL_ARGS_ASSERT_REGNODE_GUTS;
20268
20269 SIZE_ALIGN(RExC_size);
20270 change_engine_size(pRExC_state, (Ptrdiff_t) 1 + extra_size);
20271 NODE_ALIGN_FILL(REGNODE_p(ret));
20272#ifndef RE_TRACK_PATTERN_OFFSETS
20273 PERL_UNUSED_ARG(name);
20274 PERL_UNUSED_ARG(op);
20275#else
20276 assert(extra_size >= regarglen[op] || PL_regkind[op] == ANYOF);
20277
20278 if (RExC_offsets) { /* MJD */
20279 MJD_OFFSET_DEBUG(
20280 ("%s:%d: (op %s) %s %" UVuf " (len %" UVuf ") (max %" UVuf ").\n",
20281 name, __LINE__,
20282 PL_reg_name[op],
20283 (UV)(RExC_emit) > RExC_offsets[0]
20284 ? "Overwriting end of array!\n" : "OK",
20285 (UV)(RExC_emit),
20286 (UV)(RExC_parse - RExC_start),
20287 (UV)RExC_offsets[0]));
20288 Set_Node_Offset(REGNODE_p(RExC_emit), RExC_parse + (op == END));
20289 }
20290#endif
20291 return(ret);
20292}
20293
20294/*
20295- reg_node - emit a node
20296*/
20297STATIC regnode_offset /* Location. */
20298S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
20299{
20300 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node");
20301 regnode_offset ptr = ret;
20302
20303 PERL_ARGS_ASSERT_REG_NODE;
20304
20305 assert(regarglen[op] == 0);
20306
20307 FILL_ADVANCE_NODE(ptr, op);
20308 RExC_emit = ptr;
20309 return(ret);
20310}
20311
20312/*
20313- reganode - emit a node with an argument
20314*/
20315STATIC regnode_offset /* Location. */
20316S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
20317{
20318 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode");
20319 regnode_offset ptr = ret;
20320
20321 PERL_ARGS_ASSERT_REGANODE;
20322
20323 /* ANYOF are special cased to allow non-length 1 args */
20324 assert(regarglen[op] == 1);
20325
20326 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
20327 RExC_emit = ptr;
20328 return(ret);
20329}
20330
20331/*
20332- regpnode - emit a temporary node with a void* argument
20333*/
20334STATIC regnode_offset /* Location. */
20335S_regpnode(pTHX_ RExC_state_t *pRExC_state, U8 op, void * arg)
20336{
20337 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "regvnode");
20338 regnode_offset ptr = ret;
20339
20340 PERL_ARGS_ASSERT_REGPNODE;
20341
20342 FILL_ADVANCE_NODE_ARGp(ptr, op, arg);
20343 RExC_emit = ptr;
20344 return(ret);
20345}
20346
20347STATIC regnode_offset
20348S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2)
20349{
20350 /* emit a node with U32 and I32 arguments */
20351
20352 const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode");
20353 regnode_offset ptr = ret;
20354
20355 PERL_ARGS_ASSERT_REG2LANODE;
20356
20357 assert(regarglen[op] == 2);
20358
20359 FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2);
20360 RExC_emit = ptr;
20361 return(ret);
20362}
20363
20364/*
20365- reginsert - insert an operator in front of already-emitted operand
20366*
20367* That means that on exit 'operand' is the offset of the newly inserted
20368* operator, and the original operand has been relocated.
20369*
20370* IMPORTANT NOTE - it is the *callers* responsibility to correctly
20371* set up NEXT_OFF() of the inserted node if needed. Something like this:
20372*
20373* reginsert(pRExC, OPFAIL, orig_emit, depth+1);
20374* NEXT_OFF(orig_emit) = regarglen[OPFAIL] + NODE_STEP_REGNODE;
20375*
20376* ALSO NOTE - FLAGS(newly-inserted-operator) will be set to 0 as well.
20377*/
20378STATIC void
20379S_reginsert(pTHX_ RExC_state_t *pRExC_state, const U8 op,
20380 const regnode_offset operand, const U32 depth)
20381{
20382 regnode *src;
20383 regnode *dst;
20384 regnode *place;
20385 const int offset = regarglen[(U8)op];
20386 const int size = NODE_STEP_REGNODE + offset;
20387 GET_RE_DEBUG_FLAGS_DECL;
20388
20389 PERL_ARGS_ASSERT_REGINSERT;
20390 PERL_UNUSED_CONTEXT;
20391 PERL_UNUSED_ARG(depth);
20392/* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
20393 DEBUG_PARSE_FMT("inst"," - %s", PL_reg_name[op]);
20394 assert(!RExC_study_started); /* I believe we should never use reginsert once we have started
20395 studying. If this is wrong then we need to adjust RExC_recurse
20396 below like we do with RExC_open_parens/RExC_close_parens. */
20397 change_engine_size(pRExC_state, (Ptrdiff_t) size);
20398 src = REGNODE_p(RExC_emit);
20399 RExC_emit += size;
20400 dst = REGNODE_p(RExC_emit);
20401
20402 /* If we are in a "count the parentheses" pass, the numbers are unreliable,
20403 * and [perl #133871] shows this can lead to problems, so skip this
20404 * realignment of parens until a later pass when they are reliable */
20405 if (! IN_PARENS_PASS && RExC_open_parens) {
20406 int paren;
20407 /*DEBUG_PARSE_FMT("inst"," - %" IVdf, (IV)RExC_npar);*/
20408 /* remember that RExC_npar is rex->nparens + 1,
20409 * iow it is 1 more than the number of parens seen in
20410 * the pattern so far. */
20411 for ( paren=0 ; paren < RExC_npar ; paren++ ) {
20412 /* note, RExC_open_parens[0] is the start of the
20413 * regex, it can't move. RExC_close_parens[0] is the end
20414 * of the regex, it *can* move. */
20415 if ( paren && RExC_open_parens[paren] >= operand ) {
20416 /*DEBUG_PARSE_FMT("open"," - %d", size);*/
20417 RExC_open_parens[paren] += size;
20418 } else {
20419 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
20420 }
20421 if ( RExC_close_parens[paren] >= operand ) {
20422 /*DEBUG_PARSE_FMT("close"," - %d", size);*/
20423 RExC_close_parens[paren] += size;
20424 } else {
20425 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
20426 }
20427 }
20428 }
20429 if (RExC_end_op)
20430 RExC_end_op += size;
20431
20432 while (src > REGNODE_p(operand)) {
20433 StructCopy(--src, --dst, regnode);
20434#ifdef RE_TRACK_PATTERN_OFFSETS
20435 if (RExC_offsets) { /* MJD 20010112 */
20436 MJD_OFFSET_DEBUG(
20437 ("%s(%d): (op %s) %s copy %" UVuf " -> %" UVuf " (max %" UVuf ").\n",
20438 "reginsert",
20439 __LINE__,
20440 PL_reg_name[op],
20441 (UV)(REGNODE_OFFSET(dst)) > RExC_offsets[0]
20442 ? "Overwriting end of array!\n" : "OK",
20443 (UV)REGNODE_OFFSET(src),
20444 (UV)REGNODE_OFFSET(dst),
20445 (UV)RExC_offsets[0]));
20446 Set_Node_Offset_To_R(REGNODE_OFFSET(dst), Node_Offset(src));
20447 Set_Node_Length_To_R(REGNODE_OFFSET(dst), Node_Length(src));
20448 }
20449#endif
20450 }
20451
20452 place = REGNODE_p(operand); /* Op node, where operand used to be. */
20453#ifdef RE_TRACK_PATTERN_OFFSETS
20454 if (RExC_offsets) { /* MJD */
20455 MJD_OFFSET_DEBUG(
20456 ("%s(%d): (op %s) %s %" UVuf " <- %" UVuf " (max %" UVuf ").\n",
20457 "reginsert",
20458 __LINE__,
20459 PL_reg_name[op],
20460 (UV)REGNODE_OFFSET(place) > RExC_offsets[0]
20461 ? "Overwriting end of array!\n" : "OK",
20462 (UV)REGNODE_OFFSET(place),
20463 (UV)(RExC_parse - RExC_start),
20464 (UV)RExC_offsets[0]));
20465 Set_Node_Offset(place, RExC_parse);
20466 Set_Node_Length(place, 1);
20467 }
20468#endif
20469 src = NEXTOPER(place);
20470 FLAGS(place) = 0;
20471 FILL_NODE(operand, op);
20472
20473 /* Zero out any arguments in the new node */
20474 Zero(src, offset, regnode);
20475}
20476
20477/*
20478- regtail - set the next-pointer at the end of a node chain of p to val. If
20479 that value won't fit in the space available, instead returns FALSE.
20480 (Except asserts if we can't fit in the largest space the regex
20481 engine is designed for.)
20482- SEE ALSO: regtail_study
20483*/
20484STATIC bool
20485S_regtail(pTHX_ RExC_state_t * pRExC_state,
20486 const regnode_offset p,
20487 const regnode_offset val,
20488 const U32 depth)
20489{
20490 regnode_offset scan;
20491 GET_RE_DEBUG_FLAGS_DECL;
20492
20493 PERL_ARGS_ASSERT_REGTAIL;
20494#ifndef DEBUGGING
20495 PERL_UNUSED_ARG(depth);
20496#endif
20497
20498 /* Find last node. */
20499 scan = (regnode_offset) p;
20500 for (;;) {
20501 regnode * const temp = regnext(REGNODE_p(scan));
20502 DEBUG_PARSE_r({
20503 DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
20504 regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
20505 Perl_re_printf( aTHX_ "~ %s (%zu) %s %s\n",
20506 SvPV_nolen_const(RExC_mysv), scan,
20507 (temp == NULL ? "->" : ""),
20508 (temp == NULL ? PL_reg_name[OP(REGNODE_p(val))] : "")
20509 );
20510 });
20511 if (temp == NULL)
20512 break;
20513 scan = REGNODE_OFFSET(temp);
20514 }
20515
20516 assert(val >= scan);
20517 if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
20518 assert((UV) (val - scan) <= U32_MAX);
20519 ARG_SET(REGNODE_p(scan), val - scan);
20520 }
20521 else {
20522 if (val - scan > U16_MAX) {
20523 /* Populate this with something that won't loop and will likely
20524 * lead to a crash if the caller ignores the failure return, and
20525 * execution continues */
20526 NEXT_OFF(REGNODE_p(scan)) = U16_MAX;
20527 return FALSE;
20528 }
20529 NEXT_OFF(REGNODE_p(scan)) = val - scan;
20530 }
20531
20532 return TRUE;
20533}
20534
20535#ifdef DEBUGGING
20536/*
20537- regtail_study - set the next-pointer at the end of a node chain of p to val.
20538- Look for optimizable sequences at the same time.
20539- currently only looks for EXACT chains.
20540
20541This is experimental code. The idea is to use this routine to perform
20542in place optimizations on branches and groups as they are constructed,
20543with the long term intention of removing optimization from study_chunk so
20544that it is purely analytical.
20545
20546Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
20547to control which is which.
20548
20549This used to return a value that was ignored. It was a problem that it is
20550#ifdef'd to be another function that didn't return a value. khw has changed it
20551so both currently return a pass/fail return.
20552
20553*/
20554/* TODO: All four parms should be const */
20555
20556STATIC bool
20557S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode_offset p,
20558 const regnode_offset val, U32 depth)
20559{
20560 regnode_offset scan;
20561 U8 exact = PSEUDO;
20562#ifdef EXPERIMENTAL_INPLACESCAN
20563 I32 min = 0;
20564#endif
20565 GET_RE_DEBUG_FLAGS_DECL;
20566
20567 PERL_ARGS_ASSERT_REGTAIL_STUDY;
20568
20569
20570 /* Find last node. */
20571
20572 scan = p;
20573 for (;;) {
20574 regnode * const temp = regnext(REGNODE_p(scan));
20575#ifdef EXPERIMENTAL_INPLACESCAN
20576 if (PL_regkind[OP(REGNODE_p(scan))] == EXACT) {
20577 bool unfolded_multi_char; /* Unexamined in this routine */
20578 if (join_exact(pRExC_state, scan, &min,
20579 &unfolded_multi_char, 1, REGNODE_p(val), depth+1))
20580 return TRUE; /* Was return EXACT */
20581 }
20582#endif
20583 if ( exact ) {
20584 switch (OP(REGNODE_p(scan))) {
20585 case LEXACT:
20586 case EXACT:
20587 case LEXACT_REQ8:
20588 case EXACT_REQ8:
20589 case EXACTL:
20590 case EXACTF:
20591 case EXACTFU_S_EDGE:
20592 case EXACTFAA_NO_TRIE:
20593 case EXACTFAA:
20594 case EXACTFU:
20595 case EXACTFU_REQ8:
20596 case EXACTFLU8:
20597 case EXACTFUP:
20598 case EXACTFL:
20599 if( exact == PSEUDO )
20600 exact= OP(REGNODE_p(scan));
20601 else if ( exact != OP(REGNODE_p(scan)) )
20602 exact= 0;
20603 case NOTHING:
20604 break;
20605 default:
20606 exact= 0;
20607 }
20608 }
20609 DEBUG_PARSE_r({
20610 DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
20611 regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
20612 Perl_re_printf( aTHX_ "~ %s (%zu) -> %s\n",
20613 SvPV_nolen_const(RExC_mysv),
20614 scan,
20615 PL_reg_name[exact]);
20616 });
20617 if (temp == NULL)
20618 break;
20619 scan = REGNODE_OFFSET(temp);
20620 }
20621 DEBUG_PARSE_r({
20622 DEBUG_PARSE_MSG("");
20623 regprop(RExC_rx, RExC_mysv, REGNODE_p(val), NULL, pRExC_state);
20624 Perl_re_printf( aTHX_
20625 "~ attach to %s (%" IVdf ") offset to %" IVdf "\n",
20626 SvPV_nolen_const(RExC_mysv),
20627 (IV)val,
20628 (IV)(val - scan)
20629 );
20630 });
20631 if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
20632 assert((UV) (val - scan) <= U32_MAX);
20633 ARG_SET(REGNODE_p(scan), val - scan);
20634 }
20635 else {
20636 if (val - scan > U16_MAX) {
20637 /* Populate this with something that won't loop and will likely
20638 * lead to a crash if the caller ignores the failure return, and
20639 * execution continues */
20640 NEXT_OFF(REGNODE_p(scan)) = U16_MAX;
20641 return FALSE;
20642 }
20643 NEXT_OFF(REGNODE_p(scan)) = val - scan;
20644 }
20645
20646 return TRUE; /* Was 'return exact' */
20647}
20648#endif
20649
20650STATIC SV*
20651S_get_ANYOFM_contents(pTHX_ const regnode * n) {
20652
20653 /* Returns an inversion list of all the code points matched by the
20654 * ANYOFM/NANYOFM node 'n' */
20655
20656 SV * cp_list = _new_invlist(-1);
20657 const U8 lowest = (U8) ARG(n);
20658 unsigned int i;
20659 U8 count = 0;
20660 U8 needed = 1U << PL_bitcount[ (U8) ~ FLAGS(n)];
20661
20662 PERL_ARGS_ASSERT_GET_ANYOFM_CONTENTS;
20663
20664 /* Starting with the lowest code point, any code point that ANDed with the
20665 * mask yields the lowest code point is in the set */
20666 for (i = lowest; i <= 0xFF; i++) {
20667 if ((i & FLAGS(n)) == ARG(n)) {
20668 cp_list = add_cp_to_invlist(cp_list, i);
20669 count++;
20670
20671 /* We know how many code points (a power of two) that are in the
20672 * set. No use looking once we've got that number */
20673 if (count >= needed) break;
20674 }
20675 }
20676
20677 if (OP(n) == NANYOFM) {
20678 _invlist_invert(cp_list);
20679 }
20680 return cp_list;
20681}
20682
20683/*
20684 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
20685 */
20686#ifdef DEBUGGING
20687
20688static void
20689S_regdump_intflags(pTHX_ const char *lead, const U32 flags)
20690{
20691 int bit;
20692 int set=0;
20693
20694 ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8);
20695
20696 for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) {
20697 if (flags & (1<<bit)) {
20698 if (!set++ && lead)
20699 Perl_re_printf( aTHX_ "%s", lead);
20700 Perl_re_printf( aTHX_ "%s ", PL_reg_intflags_name[bit]);
20701 }
20702 }
20703 if (lead) {
20704 if (set)
20705 Perl_re_printf( aTHX_ "\n");
20706 else
20707 Perl_re_printf( aTHX_ "%s[none-set]\n", lead);
20708 }
20709}
20710
20711static void
20712S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
20713{
20714 int bit;
20715 int set=0;
20716 regex_charset cs;
20717
20718 ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8);
20719
20720 for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) {
20721 if (flags & (1<<bit)) {
20722 if ((1<<bit) & RXf_PMf_CHARSET) { /* Output separately, below */
20723 continue;
20724 }
20725 if (!set++ && lead)
20726 Perl_re_printf( aTHX_ "%s", lead);
20727 Perl_re_printf( aTHX_ "%s ", PL_reg_extflags_name[bit]);
20728 }
20729 }
20730 if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
20731 if (!set++ && lead) {
20732 Perl_re_printf( aTHX_ "%s", lead);
20733 }
20734 switch (cs) {
20735 case REGEX_UNICODE_CHARSET:
20736 Perl_re_printf( aTHX_ "UNICODE");
20737 break;
20738 case REGEX_LOCALE_CHARSET:
20739 Perl_re_printf( aTHX_ "LOCALE");
20740 break;
20741 case REGEX_ASCII_RESTRICTED_CHARSET:
20742 Perl_re_printf( aTHX_ "ASCII-RESTRICTED");
20743 break;
20744 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
20745 Perl_re_printf( aTHX_ "ASCII-MORE_RESTRICTED");
20746 break;
20747 default:
20748 Perl_re_printf( aTHX_ "UNKNOWN CHARACTER SET");
20749 break;
20750 }
20751 }
20752 if (lead) {
20753 if (set)
20754 Perl_re_printf( aTHX_ "\n");
20755 else
20756 Perl_re_printf( aTHX_ "%s[none-set]\n", lead);
20757 }
20758}
20759#endif
20760
20761void
20762Perl_regdump(pTHX_ const regexp *r)
20763{
20764#ifdef DEBUGGING
20765 int i;
20766 SV * const sv = sv_newmortal();
20767 SV *dsv= sv_newmortal();
20768 RXi_GET_DECL(r, ri);
20769 GET_RE_DEBUG_FLAGS_DECL;
20770
20771 PERL_ARGS_ASSERT_REGDUMP;
20772
20773 (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
20774
20775 /* Header fields of interest. */
20776 for (i = 0; i < 2; i++) {
20777 if (r->substrs->data[i].substr) {
20778 RE_PV_QUOTED_DECL(s, 0, dsv,
20779 SvPVX_const(r->substrs->data[i].substr),
20780 RE_SV_DUMPLEN(r->substrs->data[i].substr),
20781 PL_dump_re_max_len);
20782 Perl_re_printf( aTHX_
20783 "%s %s%s at %" IVdf "..%" UVuf " ",
20784 i ? "floating" : "anchored",
20785 s,
20786 RE_SV_TAIL(r->substrs->data[i].substr),
20787 (IV)r->substrs->data[i].min_offset,
20788 (UV)r->substrs->data[i].max_offset);
20789 }
20790 else if (r->substrs->data[i].utf8_substr) {
20791 RE_PV_QUOTED_DECL(s, 1, dsv,
20792 SvPVX_const(r->substrs->data[i].utf8_substr),
20793 RE_SV_DUMPLEN(r->substrs->data[i].utf8_substr),
20794 30);
20795 Perl_re_printf( aTHX_
20796 "%s utf8 %s%s at %" IVdf "..%" UVuf " ",
20797 i ? "floating" : "anchored",
20798 s,
20799 RE_SV_TAIL(r->substrs->data[i].utf8_substr),
20800 (IV)r->substrs->data[i].min_offset,
20801 (UV)r->substrs->data[i].max_offset);
20802 }
20803 }
20804
20805 if (r->check_substr || r->check_utf8)
20806 Perl_re_printf( aTHX_
20807 (const char *)
20808 ( r->check_substr == r->substrs->data[1].substr
20809 && r->check_utf8 == r->substrs->data[1].utf8_substr
20810 ? "(checking floating" : "(checking anchored"));
20811 if (r->intflags & PREGf_NOSCAN)
20812 Perl_re_printf( aTHX_ " noscan");
20813 if (r->extflags & RXf_CHECK_ALL)
20814 Perl_re_printf( aTHX_ " isall");
20815 if (r->check_substr || r->check_utf8)
20816 Perl_re_printf( aTHX_ ") ");
20817
20818 if (ri->regstclass) {
20819 regprop(r, sv, ri->regstclass, NULL, NULL);
20820 Perl_re_printf( aTHX_ "stclass %s ", SvPVX_const(sv));
20821 }
20822 if (r->intflags & PREGf_ANCH) {
20823 Perl_re_printf( aTHX_ "anchored");
20824 if (r->intflags & PREGf_ANCH_MBOL)
20825 Perl_re_printf( aTHX_ "(MBOL)");
20826 if (r->intflags & PREGf_ANCH_SBOL)
20827 Perl_re_printf( aTHX_ "(SBOL)");
20828 if (r->intflags & PREGf_ANCH_GPOS)
20829 Perl_re_printf( aTHX_ "(GPOS)");
20830 Perl_re_printf( aTHX_ " ");
20831 }
20832 if (r->intflags & PREGf_GPOS_SEEN)
20833 Perl_re_printf( aTHX_ "GPOS:%" UVuf " ", (UV)r->gofs);
20834 if (r->intflags & PREGf_SKIP)
20835 Perl_re_printf( aTHX_ "plus ");
20836 if (r->intflags & PREGf_IMPLICIT)
20837 Perl_re_printf( aTHX_ "implicit ");
20838 Perl_re_printf( aTHX_ "minlen %" IVdf " ", (IV)r->minlen);
20839 if (r->extflags & RXf_EVAL_SEEN)
20840 Perl_re_printf( aTHX_ "with eval ");
20841 Perl_re_printf( aTHX_ "\n");
20842 DEBUG_FLAGS_r({
20843 regdump_extflags("r->extflags: ", r->extflags);
20844 regdump_intflags("r->intflags: ", r->intflags);
20845 });
20846#else
20847 PERL_ARGS_ASSERT_REGDUMP;
20848 PERL_UNUSED_CONTEXT;
20849 PERL_UNUSED_ARG(r);
20850#endif /* DEBUGGING */
20851}
20852
20853/* Should be synchronized with ANYOF_ #defines in regcomp.h */
20854#ifdef DEBUGGING
20855
20856# if _CC_WORDCHAR != 0 || _CC_DIGIT != 1 || _CC_ALPHA != 2 \
20857 || _CC_LOWER != 3 || _CC_UPPER != 4 || _CC_PUNCT != 5 \
20858 || _CC_PRINT != 6 || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8 \
20859 || _CC_CASED != 9 || _CC_SPACE != 10 || _CC_BLANK != 11 \
20860 || _CC_XDIGIT != 12 || _CC_CNTRL != 13 || _CC_ASCII != 14 \
20861 || _CC_VERTSPACE != 15
20862# error Need to adjust order of anyofs[]
20863# endif
20864static const char * const anyofs[] = {
20865 "\\w",
20866 "\\W",
20867 "\\d",
20868 "\\D",
20869 "[:alpha:]",
20870 "[:^alpha:]",
20871 "[:lower:]",
20872 "[:^lower:]",
20873 "[:upper:]",
20874 "[:^upper:]",
20875 "[:punct:]",
20876 "[:^punct:]",
20877 "[:print:]",
20878 "[:^print:]",
20879 "[:alnum:]",
20880 "[:^alnum:]",
20881 "[:graph:]",
20882 "[:^graph:]",
20883 "[:cased:]",
20884 "[:^cased:]",
20885 "\\s",
20886 "\\S",
20887 "[:blank:]",
20888 "[:^blank:]",
20889 "[:xdigit:]",
20890 "[:^xdigit:]",
20891 "[:cntrl:]",
20892 "[:^cntrl:]",
20893 "[:ascii:]",
20894 "[:^ascii:]",
20895 "\\v",
20896 "\\V"
20897};
20898#endif
20899
20900/*
20901- regprop - printable representation of opcode, with run time support
20902*/
20903
20904void
20905Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state)
20906{
20907#ifdef DEBUGGING
20908 dVAR;
20909 int k;
20910 RXi_GET_DECL(prog, progi);
20911 GET_RE_DEBUG_FLAGS_DECL;
20912
20913 PERL_ARGS_ASSERT_REGPROP;
20914
20915 SvPVCLEAR(sv);
20916
20917 if (OP(o) > REGNODE_MAX) { /* regnode.type is unsigned */
20918 if (pRExC_state) { /* This gives more info, if we have it */
20919 FAIL3("panic: corrupted regexp opcode %d > %d",
20920 (int)OP(o), (int)REGNODE_MAX);
20921 }
20922 else {
20923 Perl_croak(aTHX_ "panic: corrupted regexp opcode %d > %d",
20924 (int)OP(o), (int)REGNODE_MAX);
20925 }
20926 }
20927 sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
20928
20929 k = PL_regkind[OP(o)];
20930
20931 if (k == EXACT) {
20932 sv_catpvs(sv, " ");
20933 /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
20934 * is a crude hack but it may be the best for now since
20935 * we have no flag "this EXACTish node was UTF-8"
20936 * --jhi */
20937 pv_pretty(sv, STRING(o), STR_LEN(o), PL_dump_re_max_len,
20938 PL_colors[0], PL_colors[1],
20939 PERL_PV_ESCAPE_UNI_DETECT |
20940 PERL_PV_ESCAPE_NONASCII |
20941 PERL_PV_PRETTY_ELLIPSES |
20942 PERL_PV_PRETTY_LTGT |
20943 PERL_PV_PRETTY_NOCLEAR
20944 );
20945 } else if (k == TRIE) {
20946 /* print the details of the trie in dumpuntil instead, as
20947 * progi->data isn't available here */
20948 const char op = OP(o);
20949 const U32 n = ARG(o);
20950 const reg_ac_data * const ac = IS_TRIE_AC(op) ?
20951 (reg_ac_data *)progi->data->data[n] :
20952 NULL;
20953 const reg_trie_data * const trie
20954 = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
20955
20956 Perl_sv_catpvf(aTHX_ sv, "-%s", PL_reg_name[o->flags]);
20957 DEBUG_TRIE_COMPILE_r({
20958 if (trie->jump)
20959 sv_catpvs(sv, "(JUMP)");
20960 Perl_sv_catpvf(aTHX_ sv,
20961 "<S:%" UVuf "/%" IVdf " W:%" UVuf " L:%" UVuf "/%" UVuf " C:%" UVuf "/%" UVuf ">",
20962 (UV)trie->startstate,
20963 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
20964 (UV)trie->wordcount,
20965 (UV)trie->minlen,
20966 (UV)trie->maxlen,
20967 (UV)TRIE_CHARCOUNT(trie),
20968 (UV)trie->uniquecharcount
20969 );
20970 });
20971 if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
20972 sv_catpvs(sv, "[");
20973 (void) put_charclass_bitmap_innards(sv,
20974 ((IS_ANYOF_TRIE(op))
20975 ? ANYOF_BITMAP(o)
20976 : TRIE_BITMAP(trie)),
20977 NULL,
20978 NULL,
20979 NULL,
20980 0,
20981 FALSE
20982 );
20983 sv_catpvs(sv, "]");
20984 }
20985 } else if (k == CURLY) {
20986 U32 lo = ARG1(o), hi = ARG2(o);
20987 if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
20988 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
20989 Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo);
20990 if (hi == REG_INFTY)
20991 sv_catpvs(sv, "INFTY");
20992 else
20993 Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi);
20994 sv_catpvs(sv, "}");
20995 }
20996 else if (k == WHILEM && o->flags) /* Ordinal/of */
20997 Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
20998 else if (k == REF || k == OPEN || k == CLOSE
20999 || k == GROUPP || OP(o)==ACCEPT)
21000 {
21001 AV *name_list= NULL;
21002 U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o);
21003 Perl_sv_catpvf(aTHX_ sv, "%" UVuf, (UV)parno); /* Parenth number */
21004 if ( RXp_PAREN_NAMES(prog) ) {
21005 name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
21006 } else if ( pRExC_state ) {
21007 name_list= RExC_paren_name_list;
21008 }
21009 if (name_list) {
21010 if ( k != REF || (OP(o) < REFN)) {
21011 SV **name= av_fetch(name_list, parno, 0 );
21012 if (name)
21013 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
21014 }
21015 else {
21016 SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]);
21017 I32 *nums=(I32*)SvPVX(sv_dat);
21018 SV **name= av_fetch(name_list, nums[0], 0 );
21019 I32 n;
21020 if (name) {
21021 for ( n=0; n<SvIVX(sv_dat); n++ ) {
21022 Perl_sv_catpvf(aTHX_ sv, "%s%" IVdf,
21023 (n ? "," : ""), (IV)nums[n]);
21024 }
21025 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
21026 }
21027 }
21028 }
21029 if ( k == REF && reginfo) {
21030 U32 n = ARG(o); /* which paren pair */
21031 I32 ln = prog->offs[n].start;
21032 if (prog->lastparen < n || ln == -1 || prog->offs[n].end == -1)
21033 Perl_sv_catpvf(aTHX_ sv, ": FAIL");
21034 else if (ln == prog->offs[n].end)
21035 Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING");
21036 else {
21037 const char *s = reginfo->strbeg + ln;
21038 Perl_sv_catpvf(aTHX_ sv, ": ");
21039 Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0,
21040 PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE );
21041 }
21042 }
21043 } else if (k == GOSUB) {
21044 AV *name_list= NULL;
21045 if ( RXp_PAREN_NAMES(prog) ) {
21046 name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
21047 } else if ( pRExC_state ) {
21048 name_list= RExC_paren_name_list;
21049 }
21050
21051 /* Paren and offset */
21052 Perl_sv_catpvf(aTHX_ sv, "%d[%+d:%d]", (int)ARG(o),(int)ARG2L(o),
21053 (int)((o + (int)ARG2L(o)) - progi->program) );
21054 if (name_list) {
21055 SV **name= av_fetch(name_list, ARG(o), 0 );
21056 if (name)
21057 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
21058 }
21059 }
21060 else if (k == LOGICAL)
21061 /* 2: embedded, otherwise 1 */
21062 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);
21063 else if (k == ANYOF || k == ANYOFR) {
21064 U8 flags;
21065 char * bitmap;
21066 U32 arg;
21067 bool do_sep = FALSE; /* Do we need to separate various components of
21068 the output? */
21069 /* Set if there is still an unresolved user-defined property */
21070 SV *unresolved = NULL;
21071
21072 /* Things that are ignored except when the runtime locale is UTF-8 */
21073 SV *only_utf8_locale_invlist = NULL;
21074
21075 /* Code points that don't fit in the bitmap */
21076 SV *nonbitmap_invlist = NULL;
21077
21078 /* And things that aren't in the bitmap, but are small enough to be */
21079 SV* bitmap_range_not_in_bitmap = NULL;
21080
21081 bool inverted;
21082
21083 if (inRANGE(OP(o), ANYOFH, ANYOFRb)) {
21084 flags = 0;
21085 bitmap = NULL;
21086 arg = 0;
21087 }
21088 else {
21089 flags = ANYOF_FLAGS(o);
21090 bitmap = ANYOF_BITMAP(o);
21091 arg = ARG(o);
21092 }
21093
21094 if (OP(o) == ANYOFL || OP(o) == ANYOFPOSIXL) {
21095 if (ANYOFL_UTF8_LOCALE_REQD(flags)) {
21096 sv_catpvs(sv, "{utf8-locale-reqd}");
21097 }
21098 if (flags & ANYOFL_FOLD) {
21099 sv_catpvs(sv, "{i}");
21100 }
21101 }
21102
21103 inverted = flags & ANYOF_INVERT;
21104
21105 /* If there is stuff outside the bitmap, get it */
21106 if (arg != ANYOF_ONLY_HAS_BITMAP) {
21107 if (inRANGE(OP(o), ANYOFR, ANYOFRb)) {
21108 nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
21109 ANYOFRbase(o),
21110 ANYOFRbase(o) + ANYOFRdelta(o));
21111 }
21112 else {
21113 (void) _get_regclass_nonbitmap_data(prog, o, FALSE,
21114 &unresolved,
21115 &only_utf8_locale_invlist,
21116 &nonbitmap_invlist);
21117 }
21118
21119 /* The non-bitmap data may contain stuff that could fit in the
21120 * bitmap. This could come from a user-defined property being
21121 * finally resolved when this call was done; or much more likely
21122 * because there are matches that require UTF-8 to be valid, and so
21123 * aren't in the bitmap (or ANYOFR). This is teased apart later */
21124 _invlist_intersection(nonbitmap_invlist,
21125 PL_InBitmap,
21126 &bitmap_range_not_in_bitmap);
21127 /* Leave just the things that don't fit into the bitmap */
21128 _invlist_subtract(nonbitmap_invlist,
21129 PL_InBitmap,
21130 &nonbitmap_invlist);
21131 }
21132
21133 /* Obey this flag to add all above-the-bitmap code points */
21134 if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
21135 nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
21136 NUM_ANYOF_CODE_POINTS,
21137 UV_MAX);
21138 }
21139
21140 /* Ready to start outputting. First, the initial left bracket */
21141 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
21142
21143 /* ANYOFH by definition doesn't have anything that will fit inside the
21144 * bitmap; ANYOFR may or may not. */
21145 if ( ! inRANGE(OP(o), ANYOFH, ANYOFHr)
21146 && ( ! inRANGE(OP(o), ANYOFR, ANYOFRb)
21147 || ANYOFRbase(o) < NUM_ANYOF_CODE_POINTS))
21148 {
21149 /* Then all the things that could fit in the bitmap */
21150 do_sep = put_charclass_bitmap_innards(sv,
21151 bitmap,
21152 bitmap_range_not_in_bitmap,
21153 only_utf8_locale_invlist,
21154 o,
21155 flags,
21156
21157 /* Can't try inverting for a
21158 * better display if there
21159 * are things that haven't
21160 * been resolved */
21161 unresolved != NULL
21162 || inRANGE(OP(o), ANYOFR, ANYOFRb));
21163 SvREFCNT_dec(bitmap_range_not_in_bitmap);
21164
21165 /* If there are user-defined properties which haven't been defined
21166 * yet, output them. If the result is not to be inverted, it is
21167 * clearest to output them in a separate [] from the bitmap range
21168 * stuff. If the result is to be complemented, we have to show
21169 * everything in one [], as the inversion applies to the whole
21170 * thing. Use {braces} to separate them from anything in the
21171 * bitmap and anything above the bitmap. */
21172 if (unresolved) {
21173 if (inverted) {
21174 if (! do_sep) { /* If didn't output anything in the bitmap
21175 */
21176 sv_catpvs(sv, "^");
21177 }
21178 sv_catpvs(sv, "{");
21179 }
21180 else if (do_sep) {
21181 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1],
21182 PL_colors[0]);
21183 }
21184 sv_catsv(sv, unresolved);
21185 if (inverted) {
21186 sv_catpvs(sv, "}");
21187 }
21188 do_sep = ! inverted;
21189 }
21190 }
21191
21192 /* And, finally, add the above-the-bitmap stuff */
21193 if (nonbitmap_invlist && _invlist_len(nonbitmap_invlist)) {
21194 SV* contents;
21195
21196 /* See if truncation size is overridden */
21197 const STRLEN dump_len = (PL_dump_re_max_len > 256)
21198 ? PL_dump_re_max_len
21199 : 256;
21200
21201 /* This is output in a separate [] */
21202 if (do_sep) {
21203 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]);
21204 }
21205
21206 /* And, for easy of understanding, it is shown in the
21207 * uncomplemented form if possible. The one exception being if
21208 * there are unresolved items, where the inversion has to be
21209 * delayed until runtime */
21210 if (inverted && ! unresolved) {
21211 _invlist_invert(nonbitmap_invlist);
21212 _invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist);
21213 }
21214
21215 contents = invlist_contents(nonbitmap_invlist,
21216 FALSE /* output suitable for catsv */
21217 );
21218
21219 /* If the output is shorter than the permissible maximum, just do it. */
21220 if (SvCUR(contents) <= dump_len) {
21221 sv_catsv(sv, contents);
21222 }
21223 else {
21224 const char * contents_string = SvPVX(contents);
21225 STRLEN i = dump_len;
21226
21227 /* Otherwise, start at the permissible max and work back to the
21228 * first break possibility */
21229 while (i > 0 && contents_string[i] != ' ') {
21230 i--;
21231 }
21232 if (i == 0) { /* Fail-safe. Use the max if we couldn't
21233 find a legal break */
21234 i = dump_len;
21235 }
21236
21237 sv_catpvn(sv, contents_string, i);
21238 sv_catpvs(sv, "...");
21239 }
21240
21241 SvREFCNT_dec_NN(contents);
21242 SvREFCNT_dec_NN(nonbitmap_invlist);
21243 }
21244
21245 /* And finally the matching, closing ']' */
21246 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
21247
21248 if (OP(o) == ANYOFHs) {
21249 Perl_sv_catpvf(aTHX_ sv, " (Leading UTF-8 bytes=%s", _byte_dump_string((U8 *) ((struct regnode_anyofhs *) o)->string, FLAGS(o), 1));
21250 }
21251 else if (inRANGE(OP(o), ANYOFH, ANYOFRb)) {
21252 U8 lowest = (OP(o) != ANYOFHr)
21253 ? FLAGS(o)
21254 : LOWEST_ANYOF_HRx_BYTE(FLAGS(o));
21255 U8 highest = (OP(o) == ANYOFHr)
21256 ? HIGHEST_ANYOF_HRx_BYTE(FLAGS(o))
21257 : (OP(o) == ANYOFH || OP(o) == ANYOFR)
21258 ? 0xFF
21259 : lowest;
21260 Perl_sv_catpvf(aTHX_ sv, " (First UTF-8 byte=%02X", lowest);
21261 if (lowest != highest) {
21262 Perl_sv_catpvf(aTHX_ sv, "-%02X", highest);
21263 }
21264 Perl_sv_catpvf(aTHX_ sv, ")");
21265 }
21266
21267 SvREFCNT_dec(unresolved);
21268 }
21269 else if (k == ANYOFM) {
21270 SV * cp_list = get_ANYOFM_contents(o);
21271
21272 Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
21273 if (OP(o) == NANYOFM) {
21274 _invlist_invert(cp_list);
21275 }
21276
21277 put_charclass_bitmap_innards(sv, NULL, cp_list, NULL, NULL, 0, TRUE);
21278 Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
21279
21280 SvREFCNT_dec(cp_list);
21281 }
21282 else if (k == POSIXD || k == NPOSIXD) {
21283 U8 index = FLAGS(o) * 2;
21284 if (index < C_ARRAY_LENGTH(anyofs)) {
21285 if (*anyofs[index] != '[') {
21286 sv_catpvs(sv, "[");
21287 }
21288 sv_catpv(sv, anyofs[index]);
21289 if (*anyofs[index] != '[') {
21290 sv_catpvs(sv, "]");
21291 }
21292 }
21293 else {
21294 Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
21295 }
21296 }
21297 else if (k == BOUND || k == NBOUND) {
21298 /* Must be synced with order of 'bound_type' in regcomp.h */
21299 const char * const bounds[] = {
21300 "", /* Traditional */
21301 "{gcb}",
21302 "{lb}",
21303 "{sb}",
21304 "{wb}"
21305 };
21306 assert(FLAGS(o) < C_ARRAY_LENGTH(bounds));
21307 sv_catpv(sv, bounds[FLAGS(o)]);
21308 }
21309 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH)) {
21310 Perl_sv_catpvf(aTHX_ sv, "[%d", -(o->flags));
21311 if (o->next_off) {
21312 Perl_sv_catpvf(aTHX_ sv, "..-%d", o->flags - o->next_off);
21313 }
21314 Perl_sv_catpvf(aTHX_ sv, "]");
21315 }
21316 else if (OP(o) == SBOL)
21317 Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^");
21318
21319 /* add on the verb argument if there is one */
21320 if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) {
21321 if ( ARG(o) )
21322 Perl_sv_catpvf(aTHX_ sv, ":%" SVf,
21323 SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
21324 else
21325 sv_catpvs(sv, ":NULL");
21326 }
21327#else
21328 PERL_UNUSED_CONTEXT;
21329 PERL_UNUSED_ARG(sv);
21330 PERL_UNUSED_ARG(o);
21331 PERL_UNUSED_ARG(prog);
21332 PERL_UNUSED_ARG(reginfo);
21333 PERL_UNUSED_ARG(pRExC_state);
21334#endif /* DEBUGGING */
21335}
21336
21337
21338
21339SV *
21340Perl_re_intuit_string(pTHX_ REGEXP * const r)
21341{ /* Assume that RE_INTUIT is set */
21342 /* Returns an SV containing a string that must appear in the target for it
21343 * to match */
21344
21345 struct regexp *const prog = ReANY(r);
21346 GET_RE_DEBUG_FLAGS_DECL;
21347
21348 PERL_ARGS_ASSERT_RE_INTUIT_STRING;
21349 PERL_UNUSED_CONTEXT;
21350
21351 DEBUG_COMPILE_r(
21352 {
21353 if (prog->maxlen > 0) {
21354 const char * const s = SvPV_nolen_const(RX_UTF8(r)
21355 ? prog->check_utf8 : prog->check_substr);
21356
21357 if (!PL_colorset) reginitcolors();
21358 Perl_re_printf( aTHX_
21359 "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
21360 PL_colors[4],
21361 RX_UTF8(r) ? "utf8 " : "",
21362 PL_colors[5], PL_colors[0],
21363 s,
21364 PL_colors[1],
21365 (strlen(s) > PL_dump_re_max_len ? "..." : ""));
21366 }
21367 } );
21368
21369 /* use UTF8 check substring if regexp pattern itself is in UTF8 */
21370 return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr;
21371}
21372
21373/*
21374 pregfree()
21375
21376 handles refcounting and freeing the perl core regexp structure. When
21377 it is necessary to actually free the structure the first thing it
21378 does is call the 'free' method of the regexp_engine associated to
21379 the regexp, allowing the handling of the void *pprivate; member
21380 first. (This routine is not overridable by extensions, which is why
21381 the extensions free is called first.)
21382
21383 See regdupe and regdupe_internal if you change anything here.
21384*/
21385#ifndef PERL_IN_XSUB_RE
21386void
21387Perl_pregfree(pTHX_ REGEXP *r)
21388{
21389 SvREFCNT_dec(r);
21390}
21391
21392void
21393Perl_pregfree2(pTHX_ REGEXP *rx)
21394{
21395 struct regexp *const r = ReANY(rx);
21396 GET_RE_DEBUG_FLAGS_DECL;
21397
21398 PERL_ARGS_ASSERT_PREGFREE2;
21399
21400 if (! r)
21401 return;
21402
21403 if (r->mother_re) {
21404 ReREFCNT_dec(r->mother_re);
21405 } else {
21406 CALLREGFREE_PVT(rx); /* free the private data */
21407 SvREFCNT_dec(RXp_PAREN_NAMES(r));
21408 }
21409 if (r->substrs) {
21410 int i;
21411 for (i = 0; i < 2; i++) {
21412 SvREFCNT_dec(r->substrs->data[i].substr);
21413 SvREFCNT_dec(r->substrs->data[i].utf8_substr);
21414 }
21415 Safefree(r->substrs);
21416 }
21417 RX_MATCH_COPY_FREE(rx);
21418#ifdef PERL_ANY_COW
21419 SvREFCNT_dec(r->saved_copy);
21420#endif
21421 Safefree(r->offs);
21422 SvREFCNT_dec(r->qr_anoncv);
21423 if (r->recurse_locinput)
21424 Safefree(r->recurse_locinput);
21425}
21426
21427
21428/* reg_temp_copy()
21429
21430 Copy ssv to dsv, both of which should of type SVt_REGEXP or SVt_PVLV,
21431 except that dsv will be created if NULL.
21432
21433 This function is used in two main ways. First to implement
21434 $r = qr/....; $s = $$r;
21435
21436 Secondly, it is used as a hacky workaround to the structural issue of
21437 match results
21438 being stored in the regexp structure which is in turn stored in
21439 PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
21440 could be PL_curpm in multiple contexts, and could require multiple
21441 result sets being associated with the pattern simultaneously, such
21442 as when doing a recursive match with (??{$qr})
21443
21444 The solution is to make a lightweight copy of the regexp structure
21445 when a qr// is returned from the code executed by (??{$qr}) this
21446 lightweight copy doesn't actually own any of its data except for
21447 the starp/end and the actual regexp structure itself.
21448
21449*/
21450
21451
21452REGEXP *
21453Perl_reg_temp_copy(pTHX_ REGEXP *dsv, REGEXP *ssv)
21454{
21455 struct regexp *drx;
21456 struct regexp *const srx = ReANY(ssv);
21457 const bool islv = dsv && SvTYPE(dsv) == SVt_PVLV;
21458
21459 PERL_ARGS_ASSERT_REG_TEMP_COPY;
21460
21461 if (!dsv)
21462 dsv = (REGEXP*) newSV_type(SVt_REGEXP);
21463 else {
21464 assert(SvTYPE(dsv) == SVt_REGEXP || (SvTYPE(dsv) == SVt_PVLV));
21465
21466 /* our only valid caller, sv_setsv_flags(), should have done
21467 * a SV_CHECK_THINKFIRST_COW_DROP() by now */
21468 assert(!SvOOK(dsv));
21469 assert(!SvIsCOW(dsv));
21470 assert(!SvROK(dsv));
21471
21472 if (SvPVX_const(dsv)) {
21473 if (SvLEN(dsv))
21474 Safefree(SvPVX(dsv));
21475 SvPVX(dsv) = NULL;
21476 }
21477 SvLEN_set(dsv, 0);
21478 SvCUR_set(dsv, 0);
21479 SvOK_off((SV *)dsv);
21480
21481 if (islv) {
21482 /* For PVLVs, the head (sv_any) points to an XPVLV, while
21483 * the LV's xpvlenu_rx will point to a regexp body, which
21484 * we allocate here */
21485 REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
21486 assert(!SvPVX(dsv));
21487 ((XPV*)SvANY(dsv))->xpv_len_u.xpvlenu_rx = temp->sv_any;
21488 temp->sv_any = NULL;
21489 SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
21490 SvREFCNT_dec_NN(temp);
21491 /* SvCUR still resides in the xpvlv struct, so the regexp copy-
21492 ing below will not set it. */
21493 SvCUR_set(dsv, SvCUR(ssv));
21494 }
21495 }
21496 /* This ensures that SvTHINKFIRST(sv) is true, and hence that
21497 sv_force_normal(sv) is called. */
21498 SvFAKE_on(dsv);
21499 drx = ReANY(dsv);
21500
21501 SvFLAGS(dsv) |= SvFLAGS(ssv) & (SVf_POK|SVp_POK|SVf_UTF8);
21502 SvPV_set(dsv, RX_WRAPPED(ssv));
21503 /* We share the same string buffer as the original regexp, on which we
21504 hold a reference count, incremented when mother_re is set below.
21505 The string pointer is copied here, being part of the regexp struct.
21506 */
21507 memcpy(&(drx->xpv_cur), &(srx->xpv_cur),
21508 sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
21509 if (!islv)
21510 SvLEN_set(dsv, 0);
21511 if (srx->offs) {
21512 const I32 npar = srx->nparens+1;
21513 Newx(drx->offs, npar, regexp_paren_pair);
21514 Copy(srx->offs, drx->offs, npar, regexp_paren_pair);
21515 }
21516 if (srx->substrs) {
21517 int i;
21518 Newx(drx->substrs, 1, struct reg_substr_data);
21519 StructCopy(srx->substrs, drx->substrs, struct reg_substr_data);
21520
21521 for (i = 0; i < 2; i++) {
21522 SvREFCNT_inc_void(drx->substrs->data[i].substr);
21523 SvREFCNT_inc_void(drx->substrs->data[i].utf8_substr);
21524 }
21525
21526 /* check_substr and check_utf8, if non-NULL, point to either their
21527 anchored or float namesakes, and don't hold a second reference. */
21528 }
21529 RX_MATCH_COPIED_off(dsv);
21530#ifdef PERL_ANY_COW
21531 drx->saved_copy = NULL;
21532#endif
21533 drx->mother_re = ReREFCNT_inc(srx->mother_re ? srx->mother_re : ssv);
21534 SvREFCNT_inc_void(drx->qr_anoncv);
21535 if (srx->recurse_locinput)
21536 Newx(drx->recurse_locinput, srx->nparens + 1, char *);
21537
21538 return dsv;
21539}
21540#endif
21541
21542
21543/* regfree_internal()
21544
21545 Free the private data in a regexp. This is overloadable by
21546 extensions. Perl takes care of the regexp structure in pregfree(),
21547 this covers the *pprivate pointer which technically perl doesn't
21548 know about, however of course we have to handle the
21549 regexp_internal structure when no extension is in use.
21550
21551 Note this is called before freeing anything in the regexp
21552 structure.
21553 */
21554
21555void
21556Perl_regfree_internal(pTHX_ REGEXP * const rx)
21557{
21558 struct regexp *const r = ReANY(rx);
21559 RXi_GET_DECL(r, ri);
21560 GET_RE_DEBUG_FLAGS_DECL;
21561
21562 PERL_ARGS_ASSERT_REGFREE_INTERNAL;
21563
21564 if (! ri) {
21565 return;
21566 }
21567
21568 DEBUG_COMPILE_r({
21569 if (!PL_colorset)
21570 reginitcolors();
21571 {
21572 SV *dsv= sv_newmortal();
21573 RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
21574 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), PL_dump_re_max_len);
21575 Perl_re_printf( aTHX_ "%sFreeing REx:%s %s\n",
21576 PL_colors[4], PL_colors[5], s);
21577 }
21578 });
21579
21580#ifdef RE_TRACK_PATTERN_OFFSETS
21581 if (ri->u.offsets)
21582 Safefree(ri->u.offsets); /* 20010421 MJD */
21583#endif
21584 if (ri->code_blocks)
21585 S_free_codeblocks(aTHX_ ri->code_blocks);
21586
21587 if (ri->data) {
21588 int n = ri->data->count;
21589
21590 while (--n >= 0) {
21591 /* If you add a ->what type here, update the comment in regcomp.h */
21592 switch (ri->data->what[n]) {
21593 case 'a':
21594 case 'r':
21595 case 's':
21596 case 'S':
21597 case 'u':
21598 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
21599 break;
21600 case 'f':
21601 Safefree(ri->data->data[n]);
21602 break;
21603 case 'l':
21604 case 'L':
21605 break;
21606 case 'T':
21607 { /* Aho Corasick add-on structure for a trie node.
21608 Used in stclass optimization only */
21609 U32 refcount;
21610 reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
21611#ifdef USE_ITHREADS
21612 dVAR;
21613#endif
21614 OP_REFCNT_LOCK;
21615 refcount = --aho->refcount;
21616 OP_REFCNT_UNLOCK;
21617 if ( !refcount ) {
21618 PerlMemShared_free(aho->states);
21619 PerlMemShared_free(aho->fail);
21620 /* do this last!!!! */
21621 PerlMemShared_free(ri->data->data[n]);
21622 /* we should only ever get called once, so
21623 * assert as much, and also guard the free
21624 * which /might/ happen twice. At the least
21625 * it will make code anlyzers happy and it
21626 * doesn't cost much. - Yves */
21627 assert(ri->regstclass);
21628 if (ri->regstclass) {
21629 PerlMemShared_free(ri->regstclass);
21630 ri->regstclass = 0;
21631 }
21632 }
21633 }
21634 break;
21635 case 't':
21636 {
21637 /* trie structure. */
21638 U32 refcount;
21639 reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
21640#ifdef USE_ITHREADS
21641 dVAR;
21642#endif
21643 OP_REFCNT_LOCK;
21644 refcount = --trie->refcount;
21645 OP_REFCNT_UNLOCK;
21646 if ( !refcount ) {
21647 PerlMemShared_free(trie->charmap);
21648 PerlMemShared_free(trie->states);
21649 PerlMemShared_free(trie->trans);
21650 if (trie->bitmap)
21651 PerlMemShared_free(trie->bitmap);
21652 if (trie->jump)
21653 PerlMemShared_free(trie->jump);
21654 PerlMemShared_free(trie->wordinfo);
21655 /* do this last!!!! */
21656 PerlMemShared_free(ri->data->data[n]);
21657 }
21658 }
21659 break;
21660 default:
21661 Perl_croak(aTHX_ "panic: regfree data code '%c'",
21662 ri->data->what[n]);
21663 }
21664 }
21665 Safefree(ri->data->what);
21666 Safefree(ri->data);
21667 }
21668
21669 Safefree(ri);
21670}
21671
21672#define av_dup_inc(s, t) MUTABLE_AV(sv_dup_inc((const SV *)s, t))
21673#define hv_dup_inc(s, t) MUTABLE_HV(sv_dup_inc((const SV *)s, t))
21674#define SAVEPVN(p, n) ((p) ? savepvn(p, n) : NULL)
21675
21676/*
21677 re_dup_guts - duplicate a regexp.
21678
21679 This routine is expected to clone a given regexp structure. It is only
21680 compiled under USE_ITHREADS.
21681
21682 After all of the core data stored in struct regexp is duplicated
21683 the regexp_engine.dupe method is used to copy any private data
21684 stored in the *pprivate pointer. This allows extensions to handle
21685 any duplication it needs to do.
21686
21687 See pregfree() and regfree_internal() if you change anything here.
21688*/
21689#if defined(USE_ITHREADS)
21690#ifndef PERL_IN_XSUB_RE
21691void
21692Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
21693{
21694 dVAR;
21695 I32 npar;
21696 const struct regexp *r = ReANY(sstr);
21697 struct regexp *ret = ReANY(dstr);
21698
21699 PERL_ARGS_ASSERT_RE_DUP_GUTS;
21700
21701 npar = r->nparens+1;
21702 Newx(ret->offs, npar, regexp_paren_pair);
21703 Copy(r->offs, ret->offs, npar, regexp_paren_pair);
21704
21705 if (ret->substrs) {
21706 /* Do it this way to avoid reading from *r after the StructCopy().
21707 That way, if any of the sv_dup_inc()s dislodge *r from the L1
21708 cache, it doesn't matter. */
21709 int i;
21710 const bool anchored = r->check_substr
21711 ? r->check_substr == r->substrs->data[0].substr
21712 : r->check_utf8 == r->substrs->data[0].utf8_substr;
21713 Newx(ret->substrs, 1, struct reg_substr_data);
21714 StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
21715
21716 for (i = 0; i < 2; i++) {
21717 ret->substrs->data[i].substr =
21718 sv_dup_inc(ret->substrs->data[i].substr, param);
21719 ret->substrs->data[i].utf8_substr =
21720 sv_dup_inc(ret->substrs->data[i].utf8_substr, param);
21721 }
21722
21723 /* check_substr and check_utf8, if non-NULL, point to either their
21724 anchored or float namesakes, and don't hold a second reference. */
21725
21726 if (ret->check_substr) {
21727 if (anchored) {
21728 assert(r->check_utf8 == r->substrs->data[0].utf8_substr);
21729
21730 ret->check_substr = ret->substrs->data[0].substr;
21731 ret->check_utf8 = ret->substrs->data[0].utf8_substr;
21732 } else {
21733 assert(r->check_substr == r->substrs->data[1].substr);
21734 assert(r->check_utf8 == r->substrs->data[1].utf8_substr);
21735
21736 ret->check_substr = ret->substrs->data[1].substr;
21737 ret->check_utf8 = ret->substrs->data[1].utf8_substr;
21738 }
21739 } else if (ret->check_utf8) {
21740 if (anchored) {
21741 ret->check_utf8 = ret->substrs->data[0].utf8_substr;
21742 } else {
21743 ret->check_utf8 = ret->substrs->data[1].utf8_substr;
21744 }
21745 }
21746 }
21747
21748 RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
21749 ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
21750 if (r->recurse_locinput)
21751 Newx(ret->recurse_locinput, r->nparens + 1, char *);
21752
21753 if (ret->pprivate)
21754 RXi_SET(ret, CALLREGDUPE_PVT(dstr, param));
21755
21756 if (RX_MATCH_COPIED(dstr))
21757 ret->subbeg = SAVEPVN(ret->subbeg, ret->sublen);
21758 else
21759 ret->subbeg = NULL;
21760#ifdef PERL_ANY_COW
21761 ret->saved_copy = NULL;
21762#endif
21763
21764 /* Whether mother_re be set or no, we need to copy the string. We
21765 cannot refrain from copying it when the storage points directly to
21766 our mother regexp, because that's
21767 1: a buffer in a different thread
21768 2: something we no longer hold a reference on
21769 so we need to copy it locally. */
21770 RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED_const(sstr), SvCUR(sstr)+1);
21771 /* set malloced length to a non-zero value so it will be freed
21772 * (otherwise in combination with SVf_FAKE it looks like an alien
21773 * buffer). It doesn't have to be the actual malloced size, since it
21774 * should never be grown */
21775 SvLEN_set(dstr, SvCUR(sstr)+1);
21776 ret->mother_re = NULL;
21777}
21778#endif /* PERL_IN_XSUB_RE */
21779
21780/*
21781 regdupe_internal()
21782
21783 This is the internal complement to regdupe() which is used to copy
21784 the structure pointed to by the *pprivate pointer in the regexp.
21785 This is the core version of the extension overridable cloning hook.
21786 The regexp structure being duplicated will be copied by perl prior
21787 to this and will be provided as the regexp *r argument, however
21788 with the /old/ structures pprivate pointer value. Thus this routine
21789 may override any copying normally done by perl.
21790
21791 It returns a pointer to the new regexp_internal structure.
21792*/
21793
21794void *
21795Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
21796{
21797 dVAR;
21798 struct regexp *const r = ReANY(rx);
21799 regexp_internal *reti;
21800 int len;
21801 RXi_GET_DECL(r, ri);
21802
21803 PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
21804
21805 len = ProgLen(ri);
21806
21807 Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode),
21808 char, regexp_internal);
21809 Copy(ri->program, reti->program, len+1, regnode);
21810
21811
21812 if (ri->code_blocks) {
21813 int n;
21814 Newx(reti->code_blocks, 1, struct reg_code_blocks);
21815 Newx(reti->code_blocks->cb, ri->code_blocks->count,
21816 struct reg_code_block);
21817 Copy(ri->code_blocks->cb, reti->code_blocks->cb,
21818 ri->code_blocks->count, struct reg_code_block);
21819 for (n = 0; n < ri->code_blocks->count; n++)
21820 reti->code_blocks->cb[n].src_regex = (REGEXP*)
21821 sv_dup_inc((SV*)(ri->code_blocks->cb[n].src_regex), param);
21822 reti->code_blocks->count = ri->code_blocks->count;
21823 reti->code_blocks->refcnt = 1;
21824 }
21825 else
21826 reti->code_blocks = NULL;
21827
21828 reti->regstclass = NULL;
21829
21830 if (ri->data) {
21831 struct reg_data *d;
21832 const int count = ri->data->count;
21833 int i;
21834
21835 Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
21836 char, struct reg_data);
21837 Newx(d->what, count, U8);
21838
21839 d->count = count;
21840 for (i = 0; i < count; i++) {
21841 d->what[i] = ri->data->what[i];
21842 switch (d->what[i]) {
21843 /* see also regcomp.h and regfree_internal() */
21844 case 'a': /* actually an AV, but the dup function is identical.
21845 values seem to be "plain sv's" generally. */
21846 case 'r': /* a compiled regex (but still just another SV) */
21847 case 's': /* an RV (currently only used for an RV to an AV by the ANYOF code)
21848 this use case should go away, the code could have used
21849 'a' instead - see S_set_ANYOF_arg() for array contents. */
21850 case 'S': /* actually an SV, but the dup function is identical. */
21851 case 'u': /* actually an HV, but the dup function is identical.
21852 values are "plain sv's" */
21853 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
21854 break;
21855 case 'f':
21856 /* Synthetic Start Class - "Fake" charclass we generate to optimize
21857 * patterns which could start with several different things. Pre-TRIE
21858 * this was more important than it is now, however this still helps
21859 * in some places, for instance /x?a+/ might produce a SSC equivalent
21860 * to [xa]. This is used by Perl_re_intuit_start() and S_find_byclass()
21861 * in regexec.c
21862 */
21863 /* This is cheating. */
21864 Newx(d->data[i], 1, regnode_ssc);
21865 StructCopy(ri->data->data[i], d->data[i], regnode_ssc);
21866 reti->regstclass = (regnode*)d->data[i];
21867 break;
21868 case 'T':
21869 /* AHO-CORASICK fail table */
21870 /* Trie stclasses are readonly and can thus be shared
21871 * without duplication. We free the stclass in pregfree
21872 * when the corresponding reg_ac_data struct is freed.
21873 */
21874 reti->regstclass= ri->regstclass;
21875 /* FALLTHROUGH */
21876 case 't':
21877 /* TRIE transition table */
21878 OP_REFCNT_LOCK;
21879 ((reg_trie_data*)ri->data->data[i])->refcount++;
21880 OP_REFCNT_UNLOCK;
21881 /* FALLTHROUGH */
21882 case 'l': /* (?{...}) or (??{ ... }) code (cb->block) */
21883 case 'L': /* same when RExC_pm_flags & PMf_HAS_CV and code
21884 is not from another regexp */
21885 d->data[i] = ri->data->data[i];
21886 break;
21887 default:
21888 Perl_croak(aTHX_ "panic: re_dup_guts unknown data code '%c'",
21889 ri->data->what[i]);
21890 }
21891 }
21892
21893 reti->data = d;
21894 }
21895 else
21896 reti->data = NULL;
21897
21898 reti->name_list_idx = ri->name_list_idx;
21899
21900#ifdef RE_TRACK_PATTERN_OFFSETS
21901 if (ri->u.offsets) {
21902 Newx(reti->u.offsets, 2*len+1, U32);
21903 Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
21904 }
21905#else
21906 SetProgLen(reti, len);
21907#endif
21908
21909 return (void*)reti;
21910}
21911
21912#endif /* USE_ITHREADS */
21913
21914#ifndef PERL_IN_XSUB_RE
21915
21916/*
21917 - regnext - dig the "next" pointer out of a node
21918 */
21919regnode *
21920Perl_regnext(pTHX_ regnode *p)
21921{
21922 I32 offset;
21923
21924 if (!p)
21925 return(NULL);
21926
21927 if (OP(p) > REGNODE_MAX) { /* regnode.type is unsigned */
21928 Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
21929 (int)OP(p), (int)REGNODE_MAX);
21930 }
21931
21932 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
21933 if (offset == 0)
21934 return(NULL);
21935
21936 return(p+offset);
21937}
21938
21939#endif
21940
21941STATIC void
21942S_re_croak(pTHX_ bool utf8, const char* pat,...)
21943{
21944 va_list args;
21945 STRLEN len = strlen(pat);
21946 char buf[512];
21947 SV *msv;
21948 const char *message;
21949
21950 PERL_ARGS_ASSERT_RE_CROAK;
21951
21952 if (len > 510)
21953 len = 510;
21954 Copy(pat, buf, len , char);
21955 buf[len] = '\n';
21956 buf[len + 1] = '\0';
21957 va_start(args, pat);
21958 msv = vmess(buf, &args);
21959 va_end(args);
21960 message = SvPV_const(msv, len);
21961 if (len > 512)
21962 len = 512;
21963 Copy(message, buf, len , char);
21964 /* len-1 to avoid \n */
21965 Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(utf8, len-1, buf));
21966}
21967
21968/* XXX Here's a total kludge. But we need to re-enter for swash routines. */
21969
21970#ifndef PERL_IN_XSUB_RE
21971void
21972Perl_save_re_context(pTHX)
21973{
21974 I32 nparens = -1;
21975 I32 i;
21976
21977 /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
21978
21979 if (PL_curpm) {
21980 const REGEXP * const rx = PM_GETRE(PL_curpm);
21981 if (rx)
21982 nparens = RX_NPARENS(rx);
21983 }
21984
21985 /* RT #124109. This is a complete hack; in the SWASHNEW case we know
21986 * that PL_curpm will be null, but that utf8.pm and the modules it
21987 * loads will only use $1..$3.
21988 * The t/porting/re_context.t test file checks this assumption.
21989 */
21990 if (nparens == -1)
21991 nparens = 3;
21992
21993 for (i = 1; i <= nparens; i++) {
21994 char digits[TYPE_CHARS(long)];
21995 const STRLEN len = my_snprintf(digits, sizeof(digits),
21996 "%lu", (long)i);
21997 GV *const *const gvp
21998 = (GV**)hv_fetch(PL_defstash, digits, len, 0);
21999
22000 if (gvp) {
22001 GV * const gv = *gvp;
22002 if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
22003 save_scalar(gv);
22004 }
22005 }
22006}
22007#endif
22008
22009#ifdef DEBUGGING
22010
22011STATIC void
22012S_put_code_point(pTHX_ SV *sv, UV c)
22013{
22014 PERL_ARGS_ASSERT_PUT_CODE_POINT;
22015
22016 if (c > 255) {
22017 Perl_sv_catpvf(aTHX_ sv, "\\x{%04" UVXf "}", c);
22018 }
22019 else if (isPRINT(c)) {
22020 const char string = (char) c;
22021
22022 /* We use {phrase} as metanotation in the class, so also escape literal
22023 * braces */
22024 if (isBACKSLASHED_PUNCT(c) || c == '{' || c == '}')
22025 sv_catpvs(sv, "\\");
22026 sv_catpvn(sv, &string, 1);
22027 }
22028 else if (isMNEMONIC_CNTRL(c)) {
22029 Perl_sv_catpvf(aTHX_ sv, "%s", cntrl_to_mnemonic((U8) c));
22030 }
22031 else {
22032 Perl_sv_catpvf(aTHX_ sv, "\\x%02X", (U8) c);
22033 }
22034}
22035
22036#define MAX_PRINT_A MAX_PRINT_A_FOR_USE_ONLY_BY_REGCOMP_DOT_C
22037
22038STATIC void
22039S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals)
22040{
22041 /* Appends to 'sv' a displayable version of the range of code points from
22042 * 'start' to 'end'. Mnemonics (like '\r') are used for the few controls
22043 * that have them, when they occur at the beginning or end of the range.
22044 * It uses hex to output the remaining code points, unless 'allow_literals'
22045 * is true, in which case the printable ASCII ones are output as-is (though
22046 * some of these will be escaped by put_code_point()).
22047 *
22048 * NOTE: This is designed only for printing ranges of code points that fit
22049 * inside an ANYOF bitmap. Higher code points are simply suppressed
22050 */
22051
22052 const unsigned int min_range_count = 3;
22053
22054 assert(start <= end);
22055
22056 PERL_ARGS_ASSERT_PUT_RANGE;
22057
22058 while (start <= end) {
22059 UV this_end;
22060 const char * format;
22061
22062 if (end - start < min_range_count) {
22063
22064 /* Output chars individually when they occur in short ranges */
22065 for (; start <= end; start++) {
22066 put_code_point(sv, start);
22067 }
22068 break;
22069 }
22070
22071 /* If permitted by the input options, and there is a possibility that
22072 * this range contains a printable literal, look to see if there is
22073 * one. */
22074 if (allow_literals && start <= MAX_PRINT_A) {
22075
22076 /* If the character at the beginning of the range isn't an ASCII
22077 * printable, effectively split the range into two parts:
22078 * 1) the portion before the first such printable,
22079 * 2) the rest
22080 * and output them separately. */
22081 if (! isPRINT_A(start)) {
22082 UV temp_end = start + 1;
22083
22084 /* There is no point looking beyond the final possible
22085 * printable, in MAX_PRINT_A */
22086 UV max = MIN(end, MAX_PRINT_A);
22087
22088 while (temp_end <= max && ! isPRINT_A(temp_end)) {
22089 temp_end++;
22090 }
22091
22092 /* Here, temp_end points to one beyond the first printable if
22093 * found, or to one beyond 'max' if not. If none found, make
22094 * sure that we use the entire range */
22095 if (temp_end > MAX_PRINT_A) {
22096 temp_end = end + 1;
22097 }
22098
22099 /* Output the first part of the split range: the part that
22100 * doesn't have printables, with the parameter set to not look
22101 * for literals (otherwise we would infinitely recurse) */
22102 put_range(sv, start, temp_end - 1, FALSE);
22103
22104 /* The 2nd part of the range (if any) starts here. */
22105 start = temp_end;
22106
22107 /* We do a continue, instead of dropping down, because even if
22108 * the 2nd part is non-empty, it could be so short that we want
22109 * to output it as individual characters, as tested for at the
22110 * top of this loop. */
22111 continue;
22112 }
22113
22114 /* Here, 'start' is a printable ASCII. If it is an alphanumeric,
22115 * output a sub-range of just the digits or letters, then process
22116 * the remaining portion as usual. */
22117 if (isALPHANUMERIC_A(start)) {
22118 UV mask = (isDIGIT_A(start))
22119 ? _CC_DIGIT
22120 : isUPPER_A(start)
22121 ? _CC_UPPER
22122 : _CC_LOWER;
22123 UV temp_end = start + 1;
22124
22125 /* Find the end of the sub-range that includes just the
22126 * characters in the same class as the first character in it */
22127 while (temp_end <= end && _generic_isCC_A(temp_end, mask)) {
22128 temp_end++;
22129 }
22130 temp_end--;
22131
22132 /* For short ranges, don't duplicate the code above to output
22133 * them; just call recursively */
22134 if (temp_end - start < min_range_count) {
22135 put_range(sv, start, temp_end, FALSE);
22136 }
22137 else { /* Output as a range */
22138 put_code_point(sv, start);
22139 sv_catpvs(sv, "-");
22140 put_code_point(sv, temp_end);
22141 }
22142 start = temp_end + 1;
22143 continue;
22144 }
22145
22146 /* We output any other printables as individual characters */
22147 if (isPUNCT_A(start) || isSPACE_A(start)) {
22148 while (start <= end && (isPUNCT_A(start)
22149 || isSPACE_A(start)))
22150 {
22151 put_code_point(sv, start);
22152 start++;
22153 }
22154 continue;
22155 }
22156 } /* End of looking for literals */
22157
22158 /* Here is not to output as a literal. Some control characters have
22159 * mnemonic names. Split off any of those at the beginning and end of
22160 * the range to print mnemonically. It isn't possible for many of
22161 * these to be in a row, so this won't overwhelm with output */
22162 if ( start <= end
22163 && (isMNEMONIC_CNTRL(start) || isMNEMONIC_CNTRL(end)))
22164 {
22165 while (isMNEMONIC_CNTRL(start) && start <= end) {
22166 put_code_point(sv, start);
22167 start++;
22168 }
22169
22170 /* If this didn't take care of the whole range ... */
22171 if (start <= end) {
22172
22173 /* Look backwards from the end to find the final non-mnemonic
22174 * */
22175 UV temp_end = end;
22176 while (isMNEMONIC_CNTRL(temp_end)) {
22177 temp_end--;
22178 }
22179
22180 /* And separately output the interior range that doesn't start
22181 * or end with mnemonics */
22182 put_range(sv, start, temp_end, FALSE);
22183
22184 /* Then output the mnemonic trailing controls */
22185 start = temp_end + 1;
22186 while (start <= end) {
22187 put_code_point(sv, start);
22188 start++;
22189 }
22190 break;
22191 }
22192 }
22193
22194 /* As a final resort, output the range or subrange as hex. */
22195
22196 if (start >= NUM_ANYOF_CODE_POINTS) {
22197 this_end = end;
22198 }
22199 else { /* Have to split range at the bitmap boundary */
22200 this_end = (end < NUM_ANYOF_CODE_POINTS)
22201 ? end
22202 : NUM_ANYOF_CODE_POINTS - 1;
22203 }
22204#if NUM_ANYOF_CODE_POINTS > 256
22205 format = (this_end < 256)
22206 ? "\\x%02" UVXf "-\\x%02" UVXf
22207 : "\\x{%04" UVXf "}-\\x{%04" UVXf "}";
22208#else
22209 format = "\\x%02" UVXf "-\\x%02" UVXf;
22210#endif
22211 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
22212 Perl_sv_catpvf(aTHX_ sv, format, start, this_end);
22213 GCC_DIAG_RESTORE_STMT;
22214 break;
22215 }
22216}
22217
22218STATIC void
22219S_put_charclass_bitmap_innards_invlist(pTHX_ SV *sv, SV* invlist)
22220{
22221 /* Concatenate onto the PV in 'sv' a displayable form of the inversion list
22222 * 'invlist' */
22223
22224 UV start, end;
22225 bool allow_literals = TRUE;
22226
22227 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_INVLIST;
22228
22229 /* Generally, it is more readable if printable characters are output as
22230 * literals, but if a range (nearly) spans all of them, it's best to output
22231 * it as a single range. This code will use a single range if all but 2
22232 * ASCII printables are in it */
22233 invlist_iterinit(invlist);
22234 while (invlist_iternext(invlist, &start, &end)) {
22235
22236 /* If the range starts beyond the final printable, it doesn't have any
22237 * in it */
22238 if (start > MAX_PRINT_A) {
22239 break;
22240 }
22241
22242 /* In both ASCII and EBCDIC, a SPACE is the lowest printable. To span
22243 * all but two, the range must start and end no later than 2 from
22244 * either end */
22245 if (start < ' ' + 2 && end > MAX_PRINT_A - 2) {
22246 if (end > MAX_PRINT_A) {
22247 end = MAX_PRINT_A;
22248 }
22249 if (start < ' ') {
22250 start = ' ';
22251 }
22252 if (end - start >= MAX_PRINT_A - ' ' - 2) {
22253 allow_literals = FALSE;
22254 }
22255 break;
22256 }
22257 }
22258 invlist_iterfinish(invlist);
22259
22260 /* Here we have figured things out. Output each range */
22261 invlist_iterinit(invlist);
22262 while (invlist_iternext(invlist, &start, &end)) {
22263 if (start >= NUM_ANYOF_CODE_POINTS) {
22264 break;
22265 }
22266 put_range(sv, start, end, allow_literals);
22267 }
22268 invlist_iterfinish(invlist);
22269
22270 return;
22271}
22272
22273STATIC SV*
22274S_put_charclass_bitmap_innards_common(pTHX_
22275 SV* invlist, /* The bitmap */
22276 SV* posixes, /* Under /l, things like [:word:], \S */
22277 SV* only_utf8, /* Under /d, matches iff the target is UTF-8 */
22278 SV* not_utf8, /* /d, matches iff the target isn't UTF-8 */
22279 SV* only_utf8_locale, /* Under /l, matches if the locale is UTF-8 */
22280 const bool invert /* Is the result to be inverted? */
22281)
22282{
22283 /* Create and return an SV containing a displayable version of the bitmap
22284 * and associated information determined by the input parameters. If the
22285 * output would have been only the inversion indicator '^', NULL is instead
22286 * returned. */
22287
22288 dVAR;
22289 SV * output;
22290
22291 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_COMMON;
22292
22293 if (invert) {
22294 output = newSVpvs("^");
22295 }
22296 else {
22297 output = newSVpvs("");
22298 }
22299
22300 /* First, the code points in the bitmap that are unconditionally there */
22301 put_charclass_bitmap_innards_invlist(output, invlist);
22302
22303 /* Traditionally, these have been placed after the main code points */
22304 if (posixes) {
22305 sv_catsv(output, posixes);
22306 }
22307
22308 if (only_utf8 && _invlist_len(only_utf8)) {
22309 Perl_sv_catpvf(aTHX_ output, "%s{utf8}%s", PL_colors[1], PL_colors[0]);
22310 put_charclass_bitmap_innards_invlist(output, only_utf8);
22311 }
22312
22313 if (not_utf8 && _invlist_len(not_utf8)) {
22314 Perl_sv_catpvf(aTHX_ output, "%s{not utf8}%s", PL_colors[1], PL_colors[0]);
22315 put_charclass_bitmap_innards_invlist(output, not_utf8);
22316 }
22317
22318 if (only_utf8_locale && _invlist_len(only_utf8_locale)) {
22319 Perl_sv_catpvf(aTHX_ output, "%s{utf8 locale}%s", PL_colors[1], PL_colors[0]);
22320 put_charclass_bitmap_innards_invlist(output, only_utf8_locale);
22321
22322 /* This is the only list in this routine that can legally contain code
22323 * points outside the bitmap range. The call just above to
22324 * 'put_charclass_bitmap_innards_invlist' will simply suppress them, so
22325 * output them here. There's about a half-dozen possible, and none in
22326 * contiguous ranges longer than 2 */
22327 if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
22328 UV start, end;
22329 SV* above_bitmap = NULL;
22330
22331 _invlist_subtract(only_utf8_locale, PL_InBitmap, &above_bitmap);
22332
22333 invlist_iterinit(above_bitmap);
22334 while (invlist_iternext(above_bitmap, &start, &end)) {
22335 UV i;
22336
22337 for (i = start; i <= end; i++) {
22338 put_code_point(output, i);
22339 }
22340 }
22341 invlist_iterfinish(above_bitmap);
22342 SvREFCNT_dec_NN(above_bitmap);
22343 }
22344 }
22345
22346 if (invert && SvCUR(output) == 1) {
22347 return NULL;
22348 }
22349
22350 return output;
22351}
22352
22353STATIC bool
22354S_put_charclass_bitmap_innards(pTHX_ SV *sv,
22355 char *bitmap,
22356 SV *nonbitmap_invlist,
22357 SV *only_utf8_locale_invlist,
22358 const regnode * const node,
22359 const U8 flags,
22360 const bool force_as_is_display)
22361{
22362 /* Appends to 'sv' a displayable version of the innards of the bracketed
22363 * character class defined by the other arguments:
22364 * 'bitmap' points to the bitmap, or NULL if to ignore that.
22365 * 'nonbitmap_invlist' is an inversion list of the code points that are in
22366 * the bitmap range, but for some reason aren't in the bitmap; NULL if
22367 * none. The reasons for this could be that they require some
22368 * condition such as the target string being or not being in UTF-8
22369 * (under /d), or because they came from a user-defined property that
22370 * was not resolved at the time of the regex compilation (under /u)
22371 * 'only_utf8_locale_invlist' is an inversion list of the code points that
22372 * are valid only if the runtime locale is a UTF-8 one; NULL if none
22373 * 'node' is the regex pattern ANYOF node. It is needed only when the
22374 * above two parameters are not null, and is passed so that this
22375 * routine can tease apart the various reasons for them.
22376 * 'flags' is the flags field of 'node'
22377 * 'force_as_is_display' is TRUE if this routine should definitely NOT try
22378 * to invert things to see if that leads to a cleaner display. If
22379 * FALSE, this routine is free to use its judgment about doing this.
22380 *
22381 * It returns TRUE if there was actually something output. (It may be that
22382 * the bitmap, etc is empty.)
22383 *
22384 * When called for outputting the bitmap of a non-ANYOF node, just pass the
22385 * bitmap, with the succeeding parameters set to NULL, and the final one to
22386 * FALSE.
22387 */
22388
22389 /* In general, it tries to display the 'cleanest' representation of the
22390 * innards, choosing whether to display them inverted or not, regardless of
22391 * whether the class itself is to be inverted. However, there are some
22392 * cases where it can't try inverting, as what actually matches isn't known
22393 * until runtime, and hence the inversion isn't either. */
22394
22395 dVAR;
22396 bool inverting_allowed = ! force_as_is_display;
22397
22398 int i;
22399 STRLEN orig_sv_cur = SvCUR(sv);
22400
22401 SV* invlist; /* Inversion list we accumulate of code points that
22402 are unconditionally matched */
22403 SV* only_utf8 = NULL; /* Under /d, list of matches iff the target is
22404 UTF-8 */
22405 SV* not_utf8 = NULL; /* /d, list of matches iff the target isn't UTF-8
22406 */
22407 SV* posixes = NULL; /* Under /l, string of things like [:word:], \D */
22408 SV* only_utf8_locale = NULL; /* Under /l, list of matches if the locale
22409 is UTF-8 */
22410
22411 SV* as_is_display; /* The output string when we take the inputs
22412 literally */
22413 SV* inverted_display; /* The output string when we invert the inputs */
22414
22415 bool invert = cBOOL(flags & ANYOF_INVERT); /* Is the input to be inverted
22416 to match? */
22417 /* We are biased in favor of displaying things without them being inverted,
22418 * as that is generally easier to understand */
22419 const int bias = 5;
22420
22421 PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS;
22422
22423 /* Start off with whatever code points are passed in. (We clone, so we
22424 * don't change the caller's list) */
22425 if (nonbitmap_invlist) {
22426 assert(invlist_highest(nonbitmap_invlist) < NUM_ANYOF_CODE_POINTS);
22427 invlist = invlist_clone(nonbitmap_invlist, NULL);
22428 }
22429 else { /* Worst case size is every other code point is matched */
22430 invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2);
22431 }
22432
22433 if (flags) {
22434 if (OP(node) == ANYOFD) {
22435
22436 /* This flag indicates that the code points below 0x100 in the
22437 * nonbitmap list are precisely the ones that match only when the
22438 * target is UTF-8 (they should all be non-ASCII). */
22439 if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
22440 {
22441 _invlist_intersection(invlist, PL_UpperLatin1, &only_utf8);
22442 _invlist_subtract(invlist, only_utf8, &invlist);
22443 }
22444
22445 /* And this flag for matching all non-ASCII 0xFF and below */
22446 if (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
22447 {
22448 not_utf8 = invlist_clone(PL_UpperLatin1, NULL);
22449 }
22450 }
22451 else if (OP(node) == ANYOFL || OP(node) == ANYOFPOSIXL) {
22452
22453 /* If either of these flags are set, what matches isn't
22454 * determinable except during execution, so don't know enough here
22455 * to invert */
22456 if (flags & (ANYOFL_FOLD|ANYOF_MATCHES_POSIXL)) {
22457 inverting_allowed = FALSE;
22458 }
22459
22460 /* What the posix classes match also varies at runtime, so these
22461 * will be output symbolically. */
22462 if (ANYOF_POSIXL_TEST_ANY_SET(node)) {
22463 int i;
22464
22465 posixes = newSVpvs("");
22466 for (i = 0; i < ANYOF_POSIXL_MAX; i++) {
22467 if (ANYOF_POSIXL_TEST(node, i)) {
22468 sv_catpv(posixes, anyofs[i]);
22469 }
22470 }
22471 }
22472 }
22473 }
22474
22475 /* Accumulate the bit map into the unconditional match list */
22476 if (bitmap) {
22477 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
22478 if (BITMAP_TEST(bitmap, i)) {
22479 int start = i++;
22480 for (;
22481 i < NUM_ANYOF_CODE_POINTS && BITMAP_TEST(bitmap, i);
22482 i++)
22483 { /* empty */ }
22484 invlist = _add_range_to_invlist(invlist, start, i-1);
22485 }
22486 }
22487 }
22488
22489 /* Make sure that the conditional match lists don't have anything in them
22490 * that match unconditionally; otherwise the output is quite confusing.
22491 * This could happen if the code that populates these misses some
22492 * duplication. */
22493 if (only_utf8) {
22494 _invlist_subtract(only_utf8, invlist, &only_utf8);
22495 }
22496 if (not_utf8) {
22497 _invlist_subtract(not_utf8, invlist, &not_utf8);
22498 }
22499
22500 if (only_utf8_locale_invlist) {
22501
22502 /* Since this list is passed in, we have to make a copy before
22503 * modifying it */
22504 only_utf8_locale = invlist_clone(only_utf8_locale_invlist, NULL);
22505
22506 _invlist_subtract(only_utf8_locale, invlist, &only_utf8_locale);
22507
22508 /* And, it can get really weird for us to try outputting an inverted
22509 * form of this list when it has things above the bitmap, so don't even
22510 * try */
22511 if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
22512 inverting_allowed = FALSE;
22513 }
22514 }
22515
22516 /* Calculate what the output would be if we take the input as-is */
22517 as_is_display = put_charclass_bitmap_innards_common(invlist,
22518 posixes,
22519 only_utf8,
22520 not_utf8,
22521 only_utf8_locale,
22522 invert);
22523
22524 /* If have to take the output as-is, just do that */
22525 if (! inverting_allowed) {
22526 if (as_is_display) {
22527 sv_catsv(sv, as_is_display);
22528 SvREFCNT_dec_NN(as_is_display);
22529 }
22530 }
22531 else { /* But otherwise, create the output again on the inverted input, and
22532 use whichever version is shorter */
22533
22534 int inverted_bias, as_is_bias;
22535
22536 /* We will apply our bias to whichever of the the results doesn't have
22537 * the '^' */
22538 if (invert) {
22539 invert = FALSE;
22540 as_is_bias = bias;
22541 inverted_bias = 0;
22542 }
22543 else {
22544 invert = TRUE;
22545 as_is_bias = 0;
22546 inverted_bias = bias;
22547 }
22548
22549 /* Now invert each of the lists that contribute to the output,
22550 * excluding from the result things outside the possible range */
22551
22552 /* For the unconditional inversion list, we have to add in all the
22553 * conditional code points, so that when inverted, they will be gone
22554 * from it */
22555 _invlist_union(only_utf8, invlist, &invlist);
22556 _invlist_union(not_utf8, invlist, &invlist);
22557 _invlist_union(only_utf8_locale, invlist, &invlist);
22558 _invlist_invert(invlist);
22559 _invlist_intersection(invlist, PL_InBitmap, &invlist);
22560
22561 if (only_utf8) {
22562 _invlist_invert(only_utf8);
22563 _invlist_intersection(only_utf8, PL_UpperLatin1, &only_utf8);
22564 }
22565 else if (not_utf8) {
22566
22567 /* If a code point matches iff the target string is not in UTF-8,
22568 * then complementing the result has it not match iff not in UTF-8,
22569 * which is the same thing as matching iff it is UTF-8. */
22570 only_utf8 = not_utf8;
22571 not_utf8 = NULL;
22572 }
22573
22574 if (only_utf8_locale) {
22575 _invlist_invert(only_utf8_locale);
22576 _invlist_intersection(only_utf8_locale,
22577 PL_InBitmap,
22578 &only_utf8_locale);
22579 }
22580
22581 inverted_display = put_charclass_bitmap_innards_common(
22582 invlist,
22583 posixes,
22584 only_utf8,
22585 not_utf8,
22586 only_utf8_locale, invert);
22587
22588 /* Use the shortest representation, taking into account our bias
22589 * against showing it inverted */
22590 if ( inverted_display
22591 && ( ! as_is_display
22592 || ( SvCUR(inverted_display) + inverted_bias
22593 < SvCUR(as_is_display) + as_is_bias)))
22594 {
22595 sv_catsv(sv, inverted_display);
22596 }
22597 else if (as_is_display) {
22598 sv_catsv(sv, as_is_display);
22599 }
22600
22601 SvREFCNT_dec(as_is_display);
22602 SvREFCNT_dec(inverted_display);
22603 }
22604
22605 SvREFCNT_dec_NN(invlist);
22606 SvREFCNT_dec(only_utf8);
22607 SvREFCNT_dec(not_utf8);
22608 SvREFCNT_dec(posixes);
22609 SvREFCNT_dec(only_utf8_locale);
22610
22611 return SvCUR(sv) > orig_sv_cur;
22612}
22613
22614#define CLEAR_OPTSTART \
22615 if (optstart) STMT_START { \
22616 DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ \
22617 " (%" IVdf " nodes)\n", (IV)(node - optstart))); \
22618 optstart=NULL; \
22619 } STMT_END
22620
22621#define DUMPUNTIL(b,e) \
22622 CLEAR_OPTSTART; \
22623 node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
22624
22625STATIC const regnode *
22626S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
22627 const regnode *last, const regnode *plast,
22628 SV* sv, I32 indent, U32 depth)
22629{
22630 U8 op = PSEUDO; /* Arbitrary non-END op. */
22631 const regnode *next;
22632 const regnode *optstart= NULL;
22633
22634 RXi_GET_DECL(r, ri);
22635 GET_RE_DEBUG_FLAGS_DECL;
22636
22637 PERL_ARGS_ASSERT_DUMPUNTIL;
22638
22639#ifdef DEBUG_DUMPUNTIL
22640 Perl_re_printf( aTHX_ "--- %d : %d - %d - %d\n", indent, node-start,
22641 last ? last-start : 0, plast ? plast-start : 0);
22642#endif
22643
22644 if (plast && plast < last)
22645 last= plast;
22646
22647 while (PL_regkind[op] != END && (!last || node < last)) {
22648 assert(node);
22649 /* While that wasn't END last time... */
22650 NODE_ALIGN(node);
22651 op = OP(node);
22652 if (op == CLOSE || op == SRCLOSE || op == WHILEM)
22653 indent--;
22654 next = regnext((regnode *)node);
22655
22656 /* Where, what. */
22657 if (OP(node) == OPTIMIZED) {
22658 if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
22659 optstart = node;
22660 else
22661 goto after_print;
22662 } else
22663 CLEAR_OPTSTART;
22664
22665 regprop(r, sv, node, NULL, NULL);
22666 Perl_re_printf( aTHX_ "%4" IVdf ":%*s%s", (IV)(node - start),
22667 (int)(2*indent + 1), "", SvPVX_const(sv));
22668
22669 if (OP(node) != OPTIMIZED) {
22670 if (next == NULL) /* Next ptr. */
22671 Perl_re_printf( aTHX_ " (0)");
22672 else if (PL_regkind[(U8)op] == BRANCH
22673 && PL_regkind[OP(next)] != BRANCH )
22674 Perl_re_printf( aTHX_ " (FAIL)");
22675 else
22676 Perl_re_printf( aTHX_ " (%" IVdf ")", (IV)(next - start));
22677 Perl_re_printf( aTHX_ "\n");
22678 }
22679
22680 after_print:
22681 if (PL_regkind[(U8)op] == BRANCHJ) {
22682 assert(next);
22683 {
22684 const regnode *nnode = (OP(next) == LONGJMP
22685 ? regnext((regnode *)next)
22686 : next);
22687 if (last && nnode > last)
22688 nnode = last;
22689 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
22690 }
22691 }
22692 else if (PL_regkind[(U8)op] == BRANCH) {
22693 assert(next);
22694 DUMPUNTIL(NEXTOPER(node), next);
22695 }
22696 else if ( PL_regkind[(U8)op] == TRIE ) {
22697 const regnode *this_trie = node;
22698 const char op = OP(node);
22699 const U32 n = ARG(node);
22700 const reg_ac_data * const ac = op>=AHOCORASICK ?
22701 (reg_ac_data *)ri->data->data[n] :
22702 NULL;
22703 const reg_trie_data * const trie =
22704 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
22705#ifdef DEBUGGING
22706 AV *const trie_words
22707 = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
22708#endif
22709 const regnode *nextbranch= NULL;
22710 I32 word_idx;
22711 SvPVCLEAR(sv);
22712 for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
22713 SV ** const elem_ptr = av_fetch(trie_words, word_idx, 0);
22714
22715 Perl_re_indentf( aTHX_ "%s ",
22716 indent+3,
22717 elem_ptr
22718 ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr),
22719 SvCUR(*elem_ptr), PL_dump_re_max_len,
22720 PL_colors[0], PL_colors[1],
22721 (SvUTF8(*elem_ptr)
22722 ? PERL_PV_ESCAPE_UNI
22723 : 0)
22724 | PERL_PV_PRETTY_ELLIPSES
22725 | PERL_PV_PRETTY_LTGT
22726 )
22727 : "???"
22728 );
22729 if (trie->jump) {
22730 U16 dist= trie->jump[word_idx+1];
22731 Perl_re_printf( aTHX_ "(%" UVuf ")\n",
22732 (UV)((dist ? this_trie + dist : next) - start));
22733 if (dist) {
22734 if (!nextbranch)
22735 nextbranch= this_trie + trie->jump[0];
22736 DUMPUNTIL(this_trie + dist, nextbranch);
22737 }
22738 if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
22739 nextbranch= regnext((regnode *)nextbranch);
22740 } else {
22741 Perl_re_printf( aTHX_ "\n");
22742 }
22743 }
22744 if (last && next > last)
22745 node= last;
22746 else
22747 node= next;
22748 }
22749 else if ( op == CURLY ) { /* "next" might be very big: optimizer */
22750 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
22751 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
22752 }
22753 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
22754 assert(next);
22755 DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
22756 }
22757 else if ( op == PLUS || op == STAR) {
22758 DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
22759 }
22760 else if (PL_regkind[(U8)op] == EXACT || op == ANYOFHs) {
22761 /* Literal string, where present. */
22762 node += NODE_SZ_STR(node) - 1;
22763 node = NEXTOPER(node);
22764 }
22765 else {
22766 node = NEXTOPER(node);
22767 node += regarglen[(U8)op];
22768 }
22769 if (op == CURLYX || op == OPEN || op == SROPEN)
22770 indent++;
22771 }
22772 CLEAR_OPTSTART;
22773#ifdef DEBUG_DUMPUNTIL
22774 Perl_re_printf( aTHX_ "--- %d\n", (int)indent);
22775#endif
22776 return node;
22777}
22778
22779#endif /* DEBUGGING */
22780
22781#ifndef PERL_IN_XSUB_RE
22782
22783# include "uni_keywords.h"
22784
22785void
22786Perl_init_uniprops(pTHX)
22787{
22788 dVAR;
22789
22790# ifdef DEBUGGING
22791 char * dump_len_string;
22792
22793 dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN");
22794 if ( ! dump_len_string
22795 || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL))
22796 {
22797 PL_dump_re_max_len = 60; /* A reasonable default */
22798 }
22799# endif
22800
22801 PL_user_def_props = newHV();
22802
22803# ifdef USE_ITHREADS
22804
22805 HvSHAREKEYS_off(PL_user_def_props);
22806 PL_user_def_props_aTHX = aTHX;
22807
22808# endif
22809
22810 /* Set up the inversion list interpreter-level variables */
22811
22812 PL_XPosix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
22813 PL_XPosix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALNUM]);
22814 PL_XPosix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALPHA]);
22815 PL_XPosix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXBLANK]);
22816 PL_XPosix_ptrs[_CC_CASED] = _new_invlist_C_array(uni_prop_ptrs[UNI_CASED]);
22817 PL_XPosix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXCNTRL]);
22818 PL_XPosix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXDIGIT]);
22819 PL_XPosix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXGRAPH]);
22820 PL_XPosix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXLOWER]);
22821 PL_XPosix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPRINT]);
22822 PL_XPosix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPUNCT]);
22823 PL_XPosix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXSPACE]);
22824 PL_XPosix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXUPPER]);
22825 PL_XPosix_ptrs[_CC_VERTSPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_VERTSPACE]);
22826 PL_XPosix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXWORD]);
22827 PL_XPosix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXXDIGIT]);
22828
22829 PL_Posix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
22830 PL_Posix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALNUM]);
22831 PL_Posix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALPHA]);
22832 PL_Posix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXBLANK]);
22833 PL_Posix_ptrs[_CC_CASED] = PL_Posix_ptrs[_CC_ALPHA];
22834 PL_Posix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXCNTRL]);
22835 PL_Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXDIGIT]);
22836 PL_Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXGRAPH]);
22837 PL_Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXLOWER]);
22838 PL_Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPRINT]);
22839 PL_Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPUNCT]);
22840 PL_Posix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXSPACE]);
22841 PL_Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXUPPER]);
22842 PL_Posix_ptrs[_CC_VERTSPACE] = NULL;
22843 PL_Posix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXWORD]);
22844 PL_Posix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXXDIGIT]);
22845
22846 PL_GCB_invlist = _new_invlist_C_array(_Perl_GCB_invlist);
22847 PL_SB_invlist = _new_invlist_C_array(_Perl_SB_invlist);
22848 PL_WB_invlist = _new_invlist_C_array(_Perl_WB_invlist);
22849 PL_LB_invlist = _new_invlist_C_array(_Perl_LB_invlist);
22850 PL_SCX_invlist = _new_invlist_C_array(_Perl_SCX_invlist);
22851
22852 PL_InBitmap = _new_invlist_C_array(InBitmap_invlist);
22853 PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
22854 PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
22855 PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist);
22856
22857 PL_Assigned_invlist = _new_invlist_C_array(uni_prop_ptrs[UNI_ASSIGNED]);
22858
22859 PL_utf8_perl_idstart = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDSTART]);
22860 PL_utf8_perl_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDCONT]);
22861
22862 PL_utf8_charname_begin = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_BEGIN]);
22863 PL_utf8_charname_continue = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_CONTINUE]);
22864
22865 PL_in_some_fold = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_ANY_FOLDS]);
22866 PL_HasMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
22867 UNI__PERL_FOLDS_TO_MULTI_CHAR]);
22868 PL_InMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
22869 UNI__PERL_IS_IN_MULTI_CHAR_FOLD]);
22870 PL_utf8_toupper = _new_invlist_C_array(Uppercase_Mapping_invlist);
22871 PL_utf8_tolower = _new_invlist_C_array(Lowercase_Mapping_invlist);
22872 PL_utf8_totitle = _new_invlist_C_array(Titlecase_Mapping_invlist);
22873 PL_utf8_tofold = _new_invlist_C_array(Case_Folding_invlist);
22874 PL_utf8_tosimplefold = _new_invlist_C_array(Simple_Case_Folding_invlist);
22875 PL_utf8_foldclosures = _new_invlist_C_array(_Perl_IVCF_invlist);
22876 PL_utf8_mark = _new_invlist_C_array(uni_prop_ptrs[UNI_M]);
22877 PL_CCC_non0_non230 = _new_invlist_C_array(_Perl_CCC_non0_non230_invlist);
22878 PL_Private_Use = _new_invlist_C_array(uni_prop_ptrs[UNI_CO]);
22879
22880# ifdef UNI_XIDC
22881 /* The below are used only by deprecated functions. They could be removed */
22882 PL_utf8_xidcont = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDC]);
22883 PL_utf8_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI_IDC]);
22884 PL_utf8_xidstart = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDS]);
22885# endif
22886}
22887
22888# if 0
22889
22890This code was mainly added for backcompat to give a warning for non-portable
22891code points in user-defined properties. But experiments showed that the
22892warning in earlier perls were only omitted on overflow, which should be an
22893error, so there really isnt a backcompat issue, and actually adding the
22894warning when none was present before might cause breakage, for little gain. So
22895khw left this code in, but not enabled. Tests were never added.
22896
22897embed.fnc entry:
22898Ei |const char *|get_extended_utf8_msg|const UV cp
22899
22900PERL_STATIC_INLINE const char *
22901S_get_extended_utf8_msg(pTHX_ const UV cp)
22902{
22903 U8 dummy[UTF8_MAXBYTES + 1];
22904 HV *msgs;
22905 SV **msg;
22906
22907 uvchr_to_utf8_flags_msgs(dummy, cp, UNICODE_WARN_PERL_EXTENDED,
22908 &msgs);
22909
22910 msg = hv_fetchs(msgs, "text", 0);
22911 assert(msg);
22912
22913 (void) sv_2mortal((SV *) msgs);
22914
22915 return SvPVX(*msg);
22916}
22917
22918# endif
22919
22920STATIC REGEXP *
22921S_compile_wildcard(pTHX_ const char * name, const STRLEN len,
22922 const bool ignore_case)
22923{
22924 U32 flags = PMf_MULTILINE|PMf_WILDCARD;
22925 REGEXP * subpattern_re;
22926
22927 PERL_ARGS_ASSERT_COMPILE_WILDCARD;
22928
22929 if (ignore_case) {
22930 flags |= PMf_FOLD;
22931 }
22932 set_regex_charset(&flags, REGEX_ASCII_MORE_RESTRICTED_CHARSET);
22933
22934 subpattern_re = re_op_compile_wrapper(sv_2mortal(newSVpvn(name, len)),
22935 /* Like in op.c, we copy the compile
22936 * time pm flags to the rx ones */
22937 (flags & RXf_PMf_COMPILETIME), flags);
22938
22939 assert(subpattern_re); /* Should have died if didn't compile successfully */
22940 return subpattern_re;
22941}
22942
22943STATIC I32
22944S_execute_wildcard(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
22945 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
22946{
22947 I32 result;
22948
22949 PERL_ARGS_ASSERT_EXECUTE_WILDCARD;
22950
22951 result = pregexec(prog, stringarg, strend, strbeg, minend, screamer, nosave);
22952
22953 return result;
22954}
22955
22956SV *
22957Perl_handle_user_defined_property(pTHX_
22958
22959 /* Parses the contents of a user-defined property definition; returning the
22960 * expanded definition if possible. If so, the return is an inversion
22961 * list.
22962 *
22963 * If there are subroutines that are part of the expansion and which aren't
22964 * known at the time of the call to this function, this returns what
22965 * parse_uniprop_string() returned for the first one encountered.
22966 *
22967 * If an error was found, NULL is returned, and 'msg' gets a suitable
22968 * message appended to it. (Appending allows the back trace of how we got
22969 * to the faulty definition to be displayed through nested calls of
22970 * user-defined subs.)
22971 *
22972 * The caller IS responsible for freeing any returned SV.
22973 *
22974 * The syntax of the contents is pretty much described in perlunicode.pod,
22975 * but we also allow comments on each line */
22976
22977 const char * name, /* Name of property */
22978 const STRLEN name_len, /* The name's length in bytes */
22979 const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */
22980 const bool to_fold, /* ? Is this under /i */
22981 const bool runtime, /* ? Are we in compile- or run-time */
22982 const bool deferrable, /* Is it ok for this property's full definition
22983 to be deferred until later? */
22984 SV* contents, /* The property's definition */
22985 bool *user_defined_ptr, /* This will be set TRUE as we wouldn't be
22986 getting called unless this is thought to be
22987 a user-defined property */
22988 SV * msg, /* Any error or warning msg(s) are appended to
22989 this */
22990 const STRLEN level) /* Recursion level of this call */
22991{
22992 STRLEN len;
22993 const char * string = SvPV_const(contents, len);
22994 const char * const e = string + len;
22995 const bool is_contents_utf8 = cBOOL(SvUTF8(contents));
22996 const STRLEN msgs_length_on_entry = SvCUR(msg);
22997
22998 const char * s0 = string; /* Points to first byte in the current line
22999 being parsed in 'string' */
23000 const char overflow_msg[] = "Code point too large in \"";
23001 SV* running_definition = NULL;
23002
23003 PERL_ARGS_ASSERT_HANDLE_USER_DEFINED_PROPERTY;
23004
23005 *user_defined_ptr = TRUE;
23006
23007 /* Look at each line */
23008 while (s0 < e) {
23009 const char * s; /* Current byte */
23010 char op = '+'; /* Default operation is 'union' */
23011 IV min = 0; /* range begin code point */
23012 IV max = -1; /* and range end */
23013 SV* this_definition;
23014
23015 /* Skip comment lines */
23016 if (*s0 == '#') {
23017 s0 = strchr(s0, '\n');
23018 if (s0 == NULL) {
23019 break;
23020 }
23021 s0++;
23022 continue;
23023 }
23024
23025 /* For backcompat, allow an empty first line */
23026 if (*s0 == '\n') {
23027 s0++;
23028 continue;
23029 }
23030
23031 /* First character in the line may optionally be the operation */
23032 if ( *s0 == '+'
23033 || *s0 == '!'
23034 || *s0 == '-'
23035 || *s0 == '&')
23036 {
23037 op = *s0++;
23038 }
23039
23040 /* If the line is one or two hex digits separated by blank space, its
23041 * a range; otherwise it is either another user-defined property or an
23042 * error */
23043
23044 s = s0;
23045
23046 if (! isXDIGIT(*s)) {
23047 goto check_if_property;
23048 }
23049
23050 do { /* Each new hex digit will add 4 bits. */
23051 if (min > ( (IV) MAX_LEGAL_CP >> 4)) {
23052 s = strchr(s, '\n');
23053 if (s == NULL) {
23054 s = e;
23055 }
23056 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23057 sv_catpv(msg, overflow_msg);
23058 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23059 UTF8fARG(is_contents_utf8, s - s0, s0));
23060 sv_catpvs(msg, "\"");
23061 goto return_failure;
23062 }
23063
23064 /* Accumulate this digit into the value */
23065 min = (min << 4) + READ_XDIGIT(s);
23066 } while (isXDIGIT(*s));
23067
23068 while (isBLANK(*s)) { s++; }
23069
23070 /* We allow comments at the end of the line */
23071 if (*s == '#') {
23072 s = strchr(s, '\n');
23073 if (s == NULL) {
23074 s = e;
23075 }
23076 s++;
23077 }
23078 else if (s < e && *s != '\n') {
23079 if (! isXDIGIT(*s)) {
23080 goto check_if_property;
23081 }
23082
23083 /* Look for the high point of the range */
23084 max = 0;
23085 do {
23086 if (max > ( (IV) MAX_LEGAL_CP >> 4)) {
23087 s = strchr(s, '\n');
23088 if (s == NULL) {
23089 s = e;
23090 }
23091 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23092 sv_catpv(msg, overflow_msg);
23093 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23094 UTF8fARG(is_contents_utf8, s - s0, s0));
23095 sv_catpvs(msg, "\"");
23096 goto return_failure;
23097 }
23098
23099 max = (max << 4) + READ_XDIGIT(s);
23100 } while (isXDIGIT(*s));
23101
23102 while (isBLANK(*s)) { s++; }
23103
23104 if (*s == '#') {
23105 s = strchr(s, '\n');
23106 if (s == NULL) {
23107 s = e;
23108 }
23109 }
23110 else if (s < e && *s != '\n') {
23111 goto check_if_property;
23112 }
23113 }
23114
23115 if (max == -1) { /* The line only had one entry */
23116 max = min;
23117 }
23118 else if (max < min) {
23119 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23120 sv_catpvs(msg, "Illegal range in \"");
23121 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23122 UTF8fARG(is_contents_utf8, s - s0, s0));
23123 sv_catpvs(msg, "\"");
23124 goto return_failure;
23125 }
23126
23127# if 0 /* See explanation at definition above of get_extended_utf8_msg() */
23128
23129 if ( UNICODE_IS_PERL_EXTENDED(min)
23130 || UNICODE_IS_PERL_EXTENDED(max))
23131 {
23132 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23133
23134 /* If both code points are non-portable, warn only on the lower
23135 * one. */
23136 sv_catpv(msg, get_extended_utf8_msg(
23137 (UNICODE_IS_PERL_EXTENDED(min))
23138 ? min : max));
23139 sv_catpvs(msg, " in \"");
23140 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23141 UTF8fARG(is_contents_utf8, s - s0, s0));
23142 sv_catpvs(msg, "\"");
23143 }
23144
23145# endif
23146
23147 /* Here, this line contains a legal range */
23148 this_definition = sv_2mortal(_new_invlist(2));
23149 this_definition = _add_range_to_invlist(this_definition, min, max);
23150 goto calculate;
23151
23152 check_if_property:
23153
23154 /* Here it isn't a legal range line. See if it is a legal property
23155 * line. First find the end of the meat of the line */
23156 s = strpbrk(s, "#\n");
23157 if (s == NULL) {
23158 s = e;
23159 }
23160
23161 /* Ignore trailing blanks in keeping with the requirements of
23162 * parse_uniprop_string() */
23163 s--;
23164 while (s > s0 && isBLANK_A(*s)) {
23165 s--;
23166 }
23167 s++;
23168
23169 this_definition = parse_uniprop_string(s0, s - s0,
23170 is_utf8, to_fold, runtime,
23171 deferrable,
23172 user_defined_ptr, msg,
23173 (name_len == 0)
23174 ? level /* Don't increase level
23175 if input is empty */
23176 : level + 1
23177 );
23178 if (this_definition == NULL) {
23179 goto return_failure; /* 'msg' should have had the reason
23180 appended to it by the above call */
23181 }
23182
23183 if (! is_invlist(this_definition)) { /* Unknown at this time */
23184 return newSVsv(this_definition);
23185 }
23186
23187 if (*s != '\n') {
23188 s = strchr(s, '\n');
23189 if (s == NULL) {
23190 s = e;
23191 }
23192 }
23193
23194 calculate:
23195
23196 switch (op) {
23197 case '+':
23198 _invlist_union(running_definition, this_definition,
23199 &running_definition);
23200 break;
23201 case '-':
23202 _invlist_subtract(running_definition, this_definition,
23203 &running_definition);
23204 break;
23205 case '&':
23206 _invlist_intersection(running_definition, this_definition,
23207 &running_definition);
23208 break;
23209 case '!':
23210 _invlist_union_complement_2nd(running_definition,
23211 this_definition, &running_definition);
23212 break;
23213 default:
23214 Perl_croak(aTHX_ "panic: %s: %d: Unexpected operation %d",
23215 __FILE__, __LINE__, op);
23216 break;
23217 }
23218
23219 /* Position past the '\n' */
23220 s0 = s + 1;
23221 } /* End of loop through the lines of 'contents' */
23222
23223 /* Here, we processed all the lines in 'contents' without error. If we
23224 * didn't add any warnings, simply return success */
23225 if (msgs_length_on_entry == SvCUR(msg)) {
23226
23227 /* If the expansion was empty, the answer isn't nothing: its an empty
23228 * inversion list */
23229 if (running_definition == NULL) {
23230 running_definition = _new_invlist(1);
23231 }
23232
23233 return running_definition;
23234 }
23235
23236 /* Otherwise, add some explanatory text, but we will return success */
23237 goto return_msg;
23238
23239 return_failure:
23240 running_definition = NULL;
23241
23242 return_msg:
23243
23244 if (name_len > 0) {
23245 sv_catpvs(msg, " in expansion of ");
23246 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
23247 }
23248
23249 return running_definition;
23250}
23251
23252/* As explained below, certain operations need to take place in the first
23253 * thread created. These macros switch contexts */
23254# ifdef USE_ITHREADS
23255# define DECLARATION_FOR_GLOBAL_CONTEXT \
23256 PerlInterpreter * save_aTHX = aTHX;
23257# define SWITCH_TO_GLOBAL_CONTEXT \
23258 PERL_SET_CONTEXT((aTHX = PL_user_def_props_aTHX))
23259# define RESTORE_CONTEXT PERL_SET_CONTEXT((aTHX = save_aTHX));
23260# define CUR_CONTEXT aTHX
23261# define ORIGINAL_CONTEXT save_aTHX
23262# else
23263# define DECLARATION_FOR_GLOBAL_CONTEXT
23264# define SWITCH_TO_GLOBAL_CONTEXT NOOP
23265# define RESTORE_CONTEXT NOOP
23266# define CUR_CONTEXT NULL
23267# define ORIGINAL_CONTEXT NULL
23268# endif
23269
23270STATIC void
23271S_delete_recursion_entry(pTHX_ void *key)
23272{
23273 /* Deletes the entry used to detect recursion when expanding user-defined
23274 * properties. This is a function so it can be set up to be called even if
23275 * the program unexpectedly quits */
23276
23277 dVAR;
23278 SV ** current_entry;
23279 const STRLEN key_len = strlen((const char *) key);
23280 DECLARATION_FOR_GLOBAL_CONTEXT;
23281
23282 SWITCH_TO_GLOBAL_CONTEXT;
23283
23284 /* If the entry is one of these types, it is a permanent entry, and not the
23285 * one used to detect recursions. This function should delete only the
23286 * recursion entry */
23287 current_entry = hv_fetch(PL_user_def_props, (const char *) key, key_len, 0);
23288 if ( current_entry
23289 && ! is_invlist(*current_entry)
23290 && ! SvPOK(*current_entry))
23291 {
23292 (void) hv_delete(PL_user_def_props, (const char *) key, key_len,
23293 G_DISCARD);
23294 }
23295
23296 RESTORE_CONTEXT;
23297}
23298
23299STATIC SV *
23300S_get_fq_name(pTHX_
23301 const char * const name, /* The first non-blank in the \p{}, \P{} */
23302 const Size_t name_len, /* Its length in bytes, not including any trailing space */
23303 const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */
23304 const bool has_colon_colon
23305 )
23306{
23307 /* Returns a mortal SV containing the fully qualified version of the input
23308 * name */
23309
23310 SV * fq_name;
23311
23312 fq_name = newSVpvs_flags("", SVs_TEMP);
23313
23314 /* Use the current package if it wasn't included in our input */
23315 if (! has_colon_colon) {
23316 const HV * pkg = (IN_PERL_COMPILETIME)
23317 ? PL_curstash
23318 : CopSTASH(PL_curcop);
23319 const char* pkgname = HvNAME(pkg);
23320
23321 Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f,
23322 UTF8fARG(is_utf8, strlen(pkgname), pkgname));
23323 sv_catpvs(fq_name, "::");
23324 }
23325
23326 Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f,
23327 UTF8fARG(is_utf8, name_len, name));
23328 return fq_name;
23329}
23330
23331SV *
23332Perl_parse_uniprop_string(pTHX_
23333
23334 /* Parse the interior of a \p{}, \P{}. Returns its definition if knowable
23335 * now. If so, the return is an inversion list.
23336 *
23337 * If the property is user-defined, it is a subroutine, which in turn
23338 * may call other subroutines. This function will call the whole nest of
23339 * them to get the definition they return; if some aren't known at the time
23340 * of the call to this function, the fully qualified name of the highest
23341 * level sub is returned. It is an error to call this function at runtime
23342 * without every sub defined.
23343 *
23344 * If an error was found, NULL is returned, and 'msg' gets a suitable
23345 * message appended to it. (Appending allows the back trace of how we got
23346 * to the faulty definition to be displayed through nested calls of
23347 * user-defined subs.)
23348 *
23349 * The caller should NOT try to free any returned inversion list.
23350 *
23351 * Other parameters will be set on return as described below */
23352
23353 const char * const name, /* The first non-blank in the \p{}, \P{} */
23354 Size_t name_len, /* Its length in bytes, not including any
23355 trailing space */
23356 const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */
23357 const bool to_fold, /* ? Is this under /i */
23358 const bool runtime, /* TRUE if this is being called at run time */
23359 const bool deferrable, /* TRUE if it's ok for the definition to not be
23360 known at this call */
23361 bool *user_defined_ptr, /* Upon return from this function it will be
23362 set to TRUE if any component is a
23363 user-defined property */
23364 SV * msg, /* Any error or warning msg(s) are appended to
23365 this */
23366 const STRLEN level) /* Recursion level of this call */
23367{
23368 dVAR;
23369 char* lookup_name; /* normalized name for lookup in our tables */
23370 unsigned lookup_len; /* Its length */
23371 enum { Not_Strict = 0, /* Some properties have stricter name */
23372 Strict, /* normalization rules, which we decide */
23373 As_Is /* upon based on parsing */
23374 } stricter = Not_Strict;
23375
23376 /* nv= or numeric_value=, or possibly one of the cjk numeric properties
23377 * (though it requires extra effort to download them from Unicode and
23378 * compile perl to know about them) */
23379 bool is_nv_type = FALSE;
23380
23381 unsigned int i, j = 0;
23382 int equals_pos = -1; /* Where the '=' is found, or negative if none */
23383 int slash_pos = -1; /* Where the '/' is found, or negative if none */
23384 int table_index = 0; /* The entry number for this property in the table
23385 of all Unicode property names */
23386 bool starts_with_Is = FALSE; /* ? Does the name start with 'Is' */
23387 Size_t lookup_offset = 0; /* Used to ignore the first few characters of
23388 the normalized name in certain situations */
23389 Size_t non_pkg_begin = 0; /* Offset of first byte in 'name' that isn't
23390 part of a package name */
23391 Size_t lun_non_pkg_begin = 0; /* Similarly for 'lookup_name' */
23392 bool could_be_user_defined = TRUE; /* ? Could this be a user-defined
23393 property rather than a Unicode
23394 one. */
23395 SV * prop_definition = NULL; /* The returned definition of 'name' or NULL
23396 if an error. If it is an inversion list,
23397 it is the definition. Otherwise it is a
23398 string containing the fully qualified sub
23399 name of 'name' */
23400 SV * fq_name = NULL; /* For user-defined properties, the fully
23401 qualified name */
23402 bool invert_return = FALSE; /* ? Do we need to complement the result before
23403 returning it */
23404 bool stripped_utf8_pkg = FALSE; /* Set TRUE if the input includes an
23405 explicit utf8:: package that we strip
23406 off */
23407 /* The expansion of properties that could be either user-defined or
23408 * official unicode ones is deferred until runtime, including a marker for
23409 * those that might be in the latter category. This boolean indicates if
23410 * we've seen that marker. If not, what we're parsing can't be such an
23411 * official Unicode property whose expansion was deferred */
23412 bool could_be_deferred_official = FALSE;
23413
23414 PERL_ARGS_ASSERT_PARSE_UNIPROP_STRING;
23415
23416 /* The input will be normalized into 'lookup_name' */
23417 Newx(lookup_name, name_len, char);
23418 SAVEFREEPV(lookup_name);
23419
23420 /* Parse the input. */
23421 for (i = 0; i < name_len; i++) {
23422 char cur = name[i];
23423
23424 /* Most of the characters in the input will be of this ilk, being parts
23425 * of a name */
23426 if (isIDCONT_A(cur)) {
23427
23428 /* Case differences are ignored. Our lookup routine assumes
23429 * everything is lowercase, so normalize to that */
23430 if (isUPPER_A(cur)) {
23431 lookup_name[j++] = toLOWER_A(cur);
23432 continue;
23433 }
23434
23435 if (cur == '_') { /* Don't include these in the normalized name */
23436 continue;
23437 }
23438
23439 lookup_name[j++] = cur;
23440
23441 /* The first character in a user-defined name must be of this type.
23442 * */
23443 if (i - non_pkg_begin == 0 && ! isIDFIRST_A(cur)) {
23444 could_be_user_defined = FALSE;
23445 }
23446
23447 continue;
23448 }
23449
23450 /* Here, the character is not something typically in a name, But these
23451 * two types of characters (and the '_' above) can be freely ignored in
23452 * most situations. Later it may turn out we shouldn't have ignored
23453 * them, and we have to reparse, but we don't have enough information
23454 * yet to make that decision */
23455 if (cur == '-' || isSPACE_A(cur)) {
23456 could_be_user_defined = FALSE;
23457 continue;
23458 }
23459
23460 /* An equals sign or single colon mark the end of the first part of
23461 * the property name */
23462 if ( cur == '='
23463 || (cur == ':' && (i >= name_len - 1 || name[i+1] != ':')))
23464 {
23465 lookup_name[j++] = '='; /* Treat the colon as an '=' */
23466 equals_pos = j; /* Note where it occurred in the input */
23467 could_be_user_defined = FALSE;
23468 break;
23469 }
23470
23471 /* If this looks like it is a marker we inserted at compile time,
23472 * set a flag and otherwise ignore it. If it isn't in the final
23473 * position, keep it as it would have been user input. */
23474 if ( UNLIKELY(cur == DEFERRED_COULD_BE_OFFICIAL_MARKERc)
23475 && ! deferrable
23476 && could_be_user_defined
23477 && i == name_len - 1)
23478 {
23479 name_len--;
23480 could_be_deferred_official = TRUE;
23481 continue;
23482 }
23483
23484 /* Otherwise, this character is part of the name. */
23485 lookup_name[j++] = cur;
23486
23487 /* Here it isn't a single colon, so if it is a colon, it must be a
23488 * double colon */
23489 if (cur == ':') {
23490
23491 /* A double colon should be a package qualifier. We note its
23492 * position and continue. Note that one could have
23493 * pkg1::pkg2::...::foo
23494 * so that the position at the end of the loop will be just after
23495 * the final qualifier */
23496
23497 i++;
23498 non_pkg_begin = i + 1;
23499 lookup_name[j++] = ':';
23500 lun_non_pkg_begin = j;
23501 }
23502 else { /* Only word chars (and '::') can be in a user-defined name */
23503 could_be_user_defined = FALSE;
23504 }
23505 } /* End of parsing through the lhs of the property name (or all of it if
23506 no rhs) */
23507
23508# define STRLENs(s) (sizeof("" s "") - 1)
23509
23510 /* If there is a single package name 'utf8::', it is ambiguous. It could
23511 * be for a user-defined property, or it could be a Unicode property, as
23512 * all of them are considered to be for that package. For the purposes of
23513 * parsing the rest of the property, strip it off */
23514 if (non_pkg_begin == STRLENs("utf8::") && memBEGINPs(name, name_len, "utf8::")) {
23515 lookup_name += STRLENs("utf8::");
23516 j -= STRLENs("utf8::");
23517 equals_pos -= STRLENs("utf8::");
23518 stripped_utf8_pkg = TRUE;
23519 }
23520
23521 /* Here, we are either done with the whole property name, if it was simple;
23522 * or are positioned just after the '=' if it is compound. */
23523
23524 if (equals_pos >= 0) {
23525 assert(stricter == Not_Strict); /* We shouldn't have set this yet */
23526
23527 /* Space immediately after the '=' is ignored */
23528 i++;
23529 for (; i < name_len; i++) {
23530 if (! isSPACE_A(name[i])) {
23531 break;
23532 }
23533 }
23534
23535 /* Most punctuation after the equals indicates a subpattern, like
23536 * \p{foo=/bar/} */
23537 if ( isPUNCT_A(name[i])
23538 && name[i] != '-'
23539 && name[i] != '+'
23540 && name[i] != '_'
23541 && name[i] != '{'
23542 /* A backslash means the real delimitter is the next character,
23543 * but it must be punctuation */
23544 && (name[i] != '\\' || (i < name_len && isPUNCT_A(name[i+1]))))
23545 {
23546 /* Find the property. The table includes the equals sign, so we
23547 * use 'j' as-is */
23548 table_index = match_uniprop((U8 *) lookup_name, j);
23549 if (table_index) {
23550 const char * const * prop_values
23551 = UNI_prop_value_ptrs[table_index];
23552 REGEXP * subpattern_re;
23553 char open = name[i++];
23554 char close;
23555 const char * pos_in_brackets;
23556 bool escaped = 0;
23557
23558 /* Backslash => delimitter is the character following. We
23559 * already checked that it is punctuation */
23560 if (open == '\\') {
23561 open = name[i++];
23562 escaped = 1;
23563 }
23564
23565 /* This data structure is constructed so that the matching
23566 * closing bracket is 3 past its matching opening. The second
23567 * set of closing is so that if the opening is something like
23568 * ']', the closing will be that as well. Something similar is
23569 * done in toke.c */
23570 pos_in_brackets = memCHRs("([<)]>)]>", open);
23571 close = (pos_in_brackets) ? pos_in_brackets[3] : open;
23572
23573 if ( i >= name_len
23574 || name[name_len-1] != close
23575 || (escaped && name[name_len-2] != '\\')
23576 /* Also make sure that there are enough characters.
23577 * e.g., '\\\' would show up incorrectly as legal even
23578 * though it is too short */
23579 || (SSize_t) (name_len - i - 1 - escaped) < 0)
23580 {
23581 sv_catpvs(msg, "Unicode property wildcard not terminated");
23582 goto append_name_to_msg;
23583 }
23584
23585 Perl_ck_warner_d(aTHX_
23586 packWARN(WARN_EXPERIMENTAL__UNIPROP_WILDCARDS),
23587 "The Unicode property wildcards feature is experimental");
23588
23589 /* Now create and compile the wildcard subpattern. Use /iaa
23590 * because nothing outside of ASCII will match, and it the
23591 * property values should all match /i. Note that when the
23592 * pattern fails to compile, our added text to the user's
23593 * pattern will be displayed to the user, which is not so
23594 * desirable. */
23595 subpattern_re = compile_wildcard(name + i,
23596 name_len - i - 1 - escaped,
23597 TRUE /* /i */
23598 );
23599
23600 /* For each legal property value, see if the supplied pattern
23601 * matches it. */
23602 while (*prop_values) {
23603 const char * const entry = *prop_values;
23604 const Size_t len = strlen(entry);
23605 SV* entry_sv = newSVpvn_flags(entry, len, SVs_TEMP);
23606
23607 if (execute_wildcard(subpattern_re,
23608 (char *) entry,
23609 (char *) entry + len,
23610 (char *) entry, 0,
23611 entry_sv,
23612 0))
23613 { /* Here, matched. Add to the returned list */
23614 Size_t total_len = j + len;
23615 SV * sub_invlist = NULL;
23616 char * this_string;
23617
23618 /* We know this is a legal \p{property=value}. Call
23619 * the function to return the list of code points that
23620 * match it */
23621 Newxz(this_string, total_len + 1, char);
23622 Copy(lookup_name, this_string, j, char);
23623 my_strlcat(this_string, entry, total_len + 1);
23624 SAVEFREEPV(this_string);
23625 sub_invlist = parse_uniprop_string(this_string,
23626 total_len,
23627 is_utf8,
23628 to_fold,
23629 runtime,
23630 deferrable,
23631 user_defined_ptr,
23632 msg,
23633 level + 1);
23634 _invlist_union(prop_definition, sub_invlist,
23635 &prop_definition);
23636 }
23637
23638 prop_values++; /* Next iteration, look at next propvalue */
23639 } /* End of looking through property values; (the data
23640 structure is terminated by a NULL ptr) */
23641
23642 SvREFCNT_dec_NN(subpattern_re);
23643
23644 if (prop_definition) {
23645 return prop_definition;
23646 }
23647
23648 sv_catpvs(msg, "No Unicode property value wildcard matches:");
23649 goto append_name_to_msg;
23650 }
23651
23652 /* Here's how khw thinks we should proceed to handle the properties
23653 * not yet done: Bidi Mirroring Glyph
23654 Bidi Paired Bracket
23655 Case Folding (both full and simple)
23656 Decomposition Mapping
23657 Equivalent Unified Ideograph
23658 Name
23659 Name Alias
23660 Lowercase Mapping (both full and simple)
23661 NFKC Case Fold
23662 Titlecase Mapping (both full and simple)
23663 Uppercase Mapping (both full and simple)
23664 * Move the part that looks at the property values into a perl
23665 * script, like utf8_heavy.pl was done. This makes things somewhat
23666 * easier, but most importantly, it avoids always adding all these
23667 * strings to the memory usage when the feature is little-used.
23668 *
23669 * The property values would all be concatenated into a single
23670 * string per property with each value on a separate line, and the
23671 * code point it's for on alternating lines. Then we match the
23672 * user's input pattern m//mg, without having to worry about their
23673 * uses of '^' and '$'. Only the values that aren't the default
23674 * would be in the strings. Code points would be in UTF-8. The
23675 * search pattern that we would construct would look like
23676 * (?: \n (code-point_re) \n (?aam: user-re ) \n )
23677 * And so $1 would contain the code point that matched the user-re.
23678 * For properties where the default is the code point itself, such
23679 * as any of the case changing mappings, the string would otherwise
23680 * consist of all Unicode code points in UTF-8 strung together.
23681 * This would be impractical. So instead, examine their compiled
23682 * pattern, looking at the ssc. If none, reject the pattern as an
23683 * error. Otherwise run the pattern against every code point in
23684 * the ssc. The ssc is kind of like tr18's 3.9 Possible Match Sets
23685 * And it might be good to create an API to return the ssc.
23686 *
23687 * For the name properties, a new function could be created in
23688 * charnames which essentially does the same thing as above,
23689 * sharing Name.pl with the other charname functions. Don't know
23690 * about loose name matching, or algorithmically determined names.
23691 * Decomposition.pl similarly.
23692 *
23693 * It might be that a new pattern modifier would have to be
23694 * created, like /t for resTricTed, which changed the behavior of
23695 * some constructs in their subpattern, like \A. */
23696 } /* End of is a wildcard subppattern */
23697
23698 /* \p{name=...} is handled specially. Instead of using the normal
23699 * mechanism involving charclass_invlists.h, it uses _charnames.pm
23700 * which has the necessary (huge) data accessible to it, and which
23701 * doesn't get loaded unless necessary. The legal syntax for names is
23702 * somewhat different than other properties due both to the vagaries of
23703 * a few outlier official names, and the fact that only a few ASCII
23704 * characters are permitted in them */
23705 if ( memEQs(lookup_name, j - 1, "name")
23706 || memEQs(lookup_name, j - 1, "na"))
23707 {
23708 dSP;
23709 HV * table;
23710 SV * character;
23711 const char * error_msg;
23712 CV* lookup_loose;
23713 SV * character_name;
23714 STRLEN character_len;
23715 UV cp;
23716
23717 stricter = As_Is;
23718
23719 /* Since the RHS (after skipping initial space) is passed unchanged
23720 * to charnames, and there are different criteria for what are
23721 * legal characters in the name, just parse it here. A character
23722 * name must begin with an ASCII alphabetic */
23723 if (! isALPHA(name[i])) {
23724 goto failed;
23725 }
23726 lookup_name[j++] = name[i];
23727
23728 for (++i; i < name_len; i++) {
23729 /* Official names can only be in the ASCII range, and only
23730 * certain characters */
23731 if (! isASCII(name[i]) || ! isCHARNAME_CONT(name[i])) {
23732 goto failed;
23733 }
23734 lookup_name[j++] = name[i];
23735 }
23736
23737 /* Finished parsing, save the name into an SV */
23738 character_name = newSVpvn(lookup_name + equals_pos, j - equals_pos);
23739
23740 /* Make sure _charnames is loaded. (The parameters give context
23741 * for any errors generated */
23742 table = load_charnames(character_name, name, name_len, &error_msg);
23743 if (table == NULL) {
23744 sv_catpv(msg, error_msg);
23745 goto append_name_to_msg;
23746 }
23747
23748 lookup_loose = get_cv("_charnames::_loose_regcomp_lookup", 0);
23749 if (! lookup_loose) {
23750 Perl_croak(aTHX_
23751 "panic: Can't find '_charnames::_loose_regcomp_lookup");
23752 }
23753
23754 PUSHSTACKi(PERLSI_OVERLOAD);
23755 ENTER ;
23756 SAVETMPS;
23757 save_re_context();
23758
23759 PUSHMARK(SP) ;
23760 XPUSHs(character_name);
23761 PUTBACK;
23762 call_sv(MUTABLE_SV(lookup_loose), G_SCALAR);
23763
23764 SPAGAIN ;
23765
23766 character = POPs;
23767 SvREFCNT_inc_simple_void_NN(character);
23768
23769 PUTBACK ;
23770 FREETMPS ;
23771 LEAVE ;
23772 POPSTACK;
23773
23774 if (! SvOK(character)) {
23775 goto failed;
23776 }
23777
23778 cp = valid_utf8_to_uvchr((U8 *) SvPVX(character), &character_len);
23779 if (character_len < SvCUR(character)) {
23780 goto failed;
23781 }
23782
23783 prop_definition = add_cp_to_invlist(NULL, cp);
23784 return prop_definition;
23785 }
23786
23787 /* Certain properties whose values are numeric need special handling.
23788 * They may optionally be prefixed by 'is'. Ignore that prefix for the
23789 * purposes of checking if this is one of those properties */
23790 if (memBEGINPs(lookup_name, j, "is")) {
23791 lookup_offset = 2;
23792 }
23793
23794 /* Then check if it is one of these specially-handled properties. The
23795 * possibilities are hard-coded because easier this way, and the list
23796 * is unlikely to change.
23797 *
23798 * All numeric value type properties are of this ilk, and are also
23799 * special in a different way later on. So find those first. There
23800 * are several numeric value type properties in the Unihan DB (which is
23801 * unlikely to be compiled with perl, but we handle it here in case it
23802 * does get compiled). They all end with 'numeric'. The interiors
23803 * aren't checked for the precise property. This would stop working if
23804 * a cjk property were to be created that ended with 'numeric' and
23805 * wasn't a numeric type */
23806 is_nv_type = memEQs(lookup_name + lookup_offset,
23807 j - 1 - lookup_offset, "numericvalue")
23808 || memEQs(lookup_name + lookup_offset,
23809 j - 1 - lookup_offset, "nv")
23810 || ( memENDPs(lookup_name + lookup_offset,
23811 j - 1 - lookup_offset, "numeric")
23812 && ( memBEGINPs(lookup_name + lookup_offset,
23813 j - 1 - lookup_offset, "cjk")
23814 || memBEGINPs(lookup_name + lookup_offset,
23815 j - 1 - lookup_offset, "k")));
23816 if ( is_nv_type
23817 || memEQs(lookup_name + lookup_offset,
23818 j - 1 - lookup_offset, "canonicalcombiningclass")
23819 || memEQs(lookup_name + lookup_offset,
23820 j - 1 - lookup_offset, "ccc")
23821 || memEQs(lookup_name + lookup_offset,
23822 j - 1 - lookup_offset, "age")
23823 || memEQs(lookup_name + lookup_offset,
23824 j - 1 - lookup_offset, "in")
23825 || memEQs(lookup_name + lookup_offset,
23826 j - 1 - lookup_offset, "presentin"))
23827 {
23828 unsigned int k;
23829
23830 /* Since the stuff after the '=' is a number, we can't throw away
23831 * '-' willy-nilly, as those could be a minus sign. Other stricter
23832 * rules also apply. However, these properties all can have the
23833 * rhs not be a number, in which case they contain at least one
23834 * alphabetic. In those cases, the stricter rules don't apply.
23835 * But the numeric type properties can have the alphas [Ee] to
23836 * signify an exponent, and it is still a number with stricter
23837 * rules. So look for an alpha that signifies not-strict */
23838 stricter = Strict;
23839 for (k = i; k < name_len; k++) {
23840 if ( isALPHA_A(name[k])
23841 && (! is_nv_type || ! isALPHA_FOLD_EQ(name[k], 'E')))
23842 {
23843 stricter = Not_Strict;
23844 break;
23845 }
23846 }
23847 }
23848
23849 if (stricter) {
23850
23851 /* A number may have a leading '+' or '-'. The latter is retained
23852 * */
23853 if (name[i] == '+') {
23854 i++;
23855 }
23856 else if (name[i] == '-') {
23857 lookup_name[j++] = '-';
23858 i++;
23859 }
23860
23861 /* Skip leading zeros including single underscores separating the
23862 * zeros, or between the final leading zero and the first other
23863 * digit */
23864 for (; i < name_len - 1; i++) {
23865 if ( name[i] != '0'
23866 && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
23867 {
23868 break;
23869 }
23870 }
23871 }
23872 }
23873 else { /* No '=' */
23874
23875 /* Only a few properties without an '=' should be parsed with stricter
23876 * rules. The list is unlikely to change. */
23877 if ( memBEGINPs(lookup_name, j, "perl")
23878 && memNEs(lookup_name + 4, j - 4, "space")
23879 && memNEs(lookup_name + 4, j - 4, "word"))
23880 {
23881 stricter = Strict;
23882
23883 /* We set the inputs back to 0 and the code below will reparse,
23884 * using strict */
23885 i = j = 0;
23886 }
23887 }
23888
23889 /* Here, we have either finished the property, or are positioned to parse
23890 * the remainder, and we know if stricter rules apply. Finish out, if not
23891 * already done */
23892 for (; i < name_len; i++) {
23893 char cur = name[i];
23894
23895 /* In all instances, case differences are ignored, and we normalize to
23896 * lowercase */
23897 if (isUPPER_A(cur)) {
23898 lookup_name[j++] = toLOWER(cur);
23899 continue;
23900 }
23901
23902 /* An underscore is skipped, but not under strict rules unless it
23903 * separates two digits */
23904 if (cur == '_') {
23905 if ( stricter
23906 && ( i == 0 || (int) i == equals_pos || i == name_len- 1
23907 || ! isDIGIT_A(name[i-1]) || ! isDIGIT_A(name[i+1])))
23908 {
23909 lookup_name[j++] = '_';
23910 }
23911 continue;
23912 }
23913
23914 /* Hyphens are skipped except under strict */
23915 if (cur == '-' && ! stricter) {
23916 continue;
23917 }
23918
23919 /* XXX Bug in documentation. It says white space skipped adjacent to
23920 * non-word char. Maybe we should, but shouldn't skip it next to a dot
23921 * in a number */
23922 if (isSPACE_A(cur) && ! stricter) {
23923 continue;
23924 }
23925
23926 lookup_name[j++] = cur;
23927
23928 /* Unless this is a non-trailing slash, we are done with it */
23929 if (i >= name_len - 1 || cur != '/') {
23930 continue;
23931 }
23932
23933 slash_pos = j;
23934
23935 /* A slash in the 'numeric value' property indicates that what follows
23936 * is a denominator. It can have a leading '+' and '0's that should be
23937 * skipped. But we have never allowed a negative denominator, so treat
23938 * a minus like every other character. (No need to rule out a second
23939 * '/', as that won't match anything anyway */
23940 if (is_nv_type) {
23941 i++;
23942 if (i < name_len && name[i] == '+') {
23943 i++;
23944 }
23945
23946 /* Skip leading zeros including underscores separating digits */
23947 for (; i < name_len - 1; i++) {
23948 if ( name[i] != '0'
23949 && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
23950 {
23951 break;
23952 }
23953 }
23954
23955 /* Store the first real character in the denominator */
23956 if (i < name_len) {
23957 lookup_name[j++] = name[i];
23958 }
23959 }
23960 }
23961
23962 /* Here are completely done parsing the input 'name', and 'lookup_name'
23963 * contains a copy, normalized.
23964 *
23965 * This special case is grandfathered in: 'L_' and 'GC=L_' are accepted and
23966 * different from without the underscores. */
23967 if ( ( UNLIKELY(memEQs(lookup_name, j, "l"))
23968 || UNLIKELY(memEQs(lookup_name, j, "gc=l")))
23969 && UNLIKELY(name[name_len-1] == '_'))
23970 {
23971 lookup_name[j++] = '&';
23972 }
23973
23974 /* If the original input began with 'In' or 'Is', it could be a subroutine
23975 * call to a user-defined property instead of a Unicode property name. */
23976 if ( name_len - non_pkg_begin > 2
23977 && name[non_pkg_begin+0] == 'I'
23978 && (name[non_pkg_begin+1] == 'n' || name[non_pkg_begin+1] == 's'))
23979 {
23980 /* Names that start with In have different characterstics than those
23981 * that start with Is */
23982 if (name[non_pkg_begin+1] == 's') {
23983 starts_with_Is = TRUE;
23984 }
23985 }
23986 else {
23987 could_be_user_defined = FALSE;
23988 }
23989
23990 if (could_be_user_defined) {
23991 CV* user_sub;
23992
23993 /* If the user defined property returns the empty string, it could
23994 * easily be because the pattern is being compiled before the data it
23995 * actually needs to compile is available. This could be argued to be
23996 * a bug in the perl code, but this is a change of behavior for Perl,
23997 * so we handle it. This means that intentionally returning nothing
23998 * will not be resolved until runtime */
23999 bool empty_return = FALSE;
24000
24001 /* Here, the name could be for a user defined property, which are
24002 * implemented as subs. */
24003 user_sub = get_cvn_flags(name, name_len, 0);
24004 if (! user_sub) {
24005
24006 /* Here, the property name could be a user-defined one, but there
24007 * is no subroutine to handle it (as of now). Defer handling it
24008 * until runtime. Otherwise, a block defined by Unicode in a later
24009 * release would get the synonym InFoo added for it, and existing
24010 * code that used that name would suddenly break if it referred to
24011 * the property before the sub was declared. See [perl #134146] */
24012 if (deferrable) {
24013 goto definition_deferred;
24014 }
24015
24016 /* Here, we are at runtime, and didn't find the user property. It
24017 * could be an official property, but only if no package was
24018 * specified, or just the utf8:: package. */
24019 if (could_be_deferred_official) {
24020 lookup_name += lun_non_pkg_begin;
24021 j -= lun_non_pkg_begin;
24022 }
24023 else if (! stripped_utf8_pkg) {
24024 goto unknown_user_defined;
24025 }
24026
24027 /* Drop down to look up in the official properties */
24028 }
24029 else {
24030 const char insecure[] = "Insecure user-defined property";
24031
24032 /* Here, there is a sub by the correct name. Normally we call it
24033 * to get the property definition */
24034 dSP;
24035 SV * user_sub_sv = MUTABLE_SV(user_sub);
24036 SV * error; /* Any error returned by calling 'user_sub' */
24037 SV * key; /* The key into the hash of user defined sub names
24038 */
24039 SV * placeholder;
24040 SV ** saved_user_prop_ptr; /* Hash entry for this property */
24041
24042 /* How many times to retry when another thread is in the middle of
24043 * expanding the same definition we want */
24044 PERL_INT_FAST8_T retry_countdown = 10;
24045
24046 DECLARATION_FOR_GLOBAL_CONTEXT;
24047
24048 /* If we get here, we know this property is user-defined */
24049 *user_defined_ptr = TRUE;
24050
24051 /* We refuse to call a potentially tainted subroutine; returning an
24052 * error instead */
24053 if (TAINT_get) {
24054 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24055 sv_catpvn(msg, insecure, sizeof(insecure) - 1);
24056 goto append_name_to_msg;
24057 }
24058
24059 /* In principal, we only call each subroutine property definition
24060 * once during the life of the program. This guarantees that the
24061 * property definition never changes. The results of the single
24062 * sub call are stored in a hash, which is used instead for future
24063 * references to this property. The property definition is thus
24064 * immutable. But, to allow the user to have a /i-dependent
24065 * definition, we call the sub once for non-/i, and once for /i,
24066 * should the need arise, passing the /i status as a parameter.
24067 *
24068 * We start by constructing the hash key name, consisting of the
24069 * fully qualified subroutine name, preceded by the /i status, so
24070 * that there is a key for /i and a different key for non-/i */
24071 key = newSVpvn(((to_fold) ? "1" : "0"), 1);
24072 fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8,
24073 non_pkg_begin != 0);
24074 sv_catsv(key, fq_name);
24075 sv_2mortal(key);
24076
24077 /* We only call the sub once throughout the life of the program
24078 * (with the /i, non-/i exception noted above). That means the
24079 * hash must be global and accessible to all threads. It is
24080 * created at program start-up, before any threads are created, so
24081 * is accessible to all children. But this creates some
24082 * complications.
24083 *
24084 * 1) The keys can't be shared, or else problems arise; sharing is
24085 * turned off at hash creation time
24086 * 2) All SVs in it are there for the remainder of the life of the
24087 * program, and must be created in the same interpreter context
24088 * as the hash, or else they will be freed from the wrong pool
24089 * at global destruction time. This is handled by switching to
24090 * the hash's context to create each SV going into it, and then
24091 * immediately switching back
24092 * 3) All accesses to the hash must be controlled by a mutex, to
24093 * prevent two threads from getting an unstable state should
24094 * they simultaneously be accessing it. The code below is
24095 * crafted so that the mutex is locked whenever there is an
24096 * access and unlocked only when the next stable state is
24097 * achieved.
24098 *
24099 * The hash stores either the definition of the property if it was
24100 * valid, or, if invalid, the error message that was raised. We
24101 * use the type of SV to distinguish.
24102 *
24103 * There's also the need to guard against the definition expansion
24104 * from infinitely recursing. This is handled by storing the aTHX
24105 * of the expanding thread during the expansion. Again the SV type
24106 * is used to distinguish this from the other two cases. If we
24107 * come to here and the hash entry for this property is our aTHX,
24108 * it means we have recursed, and the code assumes that we would
24109 * infinitely recurse, so instead stops and raises an error.
24110 * (Any recursion has always been treated as infinite recursion in
24111 * this feature.)
24112 *
24113 * If instead, the entry is for a different aTHX, it means that
24114 * that thread has gotten here first, and hasn't finished expanding
24115 * the definition yet. We just have to wait until it is done. We
24116 * sleep and retry a few times, returning an error if the other
24117 * thread doesn't complete. */
24118
24119 re_fetch:
24120 USER_PROP_MUTEX_LOCK;
24121
24122 /* If we have an entry for this key, the subroutine has already
24123 * been called once with this /i status. */
24124 saved_user_prop_ptr = hv_fetch(PL_user_def_props,
24125 SvPVX(key), SvCUR(key), 0);
24126 if (saved_user_prop_ptr) {
24127
24128 /* If the saved result is an inversion list, it is the valid
24129 * definition of this property */
24130 if (is_invlist(*saved_user_prop_ptr)) {
24131 prop_definition = *saved_user_prop_ptr;
24132
24133 /* The SV in the hash won't be removed until global
24134 * destruction, so it is stable and we can unlock */
24135 USER_PROP_MUTEX_UNLOCK;
24136
24137 /* The caller shouldn't try to free this SV */
24138 return prop_definition;
24139 }
24140
24141 /* Otherwise, if it is a string, it is the error message
24142 * that was returned when we first tried to evaluate this
24143 * property. Fail, and append the message */
24144 if (SvPOK(*saved_user_prop_ptr)) {
24145 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24146 sv_catsv(msg, *saved_user_prop_ptr);
24147
24148 /* The SV in the hash won't be removed until global
24149 * destruction, so it is stable and we can unlock */
24150 USER_PROP_MUTEX_UNLOCK;
24151
24152 return NULL;
24153 }
24154
24155 assert(SvIOK(*saved_user_prop_ptr));
24156
24157 /* Here, we have an unstable entry in the hash. Either another
24158 * thread is in the middle of expanding the property's
24159 * definition, or we are ourselves recursing. We use the aTHX
24160 * in it to distinguish */
24161 if (SvIV(*saved_user_prop_ptr) != PTR2IV(CUR_CONTEXT)) {
24162
24163 /* Here, it's another thread doing the expanding. We've
24164 * looked as much as we are going to at the contents of the
24165 * hash entry. It's safe to unlock. */
24166 USER_PROP_MUTEX_UNLOCK;
24167
24168 /* Retry a few times */
24169 if (retry_countdown-- > 0) {
24170 PerlProc_sleep(1);
24171 goto re_fetch;
24172 }
24173
24174 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24175 sv_catpvs(msg, "Timeout waiting for another thread to "
24176 "define");
24177 goto append_name_to_msg;
24178 }
24179
24180 /* Here, we are recursing; don't dig any deeper */
24181 USER_PROP_MUTEX_UNLOCK;
24182
24183 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24184 sv_catpvs(msg,
24185 "Infinite recursion in user-defined property");
24186 goto append_name_to_msg;
24187 }
24188
24189 /* Here, this thread has exclusive control, and there is no entry
24190 * for this property in the hash. So we have the go ahead to
24191 * expand the definition ourselves. */
24192
24193 PUSHSTACKi(PERLSI_MAGIC);
24194 ENTER;
24195
24196 /* Create a temporary placeholder in the hash to detect recursion
24197 * */
24198 SWITCH_TO_GLOBAL_CONTEXT;
24199 placeholder= newSVuv(PTR2IV(ORIGINAL_CONTEXT));
24200 (void) hv_store_ent(PL_user_def_props, key, placeholder, 0);
24201 RESTORE_CONTEXT;
24202
24203 /* Now that we have a placeholder, we can let other threads
24204 * continue */
24205 USER_PROP_MUTEX_UNLOCK;
24206
24207 /* Make sure the placeholder always gets destroyed */
24208 SAVEDESTRUCTOR_X(S_delete_recursion_entry, SvPVX(key));
24209
24210 PUSHMARK(SP);
24211 SAVETMPS;
24212
24213 /* Call the user's function, with the /i status as a parameter.
24214 * Note that we have gone to a lot of trouble to keep this call
24215 * from being within the locked mutex region. */
24216 XPUSHs(boolSV(to_fold));
24217 PUTBACK;
24218
24219 /* The following block was taken from swash_init(). Presumably
24220 * they apply to here as well, though we no longer use a swash --
24221 * khw */
24222 SAVEHINTS();
24223 save_re_context();
24224 /* We might get here via a subroutine signature which uses a utf8
24225 * parameter name, at which point PL_subname will have been set
24226 * but not yet used. */
24227 save_item(PL_subname);
24228
24229 /* G_SCALAR guarantees a single return value */
24230 (void) call_sv(user_sub_sv, G_EVAL|G_SCALAR);
24231
24232 SPAGAIN;
24233
24234 error = ERRSV;
24235 if (TAINT_get || SvTRUE(error)) {
24236 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24237 if (SvTRUE(error)) {
24238 sv_catpvs(msg, "Error \"");
24239 sv_catsv(msg, error);
24240 sv_catpvs(msg, "\"");
24241 }
24242 if (TAINT_get) {
24243 if (SvTRUE(error)) sv_catpvs(msg, "; ");
24244 sv_catpvn(msg, insecure, sizeof(insecure) - 1);
24245 }
24246
24247 if (name_len > 0) {
24248 sv_catpvs(msg, " in expansion of ");
24249 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8,
24250 name_len,
24251 name));
24252 }
24253
24254 (void) POPs;
24255 prop_definition = NULL;
24256 }
24257 else {
24258 SV * contents = POPs;
24259
24260 /* The contents is supposed to be the expansion of the property
24261 * definition. If the definition is deferrable, and we got an
24262 * empty string back, set a flag to later defer it (after clean
24263 * up below). */
24264 if ( deferrable
24265 && (! SvPOK(contents) || SvCUR(contents) == 0))
24266 {
24267 empty_return = TRUE;
24268 }
24269 else { /* Otherwise, call a function to check for valid syntax,
24270 and handle it */
24271
24272 prop_definition = handle_user_defined_property(
24273 name, name_len,
24274 is_utf8, to_fold, runtime,
24275 deferrable,
24276 contents, user_defined_ptr,
24277 msg,
24278 level);
24279 }
24280 }
24281
24282 /* Here, we have the results of the expansion. Delete the
24283 * placeholder, and if the definition is now known, replace it with
24284 * that definition. We need exclusive access to the hash, and we
24285 * can't let anyone else in, between when we delete the placeholder
24286 * and add the permanent entry */
24287 USER_PROP_MUTEX_LOCK;
24288
24289 S_delete_recursion_entry(aTHX_ SvPVX(key));
24290
24291 if ( ! empty_return
24292 && (! prop_definition || is_invlist(prop_definition)))
24293 {
24294 /* If we got success we use the inversion list defining the
24295 * property; otherwise use the error message */
24296 SWITCH_TO_GLOBAL_CONTEXT;
24297 (void) hv_store_ent(PL_user_def_props,
24298 key,
24299 ((prop_definition)
24300 ? newSVsv(prop_definition)
24301 : newSVsv(msg)),
24302 0);
24303 RESTORE_CONTEXT;
24304 }
24305
24306 /* All done, and the hash now has a permanent entry for this
24307 * property. Give up exclusive control */
24308 USER_PROP_MUTEX_UNLOCK;
24309
24310 FREETMPS;
24311 LEAVE;
24312 POPSTACK;
24313
24314 if (empty_return) {
24315 goto definition_deferred;
24316 }
24317
24318 if (prop_definition) {
24319
24320 /* If the definition is for something not known at this time,
24321 * we toss it, and go return the main property name, as that's
24322 * the one the user will be aware of */
24323 if (! is_invlist(prop_definition)) {
24324 SvREFCNT_dec_NN(prop_definition);
24325 goto definition_deferred;
24326 }
24327
24328 sv_2mortal(prop_definition);
24329 }
24330
24331 /* And return */
24332 return prop_definition;
24333
24334 } /* End of calling the subroutine for the user-defined property */
24335 } /* End of it could be a user-defined property */
24336
24337 /* Here it wasn't a user-defined property that is known at this time. See
24338 * if it is a Unicode property */
24339
24340 lookup_len = j; /* This is a more mnemonic name than 'j' */
24341
24342 /* Get the index into our pointer table of the inversion list corresponding
24343 * to the property */
24344 table_index = match_uniprop((U8 *) lookup_name, lookup_len);
24345
24346 /* If it didn't find the property ... */
24347 if (table_index == 0) {
24348
24349 /* Try again stripping off any initial 'Is'. This is because we
24350 * promise that an initial Is is optional. The same isn't true of
24351 * names that start with 'In'. Those can match only blocks, and the
24352 * lookup table already has those accounted for. */
24353 if (starts_with_Is) {
24354 lookup_name += 2;
24355 lookup_len -= 2;
24356 equals_pos -= 2;
24357 slash_pos -= 2;
24358
24359 table_index = match_uniprop((U8 *) lookup_name, lookup_len);
24360 }
24361
24362 if (table_index == 0) {
24363 char * canonical;
24364
24365 /* Here, we didn't find it. If not a numeric type property, and
24366 * can't be a user-defined one, it isn't a legal property */
24367 if (! is_nv_type) {
24368 if (! could_be_user_defined) {
24369 goto failed;
24370 }
24371
24372 /* Here, the property name is legal as a user-defined one. At
24373 * compile time, it might just be that the subroutine for that
24374 * property hasn't been encountered yet, but at runtime, it's
24375 * an error to try to use an undefined one */
24376 if (! deferrable) {
24377 goto unknown_user_defined;;
24378 }
24379
24380 goto definition_deferred;
24381 } /* End of isn't a numeric type property */
24382
24383 /* The numeric type properties need more work to decide. What we
24384 * do is make sure we have the number in canonical form and look
24385 * that up. */
24386
24387 if (slash_pos < 0) { /* No slash */
24388
24389 /* When it isn't a rational, take the input, convert it to a
24390 * NV, then create a canonical string representation of that
24391 * NV. */
24392
24393 NV value;
24394 SSize_t value_len = lookup_len - equals_pos;
24395
24396 /* Get the value */
24397 if ( value_len <= 0
24398 || my_atof3(lookup_name + equals_pos, &value,
24399 value_len)
24400 != lookup_name + lookup_len)
24401 {
24402 goto failed;
24403 }
24404
24405 /* If the value is an integer, the canonical value is integral
24406 * */
24407 if (Perl_ceil(value) == value) {
24408 canonical = Perl_form(aTHX_ "%.*s%.0" NVff,
24409 equals_pos, lookup_name, value);
24410 }
24411 else { /* Otherwise, it is %e with a known precision */
24412 char * exp_ptr;
24413
24414 canonical = Perl_form(aTHX_ "%.*s%.*" NVef,
24415 equals_pos, lookup_name,
24416 PL_E_FORMAT_PRECISION, value);
24417
24418 /* The exponent generated is expecting two digits, whereas
24419 * %e on some systems will generate three. Remove leading
24420 * zeros in excess of 2 from the exponent. We start
24421 * looking for them after the '=' */
24422 exp_ptr = strchr(canonical + equals_pos, 'e');
24423 if (exp_ptr) {
24424 char * cur_ptr = exp_ptr + 2; /* past the 'e[+-]' */
24425 SSize_t excess_exponent_len = strlen(cur_ptr) - 2;
24426
24427 assert(*(cur_ptr - 1) == '-' || *(cur_ptr - 1) == '+');
24428
24429 if (excess_exponent_len > 0) {
24430 SSize_t leading_zeros = strspn(cur_ptr, "0");
24431 SSize_t excess_leading_zeros
24432 = MIN(leading_zeros, excess_exponent_len);
24433 if (excess_leading_zeros > 0) {
24434 Move(cur_ptr + excess_leading_zeros,
24435 cur_ptr,
24436 strlen(cur_ptr) - excess_leading_zeros
24437 + 1, /* Copy the NUL as well */
24438 char);
24439 }
24440 }
24441 }
24442 }
24443 }
24444 else { /* Has a slash. Create a rational in canonical form */
24445 UV numerator, denominator, gcd, trial;
24446 const char * end_ptr;
24447 const char * sign = "";
24448
24449 /* We can't just find the numerator, denominator, and do the
24450 * division, then use the method above, because that is
24451 * inexact. And the input could be a rational that is within
24452 * epsilon (given our precision) of a valid rational, and would
24453 * then incorrectly compare valid.
24454 *
24455 * We're only interested in the part after the '=' */
24456 const char * this_lookup_name = lookup_name + equals_pos;
24457 lookup_len -= equals_pos;
24458 slash_pos -= equals_pos;
24459
24460 /* Handle any leading minus */
24461 if (this_lookup_name[0] == '-') {
24462 sign = "-";
24463 this_lookup_name++;
24464 lookup_len--;
24465 slash_pos--;
24466 }
24467
24468 /* Convert the numerator to numeric */
24469 end_ptr = this_lookup_name + slash_pos;
24470 if (! grok_atoUV(this_lookup_name, &numerator, &end_ptr)) {
24471 goto failed;
24472 }
24473
24474 /* It better have included all characters before the slash */
24475 if (*end_ptr != '/') {
24476 goto failed;
24477 }
24478
24479 /* Set to look at just the denominator */
24480 this_lookup_name += slash_pos;
24481 lookup_len -= slash_pos;
24482 end_ptr = this_lookup_name + lookup_len;
24483
24484 /* Convert the denominator to numeric */
24485 if (! grok_atoUV(this_lookup_name, &denominator, &end_ptr)) {
24486 goto failed;
24487 }
24488
24489 /* It better be the rest of the characters, and don't divide by
24490 * 0 */
24491 if ( end_ptr != this_lookup_name + lookup_len
24492 || denominator == 0)
24493 {
24494 goto failed;
24495 }
24496
24497 /* Get the greatest common denominator using
24498 http://en.wikipedia.org/wiki/Euclidean_algorithm */
24499 gcd = numerator;
24500 trial = denominator;
24501 while (trial != 0) {
24502 UV temp = trial;
24503 trial = gcd % trial;
24504 gcd = temp;
24505 }
24506
24507 /* If already in lowest possible terms, we have already tried
24508 * looking this up */
24509 if (gcd == 1) {
24510 goto failed;
24511 }
24512
24513 /* Reduce the rational, which should put it in canonical form
24514 * */
24515 numerator /= gcd;
24516 denominator /= gcd;
24517
24518 canonical = Perl_form(aTHX_ "%.*s%s%" UVuf "/%" UVuf,
24519 equals_pos, lookup_name, sign, numerator, denominator);
24520 }
24521
24522 /* Here, we have the number in canonical form. Try that */
24523 table_index = match_uniprop((U8 *) canonical, strlen(canonical));
24524 if (table_index == 0) {
24525 goto failed;
24526 }
24527 } /* End of still didn't find the property in our table */
24528 } /* End of didn't find the property in our table */
24529
24530 /* Here, we have a non-zero return, which is an index into a table of ptrs.
24531 * A negative return signifies that the real index is the absolute value,
24532 * but the result needs to be inverted */
24533 if (table_index < 0) {
24534 invert_return = TRUE;
24535 table_index = -table_index;
24536 }
24537
24538 /* Out-of band indices indicate a deprecated property. The proper index is
24539 * modulo it with the table size. And dividing by the table size yields
24540 * an offset into a table constructed by regen/mk_invlists.pl to contain
24541 * the corresponding warning message */
24542 if (table_index > MAX_UNI_KEYWORD_INDEX) {
24543 Size_t warning_offset = table_index / MAX_UNI_KEYWORD_INDEX;
24544 table_index %= MAX_UNI_KEYWORD_INDEX;
24545 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
24546 "Use of '%.*s' in \\p{} or \\P{} is deprecated because: %s",
24547 (int) name_len, name, deprecated_property_msgs[warning_offset]);
24548 }
24549
24550 /* In a few properties, a different property is used under /i. These are
24551 * unlikely to change, so are hard-coded here. */
24552 if (to_fold) {
24553 if ( table_index == UNI_XPOSIXUPPER
24554 || table_index == UNI_XPOSIXLOWER
24555 || table_index == UNI_TITLE)
24556 {
24557 table_index = UNI_CASED;
24558 }
24559 else if ( table_index == UNI_UPPERCASELETTER
24560 || table_index == UNI_LOWERCASELETTER
24561# ifdef UNI_TITLECASELETTER /* Missing from early Unicodes */
24562 || table_index == UNI_TITLECASELETTER
24563# endif
24564 ) {
24565 table_index = UNI_CASEDLETTER;
24566 }
24567 else if ( table_index == UNI_POSIXUPPER
24568 || table_index == UNI_POSIXLOWER)
24569 {
24570 table_index = UNI_POSIXALPHA;
24571 }
24572 }
24573
24574 /* Create and return the inversion list */
24575 prop_definition =_new_invlist_C_array(uni_prop_ptrs[table_index]);
24576 sv_2mortal(prop_definition);
24577
24578
24579 /* See if there is a private use override to add to this definition */
24580 {
24581 COPHH * hinthash = (IN_PERL_COMPILETIME)
24582 ? CopHINTHASH_get(&PL_compiling)
24583 : CopHINTHASH_get(PL_curcop);
24584 SV * pu_overrides = cophh_fetch_pv(hinthash, "private_use", 0, 0);
24585
24586 if (UNLIKELY(pu_overrides && SvPOK(pu_overrides))) {
24587
24588 /* See if there is an element in the hints hash for this table */
24589 SV * pu_lookup = Perl_newSVpvf(aTHX_ "%d=", table_index);
24590 const char * pos = strstr(SvPVX(pu_overrides), SvPVX(pu_lookup));
24591
24592 if (pos) {
24593 bool dummy;
24594 SV * pu_definition;
24595 SV * pu_invlist;
24596 SV * expanded_prop_definition =
24597 sv_2mortal(invlist_clone(prop_definition, NULL));
24598
24599 /* If so, it's definition is the string from here to the next
24600 * \a character. And its format is the same as a user-defined
24601 * property */
24602 pos += SvCUR(pu_lookup);
24603 pu_definition = newSVpvn(pos, strchr(pos, '\a') - pos);
24604 pu_invlist = handle_user_defined_property(lookup_name,
24605 lookup_len,
24606 0, /* Not UTF-8 */
24607 0, /* Not folded */
24608 runtime,
24609 deferrable,
24610 pu_definition,
24611 &dummy,
24612 msg,
24613 level);
24614 if (TAINT_get) {
24615 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24616 sv_catpvs(msg, "Insecure private-use override");
24617 goto append_name_to_msg;
24618 }
24619
24620 /* For now, as a safety measure, make sure that it doesn't
24621 * override non-private use code points */
24622 _invlist_intersection(pu_invlist, PL_Private_Use, &pu_invlist);
24623
24624 /* Add it to the list to be returned */
24625 _invlist_union(prop_definition, pu_invlist,
24626 &expanded_prop_definition);
24627 prop_definition = expanded_prop_definition;
24628 Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__PRIVATE_USE), "The private_use feature is experimental");
24629 }
24630 }
24631 }
24632
24633 if (invert_return) {
24634 _invlist_invert(prop_definition);
24635 }
24636 return prop_definition;
24637
24638 unknown_user_defined:
24639 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24640 sv_catpvs(msg, "Unknown user-defined property name");
24641 goto append_name_to_msg;
24642
24643 failed:
24644 if (non_pkg_begin != 0) {
24645 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24646 sv_catpvs(msg, "Illegal user-defined property name");
24647 }
24648 else {
24649 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24650 sv_catpvs(msg, "Can't find Unicode property definition");
24651 }
24652 /* FALLTHROUGH */
24653
24654 append_name_to_msg:
24655 {
24656 const char * prefix = (runtime && level == 0) ? " \\p{" : " \"";
24657 const char * suffix = (runtime && level == 0) ? "}" : "\"";
24658
24659 sv_catpv(msg, prefix);
24660 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
24661 sv_catpv(msg, suffix);
24662 }
24663
24664 return NULL;
24665
24666 definition_deferred:
24667
24668 {
24669 bool is_qualified = non_pkg_begin != 0; /* If has "::" */
24670
24671 /* Here it could yet to be defined, so defer evaluation of this until
24672 * its needed at runtime. We need the fully qualified property name to
24673 * avoid ambiguity */
24674 if (! fq_name) {
24675 fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8,
24676 is_qualified);
24677 }
24678
24679 /* If it didn't come with a package, or the package is utf8::, this
24680 * actually could be an official Unicode property whose inclusion we
24681 * are deferring until runtime to make sure that it isn't overridden by
24682 * a user-defined property of the same name (which we haven't
24683 * encountered yet). Add a marker to indicate this possibility, for
24684 * use at such time when we first need the definition during pattern
24685 * matching execution */
24686 if (! is_qualified || memBEGINPs(name, non_pkg_begin, "utf8::")) {
24687 sv_catpvs(fq_name, DEFERRED_COULD_BE_OFFICIAL_MARKERs);
24688 }
24689
24690 /* We also need a trailing newline */
24691 sv_catpvs(fq_name, "\n");
24692
24693 *user_defined_ptr = TRUE;
24694 return fq_name;
24695 }
24696}
24697
24698#endif /* end of ! PERL_IN_XSUB_RE */
24699
24700/*
24701 * ex: set ts=8 sts=4 sw=4 et:
24702 */