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.8 90/11/10 01:57:46 lwall Locked $
13 * Revision 3.0.1.8 90/11/10 01:57:46 lwall
14 * patch38: patterns with multiple constant strings occasionally malfed
15 * patch38: patterns like /foo.*foo/ sped up some
17 * Revision 3.0.1.7 90/10/20 02:18:32 lwall
18 * patch37: /foo.*bar$/ wrongly optimized to do tail matching on "foo"
20 * Revision 3.0.1.6 90/10/16 10:17:33 lwall
21 * patch29: patterns with multiple short literal strings sometimes failed
23 * Revision 3.0.1.5 90/08/13 22:23:29 lwall
24 * patch28: /x{m}/ didn't work right
26 * Revision 3.0.1.4 90/08/09 05:05:33 lwall
27 * patch19: sped up /x+y/ patterns greatly by not retrying on every x
28 * patch19: inhibited backoff on patterns anchored to the end like /\s+$/
29 * patch19: sped up {m,n} on simple items
30 * patch19: optimized /.*whatever/ to /^.*whatever/
31 * patch19: fixed character classes to allow backslashing hyphen
33 * Revision 3.0.1.3 90/03/12 16:59:22 lwall
34 * patch13: pattern matches can now use \0 to mean \000
36 * Revision 3.0.1.2 90/02/28 18:08:35 lwall
37 * patch9: /[\200-\377]/ didn't work on machines with signed chars
39 * Revision 3.0.1.1 89/11/11 04:51:04 lwall
40 * patch2: /[\000]/ didn't work
42 * Revision 3.0 89/10/18 15:22:29 lwall
48 * regcomp and regexec -- regsub and regerror are not used in perl
50 * Copyright (c) 1986 by University of Toronto.
51 * Written by Henry Spencer. Not derived from licensed software.
53 * Permission is granted to anyone to use this software for any
54 * purpose on any computer system, and to redistribute it freely,
55 * subject to the following restrictions:
57 * 1. The author is not responsible for the consequences of use of
58 * this software, no matter how awful, even if they arise
61 * 2. The origin of this software must not be misrepresented, either
62 * by explicit claim or by omission.
64 * 3. Altered versions must be plainly marked as such, and must not
65 * be misrepresented as being the original software.
68 **** Alterations to Henry's code are...
70 **** Copyright (c) 1989, Larry Wall
72 **** You may distribute under the terms of the GNU General Public License
73 **** as specified in the README file that comes with the perl 3.0 kit.
75 * Beware that some of this code is subtly aware of the way operator
76 * precedence is structured in regular expressions. Serious changes in
77 * regular-expression syntax might require a total rethink.
88 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
89 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
90 ((*s) == '{' && regcurly(s)))
91 #define META "^$.[()|?+*\\"
94 * Flags to be passed up and down.
96 #define HASWIDTH 01 /* Known never to match null string. */
97 #define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
98 #define SPSTART 04 /* Starts with * or +. */
99 #define WORST 0 /* Worst case. */
102 * Global work variables for regcomp().
104 static char *regprecomp; /* uncompiled string. */
105 static char *regparse; /* Input-scan pointer. */
106 static char *regxend; /* End of input for compile */
107 static int regnpar; /* () count. */
108 static char *regcode; /* Code-emit pointer; ®dummy = don't. */
109 static long regsize; /* Code size. */
111 static int regsawbracket; /* Did we do {d,d} trick? */
114 * Forward declarations for regcomp()'s friends.
116 STATIC int regcurly();
118 STATIC char *regbranch();
119 STATIC char *regpiece();
120 STATIC char *regatom();
121 STATIC char *regclass();
122 STATIC char *regnode();
124 STATIC void reginsert();
125 STATIC void regtail();
126 STATIC void regoptail();
129 - regcomp - compile a regular expression into internal code
131 * We can't allocate space until we know how big the compiled form will be,
132 * but we can't compile it (and thus know how big it is) until we've got a
133 * place to put the code. So we cheat: we compile it twice, once with code
134 * generation turned off and size counting turned on, and once "for real".
135 * This also means that we don't allocate space until we are sure that the
136 * thing really will compile successfully, and we never have to move the
137 * code and thus invalidate pointers into it. (Note that it has to be in
138 * one piece because free() must be able to free it all.) [NB: not true in perl]
140 * Beware that the optimization-preparation code in here knows about some
141 * of the structure of the compiled regexp. [I'll say.]
144 regcomp(exp,xend,fold)
151 register STR *longish;
154 register char *first;
159 extern char *safemalloc();
160 extern char *savestr();
164 fatal("NULL regexp argument");
166 /* First pass: determine size, legality. */
170 regprecomp = nsavestr(exp,xend-exp);
176 if (reg(0, &flags) == NULL) {
177 Safefree(regprecomp);
181 /* Small enough for pointer-storage convention? */
182 if (regsize >= 32767L) /* Probably could be 65535L. */
183 FAIL("regexp too big");
185 /* Allocate space. */
186 Newc(1001, r, sizeof(regexp) + (unsigned)regsize, char, regexp);
188 FAIL("regexp out of space");
190 /* Second pass: emit code. */
192 bcopy(regprecomp,exp,xend-exp);
193 r->precomp = regprecomp;
197 regcode = r->program;
199 if (reg(0, &flags) == NULL)
202 /* Dig out information for optimizations. */
203 r->regstart = Nullstr; /* Worst-case defaults. */
205 r->regmust = Nullstr;
207 r->regstclass = Nullch;
208 scan = r->program+1; /* First BRANCH. */
209 if (OP(regnext(scan)) == END) {/* Only one top-level choice. */
210 scan = NEXTOPER(scan);
213 while ((OP(first) > OPEN && OP(first) < CLOSE) ||
214 (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
215 (OP(first) == PLUS) ||
216 (OP(first) == CURLY && ARG1(first) > 0) ) {
217 if (OP(first) == CURLY)
219 else if (OP(first) == PLUS)
221 first = NEXTOPER(first);
224 /* Starting-point info. */
225 if (OP(first) == EXACTLY) {
227 str_make(OPERAND(first)+1,*OPERAND(first));
228 if (r->regstart->str_cur > !(sawstudy|fold))
229 fbmcompile(r->regstart,fold);
231 else if ((exp = index(simple,OP(first))) && exp > simple)
232 r->regstclass = first;
233 else if (OP(first) == BOUND || OP(first) == NBOUND)
234 r->regstclass = first;
235 else if (OP(first) == BOL ||
236 (OP(first) == STAR && OP(NEXTOPER(first)) == ANY) )
237 r->reganch = 1; /* kinda turn .* into ^.* */
238 r->reganch |= sawplus;
242 fprintf(stderr,"first %d next %d offset %d\n",
243 OP(first), OP(NEXTOPER(first)), first - scan);
246 * If there's something expensive in the r.e., find the
247 * longest literal string that must appear and make it the
248 * regmust. Resolve ties in favor of later strings, since
249 * the regstart check works with the beginning of the r.e.
250 * and avoiding duplication strengthens checking. Not a
251 * strong reason, but sufficient in the absence of others.
252 * [Now we resolve ties in favor of the earlier string if
253 * it happens that curback has been invalidated, since the
254 * earlier string may buy us something the later one won't.]
256 longish = str_make("",0);
257 longest = str_make("",0);
262 while (OP(scan) != END) {
263 if (OP(scan) == BRANCH) {
264 if (OP(regnext(scan)) == BRANCH) {
266 while (OP(scan) == BRANCH)
267 scan = regnext(scan);
269 else /* single branch is ok */
270 scan = NEXTOPER(scan);
272 if (OP(scan) == EXACTLY) {
274 while (OP(regnext(scan)) >= CLOSE)
275 scan = regnext(scan);
276 if (curback - backish == len) {
277 str_ncat(longish, OPERAND(first)+1,
279 len += *OPERAND(first);
280 curback += *OPERAND(first);
281 first = regnext(scan);
283 else if (*OPERAND(first) >= len + (curback >= 0)) {
284 len = *OPERAND(first);
285 str_nset(longish, OPERAND(first)+1,len);
288 first = regnext(scan);
291 curback += *OPERAND(first);
293 else if (index(varies,OP(scan))) {
296 if (longish->str_cur > longest->str_cur) {
297 str_sset(longest,longish);
300 str_nset(longish,"",0);
302 else if (index(simple,OP(scan))) {
305 if (longish->str_cur > longest->str_cur) {
306 str_sset(longest,longish);
309 str_nset(longish,"",0);
311 scan = regnext(scan);
314 /* Prefer earlier on tie, unless we can tail match latter */
316 if (longish->str_cur + (OP(first) == EOL) > longest->str_cur) {
317 str_sset(longest,longish);
321 str_nset(longish,"",0);
326 !fbminstr(r->regstart->str_ptr,
327 r->regstart->str_ptr + r->regstart->str_cur,
332 r->regmust = longest;
335 r->regback = backest;
337 > !(sawstudy || fold || OP(first) == EOL) )
338 fbmcompile(r->regmust,fold);
339 r->regmust->str_u.str_useful = 100;
340 if (OP(first) == EOL && longish->str_cur)
341 r->regmust->str_pok |= SP_TAIL;
348 r->do_folding = fold;
349 r->nparens = regnpar - 1;
358 - reg - regular expression, i.e. main body or parenthesized thing
360 * Caller must absorb opening parenthesis.
362 * Combining parenthesis handling with the base level of regular expression
363 * is a trifle forced, but the need to tie the tails of the branches to what
364 * follows makes it hard to avoid.
368 int paren; /* Parenthesized? */
373 register char *ender;
377 *flagp = HASWIDTH; /* Tentatively. */
379 /* Make an OPEN node, if parenthesized. */
381 if (regnpar >= NSUBEXP)
382 FAIL("too many () in regexp");
385 ret = regnode(OPEN+parno);
389 /* Pick up the branches, linking them together. */
390 br = regbranch(&flags);
394 regtail(ret, br); /* OPEN -> first. */
397 if (!(flags&HASWIDTH))
399 *flagp |= flags&SPSTART;
400 while (*regparse == '|') {
402 br = regbranch(&flags);
405 regtail(ret, br); /* BRANCH -> BRANCH. */
406 if (!(flags&HASWIDTH))
408 *flagp |= flags&SPSTART;
411 /* Make a closing node, and hook it on the end. */
412 ender = regnode((paren) ? CLOSE+parno : END);
415 /* Hook the tails of the branches to the closing node. */
416 for (br = ret; br != NULL; br = regnext(br))
417 regoptail(br, ender);
419 /* Check for proper termination. */
420 if (paren && *regparse++ != ')') {
421 FAIL("unmatched () in regexp");
422 } else if (!paren && regparse < regxend) {
423 if (*regparse == ')') {
424 FAIL("unmatched () in regexp");
426 FAIL("junk on end of regexp"); /* "Can't happen". */
434 - regbranch - one alternative of an | operator
436 * Implements the concatenation operator.
443 register char *chain;
444 register char *latest;
447 *flagp = WORST; /* Tentatively. */
449 ret = regnode(BRANCH);
451 while (regparse < regxend && *regparse != '|' && *regparse != ')') {
452 latest = regpiece(&flags);
455 *flagp |= flags&HASWIDTH;
456 if (chain == NULL) /* First piece. */
457 *flagp |= flags&SPSTART;
459 regtail(chain, latest);
462 if (chain == NULL) /* Loop ran zero times. */
463 (void) regnode(NOTHING);
469 - regpiece - something followed by possible [*+?]
471 * Note that the branching code sequences used for ? and the general cases
472 * of * and + are somewhat optimized: they use the same NOTHING node as
473 * both the endmarker for their branch list and the body of the last branch.
474 * It might seem that this node could be dispensed with entirely, but the
475 * endmarker role is not redundant.
485 char *origparse = regparse;
486 int orignpar = regnpar;
491 ret = regatom(&flags);
497 /* Here's a total kludge: if after the atom there's a {\d+,?\d*}
498 * then we decrement the first number by one and reset our
499 * parsing back to the beginning of the same atom. If the first number
500 * is down to 0, decrement the second number instead and fake up
501 * a ? after it. Given the way this compiler doesn't keep track
502 * of offsets on the first pass, this is the only way to replicate
503 * a piece of code. Sigh.
505 if (op == '{' && regcurly(regparse)) {
508 while (isdigit(*next) || *next == ',') {
517 if (*next == '}') { /* got one */
521 iter = atoi(regparse);
522 if (flags&SIMPLE) { /* we can do it right after all */
525 reginsert(CURLY, ret);
531 if (tmp && tmp < iter)
532 fatal("Can't do {n,m} with n > m");
533 if (regcode != ®dummy) {
535 *(unsigned short *)(ret+3) = iter;
536 *(unsigned short *)(ret+5) = tmp;
538 ret[3] = iter >> 8; ret[4] = iter & 0377;
539 ret[5] = tmp >> 8; ret[6] = tmp & 0377;
545 regsawbracket++; /* remember we clobbered exp */
548 sprintf(regparse,"%.*d", max-regparse, iter - 1);
550 if (*max == ',' && max[1] != '}') {
551 if (atoi(max+1) <= 0)
552 fatal("Can't do {n,m} with n > m");
554 sprintf(max+1,"%.*d", next-(max+1), atoi(max+1) - 1);
557 if (iter != 1 || *max == ',') {
558 regparse = origparse; /* back up input pointer */
559 regnpar = orignpar; /* don't make more parens */
571 if (max == next) { /* any number more? */
573 op = '*'; /* fake up one with a star */
576 op = '?'; /* fake up optional atom */
578 sprintf(max,"%.*d", next-max, iter - 1);
583 regparse = origparse - 1; /* offset ++ below */
588 fatal("Can't do {n,0}");
591 fatal("Can't do {0}");
600 if (!(flags&HASWIDTH) && op != '?')
601 FAIL("regexp *+ operand could be empty");
602 *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
604 if (op == '*' && (flags&SIMPLE))
605 reginsert(STAR, ret);
606 else if (op == '*') {
607 /* Emit x* as (x&|), where & means "self". */
608 reginsert(BRANCH, ret); /* Either x */
609 regoptail(ret, regnode(BACK)); /* and loop */
610 regoptail(ret, ret); /* back */
611 regtail(ret, regnode(BRANCH)); /* or */
612 regtail(ret, regnode(NOTHING)); /* null. */
613 } else if (op == '+' && (flags&SIMPLE))
614 reginsert(PLUS, ret);
615 else if (op == '+') {
616 /* Emit x+ as x(&|), where & means "self". */
617 next = regnode(BRANCH); /* Either */
619 regtail(regnode(BACK), ret); /* loop back */
620 regtail(next, regnode(BRANCH)); /* or */
621 regtail(ret, regnode(NOTHING)); /* null. */
622 } else if (op == '?') {
623 /* Emit x? as (x|) */
624 reginsert(BRANCH, ret); /* Either x */
625 regtail(ret, regnode(BRANCH)); /* or */
626 next = regnode(NOTHING); /* null. */
628 regoptail(ret, next);
632 if (ISMULT2(regparse))
633 FAIL("nested *?+ in regexp");
639 - regatom - the lowest level
641 * Optimization: gobbles an entire sequence of ordinary characters so that
642 * it can turn them into a single node, which is smaller to store and
643 * faster to run. Backslashed characters are exceptions, each becoming a
644 * separate node; the code is simpler that way and it's not worth fixing.
646 * [Yes, it is worth fixing, some scripts can run twice the speed.]
655 *flagp = WORST; /* Tentatively. */
657 switch (*regparse++) {
666 *flagp |= HASWIDTH|SIMPLE;
670 *flagp |= HASWIDTH|SIMPLE;
673 ret = reg(1, &flags);
676 *flagp |= flags&(HASWIDTH|SPSTART);
680 FAIL("internal urp in regexp"); /* Supposed to be caught earlier. */
685 FAIL("?+* follows nothing in regexp");
690 ret = regnode(ALNUM);
691 *flagp |= HASWIDTH|SIMPLE;
695 ret = regnode(NALNUM);
696 *flagp |= HASWIDTH|SIMPLE;
700 ret = regnode(BOUND);
705 ret = regnode(NBOUND);
710 ret = regnode(SPACE);
711 *flagp |= HASWIDTH|SIMPLE;
715 ret = regnode(NSPACE);
716 *flagp |= HASWIDTH|SIMPLE;
720 ret = regnode(DIGIT);
721 *flagp |= HASWIDTH|SIMPLE;
725 ret = regnode(NDIGIT);
726 *flagp |= HASWIDTH|SIMPLE;
734 case '0': case '1': case '2': case '3': case '4':
735 case '5': case '6': case '7': case '8': case '9':
736 if (isdigit(regparse[1]) || *regparse == '0')
739 ret = regnode(REF + *regparse++ - '0');
744 if (regparse >= regxend)
745 FAIL("trailing \\ in regexp");
759 ret = regnode(EXACTLY);
760 regc(0); /* save spot for len */
761 for (len=0, p=regparse-1;
762 len < 127 && p < regxend;
803 case '0': case '1': case '2': case '3':case '4':
804 case '5': case '6': case '7': case '8':case '9':
805 if (isdigit(p[1]) || *p == '0') {
808 foo = (foo<<3) + *++p - '0';
810 foo = (foo<<3) + *++p - '0';
821 FAIL("trailing \\ in regexp");
832 if (regfold && isupper(ender))
833 ender = tolower(ender);
834 if (ISMULT2(p)) { /* Back off on ?+*. */
848 FAIL("internal disaster in regexp");
852 if (regcode != ®dummy)
868 if (regcode == ®dummy)
872 bits[c >> 3] &= ~(1 << (c & 7));
874 bits[c >> 3] |= (1 << (c & 7));
882 register int lastclass;
883 register int range = 0;
887 ret = regnode(ANYOF);
888 if (*regparse == '^') { /* Complement of range. */
895 for (class = 0; class < 32; class++)
897 if (*regparse == ']' || *regparse == '-')
898 goto skipcond; /* allow 1st char to be ] or - */
899 while (regparse < regxend && *regparse != ']') {
901 class = UCHARAT(regparse++);
903 class = UCHARAT(regparse++);
906 for (class = 'a'; class <= 'z'; class++)
907 regset(bits,def,class);
908 for (class = 'A'; class <= 'Z'; class++)
909 regset(bits,def,class);
910 for (class = '0'; class <= '9'; class++)
911 regset(bits,def,class);
912 regset(bits,def,'_');
916 regset(bits,def,' ');
917 regset(bits,def,'\t');
918 regset(bits,def,'\r');
919 regset(bits,def,'\f');
920 regset(bits,def,'\n');
924 for (class = '0'; class <= '9'; class++)
925 regset(bits,def,class);
943 case '0': case '1': case '2': case '3': case '4':
944 case '5': case '6': case '7': case '8': case '9':
946 if (isdigit(*regparse)) {
948 class += *regparse++ - '0';
950 if (isdigit(*regparse)) {
952 class += *regparse++ - '0';
958 if (lastclass > class)
959 FAIL("invalid [] range in regexp");
964 if (*regparse == '-' && regparse+1 < regxend &&
965 regparse[1] != ']') {
968 continue; /* do it next time */
971 for ( ; lastclass <= class; lastclass++) {
972 regset(bits,def,lastclass);
973 if (regfold && isupper(lastclass))
974 regset(bits,def,tolower(lastclass));
978 if (*regparse != ']')
979 FAIL("unmatched [] in regexp");
985 - regnode - emit a node
987 static char * /* Location. */
995 if (ret == ®dummy) {
1006 if (!((long)ret & 1))
1012 *ptr++ = '\0'; /* Null "next" pointer. */
1020 - regc - emit (if appropriate) a byte of code
1026 if (regcode != ®dummy)
1033 - reginsert - insert an operator in front of already-emitted operand
1035 * Means relocating the operand.
1044 register char *place;
1045 register offset = (op == CURLY ? 4 : 0);
1047 if (regcode == ®dummy) {
1049 regsize += 4 + offset;
1051 regsize += 3 + offset;
1058 regcode += 4 + offset;
1060 regcode += 3 + offset;
1066 place = opnd; /* Op node, where operand used to be. */
1070 while (offset-- > 0)
1075 - regtail - set the next-pointer at the end of a node chain
1082 register char *scan;
1083 register char *temp;
1084 register int offset;
1089 /* Find last node. */
1092 temp = regnext(scan);
1099 offset = val - scan;
1101 *(short*)(scan+1) = offset;
1106 if (OP(scan) == BACK)
1107 offset = scan - val;
1109 offset = val - scan;
1110 *(scan+1) = (offset>>8)&0377;
1111 *(scan+2) = offset&0377;
1116 - regoptail - regtail on operand of first argument; nop if operandless
1123 /* "Operandless" and "op != BRANCH" are synonymous in practice. */
1124 if (p == NULL || p == ®dummy || OP(p) != BRANCH)
1126 regtail(NEXTOPER(p), val);
1130 - regcurly - a little FSA that accepts {\d+,?\d*}
1154 - regdump - dump a regexp onto stderr in vaguely comprehensible form
1161 register char op = EXACTLY; /* Arbitrary non-END op. */
1162 register char *next;
1163 extern char *index();
1167 while (op != END) { /* While that wasn't END last time... */
1173 fprintf(stderr,"%2d%s", s-r->program, regprop(s)); /* Where, what. */
1177 if (next == NULL) /* Next ptr. */
1178 fprintf(stderr,"(0)");
1180 fprintf(stderr,"(%d)", (s-r->program)+(next-s));
1185 if (op == EXACTLY) {
1186 /* Literal string, where present. */
1188 while (*s != '\0') {
1194 (void)putchar('\n');
1197 /* Header fields of interest. */
1199 fprintf(stderr,"start `%s' ", r->regstart->str_ptr);
1201 fprintf(stderr,"stclass `%s' ", regprop(r->regstclass));
1203 fprintf(stderr,"anchored ");
1205 fprintf(stderr,"plus ");
1206 if (r->regmust != NULL)
1207 fprintf(stderr,"must have \"%s\" back %d ", r->regmust->str_ptr,
1209 fprintf(stderr,"\n");
1213 - regprop - printable representation of opcode
1221 (void) strcpy(buf, ":");
1276 (void)sprintf(buf+strlen(buf), "CURLY {%d,%d}",
1290 (void)sprintf(buf+strlen(buf), "REF%d", OP(op)-REF);
1302 (void)sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
1314 (void)sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1324 FAIL("corrupted regexp opcode");
1327 (void) strcat(buf, p);
1330 #endif /* DEBUGGING */
1336 Safefree(r->precomp);
1338 Safefree(r->subbase);
1340 str_free(r->regmust);
1342 str_free(r->regstart);