This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Revert "re/pat.t: Remove TODO message on passing tests"
[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"
84#else
85# include "regcomp.h"
86#endif
a687059c 87
04e98a4d
AD
88#include "dquote_static.c"
89
d4cce5f1 90#ifdef op
11343788 91#undef op
d4cce5f1 92#endif /* op */
11343788 93
fe14fcc3 94#ifdef MSDOS
7e4e8c89 95# if defined(BUGGY_MSC6)
fe14fcc3 96 /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
7e4e8c89 97# pragma optimize("a",off)
fe14fcc3 98 /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
7e4e8c89
NC
99# pragma optimize("w",on )
100# endif /* BUGGY_MSC6 */
fe14fcc3
LW
101#endif /* MSDOS */
102
a687059c
LW
103#ifndef STATIC
104#define STATIC static
105#endif
106
830247a4 107typedef struct RExC_state_t {
e2509266 108 U32 flags; /* are we folding, multilining? */
830247a4 109 char *precomp; /* uncompiled string. */
288b8c02 110 REGEXP *rx_sv; /* The SV that is the regexp. */
f8fc2ecf
YO
111 regexp *rx; /* perl core regexp structure */
112 regexp_internal *rxi; /* internal data for regexp object pprivate field */
fac92740 113 char *start; /* Start of input for compile */
830247a4
IZ
114 char *end; /* End of input for compile */
115 char *parse; /* Input-scan pointer. */
116 I32 whilem_seen; /* number of WHILEM in this expr */
fac92740 117 regnode *emit_start; /* Start of emitted-code area */
3b57cd43 118 regnode *emit_bound; /* First regnode outside of the allocated space */
ffc61ed2 119 regnode *emit; /* Code-emit pointer; &regdummy = don't = compiling */
830247a4
IZ
120 I32 naughty; /* How bad is this pattern? */
121 I32 sawback; /* Did we see \1, ...? */
122 U32 seen;
123 I32 size; /* Code size. */
c74340f9
YO
124 I32 npar; /* Capture buffer count, (OPEN). */
125 I32 cpar; /* Capture buffer count, (CLOSE). */
e2e6a0f1 126 I32 nestroot; /* root parens we are in - used by accept */
830247a4
IZ
127 I32 extralen;
128 I32 seen_zerolen;
129 I32 seen_evals;
40d049e4
YO
130 regnode **open_parens; /* pointers to open parens */
131 regnode **close_parens; /* pointers to close parens */
132 regnode *opend; /* END node in program */
02daf0ab
YO
133 I32 utf8; /* whether the pattern is utf8 or not */
134 I32 orig_utf8; /* whether the pattern was originally in utf8 */
135 /* XXX use this for future optimisation of case
136 * where pattern must be upgraded to utf8. */
e40e74fe
KW
137 I32 uni_semantics; /* If a d charset modifier should use unicode
138 rules, even if the pattern is not in
139 utf8 */
81714fb9 140 HV *paren_names; /* Paren names */
1f1031fe 141
40d049e4
YO
142 regnode **recurse; /* Recurse regops */
143 I32 recurse_count; /* Number of recurse regops */
b57e4118 144 I32 in_lookbehind;
4624b182 145 I32 contains_locale;
830247a4
IZ
146#if ADD_TO_REGEXEC
147 char *starttry; /* -Dr: where regtry was called. */
148#define RExC_starttry (pRExC_state->starttry)
149#endif
3dab1dad 150#ifdef DEBUGGING
be8e71aa 151 const char *lastparse;
3dab1dad 152 I32 lastnum;
1f1031fe 153 AV *paren_name_list; /* idx -> name */
3dab1dad
YO
154#define RExC_lastparse (pRExC_state->lastparse)
155#define RExC_lastnum (pRExC_state->lastnum)
1f1031fe 156#define RExC_paren_name_list (pRExC_state->paren_name_list)
3dab1dad 157#endif
830247a4
IZ
158} RExC_state_t;
159
e2509266 160#define RExC_flags (pRExC_state->flags)
830247a4 161#define RExC_precomp (pRExC_state->precomp)
288b8c02 162#define RExC_rx_sv (pRExC_state->rx_sv)
830247a4 163#define RExC_rx (pRExC_state->rx)
f8fc2ecf 164#define RExC_rxi (pRExC_state->rxi)
fac92740 165#define RExC_start (pRExC_state->start)
830247a4
IZ
166#define RExC_end (pRExC_state->end)
167#define RExC_parse (pRExC_state->parse)
168#define RExC_whilem_seen (pRExC_state->whilem_seen)
7122b237
YO
169#ifdef RE_TRACK_PATTERN_OFFSETS
170#define RExC_offsets (pRExC_state->rxi->u.offsets) /* I am not like the others */
171#endif
830247a4 172#define RExC_emit (pRExC_state->emit)
fac92740 173#define RExC_emit_start (pRExC_state->emit_start)
3b57cd43 174#define RExC_emit_bound (pRExC_state->emit_bound)
830247a4
IZ
175#define RExC_naughty (pRExC_state->naughty)
176#define RExC_sawback (pRExC_state->sawback)
177#define RExC_seen (pRExC_state->seen)
178#define RExC_size (pRExC_state->size)
179#define RExC_npar (pRExC_state->npar)
e2e6a0f1 180#define RExC_nestroot (pRExC_state->nestroot)
830247a4
IZ
181#define RExC_extralen (pRExC_state->extralen)
182#define RExC_seen_zerolen (pRExC_state->seen_zerolen)
183#define RExC_seen_evals (pRExC_state->seen_evals)
1aa99e6b 184#define RExC_utf8 (pRExC_state->utf8)
e40e74fe 185#define RExC_uni_semantics (pRExC_state->uni_semantics)
02daf0ab 186#define RExC_orig_utf8 (pRExC_state->orig_utf8)
40d049e4
YO
187#define RExC_open_parens (pRExC_state->open_parens)
188#define RExC_close_parens (pRExC_state->close_parens)
189#define RExC_opend (pRExC_state->opend)
81714fb9 190#define RExC_paren_names (pRExC_state->paren_names)
40d049e4
YO
191#define RExC_recurse (pRExC_state->recurse)
192#define RExC_recurse_count (pRExC_state->recurse_count)
b57e4118 193#define RExC_in_lookbehind (pRExC_state->in_lookbehind)
4624b182 194#define RExC_contains_locale (pRExC_state->contains_locale)
830247a4 195
cde0cee5 196
a687059c
LW
197#define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
198#define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
199 ((*s) == '{' && regcurly(s)))
a687059c 200
35c8bce7
LW
201#ifdef SPSTART
202#undef SPSTART /* dratted cpp namespace... */
203#endif
a687059c
LW
204/*
205 * Flags to be passed up and down.
206 */
a687059c 207#define WORST 0 /* Worst case. */
a3b492c3 208#define HASWIDTH 0x01 /* Known to match non-null strings. */
fda99bee
KW
209
210/* Simple enough to be STAR/PLUS operand, in an EXACT node must be a single
d7b56a3c 211 * character, and if utf8, must be invariant. Note that this is not the same thing as REGNODE_SIMPLE */
fda99bee 212#define SIMPLE 0x02
a3b492c3
YO
213#define SPSTART 0x04 /* Starts with * or +. */
214#define TRYAGAIN 0x08 /* Weeded out a declaration. */
215#define POSTPONED 0x10 /* (?1),(?&name), (??{...}) or similar */
a687059c 216
3dab1dad
YO
217#define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
218
07be1b83
YO
219/* whether trie related optimizations are enabled */
220#if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
221#define TRIE_STUDY_OPT
786e8c11 222#define FULL_TRIE_STUDY
07be1b83
YO
223#define TRIE_STCLASS
224#endif
1de06328
YO
225
226
40d049e4
YO
227
228#define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
229#define PBITVAL(paren) (1 << ((paren) & 7))
230#define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
231#define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
232#define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
233
bbd61b5f
KW
234/* If not already in utf8, do a longjmp back to the beginning */
235#define UTF8_LONGJMP 42 /* Choose a value not likely to ever conflict */
236#define REQUIRE_UTF8 STMT_START { \
237 if (! UTF) JMPENV_JUMP(UTF8_LONGJMP); \
238 } STMT_END
40d049e4 239
1de06328
YO
240/* About scan_data_t.
241
242 During optimisation we recurse through the regexp program performing
243 various inplace (keyhole style) optimisations. In addition study_chunk
244 and scan_commit populate this data structure with information about
245 what strings MUST appear in the pattern. We look for the longest
3b753521 246 string that must appear at a fixed location, and we look for the
1de06328
YO
247 longest string that may appear at a floating location. So for instance
248 in the pattern:
249
250 /FOO[xX]A.*B[xX]BAR/
251
252 Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
253 strings (because they follow a .* construct). study_chunk will identify
254 both FOO and BAR as being the longest fixed and floating strings respectively.
255
256 The strings can be composites, for instance
257
258 /(f)(o)(o)/
259
260 will result in a composite fixed substring 'foo'.
261
262 For each string some basic information is maintained:
263
264 - offset or min_offset
265 This is the position the string must appear at, or not before.
266 It also implicitly (when combined with minlenp) tells us how many
3b753521
FN
267 characters must match before the string we are searching for.
268 Likewise when combined with minlenp and the length of the string it
1de06328
YO
269 tells us how many characters must appear after the string we have
270 found.
271
272 - max_offset
273 Only used for floating strings. This is the rightmost point that
3b753521 274 the string can appear at. If set to I32 max it indicates that the
1de06328
YO
275 string can occur infinitely far to the right.
276
277 - minlenp
278 A pointer to the minimum length of the pattern that the string
279 was found inside. This is important as in the case of positive
280 lookahead or positive lookbehind we can have multiple patterns
281 involved. Consider
282
283 /(?=FOO).*F/
284
285 The minimum length of the pattern overall is 3, the minimum length
286 of the lookahead part is 3, but the minimum length of the part that
287 will actually match is 1. So 'FOO's minimum length is 3, but the
288 minimum length for the F is 1. This is important as the minimum length
289 is used to determine offsets in front of and behind the string being
290 looked for. Since strings can be composites this is the length of the
486ec47a 291 pattern at the time it was committed with a scan_commit. Note that
1de06328
YO
292 the length is calculated by study_chunk, so that the minimum lengths
293 are not known until the full pattern has been compiled, thus the
294 pointer to the value.
295
296 - lookbehind
297
298 In the case of lookbehind the string being searched for can be
299 offset past the start point of the final matching string.
300 If this value was just blithely removed from the min_offset it would
301 invalidate some of the calculations for how many chars must match
302 before or after (as they are derived from min_offset and minlen and
303 the length of the string being searched for).
304 When the final pattern is compiled and the data is moved from the
305 scan_data_t structure into the regexp structure the information
306 about lookbehind is factored in, with the information that would
307 have been lost precalculated in the end_shift field for the
308 associated string.
309
310 The fields pos_min and pos_delta are used to store the minimum offset
311 and the delta to the maximum offset at the current point in the pattern.
312
313*/
2c2d71f5
JH
314
315typedef struct scan_data_t {
1de06328
YO
316 /*I32 len_min; unused */
317 /*I32 len_delta; unused */
2c2d71f5
JH
318 I32 pos_min;
319 I32 pos_delta;
320 SV *last_found;
1de06328 321 I32 last_end; /* min value, <0 unless valid. */
2c2d71f5
JH
322 I32 last_start_min;
323 I32 last_start_max;
1de06328
YO
324 SV **longest; /* Either &l_fixed, or &l_float. */
325 SV *longest_fixed; /* longest fixed string found in pattern */
326 I32 offset_fixed; /* offset where it starts */
486ec47a 327 I32 *minlen_fixed; /* pointer to the minlen relevant to the string */
1de06328
YO
328 I32 lookbehind_fixed; /* is the position of the string modfied by LB */
329 SV *longest_float; /* longest floating string found in pattern */
330 I32 offset_float_min; /* earliest point in string it can appear */
331 I32 offset_float_max; /* latest point in string it can appear */
486ec47a 332 I32 *minlen_float; /* pointer to the minlen relevant to the string */
1de06328 333 I32 lookbehind_float; /* is the position of the string modified by LB */
2c2d71f5
JH
334 I32 flags;
335 I32 whilem_c;
cb434fcc 336 I32 *last_closep;
653099ff 337 struct regnode_charclass_class *start_class;
2c2d71f5
JH
338} scan_data_t;
339
a687059c 340/*
e50aee73 341 * Forward declarations for pregcomp()'s friends.
a687059c 342 */
a0d0e21e 343
27da23d5 344static const scan_data_t zero_scan_data =
1de06328 345 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
c277df42
IZ
346
347#define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
07be1b83
YO
348#define SF_BEFORE_SEOL 0x0001
349#define SF_BEFORE_MEOL 0x0002
c277df42
IZ
350#define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
351#define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
352
09b7f37c
CB
353#ifdef NO_UNARY_PLUS
354# define SF_FIX_SHIFT_EOL (0+2)
355# define SF_FL_SHIFT_EOL (0+4)
356#else
357# define SF_FIX_SHIFT_EOL (+2)
358# define SF_FL_SHIFT_EOL (+4)
359#endif
c277df42
IZ
360
361#define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
362#define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
363
364#define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
365#define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
07be1b83
YO
366#define SF_IS_INF 0x0040
367#define SF_HAS_PAR 0x0080
368#define SF_IN_PAR 0x0100
369#define SF_HAS_EVAL 0x0200
370#define SCF_DO_SUBSTR 0x0400
653099ff
GS
371#define SCF_DO_STCLASS_AND 0x0800
372#define SCF_DO_STCLASS_OR 0x1000
373#define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
e1901655 374#define SCF_WHILEM_VISITED_POS 0x2000
c277df42 375
786e8c11 376#define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
e2e6a0f1 377#define SCF_SEEN_ACCEPT 0x8000
07be1b83 378
43fead97 379#define UTF cBOOL(RExC_utf8)
a62b1201
KW
380#define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
381#define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
cfaf538b
KW
382#define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_DEPENDS_CHARSET)
383#define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) >= REGEX_UNICODE_CHARSET)
384#define ASCII_RESTRICTED (get_regex_charset(RExC_flags) == REGEX_ASCII_RESTRICTED_CHARSET)
2f7f8cb1
KW
385#define MORE_ASCII_RESTRICTED (get_regex_charset(RExC_flags) == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
386#define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) >= REGEX_ASCII_RESTRICTED_CHARSET)
a62b1201 387
43fead97 388#define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
a0ed51b3 389
ffc61ed2 390#define OOB_UNICODE 12345678
93733859 391#define OOB_NAMEDCLASS -1
b8c5462f 392
a0ed51b3
LW
393#define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
394#define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
395
8615cb43 396
b45f050a
JF
397/* length of regex to show in messages that don't mark a position within */
398#define RegexLengthToShowInErrorMessages 127
399
400/*
401 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
402 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
403 * op/pragma/warn/regcomp.
404 */
7253e4e3
RK
405#define MARKER1 "<-- HERE" /* marker as it appears in the description */
406#define MARKER2 " <-- HERE " /* marker as it appears within the regex */
b81d288d 407
7253e4e3 408#define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
b45f050a
JF
409
410/*
411 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
412 * arg. Show regex, up to a maximum length. If it's too long, chop and add
413 * "...".
414 */
58e23c8d 415#define _FAIL(code) STMT_START { \
bfed75c6 416 const char *ellipses = ""; \
ccb2c380
MP
417 IV len = RExC_end - RExC_precomp; \
418 \
419 if (!SIZE_ONLY) \
288b8c02 420 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
ccb2c380
MP
421 if (len > RegexLengthToShowInErrorMessages) { \
422 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
423 len = RegexLengthToShowInErrorMessages - 10; \
424 ellipses = "..."; \
425 } \
58e23c8d 426 code; \
ccb2c380 427} STMT_END
8615cb43 428
58e23c8d
YO
429#define FAIL(msg) _FAIL( \
430 Perl_croak(aTHX_ "%s in regex m/%.*s%s/", \
431 msg, (int)len, RExC_precomp, ellipses))
432
433#define FAIL2(msg,arg) _FAIL( \
434 Perl_croak(aTHX_ msg " in regex m/%.*s%s/", \
435 arg, (int)len, RExC_precomp, ellipses))
436
b45f050a 437/*
b45f050a
JF
438 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
439 */
ccb2c380 440#define Simple_vFAIL(m) STMT_START { \
a28509cc 441 const IV offset = RExC_parse - RExC_precomp; \
ccb2c380
MP
442 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
443 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
444} STMT_END
b45f050a
JF
445
446/*
447 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
448 */
ccb2c380
MP
449#define vFAIL(m) STMT_START { \
450 if (!SIZE_ONLY) \
288b8c02 451 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
ccb2c380
MP
452 Simple_vFAIL(m); \
453} STMT_END
b45f050a
JF
454
455/*
456 * Like Simple_vFAIL(), but accepts two arguments.
457 */
ccb2c380 458#define Simple_vFAIL2(m,a1) STMT_START { \
a28509cc 459 const IV offset = RExC_parse - RExC_precomp; \
ccb2c380
MP
460 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, \
461 (int)offset, RExC_precomp, RExC_precomp + offset); \
462} STMT_END
b45f050a
JF
463
464/*
465 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
466 */
ccb2c380
MP
467#define vFAIL2(m,a1) STMT_START { \
468 if (!SIZE_ONLY) \
288b8c02 469 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
ccb2c380
MP
470 Simple_vFAIL2(m, a1); \
471} STMT_END
b45f050a
JF
472
473
474/*
475 * Like Simple_vFAIL(), but accepts three arguments.
476 */
ccb2c380 477#define Simple_vFAIL3(m, a1, a2) STMT_START { \
a28509cc 478 const IV offset = RExC_parse - RExC_precomp; \
ccb2c380
MP
479 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, \
480 (int)offset, RExC_precomp, RExC_precomp + offset); \
481} STMT_END
b45f050a
JF
482
483/*
484 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
485 */
ccb2c380
MP
486#define vFAIL3(m,a1,a2) STMT_START { \
487 if (!SIZE_ONLY) \
288b8c02 488 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
ccb2c380
MP
489 Simple_vFAIL3(m, a1, a2); \
490} STMT_END
b45f050a
JF
491
492/*
493 * Like Simple_vFAIL(), but accepts four arguments.
494 */
ccb2c380 495#define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
a28509cc 496 const IV offset = RExC_parse - RExC_precomp; \
ccb2c380
MP
497 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, \
498 (int)offset, RExC_precomp, RExC_precomp + offset); \
499} STMT_END
b45f050a 500
668c081a 501#define ckWARNreg(loc,m) STMT_START { \
a28509cc 502 const IV offset = loc - RExC_precomp; \
f10f4c18
NC
503 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
504 (int)offset, RExC_precomp, RExC_precomp + offset); \
ccb2c380
MP
505} STMT_END
506
668c081a 507#define ckWARNregdep(loc,m) STMT_START { \
a28509cc 508 const IV offset = loc - RExC_precomp; \
d1d15184 509 Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
f10f4c18
NC
510 m REPORT_LOCATION, \
511 (int)offset, RExC_precomp, RExC_precomp + offset); \
ccb2c380
MP
512} STMT_END
513
2335b3d3
KW
514#define ckWARN2regdep(loc,m, a1) STMT_START { \
515 const IV offset = loc - RExC_precomp; \
516 Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
517 m REPORT_LOCATION, \
518 a1, (int)offset, RExC_precomp, RExC_precomp + offset); \
519} STMT_END
520
668c081a 521#define ckWARN2reg(loc, m, a1) STMT_START { \
a28509cc 522 const IV offset = loc - RExC_precomp; \
668c081a 523 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
ccb2c380
MP
524 a1, (int)offset, RExC_precomp, RExC_precomp + offset); \
525} STMT_END
526
527#define vWARN3(loc, m, a1, a2) STMT_START { \
a28509cc 528 const IV offset = loc - RExC_precomp; \
ccb2c380
MP
529 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
530 a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
531} STMT_END
532
668c081a
NC
533#define ckWARN3reg(loc, m, a1, a2) STMT_START { \
534 const IV offset = loc - RExC_precomp; \
535 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
536 a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
537} STMT_END
538
ccb2c380 539#define vWARN4(loc, m, a1, a2, a3) STMT_START { \
a28509cc 540 const IV offset = loc - RExC_precomp; \
ccb2c380
MP
541 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
542 a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
543} STMT_END
544
668c081a
NC
545#define ckWARN4reg(loc, m, a1, a2, a3) STMT_START { \
546 const IV offset = loc - RExC_precomp; \
547 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
548 a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
549} STMT_END
550
ccb2c380 551#define vWARN5(loc, m, a1, a2, a3, a4) STMT_START { \
a28509cc 552 const IV offset = loc - RExC_precomp; \
ccb2c380
MP
553 Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
554 a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
555} STMT_END
9d1d55b5 556
8615cb43 557
cd439c50 558/* Allow for side effects in s */
ccb2c380
MP
559#define REGC(c,s) STMT_START { \
560 if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
561} STMT_END
cd439c50 562
fac92740
MJD
563/* Macros for recording node offsets. 20001227 mjd@plover.com
564 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
565 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
566 * Element 0 holds the number n.
07be1b83 567 * Position is 1 indexed.
fac92740 568 */
7122b237
YO
569#ifndef RE_TRACK_PATTERN_OFFSETS
570#define Set_Node_Offset_To_R(node,byte)
571#define Set_Node_Offset(node,byte)
572#define Set_Cur_Node_Offset
573#define Set_Node_Length_To_R(node,len)
574#define Set_Node_Length(node,len)
575#define Set_Node_Cur_Length(node)
576#define Node_Offset(n)
577#define Node_Length(n)
578#define Set_Node_Offset_Length(node,offset,len)
579#define ProgLen(ri) ri->u.proglen
580#define SetProgLen(ri,x) ri->u.proglen = x
581#else
582#define ProgLen(ri) ri->u.offsets[0]
583#define SetProgLen(ri,x) ri->u.offsets[0] = x
ccb2c380
MP
584#define Set_Node_Offset_To_R(node,byte) STMT_START { \
585 if (! SIZE_ONLY) { \
586 MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
2a49f0f5 587 __LINE__, (int)(node), (int)(byte))); \
ccb2c380 588 if((node) < 0) { \
551405c4 589 Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
ccb2c380
MP
590 } else { \
591 RExC_offsets[2*(node)-1] = (byte); \
592 } \
593 } \
594} STMT_END
595
596#define Set_Node_Offset(node,byte) \
597 Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
598#define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
599
600#define Set_Node_Length_To_R(node,len) STMT_START { \
601 if (! SIZE_ONLY) { \
602 MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
551405c4 603 __LINE__, (int)(node), (int)(len))); \
ccb2c380 604 if((node) < 0) { \
551405c4 605 Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
ccb2c380
MP
606 } else { \
607 RExC_offsets[2*(node)] = (len); \
608 } \
609 } \
610} STMT_END
611
612#define Set_Node_Length(node,len) \
613 Set_Node_Length_To_R((node)-RExC_emit_start, len)
614#define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
615#define Set_Node_Cur_Length(node) \
616 Set_Node_Length(node, RExC_parse - parse_start)
fac92740
MJD
617
618/* Get offsets and lengths */
619#define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
620#define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
621
07be1b83
YO
622#define Set_Node_Offset_Length(node,offset,len) STMT_START { \
623 Set_Node_Offset_To_R((node)-RExC_emit_start, (offset)); \
624 Set_Node_Length_To_R((node)-RExC_emit_start, (len)); \
625} STMT_END
7122b237 626#endif
07be1b83
YO
627
628#if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
629#define EXPERIMENTAL_INPLACESCAN
f427392e 630#endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
07be1b83 631
304ee84b
YO
632#define DEBUG_STUDYDATA(str,data,depth) \
633DEBUG_OPTIMISE_MORE_r(if(data){ \
1de06328 634 PerlIO_printf(Perl_debug_log, \
304ee84b
YO
635 "%*s" str "Pos:%"IVdf"/%"IVdf \
636 " Flags: 0x%"UVXf" Whilem_c: %"IVdf" Lcp: %"IVdf" %s", \
1de06328
YO
637 (int)(depth)*2, "", \
638 (IV)((data)->pos_min), \
639 (IV)((data)->pos_delta), \
304ee84b 640 (UV)((data)->flags), \
1de06328 641 (IV)((data)->whilem_c), \
304ee84b
YO
642 (IV)((data)->last_closep ? *((data)->last_closep) : -1), \
643 is_inf ? "INF " : "" \
1de06328
YO
644 ); \
645 if ((data)->last_found) \
646 PerlIO_printf(Perl_debug_log, \
647 "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
648 " %sFloat: '%s' @ %"IVdf"/%"IVdf"", \
649 SvPVX_const((data)->last_found), \
650 (IV)((data)->last_end), \
651 (IV)((data)->last_start_min), \
652 (IV)((data)->last_start_max), \
653 ((data)->longest && \
654 (data)->longest==&((data)->longest_fixed)) ? "*" : "", \
655 SvPVX_const((data)->longest_fixed), \
656 (IV)((data)->offset_fixed), \
657 ((data)->longest && \
658 (data)->longest==&((data)->longest_float)) ? "*" : "", \
659 SvPVX_const((data)->longest_float), \
660 (IV)((data)->offset_float_min), \
661 (IV)((data)->offset_float_max) \
662 ); \
663 PerlIO_printf(Perl_debug_log,"\n"); \
664});
665
acfe0abc 666static void clear_re(pTHX_ void *r);
4327152a 667
653099ff 668/* Mark that we cannot extend a found fixed substring at this point.
786e8c11 669 Update the longest found anchored substring and the longest found
653099ff
GS
670 floating substrings if needed. */
671
4327152a 672STATIC void
304ee84b 673S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp, int is_inf)
c277df42 674{
e1ec3a88
AL
675 const STRLEN l = CHR_SVLEN(data->last_found);
676 const STRLEN old_l = CHR_SVLEN(*data->longest);
1de06328 677 GET_RE_DEBUG_FLAGS_DECL;
b81d288d 678
7918f24d
NC
679 PERL_ARGS_ASSERT_SCAN_COMMIT;
680
c277df42 681 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
6b43b216 682 SvSetMagicSV(*data->longest, data->last_found);
c277df42
IZ
683 if (*data->longest == data->longest_fixed) {
684 data->offset_fixed = l ? data->last_start_min : data->pos_min;
685 if (data->flags & SF_BEFORE_EOL)
b81d288d 686 data->flags
c277df42
IZ
687 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
688 else
689 data->flags &= ~SF_FIX_BEFORE_EOL;
1de06328
YO
690 data->minlen_fixed=minlenp;
691 data->lookbehind_fixed=0;
a0ed51b3 692 }
304ee84b 693 else { /* *data->longest == data->longest_float */
c277df42 694 data->offset_float_min = l ? data->last_start_min : data->pos_min;
b81d288d
AB
695 data->offset_float_max = (l
696 ? data->last_start_max
c277df42 697 : data->pos_min + data->pos_delta);
304ee84b 698 if (is_inf || (U32)data->offset_float_max > (U32)I32_MAX)
9051bda5 699 data->offset_float_max = I32_MAX;
c277df42 700 if (data->flags & SF_BEFORE_EOL)
b81d288d 701 data->flags
c277df42
IZ
702 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
703 else
704 data->flags &= ~SF_FL_BEFORE_EOL;
1de06328
YO
705 data->minlen_float=minlenp;
706 data->lookbehind_float=0;
c277df42
IZ
707 }
708 }
709 SvCUR_set(data->last_found, 0);
0eda9292 710 {
a28509cc 711 SV * const sv = data->last_found;
097eb12c
AL
712 if (SvUTF8(sv) && SvMAGICAL(sv)) {
713 MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
714 if (mg)
715 mg->mg_len = 0;
716 }
0eda9292 717 }
c277df42
IZ
718 data->last_end = -1;
719 data->flags &= ~SF_BEFORE_EOL;
bcdf7404 720 DEBUG_STUDYDATA("commit: ",data,0);
c277df42
IZ
721}
722
653099ff
GS
723/* Can match anything (initialization) */
724STATIC void
2f88b857 725S_cl_anything(struct regnode_charclass_class *cl)
653099ff 726{
7918f24d
NC
727 PERL_ARGS_ASSERT_CL_ANYTHING;
728
f8bef550 729 ANYOF_BITMAP_SETALL(cl);
6b1ea9dd 730 ANYOF_CLASS_ZERO(cl); /* all bits set, so class is irrelevant */
cf34198e 731 cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL|ANYOF_LOC_NONBITMAP_FOLD|ANYOF_NON_UTF8_LATIN1_ALL|ANYOF_LOCALE;
75950e1c
KW
732 /* The above line set locale which given the current logic may not get
733 * cleared even if no locale is in the regex, which may lead to false
734 * positives; see the commit message */
653099ff
GS
735}
736
737/* Can match anything (initialization) */
738STATIC int
5f66b61c 739S_cl_is_anything(const struct regnode_charclass_class *cl)
653099ff
GS
740{
741 int value;
742
7918f24d
NC
743 PERL_ARGS_ASSERT_CL_IS_ANYTHING;
744
aaa51d5e 745 for (value = 0; value <= ANYOF_MAX; value += 2)
653099ff
GS
746 if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
747 return 1;
1aa99e6b
IH
748 if (!(cl->flags & ANYOF_UNICODE_ALL))
749 return 0;
10edeb5d 750 if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
f8bef550 751 return 0;
653099ff
GS
752 return 1;
753}
754
755/* Can match anything (initialization) */
756STATIC void
e755fd73 757S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
653099ff 758{
7918f24d
NC
759 PERL_ARGS_ASSERT_CL_INIT;
760
8ecf7187 761 Zero(cl, 1, struct regnode_charclass_class);
653099ff 762 cl->type = ANYOF;
2f88b857 763 cl_anything(cl);
1411dba4 764 ARG_SET(cl, ANYOF_NONBITMAP_EMPTY);
653099ff
GS
765}
766
1051e1c4
KW
767/* These two functions currently do the exact same thing */
768#define cl_init_zero S_cl_init
653099ff
GS
769
770/* 'And' a given class with another one. Can create false positives */
58b5ba03 771/* cl should not be inverted */
653099ff 772STATIC void
5f66b61c 773S_cl_and(struct regnode_charclass_class *cl,
a28509cc 774 const struct regnode_charclass_class *and_with)
653099ff 775{
7918f24d 776 PERL_ARGS_ASSERT_CL_AND;
40d049e4
YO
777
778 assert(and_with->type == ANYOF);
1e6ade67 779
c6b76537 780 /* I (khw) am not sure all these restrictions are necessary XXX */
1e6ade67
KW
781 if (!(ANYOF_CLASS_TEST_ANY_SET(and_with))
782 && !(ANYOF_CLASS_TEST_ANY_SET(cl))
653099ff 783 && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
39065660
KW
784 && !(and_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
785 && !(cl->flags & ANYOF_LOC_NONBITMAP_FOLD)) {
653099ff
GS
786 int i;
787
788 if (and_with->flags & ANYOF_INVERT)
789 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
790 cl->bitmap[i] &= ~and_with->bitmap[i];
791 else
792 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
793 cl->bitmap[i] &= and_with->bitmap[i];
794 } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
1aa99e6b 795
c6b76537 796 if (and_with->flags & ANYOF_INVERT) {
8951c461 797
c6b76537
KW
798 /* Here, the and'ed node is inverted. Get the AND of the flags that
799 * aren't affected by the inversion. Those that are affected are
800 * handled individually below */
801 U8 affected_flags = cl->flags & ~INVERSION_UNAFFECTED_FLAGS;
802 cl->flags &= (and_with->flags & INVERSION_UNAFFECTED_FLAGS);
803 cl->flags |= affected_flags;
804
805 /* We currently don't know how to deal with things that aren't in the
806 * bitmap, but we know that the intersection is no greater than what
807 * is already in cl, so let there be false positives that get sorted
808 * out after the synthetic start class succeeds, and the node is
809 * matched for real. */
810
811 /* The inversion of these two flags indicate that the resulting
812 * intersection doesn't have them */
813 if (and_with->flags & ANYOF_UNICODE_ALL) {
4713bfe1
KW
814 cl->flags &= ~ANYOF_UNICODE_ALL;
815 }
c6b76537
KW
816 if (and_with->flags & ANYOF_NON_UTF8_LATIN1_ALL) {
817 cl->flags &= ~ANYOF_NON_UTF8_LATIN1_ALL;
137165a6 818 }
1aa99e6b 819 }
c6b76537 820 else { /* and'd node is not inverted */
137165a6 821 if (! ANYOF_NONBITMAP(and_with)) {
c6b76537
KW
822
823 /* Here 'and_with' doesn't match anything outside the bitmap
824 * (except possibly ANYOF_UNICODE_ALL), which means the
825 * intersection can't either, except for ANYOF_UNICODE_ALL, in
826 * which case we don't know what the intersection is, but it's no
827 * greater than what cl already has, so can just leave it alone,
828 * with possible false positives */
829 if (! (and_with->flags & ANYOF_UNICODE_ALL)) {
830 ARG_SET(cl, ANYOF_NONBITMAP_EMPTY);
871d0d1a 831 cl->flags &= ~ANYOF_NONBITMAP_NON_UTF8;
c6b76537 832 }
137165a6 833 }
c6b76537
KW
834 else if (! ANYOF_NONBITMAP(cl)) {
835
836 /* Here, 'and_with' does match something outside the bitmap, and cl
837 * doesn't have a list of things to match outside the bitmap. If
838 * cl can match all code points above 255, the intersection will
839 * be those above-255 code points that 'and_with' matches. There
840 * may be false positives from code points in 'and_with' that are
841 * outside the bitmap but below 256, but those get sorted out
842 * after the synthetic start class succeeds). If cl can't match
843 * all Unicode code points, it means here that it can't match *
844 * anything outside the bitmap, so we leave the bitmap empty */
845 if (cl->flags & ANYOF_UNICODE_ALL) {
846 ARG_SET(cl, ARG(and_with));
847 }
848 }
849 else {
850 /* Here, both 'and_with' and cl match something outside the
851 * bitmap. Currently we do not do the intersection, so just match
852 * whatever cl had at the beginning. */
853 }
854
855
856 /* Take the intersection of the two sets of flags */
857 cl->flags &= and_with->flags;
137165a6 858 }
653099ff
GS
859}
860
861/* 'OR' a given class with another one. Can create false positives */
58b5ba03 862/* cl should not be inverted */
653099ff 863STATIC void
aa19b56b 864S_cl_or(struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
653099ff 865{
7918f24d
NC
866 PERL_ARGS_ASSERT_CL_OR;
867
653099ff 868 if (or_with->flags & ANYOF_INVERT) {
c6b76537
KW
869
870 /* Here, the or'd node is to be inverted. This means we take the
871 * complement of everything not in the bitmap, but currently we don't
872 * know what that is, so give up and match anything */
873 if (ANYOF_NONBITMAP(or_with)) {
2f88b857 874 cl_anything(cl);
c6b76537 875 }
653099ff
GS
876 /* We do not use
877 * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
878 * <= (B1 | !B2) | (CL1 | !CL2)
879 * which is wasteful if CL2 is small, but we ignore CL2:
880 * (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
881 * XXXX Can we handle case-fold? Unclear:
882 * (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
883 * (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
884 */
c6b76537 885 else if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
39065660
KW
886 && !(or_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
887 && !(cl->flags & ANYOF_LOC_NONBITMAP_FOLD) ) {
653099ff
GS
888 int i;
889
890 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
891 cl->bitmap[i] |= ~or_with->bitmap[i];
892 } /* XXXX: logic is complicated otherwise */
893 else {
2f88b857 894 cl_anything(cl);
653099ff 895 }
c6b76537
KW
896
897 /* And, we can just take the union of the flags that aren't affected
898 * by the inversion */
899 cl->flags |= or_with->flags & INVERSION_UNAFFECTED_FLAGS;
900
901 /* For the remaining flags:
902 ANYOF_UNICODE_ALL and inverted means to not match anything above
903 255, which means that the union with cl should just be
904 what cl has in it, so can ignore this flag
905 ANYOF_NON_UTF8_LATIN1_ALL and inverted means if not utf8 and ord
906 is 127-255 to match them, but then invert that, so the
907 union with cl should just be what cl has in it, so can
908 ignore this flag
909 */
910 } else { /* 'or_with' is not inverted */
653099ff
GS
911 /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
912 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
39065660
KW
913 && (!(or_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
914 || (cl->flags & ANYOF_LOC_NONBITMAP_FOLD)) ) {
653099ff
GS
915 int i;
916
917 /* OR char bitmap and class bitmap separately */
918 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
919 cl->bitmap[i] |= or_with->bitmap[i];
1e6ade67 920 if (ANYOF_CLASS_TEST_ANY_SET(or_with)) {
653099ff
GS
921 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
922 cl->classflags[i] |= or_with->classflags[i];
923 cl->flags |= ANYOF_CLASS;
924 }
925 }
926 else { /* XXXX: logic is complicated, leave it along for a moment. */
2f88b857 927 cl_anything(cl);
653099ff 928 }
9826f543 929
c6b76537
KW
930 /* Take the union */
931 cl->flags |= or_with->flags;
932
933 if (ANYOF_NONBITMAP(or_with)) {
934
935 /* Use the added node's outside-the-bit-map match if there isn't a
936 * conflict. If there is a conflict (both nodes match something
937 * outside the bitmap, but what they match outside is not the same
938 * pointer, and hence not easily compared until XXX we extend
939 * inversion lists this far), give up and allow the start class to
940 * match everything outside the bitmap */
941 if (! ANYOF_NONBITMAP(cl)) {
942 ARG_SET(cl, ARG(or_with));
943 }
944 else if (ARG(cl) != ARG(or_with)) {
945 cl->flags |= ANYOF_UNICODE_ALL;
946 }
947 }
1aa99e6b 948 }
653099ff
GS
949}
950
a3621e74
YO
951#define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
952#define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
953#define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
954#define TRIE_LIST_USED(idx) ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
955
3dab1dad
YO
956
957#ifdef DEBUGGING
07be1b83 958/*
2b8b4781
NC
959 dump_trie(trie,widecharmap,revcharmap)
960 dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
961 dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
3dab1dad
YO
962
963 These routines dump out a trie in a somewhat readable format.
07be1b83
YO
964 The _interim_ variants are used for debugging the interim
965 tables that are used to generate the final compressed
966 representation which is what dump_trie expects.
967
486ec47a 968 Part of the reason for their existence is to provide a form
3dab1dad 969 of documentation as to how the different representations function.
07be1b83
YO
970
971*/
3dab1dad
YO
972
973/*
3dab1dad
YO
974 Dumps the final compressed table form of the trie to Perl_debug_log.
975 Used for debugging make_trie().
976*/
b9a59e08 977
3dab1dad 978STATIC void
2b8b4781
NC
979S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
980 AV *revcharmap, U32 depth)
3dab1dad
YO
981{
982 U32 state;
ab3bbdeb 983 SV *sv=sv_newmortal();
55eed653 984 int colwidth= widecharmap ? 6 : 4;
2e64971a 985 U16 word;
3dab1dad
YO
986 GET_RE_DEBUG_FLAGS_DECL;
987
7918f24d 988 PERL_ARGS_ASSERT_DUMP_TRIE;
ab3bbdeb 989
3dab1dad
YO
990 PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
991 (int)depth * 2 + 2,"",
992 "Match","Base","Ofs" );
993
994 for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2b8b4781 995 SV ** const tmp = av_fetch( revcharmap, state, 0);
3dab1dad 996 if ( tmp ) {
ab3bbdeb
YO
997 PerlIO_printf( Perl_debug_log, "%*s",
998 colwidth,
ddc5bc0f 999 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
ab3bbdeb
YO
1000 PL_colors[0], PL_colors[1],
1001 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1002 PERL_PV_ESCAPE_FIRSTCHAR
1003 )
1004 );
3dab1dad
YO
1005 }
1006 }
1007 PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
1008 (int)depth * 2 + 2,"");
1009
1010 for( state = 0 ; state < trie->uniquecharcount ; state++ )
ab3bbdeb 1011 PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
3dab1dad
YO
1012 PerlIO_printf( Perl_debug_log, "\n");
1013
1e2e3d02 1014 for( state = 1 ; state < trie->statecount ; state++ ) {
be8e71aa 1015 const U32 base = trie->states[ state ].trans.base;
3dab1dad
YO
1016
1017 PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
1018
1019 if ( trie->states[ state ].wordnum ) {
1020 PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
1021 } else {
1022 PerlIO_printf( Perl_debug_log, "%6s", "" );
1023 }
1024
1025 PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
1026
1027 if ( base ) {
1028 U32 ofs = 0;
1029
1030 while( ( base + ofs < trie->uniquecharcount ) ||
1031 ( base + ofs - trie->uniquecharcount < trie->lasttrans
1032 && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
1033 ofs++;
1034
1035 PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
1036
1037 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1038 if ( ( base + ofs >= trie->uniquecharcount ) &&
1039 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
1040 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
1041 {
ab3bbdeb
YO
1042 PerlIO_printf( Perl_debug_log, "%*"UVXf,
1043 colwidth,
3dab1dad
YO
1044 (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
1045 } else {
ab3bbdeb 1046 PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
3dab1dad
YO
1047 }
1048 }
1049
1050 PerlIO_printf( Perl_debug_log, "]");
1051
1052 }
1053 PerlIO_printf( Perl_debug_log, "\n" );
1054 }
2e64971a
DM
1055 PerlIO_printf(Perl_debug_log, "%*sword_info N:(prev,len)=", (int)depth*2, "");
1056 for (word=1; word <= trie->wordcount; word++) {
1057 PerlIO_printf(Perl_debug_log, " %d:(%d,%d)",
1058 (int)word, (int)(trie->wordinfo[word].prev),
1059 (int)(trie->wordinfo[word].len));
1060 }
1061 PerlIO_printf(Perl_debug_log, "\n" );
3dab1dad
YO
1062}
1063/*
3dab1dad
YO
1064 Dumps a fully constructed but uncompressed trie in list form.
1065 List tries normally only are used for construction when the number of
1066 possible chars (trie->uniquecharcount) is very high.
1067 Used for debugging make_trie().
1068*/
1069STATIC void
55eed653 1070S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2b8b4781
NC
1071 HV *widecharmap, AV *revcharmap, U32 next_alloc,
1072 U32 depth)
3dab1dad
YO
1073{
1074 U32 state;
ab3bbdeb 1075 SV *sv=sv_newmortal();
55eed653 1076 int colwidth= widecharmap ? 6 : 4;
3dab1dad 1077 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
1078
1079 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
1080
3dab1dad 1081 /* print out the table precompression. */
ab3bbdeb
YO
1082 PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
1083 (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
1084 "------:-----+-----------------\n" );
3dab1dad
YO
1085
1086 for( state=1 ; state < next_alloc ; state ++ ) {
1087 U16 charid;
1088
ab3bbdeb 1089 PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
3dab1dad
YO
1090 (int)depth * 2 + 2,"", (UV)state );
1091 if ( ! trie->states[ state ].wordnum ) {
1092 PerlIO_printf( Perl_debug_log, "%5s| ","");
1093 } else {
1094 PerlIO_printf( Perl_debug_log, "W%4x| ",
1095 trie->states[ state ].wordnum
1096 );
1097 }
1098 for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2b8b4781 1099 SV ** const tmp = av_fetch( revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
ab3bbdeb
YO
1100 if ( tmp ) {
1101 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
1102 colwidth,
ddc5bc0f 1103 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
ab3bbdeb
YO
1104 PL_colors[0], PL_colors[1],
1105 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1106 PERL_PV_ESCAPE_FIRSTCHAR
1107 ) ,
1e2e3d02
YO
1108 TRIE_LIST_ITEM(state,charid).forid,
1109 (UV)TRIE_LIST_ITEM(state,charid).newstate
1110 );
1111 if (!(charid % 10))
664e119d
RGS
1112 PerlIO_printf(Perl_debug_log, "\n%*s| ",
1113 (int)((depth * 2) + 14), "");
1e2e3d02 1114 }
ab3bbdeb
YO
1115 }
1116 PerlIO_printf( Perl_debug_log, "\n");
3dab1dad
YO
1117 }
1118}
1119
1120/*
3dab1dad
YO
1121 Dumps a fully constructed but uncompressed trie in table form.
1122 This is the normal DFA style state transition table, with a few
1123 twists to facilitate compression later.
1124 Used for debugging make_trie().
1125*/
1126STATIC void
55eed653 1127S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2b8b4781
NC
1128 HV *widecharmap, AV *revcharmap, U32 next_alloc,
1129 U32 depth)
3dab1dad
YO
1130{
1131 U32 state;
1132 U16 charid;
ab3bbdeb 1133 SV *sv=sv_newmortal();
55eed653 1134 int colwidth= widecharmap ? 6 : 4;
3dab1dad 1135 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
1136
1137 PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
3dab1dad
YO
1138
1139 /*
1140 print out the table precompression so that we can do a visual check
1141 that they are identical.
1142 */
1143
1144 PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
1145
1146 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2b8b4781 1147 SV ** const tmp = av_fetch( revcharmap, charid, 0);
3dab1dad 1148 if ( tmp ) {
ab3bbdeb
YO
1149 PerlIO_printf( Perl_debug_log, "%*s",
1150 colwidth,
ddc5bc0f 1151 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
ab3bbdeb
YO
1152 PL_colors[0], PL_colors[1],
1153 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1154 PERL_PV_ESCAPE_FIRSTCHAR
1155 )
1156 );
3dab1dad
YO
1157 }
1158 }
1159
1160 PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
1161
1162 for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
ab3bbdeb 1163 PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
3dab1dad
YO
1164 }
1165
1166 PerlIO_printf( Perl_debug_log, "\n" );
1167
1168 for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
1169
1170 PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
1171 (int)depth * 2 + 2,"",
1172 (UV)TRIE_NODENUM( state ) );
1173
1174 for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
ab3bbdeb
YO
1175 UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
1176 if (v)
1177 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
1178 else
1179 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
3dab1dad
YO
1180 }
1181 if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
1182 PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
1183 } else {
1184 PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
1185 trie->states[ TRIE_NODENUM( state ) ].wordnum );
1186 }
1187 }
07be1b83 1188}
3dab1dad
YO
1189
1190#endif
1191
2e64971a 1192
786e8c11
YO
1193/* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1194 startbranch: the first branch in the whole branch sequence
1195 first : start branch of sequence of branch-exact nodes.
1196 May be the same as startbranch
1197 last : Thing following the last branch.
1198 May be the same as tail.
1199 tail : item following the branch sequence
1200 count : words in the sequence
1201 flags : currently the OP() type we will be building one of /EXACT(|F|Fl)/
1202 depth : indent depth
3dab1dad 1203
786e8c11 1204Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
07be1b83 1205
786e8c11
YO
1206A trie is an N'ary tree where the branches are determined by digital
1207decomposition of the key. IE, at the root node you look up the 1st character and
1208follow that branch repeat until you find the end of the branches. Nodes can be
1209marked as "accepting" meaning they represent a complete word. Eg:
07be1b83 1210
786e8c11 1211 /he|she|his|hers/
72f13be8 1212
786e8c11
YO
1213would convert into the following structure. Numbers represent states, letters
1214following numbers represent valid transitions on the letter from that state, if
1215the number is in square brackets it represents an accepting state, otherwise it
1216will be in parenthesis.
07be1b83 1217
786e8c11
YO
1218 +-h->+-e->[3]-+-r->(8)-+-s->[9]
1219 | |
1220 | (2)
1221 | |
1222 (1) +-i->(6)-+-s->[7]
1223 |
1224 +-s->(3)-+-h->(4)-+-e->[5]
07be1b83 1225
786e8c11
YO
1226 Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1227
1228This shows that when matching against the string 'hers' we will begin at state 1
1229read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1230then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1231is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1232single traverse. We store a mapping from accepting to state to which word was
1233matched, and then when we have multiple possibilities we try to complete the
1234rest of the regex in the order in which they occured in the alternation.
1235
1236The only prior NFA like behaviour that would be changed by the TRIE support is
1237the silent ignoring of duplicate alternations which are of the form:
1238
1239 / (DUPE|DUPE) X? (?{ ... }) Y /x
1240
4b714af6 1241Thus EVAL blocks following a trie may be called a different number of times with
786e8c11 1242and without the optimisation. With the optimisations dupes will be silently
486ec47a 1243ignored. This inconsistent behaviour of EVAL type nodes is well established as
786e8c11
YO
1244the following demonstrates:
1245
1246 'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1247
1248which prints out 'word' three times, but
1249
1250 'words'=~/(word|word|word)(?{ print $1 })S/
1251
1252which doesnt print it out at all. This is due to other optimisations kicking in.
1253
1254Example of what happens on a structural level:
1255
486ec47a 1256The regexp /(ac|ad|ab)+/ will produce the following debug output:
786e8c11
YO
1257
1258 1: CURLYM[1] {1,32767}(18)
1259 5: BRANCH(8)
1260 6: EXACT <ac>(16)
1261 8: BRANCH(11)
1262 9: EXACT <ad>(16)
1263 11: BRANCH(14)
1264 12: EXACT <ab>(16)
1265 16: SUCCEED(0)
1266 17: NOTHING(18)
1267 18: END(0)
1268
1269This would be optimizable with startbranch=5, first=5, last=16, tail=16
1270and should turn into:
1271
1272 1: CURLYM[1] {1,32767}(18)
1273 5: TRIE(16)
1274 [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1275 <ac>
1276 <ad>
1277 <ab>
1278 16: SUCCEED(0)
1279 17: NOTHING(18)
1280 18: END(0)
1281
1282Cases where tail != last would be like /(?foo|bar)baz/:
1283
1284 1: BRANCH(4)
1285 2: EXACT <foo>(8)
1286 4: BRANCH(7)
1287 5: EXACT <bar>(8)
1288 7: TAIL(8)
1289 8: EXACT <baz>(10)
1290 10: END(0)
1291
1292which would be optimizable with startbranch=1, first=1, last=7, tail=8
1293and would end up looking like:
1294
1295 1: TRIE(8)
1296 [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1297 <foo>
1298 <bar>
1299 7: TAIL(8)
1300 8: EXACT <baz>(10)
1301 10: END(0)
1302
1303 d = uvuni_to_utf8_flags(d, uv, 0);
1304
1305is the recommended Unicode-aware way of saying
1306
1307 *(d++) = uv;
1308*/
1309
1e2e3d02 1310#define TRIE_STORE_REVCHAR \
786e8c11 1311 STMT_START { \
73031816
NC
1312 if (UTF) { \
1313 SV *zlopp = newSV(2); \
88c9ea1e
CB
1314 unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
1315 unsigned const char *const kapow = uvuni_to_utf8(flrbbbbb, uvc & 0xFF); \
73031816
NC
1316 SvCUR_set(zlopp, kapow - flrbbbbb); \
1317 SvPOK_on(zlopp); \
1318 SvUTF8_on(zlopp); \
1319 av_push(revcharmap, zlopp); \
1320 } else { \
6bdeddd2 1321 char ooooff = (char)uvc; \
73031816
NC
1322 av_push(revcharmap, newSVpvn(&ooooff, 1)); \
1323 } \
1324 } STMT_END
786e8c11
YO
1325
1326#define TRIE_READ_CHAR STMT_START { \
1327 wordlen++; \
1328 if ( UTF ) { \
1329 if ( folder ) { \
1330 if ( foldlen > 0 ) { \
1331 uvc = utf8n_to_uvuni( scan, UTF8_MAXLEN, &len, uniflags ); \
1332 foldlen -= len; \
1333 scan += len; \
1334 len = 0; \
1335 } else { \
1336 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1337 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1338 foldlen -= UNISKIP( uvc ); \
1339 scan = foldbuf + UNISKIP( uvc ); \
1340 } \
1341 } else { \
1342 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1343 } \
1344 } else { \
1345 uvc = (U32)*uc; \
1346 len = 1; \
1347 } \
1348} STMT_END
1349
1350
1351
1352#define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
1353 if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
f9003953
NC
1354 U32 ging = TRIE_LIST_LEN( state ) *= 2; \
1355 Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
786e8c11
YO
1356 } \
1357 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
1358 TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
1359 TRIE_LIST_CUR( state )++; \
1360} STMT_END
07be1b83 1361
786e8c11
YO
1362#define TRIE_LIST_NEW(state) STMT_START { \
1363 Newxz( trie->states[ state ].trans.list, \
1364 4, reg_trie_trans_le ); \
1365 TRIE_LIST_CUR( state ) = 1; \
1366 TRIE_LIST_LEN( state ) = 4; \
1367} STMT_END
07be1b83 1368
786e8c11
YO
1369#define TRIE_HANDLE_WORD(state) STMT_START { \
1370 U16 dupe= trie->states[ state ].wordnum; \
1371 regnode * const noper_next = regnext( noper ); \
1372 \
786e8c11
YO
1373 DEBUG_r({ \
1374 /* store the word for dumping */ \
1375 SV* tmp; \
1376 if (OP(noper) != NOTHING) \
740cce10 1377 tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
786e8c11 1378 else \
740cce10 1379 tmp = newSVpvn_utf8( "", 0, UTF ); \
2b8b4781 1380 av_push( trie_words, tmp ); \
786e8c11
YO
1381 }); \
1382 \
1383 curword++; \
2e64971a
DM
1384 trie->wordinfo[curword].prev = 0; \
1385 trie->wordinfo[curword].len = wordlen; \
1386 trie->wordinfo[curword].accept = state; \
786e8c11
YO
1387 \
1388 if ( noper_next < tail ) { \
1389 if (!trie->jump) \
c944940b 1390 trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, sizeof(U16) ); \
7f69552c 1391 trie->jump[curword] = (U16)(noper_next - convert); \
786e8c11
YO
1392 if (!jumper) \
1393 jumper = noper_next; \
1394 if (!nextbranch) \
1395 nextbranch= regnext(cur); \
1396 } \
1397 \
1398 if ( dupe ) { \
2e64971a
DM
1399 /* It's a dupe. Pre-insert into the wordinfo[].prev */\
1400 /* chain, so that when the bits of chain are later */\
1401 /* linked together, the dups appear in the chain */\
1402 trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
1403 trie->wordinfo[dupe].prev = curword; \
786e8c11
YO
1404 } else { \
1405 /* we haven't inserted this word yet. */ \
1406 trie->states[ state ].wordnum = curword; \
1407 } \
1408} STMT_END
07be1b83 1409
3dab1dad 1410
786e8c11
YO
1411#define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
1412 ( ( base + charid >= ucharcount \
1413 && base + charid < ubound \
1414 && state == trie->trans[ base - ucharcount + charid ].check \
1415 && trie->trans[ base - ucharcount + charid ].next ) \
1416 ? trie->trans[ base - ucharcount + charid ].next \
1417 : ( state==1 ? special : 0 ) \
1418 )
3dab1dad 1419
786e8c11
YO
1420#define MADE_TRIE 1
1421#define MADE_JUMP_TRIE 2
1422#define MADE_EXACT_TRIE 4
3dab1dad 1423
a3621e74 1424STATIC I32
786e8c11 1425S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
a3621e74 1426{
27da23d5 1427 dVAR;
a3621e74
YO
1428 /* first pass, loop through and scan words */
1429 reg_trie_data *trie;
55eed653 1430 HV *widecharmap = NULL;
2b8b4781 1431 AV *revcharmap = newAV();
a3621e74 1432 regnode *cur;
9f7f3913 1433 const U32 uniflags = UTF8_ALLOW_DEFAULT;
a3621e74
YO
1434 STRLEN len = 0;
1435 UV uvc = 0;
1436 U16 curword = 0;
1437 U32 next_alloc = 0;
786e8c11
YO
1438 regnode *jumper = NULL;
1439 regnode *nextbranch = NULL;
7f69552c 1440 regnode *convert = NULL;
2e64971a 1441 U32 *prev_states; /* temp array mapping each state to previous one */
a3621e74 1442 /* we just use folder as a flag in utf8 */
1e696034 1443 const U8 * folder = NULL;
a3621e74 1444
2b8b4781
NC
1445#ifdef DEBUGGING
1446 const U32 data_slot = add_data( pRExC_state, 4, "tuuu" );
1447 AV *trie_words = NULL;
1448 /* along with revcharmap, this only used during construction but both are
1449 * useful during debugging so we store them in the struct when debugging.
8e11feef 1450 */
2b8b4781
NC
1451#else
1452 const U32 data_slot = add_data( pRExC_state, 2, "tu" );
3dab1dad 1453 STRLEN trie_charcount=0;
3dab1dad 1454#endif
2b8b4781 1455 SV *re_trie_maxbuff;
a3621e74 1456 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
1457
1458 PERL_ARGS_ASSERT_MAKE_TRIE;
72f13be8
YO
1459#ifndef DEBUGGING
1460 PERL_UNUSED_ARG(depth);
1461#endif
a3621e74 1462
1e696034 1463 switch (flags) {
2f7f8cb1 1464 case EXACTFA:
1e696034
KW
1465 case EXACTFU: folder = PL_fold_latin1; break;
1466 case EXACTF: folder = PL_fold; break;
1467 case EXACTFL: folder = PL_fold_locale; break;
1468 }
1469
c944940b 1470 trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
a3621e74 1471 trie->refcount = 1;
3dab1dad 1472 trie->startstate = 1;
786e8c11 1473 trie->wordcount = word_count;
f8fc2ecf 1474 RExC_rxi->data->data[ data_slot ] = (void*)trie;
c944940b 1475 trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
3dab1dad 1476 if (!(UTF && folder))
c944940b 1477 trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2e64971a
DM
1478 trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
1479 trie->wordcount+1, sizeof(reg_trie_wordinfo));
1480
a3621e74 1481 DEBUG_r({
2b8b4781 1482 trie_words = newAV();
a3621e74 1483 });
a3621e74 1484
0111c4fd 1485 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
a3621e74 1486 if (!SvIOK(re_trie_maxbuff)) {
0111c4fd 1487 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
a3621e74 1488 }
3dab1dad
YO
1489 DEBUG_OPTIMISE_r({
1490 PerlIO_printf( Perl_debug_log,
786e8c11 1491 "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
3dab1dad
YO
1492 (int)depth * 2 + 2, "",
1493 REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
786e8c11 1494 REG_NODE_NUM(last), REG_NODE_NUM(tail),
85c3142d 1495 (int)depth);
3dab1dad 1496 });
7f69552c
YO
1497
1498 /* Find the node we are going to overwrite */
1499 if ( first == startbranch && OP( last ) != BRANCH ) {
1500 /* whole branch chain */
1501 convert = first;
1502 } else {
1503 /* branch sub-chain */
1504 convert = NEXTOPER( first );
1505 }
1506
a3621e74
YO
1507 /* -- First loop and Setup --
1508
1509 We first traverse the branches and scan each word to determine if it
1510 contains widechars, and how many unique chars there are, this is
1511 important as we have to build a table with at least as many columns as we
1512 have unique chars.
1513
1514 We use an array of integers to represent the character codes 0..255
38a44b82 1515 (trie->charmap) and we use a an HV* to store Unicode characters. We use the
a3621e74
YO
1516 native representation of the character value as the key and IV's for the
1517 coded index.
1518
1519 *TODO* If we keep track of how many times each character is used we can
1520 remap the columns so that the table compression later on is more
3b753521 1521 efficient in terms of memory by ensuring the most common value is in the
a3621e74
YO
1522 middle and the least common are on the outside. IMO this would be better
1523 than a most to least common mapping as theres a decent chance the most
1524 common letter will share a node with the least common, meaning the node
486ec47a 1525 will not be compressible. With a middle is most common approach the worst
a3621e74
YO
1526 case is when we have the least common nodes twice.
1527
1528 */
1529
a3621e74 1530 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
c445ea15 1531 regnode * const noper = NEXTOPER( cur );
e1ec3a88 1532 const U8 *uc = (U8*)STRING( noper );
a28509cc 1533 const U8 * const e = uc + STR_LEN( noper );
a3621e74
YO
1534 STRLEN foldlen = 0;
1535 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2af232bd 1536 const U8 *scan = (U8*)NULL;
07be1b83 1537 U32 wordlen = 0; /* required init */
02daf0ab
YO
1538 STRLEN chars = 0;
1539 bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the bitmap?*/
a3621e74 1540
3dab1dad
YO
1541 if (OP(noper) == NOTHING) {
1542 trie->minlen= 0;
1543 continue;
1544 }
02daf0ab
YO
1545 if ( set_bit ) /* bitmap only alloced when !(UTF&&Folding) */
1546 TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
1547 regardless of encoding */
1548
a3621e74 1549 for ( ; uc < e ; uc += len ) {
3dab1dad 1550 TRIE_CHARCOUNT(trie)++;
a3621e74 1551 TRIE_READ_CHAR;
3dab1dad 1552 chars++;
a3621e74
YO
1553 if ( uvc < 256 ) {
1554 if ( !trie->charmap[ uvc ] ) {
1555 trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1556 if ( folder )
1557 trie->charmap[ folder[ uvc ] ] = trie->charmap[ uvc ];
3dab1dad 1558 TRIE_STORE_REVCHAR;
a3621e74 1559 }
02daf0ab 1560 if ( set_bit ) {
62012aee
KW
1561 /* store the codepoint in the bitmap, and its folded
1562 * equivalent. */
02daf0ab 1563 TRIE_BITMAP_SET(trie,uvc);
0921ee73
T
1564
1565 /* store the folded codepoint */
1566 if ( folder ) TRIE_BITMAP_SET(trie,folder[ uvc ]);
1567
1568 if ( !UTF ) {
1569 /* store first byte of utf8 representation of
acdf4139
KW
1570 variant codepoints */
1571 if (! UNI_IS_INVARIANT(uvc)) {
1572 TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));
0921ee73
T
1573 }
1574 }
02daf0ab
YO
1575 set_bit = 0; /* We've done our bit :-) */
1576 }
a3621e74
YO
1577 } else {
1578 SV** svpp;
55eed653
NC
1579 if ( !widecharmap )
1580 widecharmap = newHV();
a3621e74 1581
55eed653 1582 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
a3621e74
YO
1583
1584 if ( !svpp )
e4584336 1585 Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
a3621e74
YO
1586
1587 if ( !SvTRUE( *svpp ) ) {
1588 sv_setiv( *svpp, ++trie->uniquecharcount );
3dab1dad 1589 TRIE_STORE_REVCHAR;
a3621e74
YO
1590 }
1591 }
1592 }
3dab1dad
YO
1593 if( cur == first ) {
1594 trie->minlen=chars;
1595 trie->maxlen=chars;
1596 } else if (chars < trie->minlen) {
1597 trie->minlen=chars;
1598 } else if (chars > trie->maxlen) {
1599 trie->maxlen=chars;
1600 }
1601
a3621e74
YO
1602 } /* end first pass */
1603 DEBUG_TRIE_COMPILE_r(
3dab1dad
YO
1604 PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1605 (int)depth * 2 + 2,"",
55eed653 1606 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
be8e71aa
YO
1607 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1608 (int)trie->minlen, (int)trie->maxlen )
a3621e74 1609 );
a3621e74
YO
1610
1611 /*
1612 We now know what we are dealing with in terms of unique chars and
1613 string sizes so we can calculate how much memory a naive
0111c4fd
RGS
1614 representation using a flat table will take. If it's over a reasonable
1615 limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
a3621e74
YO
1616 conservative but potentially much slower representation using an array
1617 of lists.
1618
1619 At the end we convert both representations into the same compressed
1620 form that will be used in regexec.c for matching with. The latter
1621 is a form that cannot be used to construct with but has memory
1622 properties similar to the list form and access properties similar
1623 to the table form making it both suitable for fast searches and
1624 small enough that its feasable to store for the duration of a program.
1625
1626 See the comment in the code where the compressed table is produced
1627 inplace from the flat tabe representation for an explanation of how
1628 the compression works.
1629
1630 */
1631
1632
2e64971a
DM
1633 Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
1634 prev_states[1] = 0;
1635
3dab1dad 1636 if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
a3621e74
YO
1637 /*
1638 Second Pass -- Array Of Lists Representation
1639
1640 Each state will be represented by a list of charid:state records
1641 (reg_trie_trans_le) the first such element holds the CUR and LEN
1642 points of the allocated array. (See defines above).
1643
1644 We build the initial structure using the lists, and then convert
1645 it into the compressed table form which allows faster lookups
1646 (but cant be modified once converted).
a3621e74
YO
1647 */
1648
a3621e74
YO
1649 STRLEN transcount = 1;
1650
1e2e3d02
YO
1651 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1652 "%*sCompiling trie using list compiler\n",
1653 (int)depth * 2 + 2, ""));
446bd890 1654
c944940b
JH
1655 trie->states = (reg_trie_state *)
1656 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1657 sizeof(reg_trie_state) );
a3621e74
YO
1658 TRIE_LIST_NEW(1);
1659 next_alloc = 2;
1660
1661 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1662
c445ea15
AL
1663 regnode * const noper = NEXTOPER( cur );
1664 U8 *uc = (U8*)STRING( noper );
1665 const U8 * const e = uc + STR_LEN( noper );
1666 U32 state = 1; /* required init */
1667 U16 charid = 0; /* sanity init */
1668 U8 *scan = (U8*)NULL; /* sanity init */
1669 STRLEN foldlen = 0; /* required init */
07be1b83 1670 U32 wordlen = 0; /* required init */
c445ea15
AL
1671 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1672
3dab1dad 1673 if (OP(noper) != NOTHING) {
786e8c11 1674 for ( ; uc < e ; uc += len ) {
c445ea15 1675
786e8c11 1676 TRIE_READ_CHAR;
c445ea15 1677
786e8c11
YO
1678 if ( uvc < 256 ) {
1679 charid = trie->charmap[ uvc ];
c445ea15 1680 } else {
55eed653 1681 SV** const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
786e8c11
YO
1682 if ( !svpp ) {
1683 charid = 0;
1684 } else {
1685 charid=(U16)SvIV( *svpp );
1686 }
c445ea15 1687 }
786e8c11
YO
1688 /* charid is now 0 if we dont know the char read, or nonzero if we do */
1689 if ( charid ) {
a3621e74 1690
786e8c11
YO
1691 U16 check;
1692 U32 newstate = 0;
a3621e74 1693
786e8c11
YO
1694 charid--;
1695 if ( !trie->states[ state ].trans.list ) {
1696 TRIE_LIST_NEW( state );
c445ea15 1697 }
786e8c11
YO
1698 for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1699 if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1700 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1701 break;
1702 }
1703 }
1704 if ( ! newstate ) {
1705 newstate = next_alloc++;
2e64971a 1706 prev_states[newstate] = state;
786e8c11
YO
1707 TRIE_LIST_PUSH( state, charid, newstate );
1708 transcount++;
1709 }
1710 state = newstate;
1711 } else {
1712 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
c445ea15 1713 }
a28509cc 1714 }
c445ea15 1715 }
3dab1dad 1716 TRIE_HANDLE_WORD(state);
a3621e74
YO
1717
1718 } /* end second pass */
1719
1e2e3d02
YO
1720 /* next alloc is the NEXT state to be allocated */
1721 trie->statecount = next_alloc;
c944940b
JH
1722 trie->states = (reg_trie_state *)
1723 PerlMemShared_realloc( trie->states,
1724 next_alloc
1725 * sizeof(reg_trie_state) );
a3621e74 1726
3dab1dad 1727 /* and now dump it out before we compress it */
2b8b4781
NC
1728 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
1729 revcharmap, next_alloc,
1730 depth+1)
1e2e3d02 1731 );
a3621e74 1732
c944940b
JH
1733 trie->trans = (reg_trie_trans *)
1734 PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
a3621e74
YO
1735 {
1736 U32 state;
a3621e74
YO
1737 U32 tp = 0;
1738 U32 zp = 0;
1739
1740
1741 for( state=1 ; state < next_alloc ; state ++ ) {
1742 U32 base=0;
1743
1744 /*
1745 DEBUG_TRIE_COMPILE_MORE_r(
1746 PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1747 );
1748 */
1749
1750 if (trie->states[state].trans.list) {
1751 U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1752 U16 maxid=minid;
a28509cc 1753 U16 idx;
a3621e74
YO
1754
1755 for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
c445ea15
AL
1756 const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1757 if ( forid < minid ) {
1758 minid=forid;
1759 } else if ( forid > maxid ) {
1760 maxid=forid;
1761 }
a3621e74
YO
1762 }
1763 if ( transcount < tp + maxid - minid + 1) {
1764 transcount *= 2;
c944940b
JH
1765 trie->trans = (reg_trie_trans *)
1766 PerlMemShared_realloc( trie->trans,
446bd890
NC
1767 transcount
1768 * sizeof(reg_trie_trans) );
a3621e74
YO
1769 Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1770 }
1771 base = trie->uniquecharcount + tp - minid;
1772 if ( maxid == minid ) {
1773 U32 set = 0;
1774 for ( ; zp < tp ; zp++ ) {
1775 if ( ! trie->trans[ zp ].next ) {
1776 base = trie->uniquecharcount + zp - minid;
1777 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1778 trie->trans[ zp ].check = state;
1779 set = 1;
1780 break;
1781 }
1782 }
1783 if ( !set ) {
1784 trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1785 trie->trans[ tp ].check = state;
1786 tp++;
1787 zp = tp;
1788 }
1789 } else {
1790 for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
c445ea15 1791 const U32 tid = base - trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
a3621e74
YO
1792 trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1793 trie->trans[ tid ].check = state;
1794 }
1795 tp += ( maxid - minid + 1 );
1796 }
1797 Safefree(trie->states[ state ].trans.list);
1798 }
1799 /*
1800 DEBUG_TRIE_COMPILE_MORE_r(
1801 PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1802 );
1803 */
1804 trie->states[ state ].trans.base=base;
1805 }
cc601c31 1806 trie->lasttrans = tp + 1;
a3621e74
YO
1807 }
1808 } else {
1809 /*
1810 Second Pass -- Flat Table Representation.
1811
1812 we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1813 We know that we will need Charcount+1 trans at most to store the data
1814 (one row per char at worst case) So we preallocate both structures
1815 assuming worst case.
1816
1817 We then construct the trie using only the .next slots of the entry
1818 structs.
1819
3b753521 1820 We use the .check field of the first entry of the node temporarily to
a3621e74
YO
1821 make compression both faster and easier by keeping track of how many non
1822 zero fields are in the node.
1823
1824 Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1825 transition.
1826
1827 There are two terms at use here: state as a TRIE_NODEIDX() which is a
1828 number representing the first entry of the node, and state as a
1829 TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1830 TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1831 are 2 entrys per node. eg:
1832
1833 A B A B
1834 1. 2 4 1. 3 7
1835 2. 0 3 3. 0 5
1836 3. 0 0 5. 0 0
1837 4. 0 0 7. 0 0
1838
1839 The table is internally in the right hand, idx form. However as we also
1840 have to deal with the states array which is indexed by nodenum we have to
1841 use TRIE_NODENUM() to convert.
1842
1843 */
1e2e3d02
YO
1844 DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
1845 "%*sCompiling trie using table compiler\n",
1846 (int)depth * 2 + 2, ""));
3dab1dad 1847
c944940b
JH
1848 trie->trans = (reg_trie_trans *)
1849 PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
1850 * trie->uniquecharcount + 1,
1851 sizeof(reg_trie_trans) );
1852 trie->states = (reg_trie_state *)
1853 PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1854 sizeof(reg_trie_state) );
a3621e74
YO
1855 next_alloc = trie->uniquecharcount + 1;
1856
3dab1dad 1857
a3621e74
YO
1858 for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1859
c445ea15 1860 regnode * const noper = NEXTOPER( cur );
a28509cc
AL
1861 const U8 *uc = (U8*)STRING( noper );
1862 const U8 * const e = uc + STR_LEN( noper );
a3621e74
YO
1863
1864 U32 state = 1; /* required init */
1865
1866 U16 charid = 0; /* sanity init */
1867 U32 accept_state = 0; /* sanity init */
1868 U8 *scan = (U8*)NULL; /* sanity init */
1869
1870 STRLEN foldlen = 0; /* required init */
07be1b83 1871 U32 wordlen = 0; /* required init */
a3621e74
YO
1872 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1873
3dab1dad 1874 if ( OP(noper) != NOTHING ) {
786e8c11 1875 for ( ; uc < e ; uc += len ) {
a3621e74 1876
786e8c11 1877 TRIE_READ_CHAR;
a3621e74 1878
786e8c11
YO
1879 if ( uvc < 256 ) {
1880 charid = trie->charmap[ uvc ];
1881 } else {
55eed653 1882 SV* const * const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
786e8c11 1883 charid = svpp ? (U16)SvIV(*svpp) : 0;
a3621e74 1884 }
786e8c11
YO
1885 if ( charid ) {
1886 charid--;
1887 if ( !trie->trans[ state + charid ].next ) {
1888 trie->trans[ state + charid ].next = next_alloc;
1889 trie->trans[ state ].check++;
2e64971a
DM
1890 prev_states[TRIE_NODENUM(next_alloc)]
1891 = TRIE_NODENUM(state);
786e8c11
YO
1892 next_alloc += trie->uniquecharcount;
1893 }
1894 state = trie->trans[ state + charid ].next;
1895 } else {
1896 Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1897 }
1898 /* charid is now 0 if we dont know the char read, or nonzero if we do */
a3621e74 1899 }
a3621e74 1900 }
3dab1dad
YO
1901 accept_state = TRIE_NODENUM( state );
1902 TRIE_HANDLE_WORD(accept_state);
a3621e74
YO
1903
1904 } /* end second pass */
1905
3dab1dad 1906 /* and now dump it out before we compress it */
2b8b4781
NC
1907 DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
1908 revcharmap,
1909 next_alloc, depth+1));
a3621e74 1910
a3621e74
YO
1911 {
1912 /*
1913 * Inplace compress the table.*
1914
1915 For sparse data sets the table constructed by the trie algorithm will
1916 be mostly 0/FAIL transitions or to put it another way mostly empty.
1917 (Note that leaf nodes will not contain any transitions.)
1918
1919 This algorithm compresses the tables by eliminating most such
1920 transitions, at the cost of a modest bit of extra work during lookup:
1921
1922 - Each states[] entry contains a .base field which indicates the
1923 index in the state[] array wheres its transition data is stored.
1924
3b753521 1925 - If .base is 0 there are no valid transitions from that node.
a3621e74
YO
1926
1927 - If .base is nonzero then charid is added to it to find an entry in
1928 the trans array.
1929
1930 -If trans[states[state].base+charid].check!=state then the
1931 transition is taken to be a 0/Fail transition. Thus if there are fail
1932 transitions at the front of the node then the .base offset will point
1933 somewhere inside the previous nodes data (or maybe even into a node
1934 even earlier), but the .check field determines if the transition is
1935 valid.
1936
786e8c11 1937 XXX - wrong maybe?
a3621e74 1938 The following process inplace converts the table to the compressed
3b753521 1939 table: We first do not compress the root node 1,and mark all its
a3621e74 1940 .check pointers as 1 and set its .base pointer as 1 as well. This
3b753521
FN
1941 allows us to do a DFA construction from the compressed table later,
1942 and ensures that any .base pointers we calculate later are greater
1943 than 0.
a3621e74
YO
1944
1945 - We set 'pos' to indicate the first entry of the second node.
1946
1947 - We then iterate over the columns of the node, finding the first and
1948 last used entry at l and m. We then copy l..m into pos..(pos+m-l),
1949 and set the .check pointers accordingly, and advance pos
1950 appropriately and repreat for the next node. Note that when we copy
1951 the next pointers we have to convert them from the original
1952 NODEIDX form to NODENUM form as the former is not valid post
1953 compression.
1954
1955 - If a node has no transitions used we mark its base as 0 and do not
1956 advance the pos pointer.
1957
1958 - If a node only has one transition we use a second pointer into the
1959 structure to fill in allocated fail transitions from other states.
1960 This pointer is independent of the main pointer and scans forward
1961 looking for null transitions that are allocated to a state. When it
1962 finds one it writes the single transition into the "hole". If the
786e8c11 1963 pointer doesnt find one the single transition is appended as normal.
a3621e74
YO
1964
1965 - Once compressed we can Renew/realloc the structures to release the
1966 excess space.
1967
1968 See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
1969 specifically Fig 3.47 and the associated pseudocode.
1970
1971 demq
1972 */
a3b680e6 1973 const U32 laststate = TRIE_NODENUM( next_alloc );
a28509cc 1974 U32 state, charid;
a3621e74 1975 U32 pos = 0, zp=0;
1e2e3d02 1976 trie->statecount = laststate;
a3621e74
YO
1977
1978 for ( state = 1 ; state < laststate ; state++ ) {
1979 U8 flag = 0;
a28509cc
AL
1980 const U32 stateidx = TRIE_NODEIDX( state );
1981 const U32 o_used = trie->trans[ stateidx ].check;
1982 U32 used = trie->trans[ stateidx ].check;
a3621e74
YO
1983 trie->trans[ stateidx ].check = 0;
1984
1985 for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
1986 if ( flag || trie->trans[ stateidx + charid ].next ) {
1987 if ( trie->trans[ stateidx + charid ].next ) {
1988 if (o_used == 1) {
1989 for ( ; zp < pos ; zp++ ) {
1990 if ( ! trie->trans[ zp ].next ) {
1991 break;
1992 }
1993 }
1994 trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
1995 trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1996 trie->trans[ zp ].check = state;
1997 if ( ++zp > pos ) pos = zp;
1998 break;
1999 }
2000 used--;
2001 }
2002 if ( !flag ) {
2003 flag = 1;
2004 trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
2005 }
2006 trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
2007 trie->trans[ pos ].check = state;
2008 pos++;
2009 }
2010 }
2011 }
cc601c31 2012 trie->lasttrans = pos + 1;
c944940b
JH
2013 trie->states = (reg_trie_state *)
2014 PerlMemShared_realloc( trie->states, laststate
2015 * sizeof(reg_trie_state) );
a3621e74 2016 DEBUG_TRIE_COMPILE_MORE_r(
e4584336 2017 PerlIO_printf( Perl_debug_log,
3dab1dad
YO
2018 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
2019 (int)depth * 2 + 2,"",
2020 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
5d7488b2
AL
2021 (IV)next_alloc,
2022 (IV)pos,
a3621e74
YO
2023 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
2024 );
2025
2026 } /* end table compress */
2027 }
1e2e3d02
YO
2028 DEBUG_TRIE_COMPILE_MORE_r(
2029 PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
2030 (int)depth * 2 + 2, "",
2031 (UV)trie->statecount,
2032 (UV)trie->lasttrans)
2033 );
cc601c31 2034 /* resize the trans array to remove unused space */
c944940b
JH
2035 trie->trans = (reg_trie_trans *)
2036 PerlMemShared_realloc( trie->trans, trie->lasttrans
2037 * sizeof(reg_trie_trans) );
a3621e74 2038
3b753521 2039 { /* Modify the program and insert the new TRIE node */
3dab1dad
YO
2040 U8 nodetype =(U8)(flags & 0xFF);
2041 char *str=NULL;
786e8c11 2042
07be1b83 2043#ifdef DEBUGGING
e62cc96a 2044 regnode *optimize = NULL;
7122b237
YO
2045#ifdef RE_TRACK_PATTERN_OFFSETS
2046
b57a0404
JH
2047 U32 mjd_offset = 0;
2048 U32 mjd_nodelen = 0;
7122b237
YO
2049#endif /* RE_TRACK_PATTERN_OFFSETS */
2050#endif /* DEBUGGING */
a3621e74 2051 /*
3dab1dad
YO
2052 This means we convert either the first branch or the first Exact,
2053 depending on whether the thing following (in 'last') is a branch
2054 or not and whther first is the startbranch (ie is it a sub part of
2055 the alternation or is it the whole thing.)
3b753521 2056 Assuming its a sub part we convert the EXACT otherwise we convert
3dab1dad 2057 the whole branch sequence, including the first.
a3621e74 2058 */
3dab1dad 2059 /* Find the node we are going to overwrite */
7f69552c 2060 if ( first != startbranch || OP( last ) == BRANCH ) {
07be1b83 2061 /* branch sub-chain */
3dab1dad 2062 NEXT_OFF( first ) = (U16)(last - first);
7122b237 2063#ifdef RE_TRACK_PATTERN_OFFSETS
07be1b83
YO
2064 DEBUG_r({
2065 mjd_offset= Node_Offset((convert));
2066 mjd_nodelen= Node_Length((convert));
2067 });
7122b237 2068#endif
7f69552c 2069 /* whole branch chain */
7122b237
YO
2070 }
2071#ifdef RE_TRACK_PATTERN_OFFSETS
2072 else {
7f69552c
YO
2073 DEBUG_r({
2074 const regnode *nop = NEXTOPER( convert );
2075 mjd_offset= Node_Offset((nop));
2076 mjd_nodelen= Node_Length((nop));
2077 });
07be1b83
YO
2078 }
2079 DEBUG_OPTIMISE_r(
2080 PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
2081 (int)depth * 2 + 2, "",
786e8c11 2082 (UV)mjd_offset, (UV)mjd_nodelen)
07be1b83 2083 );
7122b237 2084#endif
3dab1dad
YO
2085 /* But first we check to see if there is a common prefix we can
2086 split out as an EXACT and put in front of the TRIE node. */
2087 trie->startstate= 1;
55eed653 2088 if ( trie->bitmap && !widecharmap && !trie->jump ) {
3dab1dad 2089 U32 state;
1e2e3d02 2090 for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
a3621e74 2091 U32 ofs = 0;
8e11feef
RGS
2092 I32 idx = -1;
2093 U32 count = 0;
2094 const U32 base = trie->states[ state ].trans.base;
a3621e74 2095
3dab1dad 2096 if ( trie->states[state].wordnum )
8e11feef 2097 count = 1;
a3621e74 2098
8e11feef 2099 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
cc601c31
YO
2100 if ( ( base + ofs >= trie->uniquecharcount ) &&
2101 ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
a3621e74
YO
2102 trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
2103 {
3dab1dad 2104 if ( ++count > 1 ) {
2b8b4781 2105 SV **tmp = av_fetch( revcharmap, ofs, 0);
07be1b83 2106 const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
8e11feef 2107 if ( state == 1 ) break;
3dab1dad
YO
2108 if ( count == 2 ) {
2109 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
2110 DEBUG_OPTIMISE_r(
8e11feef
RGS
2111 PerlIO_printf(Perl_debug_log,
2112 "%*sNew Start State=%"UVuf" Class: [",
2113 (int)depth * 2 + 2, "",
786e8c11 2114 (UV)state));
be8e71aa 2115 if (idx >= 0) {
2b8b4781 2116 SV ** const tmp = av_fetch( revcharmap, idx, 0);
be8e71aa 2117 const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
8e11feef 2118
3dab1dad 2119 TRIE_BITMAP_SET(trie,*ch);
8e11feef
RGS
2120 if ( folder )
2121 TRIE_BITMAP_SET(trie, folder[ *ch ]);
3dab1dad 2122 DEBUG_OPTIMISE_r(
f1f66076 2123 PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
3dab1dad 2124 );
8e11feef
RGS
2125 }
2126 }
2127 TRIE_BITMAP_SET(trie,*ch);
2128 if ( folder )
2129 TRIE_BITMAP_SET(trie,folder[ *ch ]);
2130 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
2131 }
2132 idx = ofs;
2133 }
3dab1dad
YO
2134 }
2135 if ( count == 1 ) {
2b8b4781 2136 SV **tmp = av_fetch( revcharmap, idx, 0);
c490c714
YO
2137 STRLEN len;
2138 char *ch = SvPV( *tmp, len );
de734bd5
A
2139 DEBUG_OPTIMISE_r({
2140 SV *sv=sv_newmortal();
8e11feef
RGS
2141 PerlIO_printf( Perl_debug_log,
2142 "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
2143 (int)depth * 2 + 2, "",
de734bd5
A
2144 (UV)state, (UV)idx,
2145 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
2146 PL_colors[0], PL_colors[1],
2147 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2148 PERL_PV_ESCAPE_FIRSTCHAR
2149 )
2150 );
2151 });
3dab1dad
YO
2152 if ( state==1 ) {
2153 OP( convert ) = nodetype;
2154 str=STRING(convert);
2155 STR_LEN(convert)=0;
2156 }
c490c714
YO
2157 STR_LEN(convert) += len;
2158 while (len--)
de734bd5 2159 *str++ = *ch++;
8e11feef 2160 } else {
f9049ba1 2161#ifdef DEBUGGING
8e11feef
RGS
2162 if (state>1)
2163 DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
f9049ba1 2164#endif
8e11feef
RGS
2165 break;
2166 }
2167 }
2e64971a 2168 trie->prefixlen = (state-1);
3dab1dad 2169 if (str) {
8e11feef 2170 regnode *n = convert+NODE_SZ_STR(convert);
07be1b83 2171 NEXT_OFF(convert) = NODE_SZ_STR(convert);
8e11feef 2172 trie->startstate = state;
07be1b83
YO
2173 trie->minlen -= (state - 1);
2174 trie->maxlen -= (state - 1);
33809eae
JH
2175#ifdef DEBUGGING
2176 /* At least the UNICOS C compiler choked on this
2177 * being argument to DEBUG_r(), so let's just have
2178 * it right here. */
2179 if (
2180#ifdef PERL_EXT_RE_BUILD
2181 1
2182#else
2183 DEBUG_r_TEST
2184#endif
2185 ) {
2186 regnode *fix = convert;
2187 U32 word = trie->wordcount;
2188 mjd_nodelen++;
2189 Set_Node_Offset_Length(convert, mjd_offset, state - 1);
2190 while( ++fix < n ) {
2191 Set_Node_Offset_Length(fix, 0, 0);
2192 }
2193 while (word--) {
2194 SV ** const tmp = av_fetch( trie_words, word, 0 );
2195 if (tmp) {
2196 if ( STR_LEN(convert) <= SvCUR(*tmp) )
2197 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
2198 else
2199 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
2200 }
2201 }
2202 }
2203#endif
8e11feef
RGS
2204 if (trie->maxlen) {
2205 convert = n;
2206 } else {
3dab1dad 2207 NEXT_OFF(convert) = (U16)(tail - convert);
a5ca303d 2208 DEBUG_r(optimize= n);
3dab1dad
YO
2209 }
2210 }
2211 }
a5ca303d
YO
2212 if (!jumper)
2213 jumper = last;
3dab1dad 2214 if ( trie->maxlen ) {
8e11feef
RGS
2215 NEXT_OFF( convert ) = (U16)(tail - convert);
2216 ARG_SET( convert, data_slot );
786e8c11
YO
2217 /* Store the offset to the first unabsorbed branch in
2218 jump[0], which is otherwise unused by the jump logic.
2219 We use this when dumping a trie and during optimisation. */
2220 if (trie->jump)
7f69552c 2221 trie->jump[0] = (U16)(nextbranch - convert);
a5ca303d 2222
6c48061a
YO
2223 /* If the start state is not accepting (meaning there is no empty string/NOTHING)
2224 * and there is a bitmap
2225 * and the first "jump target" node we found leaves enough room
2226 * then convert the TRIE node into a TRIEC node, with the bitmap
2227 * embedded inline in the opcode - this is hypothetically faster.
2228 */
2229 if ( !trie->states[trie->startstate].wordnum
2230 && trie->bitmap
2231 && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
786e8c11
YO
2232 {
2233 OP( convert ) = TRIEC;
2234 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
446bd890 2235 PerlMemShared_free(trie->bitmap);
786e8c11
YO
2236 trie->bitmap= NULL;
2237 } else
2238 OP( convert ) = TRIE;
a3621e74 2239
3dab1dad
YO
2240 /* store the type in the flags */
2241 convert->flags = nodetype;
a5ca303d
YO
2242 DEBUG_r({
2243 optimize = convert
2244 + NODE_STEP_REGNODE
2245 + regarglen[ OP( convert ) ];
2246 });
2247 /* XXX We really should free up the resource in trie now,
2248 as we won't use them - (which resources?) dmq */
3dab1dad 2249 }
a3621e74 2250 /* needed for dumping*/
e62cc96a 2251 DEBUG_r(if (optimize) {
07be1b83 2252 regnode *opt = convert;
bcdf7404 2253
e62cc96a 2254 while ( ++opt < optimize) {
07be1b83
YO
2255 Set_Node_Offset_Length(opt,0,0);
2256 }
786e8c11
YO
2257 /*
2258 Try to clean up some of the debris left after the
2259 optimisation.
a3621e74 2260 */
786e8c11 2261 while( optimize < jumper ) {
07be1b83 2262 mjd_nodelen += Node_Length((optimize));
a3621e74 2263 OP( optimize ) = OPTIMIZED;
07be1b83 2264 Set_Node_Offset_Length(optimize,0,0);
a3621e74
YO
2265 optimize++;
2266 }
07be1b83 2267 Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
a3621e74
YO
2268 });
2269 } /* end node insert */
2e64971a
DM
2270
2271 /* Finish populating the prev field of the wordinfo array. Walk back
2272 * from each accept state until we find another accept state, and if
2273 * so, point the first word's .prev field at the second word. If the
2274 * second already has a .prev field set, stop now. This will be the
2275 * case either if we've already processed that word's accept state,
3b753521
FN
2276 * or that state had multiple words, and the overspill words were
2277 * already linked up earlier.
2e64971a
DM
2278 */
2279 {
2280 U16 word;
2281 U32 state;
2282 U16 prev;
2283
2284 for (word=1; word <= trie->wordcount; word++) {
2285 prev = 0;
2286 if (trie->wordinfo[word].prev)
2287 continue;
2288 state = trie->wordinfo[word].accept;
2289 while (state) {
2290 state = prev_states[state];
2291 if (!state)
2292 break;
2293 prev = trie->states[state].wordnum;
2294 if (prev)
2295 break;
2296 }
2297 trie->wordinfo[word].prev = prev;
2298 }
2299 Safefree(prev_states);
2300 }
2301
2302
2303 /* and now dump out the compressed format */
2304 DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
2305
55eed653 2306 RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
2b8b4781
NC
2307#ifdef DEBUGGING
2308 RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
2309 RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
2310#else
2311 SvREFCNT_dec(revcharmap);
07be1b83 2312#endif
786e8c11
YO
2313 return trie->jump
2314 ? MADE_JUMP_TRIE
2315 : trie->startstate>1
2316 ? MADE_EXACT_TRIE
2317 : MADE_TRIE;
2318}
2319
2320STATIC void
2321S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source, regnode *stclass, U32 depth)
2322{
3b753521 2323/* The Trie is constructed and compressed now so we can build a fail array if it's needed
786e8c11
YO
2324
2325 This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
2326 "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
2327 ISBN 0-201-10088-6
2328
2329 We find the fail state for each state in the trie, this state is the longest proper
3b753521
FN
2330 suffix of the current state's 'word' that is also a proper prefix of another word in our
2331 trie. State 1 represents the word '' and is thus the default fail state. This allows
786e8c11
YO
2332 the DFA not to have to restart after its tried and failed a word at a given point, it
2333 simply continues as though it had been matching the other word in the first place.
2334 Consider
2335 'abcdgu'=~/abcdefg|cdgu/
2336 When we get to 'd' we are still matching the first word, we would encounter 'g' which would
3b753521
FN
2337 fail, which would bring us to the state representing 'd' in the second word where we would
2338 try 'g' and succeed, proceeding to match 'cdgu'.
786e8c11
YO
2339 */
2340 /* add a fail transition */
3251b653
NC
2341 const U32 trie_offset = ARG(source);
2342 reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
786e8c11
YO
2343 U32 *q;
2344 const U32 ucharcount = trie->uniquecharcount;
1e2e3d02 2345 const U32 numstates = trie->statecount;
786e8c11
YO
2346 const U32 ubound = trie->lasttrans + ucharcount;
2347 U32 q_read = 0;
2348 U32 q_write = 0;
2349 U32 charid;
2350 U32 base = trie->states[ 1 ].trans.base;
2351 U32 *fail;
2352 reg_ac_data *aho;
2353 const U32 data_slot = add_data( pRExC_state, 1, "T" );
2354 GET_RE_DEBUG_FLAGS_DECL;
7918f24d
NC
2355
2356 PERL_ARGS_ASSERT_MAKE_TRIE_FAILTABLE;
786e8c11
YO
2357#ifndef DEBUGGING
2358 PERL_UNUSED_ARG(depth);
2359#endif
2360
2361
2362 ARG_SET( stclass, data_slot );
c944940b 2363 aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
f8fc2ecf 2364 RExC_rxi->data->data[ data_slot ] = (void*)aho;
3251b653 2365 aho->trie=trie_offset;
446bd890
NC
2366 aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
2367 Copy( trie->states, aho->states, numstates, reg_trie_state );
786e8c11 2368 Newxz( q, numstates, U32);
c944940b 2369 aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
786e8c11
YO
2370 aho->refcount = 1;
2371 fail = aho->fail;
2372 /* initialize fail[0..1] to be 1 so that we always have
2373 a valid final fail state */
2374 fail[ 0 ] = fail[ 1 ] = 1;
2375
2376 for ( charid = 0; charid < ucharcount ; charid++ ) {
2377 const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2378 if ( newstate ) {
2379 q[ q_write ] = newstate;
2380 /* set to point at the root */
2381 fail[ q[ q_write++ ] ]=1;
2382 }
2383 }
2384 while ( q_read < q_write) {
2385 const U32 cur = q[ q_read++ % numstates ];
2386 base = trie->states[ cur ].trans.base;
2387
2388 for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2389 const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2390 if (ch_state) {
2391 U32 fail_state = cur;
2392 U32 fail_base;
2393 do {
2394 fail_state = fail[ fail_state ];
2395 fail_base = aho->states[ fail_state ].trans.base;
2396 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2397
2398 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2399 fail[ ch_state ] = fail_state;
2400 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2401 {
2402 aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
2403 }
2404 q[ q_write++ % numstates] = ch_state;
2405 }
2406 }
2407 }
2408 /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2409 when we fail in state 1, this allows us to use the
2410 charclass scan to find a valid start char. This is based on the principle
2411 that theres a good chance the string being searched contains lots of stuff
2412 that cant be a start char.
2413 */
2414 fail[ 0 ] = fail[ 1 ] = 0;
2415 DEBUG_TRIE_COMPILE_r({
6d99fb9b
JH
2416 PerlIO_printf(Perl_debug_log,
2417 "%*sStclass Failtable (%"UVuf" states): 0",
2418 (int)(depth * 2), "", (UV)numstates
1e2e3d02 2419 );
786e8c11
YO
2420 for( q_read=1; q_read<numstates; q_read++ ) {
2421 PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2422 }
2423 PerlIO_printf(Perl_debug_log, "\n");
2424 });
2425 Safefree(q);
2426 /*RExC_seen |= REG_SEEN_TRIEDFA;*/
a3621e74
YO
2427}
2428
786e8c11 2429
a3621e74 2430/*
5d1c421c
JH
2431 * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2432 * These need to be revisited when a newer toolchain becomes available.
2433 */
2434#if defined(__sparc64__) && defined(__GNUC__)
2435# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2436# undef SPARC64_GCC_WORKAROUND
2437# define SPARC64_GCC_WORKAROUND 1
2438# endif
2439#endif
2440
07be1b83 2441#define DEBUG_PEEP(str,scan,depth) \
b515a41d 2442 DEBUG_OPTIMISE_r({if (scan){ \
07be1b83
YO
2443 SV * const mysv=sv_newmortal(); \
2444 regnode *Next = regnext(scan); \
2445 regprop(RExC_rx, mysv, scan); \
7f69552c 2446 PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
07be1b83
YO
2447 (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2448 Next ? (REG_NODE_NUM(Next)) : 0 ); \
b515a41d 2449 }});
07be1b83 2450
1de06328
YO
2451
2452
2453
2454
07be1b83
YO
2455#define JOIN_EXACT(scan,min,flags) \
2456 if (PL_regkind[OP(scan)] == EXACT) \
2457 join_exact(pRExC_state,(scan),(min),(flags),NULL,depth+1)
2458
be8e71aa 2459STATIC U32
07be1b83
YO
2460S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, I32 *min, U32 flags,regnode *val, U32 depth) {
2461 /* Merge several consecutive EXACTish nodes into one. */
2462 regnode *n = regnext(scan);
2463 U32 stringok = 1;
2464 regnode *next = scan + NODE_SZ_STR(scan);
2465 U32 merged = 0;
2466 U32 stopnow = 0;
2467#ifdef DEBUGGING
2468 regnode *stop = scan;
72f13be8 2469 GET_RE_DEBUG_FLAGS_DECL;
f9049ba1 2470#else
d47053eb
RGS
2471 PERL_UNUSED_ARG(depth);
2472#endif
7918f24d
NC
2473
2474 PERL_ARGS_ASSERT_JOIN_EXACT;
d47053eb 2475#ifndef EXPERIMENTAL_INPLACESCAN
f9049ba1
SP
2476 PERL_UNUSED_ARG(flags);
2477 PERL_UNUSED_ARG(val);
07be1b83 2478#endif
07be1b83
YO
2479 DEBUG_PEEP("join",scan,depth);
2480
2481 /* Skip NOTHING, merge EXACT*. */
2482 while (n &&
2483 ( PL_regkind[OP(n)] == NOTHING ||
2484 (stringok && (OP(n) == OP(scan))))
2485 && NEXT_OFF(n)
2486 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
2487
2488 if (OP(n) == TAIL || n > next)
2489 stringok = 0;
2490 if (PL_regkind[OP(n)] == NOTHING) {
07be1b83
YO
2491 DEBUG_PEEP("skip:",n,depth);
2492 NEXT_OFF(scan) += NEXT_OFF(n);
2493 next = n + NODE_STEP_REGNODE;
2494#ifdef DEBUGGING
2495 if (stringok)
2496 stop = n;
2497#endif
2498 n = regnext(n);
2499 }
2500 else if (stringok) {
786e8c11 2501 const unsigned int oldl = STR_LEN(scan);
07be1b83
YO
2502 regnode * const nnext = regnext(n);
2503
2504 DEBUG_PEEP("merg",n,depth);
2505
2506 merged++;
2507 if (oldl + STR_LEN(n) > U8_MAX)
2508 break;
2509 NEXT_OFF(scan) += NEXT_OFF(n);
2510 STR_LEN(scan) += STR_LEN(n);
2511 next = n + NODE_SZ_STR(n);
2512 /* Now we can overwrite *n : */
2513 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2514#ifdef DEBUGGING
2515 stop = next - 1;
2516#endif
2517 n = nnext;
2518 if (stopnow) break;
2519 }
2520
d47053eb
RGS
2521#ifdef EXPERIMENTAL_INPLACESCAN
2522 if (flags && !NEXT_OFF(n)) {
2523 DEBUG_PEEP("atch", val, depth);
2524 if (reg_off_by_arg[OP(n)]) {
2525 ARG_SET(n, val - n);
2526 }
2527 else {
2528 NEXT_OFF(n) = val - n;
2529 }
2530 stopnow = 1;
2531 }
07be1b83
YO
2532#endif
2533 }
ced7f090
KW
2534#define GREEK_SMALL_LETTER_IOTA_WITH_DIALYTIKA_AND_TONOS 0x0390
2535#define IOTA_D_T GREEK_SMALL_LETTER_IOTA_WITH_DIALYTIKA_AND_TONOS
2536#define GREEK_SMALL_LETTER_UPSILON_WITH_DIALYTIKA_AND_TONOS 0x03B0
2537#define UPSILON_D_T GREEK_SMALL_LETTER_UPSILON_WITH_DIALYTIKA_AND_TONOS
2c2b7f86
KW
2538
2539 if (UTF
2f7f8cb1 2540 && ( OP(scan) == EXACTF || OP(scan) == EXACTFU || OP(scan) == EXACTFA)
2c2b7f86
KW
2541 && ( STR_LEN(scan) >= 6 ) )
2542 {
07be1b83
YO
2543 /*
2544 Two problematic code points in Unicode casefolding of EXACT nodes:
2545
2546 U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2547 U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2548
2549 which casefold to
2550
2551 Unicode UTF-8
2552
2553 U+03B9 U+0308 U+0301 0xCE 0xB9 0xCC 0x88 0xCC 0x81
2554 U+03C5 U+0308 U+0301 0xCF 0x85 0xCC 0x88 0xCC 0x81
2555
2556 This means that in case-insensitive matching (or "loose matching",
2557 as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte
2558 length of the above casefolded versions) can match a target string
2559 of length two (the byte length of UTF-8 encoded U+0390 or U+03B0).
2560 This would rather mess up the minimum length computation.
2561
2562 What we'll do is to look for the tail four bytes, and then peek
2563 at the preceding two bytes to see whether we need to decrease
2564 the minimum length by four (six minus two).
2565
2566 Thanks to the design of UTF-8, there cannot be false matches:
2567 A sequence of valid UTF-8 bytes cannot be a subsequence of
2568 another valid sequence of UTF-8 bytes.
2569
2570 */
2571 char * const s0 = STRING(scan), *s, *t;
2572 char * const s1 = s0 + STR_LEN(scan) - 1;
2573 char * const s2 = s1 - 4;
e294cc5d
JH
2574#ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2575 const char t0[] = "\xaf\x49\xaf\x42";
2576#else
07be1b83 2577 const char t0[] = "\xcc\x88\xcc\x81";
e294cc5d 2578#endif
07be1b83
YO
2579 const char * const t1 = t0 + 3;
2580
2581 for (s = s0 + 2;
2582 s < s2 && (t = ninstr(s, s1, t0, t1));
2583 s = t + 4) {
e294cc5d
JH
2584#ifdef EBCDIC
2585 if (((U8)t[-1] == 0x68 && (U8)t[-2] == 0xB4) ||
2586 ((U8)t[-1] == 0x46 && (U8)t[-2] == 0xB5))
2587#else
07be1b83
YO
2588 if (((U8)t[-1] == 0xB9 && (U8)t[-2] == 0xCE) ||
2589 ((U8)t[-1] == 0x85 && (U8)t[-2] == 0xCF))
e294cc5d 2590#endif
07be1b83
YO
2591 *min -= 4;
2592 }
2593 }
2594
2595#ifdef DEBUGGING
2596 /* Allow dumping */
2597 n = scan + NODE_SZ_STR(scan);
2598 while (n <= stop) {
2599 if (PL_regkind[OP(n)] != NOTHING || OP(n) == NOTHING) {
2600 OP(n) = OPTIMIZED;
2601 NEXT_OFF(n) = 0;
2602 }
2603 n++;
2604 }
2605#endif
2606 DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2607 return stopnow;
2608}
2609
486ec47a 2610/* REx optimizer. Converts nodes into quicker variants "in place".
653099ff
GS
2611 Finds fixed substrings. */
2612
a0288114 2613/* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
c277df42
IZ
2614 to the position after last scanned or to NULL. */
2615
40d049e4
YO
2616#define INIT_AND_WITHP \
2617 assert(!and_withp); \
2618 Newx(and_withp,1,struct regnode_charclass_class); \
2619 SAVEFREEPV(and_withp)
07be1b83 2620
b515a41d 2621/* this is a chain of data about sub patterns we are processing that
486ec47a 2622 need to be handled separately/specially in study_chunk. Its so
b515a41d
YO
2623 we can simulate recursion without losing state. */
2624struct scan_frame;
2625typedef struct scan_frame {
2626 regnode *last; /* last node to process in this frame */
2627 regnode *next; /* next node to process when last is reached */
2628 struct scan_frame *prev; /*previous frame*/
2629 I32 stop; /* what stopparen do we use */
2630} scan_frame;
2631
304ee84b
YO
2632
2633#define SCAN_COMMIT(s, data, m) scan_commit(s, data, m, is_inf)
2634
e1d1eefb
YO
2635#define CASE_SYNST_FNC(nAmE) \
2636case nAmE: \
2637 if (flags & SCF_DO_STCLASS_AND) { \
2638 for (value = 0; value < 256; value++) \
2639 if (!is_ ## nAmE ## _cp(value)) \
2640 ANYOF_BITMAP_CLEAR(data->start_class, value); \
2641 } \
2642 else { \
2643 for (value = 0; value < 256; value++) \
2644 if (is_ ## nAmE ## _cp(value)) \
2645 ANYOF_BITMAP_SET(data->start_class, value); \
2646 } \
2647 break; \
2648case N ## nAmE: \
2649 if (flags & SCF_DO_STCLASS_AND) { \
2650 for (value = 0; value < 256; value++) \
2651 if (is_ ## nAmE ## _cp(value)) \
2652 ANYOF_BITMAP_CLEAR(data->start_class, value); \
2653 } \
2654 else { \
2655 for (value = 0; value < 256; value++) \
2656 if (!is_ ## nAmE ## _cp(value)) \
2657 ANYOF_BITMAP_SET(data->start_class, value); \
2658 } \
2659 break
2660
2661
2662
76e3520e 2663STATIC I32
40d049e4 2664S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
1de06328 2665 I32 *minlenp, I32 *deltap,
40d049e4
YO
2666 regnode *last,
2667 scan_data_t *data,
2668 I32 stopparen,
2669 U8* recursed,
2670 struct regnode_charclass_class *and_withp,
2671 U32 flags, U32 depth)
c277df42
IZ
2672 /* scanp: Start here (read-write). */
2673 /* deltap: Write maxlen-minlen here. */
2674 /* last: Stop before this one. */
40d049e4
YO
2675 /* data: string data about the pattern */
2676 /* stopparen: treat close N as END */
2677 /* recursed: which subroutines have we recursed into */
2678 /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
c277df42 2679{
97aff369 2680 dVAR;
c277df42
IZ
2681 I32 min = 0, pars = 0, code;
2682 regnode *scan = *scanp, *next;
2683 I32 delta = 0;
2684 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
aca2d497 2685 int is_inf_internal = 0; /* The studied chunk is infinite */
c277df42
IZ
2686 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2687 scan_data_t data_fake;
a3621e74 2688 SV *re_trie_maxbuff = NULL;
786e8c11 2689 regnode *first_non_open = scan;
e2e6a0f1 2690 I32 stopmin = I32_MAX;
8aa23a47 2691 scan_frame *frame = NULL;
a3621e74 2692 GET_RE_DEBUG_FLAGS_DECL;
8aa23a47 2693
7918f24d
NC
2694 PERL_ARGS_ASSERT_STUDY_CHUNK;
2695
13a24bad 2696#ifdef DEBUGGING
40d049e4 2697 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
13a24bad 2698#endif
40d049e4 2699
786e8c11 2700 if ( depth == 0 ) {
40d049e4 2701 while (first_non_open && OP(first_non_open) == OPEN)
786e8c11
YO
2702 first_non_open=regnext(first_non_open);
2703 }
2704
b81d288d 2705
8aa23a47
YO
2706 fake_study_recurse:
2707 while ( scan && OP(scan) != END && scan < last ){
2708 /* Peephole optimizer: */
304ee84b 2709 DEBUG_STUDYDATA("Peep:", data,depth);
8aa23a47
YO
2710 DEBUG_PEEP("Peep",scan,depth);
2711 JOIN_EXACT(scan,&min,0);
2712
2713 /* Follow the next-chain of the current node and optimize
2714 away all the NOTHINGs from it. */
2715 if (OP(scan) != CURLYX) {
2716 const int max = (reg_off_by_arg[OP(scan)]
2717 ? I32_MAX
2718 /* I32 may be smaller than U16 on CRAYs! */
2719 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
2720 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
2721 int noff;
2722 regnode *n = scan;
2723
2724 /* Skip NOTHING and LONGJMP. */
2725 while ((n = regnext(n))
2726 && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
2727 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
2728 && off + noff < max)
2729 off += noff;
2730 if (reg_off_by_arg[OP(scan)])
2731 ARG(scan) = off;
2732 else
2733 NEXT_OFF(scan) = off;
2734 }
a3621e74 2735
c277df42 2736
8aa23a47
YO
2737
2738 /* The principal pseudo-switch. Cannot be a switch, since we
2739 look into several different things. */
2740 if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
2741 || OP(scan) == IFTHEN) {
2742 next = regnext(scan);
2743 code = OP(scan);
2744 /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
2745
2746 if (OP(next) == code || code == IFTHEN) {
2747 /* NOTE - There is similar code to this block below for handling
2748 TRIE nodes on a re-study. If you change stuff here check there
2749 too. */
2750 I32 max1 = 0, min1 = I32_MAX, num = 0;
2751 struct regnode_charclass_class accum;
2752 regnode * const startbranch=scan;
2753
2754 if (flags & SCF_DO_SUBSTR)
304ee84b 2755 SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
8aa23a47 2756 if (flags & SCF_DO_STCLASS)
e755fd73 2757 cl_init_zero(pRExC_state, &accum);
8aa23a47
YO
2758
2759 while (OP(scan) == code) {
2760 I32 deltanext, minnext, f = 0, fake;
2761 struct regnode_charclass_class this_class;
2762
2763 num++;
2764 data_fake.flags = 0;
2765 if (data) {
2766 data_fake.whilem_c = data->whilem_c;
2767 data_fake.last_closep = data->last_closep;
2768 }
2769 else
2770 data_fake.last_closep = &fake;
58e23c8d
YO
2771
2772 data_fake.pos_delta = delta;
8aa23a47
YO
2773 next = regnext(scan);
2774 scan = NEXTOPER(scan);
2775 if (code != BRANCH)
c277df42 2776 scan = NEXTOPER(scan);
8aa23a47 2777 if (flags & SCF_DO_STCLASS) {
e755fd73 2778 cl_init(pRExC_state, &this_class);
8aa23a47
YO
2779 data_fake.start_class = &this_class;
2780 f = SCF_DO_STCLASS_AND;
58e23c8d 2781 }
8aa23a47
YO
2782 if (flags & SCF_WHILEM_VISITED_POS)
2783 f |= SCF_WHILEM_VISITED_POS;
2784
2785 /* we suppose the run is continuous, last=next...*/
2786 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2787 next, &data_fake,
2788 stopparen, recursed, NULL, f,depth+1);
2789 if (min1 > minnext)
2790 min1 = minnext;
2791 if (max1 < minnext + deltanext)
2792 max1 = minnext + deltanext;
2793 if (deltanext == I32_MAX)
2794 is_inf = is_inf_internal = 1;
2795 scan = next;
2796 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
2797 pars++;
2798 if (data_fake.flags & SCF_SEEN_ACCEPT) {
2799 if ( stopmin > minnext)
2800 stopmin = min + min1;
2801 flags &= ~SCF_DO_SUBSTR;
2802 if (data)
2803 data->flags |= SCF_SEEN_ACCEPT;
2804 }
2805 if (data) {
2806 if (data_fake.flags & SF_HAS_EVAL)
2807 data->flags |= SF_HAS_EVAL;
2808 data->whilem_c = data_fake.whilem_c;
3dab1dad 2809 }
8aa23a47 2810 if (flags & SCF_DO_STCLASS)
aa19b56b 2811 cl_or(&accum, &this_class);
8aa23a47
YO
2812 }
2813 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
2814 min1 = 0;
2815 if (flags & SCF_DO_SUBSTR) {
2816 data->pos_min += min1;
2817 data->pos_delta += max1 - min1;
2818 if (max1 != min1 || is_inf)
2819 data->longest = &(data->longest_float);
2820 }
2821 min += min1;
2822 delta += max1 - min1;
2823 if (flags & SCF_DO_STCLASS_OR) {
aa19b56b 2824 cl_or(data->start_class, &accum);
8aa23a47
YO
2825 if (min1) {
2826 cl_and(data->start_class, and_withp);
2827 flags &= ~SCF_DO_STCLASS;
653099ff 2828 }
8aa23a47
YO
2829 }
2830 else if (flags & SCF_DO_STCLASS_AND) {
2831 if (min1) {
2832 cl_and(data->start_class, &accum);
2833 flags &= ~SCF_DO_STCLASS;
de0c8cb8 2834 }
8aa23a47
YO
2835 else {
2836 /* Switch to OR mode: cache the old value of
2837 * data->start_class */
2838 INIT_AND_WITHP;
2839 StructCopy(data->start_class, and_withp,
2840 struct regnode_charclass_class);
2841 flags &= ~SCF_DO_STCLASS_AND;
2842 StructCopy(&accum, data->start_class,
2843 struct regnode_charclass_class);
2844 flags |= SCF_DO_STCLASS_OR;
2845 data->start_class->flags |= ANYOF_EOS;
de0c8cb8 2846 }
8aa23a47 2847 }
a3621e74 2848
8aa23a47
YO
2849 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
2850 /* demq.
a3621e74 2851
8aa23a47
YO
2852 Assuming this was/is a branch we are dealing with: 'scan' now
2853 points at the item that follows the branch sequence, whatever
2854 it is. We now start at the beginning of the sequence and look
2855 for subsequences of
a3621e74 2856
8aa23a47
YO
2857 BRANCH->EXACT=>x1
2858 BRANCH->EXACT=>x2
2859 tail
a3621e74 2860
8aa23a47 2861 which would be constructed from a pattern like /A|LIST|OF|WORDS/
a3621e74 2862
486ec47a 2863 If we can find such a subsequence we need to turn the first
8aa23a47
YO
2864 element into a trie and then add the subsequent branch exact
2865 strings to the trie.
a3621e74 2866
8aa23a47 2867 We have two cases
a3621e74 2868
3b753521 2869 1. patterns where the whole set of branches can be converted.
a3621e74 2870
8aa23a47 2871 2. patterns where only a subset can be converted.
a3621e74 2872
8aa23a47
YO
2873 In case 1 we can replace the whole set with a single regop
2874 for the trie. In case 2 we need to keep the start and end
3b753521 2875 branches so
a3621e74 2876
8aa23a47
YO
2877 'BRANCH EXACT; BRANCH EXACT; BRANCH X'
2878 becomes BRANCH TRIE; BRANCH X;
786e8c11 2879
8aa23a47
YO
2880 There is an additional case, that being where there is a
2881 common prefix, which gets split out into an EXACT like node
2882 preceding the TRIE node.
a3621e74 2883
8aa23a47
YO
2884 If x(1..n)==tail then we can do a simple trie, if not we make
2885 a "jump" trie, such that when we match the appropriate word
486ec47a 2886 we "jump" to the appropriate tail node. Essentially we turn
8aa23a47 2887 a nested if into a case structure of sorts.
b515a41d 2888
8aa23a47
YO
2889 */
2890
2891 int made=0;
2892 if (!re_trie_maxbuff) {
2893 re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2894 if (!SvIOK(re_trie_maxbuff))
2895 sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2896 }
2897 if ( SvIV(re_trie_maxbuff)>=0 ) {
2898 regnode *cur;
2899 regnode *first = (regnode *)NULL;
2900 regnode *last = (regnode *)NULL;
2901 regnode *tail = scan;
2902 U8 optype = 0;
2903 U32 count=0;
a3621e74
YO
2904
2905#ifdef DEBUGGING
8aa23a47 2906 SV * const mysv = sv_newmortal(); /* for dumping */
a3621e74 2907#endif
8aa23a47
YO
2908 /* var tail is used because there may be a TAIL
2909 regop in the way. Ie, the exacts will point to the
2910 thing following the TAIL, but the last branch will
2911 point at the TAIL. So we advance tail. If we
2912 have nested (?:) we may have to move through several
2913 tails.
2914 */
2915
2916 while ( OP( tail ) == TAIL ) {
2917 /* this is the TAIL generated by (?:) */
2918 tail = regnext( tail );
2919 }
a3621e74 2920
8aa23a47
YO
2921
2922 DEBUG_OPTIMISE_r({
2923 regprop(RExC_rx, mysv, tail );
2924 PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
2925 (int)depth * 2 + 2, "",
2926 "Looking for TRIE'able sequences. Tail node is: ",
2927 SvPV_nolen_const( mysv )
2928 );
2929 });
2930
2931 /*
2932
2933 step through the branches, cur represents each
2934 branch, noper is the first thing to be matched
2935 as part of that branch and noper_next is the
2936 regnext() of that node. if noper is an EXACT
2937 and noper_next is the same as scan (our current
2938 position in the regex) then the EXACT branch is
2939 a possible optimization target. Once we have
486ec47a 2940 two or more consecutive such branches we can
8aa23a47
YO
2941 create a trie of the EXACT's contents and stich
2942 it in place. If the sequence represents all of
2943 the branches we eliminate the whole thing and
2944 replace it with a single TRIE. If it is a
2945 subsequence then we need to stitch it in. This
2946 means the first branch has to remain, and needs
2947 to be repointed at the item on the branch chain
2948 following the last branch optimized. This could
2949 be either a BRANCH, in which case the
2950 subsequence is internal, or it could be the
2951 item following the branch sequence in which
2952 case the subsequence is at the end.
2953
2954 */
2955
2956 /* dont use tail as the end marker for this traverse */
2957 for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
2958 regnode * const noper = NEXTOPER( cur );
b515a41d 2959#if defined(DEBUGGING) || defined(NOJUMPTRIE)
8aa23a47 2960 regnode * const noper_next = regnext( noper );
b515a41d
YO
2961#endif
2962
8aa23a47
YO
2963 DEBUG_OPTIMISE_r({
2964 regprop(RExC_rx, mysv, cur);
2965 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
2966 (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
2967
2968 regprop(RExC_rx, mysv, noper);
2969 PerlIO_printf( Perl_debug_log, " -> %s",
2970 SvPV_nolen_const(mysv));
2971
2972 if ( noper_next ) {
2973 regprop(RExC_rx, mysv, noper_next );
2974 PerlIO_printf( Perl_debug_log,"\t=> %s\t",
2975 SvPV_nolen_const(mysv));
2976 }
2977 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
2978 REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
2979 });
2980 if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
2981 : PL_regkind[ OP( noper ) ] == EXACT )
2982 || OP(noper) == NOTHING )
786e8c11 2983#ifdef NOJUMPTRIE
8aa23a47 2984 && noper_next == tail
786e8c11 2985#endif
8aa23a47
YO
2986 && count < U16_MAX)
2987 {
2988 count++;
2989 if ( !first || optype == NOTHING ) {
2990 if (!first) first = cur;
2991 optype = OP( noper );
2992 } else {
2993 last = cur;
2994 }
2995 } else {
a0a388a1 2996/*
0abd0d78
YO
2997 Currently we do not believe that the trie logic can
2998 handle case insensitive matching properly when the
2999 pattern is not unicode (thus forcing unicode semantics).
3000
3001 If/when this is fixed the following define can be swapped
3002 in below to fully enable trie logic.
3003
f0c16e54
KW
3004 XXX It may work if not UTF and/or /a (AT_LEAST_UNI_SEMANTICS) but perhaps
3005 not /aa
3006
a0a388a1 3007#define TRIE_TYPE_IS_SAFE 1
0abd0d78
YO
3008
3009*/
f0c16e54 3010#define TRIE_TYPE_IS_SAFE ((UTF && UNI_SEMANTICS) || optype==EXACT)
0abd0d78 3011
a0a388a1 3012 if ( last && TRIE_TYPE_IS_SAFE ) {
8aa23a47
YO
3013 make_trie( pRExC_state,
3014 startbranch, first, cur, tail, count,
3015 optype, depth+1 );
3016 }
3017 if ( PL_regkind[ OP( noper ) ] == EXACT
786e8c11 3018#ifdef NOJUMPTRIE
8aa23a47 3019 && noper_next == tail
786e8c11 3020#endif
8aa23a47
YO
3021 ){
3022 count = 1;
3023 first = cur;
3024 optype = OP( noper );
3025 } else {
3026 count = 0;
3027 first = NULL;
3028 optype = 0;
3029 }
3030 last = NULL;
3031 }
3032 }
3033 DEBUG_OPTIMISE_r({
3034 regprop(RExC_rx, mysv, cur);
3035 PerlIO_printf( Perl_debug_log,
3036 "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
3037 "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
3038
3039 });
a0a388a1
YO
3040
3041 if ( last && TRIE_TYPE_IS_SAFE ) {
8aa23a47 3042 made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
3dab1dad 3043#ifdef TRIE_STUDY_OPT
8aa23a47
YO
3044 if ( ((made == MADE_EXACT_TRIE &&
3045 startbranch == first)
3046 || ( first_non_open == first )) &&
3047 depth==0 ) {
3048 flags |= SCF_TRIE_RESTUDY;
3049 if ( startbranch == first
3050 && scan == tail )
3051 {
3052 RExC_seen &=~REG_TOP_LEVEL_BRANCHES;
3053 }
3054 }
3dab1dad 3055#endif
8aa23a47
YO
3056 }
3057 }
3058
3059 } /* do trie */
3060
653099ff 3061 }
8aa23a47
YO
3062 else if ( code == BRANCHJ ) { /* single branch is optimized. */
3063 scan = NEXTOPER(NEXTOPER(scan));
3064 } else /* single branch is optimized. */
3065 scan = NEXTOPER(scan);
3066 continue;
3067 } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
3068 scan_frame *newframe = NULL;
3069 I32 paren;
3070 regnode *start;
3071 regnode *end;
3072
3073 if (OP(scan) != SUSPEND) {
3074 /* set the pointer */
3075 if (OP(scan) == GOSUB) {
3076 paren = ARG(scan);
3077 RExC_recurse[ARG2L(scan)] = scan;
3078 start = RExC_open_parens[paren-1];
3079 end = RExC_close_parens[paren-1];
3080 } else {
3081 paren = 0;
f8fc2ecf 3082 start = RExC_rxi->program + 1;
8aa23a47
YO
3083 end = RExC_opend;
3084 }
3085 if (!recursed) {
3086 Newxz(recursed, (((RExC_npar)>>3) +1), U8);
3087 SAVEFREEPV(recursed);
3088 }
3089 if (!PAREN_TEST(recursed,paren+1)) {
3090 PAREN_SET(recursed,paren+1);
3091 Newx(newframe,1,scan_frame);
3092 } else {
3093 if (flags & SCF_DO_SUBSTR) {
304ee84b 3094 SCAN_COMMIT(pRExC_state,data,minlenp);
8aa23a47
YO
3095 data->longest = &(data->longest_float);
3096 }
3097 is_inf = is_inf_internal = 1;
3098 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
2f88b857 3099 cl_anything(data->start_class);
8aa23a47
YO
3100 flags &= ~SCF_DO_STCLASS;
3101 }
3102 } else {
3103 Newx(newframe,1,scan_frame);
3104 paren = stopparen;
3105 start = scan+2;
3106 end = regnext(scan);
3107 }
3108 if (newframe) {
3109 assert(start);
3110 assert(end);
3111 SAVEFREEPV(newframe);
3112 newframe->next = regnext(scan);
3113 newframe->last = last;
3114 newframe->stop = stopparen;
3115 newframe->prev = frame;
3116
3117 frame = newframe;
3118 scan = start;
3119 stopparen = paren;
3120 last = end;
3121
3122 continue;
3123 }
3124 }
3125 else if (OP(scan) == EXACT) {
3126 I32 l = STR_LEN(scan);
3127 UV uc;
3128 if (UTF) {
3129 const U8 * const s = (U8*)STRING(scan);
3130 l = utf8_length(s, s + l);
3131 uc = utf8_to_uvchr(s, NULL);
3132 } else {
3133 uc = *((U8*)STRING(scan));
3134 }
3135 min += l;
3136 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
3137 /* The code below prefers earlier match for fixed
3138 offset, later match for variable offset. */
3139 if (data->last_end == -1) { /* Update the start info. */
3140 data->last_start_min = data->pos_min;
3141 data->last_start_max = is_inf
3142 ? I32_MAX : data->pos_min + data->pos_delta;
b515a41d 3143 }
8aa23a47
YO
3144 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
3145 if (UTF)
3146 SvUTF8_on(data->last_found);
3147 {
3148 SV * const sv = data->last_found;
3149 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3150 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3151 if (mg && mg->mg_len >= 0)
3152 mg->mg_len += utf8_length((U8*)STRING(scan),
3153 (U8*)STRING(scan)+STR_LEN(scan));
b515a41d 3154 }
8aa23a47
YO
3155 data->last_end = data->pos_min + l;
3156 data->pos_min += l; /* As in the first entry. */
3157 data->flags &= ~SF_BEFORE_EOL;
3158 }
3159 if (flags & SCF_DO_STCLASS_AND) {
3160 /* Check whether it is compatible with what we know already! */
3161 int compat = 1;
3162
54251c2e 3163
486ec47a 3164 /* If compatible, we or it in below. It is compatible if is
54251c2e
KW
3165 * in the bitmp and either 1) its bit or its fold is set, or 2)
3166 * it's for a locale. Even if there isn't unicode semantics
3167 * here, at runtime there may be because of matching against a
3168 * utf8 string, so accept a possible false positive for
3169 * latin1-range folds */
8aa23a47
YO
3170 if (uc >= 0x100 ||
3171 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
3172 && !ANYOF_BITMAP_TEST(data->start_class, uc)
39065660 3173 && (!(data->start_class->flags & ANYOF_LOC_NONBITMAP_FOLD)
54251c2e 3174 || !ANYOF_BITMAP_TEST(data->start_class, PL_fold_latin1[uc])))
8aa23a47 3175 )
d18bf9dc 3176 {
8aa23a47 3177 compat = 0;
d18bf9dc 3178 }
8aa23a47
YO
3179 ANYOF_CLASS_ZERO(data->start_class);
3180 ANYOF_BITMAP_ZERO(data->start_class);
3181 if (compat)
3182 ANYOF_BITMAP_SET(data->start_class, uc);
d18bf9dc
KW
3183 else if (uc >= 0x100) {
3184 int i;
3185
3186 /* Some Unicode code points fold to the Latin1 range; as
3187 * XXX temporary code, instead of figuring out if this is
3188 * one, just assume it is and set all the start class bits
3189 * that could be some such above 255 code point's fold
3190 * which will generate fals positives. As the code
3191 * elsewhere that does compute the fold settles down, it
3192 * can be extracted out and re-used here */
3193 for (i = 0; i < 256; i++){
3194 if (_HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)) {
3195 ANYOF_BITMAP_SET(data->start_class, i);
3196 }
3197 }
3198 }
8aa23a47
YO
3199 data->start_class->flags &= ~ANYOF_EOS;
3200 if (uc < 0x100)
3201 data->start_class->flags &= ~ANYOF_UNICODE_ALL;
3202 }
3203 else if (flags & SCF_DO_STCLASS_OR) {
3204 /* false positive possible if the class is case-folded */
3205 if (uc < 0x100)
3206 ANYOF_BITMAP_SET(data->start_class, uc);
3207 else
3208 data->start_class->flags |= ANYOF_UNICODE_ALL;
3209 data->start_class->flags &= ~ANYOF_EOS;
3210 cl_and(data->start_class, and_withp);
3211 }
3212 flags &= ~SCF_DO_STCLASS;
3213 }
3214 else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
3215 I32 l = STR_LEN(scan);
3216 UV uc = *((U8*)STRING(scan));
3217
3218 /* Search for fixed substrings supports EXACT only. */
3219 if (flags & SCF_DO_SUBSTR) {
3220 assert(data);
304ee84b 3221 SCAN_COMMIT(pRExC_state, data, minlenp);
8aa23a47
YO
3222 }
3223 if (UTF) {
3224 const U8 * const s = (U8 *)STRING(scan);
3225 l = utf8_length(s, s + l);
3226 uc = utf8_to_uvchr(s, NULL);
3227 }
3228 min += l;
3229 if (flags & SCF_DO_SUBSTR)
3230 data->pos_min += l;
3231 if (flags & SCF_DO_STCLASS_AND) {
3232 /* Check whether it is compatible with what we know already! */
3233 int compat = 1;
8aa23a47 3234 if (uc >= 0x100 ||
54251c2e
KW
3235 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
3236 && !ANYOF_BITMAP_TEST(data->start_class, uc)
3237 && !ANYOF_BITMAP_TEST(data->start_class, PL_fold_latin1[uc])))
3238 {
8aa23a47 3239 compat = 0;
54251c2e 3240 }
8aa23a47
YO
3241 ANYOF_CLASS_ZERO(data->start_class);
3242 ANYOF_BITMAP_ZERO(data->start_class);
3243 if (compat) {
3244 ANYOF_BITMAP_SET(data->start_class, uc);
653099ff 3245 data->start_class->flags &= ~ANYOF_EOS;
39065660 3246 data->start_class->flags |= ANYOF_LOC_NONBITMAP_FOLD;
970c8436 3247 if (OP(scan) == EXACTFL) {
af302e7f
KW
3248 /* XXX This set is probably no longer necessary, and
3249 * probably wrong as LOCALE now is on in the initial
3250 * state */
8aa23a47 3251 data->start_class->flags |= ANYOF_LOCALE;
970c8436
KW
3252 }
3253 else {
3254
54251c2e
KW
3255 /* Also set the other member of the fold pair. In case
3256 * that unicode semantics is called for at runtime, use
3257 * the full latin1 fold. (Can't do this for locale,
3258 * because not known until runtime */
3259 ANYOF_BITMAP_SET(data->start_class, PL_fold_latin1[uc]);
970c8436 3260 }
653099ff 3261 }
d18bf9dc
KW
3262 else if (uc >= 0x100) {
3263 int i;
3264 for (i = 0; i < 256; i++){
3265 if (_HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)) {
3266 ANYOF_BITMAP_SET(data->start_class, i);
3267 }
3268 }
3269 }
8aa23a47
YO
3270 }
3271 else if (flags & SCF_DO_STCLASS_OR) {
39065660 3272 if (data->start_class->flags & ANYOF_LOC_NONBITMAP_FOLD) {
8aa23a47
YO
3273 /* false positive possible if the class is case-folded.
3274 Assume that the locale settings are the same... */
970c8436 3275 if (uc < 0x100) {
1aa99e6b 3276 ANYOF_BITMAP_SET(data->start_class, uc);
970c8436
KW
3277 if (OP(scan) != EXACTFL) {
3278
3279 /* And set the other member of the fold pair, but
3280 * can't do that in locale because not known until
3281 * run-time */
3282 ANYOF_BITMAP_SET(data->start_class,
54251c2e 3283 PL_fold_latin1[uc]);
970c8436
KW
3284 }
3285 }
653099ff
GS
3286 data->start_class->flags &= ~ANYOF_EOS;
3287 }
8aa23a47 3288 cl_and(data->start_class, and_withp);
653099ff 3289 }
8aa23a47
YO
3290 flags &= ~SCF_DO_STCLASS;
3291 }
e52fc539 3292 else if (REGNODE_VARIES(OP(scan))) {
8aa23a47
YO
3293 I32 mincount, maxcount, minnext, deltanext, fl = 0;
3294 I32 f = flags, pos_before = 0;
3295 regnode * const oscan = scan;
3296 struct regnode_charclass_class this_class;
3297 struct regnode_charclass_class *oclass = NULL;
3298 I32 next_is_eval = 0;
3299
3300 switch (PL_regkind[OP(scan)]) {
3301 case WHILEM: /* End of (?:...)* . */
3302 scan = NEXTOPER(scan);
3303 goto finish;
3304 case PLUS:
3305 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
3306 next = NEXTOPER(scan);
3307 if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
3308 mincount = 1;
3309 maxcount = REG_INFTY;
3310 next = regnext(scan);
3311 scan = NEXTOPER(scan);
3312 goto do_curly;
3313 }
3314 }
3315 if (flags & SCF_DO_SUBSTR)
3316 data->pos_min++;
3317 min++;
3318 /* Fall through. */
3319 case STAR:
3320 if (flags & SCF_DO_STCLASS) {
3321 mincount = 0;
3322 maxcount = REG_INFTY;
3323 next = regnext(scan);
3324 scan = NEXTOPER(scan);
3325 goto do_curly;
3326 }
3327 is_inf = is_inf_internal = 1;
3328 scan = regnext(scan);
c277df42 3329 if (flags & SCF_DO_SUBSTR) {
304ee84b 3330 SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
8aa23a47 3331 data->longest = &(data->longest_float);
c277df42 3332 }
8aa23a47
YO
3333 goto optimize_curly_tail;
3334 case CURLY:
3335 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
3336 && (scan->flags == stopparen))
3337 {
3338 mincount = 1;
3339 maxcount = 1;
3340 } else {
3341 mincount = ARG1(scan);
3342 maxcount = ARG2(scan);
653099ff 3343 }
8aa23a47
YO
3344 next = regnext(scan);
3345 if (OP(scan) == CURLYX) {
3346 I32 lp = (data ? *(data->last_closep) : 0);
3347 scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
653099ff 3348 }
8aa23a47
YO
3349 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
3350 next_is_eval = (OP(scan) == EVAL);
3351 do_curly:
3352 if (flags & SCF_DO_SUBSTR) {
304ee84b 3353 if (mincount == 0) SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
8aa23a47 3354 pos_before = data->pos_min;
b45f050a 3355 }
8aa23a47
YO
3356 if (data) {
3357 fl = data->flags;
3358 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
3359 if (is_inf)
3360 data->flags |= SF_IS_INF;
3361 }
3362 if (flags & SCF_DO_STCLASS) {
e755fd73 3363 cl_init(pRExC_state, &this_class);
8aa23a47
YO
3364 oclass = data->start_class;
3365 data->start_class = &this_class;
3366 f |= SCF_DO_STCLASS_AND;
3367 f &= ~SCF_DO_STCLASS_OR;
3368 }
779bcb7d
NC
3369 /* Exclude from super-linear cache processing any {n,m}
3370 regops for which the combination of input pos and regex
3371 pos is not enough information to determine if a match
3372 will be possible.
3373
3374 For example, in the regex /foo(bar\s*){4,8}baz/ with the
3375 regex pos at the \s*, the prospects for a match depend not
3376 only on the input position but also on how many (bar\s*)
3377 repeats into the {4,8} we are. */
3378 if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
8aa23a47 3379 f &= ~SCF_WHILEM_VISITED_POS;
b45f050a 3380
8aa23a47
YO
3381 /* This will finish on WHILEM, setting scan, or on NULL: */
3382 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
3383 last, data, stopparen, recursed, NULL,
3384 (mincount == 0
3385 ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
b515a41d 3386
8aa23a47
YO
3387 if (flags & SCF_DO_STCLASS)
3388 data->start_class = oclass;
3389 if (mincount == 0 || minnext == 0) {
3390 if (flags & SCF_DO_STCLASS_OR) {
aa19b56b 3391 cl_or(data->start_class, &this_class);
8aa23a47
YO
3392 }
3393 else if (flags & SCF_DO_STCLASS_AND) {
3394 /* Switch to OR mode: cache the old value of
3395 * data->start_class */
3396 INIT_AND_WITHP;
3397 StructCopy(data->start_class, and_withp,
3398 struct regnode_charclass_class);
3399 flags &= ~SCF_DO_STCLASS_AND;
3400 StructCopy(&this_class, data->start_class,
3401 struct regnode_charclass_class);
3402 flags |= SCF_DO_STCLASS_OR;
3403 data->start_class->flags |= ANYOF_EOS;
3404 }
3405 } else { /* Non-zero len */
3406 if (flags & SCF_DO_STCLASS_OR) {
aa19b56b 3407 cl_or(data->start_class, &this_class);
8aa23a47
YO
3408 cl_and(data->start_class, and_withp);
3409 }
3410 else if (flags & SCF_DO_STCLASS_AND)
3411 cl_and(data->start_class, &this_class);
3412 flags &= ~SCF_DO_STCLASS;
3413 }
3414 if (!scan) /* It was not CURLYX, but CURLY. */
3415 scan = next;
3416 if ( /* ? quantifier ok, except for (?{ ... }) */
3417 (next_is_eval || !(mincount == 0 && maxcount == 1))
3418 && (minnext == 0) && (deltanext == 0)
3419 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
668c081a 3420 && maxcount <= REG_INFTY/3) /* Complement check for big count */
8aa23a47 3421 {
668c081a
NC
3422 ckWARNreg(RExC_parse,
3423 "Quantifier unexpected on zero-length expression");
8aa23a47
YO
3424 }
3425
3426 min += minnext * mincount;
3427 is_inf_internal |= ((maxcount == REG_INFTY
3428 && (minnext + deltanext) > 0)
3429 || deltanext == I32_MAX);
3430 is_inf |= is_inf_internal;
3431 delta += (minnext + deltanext) * maxcount - minnext * mincount;
3432
3433 /* Try powerful optimization CURLYX => CURLYN. */
3434 if ( OP(oscan) == CURLYX && data
3435 && data->flags & SF_IN_PAR
3436 && !(data->flags & SF_HAS_EVAL)
3437 && !deltanext && minnext == 1 ) {
3438 /* Try to optimize to CURLYN. */
3439 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
3440 regnode * const nxt1 = nxt;
497b47a8 3441#ifdef DEBUGGING
8aa23a47 3442 regnode *nxt2;
497b47a8 3443#endif
c277df42 3444
8aa23a47
YO
3445 /* Skip open. */
3446 nxt = regnext(nxt);
e52fc539 3447 if (!REGNODE_SIMPLE(OP(nxt))
8aa23a47
YO
3448 && !(PL_regkind[OP(nxt)] == EXACT
3449 && STR_LEN(nxt) == 1))
3450 goto nogo;
497b47a8 3451#ifdef DEBUGGING
8aa23a47 3452 nxt2 = nxt;
497b47a8 3453#endif
8aa23a47
YO
3454 nxt = regnext(nxt);
3455 if (OP(nxt) != CLOSE)
3456 goto nogo;
3457 if (RExC_open_parens) {
3458 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3459 RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
3460 }
3461 /* Now we know that nxt2 is the only contents: */
3462 oscan->flags = (U8)ARG(nxt);
3463 OP(oscan) = CURLYN;
3464 OP(nxt1) = NOTHING; /* was OPEN. */
40d049e4 3465
c277df42 3466#ifdef DEBUGGING
8aa23a47 3467 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
fda99bee
KW
3468 NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
3469 NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
8aa23a47
YO
3470 OP(nxt) = OPTIMIZED; /* was CLOSE. */
3471 OP(nxt + 1) = OPTIMIZED; /* was count. */
fda99bee 3472 NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
b81d288d 3473#endif
8aa23a47
YO
3474 }
3475 nogo:
3476
3477 /* Try optimization CURLYX => CURLYM. */
3478 if ( OP(oscan) == CURLYX && data
3479 && !(data->flags & SF_HAS_PAR)
3480 && !(data->flags & SF_HAS_EVAL)
3481 && !deltanext /* atom is fixed width */
3482 && minnext != 0 /* CURLYM can't handle zero width */
3483 ) {
3484 /* XXXX How to optimize if data == 0? */
3485 /* Optimize to a simpler form. */
3486 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
3487 regnode *nxt2;
3488
3489 OP(oscan) = CURLYM;
3490 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
3491 && (OP(nxt2) != WHILEM))
3492 nxt = nxt2;
3493 OP(nxt2) = SUCCEED; /* Whas WHILEM */
3494 /* Need to optimize away parenths. */
b3c0965f 3495 if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
8aa23a47
YO
3496 /* Set the parenth number. */
3497 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
3498
8aa23a47
YO
3499 oscan->flags = (U8)ARG(nxt);
3500 if (RExC_open_parens) {
3501 RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3502 RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
40d049e4 3503 }
8aa23a47
YO
3504 OP(nxt1) = OPTIMIZED; /* was OPEN. */
3505 OP(nxt) = OPTIMIZED; /* was CLOSE. */
40d049e4 3506
c277df42 3507#ifdef DEBUGGING
8aa23a47
YO
3508 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3509 OP(nxt + 1) = OPTIMIZED; /* was count. */
486ec47a
PA
3510 NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
3511 NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
b81d288d 3512#endif
c277df42 3513#if 0
8aa23a47
YO
3514 while ( nxt1 && (OP(nxt1) != WHILEM)) {
3515 regnode *nnxt = regnext(nxt1);
8aa23a47
YO
3516 if (nnxt == nxt) {
3517 if (reg_off_by_arg[OP(nxt1)])
3518 ARG_SET(nxt1, nxt2 - nxt1);
3519 else if (nxt2 - nxt1 < U16_MAX)
3520 NEXT_OFF(nxt1) = nxt2 - nxt1;
3521 else
3522 OP(nxt) = NOTHING; /* Cannot beautify */
c277df42 3523 }
8aa23a47 3524 nxt1 = nnxt;
c277df42 3525 }
5d1c421c 3526#endif
8aa23a47
YO
3527 /* Optimize again: */
3528 study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
3529 NULL, stopparen, recursed, NULL, 0,depth+1);
3530 }
3531 else
3532 oscan->flags = 0;
3533 }
3534 else if ((OP(oscan) == CURLYX)
3535 && (flags & SCF_WHILEM_VISITED_POS)
3536 /* See the comment on a similar expression above.
3b753521 3537 However, this time it's not a subexpression
8aa23a47
YO
3538 we care about, but the expression itself. */
3539 && (maxcount == REG_INFTY)
3540 && data && ++data->whilem_c < 16) {
3541 /* This stays as CURLYX, we can put the count/of pair. */
3542 /* Find WHILEM (as in regexec.c) */
3543 regnode *nxt = oscan + NEXT_OFF(oscan);
3544
3545 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
3546 nxt += ARG(nxt);
3547 PREVOPER(nxt)->flags = (U8)(data->whilem_c
3548 | (RExC_whilem_seen << 4)); /* On WHILEM */
3549 }
3550 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
3551 pars++;
3552 if (flags & SCF_DO_SUBSTR) {
3553 SV *last_str = NULL;
3554 int counted = mincount != 0;
a0ed51b3 3555
8aa23a47
YO
3556 if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
3557#if defined(SPARC64_GCC_WORKAROUND)
3558 I32 b = 0;
3559 STRLEN l = 0;
3560 const char *s = NULL;
3561 I32 old = 0;
b515a41d 3562
8aa23a47
YO
3563 if (pos_before >= data->last_start_min)
3564 b = pos_before;
3565 else
3566 b = data->last_start_min;
b515a41d 3567
8aa23a47
YO
3568 l = 0;
3569 s = SvPV_const(data->last_found, l);
3570 old = b - data->last_start_min;
3571
3572#else
3573 I32 b = pos_before >= data->last_start_min
3574 ? pos_before : data->last_start_min;
3575 STRLEN l;
3576 const char * const s = SvPV_const(data->last_found, l);
3577 I32 old = b - data->last_start_min;
3578#endif
3579
3580 if (UTF)
3581 old = utf8_hop((U8*)s, old) - (U8*)s;
8aa23a47
YO
3582 l -= old;
3583 /* Get the added string: */
740cce10 3584 last_str = newSVpvn_utf8(s + old, l, UTF);
8aa23a47
YO
3585 if (deltanext == 0 && pos_before == b) {
3586 /* What was added is a constant string */
3587 if (mincount > 1) {
3588 SvGROW(last_str, (mincount * l) + 1);
3589 repeatcpy(SvPVX(last_str) + l,
3590 SvPVX_const(last_str), l, mincount - 1);
3591 SvCUR_set(last_str, SvCUR(last_str) * mincount);
3592 /* Add additional parts. */
3593 SvCUR_set(data->last_found,
3594 SvCUR(data->last_found) - l);
3595 sv_catsv(data->last_found, last_str);
3596 {
3597 SV * sv = data->last_found;
3598 MAGIC *mg =
3599 SvUTF8(sv) && SvMAGICAL(sv) ?
3600 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3601 if (mg && mg->mg_len >= 0)
bd94e887 3602 mg->mg_len += CHR_SVLEN(last_str) - l;
b515a41d 3603 }
8aa23a47 3604 data->last_end += l * (mincount - 1);
b515a41d 3605 }
8aa23a47
YO
3606 } else {
3607 /* start offset must point into the last copy */
3608 data->last_start_min += minnext * (mincount - 1);
3609 data->last_start_max += is_inf ? I32_MAX
3610 : (maxcount - 1) * (minnext + data->pos_delta);
3611 }
c277df42 3612 }
8aa23a47
YO
3613 /* It is counted once already... */
3614 data->pos_min += minnext * (mincount - counted);
3615 data->pos_delta += - counted * deltanext +
3616 (minnext + deltanext) * maxcount - minnext * mincount;
3617 if (mincount != maxcount) {
3618 /* Cannot extend fixed substrings found inside
3619 the group. */
304ee84b 3620 SCAN_COMMIT(pRExC_state,data,minlenp);
8aa23a47
YO
3621 if (mincount && last_str) {
3622 SV * const sv = data->last_found;
3623 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3624 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3625
3626 if (mg)
3627 mg->mg_len = -1;
3628 sv_setsv(sv, last_str);
3629 data->last_end = data->pos_min;
3630 data->last_start_min =
3631 data->pos_min - CHR_SVLEN(last_str);
3632 data->last_start_max = is_inf
3633 ? I32_MAX
3634 : data->pos_min + data->pos_delta
3635 - CHR_SVLEN(last_str);
3636 }
3637 data->longest = &(data->longest_float);
3638 }
3639 SvREFCNT_dec(last_str);
c277df42 3640 }
8aa23a47
YO
3641 if (data && (fl & SF_HAS_EVAL))
3642 data->flags |= SF_HAS_EVAL;
3643 optimize_curly_tail:
3644 if (OP(oscan) != CURLYX) {
3645 while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
3646 && NEXT_OFF(next))
3647 NEXT_OFF(oscan) += NEXT_OFF(next);
3648 }
3649 continue;
f56b6394 3650 default: /* REF, ANYOFV, and CLUMP only? */
8aa23a47 3651 if (flags & SCF_DO_SUBSTR) {
304ee84b 3652 SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
8aa23a47
YO
3653 data->longest = &(data->longest_float);
3654 }
3655 is_inf = is_inf_internal = 1;
3656 if (flags & SCF_DO_STCLASS_OR)
2f88b857 3657 cl_anything(data->start_class);
8aa23a47
YO
3658 flags &= ~SCF_DO_STCLASS;
3659 break;
c277df42 3660 }
8aa23a47 3661 }
e1d1eefb
YO
3662 else if (OP(scan) == LNBREAK) {
3663 if (flags & SCF_DO_STCLASS) {
3664 int value = 0;
3665 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3666 if (flags & SCF_DO_STCLASS_AND) {
3667 for (value = 0; value < 256; value++)
e64b1bd1 3668 if (!is_VERTWS_cp(value))
b9a59e08
KW
3669 ANYOF_BITMAP_CLEAR(data->start_class, value);
3670 }
3671 else {
e1d1eefb 3672 for (value = 0; value < 256; value++)
e64b1bd1 3673 if (is_VERTWS_cp(value))
b9a59e08
KW
3674 ANYOF_BITMAP_SET(data->start_class, value);
3675 }
e1d1eefb
YO
3676 if (flags & SCF_D