1 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
2 * confused with the original package (see point 3 below). Thanks, Henry!
5 /* Additional note: this code is very heavily munged from Henry's version
6 * in places. In some spots I've traded clarity for efficiency, so don't
7 * blame Henry for some of the lack of readability.
10 /* $Header: regcomp.c,v 3.0.1.5 90/08/13 22:23:29 lwall Locked $
13 * Revision 3.0.1.5 90/08/13 22:23:29 lwall
14 * patch28: /x{m}/ didn't work right
16 * Revision 3.0.1.4 90/08/09 05:05:33 lwall
17 * patch19: sped up /x+y/ patterns greatly by not retrying on every x
18 * patch19: inhibited backoff on patterns anchored to the end like /\s+$/
19 * patch19: sped up {m,n} on simple items
20 * patch19: optimized /.*whatever/ to /^.*whatever/
21 * patch19: fixed character classes to allow backslashing hyphen
23 * Revision 3.0.1.3 90/03/12 16:59:22 lwall
24 * patch13: pattern matches can now use \0 to mean \000
26 * Revision 3.0.1.2 90/02/28 18:08:35 lwall
27 * patch9: /[\200-\377]/ didn't work on machines with signed chars
29 * Revision 3.0.1.1 89/11/11 04:51:04 lwall
30 * patch2: /[\000]/ didn't work
32 * Revision 3.0 89/10/18 15:22:29 lwall
38 * regcomp and regexec -- regsub and regerror are not used in perl
40 * Copyright (c) 1986 by University of Toronto.
41 * Written by Henry Spencer. Not derived from licensed software.
43 * Permission is granted to anyone to use this software for any
44 * purpose on any computer system, and to redistribute it freely,
45 * subject to the following restrictions:
47 * 1. The author is not responsible for the consequences of use of
48 * this software, no matter how awful, even if they arise
51 * 2. The origin of this software must not be misrepresented, either
52 * by explicit claim or by omission.
54 * 3. Altered versions must be plainly marked as such, and must not
55 * be misrepresented as being the original software.
58 **** Alterations to Henry's code are...
60 **** Copyright (c) 1989, Larry Wall
62 **** You may distribute under the terms of the GNU General Public License
63 **** as specified in the README file that comes with the perl 3.0 kit.
65 * Beware that some of this code is subtly aware of the way operator
66 * precedence is structured in regular expressions. Serious changes in
67 * regular-expression syntax might require a total rethink.
78 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
79 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
80 ((*s) == '{' && regcurly(s)))
81 #define META "^$.[()|?+*\\"
84 * Flags to be passed up and down.
86 #define HASWIDTH 01 /* Known never to match null string. */
87 #define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
88 #define SPSTART 04 /* Starts with * or +. */
89 #define WORST 0 /* Worst case. */
92 * Global work variables for regcomp().
94 static char *regprecomp; /* uncompiled string. */
95 static char *regparse; /* Input-scan pointer. */
96 static char *regxend; /* End of input for compile */
97 static int regnpar; /* () count. */
98 static char *regcode; /* Code-emit pointer; ®dummy = don't. */
99 static long regsize; /* Code size. */
101 static int regsawbracket; /* Did we do {d,d} trick? */
104 * Forward declarations for regcomp()'s friends.
106 STATIC int regcurly();
108 STATIC char *regbranch();
109 STATIC char *regpiece();
110 STATIC char *regatom();
111 STATIC char *regclass();
112 STATIC char *regnode();
114 STATIC void reginsert();
115 STATIC void regtail();
116 STATIC void regoptail();
119 - regcomp - compile a regular expression into internal code
121 * We can't allocate space until we know how big the compiled form will be,
122 * but we can't compile it (and thus know how big it is) until we've got a
123 * place to put the code. So we cheat: we compile it twice, once with code
124 * generation turned off and size counting turned on, and once "for real".
125 * This also means that we don't allocate space until we are sure that the
126 * thing really will compile successfully, and we never have to move the
127 * code and thus invalidate pointers into it. (Note that it has to be in
128 * one piece because free() must be able to free it all.) [NB: not true in perl]
130 * Beware that the optimization-preparation code in here knows about some
131 * of the structure of the compiled regexp. [I'll say.]
134 regcomp(exp,xend,fold)
141 register STR *longest;
143 register char *first;
147 extern char *safemalloc();
148 extern char *savestr();
152 fatal("NULL regexp argument");
154 /* First pass: determine size, legality. */
158 regprecomp = nsavestr(exp,xend-exp);
164 if (reg(0, &flags) == NULL) {
165 Safefree(regprecomp);
169 /* Small enough for pointer-storage convention? */
170 if (regsize >= 32767L) /* Probably could be 65535L. */
171 FAIL("regexp too big");
173 /* Allocate space. */
174 Newc(1001, r, sizeof(regexp) + (unsigned)regsize, char, regexp);
176 FAIL("regexp out of space");
178 /* Second pass: emit code. */
180 bcopy(regprecomp,exp,xend-exp);
181 r->precomp = regprecomp;
185 regcode = r->program;
187 if (reg(0, &flags) == NULL)
190 /* Dig out information for optimizations. */
191 r->regstart = Nullstr; /* Worst-case defaults. */
193 r->regmust = Nullstr;
195 r->regstclass = Nullch;
196 scan = r->program+1; /* First BRANCH. */
197 if (OP(regnext(scan)) == END) {/* Only one top-level choice. */
198 scan = NEXTOPER(scan);
201 while ((OP(first) > OPEN && OP(first) < CLOSE) ||
202 (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
203 (OP(first) == PLUS) ||
204 (OP(first) == CURLY && ARG1(first) > 0) ) {
205 if (OP(first) == CURLY)
207 else if (OP(first) == PLUS)
209 first = NEXTOPER(first);
212 /* Starting-point info. */
213 if (OP(first) == EXACTLY) {
215 str_make(OPERAND(first)+1,*OPERAND(first));
216 if (r->regstart->str_cur > !(sawstudy|fold))
217 fbmcompile(r->regstart,fold);
219 else if ((exp = index(simple,OP(first))) && exp > simple)
220 r->regstclass = first;
221 else if (OP(first) == BOUND || OP(first) == NBOUND)
222 r->regstclass = first;
223 else if (OP(first) == BOL ||
224 (OP(first) == STAR && OP(NEXTOPER(first)) == ANY) )
225 r->reganch = 1; /* kinda turn .* into ^.* */
226 r->reganch |= sawplus;
230 fprintf(stderr,"first %d next %d offset %d\n",
231 OP(first), OP(NEXTOPER(first)), first - scan);
234 * If there's something expensive in the r.e., find the
235 * longest literal string that must appear and make it the
236 * regmust. Resolve ties in favor of later strings, since
237 * the regstart check works with the beginning of the r.e.
238 * and avoiding duplication strengthens checking. Not a
239 * strong reason, but sufficient in the absence of others.
240 * [Now we resolve ties in favor of the earlier string if
241 * it happens that curback has been invalidated, since the
242 * earlier string may buy us something the later one won't.]
244 longest = str_make("",0);
248 while (scan != NULL) {
249 if (OP(scan) == BRANCH) {
250 if (OP(regnext(scan)) == BRANCH) {
252 while (OP(scan) == BRANCH)
253 scan = regnext(scan);
255 else /* single branch is ok */
256 scan = NEXTOPER(scan);
258 if (OP(scan) == EXACTLY) {
260 while (OP(regnext(scan)) >= CLOSE)
261 scan = regnext(scan);
262 if (curback - back == len) {
263 str_ncat(longest, OPERAND(first)+1,
265 len += *OPERAND(first);
266 curback += *OPERAND(first);
267 first = regnext(scan);
269 else if (*OPERAND(first) >= len + (curback >= 0)) {
270 len = *OPERAND(first);
271 str_nset(longest, OPERAND(first)+1,len);
274 first = regnext(scan);
277 curback += *OPERAND(first);
279 else if (index(varies,OP(scan)))
281 else if (index(simple,OP(scan)))
283 scan = regnext(scan);
286 r->regmust = longest;
290 if (len > !(sawstudy||fold||OP(first)==EOL))
291 fbmcompile(r->regmust,fold);
292 r->regmust->str_u.str_useful = 100;
293 if (OP(first) == EOL) /* is match anchored to EOL? */
294 r->regmust->str_pok |= SP_TAIL;
300 r->do_folding = fold;
301 r->nparens = regnpar - 1;
310 - reg - regular expression, i.e. main body or parenthesized thing
312 * Caller must absorb opening parenthesis.
314 * Combining parenthesis handling with the base level of regular expression
315 * is a trifle forced, but the need to tie the tails of the branches to what
316 * follows makes it hard to avoid.
320 int paren; /* Parenthesized? */
325 register char *ender;
329 *flagp = HASWIDTH; /* Tentatively. */
331 /* Make an OPEN node, if parenthesized. */
333 if (regnpar >= NSUBEXP)
334 FAIL("too many () in regexp");
337 ret = regnode(OPEN+parno);
341 /* Pick up the branches, linking them together. */
342 br = regbranch(&flags);
346 regtail(ret, br); /* OPEN -> first. */
349 if (!(flags&HASWIDTH))
351 *flagp |= flags&SPSTART;
352 while (*regparse == '|') {
354 br = regbranch(&flags);
357 regtail(ret, br); /* BRANCH -> BRANCH. */
358 if (!(flags&HASWIDTH))
360 *flagp |= flags&SPSTART;
363 /* Make a closing node, and hook it on the end. */
364 ender = regnode((paren) ? CLOSE+parno : END);
367 /* Hook the tails of the branches to the closing node. */
368 for (br = ret; br != NULL; br = regnext(br))
369 regoptail(br, ender);
371 /* Check for proper termination. */
372 if (paren && *regparse++ != ')') {
373 FAIL("unmatched () in regexp");
374 } else if (!paren && regparse < regxend) {
375 if (*regparse == ')') {
376 FAIL("unmatched () in regexp");
378 FAIL("junk on end of regexp"); /* "Can't happen". */
386 - regbranch - one alternative of an | operator
388 * Implements the concatenation operator.
395 register char *chain;
396 register char *latest;
399 *flagp = WORST; /* Tentatively. */
401 ret = regnode(BRANCH);
403 while (regparse < regxend && *regparse != '|' && *regparse != ')') {
404 latest = regpiece(&flags);
407 *flagp |= flags&HASWIDTH;
408 if (chain == NULL) /* First piece. */
409 *flagp |= flags&SPSTART;
411 regtail(chain, latest);
414 if (chain == NULL) /* Loop ran zero times. */
415 (void) regnode(NOTHING);
421 - regpiece - something followed by possible [*+?]
423 * Note that the branching code sequences used for ? and the general cases
424 * of * and + are somewhat optimized: they use the same NOTHING node as
425 * both the endmarker for their branch list and the body of the last branch.
426 * It might seem that this node could be dispensed with entirely, but the
427 * endmarker role is not redundant.
437 char *origparse = regparse;
438 int orignpar = regnpar;
443 ret = regatom(&flags);
449 /* Here's a total kludge: if after the atom there's a {\d+,?\d*}
450 * then we decrement the first number by one and reset our
451 * parsing back to the beginning of the same atom. If the first number
452 * is down to 0, decrement the second number instead and fake up
453 * a ? after it. Given the way this compiler doesn't keep track
454 * of offsets on the first pass, this is the only way to replicate
455 * a piece of code. Sigh.
457 if (op == '{' && regcurly(regparse)) {
460 while (isdigit(*next) || *next == ',') {
469 if (*next == '}') { /* got one */
473 iter = atoi(regparse);
474 if (flags&SIMPLE) { /* we can do it right after all */
477 reginsert(CURLY, ret);
483 if (tmp && tmp < iter)
484 fatal("Can't do {n,m} with n > m");
485 if (regcode != ®dummy) {
487 *(unsigned short *)(ret+3) = iter;
488 *(unsigned short *)(ret+5) = tmp;
490 ret[3] = iter >> 8; ret[4] = iter & 0377;
491 ret[5] = tmp >> 8; ret[6] = tmp & 0377;
497 regsawbracket++; /* remember we clobbered exp */
500 sprintf(regparse,"%.*d", max-regparse, iter - 1);
502 if (*max == ',' && max[1] != '}') {
503 if (atoi(max+1) <= 0)
504 fatal("Can't do {n,m} with n > m");
506 sprintf(max+1,"%.*d", next-(max+1), atoi(max+1) - 1);
509 if (iter != 1 || *max == ',') {
510 regparse = origparse; /* back up input pointer */
511 regnpar = orignpar; /* don't make more parens */
523 if (max == next) { /* any number more? */
525 op = '*'; /* fake up one with a star */
528 op = '?'; /* fake up optional atom */
530 sprintf(max,"%.*d", next-max, iter - 1);
535 regparse = origparse - 1; /* offset ++ below */
540 fatal("Can't do {n,0}");
543 fatal("Can't do {0}");
552 if (!(flags&HASWIDTH) && op != '?')
553 FAIL("regexp *+ operand could be empty");
554 *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
556 if (op == '*' && (flags&SIMPLE))
557 reginsert(STAR, ret);
558 else if (op == '*') {
559 /* Emit x* as (x&|), where & means "self". */
560 reginsert(BRANCH, ret); /* Either x */
561 regoptail(ret, regnode(BACK)); /* and loop */
562 regoptail(ret, ret); /* back */
563 regtail(ret, regnode(BRANCH)); /* or */
564 regtail(ret, regnode(NOTHING)); /* null. */
565 } else if (op == '+' && (flags&SIMPLE))
566 reginsert(PLUS, ret);
567 else if (op == '+') {
568 /* Emit x+ as x(&|), where & means "self". */
569 next = regnode(BRANCH); /* Either */
571 regtail(regnode(BACK), ret); /* loop back */
572 regtail(next, regnode(BRANCH)); /* or */
573 regtail(ret, regnode(NOTHING)); /* null. */
574 } else if (op == '?') {
575 /* Emit x? as (x|) */
576 reginsert(BRANCH, ret); /* Either x */
577 regtail(ret, regnode(BRANCH)); /* or */
578 next = regnode(NOTHING); /* null. */
580 regoptail(ret, next);
584 if (ISMULT2(regparse))
585 FAIL("nested *?+ in regexp");
591 - regatom - the lowest level
593 * Optimization: gobbles an entire sequence of ordinary characters so that
594 * it can turn them into a single node, which is smaller to store and
595 * faster to run. Backslashed characters are exceptions, each becoming a
596 * separate node; the code is simpler that way and it's not worth fixing.
598 * [Yes, it is worth fixing, some scripts can run twice the speed.]
607 *flagp = WORST; /* Tentatively. */
609 switch (*regparse++) {
618 *flagp |= HASWIDTH|SIMPLE;
622 *flagp |= HASWIDTH|SIMPLE;
625 ret = reg(1, &flags);
628 *flagp |= flags&(HASWIDTH|SPSTART);
632 FAIL("internal urp in regexp"); /* Supposed to be caught earlier. */
637 FAIL("?+* follows nothing in regexp");
642 ret = regnode(ALNUM);
643 *flagp |= HASWIDTH|SIMPLE;
647 ret = regnode(NALNUM);
648 *flagp |= HASWIDTH|SIMPLE;
652 ret = regnode(BOUND);
657 ret = regnode(NBOUND);
662 ret = regnode(SPACE);
663 *flagp |= HASWIDTH|SIMPLE;
667 ret = regnode(NSPACE);
668 *flagp |= HASWIDTH|SIMPLE;
672 ret = regnode(DIGIT);
673 *flagp |= HASWIDTH|SIMPLE;
677 ret = regnode(NDIGIT);
678 *flagp |= HASWIDTH|SIMPLE;
686 case '0': case '1': case '2': case '3': case '4':
687 case '5': case '6': case '7': case '8': case '9':
688 if (isdigit(regparse[1]) || *regparse == '0')
691 ret = regnode(REF + *regparse++ - '0');
696 if (regparse >= regxend)
697 FAIL("trailing \\ in regexp");
711 ret = regnode(EXACTLY);
712 regc(0); /* save spot for len */
713 for (len=0, p=regparse-1;
714 len < 127 && p < regxend;
755 case '0': case '1': case '2': case '3':case '4':
756 case '5': case '6': case '7': case '8':case '9':
757 if (isdigit(p[1]) || *p == '0') {
760 foo = (foo<<3) + *++p - '0';
762 foo = (foo<<3) + *++p - '0';
773 FAIL("trailing \\ in regexp");
784 if (regfold && isupper(ender))
785 ender = tolower(ender);
786 if (ISMULT2(p)) { /* Back off on ?+*. */
800 FAIL("internal disaster in regexp");
804 if (regcode != ®dummy)
820 if (regcode == ®dummy)
824 bits[c >> 3] &= ~(1 << (c & 7));
826 bits[c >> 3] |= (1 << (c & 7));
834 register int lastclass;
835 register int range = 0;
839 ret = regnode(ANYOF);
840 if (*regparse == '^') { /* Complement of range. */
847 for (class = 0; class < 32; class++)
849 if (*regparse == ']' || *regparse == '-')
850 goto skipcond; /* allow 1st char to be ] or - */
851 while (regparse < regxend && *regparse != ']') {
853 class = UCHARAT(regparse++);
855 class = UCHARAT(regparse++);
858 for (class = 'a'; class <= 'z'; class++)
859 regset(bits,def,class);
860 for (class = 'A'; class <= 'Z'; class++)
861 regset(bits,def,class);
862 for (class = '0'; class <= '9'; class++)
863 regset(bits,def,class);
864 regset(bits,def,'_');
868 regset(bits,def,' ');
869 regset(bits,def,'\t');
870 regset(bits,def,'\r');
871 regset(bits,def,'\f');
872 regset(bits,def,'\n');
876 for (class = '0'; class <= '9'; class++)
877 regset(bits,def,class);
895 case '0': case '1': case '2': case '3': case '4':
896 case '5': case '6': case '7': case '8': case '9':
898 if (isdigit(*regparse)) {
900 class += *regparse++ - '0';
902 if (isdigit(*regparse)) {
904 class += *regparse++ - '0';
910 if (lastclass > class)
911 FAIL("invalid [] range in regexp");
916 if (*regparse == '-' && regparse+1 < regxend &&
917 regparse[1] != ']') {
920 continue; /* do it next time */
923 for ( ; lastclass <= class; lastclass++) {
924 regset(bits,def,lastclass);
925 if (regfold && isupper(lastclass))
926 regset(bits,def,tolower(lastclass));
930 if (*regparse != ']')
931 FAIL("unmatched [] in regexp");
937 - regnode - emit a node
939 static char * /* Location. */
947 if (ret == ®dummy) {
958 if (!((long)ret & 1))
964 *ptr++ = '\0'; /* Null "next" pointer. */
972 - regc - emit (if appropriate) a byte of code
978 if (regcode != ®dummy)
985 - reginsert - insert an operator in front of already-emitted operand
987 * Means relocating the operand.
996 register char *place;
997 register offset = (op == CURLY ? 4 : 0);
999 if (regcode == ®dummy) {
1001 regsize += 4 + offset;
1003 regsize += 3 + offset;
1010 regcode += 4 + offset;
1012 regcode += 3 + offset;
1018 place = opnd; /* Op node, where operand used to be. */
1022 while (offset-- > 0)
1027 - regtail - set the next-pointer at the end of a node chain
1034 register char *scan;
1035 register char *temp;
1036 register int offset;
1041 /* Find last node. */
1044 temp = regnext(scan);
1051 offset = val - scan;
1053 *(short*)(scan+1) = offset;
1058 if (OP(scan) == BACK)
1059 offset = scan - val;
1061 offset = val - scan;
1062 *(scan+1) = (offset>>8)&0377;
1063 *(scan+2) = offset&0377;
1068 - regoptail - regtail on operand of first argument; nop if operandless
1075 /* "Operandless" and "op != BRANCH" are synonymous in practice. */
1076 if (p == NULL || p == ®dummy || OP(p) != BRANCH)
1078 regtail(NEXTOPER(p), val);
1082 - regcurly - a little FSA that accepts {\d+,?\d*}
1106 - regdump - dump a regexp onto stderr in vaguely comprehensible form
1113 register char op = EXACTLY; /* Arbitrary non-END op. */
1114 register char *next;
1115 extern char *index();
1119 while (op != END) { /* While that wasn't END last time... */
1125 fprintf(stderr,"%2d%s", s-r->program, regprop(s)); /* Where, what. */
1127 if (next == NULL) /* Next ptr. */
1128 fprintf(stderr,"(0)");
1130 fprintf(stderr,"(%d)", (s-r->program)+(next-s));
1135 if (op == EXACTLY) {
1136 /* Literal string, where present. */
1138 while (*s != '\0') {
1144 (void)putchar('\n');
1147 /* Header fields of interest. */
1149 fprintf(stderr,"start `%s' ", r->regstart->str_ptr);
1151 fprintf(stderr,"stclass `%s' ", regprop(r->regstclass));
1153 fprintf(stderr,"anchored ");
1155 fprintf(stderr,"plus ");
1156 if (r->regmust != NULL)
1157 fprintf(stderr,"must have \"%s\" back %d ", r->regmust->str_ptr,
1159 fprintf(stderr,"\n");
1163 - regprop - printable representation of opcode
1171 (void) strcpy(buf, ":");
1226 (void)sprintf(buf+strlen(buf), "CURLY {%d,%d}",
1240 (void)sprintf(buf+strlen(buf), "REF%d", OP(op)-REF);
1252 (void)sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
1264 (void)sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1274 FAIL("corrupted regexp opcode");
1277 (void) strcat(buf, p);
1280 #endif /* DEBUGGING */
1286 Safefree(r->precomp);
1288 Safefree(r->subbase);
1290 str_free(r->regmust);
1292 str_free(r->regstart);