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