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 */
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 /* *These* symbols are masked to allow static link. */
39 # define Perl_pregfree my_regfree
40 # define Perl_regnext my_regnext
45 * pregcomp and pregexec -- regsub and regerror are not used in perl
47 * Copyright (c) 1986 by University of Toronto.
48 * Written by Henry Spencer. Not derived from licensed software.
50 * Permission is granted to anyone to use this software for any
51 * purpose on any computer system, and to redistribute it freely,
52 * subject to the following restrictions:
54 * 1. The author is not responsible for the consequences of use of
55 * this software, no matter how awful, even if they arise
58 * 2. The origin of this software must not be misrepresented, either
59 * by explicit claim or by omission.
61 * 3. Altered versions must be plainly marked as such, and must not
62 * be misrepresented as being the original software.
65 **** Alterations to Henry's code are...
67 **** Copyright (c) 1991-1999, Larry Wall
69 **** You may distribute under the terms of either the GNU General Public
70 **** License or the Artistic License, as specified in the README file.
73 * Beware that some of this code is subtly aware of the way operator
74 * precedence is structured in regular expressions. Serious changes in
75 * regular-expression syntax might require a total rethink.
80 #ifndef PERL_IN_XSUB_RE
92 # if defined(BUGGY_MSC6)
93 /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
94 # pragma optimize("a",off)
95 /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
96 # pragma optimize("w",on )
97 # endif /* BUGGY_MSC6 */
101 #define STATIC static
104 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
105 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
106 ((*s) == '{' && regcurly(s)))
108 #define PERL_META "^$.[()|?+*\\"
110 #define META "^$.[()|?+*\\"
114 #undef SPSTART /* dratted cpp namespace... */
117 * Flags to be passed up and down.
119 #define WORST 0 /* Worst case. */
120 #define HASWIDTH 0x1 /* Known to match non-null strings. */
121 #define SIMPLE 0x2 /* Simple enough to be STAR/PLUS operand. */
122 #define SPSTART 0x4 /* Starts with * or +. */
123 #define TRYAGAIN 0x8 /* Weeded out a declaration. */
126 * Forward declarations for pregcomp()'s friends.
130 static regnode *reg _((I32, I32 *));
131 static regnode *reganode _((U8, U32));
132 static regnode *regatom _((I32 *));
133 static regnode *regbranch _((I32 *, I32));
134 static void regc _((U8, char *));
135 static regnode *regclass _((void));
136 STATIC I32 regcurly _((char *));
137 static regnode *reg_node _((U8));
138 static regnode *regpiece _((I32 *));
139 static void reginsert _((U8, regnode *));
140 static void regoptail _((regnode *, regnode *));
141 static void regtail _((regnode *, regnode *));
142 static char* regwhite _((char *, char *));
143 static char* nextchar _((void));
144 static void re_croak2 _((const char* pat1,const char* pat2,...)) __attribute__((noreturn));
147 /* Length of a variant. */
156 I32 last_end; /* min value, <0 unless valid. */
159 SV **longest; /* Either &l_fixed, or &l_float. */
163 I32 offset_float_min;
164 I32 offset_float_max;
169 static scan_data_t zero_scan_data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
171 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
172 #define SF_BEFORE_SEOL 0x1
173 #define SF_BEFORE_MEOL 0x2
174 #define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
175 #define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
178 # define SF_FIX_SHIFT_EOL (0+2)
179 # define SF_FL_SHIFT_EOL (0+4)
181 # define SF_FIX_SHIFT_EOL (+2)
182 # define SF_FL_SHIFT_EOL (+4)
185 #define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
186 #define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
188 #define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
189 #define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
190 #define SF_IS_INF 0x40
191 #define SF_HAS_PAR 0x80
192 #define SF_IN_PAR 0x100
193 #define SF_HAS_EVAL 0x200
194 #define SCF_DO_SUBSTR 0x400
197 scan_commit(scan_data_t *data)
199 STRLEN l = SvCUR(data->last_found);
200 STRLEN old_l = SvCUR(*data->longest);
202 if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
203 sv_setsv(*data->longest, data->last_found);
204 if (*data->longest == data->longest_fixed) {
205 data->offset_fixed = l ? data->last_start_min : data->pos_min;
206 if (data->flags & SF_BEFORE_EOL)
208 |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
210 data->flags &= ~SF_FIX_BEFORE_EOL;
212 data->offset_float_min = l ? data->last_start_min : data->pos_min;
213 data->offset_float_max = (l
214 ? data->last_start_max
215 : data->pos_min + data->pos_delta);
216 if (data->flags & SF_BEFORE_EOL)
218 |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
220 data->flags &= ~SF_FL_BEFORE_EOL;
223 SvCUR_set(data->last_found, 0);
225 data->flags &= ~SF_BEFORE_EOL;
228 /* Stops at toplevel WHILEM as well as at `last'. At end *scanp is set
229 to the position after last scanned or to NULL. */
232 study_chunk(regnode **scanp, I32 *deltap, regnode *last, scan_data_t *data, U32 flags)
233 /* scanp: Start here (read-write). */
234 /* deltap: Write maxlen-minlen here. */
235 /* last: Stop before this one. */
238 I32 min = 0, pars = 0, code;
239 regnode *scan = *scanp, *next;
241 int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
242 int is_inf_internal = 0; /* The studied chunk is infinite */
243 I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
244 scan_data_t data_fake;
246 while (scan && OP(scan) != END && scan < last) {
247 /* Peephole optimizer: */
249 if (regkind[(U8)OP(scan)] == EXACT) {
250 regnode *n = regnext(scan);
253 regnode *stop = scan;
256 next = scan + (*OPERAND(scan) + 2 - 1)/sizeof(regnode) + 2;
257 /* Skip NOTHING, merge EXACT*. */
259 ( regkind[(U8)OP(n)] == NOTHING ||
260 (stringok && (OP(n) == OP(scan))))
262 && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
263 if (OP(n) == TAIL || n > next)
265 if (regkind[(U8)OP(n)] == NOTHING) {
266 NEXT_OFF(scan) += NEXT_OFF(n);
267 next = n + NODE_STEP_REGNODE;
274 int oldl = *OPERAND(scan);
275 regnode *nnext = regnext(n);
277 if (oldl + *OPERAND(n) > U8_MAX)
279 NEXT_OFF(scan) += NEXT_OFF(n);
280 *OPERAND(scan) += *OPERAND(n);
281 next = n + (*OPERAND(n) + 2 - 1)/sizeof(regnode) + 2;
282 /* Now we can overwrite *n : */
283 Move(OPERAND(n) + 1, OPERAND(scan) + oldl + 1,
284 *OPERAND(n) + 1, char);
294 n = scan + (*OPERAND(scan) + 2 - 1)/sizeof(regnode) + 2;
296 /* Purify reports a benign UMR here sometimes, because we
297 * don't initialize the OP() slot of a node when that node
298 * is occupied by just the trailing null of the string in
300 if (regkind[(U8)OP(n)] != NOTHING || OP(n) == NOTHING) {
309 if (OP(scan) != CURLYX) {
310 int max = (reg_off_by_arg[OP(scan)]
312 /* I32 may be smaller than U16 on CRAYs! */
313 : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
314 int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
318 /* Skip NOTHING and LONGJMP. */
319 while ((n = regnext(n))
320 && ((regkind[(U8)OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
321 || ((OP(n) == LONGJMP) && (noff = ARG(n))))
324 if (reg_off_by_arg[OP(scan)])
327 NEXT_OFF(scan) = off;
329 if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
330 || OP(scan) == IFTHEN || OP(scan) == SUSPEND) {
331 next = regnext(scan);
334 if (OP(next) == code || code == IFTHEN || code == SUSPEND) {
335 I32 max1 = 0, min1 = I32_MAX, num = 0;
337 if (flags & SCF_DO_SUBSTR)
339 while (OP(scan) == code) {
340 I32 deltanext, minnext;
344 next = regnext(scan);
345 scan = NEXTOPER(scan);
347 scan = NEXTOPER(scan);
348 /* We suppose the run is continuous, last=next...*/
349 minnext = study_chunk(&scan, &deltanext, next,
353 if (max1 < minnext + deltanext)
354 max1 = minnext + deltanext;
355 if (deltanext == I32_MAX)
356 is_inf = is_inf_internal = 1;
358 if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
360 if (data && (data_fake.flags & SF_HAS_EVAL))
361 data->flags |= SF_HAS_EVAL;
365 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
367 if (flags & SCF_DO_SUBSTR) {
368 data->pos_min += min1;
369 data->pos_delta += max1 - min1;
370 if (max1 != min1 || is_inf)
371 data->longest = &(data->longest_float);
374 delta += max1 - min1;
375 } else if (code == BRANCHJ) /* single branch is optimized. */
376 scan = NEXTOPER(NEXTOPER(scan));
377 else /* single branch is optimized. */
378 scan = NEXTOPER(scan);
380 } else if (OP(scan) == EXACT) {
381 min += *OPERAND(scan);
382 if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
383 I32 l = *OPERAND(scan);
385 /* The code below prefers earlier match for fixed
386 offset, later match for variable offset. */
387 if (data->last_end == -1) { /* Update the start info. */
388 data->last_start_min = data->pos_min;
389 data->last_start_max = is_inf
390 ? I32_MAX : data->pos_min + data->pos_delta;
392 sv_catpvn(data->last_found, (char *)(OPERAND(scan)+1), l);
393 data->last_end = data->pos_min + l;
394 data->pos_min += l; /* As in the first entry. */
395 data->flags &= ~SF_BEFORE_EOL;
397 } else if (regkind[(U8)OP(scan)] == EXACT) {
398 if (flags & SCF_DO_SUBSTR)
400 min += *OPERAND(scan);
401 if (data && (flags & SCF_DO_SUBSTR))
402 data->pos_min += *OPERAND(scan);
403 } else if (strchr(varies,OP(scan))) {
404 I32 mincount, maxcount, minnext, deltanext, pos_before, fl;
405 regnode *oscan = scan;
407 switch (regkind[(U8)OP(scan)]) {
409 scan = NEXTOPER(scan);
412 if (flags & SCF_DO_SUBSTR) {
413 next = NEXTOPER(scan);
414 if (OP(next) == EXACT) {
416 maxcount = REG_INFTY;
417 next = regnext(scan);
418 scan = NEXTOPER(scan);
422 if (flags & SCF_DO_SUBSTR)
427 is_inf = is_inf_internal = 1;
428 scan = regnext(scan);
429 if (flags & SCF_DO_SUBSTR) {
431 data->longest = &(data->longest_float);
433 goto optimize_curly_tail;
435 mincount = ARG1(scan);
436 maxcount = ARG2(scan);
437 next = regnext(scan);
438 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
440 if (flags & SCF_DO_SUBSTR) {
441 if (mincount == 0) scan_commit(data);
442 pos_before = data->pos_min;
446 data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
448 data->flags |= SF_IS_INF;
450 /* This will finish on WHILEM, setting scan, or on NULL: */
451 minnext = study_chunk(&scan, &deltanext, last, data,
453 ? (flags & ~SCF_DO_SUBSTR) : flags);
454 if (!scan) /* It was not CURLYX, but CURLY. */
456 if (PL_dowarn && (minnext + deltanext == 0)
457 && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
458 && maxcount <= 10000) /* Complement check for big count */
459 warn("Strange *+?{} on zero-length expression");
460 min += minnext * mincount;
461 is_inf_internal |= (maxcount == REG_INFTY
462 && (minnext + deltanext) > 0
463 || deltanext == I32_MAX);
464 is_inf |= is_inf_internal;
465 delta += (minnext + deltanext) * maxcount - minnext * mincount;
467 /* Try powerful optimization CURLYX => CURLYN. */
468 if ( OP(oscan) == CURLYX && data
469 && data->flags & SF_IN_PAR
470 && !(data->flags & SF_HAS_EVAL)
471 && !deltanext && minnext == 1 ) {
472 /* Try to optimize to CURLYN. */
473 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
474 regnode *nxt1 = nxt, *nxt2;
478 if (!strchr(simple,OP(nxt))
479 && !(regkind[(U8)OP(nxt)] == EXACT
480 && *OPERAND(nxt) == 1))
484 if (OP(nxt) != CLOSE)
486 /* Now we know that nxt2 is the only contents: */
487 oscan->flags = ARG(nxt);
489 OP(nxt1) = NOTHING; /* was OPEN. */
491 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
492 NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
493 NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
494 OP(nxt) = OPTIMIZED; /* was CLOSE. */
495 OP(nxt + 1) = OPTIMIZED; /* was count. */
496 NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
501 /* Try optimization CURLYX => CURLYM. */
502 if ( OP(oscan) == CURLYX && data
503 && !(data->flags & SF_HAS_PAR)
504 && !(data->flags & SF_HAS_EVAL)
506 /* XXXX How to optimize if data == 0? */
507 /* Optimize to a simpler form. */
508 regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
512 while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
513 && (OP(nxt2) != WHILEM))
515 OP(nxt2) = SUCCEED; /* Whas WHILEM */
516 /* Need to optimize away parenths. */
517 if (data->flags & SF_IN_PAR) {
518 /* Set the parenth number. */
519 regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
521 if (OP(nxt) != CLOSE)
522 FAIL("panic opt close");
523 oscan->flags = ARG(nxt);
524 OP(nxt1) = OPTIMIZED; /* was OPEN. */
525 OP(nxt) = OPTIMIZED; /* was CLOSE. */
527 OP(nxt1 + 1) = OPTIMIZED; /* was count. */
528 OP(nxt + 1) = OPTIMIZED; /* was count. */
529 NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
530 NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
533 while ( nxt1 && (OP(nxt1) != WHILEM)) {
534 regnode *nnxt = regnext(nxt1);
537 if (reg_off_by_arg[OP(nxt1)])
538 ARG_SET(nxt1, nxt2 - nxt1);
539 else if (nxt2 - nxt1 < U16_MAX)
540 NEXT_OFF(nxt1) = nxt2 - nxt1;
542 OP(nxt) = NOTHING; /* Cannot beautify */
547 /* Optimize again: */
548 study_chunk(&nxt1, &deltanext, nxt, NULL, 0);
552 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
554 if (flags & SCF_DO_SUBSTR) {
555 SV *last_str = Nullsv;
556 int counted = mincount != 0;
558 if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
559 I32 b = pos_before >= data->last_start_min
560 ? pos_before : data->last_start_min;
562 char *s = SvPV(data->last_found, l);
564 l -= b - data->last_start_min;
565 /* Get the added string: */
566 last_str = newSVpv(s + b - data->last_start_min, l);
567 if (deltanext == 0 && pos_before == b) {
568 /* What was added is a constant string */
570 SvGROW(last_str, (mincount * l) + 1);
571 repeatcpy(SvPVX(last_str) + l,
572 SvPVX(last_str), l, mincount - 1);
573 SvCUR(last_str) *= mincount;
574 /* Add additional parts. */
575 SvCUR_set(data->last_found,
576 SvCUR(data->last_found) - l);
577 sv_catsv(data->last_found, last_str);
578 data->last_end += l * (mincount - 1);
582 /* It is counted once already... */
583 data->pos_min += minnext * (mincount - counted);
584 data->pos_delta += - counted * deltanext +
585 (minnext + deltanext) * maxcount - minnext * mincount;
586 if (mincount != maxcount) {
588 if (mincount && last_str) {
589 sv_setsv(data->last_found, last_str);
590 data->last_end = data->pos_min;
591 data->last_start_min =
592 data->pos_min - SvCUR(last_str);
593 data->last_start_max = is_inf
595 : data->pos_min + data->pos_delta
598 data->longest = &(data->longest_float);
600 SvREFCNT_dec(last_str);
602 if (data && (fl & SF_HAS_EVAL))
603 data->flags |= SF_HAS_EVAL;
605 if (OP(oscan) != CURLYX) {
606 while (regkind[(U8)OP(next = regnext(oscan))] == NOTHING
608 NEXT_OFF(oscan) += NEXT_OFF(next);
611 default: /* REF only? */
612 if (flags & SCF_DO_SUBSTR) {
614 data->longest = &(data->longest_float);
616 is_inf = is_inf_internal = 1;
619 } else if (strchr(simple,OP(scan))) {
620 if (flags & SCF_DO_SUBSTR) {
625 } else if (regkind[(U8)OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
626 data->flags |= (OP(scan) == MEOL
629 } else if (regkind[(U8)OP(scan)] == BRANCHJ
630 && (scan->flags || data)
631 && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
632 I32 deltanext, minnext;
636 next = regnext(scan);
637 nscan = NEXTOPER(NEXTOPER(scan));
638 minnext = study_chunk(&nscan, &deltanext, last, &data_fake, 0);
641 FAIL("variable length lookbehind not implemented");
642 } else if (minnext > U8_MAX) {
643 FAIL2("lookbehind longer than %d not implemented", U8_MAX);
645 scan->flags = minnext;
647 if (data && data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
649 if (data && (data_fake.flags & SF_HAS_EVAL))
650 data->flags |= SF_HAS_EVAL;
651 } else if (OP(scan) == OPEN) {
653 } else if (OP(scan) == CLOSE && ARG(scan) == is_par) {
654 next = regnext(scan);
656 if ( next && (OP(next) != WHILEM) && next < last)
657 is_par = 0; /* Disable optimization */
658 } else if (OP(scan) == EVAL) {
660 data->flags |= SF_HAS_EVAL;
662 /* Else: zero-length, ignore. */
663 scan = regnext(scan);
668 *deltap = is_inf_internal ? I32_MAX : delta;
669 if (flags & SCF_DO_SUBSTR && is_inf)
670 data->pos_delta = I32_MAX - data->pos_min;
673 if (is_par && pars==1 && data) {
674 data->flags |= SF_IN_PAR;
675 data->flags &= ~SF_HAS_PAR;
676 } else if (pars && data) {
677 data->flags |= SF_HAS_PAR;
678 data->flags &= ~SF_IN_PAR;
684 add_data(I32 n, char *s)
687 if (PL_regcomp_rx->data) {
688 Renewc(PL_regcomp_rx->data,
689 sizeof(*PL_regcomp_rx->data) + sizeof(void*) * (PL_regcomp_rx->data->count + n - 1),
690 char, struct reg_data);
691 Renew(PL_regcomp_rx->data->what, PL_regcomp_rx->data->count + n, U8);
692 PL_regcomp_rx->data->count += n;
694 Newc(1207, PL_regcomp_rx->data, sizeof(*PL_regcomp_rx->data) + sizeof(void*) * (n - 1),
695 char, struct reg_data);
696 New(1208, PL_regcomp_rx->data->what, n, U8);
697 PL_regcomp_rx->data->count = n;
699 Copy(s, PL_regcomp_rx->data->what + PL_regcomp_rx->data->count - n, n, U8);
700 return PL_regcomp_rx->data->count - n;
704 - pregcomp - compile a regular expression into internal code
706 * We can't allocate space until we know how big the compiled form will be,
707 * but we can't compile it (and thus know how big it is) until we've got a
708 * place to put the code. So we cheat: we compile it twice, once with code
709 * generation turned off and size counting turned on, and once "for real".
710 * This also means that we don't allocate space until we are sure that the
711 * thing really will compile successfully, and we never have to move the
712 * code and thus invalidate pointers into it. (Note that it has to be in
713 * one piece because free() must be able to free it all.) [NB: not true in perl]
715 * Beware that the optimization-preparation code in here knows about some
716 * of the structure of the compiled regexp. [I'll say.]
719 pregcomp(char *exp, char *xend, PMOP *pm)
734 FAIL("NULL regexp argument");
736 PL_regprecomp = savepvn(exp, xend - exp);
737 DEBUG_r(PerlIO_printf(Perl_debug_log, "compiling RE `%*s'\n",
738 xend - exp, PL_regprecomp));
739 PL_regflags = pm->op_pmflags;
743 PL_seen_zerolen = *exp == '^' ? -1 : 0;
747 /* First pass: determine size, legality. */
748 PL_regcomp_parse = exp;
753 PL_regcode = &PL_regdummy;
754 regc((U8)MAGIC, (char*)PL_regcode);
755 if (reg(0, &flags) == NULL) {
756 Safefree(PL_regprecomp);
757 PL_regprecomp = Nullch;
760 DEBUG_r(PerlIO_printf(Perl_debug_log, "size %d ", PL_regsize));
765 char *s = PerlEnv_getenv("TERMCAP_COLORS");
769 PL_colors[0] = s = savepv(s);
773 FAIL("Not enough TABs in TERMCAP_COLORS");
782 PerlIO_printf(Perl_debug_log, "%s%s%s%s",
783 PL_colors[0],PL_colors[1],PL_colors[2],PL_colors[3]);
787 /* Small enough for pointer-storage convention?
788 If extralen==0, this means that we will not need long jumps. */
789 if (PL_regsize >= 0x10000L && PL_extralen)
790 PL_regsize += PL_extralen;
794 /* Allocate space and initialize. */
795 Newc(1001, r, sizeof(regexp) + (unsigned)PL_regsize * sizeof(regnode),
798 FAIL("regexp out of space");
800 r->prelen = xend - exp;
801 r->precomp = PL_regprecomp;
802 r->subbeg = r->subbase = NULL;
803 r->nparens = PL_regnpar - 1; /* set early to validate backrefs */
806 /* Second pass: emit code. */
807 PL_regcomp_parse = exp;
811 PL_regcode = r->program;
812 /* Store the count of eval-groups for security checks: */
813 PL_regcode->next_off = ((PL_seen_evals > U16_MAX) ? U16_MAX : PL_seen_evals);
814 regc((U8)MAGIC, (char*) PL_regcode++);
816 if (reg(0, &flags) == NULL)
819 /* Dig out information for optimizations. */
820 r->reganch = pm->op_pmflags & PMf_COMPILETIME;
821 pm->op_pmflags = PL_regflags;
822 r->regstclass = NULL;
823 r->naughty = PL_regnaughty >= 10; /* Probably an expensive pattern. */
824 scan = r->program + 1; /* First BRANCH. */
826 /* XXXX To minimize changes to RE engine we always allocate
827 3-units-long substrs field. */
828 Newz(1004, r->substrs, 1, struct reg_substr_data);
830 if (OP(scan) != BRANCH) { /* Only one top-level choice. */
833 STRLEN longest_float_length, longest_fixed_length;
835 StructCopy(&zero_scan_data, &data, scan_data_t);
837 /* Skip introductions and multiplicators >= 1. */
838 while ((OP(first) == OPEN && (sawopen = 1)) ||
839 (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
840 (OP(first) == PLUS) ||
841 (OP(first) == MINMOD) ||
842 (regkind[(U8)OP(first)] == CURLY && ARG1(first) > 0) ) {
843 if (OP(first) == PLUS)
846 first += regarglen[(U8)OP(first)];
847 first = NEXTOPER(first);
850 /* Starting-point info. */
852 if (OP(first) == EXACT); /* Empty, get anchored substr later. */
853 else if (strchr(simple+2,OP(first)))
854 r->regstclass = first;
855 else if (regkind[(U8)OP(first)] == BOUND ||
856 regkind[(U8)OP(first)] == NBOUND)
857 r->regstclass = first;
858 else if (regkind[(U8)OP(first)] == BOL) {
859 r->reganch |= (OP(first) == MBOL ? ROPT_ANCH_MBOL: ROPT_ANCH_BOL);
860 first = NEXTOPER(first);
863 else if (OP(first) == GPOS) {
864 r->reganch |= ROPT_ANCH_GPOS;
865 first = NEXTOPER(first);
868 else if ((OP(first) == STAR &&
869 regkind[(U8)OP(NEXTOPER(first))] == ANY) &&
870 !(r->reganch & ROPT_ANCH) )
872 /* turn .* into ^.* with an implied $*=1 */
873 r->reganch |= ROPT_ANCH_BOL | ROPT_IMPLICIT;
874 first = NEXTOPER(first);
877 if (sawplus && (!sawopen || !PL_regsawback))
878 r->reganch |= ROPT_SKIP; /* x+ must match 1st of run */
880 /* Scan is after the zeroth branch, first is atomic matcher. */
881 DEBUG_r(PerlIO_printf(Perl_debug_log, "first at %d\n",
884 * If there's something expensive in the r.e., find the
885 * longest literal string that must appear and make it the
886 * regmust. Resolve ties in favor of later strings, since
887 * the regstart check works with the beginning of the r.e.
888 * and avoiding duplication strengthens checking. Not a
889 * strong reason, but sufficient in the absence of others.
890 * [Now we resolve ties in favor of the earlier string if
891 * it happens that c_offset_min has been invalidated, since the
892 * earlier string may buy us something the later one won't.]
896 data.longest_fixed = newSVpv("",0);
897 data.longest_float = newSVpv("",0);
898 data.last_found = newSVpv("",0);
899 data.longest = &(data.longest_fixed);
902 minlen = study_chunk(&first, &fake, scan + PL_regsize, /* Up to end */
903 &data, SCF_DO_SUBSTR);
904 if ( PL_regnpar == 1 && data.longest == &(data.longest_fixed)
905 && data.last_start_min == 0 && data.last_end > 0
907 && (!(PL_regseen & REG_SEEN_GPOS) || (r->reganch & ROPT_ANCH_GPOS)))
908 r->reganch |= ROPT_CHECK_ALL;
910 SvREFCNT_dec(data.last_found);
912 longest_float_length = SvCUR(data.longest_float);
913 if (longest_float_length
914 || (data.flags & SF_FL_BEFORE_EOL
915 && (!(data.flags & SF_FL_BEFORE_MEOL)
916 || (PL_regflags & PMf_MULTILINE)))) {
917 if (SvCUR(data.longest_fixed)
918 && data.offset_fixed == data.offset_float_min
919 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
920 goto remove_float; /* Like in (a)+. */
922 r->float_substr = data.longest_float;
923 r->float_min_offset = data.offset_float_min;
924 r->float_max_offset = data.offset_float_max;
925 fbm_compile(r->float_substr, 0);
926 BmUSEFUL(r->float_substr) = 100;
927 if (data.flags & SF_FL_BEFORE_EOL /* Cannot have SEOL and MULTI */
928 && (!(data.flags & SF_FL_BEFORE_MEOL)
929 || (PL_regflags & PMf_MULTILINE)))
930 SvTAIL_on(r->float_substr);
933 r->float_substr = Nullsv;
934 SvREFCNT_dec(data.longest_float);
935 longest_float_length = 0;
938 longest_fixed_length = SvCUR(data.longest_fixed);
939 if (longest_fixed_length
940 || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
941 && (!(data.flags & SF_FIX_BEFORE_MEOL)
942 || (PL_regflags & PMf_MULTILINE)))) {
943 r->anchored_substr = data.longest_fixed;
944 r->anchored_offset = data.offset_fixed;
945 fbm_compile(r->anchored_substr, 0);
946 BmUSEFUL(r->anchored_substr) = 100;
947 if (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
948 && (!(data.flags & SF_FIX_BEFORE_MEOL)
949 || (PL_regflags & PMf_MULTILINE)))
950 SvTAIL_on(r->anchored_substr);
952 r->anchored_substr = Nullsv;
953 SvREFCNT_dec(data.longest_fixed);
954 longest_fixed_length = 0;
957 /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
958 if (longest_fixed_length > longest_float_length) {
959 r->check_substr = r->anchored_substr;
960 r->check_offset_min = r->check_offset_max = r->anchored_offset;
961 if (r->reganch & ROPT_ANCH_SINGLE)
962 r->reganch |= ROPT_NOSCAN;
964 r->check_substr = r->float_substr;
965 r->check_offset_min = data.offset_float_min;
966 r->check_offset_max = data.offset_float_max;
969 /* Several toplevels. Best we can is to set minlen. */
972 DEBUG_r(PerlIO_printf(Perl_debug_log, "\n"));
973 scan = r->program + 1;
974 minlen = study_chunk(&scan, &fake, scan + PL_regsize, NULL, 0);
975 r->check_substr = r->anchored_substr = r->float_substr = Nullsv;
979 if (PL_regseen & REG_SEEN_GPOS)
980 r->reganch |= ROPT_GPOS_SEEN;
981 if (PL_regseen & REG_SEEN_LOOKBEHIND)
982 r->reganch |= ROPT_LOOKBEHIND_SEEN;
983 if (PL_regseen & REG_SEEN_EVAL)
984 r->reganch |= ROPT_EVAL_SEEN;
985 Newz(1002, r->startp, PL_regnpar, char*);
986 Newz(1002, r->endp, PL_regnpar, char*);
992 - reg - regular expression, i.e. main body or parenthesized thing
994 * Caller must absorb opening parenthesis.
996 * Combining parenthesis handling with the base level of regular expression
997 * is a trifle forced, but the need to tie the tails of the branches to what
998 * follows makes it hard to avoid.
1001 reg(I32 paren, I32 *flagp)
1002 /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
1005 register regnode *ret; /* Will be the head of the group. */
1006 register regnode *br;
1007 register regnode *lastbr;
1008 register regnode *ender = 0;
1009 register I32 parno = 0;
1010 I32 flags, oregflags = PL_regflags, have_branch = 0, open = 0;
1013 *flagp = 0; /* Tentatively. */
1015 /* Make an OPEN node, if parenthesized. */
1017 if (*PL_regcomp_parse == '?') {
1018 U16 posflags = 0, negflags = 0;
1019 U16 *flagsp = &posflags;
1022 paren = *PL_regcomp_parse++;
1023 ret = NULL; /* For look-ahead/behind. */
1026 PL_regseen |= REG_SEEN_LOOKBEHIND;
1027 if (*PL_regcomp_parse == '!')
1029 if (*PL_regcomp_parse != '=' && *PL_regcomp_parse != '!')
1040 FAIL2("Sequence (?%c...) not implemented", (int)paren);
1043 while (*PL_regcomp_parse && *PL_regcomp_parse != ')')
1045 if (*PL_regcomp_parse != ')')
1046 FAIL("Sequence (?#... not terminated");
1053 I32 count = 1, n = 0;
1055 char *s = PL_regcomp_parse;
1057 OP_4tree *sop, *rop;
1060 PL_regseen |= REG_SEEN_EVAL;
1061 while (count && (c = *PL_regcomp_parse)) {
1062 if (c == '\\' && PL_regcomp_parse[1])
1070 if (*PL_regcomp_parse != ')')
1071 FAIL("Sequence (?{...}) not terminated or not {}-balanced");
1075 if (PL_regcomp_parse - 1 - s)
1076 sv = newSVpv(s, PL_regcomp_parse - 1 - s);
1078 sv = newSVpv("", 0);
1080 rop = sv_compile_2op(sv, &sop, "re", &av);
1082 n = add_data(3, "nso");
1083 PL_regcomp_rx->data->data[n] = (void*)rop;
1084 PL_regcomp_rx->data->data[n+1] = (void*)av;
1085 PL_regcomp_rx->data->data[n+2] = (void*)sop;
1087 } else { /* First pass */
1088 if (PL_reginterp_cnt < ++PL_seen_evals && PL_curcop != &PL_compiling)
1089 /* No compiled RE interpolated, has runtime
1090 components ===> unsafe. */
1091 FAIL("Eval-group not allowed at runtime, use re 'eval'");
1093 FAIL("Eval-group in insecure regular expression");
1097 return reganode(EVAL, n);
1101 if (PL_regcomp_parse[0] == '?') {
1102 if (PL_regcomp_parse[1] == '=' || PL_regcomp_parse[1] == '!'
1103 || PL_regcomp_parse[1] == '<'
1104 || PL_regcomp_parse[1] == '{') { /* Lookahead or eval. */
1107 ret = reg_node(LOGICAL);
1108 regtail(ret, reg(1, &flag));
1111 } else if (PL_regcomp_parse[0] >= '1' && PL_regcomp_parse[0] <= '9' ) {
1112 parno = atoi(PL_regcomp_parse++);
1114 while (isDIGIT(*PL_regcomp_parse))
1116 ret = reganode(GROUPP, parno);
1117 if ((c = *nextchar()) != ')')
1118 FAIL2("Switch (?(number%c not recognized", c);
1120 regtail(ret, reganode(IFTHEN, 0));
1121 br = regbranch(&flags, 1);
1123 br = reganode(LONGJMP, 0);
1125 regtail(br, reganode(LONGJMP, 0));
1130 lastbr = reganode(IFTHEN, 0); /* Fake one for optimizer. */
1131 regbranch(&flags, 1);
1132 regtail(ret, lastbr);
1139 FAIL("Switch (?(condition)... contains too many branches");
1140 ender = reg_node(TAIL);
1143 regtail(lastbr, ender);
1144 regtail(NEXTOPER(NEXTOPER(lastbr)), ender);
1146 regtail(ret, ender);
1149 FAIL2("Unknown condition for (?(%.2s", PL_regcomp_parse);
1153 FAIL("Sequence (? incomplete");
1158 while (*PL_regcomp_parse && strchr("iogcmsx", *PL_regcomp_parse)) {
1159 if (*PL_regcomp_parse != 'o')
1160 pmflag(flagsp, *PL_regcomp_parse);
1163 if (*PL_regcomp_parse == '-') {
1168 PL_regflags |= posflags;
1169 PL_regflags &= ~negflags;
1170 if (*PL_regcomp_parse == ':') {
1176 if (*PL_regcomp_parse != ')')
1177 FAIL2("Sequence (?%c...) not recognized", *PL_regcomp_parse);
1186 ret = reganode(OPEN, parno);
1192 /* Pick up the branches, linking them together. */
1193 br = regbranch(&flags, 1);
1196 if (*PL_regcomp_parse == '|') {
1197 if (!SIZE_ONLY && PL_extralen) {
1198 reginsert(BRANCHJ, br);
1200 reginsert(BRANCH, br);
1203 PL_extralen += 1; /* For BRANCHJ-BRANCH. */
1204 } else if (paren == ':') {
1205 *flagp |= flags&SIMPLE;
1207 if (open) { /* Starts with OPEN. */
1208 regtail(ret, br); /* OPEN -> first. */
1209 } else if (paren != '?') /* Not Conditional */
1213 *flagp |= flags&SPSTART;
1215 while (*PL_regcomp_parse == '|') {
1216 if (!SIZE_ONLY && PL_extralen) {
1217 ender = reganode(LONGJMP,0);
1218 regtail(NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
1221 PL_extralen += 2; /* Account for LONGJMP. */
1223 br = regbranch(&flags, 0);
1226 regtail(lastbr, br); /* BRANCH -> BRANCH. */
1230 *flagp |= flags&SPSTART;
1233 if (have_branch || paren != ':') {
1234 /* Make a closing node, and hook it on the end. */
1237 ender = reg_node(TAIL);
1240 ender = reganode(CLOSE, parno);
1246 *flagp &= ~HASWIDTH;
1249 ender = reg_node(SUCCEED);
1252 ender = reg_node(END);
1255 regtail(lastbr, ender);
1258 /* Hook the tails of the branches to the closing node. */
1259 for (br = ret; br != NULL; br = regnext(br)) {
1260 regoptail(br, ender);
1267 static char parens[] = "=!<,>";
1269 if (paren && (p = strchr(parens, paren))) {
1270 int node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
1271 int flag = (p - parens) > 1;
1274 node = SUSPEND, flag = 0;
1275 reginsert(node,ret);
1277 regtail(ret, reg_node(TAIL));
1281 /* Check for proper termination. */
1282 if (paren && (PL_regcomp_parse >= PL_regxend || *nextchar() != ')')) {
1283 FAIL("unmatched () in regexp");
1284 } else if (!paren && PL_regcomp_parse < PL_regxend) {
1285 if (*PL_regcomp_parse == ')') {
1286 FAIL("unmatched () in regexp");
1288 FAIL("junk on end of regexp"); /* "Can't happen". */
1292 PL_regflags = oregflags;
1299 - regbranch - one alternative of an | operator
1301 * Implements the concatenation operator.
1304 regbranch(I32 *flagp, I32 first)
1307 register regnode *ret;
1308 register regnode *chain = NULL;
1309 register regnode *latest;
1310 I32 flags = 0, c = 0;
1315 if (!SIZE_ONLY && PL_extralen)
1316 ret = reganode(BRANCHJ,0);
1318 ret = reg_node(BRANCH);
1321 if (!first && SIZE_ONLY)
1322 PL_extralen += 1; /* BRANCHJ */
1324 *flagp = WORST; /* Tentatively. */
1328 while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != '|' && *PL_regcomp_parse != ')') {
1330 latest = regpiece(&flags);
1331 if (latest == NULL) {
1332 if (flags & TRYAGAIN)
1335 } else if (ret == NULL)
1337 *flagp |= flags&HASWIDTH;
1338 if (chain == NULL) /* First piece. */
1339 *flagp |= flags&SPSTART;
1342 regtail(chain, latest);
1347 if (chain == NULL) { /* Loop ran zero times. */
1348 chain = reg_node(NOTHING);
1353 *flagp |= flags&SIMPLE;
1360 - regpiece - something followed by possible [*+?]
1362 * Note that the branching code sequences used for ? and the general cases
1363 * of * and + are somewhat optimized: they use the same NOTHING node as
1364 * both the endmarker for their branch list and the body of the last branch.
1365 * It might seem that this node could be dispensed with entirely, but the
1366 * endmarker role is not redundant.
1369 regpiece(I32 *flagp)
1372 register regnode *ret;
1374 register char *next;
1376 char *origparse = PL_regcomp_parse;
1379 I32 max = REG_INFTY;
1381 ret = regatom(&flags);
1383 if (flags & TRYAGAIN)
1388 op = *PL_regcomp_parse;
1390 if (op == '{' && regcurly(PL_regcomp_parse)) {
1391 next = PL_regcomp_parse + 1;
1393 while (isDIGIT(*next) || *next == ',') {
1402 if (*next == '}') { /* got one */
1406 min = atoi(PL_regcomp_parse);
1410 maxpos = PL_regcomp_parse;
1412 if (!max && *maxpos != '0')
1413 max = REG_INFTY; /* meaning "infinity" */
1414 else if (max >= REG_INFTY)
1415 FAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
1416 PL_regcomp_parse = next;
1420 if ((flags&SIMPLE)) {
1421 PL_regnaughty += 2 + PL_regnaughty / 2;
1422 reginsert(CURLY, ret);
1425 PL_regnaughty += 4 + PL_regnaughty; /* compound interest */
1426 regtail(ret, reg_node(WHILEM));
1427 if (!SIZE_ONLY && PL_extralen) {
1428 reginsert(LONGJMP,ret);
1429 reginsert(NOTHING,ret);
1430 NEXT_OFF(ret) = 3; /* Go over LONGJMP. */
1432 reginsert(CURLYX,ret);
1433 if (!SIZE_ONLY && PL_extralen)
1434 NEXT_OFF(ret) = 3; /* Go over NOTHING to LONGJMP. */
1435 regtail(ret, reg_node(NOTHING));
1445 if (max && max < min)
1446 FAIL("Can't do {n,m} with n > m");
1461 #if 0 /* Now runtime fix should be reliable. */
1462 if (!(flags&HASWIDTH) && op != '?')
1463 FAIL("regexp *+ operand could be empty");
1468 *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
1470 if (op == '*' && (flags&SIMPLE)) {
1471 reginsert(STAR, ret);
1475 else if (op == '*') {
1478 } else if (op == '+' && (flags&SIMPLE)) {
1479 reginsert(PLUS, ret);
1483 else if (op == '+') {
1486 } else if (op == '?') {
1491 if (PL_dowarn && !SIZE_ONLY && !(flags&HASWIDTH) && max > 10000) {
1492 warn("%.*s matches null string many times",
1493 PL_regcomp_parse - origparse, origparse);
1496 if (*PL_regcomp_parse == '?') {
1498 reginsert(MINMOD, ret);
1499 regtail(ret, ret + NODE_STEP_REGNODE);
1501 if (ISMULT2(PL_regcomp_parse))
1502 FAIL("nested *?+ in regexp");
1508 - regatom - the lowest level
1510 * Optimization: gobbles an entire sequence of ordinary characters so that
1511 * it can turn them into a single node, which is smaller to store and
1512 * faster to run. Backslashed characters are exceptions, each becoming a
1513 * separate node; the code is simpler that way and it's not worth fixing.
1515 * [Yes, it is worth fixing, some scripts can run twice the speed.]
1521 register regnode *ret = 0;
1524 *flagp = WORST; /* Tentatively. */
1527 switch (*PL_regcomp_parse) {
1531 if (PL_regflags & PMf_MULTILINE)
1532 ret = reg_node(MBOL);
1533 else if (PL_regflags & PMf_SINGLELINE)
1534 ret = reg_node(SBOL);
1536 ret = reg_node(BOL);
1539 if (PL_regcomp_parse[1])
1542 if (PL_regflags & PMf_MULTILINE)
1543 ret = reg_node(MEOL);
1544 else if (PL_regflags & PMf_SINGLELINE)
1545 ret = reg_node(SEOL);
1547 ret = reg_node(EOL);
1551 if (PL_regflags & PMf_SINGLELINE)
1552 ret = reg_node(SANY);
1554 ret = reg_node(ANY);
1556 *flagp |= HASWIDTH|SIMPLE;
1561 *flagp |= HASWIDTH|SIMPLE;
1565 ret = reg(1, &flags);
1567 if (flags & TRYAGAIN)
1571 *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE);
1575 if (flags & TRYAGAIN) {
1579 FAIL2("internal urp in regexp at /%s/", PL_regcomp_parse);
1580 /* Supposed to be caught earlier. */
1583 if (!regcurly(PL_regcomp_parse)) {
1591 FAIL("?+*{} follows nothing in regexp");
1594 switch (*++PL_regcomp_parse) {
1597 ret = reg_node(SBOL);
1602 ret = reg_node(GPOS);
1603 PL_regseen |= REG_SEEN_GPOS;
1608 ret = reg_node(SEOL);
1613 ret = reg_node(EOS);
1615 PL_seen_zerolen++; /* Do not optimize RE away */
1619 ret = reg_node((PL_regflags & PMf_LOCALE) ? ALNUML : ALNUM);
1620 *flagp |= HASWIDTH|SIMPLE;
1624 ret = reg_node((PL_regflags & PMf_LOCALE) ? NALNUML : NALNUM);
1625 *flagp |= HASWIDTH|SIMPLE;
1630 ret = reg_node((PL_regflags & PMf_LOCALE) ? BOUNDL : BOUND);
1636 ret = reg_node((PL_regflags & PMf_LOCALE) ? NBOUNDL : NBOUND);
1641 ret = reg_node((PL_regflags & PMf_LOCALE) ? SPACEL : SPACE);
1642 *flagp |= HASWIDTH|SIMPLE;
1646 ret = reg_node((PL_regflags & PMf_LOCALE) ? NSPACEL : NSPACE);
1647 *flagp |= HASWIDTH|SIMPLE;
1651 ret = reg_node(DIGIT);
1652 *flagp |= HASWIDTH|SIMPLE;
1656 ret = reg_node(NDIGIT);
1657 *flagp |= HASWIDTH|SIMPLE;
1670 case '1': case '2': case '3': case '4':
1671 case '5': case '6': case '7': case '8': case '9':
1673 I32 num = atoi(PL_regcomp_parse);
1675 if (num > 9 && num >= PL_regnpar)
1678 if (!SIZE_ONLY && num > PL_regcomp_rx->nparens)
1679 FAIL("reference to nonexistent group");
1681 ret = reganode((PL_regflags & PMf_FOLD)
1682 ? ((PL_regflags & PMf_LOCALE) ? REFFL : REFF)
1685 while (isDIGIT(*PL_regcomp_parse))
1693 if (PL_regcomp_parse >= PL_regxend)
1694 FAIL("trailing \\ in regexp");
1702 if (PL_regflags & PMf_EXTENDED) {
1703 while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != '\n') PL_regcomp_parse++;
1704 if (PL_regcomp_parse < PL_regxend)
1719 ret = reg_node((PL_regflags & PMf_FOLD)
1720 ? ((PL_regflags & PMf_LOCALE) ? EXACTFL : EXACTF)
1722 s = (char *) OPERAND(ret);
1723 regc(0, s++); /* save spot for len */
1724 for (len = 0, p = PL_regcomp_parse - 1;
1725 len < 127 && p < PL_regxend;
1730 if (PL_regflags & PMf_EXTENDED)
1731 p = regwhite(p, PL_regxend);
1782 ender = scan_hex(++p, 2, &numlen);
1787 ender = UCHARAT(p++);
1788 ender = toCTRL(ender);
1790 case '0': case '1': case '2': case '3':case '4':
1791 case '5': case '6': case '7': case '8':case '9':
1793 (isDIGIT(p[1]) && atoi(p) >= PL_regnpar) ) {
1794 ender = scan_oct(p, 3, &numlen);
1803 if (p >= PL_regxend)
1804 FAIL("trailing \\ in regexp");
1815 if (PL_regflags & PMf_EXTENDED)
1816 p = regwhite(p, PL_regxend);
1817 if (ISMULT2(p)) { /* Back off on ?+*. */
1829 PL_regcomp_parse = p - 1;
1832 FAIL("internal disaster in regexp");
1838 *OPERAND(ret) = len;
1841 PL_regsize += (len + 2 + sizeof(regnode) - 1) / sizeof(regnode);
1843 PL_regcode += (len + 2 + sizeof(regnode) - 1) / sizeof(regnode);
1853 regwhite(char *p, char *e)
1858 else if (*p == '#') {
1861 } while (p < e && *p != '\n');
1873 register char *opnd, *s;
1875 register I32 lastclass = 1234;
1876 register I32 range = 0;
1877 register regnode *ret;
1881 s = opnd = (char *) OPERAND(PL_regcode);
1882 ret = reg_node(ANYOF);
1883 for (Class = 0; Class < 33; Class++)
1885 if (*PL_regcomp_parse == '^') { /* Complement of range. */
1889 *opnd |= ANYOF_INVERT;
1892 PL_regcode += ANY_SKIP;
1893 if (PL_regflags & PMf_FOLD)
1894 *opnd |= ANYOF_FOLD;
1895 if (PL_regflags & PMf_LOCALE)
1896 *opnd |= ANYOF_LOCALE;
1898 PL_regsize += ANY_SKIP;
1900 if (*PL_regcomp_parse == ']' || *PL_regcomp_parse == '-')
1901 goto skipcond; /* allow 1st char to be ] or - */
1902 while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != ']') {
1904 Class = UCHARAT(PL_regcomp_parse++);
1905 if (Class == '[' && PL_regcomp_parse + 1 < PL_regxend &&
1906 /* I smell either [: or [= or [. -- POSIX has been here, right? */
1907 (*PL_regcomp_parse == ':' || *PL_regcomp_parse == '=' || *PL_regcomp_parse == '.')) {
1908 char posixccc = *PL_regcomp_parse;
1909 char* posixccs = PL_regcomp_parse++;
1911 while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != posixccc)
1913 if (PL_regcomp_parse == PL_regxend)
1914 /* Grandfather lone [:, [=, [. */
1915 PL_regcomp_parse = posixccs;
1917 PL_regcomp_parse++; /* skip over the posixccc */
1918 if (*PL_regcomp_parse == ']') {
1919 /* Not Implemented Yet.
1920 * (POSIX Extended Character Classes, that is)
1921 * The text between e.g. [: and :] would start
1922 * at posixccs + 1 and stop at regcomp_parse - 2. */
1923 if (PL_dowarn && !SIZE_ONLY)
1924 warn("Character class syntax [%c %c] is reserved for future extensions", posixccc, posixccc);
1925 PL_regcomp_parse++; /* skip over the ending ] */
1929 if (Class == '\\') {
1930 Class = UCHARAT(PL_regcomp_parse++);
1934 if (PL_regflags & PMf_LOCALE)
1935 *opnd |= ANYOF_ALNUML;
1937 for (Class = 0; Class < 256; Class++)
1939 ANYOF_SET(opnd, Class);
1946 if (PL_regflags & PMf_LOCALE)
1947 *opnd |= ANYOF_NALNUML;
1949 for (Class = 0; Class < 256; Class++)
1950 if (!isALNUM(Class))
1951 ANYOF_SET(opnd, Class);
1958 if (PL_regflags & PMf_LOCALE)
1959 *opnd |= ANYOF_SPACEL;
1961 for (Class = 0; Class < 256; Class++)
1963 ANYOF_SET(opnd, Class);
1970 if (PL_regflags & PMf_LOCALE)
1971 *opnd |= ANYOF_NSPACEL;
1973 for (Class = 0; Class < 256; Class++)
1974 if (!isSPACE(Class))
1975 ANYOF_SET(opnd, Class);
1982 for (Class = '0'; Class <= '9'; Class++)
1983 ANYOF_SET(opnd, Class);
1989 for (Class = 0; Class < '0'; Class++)
1990 ANYOF_SET(opnd, Class);
1991 for (Class = '9' + 1; Class < 256; Class++)
1992 ANYOF_SET(opnd, Class);
2018 Class = scan_hex(PL_regcomp_parse, 2, &numlen);
2019 PL_regcomp_parse += numlen;
2022 Class = UCHARAT(PL_regcomp_parse++);
2023 Class = toCTRL(Class);
2025 case '0': case '1': case '2': case '3': case '4':
2026 case '5': case '6': case '7': case '8': case '9':
2027 Class = scan_oct(--PL_regcomp_parse, 3, &numlen);
2028 PL_regcomp_parse += numlen;
2033 if (lastclass > Class)
2034 FAIL("invalid [] range in regexp");
2039 if (*PL_regcomp_parse == '-' && PL_regcomp_parse+1 < PL_regxend &&
2040 PL_regcomp_parse[1] != ']') {
2043 continue; /* do it next time */
2049 if ((isLOWER(lastclass) && isLOWER(Class)) ||
2050 (isUPPER(lastclass) && isUPPER(Class))) {
2051 if (isLOWER(lastclass)) {
2052 for (i = lastclass; i <= Class; i++)
2056 for (i = lastclass; i <= Class; i++)
2063 for ( ; lastclass <= Class; lastclass++)
2064 ANYOF_SET(opnd, lastclass);
2068 if (*PL_regcomp_parse != ']')
2069 FAIL("unmatched [] in regexp");
2071 /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
2072 if (!SIZE_ONLY && (*opnd & (0xFF ^ ANYOF_INVERT)) == ANYOF_FOLD) {
2073 for (Class = 0; Class < 256; ++Class) {
2074 if (ANYOF_TEST(opnd, Class)) {
2075 I32 cf = fold[Class];
2076 ANYOF_SET(opnd, cf);
2079 *opnd &= ~ANYOF_FOLD;
2081 /* optimize inverted simple patterns (e.g. [^a-z]) */
2082 if (!SIZE_ONLY && (*opnd & 0xFF) == ANYOF_INVERT) {
2083 for (Class = 0; Class < 32; ++Class)
2084 opnd[1 + Class] ^= 0xFF;
2094 char* retval = PL_regcomp_parse++;
2097 if (*PL_regcomp_parse == '(' && PL_regcomp_parse[1] == '?' &&
2098 PL_regcomp_parse[2] == '#') {
2099 while (*PL_regcomp_parse && *PL_regcomp_parse != ')')
2104 if (PL_regflags & PMf_EXTENDED) {
2105 if (isSPACE(*PL_regcomp_parse)) {
2109 else if (*PL_regcomp_parse == '#') {
2110 while (*PL_regcomp_parse && *PL_regcomp_parse != '\n')
2121 - reg_node - emit a node
2123 STATIC regnode * /* Location. */
2127 register regnode *ret;
2128 register regnode *ptr;
2132 SIZE_ALIGN(PL_regsize);
2137 NODE_ALIGN_FILL(ret);
2139 FILL_ADVANCE_NODE(ptr, op);
2146 - reganode - emit a node with an argument
2148 STATIC regnode * /* Location. */
2149 reganode(U8 op, U32 arg)
2152 register regnode *ret;
2153 register regnode *ptr;
2157 SIZE_ALIGN(PL_regsize);
2162 NODE_ALIGN_FILL(ret);
2164 FILL_ADVANCE_NODE_ARG(ptr, op, arg);
2171 - regc - emit (if appropriate) a byte of code
2182 - reginsert - insert an operator in front of already-emitted operand
2184 * Means relocating the operand.
2187 reginsert(U8 op, regnode *opnd)
2190 register regnode *src;
2191 register regnode *dst;
2192 register regnode *place;
2193 register int offset = regarglen[(U8)op];
2195 /* (regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
2198 PL_regsize += NODE_STEP_REGNODE + offset;
2203 PL_regcode += NODE_STEP_REGNODE + offset;
2206 StructCopy(--src, --dst, regnode);
2208 place = opnd; /* Op node, where operand used to be. */
2209 src = NEXTOPER(place);
2210 FILL_ADVANCE_NODE(place, op);
2211 Zero(src, offset, regnode);
2215 - regtail - set the next-pointer at the end of a node chain of p to val.
2218 regtail(regnode *p, regnode *val)
2221 register regnode *scan;
2222 register regnode *temp;
2223 register I32 offset;
2228 /* Find last node. */
2231 temp = regnext(scan);
2237 if (reg_off_by_arg[OP(scan)]) {
2238 ARG_SET(scan, val - scan);
2240 NEXT_OFF(scan) = val - scan;
2245 - regoptail - regtail on operand of first argument; nop if operandless
2248 regoptail(regnode *p, regnode *val)
2251 /* "Operandless" and "op != BRANCH" are synonymous in practice. */
2252 if (p == NULL || SIZE_ONLY)
2254 if (regkind[(U8)OP(p)] == BRANCH) {
2255 regtail(NEXTOPER(p), val);
2256 } else if ( regkind[(U8)OP(p)] == BRANCHJ) {
2257 regtail(NEXTOPER(NEXTOPER(p)), val);
2263 - regcurly - a little FSA that accepts {\d+,?\d*}
2266 regcurly(register char *s)
2285 dumpuntil(regnode *start, regnode *node, regnode *last, SV* sv, I32 l)
2288 register char op = EXACT; /* Arbitrary non-END op. */
2289 register regnode *next, *onode;
2291 while (op != END && (!last || node < last)) {
2292 /* While that wasn't END last time... */
2298 next = regnext(node);
2300 if (OP(node) == OPTIMIZED)
2303 PerlIO_printf(Perl_debug_log, "%4d:%*s%s", node - start,
2304 2*l + 1, "", SvPVX(sv));
2305 if (next == NULL) /* Next ptr. */
2306 PerlIO_printf(Perl_debug_log, "(0)");
2308 PerlIO_printf(Perl_debug_log, "(%d)", next - start);
2309 (void)PerlIO_putc(Perl_debug_log, '\n');
2311 if (regkind[(U8)op] == BRANCHJ) {
2312 register regnode *nnode = (OP(next) == LONGJMP
2315 if (last && nnode > last)
2317 node = dumpuntil(start, NEXTOPER(NEXTOPER(node)), nnode, sv, l + 1);
2318 } else if (regkind[(U8)op] == BRANCH) {
2319 node = dumpuntil(start, NEXTOPER(node), next, sv, l + 1);
2320 } else if ( op == CURLY) { /* `next' might be very big: optimizer */
2321 node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
2322 NEXTOPER(node) + EXTRA_STEP_2ARGS + 1, sv, l + 1);
2323 } else if (regkind[(U8)op] == CURLY && op != CURLYX) {
2324 node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
2326 } else if ( op == PLUS || op == STAR) {
2327 node = dumpuntil(start, NEXTOPER(node), NEXTOPER(node) + 1, sv, l + 1);
2328 } else if (op == ANYOF) {
2329 node = NEXTOPER(node);
2331 } else if (regkind[(U8)op] == EXACT) {
2332 /* Literal string, where present. */
2333 node += ((*OPERAND(node)) + 2 + sizeof(regnode) - 1) / sizeof(regnode);
2334 node = NEXTOPER(node);
2336 node = NEXTOPER(node);
2337 node += regarglen[(U8)op];
2339 if (op == CURLYX || op == OPEN)
2341 else if (op == WHILEM)
2344 #endif /* DEBUGGING */
2349 - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
2356 SV *sv = sv_newmortal();
2358 (void)dumpuntil(r->program, r->program + 1, NULL, sv, 0);
2360 /* Header fields of interest. */
2361 if (r->anchored_substr)
2362 PerlIO_printf(Perl_debug_log, "anchored `%s%s%s'%s at %d ",
2364 SvPVX(r->anchored_substr),
2366 SvTAIL(r->anchored_substr) ? "$" : "",
2367 r->anchored_offset);
2368 if (r->float_substr)
2369 PerlIO_printf(Perl_debug_log, "floating `%s%s%s'%s at %d..%u ",
2371 SvPVX(r->float_substr),
2373 SvTAIL(r->float_substr) ? "$" : "",
2374 r->float_min_offset, r->float_max_offset);
2375 if (r->check_substr)
2376 PerlIO_printf(Perl_debug_log,
2377 r->check_substr == r->float_substr
2378 ? "(checking floating" : "(checking anchored");
2379 if (r->reganch & ROPT_NOSCAN)
2380 PerlIO_printf(Perl_debug_log, " noscan");
2381 if (r->reganch & ROPT_CHECK_ALL)
2382 PerlIO_printf(Perl_debug_log, " isall");
2383 if (r->check_substr)
2384 PerlIO_printf(Perl_debug_log, ") ");
2386 if (r->regstclass) {
2387 regprop(sv, r->regstclass);
2388 PerlIO_printf(Perl_debug_log, "stclass `%s' ", SvPVX(sv));
2390 if (r->reganch & ROPT_ANCH) {
2391 PerlIO_printf(Perl_debug_log, "anchored");
2392 if (r->reganch & ROPT_ANCH_BOL)
2393 PerlIO_printf(Perl_debug_log, "(BOL)");
2394 if (r->reganch & ROPT_ANCH_MBOL)
2395 PerlIO_printf(Perl_debug_log, "(MBOL)");
2396 if (r->reganch & ROPT_ANCH_GPOS)
2397 PerlIO_printf(Perl_debug_log, "(GPOS)");
2398 PerlIO_putc(Perl_debug_log, ' ');
2400 if (r->reganch & ROPT_GPOS_SEEN)
2401 PerlIO_printf(Perl_debug_log, "GPOS ");
2402 if (r->reganch & ROPT_SKIP)
2403 PerlIO_printf(Perl_debug_log, "plus ");
2404 if (r->reganch & ROPT_IMPLICIT)
2405 PerlIO_printf(Perl_debug_log, "implicit ");
2406 PerlIO_printf(Perl_debug_log, "minlen %ld ", (long) r->minlen);
2407 if (r->reganch & ROPT_EVAL_SEEN)
2408 PerlIO_printf(Perl_debug_log, "with eval ");
2409 PerlIO_printf(Perl_debug_log, "\n");
2410 #endif /* DEBUGGING */
2414 - regprop - printable representation of opcode
2417 regprop(SV *sv, regnode *o)
2421 register char *p = 0;
2423 sv_setpvn(sv, "", 0);
2459 sv_catpvf(sv, "EXACT <%s%s%s>", PL_colors[0], OPERAND(o) + 1, PL_colors[1]);
2462 sv_catpvf(sv, "EXACTF <%s%s%s>", PL_colors[0], OPERAND(o) + 1, PL_colors[1]);
2465 sv_catpvf(sv, "EXACTFL <%s%s%s>", PL_colors[0], OPERAND(o) + 1, PL_colors[1]);
2492 sv_catpvf(sv, "CURLY {%d,%d}", ARG1(o), ARG2(o));
2495 sv_catpvf(sv, "CURLYM[%d] {%d,%d}", o->flags, ARG1(o), ARG2(o));
2498 sv_catpvf(sv, "CURLYN[%d] {%d,%d}", o->flags, ARG1(o), ARG2(o));
2501 sv_catpvf(sv, "CURLYX {%d,%d}", ARG1(o), ARG2(o));
2504 sv_catpvf(sv, "REF%d", ARG(o));
2507 sv_catpvf(sv, "REFF%d", ARG(o));
2510 sv_catpvf(sv, "REFFL%d", ARG(o));
2513 sv_catpvf(sv, "OPEN%d", ARG(o));
2516 sv_catpvf(sv, "CLOSE%d", ARG(o));
2532 sv_catpvf(sv, "UNLESSM[-%d]", o->flags);
2535 sv_catpvf(sv, "IFMATCH[-%d]", o->flags);
2586 sv_catpvf(sv, "GROUPP%d", ARG(o));
2601 FAIL("corrupted regexp opcode");
2605 #endif /* DEBUGGING */
2609 pregfree(struct regexp *r)
2612 if (!r || (--r->refcnt > 0))
2615 Safefree(r->precomp);
2617 Safefree(r->subbase);
2619 if (r->anchored_substr)
2620 SvREFCNT_dec(r->anchored_substr);
2621 if (r->float_substr)
2622 SvREFCNT_dec(r->float_substr);
2623 Safefree(r->substrs);
2626 int n = r->data->count;
2628 switch (r->data->what[n]) {
2630 SvREFCNT_dec((SV*)r->data->data[n]);
2633 op_free((OP_4tree*)r->data->data[n]);
2638 FAIL2("panic: regfree data code '%c'", r->data->what[n]);
2641 Safefree(r->data->what);
2644 Safefree(r->startp);
2650 - regnext - dig the "next" pointer out of a node
2652 * [Note, when REGALIGN is defined there are two places in regmatch()
2653 * that bypass this code for speed.]
2656 regnext(register regnode *p)
2659 register I32 offset;
2661 if (p == &PL_regdummy)
2664 offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
2672 re_croak2(const char* pat1,const char* pat2,...)
2675 STRLEN l1 = strlen(pat1);
2676 STRLEN l2 = strlen(pat2);
2684 Copy(pat1, buf, l1 , char);
2685 Copy(pat2, buf + l1, l2 , char);
2686 buf[l1 + l2] = '\n';
2687 buf[l1 + l2 + 1] = '\0';
2688 va_start(args, pat2);
2689 message = mess(buf, &args);
2691 l1 = strlen(message);
2694 Copy(message, buf, l1 , char);
2695 buf[l1] = '\0'; /* Overwrite \n */