2 * regcomp and regexec -- regsub and regerror are elsewhere
4 * Copyright (c) 1986 by University of Toronto.
5 * Written by Henry Spencer. Not derived from licensed software.
7 * Permission is granted to anyone to use this software for any
8 * purpose on any computer system, and to redistribute it freely,
9 * subject to the following restrictions:
11 * 1. The author is not responsible for the consequences of use of
12 * this software, no matter how awful, even if they arise
15 * 2. The origin of this software must not be misrepresented, either
16 * by explicit claim or by omission.
18 * 3. Altered versions must be plainly marked as such, and must not
19 * be misrepresented as being the original software.
21 * Beware that some of this code is subtly aware of the way operator
22 * precedence is structured in regular expressions. Serious changes in
23 * regular-expression syntax might require a total rethink.
25 * *** NOTE: this code has been altered slightly for use in Tcl. ***
26 * *** The only change is to use ckalloc and ckfree instead of ***
27 * *** malloc and free. ***
29 * *** and again for Expect!!! - DEL
31 * *** More minor corrections stolen from tcl7.5p1/regexp.c - DEL
36 #include "expect_cf.h"
38 #include "tclRegexp.h"
39 #include "exp_regexp.h"
42 #define NOTSTATIC /* was at one time, but Expect needs access */
45 * The "internal use only" fields in regexp.h are present to pass info from
46 * compile to execute that permits the execute phase to run lots faster on
47 * simple cases. They are:
49 * regstart char that must begin a match; '\0' if none obvious
50 * reganch is the match anchored (at beginning-of-line only)?
51 * regmust string (pointer into program) that match must include, or NULL
52 * regmlen length of regmust string
54 * Regstart and reganch permit very fast decisions on suitable starting points
55 * for a match, cutting down the work a lot. Regmust permits fast rejection
56 * of lines that cannot possibly match. The regmust tests are costly enough
57 * that regcomp() supplies a regmust only if the r.e. contains something
58 * potentially expensive (at present, the only such thing detected is * or +
59 * at the start of the r.e., which can involve a lot of backup). Regmlen is
60 * supplied because the test in regexec() needs it and regcomp() is computing
65 * Structure for regexp "program". This is essentially a linear encoding
66 * of a nondeterministic finite-state machine (aka syntax charts or
67 * "railroad normal form" in parsing technology). Each node is an opcode
68 * plus a "next" pointer, possibly plus an operand. "Next" pointers of
69 * all nodes except BRANCH implement concatenation; a "next" pointer with
70 * a BRANCH on both ends of it is connecting two alternatives. (Here we
71 * have one of the subtle syntax dependencies: an individual BRANCH (as
72 * opposed to a collection of them) is never concatenated with anything
73 * because of operator precedence.) The operand of some types of node is
74 * a literal string; for others, it is a node leading into a sub-FSM. In
75 * particular, the operand of a BRANCH node is the first node of the branch.
76 * (NB this is *not* a tree structure: the tail of the branch connects
77 * to the thing following the set of BRANCHes.) The opcodes are:
80 /* definition number opnd? meaning */
81 #define END 0 /* no End of program. */
82 #define BOL 1 /* no Match "" at beginning of line. */
83 #define EOL 2 /* no Match "" at end of line. */
84 #define ANY 3 /* no Match any one character. */
85 #define ANYOF 4 /* str Match any character in this string. */
86 #define ANYBUT 5 /* str Match any character not in this string. */
87 #define BRANCH 6 /* node Match this alternative, or the next... */
88 #define BACK 7 /* no Match "", "next" ptr points backward. */
89 #define EXACTLY 8 /* str Match this string. */
90 #define NOTHING 9 /* no Match empty string. */
91 #define STAR 10 /* node Match this (simple) thing 0 or more times. */
92 #define PLUS 11 /* node Match this (simple) thing 1 or more times. */
93 #define OPEN 20 /* no Mark this point in input as start of #n. */
94 /* OPEN+1 is number 1, etc. */
95 #define CLOSE (OPEN+NSUBEXP) /* no Analogous to OPEN. */
100 * BRANCH The set of branches constituting a single choice are hooked
101 * together with their "next" pointers, since precedence prevents
102 * anything being concatenated to any individual branch. The
103 * "next" pointer of the last BRANCH in a choice points to the
104 * thing following the whole choice. This is also where the
105 * final "next" pointer of each individual branch points; each
106 * branch starts with the operand node of a BRANCH node.
108 * BACK Normal "next" pointers all implicitly point forward; BACK
109 * exists to make loop structures possible.
111 * STAR,PLUS '?', and complex '*' and '+', are implemented as circular
112 * BRANCH structures using BACK. Simple cases (one character
113 * per match) are implemented with STAR and PLUS for speed
114 * and to minimize recursive plunges.
116 * OPEN,CLOSE ...are numbered at compile time.
120 * A node is one char of opcode followed by two chars of "next" pointer.
121 * "Next" pointers are stored as two 8-bit pieces, high order first. The
122 * value is a positive offset from the opcode of the node containing it.
123 * An operand, if any, simply follows the node. (Note that much of the
124 * code generation knows about this implicit relationship.)
126 * Using two bytes for the "next" pointer is vast overkill for most things,
127 * but allows patterns to get big without disasters.
130 #define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
131 #define OPERAND(p) ((p) + 3)
134 * See regmagic.h for one further detail of program structure.
139 * Utility definitions.
142 #define UCHARAT(p) ((int)*(unsigned char *)(p))
144 #define UCHARAT(p) ((int)*(p)&CHARBITS)
147 #define FAIL(m) { regerror(m); return(NULL); }
148 #define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
149 #define META "^$.[()|?+*\\"
152 * Flags to be passed up and down.
154 #define HASWIDTH 01 /* Known never to match null string. */
155 #define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
156 #define SPSTART 04 /* Starts with * or +. */
157 #define WORST 0 /* Worst case. */
160 * Global work variables for regcomp().
162 static char *regparse; /* Input-scan pointer. */
163 static int regnpar; /* () count. */
164 static char regdummy;
165 static char *regcode; /* Code-emit pointer; ®dummy = don't. */
166 static long regsize; /* Code size. */
169 * The first byte of the regexp internal "program" is actually this magic
170 * number; the start node begins in the second byte.
176 * Forward declarations for regcomp()'s friends.
179 #define STATIC static
182 STATIC char *regbranch();
183 STATIC char *regpiece();
184 STATIC char *regatom();
185 STATIC char *regnode();
186 STATIC char *regnext();
188 STATIC void reginsert();
189 STATIC void regtail();
190 STATIC void regoptail();
192 STATIC int strcspn();
195 /* regcomp originally appeared here - DEL */
198 - reg - regular expression, i.e. main body or parenthesized thing
200 * Caller must absorb opening parenthesis.
202 * Combining parenthesis handling with the base level of regular expression
203 * is a trifle forced, but the need to tie the tails of the branches to what
204 * follows makes it hard to avoid.
208 int paren; /* Parenthesized? */
213 register char *ender;
214 register int parno = 0;
217 *flagp = HASWIDTH; /* Tentatively. */
219 /* Make an OPEN node, if parenthesized. */
221 if (regnpar >= NSUBEXP)
225 ret = regnode(OPEN+parno);
229 /* Pick up the branches, linking them together. */
230 br = regbranch(&flags);
234 regtail(ret, br); /* OPEN -> first. */
237 if (!(flags&HASWIDTH))
239 *flagp |= flags&SPSTART;
240 while (*regparse == '|') {
242 br = regbranch(&flags);
245 regtail(ret, br); /* BRANCH -> BRANCH. */
246 if (!(flags&HASWIDTH))
248 *flagp |= flags&SPSTART;
251 /* Make a closing node, and hook it on the end. */
252 ender = regnode((paren) ? CLOSE+parno : END);
255 /* Hook the tails of the branches to the closing node. */
256 for (br = ret; br != NULL; br = regnext(br))
257 regoptail(br, ender);
259 /* Check for proper termination. */
260 if (paren && *regparse++ != ')') {
261 FAIL("unmatched ()");
262 } else if (!paren && *regparse != '\0') {
263 if (*regparse == ')') {
264 FAIL("unmatched ()");
266 FAIL("junk on end"); /* "Can't happen". */
274 - regbranch - one alternative of an | operator
276 * Implements the concatenation operator.
283 register char *chain;
284 register char *latest;
287 *flagp = WORST; /* Tentatively. */
289 ret = regnode(BRANCH);
291 while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
292 latest = regpiece(&flags);
295 *flagp |= flags&HASWIDTH;
296 if (chain == NULL) /* First piece. */
297 *flagp |= flags&SPSTART;
299 regtail(chain, latest);
302 if (chain == NULL) /* Loop ran zero times. */
303 (void) regnode(NOTHING);
309 - regpiece - something followed by possible [*+?]
311 * Note that the branching code sequences used for ? and the general cases
312 * of * and + are somewhat optimized: they use the same NOTHING node as
313 * both the endmarker for their branch list and the body of the last branch.
314 * It might seem that this node could be dispensed with entirely, but the
315 * endmarker role is not redundant.
326 ret = regatom(&flags);
336 if (!(flags&HASWIDTH) && op != '?')
337 FAIL("*+ operand could be empty");
338 *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
340 if (op == '*' && (flags&SIMPLE))
341 reginsert(STAR, ret);
342 else if (op == '*') {
343 /* Emit x* as (x&|), where & means "self". */
344 reginsert(BRANCH, ret); /* Either x */
345 regoptail(ret, regnode(BACK)); /* and loop */
346 regoptail(ret, ret); /* back */
347 regtail(ret, regnode(BRANCH)); /* or */
348 regtail(ret, regnode(NOTHING)); /* null. */
349 } else if (op == '+' && (flags&SIMPLE))
350 reginsert(PLUS, ret);
351 else if (op == '+') {
352 /* Emit x+ as x(&|), where & means "self". */
353 next = regnode(BRANCH); /* Either */
355 regtail(regnode(BACK), ret); /* loop back */
356 regtail(next, regnode(BRANCH)); /* or */
357 regtail(ret, regnode(NOTHING)); /* null. */
358 } else if (op == '?') {
359 /* Emit x? as (x|) */
360 reginsert(BRANCH, ret); /* Either x */
361 regtail(ret, regnode(BRANCH)); /* or */
362 next = regnode(NOTHING); /* null. */
364 regoptail(ret, next);
367 if (ISMULT(*regparse))
374 - regatom - the lowest level
376 * Optimization: gobbles an entire sequence of ordinary characters so that
377 * it can turn them into a single node, which is smaller to store and
378 * faster to run. Backslashed characters are exceptions, each becoming a
379 * separate node; the code is simpler that way and it's not worth fixing.
388 *flagp = WORST; /* Tentatively. */
390 switch (*regparse++) {
399 *flagp |= HASWIDTH|SIMPLE;
403 register int classend;
405 if (*regparse == '^') { /* Complement of range. */
406 ret = regnode(ANYBUT);
409 ret = regnode(ANYOF);
410 if (*regparse == ']' || *regparse == '-')
412 while (*regparse != '\0' && *regparse != ']') {
413 if (*regparse == '-') {
415 if (*regparse == ']' || *regparse == '\0')
418 clss = UCHARAT(regparse-2)+1;
419 classend = UCHARAT(regparse);
420 if (clss > classend+1)
421 FAIL("invalid [] range");
422 for (; clss <= classend; clss++)
430 if (*regparse != ']')
431 FAIL("unmatched []");
433 *flagp |= HASWIDTH|SIMPLE;
437 ret = reg(1, &flags);
440 *flagp |= flags&(HASWIDTH|SPSTART);
445 FAIL("internal urp"); /* Supposed to be caught earlier. */
451 FAIL("?+* follows nothing");
455 if (*regparse == '\0')
457 ret = regnode(EXACTLY);
460 *flagp |= HASWIDTH|SIMPLE;
467 len = strcspn(regparse, META);
469 FAIL("internal disaster");
470 ender = *(regparse+len);
471 if (len > 1 && ISMULT(ender))
472 len--; /* Back off clear of ?+* operand. */
476 ret = regnode(EXACTLY);
490 - regnode - emit a node
492 static char * /* Location. */
500 if (ret == ®dummy) {
507 *ptr++ = '\0'; /* Null "next" pointer. */
515 - regc - emit (if appropriate) a byte of code
521 if (regcode != ®dummy)
522 *regcode++ = (char)b;
528 - reginsert - insert an operator in front of already-emitted operand
530 * Means relocating the operand.
539 register char *place;
541 if (regcode == ®dummy) {
552 place = opnd; /* Op node, where operand used to be. */
559 - regtail - set the next-pointer at the end of a node chain
573 /* Find last node. */
576 temp = regnext(scan);
582 if (OP(scan) == BACK)
586 *(scan+1) = (char)(offset>>8)&0377;
587 *(scan+2) = (char)offset&0377;
591 - regoptail - regtail on operand of first argument; nop if operandless
598 /* "Operandless" and "op != BRANCH" are synonymous in practice. */
599 if (p == NULL || p == ®dummy || OP(p) != BRANCH)
601 regtail(OPERAND(p), val);
605 * regexec and friends
609 * Global work variables for regexec().
611 static char *reginput; /* String-input pointer. */
612 NOTSTATIC char *regbol; /* Beginning of input, for ^ check. */
613 static char **regstartp; /* Pointer to startp array. */
614 static char **regendp; /* Ditto for endp. */
620 NOTSTATIC int regtry();
621 STATIC int regmatch();
622 STATIC int regrepeat();
627 STATIC char *regprop();
632 - regexec - match a regexp against a string
635 regexec(prog, string, stringlength, matchlength)
636 register regexp *prog;
637 register char *string; /* note: CURRENTLY ASSUMED TO BE NULL-TERMINATED!!! */
638 int stringlength; /* length of string */
639 int *matchlength; /* number of chars matched (or to be skipped) */
640 /* set when MATCH or CANT_MATCH */
643 extern char *strchr();
646 if (prog == NULL || string == NULL) {
647 regerror("NULL parameter");
648 return(EXP_TCLERROR);
651 /* Check validity of program. */
652 if (UCHARAT(prog->program) != MAGIC) {
653 regerror("corrupted program");
654 return(EXP_KM_ERROR);
658 /* no need for this shortcut anyway */
659 /* If there is a "must appear" string, look for it. */
660 if (prog->regmust != NULL) {
662 while ((s = strchr(s, prog->regmust[0])) != NULL) {
663 if (strncmp(s, prog->regmust, prog->regmlen) == 0)
664 break; /* Found it. */
667 if (s == NULL) /* Not present. */
672 /* Mark beginning of line for ^ . */
675 /* Simplest case: anchored match need be tried only once. */
677 int r = regtry(prog,string,matchlength);
678 if (r == CANT_MATCH) *matchlength = stringlength;
682 /* Messy cases: unanchored match. */
684 if (prog->regstart != '\0') {
685 register char *s2 = s;
687 /* We know what char it must start with. */
691 s2 = strchr(s2,prog->regstart);
693 *matchlength = stringlength;
696 r = regtry(prog,s2,matchlength);
697 if (r == CANT_MATCH) {
701 if (s2 == s) return(r);
706 /* We don't -- general case. */
707 register char *s2 = s;
708 int r = regtry(prog,s,matchlength);
709 if (r == EXP_MATCH) return(r);
710 else if (r == EXP_CANMATCH) return(r);
711 /* at this point, we know some characters at front */
712 /* of string don't match */
713 for (s2++;*s2;s2++) {
714 r = regtry(prog,s2,matchlength);
715 if (r == CANT_MATCH) continue;
716 /* if we match or can_match, say cant_match and */
717 /* record the number of chars at front that don't match */
721 /* made it thru string with CANT_MATCH all the way */
722 *matchlength = stringlength;
729 - regtry - try match at specific point
731 /* return CAN_MATCH, CANT_MATCH or MATCH */
732 int /* 0 failure, 1 success */
733 regtry(prog, string, matchlength)
736 int *matchlength; /* only set for MATCH */
741 int r; /* result of regmatch */
744 regstartp = prog->startp;
745 regendp = prog->endp;
749 for (i = NSUBEXP; i > 0; i--) {
753 r = regmatch(prog->program + 1);
754 if (EXP_MATCH == r) {
755 prog->startp[0] = string;
756 prog->endp[0] = reginput;
757 *matchlength = reginput-string;
760 return(r); /* CAN_MATCH or CANT_MATCH */
764 - regmatch - main matching routine
766 * Conceptually the strategy is simple: check to see whether the current
767 * node matches, call self recursively to see whether the rest matches,
768 * and then act accordingly. In practice we make some effort to avoid
769 * recursion, in particular by going through "ordinary" nodes (that don't
770 * need to know whether the rest of the match failed) by a loop instead of
773 /* returns CAN, CANT or MATCH */
774 static int /* 0 failure, 1 success */
778 register char *scan; /* Current node. */
779 char *next; /* Next node. */
780 #ifndef strchr /* May be #defined to something else */
781 extern char *strchr();
786 if (scan != NULL && regnarrate)
787 fprintf(stderr, "%s(\n", regprop(scan));
789 while (scan != NULL) {
792 fprintf(stderr, "%s...\n", regprop(scan));
794 next = regnext(scan);
798 if (reginput != regbol)
800 return(EXP_CANTMATCH);
803 if (*reginput != '\0')
805 /* note this implies that "$" must match everything received to this point! */
806 return(EXP_CANTMATCH);
809 if (*reginput == '\0')
811 return(EXP_CANMATCH);
815 /* register int len;*/
818 opnd = OPERAND(scan);
820 /* this section of code is totally rewritten - DEL */
821 /* group of literal chars in pattern */
822 /* compare each one */
824 if (*opnd != *reginput) {
825 if (*reginput == '\0') {
827 } else return EXP_CANTMATCH;
832 } while (*opnd != '\0');
836 /* if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL)
839 if (*reginput == '\0')
840 return(EXP_CANMATCH);
841 if (strchr(OPERAND(scan),*reginput) == NULL)
842 return(EXP_CANTMATCH);
846 /* if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL)
849 if (*reginput == '\0')
850 return(EXP_CANMATCH);
851 if (strchr(OPERAND(scan),*reginput) != NULL)
852 return(EXP_CANTMATCH);
870 int r; /* result of regmatch */
873 no = OP(scan) - OPEN;
877 if (r == EXP_MATCH) {
879 * Don't set startp if some later
880 * invocation of the same parentheses
883 if (regstartp[no] == NULL)
884 regstartp[no] = save;
901 int r; /* result of regmatch */
904 no = OP(scan) - CLOSE;
908 if (r == EXP_MATCH) {
910 * Don't set endp if some later
911 * invocation of the same parentheses
914 if (regendp[no] == NULL)
925 if (OP(next) != BRANCH) /* No choice. */
926 next = OPERAND(scan); /* Avoid recursion. */
928 match_status = EXP_CANTMATCH;
934 r = regmatch(OPERAND(scan));
935 if (r == EXP_MATCH) return(r);
936 if (r == EXP_CANMATCH) {
940 scan = regnext(scan);
941 } while (scan != NULL && OP(scan) == BRANCH);
942 return(match_status);
950 register char nextch;
957 * Lookahead to avoid useless match attempts
958 * when we know what character comes next.
960 match_status = EXP_CANTMATCH;
962 if (OP(next) == EXACTLY)
963 nextch = *OPERAND(next);
964 min = (OP(scan) == STAR) ? 0 : 1;
966 no = regrepeat(OPERAND(scan));
968 /* If it could work, try it. */
969 /* 3rd condition allows for CAN_MATCH */
970 if (nextch == '\0' || *reginput == nextch || *reginput == '\0') {
971 int r = regmatch(next);
974 if (r == EXP_CANMATCH)
977 /* Couldn't or didn't -- back up. */
979 reginput = save + no;
981 return(match_status);
986 return(EXP_MATCH); /* Success! */
990 if (OP(scan) > OPEN && OP(scan) < OPEN+NSUBEXP) {
992 } else if (OP(scan) > CLOSE && OP(scan) < CLOSE+NSUBEXP) {
995 regerror("memory corruption");
996 return(EXP_TCLERROR);
1005 * We get here only if there's trouble -- normally "case END" is
1006 * the terminating point.
1008 regerror("corrupted pointers");
1009 return(EXP_TCLERROR);
1013 - regrepeat - repeatedly match something simple, report how many
1019 register int count = 0;
1020 register char *scan;
1021 register char *opnd;
1022 #ifndef strchr /* May be #defined to something else */
1023 /*DEL*/ extern char *strchr();
1030 count = strlen(scan);
1034 while (*opnd == *scan) {
1040 while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
1046 while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
1051 default: /* Oh dear. Called inappropriately. */
1052 regerror("internal foulup");
1053 count = 0; /* Best compromise. */
1062 - regnext - dig the "next" pointer out of a node
1068 register int offset;
1085 STATIC char *regprop();
1088 - regdump - dump a regexp onto stdout in vaguely comprehensible form
1095 register char op = EXACTLY; /* Arbitrary non-END op. */
1096 register char *next;
1097 extern char *strchr();
1101 while (op != END) { /* While that wasn't END last time... */
1103 printf("%2d%s", s-r->program, regprop(s)); /* Where, what. */
1105 if (next == NULL) /* Next ptr. */
1108 printf("(%d)", (s-r->program)+(next-s));
1110 if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
1111 /* Literal string, where present. */
1112 while (*s != '\0') {
1121 /* Header fields of interest. */
1122 if (r->regstart != '\0')
1123 printf("start `%c' ", r->regstart);
1125 printf("anchored ");
1126 if (r->regmust != NULL)
1127 printf("must have \"%s\"", r->regmust);
1132 - regprop - printable representation of opcode
1139 static char buf[50];
1141 (void) strcpy(buf, ":");
1183 sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
1195 sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1205 if (OP(op) > OPEN && OP(op) < OPEN+NSUBEXP) {
1206 sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
1209 } else if (OP(op) > CLOSE && OP(op) < CLOSE+NSUBEXP) {
1210 sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1213 TclRegError("corrupted opcode");
1218 (void) strcat(buf, p);
1224 * The following is provided for those people who do not have strcspn() in
1225 * their C libraries. They should get off their butts and do something
1226 * about it; at least one public-domain implementation of those (highly
1227 * useful) string routines has been published on Usenet.
1231 * strcspn - find length of initial segment of s1 consisting entirely
1232 * of characters not from s2
1240 register char *scan1;
1241 register char *scan2;
1245 for (scan1 = s1; *scan1 != '\0'; scan1++) {
1246 for (scan2 = s2; *scan2 != '\0';) /* ++ moved down. */
1247 if (*scan1 == *scan2++)