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