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