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
48 * pregcomp and pregexec -- regsub and regerror are not used in perl
50 * Copyright (c) 1986 by University of Toronto.
51 * Written by Henry Spencer. Not derived from licensed software.
53 * Permission is granted to anyone to use this software for any
54 * purpose on any computer system, and to redistribute it freely,
55 * subject to the following restrictions:
57 * 1. The author is not responsible for the consequences of use of
58 * this software, no matter how awful, even if they arise
61 * 2. The origin of this software must not be misrepresented, either
62 * by explicit claim or by omission.
64 * 3. Altered versions must be plainly marked as such, and must not
65 * be misrepresented as being the original software.
68 **** Alterations to Henry's code are...
70 **** Copyright (c) 1991-1999, Larry Wall
72 **** You may distribute under the terms of either the GNU General Public
73 **** License or the Artistic License, as specified in the README file.
76 * Beware that some of this code is subtly aware of the way operator
77 * precedence is structured in regular expressions. Serious changes in
78 * regular-expression syntax might require a total rethink.
81 #define PERL_IN_REGCOMP_C
84 #ifndef PERL_IN_XSUB_RE
96 # if defined(BUGGY_MSC6)
97 /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
98 # pragma optimize("a",off)
99 /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
100 # pragma optimize("w",on )
101 # endif /* BUGGY_MSC6 */
105 #define STATIC static
108 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
109 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
110 ((*s) == '{' && regcurly(s)))
112 #define PERL_META "^$.[()|?+*\\"
114 #define META "^$.[()|?+*\\"
118 #undef SPSTART /* dratted cpp namespace... */
121 * Flags to be passed up and down.
123 #define WORST 0 /* Worst case. */
124 #define HASWIDTH 0x1 /* Known to match non-null strings. */
125 #define SIMPLE 0x2 /* Simple enough to be STAR/PLUS operand. */
126 #define SPSTART 0x4 /* Starts with * or +. */
127 #define TRYAGAIN 0x8 /* Weeded out a declaration. */
130 * Forward declarations for pregcomp()'s friends.
133 static scan_data_t zero_scan_data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
136 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
137 #define SF_BEFORE_SEOL 0x1
138 #define SF_BEFORE_MEOL 0x2
139 #define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
140 #define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
143 # define SF_FIX_SHIFT_EOL (0+2)
144 # define SF_FL_SHIFT_EOL (0+4)
146 # define SF_FIX_SHIFT_EOL (+2)
147 # define SF_FL_SHIFT_EOL (+4)
150 #define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
151 #define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
153 #define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
154 #define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
155 #define SF_IS_INF 0x40
156 #define SF_HAS_PAR 0x80
157 #define SF_IN_PAR 0x100
158 #define SF_HAS_EVAL 0x200
159 #define SCF_DO_SUBSTR 0x400
162 #define UTF (PL_reg_flags & RF_utf8)
163 #define LOC (PL_regflags & PMf_LOCALE)
164 #define FOLD (PL_regflags & PMf_FOLD)
166 #define OOB_CHAR8 1234
167 #define OOB_UTF8 123456
169 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
170 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
173 S_clear_re(pTHX_ void *r)
175 ReREFCNT_dec((regexp *)r);
179 S_scan_commit(pTHX_ scan_data_t *data)
182 STRLEN l = CHR_SVLEN(data->last_found);
183 STRLEN old_l = CHR_SVLEN(*data->longest);
185 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
186 sv_setsv(*data->longest, data->last_found);
187 if (*data->longest == data->longest_fixed) {
188 data->offset_fixed = l ? data->last_start_min : data->pos_min;
189 if (data->flags & SF_BEFORE_EOL)
191 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
193 data->flags &= ~SF_FIX_BEFORE_EOL;
196 data->offset_float_min = l ? data->last_start_min : data->pos_min;
197 data->offset_float_max = (l
198 ? data->last_start_max
199 : data->pos_min + data->pos_delta);
200 if (data->flags & SF_BEFORE_EOL)
202 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
204 data->flags &= ~SF_FL_BEFORE_EOL;
207 SvCUR_set(data->last_found, 0);
209 data->flags &= ~SF_BEFORE_EOL;
212 /* Stops at toplevel WHILEM as well as at `last'. At end *scanp is set
213 to the position after last scanned or to NULL. */
216 S_study_chunk(pTHX_ regnode **scanp, I32 *deltap, regnode *last, scan_data_t *data, U32 flags)
217 /* scanp: Start here (read-write). */
218 /* deltap: Write maxlen-minlen here. */
219 /* last: Stop before this one. */
222 I32 min = 0, pars = 0, code;
223 regnode *scan = *scanp, *next;
225 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
226 int is_inf_internal = 0; /* The studied chunk is infinite */
227 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
228 scan_data_t data_fake;
230 while (scan && OP(scan) != END && scan < last) {
231 /* Peephole optimizer: */
233 if (PL_regkind[(U8)OP(scan)] == EXACT) {
234 regnode *n = regnext(scan);
237 regnode *stop = scan;
240 next = scan + (*OPERAND(scan) + 2 - 1)/sizeof(regnode) + 2;
241 /* Skip NOTHING, merge EXACT*. */
243 ( PL_regkind[(U8)OP(n)] == NOTHING ||
244 (stringok && (OP(n) == OP(scan))))
246 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
247 if (OP(n) == TAIL || n > next)
249 if (PL_regkind[(U8)OP(n)] == NOTHING) {
250 NEXT_OFF(scan) += NEXT_OFF(n);
251 next = n + NODE_STEP_REGNODE;
259 int oldl = *OPERAND(scan);
260 regnode *nnext = regnext(n);
262 if (oldl + *OPERAND(n) > U8_MAX)
264 NEXT_OFF(scan) += NEXT_OFF(n);
265 *OPERAND(scan) += *OPERAND(n);
266 next = n + (*OPERAND(n) + 2 - 1)/sizeof(regnode) + 2;
267 /* Now we can overwrite *n : */
268 Move(OPERAND(n) + 1, OPERAND(scan) + oldl + 1,
269 *OPERAND(n) + 1, char);
279 n = scan + (*OPERAND(scan) + 2 - 1)/sizeof(regnode) + 2;
281 /* Purify reports a benign UMR here sometimes, because we
282 * don't initialize the OP() slot of a node when that node
283 * is occupied by just the trailing null of the string in
285 if (PL_regkind[(U8)OP(n)] != NOTHING || OP(n) == NOTHING) {
294 if (OP(scan) != CURLYX) {
295 int max = (reg_off_by_arg[OP(scan)]
297 /* I32 may be smaller than U16 on CRAYs! */
298 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
299 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
303 /* Skip NOTHING and LONGJMP. */
304 while ((n = regnext(n))
305 && ((PL_regkind[(U8)OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
306 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
309 if (reg_off_by_arg[OP(scan)])
312 NEXT_OFF(scan) = off;
314 if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
315 || OP(scan) == IFTHEN || OP(scan) == SUSPEND) {
316 next = regnext(scan);
319 if (OP(next) == code || code == IFTHEN || code == SUSPEND) {
320 I32 max1 = 0, min1 = I32_MAX, num = 0;
322 if (flags & SCF_DO_SUBSTR)
324 while (OP(scan) == code) {
325 I32 deltanext, minnext;
329 next = regnext(scan);
330 scan = NEXTOPER(scan);
332 scan = NEXTOPER(scan);
333 /* We suppose the run is continuous, last=next...*/
334 minnext = study_chunk(&scan, &deltanext, next,
338 if (max1 < minnext + deltanext)
339 max1 = minnext + deltanext;
340 if (deltanext == I32_MAX)
341 is_inf = is_inf_internal = 1;
343 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
345 if (data && (data_fake.flags & SF_HAS_EVAL))
346 data->flags |= SF_HAS_EVAL;
350 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
352 if (flags & SCF_DO_SUBSTR) {
353 data->pos_min += min1;
354 data->pos_delta += max1 - min1;
355 if (max1 != min1 || is_inf)
356 data->longest = &(data->longest_float);
359 delta += max1 - min1;
361 else if (code == BRANCHJ) /* single branch is optimized. */
362 scan = NEXTOPER(NEXTOPER(scan));
363 else /* single branch is optimized. */
364 scan = NEXTOPER(scan);
367 else if (OP(scan) == EXACT) {
368 I32 l = *OPERAND(scan);
370 unsigned char *s = (unsigned char *)(OPERAND(scan)+1);
371 unsigned char *e = s + l;
380 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
381 /* The code below prefers earlier match for fixed
382 offset, later match for variable offset. */
383 if (data->last_end == -1) { /* Update the start info. */
384 data->last_start_min = data->pos_min;
385 data->last_start_max = is_inf
386 ? I32_MAX : data->pos_min + data->pos_delta;
388 sv_catpvn(data->last_found, (char *)(OPERAND(scan)+1), *OPERAND(scan));
389 data->last_end = data->pos_min + l;
390 data->pos_min += l; /* As in the first entry. */
391 data->flags &= ~SF_BEFORE_EOL;
394 else if (PL_regkind[(U8)OP(scan)] == EXACT) {
395 I32 l = *OPERAND(scan);
396 if (flags & SCF_DO_SUBSTR)
399 unsigned char *s = (unsigned char *)(OPERAND(scan)+1);
400 unsigned char *e = s + l;
409 if (data && (flags & SCF_DO_SUBSTR))
412 else if (strchr(PL_varies,OP(scan))) {
413 I32 mincount, maxcount, minnext, deltanext, pos_before, fl;
414 regnode *oscan = scan;
416 switch (PL_regkind[(U8)OP(scan)]) {
418 scan = NEXTOPER(scan);
421 if (flags & SCF_DO_SUBSTR) {
422 next = NEXTOPER(scan);
423 if (OP(next) == EXACT) {
425 maxcount = REG_INFTY;
426 next = regnext(scan);
427 scan = NEXTOPER(scan);
431 if (flags & SCF_DO_SUBSTR)
436 is_inf = is_inf_internal = 1;
437 scan = regnext(scan);
438 if (flags & SCF_DO_SUBSTR) {
440 data->longest = &(data->longest_float);
442 goto optimize_curly_tail;
444 mincount = ARG1(scan);
445 maxcount = ARG2(scan);
446 next = regnext(scan);
447 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
449 if (flags & SCF_DO_SUBSTR) {
450 if (mincount == 0) scan_commit(data);
451 pos_before = data->pos_min;
455 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
457 data->flags |= SF_IS_INF;
459 /* This will finish on WHILEM, setting scan, or on NULL: */
460 minnext = study_chunk(&scan, &deltanext, last, data,
462 ? (flags & ~SCF_DO_SUBSTR) : flags);
463 if (!scan) /* It was not CURLYX, but CURLY. */
465 if (ckWARN(WARN_UNSAFE) && (minnext + deltanext == 0)
466 && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
467 && maxcount <= REG_INFTY/3) /* Complement check for big count */
468 Perl_warner(aTHX_ WARN_UNSAFE, "Strange *+?{} on zero-length expression");
469 min += minnext * mincount;
470 is_inf_internal |= (maxcount == REG_INFTY
471 && (minnext + deltanext) > 0
472 || deltanext == I32_MAX);
473 is_inf |= is_inf_internal;
474 delta += (minnext + deltanext) * maxcount - minnext * mincount;
476 /* Try powerful optimization CURLYX => CURLYN. */
477 if ( OP(oscan) == CURLYX && data
478 && data->flags & SF_IN_PAR
479 && !(data->flags & SF_HAS_EVAL)
480 && !deltanext && minnext == 1 ) {
481 /* Try to optimize to CURLYN. */
482 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
483 regnode *nxt1 = nxt, *nxt2;
487 if (!strchr(PL_simple,OP(nxt))
488 && !(PL_regkind[(U8)OP(nxt)] == EXACT
489 && *OPERAND(nxt) == 1))
493 if (OP(nxt) != CLOSE)
495 /* Now we know that nxt2 is the only contents: */
496 oscan->flags = ARG(nxt);
498 OP(nxt1) = NOTHING; /* was OPEN. */
500 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
501 NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
502 NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
503 OP(nxt) = OPTIMIZED; /* was CLOSE. */
504 OP(nxt + 1) = OPTIMIZED; /* was count. */
505 NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
510 /* Try optimization CURLYX => CURLYM. */
511 if ( OP(oscan) == CURLYX && data
512 && !(data->flags & SF_HAS_PAR)
513 && !(data->flags & SF_HAS_EVAL)
515 /* XXXX How to optimize if data == 0? */
516 /* Optimize to a simpler form. */
517 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
521 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
522 && (OP(nxt2) != WHILEM))
524 OP(nxt2) = SUCCEED; /* Whas WHILEM */
525 /* Need to optimize away parenths. */
526 if (data->flags & SF_IN_PAR) {
527 /* Set the parenth number. */
528 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
530 if (OP(nxt) != CLOSE)
531 FAIL("panic opt close");
532 oscan->flags = ARG(nxt);
533 OP(nxt1) = OPTIMIZED; /* was OPEN. */
534 OP(nxt) = OPTIMIZED; /* was CLOSE. */
536 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
537 OP(nxt + 1) = OPTIMIZED; /* was count. */
538 NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
539 NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
542 while ( nxt1 && (OP(nxt1) != WHILEM)) {
543 regnode *nnxt = regnext(nxt1);
546 if (reg_off_by_arg[OP(nxt1)])
547 ARG_SET(nxt1, nxt2 - nxt1);
548 else if (nxt2 - nxt1 < U16_MAX)
549 NEXT_OFF(nxt1) = nxt2 - nxt1;
551 OP(nxt) = NOTHING; /* Cannot beautify */
556 /* Optimize again: */
557 study_chunk(&nxt1, &deltanext, nxt, NULL, 0);
562 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
564 if (flags & SCF_DO_SUBSTR) {
565 SV *last_str = Nullsv;
566 int counted = mincount != 0;
568 if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
569 I32 b = pos_before >= data->last_start_min
570 ? pos_before : data->last_start_min;
572 char *s = SvPV(data->last_found, l);
573 I32 old = b - data->last_start_min;
576 old = utf8_hop((U8*)s, old) - (U8*)s;
579 /* Get the added string: */
580 last_str = newSVpvn(s + old, l);
581 if (deltanext == 0 && pos_before == b) {
582 /* What was added is a constant string */
584 SvGROW(last_str, (mincount * l) + 1);
585 repeatcpy(SvPVX(last_str) + l,
586 SvPVX(last_str), l, mincount - 1);
587 SvCUR(last_str) *= mincount;
588 /* Add additional parts. */
589 SvCUR_set(data->last_found,
590 SvCUR(data->last_found) - l);
591 sv_catsv(data->last_found, last_str);
592 data->last_end += l * (mincount - 1);
596 /* It is counted once already... */
597 data->pos_min += minnext * (mincount - counted);
598 data->pos_delta += - counted * deltanext +
599 (minnext + deltanext) * maxcount - minnext * mincount;
600 if (mincount != maxcount) {
602 if (mincount && last_str) {
603 sv_setsv(data->last_found, last_str);
604 data->last_end = data->pos_min;
605 data->last_start_min =
606 data->pos_min - CHR_SVLEN(last_str);
607 data->last_start_max = is_inf
609 : data->pos_min + data->pos_delta
610 - CHR_SVLEN(last_str);
612 data->longest = &(data->longest_float);
614 SvREFCNT_dec(last_str);
616 if (data && (fl & SF_HAS_EVAL))
617 data->flags |= SF_HAS_EVAL;
619 if (OP(oscan) != CURLYX) {
620 while (PL_regkind[(U8)OP(next = regnext(oscan))] == NOTHING
622 NEXT_OFF(oscan) += NEXT_OFF(next);
625 default: /* REF only? */
626 if (flags & SCF_DO_SUBSTR) {
628 data->longest = &(data->longest_float);
630 is_inf = is_inf_internal = 1;
634 else if (strchr(PL_simple,OP(scan)) || PL_regkind[(U8)OP(scan)] == ANYUTF8) {
635 if (flags & SCF_DO_SUBSTR) {
641 else if (PL_regkind[(U8)OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
642 data->flags |= (OP(scan) == MEOL
646 else if (PL_regkind[(U8)OP(scan)] == BRANCHJ
647 && (scan->flags || data)
648 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
649 I32 deltanext, minnext;
653 next = regnext(scan);
654 nscan = NEXTOPER(NEXTOPER(scan));
655 minnext = study_chunk(&nscan, &deltanext, last, &data_fake, 0);
658 FAIL("variable length lookbehind not implemented");
660 else if (minnext > U8_MAX) {
661 FAIL2("lookbehind longer than %d not implemented", U8_MAX);
663 scan->flags = minnext;
665 if (data && data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
667 if (data && (data_fake.flags & SF_HAS_EVAL))
668 data->flags |= SF_HAS_EVAL;
670 else if (OP(scan) == OPEN) {
673 else if (OP(scan) == CLOSE && ARG(scan) == is_par) {
674 next = regnext(scan);
676 if ( next && (OP(next) != WHILEM) && next < last)
677 is_par = 0; /* Disable optimization */
679 else if (OP(scan) == EVAL) {
681 data->flags |= SF_HAS_EVAL;
683 else if (OP(scan) == LOGICAL && scan->flags == 2) { /* Embedded */
684 if (flags & SCF_DO_SUBSTR) {
686 data->longest = &(data->longest_float);
688 is_inf = is_inf_internal = 1;
690 /* Else: zero-length, ignore. */
691 scan = regnext(scan);
696 *deltap = is_inf_internal ? I32_MAX : delta;
697 if (flags & SCF_DO_SUBSTR && is_inf)
698 data->pos_delta = I32_MAX - data->pos_min;
701 if (is_par && pars==1 && data) {
702 data->flags |= SF_IN_PAR;
703 data->flags &= ~SF_HAS_PAR;
705 else if (pars && data) {
706 data->flags |= SF_HAS_PAR;
707 data->flags &= ~SF_IN_PAR;
713 S_add_data(pTHX_ I32 n, char *s)
716 if (PL_regcomp_rx->data) {
717 Renewc(PL_regcomp_rx->data,
718 sizeof(*PL_regcomp_rx->data) + sizeof(void*) * (PL_regcomp_rx->data->count + n - 1),
719 char, struct reg_data);
720 Renew(PL_regcomp_rx->data->what, PL_regcomp_rx->data->count + n, U8);
721 PL_regcomp_rx->data->count += n;
724 Newc(1207, PL_regcomp_rx->data, sizeof(*PL_regcomp_rx->data) + sizeof(void*) * (n - 1),
725 char, struct reg_data);
726 New(1208, PL_regcomp_rx->data->what, n, U8);
727 PL_regcomp_rx->data->count = n;
729 Copy(s, PL_regcomp_rx->data->what + PL_regcomp_rx->data->count - n, n, U8);
730 return PL_regcomp_rx->data->count - n;
734 Perl_reginitcolors(pTHX)
738 char *s = PerlEnv_getenv("PERL_RE_COLORS");
741 PL_colors[0] = s = savepv(s);
749 PL_colors[i] = s = "";
759 - pregcomp - compile a regular expression into internal code
761 * We can't allocate space until we know how big the compiled form will be,
762 * but we can't compile it (and thus know how big it is) until we've got a
763 * place to put the code. So we cheat: we compile it twice, once with code
764 * generation turned off and size counting turned on, and once "for real".
765 * This also means that we don't allocate space until we are sure that the
766 * thing really will compile successfully, and we never have to move the
767 * code and thus invalidate pointers into it. (Note that it has to be in
768 * one piece because free() must be able to free it all.) [NB: not true in perl]
770 * Beware that the optimization-preparation code in here knows about some
771 * of the structure of the compiled regexp. [I'll say.]
774 Perl_pregcomp(pTHX_ char *exp, char *xend, PMOP *pm)
789 FAIL("NULL regexp argument");
791 if (PL_curcop == &PL_compiling ? (PL_hints & HINT_UTF8) : IN_UTF8)
792 PL_reg_flags |= RF_utf8;
796 PL_regprecomp = savepvn(exp, xend - exp);
797 DEBUG_r(if (!PL_colorset) reginitcolors());
798 DEBUG_r(PerlIO_printf(Perl_debug_log, "%sCompiling%s RE `%s%*s%s'\n",
799 PL_colors[4],PL_colors[5],PL_colors[0],
800 xend - exp, PL_regprecomp, PL_colors[1]));
801 PL_regflags = pm->op_pmflags;
805 PL_seen_zerolen = *exp == '^' ? -1 : 0;
809 /* First pass: determine size, legality. */
810 PL_regcomp_parse = exp;
815 PL_regcode = &PL_regdummy;
816 regc((U8)REG_MAGIC, (char*)PL_regcode);
817 if (reg(0, &flags) == NULL) {
818 Safefree(PL_regprecomp);
819 PL_regprecomp = Nullch;
822 DEBUG_r(PerlIO_printf(Perl_debug_log, "size %d ", PL_regsize));
824 /* Small enough for pointer-storage convention?
825 If extralen==0, this means that we will not need long jumps. */
826 if (PL_regsize >= 0x10000L && PL_extralen)
827 PL_regsize += PL_extralen;
831 /* Allocate space and initialize. */
832 Newc(1001, r, sizeof(regexp) + (unsigned)PL_regsize * sizeof(regnode),
835 FAIL("regexp out of space");
837 r->prelen = xend - exp;
838 r->precomp = PL_regprecomp;
840 r->reganch = pm->op_pmflags & PMf_COMPILETIME;
841 r->nparens = PL_regnpar - 1; /* set early to validate backrefs */
843 r->substrs = 0; /* Useful during FAIL. */
844 r->startp = 0; /* Useful during FAIL. */
845 r->endp = 0; /* Useful during FAIL. */
849 /* Second pass: emit code. */
850 PL_regcomp_parse = exp;
854 PL_regcode = r->program;
855 /* Store the count of eval-groups for security checks: */
856 PL_regcode->next_off = ((PL_seen_evals > U16_MAX) ? U16_MAX : PL_seen_evals);
857 regc((U8)REG_MAGIC, (char*) PL_regcode++);
859 if (reg(0, &flags) == NULL)
862 /* Dig out information for optimizations. */
863 r->reganch = pm->op_pmflags & PMf_COMPILETIME; /* Again? */
864 pm->op_pmflags = PL_regflags;
866 r->reganch |= ROPT_UTF8;
867 r->regstclass = NULL;
868 if (PL_regnaughty >= 10) /* Probably an expensive pattern. */
869 r->reganch |= ROPT_NAUGHTY;
870 scan = r->program + 1; /* First BRANCH. */
872 /* XXXX To minimize changes to RE engine we always allocate
873 3-units-long substrs field. */
874 Newz(1004, r->substrs, 1, struct reg_substr_data);
876 if (OP(scan) != BRANCH) { /* Only one top-level choice. */
879 STRLEN longest_float_length, longest_fixed_length;
881 StructCopy(&zero_scan_data, &data, scan_data_t);
883 /* Skip introductions and multiplicators >= 1. */
884 while ((OP(first) == OPEN && (sawopen = 1)) ||
885 (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
886 (OP(first) == PLUS) ||
887 (OP(first) == MINMOD) ||
888 (PL_regkind[(U8)OP(first)] == CURLY && ARG1(first) > 0) ) {
889 if (OP(first) == PLUS)
892 first += regarglen[(U8)OP(first)];
893 first = NEXTOPER(first);
896 /* Starting-point info. */
898 if (OP(first) == EXACT); /* Empty, get anchored substr later. */
899 else if (strchr(PL_simple+4,OP(first)))
900 r->regstclass = first;
901 else if (PL_regkind[(U8)OP(first)] == BOUND ||
902 PL_regkind[(U8)OP(first)] == NBOUND)
903 r->regstclass = first;
904 else if (PL_regkind[(U8)OP(first)] == BOL) {
905 r->reganch |= (OP(first) == MBOL
910 first = NEXTOPER(first);
913 else if (OP(first) == GPOS) {
914 r->reganch |= ROPT_ANCH_GPOS;
915 first = NEXTOPER(first);
918 else if ((OP(first) == STAR &&
919 PL_regkind[(U8)OP(NEXTOPER(first))] == REG_ANY) &&
920 !(r->reganch & ROPT_ANCH) )
922 /* turn .* into ^.* with an implied $*=1 */
923 int type = OP(NEXTOPER(first));
925 if (type == REG_ANY || type == ANYUTF8)
926 type = ROPT_ANCH_MBOL;
928 type = ROPT_ANCH_SBOL;
930 r->reganch |= type | ROPT_IMPLICIT;
931 first = NEXTOPER(first);
934 if (sawplus && (!sawopen || !PL_regsawback)
935 && !(PL_regseen & REG_SEEN_EVAL)) /* May examine pos and $& */
936 /* x+ must match at the 1st pos of run of x's */
937 r->reganch |= ROPT_SKIP;
939 /* Scan is after the zeroth branch, first is atomic matcher. */
940 DEBUG_r(PerlIO_printf(Perl_debug_log, "first at %d\n",
943 * If there's something expensive in the r.e., find the
944 * longest literal string that must appear and make it the
945 * regmust. Resolve ties in favor of later strings, since
946 * the regstart check works with the beginning of the r.e.
947 * and avoiding duplication strengthens checking. Not a
948 * strong reason, but sufficient in the absence of others.
949 * [Now we resolve ties in favor of the earlier string if
950 * it happens that c_offset_min has been invalidated, since the
951 * earlier string may buy us something the later one won't.]
955 data.longest_fixed = newSVpvn("",0);
956 data.longest_float = newSVpvn("",0);
957 data.last_found = newSVpvn("",0);
958 data.longest = &(data.longest_fixed);
961 minlen = study_chunk(&first, &fake, scan + PL_regsize, /* Up to end */
962 &data, SCF_DO_SUBSTR);
963 if ( PL_regnpar == 1 && data.longest == &(data.longest_fixed)
964 && data.last_start_min == 0 && data.last_end > 0
966 && (!(PL_regseen & REG_SEEN_GPOS) || (r->reganch & ROPT_ANCH_GPOS)))
967 r->reganch |= ROPT_CHECK_ALL;
969 SvREFCNT_dec(data.last_found);
971 longest_float_length = CHR_SVLEN(data.longest_float);
972 if (longest_float_length
973 || (data.flags & SF_FL_BEFORE_EOL
974 && (!(data.flags & SF_FL_BEFORE_MEOL)
975 || (PL_regflags & PMf_MULTILINE)))) {
978 if (SvCUR(data.longest_fixed) /* ok to leave SvCUR */
979 && data.offset_fixed == data.offset_float_min
980 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
981 goto remove_float; /* As in (a)+. */
983 r->float_substr = data.longest_float;
984 r->float_min_offset = data.offset_float_min;
985 r->float_max_offset = data.offset_float_max;
986 t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
987 && (!(data.flags & SF_FL_BEFORE_MEOL)
988 || (PL_regflags & PMf_MULTILINE)));
989 fbm_compile(r->float_substr, t ? FBMcf_TAIL : 0);
993 r->float_substr = Nullsv;
994 SvREFCNT_dec(data.longest_float);
995 longest_float_length = 0;
998 longest_fixed_length = CHR_SVLEN(data.longest_fixed);
999 if (longest_fixed_length
1000 || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
1001 && (!(data.flags & SF_FIX_BEFORE_MEOL)
1002 || (PL_regflags & PMf_MULTILINE)))) {
1005 r->anchored_substr = data.longest_fixed;
1006 r->anchored_offset = data.offset_fixed;
1007 t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
1008 && (!(data.flags & SF_FIX_BEFORE_MEOL)
1009 || (PL_regflags & PMf_MULTILINE)));
1010 fbm_compile(r->anchored_substr, t ? FBMcf_TAIL : 0);
1013 r->anchored_substr = Nullsv;
1014 SvREFCNT_dec(data.longest_fixed);
1015 longest_fixed_length = 0;
1018 /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
1019 if (longest_fixed_length > longest_float_length) {
1020 r->check_substr = r->anchored_substr;
1021 r->check_offset_min = r->check_offset_max = r->anchored_offset;
1022 if (r->reganch & ROPT_ANCH_SINGLE)
1023 r->reganch |= ROPT_NOSCAN;
1026 r->check_substr = r->float_substr;
1027 r->check_offset_min = data.offset_float_min;
1028 r->check_offset_max = data.offset_float_max;
1030 if (r->check_substr) {
1031 r->reganch |= RE_USE_INTUIT;
1032 if (SvTAIL(r->check_substr))
1033 r->reganch |= RE_INTUIT_TAIL;
1037 /* Several toplevels. Best we can is to set minlen. */
1040 DEBUG_r(PerlIO_printf(Perl_debug_log, "\n"));
1041 scan = r->program + 1;
1042 minlen = study_chunk(&scan, &fake, scan + PL_regsize, NULL, 0);
1043 r->check_substr = r->anchored_substr = r->float_substr = Nullsv;
1047 if (PL_regseen & REG_SEEN_GPOS)
1048 r->reganch |= ROPT_GPOS_SEEN;
1049 if (PL_regseen & REG_SEEN_LOOKBEHIND)
1050 r->reganch |= ROPT_LOOKBEHIND_SEEN;
1051 if (PL_regseen & REG_SEEN_EVAL)
1052 r->reganch |= ROPT_EVAL_SEEN;
1053 Newz(1002, r->startp, PL_regnpar, I32);
1054 Newz(1002, r->endp, PL_regnpar, I32);
1055 DEBUG_r(regdump(r));
1060 - reg - regular expression, i.e. main body or parenthesized thing
1062 * Caller must absorb opening parenthesis.
1064 * Combining parenthesis handling with the base level of regular expression
1065 * is a trifle forced, but the need to tie the tails of the branches to what
1066 * follows makes it hard to avoid.
1069 S_reg(pTHX_ I32 paren, I32 *flagp)
1070 /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
1073 register regnode *ret; /* Will be the head of the group. */
1074 register regnode *br;
1075 register regnode *lastbr;
1076 register regnode *ender = 0;
1077 register I32 parno = 0;
1078 I32 flags, oregflags = PL_regflags, have_branch = 0, open = 0;
1081 *flagp = 0; /* Tentatively. */
1083 /* Make an OPEN node, if parenthesized. */
1085 if (*PL_regcomp_parse == '?') {
1086 U16 posflags = 0, negflags = 0;
1087 U16 *flagsp = &posflags;
1091 paren = *PL_regcomp_parse++;
1092 ret = NULL; /* For look-ahead/behind. */
1095 PL_regseen |= REG_SEEN_LOOKBEHIND;
1096 if (*PL_regcomp_parse == '!')
1098 if (*PL_regcomp_parse != '=' && *PL_regcomp_parse != '!')
1109 FAIL2("Sequence (?%c...) not implemented", (int)paren);
1112 while (*PL_regcomp_parse && *PL_regcomp_parse != ')')
1114 if (*PL_regcomp_parse != ')')
1115 FAIL("Sequence (?#... not terminated");
1121 paren = *PL_regcomp_parse++;
1126 I32 count = 1, n = 0;
1128 char *s = PL_regcomp_parse;
1130 OP_4tree *sop, *rop;
1133 PL_regseen |= REG_SEEN_EVAL;
1134 while (count && (c = *PL_regcomp_parse)) {
1135 if (c == '\\' && PL_regcomp_parse[1])
1143 if (*PL_regcomp_parse != ')')
1144 FAIL("Sequence (?{...}) not terminated or not {}-balanced");
1148 if (PL_regcomp_parse - 1 - s)
1149 sv = newSVpvn(s, PL_regcomp_parse - 1 - s);
1151 sv = newSVpvn("", 0);
1153 rop = sv_compile_2op(sv, &sop, "re", &av);
1155 n = add_data(3, "nop");
1156 PL_regcomp_rx->data->data[n] = (void*)rop;
1157 PL_regcomp_rx->data->data[n+1] = (void*)sop;
1158 PL_regcomp_rx->data->data[n+2] = (void*)av;
1161 else { /* First pass */
1162 if (PL_reginterp_cnt < ++PL_seen_evals
1163 && PL_curcop != &PL_compiling)
1164 /* No compiled RE interpolated, has runtime
1165 components ===> unsafe. */
1166 FAIL("Eval-group not allowed at runtime, use re 'eval'");
1168 FAIL("Eval-group in insecure regular expression");
1173 ret = reg_node(LOGICAL);
1176 regtail(ret, reganode(EVAL, n));
1179 return reganode(EVAL, n);
1183 if (PL_regcomp_parse[0] == '?') {
1184 if (PL_regcomp_parse[1] == '=' || PL_regcomp_parse[1] == '!'
1185 || PL_regcomp_parse[1] == '<'
1186 || PL_regcomp_parse[1] == '{') { /* Lookahead or eval. */
1189 ret = reg_node(LOGICAL);
1192 regtail(ret, reg(1, &flag));
1196 else if (PL_regcomp_parse[0] >= '1' && PL_regcomp_parse[0] <= '9' ) {
1197 parno = atoi(PL_regcomp_parse++);
1199 while (isDIGIT(*PL_regcomp_parse))
1201 ret = reganode(GROUPP, parno);
1202 if ((c = *nextchar()) != ')')
1203 FAIL2("Switch (?(number%c not recognized", c);
1205 regtail(ret, reganode(IFTHEN, 0));
1206 br = regbranch(&flags, 1);
1208 br = reganode(LONGJMP, 0);
1210 regtail(br, reganode(LONGJMP, 0));
1215 lastbr = reganode(IFTHEN, 0); /* Fake one for optimizer. */
1216 regbranch(&flags, 1);
1217 regtail(ret, lastbr);
1225 FAIL("Switch (?(condition)... contains too many branches");
1226 ender = reg_node(TAIL);
1229 regtail(lastbr, ender);
1230 regtail(NEXTOPER(NEXTOPER(lastbr)), ender);
1233 regtail(ret, ender);
1237 FAIL2("Unknown condition for (?(%.2s", PL_regcomp_parse);
1241 FAIL("Sequence (? incomplete");
1246 while (*PL_regcomp_parse && strchr("iogcmsx", *PL_regcomp_parse)) {
1247 if (*PL_regcomp_parse != 'o')
1248 pmflag(flagsp, *PL_regcomp_parse);
1251 if (*PL_regcomp_parse == '-') {
1256 PL_regflags |= posflags;
1257 PL_regflags &= ~negflags;
1258 if (*PL_regcomp_parse == ':') {
1264 if (*PL_regcomp_parse != ')')
1265 FAIL2("Sequence (?%c...) not recognized", *PL_regcomp_parse);
1274 ret = reganode(OPEN, parno);
1281 /* Pick up the branches, linking them together. */
1282 br = regbranch(&flags, 1);
1285 if (*PL_regcomp_parse == '|') {
1286 if (!SIZE_ONLY && PL_extralen) {
1287 reginsert(BRANCHJ, br);
1290 reginsert(BRANCH, br);
1293 PL_extralen += 1; /* For BRANCHJ-BRANCH. */
1295 else if (paren == ':') {
1296 *flagp |= flags&SIMPLE;
1298 if (open) { /* Starts with OPEN. */
1299 regtail(ret, br); /* OPEN -> first. */
1301 else if (paren != '?') /* Not Conditional */
1305 *flagp |= flags&SPSTART;
1307 while (*PL_regcomp_parse == '|') {
1308 if (!SIZE_ONLY && PL_extralen) {
1309 ender = reganode(LONGJMP,0);
1310 regtail(NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
1313 PL_extralen += 2; /* Account for LONGJMP. */
1315 br = regbranch(&flags, 0);
1318 regtail(lastbr, br); /* BRANCH -> BRANCH. */
1322 *flagp |= flags&SPSTART;
1325 if (have_branch || paren != ':') {
1326 /* Make a closing node, and hook it on the end. */
1329 ender = reg_node(TAIL);
1332 ender = reganode(CLOSE, parno);
1338 *flagp &= ~HASWIDTH;
1341 ender = reg_node(SUCCEED);
1344 ender = reg_node(END);
1347 regtail(lastbr, ender);
1350 /* Hook the tails of the branches to the closing node. */
1351 for (br = ret; br != NULL; br = regnext(br)) {
1352 regoptail(br, ender);
1359 static char parens[] = "=!<,>";
1361 if (paren && (p = strchr(parens, paren))) {
1362 int node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
1363 int flag = (p - parens) > 1;
1366 node = SUSPEND, flag = 0;
1367 reginsert(node,ret);
1369 regtail(ret, reg_node(TAIL));
1373 /* Check for proper termination. */
1375 PL_regflags = oregflags;
1376 if (PL_regcomp_parse >= PL_regxend || *nextchar() != ')') {
1377 FAIL("unmatched () in regexp");
1380 else if (!paren && PL_regcomp_parse < PL_regxend) {
1381 if (*PL_regcomp_parse == ')') {
1382 FAIL("unmatched () in regexp");
1385 FAIL("junk on end of regexp"); /* "Can't happen". */
1393 - regbranch - one alternative of an | operator
1395 * Implements the concatenation operator.
1398 S_regbranch(pTHX_ I32 *flagp, I32 first)
1401 register regnode *ret;
1402 register regnode *chain = NULL;
1403 register regnode *latest;
1404 I32 flags = 0, c = 0;
1409 if (!SIZE_ONLY && PL_extralen)
1410 ret = reganode(BRANCHJ,0);
1412 ret = reg_node(BRANCH);
1415 if (!first && SIZE_ONLY)
1416 PL_extralen += 1; /* BRANCHJ */
1418 *flagp = WORST; /* Tentatively. */
1422 while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != '|' && *PL_regcomp_parse != ')') {
1424 latest = regpiece(&flags);
1425 if (latest == NULL) {
1426 if (flags & TRYAGAIN)
1430 else if (ret == NULL)
1432 *flagp |= flags&HASWIDTH;
1433 if (chain == NULL) /* First piece. */
1434 *flagp |= flags&SPSTART;
1437 regtail(chain, latest);
1442 if (chain == NULL) { /* Loop ran zero times. */
1443 chain = reg_node(NOTHING);
1448 *flagp |= flags&SIMPLE;
1455 - regpiece - something followed by possible [*+?]
1457 * Note that the branching code sequences used for ? and the general cases
1458 * of * and + are somewhat optimized: they use the same NOTHING node as
1459 * both the endmarker for their branch list and the body of the last branch.
1460 * It might seem that this node could be dispensed with entirely, but the
1461 * endmarker role is not redundant.
1464 S_regpiece(pTHX_ I32 *flagp)
1467 register regnode *ret;
1469 register char *next;
1471 char *origparse = PL_regcomp_parse;
1474 I32 max = REG_INFTY;
1476 ret = regatom(&flags);
1478 if (flags & TRYAGAIN)
1483 op = *PL_regcomp_parse;
1485 if (op == '{' && regcurly(PL_regcomp_parse)) {
1486 next = PL_regcomp_parse + 1;
1488 while (isDIGIT(*next) || *next == ',') {
1497 if (*next == '}') { /* got one */
1501 min = atoi(PL_regcomp_parse);
1505 maxpos = PL_regcomp_parse;
1507 if (!max && *maxpos != '0')
1508 max = REG_INFTY; /* meaning "infinity" */
1509 else if (max >= REG_INFTY)
1510 FAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
1511 PL_regcomp_parse = next;
1515 if ((flags&SIMPLE)) {
1516 PL_regnaughty += 2 + PL_regnaughty / 2;
1517 reginsert(CURLY, ret);
1520 PL_regnaughty += 4 + PL_regnaughty; /* compound interest */
1521 regtail(ret, reg_node(WHILEM));
1522 if (!SIZE_ONLY && PL_extralen) {
1523 reginsert(LONGJMP,ret);
1524 reginsert(NOTHING,ret);
1525 NEXT_OFF(ret) = 3; /* Go over LONGJMP. */
1527 reginsert(CURLYX,ret);
1528 if (!SIZE_ONLY && PL_extralen)
1529 NEXT_OFF(ret) = 3; /* Go over NOTHING to LONGJMP. */
1530 regtail(ret, reg_node(NOTHING));
1540 if (max && max < min)
1541 FAIL("Can't do {n,m} with n > m");
1556 #if 0 /* Now runtime fix should be reliable. */
1557 if (!(flags&HASWIDTH) && op != '?')
1558 FAIL("regexp *+ operand could be empty");
1563 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
1565 if (op == '*' && (flags&SIMPLE)) {
1566 reginsert(STAR, ret);
1570 else if (op == '*') {
1574 else if (op == '+' && (flags&SIMPLE)) {
1575 reginsert(PLUS, ret);
1579 else if (op == '+') {
1583 else if (op == '?') {
1588 if (ckWARN(WARN_UNSAFE) && !SIZE_ONLY && !(flags&HASWIDTH) && max > REG_INFTY/3) {
1589 Perl_warner(aTHX_ WARN_UNSAFE, "%.*s matches null string many times",
1590 PL_regcomp_parse - origparse, origparse);
1593 if (*PL_regcomp_parse == '?') {
1595 reginsert(MINMOD, ret);
1596 regtail(ret, ret + NODE_STEP_REGNODE);
1598 if (ISMULT2(PL_regcomp_parse))
1599 FAIL("nested *?+ in regexp");
1605 - regatom - the lowest level
1607 * Optimization: gobbles an entire sequence of ordinary characters so that
1608 * it can turn them into a single node, which is smaller to store and
1609 * faster to run. Backslashed characters are exceptions, each becoming a
1610 * separate node; the code is simpler that way and it's not worth fixing.
1612 * [Yes, it is worth fixing, some scripts can run twice the speed.]
1615 S_regatom(pTHX_ I32 *flagp)
1618 register regnode *ret = 0;
1621 *flagp = WORST; /* Tentatively. */
1624 switch (*PL_regcomp_parse) {
1628 if (PL_regflags & PMf_MULTILINE)
1629 ret = reg_node(MBOL);
1630 else if (PL_regflags & PMf_SINGLELINE)
1631 ret = reg_node(SBOL);
1633 ret = reg_node(BOL);
1636 if (PL_regcomp_parse[1])
1639 if (PL_regflags & PMf_MULTILINE)
1640 ret = reg_node(MEOL);
1641 else if (PL_regflags & PMf_SINGLELINE)
1642 ret = reg_node(SEOL);
1644 ret = reg_node(EOL);
1649 if (PL_regflags & PMf_SINGLELINE)
1650 ret = reg_node(SANYUTF8);
1652 ret = reg_node(ANYUTF8);
1656 if (PL_regflags & PMf_SINGLELINE)
1657 ret = reg_node(SANY);
1659 ret = reg_node(REG_ANY);
1660 *flagp |= HASWIDTH|SIMPLE;
1666 ret = (UTF ? regclassutf8() : regclass());
1667 if (*PL_regcomp_parse != ']')
1668 FAIL("unmatched [] in regexp");
1670 *flagp |= HASWIDTH|SIMPLE;
1674 ret = reg(1, &flags);
1676 if (flags & TRYAGAIN)
1680 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE);
1684 if (flags & TRYAGAIN) {
1688 FAIL2("internal urp in regexp at /%s/", PL_regcomp_parse);
1689 /* Supposed to be caught earlier. */
1692 if (!regcurly(PL_regcomp_parse)) {
1700 FAIL("?+*{} follows nothing in regexp");
1703 switch (*++PL_regcomp_parse) {
1706 ret = reg_node(SBOL);
1711 ret = reg_node(GPOS);
1712 PL_regseen |= REG_SEEN_GPOS;
1717 ret = reg_node(SEOL);
1722 ret = reg_node(EOS);
1724 PL_seen_zerolen++; /* Do not optimize RE away */
1728 ret = reg_node(SANY);
1729 *flagp |= HASWIDTH|SIMPLE;
1733 ret = reg_node(CLUMP);
1736 if (UTF && !PL_utf8_mark)
1737 is_utf8_mark((U8*)"~"); /* preload table */
1742 ? (LOC ? ALNUMLUTF8 : ALNUMUTF8)
1743 : (LOC ? ALNUML : ALNUM));
1744 *flagp |= HASWIDTH|SIMPLE;
1746 if (UTF && !PL_utf8_alnum)
1747 is_utf8_alnum((U8*)"a"); /* preload table */
1752 ? (LOC ? NALNUMLUTF8 : NALNUMUTF8)
1753 : (LOC ? NALNUML : NALNUM));
1754 *flagp |= HASWIDTH|SIMPLE;
1756 if (UTF && !PL_utf8_alnum)
1757 is_utf8_alnum((U8*)"a"); /* preload table */
1761 PL_regseen |= REG_SEEN_LOOKBEHIND;
1764 ? (LOC ? BOUNDLUTF8 : BOUNDUTF8)
1765 : (LOC ? BOUNDL : BOUND));
1768 if (UTF && !PL_utf8_alnum)
1769 is_utf8_alnum((U8*)"a"); /* preload table */
1773 PL_regseen |= REG_SEEN_LOOKBEHIND;
1776 ? (LOC ? NBOUNDLUTF8 : NBOUNDUTF8)
1777 : (LOC ? NBOUNDL : NBOUND));
1780 if (UTF && !PL_utf8_alnum)
1781 is_utf8_alnum((U8*)"a"); /* preload table */
1786 ? (LOC ? SPACELUTF8 : SPACEUTF8)
1787 : (LOC ? SPACEL : SPACE));
1788 *flagp |= HASWIDTH|SIMPLE;
1790 if (UTF && !PL_utf8_space)
1791 is_utf8_space((U8*)" "); /* preload table */
1796 ? (LOC ? NSPACELUTF8 : NSPACEUTF8)
1797 : (LOC ? NSPACEL : NSPACE));
1798 *flagp |= HASWIDTH|SIMPLE;
1800 if (UTF && !PL_utf8_space)
1801 is_utf8_space((U8*)" "); /* preload table */
1804 ret = reg_node(UTF ? DIGITUTF8 : DIGIT);
1805 *flagp |= HASWIDTH|SIMPLE;
1807 if (UTF && !PL_utf8_digit)
1808 is_utf8_digit((U8*)"1"); /* preload table */
1811 ret = reg_node(UTF ? NDIGITUTF8 : NDIGIT);
1812 *flagp |= HASWIDTH|SIMPLE;
1814 if (UTF && !PL_utf8_digit)
1815 is_utf8_digit((U8*)"1"); /* preload table */
1819 { /* a lovely hack--pretend we saw [\pX] instead */
1820 char* oldregxend = PL_regxend;
1822 if (PL_regcomp_parse[1] == '{') {
1823 PL_regxend = strchr(PL_regcomp_parse, '}');
1825 FAIL("Missing right brace on \\p{}");
1829 PL_regxend = PL_regcomp_parse + 2;
1832 ret = regclassutf8();
1834 PL_regxend = oldregxend;
1837 *flagp |= HASWIDTH|SIMPLE;
1850 case '1': case '2': case '3': case '4':
1851 case '5': case '6': case '7': case '8': case '9':
1853 I32 num = atoi(PL_regcomp_parse);
1855 if (num > 9 && num >= PL_regnpar)
1858 if (!SIZE_ONLY && num > PL_regcomp_rx->nparens)
1859 FAIL("reference to nonexistent group");
1862 ? (LOC ? REFFL : REFF)
1865 while (isDIGIT(*PL_regcomp_parse))
1873 if (PL_regcomp_parse >= PL_regxend)
1874 FAIL("trailing \\ in regexp");
1877 /* Do not generate `unrecognized' warnings here, we fall
1878 back into the quick-grab loop below */
1884 if (PL_regflags & PMf_EXTENDED) {
1885 while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != '\n') PL_regcomp_parse++;
1886 if (PL_regcomp_parse < PL_regxend)
1902 ? (LOC ? EXACTFL : EXACTF)
1904 s = (char *) OPERAND(ret);
1905 regc(0, s++); /* save spot for len */
1906 for (len = 0, p = PL_regcomp_parse - 1;
1907 len < 127 && p < PL_regxend;
1912 if (PL_regflags & PMf_EXTENDED)
1913 p = regwhite(p, PL_regxend);
1967 char* e = strchr(p, '}');
1970 FAIL("Missing right brace on \\x{}");
1972 ender = scan_hex(p + 1, e - p, &numlen);
1973 if (numlen + len >= 127) { /* numlen is generous */
1980 FAIL("Can't use \\x{} without 'use utf8' declaration");
1983 ender = scan_hex(p, 2, &numlen);
1989 ender = UCHARAT(p++);
1990 ender = toCTRL(ender);
1992 case '0': case '1': case '2': case '3':case '4':
1993 case '5': case '6': case '7': case '8':case '9':
1995 (isDIGIT(p[1]) && atoi(p) >= PL_regnpar) ) {
1996 ender = scan_oct(p, 3, &numlen);
2005 if (p >= PL_regxend)
2006 FAIL("trailing \\ in regexp");
2009 if (!SIZE_ONLY && ckWARN(WARN_UNSAFE) && isALPHA(*p))
2010 Perl_warner(aTHX_ WARN_UNSAFE,
2011 "/%.127s/: Unrecognized escape \\%c passed through",
2014 goto normal_default;
2019 if ((*p & 0xc0) == 0xc0 && UTF) {
2020 ender = utf8_to_uv((U8*)p, &numlen);
2027 if (PL_regflags & PMf_EXTENDED)
2028 p = regwhite(p, PL_regxend);
2031 ender = toLOWER_LC_uni(ender);
2033 ender = toLOWER_uni(ender);
2035 if (ISMULT2(p)) { /* Back off on ?+*. */
2038 else if (ender >= 0x80 && UTF) {
2039 reguni(ender, s, &numlen);
2049 if (ender >= 0x80 && UTF) {
2050 reguni(ender, s, &numlen);
2058 PL_regcomp_parse = p - 1;
2061 FAIL("internal disaster in regexp");
2067 *OPERAND(ret) = len;
2070 PL_regsize += (len + 2 + sizeof(regnode) - 1) / sizeof(regnode);
2073 PL_regcode += (len + 2 + sizeof(regnode) - 1) / sizeof(regnode);
2083 S_regwhite(pTHX_ char *p, char *e)
2088 else if (*p == '#') {
2091 } while (p < e && *p != '\n');
2099 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
2100 Character classes ([:foo:]) can also be negated ([:^foo:]).
2101 Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
2102 Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
2103 but trigger warnings because they are currently unimplemented. */
2105 S_regpposixcc(pTHX_ I32 value)
2109 I32 namedclass = -1;
2111 if (value == '[' && PL_regcomp_parse + 1 < PL_regxend &&
2112 /* I smell either [: or [= or [. -- POSIX has been here, right? */
2113 (*PL_regcomp_parse == ':' ||
2114 *PL_regcomp_parse == '=' ||
2115 *PL_regcomp_parse == '.')) {
2116 char c = *PL_regcomp_parse;
2117 char* s = PL_regcomp_parse++;
2119 while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != c)
2121 if (PL_regcomp_parse == PL_regxend)
2122 /* Grandfather lone [:, [=, [. */
2123 PL_regcomp_parse = s;
2125 char* t = PL_regcomp_parse++; /* skip over the c */
2127 if (*PL_regcomp_parse == ']') {
2128 PL_regcomp_parse++; /* skip over the ending ] */
2131 I32 complement = *posixcc == '^' ? *posixcc++ : 0;
2132 I32 skip = 5; /* the most common skip */
2136 if (strnEQ(posixcc, "alnum", 5))
2138 complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
2139 else if (strnEQ(posixcc, "alpha", 5))
2141 complement ? ANYOF_NALPHA : ANYOF_ALPHA;
2142 else if (strnEQ(posixcc, "ascii", 5))
2144 complement ? ANYOF_NASCII : ANYOF_ASCII;
2147 if (strnEQ(posixcc, "cntrl", 5))
2149 complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
2152 if (strnEQ(posixcc, "digit", 5))
2154 complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
2157 if (strnEQ(posixcc, "graph", 5))
2159 complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
2162 if (strnEQ(posixcc, "lower", 5))
2164 complement ? ANYOF_NLOWER : ANYOF_LOWER;
2167 if (strnEQ(posixcc, "print", 5))
2169 complement ? ANYOF_NPRINT : ANYOF_PRINT;
2170 else if (strnEQ(posixcc, "punct", 5))
2172 complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
2175 if (strnEQ(posixcc, "space", 5))
2177 complement ? ANYOF_NSPACE : ANYOF_SPACE;
2179 if (strnEQ(posixcc, "upper", 5))
2181 complement ? ANYOF_NUPPER : ANYOF_UPPER;
2183 case 'w': /* this is not POSIX, this is the Perl \w */
2184 if (strnEQ(posixcc, "word", 4)) {
2186 complement ? ANYOF_NALNUM : ANYOF_ALNUM;
2191 if (strnEQ(posixcc, "xdigit", 6)) {
2193 complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
2198 if ((namedclass == -1 ||
2199 !(posixcc + skip + 2 < PL_regxend &&
2200 (posixcc[skip] == ':' &&
2201 posixcc[skip + 1] == ']'))))
2202 Perl_croak(aTHX_ "Character class [:%.*s:] unknown",
2204 } else if (ckWARN(WARN_UNSAFE) && !SIZE_ONLY)
2205 /* [[=foo=]] and [[.foo.]] are still future. */
2206 Perl_warner(aTHX_ WARN_UNSAFE,
2207 "Character class syntax [%c %c] is reserved for future extensions", c, c);
2209 /* Maternal grandfather:
2210 * "[:" ending in ":" but not in ":]" */
2211 PL_regcomp_parse = s;
2220 S_checkposixcc(pTHX)
2222 if (ckWARN(WARN_UNSAFE) && !SIZE_ONLY &&
2223 (*PL_regcomp_parse == ':' ||
2224 *PL_regcomp_parse == '=' ||
2225 *PL_regcomp_parse == '.')) {
2226 char *s = PL_regcomp_parse;
2229 while(*s && isALNUM(*s))
2231 if (*s && c == *s && s[1] == ']') {
2232 Perl_warner(aTHX_ WARN_UNSAFE,
2233 "Character class syntax [%c %c] belongs inside character classes", c, c);
2234 if (c == '=' || c == '.')
2235 Perl_warner(aTHX_ WARN_UNSAFE,
2236 "Character class syntax [%c %c] is reserved for future extensions", c, c);
2245 register char *opnd, *s;
2247 register I32 lastvalue = OOB_CHAR8;
2248 register I32 range = 0;
2249 register regnode *ret;
2254 s = opnd = (char *) OPERAND(PL_regcode);
2255 ret = reg_node(ANYOF);
2256 for (value = 0; value < ANYOF_SIZE; value++)
2258 if (*PL_regcomp_parse == '^') { /* Complement of range. */
2262 ANYOF_FLAGS(opnd) |= ANYOF_INVERT;
2265 PL_regcode += ANY_SKIP;
2267 ANYOF_FLAGS(opnd) |= ANYOF_FOLD;
2269 ANYOF_FLAGS(opnd) |= ANYOF_LOCALE;
2272 PL_regsize += ANY_SKIP;
2277 if (*PL_regcomp_parse == ']' || *PL_regcomp_parse == '-')
2278 goto skipcond; /* allow 1st char to be ] or - */
2279 while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != ']') {
2282 value = UCHARAT(PL_regcomp_parse++);
2284 namedclass = regpposixcc(value);
2285 else if (value == '\\') {
2286 value = UCHARAT(PL_regcomp_parse++);
2288 case 'w': namedclass = ANYOF_ALNUM; break;
2289 case 'W': namedclass = ANYOF_NALNUM; break;
2290 case 's': namedclass = ANYOF_SPACE; break;
2291 case 'S': namedclass = ANYOF_NSPACE; break;
2292 case 'd': namedclass = ANYOF_DIGIT; break;
2293 case 'D': namedclass = ANYOF_NDIGIT; break;
2294 case 'n': value = '\n'; break;
2295 case 'r': value = '\r'; break;
2296 case 't': value = '\t'; break;
2297 case 'f': value = '\f'; break;
2298 case 'b': value = '\b'; break;
2299 case 'e': value = '\033'; break;
2300 case 'a': value = '\007'; break;
2302 value = scan_hex(PL_regcomp_parse, 2, &numlen);
2303 PL_regcomp_parse += numlen;
2306 value = UCHARAT(PL_regcomp_parse++);
2307 value = toCTRL(value);
2309 case '0': case '1': case '2': case '3': case '4':
2310 case '5': case '6': case '7': case '8': case '9':
2311 value = scan_oct(--PL_regcomp_parse, 3, &numlen);
2312 PL_regcomp_parse += numlen;
2316 if (!SIZE_ONLY && namedclass > -1) {
2317 switch (namedclass) {
2320 ANYOF_CLASS_SET(opnd, ANYOF_ALNUM);
2322 for (value = 0; value < 256; value++)
2324 ANYOF_BITMAP_SET(opnd, value);
2329 ANYOF_CLASS_SET(opnd, ANYOF_NALNUM);
2331 for (value = 0; value < 256; value++)
2332 if (!isALNUM(value))
2333 ANYOF_BITMAP_SET(opnd, value);
2338 ANYOF_CLASS_SET(opnd, ANYOF_SPACE);
2340 for (value = 0; value < 256; value++)
2342 ANYOF_BITMAP_SET(opnd, value);
2347 ANYOF_CLASS_SET(opnd, ANYOF_NSPACE);
2349 for (value = 0; value < 256; value++)
2350 if (!isSPACE(value))
2351 ANYOF_BITMAP_SET(opnd, value);
2356 ANYOF_CLASS_SET(opnd, ANYOF_DIGIT);
2358 for (value = '0'; value <= '9'; value++)
2359 ANYOF_BITMAP_SET(opnd, value);
2364 ANYOF_CLASS_SET(opnd, ANYOF_NDIGIT);
2366 for (value = 0; value < '0'; value++)
2367 ANYOF_BITMAP_SET(opnd, value);
2368 for (value = '9' + 1; value < 256; value++)
2369 ANYOF_BITMAP_SET(opnd, value);
2374 ANYOF_CLASS_SET(opnd, ANYOF_NALNUMC);
2376 for (value = 0; value < 256; value++)
2377 if (!isALNUMC(value))
2378 ANYOF_BITMAP_SET(opnd, value);
2383 ANYOF_CLASS_SET(opnd, ANYOF_ALNUMC);
2385 for (value = 0; value < 256; value++)
2386 if (isALNUMC(value))
2387 ANYOF_BITMAP_SET(opnd, value);
2392 ANYOF_CLASS_SET(opnd, ANYOF_ALPHA);
2394 for (value = 0; value < 256; value++)
2396 ANYOF_BITMAP_SET(opnd, value);
2401 ANYOF_CLASS_SET(opnd, ANYOF_NALPHA);
2403 for (value = 0; value < 256; value++)
2404 if (!isALPHA(value))
2405 ANYOF_BITMAP_SET(opnd, value);
2410 ANYOF_CLASS_SET(opnd, ANYOF_ASCII);
2412 for (value = 0; value < 128; value++)
2413 ANYOF_BITMAP_SET(opnd, value);
2418 ANYOF_CLASS_SET(opnd, ANYOF_NASCII);
2420 for (value = 128; value < 256; value++)
2421 ANYOF_BITMAP_SET(opnd, value);
2426 ANYOF_CLASS_SET(opnd, ANYOF_CNTRL);
2428 for (value = 0; value < 256; value++)
2430 ANYOF_BITMAP_SET(opnd, value);
2432 lastvalue = OOB_CHAR8;
2436 ANYOF_CLASS_SET(opnd, ANYOF_NCNTRL);
2438 for (value = 0; value < 256; value++)
2439 if (!isCNTRL(value))
2440 ANYOF_BITMAP_SET(opnd, value);
2445 ANYOF_CLASS_SET(opnd, ANYOF_GRAPH);
2447 for (value = 0; value < 256; value++)
2449 ANYOF_BITMAP_SET(opnd, value);
2454 ANYOF_CLASS_SET(opnd, ANYOF_NGRAPH);
2456 for (value = 0; value < 256; value++)
2457 if (!isGRAPH(value))
2458 ANYOF_BITMAP_SET(opnd, value);
2463 ANYOF_CLASS_SET(opnd, ANYOF_LOWER);
2465 for (value = 0; value < 256; value++)
2467 ANYOF_BITMAP_SET(opnd, value);
2472 ANYOF_CLASS_SET(opnd, ANYOF_NLOWER);
2474 for (value = 0; value < 256; value++)
2475 if (!isLOWER(value))
2476 ANYOF_BITMAP_SET(opnd, value);
2481 ANYOF_CLASS_SET(opnd, ANYOF_PRINT);
2483 for (value = 0; value < 256; value++)
2485 ANYOF_BITMAP_SET(opnd, value);
2490 ANYOF_CLASS_SET(opnd, ANYOF_NPRINT);
2492 for (value = 0; value < 256; value++)
2493 if (!isPRINT(value))
2494 ANYOF_BITMAP_SET(opnd, value);
2499 ANYOF_CLASS_SET(opnd, ANYOF_PUNCT);
2501 for (value = 0; value < 256; value++)
2503 ANYOF_BITMAP_SET(opnd, value);
2508 ANYOF_CLASS_SET(opnd, ANYOF_NPUNCT);
2510 for (value = 0; value < 256; value++)
2511 if (!isPUNCT(value))
2512 ANYOF_BITMAP_SET(opnd, value);
2517 ANYOF_CLASS_SET(opnd, ANYOF_UPPER);
2519 for (value = 0; value < 256; value++)
2521 ANYOF_BITMAP_SET(opnd, value);
2526 ANYOF_CLASS_SET(opnd, ANYOF_NUPPER);
2528 for (value = 0; value < 256; value++)
2529 if (!isUPPER(value))
2530 ANYOF_BITMAP_SET(opnd, value);
2535 ANYOF_CLASS_SET(opnd, ANYOF_XDIGIT);
2537 for (value = 0; value < 256; value++)
2538 if (isXDIGIT(value))
2539 ANYOF_BITMAP_SET(opnd, value);
2544 ANYOF_CLASS_SET(opnd, ANYOF_NXDIGIT);
2546 for (value = 0; value < 256; value++)
2547 if (!isXDIGIT(value))
2548 ANYOF_BITMAP_SET(opnd, value);
2552 FAIL("invalid [::] class in regexp");
2556 ANYOF_FLAGS(opnd) |= ANYOF_CLASS;
2557 lastvalue = OOB_CHAR8;
2561 if (lastvalue > value)
2562 FAIL("invalid [] range in regexp");
2567 if (*PL_regcomp_parse == '-' && PL_regcomp_parse+1 < PL_regxend &&
2568 PL_regcomp_parse[1] != ']') {
2571 continue; /* do it next time */
2576 if ((isLOWER(lastvalue) && isLOWER(value)) ||
2577 (isUPPER(lastvalue) && isUPPER(value)))
2580 if (isLOWER(lastvalue)) {
2581 for (i = lastvalue; i <= value; i++)
2583 ANYOF_BITMAP_SET(opnd, i);
2585 for (i = lastvalue; i <= value; i++)
2587 ANYOF_BITMAP_SET(opnd, i);
2592 for ( ; lastvalue <= value; lastvalue++)
2593 ANYOF_BITMAP_SET(opnd, lastvalue);
2597 /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
2599 (ANYOF_FLAGS(opnd) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD) {
2600 for (value = 0; value < 256; ++value) {
2601 if (ANYOF_BITMAP_TEST(opnd, value)) {
2602 I32 cf = PL_fold[value];
2603 ANYOF_BITMAP_SET(opnd, cf);
2606 ANYOF_FLAGS(opnd) &= ~ANYOF_FOLD;
2608 /* optimize inverted simple patterns (e.g. [^a-z]) */
2609 if (!SIZE_ONLY && (ANYOF_FLAGS(opnd) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
2610 for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
2611 opnd[ANYOF_BITMAP_OFFSET + value] ^= ANYOF_FLAGS_ALL;
2612 ANYOF_FLAGS(opnd) = 0;
2618 S_regclassutf8(pTHX)
2621 register char *opnd, *e;
2623 register U32 lastvalue = OOB_UTF8;
2624 register I32 range = 0;
2625 register regnode *ret;
2632 if (*PL_regcomp_parse == '^') { /* Complement of range. */
2636 flags |= ANYOF_INVERT;
2640 flags |= ANYOF_FOLD;
2642 flags |= ANYOF_LOCALE;
2643 listsv = newSVpvn("# comment\n",10);
2648 if (*PL_regcomp_parse == ']' || *PL_regcomp_parse == '-')
2649 goto skipcond; /* allow 1st char to be ] or - */
2651 while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != ']') {
2654 value = utf8_to_uv((U8*)PL_regcomp_parse, &numlen);
2655 PL_regcomp_parse += numlen;
2658 namedclass = regpposixcc(value);
2659 else if (value == '\\') {
2660 value = utf8_to_uv((U8*)PL_regcomp_parse, &numlen);
2661 PL_regcomp_parse += numlen;
2663 case 'w': namedclass = ANYOF_ALNUM; break;
2664 case 'W': namedclass = ANYOF_NALNUM; break;
2665 case 's': namedclass = ANYOF_SPACE; break;
2666 case 'S': namedclass = ANYOF_NSPACE; break;
2667 case 'd': namedclass = ANYOF_DIGIT; break;
2668 case 'D': namedclass = ANYOF_NDIGIT; break;
2671 if (*PL_regcomp_parse == '{') {
2672 e = strchr(PL_regcomp_parse++, '}');
2674 FAIL("Missing right brace on \\p{}");
2675 n = e - PL_regcomp_parse;
2678 e = PL_regcomp_parse;
2683 Perl_sv_catpvf(aTHX_ listsv,
2684 "+utf8::%.*s\n", n, PL_regcomp_parse);
2686 Perl_sv_catpvf(aTHX_ listsv,
2687 "!utf8::%.*s\n", n, PL_regcomp_parse);
2689 PL_regcomp_parse = e + 1;
2690 lastvalue = OOB_UTF8;
2692 case 'n': value = '\n'; break;
2693 case 'r': value = '\r'; break;
2694 case 't': value = '\t'; break;
2695 case 'f': value = '\f'; break;
2696 case 'b': value = '\b'; break;
2697 case 'e': value = '\033'; break;
2698 case 'a': value = '\007'; break;
2700 if (*PL_regcomp_parse == '{') {
2701 e = strchr(PL_regcomp_parse++, '}');
2703 FAIL("Missing right brace on \\x{}");
2704 value = scan_hex(PL_regcomp_parse,
2705 e - PL_regcomp_parse,
2707 PL_regcomp_parse = e + 1;
2710 value = scan_hex(PL_regcomp_parse, 2, &numlen);
2711 PL_regcomp_parse += numlen;
2715 value = UCHARAT(PL_regcomp_parse++);
2716 value = toCTRL(value);
2718 case '0': case '1': case '2': case '3': case '4':
2719 case '5': case '6': case '7': case '8': case '9':
2720 value = scan_oct(--PL_regcomp_parse, 3, &numlen);
2721 PL_regcomp_parse += numlen;
2725 if (!SIZE_ONLY && namedclass > -1) {
2726 switch (namedclass) {
2728 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsWord\n"); break;
2730 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsWord\n"); break;
2732 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsAlnum\n"); break;
2734 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlnum\n"); break;
2736 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsAlpha\n"); break;
2738 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlpha\n"); break;
2740 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsASCII\n"); break;
2742 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsASCII\n"); break;
2744 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsCntrl\n"); break;
2746 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsCntrl\n"); break;
2748 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsGraph\n"); break;
2750 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsGraph\n"); break;
2752 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsDigit\n"); break;
2754 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsDigit\n"); break;
2756 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsLower\n"); break;
2758 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsLower\n"); break;
2760 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPrint\n"); break;
2762 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsPrint\n"); break;
2764 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPunct\n"); break;
2766 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsPunct\n"); break;
2768 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsSpace\n"); break;
2770 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsSpace\n"); break;
2772 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsUpper\n"); break;
2774 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsUpper\n"); break;
2776 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsXDigit\n"); break;
2778 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsXDigit\n"); break;
2783 if (lastvalue > value)
2784 FAIL("invalid [] range in regexp");
2786 Perl_sv_catpvf(aTHX_ listsv, "%04x\t%04x\n", lastvalue, value);
2792 if (*PL_regcomp_parse == '-' && PL_regcomp_parse+1 < PL_regxend &&
2793 PL_regcomp_parse[1] != ']') {
2796 continue; /* do it next time */
2799 Perl_sv_catpvf(aTHX_ listsv, "%04x\n", value);
2803 ret = reganode(ANYOFUTF8, 0);
2806 SV *rv = swash_init("utf8", "", listsv, 1, 0);
2807 SvREFCNT_dec(listsv);
2808 n = add_data(1,"s");
2809 PL_regcomp_rx->data->data[n] = (void*)rv;
2810 ARG1_SET(ret, flags);
2821 char* retval = PL_regcomp_parse++;
2824 if (*PL_regcomp_parse == '(' && PL_regcomp_parse[1] == '?' &&
2825 PL_regcomp_parse[2] == '#') {
2826 while (*PL_regcomp_parse && *PL_regcomp_parse != ')')
2831 if (PL_regflags & PMf_EXTENDED) {
2832 if (isSPACE(*PL_regcomp_parse)) {
2836 else if (*PL_regcomp_parse == '#') {
2837 while (*PL_regcomp_parse && *PL_regcomp_parse != '\n')
2848 - reg_node - emit a node
2850 STATIC regnode * /* Location. */
2851 S_reg_node(pTHX_ U8 op)
2854 register regnode *ret;
2855 register regnode *ptr;
2859 SIZE_ALIGN(PL_regsize);
2864 NODE_ALIGN_FILL(ret);
2866 FILL_ADVANCE_NODE(ptr, op);
2873 - reganode - emit a node with an argument
2875 STATIC regnode * /* Location. */
2876 S_reganode(pTHX_ U8 op, U32 arg)
2879 register regnode *ret;
2880 register regnode *ptr;
2884 SIZE_ALIGN(PL_regsize);
2889 NODE_ALIGN_FILL(ret);
2891 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
2898 - regc - emit (if appropriate) a Unicode character
2901 S_reguni(pTHX_ UV uv, char* s, I32* lenp)
2906 *lenp = uv_to_utf8(tmpbuf, uv) - tmpbuf;
2909 *lenp = uv_to_utf8((U8*)s, uv) - (U8*)s;
2914 - regc - emit (if appropriate) a byte of code
2917 S_regc(pTHX_ U8 b, char* s)
2925 - reginsert - insert an operator in front of already-emitted operand
2927 * Means relocating the operand.
2930 S_reginsert(pTHX_ U8 op, regnode *opnd)
2933 register regnode *src;
2934 register regnode *dst;
2935 register regnode *place;
2936 register int offset = regarglen[(U8)op];
2938 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
2941 PL_regsize += NODE_STEP_REGNODE + offset;
2946 PL_regcode += NODE_STEP_REGNODE + offset;
2949 StructCopy(--src, --dst, regnode);
2951 place = opnd; /* Op node, where operand used to be. */
2952 src = NEXTOPER(place);
2953 FILL_ADVANCE_NODE(place, op);
2954 Zero(src, offset, regnode);
2958 - regtail - set the next-pointer at the end of a node chain of p to val.
2961 S_regtail(pTHX_ regnode *p, regnode *val)
2964 register regnode *scan;
2965 register regnode *temp;
2966 register I32 offset;
2971 /* Find last node. */
2974 temp = regnext(scan);
2980 if (reg_off_by_arg[OP(scan)]) {
2981 ARG_SET(scan, val - scan);
2984 NEXT_OFF(scan) = val - scan;
2989 - regoptail - regtail on operand of first argument; nop if operandless
2992 S_regoptail(pTHX_ regnode *p, regnode *val)
2995 /* "Operandless" and "op != BRANCH" are synonymous in practice. */
2996 if (p == NULL || SIZE_ONLY)
2998 if (PL_regkind[(U8)OP(p)] == BRANCH) {
2999 regtail(NEXTOPER(p), val);
3001 else if ( PL_regkind[(U8)OP(p)] == BRANCHJ) {
3002 regtail(NEXTOPER(NEXTOPER(p)), val);
3009 - regcurly - a little FSA that accepts {\d+,?\d*}
3012 S_regcurly(pTHX_ register char *s)
3031 S_dumpuntil(pTHX_ regnode *start, regnode *node, regnode *last, SV* sv, I32 l)
3034 register char op = EXACT; /* Arbitrary non-END op. */
3035 register regnode *next, *onode;
3037 while (op != END && (!last || node < last)) {
3038 /* While that wasn't END last time... */
3044 next = regnext(node);
3046 if (OP(node) == OPTIMIZED)
3049 PerlIO_printf(Perl_debug_log, "%4d:%*s%s", node - start,
3050 2*l + 1, "", SvPVX(sv));
3051 if (next == NULL) /* Next ptr. */
3052 PerlIO_printf(Perl_debug_log, "(0)");
3054 PerlIO_printf(Perl_debug_log, "(%d)", next - start);
3055 (void)PerlIO_putc(Perl_debug_log, '\n');
3057 if (PL_regkind[(U8)op] == BRANCHJ) {
3058 register regnode *nnode = (OP(next) == LONGJMP
3061 if (last && nnode > last)
3063 node = dumpuntil(start, NEXTOPER(NEXTOPER(node)), nnode, sv, l + 1);
3065 else if (PL_regkind[(U8)op] == BRANCH) {
3066 node = dumpuntil(start, NEXTOPER(node), next, sv, l + 1);
3068 else if ( op == CURLY) { /* `next' might be very big: optimizer */
3069 node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
3070 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1, sv, l + 1);
3072 else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
3073 node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
3076 else if ( op == PLUS || op == STAR) {
3077 node = dumpuntil(start, NEXTOPER(node), NEXTOPER(node) + 1, sv, l + 1);
3079 else if (op == ANYOF) {
3080 node = NEXTOPER(node);
3083 else if (PL_regkind[(U8)op] == EXACT) {
3084 /* Literal string, where present. */
3085 node += ((*OPERAND(node)) + 2 + sizeof(regnode) - 1) / sizeof(regnode);
3086 node = NEXTOPER(node);
3089 node = NEXTOPER(node);
3090 node += regarglen[(U8)op];
3092 if (op == CURLYX || op == OPEN)
3094 else if (op == WHILEM)
3097 #endif /* DEBUGGING */
3102 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
3105 Perl_regdump(pTHX_ regexp *r)
3109 SV *sv = sv_newmortal();
3111 (void)dumpuntil(r->program, r->program + 1, NULL, sv, 0);
3113 /* Header fields of interest. */
3114 if (r->anchored_substr)
3115 PerlIO_printf(Perl_debug_log, "anchored `%s%s%s'%s at %d ",
3117 SvPVX(r->anchored_substr),
3119 SvTAIL(r->anchored_substr) ? "$" : "",
3120 r->anchored_offset);
3121 if (r->float_substr)
3122 PerlIO_printf(Perl_debug_log, "floating `%s%s%s'%s at %d..%u ",
3124 SvPVX(r->float_substr),
3126 SvTAIL(r->float_substr) ? "$" : "",
3127 r->float_min_offset, r->float_max_offset);
3128 if (r->check_substr)
3129 PerlIO_printf(Perl_debug_log,
3130 r->check_substr == r->float_substr
3131 ? "(checking floating" : "(checking anchored");
3132 if (r->reganch & ROPT_NOSCAN)
3133 PerlIO_printf(Perl_debug_log, " noscan");
3134 if (r->reganch & ROPT_CHECK_ALL)
3135 PerlIO_printf(Perl_debug_log, " isall");
3136 if (r->check_substr)
3137 PerlIO_printf(Perl_debug_log, ") ");
3139 if (r->regstclass) {
3140 regprop(sv, r->regstclass);
3141 PerlIO_printf(Perl_debug_log, "stclass `%s' ", SvPVX(sv));
3143 if (r->reganch & ROPT_ANCH) {
3144 PerlIO_printf(Perl_debug_log, "anchored");
3145 if (r->reganch & ROPT_ANCH_BOL)
3146 PerlIO_printf(Perl_debug_log, "(BOL)");
3147 if (r->reganch & ROPT_ANCH_MBOL)
3148 PerlIO_printf(Perl_debug_log, "(MBOL)");
3149 if (r->reganch & ROPT_ANCH_SBOL)
3150 PerlIO_printf(Perl_debug_log, "(SBOL)");
3151 if (r->reganch & ROPT_ANCH_GPOS)
3152 PerlIO_printf(Perl_debug_log, "(GPOS)");
3153 PerlIO_putc(Perl_debug_log, ' ');
3155 if (r->reganch & ROPT_GPOS_SEEN)
3156 PerlIO_printf(Perl_debug_log, "GPOS ");
3157 if (r->reganch & ROPT_SKIP)
3158 PerlIO_printf(Perl_debug_log, "plus ");
3159 if (r->reganch & ROPT_IMPLICIT)
3160 PerlIO_printf(Perl_debug_log, "implicit ");
3161 PerlIO_printf(Perl_debug_log, "minlen %ld ", (long) r->minlen);
3162 if (r->reganch & ROPT_EVAL_SEEN)
3163 PerlIO_printf(Perl_debug_log, "with eval ");
3164 PerlIO_printf(Perl_debug_log, "\n");
3165 #endif /* DEBUGGING */
3169 - regprop - printable representation of opcode
3172 Perl_regprop(pTHX_ SV *sv, regnode *o)
3178 sv_setpvn(sv, "", 0);
3179 if (OP(o) >= reg_num) /* regnode.type is unsigned */
3180 FAIL("corrupted regexp opcode");
3181 sv_catpv(sv, (char*)reg_name[OP(o)]); /* Take off const! */
3183 k = PL_regkind[(U8)OP(o)];
3186 Perl_sv_catpvf(aTHX_ sv, " <%s%s%s>", PL_colors[0], OPERAND(o) + 1, PL_colors[1]);
3187 else if (k == CURLY) {
3188 if (OP(o) == CURLYM || OP(o) == CURLYN)
3189 Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
3190 Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
3192 else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP )
3193 Perl_sv_catpvf(aTHX_ sv, "%d", ARG(o)); /* Parenth number */
3194 else if (k == LOGICAL)
3195 Perl_sv_catpvf(aTHX_ sv, "[%d]", ARG(o)); /* 2: embedded, otherwise 1 */
3196 else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
3197 Perl_sv_catpvf(aTHX_ sv, "[-%d]", o->flags);
3198 #endif /* DEBUGGING */
3202 Perl_re_intuit_string(pTHX_ regexp *prog)
3203 { /* Assume that RE_INTUIT is set */
3206 char *s = SvPV(prog->check_substr,n_a);
3208 if (!PL_colorset) reginitcolors();
3209 PerlIO_printf(Perl_debug_log,
3210 "%sUsing REx substr:%s `%s%.60s%s%s'\n",
3211 PL_colors[4],PL_colors[5],PL_colors[0],
3214 (strlen(s) > 60 ? "..." : ""));
3217 return prog->check_substr;
3221 Perl_pregfree(pTHX_ struct regexp *r)
3224 DEBUG_r(PerlIO_printf(Perl_debug_log,
3225 "%sFreeing REx:%s `%s%.60s%s%s'\n",
3226 PL_colors[4],PL_colors[5],PL_colors[0],
3229 (strlen(r->precomp) > 60 ? "..." : "")));
3232 if (!r || (--r->refcnt > 0))
3235 Safefree(r->precomp);
3236 if (RX_MATCH_COPIED(r))
3237 Safefree(r->subbeg);
3239 if (r->anchored_substr)
3240 SvREFCNT_dec(r->anchored_substr);
3241 if (r->float_substr)
3242 SvREFCNT_dec(r->float_substr);
3243 Safefree(r->substrs);
3246 int n = r->data->count;
3247 AV* new_comppad = NULL;
3252 switch (r->data->what[n]) {
3254 SvREFCNT_dec((SV*)r->data->data[n]);
3257 new_comppad = (AV*)r->data->data[n];
3260 if (new_comppad == NULL)
3261 Perl_croak(aTHX_ "panic: pregfree comppad");
3262 old_comppad = PL_comppad;
3263 old_curpad = PL_curpad;
3264 PL_comppad = new_comppad;
3265 PL_curpad = AvARRAY(new_comppad);
3266 op_free((OP_4tree*)r->data->data[n]);
3267 PL_comppad = old_comppad;
3268 PL_curpad = old_curpad;
3269 SvREFCNT_dec((SV*)new_comppad);
3275 FAIL2("panic: regfree data code '%c'", r->data->what[n]);
3278 Safefree(r->data->what);
3281 Safefree(r->startp);
3287 - regnext - dig the "next" pointer out of a node
3289 * [Note, when REGALIGN is defined there are two places in regmatch()
3290 * that bypass this code for speed.]
3293 Perl_regnext(pTHX_ register regnode *p)
3296 register I32 offset;
3298 if (p == &PL_regdummy)
3301 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
3309 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
3312 STRLEN l1 = strlen(pat1);
3313 STRLEN l2 = strlen(pat2);
3322 Copy(pat1, buf, l1 , char);
3323 Copy(pat2, buf + l1, l2 , char);
3324 buf[l1 + l2] = '\n';
3325 buf[l1 + l2 + 1] = '\0';
3327 /* ANSI variant takes additional second argument */
3328 va_start(args, pat2);
3332 msv = mess(buf, &args);
3334 message = SvPV(msv,l1);
3337 Copy(message, buf, l1 , char);
3338 buf[l1] = '\0'; /* Overwrite \n */
3339 Perl_croak(aTHX_ "%s", buf);
3342 /* XXX Here's a total kludge. But we need to re-enter for swash routines. */
3345 Perl_save_re_context(pTHX)
3349 SAVEPPTR(PL_regprecomp); /* uncompiled string. */
3350 SAVEI32(PL_regnpar); /* () count. */
3351 SAVEI32(PL_regsize); /* Code size. */
3352 SAVEI16(PL_regflags); /* are we folding, multilining? */
3353 SAVEPPTR(PL_reginput); /* String-input pointer. */
3354 SAVEPPTR(PL_regbol); /* Beginning of input, for ^ check. */
3355 SAVEPPTR(PL_regeol); /* End of input, for $ check. */
3356 SAVESPTR(PL_regstartp); /* Pointer to startp array. */
3357 SAVESPTR(PL_regendp); /* Ditto for endp. */
3358 SAVESPTR(PL_reglastparen); /* Similarly for lastparen. */
3359 SAVEPPTR(PL_regtill); /* How far we are required to go. */
3360 SAVEI32(PL_regprev); /* char before regbol, \n if none */
3361 SAVESPTR(PL_reg_start_tmp); /* from regexec.c */
3362 PL_reg_start_tmp = 0;
3363 SAVEFREEPV(PL_reg_start_tmp);
3364 SAVEI32(PL_reg_start_tmpl); /* from regexec.c */
3365 PL_reg_start_tmpl = 0;
3366 SAVESPTR(PL_regdata);
3367 SAVEI32(PL_reg_flags); /* from regexec.c */
3368 SAVEI32(PL_reg_eval_set); /* from regexec.c */
3369 SAVEI32(PL_regnarrate); /* from regexec.c */
3370 SAVESPTR(PL_regprogram); /* from regexec.c */
3371 SAVEINT(PL_regindent); /* from regexec.c */
3372 SAVESPTR(PL_regcc); /* from regexec.c */
3373 SAVESPTR(PL_curcop);
3374 SAVESPTR(PL_regcomp_rx); /* from regcomp.c */
3375 SAVEI32(PL_regseen); /* from regcomp.c */
3376 SAVEI32(PL_regsawback); /* Did we see \1, ...? */
3377 SAVEI32(PL_regnaughty); /* How bad is this pattern? */
3378 SAVESPTR(PL_regcode); /* Code-emit pointer; ®dummy = don't */
3379 SAVEPPTR(PL_regxend); /* End of input for compile */
3380 SAVEPPTR(PL_regcomp_parse); /* Input-scan pointer. */
3381 SAVESPTR(PL_reg_call_cc); /* from regexec.c */
3382 SAVESPTR(PL_reg_re); /* from regexec.c */
3383 SAVEPPTR(PL_reg_ganch); /* from regexec.c */
3384 SAVESPTR(PL_reg_sv); /* from regexec.c */
3385 SAVESPTR(PL_reg_magic); /* from regexec.c */
3386 SAVEI32(PL_reg_oldpos); /* from regexec.c */
3387 SAVESPTR(PL_reg_oldcurpm); /* from regexec.c */
3388 SAVESPTR(PL_reg_curpm); /* from regexec.c */
3390 SAVEPPTR(PL_reg_starttry); /* from regexec.c */