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 #define regcpblow(cp) leave_scope(cp)
142 * pregexec and friends
149 static I32 regmatch _((char *prog));
150 static I32 regrepeat _((char *p, I32 max));
151 static I32 regtry _((regexp *prog, char *startpos));
152 static bool reginclass _((char *p, I32 c));
154 static bool regtainted; /* tainted information used? */
157 - pregexec - match a regexp against a string
160 pregexec(prog, stringarg, strend, strbeg, minend, screamer, safebase)
161 register regexp *prog;
163 register char *strend; /* pointer to null at end of string */
164 char *strbeg; /* real beginning of string */
165 I32 minend; /* end of match must be at least minend after stringarg */
167 I32 safebase; /* no need to remember string in subbase */
171 register char *startpos = stringarg;
173 I32 minlen = 0; /* must match at least this many chars */
174 I32 dontbother = 0; /* how many characters not to try at end */
182 regnarrate = debug & 512;
183 regprogram = prog->program;
187 if (prog == NULL || startpos == NULL) {
188 croak("NULL regexp parameter");
192 if (startpos == strbeg) /* is ^ valid at stringarg? */
195 regprev = stringarg[-1];
196 if (!multiline && regprev == '\n')
197 regprev = '\0'; /* force ^ to NOT match */
200 regprecomp = prog->precomp;
201 /* Check validity of program. */
202 if (UCHARAT(prog->program) != MAGIC) {
203 FAIL("corrupted regexp program");
206 regnpar = prog->nparens;
209 /* If there is a "must appear" string, look for it. */
211 if (prog->regmust != Nullsv &&
212 !(prog->reganch & ROPT_ANCH_GPOS) &&
213 (!(prog->reganch & ROPT_ANCH_BOL)
214 || (multiline && prog->regback >= 0)) )
216 if (stringarg == strbeg && screamer) {
217 if (screamfirst[BmRARE(prog->regmust)] >= 0)
218 s = screaminstr(screamer,prog->regmust);
223 s = fbm_instr((unsigned char*)s, (unsigned char*)strend,
226 ++BmUSEFUL(prog->regmust); /* hooray */
227 goto phooey; /* not present */
229 else if (prog->regback >= 0) {
233 minlen = prog->regback + SvCUR(prog->regmust);
235 else if (!prog->naughty && --BmUSEFUL(prog->regmust) < 0) { /* boo */
236 SvREFCNT_dec(prog->regmust);
237 prog->regmust = Nullsv; /* disable regmust */
242 minlen = SvCUR(prog->regmust);
246 /* Mark beginning of line for ^ . */
249 /* Mark end of line for $ (and such) */
252 /* see how far we have to get to not match where we matched before */
253 regtill = startpos+minend;
255 /* Simplest case: anchored match need be tried only once. */
256 /* [unless only anchor is BOL and multiline is set] */
257 if (prog->reganch & ROPT_ANCH) {
258 if (regtry(prog, startpos))
260 else if (!(prog->reganch & ROPT_ANCH_GPOS) &&
261 (multiline || (prog->reganch & ROPT_IMPLICIT)))
264 dontbother = minlen - 1;
265 strend -= dontbother;
266 /* for multiline we only have to try after newlines */
271 if (s < strend && regtry(prog, s))
279 /* Messy cases: unanchored match. */
280 if (prog->regstart) {
281 if (prog->reganch & ROPT_SKIP) { /* we have /x+whatever/ */
282 /* it must be a one character string */
283 char ch = SvPVX(prog->regstart)[0];
289 while (s < strend && *s == ch)
295 else if (SvTYPE(prog->regstart) == SVt_PVBM) {
296 /* We know what string it must start with. */
297 while ((s = fbm_instr((unsigned char*)s,
298 (unsigned char*)strend, prog->regstart)) != NULL)
305 else { /* Optimized fbm_instr: */
306 c = SvPVX(prog->regstart);
307 while ((s = ninstr(s, strend, c, c + SvCUR(prog->regstart))) != NULL)
317 if (c = prog->regstclass) {
318 I32 doevery = (prog->reganch & ROPT_SKIP) == 0;
321 dontbother = minlen - 1;
322 strend -= dontbother; /* don't bother with what can't match */
324 /* We know what class it must start with. */
329 if (reginclass(c, *s)) {
330 if (tmp && regtry(prog, s))
345 dontbother++,strend--;
346 tmp = (s != startpos) ? UCHARAT(s - 1) : regprev;
347 tmp = ((OP(c) == BOUND ? isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
349 if (tmp == !(OP(c) == BOUND ? isALNUM(*s) : isALNUM_LC(*s))) {
356 if ((minlen || tmp) && regtry(prog,s))
364 dontbother++,strend--;
365 tmp = (s != startpos) ? UCHARAT(s - 1) : regprev;
366 tmp = ((OP(c) == NBOUND ? isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
368 if (tmp == !(OP(c) == NBOUND ? isALNUM(*s) : isALNUM_LC(*s)))
370 else if (regtry(prog, s))
374 if ((minlen || !tmp) && regtry(prog,s))
380 if (tmp && regtry(prog, s))
393 if (isALNUM_LC(*s)) {
394 if (tmp && regtry(prog, s))
407 if (tmp && regtry(prog, s))
420 if (!isALNUM_LC(*s)) {
421 if (tmp && regtry(prog, s))
434 if (tmp && regtry(prog, s))
447 if (isSPACE_LC(*s)) {
448 if (tmp && regtry(prog, s))
461 if (tmp && regtry(prog, s))
474 if (!isSPACE_LC(*s)) {
475 if (tmp && regtry(prog, s))
488 if (tmp && regtry(prog, s))
501 if (tmp && regtry(prog, s))
515 dontbother = minlen - 1;
516 strend -= dontbother;
517 /* We don't know much -- general case. */
521 } while (s++ < strend);
528 strend += dontbother; /* uncheat */
529 prog->subbeg = strbeg;
530 prog->subend = strend;
531 prog->exec_tainted = regtainted;
533 /* make sure $`, $&, $', and $digit will work later */
534 if (strbeg != prog->subbase) {
537 Safefree(prog->subbase);
538 prog->subbase = Nullch;
542 I32 i = strend - startpos + (stringarg - strbeg);
543 s = savepvn(strbeg, i);
544 Safefree(prog->subbase);
546 prog->subbeg = prog->subbase;
547 prog->subend = prog->subbase + i;
548 s = prog->subbase + (stringarg - strbeg);
549 for (i = 0; i <= prog->nparens; i++) {
551 prog->startp[i] = s + (prog->startp[i] - startpos);
552 prog->endp[i] = s + (prog->endp[i] - startpos);
564 - regtry - try match at specific point
566 static I32 /* 0 failure, 1 success */
567 regtry(prog, startpos)
576 regstartp = prog->startp;
577 regendp = prog->endp;
578 reglastparen = &prog->lastparen;
585 for (i = prog->nparens; i >= 0; i--) {
590 if (regmatch(prog->program + 1) && reginput >= regtill) {
591 prog->startp[0] = startpos;
592 prog->endp[0] = reginput;
600 - regmatch - main matching routine
602 * Conceptually the strategy is simple: check to see whether the current
603 * node matches, call self recursively to see whether the rest matches,
604 * and then act accordingly. In practice we make some effort to avoid
605 * recursion, in particular by going through "ordinary" nodes (that don't
606 * need to know whether the rest of the match failed) by a loop instead of
609 /* [lwall] I've hoisted the register declarations to the outer block in order to
610 * maybe save a little bit of pushing and popping on the stack. It also takes
611 * advantage of machines that use a register save mask on subroutine entry.
613 static I32 /* 0 failure, 1 success */
617 register char *scan; /* Current node. */
618 char *next; /* Next node. */
619 register I32 nextchar;
620 register I32 n; /* no or next */
621 register I32 ln; /* len or last */
622 register char *s; /* operand or save */
623 register char *locinput = reginput;
624 register I32 c1, c2; /* case fold search */
627 static int regindent = 0;
631 nextchar = UCHARAT(locinput);
633 while (scan != NULL) {
635 #define sayYES goto yes
636 #define sayNO goto no
637 #define saySAME(x) if (x) goto yes; else goto no
639 SV *prop = sv_newmortal();
641 PerlIO_printf(Perl_debug_log, "%*s%2d%-8.8s\t<%.10s>\n",
642 regindent*2, "", scan - regprogram,
643 SvPVX(prop), locinput);
646 #define sayYES return 1
647 #define sayNO return 0
648 #define saySAME(x) return x
652 next = scan + NEXT(scan);
656 next = regnext(scan);
661 if (locinput == regbol
663 : ((nextchar || locinput < regeol) && locinput[-1] == '\n') )
665 /* regtill = regbol; */
670 if (locinput == regbol
672 : ((nextchar || locinput < regeol) && locinput[-1] == '\n') )
678 if (locinput == regbol && regprev == '\n')
682 if (locinput == regbol)
692 if ((nextchar || locinput < regeol) && nextchar != '\n')
697 if ((nextchar || locinput < regeol) && nextchar != '\n')
699 if (regeol - locinput > 1)
703 if (!nextchar && locinput >= regeol)
705 nextchar = UCHARAT(++locinput);
708 if (!nextchar && locinput >= regeol || nextchar == '\n')
710 nextchar = UCHARAT(++locinput);
715 /* Inline the first character, for speed. */
716 if (UCHARAT(s) != nextchar)
718 if (regeol - locinput < ln)
720 if (ln > 1 && memNE(s, locinput, ln))
723 nextchar = UCHARAT(locinput);
731 /* Inline the first character, for speed. */
732 if (UCHARAT(s) != nextchar &&
733 UCHARAT(s) != ((OP(scan) == EXACTF)
734 ? fold : fold_locale)[nextchar])
736 if (regeol - locinput < ln)
738 if (ln > 1 && (OP(scan) == EXACTF
739 ? ibcmp(s, locinput, ln)
740 : ibcmp_locale(s, locinput, ln)))
743 nextchar = UCHARAT(locinput);
748 nextchar = UCHARAT(locinput);
749 if (!reginclass(s, nextchar))
751 if (!nextchar && locinput >= regeol)
753 nextchar = UCHARAT(++locinput);
761 if (!(OP(scan) == ALNUM
762 ? isALNUM(nextchar) : isALNUM_LC(nextchar)))
764 nextchar = UCHARAT(++locinput);
770 if (!nextchar && locinput >= regeol)
772 if (OP(scan) == NALNUM
773 ? isALNUM(nextchar) : isALNUM_LC(nextchar))
775 nextchar = UCHARAT(++locinput);
783 /* was last char in word? */
784 ln = (locinput != regbol) ? UCHARAT(locinput - 1) : regprev;
785 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
787 n = isALNUM(nextchar);
791 n = isALNUM_LC(nextchar);
793 if (((!ln) == (!n)) == (OP(scan) == BOUND || OP(scan) == BOUNDL))
800 if (!nextchar && locinput >= regeol)
802 if (!(OP(scan) == SPACE
803 ? isSPACE(nextchar) : isSPACE_LC(nextchar)))
805 nextchar = UCHARAT(++locinput);
813 if (OP(scan) == SPACE
814 ? isSPACE(nextchar) : isSPACE_LC(nextchar))
816 nextchar = UCHARAT(++locinput);
819 if (!isDIGIT(nextchar))
821 nextchar = UCHARAT(++locinput);
824 if (!nextchar && locinput >= regeol)
826 if (isDIGIT(nextchar))
828 nextchar = UCHARAT(++locinput);
831 n = ARG1(scan); /* which paren pair */
839 /* Inline the first character, for speed. */
840 if (UCHARAT(s) != nextchar)
843 if (locinput + ln > regeol)
845 if (ln > 1 && memNE(s, locinput, ln))
848 nextchar = UCHARAT(locinput);
856 n = ARG1(scan); /* which paren pair */
857 regstartp[n] = locinput;
862 n = ARG1(scan); /* which paren pair */
863 regendp[n] = locinput;
864 if (n > *reglastparen)
870 CHECKPOINT cp = savestack_ix;
873 cc.parenfloor = *reglastparen;
877 cc.scan = NEXTOPER(scan) + 4;
882 n = regmatch(PREVOPER(next)); /* start on the WHILEM */
890 * This is really hard to understand, because after we match
891 * what we're trying to match, we must make sure the rest of
892 * the RE is going to match for sure, and to do that we have
893 * to go back UP the parse tree by recursing ever deeper. And
894 * if it fails, we have to reset our parent's current state
895 * that we can try again after backing off.
900 n = cc->cur + 1; /* how many we know we matched */
905 PerlIO_printf(Perl_debug_log, "%*s %ld %lx\n", regindent*2, "",
909 /* If degenerate scan matches "", assume scan done. */
911 if (locinput == cc->lastloc && n >= cc->min) {
914 if (regmatch(cc->next))
921 /* First just match a string of min scans. */
925 cc->lastloc = locinput;
926 if (regmatch(cc->scan))
932 /* Prefer next over scan for minimal matching. */
937 cp = regcppush(cc->parenfloor);
938 if (regmatch(cc->next)) {
940 sayYES; /* All done. */
946 if (n >= cc->max) /* Maximum greed exceeded? */
949 /* Try scanning more and see if it helps. */
952 cc->lastloc = locinput;
953 cp = regcppush(cc->parenfloor);
954 if (regmatch(cc->scan)) {
963 /* Prefer scan over next for maximal matching. */
965 if (n < cc->max) { /* More greed allowed? */
966 cp = regcppush(cc->parenfloor);
968 cc->lastloc = locinput;
969 if (regmatch(cc->scan)) {
973 regcppop(); /* Restore some previous $<digit>s? */
977 /* Failed deeper matches of scan, so see if this one works. */
980 if (regmatch(cc->next))
989 if (OP(next) != BRANCH) /* No choice. */
990 next = NEXTOPER(scan);/* Avoid recursion. */
992 int lastparen = *reglastparen;
995 if (regmatch(NEXTOPER(scan)))
997 for (n = *reglastparen; n > lastparen; n--)
1008 scan = regnext(scan);
1010 } while (scan != NULL && OP(scan) == BRANCH);
1020 ln = ARG1(scan); /* min to match */
1021 n = ARG2(scan); /* max to match */
1022 scan = NEXTOPER(scan) + 4;
1027 scan = NEXTOPER(scan);
1031 * Lookahead to avoid useless match attempts
1032 * when we know what character comes next.
1036 scan = NEXTOPER(scan);
1038 if (regkind[(U8)OP(next)] == EXACT) {
1039 c1 = UCHARAT(OPERAND(next) + 1);
1040 if (OP(next) == EXACTF)
1042 else if (OP(next) == EXACTFL)
1043 c2 = fold_locale[c1];
1049 reginput = locinput;
1052 if (ln && regrepeat(scan, ln) < ln)
1054 while (n >= ln || (n == 32767 && ln > 0)) { /* ln overflow ? */
1055 /* If it could work, try it. */
1057 UCHARAT(reginput) == c1 ||
1058 UCHARAT(reginput) == c2)
1063 /* Couldn't or didn't -- back up. */
1064 reginput = locinput + ln;
1065 if (regrepeat(scan, 1)) {
1067 reginput = locinput + ln;
1074 n = regrepeat(scan, n);
1075 if (ln < n && regkind[(U8)OP(next)] == EOL &&
1076 (!multiline || OP(next) == SEOL))
1077 ln = n; /* why back off? */
1079 /* If it could work, try it. */
1081 UCHARAT(reginput) == c1 ||
1082 UCHARAT(reginput) == c2)
1087 /* Couldn't or didn't -- back up. */
1089 reginput = locinput + n;
1095 reginput = locinput; /* put where regtry can find it */
1096 sayYES; /* Success! */
1098 reginput = locinput;
1099 scan = NEXTOPER(scan);
1100 if (!regmatch(scan))
1104 reginput = locinput;
1105 scan = NEXTOPER(scan);
1110 PerlIO_printf(PerlIO_stderr(), "%lx %d\n",
1111 (unsigned long)scan, scan[1]);
1112 FAIL("regexp memory corruption");
1118 * We get here only if there's trouble -- normally "case END" is
1119 * the terminating point.
1121 FAIL("corrupted regexp pointers");
1139 - regrepeat - repeatedly match something simple, report how many
1142 * [This routine now assumes that it will only match on things of length 1.
1143 * That was true before, but now we assume scan - reginput is the count,
1144 * rather than incrementing count on every character.]
1151 register char *scan;
1152 register char *opnd;
1154 register char *loceol = regeol;
1157 if (max != 32767 && max < loceol - scan)
1158 loceol = scan + max;
1162 while (scan < loceol && *scan != '\n')
1168 case EXACT: /* length of string is 1 */
1169 c = UCHARAT(++opnd);
1170 while (scan < loceol && UCHARAT(scan) == c)
1173 case EXACTF: /* length of string is 1 */
1174 c = UCHARAT(++opnd);
1175 while (scan < loceol &&
1176 (UCHARAT(scan) == c || UCHARAT(scan) == fold[c]))
1179 case EXACTFL: /* length of string is 1 */
1181 c = UCHARAT(++opnd);
1182 while (scan < loceol &&
1183 (UCHARAT(scan) == c || UCHARAT(scan) == fold_locale[c]))
1187 while (scan < loceol && reginclass(opnd, *scan))
1191 while (scan < loceol && isALNUM(*scan))
1196 while (scan < loceol && isALNUM_LC(*scan))
1200 while (scan < loceol && !isALNUM(*scan))
1205 while (scan < loceol && !isALNUM_LC(*scan))
1209 while (scan < loceol && isSPACE(*scan))
1214 while (scan < loceol && isSPACE_LC(*scan))
1218 while (scan < loceol && !isSPACE(*scan))
1223 while (scan < loceol && !isSPACE_LC(*scan))
1227 while (scan < loceol && isDIGIT(*scan))
1231 while (scan < loceol && !isDIGIT(*scan))
1234 default: /* Called on something of 0 width. */
1235 break; /* So match right here or not at all. */
1238 c = scan - reginput;
1245 - regclass - determine if a character falls into a character class
1257 if (p[1 + (c >> 3)] & (1 << (c & 7)))
1259 else if (flags & ANYOF_FOLD) {
1261 if (flags & ANYOF_LOCALE) {
1263 cf = fold_locale[c];
1267 if (p[1 + (cf >> 3)] & (1 << (cf & 7)))
1271 if (!match && (flags & ANYOF_ISA)) {
1274 if (((flags & ANYOF_ALNUML) && isALNUM_LC(c)) ||
1275 ((flags & ANYOF_NALNUML) && !isALNUM_LC(c)) ||
1276 ((flags & ANYOF_SPACEL) && isSPACE_LC(c)) ||
1277 ((flags & ANYOF_NSPACEL) && !isSPACE_LC(c)))
1283 return match ^ ((flags & ANYOF_INVERT) != 0);
1287 - regnext - dig the "next" pointer out of a node
1289 * [Note, when REGALIGN is defined there are two places in regmatch()
1290 * that bypass this code for speed.]
1296 register I32 offset;