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