This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
regcomp.c: Clarify comment
[perl5.git] / regcomp.c
CommitLineData
a0d0e21e
LW
1/* regcomp.c
2 */
3
4/*
4ac71550
TC
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"]
a0d0e21e
LW
8 */
9
61296642
DM
10/* This file contains functions for compiling a regular expression. See
11 * also regexec.c which funnily enough, contains functions for executing
166f8a29 12 * a regular expression.
e4a054ea
DM
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.
166f8a29
DM
18 */
19
a687059c
LW
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
e50aee73 29/* The names of the functions have been changed from regcomp and
3b753521 30 * regexec to pregcomp and pregexec in order to avoid conflicts
e50aee73
AD
31 * with the POSIX routines of the same names.
32*/
33
b9d5759e 34#ifdef PERL_EXT_RE_BUILD
54df2634 35#include "re_top.h"
b81d288d 36#endif
56953603 37
a687059c 38/*
e50aee73 39 * pregcomp and pregexec -- regsub and regerror are not used in perl
a687059c
LW
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 ****
4bb101f2 61 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
1129b882
NC
62 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
63 **** by Larry Wall and others
a687059c 64 ****
9ef589d8
LW
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
a687059c
LW
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"
864dbfa3 74#define PERL_IN_REGCOMP_C
a687059c 75#include "perl.h"
d06ea78c 76
acfe0abc 77#ifndef PERL_IN_XSUB_RE
d06ea78c
GS
78# include "INTERN.h"
79#endif
c277df42
IZ
80
81#define REG_COMP_C
54df2634
NC
82#ifdef PERL_IN_XSUB_RE
83# include "re_comp.h"
afda64e8 84EXTERN_C const struct regexp_engine my_reg_engine;
54df2634
NC
85#else
86# include "regcomp.h"
87#endif
a687059c 88
f7e03a10 89#include "dquote_inline.h"
b992490d 90#include "invlist_inline.h"
1b0f46bf 91#include "unicode_constants.h"
04e98a4d 92
538e84ed
KW
93#define HAS_NONLATIN1_FOLD_CLOSURE(i) \
94 _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
f12c0118
KW
95#define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
96 _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
26faadbd 97#define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
2c61f163 98#define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
94dc5c2d 99
a687059c
LW
100#ifndef STATIC
101#define STATIC static
102#endif
103
3f910e62
YO
104/* this is a chain of data about sub patterns we are processing that
105 need to be handled separately/specially in study_chunk. Its so
106 we can simulate recursion without losing state. */
107struct scan_frame;
108typedef struct scan_frame {
109 regnode *last_regnode; /* last node to process in this frame */
110 regnode *next_regnode; /* next node to process when last is reached */
111 U32 prev_recursed_depth;
112 I32 stopparen; /* what stopparen do we use */
3f910e62
YO
113
114 struct scan_frame *this_prev_frame; /* this previous frame */
115 struct scan_frame *prev_frame; /* previous frame */
116 struct scan_frame *next_frame; /* next frame */
117} scan_frame;
118
f4ae5a27
KW
119/* Certain characters are output as a sequence with the first being a
120 * backslash. */
eb7486de 121#define isBACKSLASHED_PUNCT(c) strchr("-[]\\^", c)
f4ae5a27
KW
122
123
09b2b2e6 124struct RExC_state_t {
514a91f1
DM
125 U32 flags; /* RXf_* are we folding, multilining? */
126 U32 pm_flags; /* PMf_* stuff from the calling PMOP */
830247a4 127 char *precomp; /* uncompiled string. */
711b303b 128 char *precomp_end; /* pointer to end of uncompiled string. */
288b8c02 129 REGEXP *rx_sv; /* The SV that is the regexp. */
f8fc2ecf 130 regexp *rx; /* perl core regexp structure */
538e84ed
KW
131 regexp_internal *rxi; /* internal data for regexp object
132 pprivate field */
fac92740 133 char *start; /* Start of input for compile */
830247a4
IZ
134 char *end; /* End of input for compile */
135 char *parse; /* Input-scan pointer. */
51684e3c
KW
136 char *copy_start; /* start of copy of input within
137 constructed parse string */
138 char *copy_start_in_input; /* Position in input string
139 corresponding to copy_start */
ea3daa5d 140 SSize_t whilem_seen; /* number of WHILEM in this expr */
fac92740 141 regnode *emit_start; /* Start of emitted-code area */
f55b7b26 142 regnode_offset emit; /* Code-emit pointer */
830247a4
IZ
143 I32 naughty; /* How bad is this pattern? */
144 I32 sawback; /* Did we see \1, ...? */
145 U32 seen;
88f063b4
KW
146 SSize_t size; /* Number of regnode equivalents in
147 pattern */
7c932d07
KW
148
149 /* position beyond 'precomp' of the warning message furthest away from
150 * 'precomp'. During the parse, no warnings are raised for any problems
151 * earlier in the parse than this position. This works if warnings are
152 * raised the first time a given spot is parsed, and if only one
153 * independent warning is raised for any given spot */
154 Size_t latest_warn_offset;
155
156 I32 npar; /* Capture buffer count so far in the
157 parse, (OPEN) plus one. ("par" 0 is
158 the whole pattern)*/
159 I32 total_par; /* During initial parse, is either 0,
160 or -1; the latter indicating a
161 reparse is needed. After that pass,
162 it is what 'npar' became after the
163 pass. Hence, it being > 0 indicates
164 we are in a reparse situation */
538e84ed
KW
165 I32 nestroot; /* root parens we are in - used by
166 accept */
830247a4 167 I32 seen_zerolen;
f55b7b26
KW
168 regnode_offset *open_parens; /* offsets to open parens */
169 regnode_offset *close_parens; /* offsets to close parens */
d5a00e4a 170 regnode *end_op; /* END node in program */
02daf0ab
YO
171 I32 utf8; /* whether the pattern is utf8 or not */
172 I32 orig_utf8; /* whether the pattern was originally in utf8 */
173 /* XXX use this for future optimisation of case
174 * where pattern must be upgraded to utf8. */
e40e74fe
KW
175 I32 uni_semantics; /* If a d charset modifier should use unicode
176 rules, even if the pattern is not in
177 utf8 */
81714fb9 178 HV *paren_names; /* Paren names */
538e84ed 179
40d049e4 180 regnode **recurse; /* Recurse regops */
88f063b4 181 I32 recurse_count; /* Number of recurse regops we have generated */
4286711a 182 U8 *study_chunk_recursed; /* bitmap of which subs we have moved
538e84ed 183 through */
09a65838 184 U32 study_chunk_recursed_bytes; /* bytes in bitmap */
b57e4118 185 I32 in_lookbehind;
4624b182 186 I32 contains_locale;
bb3f3ed2 187 I32 override_recoding;
b6d67071
KW
188#ifdef EBCDIC
189 I32 recode_x_to_native;
190#endif
9d53c457 191 I32 in_multi_char_class;
1acab4c5 192 struct reg_code_blocks *code_blocks;/* positions of literal (?{})
68e2671b 193 within pattern */
b1603ef8 194 int code_index; /* next code_blocks[] slot */
ee273784 195 SSize_t maxlen; /* mininum possible number of chars in string to match */
3f910e62
YO
196 scan_frame *frame_head;
197 scan_frame *frame_last;
198 U32 frame_count;
7eec73eb 199 AV *warn_text;
dc6d7f5c 200#ifdef ADD_TO_REGEXEC
830247a4
IZ
201 char *starttry; /* -Dr: where regtry was called. */
202#define RExC_starttry (pRExC_state->starttry)
203#endif
d24ca0c5 204 SV *runtime_code_qr; /* qr with the runtime code blocks */
3dab1dad 205#ifdef DEBUGGING
be8e71aa 206 const char *lastparse;
3dab1dad 207 I32 lastnum;
1f1031fe 208 AV *paren_name_list; /* idx -> name */
d9a72fcc 209 U32 study_chunk_recursed_count;
c9f0d54c
YO
210 SV *mysv1;
211 SV *mysv2;
88f063b4 212
3dab1dad
YO
213#define RExC_lastparse (pRExC_state->lastparse)
214#define RExC_lastnum (pRExC_state->lastnum)
1f1031fe 215#define RExC_paren_name_list (pRExC_state->paren_name_list)
d9a72fcc 216#define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count)
c9f0d54c
YO
217#define RExC_mysv (pRExC_state->mysv1)
218#define RExC_mysv1 (pRExC_state->mysv1)
219#define RExC_mysv2 (pRExC_state->mysv2)
220
3dab1dad 221#endif
bd0b62a6 222 bool seen_d_op;
911bd04e 223 bool strict;
da7cf1cc 224 bool study_started;
034602eb 225 bool in_script_run;
7c932d07 226 bool use_BRANCHJ;
09b2b2e6 227};
830247a4 228
e2509266 229#define RExC_flags (pRExC_state->flags)
514a91f1 230#define RExC_pm_flags (pRExC_state->pm_flags)
830247a4 231#define RExC_precomp (pRExC_state->precomp)
51684e3c
KW
232#define RExC_copy_start_in_input (pRExC_state->copy_start_in_input)
233#define RExC_copy_start_in_constructed (pRExC_state->copy_start)
711b303b 234#define RExC_precomp_end (pRExC_state->precomp_end)
288b8c02 235#define RExC_rx_sv (pRExC_state->rx_sv)
830247a4 236#define RExC_rx (pRExC_state->rx)
f8fc2ecf 237#define RExC_rxi (pRExC_state->rxi)
fac92740 238#define RExC_start (pRExC_state->start)
830247a4
IZ
239#define RExC_end (pRExC_state->end)
240#define RExC_parse (pRExC_state->parse)
7c932d07 241#define RExC_latest_warn_offset (pRExC_state->latest_warn_offset )
830247a4 242#define RExC_whilem_seen (pRExC_state->whilem_seen)
bd0b62a6
KW
243#define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs
244 under /d from /u ? */
512c0f5a 245
512c0f5a 246
7122b237 247#ifdef RE_TRACK_PATTERN_OFFSETS
44f36cd3 248# define RExC_offsets (RExC_rxi->u.offsets) /* I am not like the
538e84ed 249 others */
7122b237 250#endif
830247a4 251#define RExC_emit (pRExC_state->emit)
fac92740 252#define RExC_emit_start (pRExC_state->emit_start)
830247a4
IZ
253#define RExC_sawback (pRExC_state->sawback)
254#define RExC_seen (pRExC_state->seen)
255#define RExC_size (pRExC_state->size)
ee273784 256#define RExC_maxlen (pRExC_state->maxlen)
830247a4 257#define RExC_npar (pRExC_state->npar)
1533d1d2 258#define RExC_total_parens (pRExC_state->total_par)
e2e6a0f1 259#define RExC_nestroot (pRExC_state->nestroot)
830247a4 260#define RExC_seen_zerolen (pRExC_state->seen_zerolen)
1aa99e6b 261#define RExC_utf8 (pRExC_state->utf8)
e40e74fe 262#define RExC_uni_semantics (pRExC_state->uni_semantics)
02daf0ab 263#define RExC_orig_utf8 (pRExC_state->orig_utf8)
40d049e4
YO
264#define RExC_open_parens (pRExC_state->open_parens)
265#define RExC_close_parens (pRExC_state->close_parens)
5bd2d46e 266#define RExC_end_op (pRExC_state->end_op)
81714fb9 267#define RExC_paren_names (pRExC_state->paren_names)
40d049e4
YO
268#define RExC_recurse (pRExC_state->recurse)
269#define RExC_recurse_count (pRExC_state->recurse_count)
09a65838 270#define RExC_study_chunk_recursed (pRExC_state->study_chunk_recursed)
538e84ed
KW
271#define RExC_study_chunk_recursed_bytes \
272 (pRExC_state->study_chunk_recursed_bytes)
b57e4118 273#define RExC_in_lookbehind (pRExC_state->in_lookbehind)
4624b182 274#define RExC_contains_locale (pRExC_state->contains_locale)
b6d67071
KW
275#ifdef EBCDIC
276# define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
277#endif
9d53c457 278#define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
3f910e62
YO
279#define RExC_frame_head (pRExC_state->frame_head)
280#define RExC_frame_last (pRExC_state->frame_last)
281#define RExC_frame_count (pRExC_state->frame_count)
67cdf558 282#define RExC_strict (pRExC_state->strict)
da7cf1cc 283#define RExC_study_started (pRExC_state->study_started)
7eec73eb 284#define RExC_warn_text (pRExC_state->warn_text)
034602eb 285#define RExC_in_script_run (pRExC_state->in_script_run)
7c932d07 286#define RExC_use_BRANCHJ (pRExC_state->use_BRANCHJ)
830247a4 287
99807a43
HS
288/* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
289 * a flag to disable back-off on the fixed/floating substrings - if it's
290 * a high complexity pattern we assume the benefit of avoiding a full match
291 * is worth the cost of checking for the substrings even if they rarely help.
292 */
293#define RExC_naughty (pRExC_state->naughty)
294#define TOO_NAUGHTY (10)
295#define MARK_NAUGHTY(add) \
296 if (RExC_naughty < TOO_NAUGHTY) \
297 RExC_naughty += (add)
298#define MARK_NAUGHTY_EXP(exp, add) \
299 if (RExC_naughty < TOO_NAUGHTY) \
300 RExC_naughty += RExC_naughty / (exp) + (add)
cde0cee5 301
a687059c
LW
302#define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
303#define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
412f55bb 304 ((*s) == '{' && regcurly(s)))
a687059c
LW
305
306/*
307 * Flags to be passed up and down.
308 */
a687059c 309#define WORST 0 /* Worst case. */
c4ead770
KW
310#define HASWIDTH 0x01 /* Known to not match null strings, could match
311 non-null ones. */
fda99bee 312
e64f369d 313/* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
2fd92675
KW
314 * character. (There needs to be a case: in the switch statement in regexec.c
315 * for any node marked SIMPLE.) Note that this is not the same thing as
316 * REGNODE_SIMPLE */
fda99bee 317#define SIMPLE 0x02
e64f369d 318#define SPSTART 0x04 /* Starts with * or + */
8d9c2815
NC
319#define POSTPONED 0x08 /* (?1),(?&name), (??{...}) or similar */
320#define TRYAGAIN 0x10 /* Weeded out a declaration. */
c36361b2
KW
321#define RESTART_PARSE 0x20 /* Need to redo the parse */
322#define NEED_UTF8 0x40 /* In conjunction with RESTART_PARSE, need to
323 calcuate sizes as UTF-8 */
a687059c 324
3dab1dad
YO
325#define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
326
07be1b83
YO
327/* whether trie related optimizations are enabled */
328#if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
329#define TRIE_STUDY_OPT
786e8c11 330#define FULL_TRIE_STUDY
07be1b83
YO
331#define TRIE_STCLASS
332#endif
1de06328
YO
333
334
40d049e4
YO
335
336#define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
337#define PBITVAL(paren) (1 << ((paren) & 7))
338#define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
339#define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
340#define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
341
82a6ada4 342#define REQUIRE_UTF8(flagp) STMT_START { \
8d9c2815 343 if (!UTF) { \
c36361b2 344 *flagp = RESTART_PARSE|NEED_UTF8; \
f55b7b26 345 return 0; \
8d9c2815 346 } \
82a6ada4 347 } STMT_END
40d049e4 348
d63d75f5
KW
349/* Change from /d into /u rules, and restart the parse. RExC_uni_semantics is
350 * a flag that indicates we've changed to /u during the parse. */
512c0f5a
KW
351#define REQUIRE_UNI_RULES(flagp, restart_retval) \
352 STMT_START { \
353 if (DEPENDS_SEMANTICS) { \
512c0f5a
KW
354 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); \
355 RExC_uni_semantics = 1; \
bd0b62a6
KW
356 if (RExC_seen_d_op && LIKELY(RExC_total_parens >= 0)) { \
357 /* No need to restart the parse if we haven't seen \
358 * anything that differs between /u and /d, and no need \
359 * to restart immediately if we're going to reparse \
360 * anyway to count parens */ \
c36361b2 361 *flagp |= RESTART_PARSE; \
512c0f5a 362 return restart_retval; \
d1be211c 363 } \
512c0f5a
KW
364 } \
365 } STMT_END
366
7c932d07
KW
367#define BRANCH_MAX_OFFSET U16_MAX
368#define REQUIRE_BRANCHJ(flagp, restart_retval) \
369 STMT_START { \
370 RExC_use_BRANCHJ = 1; \
523a2924
KW
371 if (LIKELY(RExC_total_parens >= 0)) { \
372 /* No need to restart the parse immediately if we're \
373 * going to reparse anyway to count parens */ \
374 *flagp |= RESTART_PARSE; \
375 return restart_retval; \
376 } \
7c932d07
KW
377 } STMT_END
378
379#define REQUIRE_PARENS_PASS \
380 STMT_START { \
381 if (RExC_total_parens == 0) RExC_total_parens = -1; \
382 } STMT_END
383
f358228e
KW
384/* This is used to return failure (zero) early from the calling function if
385 * various flags in 'flags' are set. Two flags always cause a return:
386 * 'RESTART_PARSE' and 'NEED_UTF8'. 'extra' can be used to specify any
387 * additional flags that should cause a return; 0 if none. If the return will
388 * be done, '*flagp' is first set to be all of the flags that caused the
389 * return. */
390#define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra) \
fd7fc6ae 391 STMT_START { \
c36361b2
KW
392 if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) { \
393 *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra)); \
f358228e 394 return 0; \
fd7fc6ae
YO
395 } \
396 } STMT_END
397
c36361b2 398#define MUST_RESTART(flags) ((flags) & (RESTART_PARSE))
fd7fc6ae 399
5d555bb8 400#define RETURN_FAIL_ON_RESTART(flags,flagp) \
f358228e 401 RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0)
5d555bb8 402#define RETURN_FAIL_ON_RESTART_FLAGP(flagp) \
f358228e 403 if (MUST_RESTART(*(flagp))) return 0
fd7fc6ae 404
f19b1a63
KW
405/* This converts the named class defined in regcomp.h to its equivalent class
406 * number defined in handy.h. */
407#define namedclass_to_classnum(class) ((int) ((class) / 2))
408#define classnum_to_namedclass(classnum) ((classnum) * 2)
409
de92f5e6
KW
410#define _invlist_union_complement_2nd(a, b, output) \
411 _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
412#define _invlist_intersection_complement_2nd(a, b, output) \
413 _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
414
1de06328
YO
415/* About scan_data_t.
416
417 During optimisation we recurse through the regexp program performing
418 various inplace (keyhole style) optimisations. In addition study_chunk
419 and scan_commit populate this data structure with information about
538e84ed 420 what strings MUST appear in the pattern. We look for the longest
3b753521 421 string that must appear at a fixed location, and we look for the
1de06328
YO
422 longest string that may appear at a floating location. So for instance
423 in the pattern:
538e84ed 424
1de06328 425 /FOO[xX]A.*B[xX]BAR/
538e84ed 426
1de06328
YO
427 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
428 strings (because they follow a .* construct). study_chunk will identify
429 both FOO and BAR as being the longest fixed and floating strings respectively.
538e84ed 430
1de06328 431 The strings can be composites, for instance
538e84ed 432
1de06328 433 /(f)(o)(o)/
538e84ed 434
1de06328 435 will result in a composite fixed substring 'foo'.
538e84ed 436
1de06328 437 For each string some basic information is maintained:
538e84ed 438
6ea77169 439 - min_offset
1de06328
YO
440 This is the position the string must appear at, or not before.
441 It also implicitly (when combined with minlenp) tells us how many
3b753521
FN
442 characters must match before the string we are searching for.
443 Likewise when combined with minlenp and the length of the string it
538e84ed 444 tells us how many characters must appear after the string we have
1de06328 445 found.
538e84ed 446
1de06328
YO
447 - max_offset
448 Only used for floating strings. This is the rightmost point that
ea3daa5d 449 the string can appear at. If set to SSize_t_MAX it indicates that the
1de06328 450 string can occur infinitely far to the right.
6e12f832 451 For fixed strings, it is equal to min_offset.
538e84ed 452
1de06328 453 - minlenp
2d608413
KW
454 A pointer to the minimum number of characters of the pattern that the
455 string was found inside. This is important as in the case of positive
538e84ed 456 lookahead or positive lookbehind we can have multiple patterns
1de06328 457 involved. Consider
538e84ed 458
1de06328 459 /(?=FOO).*F/
538e84ed 460
1de06328
YO
461 The minimum length of the pattern overall is 3, the minimum length
462 of the lookahead part is 3, but the minimum length of the part that
538e84ed 463 will actually match is 1. So 'FOO's minimum length is 3, but the
1de06328 464 minimum length for the F is 1. This is important as the minimum length
538e84ed 465 is used to determine offsets in front of and behind the string being
1de06328 466 looked for. Since strings can be composites this is the length of the
486ec47a 467 pattern at the time it was committed with a scan_commit. Note that
1de06328 468 the length is calculated by study_chunk, so that the minimum lengths
538e84ed 469 are not known until the full pattern has been compiled, thus the
1de06328 470 pointer to the value.
538e84ed 471
1de06328 472 - lookbehind
538e84ed 473
1de06328 474 In the case of lookbehind the string being searched for can be
538e84ed 475 offset past the start point of the final matching string.
1de06328
YO
476 If this value was just blithely removed from the min_offset it would
477 invalidate some of the calculations for how many chars must match
478 before or after (as they are derived from min_offset and minlen and
538e84ed 479 the length of the string being searched for).
1de06328
YO
480 When the final pattern is compiled and the data is moved from the
481 scan_data_t structure into the regexp structure the information
538e84ed
KW
482 about lookbehind is factored in, with the information that would
483 have been lost precalculated in the end_shift field for the
1de06328
YO
484 associated string.
485
486 The fields pos_min and pos_delta are used to store the minimum offset
538e84ed 487 and the delta to the maximum offset at the current point in the pattern.
1de06328
YO
488
489*/
2c2d71f5 490
cb6aef8b
DM
491struct scan_data_substrs {
492 SV *str; /* longest substring found in pattern */
493 SSize_t min_offset; /* earliest point in string it can appear */
494 SSize_t max_offset; /* latest point in string it can appear */
495 SSize_t *minlenp; /* pointer to the minlen relevant to the string */
496 SSize_t lookbehind; /* is the pos of the string modified by LB */
11683ecb 497 I32 flags; /* per substring SF_* and SCF_* flags */
cb6aef8b
DM
498};
499
2c2d71f5 500typedef struct scan_data_t {
1de06328
YO
501 /*I32 len_min; unused */
502 /*I32 len_delta; unused */
49f55535 503 SSize_t pos_min;
ea3daa5d 504 SSize_t pos_delta;
2c2d71f5 505 SV *last_found;
ea3daa5d 506 SSize_t last_end; /* min value, <0 unless valid. */
49f55535 507 SSize_t last_start_min;
ea3daa5d 508 SSize_t last_start_max;
2099df82
DM
509 U8 cur_is_floating; /* whether the last_* values should be set as
510 * the next fixed (0) or floating (1)
511 * substring */
6ea77169 512
2099df82
DM
513 /* [0] is longest fixed substring so far, [1] is longest float so far */
514 struct scan_data_substrs substrs[2];
6ea77169 515
11683ecb 516 I32 flags; /* common SF_* and SCF_* flags */
2c2d71f5 517 I32 whilem_c;
49f55535 518 SSize_t *last_closep;
b8f7bb16 519 regnode_ssc *start_class;
2c2d71f5
JH
520} scan_data_t;
521
a687059c 522/*
e50aee73 523 * Forward declarations for pregcomp()'s friends.
a687059c 524 */
a0d0e21e 525
6ea77169 526static const scan_data_t zero_scan_data = {
a2ca2017 527 0, 0, NULL, 0, 0, 0, 0,
6ea77169 528 {
11683ecb
DM
529 { NULL, 0, 0, 0, 0, 0 },
530 { NULL, 0, 0, 0, 0, 0 },
6ea77169
DM
531 },
532 0, 0, NULL, NULL
533};
c277df42 534
11683ecb
DM
535/* study flags */
536
07be1b83
YO
537#define SF_BEFORE_SEOL 0x0001
538#define SF_BEFORE_MEOL 0x0002
11683ecb 539#define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
c277df42 540
07be1b83
YO
541#define SF_IS_INF 0x0040
542#define SF_HAS_PAR 0x0080
543#define SF_IN_PAR 0x0100
544#define SF_HAS_EVAL 0x0200
bc604ad8
KW
545
546
547/* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
548 * longest substring in the pattern. When it is not set the optimiser keeps
549 * track of position, but does not keep track of the actual strings seen,
550 *
551 * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
552 * /foo/i will not.
553 *
554 * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
555 * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
556 * turned off because of the alternation (BRANCH). */
07be1b83 557#define SCF_DO_SUBSTR 0x0400
bc604ad8 558
653099ff
GS
559#define SCF_DO_STCLASS_AND 0x0800
560#define SCF_DO_STCLASS_OR 0x1000
561#define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
e1901655 562#define SCF_WHILEM_VISITED_POS 0x2000
c277df42 563
786e8c11 564#define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
538e84ed 565#define SCF_SEEN_ACCEPT 0x8000
688e0391 566#define SCF_TRIE_DOING_RESTUDY 0x10000
4286711a
YO
567#define SCF_IN_DEFINE 0x20000
568
569
570
07be1b83 571
43fead97 572#define UTF cBOOL(RExC_utf8)
00b27cfc
KW
573
574/* The enums for all these are ordered so things work out correctly */
a62b1201 575#define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
538e84ed
KW
576#define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) \
577 == REGEX_DEPENDS_CHARSET)
00b27cfc 578#define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
538e84ed
KW
579#define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) \
580 >= REGEX_UNICODE_CHARSET)
581#define ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
582 == REGEX_ASCII_RESTRICTED_CHARSET)
583#define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) \
584 >= REGEX_ASCII_RESTRICTED_CHARSET)
585#define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) \
586 == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
a62b1201 587
43fead97 588#define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
a0ed51b3 589
f2c2a6ab
KW
590/* For programs that want to be strictly Unicode compatible by dying if any
591 * attempt is made to match a non-Unicode code point against a Unicode
592 * property. */
593#define ALWAYS_WARN_SUPER ckDEAD(packWARN(WARN_NON_UNICODE))
594
93733859 595#define OOB_NAMEDCLASS -1
b8c5462f 596
8e661ac5
KW
597/* There is no code point that is out-of-bounds, so this is problematic. But
598 * its only current use is to initialize a variable that is always set before
599 * looked at. */
600#define OOB_UNICODE 0xDEADBEEF
601
a0ed51b3 602#define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
a0ed51b3 603
8615cb43 604
b45f050a
JF
605/* length of regex to show in messages that don't mark a position within */
606#define RegexLengthToShowInErrorMessages 127
607
608/*
609 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
610 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
611 * op/pragma/warn/regcomp.
612 */
7253e4e3
RK
613#define MARKER1 "<-- HERE" /* marker as it appears in the description */
614#define MARKER2 " <-- HERE " /* marker as it appears within the regex */
b81d288d 615
538e84ed 616#define REPORT_LOCATION " in regex; marked by " MARKER1 \
147e3846 617 " in m/%" UTF8f MARKER2 "%" UTF8f "/"
b45f050a 618
285b5ca0
KW
619/* The code in this file in places uses one level of recursion with parsing
620 * rebased to an alternate string constructed by us in memory. This can take
621 * the form of something that is completely different from the input, or
622 * something that uses the input as part of the alternate. In the first case,
623 * there should be no possibility of an error, as we are in complete control of
51684e3c
KW
624 * the alternate string. But in the second case we don't completely control
625 * the input portion, so there may be errors in that. Here's an example:
285b5ca0
KW
626 * /[abc\x{DF}def]/ui
627 * is handled specially because \x{df} folds to a sequence of more than one
51684e3c 628 * character: 'ss'. What is done is to create and parse an alternate string,
285b5ca0
KW
629 * which looks like this:
630 * /(?:\x{DF}|[abc\x{DF}def])/ui
631 * where it uses the input unchanged in the middle of something it constructs,
632 * which is a branch for the DF outside the character class, and clustering
633 * parens around the whole thing. (It knows enough to skip the DF inside the
634 * class while in this substitute parse.) 'abc' and 'def' may have errors that
635 * need to be reported. The general situation looks like this:
636 *
51684e3c 637 * |<------- identical ------>|
285b5ca0 638 * sI tI xI eI
51684e3c 639 * Input: ---------------------------------------------------------------
285b5ca0
KW
640 * Constructed: ---------------------------------------------------
641 * sC tC xC eC EC
51684e3c 642 * |<------- identical ------>|
285b5ca0 643 *
51684e3c
KW
644 * sI..eI is the portion of the input pattern we are concerned with here.
645 * sC..EC is the constructed substitute parse string.
646 * sC..tC is constructed by us
647 * tC..eC is an exact duplicate of the portion of the input pattern tI..eI.
648 * In the diagram, these are vertically aligned.
649 * eC..EC is also constructed by us.
650 * xC is the position in the substitute parse string where we found a
651 * problem.
652 * xI is the position in the original pattern corresponding to xC.
285b5ca0 653 *
51684e3c
KW
654 * We want to display a message showing the real input string. Thus we need to
655 * translate from xC to xI. We know that xC >= tC, since the portion of the
656 * string sC..tC has been constructed by us, and so shouldn't have errors. We
657 * get:
658 * xI = tI + (xC - tC)
285b5ca0 659 *
51684e3c
KW
660 * When the substitute parse is constructed, the code needs to set:
661 * RExC_start (sC)
662 * RExC_end (eC)
663 * RExC_copy_start_in_input (tI)
664 * RExC_copy_start_in_constructed (tC)
665 * and restore them when done.
285b5ca0 666 *
51684e3c
KW
667 * During normal processing of the input pattern, both
668 * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to
669 * sI, so that xC equals xI.
285b5ca0
KW
670 */
671
51684e3c
KW
672#define sI RExC_precomp
673#define eI RExC_precomp_end
674#define sC RExC_start
675#define eC RExC_end
676#define tI RExC_copy_start_in_input
677#define tC RExC_copy_start_in_constructed
678#define xI(xC) (tI + (xC - tC))
679#define xI_offset(xC) (xI(xC) - sI)
285b5ca0
KW
680
681#define REPORT_LOCATION_ARGS(xC) \
682 UTF8fARG(UTF, \
51684e3c 683 (xI(xC) > eI) /* Don't run off end */ \
232b691f 684 ? eI - sI /* Length before the <--HERE */ \
bc929b61
KW
685 : ((xI_offset(xC) >= 0) \
686 ? xI_offset(xC) \
687 : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %" \
688 IVdf " trying to output message for " \
689 " pattern %.*s", \
51684e3c 690 __FILE__, __LINE__, (IV) xI_offset(xC), \
bc929b61 691 ((int) (eC - sC)), sC), 0)), \
51684e3c 692 sI), /* The input pattern printed up to the <--HERE */ \
285b5ca0 693 UTF8fARG(UTF, \
51684e3c
KW
694 (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */ \
695 (xI(xC) > eI) ? eI : xI(xC)) /* pattern after <--HERE */
c1d900c3 696
8a6d8ec6
HS
697/* Used to point after bad bytes for an error message, but avoid skipping
698 * past a nul byte. */
699#define SKIP_IF_CHAR(s) (!*(s) ? 0 : UTF ? UTF8SKIP(s) : 1)
700
ed68fe11
KW
701/* Set up to clean up after our imminent demise */
702#define PREPARE_TO_DIE \
703 STMT_START { \
704 if (RExC_rx_sv) \
705 SAVEFREESV(RExC_rx_sv); \
7c932d07
KW
706 if (RExC_open_parens) \
707 SAVEFREEPV(RExC_open_parens); \
708 if (RExC_close_parens) \
709 SAVEFREEPV(RExC_close_parens); \
ed68fe11
KW
710 } STMT_END
711
b45f050a
JF
712/*
713 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
714 * arg. Show regex, up to a maximum length. If it's too long, chop and add
715 * "...".
716 */
58e23c8d 717#define _FAIL(code) STMT_START { \
bfed75c6 718 const char *ellipses = ""; \
88f063b4 719 IV len = RExC_precomp_end - RExC_precomp; \
ccb2c380 720 \
ed68fe11 721 PREPARE_TO_DIE; \
ccb2c380
MP
722 if (len > RegexLengthToShowInErrorMessages) { \
723 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
724 len = RegexLengthToShowInErrorMessages - 10; \
725 ellipses = "..."; \
726 } \
58e23c8d 727 code; \
ccb2c380 728} STMT_END
8615cb43 729
58e23c8d 730#define FAIL(msg) _FAIL( \
147e3846 731 Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/", \
c1d900c3 732 msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
58e23c8d
YO
733
734#define FAIL2(msg,arg) _FAIL( \
147e3846 735 Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \
c1d900c3 736 arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
58e23c8d 737
b45f050a 738/*
b45f050a
JF
739 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
740 */
ccb2c380 741#define Simple_vFAIL(m) STMT_START { \
ccb2c380 742 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
d528642a 743 m, REPORT_LOCATION_ARGS(RExC_parse)); \
ccb2c380 744} STMT_END
b45f050a
JF
745
746/*
747 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
748 */
ccb2c380 749#define vFAIL(m) STMT_START { \
ed68fe11 750 PREPARE_TO_DIE; \
ccb2c380
MP
751 Simple_vFAIL(m); \
752} STMT_END
b45f050a
JF
753
754/*
755 * Like Simple_vFAIL(), but accepts two arguments.
756 */
ccb2c380 757#define Simple_vFAIL2(m,a1) STMT_START { \
d528642a
KW
758 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
759 REPORT_LOCATION_ARGS(RExC_parse)); \
ccb2c380 760} STMT_END
b45f050a
JF
761
762/*
763 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
764 */
ccb2c380 765#define vFAIL2(m,a1) STMT_START { \
ed68fe11 766 PREPARE_TO_DIE; \
ccb2c380
MP
767 Simple_vFAIL2(m, a1); \
768} STMT_END
b45f050a
JF
769
770
771/*
772 * Like Simple_vFAIL(), but accepts three arguments.
773 */
ccb2c380 774#define Simple_vFAIL3(m, a1, a2) STMT_START { \
c1d900c3 775 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
d528642a 776 REPORT_LOCATION_ARGS(RExC_parse)); \
ccb2c380 777} STMT_END
b45f050a
JF
778
779/*
780 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
781 */
ccb2c380 782#define vFAIL3(m,a1,a2) STMT_START { \
ed68fe11 783 PREPARE_TO_DIE; \
ccb2c380
MP
784 Simple_vFAIL3(m, a1, a2); \
785} STMT_END
b45f050a
JF
786
787/*
788 * Like Simple_vFAIL(), but accepts four arguments.
789 */
ccb2c380 790#define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
d528642a
KW
791 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3, \
792 REPORT_LOCATION_ARGS(RExC_parse)); \
ccb2c380 793} STMT_END
b45f050a 794
95db3ffa 795#define vFAIL4(m,a1,a2,a3) STMT_START { \
ed68fe11 796 PREPARE_TO_DIE; \
95db3ffa
KW
797 Simple_vFAIL4(m, a1, a2, a3); \
798} STMT_END
799
946095af 800/* A specialized version of vFAIL2 that works with UTF8f */
d528642a 801#define vFAIL2utf8f(m, a1) STMT_START { \
ed68fe11 802 PREPARE_TO_DIE; \
d528642a
KW
803 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \
804 REPORT_LOCATION_ARGS(RExC_parse)); \
946095af
BF
805} STMT_END
806
3ba22297 807#define vFAIL3utf8f(m, a1, a2) STMT_START { \
ed68fe11 808 PREPARE_TO_DIE; \
3ba22297 809 S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \
d528642a 810 REPORT_LOCATION_ARGS(RExC_parse)); \
3ba22297
KW
811} STMT_END
812
d62e749e
KW
813/* Setting this to NULL is a signal to not output warnings */
814#define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE RExC_copy_start_in_constructed = NULL
815#define RESTORE_WARNINGS RExC_copy_start_in_constructed = RExC_precomp
816
7c932d07
KW
817/* Since a warning can be generated multiple times as the input is reparsed, we
818 * output it the first time we come to that point in the parse, but suppress it
819 * otherwise. 'RExC_copy_start_in_constructed' being NULL is a flag to not
820 * generate any warnings */
55bcf857 821#define TO_OUTPUT_WARNINGS(loc) \
7c932d07
KW
822 ( RExC_copy_start_in_constructed \
823 && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset)
55bcf857 824
7c932d07
KW
825/* After we've emitted a warning, we save the position in the input so we don't
826 * output it again */
827#define UPDATE_WARNINGS_LOC(loc) \
828 STMT_START { \
829 if (TO_OUTPUT_WARNINGS(loc)) { \
830 RExC_latest_warn_offset = (xI(loc)) - RExC_precomp; \
831 } \
832 } STMT_END
77ccba3c 833
086f21bf 834/* 'warns' is the output of the packWARNx macro used in 'code' */
f8220fe2
KW
835#define _WARN_HELPER(loc, warns, code) \
836 STMT_START { \
d62e749e
KW
837 if (! RExC_copy_start_in_constructed) { \
838 Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none" \
839 " expected at '%s'", \
840 __FILE__, __LINE__, loc); \
841 } \
55bcf857 842 if (TO_OUTPUT_WARNINGS(loc)) { \
086f21bf
KW
843 if (ckDEAD(warns)) \
844 PREPARE_TO_DIE; \
338190a1 845 code; \
77ccba3c 846 UPDATE_WARNINGS_LOC(loc); \
338190a1 847 } \
f8220fe2 848 } STMT_END
946095af 849
5e0a247b 850/* m is not necessarily a "literal string", in this macro */
f8220fe2
KW
851#define reg_warn_non_literal_string(loc, m) \
852 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
853 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
d528642a 854 "%s" REPORT_LOCATION, \
f8220fe2 855 m, REPORT_LOCATION_ARGS(loc)))
5e0a247b 856
f8220fe2
KW
857#define ckWARNreg(loc,m) \
858 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
859 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
d528642a 860 m REPORT_LOCATION, \
f8220fe2 861 REPORT_LOCATION_ARGS(loc)))
ccb2c380 862
f8220fe2
KW
863#define vWARN(loc, m) \
864 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
865 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
d528642a 866 m REPORT_LOCATION, \
f8220fe2 867 REPORT_LOCATION_ARGS(loc))) \
b927b7e9 868
f8220fe2
KW
869#define vWARN_dep(loc, m) \
870 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
871 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), \
d528642a 872 m REPORT_LOCATION, \
f8220fe2 873 REPORT_LOCATION_ARGS(loc)))
0d6106aa 874
f8220fe2
KW
875#define ckWARNdep(loc,m) \
876 _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \
877 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
d528642a 878 m REPORT_LOCATION, \
f8220fe2 879 REPORT_LOCATION_ARGS(loc)))
147508a2 880
f8220fe2
KW
881#define ckWARNregdep(loc,m) \
882 _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
883 Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, \
d528642a
KW
884 WARN_REGEXP), \
885 m REPORT_LOCATION, \
f8220fe2 886 REPORT_LOCATION_ARGS(loc)))
ccb2c380 887
f8220fe2
KW
888#define ckWARN2reg_d(loc,m, a1) \
889 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
890 Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP), \
d528642a 891 m REPORT_LOCATION, \
f8220fe2 892 a1, REPORT_LOCATION_ARGS(loc)))
2335b3d3 893
f8220fe2
KW
894#define ckWARN2reg(loc, m, a1) \
895 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
896 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
d528642a 897 m REPORT_LOCATION, \
f8220fe2 898 a1, REPORT_LOCATION_ARGS(loc)))
ccb2c380 899
f8220fe2
KW
900#define vWARN3(loc, m, a1, a2) \
901 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
902 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
d528642a 903 m REPORT_LOCATION, \
f8220fe2 904 a1, a2, REPORT_LOCATION_ARGS(loc)))
ccb2c380 905
f8220fe2
KW
906#define ckWARN3reg(loc, m, a1, a2) \
907 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
908 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
d528642a
KW
909 m REPORT_LOCATION, \
910 a1, a2, \
f8220fe2 911 REPORT_LOCATION_ARGS(loc)))
668c081a 912
f8220fe2
KW
913#define vWARN4(loc, m, a1, a2, a3) \
914 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
915 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
d528642a
KW
916 m REPORT_LOCATION, \
917 a1, a2, a3, \
f8220fe2 918 REPORT_LOCATION_ARGS(loc)))
ccb2c380 919
f8220fe2
KW
920#define ckWARN4reg(loc, m, a1, a2, a3) \
921 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
922 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \
d528642a
KW
923 m REPORT_LOCATION, \
924 a1, a2, a3, \
f8220fe2 925 REPORT_LOCATION_ARGS(loc)))
668c081a 926
f8220fe2
KW
927#define vWARN5(loc, m, a1, a2, a3, a4) \
928 _WARN_HELPER(loc, packWARN(WARN_REGEXP), \
929 Perl_warner(aTHX_ packWARN(WARN_REGEXP), \
d528642a
KW
930 m REPORT_LOCATION, \
931 a1, a2, a3, a4, \
f8220fe2 932 REPORT_LOCATION_ARGS(loc)))
9d1d55b5 933
aea5f181
KW
934#define ckWARNexperimental(loc, class, m) \
935 _WARN_HELPER(loc, packWARN(class), \
936 Perl_ck_warner_d(aTHX_ packWARN(class), \
937 m REPORT_LOCATION, \
938 REPORT_LOCATION_ARGS(loc)))
939
1a322bb4
KW
940/* Convert between a pointer to a node and its offset from the beginning of the
941 * program */
942#define REGNODE_p(offset) (RExC_emit_start + (offset))
943#define REGNODE_OFFSET(node) ((node) - RExC_emit_start)
944
538e84ed 945/* Macros for recording node offsets. 20001227 mjd@plover.com
fac92740
MJD
946 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
947 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
948 * Element 0 holds the number n.
07be1b83 949 * Position is 1 indexed.
fac92740 950 */
7122b237 951#ifndef RE_TRACK_PATTERN_OFFSETS
d7c442ce 952#define Set_Node_Offset_To_R(offset,byte)
7122b237
YO
953#define Set_Node_Offset(node,byte)
954#define Set_Cur_Node_Offset
955#define Set_Node_Length_To_R(node,len)
956#define Set_Node_Length(node,len)
6a86c6ad 957#define Set_Node_Cur_Length(node,start)
538e84ed
KW
958#define Node_Offset(n)
959#define Node_Length(n)
7122b237
YO
960#define Set_Node_Offset_Length(node,offset,len)
961#define ProgLen(ri) ri->u.proglen
962#define SetProgLen(ri,x) ri->u.proglen = x
4cbeff97 963#define Track_Code(code)
7122b237
YO
964#else
965#define ProgLen(ri) ri->u.offsets[0]
966#define SetProgLen(ri,x) ri->u.offsets[0] = x
d7c442ce 967#define Set_Node_Offset_To_R(offset,byte) STMT_START { \
ccb2c380 968 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
d7c442ce
KW
969 __LINE__, (int)(offset), (int)(byte))); \
970 if((offset) < 0) { \
538e84ed 971 Perl_croak(aTHX_ "value of node is %d in Offset macro", \
d7c442ce 972 (int)(offset)); \
ccb2c380 973 } else { \
d7c442ce 974 RExC_offsets[2*(offset)-1] = (byte); \
ccb2c380 975 } \
ccb2c380
MP
976} STMT_END
977
88f063b4 978#define Set_Node_Offset(node,byte) \
1a322bb4 979 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start)
ccb2c380
MP
980#define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
981
982#define Set_Node_Length_To_R(node,len) STMT_START { \
ccb2c380 983 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
551405c4 984 __LINE__, (int)(node), (int)(len))); \
ccb2c380 985 if((node) < 0) { \
538e84ed
KW
986 Perl_croak(aTHX_ "value of node is %d in Length macro", \
987 (int)(node)); \
ccb2c380
MP
988 } else { \
989 RExC_offsets[2*(node)] = (len); \
990 } \
ccb2c380
MP
991} STMT_END
992
993#define Set_Node_Length(node,len) \
1a322bb4 994 Set_Node_Length_To_R(REGNODE_OFFSET(node), len)
6a86c6ad
NC
995#define Set_Node_Cur_Length(node, start) \
996 Set_Node_Length(node, RExC_parse - start)
fac92740
MJD
997
998/* Get offsets and lengths */
1a322bb4
KW
999#define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1])
1000#define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))])
fac92740 1001
07be1b83 1002#define Set_Node_Offset_Length(node,offset,len) STMT_START { \
1a322bb4
KW
1003 Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset)); \
1004 Set_Node_Length_To_R(REGNODE_OFFSET(node), (len)); \
07be1b83 1005} STMT_END
4cbeff97
TC
1006
1007#define Track_Code(code) STMT_START { code } STMT_END
7122b237 1008#endif
07be1b83
YO
1009
1010#if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
1011#define EXPERIMENTAL_INPLACESCAN
f427392e 1012#endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
07be1b83 1013
cb41e5d6
YO
1014#ifdef DEBUGGING
1015int
6ad9a8ab 1016Perl_re_printf(pTHX_ const char *fmt, ...)
cb41e5d6
YO
1017{
1018 va_list ap;
1019 int result;
1020 PerlIO *f= Perl_debug_log;
1021 PERL_ARGS_ASSERT_RE_PRINTF;
1022 va_start(ap, fmt);
1023 result = PerlIO_vprintf(f, fmt, ap);
1024 va_end(ap);
1025 return result;
1026}
1027
1028int
7b031478 1029Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
cb41e5d6
YO
1030{
1031 va_list ap;
1032 int result;
1033 PerlIO *f= Perl_debug_log;
1034 PERL_ARGS_ASSERT_RE_INDENTF;
1035 va_start(ap, depth);
daeb874b 1036 PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
cb41e5d6
YO
1037 result = PerlIO_vprintf(f, fmt, ap);
1038 va_end(ap);
1039 return result;
1040}
1041#endif /* DEBUGGING */
1042
7b031478 1043#define DEBUG_RExC_seen() \
538e84ed 1044 DEBUG_OPTIMISE_MORE_r({ \
88f063b4 1045 Perl_re_printf( aTHX_ "RExC_seen: "); \
538e84ed 1046 \
e384d5c1 1047 if (RExC_seen & REG_ZERO_LEN_SEEN) \
88f063b4 1048 Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN "); \
538e84ed 1049 \
e384d5c1 1050 if (RExC_seen & REG_LOOKBEHIND_SEEN) \
88f063b4 1051 Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN "); \
538e84ed 1052 \
e384d5c1 1053 if (RExC_seen & REG_GPOS_SEEN) \
88f063b4 1054 Perl_re_printf( aTHX_ "REG_GPOS_SEEN "); \
538e84ed 1055 \
e384d5c1 1056 if (RExC_seen & REG_RECURSE_SEEN) \
88f063b4 1057 Perl_re_printf( aTHX_ "REG_RECURSE_SEEN "); \
538e84ed 1058 \
7b031478 1059 if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN) \
88f063b4 1060 Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN "); \
538e84ed 1061 \
e384d5c1 1062 if (RExC_seen & REG_VERBARG_SEEN) \
88f063b4 1063 Perl_re_printf( aTHX_ "REG_VERBARG_SEEN "); \
538e84ed 1064 \
e384d5c1 1065 if (RExC_seen & REG_CUTGROUP_SEEN) \
88f063b4 1066 Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN "); \
538e84ed 1067 \
e384d5c1 1068 if (RExC_seen & REG_RUN_ON_COMMENT_SEEN) \
88f063b4 1069 Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN "); \
538e84ed 1070 \
e384d5c1 1071 if (RExC_seen & REG_UNFOLDED_MULTI_SEEN) \
88f063b4 1072 Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN "); \
538e84ed 1073 \
7b031478 1074 if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) \
88f063b4 1075 Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN "); \
ee273784 1076 \
88f063b4 1077 Perl_re_printf( aTHX_ "\n"); \
9e9ecfdf
YO
1078 });
1079
fdfb4f21 1080#define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
6ad9a8ab 1081 if ((flags) & flag) Perl_re_printf( aTHX_ "%s ", #flag)
fdfb4f21 1082
fdfb4f21 1083
f5a36d78
DM
1084#ifdef DEBUGGING
1085static void
1086S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
1087 const char *close_str)
1088{
1089 if (!flags)
1090 return;
1091
1092 Perl_re_printf( aTHX_ "%s", open_str);
11683ecb
DM
1093 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
1094 DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
f5a36d78
DM
1095 DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
1096 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
1097 DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
1098 DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
1099 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
1100 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
1101 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
1102 DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
1103 DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
1104 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
1105 DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
1106 DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
1107 DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
1108 Perl_re_printf( aTHX_ "%s", close_str);
1109}
1110
1111
1112static void
1113S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
1114 U32 depth, int is_inf)
1115{
1116 GET_RE_DEBUG_FLAGS_DECL;
1117
1118 DEBUG_OPTIMISE_MORE_r({
1119 if (!data)
1120 return;
1121 Perl_re_indentf(aTHX_ "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
1122 depth,
1123 where,
1124 (IV)data->pos_min,
1125 (IV)data->pos_delta,
1126 (UV)data->flags
1127 );
1128
1129 S_debug_show_study_flags(aTHX_ data->flags," [","]");
fdfb4f21 1130
f5a36d78
DM
1131 Perl_re_printf( aTHX_
1132 " Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
1133 (IV)data->whilem_c,
1134 (IV)(data->last_closep ? *((data)->last_closep) : -1),
1135 is_inf ? "INF " : ""
1136 );
1137
11683ecb 1138 if (data->last_found) {
37b6262f 1139 int i;
11683ecb
DM
1140 Perl_re_printf(aTHX_
1141 "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
1142 SvPVX_const(data->last_found),
1143 (IV)data->last_end,
1144 (IV)data->last_start_min,
1145 (IV)data->last_start_max
1146 );
1147
2099df82 1148 for (i = 0; i < 2; i++) {
37b6262f
DM
1149 Perl_re_printf(aTHX_
1150 " %s%s: '%s' @ %" IVdf "/%" IVdf,
2099df82
DM
1151 data->cur_is_floating == i ? "*" : "",
1152 i ? "Float" : "Fixed",
37b6262f
DM
1153 SvPVX_const(data->substrs[i].str),
1154 (IV)data->substrs[i].min_offset,
1155 (IV)data->substrs[i].max_offset
1156 );
1157 S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
1158 }
11683ecb 1159 }
f5a36d78
DM
1160
1161 Perl_re_printf( aTHX_ "\n");
1162 });
1163}
1164
1165
1166static void
1167S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
1168 regnode *scan, U32 depth, U32 flags)
1169{
1170 GET_RE_DEBUG_FLAGS_DECL;
1171
1172 DEBUG_OPTIMISE_r({
1173 regnode *Next;
1174
1175 if (!scan)
1176 return;
1177 Next = regnext(scan);
1178 regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
1179 Perl_re_indentf( aTHX_ "%s>%3d: %s (%d)",
1180 depth,
1181 str,
1182 REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
1183 Next ? (REG_NODE_NUM(Next)) : 0 );
1184 S_debug_show_study_flags(aTHX_ flags," [ ","]");
1185 Perl_re_printf( aTHX_ "\n");
1186 });
1187}
1188
1189
1190# define DEBUG_STUDYDATA(where, data, depth, is_inf) \
1191 S_debug_studydata(aTHX_ where, data, depth, is_inf)
1192
1193# define DEBUG_PEEP(str, scan, depth, flags) \
1194 S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
1195
1196#else
1197# define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
1198# define DEBUG_PEEP(str, scan, depth, flags) NOOP
1199#endif
1de06328 1200
cb41e5d6 1201
c6871b76
KW
1202/* =========================================================
1203 * BEGIN edit_distance stuff.
1204 *
1205 * This calculates how many single character changes of any type are needed to
1206 * transform a string into another one. It is taken from version 3.1 of
1207 *
1208 * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1209 */
1210
1211/* Our unsorted dictionary linked list. */
1212/* Note we use UVs, not chars. */
1213
1214struct dictionary{
1215 UV key;
1216 UV value;
1217 struct dictionary* next;
1218};
1219typedef struct dictionary item;
1220
1221
1222PERL_STATIC_INLINE item*
88f063b4 1223push(UV key, item* curr)
c6871b76
KW
1224{
1225 item* head;
d09f14bf 1226 Newx(head, 1, item);
c6871b76
KW
1227 head->key = key;
1228 head->value = 0;
1229 head->next = curr;
1230 return head;
1231}
1232
1233
1234PERL_STATIC_INLINE item*
1235find(item* head, UV key)
1236{
1237 item* iterator = head;
1238 while (iterator){
1239 if (iterator->key == key){
1240 return iterator;
1241 }
1242 iterator = iterator->next;
1243 }
1244
1245 return NULL;
1246}
1247
1248PERL_STATIC_INLINE item*
88f063b4 1249uniquePush(item* head, UV key)
c6871b76
KW
1250{
1251 item* iterator = head;
1252
1253 while (iterator){
1254 if (iterator->key == key) {
1255 return head;
1256 }
1257 iterator = iterator->next;
1258 }
1259
88f063b4 1260 return push(key, head);
c6871b76
KW
1261}
1262
1263PERL_STATIC_INLINE void
1264dict_free(item* head)
1265{
1266 item* iterator = head;
1267
1268 while (iterator) {
1269 item* temp = iterator;
1270 iterator = iterator->next;
1271 Safefree(temp);
1272 }
1273
1274 head = NULL;
1275}
1276
1277/* End of Dictionary Stuff */
1278
1279/* All calculations/work are done here */
1280STATIC int
1281S_edit_distance(const UV* src,
1282 const UV* tgt,
1283 const STRLEN x, /* length of src[] */
1284 const STRLEN y, /* length of tgt[] */
1285 const SSize_t maxDistance
1286)
1287{
1288 item *head = NULL;
88f063b4 1289 UV swapCount, swapScore, targetCharCount, i, j;
c6871b76
KW
1290 UV *scores;
1291 UV score_ceil = x + y;
1292
1293 PERL_ARGS_ASSERT_EDIT_DISTANCE;
1294
1295 /* intialize matrix start values */
d09f14bf 1296 Newx(scores, ( (x + 2) * (y + 2)), UV);
c6871b76
KW
1297 scores[0] = score_ceil;
1298 scores[1 * (y + 2) + 0] = score_ceil;
1299 scores[0 * (y + 2) + 1] = score_ceil;
1300 scores[1 * (y + 2) + 1] = 0;
88f063b4 1301 head = uniquePush(uniquePush(head, src[0]), tgt[0]);
c6871b76
KW
1302
1303 /* work loops */
1304 /* i = src index */
1305 /* j = tgt index */
1306 for (i=1;i<=x;i++) {
1307 if (i < x)
88f063b4 1308 head = uniquePush(head, src[i]);
c6871b76
KW
1309 scores[(i+1) * (y + 2) + 1] = i;
1310 scores[(i+1) * (y + 2) + 0] = score_ceil;
1311 swapCount = 0;
1312
1313 for (j=1;j<=y;j++) {
1314 if (i == 1) {
1315 if(j < y)
88f063b4 1316 head = uniquePush(head, tgt[j]);
c6871b76
KW
1317 scores[1 * (y + 2) + (j + 1)] = j;
1318 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1319 }
1320
88f063b4 1321 targetCharCount = find(head, tgt[j-1])->value;
c6871b76
KW
1322 swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1323
1324 if (src[i-1] != tgt[j-1]){
1325 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));
1326 }
1327 else {
1328 swapCount = j;
1329 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1330 }
1331 }
1332
88f063b4 1333 find(head, src[i-1])->value = i;
c6871b76
KW
1334 }
1335
1336 {
1337 IV score = scores[(x+1) * (y + 2) + (y + 1)];
1338 dict_free(head);
1339 Safefree(scores);
1340 return (maxDistance != 0 && maxDistance < score)?(-1):score;
1341 }
1342}
1343
1344/* END of edit_distance() stuff
1345 * ========================================================= */
1346
8e35b056
KW
1347/* is c a control character for which we have a mnemonic? */
1348#define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
1349
549b4e78
KW
1350STATIC const char *
1351S_cntrl_to_mnemonic(const U8 c)
1352{
1353 /* Returns the mnemonic string that represents character 'c', if one
1354 * exists; NULL otherwise. The only ones that exist for the purposes of
1355 * this routine are a few control characters */
1356
1357 switch (c) {
1358 case '\a': return "\\a";
1359 case '\b': return "\\b";
1360 case ESC_NATIVE: return "\\e";
1361 case '\f': return "\\f";
1362 case '\n': return "\\n";
1363 case '\r': return "\\r";
1364 case '\t': return "\\t";
1365 }
1366
1367 return NULL;
1368}
1369
653099ff 1370/* Mark that we cannot extend a found fixed substring at this point.
37b6262f 1371 Update the longest found anchored substring or the longest found
653099ff
GS
1372 floating substrings if needed. */
1373
4327152a 1374STATIC void
ea3daa5d
FC
1375S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1376 SSize_t *minlenp, int is_inf)
c277df42 1377{
e1ec3a88 1378 const STRLEN l = CHR_SVLEN(data->last_found);
2099df82 1379 SV * const longest_sv = data->substrs[data->cur_is_floating].str;
a2ca2017 1380 const STRLEN old_l = CHR_SVLEN(longest_sv);
1de06328 1381 GET_RE_DEBUG_FLAGS_DECL;
b81d288d 1382
7918f24d
NC
1383 PERL_ARGS_ASSERT_SCAN_COMMIT;
1384
c277df42 1385 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
2099df82 1386 const U8 i = data->cur_is_floating;
a2ca2017 1387 SvSetMagicSV(longest_sv, data->last_found);
37b6262f
DM
1388 data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
1389
2099df82
DM
1390 if (!i) /* fixed */
1391 data->substrs[0].max_offset = data->substrs[0].min_offset;
1392 else { /* float */
1393 data->substrs[1].max_offset = (l
646e8787
DM
1394 ? data->last_start_max
1395 : (data->pos_delta > SSize_t_MAX - data->pos_min
ea3daa5d
FC
1396 ? SSize_t_MAX
1397 : data->pos_min + data->pos_delta));
1398 if (is_inf
2099df82
DM
1399 || (STRLEN)data->substrs[1].max_offset > (STRLEN)SSize_t_MAX)
1400 data->substrs[1].max_offset = SSize_t_MAX;
37b6262f 1401 }
11683ecb 1402
37b6262f
DM
1403 if (data->flags & SF_BEFORE_EOL)
1404 data->substrs[i].flags |= (data->flags & SF_BEFORE_EOL);
1405 else
1406 data->substrs[i].flags &= ~SF_BEFORE_EOL;
1407 data->substrs[i].minlenp = minlenp;
1408 data->substrs[i].lookbehind = 0;
c277df42 1409 }
37b6262f 1410
c277df42 1411 SvCUR_set(data->last_found, 0);
0eda9292 1412 {
a28509cc 1413 SV * const sv = data->last_found;
097eb12c
AL
1414 if (SvUTF8(sv) && SvMAGICAL(sv)) {
1415 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1416 if (mg)
1417 mg->mg_len = 0;
1418 }
0eda9292 1419 }
c277df42
IZ
1420 data->last_end = -1;
1421 data->flags &= ~SF_BEFORE_EOL;
f5a36d78 1422 DEBUG_STUDYDATA("commit", data, 0, is_inf);
c277df42
IZ
1423}
1424
cdd87c1d
KW
1425/* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1426 * list that describes which code points it matches */
1427
653099ff 1428STATIC void
3420edd7 1429S_ssc_anything(pTHX_ regnode_ssc *ssc)
653099ff 1430{
cdd87c1d
KW
1431 /* Set the SSC 'ssc' to match an empty string or any code point */
1432
557bd3fb 1433 PERL_ARGS_ASSERT_SSC_ANYTHING;
7918f24d 1434
71068078 1435 assert(is_ANYOF_SYNTHETIC(ssc));
3fffb88a 1436
0854ea0b
KW
1437 /* mortalize so won't leak */
1438 ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
93e92956 1439 ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING; /* Plus matches empty */
653099ff
GS
1440}
1441
653099ff 1442STATIC int
dc3bf405 1443S_ssc_is_anything(const regnode_ssc *ssc)
653099ff 1444{
c144baaa
KW
1445 /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1446 * point; FALSE otherwise. Thus, this is used to see if using 'ssc' buys
1447 * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1448 * in any way, so there's no point in using it */
cdd87c1d
KW
1449
1450 UV start, end;
1451 bool ret;
653099ff 1452
557bd3fb 1453 PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
7918f24d 1454
71068078 1455 assert(is_ANYOF_SYNTHETIC(ssc));
cdd87c1d 1456
93e92956 1457 if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
cdd87c1d
KW
1458 return FALSE;
1459 }
1460
1461 /* See if the list consists solely of the range 0 - Infinity */
1462 invlist_iterinit(ssc->invlist);
1463 ret = invlist_iternext(ssc->invlist, &start, &end)
1464 && start == 0
1465 && end == UV_MAX;
1466
1467 invlist_iterfinish(ssc->invlist);
1468
1469 if (ret) {
1470 return TRUE;
1471 }
1472
1473 /* If e.g., both \w and \W are set, matches everything */
e0e1be5f 1474 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
cdd87c1d
KW
1475 int i;
1476 for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1477 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1478 return TRUE;
1479 }
1480 }
1481 }
1482
1483 return FALSE;
653099ff
GS
1484}
1485
653099ff 1486STATIC void
cdd87c1d 1487S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
653099ff 1488{
cdd87c1d
KW
1489 /* Initializes the SSC 'ssc'. This includes setting it to match an empty
1490 * string, any code point, or any posix class under locale */
1491
557bd3fb 1492 PERL_ARGS_ASSERT_SSC_INIT;
7918f24d 1493
557bd3fb 1494 Zero(ssc, 1, regnode_ssc);
71068078 1495 set_ANYOF_SYNTHETIC(ssc);
93e92956 1496 ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
3420edd7 1497 ssc_anything(ssc);
cdd87c1d 1498
2f306ab9
KW
1499 /* If any portion of the regex is to operate under locale rules that aren't
1500 * fully known at compile time, initialization includes it. The reason
1501 * this isn't done for all regexes is that the optimizer was written under
1502 * the assumption that locale was all-or-nothing. Given the complexity and
1503 * lack of documentation in the optimizer, and that there are inadequate
1504 * test cases for locale, many parts of it may not work properly, it is
1505 * safest to avoid locale unless necessary. */
cdd87c1d
KW
1506 if (RExC_contains_locale) {
1507 ANYOF_POSIXL_SETALL(ssc);
cdd87c1d
KW
1508 }
1509 else {
1510 ANYOF_POSIXL_ZERO(ssc);
1511 }
653099ff
GS
1512}
1513
b423522f 1514STATIC int
dc3bf405
BF
1515S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1516 const regnode_ssc *ssc)
b423522f
KW
1517{
1518 /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1519 * to the list of code points matched, and locale posix classes; hence does
1520 * not check its flags) */
1521
1522 UV start, end;
1523 bool ret;
1524
1525 PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1526
71068078 1527 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
1528
1529 invlist_iterinit(ssc->invlist);
1530 ret = invlist_iternext(ssc->invlist, &start, &end)
1531 && start == 0
1532 && end == UV_MAX;
1533
1534 invlist_iterfinish(ssc->invlist);
1535
1536 if (! ret) {
1537 return FALSE;
1538 }
1539
e0e1be5f 1540 if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
31f05a37 1541 return FALSE;
b423522f
KW
1542 }
1543
1544 return TRUE;
1545}
1546
1547STATIC SV*
1548S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
5c0f85ef 1549 const regnode_charclass* const node)
b423522f
KW
1550{
1551 /* Returns a mortal inversion list defining which code points are matched
1552 * by 'node', which is of type ANYOF. Handles complementing the result if
1553 * appropriate. If some code points aren't knowable at this time, the
31f05a37
KW
1554 * returned list must, and will, contain every code point that is a
1555 * possibility. */
b423522f 1556
e2506fa7 1557 SV* invlist = NULL;
1ee208c4 1558 SV* only_utf8_locale_invlist = NULL;
b423522f
KW
1559 unsigned int i;
1560 const U32 n = ARG(node);
31f05a37 1561 bool new_node_has_latin1 = FALSE;
b423522f
KW
1562
1563 PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1564
1565 /* Look at the data structure created by S_set_ANYOF_arg() */
93e92956 1566 if (n != ANYOF_ONLY_HAS_BITMAP) {
b423522f
KW
1567 SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1568 AV * const av = MUTABLE_AV(SvRV(rv));
1569 SV **const ary = AvARRAY(av);
1570 assert(RExC_rxi->data->what[n] == 's');
1571
1572 if (ary[1] && ary[1] != &PL_sv_undef) { /* Has compile-time swash */
28118b9c 1573 invlist = sv_2mortal(invlist_clone(_get_swash_invlist(ary[1]), NULL));
b423522f
KW
1574 }
1575 else if (ary[0] && ary[0] != &PL_sv_undef) {
1576
1577 /* Here, no compile-time swash, and there are things that won't be
1578 * known until runtime -- we have to assume it could be anything */
e2506fa7 1579 invlist = sv_2mortal(_new_invlist(1));
b423522f
KW
1580 return _add_range_to_invlist(invlist, 0, UV_MAX);
1581 }
1ee208c4 1582 else if (ary[3] && ary[3] != &PL_sv_undef) {
b423522f
KW
1583
1584 /* Here no compile-time swash, and no run-time only data. Use the
1585 * node's inversion list */
28118b9c 1586 invlist = sv_2mortal(invlist_clone(ary[3], NULL));
1ee208c4
KW
1587 }
1588
1589 /* Get the code points valid only under UTF-8 locales */
037715a6 1590 if ((ANYOF_FLAGS(node) & ANYOFL_FOLD)
1ee208c4
KW
1591 && ary[2] && ary[2] != &PL_sv_undef)
1592 {
1593 only_utf8_locale_invlist = ary[2];
b423522f
KW
1594 }
1595 }
1596
e2506fa7
KW
1597 if (! invlist) {
1598 invlist = sv_2mortal(_new_invlist(0));
1599 }
1600
dcb20b36
KW
1601 /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1602 * code points, and an inversion list for the others, but if there are code
1603 * points that should match only conditionally on the target string being
1604 * UTF-8, those are placed in the inversion list, and not the bitmap.
1605 * Since there are circumstances under which they could match, they are
1606 * included in the SSC. But if the ANYOF node is to be inverted, we have
1607 * to exclude them here, so that when we invert below, the end result
1608 * actually does include them. (Think about "\xe0" =~ /[^\xc0]/di;). We
1609 * have to do this here before we add the unconditionally matched code
1610 * points */
b423522f
KW
1611 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1612 _invlist_intersection_complement_2nd(invlist,
1613 PL_UpperLatin1,
1614 &invlist);
1615 }
1616
1617 /* Add in the points from the bit map */
dcb20b36 1618 for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
b423522f 1619 if (ANYOF_BITMAP_TEST(node, i)) {
6f8848d5
TC
1620 unsigned int start = i++;
1621
1622 for (; i < NUM_ANYOF_CODE_POINTS && ANYOF_BITMAP_TEST(node, i); ++i) {
1623 /* empty */
1624 }
1625 invlist = _add_range_to_invlist(invlist, start, i-1);
31f05a37 1626 new_node_has_latin1 = TRUE;
b423522f
KW
1627 }
1628 }
1629
1630 /* If this can match all upper Latin1 code points, have to add them
ac33c516
KW
1631 * as well. But don't add them if inverting, as when that gets done below,
1632 * it would exclude all these characters, including the ones it shouldn't
1633 * that were added just above */
1634 if (! (ANYOF_FLAGS(node) & ANYOF_INVERT) && OP(node) == ANYOFD
f240c685
KW
1635 && (ANYOF_FLAGS(node) & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1636 {
b423522f
KW
1637 _invlist_union(invlist, PL_UpperLatin1, &invlist);
1638 }
1639
1640 /* Similarly for these */
93e92956 1641 if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
e0a1ff7a 1642 _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
b423522f
KW
1643 }
1644
1645 if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1646 _invlist_invert(invlist);
1647 }
037715a6 1648 else if (new_node_has_latin1 && ANYOF_FLAGS(node) & ANYOFL_FOLD) {
31f05a37
KW
1649
1650 /* Under /li, any 0-255 could fold to any other 0-255, depending on the
1651 * locale. We can skip this if there are no 0-255 at all. */
1652 _invlist_union(invlist, PL_Latin1, &invlist);
1653 }
1654
1ee208c4
KW
1655 /* Similarly add the UTF-8 locale possible matches. These have to be
1656 * deferred until after the non-UTF-8 locale ones are taken care of just
1657 * above, or it leads to wrong results under ANYOF_INVERT */
1658 if (only_utf8_locale_invlist) {
31f05a37 1659 _invlist_union_maybe_complement_2nd(invlist,
1ee208c4 1660 only_utf8_locale_invlist,
31f05a37
KW
1661 ANYOF_FLAGS(node) & ANYOF_INVERT,
1662 &invlist);
1663 }
b423522f
KW
1664
1665 return invlist;
1666}
1667
1051e1c4 1668/* These two functions currently do the exact same thing */
557bd3fb 1669#define ssc_init_zero ssc_init
653099ff 1670
cdd87c1d
KW
1671#define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp))
1672#define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1673
557bd3fb 1674/* 'AND' a given class with another one. Can create false positives. 'ssc'
93e92956
KW
1675 * should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1676 * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
cdd87c1d 1677
653099ff 1678STATIC void
b423522f 1679S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
7dcac5f6 1680 const regnode_charclass *and_with)
653099ff 1681{
cdd87c1d
KW
1682 /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1683 * another SSC or a regular ANYOF class. Can create false positives. */
40d049e4 1684
a0dd4231
KW
1685 SV* anded_cp_list;
1686 U8 anded_flags;
1e6ade67 1687
cdd87c1d 1688 PERL_ARGS_ASSERT_SSC_AND;
653099ff 1689
71068078 1690 assert(is_ANYOF_SYNTHETIC(ssc));
a0dd4231
KW
1691
1692 /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1693 * the code point inversion list and just the relevant flags */
71068078 1694 if (is_ANYOF_SYNTHETIC(and_with)) {
7dcac5f6 1695 anded_cp_list = ((regnode_ssc *)and_with)->invlist;
a0dd4231 1696 anded_flags = ANYOF_FLAGS(and_with);
e9b08962
KW
1697
1698 /* XXX This is a kludge around what appears to be deficiencies in the
1699 * optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag,
1700 * there are paths through the optimizer where it doesn't get weeded
1701 * out when it should. And if we don't make some extra provision for
1702 * it like the code just below, it doesn't get added when it should.
1703 * This solution is to add it only when AND'ing, which is here, and
1704 * only when what is being AND'ed is the pristine, original node
1705 * matching anything. Thus it is like adding it to ssc_anything() but
1706 * only when the result is to be AND'ed. Probably the same solution
1707 * could be adopted for the same problem we have with /l matching,
1708 * which is solved differently in S_ssc_init(), and that would lead to
1709 * fewer false positives than that solution has. But if this solution
1710 * creates bugs, the consequences are only that a warning isn't raised
1711 * that should be; while the consequences for having /l bugs is
1712 * incorrect matches */
7dcac5f6 1713 if (ssc_is_anything((regnode_ssc *)and_with)) {
f240c685 1714 anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
e9b08962 1715 }
a0dd4231
KW
1716 }
1717 else {
5c0f85ef 1718 anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
f240c685
KW
1719 if (OP(and_with) == ANYOFD) {
1720 anded_flags = ANYOF_FLAGS(and_with) & ANYOF_COMMON_FLAGS;
1721 }
1722 else {
1723 anded_flags = ANYOF_FLAGS(and_with)
1724 &( ANYOF_COMMON_FLAGS
108316fb
KW
1725 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1726 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
d1c40ef5
KW
1727 if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(and_with))) {
1728 anded_flags &=
1729 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1730 }
f240c685 1731 }
a0dd4231
KW
1732 }
1733
1734 ANYOF_FLAGS(ssc) &= anded_flags;
cdd87c1d
KW
1735
1736 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1737 * C2 is the list of code points in 'and-with'; P2, its posix classes.
1738 * 'and_with' may be inverted. When not inverted, we have the situation of
1739 * computing:
1740 * (C1 | P1) & (C2 | P2)
1741 * = (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1742 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1743 * <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2))
1744 * <= ((C1 & C2) | P1 | P2)
1745 * Alternatively, the last few steps could be:
1746 * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1747 * <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2))
1748 * <= (C1 | C2 | (P1 & P2))
1749 * We favor the second approach if either P1 or P2 is non-empty. This is
1750 * because these components are a barrier to doing optimizations, as what
1751 * they match cannot be known until the moment of matching as they are
1752 * dependent on the current locale, 'AND"ing them likely will reduce or
1753 * eliminate them.
1754 * But we can do better if we know that C1,P1 are in their initial state (a
1755 * frequent occurrence), each matching everything:
1756 * (<everything>) & (C2 | P2) = C2 | P2
1757 * Similarly, if C2,P2 are in their initial state (again a frequent
1758 * occurrence), the result is a no-op
1759 * (C1 | P1) & (<everything>) = C1 | P1
1760 *
1761 * Inverted, we have
1762 * (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2)
1763 * = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1764 * <= (C1 & ~C2) | (P1 & ~P2)
1765 * */
1aa99e6b 1766
a0dd4231 1767 if ((ANYOF_FLAGS(and_with) & ANYOF_INVERT)
71068078 1768 && ! is_ANYOF_SYNTHETIC(and_with))
a0dd4231 1769 {
cdd87c1d 1770 unsigned int i;
8951c461 1771
cdd87c1d
KW
1772 ssc_intersection(ssc,
1773 anded_cp_list,
1774 FALSE /* Has already been inverted */
1775 );
c6b76537 1776
cdd87c1d
KW
1777 /* If either P1 or P2 is empty, the intersection will be also; can skip
1778 * the loop */
93e92956 1779 if (! (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL)) {
cdd87c1d
KW
1780 ANYOF_POSIXL_ZERO(ssc);
1781 }
e0e1be5f 1782 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
cdd87c1d
KW
1783
1784 /* Note that the Posix class component P from 'and_with' actually
1785 * looks like:
1786 * P = Pa | Pb | ... | Pn
1787 * where each component is one posix class, such as in [\w\s].
1788 * Thus
1789 * ~P = ~(Pa | Pb | ... | Pn)
1790 * = ~Pa & ~Pb & ... & ~Pn
1791 * <= ~Pa | ~Pb | ... | ~Pn
1792 * The last is something we can easily calculate, but unfortunately
1793 * is likely to have many false positives. We could do better
1794 * in some (but certainly not all) instances if two classes in
1795 * P have known relationships. For example
1796 * :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1797 * So
1798 * :lower: & :print: = :lower:
1799 * And similarly for classes that must be disjoint. For example,
1800 * since \s and \w can have no elements in common based on rules in
1801 * the POSIX standard,
1802 * \w & ^\S = nothing
1803 * Unfortunately, some vendor locales do not meet the Posix
1804 * standard, in particular almost everything by Microsoft.
1805 * The loop below just changes e.g., \w into \W and vice versa */
1806
1ee208c4 1807 regnode_charclass_posixl temp;
cdd87c1d
KW
1808 int add = 1; /* To calculate the index of the complement */
1809
b1234259 1810 Zero(&temp, 1, regnode_charclass_posixl);
cdd87c1d
KW
1811 ANYOF_POSIXL_ZERO(&temp);
1812 for (i = 0; i < ANYOF_MAX; i++) {
1813 assert(i % 2 != 0
7dcac5f6
KW
1814 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1815 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
cdd87c1d 1816
7dcac5f6 1817 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
cdd87c1d
KW
1818 ANYOF_POSIXL_SET(&temp, i + add);
1819 }
1820 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1821 }
1822 ANYOF_POSIXL_AND(&temp, ssc);
c6b76537 1823
cdd87c1d
KW
1824 } /* else ssc already has no posixes */
1825 } /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC
1826 in its initial state */
71068078 1827 else if (! is_ANYOF_SYNTHETIC(and_with)
7dcac5f6 1828 || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
cdd87c1d
KW
1829 {
1830 /* But if 'ssc' is in its initial state, the result is just 'and_with';
1831 * copy it over 'ssc' */
1832 if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
71068078 1833 if (is_ANYOF_SYNTHETIC(and_with)) {
cdd87c1d
KW
1834 StructCopy(and_with, ssc, regnode_ssc);
1835 }
1836 else {
1837 ssc->invlist = anded_cp_list;
1838 ANYOF_POSIXL_ZERO(ssc);
93e92956 1839 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
7dcac5f6 1840 ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
cdd87c1d
KW
1841 }
1842 }
1843 }
e0e1be5f 1844 else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
93e92956 1845 || (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL))
cdd87c1d
KW
1846 {
1847 /* One or the other of P1, P2 is non-empty. */
93e92956 1848 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1ea8b7fe
KW
1849 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1850 }
cdd87c1d
KW
1851 ssc_union(ssc, anded_cp_list, FALSE);
1852 }
1853 else { /* P1 = P2 = empty */
1854 ssc_intersection(ssc, anded_cp_list, FALSE);
1855 }
137165a6 1856 }
653099ff
GS
1857}
1858
653099ff 1859STATIC void
cdd87c1d 1860S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
7dcac5f6 1861 const regnode_charclass *or_with)
653099ff 1862{
cdd87c1d
KW
1863 /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1864 * another SSC or a regular ANYOF class. Can create false positives if
1865 * 'or_with' is to be inverted. */
7918f24d 1866
a0dd4231
KW
1867 SV* ored_cp_list;
1868 U8 ored_flags;
c6b76537 1869
cdd87c1d 1870 PERL_ARGS_ASSERT_SSC_OR;
c6b76537 1871
71068078 1872 assert(is_ANYOF_SYNTHETIC(ssc));
a0dd4231
KW
1873
1874 /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1875 * the code point inversion list and just the relevant flags */
71068078 1876 if (is_ANYOF_SYNTHETIC(or_with)) {
7dcac5f6 1877 ored_cp_list = ((regnode_ssc*) or_with)->invlist;
a0dd4231
KW
1878 ored_flags = ANYOF_FLAGS(or_with);
1879 }
1880 else {
5c0f85ef 1881 ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
eff8b7dc 1882 ored_flags = ANYOF_FLAGS(or_with) & ANYOF_COMMON_FLAGS;
f240c685
KW
1883 if (OP(or_with) != ANYOFD) {
1884 ored_flags
1885 |= ANYOF_FLAGS(or_with)
108316fb
KW
1886 & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1887 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
d1c40ef5
KW
1888 if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(or_with))) {
1889 ored_flags |=
1890 ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1891 }
f240c685 1892 }
a0dd4231
KW
1893 }
1894
1895 ANYOF_FLAGS(ssc) |= ored_flags;
cdd87c1d
KW
1896
1897 /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1898 * C2 is the list of code points in 'or-with'; P2, its posix classes.
1899 * 'or_with' may be inverted. When not inverted, we have the simple
1900 * situation of computing:
1901 * (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2)
1902 * If P1|P2 yields a situation with both a class and its complement are
1903 * set, like having both \w and \W, this matches all code points, and we
1904 * can delete these from the P component of the ssc going forward. XXX We
1905 * might be able to delete all the P components, but I (khw) am not certain
1906 * about this, and it is better to be safe.
1907 *
1908 * Inverted, we have
1909 * (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2)
1910 * <= (C1 | P1) | ~C2
1911 * <= (C1 | ~C2) | P1
1912 * (which results in actually simpler code than the non-inverted case)
1913 * */
9826f543 1914
a0dd4231 1915 if ((ANYOF_FLAGS(or_with) & ANYOF_INVERT)
71068078 1916 && ! is_ANYOF_SYNTHETIC(or_with))
a0dd4231 1917 {
cdd87c1d 1918 /* We ignore P2, leaving P1 going forward */
1ea8b7fe 1919 } /* else Not inverted */
93e92956 1920 else if (ANYOF_FLAGS(or_with) & ANYOF_MATCHES_POSIXL) {
7dcac5f6 1921 ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
e0e1be5f 1922 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
cdd87c1d
KW
1923 unsigned int i;
1924 for (i = 0; i < ANYOF_MAX; i += 2) {
1925 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1926 {
1927 ssc_match_all_cp(ssc);
1928 ANYOF_POSIXL_CLEAR(ssc, i);
1929 ANYOF_POSIXL_CLEAR(ssc, i+1);
cdd87c1d
KW
1930 }
1931 }
1932 }
1aa99e6b 1933 }
cdd87c1d
KW
1934
1935 ssc_union(ssc,
1936 ored_cp_list,
1937 FALSE /* Already has been inverted */
1938 );
653099ff
GS
1939}
1940
b423522f
KW
1941PERL_STATIC_INLINE void
1942S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
1943{
1944 PERL_ARGS_ASSERT_SSC_UNION;
1945
71068078 1946 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
1947
1948 _invlist_union_maybe_complement_2nd(ssc->invlist,
1949 invlist,
1950 invert2nd,
1951 &ssc->invlist);
1952}
1953
1954PERL_STATIC_INLINE void
1955S_ssc_intersection(pTHX_ regnode_ssc *ssc,
1956 SV* const invlist,
1957 const bool invert2nd)
1958{
1959 PERL_ARGS_ASSERT_SSC_INTERSECTION;
1960
71068078 1961 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
1962
1963 _invlist_intersection_maybe_complement_2nd(ssc->invlist,
1964 invlist,
1965 invert2nd,
1966 &ssc->invlist);
1967}
1968
1969PERL_STATIC_INLINE void
1970S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
1971{
1972 PERL_ARGS_ASSERT_SSC_ADD_RANGE;
1973
71068078 1974 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
1975
1976 ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
1977}
1978
1979PERL_STATIC_INLINE void
1980S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
1981{
1982 /* AND just the single code point 'cp' into the SSC 'ssc' */
1983
1984 SV* cp_list = _new_invlist(2);
1985
1986 PERL_ARGS_ASSERT_SSC_CP_AND;
1987
71068078 1988 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
1989
1990 cp_list = add_cp_to_invlist(cp_list, cp);
1991 ssc_intersection(ssc, cp_list,
1992 FALSE /* Not inverted */
1993 );
1994 SvREFCNT_dec_NN(cp_list);
1995}
1996
1997PERL_STATIC_INLINE void
dc3bf405 1998S_ssc_clear_locale(regnode_ssc *ssc)
b423522f
KW
1999{
2000 /* Set the SSC 'ssc' to not match any locale things */
b423522f
KW
2001 PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
2002
71068078 2003 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f
KW
2004
2005 ANYOF_POSIXL_ZERO(ssc);
2006 ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
2007}
2008
b35552de
KW
2009#define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
2010
2011STATIC bool
2012S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
2013{
2014 /* The synthetic start class is used to hopefully quickly winnow down
2015 * places where a pattern could start a match in the target string. If it
2016 * doesn't really narrow things down that much, there isn't much point to
2017 * having the overhead of using it. This function uses some very crude
2018 * heuristics to decide if to use the ssc or not.
2019 *
2020 * It returns TRUE if 'ssc' rules out more than half what it considers to
2021 * be the "likely" possible matches, but of course it doesn't know what the
2022 * actual things being matched are going to be; these are only guesses
2023 *
2024 * For /l matches, it assumes that the only likely matches are going to be
2025 * in the 0-255 range, uniformly distributed, so half of that is 127
2026 * For /a and /d matches, it assumes that the likely matches will be just
2027 * the ASCII range, so half of that is 63
2028 * For /u and there isn't anything matching above the Latin1 range, it
2029 * assumes that that is the only range likely to be matched, and uses
2030 * half that as the cut-off: 127. If anything matches above Latin1,
2031 * it assumes that all of Unicode could match (uniformly), except for
2032 * non-Unicode code points and things in the General Category "Other"
2033 * (unassigned, private use, surrogates, controls and formats). This
2034 * is a much large number. */
2035
b35552de
KW
2036 U32 count = 0; /* Running total of number of code points matched by
2037 'ssc' */
2038 UV start, end; /* Start and end points of current range in inversion
2039 list */
72400949
KW
2040 const U32 max_code_points = (LOC)
2041 ? 256
2042 : (( ! UNI_SEMANTICS
2043 || invlist_highest(ssc->invlist) < 256)
2044 ? 128
2045 : NON_OTHER_COUNT);
2046 const U32 max_match = max_code_points / 2;
b35552de
KW
2047
2048 PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
2049
2050 invlist_iterinit(ssc->invlist);
2051 while (invlist_iternext(ssc->invlist, &start, &end)) {
72400949
KW
2052 if (start >= max_code_points) {
2053 break;
b35552de 2054 }
72400949 2055 end = MIN(end, max_code_points - 1);
b35552de 2056 count += end - start + 1;
72400949 2057 if (count >= max_match) {
b35552de
KW
2058 invlist_iterfinish(ssc->invlist);
2059 return FALSE;
2060 }
2061 }
2062
2063 return TRUE;
2064}
2065
2066
b423522f
KW
2067STATIC void
2068S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
2069{
2070 /* The inversion list in the SSC is marked mortal; now we need a more
2071 * permanent copy, which is stored the same way that is done in a regular
dcb20b36
KW
2072 * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
2073 * map */
b423522f 2074
28118b9c 2075 SV* invlist = invlist_clone(ssc->invlist, NULL);
b423522f
KW
2076
2077 PERL_ARGS_ASSERT_SSC_FINALIZE;
2078
71068078 2079 assert(is_ANYOF_SYNTHETIC(ssc));
b423522f 2080
a0dd4231 2081 /* The code in this file assumes that all but these flags aren't relevant
93e92956
KW
2082 * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
2083 * by the time we reach here */
f240c685
KW
2084 assert(! (ANYOF_FLAGS(ssc)
2085 & ~( ANYOF_COMMON_FLAGS
108316fb
KW
2086 |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2087 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
a0dd4231 2088
b423522f
KW
2089 populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
2090
1ee208c4
KW
2091 set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist,
2092 NULL, NULL, NULL, FALSE);
b423522f 2093
85c8e306
KW
2094 /* Make sure is clone-safe */
2095 ssc->invlist = NULL;
2096
e0e1be5f 2097 if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
93e92956 2098 ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
d156f5cb 2099 OP(ssc) = ANYOFPOSIXL;
e0e1be5f 2100 }
d156f5cb 2101 else if (RExC_contains_locale) {
b2e90ddf
KW
2102 OP(ssc) = ANYOFL;
2103 }
2104
1462525b 2105 assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
b423522f
KW
2106}
2107
a3621e74
YO
2108#define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
2109#define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
2110#define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
538e84ed
KW
2111#define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \
2112 ? (TRIE_LIST_CUR( idx ) - 1) \
2113 : 0 )
a3621e74 2114
3dab1dad
YO
2115
2116#ifdef DEBUGGING
07be1b83 2117/*
2b8b4781
NC
2118 dump_trie(trie,widecharmap,revcharmap)
2119 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
2120 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
3dab1dad
YO
2121
2122 These routines dump out a trie in a somewhat readable format.
07be1b83
YO
2123 The _interim_ variants are used for debugging the interim
2124 tables that are used to generate the final compressed
2125 representation which is what dump_trie expects.
2126
486ec47a 2127 Part of the reason for their existence is to provide a form
3dab1dad 2128 of documentation as to how the different representations function.
07be1b83
YO
2129
2130*/
3dab1dad
YO
2131
2132/*
3dab1dad
YO
2133 Dumps the final compressed table form of the trie to Perl_debug_log.
2134 Used for debugging make_trie().
2135*/
b9a59e08 2136
3dab1dad 2137STATIC void
2b8b4781
NC
2138S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
2139 AV *revcharmap, U32 depth)
3dab1dad
YO
2140{
2141 U32 state;
ab3bbdeb 2142 SV *sv=sv_newmortal();
55eed653 2143 int colwidth= widecharmap ? 6 : 4;
2e64971a 2144 U16 word;
3dab1dad
YO
2145 GET_RE_DEBUG_FLAGS_DECL;
2146
7918f24d 2147 PERL_ARGS_ASSERT_DUMP_TRIE;
ab3bbdeb 2148
6ad9a8ab 2149 Perl_re_indentf( aTHX_ "Char : %-6s%-6s%-4s ",
1e37780e 2150 depth+1, "Match","Base","Ofs" );
3dab1dad
YO
2151
2152 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2b8b4781 2153 SV ** const tmp = av_fetch( revcharmap, state, 0);
3dab1dad 2154 if ( tmp ) {
6ad9a8ab 2155 Perl_re_printf( aTHX_ "%*s",
ab3bbdeb 2156 colwidth,
538e84ed 2157 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
ab3bbdeb
YO
2158 PL_colors[0], PL_colors[1],
2159 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
538e84ed
KW
2160 PERL_PV_ESCAPE_FIRSTCHAR
2161 )
ab3bbdeb 2162 );
3dab1dad
YO
2163 }
2164 }
1e37780e
YO
2165 Perl_re_printf( aTHX_ "\n");
2166 Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
3dab1dad
YO
2167
2168 for( state = 0 ; state < trie->uniquecharcount ; state++ )
6ad9a8ab
YO
2169 Perl_re_printf( aTHX_ "%.*s", colwidth, "--------");
2170 Perl_re_printf( aTHX_ "\n");
3dab1dad 2171
1e2e3d02 2172 for( state = 1 ; state < trie->statecount ; state++ ) {
be8e71aa 2173 const U32 base = trie->states[ state ].trans.base;
3dab1dad 2174
147e3846 2175 Perl_re_indentf( aTHX_ "#%4" UVXf "|", depth+1, (UV)state);
3dab1dad
YO
2176
2177 if ( trie->states[ state ].wordnum ) {
1e37780e 2178 Perl_re_printf( aTHX_ " W%4X", trie->states[ state ].wordnum );
3dab1dad 2179 } else {
6ad9a8ab 2180 Perl_re_printf( aTHX_ "%6s", "" );
3dab1dad
YO
2181 }
2182
147e3846 2183 Perl_re_printf( aTHX_ " @%4" UVXf " ", (UV)base );
3dab1dad
YO
2184
2185 if ( base ) {
2186 U32 ofs = 0;
2187
2188 while( ( base + ofs < trie->uniquecharcount ) ||
2189 ( base + ofs - trie->uniquecharcount < trie->lasttrans
538e84ed
KW
2190 && trie->trans[ base + ofs - trie->uniquecharcount ].check
2191 != state))
3dab1dad
YO
2192 ofs++;
2193
147e3846 2194 Perl_re_printf( aTHX_ "+%2" UVXf "[ ", (UV)ofs);
3dab1dad
YO
2195
2196 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
538e84ed
KW
2197 if ( ( base + ofs >= trie->uniquecharcount )
2198 && ( base + ofs - trie->uniquecharcount
2199 < trie->lasttrans )
2200 && trie->trans[ base + ofs
2201 - trie->uniquecharcount ].check == state )
3dab1dad 2202 {
147e3846 2203 Perl_re_printf( aTHX_ "%*" UVXf, colwidth,
1e37780e
YO
2204 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
2205 );
3dab1dad 2206 } else {
88f063b4 2207 Perl_re_printf( aTHX_ "%*s", colwidth," ." );
3dab1dad
YO
2208 }
2209 }
2210
6ad9a8ab 2211 Perl_re_printf( aTHX_ "]");
3dab1dad
YO
2212
2213 }
6ad9a8ab 2214 Perl_re_printf( aTHX_ "\n" );
3dab1dad 2215 }
6ad9a8ab 2216 Perl_re_indentf( aTHX_ "word_info N:(prev,len)=",
cb41e5d6 2217 depth);
2e64971a 2218 for (word=1; word <= trie->wordcount; word++) {
6ad9a8ab 2219 Perl_re_printf( aTHX_ " %d:(%d,%d)",
2e64971a
DM
2220 (int)word, (int)(trie->wordinfo[word].prev),
2221 (int)(trie->wordinfo[word].len));
2222 }
6ad9a8ab 2223 Perl_re_printf( aTHX_ "\n" );
538e84ed 2224}
3dab1dad 2225/*
3dab1dad 2226 Dumps a fully constructed but uncompressed trie in list form.
538e84ed 2227 List tries normally only are used for construction when the number of
3dab1dad
YO
2228 possible chars (trie->uniquecharcount) is very high.
2229 Used for debugging make_trie().
2230*/
2231STATIC void
55eed653 2232S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2b8b4781
NC
2233 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2234 U32 depth)
3dab1dad
YO
2235{
2236 U32 state;
ab3bbdeb 2237 SV *sv=sv_newmortal();
55eed653 2238 int colwidth= widecharmap ? 6 : 4;
3dab1dad 2239 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
2240
2241 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2242
3dab1dad 2243 /* print out the table precompression. */
6ad9a8ab 2244 Perl_re_indentf( aTHX_ "State :Word | Transition Data\n",
cb41e5d6 2245 depth+1 );
6ad9a8ab 2246 Perl_re_indentf( aTHX_ "%s",
cb41e5d6 2247 depth+1, "------:-----+-----------------\n" );
538e84ed 2248
3dab1dad
YO
2249 for( state=1 ; state < next_alloc ; state ++ ) {
2250 U16 charid;
538e84ed 2251
147e3846 2252 Perl_re_indentf( aTHX_ " %4" UVXf " :",
cb41e5d6 2253 depth+1, (UV)state );
3dab1dad 2254 if ( ! trie->states[ state ].wordnum ) {
6ad9a8ab 2255 Perl_re_printf( aTHX_ "%5s| ","");
3dab1dad 2256 } else {
6ad9a8ab 2257 Perl_re_printf( aTHX_ "W%4x| ",
3dab1dad
YO
2258 trie->states[ state ].wordnum
2259 );
2260 }
2261 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
538e84ed 2262 SV ** const tmp = av_fetch( revcharmap,
88f063b4 2263 TRIE_LIST_ITEM(state, charid).forid, 0);
ab3bbdeb 2264 if ( tmp ) {
147e3846 2265 Perl_re_printf( aTHX_ "%*s:%3X=%4" UVXf " | ",
ab3bbdeb 2266 colwidth,
538e84ed
KW
2267 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2268 colwidth,
2269 PL_colors[0], PL_colors[1],
2270 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2271 | PERL_PV_ESCAPE_FIRSTCHAR
ab3bbdeb 2272 ) ,
88f063b4
KW
2273 TRIE_LIST_ITEM(state, charid).forid,
2274 (UV)TRIE_LIST_ITEM(state, charid).newstate
1e2e3d02 2275 );
538e84ed 2276 if (!(charid % 10))
6ad9a8ab 2277 Perl_re_printf( aTHX_ "\n%*s| ",
664e119d 2278 (int)((depth * 2) + 14), "");
1e2e3d02 2279 }
ab3bbdeb 2280 }
6ad9a8ab 2281 Perl_re_printf( aTHX_ "\n");
3dab1dad 2282 }
538e84ed 2283}
3dab1dad
YO
2284
2285/*
3dab1dad 2286 Dumps a fully constructed but uncompressed trie in table form.
538e84ed
KW
2287 This is the normal DFA style state transition table, with a few
2288 twists to facilitate compression later.
3dab1dad
YO
2289 Used for debugging make_trie().
2290*/
2291STATIC void
55eed653 2292S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2b8b4781
NC
2293 HV *widecharmap, AV *revcharmap, U32 next_alloc,
2294 U32 depth)
3dab1dad
YO
2295{
2296 U32 state;
2297 U16 charid;
ab3bbdeb 2298 SV *sv=sv_newmortal();
55eed653 2299 int colwidth= widecharmap ? 6 : 4;
3dab1dad 2300 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
2301
2302 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
538e84ed 2303
3dab1dad
YO
2304 /*
2305 print out the table precompression so that we can do a visual check
2306 that they are identical.
2307 */
538e84ed 2308
6ad9a8ab 2309 Perl_re_indentf( aTHX_ "Char : ", depth+1 );
3dab1dad
YO
2310
2311 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2b8b4781 2312 SV ** const tmp = av_fetch( revcharmap, charid, 0);
3dab1dad 2313 if ( tmp ) {
6ad9a8ab 2314 Perl_re_printf( aTHX_ "%*s",
ab3bbdeb 2315 colwidth,
538e84ed 2316 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
ab3bbdeb
YO
2317 PL_colors[0], PL_colors[1],
2318 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
538e84ed
KW
2319 PERL_PV_ESCAPE_FIRSTCHAR
2320 )
ab3bbdeb 2321 );
3dab1dad
YO
2322 }
2323 }
2324
4aaafc03
YO
2325 Perl_re_printf( aTHX_ "\n");
2326 Perl_re_indentf( aTHX_ "State+-", depth+1 );
3dab1dad
YO
2327
2328 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
6ad9a8ab 2329 Perl_re_printf( aTHX_ "%.*s", colwidth,"--------");
3dab1dad
YO
2330 }
2331
6ad9a8ab 2332 Perl_re_printf( aTHX_ "\n" );
3dab1dad
YO
2333
2334 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2335
147e3846 2336 Perl_re_indentf( aTHX_ "%4" UVXf " : ",
cb41e5d6 2337 depth+1,
3dab1dad
YO
2338 (UV)TRIE_NODENUM( state ) );
2339
2340 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
ab3bbdeb
YO
2341 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2342 if (v)
147e3846 2343 Perl_re_printf( aTHX_ "%*" UVXf, colwidth, v );
ab3bbdeb 2344 else
6ad9a8ab 2345 Perl_re_printf( aTHX_ "%*s", colwidth, "." );
3dab1dad
YO
2346 }
2347 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
147e3846 2348 Perl_re_printf( aTHX_ " (%4" UVXf ")\n",
538e84ed 2349 (UV)trie->trans[ state ].check );
3dab1dad 2350 } else {
147e3846 2351 Perl_re_printf( aTHX_ " (%4" UVXf ") W%4X\n",
538e84ed 2352 (UV)trie->trans[ state ].check,
3dab1dad
YO
2353 trie->states[ TRIE_NODENUM( state ) ].wordnum );
2354 }
2355 }
07be1b83 2356}
3dab1dad
YO
2357
2358#endif
2359
2e64971a 2360
786e8c11
YO
2361/* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2362 startbranch: the first branch in the whole branch sequence
2363 first : start branch of sequence of branch-exact nodes.
2364 May be the same as startbranch
2365 last : Thing following the last branch.
2366 May be the same as tail.
2367 tail : item following the branch sequence
2368 count : words in the sequence
a4525e78 2369 flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
786e8c11 2370 depth : indent depth
3dab1dad 2371
786e8c11 2372Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
07be1b83 2373
786e8c11
YO
2374A trie is an N'ary tree where the branches are determined by digital
2375decomposition of the key. IE, at the root node you look up the 1st character and
2376follow that branch repeat until you find the end of the branches. Nodes can be
2377marked as "accepting" meaning they represent a complete word. Eg:
07be1b83 2378
786e8c11 2379 /he|she|his|hers/
72f13be8 2380
786e8c11
YO
2381would convert into the following structure. Numbers represent states, letters
2382following numbers represent valid transitions on the letter from that state, if
2383the number is in square brackets it represents an accepting state, otherwise it
2384will be in parenthesis.
07be1b83 2385
786e8c11
YO
2386 +-h->+-e->[3]-+-r->(8)-+-s->[9]
2387 | |
2388 | (2)
2389 | |
2390 (1) +-i->(6)-+-s->[7]
2391 |
2392 +-s->(3)-+-h->(4)-+-e->[5]
07be1b83 2393
786e8c11
YO
2394 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2395
2396This shows that when matching against the string 'hers' we will begin at state 1
2397read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2398then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2399is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2400single traverse. We store a mapping from accepting to state to which word was
2401matched, and then when we have multiple possibilities we try to complete the
b8fda935 2402rest of the regex in the order in which they occurred in the alternation.
786e8c11
YO
2403
2404The only prior NFA like behaviour that would be changed by the TRIE support is
2405the silent ignoring of duplicate alternations which are of the form:
2406
2407 / (DUPE|DUPE) X? (?{ ... }) Y /x
2408
4b714af6 2409Thus EVAL blocks following a trie may be called a different number of times with
786e8c11 2410and without the optimisation. With the optimisations dupes will be silently
486ec47a 2411ignored. This inconsistent behaviour of EVAL type nodes is well established as
786e8c11
YO
2412the following demonstrates:
2413
2414 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2415
2416which prints out 'word' three times, but
2417
2418 'words'=~/(word|word|word)(?{ print $1 })S/
2419
2420which doesnt print it out at all. This is due to other optimisations kicking in.
2421
2422Example of what happens on a structural level:
2423
486ec47a 2424The regexp /(ac|ad|ab)+/ will produce the following debug output:
786e8c11
YO
2425
2426 1: CURLYM[1] {1,32767}(18)
2427 5: BRANCH(8)
2428 6: EXACT <ac>(16)
2429 8: BRANCH(11)
2430 9: EXACT <ad>(16)
2431 11: BRANCH(14)
2432 12: EXACT <ab>(16)
2433 16: SUCCEED(0)
2434 17: NOTHING(18)
2435 18: END(0)
2436
2437This would be optimizable with startbranch=5, first=5, last=16, tail=16
2438and should turn into:
2439
2440 1: CURLYM[1] {1,32767}(18)
2441 5: TRIE(16)
2442 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2443 <ac>
2444 <ad>
2445 <ab>
2446 16: SUCCEED(0)
2447 17: NOTHING(18)
2448 18: END(0)
2449
2450Cases where tail != last would be like /(?foo|bar)baz/:
2451
2452 1: BRANCH(4)
2453 2: EXACT <foo>(8)
2454 4: BRANCH(7)
2455 5: EXACT <bar>(8)
2456 7: TAIL(8)
2457 8: EXACT <baz>(10)
2458 10: END(0)
2459
2460which would be optimizable with startbranch=1, first=1, last=7, tail=8
2461and would end up looking like:
2462
2463 1: TRIE(8)
2464 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2465 <foo>
2466 <bar>
2467 7: TAIL(8)
2468 8: EXACT <baz>(10)
2469 10: END(0)
2470
c80e42f3 2471 d = uvchr_to_utf8_flags(d, uv, 0);
786e8c11
YO
2472
2473is the recommended Unicode-aware way of saying
2474
2475 *(d++) = uv;
2476*/
2477
fab2782b 2478#define TRIE_STORE_REVCHAR(val) \
786e8c11 2479 STMT_START { \
73031816 2480 if (UTF) { \
668fcfea 2481 SV *zlopp = newSV(UTF8_MAXBYTES); \
88c9ea1e 2482 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
c80e42f3 2483 unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
73031816
NC
2484 SvCUR_set(zlopp, kapow - flrbbbbb); \
2485 SvPOK_on(zlopp); \
2486 SvUTF8_on(zlopp); \
2487 av_push(revcharmap, zlopp); \
2488 } else { \
fab2782b 2489 char ooooff = (char)val; \
73031816
NC
2490 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
2491 } \
2492 } STMT_END
786e8c11 2493
914a25d5
KW
2494/* This gets the next character from the input, folding it if not already
2495 * folded. */
2496#define TRIE_READ_CHAR STMT_START { \
2497 wordlen++; \
2498 if ( UTF ) { \
2499 /* if it is UTF then it is either already folded, or does not need \
2500 * folding */ \
1c1d615a 2501 uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \
914a25d5
KW
2502 } \
2503 else if (folder == PL_fold_latin1) { \
7d006b13
KW
2504 /* This folder implies Unicode rules, which in the range expressible \
2505 * by not UTF is the lower case, with the two exceptions, one of \
2506 * which should have been taken care of before calling this */ \
2507 assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \
2508 uvc = toLOWER_L1(*uc); \
2509 if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \
2510 len = 1; \
914a25d5
KW
2511 } else { \
2512 /* raw data, will be folded later if needed */ \
2513 uvc = (U32)*uc; \
2514 len = 1; \
2515 } \
786e8c11
YO
2516} STMT_END
2517
2518
2519
2520#define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
2521 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
00195859 2522 U32 ging = TRIE_LIST_LEN( state ) * 2; \
f9003953 2523 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
00195859 2524 TRIE_LIST_LEN( state ) = ging; \
786e8c11
YO
2525 } \
2526 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
2527 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
2528 TRIE_LIST_CUR( state )++; \
2529} STMT_END
07be1b83 2530
786e8c11 2531#define TRIE_LIST_NEW(state) STMT_START { \
d09f14bf 2532 Newx( trie->states[ state ].trans.list, \
786e8c11
YO
2533 4, reg_trie_trans_le ); \
2534 TRIE_LIST_CUR( state ) = 1; \
2535 TRIE_LIST_LEN( state ) = 4; \
2536} STMT_END
07be1b83 2537
786e8c11
YO
2538#define TRIE_HANDLE_WORD(state) STMT_START { \
2539 U16 dupe= trie->states[ state ].wordnum; \
2540 regnode * const noper_next = regnext( noper ); \
2541 \
786e8c11
YO
2542 DEBUG_r({ \
2543 /* store the word for dumping */ \
2544 SV* tmp; \
2545 if (OP(noper) != NOTHING) \
740cce10 2546 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
786e8c11 2547 else \
740cce10 2548 tmp = newSVpvn_utf8( "", 0, UTF ); \
2b8b4781 2549 av_push( trie_words, tmp ); \
786e8c11
YO
2550 }); \
2551 \
2552 curword++; \
2e64971a
DM
2553 trie->wordinfo[curword].prev = 0; \
2554 trie->wordinfo[curword].len = wordlen; \
2555 trie->wordinfo[curword].accept = state; \
786e8c11
YO
2556 \
2557 if ( noper_next < tail ) { \
2558 if (!trie->jump) \
538e84ed
KW
2559 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2560 sizeof(U16) ); \
7f69552c 2561 trie->jump[curword] = (U16)(noper_next - convert); \
786e8c11
YO
2562 if (!jumper) \
2563 jumper = noper_next; \
2564 if (!nextbranch) \
2565 nextbranch= regnext(cur); \
2566 } \
2567 \
2568 if ( dupe ) { \
2e64971a
DM
2569 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
2570 /* chain, so that when the bits of chain are later */\
2571 /* linked together, the dups appear in the chain */\
2572 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2573 trie->wordinfo[dupe].prev = curword; \
786e8c11
YO
2574 } else { \
2575 /* we haven't inserted this word yet. */ \
2576 trie->states[ state ].wordnum = curword; \
2577 } \
2578} STMT_END
07be1b83 2579
3dab1dad 2580
786e8c11
YO
2581#define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
2582 ( ( base + charid >= ucharcount \
2583 && base + charid < ubound \
2584 && state == trie->trans[ base - ucharcount + charid ].check \
2585 && trie->trans[ base - ucharcount + charid ].next ) \
2586 ? trie->trans[ base - ucharcount + charid ].next \
2587 : ( state==1 ? special : 0 ) \
2588 )
3dab1dad 2589
8bcafbf4
YO
2590#define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder) \
2591STMT_START { \
2592 TRIE_BITMAP_SET(trie, uvc); \
2593 /* store the folded codepoint */ \
2594 if ( folder ) \
2595 TRIE_BITMAP_SET(trie, folder[(U8) uvc ]); \
2596 \
2597 if ( !UTF ) { \
2598 /* store first byte of utf8 representation of */ \
2599 /* variant codepoints */ \
2600 if (! UVCHR_IS_INVARIANT(uvc)) { \
2601 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc)); \
2602 } \
2603 } \
2604} STMT_END
786e8c11
YO
2605#define MADE_TRIE 1
2606#define MADE_JUMP_TRIE 2
2607#define MADE_EXACT_TRIE 4
3dab1dad 2608
a3621e74 2609STATIC I32
538e84ed
KW
2610S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2611 regnode *first, regnode *last, regnode *tail,
2612 U32 word_count, U32 flags, U32 depth)
a3621e74
YO
2613{
2614 /* first pass, loop through and scan words */
2615 reg_trie_data *trie;
55eed653 2616 HV *widecharmap = NULL;
2b8b4781 2617 AV *revcharmap = newAV();
a3621e74 2618 regnode *cur;
a3621e74
YO
2619 STRLEN len = 0;
2620 UV uvc = 0;
2621 U16 curword = 0;
2622 U32 next_alloc = 0;
786e8c11
YO
2623 regnode *jumper = NULL;
2624 regnode *nextbranch = NULL;
7f69552c 2625 regnode *convert = NULL;
2e64971a 2626 U32 *prev_states; /* temp array mapping each state to previous one */
a3621e74 2627 /* we just use folder as a flag in utf8 */
1e696034 2628 const U8 * folder = NULL;
a3621e74 2629
3a611511
YO
2630 /* in the below add_data call we are storing either 'tu' or 'tuaa'
2631 * which stands for one trie structure, one hash, optionally followed
2632 * by two arrays */
2b8b4781 2633#ifdef DEBUGGING
3a611511 2634 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
2b8b4781
NC
2635 AV *trie_words = NULL;
2636 /* along with revcharmap, this only used during construction but both are
2637 * useful during debugging so we store them in the struct when debugging.
8e11feef 2638 */
2b8b4781 2639#else
cf78de0b 2640 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
3dab1dad 2641 STRLEN trie_charcount=0;
3dab1dad 2642#endif
2b8b4781 2643 SV *re_trie_maxbuff;
a3621e74 2644 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
2645
2646 PERL_ARGS_ASSERT_MAKE_TRIE;
72f13be8
YO
2647#ifndef DEBUGGING
2648 PERL_UNUSED_ARG(depth);
2649#endif
a3621e74 2650
1e696034 2651 switch (flags) {
f6b4b99d 2652 case EXACT: case EXACT_ONLY8: case EXACTL: break;
89829bb5 2653 case EXACTFAA:
fab2782b 2654 case EXACTFU_SS:
a4525e78
KW
2655 case EXACTFU:
2656 case EXACTFLU8: folder = PL_fold_latin1; break;
1e696034 2657 case EXACTF: folder = PL_fold; break;
fab2782b 2658 default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
1e696034
KW
2659 }
2660
c944940b 2661 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
a3621e74 2662 trie->refcount = 1;
3dab1dad 2663 trie->startstate = 1;
786e8c11 2664 trie->wordcount = word_count;
f8fc2ecf 2665 RExC_rxi->data->data[ data_slot ] = (void*)trie;
c944940b 2666 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
f6b4b99d 2667 if (flags == EXACT || flags == EXACT_ONLY8 || flags == EXACTL)
c944940b 2668 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2e64971a
DM
2669 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2670 trie->wordcount+1, sizeof(reg_trie_wordinfo));
2671
a3621e74 2672 DEBUG_r({
2b8b4781 2673 trie_words = newAV();
a3621e74 2674 });
a3621e74 2675
0111c4fd 2676 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
316ebaf2 2677 assert(re_trie_maxbuff);
a3621e74 2678 if (!SvIOK(re_trie_maxbuff)) {
0111c4fd 2679 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
a3621e74 2680 }
df826430 2681 DEBUG_TRIE_COMPILE_r({
6ad9a8ab 2682 Perl_re_indentf( aTHX_
cb41e5d6
YO
2683 "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2684 depth+1,
88f063b4 2685 REG_NODE_NUM(startbranch), REG_NODE_NUM(first),
538e84ed 2686 REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
3dab1dad 2687 });
538e84ed 2688
7f69552c
YO
2689 /* Find the node we are going to overwrite */
2690 if ( first == startbranch && OP( last ) != BRANCH ) {
2691 /* whole branch chain */
2692 convert = first;
2693 } else {
2694 /* branch sub-chain */
2695 convert = NEXTOPER( first );
2696 }
538e84ed 2697
a3621e74
YO
2698 /* -- First loop and Setup --
2699
2700 We first traverse the branches and scan each word to determine if it
2701 contains widechars, and how many unique chars there are, this is
2702 important as we have to build a table with at least as many columns as we
2703 have unique chars.
2704
2705 We use an array of integers to represent the character codes 0..255
538e84ed
KW
2706 (trie->charmap) and we use a an HV* to store Unicode characters. We use
2707 the native representation of the character value as the key and IV's for
2708 the coded index.
a3621e74
YO
2709
2710 *TODO* If we keep track of how many times each character is used we can
2711 remap the columns so that the table compression later on is more
3b753521 2712 efficient in terms of memory by ensuring the most common value is in the
a3621e74
YO
2713 middle and the least common are on the outside. IMO this would be better
2714 than a most to least common mapping as theres a decent chance the most
2715 common letter will share a node with the least common, meaning the node
486ec47a 2716 will not be compressible. With a middle is most common approach the worst
a3621e74
YO
2717 case is when we have the least common nodes twice.
2718
2719 */
2720
a3621e74 2721 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
df826430 2722 regnode *noper = NEXTOPER( cur );
944e05e3
YO
2723 const U8 *uc;
2724 const U8 *e;
bc031a7d 2725 int foldlen = 0;
07be1b83 2726 U32 wordlen = 0; /* required init */
bc031a7d
KW
2727 STRLEN minchars = 0;
2728 STRLEN maxchars = 0;
538e84ed
KW
2729 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2730 bitmap?*/
a3621e74 2731
3dab1dad 2732 if (OP(noper) == NOTHING) {
20ed8c88
YO
2733 /* skip past a NOTHING at the start of an alternation
2734 * eg, /(?:)a|(?:b)/ should be the same as /a|b/
2735 */
df826430 2736 regnode *noper_next= regnext(noper);
944e05e3
YO
2737 if (noper_next < tail)
2738 noper= noper_next;
2739 }
2740
f6b4b99d
KW
2741 if ( noper < tail
2742 && ( OP(noper) == flags
2743 || (flags == EXACT && OP(noper) == EXACT_ONLY8)
a9f8c7ac
KW
2744 || (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8
2745 || OP(noper) == EXACTFU_SS))) )
f6b4b99d 2746 {
944e05e3
YO
2747 uc= (U8*)STRING(noper);
2748 e= uc + STR_LEN(noper);
2749 } else {
2750 trie->minlen= 0;
2751 continue;
3dab1dad 2752 }
df826430 2753
944e05e3 2754
fab2782b 2755 if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
02daf0ab
YO
2756 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2757 regardless of encoding */
fab2782b
YO
2758 if (OP( noper ) == EXACTFU_SS) {
2759 /* false positives are ok, so just set this */
0dc4a61d 2760 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
fab2782b
YO
2761 }
2762 }
dca5fc4c 2763
bc031a7d
KW
2764 for ( ; uc < e ; uc += len ) { /* Look at each char in the current
2765 branch */
3dab1dad 2766 TRIE_CHARCOUNT(trie)++;
a3621e74 2767 TRIE_READ_CHAR;
645de4ce 2768
bc031a7d
KW
2769 /* TRIE_READ_CHAR returns the current character, or its fold if /i
2770 * is in effect. Under /i, this character can match itself, or
2771 * anything that folds to it. If not under /i, it can match just
2772 * itself. Most folds are 1-1, for example k, K, and KELVIN SIGN
2773 * all fold to k, and all are single characters. But some folds
2774 * expand to more than one character, so for example LATIN SMALL
2775 * LIGATURE FFI folds to the three character sequence 'ffi'. If
2776 * the string beginning at 'uc' is 'ffi', it could be matched by
2777 * three characters, or just by the one ligature character. (It
2778 * could also be matched by two characters: LATIN SMALL LIGATURE FF
2779 * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2780 * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2781 * match.) The trie needs to know the minimum and maximum number
2782 * of characters that could match so that it can use size alone to
2783 * quickly reject many match attempts. The max is simple: it is
2784 * the number of folded characters in this branch (since a fold is
2785 * never shorter than what folds to it. */
2786
2787 maxchars++;
2788
2789 /* And the min is equal to the max if not under /i (indicated by
2790 * 'folder' being NULL), or there are no multi-character folds. If
2791 * there is a multi-character fold, the min is incremented just
2792 * once, for the character that folds to the sequence. Each
2793 * character in the sequence needs to be added to the list below of
2794 * characters in the trie, but we count only the first towards the
2795 * min number of characters needed. This is done through the
2796 * variable 'foldlen', which is returned by the macros that look
2797 * for these sequences as the number of bytes the sequence
2798 * occupies. Each time through the loop, we decrement 'foldlen' by
2799 * how many bytes the current char occupies. Only when it reaches
2800 * 0 do we increment 'minchars' or look for another multi-character
2801 * sequence. */
2802 if (folder == NULL) {
2803 minchars++;
2804 }
2805 else if (foldlen > 0) {
2806 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
645de4ce
KW
2807 }
2808 else {
bc031a7d
KW
2809 minchars++;
2810
2811 /* See if *uc is the beginning of a multi-character fold. If
2812 * so, we decrement the length remaining to look at, to account
2813 * for the current character this iteration. (We can use 'uc'
2814 * instead of the fold returned by TRIE_READ_CHAR because for
2815 * non-UTF, the latin1_safe macro is smart enough to account
2816 * for all the unfolded characters, and because for UTF, the
2817 * string will already have been folded earlier in the
2818 * compilation process */
2819 if (UTF) {
2820 if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2821 foldlen -= UTF8SKIP(uc);
645de4ce
KW
2822 }
2823 }
bc031a7d
KW
2824 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2825 foldlen--;
2826 }
645de4ce 2827 }
bc031a7d
KW
2828
2829 /* The current character (and any potential folds) should be added
2830 * to the possible matching characters for this position in this
2831 * branch */
a3621e74 2832 if ( uvc < 256 ) {
fab2782b
YO
2833 if ( folder ) {
2834 U8 folded= folder[ (U8) uvc ];
2835 if ( !trie->charmap[ folded ] ) {
2836 trie->charmap[ folded ]=( ++trie->uniquecharcount );
2837 TRIE_STORE_REVCHAR( folded );
2838 }
2839 }
a3621e74
YO
2840 if ( !trie->charmap[ uvc ] ) {
2841 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
fab2782b 2842 TRIE_STORE_REVCHAR( uvc );
a3621e74 2843 }
02daf0ab 2844 if ( set_bit ) {
62012aee
KW
2845 /* store the codepoint in the bitmap, and its folded
2846 * equivalent. */
8bcafbf4 2847 TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
02daf0ab
YO
2848 set_bit = 0; /* We've done our bit :-) */
2849 }
a3621e74 2850 } else {
bc031a7d
KW
2851
2852 /* XXX We could come up with the list of code points that fold
2853 * to this using PL_utf8_foldclosures, except not for
2854 * multi-char folds, as there may be multiple combinations
2855 * there that could work, which needs to wait until runtime to
2856 * resolve (The comment about LIGATURE FFI above is such an
2857 * example */
2858
a3621e74 2859 SV** svpp;
55eed653
NC
2860 if ( !widecharmap )
2861 widecharmap = newHV();
a3621e74 2862
55eed653 2863 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
a3621e74
YO
2864
2865 if ( !svpp )
147e3846 2866 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
a3621e74
YO
2867
2868 if ( !SvTRUE( *svpp ) ) {
2869 sv_setiv( *svpp, ++trie->uniquecharcount );
fab2782b 2870 TRIE_STORE_REVCHAR(uvc);
a3621e74
YO
2871 }
2872 }
bc031a7d
KW
2873 } /* end loop through characters in this branch of the trie */
2874
2875 /* We take the min and max for this branch and combine to find the min
2876 * and max for all branches processed so far */
3dab1dad 2877 if( cur == first ) {
bc031a7d
KW
2878 trie->minlen = minchars;
2879 trie->maxlen = maxchars;
2880 } else if (minchars < trie->minlen) {
2881 trie->minlen = minchars;
2882 } else if (maxchars > trie->maxlen) {
2883 trie->maxlen = maxchars;
fab2782b 2884 }
a3621e74
YO
2885 } /* end first pass */
2886 DEBUG_TRIE_COMPILE_r(
6ad9a8ab 2887 Perl_re_indentf( aTHX_
cb41e5d6
YO
2888 "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2889 depth+1,
55eed653 2890 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
be8e71aa
YO
2891 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2892 (int)trie->minlen, (int)trie->maxlen )
a3621e74 2893 );
a3621e74
YO
2894
2895 /*
2896 We now know what we are dealing with in terms of unique chars and
2897 string sizes so we can calculate how much memory a naive
0111c4fd
RGS
2898 representation using a flat table will take. If it's over a reasonable
2899 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
a3621e74
YO
2900 conservative but potentially much slower representation using an array
2901 of lists.
2902
2903 At the end we convert both representations into the same compressed
2904 form that will be used in regexec.c for matching with. The latter
2905 is a form that cannot be used to construct with but has memory
2906 properties similar to the list form and access properties similar
2907 to the table form making it both suitable for fast searches and
2908 small enough that its feasable to store for the duration of a program.
2909
2910 See the comment in the code where the compressed table is produced
2911 inplace from the flat tabe representation for an explanation of how
2912 the compression works.
2913
2914 */
2915
2916
2e64971a
DM
2917 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2918 prev_states[1] = 0;
2919
538e84ed
KW
2920 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2921 > SvIV(re_trie_maxbuff) )
2922 {
a3621e74
YO
2923 /*
2924 Second Pass -- Array Of Lists Representation
2925
2926 Each state will be represented by a list of charid:state records
2927 (reg_trie_trans_le) the first such element holds the CUR and LEN
2928 points of the allocated array. (See defines above).
2929
2930 We build the initial structure using the lists, and then convert
2931 it into the compressed table form which allows faster lookups
2932 (but cant be modified once converted).
a3621e74
YO
2933 */
2934
a3621e74
YO
2935 STRLEN transcount = 1;
2936
6ad9a8ab 2937 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using list compiler\n",
cb41e5d6 2938 depth+1));
686b73d4 2939
c944940b
JH
2940 trie->states = (reg_trie_state *)
2941 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2942 sizeof(reg_trie_state) );
a3621e74
YO
2943 TRIE_LIST_NEW(1);
2944 next_alloc = 2;
2945
2946 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2947
df826430 2948 regnode *noper = NEXTOPER( cur );
c445ea15
AL
2949 U32 state = 1; /* required init */
2950 U16 charid = 0; /* sanity init */
07be1b83 2951 U32 wordlen = 0; /* required init */
c445ea15 2952
df826430
YO
2953 if (OP(noper) == NOTHING) {
2954 regnode *noper_next= regnext(noper);
944e05e3
YO
2955 if (noper_next < tail)
2956 noper= noper_next;
df826430
YO
2957 }
2958
f6b4b99d
KW
2959 if ( noper < tail
2960 && ( OP(noper) == flags
2961 || (flags == EXACT && OP(noper) == EXACT_ONLY8)
a9f8c7ac
KW
2962 || (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8
2963 || OP(noper) == EXACTFU_SS))) )
f6b4b99d 2964 {
944e05e3
YO
2965 const U8 *uc= (U8*)STRING(noper);
2966 const U8 *e= uc + STR_LEN(noper);
2967
786e8c11 2968 for ( ; uc < e ; uc += len ) {
c445ea15 2969
786e8c11 2970 TRIE_READ_CHAR;
c445ea15 2971
786e8c11
YO
2972 if ( uvc < 256 ) {
2973 charid = trie->charmap[ uvc ];
c445ea15 2974 } else {
538e84ed
KW
2975 SV** const svpp = hv_fetch( widecharmap,
2976 (char*)&uvc,
2977 sizeof( UV ),
2978 0);
786e8c11
YO
2979 if ( !svpp ) {
2980 charid = 0;
2981 } else {
2982 charid=(U16)SvIV( *svpp );
2983 }
c445ea15 2984 }
538e84ed
KW
2985 /* charid is now 0 if we dont know the char read, or
2986 * nonzero if we do */
786e8c11 2987 if ( charid ) {
a3621e74 2988
786e8c11
YO
2989 U16 check;
2990 U32 newstate = 0;
a3621e74 2991
786e8c11
YO
2992 charid--;
2993 if ( !trie->states[ state ].trans.list ) {
2994 TRIE_LIST_NEW( state );
c445ea15 2995 }
538e84ed
KW
2996 for ( check = 1;
2997 check <= TRIE_LIST_USED( state );
2998 check++ )
2999 {
3000 if ( TRIE_LIST_ITEM( state, check ).forid
3001 == charid )
3002 {
786e8c11
YO
3003 newstate = TRIE_LIST_ITEM( state, check ).newstate;
3004 break;
3005 }
3006 }
3007 if ( ! newstate ) {
3008 newstate = next_alloc++;
2e64971a 3009 prev_states[newstate] = state;
786e8c11
YO
3010 TRIE_LIST_PUSH( state, charid, newstate );
3011 transcount++;
3012 }
3013 state = newstate;
3014 } else {
147e3846 3015 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
c445ea15 3016 }
a28509cc 3017 }
c445ea15 3018 }
3dab1dad 3019 TRIE_HANDLE_WORD(state);
a3621e74
YO
3020
3021 } /* end second pass */
3022
1e2e3d02 3023 /* next alloc is the NEXT state to be allocated */
538e84ed 3024 trie->statecount = next_alloc;
c944940b
JH
3025 trie->states = (reg_trie_state *)
3026 PerlMemShared_realloc( trie->states,
3027 next_alloc
3028 * sizeof(reg_trie_state) );
a3621e74 3029
3dab1dad 3030 /* and now dump it out before we compress it */
2b8b4781
NC
3031 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
3032 revcharmap, next_alloc,
3033 depth+1)
1e2e3d02 3034 );
a3621e74 3035
c944940b
JH
3036 trie->trans = (reg_trie_trans *)
3037 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
a3621e74
YO
3038 {
3039 U32 state;
a3621e74
YO
3040 U32 tp = 0;
3041 U32 zp = 0;
3042
3043
3044 for( state=1 ; state < next_alloc ; state ++ ) {
3045 U32 base=0;
3046
3047 /*
3048 DEBUG_TRIE_COMPILE_MORE_r(
6ad9a8ab 3049 Perl_re_printf( aTHX_ "tp: %d zp: %d ",tp,zp)
a3621e74
YO
3050 );
3051 */
3052
3053 if (trie->states[state].trans.list) {
3054 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
3055 U16 maxid=minid;
a28509cc 3056 U16 idx;
a3621e74
YO
3057
3058 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
c445ea15
AL
3059 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
3060 if ( forid < minid ) {
3061 minid=forid;
3062 } else if ( forid > maxid ) {
3063 maxid=forid;
3064 }
a3621e74
YO
3065 }
3066 if ( transcount < tp + maxid - minid + 1) {
3067 transcount *= 2;
c944940b
JH
3068 trie->trans = (reg_trie_trans *)
3069 PerlMemShared_realloc( trie->trans,
446bd890
NC
3070 transcount
3071 * sizeof(reg_trie_trans) );
538e84ed
KW
3072 Zero( trie->trans + (transcount / 2),
3073 transcount / 2,
3074 reg_trie_trans );
a3621e74
YO
3075 }
3076 base = trie->uniquecharcount + tp - minid;
3077 if ( maxid == minid ) {
3078 U32 set = 0;
3079 for ( ; zp < tp ; zp++ ) {
3080 if ( ! trie->trans[ zp ].next ) {
3081 base = trie->uniquecharcount + zp - minid;
538e84ed
KW
3082 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
3083 1).newstate;
a3621e74
YO
3084 trie->trans[ zp ].check = state;
3085 set = 1;
3086 break;
3087 }
3088 }
3089 if ( !set ) {
538e84ed
KW
3090 trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
3091 1).newstate;
a3621e74
YO
3092 trie->trans[ tp ].check = state;
3093 tp++;
3094 zp = tp;
3095 }
3096 } else {
3097 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
538e84ed
KW
3098 const U32 tid = base
3099 - trie->uniquecharcount
3100 + TRIE_LIST_ITEM( state, idx ).forid;
3101 trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
3102 idx ).newstate;
a3621e74
YO
3103 trie->trans[ tid ].check = state;
3104 }
3105 tp += ( maxid - minid + 1 );
3106 }
3107 Safefree(trie->states[ state ].trans.list);
3108 }
3109 /*
3110 DEBUG_TRIE_COMPILE_MORE_r(
6ad9a8ab 3111 Perl_re_printf( aTHX_ " base: %d\n",base);
a3621e74
YO
3112 );
3113 */
3114 trie->states[ state ].trans.base=base;
3115 }
cc601c31 3116 trie->lasttrans = tp + 1;
a3621e74
YO
3117 }
3118 } else {
3119 /*
3120 Second Pass -- Flat Table Representation.
3121
b423522f
KW
3122 we dont use the 0 slot of either trans[] or states[] so we add 1 to
3123 each. We know that we will need Charcount+1 trans at most to store
3124 the data (one row per char at worst case) So we preallocate both
3125 structures assuming worst case.
a3621e74
YO
3126
3127 We then construct the trie using only the .next slots of the entry
3128 structs.
3129
b423522f
KW
3130 We use the .check field of the first entry of the node temporarily
3131 to make compression both faster and easier by keeping track of how
3132 many non zero fields are in the node.
a3621e74
YO
3133
3134 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
3135 transition.
3136
b423522f
KW
3137 There are two terms at use here: state as a TRIE_NODEIDX() which is
3138 a number representing the first entry of the node, and state as a
3139 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
3140 and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
3141 if there are 2 entrys per node. eg:
a3621e74
YO
3142
3143 A B A B
3144 1. 2 4 1. 3 7
3145 2. 0 3 3. 0 5
3146 3. 0 0 5. 0 0
3147 4. 0 0 7. 0 0
3148
b423522f
KW
3149 The table is internally in the right hand, idx form. However as we
3150 also have to deal with the states array which is indexed by nodenum
3151 we have to use TRIE_NODENUM() to convert.
a3621e74
YO
3152
3153 */
6ad9a8ab 3154 DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using table compiler\n",
cb41e5d6 3155 depth+1));
3dab1dad 3156
c944940b
JH
3157 trie->trans = (reg_trie_trans *)
3158 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
3159 * trie->uniquecharcount + 1,
3160 sizeof(reg_trie_trans) );
3161 trie->states = (reg_trie_state *)
3162 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3163 sizeof(reg_trie_state) );
a3621e74
YO
3164 next_alloc = trie->uniquecharcount + 1;
3165
3dab1dad 3166
a3621e74
YO
3167 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3168
df826430 3169 regnode *noper = NEXTOPER( cur );
a3621e74
YO
3170
3171 U32 state = 1; /* required init */
3172
3173 U16 charid = 0; /* sanity init */
3174 U32 accept_state = 0; /* sanity init */
a3621e74 3175
07be1b83 3176 U32 wordlen = 0; /* required init */
a3621e74 3177
df826430
YO
3178 if (OP(noper) == NOTHING) {
3179 regnode *noper_next= regnext(noper);
944e05e3
YO
3180 if (noper_next < tail)
3181 noper= noper_next;
df826430 3182 }
fab2782b 3183
f6b4b99d
KW
3184 if ( noper < tail
3185 && ( OP(noper) == flags
3186 || (flags == EXACT && OP(noper) == EXACT_ONLY8)
a9f8c7ac
KW
3187 || (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8
3188 || OP(noper) == EXACTFU_SS))) )
f6b4b99d 3189 {
944e05e3
YO
3190 const U8 *uc= (U8*)STRING(noper);
3191 const U8 *e= uc + STR_LEN(noper);
3192
786e8c11 3193 for ( ; uc < e ; uc += len ) {
a3621e74 3194
786e8c11 3195 TRIE_READ_CHAR;
a3621e74 3196
786e8c11
YO
3197 if ( uvc < 256 ) {
3198 charid = trie->charmap[ uvc ];
3199 } else {
538e84ed
KW
3200 SV* const * const svpp = hv_fetch( widecharmap,
3201 (char*)&uvc,
3202 sizeof( UV ),
3203 0);
786e8c11 3204 charid = svpp ? (U16)SvIV(*svpp) : 0;
a3621e74 3205 }
786e8c11
YO
3206 if ( charid ) {
3207 charid--;
3208 if ( !trie->trans[ state + charid ].next ) {
3209 trie->trans[ state + charid ].next = next_alloc;
3210 trie->trans[ state ].check++;
2e64971a
DM
3211 prev_states[TRIE_NODENUM(next_alloc)]
3212 = TRIE_NODENUM(state);
786e8c11
YO
3213 next_alloc += trie->uniquecharcount;
3214 }
3215 state = trie->trans[ state + charid ].next;
3216 } else {
147e3846 3217 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
786e8c11 3218 }
538e84ed
KW
3219 /* charid is now 0 if we dont know the char read, or
3220 * nonzero if we do */
a3621e74 3221 }
a3621e74 3222 }
3dab1dad
YO
3223 accept_state = TRIE_NODENUM( state );
3224 TRIE_HANDLE_WORD(accept_state);
a3621e74
YO
3225
3226 } /* end second pass */
3227
3dab1dad 3228 /* and now dump it out before we compress it */
2b8b4781
NC
3229 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3230 revcharmap,
3231 next_alloc, depth+1));
a3621e74 3232
a3621e74
YO
3233 {
3234 /*
3235 * Inplace compress the table.*
3236
3237 For sparse data sets the table constructed by the trie algorithm will
3238 be mostly 0/FAIL transitions or to put it another way mostly empty.
3239 (Note that leaf nodes will not contain any transitions.)
3240
3241 This algorithm compresses the tables by eliminating most such
3242 transitions, at the cost of a modest bit of extra work during lookup:
3243
3244 - Each states[] entry contains a .base field which indicates the
3245 index in the state[] array wheres its transition data is stored.
3246
3b753521 3247 - If .base is 0 there are no valid transitions from that node.
a3621e74
YO
3248
3249 - If .base is nonzero then charid is added to it to find an entry in
3250 the trans array.
3251
3252 -If trans[states[state].base+charid].check!=state then the
3253 transition is taken to be a 0/Fail transition. Thus if there are fail
3254 transitions at the front of the node then the .base offset will point
3255 somewhere inside the previous nodes data (or maybe even into a node
3256 even earlier), but the .check field determines if the transition is
3257 valid.
3258
786e8c11 3259 XXX - wrong maybe?
a3621e74 3260 The following process inplace converts the table to the compressed
3b753521 3261 table: We first do not compress the root node 1,and mark all its
a3621e74 3262 .check pointers as 1 and set its .base pointer as 1 as well. This
3b753521
FN
3263 allows us to do a DFA construction from the compressed table later,
3264 and ensures that any .base pointers we calculate later are greater
3265 than 0.
a3621e74
YO
3266
3267 - We set 'pos' to indicate the first entry of the second node.
3268
3269 - We then iterate over the columns of the node, finding the first and
3270 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3271 and set the .check pointers accordingly, and advance pos
3272 appropriately and repreat for the next node. Note that when we copy
3273 the next pointers we have to convert them from the original
3274 NODEIDX form to NODENUM form as the former is not valid post
3275 compression.
3276
3277 - If a node has no transitions used we mark its base as 0 and do not
3278 advance the pos pointer.
3279
3280 - If a node only has one transition we use a second pointer into the
3281 structure to fill in allocated fail transitions from other states.
3282 This pointer is independent of the main pointer and scans forward
3283 looking for null transitions that are allocated to a state. When it
3284 finds one it writes the single transition into the "hole". If the
786e8c11 3285 pointer doesnt find one the single transition is appended as normal.
a3621e74
YO
3286
3287 - Once compressed we can Renew/realloc the structures to release the
3288 excess space.
3289
3290 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3291 specifically Fig 3.47 and the associated pseudocode.
3292
3293 demq
3294 */
a3b680e6 3295 const U32 laststate = TRIE_NODENUM( next_alloc );
a28509cc 3296 U32 state, charid;
a3621e74 3297 U32 pos = 0, zp=0;
1e2e3d02 3298 trie->statecount = laststate;
a3621e74
YO
3299
3300 for ( state = 1 ; state < laststate ; state++ ) {
3301 U8 flag = 0;
a28509cc
AL
3302 const U32 stateidx = TRIE_NODEIDX( state );
3303 const U32 o_used = trie->trans[ stateidx ].check;
3304 U32 used = trie->trans[ stateidx ].check;
a3621e74
YO
3305 trie->trans[ stateidx ].check = 0;
3306
538e84ed
KW
3307 for ( charid = 0;
3308 used && charid < trie->uniquecharcount;
3309 charid++ )
3310 {
a3621e74
YO
3311 if ( flag || trie->trans[ stateidx + charid ].next ) {
3312 if ( trie->trans[ stateidx + charid ].next ) {
3313 if (o_used == 1) {
3314 for ( ; zp < pos ; zp++ ) {
3315 if ( ! trie->trans[ zp ].next ) {
3316 break;
3317 }
3318 }
538e84ed
KW
3319 trie->states[ state ].trans.base
3320 = zp
3321 + trie->uniquecharcount
3322 - charid ;
3323 trie->trans[ zp ].next
3324 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3325 + charid ].next );
a3621e74
YO
3326 trie->trans[ zp ].check = state;
3327 if ( ++zp > pos ) pos = zp;
3328 break;
3329 }
3330 used--;
3331 }
3332 if ( !flag ) {
3333 flag = 1;
538e84ed
KW
3334 trie->states[ state ].trans.base
3335 = pos + trie->uniquecharcount - charid ;
a3621e74 3336 }
538e84ed
KW
3337 trie->trans[ pos ].next
3338 = SAFE_TRIE_NODENUM(
3339 trie->trans[ stateidx + charid ].next );
a3621e74
YO
3340 trie->trans[ pos ].check = state;
3341 pos++;
3342 }
3343 }
3344 }
cc601c31 3345 trie->lasttrans = pos + 1;
c944940b
JH
3346 trie->states = (reg_trie_state *)
3347 PerlMemShared_realloc( trie->states, laststate
3348 * sizeof(reg_trie_state) );
a3621e74 3349 DEBUG_TRIE_COMPILE_MORE_r(
147e3846 3350 Perl_re_indentf( aTHX_ "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
cb41e5d6 3351 depth+1,
538e84ed
KW
3352 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3353 + 1 ),
3354 (IV)next_alloc,
3355 (IV)pos,
3356 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
a3621e74
YO
3357 );
3358
3359 } /* end table compress */
3360 }
1e2e3d02 3361 DEBUG_TRIE_COMPILE_MORE_r(
147e3846 3362 Perl_re_indentf( aTHX_ "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
cb41e5d6 3363 depth+1,
1e2e3d02
YO
3364 (UV)trie->statecount,
3365 (UV)trie->lasttrans)
3366 );
cc601c31 3367 /* resize the trans array to remove unused space */
c944940b
JH
3368 trie->trans = (reg_trie_trans *)
3369 PerlMemShared_realloc( trie->trans, trie->lasttrans
3370 * sizeof(reg_trie_trans) );
a3621e74 3371
538e84ed 3372 { /* Modify the program and insert the new TRIE node */
3dab1dad
YO
3373 U8 nodetype =(U8)(flags & 0xFF);
3374 char *str=NULL;
538e84ed 3375
07be1b83 3376#ifdef DEBUGGING
e62cc96a 3377 regnode *optimize = NULL;
7122b237
YO
3378#ifdef RE_TRACK_PATTERN_OFFSETS
3379
b57a0404
JH
3380 U32 mjd_offset = 0;
3381 U32 mjd_nodelen = 0;
7122b237
YO
3382#endif /* RE_TRACK_PATTERN_OFFSETS */
3383#endif /* DEBUGGING */
a3621e74 3384 /*
3dab1dad
YO
3385 This means we convert either the first branch or the first Exact,
3386 depending on whether the thing following (in 'last') is a branch
3387 or not and whther first is the startbranch (ie is it a sub part of
3388 the alternation or is it the whole thing.)
3b753521 3389 Assuming its a sub part we convert the EXACT otherwise we convert
3dab1dad 3390 the whole branch sequence, including the first.
a3621e74 3391 */
3dab1dad 3392 /* Find the node we are going to overwrite */
7f69552c 3393 if ( first != startbranch || OP( last ) == BRANCH ) {
07be1b83 3394 /* branch sub-chain */
3dab1dad 3395 NEXT_OFF( first ) = (U16)(last - first);
7122b237 3396#ifdef RE_TRACK_PATTERN_OFFSETS
07be1b83
YO
3397 DEBUG_r({
3398 mjd_offset= Node_Offset((convert));
3399 mjd_nodelen= Node_Length((convert));
3400 });
7122b237 3401#endif
7f69552c 3402 /* whole branch chain */
7122b237
YO
3403 }
3404#ifdef RE_TRACK_PATTERN_OFFSETS
3405 else {
7f69552c
YO
3406 DEBUG_r({
3407 const regnode *nop = NEXTOPER( convert );
3408 mjd_offset= Node_Offset((nop));
3409 mjd_nodelen= Node_Length((nop));
3410 });
07be1b83
YO
3411 }
3412 DEBUG_OPTIMISE_r(
147e3846 3413 Perl_re_indentf( aTHX_ "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
cb41e5d6 3414 depth+1,
786e8c11 3415 (UV)mjd_offset, (UV)mjd_nodelen)
07be1b83 3416 );
7122b237 3417#endif
538e84ed 3418 /* But first we check to see if there is a common prefix we can
3dab1dad
YO
3419 split out as an EXACT and put in front of the TRIE node. */
3420 trie->startstate= 1;
55eed653 3421 if ( trie->bitmap && !widecharmap && !trie->jump ) {
5ee57374
YO
3422 /* we want to find the first state that has more than
3423 * one transition, if that state is not the first state
3424 * then we have a common prefix which we can remove.
3425 */
3dab1dad 3426 U32 state;
1e2e3d02 3427 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
a3621e74 3428 U32 ofs = 0;
ee0dfd0b
YO
3429 I32 first_ofs = -1; /* keeps track of the ofs of the first
3430 transition, -1 means none */
8e11feef
RGS