5 * "A fair jaw-cracker dwarf-language must be." --Samwise Gamgee
8 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
9 * confused with the original package (see point 3 below). Thanks, Henry!
12 /* Additional note: this code is very heavily munged from Henry's version
13 * in places. In some spots I've traded clarity for efficiency, so don't
14 * blame Henry for some of the lack of readability.
17 /* The names of the functions have been changed from regcomp and
18 * regexec to pregcomp and pregexec in order to avoid conflicts
19 * with the POSIX routines of the same names.
22 #ifdef PERL_EXT_RE_BUILD
23 /* need to replace pregcomp et al, so enable that */
24 # ifndef PERL_IN_XSUB_RE
25 # define PERL_IN_XSUB_RE
27 /* need access to debugger hooks */
28 # if defined(PERL_EXT_RE_DEBUG) && !defined(DEBUGGING)
33 #ifdef PERL_IN_XSUB_RE
34 /* We *really* need to overwrite these symbols: */
35 # define Perl_pregcomp my_regcomp
36 # define Perl_regdump my_regdump
37 # define Perl_regprop my_regprop
38 # define Perl_pregfree my_regfree
39 # define Perl_re_intuit_string my_re_intuit_string
40 /* *These* symbols are masked to allow static link. */
41 # define Perl_regnext my_regnext
42 # define Perl_save_re_context my_save_re_context
43 # define Perl_reginitcolors my_reginitcolors
45 # define PERL_NO_GET_CONTEXT
50 * pregcomp and pregexec -- regsub and regerror are not used in perl
52 * Copyright (c) 1986 by University of Toronto.
53 * Written by Henry Spencer. Not derived from licensed software.
55 * Permission is granted to anyone to use this software for any
56 * purpose on any computer system, and to redistribute it freely,
57 * subject to the following restrictions:
59 * 1. The author is not responsible for the consequences of use of
60 * this software, no matter how awful, even if they arise
63 * 2. The origin of this software must not be misrepresented, either
64 * by explicit claim or by omission.
66 * 3. Altered versions must be plainly marked as such, and must not
67 * be misrepresented as being the original software.
70 **** Alterations to Henry's code are...
72 **** Copyright (c) 1991-2001, Larry Wall
74 **** You may distribute under the terms of either the GNU General Public
75 **** License or the Artistic License, as specified in the README file.
78 * Beware that some of this code is subtly aware of the way operator
79 * precedence is structured in regular expressions. Serious changes in
80 * regular-expression syntax might require a total rethink.
83 #define PERL_IN_REGCOMP_C
86 #ifndef PERL_IN_XSUB_RE
98 # if defined(BUGGY_MSC6)
99 /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
100 # pragma optimize("a",off)
101 /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
102 # pragma optimize("w",on )
103 # endif /* BUGGY_MSC6 */
107 #define STATIC static
110 typedef struct RExC_state_t {
111 U16 flags16; /* are we folding, multilining? */
112 char *precomp; /* uncompiled string. */
114 char *start; /* Start of input for compile */
115 char *end; /* End of input for compile */
116 char *parse; /* Input-scan pointer. */
117 I32 whilem_seen; /* number of WHILEM in this expr */
118 regnode *emit_start; /* Start of emitted-code area */
119 regnode *emit; /* Code-emit pointer; ®dummy = don't = compiling */
120 I32 naughty; /* How bad is this pattern? */
121 I32 sawback; /* Did we see \1, ...? */
123 I32 size; /* Code size. */
124 I32 npar; /* () count. */
130 char *starttry; /* -Dr: where regtry was called. */
131 #define RExC_starttry (pRExC_state->starttry)
135 #define RExC_flags16 (pRExC_state->flags16)
136 #define RExC_precomp (pRExC_state->precomp)
137 #define RExC_rx (pRExC_state->rx)
138 #define RExC_start (pRExC_state->start)
139 #define RExC_end (pRExC_state->end)
140 #define RExC_parse (pRExC_state->parse)
141 #define RExC_whilem_seen (pRExC_state->whilem_seen)
142 #define RExC_offsets (pRExC_state->rx->offsets) /* I am not like the others */
143 #define RExC_emit (pRExC_state->emit)
144 #define RExC_emit_start (pRExC_state->emit_start)
145 #define RExC_naughty (pRExC_state->naughty)
146 #define RExC_sawback (pRExC_state->sawback)
147 #define RExC_seen (pRExC_state->seen)
148 #define RExC_size (pRExC_state->size)
149 #define RExC_npar (pRExC_state->npar)
150 #define RExC_extralen (pRExC_state->extralen)
151 #define RExC_seen_zerolen (pRExC_state->seen_zerolen)
152 #define RExC_seen_evals (pRExC_state->seen_evals)
153 #define RExC_utf8 (pRExC_state->utf8)
155 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
156 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
157 ((*s) == '{' && regcurly(s)))
160 #undef SPSTART /* dratted cpp namespace... */
163 * Flags to be passed up and down.
165 #define WORST 0 /* Worst case. */
166 #define HASWIDTH 0x1 /* Known to match non-null strings. */
167 #define SIMPLE 0x2 /* Simple enough to be STAR/PLUS operand. */
168 #define SPSTART 0x4 /* Starts with * or +. */
169 #define TRYAGAIN 0x8 /* Weeded out a declaration. */
171 /* Length of a variant. */
173 typedef struct scan_data_t {
179 I32 last_end; /* min value, <0 unless valid. */
182 SV **longest; /* Either &l_fixed, or &l_float. */
186 I32 offset_float_min;
187 I32 offset_float_max;
191 struct regnode_charclass_class *start_class;
195 * Forward declarations for pregcomp()'s friends.
198 static scan_data_t zero_scan_data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
201 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
202 #define SF_BEFORE_SEOL 0x1
203 #define SF_BEFORE_MEOL 0x2
204 #define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
205 #define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
208 # define SF_FIX_SHIFT_EOL (0+2)
209 # define SF_FL_SHIFT_EOL (0+4)
211 # define SF_FIX_SHIFT_EOL (+2)
212 # define SF_FL_SHIFT_EOL (+4)
215 #define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
216 #define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
218 #define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
219 #define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
220 #define SF_IS_INF 0x40
221 #define SF_HAS_PAR 0x80
222 #define SF_IN_PAR 0x100
223 #define SF_HAS_EVAL 0x200
224 #define SCF_DO_SUBSTR 0x400
225 #define SCF_DO_STCLASS_AND 0x0800
226 #define SCF_DO_STCLASS_OR 0x1000
227 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
228 #define SCF_WHILEM_VISITED_POS 0x2000
230 #define UTF RExC_utf8
231 #define LOC (RExC_flags16 & PMf_LOCALE)
232 #define FOLD (RExC_flags16 & PMf_FOLD)
234 #define OOB_UNICODE 12345678
235 #define OOB_NAMEDCLASS -1
237 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
238 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
241 /* length of regex to show in messages that don't mark a position within */
242 #define RegexLengthToShowInErrorMessages 127
245 * If MARKER[12] are adjusted, be sure to adjust the constants at the top
246 * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
247 * op/pragma/warn/regcomp.
249 #define MARKER1 "<-- HERE" /* marker as it appears in the description */
250 #define MARKER2 " <-- HERE " /* marker as it appears within the regex */
252 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
255 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
256 * arg. Show regex, up to a maximum length. If it's too long, chop and add
261 char *ellipses = ""; \
262 IV len = RExC_end - RExC_precomp; \
265 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
267 if (len > RegexLengthToShowInErrorMessages) { \
268 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
269 len = RegexLengthToShowInErrorMessages - 10; \
272 Perl_croak(aTHX_ "%s in regex m/%.*s%s/", \
273 msg, (int)len, RExC_precomp, ellipses); \
277 * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
278 * args. Show regex, up to a maximum length. If it's too long, chop and add
281 #define FAIL2(pat,msg) \
283 char *ellipses = ""; \
284 IV len = RExC_end - RExC_precomp; \
287 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
289 if (len > RegexLengthToShowInErrorMessages) { \
290 /* chop 10 shorter than the max, to ensure meaning of "..." */ \
291 len = RegexLengthToShowInErrorMessages - 10; \
294 S_re_croak2(aTHX_ pat, " in regex m/%.*s%s/", \
295 msg, (int)len, RExC_precomp, ellipses); \
300 * Simple_vFAIL -- like FAIL, but marks the current location in the scan
302 #define Simple_vFAIL(m) \
304 IV offset = RExC_parse - RExC_precomp; \
306 Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
307 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
311 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
316 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
321 * Like Simple_vFAIL(), but accepts two arguments.
323 #define Simple_vFAIL2(m,a1) \
325 IV offset = RExC_parse - RExC_precomp; \
327 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, \
328 (int)offset, RExC_precomp, RExC_precomp + offset); \
332 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
334 #define vFAIL2(m,a1) \
337 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
338 Simple_vFAIL2(m, a1); \
343 * Like Simple_vFAIL(), but accepts three arguments.
345 #define Simple_vFAIL3(m, a1, a2) \
347 IV offset = RExC_parse - RExC_precomp; \
349 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, \
350 (int)offset, RExC_precomp, RExC_precomp + offset); \
354 * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
356 #define vFAIL3(m,a1,a2) \
359 SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx); \
360 Simple_vFAIL3(m, a1, a2); \
364 * Like Simple_vFAIL(), but accepts four arguments.
366 #define Simple_vFAIL4(m, a1, a2, a3) \
368 IV offset = RExC_parse - RExC_precomp; \
370 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3,\
371 (int)offset, RExC_precomp, RExC_precomp + offset); \
375 * Like Simple_vFAIL(), but accepts five arguments.
377 #define Simple_vFAIL5(m, a1, a2, a3, a4) \
379 IV offset = RExC_parse - RExC_precomp; \
380 S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, a4,\
381 (int)offset, RExC_precomp, RExC_precomp + offset); \
385 #define vWARN(loc,m) \
387 IV offset = loc - RExC_precomp; \
388 Perl_warner(aTHX_ WARN_REGEXP, "%s" REPORT_LOCATION,\
389 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
392 #define vWARNdep(loc,m) \
394 IV offset = loc - RExC_precomp; \
395 int warn_cat = ckWARN(WARN_REGEXP) ? WARN_REGEXP : WARN_DEPRECATED; \
396 Perl_warner(aTHX_ warn_cat, "%s" REPORT_LOCATION,\
397 m, (int)offset, RExC_precomp, RExC_precomp + offset); \
401 #define vWARN2(loc, m, a1) \
403 IV offset = loc - RExC_precomp; \
404 Perl_warner(aTHX_ WARN_REGEXP, m REPORT_LOCATION,\
406 (int)offset, RExC_precomp, RExC_precomp + offset); \
409 #define vWARN3(loc, m, a1, a2) \
411 IV offset = loc - RExC_precomp; \
412 Perl_warner(aTHX_ WARN_REGEXP, m REPORT_LOCATION, \
414 (int)offset, RExC_precomp, RExC_precomp + offset); \
417 #define vWARN4(loc, m, a1, a2, a3) \
419 IV offset = loc - RExC_precomp; \
420 Perl_warner(aTHX_ WARN_REGEXP, m REPORT_LOCATION,\
422 (int)offset, RExC_precomp, RExC_precomp + offset); \
425 /* used for the parse_flags section for (?c) -- japhy */
426 #define vWARN5(loc, m, a1, a2, a3, a4) \
428 IV offset = loc - RExC_precomp; \
429 Perl_warner(aTHX_ WARN_REGEXP, m REPORT_LOCATION, \
431 (int)offset, RExC_precomp, RExC_precomp + offset); \
435 /* Allow for side effects in s */
436 #define REGC(c,s) STMT_START { if (!SIZE_ONLY) *(s) = (c); else (void)(s);} STMT_END
438 /* Macros for recording node offsets. 20001227 mjd@plover.com
439 * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
440 * element 2*n-1 of the array. Element #2n holds the byte length node #n.
441 * Element 0 holds the number n.
444 #define MJD_OFFSET_DEBUG(x)
445 /* #define MJD_OFFSET_DEBUG(x) fprintf x */
448 # define Set_Node_Offset_To_R(node,byte) \
452 Perl_croak(aTHX_ "value of node is %d in Offset macro", node); \
454 RExC_offsets[2*(node)-1] = (byte); \
459 # define Set_Node_Offset(node,byte) Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
460 # define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
462 # define Set_Node_Length_To_R(node,len) \
465 MJD_OFFSET_DEBUG((stderr, "** (%d) size of node %d is %d.\n", __LINE__, (node), (len))); \
467 Perl_croak(aTHX_ "value of node is %d in Length macro", node); \
469 RExC_offsets[2*(node)] = (len); \
474 # define Set_Node_Length(node,len) Set_Node_Length_To_R((node)-RExC_emit_start, len)
475 # define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
476 # define Set_Node_Cur_Length(node) Set_Node_Length(node, RExC_parse - parse_start)
478 /* Get offsets and lengths */
479 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
480 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
482 static void clear_re(pTHX_ void *r);
484 /* Mark that we cannot extend a found fixed substring at this point.
485 Updata the longest found anchored substring and the longest found
486 floating substrings if needed. */
489 S_scan_commit(pTHX_ RExC_state_t *pRExC_state, scan_data_t *data)
491 STRLEN l = CHR_SVLEN(data->last_found);
492 STRLEN old_l = CHR_SVLEN(*data->longest);
494 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
495 sv_setsv(*data->longest, data->last_found);
496 if (*data->longest == data->longest_fixed) {
497 data->offset_fixed = l ? data->last_start_min : data->pos_min;
498 if (data->flags & SF_BEFORE_EOL)
500 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
502 data->flags &= ~SF_FIX_BEFORE_EOL;
505 data->offset_float_min = l ? data->last_start_min : data->pos_min;
506 data->offset_float_max = (l
507 ? data->last_start_max
508 : data->pos_min + data->pos_delta);
509 if (data->flags & SF_BEFORE_EOL)
511 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
513 data->flags &= ~SF_FL_BEFORE_EOL;
516 SvCUR_set(data->last_found, 0);
518 data->flags &= ~SF_BEFORE_EOL;
521 /* Can match anything (initialization) */
523 S_cl_anything(pTHX_ RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
525 ANYOF_CLASS_ZERO(cl);
526 ANYOF_BITMAP_SETALL(cl);
527 cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL;
529 cl->flags |= ANYOF_LOCALE;
532 /* Can match anything (initialization) */
534 S_cl_is_anything(pTHX_ struct regnode_charclass_class *cl)
538 for (value = 0; value <= ANYOF_MAX; value += 2)
539 if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
541 if (!(cl->flags & ANYOF_UNICODE_ALL))
543 if (!ANYOF_BITMAP_TESTALLSET(cl))
548 /* Can match anything (initialization) */
550 S_cl_init(pTHX_ RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
552 Zero(cl, 1, struct regnode_charclass_class);
554 cl_anything(pRExC_state, cl);
558 S_cl_init_zero(pTHX_ RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
560 Zero(cl, 1, struct regnode_charclass_class);
562 cl_anything(pRExC_state, cl);
564 cl->flags |= ANYOF_LOCALE;
567 /* 'And' a given class with another one. Can create false positives */
568 /* We assume that cl is not inverted */
570 S_cl_and(pTHX_ struct regnode_charclass_class *cl,
571 struct regnode_charclass_class *and_with)
573 if (!(and_with->flags & ANYOF_CLASS)
574 && !(cl->flags & ANYOF_CLASS)
575 && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
576 && !(and_with->flags & ANYOF_FOLD)
577 && !(cl->flags & ANYOF_FOLD)) {
580 if (and_with->flags & ANYOF_INVERT)
581 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
582 cl->bitmap[i] &= ~and_with->bitmap[i];
584 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
585 cl->bitmap[i] &= and_with->bitmap[i];
586 } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
587 if (!(and_with->flags & ANYOF_EOS))
588 cl->flags &= ~ANYOF_EOS;
590 if (cl->flags & ANYOF_UNICODE_ALL && and_with->flags & ANYOF_UNICODE) {
591 cl->flags &= ~ANYOF_UNICODE_ALL;
592 cl->flags |= ANYOF_UNICODE;
593 ARG_SET(cl, ARG(and_with));
595 if (!(and_with->flags & ANYOF_UNICODE_ALL))
596 cl->flags &= ~ANYOF_UNICODE_ALL;
597 if (!(and_with->flags & (ANYOF_UNICODE|ANYOF_UNICODE_ALL)))
598 cl->flags &= ~ANYOF_UNICODE;
601 /* 'OR' a given class with another one. Can create false positives */
602 /* We assume that cl is not inverted */
604 S_cl_or(pTHX_ RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, struct regnode_charclass_class *or_with)
606 if (or_with->flags & ANYOF_INVERT) {
608 * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
609 * <= (B1 | !B2) | (CL1 | !CL2)
610 * which is wasteful if CL2 is small, but we ignore CL2:
611 * (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
612 * XXXX Can we handle case-fold? Unclear:
613 * (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
614 * (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
616 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
617 && !(or_with->flags & ANYOF_FOLD)
618 && !(cl->flags & ANYOF_FOLD) ) {
621 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
622 cl->bitmap[i] |= ~or_with->bitmap[i];
623 } /* XXXX: logic is complicated otherwise */
625 cl_anything(pRExC_state, cl);
628 /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
629 if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
630 && (!(or_with->flags & ANYOF_FOLD)
631 || (cl->flags & ANYOF_FOLD)) ) {
634 /* OR char bitmap and class bitmap separately */
635 for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
636 cl->bitmap[i] |= or_with->bitmap[i];
637 if (or_with->flags & ANYOF_CLASS) {
638 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
639 cl->classflags[i] |= or_with->classflags[i];
640 cl->flags |= ANYOF_CLASS;
643 else { /* XXXX: logic is complicated, leave it along for a moment. */
644 cl_anything(pRExC_state, cl);
647 if (or_with->flags & ANYOF_EOS)
648 cl->flags |= ANYOF_EOS;
650 if (cl->flags & ANYOF_UNICODE && or_with->flags & ANYOF_UNICODE &&
651 ARG(cl) != ARG(or_with)) {
652 cl->flags |= ANYOF_UNICODE_ALL;
653 cl->flags &= ~ANYOF_UNICODE;
655 if (or_with->flags & ANYOF_UNICODE_ALL) {
656 cl->flags |= ANYOF_UNICODE_ALL;
657 cl->flags &= ~ANYOF_UNICODE;
662 * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
663 * These need to be revisited when a newer toolchain becomes available.
665 #if defined(__sparc64__) && defined(__GNUC__)
666 # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
667 # undef SPARC64_GCC_WORKAROUND
668 # define SPARC64_GCC_WORKAROUND 1
672 /* REx optimizer. Converts nodes into quickier variants "in place".
673 Finds fixed substrings. */
675 /* Stops at toplevel WHILEM as well as at `last'. At end *scanp is set
676 to the position after last scanned or to NULL. */
679 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp, I32 *deltap, regnode *last, scan_data_t *data, U32 flags)
680 /* scanp: Start here (read-write). */
681 /* deltap: Write maxlen-minlen here. */
682 /* last: Stop before this one. */
684 I32 min = 0, pars = 0, code;
685 regnode *scan = *scanp, *next;
687 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
688 int is_inf_internal = 0; /* The studied chunk is infinite */
689 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
690 scan_data_t data_fake;
691 struct regnode_charclass_class and_with; /* Valid if flags & SCF_DO_STCLASS_OR */
693 while (scan && OP(scan) != END && scan < last) {
694 /* Peephole optimizer: */
696 if (PL_regkind[(U8)OP(scan)] == EXACT) {
697 /* Merge several consecutive EXACTish nodes into one. */
698 regnode *n = regnext(scan);
701 regnode *stop = scan;
704 next = scan + NODE_SZ_STR(scan);
705 /* Skip NOTHING, merge EXACT*. */
707 ( PL_regkind[(U8)OP(n)] == NOTHING ||
708 (stringok && (OP(n) == OP(scan))))
710 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
711 if (OP(n) == TAIL || n > next)
713 if (PL_regkind[(U8)OP(n)] == NOTHING) {
714 NEXT_OFF(scan) += NEXT_OFF(n);
715 next = n + NODE_STEP_REGNODE;
723 int oldl = STR_LEN(scan);
724 regnode *nnext = regnext(n);
726 if (oldl + STR_LEN(n) > U8_MAX)
728 NEXT_OFF(scan) += NEXT_OFF(n);
729 STR_LEN(scan) += STR_LEN(n);
730 next = n + NODE_SZ_STR(n);
731 /* Now we can overwrite *n : */
732 Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
741 n = scan + NODE_SZ_STR(scan);
743 if (PL_regkind[(U8)OP(n)] != NOTHING || OP(n) == NOTHING) {
751 /* Follow the next-chain of the current node and optimize
752 away all the NOTHINGs from it. */
753 if (OP(scan) != CURLYX) {
754 int max = (reg_off_by_arg[OP(scan)]
756 /* I32 may be smaller than U16 on CRAYs! */
757 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
758 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
762 /* Skip NOTHING and LONGJMP. */
763 while ((n = regnext(n))
764 && ((PL_regkind[(U8)OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
765 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
768 if (reg_off_by_arg[OP(scan)])
771 NEXT_OFF(scan) = off;
773 /* The principal pseudo-switch. Cannot be a switch, since we
774 look into several different things. */
775 if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
776 || OP(scan) == IFTHEN || OP(scan) == SUSPEND) {
777 next = regnext(scan);
780 if (OP(next) == code || code == IFTHEN || code == SUSPEND) {
781 I32 max1 = 0, min1 = I32_MAX, num = 0;
782 struct regnode_charclass_class accum;
784 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
785 scan_commit(pRExC_state, data); /* Cannot merge strings after this. */
786 if (flags & SCF_DO_STCLASS)
787 cl_init_zero(pRExC_state, &accum);
788 while (OP(scan) == code) {
789 I32 deltanext, minnext, f = 0, fake;
790 struct regnode_charclass_class this_class;
795 data_fake.whilem_c = data->whilem_c;
796 data_fake.last_closep = data->last_closep;
799 data_fake.last_closep = &fake;
800 next = regnext(scan);
801 scan = NEXTOPER(scan);
803 scan = NEXTOPER(scan);
804 if (flags & SCF_DO_STCLASS) {
805 cl_init(pRExC_state, &this_class);
806 data_fake.start_class = &this_class;
807 f = SCF_DO_STCLASS_AND;
809 if (flags & SCF_WHILEM_VISITED_POS)
810 f |= SCF_WHILEM_VISITED_POS;
811 /* we suppose the run is continuous, last=next...*/
812 minnext = study_chunk(pRExC_state, &scan, &deltanext,
813 next, &data_fake, f);
816 if (max1 < minnext + deltanext)
817 max1 = minnext + deltanext;
818 if (deltanext == I32_MAX)
819 is_inf = is_inf_internal = 1;
821 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
823 if (data && (data_fake.flags & SF_HAS_EVAL))
824 data->flags |= SF_HAS_EVAL;
826 data->whilem_c = data_fake.whilem_c;
827 if (flags & SCF_DO_STCLASS)
828 cl_or(pRExC_state, &accum, &this_class);
832 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
834 if (flags & SCF_DO_SUBSTR) {
835 data->pos_min += min1;
836 data->pos_delta += max1 - min1;
837 if (max1 != min1 || is_inf)
838 data->longest = &(data->longest_float);
841 delta += max1 - min1;
842 if (flags & SCF_DO_STCLASS_OR) {
843 cl_or(pRExC_state, data->start_class, &accum);
845 cl_and(data->start_class, &and_with);
846 flags &= ~SCF_DO_STCLASS;
849 else if (flags & SCF_DO_STCLASS_AND) {
851 cl_and(data->start_class, &accum);
852 flags &= ~SCF_DO_STCLASS;
855 /* Switch to OR mode: cache the old value of
856 * data->start_class */
857 StructCopy(data->start_class, &and_with,
858 struct regnode_charclass_class);
859 flags &= ~SCF_DO_STCLASS_AND;
860 StructCopy(&accum, data->start_class,
861 struct regnode_charclass_class);
862 flags |= SCF_DO_STCLASS_OR;
863 data->start_class->flags |= ANYOF_EOS;
867 else if (code == BRANCHJ) /* single branch is optimized. */
868 scan = NEXTOPER(NEXTOPER(scan));
869 else /* single branch is optimized. */
870 scan = NEXTOPER(scan);
873 else if (OP(scan) == EXACT) {
874 I32 l = STR_LEN(scan);
875 UV uc = *((U8*)STRING(scan));
877 U8 *s = (U8*)STRING(scan);
878 l = utf8_length(s, s + l);
879 uc = utf8_to_uvchr(s, NULL);
882 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
883 /* The code below prefers earlier match for fixed
884 offset, later match for variable offset. */
885 if (data->last_end == -1) { /* Update the start info. */
886 data->last_start_min = data->pos_min;
887 data->last_start_max = is_inf
888 ? I32_MAX : data->pos_min + data->pos_delta;
890 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
891 data->last_end = data->pos_min + l;
892 data->pos_min += l; /* As in the first entry. */
893 data->flags &= ~SF_BEFORE_EOL;
895 if (flags & SCF_DO_STCLASS_AND) {
896 /* Check whether it is compatible with what we know already! */
900 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
901 && !ANYOF_BITMAP_TEST(data->start_class, uc)
902 && (!(data->start_class->flags & ANYOF_FOLD)
903 || !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
906 ANYOF_CLASS_ZERO(data->start_class);
907 ANYOF_BITMAP_ZERO(data->start_class);
909 ANYOF_BITMAP_SET(data->start_class, uc);
910 data->start_class->flags &= ~ANYOF_EOS;
912 data->start_class->flags &= ~ANYOF_UNICODE_ALL;
914 else if (flags & SCF_DO_STCLASS_OR) {
915 /* false positive possible if the class is case-folded */
917 ANYOF_BITMAP_SET(data->start_class, uc);
919 data->start_class->flags |= ANYOF_UNICODE_ALL;
920 data->start_class->flags &= ~ANYOF_EOS;
921 cl_and(data->start_class, &and_with);
923 flags &= ~SCF_DO_STCLASS;
925 else if (PL_regkind[(U8)OP(scan)] == EXACT) { /* But OP != EXACT! */
926 I32 l = STR_LEN(scan);
927 UV uc = *((U8*)STRING(scan));
929 /* Search for fixed substrings supports EXACT only. */
930 if (flags & SCF_DO_SUBSTR)
931 scan_commit(pRExC_state, data);
933 U8 *s = (U8 *)STRING(scan);
934 l = utf8_length(s, s + l);
935 uc = utf8_to_uvchr(s, NULL);
938 if (data && (flags & SCF_DO_SUBSTR))
940 if (flags & SCF_DO_STCLASS_AND) {
941 /* Check whether it is compatible with what we know already! */
945 (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
946 && !ANYOF_BITMAP_TEST(data->start_class, uc)
947 && !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
949 ANYOF_CLASS_ZERO(data->start_class);
950 ANYOF_BITMAP_ZERO(data->start_class);
952 ANYOF_BITMAP_SET(data->start_class, uc);
953 data->start_class->flags &= ~ANYOF_EOS;
954 data->start_class->flags |= ANYOF_FOLD;
955 if (OP(scan) == EXACTFL)
956 data->start_class->flags |= ANYOF_LOCALE;
959 else if (flags & SCF_DO_STCLASS_OR) {
960 if (data->start_class->flags & ANYOF_FOLD) {
961 /* false positive possible if the class is case-folded.
962 Assume that the locale settings are the same... */
964 ANYOF_BITMAP_SET(data->start_class, uc);
965 data->start_class->flags &= ~ANYOF_EOS;
967 cl_and(data->start_class, &and_with);
969 flags &= ~SCF_DO_STCLASS;
971 else if (strchr((char*)PL_varies,OP(scan))) {
972 I32 mincount, maxcount, minnext, deltanext, fl = 0;
973 I32 f = flags, pos_before = 0;
974 regnode *oscan = scan;
975 struct regnode_charclass_class this_class;
976 struct regnode_charclass_class *oclass = NULL;
977 I32 next_is_eval = 0;
979 switch (PL_regkind[(U8)OP(scan)]) {
980 case WHILEM: /* End of (?:...)* . */
981 scan = NEXTOPER(scan);
984 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
985 next = NEXTOPER(scan);
986 if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
988 maxcount = REG_INFTY;
989 next = regnext(scan);
990 scan = NEXTOPER(scan);
994 if (flags & SCF_DO_SUBSTR)
999 if (flags & SCF_DO_STCLASS) {
1001 maxcount = REG_INFTY;
1002 next = regnext(scan);
1003 scan = NEXTOPER(scan);
1006 is_inf = is_inf_internal = 1;
1007 scan = regnext(scan);
1008 if (flags & SCF_DO_SUBSTR) {
1009 scan_commit(pRExC_state, data); /* Cannot extend fixed substrings */
1010 data->longest = &(data->longest_float);
1012 goto optimize_curly_tail;
1014 mincount = ARG1(scan);
1015 maxcount = ARG2(scan);
1016 next = regnext(scan);
1017 if (OP(scan) == CURLYX) {
1018 I32 lp = (data ? *(data->last_closep) : 0);
1020 scan->flags = ((lp <= U8_MAX) ? lp : U8_MAX);
1022 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
1023 next_is_eval = (OP(scan) == EVAL);
1025 if (flags & SCF_DO_SUBSTR) {
1026 if (mincount == 0) scan_commit(pRExC_state,data); /* Cannot extend fixed substrings */
1027 pos_before = data->pos_min;
1031 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
1033 data->flags |= SF_IS_INF;
1035 if (flags & SCF_DO_STCLASS) {
1036 cl_init(pRExC_state, &this_class);
1037 oclass = data->start_class;
1038 data->start_class = &this_class;
1039 f |= SCF_DO_STCLASS_AND;
1040 f &= ~SCF_DO_STCLASS_OR;
1042 /* These are the cases when once a subexpression
1043 fails at a particular position, it cannot succeed
1044 even after backtracking at the enclosing scope.
1046 XXXX what if minimal match and we are at the
1047 initial run of {n,m}? */
1048 if ((mincount != maxcount - 1) && (maxcount != REG_INFTY))
1049 f &= ~SCF_WHILEM_VISITED_POS;
1051 /* This will finish on WHILEM, setting scan, or on NULL: */
1052 minnext = study_chunk(pRExC_state, &scan, &deltanext, last, data,
1054 ? (f & ~SCF_DO_SUBSTR) : f);
1056 if (flags & SCF_DO_STCLASS)
1057 data->start_class = oclass;
1058 if (mincount == 0 || minnext == 0) {
1059 if (flags & SCF_DO_STCLASS_OR) {
1060 cl_or(pRExC_state, data->start_class, &this_class);
1062 else if (flags & SCF_DO_STCLASS_AND) {
1063 /* Switch to OR mode: cache the old value of
1064 * data->start_class */
1065 StructCopy(data->start_class, &and_with,
1066 struct regnode_charclass_class);
1067 flags &= ~SCF_DO_STCLASS_AND;
1068 StructCopy(&this_class, data->start_class,
1069 struct regnode_charclass_class);
1070 flags |= SCF_DO_STCLASS_OR;
1071 data->start_class->flags |= ANYOF_EOS;
1073 } else { /* Non-zero len */
1074 if (flags & SCF_DO_STCLASS_OR) {
1075 cl_or(pRExC_state, data->start_class, &this_class);
1076 cl_and(data->start_class, &and_with);
1078 else if (flags & SCF_DO_STCLASS_AND)
1079 cl_and(data->start_class, &this_class);
1080 flags &= ~SCF_DO_STCLASS;
1082 if (!scan) /* It was not CURLYX, but CURLY. */
1084 if (ckWARN(WARN_REGEXP)
1085 /* ? quantifier ok, except for (?{ ... }) */
1086 && (next_is_eval || !(mincount == 0 && maxcount == 1))
1087 && (minnext == 0) && (deltanext == 0)
1088 && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
1089 && maxcount <= REG_INFTY/3) /* Complement check for big count */
1092 "Quantifier unexpected on zero-length expression");
1095 min += minnext * mincount;
1096 is_inf_internal |= ((maxcount == REG_INFTY
1097 && (minnext + deltanext) > 0)
1098 || deltanext == I32_MAX);
1099 is_inf |= is_inf_internal;
1100 delta += (minnext + deltanext) * maxcount - minnext * mincount;
1102 /* Try powerful optimization CURLYX => CURLYN. */
1103 if ( OP(oscan) == CURLYX && data
1104 && data->flags & SF_IN_PAR
1105 && !(data->flags & SF_HAS_EVAL)
1106 && !deltanext && minnext == 1 ) {
1107 /* Try to optimize to CURLYN. */
1108 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
1109 regnode *nxt1 = nxt;
1116 if (!strchr((char*)PL_simple,OP(nxt))
1117 && !(PL_regkind[(U8)OP(nxt)] == EXACT
1118 && STR_LEN(nxt) == 1))
1124 if (OP(nxt) != CLOSE)
1126 /* Now we know that nxt2 is the only contents: */
1127 oscan->flags = ARG(nxt);
1129 OP(nxt1) = NOTHING; /* was OPEN. */
1131 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
1132 NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
1133 NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
1134 OP(nxt) = OPTIMIZED; /* was CLOSE. */
1135 OP(nxt + 1) = OPTIMIZED; /* was count. */
1136 NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
1141 /* Try optimization CURLYX => CURLYM. */
1142 if ( OP(oscan) == CURLYX && data
1143 && !(data->flags & SF_HAS_PAR)
1144 && !(data->flags & SF_HAS_EVAL)
1146 /* XXXX How to optimize if data == 0? */
1147 /* Optimize to a simpler form. */
1148 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
1152 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
1153 && (OP(nxt2) != WHILEM))
1155 OP(nxt2) = SUCCEED; /* Whas WHILEM */
1156 /* Need to optimize away parenths. */
1157 if (data->flags & SF_IN_PAR) {
1158 /* Set the parenth number. */
1159 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
1161 if (OP(nxt) != CLOSE)
1162 FAIL("Panic opt close");
1163 oscan->flags = ARG(nxt);
1164 OP(nxt1) = OPTIMIZED; /* was OPEN. */
1165 OP(nxt) = OPTIMIZED; /* was CLOSE. */
1167 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
1168 OP(nxt + 1) = OPTIMIZED; /* was count. */
1169 NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
1170 NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
1173 while ( nxt1 && (OP(nxt1) != WHILEM)) {
1174 regnode *nnxt = regnext(nxt1);
1177 if (reg_off_by_arg[OP(nxt1)])
1178 ARG_SET(nxt1, nxt2 - nxt1);
1179 else if (nxt2 - nxt1 < U16_MAX)
1180 NEXT_OFF(nxt1) = nxt2 - nxt1;
1182 OP(nxt) = NOTHING; /* Cannot beautify */
1187 /* Optimize again: */
1188 study_chunk(pRExC_state, &nxt1, &deltanext, nxt,
1194 else if ((OP(oscan) == CURLYX)
1195 && (flags & SCF_WHILEM_VISITED_POS)
1196 /* See the comment on a similar expression above.
1197 However, this time it not a subexpression
1198 we care about, but the expression itself. */
1199 && (maxcount == REG_INFTY)
1200 && data && ++data->whilem_c < 16) {
1201 /* This stays as CURLYX, we can put the count/of pair. */
1202 /* Find WHILEM (as in regexec.c) */
1203 regnode *nxt = oscan + NEXT_OFF(oscan);
1205 if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
1207 PREVOPER(nxt)->flags = data->whilem_c
1208 | (RExC_whilem_seen << 4); /* On WHILEM */
1210 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
1212 if (flags & SCF_DO_SUBSTR) {
1213 SV *last_str = Nullsv;
1214 int counted = mincount != 0;
1216 if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
1217 #if defined(SPARC64_GCC_WORKAROUND)
1223 if (pos_before >= data->last_start_min)
1226 b = data->last_start_min;
1229 s = SvPV(data->last_found, l);
1230 old = b - data->last_start_min;
1233 I32 b = pos_before >= data->last_start_min
1234 ? pos_before : data->last_start_min;
1236 char *s = SvPV(data->last_found, l);
1237 I32 old = b - data->last_start_min;
1241 old = utf8_hop((U8*)s, old) - (U8*)s;
1244 /* Get the added string: */
1245 last_str = newSVpvn(s + old, l);
1246 if (deltanext == 0 && pos_before == b) {
1247 /* What was added is a constant string */
1249 SvGROW(last_str, (mincount * l) + 1);
1250 repeatcpy(SvPVX(last_str) + l,
1251 SvPVX(last_str), l, mincount - 1);
1252 SvCUR(last_str) *= mincount;
1253 /* Add additional parts. */
1254 SvCUR_set(data->last_found,
1255 SvCUR(data->last_found) - l);
1256 sv_catsv(data->last_found, last_str);
1257 data->last_end += l * (mincount - 1);
1260 /* start offset must point into the last copy */
1261 data->last_start_min += minnext * (mincount - 1);
1262 data->last_start_max += is_inf ? 0 : (maxcount - 1)
1263 * (minnext + data->pos_delta);
1266 /* It is counted once already... */
1267 data->pos_min += minnext * (mincount - counted);
1268 data->pos_delta += - counted * deltanext +
1269 (minnext + deltanext) * maxcount - minnext * mincount;
1270 if (mincount != maxcount) {
1271 /* Cannot extend fixed substrings found inside
1273 scan_commit(pRExC_state,data);
1274 if (mincount && last_str) {
1275 sv_setsv(data->last_found, last_str);
1276 data->last_end = data->pos_min;
1277 data->last_start_min =
1278 data->pos_min - CHR_SVLEN(last_str);
1279 data->last_start_max = is_inf
1281 : data->pos_min + data->pos_delta
1282 - CHR_SVLEN(last_str);
1284 data->longest = &(data->longest_float);
1286 SvREFCNT_dec(last_str);
1288 if (data && (fl & SF_HAS_EVAL))
1289 data->flags |= SF_HAS_EVAL;
1290 optimize_curly_tail:
1291 if (OP(oscan) != CURLYX) {
1292 while (PL_regkind[(U8)OP(next = regnext(oscan))] == NOTHING
1294 NEXT_OFF(oscan) += NEXT_OFF(next);
1297 default: /* REF and CLUMP only? */
1298 if (flags & SCF_DO_SUBSTR) {
1299 scan_commit(pRExC_state,data); /* Cannot expect anything... */
1300 data->longest = &(data->longest_float);
1302 is_inf = is_inf_internal = 1;
1303 if (flags & SCF_DO_STCLASS_OR)
1304 cl_anything(pRExC_state, data->start_class);
1305 flags &= ~SCF_DO_STCLASS;
1309 else if (strchr((char*)PL_simple,OP(scan))) {
1312 if (flags & SCF_DO_SUBSTR) {
1313 scan_commit(pRExC_state,data);
1317 if (flags & SCF_DO_STCLASS) {
1318 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
1320 /* Some of the logic below assumes that switching
1321 locale on will only add false positives. */
1322 switch (PL_regkind[(U8)OP(scan)]) {
1326 /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
1327 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
1328 cl_anything(pRExC_state, data->start_class);
1331 if (OP(scan) == SANY)
1333 if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
1334 value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
1335 || (data->start_class->flags & ANYOF_CLASS));
1336 cl_anything(pRExC_state, data->start_class);
1338 if (flags & SCF_DO_STCLASS_AND || !value)
1339 ANYOF_BITMAP_CLEAR(data->start_class,'\n');
1342 if (flags & SCF_DO_STCLASS_AND)
1343 cl_and(data->start_class,
1344 (struct regnode_charclass_class*)scan);
1346 cl_or(pRExC_state, data->start_class,
1347 (struct regnode_charclass_class*)scan);
1350 if (flags & SCF_DO_STCLASS_AND) {
1351 if (!(data->start_class->flags & ANYOF_LOCALE)) {
1352 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
1353 for (value = 0; value < 256; value++)
1354 if (!isALNUM(value))
1355 ANYOF_BITMAP_CLEAR(data->start_class, value);
1359 if (data->start_class->flags & ANYOF_LOCALE)
1360 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
1362 for (value = 0; value < 256; value++)
1364 ANYOF_BITMAP_SET(data->start_class, value);
1369 if (flags & SCF_DO_STCLASS_AND) {
1370 if (data->start_class->flags & ANYOF_LOCALE)
1371 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
1374 ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
1375 data->start_class->flags |= ANYOF_LOCALE;
1379 if (flags & SCF_DO_STCLASS_AND) {
1380 if (!(data->start_class->flags & ANYOF_LOCALE)) {
1381 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
1382 for (value = 0; value < 256; value++)
1384 ANYOF_BITMAP_CLEAR(data->start_class, value);
1388 if (data->start_class->flags & ANYOF_LOCALE)
1389 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
1391 for (value = 0; value < 256; value++)
1392 if (!isALNUM(value))
1393 ANYOF_BITMAP_SET(data->start_class, value);
1398 if (flags & SCF_DO_STCLASS_AND) {
1399 if (data->start_class->flags & ANYOF_LOCALE)
1400 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
1403 data->start_class->flags |= ANYOF_LOCALE;
1404 ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
1408 if (flags & SCF_DO_STCLASS_AND) {
1409 if (!(data->start_class->flags & ANYOF_LOCALE)) {
1410 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
1411 for (value = 0; value < 256; value++)
1412 if (!isSPACE(value))
1413 ANYOF_BITMAP_CLEAR(data->start_class, value);
1417 if (data->start_class->flags & ANYOF_LOCALE)
1418 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
1420 for (value = 0; value < 256; value++)
1422 ANYOF_BITMAP_SET(data->start_class, value);
1427 if (flags & SCF_DO_STCLASS_AND) {
1428 if (data->start_class->flags & ANYOF_LOCALE)
1429 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
1432 data->start_class->flags |= ANYOF_LOCALE;
1433 ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
1437 if (flags & SCF_DO_STCLASS_AND) {
1438 if (!(data->start_class->flags & ANYOF_LOCALE)) {
1439 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
1440 for (value = 0; value < 256; value++)
1442 ANYOF_BITMAP_CLEAR(data->start_class, value);
1446 if (data->start_class->flags & ANYOF_LOCALE)
1447 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
1449 for (value = 0; value < 256; value++)
1450 if (!isSPACE(value))
1451 ANYOF_BITMAP_SET(data->start_class, value);
1456 if (flags & SCF_DO_STCLASS_AND) {
1457 if (data->start_class->flags & ANYOF_LOCALE) {
1458 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
1459 for (value = 0; value < 256; value++)
1460 if (!isSPACE(value))
1461 ANYOF_BITMAP_CLEAR(data->start_class, value);
1465 data->start_class->flags |= ANYOF_LOCALE;
1466 ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
1470 if (flags & SCF_DO_STCLASS_AND) {
1471 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
1472 for (value = 0; value < 256; value++)
1473 if (!isDIGIT(value))
1474 ANYOF_BITMAP_CLEAR(data->start_class, value);
1477 if (data->start_class->flags & ANYOF_LOCALE)
1478 ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
1480 for (value = 0; value < 256; value++)
1482 ANYOF_BITMAP_SET(data->start_class, value);
1487 if (flags & SCF_DO_STCLASS_AND) {
1488 ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
1489 for (value = 0; value < 256; value++)
1491 ANYOF_BITMAP_CLEAR(data->start_class, value);
1494 if (data->start_class->flags & ANYOF_LOCALE)
1495 ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
1497 for (value = 0; value < 256; value++)
1498 if (!isDIGIT(value))
1499 ANYOF_BITMAP_SET(data->start_class, value);
1504 if (flags & SCF_DO_STCLASS_OR)
1505 cl_and(data->start_class, &and_with);
1506 flags &= ~SCF_DO_STCLASS;
1509 else if (PL_regkind[(U8)OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
1510 data->flags |= (OP(scan) == MEOL
1514 else if ( PL_regkind[(U8)OP(scan)] == BRANCHJ
1515 /* Lookbehind, or need to calculate parens/evals/stclass: */
1516 && (scan->flags || data || (flags & SCF_DO_STCLASS))
1517 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
1518 /* Lookahead/lookbehind */
1519 I32 deltanext, minnext, fake = 0;
1521 struct regnode_charclass_class intrnl;
1524 data_fake.flags = 0;
1526 data_fake.whilem_c = data->whilem_c;
1527 data_fake.last_closep = data->last_closep;
1530 data_fake.last_closep = &fake;
1531 if ( flags & SCF_DO_STCLASS && !scan->flags
1532 && OP(scan) == IFMATCH ) { /* Lookahead */
1533 cl_init(pRExC_state, &intrnl);
1534 data_fake.start_class = &intrnl;
1535 f |= SCF_DO_STCLASS_AND;
1537 if (flags & SCF_WHILEM_VISITED_POS)
1538 f |= SCF_WHILEM_VISITED_POS;
1539 next = regnext(scan);
1540 nscan = NEXTOPER(NEXTOPER(scan));
1541 minnext = study_chunk(pRExC_state, &nscan, &deltanext, last, &data_fake, f);
1544 vFAIL("Variable length lookbehind not implemented");
1546 else if (minnext > U8_MAX) {
1547 vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
1549 scan->flags = minnext;
1551 if (data && data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
1553 if (data && (data_fake.flags & SF_HAS_EVAL))
1554 data->flags |= SF_HAS_EVAL;
1556 data->whilem_c = data_fake.whilem_c;
1557 if (f & SCF_DO_STCLASS_AND) {
1558 int was = (data->start_class->flags & ANYOF_EOS);
1560 cl_and(data->start_class, &intrnl);
1562 data->start_class->flags |= ANYOF_EOS;
1565 else if (OP(scan) == OPEN) {
1568 else if (OP(scan) == CLOSE) {
1569 if (ARG(scan) == is_par) {
1570 next = regnext(scan);
1572 if ( next && (OP(next) != WHILEM) && next < last)
1573 is_par = 0; /* Disable optimization */
1576 *(data->last_closep) = ARG(scan);
1578 else if (OP(scan) == EVAL) {
1580 data->flags |= SF_HAS_EVAL;
1582 else if (OP(scan) == LOGICAL && scan->flags == 2) { /* Embedded follows */
1583 if (flags & SCF_DO_SUBSTR) {
1584 scan_commit(pRExC_state,data);
1585 data->longest = &(data->longest_float);
1587 is_inf = is_inf_internal = 1;
1588 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
1589 cl_anything(pRExC_state, data->start_class);
1590 flags &= ~SCF_DO_STCLASS;
1592 /* Else: zero-length, ignore. */
1593 scan = regnext(scan);
1598 *deltap = is_inf_internal ? I32_MAX : delta;
1599 if (flags & SCF_DO_SUBSTR && is_inf)
1600 data->pos_delta = I32_MAX - data->pos_min;
1601 if (is_par > U8_MAX)
1603 if (is_par && pars==1 && data) {
1604 data->flags |= SF_IN_PAR;
1605 data->flags &= ~SF_HAS_PAR;
1607 else if (pars && data) {
1608 data->flags |= SF_HAS_PAR;
1609 data->flags &= ~SF_IN_PAR;
1611 if (flags & SCF_DO_STCLASS_OR)
1612 cl_and(data->start_class, &and_with);
1617 S_add_data(pTHX_ RExC_state_t *pRExC_state, I32 n, char *s)
1619 if (RExC_rx->data) {
1620 Renewc(RExC_rx->data,
1621 sizeof(*RExC_rx->data) + sizeof(void*) * (RExC_rx->data->count + n - 1),
1622 char, struct reg_data);
1623 Renew(RExC_rx->data->what, RExC_rx->data->count + n, U8);
1624 RExC_rx->data->count += n;
1627 Newc(1207, RExC_rx->data, sizeof(*RExC_rx->data) + sizeof(void*) * (n - 1),
1628 char, struct reg_data);
1629 New(1208, RExC_rx->data->what, n, U8);
1630 RExC_rx->data->count = n;
1632 Copy(s, RExC_rx->data->what + RExC_rx->data->count - n, n, U8);
1633 return RExC_rx->data->count - n;
1637 Perl_reginitcolors(pTHX)
1640 char *s = PerlEnv_getenv("PERL_RE_COLORS");
1643 PL_colors[0] = s = savepv(s);
1645 s = strchr(s, '\t');
1651 PL_colors[i] = s = "";
1655 PL_colors[i++] = "";
1662 - pregcomp - compile a regular expression into internal code
1664 * We can't allocate space until we know how big the compiled form will be,
1665 * but we can't compile it (and thus know how big it is) until we've got a
1666 * place to put the code. So we cheat: we compile it twice, once with code
1667 * generation turned off and size counting turned on, and once "for real".
1668 * This also means that we don't allocate space until we are sure that the
1669 * thing really will compile successfully, and we never have to move the
1670 * code and thus invalidate pointers into it. (Note that it has to be in
1671 * one piece because free() must be able to free it all.) [NB: not true in perl]
1673 * Beware that the optimization-preparation code in here knows about some
1674 * of the structure of the compiled regexp. [I'll say.]
1677 Perl_pregcomp(pTHX_ char *exp, char *xend, PMOP *pm)
1687 RExC_state_t RExC_state;
1688 RExC_state_t *pRExC_state = &RExC_state;
1691 FAIL("NULL regexp argument");
1693 RExC_utf8 = pm->op_pmdynflags & PMdf_CMP_UTF8;
1697 if (!PL_colorset) reginitcolors();
1698 PerlIO_printf(Perl_debug_log, "%sCompiling REx%s `%s%*s%s'\n",
1699 PL_colors[4],PL_colors[5],PL_colors[0],
1700 (int)(xend - exp), RExC_precomp, PL_colors[1]);
1702 RExC_flags16 = pm->op_pmflags;
1706 RExC_seen_zerolen = *exp == '^' ? -1 : 0;
1707 RExC_seen_evals = 0;
1710 /* First pass: determine size, legality. */
1717 RExC_emit = &PL_regdummy;
1718 RExC_whilem_seen = 0;
1719 #if 0 /* REGC() is (currently) a NOP at the first pass.
1720 * Clever compilers notice this and complain. --jhi */
1721 REGC((U8)REG_MAGIC, (char*)RExC_emit);
1723 if (reg(pRExC_state, 0, &flags) == NULL) {
1724 RExC_precomp = Nullch;
1727 DEBUG_r(PerlIO_printf(Perl_debug_log, "size %"IVdf" ", (IV)RExC_size));
1729 /* Small enough for pointer-storage convention?
1730 If extralen==0, this means that we will not need long jumps. */
1731 if (RExC_size >= 0x10000L && RExC_extralen)
1732 RExC_size += RExC_extralen;
1735 if (RExC_whilem_seen > 15)
1736 RExC_whilem_seen = 15;
1738 /* Allocate space and initialize. */
1739 Newc(1001, r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode),
1742 FAIL("Regexp out of space");
1745 /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
1746 Zero(r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode), char);
1749 r->prelen = xend - exp;
1750 r->precomp = savepvn(RExC_precomp, r->prelen);
1752 r->reganch = pm->op_pmflags & PMf_COMPILETIME;
1753 r->nparens = RExC_npar - 1; /* set early to validate backrefs */
1755 r->substrs = 0; /* Useful during FAIL. */
1756 r->startp = 0; /* Useful during FAIL. */
1757 r->endp = 0; /* Useful during FAIL. */
1759 Newz(1304, r->offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
1761 r->offsets[0] = RExC_size;
1763 DEBUG_r(PerlIO_printf(Perl_debug_log,
1764 "%s %"UVuf" bytes for offset annotations.\n",
1765 r->offsets ? "Got" : "Couldn't get",
1766 (UV)((2*RExC_size+1) * sizeof(U32))));
1770 /* Second pass: emit code. */
1771 RExC_flags16 = pm->op_pmflags; /* don't let top level (?i) bleed */
1776 RExC_emit_start = r->program;
1777 RExC_emit = r->program;
1778 /* Store the count of eval-groups for security checks: */
1779 RExC_emit->next_off = ((RExC_seen_evals > U16_MAX) ? U16_MAX : RExC_seen_evals);
1780 REGC((U8)REG_MAGIC, (char*) RExC_emit++);
1782 if (reg(pRExC_state, 0, &flags) == NULL)
1785 /* Dig out information for optimizations. */
1786 r->reganch = pm->op_pmflags & PMf_COMPILETIME; /* Again? */
1787 pm->op_pmflags = RExC_flags16;
1789 r->reganch |= ROPT_UTF8; /* Unicode in it? */
1790 r->regstclass = NULL;
1791 if (RExC_naughty >= 10) /* Probably an expensive pattern. */
1792 r->reganch |= ROPT_NAUGHTY;
1793 scan = r->program + 1; /* First BRANCH. */
1795 /* XXXX To minimize changes to RE engine we always allocate
1796 3-units-long substrs field. */
1797 Newz(1004, r->substrs, 1, struct reg_substr_data);
1799 StructCopy(&zero_scan_data, &data, scan_data_t);
1800 /* XXXX Should not we check for something else? Usually it is OPEN1... */
1801 if (OP(scan) != BRANCH) { /* Only one top-level choice. */
1803 STRLEN longest_float_length, longest_fixed_length;
1804 struct regnode_charclass_class ch_class;
1809 /* Skip introductions and multiplicators >= 1. */
1810 while ((OP(first) == OPEN && (sawopen = 1)) ||
1811 /* An OR of *one* alternative - should not happen now. */
1812 (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
1813 (OP(first) == PLUS) ||
1814 (OP(first) == MINMOD) ||
1815 /* An {n,m} with n>0 */
1816 (PL_regkind[(U8)OP(first)] == CURLY && ARG1(first) > 0) ) {
1817 if (OP(first) == PLUS)
1820 first += regarglen[(U8)OP(first)];
1821 first = NEXTOPER(first);
1824 /* Starting-point info. */
1826 if (PL_regkind[(U8)OP(first)] == EXACT) {
1827 if (OP(first) == EXACT)
1828 ; /* Empty, get anchored substr later. */
1829 else if ((OP(first) == EXACTF || OP(first) == EXACTFL))
1830 r->regstclass = first;
1832 else if (strchr((char*)PL_simple,OP(first)))
1833 r->regstclass = first;
1834 else if (PL_regkind[(U8)OP(first)] == BOUND ||
1835 PL_regkind[(U8)OP(first)] == NBOUND)
1836 r->regstclass = first;
1837 else if (PL_regkind[(U8)OP(first)] == BOL) {
1838 r->reganch |= (OP(first) == MBOL
1840 : (OP(first) == SBOL
1843 first = NEXTOPER(first);
1846 else if (OP(first) == GPOS) {
1847 r->reganch |= ROPT_ANCH_GPOS;
1848 first = NEXTOPER(first);
1851 else if ((OP(first) == STAR &&
1852 PL_regkind[(U8)OP(NEXTOPER(first))] == REG_ANY) &&
1853 !(r->reganch & ROPT_ANCH) )
1855 /* turn .* into ^.* with an implied $*=1 */
1856 int type = OP(NEXTOPER(first));
1858 if (type == REG_ANY)
1859 type = ROPT_ANCH_MBOL;
1861 type = ROPT_ANCH_SBOL;
1863 r->reganch |= type | ROPT_IMPLICIT;
1864 first = NEXTOPER(first);
1867 if (sawplus && (!sawopen || !RExC_sawback)
1868 && !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
1869 /* x+ must match at the 1st pos of run of x's */
1870 r->reganch |= ROPT_SKIP;
1872 /* Scan is after the zeroth branch, first is atomic matcher. */
1873 DEBUG_r(PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
1874 (IV)(first - scan + 1)));
1876 * If there's something expensive in the r.e., find the
1877 * longest literal string that must appear and make it the
1878 * regmust. Resolve ties in favor of later strings, since
1879 * the regstart check works with the beginning of the r.e.
1880 * and avoiding duplication strengthens checking. Not a
1881 * strong reason, but sufficient in the absence of others.
1882 * [Now we resolve ties in favor of the earlier string if
1883 * it happens that c_offset_min has been invalidated, since the
1884 * earlier string may buy us something the later one won't.]
1888 data.longest_fixed = newSVpvn("",0);
1889 data.longest_float = newSVpvn("",0);
1890 data.last_found = newSVpvn("",0);
1891 data.longest = &(data.longest_fixed);
1893 if (!r->regstclass) {
1894 cl_init(pRExC_state, &ch_class);
1895 data.start_class = &ch_class;
1896 stclass_flag = SCF_DO_STCLASS_AND;
1897 } else /* XXXX Check for BOUND? */
1899 data.last_closep = &last_close;
1901 minlen = study_chunk(pRExC_state, &first, &fake, scan + RExC_size, /* Up to end */
1902 &data, SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag);
1903 if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
1904 && data.last_start_min == 0 && data.last_end > 0
1905 && !RExC_seen_zerolen
1906 && (!(RExC_seen & REG_SEEN_GPOS) || (r->reganch & ROPT_ANCH_GPOS)))
1907 r->reganch |= ROPT_CHECK_ALL;
1908 scan_commit(pRExC_state, &data);
1909 SvREFCNT_dec(data.last_found);
1911 longest_float_length = CHR_SVLEN(data.longest_float);
1912 if (longest_float_length
1913 || (data.flags & SF_FL_BEFORE_EOL
1914 && (!(data.flags & SF_FL_BEFORE_MEOL)
1915 || (RExC_flags16 & PMf_MULTILINE)))) {
1918 if (SvCUR(data.longest_fixed) /* ok to leave SvCUR */
1919 && data.offset_fixed == data.offset_float_min
1920 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
1921 goto remove_float; /* As in (a)+. */
1923 r->float_substr = data.longest_float;
1924 r->float_min_offset = data.offset_float_min;
1925 r->float_max_offset = data.offset_float_max;
1926 t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
1927 && (!(data.flags & SF_FL_BEFORE_MEOL)
1928 || (RExC_flags16 & PMf_MULTILINE)));
1929 fbm_compile(r->float_substr, t ? FBMcf_TAIL : 0);
1933 r->float_substr = Nullsv;
1934 SvREFCNT_dec(data.longest_float);
1935 longest_float_length = 0;
1938 longest_fixed_length = CHR_SVLEN(data.longest_fixed);
1939 if (longest_fixed_length
1940 || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
1941 && (!(data.flags & SF_FIX_BEFORE_MEOL)
1942 || (RExC_flags16 & PMf_MULTILINE)))) {
1945 r->anchored_substr = data.longest_fixed;
1946 r->anchored_offset = data.offset_fixed;
1947 t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
1948 && (!(data.flags & SF_FIX_BEFORE_MEOL)
1949 || (RExC_flags16 & PMf_MULTILINE)));
1950 fbm_compile(r->anchored_substr, t ? FBMcf_TAIL : 0);
1953 r->anchored_substr = Nullsv;
1954 SvREFCNT_dec(data.longest_fixed);
1955 longest_fixed_length = 0;
1958 && (OP(r->regstclass) == REG_ANY || OP(r->regstclass) == SANY))
1959 r->regstclass = NULL;
1960 if ((!r->anchored_substr || r->anchored_offset) && stclass_flag
1961 && !(data.start_class->flags & ANYOF_EOS)
1962 && !cl_is_anything(data.start_class)) {
1963 I32 n = add_data(pRExC_state, 1, "f");
1965 New(1006, RExC_rx->data->data[n], 1,
1966 struct regnode_charclass_class);
1967 StructCopy(data.start_class,
1968 (struct regnode_charclass_class*)RExC_rx->data->data[n],
1969 struct regnode_charclass_class);
1970 r->regstclass = (regnode*)RExC_rx->data->data[n];
1971 r->reganch &= ~ROPT_SKIP; /* Used in find_byclass(). */
1972 PL_regdata = r->data; /* for regprop() */
1973 DEBUG_r({ SV *sv = sv_newmortal();
1974 regprop(sv, (regnode*)data.start_class);
1975 PerlIO_printf(Perl_debug_log,
1976 "synthetic stclass `%s'.\n",
1980 /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
1981 if (longest_fixed_length > longest_float_length) {
1982 r->check_substr = r->anchored_substr;
1983 r->check_offset_min = r->check_offset_max = r->anchored_offset;
1984 if (r->reganch & ROPT_ANCH_SINGLE)
1985 r->reganch |= ROPT_NOSCAN;
1988 r->check_substr = r->float_substr;
1989 r->check_offset_min = data.offset_float_min;
1990 r->check_offset_max = data.offset_float_max;
1992 /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
1993 This should be changed ASAP! */
1994 if (r->check_substr && !(r->reganch & ROPT_ANCH_GPOS)) {
1995 r->reganch |= RE_USE_INTUIT;
1996 if (SvTAIL(r->check_substr))
1997 r->reganch |= RE_INTUIT_TAIL;
2001 /* Several toplevels. Best we can is to set minlen. */
2003 struct regnode_charclass_class ch_class;
2006 DEBUG_r(PerlIO_printf(Perl_debug_log, "\n"));
2007 scan = r->program + 1;
2008 cl_init(pRExC_state, &ch_class);
2009 data.start_class = &ch_class;
2010 data.last_closep = &last_close;
2011 minlen = study_chunk(pRExC_state, &scan, &fake, scan + RExC_size, &data, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS);
2012 r->check_substr = r->anchored_substr = r->float_substr = Nullsv;
2013 if (!(data.start_class->flags & ANYOF_EOS)
2014 && !cl_is_anything(data.start_class)) {
2015 I32 n = add_data(pRExC_state, 1, "f");
2017 New(1006, RExC_rx->data->data[n], 1,
2018 struct regnode_charclass_class);
2019 StructCopy(data.start_class,
2020 (struct regnode_charclass_class*)RExC_rx->data->data[n],
2021 struct regnode_charclass_class);
2022 r->regstclass = (regnode*)RExC_rx->data->data[n];
2023 r->reganch &= ~ROPT_SKIP; /* Used in find_byclass(). */
2024 DEBUG_r({ SV* sv = sv_newmortal();
2025 regprop(sv, (regnode*)data.start_class);
2026 PerlIO_printf(Perl_debug_log,
2027 "synthetic stclass `%s'.\n",
2033 if (RExC_seen & REG_SEEN_GPOS)
2034 r->reganch |= ROPT_GPOS_SEEN;
2035 if (RExC_seen & REG_SEEN_LOOKBEHIND)
2036 r->reganch |= ROPT_LOOKBEHIND_SEEN;
2037 if (RExC_seen & REG_SEEN_EVAL)
2038 r->reganch |= ROPT_EVAL_SEEN;
2039 if (RExC_seen & REG_SEEN_CANY)
2040 r->reganch |= ROPT_CANY_SEEN;
2041 Newz(1002, r->startp, RExC_npar, I32);
2042 Newz(1002, r->endp, RExC_npar, I32);
2043 PL_regdata = r->data; /* for regprop() */
2044 DEBUG_r(regdump(r));
2049 - reg - regular expression, i.e. main body or parenthesized thing
2051 * Caller must absorb opening parenthesis.
2053 * Combining parenthesis handling with the base level of regular expression
2054 * is a trifle forced, but the need to tie the tails of the branches to what
2055 * follows makes it hard to avoid.
2058 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp)
2059 /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
2061 register regnode *ret; /* Will be the head of the group. */
2062 register regnode *br;
2063 register regnode *lastbr;
2064 register regnode *ender = 0;
2065 register I32 parno = 0;
2066 I32 flags, oregflags = RExC_flags16, have_branch = 0, open = 0;
2068 /* for (?g), (?gc), and (?o) warnings; warning
2069 about (?c) will warn about (?g) -- japhy */
2071 I32 wastedflags = 0x00,
2074 wasted_gc = 0x02 | 0x04,
2077 char * parse_start = RExC_parse; /* MJD */
2078 char *oregcomp_parse = RExC_parse;
2081 *flagp = 0; /* Tentatively. */
2084 /* Make an OPEN node, if parenthesized. */
2086 if (*RExC_parse == '?') { /* (?...) */
2087 U16 posflags = 0, negflags = 0;
2088 U16 *flagsp = &posflags;
2090 char *seqstart = RExC_parse;
2093 paren = *RExC_parse++;
2094 ret = NULL; /* For look-ahead/behind. */
2096 case '<': /* (?<...) */
2097 RExC_seen |= REG_SEEN_LOOKBEHIND;
2098 if (*RExC_parse == '!')
2100 if (*RExC_parse != '=' && *RExC_parse != '!')
2103 case '=': /* (?=...) */
2104 case '!': /* (?!...) */
2105 RExC_seen_zerolen++;
2106 case ':': /* (?:...) */
2107 case '>': /* (?>...) */
2109 case '$': /* (?$...) */
2110 case '@': /* (?@...) */
2111 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
2113 case '#': /* (?#...) */
2114 while (*RExC_parse && *RExC_parse != ')')
2116 if (*RExC_parse != ')')
2117 FAIL("Sequence (?#... not terminated");
2118 nextchar(pRExC_state);
2121 case 'p': /* (?p...) */
2122 if (SIZE_ONLY && ckWARN2(WARN_DEPRECATED, WARN_REGEXP))
2123 vWARNdep(RExC_parse, "(?p{}) is deprecated - use (??{})");
2125 case '?': /* (??...) */
2127 paren = *RExC_parse++;
2129 case '{': /* (?{...}) */
2131 I32 count = 1, n = 0;
2133 char *s = RExC_parse;
2135 OP_4tree *sop, *rop;
2137 RExC_seen_zerolen++;
2138 RExC_seen |= REG_SEEN_EVAL;
2139 while (count && (c = *RExC_parse)) {
2140 if (c == '\\' && RExC_parse[1])
2148 if (*RExC_parse != ')')
2151 vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
2156 if (RExC_parse - 1 - s)
2157 sv = newSVpvn(s, RExC_parse - 1 - s);
2159 sv = newSVpvn("", 0);
2162 Perl_save_re_context(aTHX);
2163 rop = sv_compile_2op(sv, &sop, "re", &av);
2164 sop->op_private |= OPpREFCOUNTED;
2165 /* re_dup will OpREFCNT_inc */
2166 OpREFCNT_set(sop, 1);
2169 n = add_data(pRExC_state, 3, "nop");
2170 RExC_rx->data->data[n] = (void*)rop;
2171 RExC_rx->data->data[n+1] = (void*)sop;
2172 RExC_rx->data->data[n+2] = (void*)av;
2175 else { /* First pass */
2176 if (PL_reginterp_cnt < ++RExC_seen_evals
2177 && PL_curcop != &PL_compiling)
2178 /* No compiled RE interpolated, has runtime
2179 components ===> unsafe. */
2180 FAIL("Eval-group not allowed at runtime, use re 'eval'");
2181 if (PL_tainting && PL_tainted)
2182 FAIL("Eval-group in insecure regular expression");
2185 nextchar(pRExC_state);
2187 ret = reg_node(pRExC_state, LOGICAL);
2190 regtail(pRExC_state, ret, reganode(pRExC_state, EVAL, n));
2191 /* deal with the length of this later - MJD */
2194 return reganode(pRExC_state, EVAL, n);
2196 case '(': /* (?(?{...})...) and (?(?=...)...) */
2198 if (RExC_parse[0] == '?') { /* (?(?...)) */
2199 if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
2200 || RExC_parse[1] == '<'
2201 || RExC_parse[1] == '{') { /* Lookahead or eval. */
2204 ret = reg_node(pRExC_state, LOGICAL);
2207 regtail(pRExC_state, ret, reg(pRExC_state, 1, &flag));
2211 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
2213 parno = atoi(RExC_parse++);
2215 while (isDIGIT(*RExC_parse))
2217 ret = reganode(pRExC_state, GROUPP, parno);
2219 if ((c = *nextchar(pRExC_state)) != ')')
2220 vFAIL("Switch condition not recognized");
2222 regtail(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
2223 br = regbranch(pRExC_state, &flags, 1);
2225 br = reganode(pRExC_state, LONGJMP, 0);
2227 regtail(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
2228 c = *nextchar(pRExC_state);
2232 lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
2233 regbranch(pRExC_state, &flags, 1);
2234 regtail(pRExC_state, ret, lastbr);
2237 c = *nextchar(pRExC_state);
2242 vFAIL("Switch (?(condition)... contains too many branches");
2243 ender = reg_node(pRExC_state, TAIL);
2244 regtail(pRExC_state, br, ender);
2246 regtail(pRExC_state, lastbr, ender);
2247 regtail(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
2250 regtail(pRExC_state, ret, ender);
2254 vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
2258 RExC_parse--; /* for vFAIL to print correctly */
2259 vFAIL("Sequence (? incomplete");
2263 parse_flags: /* (?i) */
2264 while (*RExC_parse && strchr("iogcmsx", *RExC_parse)) {
2265 /* (?g), (?gc) and (?o) are useless here
2266 and must be globally applied -- japhy */
2268 if (*RExC_parse == 'o' || *RExC_parse == 'g') {
2269 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
2270 I32 wflagbit = *RExC_parse == 'o' ? wasted_o : wasted_g;
2271 if (! (wastedflags & wflagbit) ) {
2272 wastedflags |= wflagbit;
2275 "Useless (%s%c) - %suse /%c modifier",
2276 flagsp == &negflags ? "?-" : "?",
2278 flagsp == &negflags ? "don't " : "",
2284 else if (*RExC_parse == 'c') {
2285 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
2286 if (! (wastedflags & wasted_c) ) {
2287 wastedflags |= wasted_gc;
2290 "Useless (%sc) - %suse /gc modifier",
2291 flagsp == &negflags ? "?-" : "?",
2292 flagsp == &negflags ? "don't " : ""
2297 else { pmflag(flagsp, *RExC_parse); }
2301 if (*RExC_parse == '-') {
2303 wastedflags = 0; /* reset so (?g-c) warns twice */
2307 RExC_flags16 |= posflags;
2308 RExC_flags16 &= ~negflags;
2309 if (*RExC_parse == ':') {
2315 if (*RExC_parse != ')') {
2317 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
2319 nextchar(pRExC_state);
2327 ret = reganode(pRExC_state, OPEN, parno);
2328 Set_Node_Length(ret, 1); /* MJD */
2329 Set_Node_Offset(ret, RExC_parse); /* MJD */
2336 /* Pick up the branches, linking them together. */
2337 parse_start = RExC_parse; /* MJD */
2338 br = regbranch(pRExC_state, &flags, 1);
2339 /* branch_len = (paren != 0); */
2343 if (*RExC_parse == '|') {
2344 if (!SIZE_ONLY && RExC_extralen) {
2345 reginsert(pRExC_state, BRANCHJ, br);
2348 reginsert(pRExC_state, BRANCH, br);
2349 Set_Node_Length(br, paren != 0);
2350 Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
2354 RExC_extralen += 1; /* For BRANCHJ-BRANCH. */
2356 else if (paren == ':') {
2357 *flagp |= flags&SIMPLE;
2359 if (open) { /* Starts with OPEN. */
2360 regtail(pRExC_state, ret, br); /* OPEN -> first. */
2362 else if (paren != '?') /* Not Conditional */
2366 *flagp |= flags&SPSTART;
2368 while (*RExC_parse == '|') {
2369 if (!SIZE_ONLY && RExC_extralen) {
2370 ender = reganode(pRExC_state, LONGJMP,0);
2371 regtail(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
2374 RExC_extralen += 2; /* Account for LONGJMP. */
2375 nextchar(pRExC_state);
2376 br = regbranch(pRExC_state, &flags, 0);
2380 regtail(pRExC_state, lastbr, br); /* BRANCH -> BRANCH. */
2384 *flagp |= flags&SPSTART;
2387 if (have_branch || paren != ':') {
2388 /* Make a closing node, and hook it on the end. */
2391 ender = reg_node(pRExC_state, TAIL);
2394 ender = reganode(pRExC_state, CLOSE, parno);
2395 Set_Node_Offset(ender,RExC_parse+1); /* MJD */
2396 Set_Node_Length(ender,1); /* MJD */
2402 *flagp &= ~HASWIDTH;
2405 ender = reg_node(pRExC_state, SUCCEED);
2408 ender = reg_node(pRExC_state, END);
2411 regtail(pRExC_state, lastbr, ender);
2414 /* Hook the tails of the branches to the closing node. */
2415 for (br = ret; br != NULL; br = regnext(br)) {
2416 regoptail(pRExC_state, br, ender);
2423 static char parens[] = "=!<,>";
2425 if (paren && (p = strchr(parens, paren))) {
2426 int node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
2427 int flag = (p - parens) > 1;
2430 node = SUSPEND, flag = 0;
2431 reginsert(pRExC_state, node,ret);
2433 regtail(pRExC_state, ret, reg_node(pRExC_state, TAIL));
2437 /* Check for proper termination. */
2439 RExC_flags16 = oregflags;
2440 if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
2441 RExC_parse = oregcomp_parse;
2442 vFAIL("Unmatched (");
2445 else if (!paren && RExC_parse < RExC_end) {
2446 if (*RExC_parse == ')') {
2448 vFAIL("Unmatched )");
2451 FAIL("Junk on end of regexp"); /* "Can't happen". */
2459 - regbranch - one alternative of an | operator
2461 * Implements the concatenation operator.
2464 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first)
2466 register regnode *ret;
2467 register regnode *chain = NULL;
2468 register regnode *latest;
2469 I32 flags = 0, c = 0;
2474 if (!SIZE_ONLY && RExC_extralen)
2475 ret = reganode(pRExC_state, BRANCHJ,0);
2477 ret = reg_node(pRExC_state, BRANCH);
2478 Set_Node_Length(ret, 1);
2482 if (!first && SIZE_ONLY)
2483 RExC_extralen += 1; /* BRANCHJ */
2485 *flagp = WORST; /* Tentatively. */
2488 nextchar(pRExC_state);
2489 while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
2491 latest = regpiece(pRExC_state, &flags);
2492 if (latest == NULL) {
2493 if (flags & TRYAGAIN)
2497 else if (ret == NULL)
2499 *flagp |= flags&HASWIDTH;
2500 if (chain == NULL) /* First piece. */
2501 *flagp |= flags&SPSTART;
2504 regtail(pRExC_state, chain, latest);
2509 if (chain == NULL) { /* Loop ran zero times. */
2510 chain = reg_node(pRExC_state, NOTHING);
2515 *flagp |= flags&SIMPLE;
2522 - regpiece - something followed by possible [*+?]
2524 * Note that the branching code sequences used for ? and the general cases
2525 * of * and + are somewhat optimized: they use the same NOTHING node as
2526 * both the endmarker for their branch list and the body of the last branch.
2527 * It might seem that this node could be dispensed with entirely, but the
2528 * endmarker role is not redundant.
2531 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp)
2533 register regnode *ret;
2535 register char *next;
2537 char *origparse = RExC_parse;
2540 I32 max = REG_INFTY;
2543 ret = regatom(pRExC_state, &flags);
2545 if (flags & TRYAGAIN)
2552 if (op == '{' && regcurly(RExC_parse)) {
2553 parse_start = RExC_parse; /* MJD */
2554 next = RExC_parse + 1;
2556 while (isDIGIT(*next) || *next == ',') {
2565 if (*next == '}') { /* got one */
2569 min = atoi(RExC_parse);
2573 maxpos = RExC_parse;
2575 if (!max && *maxpos != '0')
2576 max = REG_INFTY; /* meaning "infinity" */
2577 else if (max >= REG_INFTY)
2578 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
2580 nextchar(pRExC_state);
2583 if ((flags&SIMPLE)) {
2584 RExC_naughty += 2 + RExC_naughty / 2;
2585 reginsert(pRExC_state, CURLY, ret);
2586 Set_Node_Offset(ret, parse_start+1); /* MJD */
2587 Set_Node_Cur_Length(ret);
2590 regnode *w = reg_node(pRExC_state, WHILEM);
2593 regtail(pRExC_state, ret, w);
2594 if (!SIZE_ONLY && RExC_extralen) {
2595 reginsert(pRExC_state, LONGJMP,ret);
2596 reginsert(pRExC_state, NOTHING,ret);
2597 NEXT_OFF(ret) = 3; /* Go over LONGJMP. */
2599 reginsert(pRExC_state, CURLYX,ret);
2601 Set_Node_Offset(ret, parse_start+1);
2602 Set_Node_Length(ret,
2603 op == '{' ? (RExC_parse - parse_start) : 1);
2605 if (!SIZE_ONLY && RExC_extralen)
2606 NEXT_OFF(ret) = 3; /* Go over NOTHING to LONGJMP. */
2607 regtail(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
2609 RExC_whilem_seen++, RExC_extralen += 3;
2610 RExC_naughty += 4 + RExC_naughty; /* compound interest */
2618 if (max && max < min)
2619 vFAIL("Can't do {n,m} with n > m");
2634 #if 0 /* Now runtime fix should be reliable. */
2636 /* if this is reinstated, don't forget to put this back into perldiag:
2638 =item Regexp *+ operand could be empty at {#} in regex m/%s/
2640 (F) The part of the regexp subject to either the * or + quantifier
2641 could match an empty string. The {#} shows in the regular
2642 expression about where the problem was discovered.
2646 if (!(flags&HASWIDTH) && op != '?')
2647 vFAIL("Regexp *+ operand could be empty");
2650 parse_start = RExC_parse;
2651 nextchar(pRExC_state);
2653 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
2655 if (op == '*' && (flags&SIMPLE)) {
2656 reginsert(pRExC_state, STAR, ret);
2660 else if (op == '*') {
2664 else if (op == '+' && (flags&SIMPLE)) {
2665 reginsert(pRExC_state, PLUS, ret);
2669 else if (op == '+') {
2673 else if (op == '?') {
2678 if (ckWARN(WARN_REGEXP) && !SIZE_ONLY && !(flags&HASWIDTH) && max > REG_INFTY/3) {
2680 "%.*s matches null string many times",
2681 RExC_parse - origparse,
2685 if (*RExC_parse == '?') {
2686 nextchar(pRExC_state);
2687 reginsert(pRExC_state, MINMOD, ret);
2688 regtail(pRExC_state, ret, ret + NODE_STEP_REGNODE);
2690 if (ISMULT2(RExC_parse)) {
2692 vFAIL("Nested quantifiers");
2699 - regatom - the lowest level
2701 * Optimization: gobbles an entire sequence of ordinary characters so that
2702 * it can turn them into a single node, which is smaller to store and
2703 * faster to run. Backslashed characters are exceptions, each becoming a
2704 * separate node; the code is simpler that way and it's not worth fixing.
2706 * [Yes, it is worth fixing, some scripts can run twice the speed.] */
2708 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp)
2710 register regnode *ret = 0;
2712 char *parse_start = 0;
2714 *flagp = WORST; /* Tentatively. */
2717 switch (*RExC_parse) {
2719 RExC_seen_zerolen++;
2720 nextchar(pRExC_state);
2721 if (RExC_flags16 & PMf_MULTILINE)
2722 ret = reg_node(pRExC_state, MBOL);
2723 else if (RExC_flags16 & PMf_SINGLELINE)
2724 ret = reg_node(pRExC_state, SBOL);
2726 ret = reg_node(pRExC_state, BOL);
2727 Set_Node_Length(ret, 1); /* MJD */
2730 nextchar(pRExC_state);
2732 RExC_seen_zerolen++;
2733 if (RExC_flags16 & PMf_MULTILINE)
2734 ret = reg_node(pRExC_state, MEOL);
2735 else if (RExC_flags16 & PMf_SINGLELINE)
2736 ret = reg_node(pRExC_state, SEOL);
2738 ret = reg_node(pRExC_state, EOL);
2739 Set_Node_Length(ret, 1); /* MJD */
2742 nextchar(pRExC_state);
2743 if (RExC_flags16 & PMf_SINGLELINE)
2744 ret = reg_node(pRExC_state, SANY);
2746 ret = reg_node(pRExC_state, REG_ANY);
2747 *flagp |= HASWIDTH|SIMPLE;
2749 Set_Node_Length(ret, 1); /* MJD */
2753 char *oregcomp_parse = ++RExC_parse;
2754 ret = regclass(pRExC_state);
2755 if (*RExC_parse != ']') {
2756 RExC_parse = oregcomp_parse;
2757 vFAIL("Unmatched [");
2759 nextchar(pRExC_state);
2760 *flagp |= HASWIDTH|SIMPLE;
2761 Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
2765 nextchar(pRExC_state);
2766 ret = reg(pRExC_state, 1, &flags);
2768 if (flags & TRYAGAIN) {
2769 if (RExC_parse == RExC_end) {
2770 /* Make parent create an empty node if needed. */
2778 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE);
2782 if (flags & TRYAGAIN) {
2786 vFAIL("Internal urp");
2787 /* Supposed to be caught earlier. */
2790 if (!regcurly(RExC_parse)) {
2799 vFAIL("Quantifier follows nothing");
2802 switch (*++RExC_parse) {
2804 RExC_seen_zerolen++;
2805 ret = reg_node(pRExC_state, SBOL);
2807 nextchar(pRExC_state);
2808 Set_Node_Length(ret, 2); /* MJD */
2811 ret = reg_node(pRExC_state, GPOS);
2812 RExC_seen |= REG_SEEN_GPOS;
2814 nextchar(pRExC_state);
2815 Set_Node_Length(ret, 2); /* MJD */
2818 ret = reg_node(pRExC_state, SEOL);
2820 RExC_seen_zerolen++; /* Do not optimize RE away */
2821 nextchar(pRExC_state);
2824 ret = reg_node(pRExC_state, EOS);
2826 RExC_seen_zerolen++; /* Do not optimize RE away */
2827 nextchar(pRExC_state);
2828 Set_Node_Length(ret, 2); /* MJD */
2831 ret = reg_node(pRExC_state, CANY);
2832 RExC_seen |= REG_SEEN_CANY;
2833 *flagp |= HASWIDTH|SIMPLE;
2834 nextchar(pRExC_state);
2835 Set_Node_Length(ret, 2); /* MJD */
2838 ret = reg_node(pRExC_state, CLUMP);
2840 nextchar(pRExC_state);
2841 Set_Node_Length(ret, 2); /* MJD */
2844 ret = reg_node(pRExC_state, LOC ? ALNUML : ALNUM);
2845 *flagp |= HASWIDTH|SIMPLE;
2846 nextchar(pRExC_state);
2847 Set_Node_Length(ret, 2); /* MJD */
2850 ret = reg_node(pRExC_state, LOC ? NALNUML : NALNUM);
2851 *flagp |= HASWIDTH|SIMPLE;
2852 nextchar(pRExC_state);
2853 Set_Node_Length(ret, 2); /* MJD */
2856 RExC_seen_zerolen++;
2857 RExC_seen |= REG_SEEN_LOOKBEHIND;
2858 ret = reg_node(pRExC_state, LOC ? BOUNDL : BOUND);
2860 nextchar(pRExC_state);
2861 Set_Node_Length(ret, 2); /* MJD */
2864 RExC_seen_zerolen++;
2865 RExC_seen |= REG_SEEN_LOOKBEHIND;
2866 ret = reg_node(pRExC_state, LOC ? NBOUNDL : NBOUND);
2868 nextchar(pRExC_state);
2869 Set_Node_Length(ret, 2); /* MJD */
2872 ret = reg_node(pRExC_state, LOC ? SPACEL : SPACE);
2873 *flagp |= HASWIDTH|SIMPLE;
2874 nextchar(pRExC_state);
2875 Set_Node_Length(ret, 2); /* MJD */
2878 ret = reg_node(pRExC_state, LOC ? NSPACEL : NSPACE);
2879 *flagp |= HASWIDTH|SIMPLE;
2880 nextchar(pRExC_state);
2881 Set_Node_Length(ret, 2); /* MJD */
2884 ret = reg_node(pRExC_state, DIGIT);
2885 *flagp |= HASWIDTH|SIMPLE;
2886 nextchar(pRExC_state);
2887 Set_Node_Length(ret, 2); /* MJD */
2890 ret = reg_node(pRExC_state, NDIGIT);
2891 *flagp |= HASWIDTH|SIMPLE;
2892 nextchar(pRExC_state);
2893 Set_Node_Length(ret, 2); /* MJD */
2898 char* oldregxend = RExC_end;
2899 char* parse_start = RExC_parse;
2901 if (RExC_parse[1] == '{') {
2902 /* a lovely hack--pretend we saw [\pX] instead */
2903 RExC_end = strchr(RExC_parse, '}');
2905 U8 c = (U8)*RExC_parse;
2907 RExC_end = oldregxend;
2908 vFAIL2("Missing right brace on \\%c{}", c);
2913 RExC_end = RExC_parse + 2;
2916 ret = regclass(pRExC_state);
2918 RExC_end = oldregxend;
2920 Set_Node_Cur_Length(ret); /* MJD */
2921 nextchar(pRExC_state);
2922 *flagp |= HASWIDTH|SIMPLE;
2935 case '1': case '2': case '3': case '4':
2936 case '5': case '6': case '7': case '8': case '9':
2938 I32 num = atoi(RExC_parse);
2940 if (num > 9 && num >= RExC_npar)
2943 char * parse_start = RExC_parse - 1; /* MJD */
2944 while (isDIGIT(*RExC_parse))
2947 if (!SIZE_ONLY && num > RExC_rx->nparens)
2948 vFAIL("Reference to nonexistent group");
2950 ret = reganode(pRExC_state, FOLD
2951 ? (LOC ? REFFL : REFF)
2955 /* override incorrect value set in reganode MJD */
2956 Set_Node_Offset(ret, parse_start+1);
2957 Set_Node_Cur_Length(ret); /* MJD */
2959 nextchar(pRExC_state);
2964 if (RExC_parse >= RExC_end)
2965 FAIL("Trailing \\");
2968 /* Do not generate `unrecognized' warnings here, we fall
2969 back into the quick-grab loop below */
2975 if (RExC_flags16 & PMf_EXTENDED) {
2976 while (RExC_parse < RExC_end && *RExC_parse != '\n') RExC_parse++;
2977 if (RExC_parse < RExC_end)
2983 register STRLEN len;
2989 U8 tmpbuf[UTF8_MAXLEN_FOLD+1], *foldbuf;
2991 parse_start = RExC_parse - 1;
2996 ret = reg_node(pRExC_state, FOLD
2997 ? (LOC ? EXACTFL : EXACTF)
3000 for (len = 0, p = RExC_parse - 1;
3001 len < 127 && p < RExC_end;
3006 if (RExC_flags16 & PMf_EXTENDED)
3007 p = regwhite(p, RExC_end);
3054 ender = ASCII_TO_NATIVE('\033');
3058 ender = ASCII_TO_NATIVE('\007');
3063 char* e = strchr(p, '}');
3067 vFAIL("Missing right brace on \\x{}");
3070 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
3071 | PERL_SCAN_DISALLOW_PREFIX;
3073 ender = grok_hex(p + 1, &numlen, &flags, NULL);
3076 /* numlen is generous */
3077 if (numlen + len >= 127) {
3085 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
3087 ender = grok_hex(p, &numlen, &flags, NULL);
3093 ender = UCHARAT(p++);
3094 ender = toCTRL(ender);
3096 case '0': case '1': case '2': case '3':case '4':
3097 case '5': case '6': case '7': case '8':case '9':
3099 (isDIGIT(p[1]) && atoi(p) >= RExC_npar) ) {
3102 ender = grok_oct(p, &numlen, &flags, NULL);
3112 FAIL("Trailing \\");
3115 if (!SIZE_ONLY && ckWARN(WARN_REGEXP) && isALPHA(*p))
3116 vWARN2(p + 1, "Unrecognized escape \\%c passed through", UCHARAT(p));
3117 goto normal_default;
3122 if (UTF8_IS_START(*p) && UTF) {
3123 ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
3131 if (RExC_flags16 & PMf_EXTENDED)
3132 p = regwhite(p, RExC_end);
3134 /* Prime the casefolded buffer. */
3135 ender = toFOLD_uni(ender, tmpbuf, &foldlen);
3137 if (ISMULT2(p)) { /* Back off on ?+*. */
3142 /* Emit all the Unicode characters. */
3143 for (foldbuf = tmpbuf;
3145 foldlen -= numlen) {
3146 ender = utf8_to_uvchr(foldbuf, &numlen);
3147 reguni(pRExC_state, ender, s, &numlen);
3154 reguni(pRExC_state, ender, s, &numlen);
3167 /* Emit all the Unicode characters. */
3168 for (foldbuf = tmpbuf;
3170 foldlen -= numlen) {
3171 ender = utf8_to_uvchr(foldbuf, &numlen);
3172 reguni(pRExC_state, ender, s, &numlen);
3179 reguni(pRExC_state, ender, s, &numlen);
3190 Set_Node_Cur_Length(ret); /* MJD */
3191 nextchar(pRExC_state);
3193 /* len is STRLEN which is unsigned, need to copy to signed */
3196 vFAIL("Internal disaster");
3205 RExC_size += STR_SZ(len);
3207 RExC_emit += STR_SZ(len);
3212 /* If the encoding pragma is in effect recode the text of
3213 * any EXACT-kind nodes. */
3214 if (PL_encoding && PL_regkind[(U8)OP(ret)] == EXACT) {
3215 STRLEN oldlen = STR_LEN(ret);
3216 SV *sv = sv_2mortal(newSVpvn(STRING(ret), oldlen));
3220 if (sv_utf8_downgrade(sv, TRUE)) {
3221 char *s = Perl_sv_recode_to_utf8(aTHX_ sv, PL_encoding);
3222 STRLEN newlen = SvCUR(sv);
3225 DEBUG_r(PerlIO_printf(Perl_debug_log, "recode %*s to %*s\n",
3226 (int)oldlen, STRING(ret),
3228 Copy(s, STRING(ret), newlen, char);
3229 STR_LEN(ret) += newlen - oldlen;
3230 RExC_emit += STR_SZ(newlen) - STR_SZ(oldlen);
3232 RExC_size += STR_SZ(newlen) - STR_SZ(oldlen);
3240 S_regwhite(pTHX_ char *p, char *e)
3245 else if (*p == '#') {
3248 } while (p < e && *p != '\n');
3256 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
3257 Character classes ([:foo:]) can also be negated ([:^foo:]).
3258 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
3259 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
3260 but trigger failures because they are currently unimplemented. */
3262 #define POSIXCC_DONE(c) ((c) == ':')
3263 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
3264 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
3267 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
3270 I32 namedclass = OOB_NAMEDCLASS;
3272 if (value == '[' && RExC_parse + 1 < RExC_end &&
3273 /* I smell either [: or [= or [. -- POSIX has been here, right? */
3274 POSIXCC(UCHARAT(RExC_parse))) {
3275 char c = UCHARAT(RExC_parse);
3276 char* s = RExC_parse++;
3278 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
3280 if (RExC_parse == RExC_end)
3281 /* Grandfather lone [:, [=, [. */
3284 char* t = RExC_parse++; /* skip over the c */
3286 if (UCHARAT(RExC_parse) == ']') {
3287 RExC_parse++; /* skip over the ending ] */
3290 I32 complement = *posixcc == '^' ? *posixcc++ : 0;
3291 I32 skip = 5; /* the most common skip */
3295 if (strnEQ(posixcc, "alnum", 5))
3297 complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
3298 else if (strnEQ(posixcc, "alpha", 5))
3300 complement ? ANYOF_NALPHA : ANYOF_ALPHA;
3301 else if (strnEQ(posixcc, "ascii", 5))
3303 complement ? ANYOF_NASCII : ANYOF_ASCII;
3306 if (strnEQ(posixcc, "blank", 5))
3308 complement ? ANYOF_NBLANK : ANYOF_BLANK;
3311 if (strnEQ(posixcc, "cntrl", 5))
3313 complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
3316 if (strnEQ(posixcc, "digit", 5))
3318 complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
3321 if (strnEQ(posixcc, "graph", 5))
3323 complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
3326 if (strnEQ(posixcc, "lower", 5))
3328 complement ? ANYOF_NLOWER : ANYOF_LOWER;
3331 if (strnEQ(posixcc, "print", 5))
3333 complement ? ANYOF_NPRINT : ANYOF_PRINT;
3334 else if (strnEQ(posixcc, "punct", 5))
3336 complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
3339 if (strnEQ(posixcc, "space", 5))
3341 complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
3344 if (strnEQ(posixcc, "upper", 5))
3346 complement ? ANYOF_NUPPER : ANYOF_UPPER;
3348 case 'w': /* this is not POSIX, this is the Perl \w */
3349 if (strnEQ(posixcc, "word", 4)) {
3351 complement ? ANYOF_NALNUM : ANYOF_ALNUM;
3356 if (strnEQ(posixcc, "xdigit", 6)) {
3358 complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
3363 if (namedclass == OOB_NAMEDCLASS ||
3364 posixcc[skip] != ':' ||
3365 posixcc[skip+1] != ']')
3367 Simple_vFAIL3("POSIX class [:%.*s:] unknown",
3370 } else if (!SIZE_ONLY) {
3371 /* [[=foo=]] and [[.foo.]] are still future. */
3373 /* adjust RExC_parse so the warning shows after
3375 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
3377 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
3380 /* Maternal grandfather:
3381 * "[:" ending in ":" but not in ":]" */
3391 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
3393 if (!SIZE_ONLY && ckWARN(WARN_REGEXP) &&
3394 POSIXCC(UCHARAT(RExC_parse))) {
3395 char *s = RExC_parse;
3398 while(*s && isALNUM(*s))
3400 if (*s && c == *s && s[1] == ']') {
3401 vWARN3(s+2, "POSIX syntax [%c %c] belongs inside character classes", c, c);
3403 /* [[=foo=]] and [[.foo.]] are still future. */
3404 if (POSIXCC_NOTYET(c)) {
3405 /* adjust RExC_parse so the error shows after
3407 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
3409 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
3416 S_regclass(pTHX_ RExC_state_t *pRExC_state)
3419 register UV nextvalue;
3420 register IV prevvalue = OOB_UNICODE;
3421 register IV range = 0;
3422 register regnode *ret;
3425 char *rangebegin = 0;
3426 bool need_class = 0;
3427 SV *listsv = Nullsv;
3430 bool optimize_invert = TRUE;
3431 AV* unicode_alternate = 0;
3433 ret = reganode(pRExC_state, ANYOF, 0);
3436 ANYOF_FLAGS(ret) = 0;
3438 if (UCHARAT(RExC_parse) == '^') { /* Complement of range. */
3442 ANYOF_FLAGS(ret) |= ANYOF_INVERT;
3446 RExC_size += ANYOF_SKIP;
3448 RExC_emit += ANYOF_SKIP;
3450 ANYOF_FLAGS(ret) |= ANYOF_FOLD;
3452 ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
3453 ANYOF_BITMAP_ZERO(ret);
3454 listsv = newSVpvn("# comment\n", 10);
3457 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
3459 if (!SIZE_ONLY && ckWARN(WARN_REGEXP) && POSIXCC(nextvalue))
3460 checkposixcc(pRExC_state);
3462 if (UCHARAT(RExC_parse) == ']' || UCHARAT(RExC_parse) == '-')
3463 goto charclassloop; /* allow 1st char to be ] or - */
3465 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
3469 namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
3472 rangebegin = RExC_parse;
3474 value = utf8n_to_uvchr((U8*)RExC_parse,
3475 RExC_end - RExC_parse,
3477 RExC_parse += numlen;
3480 value = UCHARAT(RExC_parse++);
3481 nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
3482 if (value == '[' && POSIXCC(nextvalue))
3483 namedclass = regpposixcc(pRExC_state, value);
3484 else if (value == '\\') {
3486 value = utf8n_to_uvchr((U8*)RExC_parse,
3487 RExC_end - RExC_parse,
3489 RExC_parse += numlen;
3492 value = UCHARAT(RExC_parse++);
3493 /* Some compilers cannot handle switching on 64-bit integer
3494 * values, therefore value cannot be an UV. Yes, this will
3495 * be a problem later if we want switch on Unicode.
3496 * A similar issue a little bit later when switching on
3497 * namedclass. --jhi */
3498 switch ((I32)value) {
3499 case 'w': namedclass = ANYOF_ALNUM; break;
3500 case 'W': namedclass = ANYOF_NALNUM; break;
3501 case 's': namedclass = ANYOF_SPACE; break;
3502 case 'S': namedclass = ANYOF_NSPACE; break;
3503 case 'd': namedclass = ANYOF_DIGIT; break;
3504 case 'D': namedclass = ANYOF_NDIGIT; break;
3507 if (*RExC_parse == '{') {
3509 e = strchr(RExC_parse++, '}');
3511 vFAIL2("Missing right brace on \\%c{}", c);
3512 while (isSPACE(UCHARAT(RExC_parse)))
3514 if (e == RExC_parse)
3515 vFAIL2("Empty \\%c{}", c);
3517 while (isSPACE(UCHARAT(RExC_parse + n - 1)))
3525 if (UCHARAT(RExC_parse) == '^') {
3528 value = value == 'p' ? 'P' : 'p'; /* toggle */
3529 while (isSPACE(UCHARAT(RExC_parse))) {
3535 Perl_sv_catpvf(aTHX_ listsv,
3536 "+utf8::%.*s\n", (int)n, RExC_parse);
3538 Perl_sv_catpvf(aTHX_ listsv,
3539 "!utf8::%.*s\n", (int)n, RExC_parse);
3542 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
3544 case 'n': value = '\n'; break;
3545 case 'r': value = '\r'; break;
3546 case 't': value = '\t'; break;
3547 case 'f': value = '\f'; break;
3548 case 'b': value = '\b'; break;
3549 case 'e': value = ASCII_TO_NATIVE('\033');break;
3550 case 'a': value = ASCII_TO_NATIVE('\007');break;
3552 if (*RExC_parse == '{') {
3553 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
3554 | PERL_SCAN_DISALLOW_PREFIX;
3555 e = strchr(RExC_parse++, '}');
3557 vFAIL("Missing right brace on \\x{}");
3559 numlen = e - RExC_parse;
3560 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
3564 I32 flags = PERL_SCAN_DISALLOW_PREFIX;
3566 value = grok_hex(RExC_parse, &numlen, &flags, NULL);
3567 RExC_parse += numlen;
3571 value = UCHARAT(RExC_parse++);
3572 value = toCTRL(value);
3574 case '0': case '1': case '2': case '3': case '4':
3575 case '5': case '6': case '7': case '8': case '9':
3579 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
3580 RExC_parse += numlen;
3584 if (!SIZE_ONLY && ckWARN(WARN_REGEXP) && isALPHA(value))
3586 "Unrecognized escape \\%c in character class passed through",
3590 } /* end of \blah */
3592 if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
3594 if (!SIZE_ONLY && !need_class)
3595 ANYOF_CLASS_ZERO(ret);
3599 /* a bad range like a-\d, a-[:digit:] ? */
3602 if (ckWARN(WARN_REGEXP))
3604 "False [] range \"%*.*s\"",
3605 RExC_parse - rangebegin,
3606 RExC_parse - rangebegin,
3608 if (prevvalue < 256) {
3609 ANYOF_BITMAP_SET(ret, prevvalue);
3610 ANYOF_BITMAP_SET(ret, '-');
3613 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
3614 Perl_sv_catpvf(aTHX_ listsv,
3615 "%04"UVxf"\n%04"UVxf"\n", (UV)prevvalue, (UV) '-');
3619 range = 0; /* this was not a true range */
3623 if (namedclass > OOB_NAMEDCLASS)
3624 optimize_invert = FALSE;
3625 /* Possible truncation here but in some 64-bit environments
3626 * the compiler gets heartburn about switch on 64-bit values.
3627 * A similar issue a little earlier when switching on value.
3629 switch ((I32)namedclass) {
3632 ANYOF_CLASS_SET(ret, ANYOF_ALNUM);
3634 for (value = 0; value < 256; value++)
3636 ANYOF_BITMAP_SET(ret, value);
3638 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsWord\n");
3642 ANYOF_CLASS_SET(ret, ANYOF_NALNUM);
3644 for (value = 0; value < 256; value++)
3645 if (!isALNUM(value))
3646 ANYOF_BITMAP_SET(ret, value);
3648 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsWord\n");
3652 ANYOF_CLASS_SET(ret, ANYOF_ALNUMC);
3654 for (value = 0; value < 256; value++)
3655 if (isALNUMC(value))
3656 ANYOF_BITMAP_SET(ret, value);
3658 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsAlnum\n");
3662 ANYOF_CLASS_SET(ret, ANYOF_NALNUMC);
3664 for (value = 0; value < 256; value++)
3665 if (!isALNUMC(value))
3666 ANYOF_BITMAP_SET(ret, value);
3668 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlnum\n");
3672 ANYOF_CLASS_SET(ret, ANYOF_ALPHA);
3674 for (value = 0; value < 256; value++)
3676 ANYOF_BITMAP_SET(ret, value);
3678 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsAlpha\n");
3682 ANYOF_CLASS_SET(ret, ANYOF_NALPHA);
3684 for (value = 0; value < 256; value++)
3685 if (!isALPHA(value))
3686 ANYOF_BITMAP_SET(ret, value);
3688 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlpha\n");
3692 ANYOF_CLASS_SET(ret, ANYOF_ASCII);
3695 for (value = 0; value < 128; value++)
3696 ANYOF_BITMAP_SET(ret, value);
3698 for (value = 0; value < 256; value++) {
3700 ANYOF_BITMAP_SET(ret, value);
3704 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsASCII\n");
3708 ANYOF_CLASS_SET(ret, ANYOF_NASCII);
3711 for (value = 128; value < 256; value++)
3712 ANYOF_BITMAP_SET(ret, value);
3714 for (value = 0; value < 256; value++) {
3715 if (!isASCII(value))
3716 ANYOF_BITMAP_SET(ret, value);
3720 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsASCII\n");
3724 ANYOF_CLASS_SET(ret, ANYOF_BLANK);
3726 for (value = 0; value < 256; value++)
3728 ANYOF_BITMAP_SET(ret, value);
3730 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsBlank\n");
3734 ANYOF_CLASS_SET(ret, ANYOF_NBLANK);
3736 for (value = 0; value < 256; value++)
3737 if (!isBLANK(value))
3738 ANYOF_BITMAP_SET(ret, value);
3740 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsBlank\n");
3744 ANYOF_CLASS_SET(ret, ANYOF_CNTRL);
3746 for (value = 0; value < 256; value++)
3748 ANYOF_BITMAP_SET(ret, value);
3750 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsCntrl\n");
3754 ANYOF_CLASS_SET(ret, ANYOF_NCNTRL);
3756 for (value = 0; value < 256; value++)
3757 if (!isCNTRL(value))
3758 ANYOF_BITMAP_SET(ret, value);
3760 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsCntrl\n");
3764 ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
3766 /* consecutive digits assumed */
3767 for (value = '0'; value <= '9'; value++)
3768 ANYOF_BITMAP_SET(ret, value);
3770 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsDigit\n");
3774 ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
3776 /* consecutive digits assumed */
3777 for (value = 0; value < '0'; value++)
3778 ANYOF_BITMAP_SET(ret, value);
3779 for (value = '9' + 1; value < 256; value++)
3780 ANYOF_BITMAP_SET(ret, value);
3782 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsDigit\n");
3786 ANYOF_CLASS_SET(ret, ANYOF_GRAPH);
3788 for (value = 0; value < 256; value++)
3790 ANYOF_BITMAP_SET(ret, value);
3792 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsGraph\n");
3796 ANYOF_CLASS_SET(ret, ANYOF_NGRAPH);
3798 for (value = 0; value < 256; value++)
3799 if (!isGRAPH(value))
3800 ANYOF_BITMAP_SET(ret, value);
3802 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsGraph\n");
3806 ANYOF_CLASS_SET(ret, ANYOF_LOWER);
3808 for (value = 0; value < 256; value++)
3810 ANYOF_BITMAP_SET(ret, value);
3812 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsLower\n");
3816 ANYOF_CLASS_SET(ret, ANYOF_NLOWER);
3818 for (value = 0; value < 256; value++)
3819 if (!isLOWER(value))
3820 ANYOF_BITMAP_SET(ret, value);
3822 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsLower\n");
3826 ANYOF_CLASS_SET(ret, ANYOF_PRINT);
3828 for (value = 0; value < 256; value++)
3830 ANYOF_BITMAP_SET(ret, value);
3832 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPrint\n");
3836 ANYOF_CLASS_SET(ret, ANYOF_NPRINT);
3838 for (value = 0; value < 256; value++)
3839 if (!isPRINT(value))
3840 ANYOF_BITMAP_SET(ret, value);
3842 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsPrint\n");
3846 ANYOF_CLASS_SET(ret, ANYOF_PSXSPC);
3848 for (value = 0; value < 256; value++)
3849 if (isPSXSPC(value))
3850 ANYOF_BITMAP_SET(ret, value);
3852 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsSpace\n");
3856 ANYOF_CLASS_SET(ret, ANYOF_NPSXSPC);
3858 for (value = 0; value < 256; value++)
3859 if (!isPSXSPC(value))
3860 ANYOF_BITMAP_SET(ret, value);
3862 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsSpace\n");
3866 ANYOF_CLASS_SET(ret, ANYOF_PUNCT);
3868 for (value = 0; value < 256; value++)
3870 ANYOF_BITMAP_SET(ret, value);
3872 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPunct\n");
3876 ANYOF_CLASS_SET(ret, ANYOF_NPUNCT);
3878 for (value = 0; value < 256; value++)