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-1994, 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 CHECKPOINT regcppush _((I32 parenfloor));
86 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 #define regcpblow(cp) leave_scope(cp)
140 * pregexec and friends
147 static I32 regmatch _((char *prog));
148 static I32 regrepeat _((char *p, I32 max));
149 static I32 regtry _((regexp *prog, char *startpos));
152 - pregexec - match a regexp against a string
155 pregexec(prog, stringarg, strend, strbeg, minend, screamer, safebase)
156 register regexp *prog;
158 register char *strend; /* pointer to null at end of string */
159 char *strbeg; /* real beginning of string */
160 I32 minend; /* end of match must be at least minend after stringarg */
162 I32 safebase; /* no need to remember string in subbase */
167 register char *startpos = stringarg;
169 I32 minlen = 0; /* must match at least this many chars */
170 I32 dontbother = 0; /* how many characters not to try at end */
178 regnarrate = debug & 512;
179 regprogram = prog->program;
183 if (prog == NULL || startpos == NULL) {
184 croak("NULL regexp parameter");
188 if (startpos == strbeg) /* is ^ valid at stringarg? */
191 regprev = stringarg[-1];
192 if (!multiline && regprev == '\n')
193 regprev = '\0'; /* force ^ to NOT match */
195 regprecomp = prog->precomp;
196 regnpar = prog->nparens;
197 /* Check validity of program. */
198 if (UCHARAT(prog->program) != MAGIC) {
199 FAIL("corrupted regexp program");
202 if (prog->do_folding) {
203 i = strend - startpos;
204 New(1101,c,i+1,char);
205 Copy(startpos, c, i+1, char);
207 strend = startpos + i;
208 for (s = startpos; s < strend; s++)
213 /* If there is a "must appear" string, look for it. */
215 if (prog->regmust != Nullsv &&
216 (!(prog->reganch & ROPT_ANCH)
217 || (multiline && prog->regback >= 0)) )
219 if (stringarg == strbeg && screamer) {
220 if (screamfirst[BmRARE(prog->regmust)] >= 0)
221 s = screaminstr(screamer,prog->regmust);
226 s = fbm_instr((unsigned char*)s, (unsigned char*)strend,
229 ++BmUSEFUL(prog->regmust); /* hooray */
230 goto phooey; /* not present */
232 else if (prog->regback >= 0) {
236 minlen = prog->regback + SvCUR(prog->regmust);
238 else if (!prog->naughty && --BmUSEFUL(prog->regmust) < 0) { /* boo */
239 SvREFCNT_dec(prog->regmust);
240 prog->regmust = Nullsv; /* disable regmust */
245 minlen = SvCUR(prog->regmust);
249 /* Mark beginning of line for ^ . */
252 /* Mark end of line for $ (and such) */
255 /* see how far we have to get to not match where we matched before */
256 regtill = startpos+minend;
258 /* Simplest case: anchored match need be tried only once. */
259 /* [unless multiline is set] */
260 if (prog->reganch & ROPT_ANCH) {
261 if (regtry(prog, startpos))
263 else if (multiline || (prog->reganch & ROPT_IMPLICIT)) {
265 dontbother = minlen - 1;
266 strend -= dontbother;
267 /* for multiline we only have to try after newlines */
272 if (s < strend && regtry(prog, s))
280 /* Messy cases: unanchored match. */
281 if (prog->regstart) {
282 if (prog->reganch & ROPT_SKIP) { /* we have /x+whatever/ */
283 /* it must be a one character string */
284 i = SvPVX(prog->regstart)[0];
290 while (s < strend && *s == i)
296 else if (SvPOK(prog->regstart) == 3) {
297 /* We know what string it must start with. */
298 while ((s = fbm_instr((unsigned char*)s,
299 (unsigned char*)strend, prog->regstart)) != NULL)
307 c = SvPVX(prog->regstart);
308 while ((s = ninstr(s, strend, c, c + SvCUR(prog->regstart))) != NULL)
318 if (c = prog->regstclass) {
319 I32 doevery = (prog->reganch & ROPT_SKIP) == 0;
322 dontbother = minlen - 1;
323 strend -= dontbother; /* don't bother with what can't match */
325 /* We know what class it must start with. */
331 if (!(c[i >> 3] & (1 << (i&7)))) {
332 if (tmp && regtry(prog, s))
344 dontbother++,strend--;
350 tmp = isALNUM(regprev); /* assume not alphanumeric */
353 if (tmp != isALNUM(i)) {
360 if ((minlen || tmp) && regtry(prog,s))
365 dontbother++,strend--;
371 tmp = isALNUM(regprev); /* assume not alphanumeric */
374 if (tmp != isALNUM(i))
376 else if (regtry(prog, s))
380 if ((minlen || !tmp) && regtry(prog,s))
387 if (tmp && regtry(prog, s))
401 if (tmp && regtry(prog, s))
414 if (tmp && regtry(prog, s))
427 if (tmp && regtry(prog, s))
440 if (tmp && regtry(prog, s))
453 if (tmp && regtry(prog, s))
467 dontbother = minlen - 1;
468 strend -= dontbother;
469 /* We don't know much -- general case. */
473 } while (s++ < strend);
480 strend += dontbother; /* uncheat */
481 prog->subbeg = strbeg;
482 prog->subend = strend;
483 if ((!safebase && (prog->nparens || sawampersand)) || prog->do_folding) {
484 i = strend - startpos + (stringarg - strbeg);
485 if (safebase) { /* no need for $digit later */
489 else if (strbeg != prog->subbase) {
490 s = savepvn(strbeg,i); /* so $digit will work later */
492 Safefree(prog->subbase);
493 prog->subbeg = prog->subbase = s;
497 prog->subbeg = s = prog->subbase;
500 s += (stringarg - strbeg);
501 for (i = 0; i <= prog->nparens; i++) {
503 prog->startp[i] = s + (prog->startp[i] - startpos);
504 prog->endp[i] = s + (prog->endp[i] - startpos);
507 if (prog->do_folding)
513 if (prog->do_folding)
519 - regtry - try match at specific point
521 static I32 /* 0 failure, 1 success */
522 regtry(prog, startpos)
531 regstartp = prog->startp;
532 regendp = prog->endp;
533 reglastparen = &prog->lastparen;
540 for (i = prog->nparens; i >= 0; i--) {
545 if (regmatch(prog->program + 1) && reginput >= regtill) {
546 prog->startp[0] = startpos;
547 prog->endp[0] = reginput;
555 - regmatch - main matching routine
557 * Conceptually the strategy is simple: check to see whether the current
558 * node matches, call self recursively to see whether the rest matches,
559 * and then act accordingly. In practice we make some effort to avoid
560 * recursion, in particular by going through "ordinary" nodes (that don't
561 * need to know whether the rest of the match failed) by a loop instead of
564 /* [lwall] I've hoisted the register declarations to the outer block in order to
565 * maybe save a little bit of pushing and popping on the stack. It also takes
566 * advantage of machines that use a register save mask on subroutine entry.
568 static I32 /* 0 failure, 1 success */
572 register char *scan; /* Current node. */
573 char *next; /* Next node. */
574 register I32 nextchar;
575 register I32 n; /* no or next */
576 register I32 ln; /* len or last */
577 register char *s; /* operand or save */
578 register char *locinput = reginput;
581 static int regindent = 0;
585 nextchar = *locinput;
587 while (scan != NULL) {
589 #define sayYES goto yes
590 #define sayNO goto no
591 #define saySAME(x) if (x) goto yes; else goto no
593 fprintf(stderr, "%*s%2d%-8.8s\t<%.10s>\n", regindent*2, "",
594 scan - regprogram, regprop(scan), locinput);
597 #define sayYES return 1
598 #define sayNO return 0
599 #define saySAME(x) return x
603 next = scan + NEXT(scan);
607 next = regnext(scan);
612 if (locinput == regbol
614 : ((nextchar || locinput < regeol) && locinput[-1] == '\n') )
616 /* regtill = regbol; */
621 if (locinput == regbol
623 : ((nextchar || locinput < regeol) && locinput[-1] == '\n') )
629 if (locinput == regbol && regprev == '\n')
633 if (locinput == regbol)
643 if ((nextchar || locinput < regeol) && nextchar != '\n')
648 if ((nextchar || locinput < regeol) && nextchar != '\n')
650 if (regeol - locinput > 1)
654 if (!nextchar && locinput >= regeol)
656 nextchar = *++locinput;
659 if (!nextchar && locinput >= regeol || nextchar == '\n')
661 nextchar = *++locinput;
666 /* Inline the first character, for speed. */
669 if (regeol - locinput < ln)
671 if (ln > 1 && bcmp(s, locinput, ln) != 0)
674 nextchar = *locinput;
679 nextchar = UCHARAT(locinput);
680 if (s[nextchar >> 3] & (1 << (nextchar&7)))
682 if (!nextchar && locinput >= regeol)
684 nextchar = *++locinput;
689 if (!isALNUM(nextchar))
691 nextchar = *++locinput;
694 if (!nextchar && locinput >= regeol)
696 if (isALNUM(nextchar))
698 nextchar = *++locinput;
702 if (locinput == regbol) /* was last char in word? */
703 ln = isALNUM(regprev);
705 ln = isALNUM(locinput[-1]);
706 n = isALNUM(nextchar); /* is next char in word? */
707 if ((ln == n) == (OP(scan) == BOUND))
711 if (!nextchar && locinput >= regeol)
713 if (!isSPACE(nextchar))
715 nextchar = *++locinput;
720 if (isSPACE(nextchar))
722 nextchar = *++locinput;
725 if (!isDIGIT(nextchar))
727 nextchar = *++locinput;
730 if (!nextchar && locinput >= regeol)
732 if (isDIGIT(nextchar))
734 nextchar = *++locinput;
737 n = ARG1(scan); /* which paren pair */
745 /* Inline the first character, for speed. */
749 if (locinput + ln > regeol)
751 if (ln > 1 && bcmp(s, locinput, ln) != 0)
754 nextchar = *locinput;
762 n = ARG1(scan); /* which paren pair */
763 regstartp[n] = locinput;
768 n = ARG1(scan); /* which paren pair */
769 regendp[n] = locinput;
770 if (n > *reglastparen)
775 CHECKPOINT cp = savestack_ix;
778 cc.parenfloor = *reglastparen;
782 cc.scan = NEXTOPER(scan) + 4;
787 n = regmatch(PREVOPER(next)); /* start on the WHILEM */
795 * This is really hard to understand, because after we match
796 * what we're trying to match, we must make sure the rest of
797 * the RE is going to match for sure, and to do that we have
798 * to go back UP the parse tree by recursing ever deeper. And
799 * if it fails, we have to reset our parent's current state
800 * that we can try again after backing off.
804 n = cc->cur + 1; /* how many we know we matched */
809 fprintf(stderr, "%*s %d %lx\n", regindent*2, "",
813 /* If degenerate scan matches "", assume scan done. */
815 if (locinput == cc->lastloc) {
818 if (regmatch(cc->next))
825 /* First just match a string of min scans. */
829 cc->lastloc = locinput;
830 if (regmatch(cc->scan))
836 /* Prefer next over scan for minimal matching. */
841 if (regmatch(cc->next))
842 sayYES; /* All done. */
846 if (n >= cc->max) /* Maximum greed exceeded? */
849 /* Try scanning more and see if it helps. */
852 cc->lastloc = locinput;
853 if (regmatch(cc->scan))
859 /* Prefer scan over next for maximal matching. */
861 if (n < cc->max) { /* More greed allowed? */
862 regcppush(cc->parenfloor);
864 cc->lastloc = locinput;
865 if (regmatch(cc->scan))
867 regcppop(); /* Restore some previous $<digit>s? */
871 /* Failed deeper matches of scan, so see if this one works. */
874 if (regmatch(cc->next))
883 if (OP(next) != BRANCH) /* No choice. */
884 next = NEXTOPER(scan);/* Avoid recursion. */
886 int lastparen = *reglastparen;
889 if (regmatch(NEXTOPER(scan)))
891 for (n = *reglastparen; n > lastparen; n--)
902 scan = regnext(scan);
904 } while (scan != NULL && OP(scan) == BRANCH);
914 ln = ARG1(scan); /* min to match */
915 n = ARG2(scan); /* max to match */
916 scan = NEXTOPER(scan) + 4;
921 scan = NEXTOPER(scan);
925 * Lookahead to avoid useless match attempts
926 * when we know what character comes next.
930 scan = NEXTOPER(scan);
932 if (OP(next) == EXACTLY)
933 nextchar = *(OPERAND(next)+1);
939 if (ln && regrepeat(scan, ln) < ln)
941 while (n >= ln || (n == 32767 && ln > 0)) { /* ln overflow ? */
942 /* If it could work, try it. */
943 if (nextchar == -1000 || *reginput == nextchar)
946 /* Couldn't or didn't -- back up. */
947 reginput = locinput + ln;
948 if (regrepeat(scan, 1)) {
950 reginput = locinput + ln;
957 n = regrepeat(scan, n);
958 if (ln < n && regkind[(U8)OP(next)] == EOL &&
959 (!multiline || OP(next) == SEOL))
960 ln = n; /* why back off? */
962 /* If it could work, try it. */
963 if (nextchar == -1000 || *reginput == nextchar)
966 /* Couldn't or didn't -- back up. */
968 reginput = locinput + n;
974 reginput = locinput; /* put where regtry can find it */
975 sayYES; /* Success! */
978 scan = NEXTOPER(scan);
984 scan = NEXTOPER(scan);
989 fprintf(stderr, "%x %d\n",(unsigned)scan,scan[1]);
990 FAIL("regexp memory corruption");
996 * We get here only if there's trouble -- normally "case END" is
997 * the terminating point.
999 FAIL("corrupted regexp pointers");
1017 - regrepeat - repeatedly match something simple, report how many
1020 * [This routine now assumes that it will only match on things of length 1.
1021 * That was true before, but now we assume scan - reginput is the count,
1022 * rather than incrementing count on every character.]
1029 register char *scan;
1030 register char *opnd;
1032 register char *loceol = regeol;
1035 if (max != 32767 && max < loceol - scan)
1036 loceol = scan + max;
1040 while (scan < loceol && *scan != '\n')
1046 case EXACTLY: /* length of string is 1 */
1048 while (scan < loceol && *opnd == *scan)
1053 while (scan < loceol && !(opnd[c >> 3] & (1 << (c & 7)))) {
1059 while (scan < loceol && isALNUM(*scan))
1063 while (scan < loceol && !isALNUM(*scan))
1067 while (scan < loceol && isSPACE(*scan))
1071 while (scan < loceol && !isSPACE(*scan))
1075 while (scan < loceol && isDIGIT(*scan))
1079 while (scan < loceol && !isDIGIT(*scan))
1082 default: /* Called on something of 0 width. */
1083 break; /* So match right here or not at all. */
1086 c = scan - reginput;
1093 - regnext - dig the "next" pointer out of a node
1095 * [Note, when REGALIGN is defined there are two places in regmatch()
1096 * that bypass this code for speed.]
1102 register I32 offset;