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]
152 assert(i == SAVEt_REGCONTEXT);
154 /* input, lastparen, size */
155 SSPOPPTR; SSPOPINT; SSPOPINT;
156 for (i -= 3; i > 0; i -= 3) {
157 paren = (U32)SSPOPINT;
158 startp = (char *) SSPOPPTR;
159 endp = (char *) SSPOPPTR;
160 if (paren <= *reglastparen && regendp[paren] == endp)
161 regstartp[paren] = startp;
165 #define regcpblow(cp) leave_scope(cp)
168 * pregexec and friends
175 static I32 regmatch _((char *prog));
176 static I32 regrepeat _((char *p, I32 max));
177 static I32 regtry _((regexp *prog, char *startpos));
178 static bool reginclass _((char *p, I32 c));
180 static bool regtainted; /* tainted information used? */
183 - pregexec - match a regexp against a string
186 pregexec(prog, stringarg, strend, strbeg, minend, screamer, safebase)
187 register regexp *prog;
189 register char *strend; /* pointer to null at end of string */
190 char *strbeg; /* real beginning of string */
191 I32 minend; /* end of match must be at least minend after stringarg */
193 I32 safebase; /* no need to remember string in subbase */
197 register char *startpos = stringarg;
199 I32 minlen = 0; /* must match at least this many chars */
200 I32 dontbother = 0; /* how many characters not to try at end */
208 regnarrate = debug & 512;
209 regprogram = prog->program;
213 if (prog == NULL || startpos == NULL) {
214 croak("NULL regexp parameter");
218 if (startpos == strbeg) /* is ^ valid at stringarg? */
221 regprev = stringarg[-1];
222 if (!multiline && regprev == '\n')
223 regprev = '\0'; /* force ^ to NOT match */
226 regprecomp = prog->precomp;
227 /* Check validity of program. */
228 if (UCHARAT(prog->program) != MAGIC) {
229 FAIL("corrupted regexp program");
232 regnpar = prog->nparens;
235 /* If there is a "must appear" string, look for it. */
237 if (prog->regmust != Nullsv &&
238 !(prog->reganch & ROPT_ANCH_GPOS) &&
239 (!(prog->reganch & ROPT_ANCH_BOL)
240 || (multiline && prog->regback >= 0)) )
242 if (stringarg == strbeg && screamer) {
243 if (screamfirst[BmRARE(prog->regmust)] >= 0)
244 s = screaminstr(screamer,prog->regmust);
249 s = fbm_instr((unsigned char*)s, (unsigned char*)strend,
252 ++BmUSEFUL(prog->regmust); /* hooray */
253 goto phooey; /* not present */
255 else if (prog->regback >= 0) {
259 minlen = prog->regback + SvCUR(prog->regmust);
261 else if (!prog->naughty && --BmUSEFUL(prog->regmust) < 0) { /* boo */
262 SvREFCNT_dec(prog->regmust);
263 prog->regmust = Nullsv; /* disable regmust */
268 minlen = SvCUR(prog->regmust);
272 /* Mark beginning of line for ^ . */
275 /* Mark end of line for $ (and such) */
278 /* see how far we have to get to not match where we matched before */
279 regtill = startpos+minend;
281 /* Simplest case: anchored match need be tried only once. */
282 /* [unless only anchor is BOL and multiline is set] */
283 if (prog->reganch & ROPT_ANCH) {
284 if (regtry(prog, startpos))
286 else if (!(prog->reganch & ROPT_ANCH_GPOS) &&
287 (multiline || (prog->reganch & ROPT_IMPLICIT)))
290 dontbother = minlen - 1;
291 strend -= dontbother;
292 /* for multiline we only have to try after newlines */
297 if (s < strend && regtry(prog, s))
305 /* Messy cases: unanchored match. */
306 if (prog->regstart) {
307 if (prog->reganch & ROPT_SKIP) { /* we have /x+whatever/ */
308 /* it must be a one character string */
309 char ch = SvPVX(prog->regstart)[0];
315 while (s < strend && *s == ch)
321 else if (SvTYPE(prog->regstart) == SVt_PVBM) {
322 /* We know what string it must start with. */
323 while ((s = fbm_instr((unsigned char*)s,
324 (unsigned char*)strend, prog->regstart)) != NULL)
331 else { /* Optimized fbm_instr: */
332 c = SvPVX(prog->regstart);
333 while ((s = ninstr(s, strend, c, c + SvCUR(prog->regstart))) != NULL)
343 if (c = prog->regstclass) {
344 I32 doevery = (prog->reganch & ROPT_SKIP) == 0;
347 dontbother = minlen - 1;
348 strend -= dontbother; /* don't bother with what can't match */
350 /* We know what class it must start with. */
355 if (reginclass(c, *s)) {
356 if (tmp && regtry(prog, s))
371 dontbother++,strend--;
372 tmp = (s != startpos) ? UCHARAT(s - 1) : regprev;
373 tmp = ((OP(c) == BOUND ? isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
375 if (tmp == !(OP(c) == BOUND ? isALNUM(*s) : isALNUM_LC(*s))) {
382 if ((minlen || tmp) && regtry(prog,s))
390 dontbother++,strend--;
391 tmp = (s != startpos) ? UCHARAT(s - 1) : regprev;
392 tmp = ((OP(c) == NBOUND ? isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
394 if (tmp == !(OP(c) == NBOUND ? isALNUM(*s) : isALNUM_LC(*s)))
396 else if (regtry(prog, s))
400 if ((minlen || !tmp) && regtry(prog,s))
406 if (tmp && regtry(prog, s))
419 if (isALNUM_LC(*s)) {
420 if (tmp && regtry(prog, s))
433 if (tmp && regtry(prog, s))
446 if (!isALNUM_LC(*s)) {
447 if (tmp && regtry(prog, s))
460 if (tmp && regtry(prog, s))
473 if (isSPACE_LC(*s)) {
474 if (tmp && regtry(prog, s))
487 if (tmp && regtry(prog, s))
500 if (!isSPACE_LC(*s)) {
501 if (tmp && regtry(prog, s))
514 if (tmp && regtry(prog, s))
527 if (tmp && regtry(prog, s))
541 dontbother = minlen - 1;
542 strend -= dontbother;
543 /* We don't know much -- general case. */
547 } while (s++ < strend);
554 strend += dontbother; /* uncheat */
555 prog->subbeg = strbeg;
556 prog->subend = strend;
557 prog->exec_tainted = regtainted;
559 /* make sure $`, $&, $', and $digit will work later */
560 if (strbeg != prog->subbase) {
563 Safefree(prog->subbase);
564 prog->subbase = Nullch;
568 I32 i = strend - startpos + (stringarg - strbeg);
569 s = savepvn(strbeg, i);
570 Safefree(prog->subbase);
572 prog->subbeg = prog->subbase;
573 prog->subend = prog->subbase + i;
574 s = prog->subbase + (stringarg - strbeg);
575 for (i = 0; i <= prog->nparens; i++) {
577 prog->startp[i] = s + (prog->startp[i] - startpos);
578 prog->endp[i] = s + (prog->endp[i] - startpos);
590 - regtry - try match at specific point
592 static I32 /* 0 failure, 1 success */
593 regtry(prog, startpos)
602 regstartp = prog->startp;
603 regendp = prog->endp;
604 reglastparen = &prog->lastparen;
611 for (i = prog->nparens; i >= 0; i--) {
616 if (regmatch(prog->program + 1) && reginput >= regtill) {
617 prog->startp[0] = startpos;
618 prog->endp[0] = reginput;
626 - regmatch - main matching routine
628 * Conceptually the strategy is simple: check to see whether the current
629 * node matches, call self recursively to see whether the rest matches,
630 * and then act accordingly. In practice we make some effort to avoid
631 * recursion, in particular by going through "ordinary" nodes (that don't
632 * need to know whether the rest of the match failed) by a loop instead of
635 /* [lwall] I've hoisted the register declarations to the outer block in order to
636 * maybe save a little bit of pushing and popping on the stack. It also takes
637 * advantage of machines that use a register save mask on subroutine entry.
639 static I32 /* 0 failure, 1 success */
643 register char *scan; /* Current node. */
644 char *next; /* Next node. */
645 register I32 nextchar;
646 register I32 n; /* no or next */
647 register I32 ln; /* len or last */
648 register char *s; /* operand or save */
649 register char *locinput = reginput;
650 register I32 c1, c2; /* case fold search */
653 static int regindent = 0;
657 nextchar = UCHARAT(locinput);
659 while (scan != NULL) {
661 #define sayYES goto yes
662 #define sayNO goto no
663 #define saySAME(x) if (x) goto yes; else goto no
665 SV *prop = sv_newmortal();
667 PerlIO_printf(Perl_debug_log, "%*s%2d%-8.8s\t<%.10s>\n",
668 regindent*2, "", scan - regprogram,
669 SvPVX(prop), locinput);
672 #define sayYES return 1
673 #define sayNO return 0
674 #define saySAME(x) return x
678 next = scan + NEXT(scan);
682 next = regnext(scan);
687 if (locinput == regbol
689 : ((nextchar || locinput < regeol) && locinput[-1] == '\n') )
691 /* regtill = regbol; */
696 if (locinput == regbol
698 : ((nextchar || locinput < regeol) && locinput[-1] == '\n') )
704 if (locinput == regbol && regprev == '\n')
708 if (locinput == regbol)
718 if ((nextchar || locinput < regeol) && nextchar != '\n')
723 if ((nextchar || locinput < regeol) && nextchar != '\n')
725 if (regeol - locinput > 1)
729 if (!nextchar && locinput >= regeol)
731 nextchar = UCHARAT(++locinput);
734 if (!nextchar && locinput >= regeol || nextchar == '\n')
736 nextchar = UCHARAT(++locinput);
741 /* Inline the first character, for speed. */
742 if (UCHARAT(s) != nextchar)
744 if (regeol - locinput < ln)
746 if (ln > 1 && memNE(s, locinput, ln))
749 nextchar = UCHARAT(locinput);
757 /* Inline the first character, for speed. */
758 if (UCHARAT(s) != nextchar &&
759 UCHARAT(s) != ((OP(scan) == EXACTF)
760 ? fold : fold_locale)[nextchar])
762 if (regeol - locinput < ln)
764 if (ln > 1 && (OP(scan) == EXACTF
765 ? ibcmp(s, locinput, ln)
766 : ibcmp_locale(s, locinput, ln)))
769 nextchar = UCHARAT(locinput);
774 nextchar = UCHARAT(locinput);
775 if (!reginclass(s, nextchar))
777 if (!nextchar && locinput >= regeol)
779 nextchar = UCHARAT(++locinput);
787 if (!(OP(scan) == ALNUM
788 ? isALNUM(nextchar) : isALNUM_LC(nextchar)))
790 nextchar = UCHARAT(++locinput);
796 if (!nextchar && locinput >= regeol)
798 if (OP(scan) == NALNUM
799 ? isALNUM(nextchar) : isALNUM_LC(nextchar))
801 nextchar = UCHARAT(++locinput);
809 /* was last char in word? */
810 ln = (locinput != regbol) ? UCHARAT(locinput - 1) : regprev;
811 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
813 n = isALNUM(nextchar);
817 n = isALNUM_LC(nextchar);
819 if (((!ln) == (!n)) == (OP(scan) == BOUND || OP(scan) == BOUNDL))
826 if (!nextchar && locinput >= regeol)
828 if (!(OP(scan) == SPACE
829 ? isSPACE(nextchar) : isSPACE_LC(nextchar)))
831 nextchar = UCHARAT(++locinput);
839 if (OP(scan) == SPACE
840 ? isSPACE(nextchar) : isSPACE_LC(nextchar))
842 nextchar = UCHARAT(++locinput);
845 if (!isDIGIT(nextchar))
847 nextchar = UCHARAT(++locinput);
850 if (!nextchar && locinput >= regeol)
852 if (isDIGIT(nextchar))
854 nextchar = UCHARAT(++locinput);
861 n = ARG1(scan); /* which paren pair */
869 /* Inline the first character, for speed. */
870 if (UCHARAT(s) != nextchar &&
872 (UCHARAT(s) != ((OP(scan) == REFF
873 ? fold : fold_locale)[nextchar]))))
876 if (locinput + ln > regeol)
878 if (ln > 1 && (OP(scan) == REF
879 ? memNE(s, locinput, ln)
881 ? ibcmp(s, locinput, ln)
882 : ibcmp_locale(s, locinput, ln))))
885 nextchar = UCHARAT(locinput);
893 n = ARG1(scan); /* which paren pair */
894 regstartp[n] = locinput;
899 n = ARG1(scan); /* which paren pair */
900 regendp[n] = locinput;
901 if (n > *reglastparen)
906 CHECKPOINT cp = savestack_ix;
909 cc.parenfloor = *reglastparen;
913 cc.scan = NEXTOPER(scan) + 4;
918 n = regmatch(PREVOPER(next)); /* start on the WHILEM */
926 * This is really hard to understand, because after we match
927 * what we're trying to match, we must make sure the rest of
928 * the RE is going to match for sure, and to do that we have
929 * to go back UP the parse tree by recursing ever deeper. And
930 * if it fails, we have to reset our parent's current state
931 * that we can try again after backing off.
936 n = cc->cur + 1; /* how many we know we matched */
941 PerlIO_printf(Perl_debug_log, "%*s %ld %lx\n", regindent*2, "",
945 /* If degenerate scan matches "", assume scan done. */
947 if (locinput == cc->lastloc && n >= cc->min) {
950 if (regmatch(cc->next))
957 /* First just match a string of min scans. */
961 cc->lastloc = locinput;
962 if (regmatch(cc->scan))
968 /* Prefer next over scan for minimal matching. */
973 cp = regcppush(cc->parenfloor);
974 if (regmatch(cc->next)) {
976 sayYES; /* All done. */
982 if (n >= cc->max) /* Maximum greed exceeded? */
985 /* Try scanning more and see if it helps. */
988 cc->lastloc = locinput;
989 cp = regcppush(cc->parenfloor);
990 if (regmatch(cc->scan)) {
999 /* Prefer scan over next for maximal matching. */
1001 if (n < cc->max) { /* More greed allowed? */
1002 cp = regcppush(cc->parenfloor);
1004 cc->lastloc = locinput;
1005 if (regmatch(cc->scan)) {
1009 regcppop(); /* Restore some previous $<digit>s? */
1010 reginput = locinput;
1013 /* Failed deeper matches of scan, so see if this one works. */
1016 if (regmatch(cc->next))
1025 if (OP(next) != BRANCH) /* No choice. */
1026 next = NEXTOPER(scan);/* Avoid recursion. */
1028 int lastparen = *reglastparen;
1030 reginput = locinput;
1031 if (regmatch(NEXTOPER(scan)))
1033 for (n = *reglastparen; n > lastparen; n--)
1044 scan = regnext(scan);
1046 } while (scan != NULL && OP(scan) == BRANCH);
1056 ln = ARG1(scan); /* min to match */
1057 n = ARG2(scan); /* max to match */
1058 scan = NEXTOPER(scan) + 4;
1063 scan = NEXTOPER(scan);
1067 * Lookahead to avoid useless match attempts
1068 * when we know what character comes next.
1072 scan = NEXTOPER(scan);
1074 if (regkind[(U8)OP(next)] == EXACT) {
1075 c1 = UCHARAT(OPERAND(next) + 1);
1076 if (OP(next) == EXACTF)
1078 else if (OP(next) == EXACTFL)
1079 c2 = fold_locale[c1];
1085 reginput = locinput;
1088 if (ln && regrepeat(scan, ln) < ln)
1090 while (n >= ln || (n == 32767 && ln > 0)) { /* ln overflow ? */
1091 /* If it could work, try it. */
1093 UCHARAT(reginput) == c1 ||
1094 UCHARAT(reginput) == c2)
1099 /* Couldn't or didn't -- back up. */
1100 reginput = locinput + ln;
1101 if (regrepeat(scan, 1)) {
1103 reginput = locinput + ln;
1110 n = regrepeat(scan, n);
1111 if (ln < n && regkind[(U8)OP(next)] == EOL &&
1112 (!multiline || OP(next) == SEOL))
1113 ln = n; /* why back off? */
1115 /* If it could work, try it. */
1117 UCHARAT(reginput) == c1 ||
1118 UCHARAT(reginput) == c2)
1123 /* Couldn't or didn't -- back up. */
1125 reginput = locinput + n;
1131 reginput = locinput; /* put where regtry can find it */
1132 sayYES; /* Success! */
1134 reginput = locinput;
1135 scan = NEXTOPER(scan);
1136 if (!regmatch(scan))
1140 reginput = locinput;
1141 scan = NEXTOPER(scan);
1146 PerlIO_printf(PerlIO_stderr(), "%lx %d\n",
1147 (unsigned long)scan, scan[1]);
1148 FAIL("regexp memory corruption");
1154 * We get here only if there's trouble -- normally "case END" is
1155 * the terminating point.
1157 FAIL("corrupted regexp pointers");
1175 - regrepeat - repeatedly match something simple, report how many
1178 * [This routine now assumes that it will only match on things of length 1.
1179 * That was true before, but now we assume scan - reginput is the count,
1180 * rather than incrementing count on every character.]
1187 register char *scan;
1188 register char *opnd;
1190 register char *loceol = regeol;
1193 if (max != 32767 && max < loceol - scan)
1194 loceol = scan + max;
1198 while (scan < loceol && *scan != '\n')
1204 case EXACT: /* length of string is 1 */
1205 c = UCHARAT(++opnd);
1206 while (scan < loceol && UCHARAT(scan) == c)
1209 case EXACTF: /* length of string is 1 */
1210 c = UCHARAT(++opnd);
1211 while (scan < loceol &&
1212 (UCHARAT(scan) == c || UCHARAT(scan) == fold[c]))
1215 case EXACTFL: /* length of string is 1 */
1217 c = UCHARAT(++opnd);
1218 while (scan < loceol &&
1219 (UCHARAT(scan) == c || UCHARAT(scan) == fold_locale[c]))
1223 while (scan < loceol && reginclass(opnd, *scan))
1227 while (scan < loceol && isALNUM(*scan))
1232 while (scan < loceol && isALNUM_LC(*scan))
1236 while (scan < loceol && !isALNUM(*scan))
1241 while (scan < loceol && !isALNUM_LC(*scan))
1245 while (scan < loceol && isSPACE(*scan))
1250 while (scan < loceol && isSPACE_LC(*scan))
1254 while (scan < loceol && !isSPACE(*scan))
1259 while (scan < loceol && !isSPACE_LC(*scan))
1263 while (scan < loceol && isDIGIT(*scan))
1267 while (scan < loceol && !isDIGIT(*scan))
1270 default: /* Called on something of 0 width. */
1271 break; /* So match right here or not at all. */
1274 c = scan - reginput;
1281 - regclass - determine if a character falls into a character class
1293 if (p[1 + (c >> 3)] & (1 << (c & 7)))
1295 else if (flags & ANYOF_FOLD) {
1297 if (flags & ANYOF_LOCALE) {
1299 cf = fold_locale[c];
1303 if (p[1 + (cf >> 3)] & (1 << (cf & 7)))
1307 if (!match && (flags & ANYOF_ISA)) {
1310 if (((flags & ANYOF_ALNUML) && isALNUM_LC(c)) ||
1311 ((flags & ANYOF_NALNUML) && !isALNUM_LC(c)) ||
1312 ((flags & ANYOF_SPACEL) && isSPACE_LC(c)) ||
1313 ((flags & ANYOF_NSPACEL) && !isSPACE_LC(c)))
1319 return match ^ ((flags & ANYOF_INVERT) != 0);
1323 - regnext - dig the "next" pointer out of a node
1325 * [Note, when REGALIGN is defined there are two places in regmatch()
1326 * that bypass this code for speed.]
1332 register I32 offset;