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.3 90/03/12 16:59:22 lwall Locked $
13 * Revision 3.0.1.3 90/03/12 16:59:22 lwall
14 * patch13: pattern matches can now use \0 to mean \000
16 * Revision 3.0.1.2 90/02/28 18:08:35 lwall
17 * patch9: /[\200-\377]/ didn't work on machines with signed chars
19 * Revision 3.0.1.1 89/11/11 04:51:04 lwall
20 * patch2: /[\000]/ didn't work
22 * Revision 3.0 89/10/18 15:22:29 lwall
28 * regcomp and regexec -- regsub and regerror are not used in perl
30 * Copyright (c) 1986 by University of Toronto.
31 * Written by Henry Spencer. Not derived from licensed software.
33 * Permission is granted to anyone to use this software for any
34 * purpose on any computer system, and to redistribute it freely,
35 * subject to the following restrictions:
37 * 1. The author is not responsible for the consequences of use of
38 * this software, no matter how awful, even if they arise
41 * 2. The origin of this software must not be misrepresented, either
42 * by explicit claim or by omission.
44 * 3. Altered versions must be plainly marked as such, and must not
45 * be misrepresented as being the original software.
48 **** Alterations to Henry's code are...
50 **** Copyright (c) 1989, Larry Wall
52 **** You may distribute under the terms of the GNU General Public License
53 **** as specified in the README file that comes with the perl 3.0 kit.
55 * Beware that some of this code is subtly aware of the way operator
56 * precedence is structured in regular expressions. Serious changes in
57 * regular-expression syntax might require a total rethink.
68 #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
69 #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
70 ((*s) == '{' && regcurly(s)))
71 #define META "^$.[()|?+*\\"
74 * Flags to be passed up and down.
76 #define HASWIDTH 01 /* Known never to match null string. */
77 #define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
78 #define SPSTART 04 /* Starts with * or +. */
79 #define WORST 0 /* Worst case. */
82 * Global work variables for regcomp().
84 static char *regprecomp; /* uncompiled string. */
85 static char *regparse; /* Input-scan pointer. */
86 static char *regxend; /* End of input for compile */
87 static int regnpar; /* () count. */
88 static char *regcode; /* Code-emit pointer; ®dummy = don't. */
89 static long regsize; /* Code size. */
91 static int regsawbracket; /* Did we do {d,d} trick? */
94 * Forward declarations for regcomp()'s friends.
96 STATIC int regcurly();
98 STATIC char *regbranch();
99 STATIC char *regpiece();
100 STATIC char *regatom();
101 STATIC char *regclass();
102 STATIC char *regnode();
104 STATIC void reginsert();
105 STATIC void regtail();
106 STATIC void regoptail();
109 - regcomp - compile a regular expression into internal code
111 * We can't allocate space until we know how big the compiled form will be,
112 * but we can't compile it (and thus know how big it is) until we've got a
113 * place to put the code. So we cheat: we compile it twice, once with code
114 * generation turned off and size counting turned on, and once "for real".
115 * This also means that we don't allocate space until we are sure that the
116 * thing really will compile successfully, and we never have to move the
117 * code and thus invalidate pointers into it. (Note that it has to be in
118 * one piece because free() must be able to free it all.) [NB: not true in perl]
120 * Beware that the optimization-preparation code in here knows about some
121 * of the structure of the compiled regexp. [I'll say.]
124 regcomp(exp,xend,fold,rare)
132 register STR *longest;
134 register char *first;
138 extern char *safemalloc();
139 extern char *savestr();
142 fatal("NULL regexp argument");
144 /* First pass: determine size, legality. */
148 regprecomp = nsavestr(exp,xend-exp);
154 if (reg(0, &flags) == NULL) {
155 Safefree(regprecomp);
159 /* Small enough for pointer-storage convention? */
160 if (regsize >= 32767L) /* Probably could be 65535L. */
161 FAIL("regexp too big");
163 /* Allocate space. */
164 Newc(1001, r, sizeof(regexp) + (unsigned)regsize, char, regexp);
166 FAIL("regexp out of space");
168 /* Second pass: emit code. */
170 bcopy(regprecomp,exp,xend-exp);
171 r->precomp = regprecomp;
175 regcode = r->program;
177 if (reg(0, &flags) == NULL)
180 /* Dig out information for optimizations. */
181 r->regstart = Nullstr; /* Worst-case defaults. */
183 r->regmust = Nullstr;
185 r->regstclass = Nullch;
186 scan = r->program+1; /* First BRANCH. */
187 if (OP(regnext(scan)) == END) {/* Only one top-level choice. */
188 scan = NEXTOPER(scan);
191 while ((OP(first) > OPEN && OP(first) < CLOSE) ||
192 (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
193 (OP(first) == PLUS) )
194 first = NEXTOPER(first);
196 /* Starting-point info. */
197 if (OP(first) == EXACTLY) {
199 str_make(OPERAND(first)+1,*OPERAND(first));
200 if (r->regstart->str_cur > !(sawstudy|fold))
201 fbmcompile(r->regstart,fold);
203 else if ((exp = index(simple,OP(first))) && exp > simple)
204 r->regstclass = first;
205 else if (OP(first) == BOUND || OP(first) == NBOUND)
206 r->regstclass = first;
207 else if (OP(first) == BOL)
212 fprintf(stderr,"first %d next %d offset %d\n",
213 OP(first), OP(NEXTOPER(first)), first - scan);
216 * If there's something expensive in the r.e., find the
217 * longest literal string that must appear and make it the
218 * regmust. Resolve ties in favor of later strings, since
219 * the regstart check works with the beginning of the r.e.
220 * and avoiding duplication strengthens checking. Not a
221 * strong reason, but sufficient in the absence of others.
222 * [Now we resolve ties in favor of the earlier string if
223 * it happens that curback has been invalidated, since the
224 * earlier string may buy us something the later one won't.]
226 longest = str_make("",0);
230 while (scan != NULL) {
231 if (OP(scan) == BRANCH) {
232 if (OP(regnext(scan)) == BRANCH) {
234 while (OP(scan) == BRANCH)
235 scan = regnext(scan);
237 else /* single branch is ok */
238 scan = NEXTOPER(scan);
240 if (OP(scan) == EXACTLY) {
242 while (OP(regnext(scan)) >= CLOSE)
243 scan = regnext(scan);
244 if (curback - back == len) {
245 str_ncat(longest, OPERAND(first)+1,
247 len += *OPERAND(first);
248 curback += *OPERAND(first);
249 first = regnext(scan);
251 else if (*OPERAND(first) >= len + (curback >= 0)) {
252 len = *OPERAND(first);
253 str_nset(longest, OPERAND(first)+1,len);
256 first = regnext(scan);
259 curback += *OPERAND(first);
261 else if (index(varies,OP(scan)))
263 else if (index(simple,OP(scan)))
265 scan = regnext(scan);
268 r->regmust = longest;
272 if (len > !(sawstudy||fold||OP(first)==EOL))
273 fbmcompile(r->regmust,fold);
274 r->regmust->str_u.str_useful = 100;
275 if (OP(first) == EOL) /* is match anchored to EOL? */
276 r->regmust->str_pok |= SP_TAIL;
282 r->do_folding = fold;
283 r->nparens = regnpar - 1;
292 - reg - regular expression, i.e. main body or parenthesized thing
294 * Caller must absorb opening parenthesis.
296 * Combining parenthesis handling with the base level of regular expression
297 * is a trifle forced, but the need to tie the tails of the branches to what
298 * follows makes it hard to avoid.
302 int paren; /* Parenthesized? */
307 register char *ender;
311 *flagp = HASWIDTH; /* Tentatively. */
313 /* Make an OPEN node, if parenthesized. */
315 if (regnpar >= NSUBEXP)
316 FAIL("too many () in regexp");
319 ret = regnode(OPEN+parno);
323 /* Pick up the branches, linking them together. */
324 br = regbranch(&flags);
328 regtail(ret, br); /* OPEN -> first. */
331 if (!(flags&HASWIDTH))
333 *flagp |= flags&SPSTART;
334 while (*regparse == '|') {
336 br = regbranch(&flags);
339 regtail(ret, br); /* BRANCH -> BRANCH. */
340 if (!(flags&HASWIDTH))
342 *flagp |= flags&SPSTART;
345 /* Make a closing node, and hook it on the end. */
346 ender = regnode((paren) ? CLOSE+parno : END);
349 /* Hook the tails of the branches to the closing node. */
350 for (br = ret; br != NULL; br = regnext(br))
351 regoptail(br, ender);
353 /* Check for proper termination. */
354 if (paren && *regparse++ != ')') {
355 FAIL("unmatched () in regexp");
356 } else if (!paren && regparse < regxend) {
357 if (*regparse == ')') {
358 FAIL("unmatched () in regexp");
360 FAIL("junk on end of regexp"); /* "Can't happen". */
368 - regbranch - one alternative of an | operator
370 * Implements the concatenation operator.
377 register char *chain;
378 register char *latest;
381 *flagp = WORST; /* Tentatively. */
383 ret = regnode(BRANCH);
385 while (regparse < regxend && *regparse != '|' && *regparse != ')') {
386 latest = regpiece(&flags);
389 *flagp |= flags&HASWIDTH;
390 if (chain == NULL) /* First piece. */
391 *flagp |= flags&SPSTART;
393 regtail(chain, latest);
396 if (chain == NULL) /* Loop ran zero times. */
397 (void) regnode(NOTHING);
403 - regpiece - something followed by possible [*+?]
405 * Note that the branching code sequences used for ? and the general cases
406 * of * and + are somewhat optimized: they use the same NOTHING node as
407 * both the endmarker for their branch list and the body of the last branch.
408 * It might seem that this node could be dispensed with entirely, but the
409 * endmarker role is not redundant.
419 char *origparse = regparse;
420 int orignpar = regnpar;
425 ret = regatom(&flags);
431 /* Here's a total kludge: if after the atom there's a {\d+,?\d*}
432 * then we decrement the first number by one and reset our
433 * parsing back to the beginning of the same atom. If the first number
434 * is down to 0, decrement the second number instead and fake up
435 * a ? after it. Given the way this compiler doesn't keep track
436 * of offsets on the first pass, this is the only way to replicate
437 * a piece of code. Sigh.
439 if (op == '{' && regcurly(regparse)) {
442 while (isdigit(*next) || *next == ',') {
451 if (*next == '}') { /* got one */
452 regsawbracket++; /* remember we clobbered exp */
456 iter = atoi(regparse);
459 sprintf(regparse,"%.*d", max-regparse, iter - 1);
461 if (*max == ',' && atoi(max+1) > 0) {
463 sprintf(max+1,"%.*d", next-(max+1), atoi(max+1) - 1);
466 if (iter != 1 || (*max == ',' || atoi(max+1))) {
467 regparse = origparse; /* back up input pointer */
468 regnpar = orignpar; /* don't make more parens */
480 if (max == next) { /* any number more? */
482 op = '*'; /* fake up one with a star */
485 op = '?'; /* fake up optional atom */
487 sprintf(max,"%.*d", next-max, iter - 1);
492 regparse = origparse - 1; /* offset ++ below */
497 fatal("Can't do {n,0}");
500 fatal("Can't do {0}");
509 if (!(flags&HASWIDTH) && op != '?')
510 FAIL("regexp *+ operand could be empty");
511 *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
513 if (op == '*' && (flags&SIMPLE))
514 reginsert(STAR, ret);
515 else if (op == '*') {
516 /* Emit x* as (x&|), where & means "self". */
517 reginsert(BRANCH, ret); /* Either x */
518 regoptail(ret, regnode(BACK)); /* and loop */
519 regoptail(ret, ret); /* back */
520 regtail(ret, regnode(BRANCH)); /* or */
521 regtail(ret, regnode(NOTHING)); /* null. */
522 } else if (op == '+' && (flags&SIMPLE))
523 reginsert(PLUS, ret);
524 else if (op == '+') {
525 /* Emit x+ as x(&|), where & means "self". */
526 next = regnode(BRANCH); /* Either */
528 regtail(regnode(BACK), ret); /* loop back */
529 regtail(next, regnode(BRANCH)); /* or */
530 regtail(ret, regnode(NOTHING)); /* null. */
531 } else if (op == '?') {
532 /* Emit x? as (x|) */
533 reginsert(BRANCH, ret); /* Either x */
534 regtail(ret, regnode(BRANCH)); /* or */
535 next = regnode(NOTHING); /* null. */
537 regoptail(ret, next);
541 if (ISMULT2(regparse))
542 FAIL("nested *?+ in regexp");
548 - regatom - the lowest level
550 * Optimization: gobbles an entire sequence of ordinary characters so that
551 * it can turn them into a single node, which is smaller to store and
552 * faster to run. Backslashed characters are exceptions, each becoming a
553 * separate node; the code is simpler that way and it's not worth fixing.
555 * [Yes, it is worth fixing, some scripts can run twice the speed.]
564 *flagp = WORST; /* Tentatively. */
566 switch (*regparse++) {
575 *flagp |= HASWIDTH|SIMPLE;
579 *flagp |= HASWIDTH|SIMPLE;
582 ret = reg(1, &flags);
585 *flagp |= flags&(HASWIDTH|SPSTART);
589 FAIL("internal urp in regexp"); /* Supposed to be caught earlier. */
594 FAIL("?+* follows nothing in regexp");
599 ret = regnode(ALNUM);
600 *flagp |= HASWIDTH|SIMPLE;
604 ret = regnode(NALNUM);
605 *flagp |= HASWIDTH|SIMPLE;
609 ret = regnode(BOUND);
614 ret = regnode(NBOUND);
619 ret = regnode(SPACE);
620 *flagp |= HASWIDTH|SIMPLE;
624 ret = regnode(NSPACE);
625 *flagp |= HASWIDTH|SIMPLE;
629 ret = regnode(DIGIT);
630 *flagp |= HASWIDTH|SIMPLE;
634 ret = regnode(NDIGIT);
635 *flagp |= HASWIDTH|SIMPLE;
643 case '0': case '1': case '2': case '3': case '4':
644 case '5': case '6': case '7': case '8': case '9':
645 if (isdigit(regparse[1]) || *regparse == '0')
648 ret = regnode(REF + *regparse++ - '0');
653 if (regparse >= regxend)
654 FAIL("trailing \\ in regexp");
668 ret = regnode(EXACTLY);
669 regc(0); /* save spot for len */
670 for (len=0, p=regparse-1;
671 len < 127 && p < regxend;
712 case '0': case '1': case '2': case '3':case '4':
713 case '5': case '6': case '7': case '8':case '9':
714 if (isdigit(p[1]) || *p == '0') {
717 foo = (foo<<3) + *++p - '0';
719 foo = (foo<<3) + *++p - '0';
730 FAIL("trailing \\ in regexp");
741 if (regfold && isupper(ender))
742 ender = tolower(ender);
743 if (ISMULT2(p)) { /* Back off on ?+*. */
757 FAIL("internal disaster in regexp");
761 if (regcode != ®dummy)
777 if (regcode == ®dummy)
781 bits[c >> 3] &= ~(1 << (c & 7));
783 bits[c >> 3] |= (1 << (c & 7));
791 register int lastclass;
792 register int range = 0;
796 if (*regparse == '^') { /* Complement of range. */
797 ret = regnode(ANYBUT);
801 ret = regnode(ANYOF);
805 for (class = 0; class < 32; class++)
807 if (*regparse == ']' || *regparse == '-')
808 regset(bits,def,lastclass = *regparse++);
809 while (regparse < regxend && *regparse != ']') {
810 class = UCHARAT(regparse++);
812 class = UCHARAT(regparse++);
815 for (class = 'a'; class <= 'z'; class++)
816 regset(bits,def,class);
817 for (class = 'A'; class <= 'Z'; class++)
818 regset(bits,def,class);
819 for (class = '0'; class <= '9'; class++)
820 regset(bits,def,class);
821 regset(bits,def,'_');
825 regset(bits,def,' ');
826 regset(bits,def,'\t');
827 regset(bits,def,'\r');
828 regset(bits,def,'\f');
829 regset(bits,def,'\n');
833 for (class = '0'; class <= '9'; class++)
834 regset(bits,def,class);
852 case '0': case '1': case '2': case '3': case '4':
853 case '5': case '6': case '7': case '8': case '9':
855 if (isdigit(*regparse)) {
857 class += *regparse++ - '0';
859 if (isdigit(*regparse)) {
861 class += *regparse++ - '0';
866 if (!range && class == '-' && regparse < regxend &&
872 if (lastclass > class)
873 FAIL("invalid [] range in regexp");
876 lastclass = class - 1;
878 for (lastclass++; lastclass <= class; lastclass++) {
879 regset(bits,def,lastclass);
880 if (regfold && isupper(lastclass))
881 regset(bits,def,tolower(lastclass));
885 if (*regparse != ']')
886 FAIL("unmatched [] in regexp");
892 - regnode - emit a node
894 static char * /* Location. */
902 if (ret == ®dummy) {
913 if (!((long)ret & 1))
919 *ptr++ = '\0'; /* Null "next" pointer. */
927 - regc - emit (if appropriate) a byte of code
933 if (regcode != ®dummy)
940 - reginsert - insert an operator in front of already-emitted operand
942 * Means relocating the operand.
951 register char *place;
953 if (regcode == ®dummy) {
972 place = opnd; /* Op node, where operand used to be. */
979 - regtail - set the next-pointer at the end of a node chain
993 /* Find last node. */
996 temp = regnext(scan);
1003 offset = val - scan;
1005 *(short*)(scan+1) = offset;
1010 if (OP(scan) == BACK)
1011 offset = scan - val;
1013 offset = val - scan;
1014 *(scan+1) = (offset>>8)&0377;
1015 *(scan+2) = offset&0377;
1020 - regoptail - regtail on operand of first argument; nop if operandless
1027 /* "Operandless" and "op != BRANCH" are synonymous in practice. */
1028 if (p == NULL || p == ®dummy || OP(p) != BRANCH)
1030 regtail(NEXTOPER(p), val);
1034 - regcurly - a little FSA that accepts {\d+,?\d*}
1058 - regdump - dump a regexp onto stderr in vaguely comprehensible form
1065 register char op = EXACTLY; /* Arbitrary non-END op. */
1066 register char *next;
1067 extern char *index();
1071 while (op != END) { /* While that wasn't END last time... */
1077 fprintf(stderr,"%2d%s", s-r->program, regprop(s)); /* Where, what. */
1079 if (next == NULL) /* Next ptr. */
1080 fprintf(stderr,"(0)");
1082 fprintf(stderr,"(%d)", (s-r->program)+(next-s));
1084 if (op == ANYOF || op == ANYBUT) {
1087 if (op == EXACTLY) {
1088 /* Literal string, where present. */
1090 while (*s != '\0') {
1096 (void)putchar('\n');
1099 /* Header fields of interest. */
1101 fprintf(stderr,"start `%s' ", r->regstart->str_ptr);
1103 fprintf(stderr,"stclass `%s' ", regprop(r->regstclass));
1105 fprintf(stderr,"anchored ");
1106 if (r->regmust != NULL)
1107 fprintf(stderr,"must have \"%s\" back %d ", r->regmust->str_ptr,
1109 fprintf(stderr,"\n");
1113 - regprop - printable representation of opcode
1121 (void) strcpy(buf, ":");
1188 (void)sprintf(buf+strlen(buf), "REF%d", OP(op)-REF);
1200 (void)sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
1212 (void)sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1222 FAIL("corrupted regexp opcode");
1225 (void) strcat(buf, p);
1228 #endif /* DEBUGGING */
1234 Safefree(r->precomp);
1236 Safefree(r->subbase);
1238 str_free(r->regmust);
1240 str_free(r->regstart);