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));
93 int retval = savestack_ix;
94 int i = (regsize - parenfloor) * 3;
98 for (p = regsize; p > parenfloor; p--) {
99 SSPUSHPTR(regendp[p]);
100 SSPUSHPTR(regstartp[p]);
104 SSPUSHINT(*reglastparen);
107 SSPUSHINT(SAVEt_REGCONTEXT);
119 assert(i == SAVEt_REGCONTEXT);
121 input = (char *) SSPOPPTR;
122 *reglastparen = SSPOPINT;
124 for (i -= 3; i > 0; i -= 3) {
125 paren = (U32)SSPOPINT;
126 regstartp[paren] = (char *) SSPOPPTR;
127 tmps = (char*)SSPOPPTR;
128 if (paren <= *reglastparen)
129 regendp[paren] = tmps;
131 for (paren = *reglastparen + 1; paren <= regnpar; paren++) {
133 regstartp[paren] = Nullch;
134 regendp[paren] = Nullch;
139 /* After a successful match in WHILEM, we want to restore paren matches
140 * that have been overwritten by a failed match attempt in the process
141 * of reaching this success. We do this by restoring regstartp[i]
142 * wherever regendp[i] has not changed; if OPEN is changed to modify
143 * regendp[], the '== endp' test below should be changed to match.
144 * This corrects the error of:
145 * 0 > length [ "foobar" =~ / ( (foo) | (bar) )* /x ]->[1]
155 assert(i == SAVEt_REGCONTEXT);
157 /* input, lastparen, size */
158 SSPOPPTR; SSPOPINT; SSPOPINT;
159 for (i -= 3; i > 0; i -= 3) {
160 paren = (U32)SSPOPINT;
161 startp = (char *) SSPOPPTR;
162 endp = (char *) SSPOPPTR;
163 if (paren <= *reglastparen && regendp[paren] == endp)
164 regstartp[paren] = startp;
168 #define regcpblow(cp) leave_scope(cp)
171 * pregexec and friends
178 static I32 regmatch _((char *prog));
179 static I32 regrepeat _((char *p, I32 max));
180 static I32 regtry _((regexp *prog, char *startpos));
181 static bool reginclass _((char *p, I32 c));
183 static bool regtainted; /* tainted information used? */
186 - pregexec - match a regexp against a string
189 pregexec(prog, stringarg, strend, strbeg, minend, screamer, safebase)
190 register regexp *prog;
192 register char *strend; /* pointer to null at end of string */
193 char *strbeg; /* real beginning of string */
194 I32 minend; /* end of match must be at least minend after stringarg */
196 I32 safebase; /* no need to remember string in subbase */
200 register char *startpos = stringarg;
202 I32 minlen = 0; /* must match at least this many chars */
203 I32 dontbother = 0; /* how many characters not to try at end */
211 regnarrate = debug & 512;
212 regprogram = prog->program;
216 if (prog == NULL || startpos == NULL) {
217 croak("NULL regexp parameter");
221 if (startpos == strbeg) /* is ^ valid at stringarg? */
224 regprev = stringarg[-1];
225 if (!multiline && regprev == '\n')
226 regprev = '\0'; /* force ^ to NOT match */
229 regprecomp = prog->precomp;
230 /* Check validity of program. */
231 if (UCHARAT(prog->program) != MAGIC) {
232 FAIL("corrupted regexp program");
235 regnpar = prog->nparens;
238 /* If there is a "must appear" string, look for it. */
240 if (prog->regmust != Nullsv &&
241 !(prog->reganch & ROPT_ANCH_GPOS) &&
242 (!(prog->reganch & ROPT_ANCH_BOL)
243 || (multiline && prog->regback >= 0)) )
245 if (stringarg == strbeg && screamer) {
246 if (screamfirst[BmRARE(prog->regmust)] >= 0)
247 s = screaminstr(screamer,prog->regmust);
252 s = fbm_instr((unsigned char*)s, (unsigned char*)strend,
255 ++BmUSEFUL(prog->regmust); /* hooray */
256 goto phooey; /* not present */
258 else if (prog->regback >= 0) {
262 minlen = prog->regback + SvCUR(prog->regmust);
264 else if (!prog->naughty && --BmUSEFUL(prog->regmust) < 0) { /* boo */
265 SvREFCNT_dec(prog->regmust);
266 prog->regmust = Nullsv; /* disable regmust */
271 minlen = SvCUR(prog->regmust);
275 /* Mark beginning of line for ^ . */
278 /* Mark end of line for $ (and such) */
281 /* see how far we have to get to not match where we matched before */
282 regtill = startpos+minend;
284 /* Simplest case: anchored match need be tried only once. */
285 /* [unless only anchor is BOL and multiline is set] */
286 if (prog->reganch & ROPT_ANCH) {
287 if (regtry(prog, startpos))
289 else if (!(prog->reganch & ROPT_ANCH_GPOS) &&
290 (multiline || (prog->reganch & ROPT_IMPLICIT)))
293 dontbother = minlen - 1;
294 strend -= dontbother;
295 /* for multiline we only have to try after newlines */
300 if (s < strend && regtry(prog, s))
308 /* Messy cases: unanchored match. */
309 if (prog->regstart) {
310 if (prog->reganch & ROPT_SKIP) { /* we have /x+whatever/ */
311 /* it must be a one character string */
312 char ch = SvPVX(prog->regstart)[0];
318 while (s < strend && *s == ch)
324 else if (SvTYPE(prog->regstart) == SVt_PVBM) {
325 /* We know what string it must start with. */
326 while ((s = fbm_instr((unsigned char*)s,
327 (unsigned char*)strend, prog->regstart)) != NULL)
334 else { /* Optimized fbm_instr: */
335 c = SvPVX(prog->regstart);
336 while ((s = ninstr(s, strend, c, c + SvCUR(prog->regstart))) != NULL)
346 if (c = prog->regstclass) {
347 I32 doevery = (prog->reganch & ROPT_SKIP) == 0;
350 dontbother = minlen - 1;
351 strend -= dontbother; /* don't bother with what can't match */
353 /* We know what class it must start with. */
358 if (reginclass(c, *s)) {
359 if (tmp && regtry(prog, s))
374 dontbother++,strend--;
375 tmp = (s != startpos) ? UCHARAT(s - 1) : regprev;
376 tmp = ((OP(c) == BOUND ? isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
378 if (tmp == !(OP(c) == BOUND ? isALNUM(*s) : isALNUM_LC(*s))) {
385 if ((minlen || tmp) && regtry(prog,s))
393 dontbother++,strend--;
394 tmp = (s != startpos) ? UCHARAT(s - 1) : regprev;
395 tmp = ((OP(c) == NBOUND ? isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
397 if (tmp == !(OP(c) == NBOUND ? isALNUM(*s) : isALNUM_LC(*s)))
399 else if (regtry(prog, s))
403 if ((minlen || !tmp) && regtry(prog,s))
409 if (tmp && regtry(prog, s))
422 if (isALNUM_LC(*s)) {
423 if (tmp && regtry(prog, s))
436 if (tmp && regtry(prog, s))
449 if (!isALNUM_LC(*s)) {
450 if (tmp && regtry(prog, s))
463 if (tmp && regtry(prog, s))
476 if (isSPACE_LC(*s)) {
477 if (tmp && regtry(prog, s))
490 if (tmp && regtry(prog, s))
503 if (!isSPACE_LC(*s)) {
504 if (tmp && regtry(prog, s))
517 if (tmp && regtry(prog, s))
530 if (tmp && regtry(prog, s))
544 dontbother = minlen - 1;
545 strend -= dontbother;
546 /* We don't know much -- general case. */
550 } while (s++ < strend);
557 strend += dontbother; /* uncheat */
558 prog->subbeg = strbeg;
559 prog->subend = strend;
560 prog->exec_tainted = regtainted;
562 /* make sure $`, $&, $', and $digit will work later */
563 if (strbeg != prog->subbase) {
566 Safefree(prog->subbase);
567 prog->subbase = Nullch;
571 I32 i = strend - startpos + (stringarg - strbeg);
572 s = savepvn(strbeg, i);
573 Safefree(prog->subbase);
575 prog->subbeg = prog->subbase;
576 prog->subend = prog->subbase + i;
577 s = prog->subbase + (stringarg - strbeg);
578 for (i = 0; i <= prog->nparens; i++) {
580 prog->startp[i] = s + (prog->startp[i] - startpos);
581 prog->endp[i] = s + (prog->endp[i] - startpos);
593 - regtry - try match at specific point
595 static I32 /* 0 failure, 1 success */
596 regtry(prog, startpos)
605 regstartp = prog->startp;
606 regendp = prog->endp;
607 reglastparen = &prog->lastparen;
614 for (i = prog->nparens; i >= 0; i--) {
619 if (regmatch(prog->program + 1) && reginput >= regtill) {
620 prog->startp[0] = startpos;
621 prog->endp[0] = reginput;
629 - regmatch - main matching routine
631 * Conceptually the strategy is simple: check to see whether the current
632 * node matches, call self recursively to see whether the rest matches,
633 * and then act accordingly. In practice we make some effort to avoid
634 * recursion, in particular by going through "ordinary" nodes (that don't
635 * need to know whether the rest of the match failed) by a loop instead of
638 /* [lwall] I've hoisted the register declarations to the outer block in order to
639 * maybe save a little bit of pushing and popping on the stack. It also takes
640 * advantage of machines that use a register save mask on subroutine entry.
642 static I32 /* 0 failure, 1 success */
646 register char *scan; /* Current node. */
647 char *next; /* Next node. */
648 register I32 nextchar;
649 register I32 n; /* no or next */
650 register I32 ln; /* len or last */
651 register char *s; /* operand or save */
652 register char *locinput = reginput;
653 register I32 c1, c2; /* case fold search */
656 static int regindent = 0;
660 nextchar = UCHARAT(locinput);
662 while (scan != NULL) {
664 #define sayYES goto yes
665 #define sayNO goto no
666 #define saySAME(x) if (x) goto yes; else goto no
668 SV *prop = sv_newmortal();
670 PerlIO_printf(Perl_debug_log, "%*s%2d%-8.8s\t<%.10s>\n",
671 regindent*2, "", scan - regprogram,
672 SvPVX(prop), locinput);
675 #define sayYES return 1
676 #define sayNO return 0
677 #define saySAME(x) return x
681 next = scan + NEXT(scan);
685 next = regnext(scan);
690 if (locinput == regbol
692 : ((nextchar || locinput < regeol) && locinput[-1] == '\n') )
694 /* regtill = regbol; */
699 if (locinput == regbol
701 : ((nextchar || locinput < regeol) && locinput[-1] == '\n') )
707 if (locinput == regbol && regprev == '\n')
711 if (locinput == regbol)
721 if ((nextchar || locinput < regeol) && nextchar != '\n')
726 if ((nextchar || locinput < regeol) && nextchar != '\n')
728 if (regeol - locinput > 1)
732 if (!nextchar && locinput >= regeol)
734 nextchar = UCHARAT(++locinput);
737 if (!nextchar && locinput >= regeol || nextchar == '\n')
739 nextchar = UCHARAT(++locinput);
744 /* Inline the first character, for speed. */
745 if (UCHARAT(s) != nextchar)
747 if (regeol - locinput < ln)
749 if (ln > 1 && memNE(s, locinput, ln))
752 nextchar = UCHARAT(locinput);
760 /* Inline the first character, for speed. */
761 if (UCHARAT(s) != nextchar &&
762 UCHARAT(s) != ((OP(scan) == EXACTF)
763 ? fold : fold_locale)[nextchar])
765 if (regeol - locinput < ln)
767 if (ln > 1 && (OP(scan) == EXACTF
768 ? ibcmp(s, locinput, ln)
769 : ibcmp_locale(s, locinput, ln)))
772 nextchar = UCHARAT(locinput);
777 nextchar = UCHARAT(locinput);
778 if (!reginclass(s, nextchar))
780 if (!nextchar && locinput >= regeol)
782 nextchar = UCHARAT(++locinput);
790 if (!(OP(scan) == ALNUM
791 ? isALNUM(nextchar) : isALNUM_LC(nextchar)))
793 nextchar = UCHARAT(++locinput);
799 if (!nextchar && locinput >= regeol)
801 if (OP(scan) == NALNUM
802 ? isALNUM(nextchar) : isALNUM_LC(nextchar))
804 nextchar = UCHARAT(++locinput);
812 /* was last char in word? */
813 ln = (locinput != regbol) ? UCHARAT(locinput - 1) : regprev;
814 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
816 n = isALNUM(nextchar);
820 n = isALNUM_LC(nextchar);
822 if (((!ln) == (!n)) == (OP(scan) == BOUND || OP(scan) == BOUNDL))
829 if (!nextchar && locinput >= regeol)
831 if (!(OP(scan) == SPACE
832 ? isSPACE(nextchar) : isSPACE_LC(nextchar)))
834 nextchar = UCHARAT(++locinput);
842 if (OP(scan) == SPACE
843 ? isSPACE(nextchar) : isSPACE_LC(nextchar))
845 nextchar = UCHARAT(++locinput);
848 if (!isDIGIT(nextchar))
850 nextchar = UCHARAT(++locinput);
853 if (!nextchar && locinput >= regeol)
855 if (isDIGIT(nextchar))
857 nextchar = UCHARAT(++locinput);
864 n = ARG1(scan); /* which paren pair */
872 /* Inline the first character, for speed. */
873 if (UCHARAT(s) != nextchar &&
875 (UCHARAT(s) != ((OP(scan) == REFF
876 ? fold : fold_locale)[nextchar]))))
879 if (locinput + ln > regeol)
881 if (ln > 1 && (OP(scan) == REF
882 ? memNE(s, locinput, ln)
884 ? ibcmp(s, locinput, ln)
885 : ibcmp_locale(s, locinput, ln))))
888 nextchar = UCHARAT(locinput);
896 n = ARG1(scan); /* which paren pair */
897 regstartp[n] = locinput;
902 n = ARG1(scan); /* which paren pair */
903 regendp[n] = locinput;
904 if (n > *reglastparen)
910 CHECKPOINT cp = savestack_ix;
913 cc.parenfloor = *reglastparen;
917 cc.scan = NEXTOPER(scan) + 4;
922 n = regmatch(PREVOPER(next)); /* start on the WHILEM */
930 * This is really hard to understand, because after we match
931 * what we're trying to match, we must make sure the rest of
932 * the RE is going to match for sure, and to do that we have
933 * to go back UP the parse tree by recursing ever deeper. And
934 * if it fails, we have to reset our parent's current state
935 * that we can try again after backing off.
940 n = cc->cur + 1; /* how many we know we matched */
945 PerlIO_printf(Perl_debug_log, "%*s %ld %lx\n", regindent*2, "",
949 /* If degenerate scan matches "", assume scan done. */
951 if (locinput == cc->lastloc && n >= cc->min) {
954 if (regmatch(cc->next))
961 /* First just match a string of min scans. */
965 cc->lastloc = locinput;
966 if (regmatch(cc->scan))
972 /* Prefer next over scan for minimal matching. */
977 cp = regcppush(cc->parenfloor);
978 if (regmatch(cc->next)) {
980 sayYES; /* All done. */
986 if (n >= cc->max) /* Maximum greed exceeded? */
989 /* Try scanning more and see if it helps. */
992 cc->lastloc = locinput;
993 cp = regcppush(cc->parenfloor);
994 if (regmatch(cc->scan)) {
1003 /* Prefer scan over next for maximal matching. */
1005 if (n < cc->max) { /* More greed allowed? */
1006 cp = regcppush(cc->parenfloor);
1008 cc->lastloc = locinput;
1009 if (regmatch(cc->scan)) {
1013 regcppop(); /* Restore some previous $<digit>s? */
1014 reginput = locinput;
1017 /* Failed deeper matches of scan, so see if this one works. */
1020 if (regmatch(cc->next))
1029 if (OP(next) != BRANCH) /* No choice. */
1030 next = NEXTOPER(scan);/* Avoid recursion. */
1032 int lastparen = *reglastparen;
1034 reginput = locinput;
1035 if (regmatch(NEXTOPER(scan)))
1037 for (n = *reglastparen; n > lastparen; n--)
1048 scan = regnext(scan);
1050 } while (scan != NULL && OP(scan) == BRANCH);
1060 ln = ARG1(scan); /* min to match */
1061 n = ARG2(scan); /* max to match */
1062 scan = NEXTOPER(scan) + 4;
1067 scan = NEXTOPER(scan);
1071 * Lookahead to avoid useless match attempts
1072 * when we know what character comes next.
1076 scan = NEXTOPER(scan);
1078 if (regkind[(U8)OP(next)] == EXACT) {
1079 c1 = UCHARAT(OPERAND(next) + 1);
1080 if (OP(next) == EXACTF)
1082 else if (OP(next) == EXACTFL)
1083 c2 = fold_locale[c1];
1089 reginput = locinput;
1092 if (ln && regrepeat(scan, ln) < ln)
1094 while (n >= ln || (n == 32767 && ln > 0)) { /* ln overflow ? */
1095 /* If it could work, try it. */
1097 UCHARAT(reginput) == c1 ||
1098 UCHARAT(reginput) == c2)
1103 /* Couldn't or didn't -- back up. */
1104 reginput = locinput + ln;
1105 if (regrepeat(scan, 1)) {
1107 reginput = locinput + ln;
1114 n = regrepeat(scan, n);
1115 if (ln < n && regkind[(U8)OP(next)] == EOL &&
1116 (!multiline || OP(next) == SEOL))
1117 ln = n; /* why back off? */
1119 /* If it could work, try it. */
1121 UCHARAT(reginput) == c1 ||
1122 UCHARAT(reginput) == c2)
1127 /* Couldn't or didn't -- back up. */
1129 reginput = locinput + n;
1135 reginput = locinput; /* put where regtry can find it */
1136 sayYES; /* Success! */
1138 reginput = locinput;
1139 scan = NEXTOPER(scan);
1140 if (!regmatch(scan))
1144 reginput = locinput;
1145 scan = NEXTOPER(scan);
1150 PerlIO_printf(PerlIO_stderr(), "%lx %d\n",
1151 (unsigned long)scan, scan[1]);
1152 FAIL("regexp memory corruption");
1158 * We get here only if there's trouble -- normally "case END" is
1159 * the terminating point.
1161 FAIL("corrupted regexp pointers");
1179 - regrepeat - repeatedly match something simple, report how many
1182 * [This routine now assumes that it will only match on things of length 1.
1183 * That was true before, but now we assume scan - reginput is the count,
1184 * rather than incrementing count on every character.]
1191 register char *scan;
1192 register char *opnd;
1194 register char *loceol = regeol;
1197 if (max != 32767 && max < loceol - scan)
1198 loceol = scan + max;
1202 while (scan < loceol && *scan != '\n')
1208 case EXACT: /* length of string is 1 */
1209 c = UCHARAT(++opnd);
1210 while (scan < loceol && UCHARAT(scan) == c)
1213 case EXACTF: /* length of string is 1 */
1214 c = UCHARAT(++opnd);
1215 while (scan < loceol &&
1216 (UCHARAT(scan) == c || UCHARAT(scan) == fold[c]))
1219 case EXACTFL: /* length of string is 1 */
1221 c = UCHARAT(++opnd);
1222 while (scan < loceol &&
1223 (UCHARAT(scan) == c || UCHARAT(scan) == fold_locale[c]))
1227 while (scan < loceol && reginclass(opnd, *scan))
1231 while (scan < loceol && isALNUM(*scan))
1236 while (scan < loceol && isALNUM_LC(*scan))
1240 while (scan < loceol && !isALNUM(*scan))
1245 while (scan < loceol && !isALNUM_LC(*scan))
1249 while (scan < loceol && isSPACE(*scan))
1254 while (scan < loceol && isSPACE_LC(*scan))
1258 while (scan < loceol && !isSPACE(*scan))
1263 while (scan < loceol && !isSPACE_LC(*scan))
1267 while (scan < loceol && isDIGIT(*scan))
1271 while (scan < loceol && !isDIGIT(*scan))
1274 default: /* Called on something of 0 width. */
1275 break; /* So match right here or not at all. */
1278 c = scan - reginput;
1285 - regclass - determine if a character falls into a character class
1297 if (p[1 + (c >> 3)] & (1 << (c & 7)))
1299 else if (flags & ANYOF_FOLD) {
1301 if (flags & ANYOF_LOCALE) {
1303 cf = fold_locale[c];
1307 if (p[1 + (cf >> 3)] & (1 << (cf & 7)))
1311 if (!match && (flags & ANYOF_ISA)) {
1314 if (((flags & ANYOF_ALNUML) && isALNUM_LC(c)) ||
1315 ((flags & ANYOF_NALNUML) && !isALNUM_LC(c)) ||
1316 ((flags & ANYOF_SPACEL) && isSPACE_LC(c)) ||
1317 ((flags & ANYOF_NSPACEL) && !isSPACE_LC(c)))
1323 return match ^ ((flags & ANYOF_INVERT) != 0);
1327 - regnext - dig the "next" pointer out of a node
1329 * [Note, when REGALIGN is defined there are two places in regmatch()
1330 * that bypass this code for speed.]
1336 register I32 offset;