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