1 /* $NetBSD: regexp.c,v 1.3 2013/09/04 19:44:21 tron Exp $ */
4 * regcomp and regexec -- regsub and regerror are elsewhere
6 * Copyright (c) 1986 by University of Toronto.
7 * Written by Henry Spencer. Not derived from licensed software.
9 * Permission is granted to anyone to use this software for any
10 * purpose on any computer system, and to redistribute it freely,
11 * subject to the following restrictions:
13 * 1. The author is not responsible for the consequences of use of
14 * this software, no matter how awful, even if they arise
17 * 2. The origin of this software must not be misrepresented, either
18 * by explicit claim or by omission.
20 * 3. Altered versions must be plainly marked as such, and must not
21 * be misrepresented as being the original software.
23 * Beware that some of this code is subtly aware of the way operator
24 * precedence is structured in regular expressions. Serious changes in
25 * regular-expression syntax might require a total rethink.
27 * *** NOTE: this code has been altered slightly for use in Tcl. ***
28 * Slightly modified by David MacKenzie to undo most of the changes for TCL.
29 * Added regexec2 with notbol parameter. -- 4/19/99 Mark Nudelman
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
61 * computing it anyway.
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 */
82 #define END 0 /* no End of program. */
83 #define BOL 1 /* no Match "" at beginning of line. */
84 #define EOL 2 /* no Match "" at end of line. */
85 #define ANY 3 /* no Match any one character. */
86 #define ANYOF 4 /* str Match any character in this string. */
87 #define ANYBUT 5 /* str Match any character not in this string. */
88 #define BRANCH 6 /* node Match this alternative, or the next... */
89 #define BACK 7 /* no Match "", "next" ptr points backward. */
90 #define EXACTLY 8 /* str Match this string. */
91 #define NOTHING 9 /* no Match empty string. */
92 #define STAR 10 /* node Match this (simple) thing 0 or more times. */
93 #define PLUS 11 /* node Match this (simple) thing 1 or more times. */
94 #define OPEN 20 /* no Mark this point in input as start of #n. */
95 /* OPEN+1 is number 1, etc. */
96 #define CLOSE 30 /* no Analogous to OPEN. */
101 * BRANCH The set of branches constituting a single choice are hooked
102 * together with their "next" pointers, since precedence prevents
103 * anything being concatenated to any individual branch. The
104 * "next" pointer of the last BRANCH in a choice points to the
105 * thing following the whole choice. This is also where the
106 * final "next" pointer of each individual branch points; each
107 * branch starts with the operand node of a BRANCH node.
109 * BACK Normal "next" pointers all implicitly point forward; BACK
110 * exists to make loop structures possible.
112 * STAR,PLUS '?', and complex '*' and '+', are implemented as circular
113 * BRANCH structures using BACK. Simple cases (one character
114 * per match) are implemented with STAR and PLUS for speed
115 * and to minimize recursive plunges.
117 * OPEN,CLOSE ...are numbered at compile time.
121 * A node is one char of opcode followed by two chars of "next" pointer.
122 * "Next" pointers are stored as two 8-bit pieces, high order first. The
123 * value is a positive offset from the opcode of the node containing it.
124 * An operand, if any, simply follows the node. (Note that much of the
125 * code generation knows about this implicit relationship.)
127 * Using two bytes for the "next" pointer is vast overkill for most things,
128 * but allows patterns to get big without disasters.
131 #define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
132 #define OPERAND(p) ((p) + 3)
135 * See regmagic.h for one further detail of program structure.
140 * Utility definitions.
143 #define UCHARAT(p) ((int)*(unsigned char *)(p))
145 #define UCHARAT(p) ((int)*(p)&CHARBITS)
148 #define FAIL(m) { regerror(m); return(NULL); }
149 #define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
150 #define META "^$.[()|?+*\\"
153 * Flags to be passed up and down.
155 #define HASWIDTH 01 /* Known never to match null string. */
156 #define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
157 #define SPSTART 04 /* Starts with * or +. */
158 #define WORST 0 /* Worst case. */
161 * Global work variables for regcomp().
163 static char *regparse
; /* Input-scan pointer. */
164 static int regnpar
; /* () count. */
165 static char regdummy
;
166 static char *regcode
; /* Code-emit pointer; ®dummy = don't. */
167 static long regsize
; /* Code size. */
170 * The first byte of the regexp internal "program" is actually this magic
171 * number; the start node begins in the second byte.
177 * Forward declarations for regcomp()'s friends.
180 #define STATIC static
183 STATIC
char *regbranch();
184 STATIC
char *regpiece();
185 STATIC
char *regatom();
186 STATIC
char *regnode();
187 STATIC
char *regnext();
189 STATIC
void reginsert();
190 STATIC
void regtail();
191 STATIC
void regoptail();
193 STATIC
int strcspn();
197 - regcomp - compile a regular expression into internal code
199 * We can't allocate space until we know how big the compiled form will be,
200 * but we can't compile it (and thus know how big it is) until we've got a
201 * place to put the code. So we cheat: we compile it twice, once with code
202 * generation turned off and size counting turned on, and once "for real".
203 * This also means that we don't allocate space until we are sure that the
204 * thing really will compile successfully, and we never have to move the
205 * code and thus invalidate pointers into it. (Note that it has to be in
206 * one piece because free() must be able to free it all.)
208 * Beware that the optimization-preparation code in here knows about some
209 * of the structure of the compiled regexp.
217 register char *longest
;
222 FAIL("NULL argument");
224 /* First pass: determine size, legality. */
230 if (reg(0, &flags
) == NULL
)
233 /* Small enough for pointer-storage convention? */
234 if (regsize
>= 32767L) /* Probably could be 65535L. */
235 FAIL("regexp too big");
237 /* Allocate space. */
238 r
= (regexp
*)malloc(sizeof(regexp
) + (unsigned)regsize
);
240 FAIL("out of space");
242 /* Second pass: emit code. */
245 regcode
= r
->program
;
247 if (reg(0, &flags
) == NULL
)
250 /* Dig out information for optimizations. */
251 r
->regstart
= '\0'; /* Worst-case defaults. */
255 scan
= r
->program
+1; /* First BRANCH. */
256 if (OP(regnext(scan
)) == END
) { /* Only one top-level choice. */
257 scan
= OPERAND(scan
);
259 /* Starting-point info. */
260 if (OP(scan
) == EXACTLY
)
261 r
->regstart
= *OPERAND(scan
);
262 else if (OP(scan
) == BOL
)
266 * If there's something expensive in the r.e., find the
267 * longest literal string that must appear and make it the
268 * regmust. Resolve ties in favor of later strings, since
269 * the regstart check works with the beginning of the r.e.
270 * and avoiding duplication strengthens checking. Not a
271 * strong reason, but sufficient in the absence of others.
276 for (; scan
!= NULL
; scan
= regnext(scan
))
277 if (OP(scan
) == EXACTLY
&& ((int) strlen(OPERAND(scan
))) >= len
) {
278 longest
= OPERAND(scan
);
279 len
= strlen(OPERAND(scan
));
281 r
->regmust
= longest
;
290 - reg - regular expression, i.e. main body or parenthesized thing
292 * Caller must absorb opening parenthesis.
294 * Combining parenthesis handling with the base level of regular expression
295 * is a trifle forced, but the need to tie the tails of the branches to what
296 * follows makes it hard to avoid.
300 int paren
; /* Parenthesized? */
305 register char *ender
;
306 register int parno
= 0;
309 *flagp
= HASWIDTH
; /* Tentatively. */
311 /* Make an OPEN node, if parenthesized. */
313 if (regnpar
>= NSUBEXP
)
317 ret
= regnode(OPEN
+parno
);
321 /* Pick up the branches, linking them together. */
322 br
= regbranch(&flags
);
326 regtail(ret
, br
); /* OPEN -> first. */
329 if (!(flags
&HASWIDTH
))
331 *flagp
|= flags
&SPSTART
;
332 while (*regparse
== '|') {
334 br
= regbranch(&flags
);
337 regtail(ret
, br
); /* BRANCH -> BRANCH. */
338 if (!(flags
&HASWIDTH
))
340 *flagp
|= flags
&SPSTART
;
343 /* Make a closing node, and hook it on the end. */
344 ender
= regnode((paren
) ? CLOSE
+parno
: END
);
347 /* Hook the tails of the branches to the closing node. */
348 for (br
= ret
; br
!= NULL
; br
= regnext(br
))
349 regoptail(br
, ender
);
351 /* Check for proper termination. */
352 if (paren
&& *regparse
++ != ')') {
353 FAIL("unmatched ()");
354 } else if (!paren
&& *regparse
!= '\0') {
355 if (*regparse
== ')') {
356 FAIL("unmatched ()");
358 FAIL("junk on end"); /* "Can't happen". */
366 - regbranch - one alternative of an | operator
368 * Implements the concatenation operator.
375 register char *chain
;
376 register char *latest
;
379 *flagp
= WORST
; /* Tentatively. */
381 ret
= regnode(BRANCH
);
383 while (*regparse
!= '\0' && *regparse
!= '|' && *regparse
!= ')') {
384 latest
= regpiece(&flags
);
387 *flagp
|= flags
&HASWIDTH
;
388 if (chain
== NULL
) /* First piece. */
389 *flagp
|= flags
&SPSTART
;
391 regtail(chain
, latest
);
394 if (chain
== NULL
) /* Loop ran zero times. */
395 (void) regnode(NOTHING
);
401 - regpiece - something followed by possible [*+?]
403 * Note that the branching code sequences used for ? and the general cases
404 * of * and + are somewhat optimized: they use the same NOTHING node as
405 * both the endmarker for their branch list and the body of the last branch.
406 * It might seem that this node could be dispensed with entirely, but the
407 * endmarker role is not redundant.
418 ret
= regatom(&flags
);
428 if (!(flags
&HASWIDTH
) && op
!= '?')
429 FAIL("*+ operand could be empty");
430 *flagp
= (op
!= '+') ? (WORST
|SPSTART
) : (WORST
|HASWIDTH
);
432 if (op
== '*' && (flags
&SIMPLE
))
433 reginsert(STAR
, ret
);
434 else if (op
== '*') {
435 /* Emit x* as (x&|), where & means "self". */
436 reginsert(BRANCH
, ret
); /* Either x */
437 regoptail(ret
, regnode(BACK
)); /* and loop */
438 regoptail(ret
, ret
); /* back */
439 regtail(ret
, regnode(BRANCH
)); /* or */
440 regtail(ret
, regnode(NOTHING
)); /* null. */
441 } else if (op
== '+' && (flags
&SIMPLE
))
442 reginsert(PLUS
, ret
);
443 else if (op
== '+') {
444 /* Emit x+ as x(&|), where & means "self". */
445 next
= regnode(BRANCH
); /* Either */
447 regtail(regnode(BACK
), ret
); /* loop back */
448 regtail(next
, regnode(BRANCH
)); /* or */
449 regtail(ret
, regnode(NOTHING
)); /* null. */
450 } else if (op
== '?') {
451 /* Emit x? as (x|) */
452 reginsert(BRANCH
, ret
); /* Either x */
453 regtail(ret
, regnode(BRANCH
)); /* or */
454 next
= regnode(NOTHING
); /* null. */
456 regoptail(ret
, next
);
459 if (ISMULT(*regparse
))
466 - regatom - the lowest level
468 * Optimization: gobbles an entire sequence of ordinary characters so that
469 * it can turn them into a single node, which is smaller to store and
470 * faster to run. Backslashed characters are exceptions, each becoming a
471 * separate node; the code is simpler that way and it's not worth fixing.
480 *flagp
= WORST
; /* Tentatively. */
482 switch (*regparse
++) {
491 *flagp
|= HASWIDTH
|SIMPLE
;
495 register int classend
;
497 if (*regparse
== '^') { /* Complement of range. */
498 ret
= regnode(ANYBUT
);
501 ret
= regnode(ANYOF
);
502 if (*regparse
== ']' || *regparse
== '-')
504 while (*regparse
!= '\0' && *regparse
!= ']') {
505 if (*regparse
== '-') {
507 if (*regparse
== ']' || *regparse
== '\0')
510 clss
= UCHARAT(regparse
-2)+1;
511 classend
= UCHARAT(regparse
);
512 if (clss
> classend
+1)
513 FAIL("invalid [] range");
514 for (; clss
<= classend
; clss
++)
522 if (*regparse
!= ']')
523 FAIL("unmatched []");
525 *flagp
|= HASWIDTH
|SIMPLE
;
529 ret
= reg(1, &flags
);
532 *flagp
|= flags
&(HASWIDTH
|SPSTART
);
537 FAIL("internal urp"); /* Supposed to be caught earlier. */
543 FAIL("?+* follows nothing");
547 if (*regparse
== '\0')
549 ret
= regnode(EXACTLY
);
552 *flagp
|= HASWIDTH
|SIMPLE
;
559 len
= strcspn(regparse
, META
);
561 FAIL("internal disaster");
562 ender
= *(regparse
+len
);
563 if (len
> 1 && ISMULT(ender
))
564 len
--; /* Back off clear of ?+* operand. */
568 ret
= regnode(EXACTLY
);
582 - regnode - emit a node
584 static char * /* Location. */
592 if (ret
== ®dummy
) {
599 *ptr
++ = '\0'; /* Null "next" pointer. */
607 - regc - emit (if appropriate) a byte of code
613 if (regcode
!= ®dummy
)
620 - reginsert - insert an operator in front of already-emitted operand
622 * Means relocating the operand.
631 register char *place
;
633 if (regcode
== ®dummy
) {
644 place
= opnd
; /* Op node, where operand used to be. */
651 - regtail - set the next-pointer at the end of a node chain
665 /* Find last node. */
668 temp
= regnext(scan
);
674 if (OP(scan
) == BACK
)
678 *(scan
+1) = (offset
>>8)&0377;
679 *(scan
+2) = offset
&0377;
683 - regoptail - regtail on operand of first argument; nop if operandless
690 /* "Operandless" and "op != BRANCH" are synonymous in practice. */
691 if (p
== NULL
|| p
== ®dummy
|| OP(p
) != BRANCH
)
693 regtail(OPERAND(p
), val
);
697 * regexec and friends
701 * Global work variables for regexec().
703 static char *reginput
; /* String-input pointer. */
704 static char *regbol
; /* Beginning of input, for ^ check. */
705 static char **regstartp
; /* Pointer to startp array. */
706 static char **regendp
; /* Ditto for endp. */
712 STATIC
int regmatch();
713 STATIC
int regrepeat();
718 STATIC
char *regprop();
722 - regexec - match a regexp against a string
725 regexec2(prog
, string
, notbol
)
726 register regexp
*prog
;
727 register char *string
;
733 if (prog
== NULL
|| string
== NULL
) {
734 regerror("NULL parameter");
738 /* Check validity of program. */
739 if (UCHARAT(prog
->program
) != MAGIC
) {
740 regerror("corrupted program");
744 /* If there is a "must appear" string, look for it. */
745 if (prog
->regmust
!= NULL
) {
747 while ((s
= strchr(s
, prog
->regmust
[0])) != NULL
) {
748 if (strncmp(s
, prog
->regmust
, prog
->regmlen
) == 0)
749 break; /* Found it. */
752 if (s
== NULL
) /* Not present. */
756 /* Mark beginning of line for ^ . */
762 /* Simplest case: anchored match need be tried only once. */
764 return(regtry(prog
, string
));
766 /* Messy cases: unanchored match. */
768 if (prog
->regstart
!= '\0')
769 /* We know what char it must start with. */
770 while ((s
= strchr(s
, prog
->regstart
)) != NULL
) {
776 /* We don't -- general case. */
780 } while (*s
++ != '\0');
787 regexec(prog
, string
)
788 register regexp
*prog
;
789 register char *string
;
791 return regexec2(prog
, string
, 0);
795 - regtry - try match at specific point
797 static int /* 0 failure, 1 success */
807 regstartp
= prog
->startp
;
808 regendp
= prog
->endp
;
812 for (i
= NSUBEXP
; i
> 0; i
--) {
816 if (regmatch(prog
->program
+ 1)) {
817 prog
->startp
[0] = string
;
818 prog
->endp
[0] = reginput
;
825 - regmatch - main matching routine
827 * Conceptually the strategy is simple: check to see whether the current
828 * node matches, call self recursively to see whether the rest matches,
829 * and then act accordingly. In practice we make some effort to avoid
830 * recursion, in particular by going through "ordinary" nodes (that don't
831 * need to know whether the rest of the match failed) by a loop instead of
834 static int /* 0 failure, 1 success */
838 register char *scan
; /* Current node. */
839 char *next
; /* Next node. */
843 if (scan
!= NULL
&& regnarrate
)
844 fprintf(stderr
, "%s(\n", regprop(scan
));
846 while (scan
!= NULL
) {
849 fprintf(stderr
, "%s...\n", regprop(scan
));
851 next
= regnext(scan
);
855 if (reginput
!= regbol
)
859 if (*reginput
!= '\0')
863 if (*reginput
== '\0')
871 opnd
= OPERAND(scan
);
872 /* Inline the first character, for speed. */
873 if (*opnd
!= *reginput
)
876 if (len
> 1 && strncmp(opnd
, reginput
, len
) != 0)
882 if (*reginput
== '\0' || strchr(OPERAND(scan
), *reginput
) == NULL
)
887 if (*reginput
== '\0' || strchr(OPERAND(scan
), *reginput
) != NULL
)
907 no
= OP(scan
) - OPEN
;
910 if (regmatch(next
)) {
912 * Don't set startp if some later
913 * invocation of the same parentheses
916 if (regstartp
[no
] == NULL
)
917 regstartp
[no
] = save
;
936 no
= OP(scan
) - CLOSE
;
939 if (regmatch(next
)) {
941 * Don't set endp if some later
942 * invocation of the same parentheses
945 if (regendp
[no
] == NULL
)
956 if (OP(next
) != BRANCH
) /* No choice. */
957 next
= OPERAND(scan
); /* Avoid recursion. */
961 if (regmatch(OPERAND(scan
)))
964 scan
= regnext(scan
);
965 } while (scan
!= NULL
&& OP(scan
) == BRANCH
);
974 register char nextch
;
980 * Lookahead to avoid useless match attempts
981 * when we know what character comes next.
984 if (OP(next
) == EXACTLY
)
985 nextch
= *OPERAND(next
);
986 min
= (OP(scan
) == STAR
) ? 0 : 1;
988 no
= regrepeat(OPERAND(scan
));
990 /* If it could work, try it. */
991 if (nextch
== '\0' || *reginput
== nextch
)
994 /* Couldn't or didn't -- back up. */
996 reginput
= save
+ no
;
1003 return(1); /* Success! */
1007 regerror("memory corruption");
1017 * We get here only if there's trouble -- normally "case END" is
1018 * the terminating point.
1020 regerror("corrupted pointers");
1025 - regrepeat - repeatedly match something simple, report how many
1031 register int count
= 0;
1032 register char *scan
;
1033 register char *opnd
;
1039 count
= strlen(scan
);
1043 while (*opnd
== *scan
) {
1049 while (*scan
!= '\0' && strchr(opnd
, *scan
) != NULL
) {
1055 while (*scan
!= '\0' && strchr(opnd
, *scan
) == NULL
) {
1060 default: /* Oh dear. Called inappropriately. */
1061 regerror("internal foulup");
1062 count
= 0; /* Best compromise. */
1071 - regnext - dig the "next" pointer out of a node
1077 register int offset
;
1094 STATIC
char *regprop();
1097 - regdump - dump a regexp onto stdout in vaguely comprehensible form
1104 register char op
= EXACTLY
; /* Arbitrary non-END op. */
1105 register char *next
;
1109 while (op
!= END
) { /* While that wasn't END last time... */
1111 printf("%2d%s", s
-r
->program
, regprop(s
)); /* Where, what. */
1113 if (next
== NULL
) /* Next ptr. */
1116 printf("(%d)", (s
-r
->program
)+(next
-s
));
1118 if (op
== ANYOF
|| op
== ANYBUT
|| op
== EXACTLY
) {
1119 /* Literal string, where present. */
1120 while (*s
!= '\0') {
1129 /* Header fields of interest. */
1130 if (r
->regstart
!= '\0')
1131 printf("start `%c' ", r
->regstart
);
1133 printf("anchored ");
1134 if (r
->regmust
!= NULL
)
1135 printf("must have \"%s\"", r
->regmust
);
1140 - regprop - printable representation of opcode
1147 static char buf
[50];
1149 (void) strcpy(buf
, ":");
1191 sprintf(buf
+strlen(buf
), "OPEN%d", OP(op
)-OPEN
);
1203 sprintf(buf
+strlen(buf
), "CLOSE%d", OP(op
)-CLOSE
);
1213 regerror("corrupted opcode");
1217 (void) strcat(buf
, p
);
1223 * The following is provided for those people who do not have strcspn() in
1224 * their C libraries. They should get off their butts and do something
1225 * about it; at least one public-domain implementation of those (highly
1226 * useful) string routines has been published on Usenet.
1230 * strcspn - find length of initial segment of s1 consisting entirely
1231 * of characters not from s2
1239 register char *scan1
;
1240 register char *scan2
;
1244 for (scan1
= s1
; *scan1
!= '\0'; scan1
++) {
1245 for (scan2
= s2
; *scan2
!= '\0';) /* ++ moved down. */
1246 if (*scan1
== *scan2
++)