]>
cvs.zerfleddert.de Git - micropolis/blob - src/tcl/regexp.c
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. ***
32 * The "internal use only" fields in regexp.h are present to pass info from
33 * compile to execute that permits the execute phase to run lots faster on
34 * simple cases. They are:
36 * regstart char that must begin a match; '\0' if none obvious
37 * reganch is the match anchored (at beginning-of-line only)?
38 * regmust string (pointer into program) that match must include, or NULL
39 * regmlen length of regmust string
41 * Regstart and reganch permit very fast decisions on suitable starting points
42 * for a match, cutting down the work a lot. Regmust permits fast rejection
43 * of lines that cannot possibly match. The regmust tests are costly enough
44 * that regcomp() supplies a regmust only if the r.e. contains something
45 * potentially expensive (at present, the only such thing detected is * or +
46 * at the start of the r.e., which can involve a lot of backup). Regmlen is
47 * supplied because the test in regexec() needs it and regcomp() is computing
52 * Structure for regexp "program". This is essentially a linear encoding
53 * of a nondeterministic finite-state machine (aka syntax charts or
54 * "railroad normal form" in parsing technology). Each node is an opcode
55 * plus a "next" pointer, possibly plus an operand. "Next" pointers of
56 * all nodes except BRANCH implement concatenation; a "next" pointer with
57 * a BRANCH on both ends of it is connecting two alternatives. (Here we
58 * have one of the subtle syntax dependencies: an individual BRANCH (as
59 * opposed to a collection of them) is never concatenated with anything
60 * because of operator precedence.) The operand of some types of node is
61 * a literal string; for others, it is a node leading into a sub-FSM. In
62 * particular, the operand of a BRANCH node is the first node of the branch.
63 * (NB this is *not* a tree structure: the tail of the branch connects
64 * to the thing following the set of BRANCHes.) The opcodes are:
67 /* definition number opnd? meaning */
68 #define END 0 /* no End of program. */
69 #define BOL 1 /* no Match "" at beginning of line. */
70 #define EOL 2 /* no Match "" at end of line. */
71 #define ANY 3 /* no Match any one character. */
72 #define ANYOF 4 /* str Match any character in this string. */
73 #define ANYBUT 5 /* str Match any character not in this string. */
74 #define BRANCH 6 /* node Match this alternative, or the next... */
75 #define BACK 7 /* no Match "", "next" ptr points backward. */
76 #define EXACTLY 8 /* str Match this string. */
77 #define NOTHING 9 /* no Match empty string. */
78 #define STAR 10 /* node Match this (simple) thing 0 or more times. */
79 #define PLUS 11 /* node Match this (simple) thing 1 or more times. */
80 #define OPEN 20 /* no Mark this point in input as start of #n. */
81 /* OPEN+1 is number 1, etc. */
82 #define CLOSE 30 /* no Analogous to OPEN. */
87 * BRANCH The set of branches constituting a single choice are hooked
88 * together with their "next" pointers, since precedence prevents
89 * anything being concatenated to any individual branch. The
90 * "next" pointer of the last BRANCH in a choice points to the
91 * thing following the whole choice. This is also where the
92 * final "next" pointer of each individual branch points; each
93 * branch starts with the operand node of a BRANCH node.
95 * BACK Normal "next" pointers all implicitly point forward; BACK
96 * exists to make loop structures possible.
98 * STAR,PLUS '?', and complex '*' and '+', are implemented as circular
99 * BRANCH structures using BACK. Simple cases (one character
100 * per match) are implemented with STAR and PLUS for speed
101 * and to minimize recursive plunges.
103 * OPEN,CLOSE ...are numbered at compile time.
107 * A node is one char of opcode followed by two chars of "next" pointer.
108 * "Next" pointers are stored as two 8-bit pieces, high order first. The
109 * value is a positive offset from the opcode of the node containing it.
110 * An operand, if any, simply follows the node. (Note that much of the
111 * code generation knows about this implicit relationship.)
113 * Using two bytes for the "next" pointer is vast overkill for most things,
114 * but allows patterns to get big without disasters.
117 #define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
118 #define OPERAND(p) ((p) + 3)
121 * See regmagic.h for one further detail of program structure.
126 * Utility definitions.
129 #define UCHARAT(p) ((int)*(unsigned char *)(p))
131 #define UCHARAT(p) ((int)*(p)&CHARBITS)
134 #define FAIL(m) { regerror(m); return(NULL); }
135 #define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
136 #define META "^$.[()|?+*\\"
139 * Flags to be passed up and down.
141 #define HASWIDTH 01 /* Known never to match null string. */
142 #define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
143 #define SPSTART 04 /* Starts with * or +. */
144 #define WORST 0 /* Worst case. */
147 * Global work variables for regcomp().
149 static char *regparse
; /* Input-scan pointer. */
150 static int regnpar
; /* () count. */
151 static char regdummy
;
152 static char *regcode
; /* Code-emit pointer; ®dummy = don't. */
153 static long regsize
; /* Code size. */
156 * The first byte of the regexp internal "program" is actually this magic
157 * number; the start node begins in the second byte.
163 * Forward declarations for regcomp()'s friends.
166 #define STATIC static
169 STATIC
char *regbranch();
170 STATIC
char *regpiece();
171 STATIC
char *regatom();
172 STATIC
char *regnode();
173 STATIC
char *regnext();
175 STATIC
void reginsert();
176 STATIC
void regtail();
177 STATIC
void regoptail();
179 STATIC
int strcspn();
183 - regcomp - compile a regular expression into internal code
185 * We can't allocate space until we know how big the compiled form will be,
186 * but we can't compile it (and thus know how big it is) until we've got a
187 * place to put the code. So we cheat: we compile it twice, once with code
188 * generation turned off and size counting turned on, and once "for real".
189 * This also means that we don't allocate space until we are sure that the
190 * thing really will compile successfully, and we never have to move the
191 * code and thus invalidate pointers into it. (Note that it has to be in
192 * one piece because free() must be able to free it all.)
194 * Beware that the optimization-preparation code in here knows about some
195 * of the structure of the compiled regexp.
203 register char *longest
;
208 FAIL("NULL argument");
210 /* First pass: determine size, legality. */
216 if (reg(0, &flags
) == NULL
)
219 /* Small enough for pointer-storage convention? */
220 if (regsize
>= 32767L) /* Probably could be 65535L. */
221 FAIL("regexp too big");
223 /* Allocate space. */
224 r
= (regexp
*)ckalloc(sizeof(regexp
) + (unsigned)regsize
);
226 FAIL("out of space");
228 /* Second pass: emit code. */
231 regcode
= r
->program
;
233 if (reg(0, &flags
) == NULL
)
236 /* Dig out information for optimizations. */
237 r
->regstart
= '\0'; /* Worst-case defaults. */
241 scan
= r
->program
+1; /* First BRANCH. */
242 if (OP(regnext(scan
)) == END
) { /* Only one top-level choice. */
243 scan
= OPERAND(scan
);
245 /* Starting-point info. */
246 if (OP(scan
) == EXACTLY
)
247 r
->regstart
= *OPERAND(scan
);
248 else if (OP(scan
) == BOL
)
252 * If there's something expensive in the r.e., find the
253 * longest literal string that must appear and make it the
254 * regmust. Resolve ties in favor of later strings, since
255 * the regstart check works with the beginning of the r.e.
256 * and avoiding duplication strengthens checking. Not a
257 * strong reason, but sufficient in the absence of others.
262 for (; scan
!= NULL
; scan
= regnext(scan
))
263 if (OP(scan
) == EXACTLY
&& strlen(OPERAND(scan
)) >= len
) {
264 longest
= OPERAND(scan
);
265 len
= strlen(OPERAND(scan
));
267 r
->regmust
= longest
;
276 - reg - regular expression, i.e. main body or parenthesized thing
278 * Caller must absorb opening parenthesis.
280 * Combining parenthesis handling with the base level of regular expression
281 * is a trifle forced, but the need to tie the tails of the branches to what
282 * follows makes it hard to avoid.
286 int paren
; /* Parenthesized? */
291 register char *ender
;
292 register int parno
= 0;
295 *flagp
= HASWIDTH
; /* Tentatively. */
297 /* Make an OPEN node, if parenthesized. */
299 if (regnpar
>= NSUBEXP
)
303 ret
= regnode(OPEN
+parno
);
307 /* Pick up the branches, linking them together. */
308 br
= regbranch(&flags
);
312 regtail(ret
, br
); /* OPEN -> first. */
315 if (!(flags
&HASWIDTH
))
317 *flagp
|= flags
&SPSTART
;
318 while (*regparse
== '|') {
320 br
= regbranch(&flags
);
323 regtail(ret
, br
); /* BRANCH -> BRANCH. */
324 if (!(flags
&HASWIDTH
))
326 *flagp
|= flags
&SPSTART
;
329 /* Make a closing node, and hook it on the end. */
330 ender
= regnode((paren
) ? CLOSE
+parno
: END
);
333 /* Hook the tails of the branches to the closing node. */
334 for (br
= ret
; br
!= NULL
; br
= regnext(br
))
335 regoptail(br
, ender
);
337 /* Check for proper termination. */
338 if (paren
&& *regparse
++ != ')') {
339 FAIL("unmatched ()");
340 } else if (!paren
&& *regparse
!= '\0') {
341 if (*regparse
== ')') {
342 FAIL("unmatched ()");
344 FAIL("junk on end"); /* "Can't happen". */
352 - regbranch - one alternative of an | operator
354 * Implements the concatenation operator.
361 register char *chain
;
362 register char *latest
;
365 *flagp
= WORST
; /* Tentatively. */
367 ret
= regnode(BRANCH
);
369 while (*regparse
!= '\0' && *regparse
!= '|' && *regparse
!= ')') {
370 latest
= regpiece(&flags
);
373 *flagp
|= flags
&HASWIDTH
;
374 if (chain
== NULL
) /* First piece. */
375 *flagp
|= flags
&SPSTART
;
377 regtail(chain
, latest
);
380 if (chain
== NULL
) /* Loop ran zero times. */
381 (void) regnode(NOTHING
);
387 - regpiece - something followed by possible [*+?]
389 * Note that the branching code sequences used for ? and the general cases
390 * of * and + are somewhat optimized: they use the same NOTHING node as
391 * both the endmarker for their branch list and the body of the last branch.
392 * It might seem that this node could be dispensed with entirely, but the
393 * endmarker role is not redundant.
404 ret
= regatom(&flags
);
414 if (!(flags
&HASWIDTH
) && op
!= '?')
415 FAIL("*+ operand could be empty");
416 *flagp
= (op
!= '+') ? (WORST
|SPSTART
) : (WORST
|HASWIDTH
);
418 if (op
== '*' && (flags
&SIMPLE
))
419 reginsert(STAR
, ret
);
420 else if (op
== '*') {
421 /* Emit x* as (x&|), where & means "self". */
422 reginsert(BRANCH
, ret
); /* Either x */
423 regoptail(ret
, regnode(BACK
)); /* and loop */
424 regoptail(ret
, ret
); /* back */
425 regtail(ret
, regnode(BRANCH
)); /* or */
426 regtail(ret
, regnode(NOTHING
)); /* null. */
427 } else if (op
== '+' && (flags
&SIMPLE
))
428 reginsert(PLUS
, ret
);
429 else if (op
== '+') {
430 /* Emit x+ as x(&|), where & means "self". */
431 next
= regnode(BRANCH
); /* Either */
433 regtail(regnode(BACK
), ret
); /* loop back */
434 regtail(next
, regnode(BRANCH
)); /* or */
435 regtail(ret
, regnode(NOTHING
)); /* null. */
436 } else if (op
== '?') {
437 /* Emit x? as (x|) */
438 reginsert(BRANCH
, ret
); /* Either x */
439 regtail(ret
, regnode(BRANCH
)); /* or */
440 next
= regnode(NOTHING
); /* null. */
442 regoptail(ret
, next
);
445 if (ISMULT(*regparse
))
452 - regatom - the lowest level
454 * Optimization: gobbles an entire sequence of ordinary characters so that
455 * it can turn them into a single node, which is smaller to store and
456 * faster to run. Backslashed characters are exceptions, each becoming a
457 * separate node; the code is simpler that way and it's not worth fixing.
466 *flagp
= WORST
; /* Tentatively. */
468 switch (*regparse
++) {
477 *flagp
|= HASWIDTH
|SIMPLE
;
481 register int classend
;
483 if (*regparse
== '^') { /* Complement of range. */
484 ret
= regnode(ANYBUT
);
487 ret
= regnode(ANYOF
);
488 if (*regparse
== ']' || *regparse
== '-')
490 while (*regparse
!= '\0' && *regparse
!= ']') {
491 if (*regparse
== '-') {
493 if (*regparse
== ']' || *regparse
== '\0')
496 clss
= UCHARAT(regparse
-2)+1;
497 classend
= UCHARAT(regparse
);
498 if (clss
> classend
+1)
499 FAIL("invalid [] range");
500 for (; clss
<= classend
; clss
++)
508 if (*regparse
!= ']')
509 FAIL("unmatched []");
511 *flagp
|= HASWIDTH
|SIMPLE
;
515 ret
= reg(1, &flags
);
518 *flagp
|= flags
&(HASWIDTH
|SPSTART
);
523 FAIL("internal urp"); /* Supposed to be caught earlier. */
529 FAIL("?+* follows nothing");
533 if (*regparse
== '\0')
535 ret
= regnode(EXACTLY
);
538 *flagp
|= HASWIDTH
|SIMPLE
;
545 len
= strcspn(regparse
, META
);
547 FAIL("internal disaster");
548 ender
= *(regparse
+len
);
549 if (len
> 1 && ISMULT(ender
))
550 len
--; /* Back off clear of ?+* operand. */
554 ret
= regnode(EXACTLY
);
568 - regnode - emit a node
570 static char * /* Location. */
578 if (ret
== ®dummy
) {
585 *ptr
++ = '\0'; /* Null "next" pointer. */
593 - regc - emit (if appropriate) a byte of code
599 if (regcode
!= ®dummy
)
606 - reginsert - insert an operator in front of already-emitted operand
608 * Means relocating the operand.
617 register char *place
;
619 if (regcode
== ®dummy
) {
630 place
= opnd
; /* Op node, where operand used to be. */
637 - regtail - set the next-pointer at the end of a node chain
651 /* Find last node. */
654 temp
= regnext(scan
);
660 if (OP(scan
) == BACK
)
664 *(scan
+1) = (offset
>>8)&0377;
665 *(scan
+2) = offset
&0377;
669 - regoptail - regtail on operand of first argument; nop if operandless
676 /* "Operandless" and "op != BRANCH" are synonymous in practice. */
677 if (p
== NULL
|| p
== ®dummy
|| OP(p
) != BRANCH
)
679 regtail(OPERAND(p
), val
);
683 * regexec and friends
687 * Global work variables for regexec().
689 static char *reginput
; /* String-input pointer. */
690 static char *regbol
; /* Beginning of input, for ^ check. */
691 static char **regstartp
; /* Pointer to startp array. */
692 static char **regendp
; /* Ditto for endp. */
698 STATIC
int regmatch();
699 STATIC
int regrepeat();
704 STATIC
char *regprop();
708 - regexec - match a regexp against a string
711 regexec(prog
, string
)
712 register regexp
*prog
;
713 register char *string
;
717 extern char *strchr();
721 if (prog
== NULL
|| string
== NULL
) {
722 regerror("NULL parameter");
726 /* Check validity of program. */
727 if (UCHARAT(prog
->program
) != MAGIC
) {
728 regerror("corrupted program");
732 /* If there is a "must appear" string, look for it. */
733 if (prog
->regmust
!= NULL
) {
735 while ((s
= strchr(s
, prog
->regmust
[0])) != NULL
) {
736 if (strncmp(s
, prog
->regmust
, prog
->regmlen
) == 0)
737 break; /* Found it. */
740 if (s
== NULL
) /* Not present. */
744 /* Mark beginning of line for ^ . */
747 /* Simplest case: anchored match need be tried only once. */
749 return(regtry(prog
, string
));
751 /* Messy cases: unanchored match. */
753 if (prog
->regstart
!= '\0')
754 /* We know what char it must start with. */
755 while ((s
= strchr(s
, prog
->regstart
)) != NULL
) {
761 /* We don't -- general case. */
765 } while (*s
++ != '\0');
772 - regtry - try match at specific point
774 static int /* 0 failure, 1 success */
784 regstartp
= prog
->startp
;
785 regendp
= prog
->endp
;
789 for (i
= NSUBEXP
; i
> 0; i
--) {
793 if (regmatch(prog
->program
+ 1)) {
794 prog
->startp
[0] = string
;
795 prog
->endp
[0] = reginput
;
802 - regmatch - main matching routine
804 * Conceptually the strategy is simple: check to see whether the current
805 * node matches, call self recursively to see whether the rest matches,
806 * and then act accordingly. In practice we make some effort to avoid
807 * recursion, in particular by going through "ordinary" nodes (that don't
808 * need to know whether the rest of the match failed) by a loop instead of
811 static int /* 0 failure, 1 success */
815 register char *scan
; /* Current node. */
816 char *next
; /* Next node. */
818 extern char *strchr();
823 if (scan
!= NULL
&& regnarrate
)
824 fprintf(stderr
, "%s(\n", regprop(scan
));
826 while (scan
!= NULL
) {
829 fprintf(stderr
, "%s...\n", regprop(scan
));
831 next
= regnext(scan
);
835 if (reginput
!= regbol
)
839 if (*reginput
!= '\0')
843 if (*reginput
== '\0')
851 opnd
= OPERAND(scan
);
852 /* Inline the first character, for speed. */
853 if (*opnd
!= *reginput
)
856 if (len
> 1 && strncmp(opnd
, reginput
, len
) != 0)
862 if (*reginput
== '\0' || strchr(OPERAND(scan
), *reginput
) == NULL
)
867 if (*reginput
== '\0' || strchr(OPERAND(scan
), *reginput
) != NULL
)
887 no
= OP(scan
) - OPEN
;
890 if (regmatch(next
)) {
892 * Don't set startp if some later
893 * invocation of the same parentheses
896 if (regstartp
[no
] == NULL
)
897 regstartp
[no
] = save
;
916 no
= OP(scan
) - CLOSE
;
919 if (regmatch(next
)) {
921 * Don't set endp if some later
922 * invocation of the same parentheses
925 if (regendp
[no
] == NULL
)
936 if (OP(next
) != BRANCH
) /* No choice. */
937 next
= OPERAND(scan
); /* Avoid recursion. */
941 if (regmatch(OPERAND(scan
)))
944 scan
= regnext(scan
);
945 } while (scan
!= NULL
&& OP(scan
) == BRANCH
);
954 register char nextch
;
960 * Lookahead to avoid useless match attempts
961 * when we know what character comes next.
964 if (OP(next
) == EXACTLY
)
965 nextch
= *OPERAND(next
);
966 min
= (OP(scan
) == STAR
) ? 0 : 1;
968 no
= regrepeat(OPERAND(scan
));
970 /* If it could work, try it. */
971 if (nextch
== '\0' || *reginput
== nextch
)
974 /* Couldn't or didn't -- back up. */
976 reginput
= save
+ no
;
983 return(1); /* Success! */
987 regerror("memory corruption");
997 * We get here only if there's trouble -- normally "case END" is
998 * the terminating point.
1000 regerror("corrupted pointers");
1005 - regrepeat - repeatedly match something simple, report how many
1011 register int count
= 0;
1012 register char *scan
;
1013 register char *opnd
;
1019 count
= strlen(scan
);
1023 while (*opnd
== *scan
) {
1029 while (*scan
!= '\0' && strchr(opnd
, *scan
) != NULL
) {
1035 while (*scan
!= '\0' && strchr(opnd
, *scan
) == NULL
) {
1040 default: /* Oh dear. Called inappropriately. */
1041 regerror("internal foulup");
1042 count
= 0; /* Best compromise. */
1051 - regnext - dig the "next" pointer out of a node
1057 register int offset
;
1074 STATIC
char *regprop();
1077 - regdump - dump a regexp onto stdout in vaguely comprehensible form
1084 register char op
= EXACTLY
; /* Arbitrary non-END op. */
1085 register char *next
;
1086 extern char *strchr();
1090 while (op
!= END
) { /* While that wasn't END last time... */
1092 printf("%2d%s", s
-r
->program
, regprop(s
)); /* Where, what. */
1094 if (next
== NULL
) /* Next ptr. */
1097 printf("(%d)", (s
-r
->program
)+(next
-s
));
1099 if (op
== ANYOF
|| op
== ANYBUT
|| op
== EXACTLY
) {
1100 /* Literal string, where present. */
1101 while (*s
!= '\0') {
1110 /* Header fields of interest. */
1111 if (r
->regstart
!= '\0')
1112 printf("start `%c' ", r
->regstart
);
1114 printf("anchored ");
1115 if (r
->regmust
!= NULL
)
1116 printf("must have \"%s\"", r
->regmust
);
1121 - regprop - printable representation of opcode
1128 static char buf
[50];
1130 (void) strcpy(buf
, ":");
1172 sprintf(buf
+strlen(buf
), "OPEN%d", OP(op
)-OPEN
);
1184 sprintf(buf
+strlen(buf
), "CLOSE%d", OP(op
)-CLOSE
);
1194 regerror("corrupted opcode");
1198 (void) strcat(buf
, p
);
1204 * The following is provided for those people who do not have strcspn() in
1205 * their C libraries. They should get off their butts and do something
1206 * about it; at least one public-domain implementation of those (highly
1207 * useful) string routines has been published on Usenet.
1211 * strcspn - find length of initial segment of s1 consisting entirely
1212 * of characters not from s2
1220 register char *scan1
;
1221 register char *scan2
;
1225 for (scan1
= s1
; *scan1
!= '\0'; scan1
++) {
1226 for (scan2
= s2
; *scan2
!= '\0';) /* ++ moved down. */
1227 if (*scan1
== *scan2
++)