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