5 * "One Ring to rule them all, One Ring to find them..."
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.
24 * pregcomp and pregexec -- regsub and regerror are not used in perl
26 * Copyright (c) 1986 by University of Toronto.
27 * Written by Henry Spencer. Not derived from licensed software.
29 * Permission is granted to anyone to use this software for any
30 * purpose on any computer system, and to redistribute it freely,
31 * subject to the following restrictions:
33 * 1. The author is not responsible for the consequences of use of
34 * this software, no matter how awful, even if they arise
37 * 2. The origin of this software must not be misrepresented, either
38 * by explicit claim or by omission.
40 * 3. Altered versions must be plainly marked as such, and must not
41 * be misrepresented as being the original software.
43 **** Alterations to Henry's code are...
45 **** Copyright (c) 1991-1997, Larry Wall
47 **** You may distribute under the terms of either the GNU General Public
48 **** License or the Artistic License, as specified in the README file.
50 * Beware that some of this code is subtly aware of the way operator
51 * precedence is structured in regular expressions. Serious changes in
52 * regular-expression syntax might require a total rethink.
63 static I32 regnarrate = 0;
64 static char* regprogram = 0;
67 /* Current curly descriptor */
68 typedef struct curcur CURCUR;
70 int parenfloor; /* how far back to strip paren data */
71 int cur; /* how many instances of scan we've matched */
72 int min; /* the minimal number of scans to match */
73 int max; /* the maximal number of scans to match */
74 int minmod; /* whether to work our way up or down */
75 char * scan; /* the thing to match */
76 char * next; /* what has to match after it */
77 char * lastloc; /* where we started matching this scan */
78 CURCUR * oldcc; /* current curly before we started this one */
83 typedef I32 CHECKPOINT;
85 static CHECKPOINT regcppush _((I32 parenfloor));
86 static char * regcppop _((void));
92 int retval = savestack_ix;
93 int i = (regsize - parenfloor) * 3;
97 for (p = regsize; p > parenfloor; p--) {
98 SSPUSHPTR(regendp[p]);
99 SSPUSHPTR(regstartp[p]);
103 SSPUSHINT(*reglastparen);
106 SSPUSHINT(SAVEt_REGCONTEXT);
117 assert(i == SAVEt_REGCONTEXT);
119 input = (char *) SSPOPPTR;
120 *reglastparen = SSPOPINT;
122 for (i -= 3; i > 0; i -= 3) {
123 paren = (U32)SSPOPINT;
124 regstartp[paren] = (char *) SSPOPPTR;
125 tmps = (char*)SSPOPPTR;
126 if (paren <= *reglastparen)
127 regendp[paren] = tmps;
129 for (paren = *reglastparen + 1; paren <= regnpar; paren++) {
131 regstartp[paren] = Nullch;
132 regendp[paren] = Nullch;
137 /* After a successful match in WHILEM, we want to restore paren matches
138 * that have been overwritten by a failed match attempt in the process
139 * of reaching this success. We do this by restoring regstartp[i]
140 * wherever regendp[i] has not changed; if OPEN is changed to modify
141 * regendp[], the '== endp' test below should be changed to match.
142 * This corrects the error of:
143 * 0 > length [ "foobar" =~ / ( (foo) | (bar) )* /x ]->[1]
153 assert(i == SAVEt_REGCONTEXT);
155 /* input, lastparen, size */
156 SSPOPPTR; SSPOPINT; SSPOPINT;
157 for (i -= 3; i > 0; i -= 3) {
158 paren = (U32)SSPOPINT;
159 startp = (char *) SSPOPPTR;
160 endp = (char *) SSPOPPTR;
161 if (paren <= *reglastparen && regendp[paren] == endp)
162 regstartp[paren] = startp;
164 assert(savestack_ix == base);
167 #define regcpblow(cp) leave_scope(cp)
170 * pregexec and friends
177 static I32 regmatch _((char *prog));
178 static I32 regrepeat _((char *p, I32 max));
179 static I32 regtry _((regexp *prog, char *startpos));
180 static bool reginclass _((char *p, I32 c));
182 static bool regtainted; /* tainted information used? */
185 - pregexec - match a regexp against a string
188 pregexec(prog, stringarg, strend, strbeg, minend, screamer, safebase)
189 register regexp *prog;
191 register char *strend; /* pointer to null at end of string */
192 char *strbeg; /* real beginning of string */
193 I32 minend; /* end of match must be at least minend after stringarg */
195 I32 safebase; /* no need to remember string in subbase */
199 register char *startpos = stringarg;
201 I32 minlen = 0; /* must match at least this many chars */
202 I32 dontbother = 0; /* how many characters not to try at end */
210 regnarrate = debug & 512;
211 regprogram = prog->program;
215 if (prog == NULL || startpos == NULL) {
216 croak("NULL regexp parameter");
220 if (startpos == strbeg) /* is ^ valid at stringarg? */
223 regprev = stringarg[-1];
224 if (!multiline && regprev == '\n')
225 regprev = '\0'; /* force ^ to NOT match */
228 regprecomp = prog->precomp;
229 /* Check validity of program. */
230 if (UCHARAT(prog->program) != MAGIC) {
231 FAIL("corrupted regexp program");
234 regnpar = prog->nparens;
237 /* If there is a "must appear" string, look for it. */
239 if (prog->regmust != Nullsv &&
240 !(prog->reganch & ROPT_ANCH_GPOS) &&
241 (!(prog->reganch & ROPT_ANCH_BOL)
242 || (multiline && prog->regback >= 0)) )
244 if (stringarg == strbeg && screamer) {
245 if (screamfirst[BmRARE(prog->regmust)] >= 0)
246 s = screaminstr(screamer,prog->regmust);
251 s = fbm_instr((unsigned char*)s, (unsigned char*)strend,
254 ++BmUSEFUL(prog->regmust); /* hooray */
255 goto phooey; /* not present */
257 else if (prog->regback >= 0) {
261 minlen = prog->regback + SvCUR(prog->regmust);
263 else if (!prog->naughty && --BmUSEFUL(prog->regmust) < 0) { /* boo */
264 SvREFCNT_dec(prog->regmust);
265 prog->regmust = Nullsv; /* disable regmust */
270 minlen = SvCUR(prog->regmust);
274 /* Mark beginning of line for ^ . */
277 /* Mark end of line for $ (and such) */
280 /* see how far we have to get to not match where we matched before */
281 regtill = startpos+minend;
283 /* Simplest case: anchored match need be tried only once. */
284 /* [unless only anchor is BOL and multiline is set] */
285 if (prog->reganch & ROPT_ANCH) {
286 if (regtry(prog, startpos))
288 else if (!(prog->reganch & ROPT_ANCH_GPOS) &&
289 (multiline || (prog->reganch & ROPT_IMPLICIT)))
292 dontbother = minlen - 1;
293 strend -= dontbother;
294 /* for multiline we only have to try after newlines */
299 if (s < strend && regtry(prog, s))
307 /* Messy cases: unanchored match. */
308 if (prog->regstart) {
309 if (prog->reganch & ROPT_SKIP) { /* we have /x+whatever/ */
310 /* it must be a one character string */
311 char ch = SvPVX(prog->regstart)[0];
317 while (s < strend && *s == ch)
323 else if (SvTYPE(prog->regstart) == SVt_PVBM) {
324 /* We know what string it must start with. */
325 while ((s = fbm_instr((unsigned char*)s,
326 (unsigned char*)strend, prog->regstart)) != NULL)
333 else { /* Optimized fbm_instr: */
334 c = SvPVX(prog->regstart);
335 while ((s = ninstr(s, strend, c, c + SvCUR(prog->regstart))) != NULL)
345 if (c = prog->regstclass) {
346 I32 doevery = (prog->reganch & ROPT_SKIP) == 0;
349 dontbother = minlen - 1;
350 strend -= dontbother; /* don't bother with what can't match */
352 /* We know what class it must start with. */
357 if (reginclass(c, *s)) {
358 if (tmp && regtry(prog, s))
373 dontbother++,strend--;
374 tmp = (s != startpos) ? UCHARAT(s - 1) : regprev;
375 tmp = ((OP(c) == BOUND ? isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
377 if (tmp == !(OP(c) == BOUND ? isALNUM(*s) : isALNUM_LC(*s))) {
384 if ((minlen || tmp) && regtry(prog,s))
392 dontbother++,strend--;
393 tmp = (s != startpos) ? UCHARAT(s - 1) : regprev;
394 tmp = ((OP(c) == NBOUND ? isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
396 if (tmp == !(OP(c) == NBOUND ? isALNUM(*s) : isALNUM_LC(*s)))
398 else if (regtry(prog, s))
402 if ((minlen || !tmp) && regtry(prog,s))
408 if (tmp && regtry(prog, s))
421 if (isALNUM_LC(*s)) {
422 if (tmp && regtry(prog, s))
435 if (tmp && regtry(prog, s))
448 if (!isALNUM_LC(*s)) {
449 if (tmp && regtry(prog, s))
462 if (tmp && regtry(prog, s))
475 if (isSPACE_LC(*s)) {
476 if (tmp && regtry(prog, s))
489 if (tmp && regtry(prog, s))
502 if (!isSPACE_LC(*s)) {
503 if (tmp && regtry(prog, s))
516 if (tmp && regtry(prog, s))
529 if (tmp && regtry(prog, s))
543 dontbother = minlen - 1;
544 strend -= dontbother;
545 /* We don't know much -- general case. */
549 } while (s++ < strend);
556 strend += dontbother; /* uncheat */
557 prog->subbeg = strbeg;
558 prog->subend = strend;
559 prog->exec_tainted = regtainted;
561 /* make sure $`, $&, $', and $digit will work later */
562 if (strbeg != prog->subbase) {
565 Safefree(prog->subbase);
566 prog->subbase = Nullch;
570 I32 i = strend - startpos + (stringarg - strbeg);
571 s = savepvn(strbeg, i);
572 Safefree(prog->subbase);
574 prog->subbeg = prog->subbase;
575 prog->subend = prog->subbase + i;
576 s = prog->subbase + (stringarg - strbeg);
577 for (i = 0; i <= prog->nparens; i++) {
579 prog->startp[i] = s + (prog->startp[i] - startpos);
580 prog->endp[i] = s + (prog->endp[i] - startpos);
592 - regtry - try match at specific point
594 static I32 /* 0 failure, 1 success */
595 regtry(prog, startpos)
604 regstartp = prog->startp;
605 regendp = prog->endp;
606 reglastparen = &prog->lastparen;
613 for (i = prog->nparens; i >= 0; i--) {
618 if (regmatch(prog->program + 1) && reginput >= regtill) {
619 prog->startp[0] = startpos;
620 prog->endp[0] = reginput;
628 - regmatch - main matching routine
630 * Conceptually the strategy is simple: check to see whether the current
631 * node matches, call self recursively to see whether the rest matches,
632 * and then act accordingly. In practice we make some effort to avoid
633 * recursion, in particular by going through "ordinary" nodes (that don't
634 * need to know whether the rest of the match failed) by a loop instead of
637 /* [lwall] I've hoisted the register declarations to the outer block in order to
638 * maybe save a little bit of pushing and popping on the stack. It also takes
639 * advantage of machines that use a register save mask on subroutine entry.
641 static I32 /* 0 failure, 1 success */
645 register char *scan; /* Current node. */
646 char *next; /* Next node. */
647 register I32 nextchar;
648 register I32 n; /* no or next */
649 register I32 ln; /* len or last */
650 register char *s; /* operand or save */
651 register char *locinput = reginput;
652 register I32 c1, c2; /* case fold search */
655 static int regindent = 0;
659 nextchar = UCHARAT(locinput);
661 while (scan != NULL) {
663 #define sayYES goto yes
664 #define sayNO goto no
665 #define saySAME(x) if (x) goto yes; else goto no
667 SV *prop = sv_newmortal();
669 PerlIO_printf(Perl_debug_log, "%*s%2ld%-8.8s\t<%.10s>\n",
670 regindent*2, "", (long)(scan - regprogram),
671 SvPVX(prop), locinput);
674 #define sayYES return 1
675 #define sayNO return 0
676 #define saySAME(x) return x
680 next = scan + NEXT(scan);
684 next = regnext(scan);
689 if (locinput == regbol
691 : ((nextchar || locinput < regeol) && locinput[-1] == '\n') )
693 /* regtill = regbol; */
698 if (locinput == regbol
700 : ((nextchar || locinput < regeol) && locinput[-1] == '\n') )
706 if (locinput == regbol && regprev == '\n')
710 if (locinput == regbol)
720 if ((nextchar || locinput < regeol) && nextchar != '\n')
725 if ((nextchar || locinput < regeol) && nextchar != '\n')
727 if (regeol - locinput > 1)
731 if (!nextchar && locinput >= regeol)
733 nextchar = UCHARAT(++locinput);
736 if (!nextchar && locinput >= regeol || nextchar == '\n')
738 nextchar = UCHARAT(++locinput);
743 /* Inline the first character, for speed. */
744 if (UCHARAT(s) != nextchar)
746 if (regeol - locinput < ln)
748 if (ln > 1 && memNE(s, locinput, ln))
751 nextchar = UCHARAT(locinput);
759 /* Inline the first character, for speed. */
760 if (UCHARAT(s) != nextchar &&
761 UCHARAT(s) != ((OP(scan) == EXACTF)
762 ? fold : fold_locale)[nextchar])
764 if (regeol - locinput < ln)
766 if (ln > 1 && (OP(scan) == EXACTF
767 ? ibcmp(s, locinput, ln)
768 : ibcmp_locale(s, locinput, ln)))
771 nextchar = UCHARAT(locinput);
776 nextchar = UCHARAT(locinput);
777 if (!reginclass(s, nextchar))
779 if (!nextchar && locinput >= regeol)
781 nextchar = UCHARAT(++locinput);
789 if (!(OP(scan) == ALNUM
790 ? isALNUM(nextchar) : isALNUM_LC(nextchar)))
792 nextchar = UCHARAT(++locinput);
798 if (!nextchar && locinput >= regeol)
800 if (OP(scan) == NALNUM
801 ? isALNUM(nextchar) : isALNUM_LC(nextchar))
803 nextchar = UCHARAT(++locinput);
811 /* was last char in word? */
812 ln = (locinput != regbol) ? UCHARAT(locinput - 1) : regprev;
813 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
815 n = isALNUM(nextchar);
819 n = isALNUM_LC(nextchar);
821 if (((!ln) == (!n)) == (OP(scan) == BOUND || OP(scan) == BOUNDL))
828 if (!nextchar && locinput >= regeol)
830 if (!(OP(scan) == SPACE
831 ? isSPACE(nextchar) : isSPACE_LC(nextchar)))
833 nextchar = UCHARAT(++locinput);
841 if (OP(scan) == SPACE
842 ? isSPACE(nextchar) : isSPACE_LC(nextchar))
844 nextchar = UCHARAT(++locinput);
847 if (!isDIGIT(nextchar))
849 nextchar = UCHARAT(++locinput);
852 if (!nextchar && locinput >= regeol)
854 if (isDIGIT(nextchar))
856 nextchar = UCHARAT(++locinput);
863 n = ARG1(scan); /* which paren pair */
871 /* Inline the first character, for speed. */
872 if (UCHARAT(s) != nextchar &&
874 (UCHARAT(s) != ((OP(scan) == REFF
875 ? fold : fold_locale)[nextchar]))))
878 if (locinput + ln > regeol)
880 if (ln > 1 && (OP(scan) == REF
881 ? memNE(s, locinput, ln)
883 ? ibcmp(s, locinput, ln)
884 : ibcmp_locale(s, locinput, ln))))
887 nextchar = UCHARAT(locinput);
895 n = ARG1(scan); /* which paren pair */
896 regstartp[n] = locinput;
901 n = ARG1(scan); /* which paren pair */
902 regendp[n] = locinput;
903 if (n > *reglastparen)
908 CHECKPOINT cp = savestack_ix;
911 cc.parenfloor = *reglastparen;
915 cc.scan = NEXTOPER(scan) + 4;
920 n = regmatch(PREVOPER(next)); /* start on the WHILEM */
928 * This is really hard to understand, because after we match
929 * what we're trying to match, we must make sure the rest of
930 * the RE is going to match for sure, and to do that we have
931 * to go back UP the parse tree by recursing ever deeper. And
932 * if it fails, we have to reset our parent's current state
933 * that we can try again after backing off.
938 n = cc->cur + 1; /* how many we know we matched */
943 PerlIO_printf(Perl_debug_log, "%*s %ld %lx\n", regindent*2, "",
947 /* If degenerate scan matches "", assume scan done. */
949 if (locinput == cc->lastloc && n >= cc->min) {
952 if (regmatch(cc->next))
959 /* First just match a string of min scans. */
963 cc->lastloc = locinput;
964 if (regmatch(cc->scan))
970 /* Prefer next over scan for minimal matching. */
975 cp = regcppush(cc->parenfloor);
976 if (regmatch(cc->next)) {
978 sayYES; /* All done. */
984 if (n >= cc->max) /* Maximum greed exceeded? */
987 /* Try scanning more and see if it helps. */
990 cc->lastloc = locinput;
991 cp = regcppush(cc->parenfloor);
992 if (regmatch(cc->scan)) {
1001 /* Prefer scan over next for maximal matching. */
1003 if (n < cc->max) { /* More greed allowed? */
1004 cp = regcppush(cc->parenfloor);
1006 cc->lastloc = locinput;
1007 if (regmatch(cc->scan)) {
1011 regcppop(); /* Restore some previous $<digit>s? */
1012 reginput = locinput;
1015 /* Failed deeper matches of scan, so see if this one works. */
1018 if (regmatch(cc->next))
1027 if (OP(next) != BRANCH) /* No choice. */
1028 next = NEXTOPER(scan);/* Avoid recursion. */
1030 int lastparen = *reglastparen;
1032 reginput = locinput;
1033 if (regmatch(NEXTOPER(scan)))
1035 for (n = *reglastparen; n > lastparen; n--)
1046 scan = regnext(scan);
1048 } while (scan != NULL && OP(scan) == BRANCH);
1058 ln = ARG1(scan); /* min to match */
1059 n = ARG2(scan); /* max to match */
1060 scan = NEXTOPER(scan) + 4;
1065 scan = NEXTOPER(scan);
1069 * Lookahead to avoid useless match attempts
1070 * when we know what character comes next.
1074 scan = NEXTOPER(scan);
1076 if (regkind[(U8)OP(next)] == EXACT) {
1077 c1 = UCHARAT(OPERAND(next) + 1);
1078 if (OP(next) == EXACTF)
1080 else if (OP(next) == EXACTFL)
1081 c2 = fold_locale[c1];
1087 reginput = locinput;
1090 if (ln && regrepeat(scan, ln) < ln)
1092 while (n >= ln || (n == 32767 && ln > 0)) { /* ln overflow ? */
1093 /* If it could work, try it. */
1095 UCHARAT(reginput) == c1 ||
1096 UCHARAT(reginput) == c2)
1101 /* Couldn't or didn't -- back up. */
1102 reginput = locinput + ln;
1103 if (regrepeat(scan, 1)) {
1105 reginput = locinput + ln;
1112 n = regrepeat(scan, n);
1113 if (ln < n && regkind[(U8)OP(next)] == EOL &&
1114 (!multiline || OP(next) == SEOL))
1115 ln = n; /* why back off? */
1117 /* If it could work, try it. */
1119 UCHARAT(reginput) == c1 ||
1120 UCHARAT(reginput) == c2)
1125 /* Couldn't or didn't -- back up. */
1127 reginput = locinput + n;
1133 reginput = locinput; /* put where regtry can find it */
1134 sayYES; /* Success! */
1136 reginput = locinput;
1137 scan = NEXTOPER(scan);
1138 if (!regmatch(scan))
1142 reginput = locinput;
1143 scan = NEXTOPER(scan);
1148 PerlIO_printf(PerlIO_stderr(), "%lx %d\n",
1149 (unsigned long)scan, scan[1]);
1150 FAIL("regexp memory corruption");
1156 * We get here only if there's trouble -- normally "case END" is
1157 * the terminating point.
1159 FAIL("corrupted regexp pointers");
1177 - regrepeat - repeatedly match something simple, report how many
1180 * [This routine now assumes that it will only match on things of length 1.
1181 * That was true before, but now we assume scan - reginput is the count,
1182 * rather than incrementing count on every character.]
1189 register char *scan;
1190 register char *opnd;
1192 register char *loceol = regeol;
1195 if (max != 32767 && max < loceol - scan)
1196 loceol = scan + max;
1200 while (scan < loceol && *scan != '\n')
1206 case EXACT: /* length of string is 1 */
1207 c = UCHARAT(++opnd);
1208 while (scan < loceol && UCHARAT(scan) == c)
1211 case EXACTF: /* length of string is 1 */
1212 c = UCHARAT(++opnd);
1213 while (scan < loceol &&
1214 (UCHARAT(scan) == c || UCHARAT(scan) == fold[c]))
1217 case EXACTFL: /* length of string is 1 */
1219 c = UCHARAT(++opnd);
1220 while (scan < loceol &&
1221 (UCHARAT(scan) == c || UCHARAT(scan) == fold_locale[c]))
1225 while (scan < loceol && reginclass(opnd, *scan))
1229 while (scan < loceol && isALNUM(*scan))
1234 while (scan < loceol && isALNUM_LC(*scan))
1238 while (scan < loceol && !isALNUM(*scan))
1243 while (scan < loceol && !isALNUM_LC(*scan))
1247 while (scan < loceol && isSPACE(*scan))
1252 while (scan < loceol && isSPACE_LC(*scan))
1256 while (scan < loceol && !isSPACE(*scan))
1261 while (scan < loceol && !isSPACE_LC(*scan))
1265 while (scan < loceol && isDIGIT(*scan))
1269 while (scan < loceol && !isDIGIT(*scan))
1272 default: /* Called on something of 0 width. */
1273 break; /* So match right here or not at all. */
1276 c = scan - reginput;
1283 - regclass - determine if a character falls into a character class
1295 if (p[1 + (c >> 3)] & (1 << (c & 7)))
1297 else if (flags & ANYOF_FOLD) {
1299 if (flags & ANYOF_LOCALE) {
1301 cf = fold_locale[c];
1305 if (p[1 + (cf >> 3)] & (1 << (cf & 7)))
1309 if (!match && (flags & ANYOF_ISA)) {
1312 if (((flags & ANYOF_ALNUML) && isALNUM_LC(c)) ||
1313 ((flags & ANYOF_NALNUML) && !isALNUM_LC(c)) ||
1314 ((flags & ANYOF_SPACEL) && isSPACE_LC(c)) ||
1315 ((flags & ANYOF_NSPACEL) && !isSPACE_LC(c)))
1321 return match ^ ((flags & ANYOF_INVERT) != 0);
1325 - regnext - dig the "next" pointer out of a node
1327 * [Note, when REGALIGN is defined there are two places in regmatch()
1328 * that bypass this code for speed.]
1334 register I32 offset;