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