This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Add regex nodes for locale
[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 1046
2f306ab9
KW
1047 /* If any portion of the regex is to operate under locale rules that aren't
1048 * fully known at compile time, initialization includes it. The reason
1049 * this isn't done for all regexes is that the optimizer was written under
1050 * the assumption that locale was all-or-nothing. Given the complexity and
1051 * lack of documentation in the optimizer, and that there are inadequate
1052 * test cases for locale, many parts of it may not work properly, it is
1053 * safest to avoid locale unless necessary. */
cdd87c1d
KW
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
a4525e78 1882 flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
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) {
a4525e78 2146 case EXACT: case EXACTL: break;
2f7f8cb1 2147 case EXACTFA:
fab2782b 2148 case EXACTFU_SS:
a4525e78
KW
2149 case EXACTFU:
2150 case EXACTFLU8: folder = PL_fold_latin1; break;
1e696034 2151 case EXACTF: folder = PL_fold; break;
fab2782b 2152 default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
1e696034
KW
2153 }
2154
c944940b 2155 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
a3621e74 2156 trie->refcount = 1;
3dab1dad 2157 trie->startstate = 1;
786e8c11 2158 trie->wordcount = word_count;
f8fc2ecf 2159 RExC_rxi->data->data[ data_slot ] = (void*)trie;
c944940b 2160 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
a4525e78 2161 if (flags == EXACT || flags == EXACTL)
c944940b 2162 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2e64971a
DM
2163 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2164 trie->wordcount+1, sizeof(reg_trie_wordinfo));
2165
a3621e74 2166 DEBUG_r({
2b8b4781 2167 trie_words = newAV();
a3621e74 2168 });
a3621e74 2169
0111c4fd 2170 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
316ebaf2 2171 assert(re_trie_maxbuff);
a3621e74 2172 if (!SvIOK(re_trie_maxbuff)) {
0111c4fd 2173 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
a3621e74 2174 }
df826430 2175 DEBUG_TRIE_COMPILE_r({
538e84ed
KW
2176 PerlIO_printf( Perl_debug_log,
2177 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2178 (int)depth * 2 + 2, "",
2179 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
2180 REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
3dab1dad 2181 });
538e84ed 2182
7f69552c
YO
2183 /* Find the node we are going to overwrite */
2184 if ( first == startbranch && OP( last ) != BRANCH ) {
2185 /* whole branch chain */
2186 convert = first;
2187 } else {
2188 /* branch sub-chain */
2189 convert = NEXTOPER( first );
2190 }
538e84ed 2191
a3621e74
YO
2192 /* -- First loop and Setup --
2193
2194 We first traverse the branches and scan each word to determine if it
2195 contains widechars, and how many unique chars there are, this is
2196 important as we have to build a table with at least as many columns as we
2197 have unique chars.
2198
2199 We use an array of integers to represent the character codes 0..255
538e84ed
KW
2200 (trie->charmap) and we use a an HV* to store Unicode characters. We use
2201 the native representation of the character value as the key and IV's for
2202 the coded index.
a3621e74
YO
2203
2204 *TODO* If we keep track of how many times each character is used we can
2205 remap the columns so that the table compression later on is more
3b753521 2206 efficient in terms of memory by ensuring the most common value is in the
a3621e74
YO
2207 middle and the least common are on the outside. IMO this would be better
2208 than a most to least common mapping as theres a decent chance the most
2209 common letter will share a node with the least common, meaning the node
486ec47a 2210 will not be compressible. With a middle is most common approach the worst
a3621e74
YO
2211 case is when we have the least common nodes twice.
2212
2213 */
2214
a3621e74 2215 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
df826430 2216 regnode *noper = NEXTOPER( cur );
e1ec3a88 2217 const U8 *uc = (U8*)STRING( noper );
df826430 2218 const U8 *e = uc + STR_LEN( noper );
bc031a7d 2219 int foldlen = 0;
07be1b83 2220 U32 wordlen = 0; /* required init */
bc031a7d
KW
2221 STRLEN minchars = 0;
2222 STRLEN maxchars = 0;
538e84ed
KW
2223 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2224 bitmap?*/
a3621e74 2225
3dab1dad 2226 if (OP(noper) == NOTHING) {
df826430
YO
2227 regnode *noper_next= regnext(noper);
2228 if (noper_next != tail && OP(noper_next) == flags) {
2229 noper = noper_next;
2230 uc= (U8*)STRING(noper);
2231 e= uc + STR_LEN(noper);
2232 trie->minlen= STR_LEN(noper);
2233 } else {
2234 trie->minlen= 0;
2235 continue;
2236 }
3dab1dad 2237 }
df826430 2238
fab2782b 2239 if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
02daf0ab
YO
2240 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2241 regardless of encoding */
fab2782b
YO
2242 if (OP( noper ) == EXACTFU_SS) {
2243 /* false positives are ok, so just set this */
0dc4a61d 2244 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
fab2782b
YO
2245 }
2246 }
bc031a7d
KW
2247 for ( ; uc < e ; uc += len ) { /* Look at each char in the current
2248 branch */
3dab1dad 2249 TRIE_CHARCOUNT(trie)++;
a3621e74 2250 TRIE_READ_CHAR;
645de4ce 2251
bc031a7d
KW
2252 /* TRIE_READ_CHAR returns the current character, or its fold if /i
2253 * is in effect. Under /i, this character can match itself, or
2254 * anything that folds to it. If not under /i, it can match just
2255 * itself. Most folds are 1-1, for example k, K, and KELVIN SIGN
2256 * all fold to k, and all are single characters. But some folds
2257 * expand to more than one character, so for example LATIN SMALL
2258 * LIGATURE FFI folds to the three character sequence 'ffi'. If
2259 * the string beginning at 'uc' is 'ffi', it could be matched by
2260 * three characters, or just by the one ligature character. (It
2261 * could also be matched by two characters: LATIN SMALL LIGATURE FF
2262 * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2263 * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2264 * match.) The trie needs to know the minimum and maximum number
2265 * of characters that could match so that it can use size alone to
2266 * quickly reject many match attempts. The max is simple: it is
2267 * the number of folded characters in this branch (since a fold is
2268 * never shorter than what folds to it. */
2269
2270 maxchars++;
2271
2272 /* And the min is equal to the max if not under /i (indicated by
2273 * 'folder' being NULL), or there are no multi-character folds. If
2274 * there is a multi-character fold, the min is incremented just
2275 * once, for the character that folds to the sequence. Each
2276 * character in the sequence needs to be added to the list below of
2277 * characters in the trie, but we count only the first towards the
2278 * min number of characters needed. This is done through the
2279 * variable 'foldlen', which is returned by the macros that look
2280 * for these sequences as the number of bytes the sequence
2281 * occupies. Each time through the loop, we decrement 'foldlen' by
2282 * how many bytes the current char occupies. Only when it reaches
2283 * 0 do we increment 'minchars' or look for another multi-character
2284 * sequence. */
2285 if (folder == NULL) {
2286 minchars++;
2287 }
2288 else if (foldlen > 0) {
2289 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
645de4ce
KW
2290 }
2291 else {
bc031a7d
KW
2292 minchars++;
2293
2294 /* See if *uc is the beginning of a multi-character fold. If
2295 * so, we decrement the length remaining to look at, to account
2296 * for the current character this iteration. (We can use 'uc'
2297 * instead of the fold returned by TRIE_READ_CHAR because for
2298 * non-UTF, the latin1_safe macro is smart enough to account
2299 * for all the unfolded characters, and because for UTF, the
2300 * string will already have been folded earlier in the
2301 * compilation process */
2302 if (UTF) {
2303 if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2304 foldlen -= UTF8SKIP(uc);
645de4ce
KW
2305 }
2306 }
bc031a7d
KW
2307 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2308 foldlen--;
2309 }
645de4ce 2310 }
bc031a7d
KW
2311
2312 /* The current character (and any potential folds) should be added
2313 * to the possible matching characters for this position in this
2314 * branch */
a3621e74 2315 if ( uvc < 256 ) {
fab2782b
YO
2316 if ( folder ) {
2317 U8 folded= folder[ (U8) uvc ];
2318 if ( !trie->charmap[ folded ] ) {
2319 trie->charmap[ folded ]=( ++trie->uniquecharcount );
2320 TRIE_STORE_REVCHAR( folded );
2321 }
2322 }
a3621e74
YO
2323 if ( !trie->charmap[ uvc ] ) {
2324 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
fab2782b 2325 TRIE_STORE_REVCHAR( uvc );
a3621e74 2326 }
02daf0ab 2327 if ( set_bit ) {
62012aee
KW
2328 /* store the codepoint in the bitmap, and its folded
2329 * equivalent. */
fab2782b 2330 TRIE_BITMAP_SET(trie, uvc);
0921ee73
T
2331
2332 /* store the folded codepoint */
fab2782b 2333 if ( folder ) TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);
0921ee73
T
2334
2335 if ( !UTF ) {
2336 /* store first byte of utf8 representation of
acdf4139 2337 variant codepoints */
6f2d5cbc 2338 if (! UVCHR_IS_INVARIANT(uvc)) {
acdf4139 2339 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));
0921ee73
T
2340 }
2341 }
02daf0ab
YO
2342 set_bit = 0; /* We've done our bit :-) */
2343 }
a3621e74 2344 } else {
bc031a7d
KW
2345
2346 /* XXX We could come up with the list of code points that fold
2347 * to this using PL_utf8_foldclosures, except not for
2348 * multi-char folds, as there may be multiple combinations
2349 * there that could work, which needs to wait until runtime to
2350 * resolve (The comment about LIGATURE FFI above is such an
2351 * example */
2352
a3621e74 2353 SV** svpp;
55eed653
NC
2354 if ( !widecharmap )
2355 widecharmap = newHV();
a3621e74 2356
55eed653 2357 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
a3621e74
YO
2358
2359 if ( !svpp )
e4584336 2360 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
a3621e74
YO
2361
2362 if ( !SvTRUE( *svpp ) ) {
2363 sv_setiv( *svpp, ++trie->uniquecharcount );
fab2782b 2364 TRIE_STORE_REVCHAR(uvc);
a3621e74
YO
2365 }
2366 }
bc031a7d
KW
2367 } /* end loop through characters in this branch of the trie */
2368
2369 /* We take the min and max for this branch and combine to find the min
2370 * and max for all branches processed so far */
3dab1dad 2371 if( cur == first ) {
bc031a7d
KW
2372 trie->minlen = minchars;
2373 trie->maxlen = maxchars;
2374 } else if (minchars < trie->minlen) {
2375 trie->minlen = minchars;
2376 } else if (maxchars > trie->maxlen) {
2377 trie->maxlen = maxchars;
fab2782b 2378 }
a3621e74
YO
2379 } /* end first pass */
2380 DEBUG_TRIE_COMPILE_r(
538e84ed
KW
2381 PerlIO_printf( Perl_debug_log,
2382 "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
3dab1dad 2383 (int)depth * 2 + 2,"",
55eed653 2384 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
be8e71aa
YO
2385 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2386 (int)trie->minlen, (int)trie->maxlen )
a3621e74 2387 );
a3621e74
YO
2388
2389 /*
2390 We now know what we are dealing with in terms of unique chars and
2391 string sizes so we can calculate how much memory a naive
0111c4fd
RGS
2392 representation using a flat table will take. If it's over a reasonable
2393 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
a3621e74
YO
2394 conservative but potentially much slower representation using an array
2395 of lists.
2396
2397 At the end we convert both representations into the same compressed
2398 form that will be used in regexec.c for matching with. The latter
2399 is a form that cannot be used to construct with but has memory
2400 properties similar to the list form and access properties similar
2401 to the table form making it both suitable for fast searches and
2402 small enough that its feasable to store for the duration of a program.
2403
2404 See the comment in the code where the compressed table is produced
2405 inplace from the flat tabe representation for an explanation of how
2406 the compression works.
2407
2408 */
2409
2410
2e64971a
DM
2411 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2412 prev_states[1] = 0;
2413
538e84ed
KW
2414 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2415 > SvIV(re_trie_maxbuff) )
2416 {
a3621e74
YO
2417 /*
2418 Second Pass -- Array Of Lists Representation
2419
2420 Each state will be represented by a list of charid:state records
2421 (reg_trie_trans_le) the first such element holds the CUR and LEN
2422 points of the allocated array. (See defines above).
2423
2424 We build the initial structure using the lists, and then convert
2425 it into the compressed table form which allows faster lookups
2426 (but cant be modified once converted).
a3621e74
YO
2427 */
2428
a3621e74
YO
2429 STRLEN transcount = 1;
2430
538e84ed 2431 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1e2e3d02
YO
2432 "%*sCompiling trie using list compiler\n",
2433 (int)depth * 2 + 2, ""));
686b73d4 2434
c944940b
JH
2435 trie->states = (reg_trie_state *)
2436 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2437 sizeof(reg_trie_state) );
a3621e74
YO
2438 TRIE_LIST_NEW(1);
2439 next_alloc = 2;
2440
2441 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2442
df826430 2443 regnode *noper = NEXTOPER( cur );
c445ea15 2444 U8 *uc = (U8*)STRING( noper );
df826430 2445 const U8 *e = uc + STR_LEN( noper );
c445ea15
AL
2446 U32 state = 1; /* required init */
2447 U16 charid = 0; /* sanity init */
07be1b83 2448 U32 wordlen = 0; /* required init */
c445ea15 2449
df826430
YO
2450 if (OP(noper) == NOTHING) {
2451 regnode *noper_next= regnext(noper);
2452 if (noper_next != tail && OP(noper_next) == flags) {
2453 noper = noper_next;
2454 uc= (U8*)STRING(noper);
2455 e= uc + STR_LEN(noper);
2456 }
2457 }
2458
3dab1dad 2459 if (OP(noper) != NOTHING) {
786e8c11 2460 for ( ; uc < e ; uc += len ) {
c445ea15 2461
786e8c11 2462 TRIE_READ_CHAR;
c445ea15 2463
786e8c11
YO
2464 if ( uvc < 256 ) {
2465 charid = trie->charmap[ uvc ];
c445ea15 2466 } else {
538e84ed
KW
2467 SV** const svpp = hv_fetch( widecharmap,
2468 (char*)&uvc,
2469 sizeof( UV ),
2470 0);
786e8c11
YO
2471 if ( !svpp ) {
2472 charid = 0;
2473 } else {
2474 charid=(U16)SvIV( *svpp );
2475 }
c445ea15 2476 }
538e84ed
KW
2477 /* charid is now 0 if we dont know the char read, or
2478 * nonzero if we do */
786e8c11 2479 if ( charid ) {
a3621e74 2480
786e8c11
YO
2481 U16 check;
2482 U32 newstate = 0;
a3621e74 2483
786e8c11
YO
2484 charid--;
2485 if ( !trie->states[ state ].trans.list ) {
2486 TRIE_LIST_NEW( state );
c445ea15 2487 }
538e84ed
KW
2488 for ( check = 1;
2489 check <= TRIE_LIST_USED( state );
2490 check++ )
2491 {
2492 if ( TRIE_LIST_ITEM( state, check ).forid
2493 == charid )
2494 {
786e8c11
YO
2495 newstate = TRIE_LIST_ITEM( state, check ).newstate;
2496 break;
2497 }
2498 }
2499 if ( ! newstate ) {
2500 newstate = next_alloc++;
2e64971a 2501 prev_states[newstate] = state;
786e8c11
YO
2502 TRIE_LIST_PUSH( state, charid, newstate );
2503 transcount++;
2504 }
2505 state = newstate;
2506 } else {
2507 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
c445ea15 2508 }
a28509cc 2509 }
c445ea15 2510 }
3dab1dad 2511 TRIE_HANDLE_WORD(state);
a3621e74
YO
2512
2513 } /* end second pass */
2514
1e2e3d02 2515 /* next alloc is the NEXT state to be allocated */
538e84ed 2516 trie->statecount = next_alloc;
c944940b
JH
2517 trie->states = (reg_trie_state *)
2518 PerlMemShared_realloc( trie->states,
2519 next_alloc
2520 * sizeof(reg_trie_state) );
a3621e74 2521
3dab1dad 2522 /* and now dump it out before we compress it */
2b8b4781
NC
2523 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
2524 revcharmap, next_alloc,
2525 depth+1)
1e2e3d02 2526 );
a3621e74 2527
c944940b
JH
2528 trie->trans = (reg_trie_trans *)
2529 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
a3621e74
YO
2530 {
2531 U32 state;
a3621e74
YO
2532 U32 tp = 0;
2533 U32 zp = 0;
2534
2535
2536 for( state=1 ; state < next_alloc ; state ++ ) {
2537 U32 base=0;
2538
2539 /*
2540 DEBUG_TRIE_COMPILE_MORE_r(
2541 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
2542 );
2543 */
2544
2545 if (trie->states[state].trans.list) {
2546 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
2547 U16 maxid=minid;
a28509cc 2548 U16 idx;
a3621e74
YO
2549
2550 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
c445ea15
AL
2551 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
2552 if ( forid < minid ) {
2553 minid=forid;
2554 } else if ( forid > maxid ) {
2555 maxid=forid;
2556 }
a3621e74
YO
2557 }
2558 if ( transcount < tp + maxid - minid + 1) {
2559 transcount *= 2;
c944940b
JH
2560 trie->trans = (reg_trie_trans *)
2561 PerlMemShared_realloc( trie->trans,
446bd890
NC
2562 transcount
2563 * sizeof(reg_trie_trans) );
538e84ed
KW
2564 Zero( trie->trans + (transcount / 2),
2565 transcount / 2,
2566 reg_trie_trans );
a3621e74
YO
2567 }
2568 base = trie->uniquecharcount + tp - minid;
2569 if ( maxid == minid ) {
2570 U32 set = 0;
2571 for ( ; zp < tp ; zp++ ) {
2572 if ( ! trie->trans[ zp ].next ) {
2573 base = trie->uniquecharcount + zp - minid;
538e84ed
KW
2574 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
2575 1).newstate;
a3621e74
YO
2576 trie->trans[ zp ].check = state;
2577 set = 1;
2578 break;
2579 }
2580 }
2581 if ( !set ) {
538e84ed
KW
2582 trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
2583 1).newstate;
a3621e74
YO
2584 trie->trans[ tp ].check = state;
2585 tp++;
2586 zp = tp;
2587 }
2588 } else {
2589 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
538e84ed
KW
2590 const U32 tid = base
2591 - trie->uniquecharcount
2592 + TRIE_LIST_ITEM( state, idx ).forid;
2593 trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
2594 idx ).newstate;
a3621e74
YO
2595 trie->trans[ tid ].check = state;
2596 }
2597 tp += ( maxid - minid + 1 );
2598 }
2599 Safefree(trie->states[ state ].trans.list);
2600 }
2601 /*
2602 DEBUG_TRIE_COMPILE_MORE_r(
2603 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
2604 );
2605 */
2606 trie->states[ state ].trans.base=base;
2607 }
cc601c31 2608 trie->lasttrans = tp + 1;
a3621e74
YO
2609 }
2610 } else {
2611 /*
2612 Second Pass -- Flat Table Representation.
2613
b423522f
KW
2614 we dont use the 0 slot of either trans[] or states[] so we add 1 to
2615 each. We know that we will need Charcount+1 trans at most to store
2616 the data (one row per char at worst case) So we preallocate both
2617 structures assuming worst case.
a3621e74
YO
2618
2619 We then construct the trie using only the .next slots of the entry
2620 structs.
2621
b423522f
KW
2622 We use the .check field of the first entry of the node temporarily
2623 to make compression both faster and easier by keeping track of how
2624 many non zero fields are in the node.
a3621e74
YO
2625
2626 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
2627 transition.
2628
b423522f
KW
2629 There are two terms at use here: state as a TRIE_NODEIDX() which is
2630 a number representing the first entry of the node, and state as a
2631 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
2632 and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
2633 if there are 2 entrys per node. eg:
a3621e74
YO
2634
2635 A B A B
2636 1. 2 4 1. 3 7
2637 2. 0 3 3. 0 5
2638 3. 0 0 5. 0 0
2639 4. 0 0 7. 0 0
2640
b423522f
KW
2641 The table is internally in the right hand, idx form. However as we
2642 also have to deal with the states array which is indexed by nodenum
2643 we have to use TRIE_NODENUM() to convert.
a3621e74
YO
2644
2645 */
538e84ed 2646 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1e2e3d02
YO
2647 "%*sCompiling trie using table compiler\n",
2648 (int)depth * 2 + 2, ""));
3dab1dad 2649
c944940b
JH
2650 trie->trans = (reg_trie_trans *)
2651 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
2652 * trie->uniquecharcount + 1,
2653 sizeof(reg_trie_trans) );
2654 trie->states = (reg_trie_state *)
2655 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2656 sizeof(reg_trie_state) );
a3621e74
YO
2657 next_alloc = trie->uniquecharcount + 1;
2658
3dab1dad 2659
a3621e74
YO
2660 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2661
df826430 2662 regnode *noper = NEXTOPER( cur );
a28509cc 2663 const U8 *uc = (U8*)STRING( noper );
df826430 2664 const U8 *e = uc + STR_LEN( noper );
a3621e74
YO
2665
2666 U32 state = 1; /* required init */
2667
2668 U16 charid = 0; /* sanity init */
2669 U32 accept_state = 0; /* sanity init */
a3621e74 2670
07be1b83 2671 U32 wordlen = 0; /* required init */
a3621e74 2672
df826430
YO
2673 if (OP(noper) == NOTHING) {
2674 regnode *noper_next= regnext(noper);
2675 if (noper_next != tail && OP(noper_next) == flags) {
2676 noper = noper_next;
2677 uc= (U8*)STRING(noper);
2678 e= uc + STR_LEN(noper);
2679 }
2680 }
fab2782b 2681
3dab1dad 2682 if ( OP(noper) != NOTHING ) {
786e8c11 2683 for ( ; uc < e ; uc += len ) {
a3621e74 2684
786e8c11 2685 TRIE_READ_CHAR;
a3621e74 2686
786e8c11
YO
2687 if ( uvc < 256 ) {
2688 charid = trie->charmap[ uvc ];
2689 } else {
538e84ed
KW
2690 SV* const * const svpp = hv_fetch( widecharmap,
2691 (char*)&uvc,
2692 sizeof( UV ),
2693 0);
786e8c11 2694 charid = svpp ? (U16)SvIV(*svpp) : 0;
a3621e74 2695 }
786e8c11
YO
2696 if ( charid ) {
2697 charid--;
2698 if ( !trie->trans[ state + charid ].next ) {
2699 trie->trans[ state + charid ].next = next_alloc;
2700 trie->trans[ state ].check++;
2e64971a
DM
2701 prev_states[TRIE_NODENUM(next_alloc)]
2702 = TRIE_NODENUM(state);
786e8c11
YO
2703 next_alloc += trie->uniquecharcount;
2704 }
2705 state = trie->trans[ state + charid ].next;
2706 } else {
2707 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2708 }
538e84ed
KW
2709 /* charid is now 0 if we dont know the char read, or
2710 * nonzero if we do */
a3621e74 2711 }
a3621e74 2712 }
3dab1dad
YO
2713 accept_state = TRIE_NODENUM( state );
2714 TRIE_HANDLE_WORD(accept_state);
a3621e74
YO
2715
2716 } /* end second pass */
2717
3dab1dad 2718 /* and now dump it out before we compress it */
2b8b4781
NC
2719 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
2720 revcharmap,
2721 next_alloc, depth+1));
a3621e74 2722
a3621e74
YO
2723 {
2724 /*
2725 * Inplace compress the table.*
2726
2727 For sparse data sets the table constructed by the trie algorithm will
2728 be mostly 0/FAIL transitions or to put it another way mostly empty.
2729 (Note that leaf nodes will not contain any transitions.)
2730
2731 This algorithm compresses the tables by eliminating most such
2732 transitions, at the cost of a modest bit of extra work during lookup:
2733
2734 - Each states[] entry contains a .base field which indicates the
2735 index in the state[] array wheres its transition data is stored.
2736
3b753521 2737 - If .base is 0 there are no valid transitions from that node.
a3621e74
YO
2738
2739 - If .base is nonzero then charid is added to it to find an entry in
2740 the trans array.
2741
2742 -If trans[states[state].base+charid].check!=state then the
2743 transition is taken to be a 0/Fail transition. Thus if there are fail
2744 transitions at the front of the node then the .base offset will point
2745 somewhere inside the previous nodes data (or maybe even into a node
2746 even earlier), but the .check field determines if the transition is
2747 valid.
2748
786e8c11 2749 XXX - wrong maybe?
a3621e74 2750 The following process inplace converts the table to the compressed
3b753521 2751 table: We first do not compress the root node 1,and mark all its
a3621e74 2752 .check pointers as 1 and set its .base pointer as 1 as well. This
3b753521
FN
2753 allows us to do a DFA construction from the compressed table later,
2754 and ensures that any .base pointers we calculate later are greater
2755 than 0.
a3621e74
YO
2756
2757 - We set 'pos' to indicate the first entry of the second node.
2758
2759 - We then iterate over the columns of the node, finding the first and
2760 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
2761 and set the .check pointers accordingly, and advance pos
2762 appropriately and repreat for the next node. Note that when we copy
2763 the next pointers we have to convert them from the original
2764 NODEIDX form to NODENUM form as the former is not valid post
2765 compression.
2766
2767 - If a node has no transitions used we mark its base as 0 and do not
2768 advance the pos pointer.
2769
2770 - If a node only has one transition we use a second pointer into the
2771 structure to fill in allocated fail transitions from other states.
2772 This pointer is independent of the main pointer and scans forward
2773 looking for null transitions that are allocated to a state. When it
2774 finds one it writes the single transition into the "hole". If the
786e8c11 2775 pointer doesnt find one the single transition is appended as normal.
a3621e74
YO
2776
2777 - Once compressed we can Renew/realloc the structures to release the
2778 excess space.
2779
2780 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
2781 specifically Fig 3.47 and the associated pseudocode.
2782
2783 demq
2784 */
a3b680e6 2785 const U32 laststate = TRIE_NODENUM( next_alloc );
a28509cc 2786 U32 state, charid;
a3621e74 2787 U32 pos = 0, zp=0;
1e2e3d02 2788 trie->statecount = laststate;
a3621e74
YO
2789
2790 for ( state = 1 ; state < laststate ; state++ ) {
2791 U8 flag = 0;
a28509cc
AL
2792 const U32 stateidx = TRIE_NODEIDX( state );
2793 const U32 o_used = trie->trans[ stateidx ].check;
2794 U32 used = trie->trans[ stateidx ].check;
a3621e74
YO
2795 trie->trans[ stateidx ].check = 0;
2796
538e84ed
KW
2797 for ( charid = 0;
2798 used && charid < trie->uniquecharcount;
2799 charid++ )
2800 {
a3621e74
YO
2801 if ( flag || trie->trans[ stateidx + charid ].next ) {
2802 if ( trie->trans[ stateidx + charid ].next ) {
2803 if (o_used == 1) {
2804 for ( ; zp < pos ; zp++ ) {
2805 if ( ! trie->trans[ zp ].next ) {
2806 break;
2807 }
2808 }
538e84ed
KW
2809 trie->states[ state ].trans.base
2810 = zp
2811 + trie->uniquecharcount
2812 - charid ;
2813 trie->trans[ zp ].next
2814 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
2815 + charid ].next );
a3621e74
YO
2816 trie->trans[ zp ].check = state;
2817 if ( ++zp > pos ) pos = zp;
2818 break;
2819 }
2820 used--;
2821 }
2822 if ( !flag ) {
2823 flag = 1;
538e84ed
KW
2824 trie->states[ state ].trans.base
2825 = pos + trie->uniquecharcount - charid ;
a3621e74 2826 }
538e84ed
KW
2827 trie->trans[ pos ].next
2828 = SAFE_TRIE_NODENUM(
2829 trie->trans[ stateidx + charid ].next );
a3621e74
YO
2830 trie->trans[ pos ].check = state;
2831 pos++;
2832 }
2833 }
2834 }
cc601c31 2835 trie->lasttrans = pos + 1;
c944940b
JH
2836 trie->states = (reg_trie_state *)
2837 PerlMemShared_realloc( trie->states, laststate
2838 * sizeof(reg_trie_state) );
a3621e74 2839 DEBUG_TRIE_COMPILE_MORE_r(
538e84ed
KW
2840 PerlIO_printf( Perl_debug_log,
2841 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
2842 (int)depth * 2 + 2,"",
2843 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
2844 + 1 ),
2845 (IV)next_alloc,
2846 (IV)pos,
2847 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
a3621e74
YO
2848 );
2849
2850 } /* end table compress */
2851 }
1e2e3d02 2852 DEBUG_TRIE_COMPILE_MORE_r(
538e84ed
KW
2853 PerlIO_printf(Perl_debug_log,
2854 "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
1e2e3d02
YO
2855 (int)depth * 2 + 2, "",
2856 (UV)trie->statecount,
2857 (UV)trie->lasttrans)
2858 );
cc601c31 2859 /* resize the trans array to remove unused space */
c944940b
JH
2860 trie->trans = (reg_trie_trans *)
2861 PerlMemShared_realloc( trie->trans, trie->lasttrans
2862 * sizeof(reg_trie_trans) );
a3621e74 2863
538e84ed 2864 { /* Modify the program and insert the new TRIE node */
3dab1dad
YO
2865 U8 nodetype =(U8)(flags & 0xFF);
2866 char *str=NULL;
538e84ed 2867
07be1b83 2868#ifdef DEBUGGING
e62cc96a 2869 regnode *optimize = NULL;
7122b237
YO
2870#ifdef RE_TRACK_PATTERN_OFFSETS
2871
b57a0404
JH
2872 U32 mjd_offset = 0;
2873 U32 mjd_nodelen = 0;
7122b237
YO
2874#endif /* RE_TRACK_PATTERN_OFFSETS */
2875#endif /* DEBUGGING */
a3621e74 2876 /*
3dab1dad
YO
2877 This means we convert either the first branch or the first Exact,
2878 depending on whether the thing following (in 'last') is a branch
2879 or not and whther first is the startbranch (ie is it a sub part of
2880 the alternation or is it the whole thing.)
3b753521 2881 Assuming its a sub part we convert the EXACT otherwise we convert
3dab1dad 2882 the whole branch sequence, including the first.
a3621e74 2883 */
3dab1dad 2884 /* Find the node we are going to overwrite */
7f69552c 2885 if ( first != startbranch || OP( last ) == BRANCH ) {
07be1b83 2886 /* branch sub-chain */
3dab1dad 2887 NEXT_OFF( first ) = (U16)(last - first);
7122b237 2888#ifdef RE_TRACK_PATTERN_OFFSETS
07be1b83
YO
2889 DEBUG_r({
2890 mjd_offset= Node_Offset((convert));
2891 mjd_nodelen= Node_Length((convert));
2892 });
7122b237 2893#endif
7f69552c 2894 /* whole branch chain */
7122b237
YO
2895 }
2896#ifdef RE_TRACK_PATTERN_OFFSETS
2897 else {
7f69552c
YO
2898 DEBUG_r({
2899 const regnode *nop = NEXTOPER( convert );
2900 mjd_offset= Node_Offset((nop));
2901 mjd_nodelen= Node_Length((nop));
2902 });
07be1b83
YO
2903 }
2904 DEBUG_OPTIMISE_r(
538e84ed
KW
2905 PerlIO_printf(Perl_debug_log,
2906 "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
07be1b83 2907 (int)depth * 2 + 2, "",
786e8c11 2908 (UV)mjd_offset, (UV)mjd_nodelen)
07be1b83 2909 );
7122b237 2910#endif
538e84ed 2911 /* But first we check to see if there is a common prefix we can
3dab1dad
YO
2912 split out as an EXACT and put in front of the TRIE node. */
2913 trie->startstate= 1;
55eed653 2914 if ( trie->bitmap && !widecharmap && !trie->jump ) {
3dab1dad 2915 U32 state;
1e2e3d02 2916 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
a3621e74 2917 U32 ofs = 0;
8e11feef
RGS
2918 I32 idx = -1;
2919 U32 count = 0;
2920 const U32 base = trie->states[ state ].trans.base;
a3621e74 2921
3dab1dad 2922 if ( trie->states[state].wordnum )
8e11feef 2923 count = 1;
a3621e74 2924
8e11feef 2925 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
cc601c31
YO
2926 if ( ( base + ofs >= trie->uniquecharcount ) &&
2927 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
a3621e74
YO
2928 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
2929 {
3dab1dad 2930 if ( ++count > 1 ) {
2b8b4781 2931 SV **tmp = av_fetch( revcharmap, ofs, 0);
07be1b83 2932 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
8e11feef 2933 if ( state == 1 ) break;
3dab1dad
YO
2934 if ( count == 2 ) {
2935 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
2936 DEBUG_OPTIMISE_r(
8e11feef
RGS
2937 PerlIO_printf(Perl_debug_log,
2938 "%*sNew Start State=%"UVuf" Class: [",
2939 (int)depth * 2 + 2, "",
786e8c11 2940 (UV)state));
be8e71aa 2941 if (idx >= 0) {
2b8b4781 2942 SV ** const tmp = av_fetch( revcharmap, idx, 0);
be8e71aa 2943 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
8e11feef 2944
3dab1dad 2945 TRIE_BITMAP_SET(trie,*ch);
8e11feef
RGS
2946 if ( folder )
2947 TRIE_BITMAP_SET(trie, folder[ *ch ]);
3dab1dad 2948 DEBUG_OPTIMISE_r(
f1f66076 2949 PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
3dab1dad 2950 );
8e11feef
RGS
2951 }
2952 }
2953 TRIE_BITMAP_SET(trie,*ch);
2954 if ( folder )
2955 TRIE_BITMAP_SET(trie,folder[ *ch ]);
2956 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
2957 }
2958 idx = ofs;
2959 }
3dab1dad
YO
2960 }
2961 if ( count == 1 ) {
2b8b4781 2962 SV **tmp = av_fetch( revcharmap, idx, 0);
c490c714
YO
2963 STRLEN len;
2964 char *ch = SvPV( *tmp, len );
de734bd5
A
2965 DEBUG_OPTIMISE_r({
2966 SV *sv=sv_newmortal();
8e11feef
RGS
2967 PerlIO_printf( Perl_debug_log,
2968 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
2969 (int)depth * 2 + 2, "",
538e84ed
KW
2970 (UV)state, (UV)idx,
2971 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
de734bd5
A
2972 PL_colors[0], PL_colors[1],
2973 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
538e84ed 2974 PERL_PV_ESCAPE_FIRSTCHAR
de734bd5
A
2975 )
2976 );
2977 });
3dab1dad
YO
2978 if ( state==1 ) {
2979 OP( convert ) = nodetype;
2980 str=STRING(convert);
2981 STR_LEN(convert)=0;
2982 }
c490c714
YO
2983 STR_LEN(convert) += len;
2984 while (len--)
de734bd5 2985 *str++ = *ch++;
8e11feef 2986 } else {
538e84ed 2987#ifdef DEBUGGING
8e11feef
RGS
2988 if (state>1)
2989 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
f9049ba1 2990#endif
8e11feef
RGS
2991 break;
2992 }
2993 }
2e64971a 2994 trie->prefixlen = (state-1);
3dab1dad 2995 if (str) {
8e11feef 2996 regnode *n = convert+NODE_SZ_STR(convert);
07be1b83 2997 NEXT_OFF(convert) = NODE_SZ_STR(convert);
8e11feef 2998 trie->startstate = state;
07be1b83
YO
2999 trie->minlen -= (state - 1);
3000 trie->maxlen -= (state - 1);
33809eae
JH
3001#ifdef DEBUGGING
3002 /* At least the UNICOS C compiler choked on this
3003 * being argument to DEBUG_r(), so let's just have
3004 * it right here. */
3005 if (
3006#ifdef PERL_EXT_RE_BUILD
3007 1
3008#else
3009 DEBUG_r_TEST
3010#endif
3011 ) {
3012 regnode *fix = convert;
3013 U32 word = trie->wordcount;
3014 mjd_nodelen++;
3015 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3016 while( ++fix < n ) {
3017 Set_Node_Offset_Length(fix, 0, 0);
3018 }
3019 while (word--) {
3020 SV ** const tmp = av_fetch( trie_words, word, 0 );
3021 if (tmp) {
3022 if ( STR_LEN(convert) <= SvCUR(*tmp) )
3023 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3024 else
3025 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3026 }
3027 }
3028 }
3029#endif
8e11feef
RGS
3030 if (trie->maxlen) {
3031 convert = n;
3032 } else {
3dab1dad 3033 NEXT_OFF(convert) = (U16)(tail - convert);
a5ca303d 3034 DEBUG_r(optimize= n);
3dab1dad
YO
3035 }
3036 }
3037 }
538e84ed
KW
3038 if (!jumper)
3039 jumper = last;
3dab1dad 3040 if ( trie->maxlen ) {
8e11feef
RGS
3041 NEXT_OFF( convert ) = (U16)(tail - convert);
3042 ARG_SET( convert, data_slot );
538e84ed
KW
3043 /* Store the offset to the first unabsorbed branch in
3044 jump[0], which is otherwise unused by the jump logic.
786e8c11 3045 We use this when dumping a trie and during optimisation. */
538e84ed 3046 if (trie->jump)
7f69552c 3047 trie->jump[0] = (U16)(nextbranch - convert);
538e84ed 3048
6c48061a
YO
3049 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3050 * and there is a bitmap
3051 * and the first "jump target" node we found leaves enough room
3052 * then convert the TRIE node into a TRIEC node, with the bitmap
3053 * embedded inline in the opcode - this is hypothetically faster.
3054 */
3055 if ( !trie->states[trie->startstate].wordnum
3056 && trie->bitmap
3057 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
786e8c11
YO
3058 {
3059 OP( convert ) = TRIEC;
3060 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
446bd890 3061 PerlMemShared_free(trie->bitmap);
786e8c11 3062 trie->bitmap= NULL;
538e84ed 3063 } else
786e8c11 3064 OP( convert ) = TRIE;
a3621e74 3065
3dab1dad
YO
3066 /* store the type in the flags */
3067 convert->flags = nodetype;
a5ca303d 3068 DEBUG_r({
538e84ed
KW
3069 optimize = convert
3070 + NODE_STEP_REGNODE
a5ca303d
YO
3071 + regarglen[ OP( convert ) ];
3072 });
538e84ed 3073 /* XXX We really should free up the resource in trie now,
a5ca303d 3074 as we won't use them - (which resources?) dmq */
3dab1dad 3075 }
a3621e74 3076 /* needed for dumping*/
e62cc96a 3077 DEBUG_r(if (optimize) {
07be1b83 3078 regnode *opt = convert;
bcdf7404 3079
e62cc96a 3080 while ( ++opt < optimize) {
07be1b83
YO
3081 Set_Node_Offset_Length(opt,0,0);
3082 }
538e84ed
KW
3083 /*
3084 Try to clean up some of the debris left after the
786e8c11 3085 optimisation.
a3621e74 3086 */
786e8c11 3087 while( optimize < jumper ) {
07be1b83 3088 mjd_nodelen += Node_Length((optimize));
a3621e74 3089 OP( optimize ) = OPTIMIZED;
07be1b83 3090 Set_Node_Offset_Length(optimize,0,0);
a3621e74
YO
3091 optimize++;
3092 }
07be1b83 3093 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
a3621e74
YO
3094 });
3095 } /* end node insert */
2e64971a
DM
3096
3097 /* Finish populating the prev field of the wordinfo array. Walk back
3098 * from each accept state until we find another accept state, and if
3099 * so, point the first word's .prev field at the second word. If the
3100 * second already has a .prev field set, stop now. This will be the
3101 * case either if we've already processed that word's accept state,
3b753521
FN
3102 * or that state had multiple words, and the overspill words were
3103 * already linked up earlier.
2e64971a
DM
3104 */
3105 {
3106 U16 word;
3107 U32 state;
3108 U16 prev;
3109
3110 for (word=1; word <= trie->wordcount; word++) {
3111 prev = 0;
3112 if (trie->wordinfo[word].prev)
3113 continue;
3114 state = trie->wordinfo[word].accept;
3115 while (state) {
3116 state = prev_states[state];
3117 if (!state)
3118 break;
3119 prev = trie->states[state].wordnum;
3120 if (prev)
3121 break;
3122 }
3123 trie->wordinfo[word].prev = prev;
3124 }
3125 Safefree(prev_states);
3126 }
3127
3128
3129 /* and now dump out the compressed format */
3130 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3131
55eed653 3132 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
2b8b4781
NC
3133#ifdef DEBUGGING
3134 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3135 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3136#else
03e70be4 3137 SvREFCNT_dec_NN(revcharmap);
07be1b83 3138#endif
538e84ed
KW
3139 return trie->jump
3140 ? MADE_JUMP_TRIE
3141 : trie->startstate>1
3142 ? MADE_EXACT_TRIE
786e8c11
YO
3143 : MADE_TRIE;
3144}
3145
615a2e7f
YO
3146STATIC regnode *
3147S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
786e8c11 3148{
b423522f
KW
3149/* The Trie is constructed and compressed now so we can build a fail array if
3150 * it's needed
786e8c11 3151
b423522f
KW
3152 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3153 3.32 in the
3154 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3155 Ullman 1985/88
786e8c11
YO
3156 ISBN 0-201-10088-6
3157
b423522f
KW
3158 We find the fail state for each state in the trie, this state is the longest
3159 proper suffix of the current state's 'word' that is also a proper prefix of
3160 another word in our trie. State 1 represents the word '' and is thus the
3161 default fail state. This allows the DFA not to have to restart after its
3162 tried and failed a word at a given point, it simply continues as though it
3163 had been matching the other word in the first place.
786e8c11
YO
3164 Consider
3165 'abcdgu'=~/abcdefg|cdgu/
b423522f
KW
3166 When we get to 'd' we are still matching the first word, we would encounter
3167 'g' which would fail, which would bring us to the state representing 'd' in
3168 the second word where we would try 'g' and succeed, proceeding to match
3169 'cdgu'.
786e8c11
YO
3170 */
3171 /* add a fail transition */
3251b653
NC
3172 const U32 trie_offset = ARG(source);
3173 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
786e8c11
YO
3174 U32 *q;
3175 const U32 ucharcount = trie->uniquecharcount;
1e2e3d02 3176 const U32 numstates = trie->statecount;
786e8c11
YO
3177 const U32 ubound = trie->lasttrans + ucharcount;
3178 U32 q_read = 0;
3179 U32 q_write = 0;
3180 U32 charid;
3181 U32 base = trie->states[ 1 ].trans.base;
3182 U32 *fail;
3183 reg_ac_data *aho;
cf78de0b 3184 const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
615a2e7f 3185 regnode *stclass;
786e8c11 3186 GET_RE_DEBUG_FLAGS_DECL;
7918f24d 3187
615a2e7f 3188 PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
81611534 3189 PERL_UNUSED_CONTEXT;
786e8c11
YO
3190#ifndef DEBUGGING
3191 PERL_UNUSED_ARG(depth);
3192#endif
3193
615a2e7f
YO
3194 if ( OP(source) == TRIE ) {
3195 struct regnode_1 *op = (struct regnode_1 *)
3196 PerlMemShared_calloc(1, sizeof(struct regnode_1));
3197 StructCopy(source,op,struct regnode_1);
3198 stclass = (regnode *)op;
3199 } else {
3200 struct regnode_charclass *op = (struct regnode_charclass *)
3201 PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3202 StructCopy(source,op,struct regnode_charclass);
3203 stclass = (regnode *)op;
3204 }
2f306ab9 3205 OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
786e8c11
YO
3206
3207 ARG_SET( stclass, data_slot );
c944940b 3208 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
f8fc2ecf 3209 RExC_rxi->data->data[ data_slot ] = (void*)aho;
3251b653 3210 aho->trie=trie_offset;
446bd890
NC
3211 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3212 Copy( trie->states, aho->states, numstates, reg_trie_state );
786e8c11 3213 Newxz( q, numstates, U32);
c944940b 3214 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
786e8c11
YO
3215 aho->refcount = 1;
3216 fail = aho->fail;
3217 /* initialize fail[0..1] to be 1 so that we always have
3218 a valid final fail state */
3219 fail[ 0 ] = fail[ 1 ] = 1;
3220
3221 for ( charid = 0; charid < ucharcount ; charid++ ) {
3222 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3223 if ( newstate ) {
3224 q[ q_write ] = newstate;
3225 /* set to point at the root */
3226 fail[ q[ q_write++ ] ]=1;
3227 }
3228 }
3229 while ( q_read < q_write) {
3230 const U32 cur = q[ q_read++ % numstates ];
3231 base = trie->states[ cur ].trans.base;
3232
3233 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3234 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3235 if (ch_state) {
3236 U32 fail_state = cur;
3237 U32 fail_base;
3238 do {
3239 fail_state = fail[ fail_state ];
3240 fail_base = aho->states[ fail_state ].trans.base;
3241 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3242
3243 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3244 fail[ ch_state ] = fail_state;
3245 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3246 {
3247 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
3248 }
3249 q[ q_write++ % numstates] = ch_state;
3250 }
3251 }
3252 }
3253 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3254 when we fail in state 1, this allows us to use the
3255 charclass scan to find a valid start char. This is based on the principle
3256 that theres a good chance the string being searched contains lots of stuff
3257 that cant be a start char.
3258 */
3259 fail[ 0 ] = fail[ 1 ] = 0;
3260 DEBUG_TRIE_COMPILE_r({
6d99fb9b 3261 PerlIO_printf(Perl_debug_log,
538e84ed 3262 "%*sStclass Failtable (%"UVuf" states): 0",
6d99fb9b 3263 (int)(depth * 2), "", (UV)numstates
1e2e3d02 3264 );
786e8c11
YO
3265 for( q_read=1; q_read<numstates; q_read++ ) {
3266 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
3267 }
3268 PerlIO_printf(Perl_debug_log, "\n");
3269 });
3270 Safefree(q);
e384d5c1 3271 /*RExC_seen |= REG_TRIEDFA_SEEN;*/
615a2e7f 3272 return stclass;
a3621e74
YO
3273}
3274
786e8c11 3275
07be1b83 3276#define DEBUG_PEEP(str,scan,depth) \
b515a41d 3277 DEBUG_OPTIMISE_r({if (scan){ \
07be1b83 3278 regnode *Next = regnext(scan); \
8b9781c9 3279 regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state); \
fdfb4f21 3280 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)", \
c9f0d54c
YO
3281 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),\
3282 Next ? (REG_NODE_NUM(Next)) : 0 ); \
fdfb4f21
YO
3283 DEBUG_SHOW_STUDY_FLAGS(flags," [ ","]");\
3284 PerlIO_printf(Perl_debug_log, "\n"); \
b515a41d 3285 }});
07be1b83 3286
bb914485 3287/* The below joins as many adjacent EXACTish nodes as possible into a single
0a982f06
KW
3288 * one. The regop may be changed if the node(s) contain certain sequences that
3289 * require special handling. The joining is only done if:
bb914485
KW
3290 * 1) there is room in the current conglomerated node to entirely contain the
3291 * next one.
3292 * 2) they are the exact same node type
3293 *
87b8b349 3294 * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
bb914485
KW
3295 * these get optimized out
3296 *
0a982f06
KW
3297 * If a node is to match under /i (folded), the number of characters it matches
3298 * can be different than its character length if it contains a multi-character
31f05a37
KW
3299 * fold. *min_subtract is set to the total delta number of characters of the
3300 * input nodes.
bb914485 3301 *
fb29cc72 3302 * And *unfolded_multi_char is set to indicate whether or not the node contains
31f05a37
KW
3303 * an unfolded multi-char fold. This happens when whether the fold is valid or
3304 * not won't be known until runtime; namely for EXACTF nodes that contain LATIN
3305 * SMALL LETTER SHARP S, as only if the target string being matched against
3306 * turns out to be UTF-8 is that fold valid; and also for EXACTFL nodes whose
3307 * folding rules depend on the locale in force at runtime. (Multi-char folds
3308 * whose components are all above the Latin1 range are not run-time locale
3309 * dependent, and have already been folded by the time this function is
3310 * called.)
f758bddf 3311 *
bb914485 3312 * This is as good a place as any to discuss the design of handling these
0a982f06
KW
3313 * multi-character fold sequences. It's been wrong in Perl for a very long
3314 * time. There are three code points in Unicode whose multi-character folds
3315 * were long ago discovered to mess things up. The previous designs for
3316 * dealing with these involved assigning a special node for them. This
538e84ed 3317 * approach doesn't always work, as evidenced by this example:
a0c4c608 3318 * "\xDFs" =~ /s\xDF/ui # Used to fail before these patches
538e84ed 3319 * Both sides fold to "sss", but if the pattern is parsed to create a node that
0a982f06 3320 * would match just the \xDF, it won't be able to handle the case where a
bb914485
KW
3321 * successful match would have to cross the node's boundary. The new approach
3322 * that hopefully generally solves the problem generates an EXACTFU_SS node
538e84ed 3323 * that is "sss" in this case.
bb914485 3324 *
0a982f06 3325 * It turns out that there are problems with all multi-character folds, and not
cb117658
KW
3326 * just these three. Now the code is general, for all such cases. The
3327 * approach taken is:
0a982f06 3328 * 1) This routine examines each EXACTFish node that could contain multi-
538e84ed
KW
3329 * character folded sequences. Since a single character can fold into
3330 * such a sequence, the minimum match length for this node is less than
3331 * the number of characters in the node. This routine returns in
31f05a37
KW
3332 * *min_subtract how many characters to subtract from the the actual
3333 * length of the string to get a real minimum match length; it is 0 if
3334 * there are no multi-char foldeds. This delta is used by the caller to
3335 * adjust the min length of the match, and the delta between min and max,
3336 * so that the optimizer doesn't reject these possibilities based on size
3337 * constraints.
cb117658 3338 * 2) For the sequence involving the Sharp s (\xDF), the node type EXACTFU_SS
0a982f06
KW
3339 * is used for an EXACTFU node that contains at least one "ss" sequence in
3340 * it. For non-UTF-8 patterns and strings, this is the only case where
3341 * there is a possible fold length change. That means that a regular
3342 * EXACTFU node without UTF-8 involvement doesn't have to concern itself
3343 * with length changes, and so can be processed faster. regexec.c takes
3344 * advantage of this. Generally, an EXACTFish node that is in UTF-8 is
31f05a37
KW
3345 * pre-folded by regcomp.c (except EXACTFL, some of whose folds aren't
3346 * known until runtime). This saves effort in regex matching. However,
3347 * the pre-folding isn't done for non-UTF8 patterns because the fold of
3348 * the MICRO SIGN requires UTF-8, and we don't want to slow things down by
3349 * forcing the pattern into UTF8 unless necessary. Also what EXACTF (and,
3350 * again, EXACTFL) nodes fold to isn't known until runtime. The fold
0a982f06
KW
3351 * possibilities for the non-UTF8 patterns are quite simple, except for
3352 * the sharp s. All the ones that don't involve a UTF-8 target string are
3353 * members of a fold-pair, and arrays are set up for all of them so that
3354 * the other member of the pair can be found quickly. Code elsewhere in
3355 * this file makes sure that in EXACTFU nodes, the sharp s gets folded to
3356 * 'ss', even if the pattern isn't UTF-8. This avoids the issues
3357 * described in the next item.
31f05a37
KW
3358 * 3) A problem remains for unfolded multi-char folds. (These occur when the
3359 * validity of the fold won't be known until runtime, and so must remain
3360 * unfolded for now. This happens for the sharp s in EXACTF and EXACTFA
3361 * nodes when the pattern isn't in UTF-8. (Note, BTW, that there cannot
3362 * be an EXACTF node with a UTF-8 pattern.) They also occur for various
3363 * folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
3364 * The reason this is a problem is that the optimizer part of regexec.c
3365 * (probably unwittingly, in Perl_regexec_flags()) makes an assumption
3366 * that a character in the pattern corresponds to at most a single
3367 * character in the target string. (And I do mean character, and not byte
3368 * here, unlike other parts of the documentation that have never been
3369 * updated to account for multibyte Unicode.) sharp s in EXACTF and
3370 * EXACTFL nodes can match the two character string 'ss'; in EXACTFA nodes
3371 * it can match "\x{17F}\x{17F}". These, along with other ones in EXACTFL
3372 * nodes, violate the assumption, and they are the only instances where it
3373 * is violated. I'm reluctant to try to change the assumption, as the
3374 * code involved is impenetrable to me (khw), so instead the code here
3375 * punts. This routine examines EXACTFL nodes, and (when the pattern
3376 * isn't UTF-8) EXACTF and EXACTFA for such unfolded folds, and returns a
3377 * boolean indicating whether or not the node contains such a fold. When
3378 * it is true, the caller sets a flag that later causes the optimizer in
3379 * this file to not set values for the floating and fixed string lengths,
3380 * and thus avoids the optimizer code in regexec.c that makes the invalid
1ca267a5 3381 * assumption. Thus, there is no optimization based on string lengths for
31f05a37
KW
3382 * EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
3383 * EXACTF and EXACTFA nodes that contain the sharp s. (The reason the
3384 * assumption is wrong only in these cases is that all other non-UTF-8
3385 * folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
3386 * their expanded versions. (Again, we can't prefold sharp s to 'ss' in
3387 * EXACTF nodes because we don't know at compile time if it actually
3388 * matches 'ss' or not. For EXACTF nodes it will match iff the target
3389 * string is in UTF-8. This is in contrast to EXACTFU nodes, where it
3390 * always matches; and EXACTFA where it never does. In an EXACTFA node in
3391 * a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
3392 * problem; but in a non-UTF8 pattern, folding it to that above-Latin1
3393 * string would require the pattern to be forced into UTF-8, the overhead
3394 * of which we want to avoid. Similarly the unfolded multi-char folds in
3395 * EXACTFL nodes will match iff the locale at the time of match is a UTF-8
3396 * locale.)
098b07d5
KW
3397 *
3398 * Similarly, the code that generates tries doesn't currently handle
3399 * not-already-folded multi-char folds, and it looks like a pain to change
3400 * that. Therefore, trie generation of EXACTFA nodes with the sharp s
3401 * doesn't work. Instead, such an EXACTFA is turned into a new regnode,
3402 * EXACTFA_NO_TRIE, which the trie code knows not to handle. Most people
3403 * using /iaa matching will be doing so almost entirely with ASCII
3404 * strings, so this should rarely be encountered in practice */
1de06328 3405
fb29cc72 3406#define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
07be1b83 3407 if (PL_regkind[OP(scan)] == EXACT) \
fb29cc72 3408 join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags),NULL,depth+1)
07be1b83 3409
be8e71aa 3410STATIC U32
538e84ed 3411S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
fb29cc72 3412 UV *min_subtract, bool *unfolded_multi_char,
538e84ed
KW
3413 U32 flags,regnode *val, U32 depth)
3414{
07be1b83
YO
3415 /* Merge several consecutive EXACTish nodes into one. */
3416 regnode *n = regnext(scan);
3417 U32 stringok = 1;
3418 regnode *next = scan + NODE_SZ_STR(scan);
3419 U32 merged = 0;
3420 U32 stopnow = 0;
3421#ifdef DEBUGGING
3422 regnode *stop = scan;
72f13be8 3423 GET_RE_DEBUG_FLAGS_DECL;
f9049ba1 3424#else
d47053eb
RGS
3425 PERL_UNUSED_ARG(depth);
3426#endif
7918f24d
NC
3427
3428 PERL_ARGS_ASSERT_JOIN_EXACT;
d47053eb 3429#ifndef EXPERIMENTAL_INPLACESCAN
f9049ba1
SP
3430 PERL_UNUSED_ARG(flags);
3431 PERL_UNUSED_ARG(val);
07be1b83 3432#endif
07be1b83 3433 DEBUG_PEEP("join",scan,depth);
bb914485 3434
3f410cf6
KW
3435 /* Look through the subsequent nodes in the chain. Skip NOTHING, merge
3436 * EXACT ones that are mergeable to the current one. */
3437 while (n
3438 && (PL_regkind[OP(n)] == NOTHING
3439 || (stringok && OP(n) == OP(scan)))
07be1b83 3440 && NEXT_OFF(n)
3f410cf6
KW
3441 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
3442 {
538e84ed 3443
07be1b83
YO
3444 if (OP(n) == TAIL || n > next)
3445 stringok = 0;
3446 if (PL_regkind[OP(n)] == NOTHING) {
07be1b83
YO
3447 DEBUG_PEEP("skip:",n,depth);
3448 NEXT_OFF(scan) += NEXT_OFF(n);
3449 next = n + NODE_STEP_REGNODE;
3450#ifdef DEBUGGING
3451 if (stringok)
3452 stop = n;
3453#endif
3454 n = regnext(n);
3455 }
3456 else if (stringok) {
786e8c11 3457 const unsigned int oldl = STR_LEN(scan);
07be1b83 3458 regnode * const nnext = regnext(n);
b2230d39 3459
baa60164
KW
3460 /* XXX I (khw) kind of doubt that this works on platforms (should
3461 * Perl ever run on one) where U8_MAX is above 255 because of lots
3462 * of other assumptions */
79a81a6e 3463 /* Don't join if the sum can't fit into a single node */
b2230d39
KW
3464 if (oldl + STR_LEN(n) > U8_MAX)
3465 break;
538e84ed 3466
07be1b83 3467 DEBUG_PEEP("merg",n,depth);
07be1b83 3468 merged++;