1 /*
2 * regcomp and regexec -- regsub and regerror are elsewhere
3 *
4 * Copyright (c) 1986 by University of Toronto.
5 * Written by Henry Spencer. Not derived from licensed software.
6 *
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:
10 *
11 * 1. The author is not responsible for the consequences of use of
12 * this software, no matter how awful, even if they arise
13 * from defects in it.
14 *
15 * 2. The origin of this software must not be misrepresented, either
16 * by explicit claim or by omission.
17 *
18 * 3. Altered versions must be plainly marked as such, and must not
19 * be misrepresented as being the original software.
20 *** THIS IS AN ALTERED VERSION. It was altered by John Gilmore,
21 *** hoptoad!gnu, on 27 Dec 1986, to add \n as an alternative to |
22 *** to assist in implementing egrep.
23 *** THIS IS AN ALTERED VERSION. It was altered by John Gilmore,
24 *** hoptoad!gnu, on 27 Dec 1986, to add \< and \> for word-matching
25 *** as in BSD grep and ex.
26 *** THIS IS AN ALTERED VERSION. It was altered by John Gilmore,
27 *** hoptoad!gnu, on 28 Dec 1986, to optimize characters quoted with \.
28 *** THIS IS AN ALTERED VERSION. It was altered by James A. Woods,
29 *** ames!jaw, on 19 June 1987, to quash a regcomp() redundancy.
30 *** THIS IS AN ALTERED VERSION. It was altered by Christopher Seiwald
31 *** seiwald@vix.com, on 28 August 1993, for use in jam. Regmagic.h
32 *** was moved into regexp.h, and the include of regexp.h now uses "'s
33 *** to avoid conflicting with the system regexp.h. Const, bless its
34 *** soul, was removed so it can compile everywhere. The declaration
35 *** of strchr() was in conflict on AIX, so it was removed (as it is
36 *** happily defined in string.h).
37 *** THIS IS AN ALTERED VERSION. It was altered by Christopher Seiwald
38 *** seiwald@perforce.com, on 20 January 2000, to use function prototypes.
39 *** THIS IS AN ALTERED VERSION. It was altered by Christopher Seiwald
40 *** seiwald@perforce.com, on 05 November 2002, to const string literals.
41 *
42 * Beware that some of this code is subtly aware of the way operator
43 * precedence is structured in regular expressions. Serious changes in
44 * regular-expression syntax might require a total rethink.
45 */
46 #include "regexp.h"
47 #include <stdio.h>
48 #include <ctype.h>
49 #ifndef ultrix
50 #include <stdlib.h>
51 #endif
52 #include <string.h>
53
54 /*
55 * The "internal use only" fields in regexp.h are present to pass info from
56 * compile to execute that permits the execute phase to run lots faster on
57 * simple cases. They are:
58 *
59 * regstart char that must begin a match; '\0' if none obvious
60 * reganch is the match anchored (at beginning-of-line only)?
61 * regmust string (pointer into program) that match must include, or NULL
62 * regmlen length of regmust string
63 *
64 * Regstart and reganch permit very fast decisions on suitable starting points
65 * for a match, cutting down the work a lot. Regmust permits fast rejection
66 * of lines that cannot possibly match. The regmust tests are costly enough
67 * that regcomp() supplies a regmust only if the r.e. contains something
68 * potentially expensive (at present, the only such thing detected is * or +
69 * at the start of the r.e., which can involve a lot of backup). Regmlen is
70 * supplied because the test in regexec() needs it and regcomp() is computing
71 * it anyway.
72 */
73
74 /*
75 * Structure for regexp "program". This is essentially a linear encoding
76 * of a nondeterministic finite-state machine (aka syntax charts or
77 * "railroad normal form" in parsing technology). Each node is an opcode
78 * plus a "next" pointer, possibly plus an operand. "Next" pointers of
79 * all nodes except BRANCH implement concatenation; a "next" pointer with
80 * a BRANCH on both ends of it is connecting two alternatives. (Here we
81 * have one of the subtle syntax dependencies: an individual BRANCH (as
82 * opposed to a collection of them) is never concatenated with anything
83 * because of operator precedence.) The operand of some types of node is
84 * a literal string; for others, it is a node leading into a sub-FSM. In
85 * particular, the operand of a BRANCH node is the first node of the branch.
86 * (NB this is *not* a tree structure: the tail of the branch connects
87 * to the thing following the set of BRANCHes.) The opcodes are:
88 */
89
90 /* definition number opnd? meaning */
91 #define END 0 /* no End of program. */
92 #define BOL 1 /* no Match "" at beginning of line. */
93 #define EOL 2 /* no Match "" at end of line. */
94 #define ANY 3 /* no Match any one character. */
95 #define ANYOF 4 /* str Match any character in this string. */
96 #define ANYBUT 5 /* str Match any character not in this string. */
97 #define BRANCH 6 /* node Match this alternative, or the next... */
98 #define BACK 7 /* no Match "", "next" ptr points backward. */
99 #define EXACTLY 8 /* str Match this string. */
100 #define NOTHING 9 /* no Match empty string. */
101 #define STAR 10 /* node Match this (simple) thing 0 or more times. */
102 #define PLUS 11 /* node Match this (simple) thing 1 or more times. */
103 #define WORDA 12 /* no Match "" at wordchar, where prev is nonword */
104 #define WORDZ 13 /* no Match "" at nonwordchar, where prev is word */
105 #define OPEN 20 /* no Mark this point in input as start of #n. */
106 /* OPEN+1 is number 1, etc. */
107 #define CLOSE 30 /* no Analogous to OPEN. */
108
109 /*
110 * Opcode notes:
111 *
112 * BRANCH The set of branches constituting a single choice are hooked
113 * together with their "next" pointers, since precedence prevents
114 * anything being concatenated to any individual branch. The
115 * "next" pointer of the last BRANCH in a choice points to the
116 * thing following the whole choice. This is also where the
117 * final "next" pointer of each individual branch points; each
118 * branch starts with the operand node of a BRANCH node.
119 *
120 * BACK Normal "next" pointers all implicitly point forward; BACK
121 * exists to make loop structures possible.
122 *
123 * STAR,PLUS '?', and complex '*' and '+', are implemented as circular
124 * BRANCH structures using BACK. Simple cases (one character
125 * per match) are implemented with STAR and PLUS for speed
126 * and to minimize recursive plunges.
127 *
128 * OPEN,CLOSE ...are numbered at compile time.
129 */
130
131 /*
132 * A node is one char of opcode followed by two chars of "next" pointer.
133 * "Next" pointers are stored as two 8-bit pieces, high order first. The
134 * value is a positive offset from the opcode of the node containing it.
135 * An operand, if any, simply follows the node. (Note that much of the
136 * code generation knows about this implicit relationship.)
137 *
138 * Using two bytes for the "next" pointer is vast overkill for most things,
139 * but allows patterns to get big without disasters.
140 */
141 #define OP(p) (*(p))
142 #define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
143 #define OPERAND(p) ((p) + 3)
144
145 /*
146 * See regmagic.h for one further detail of program structure.
147 */
148
149
150 /*
151 * Utility definitions.
152 */
153 #ifndef CHARBITS
154 #define UCHARAT(p) ((int)*(unsigned char *)(p))
155 #else
156 #define UCHARAT(p) ((int)*(p)&CHARBITS)
157 #endif
158
159 #define FAIL(m) { my_regerror(m); return(NULL); }
160 #define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
161
162 /*
163 * Flags to be passed up and down.
164 */
165 #define HASWIDTH 01 /* Known never to match null string. */
166 #define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
167 #define SPSTART 04 /* Starts with * or +. */
168 #define WORST 0 /* Worst case. */
169
170 /*
171 * Global work variables for regcomp().
172 */
173 static char *regparse; /* Input-scan pointer. */
174 static int regnpar; /* () count. */
175 static char regdummy;
176 static char *regcode; /* Code-emit pointer; ®dummy = don't. */
177 static long regsize; /* Code size. */
178
179 /*
180 * Forward declarations for regcomp()'s friends.
181 */
182 #ifndef STATIC
183 #define STATIC static
184 #endif
185 STATIC char *reg( int paren, int *flagp );
186 STATIC char *regbranch( int *flagp );
187 STATIC char *regpiece( int *flagp );
188 STATIC char *regatom( int *flagp );
189 STATIC char *regnode( int op );
190 STATIC char *regnext( register char *p );
191 STATIC void regc( int b );
192 STATIC void reginsert( char op, char *opnd );
193 STATIC void regtail( char *p, char *val );
194 STATIC void regoptail( char *p, char *val );
195 #ifdef STRCSPN
196 STATIC int strcspn();
197 #endif
198
199 /*
200 - regcomp - compile a regular expression into internal code
201 *
202 * We can't allocate space until we know how big the compiled form will be,
203 * but we can't compile it (and thus know how big it is) until we've got a
204 * place to put the code. So we cheat: we compile it twice, once with code
205 * generation turned off and size counting turned on, and once "for real".
206 * This also means that we don't allocate space until we are sure that the
207 * thing really will compile successfully, and we never have to move the
208 * code and thus invalidate pointers into it. (Note that it has to be in
209 * one piece because free() must be able to free it all.)
210 *
211 * Beware that the optimization-preparation code in here knows about some
212 * of the structure of the compiled regexp.
213 */
214 regexp *
my_regcomp(const char * exp)215 my_regcomp( const char *exp )
216 {
217 register regexp *r;
218 register char *scan;
219 register char *longest;
220 register unsigned len;
221 int flags;
222
223 if (exp == NULL)
224 FAIL("NULL argument");
225
226 /* First pass: determine size, legality. */
227 #ifdef notdef
228 if (exp[0] == '.' && exp[1] == '*') exp += 2; /* aid grep */
229 #endif
230 regparse = (char *)exp;
231 regnpar = 1;
232 regsize = 0L;
233 regcode = ®dummy;
234 regc(MAGIC);
235 if (reg(0, &flags) == NULL)
236 return(NULL);
237
238 /* Small enough for pointer-storage convention? */
239 if (regsize >= 32767L) /* Probably could be 65535L. */
240 FAIL("regexp too big");
241
242 /* Allocate space. */
243 r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize);
244 if (r == NULL)
245 FAIL("out of space");
246
247 /* Second pass: emit code. */
248 regparse = (char *)exp;
249 regnpar = 1;
250 regcode = r->program;
251 regc(MAGIC);
252 if (reg(0, &flags) == NULL)
253 {
254 free(r);
255 return(NULL);
256 }
257
258 /* Dig out information for optimizations. */
259 r->regstart = '\0'; /* Worst-case defaults. */
260 r->reganch = 0;
261 r->regmust = NULL;
262 r->regmlen = 0;
263 scan = r->program+1; /* First BRANCH. */
264 if (OP(regnext(scan)) == END) { /* Only one top-level choice. */
265 scan = OPERAND(scan);
266
267 /* Starting-point info. */
268 if (OP(scan) == EXACTLY)
269 r->regstart = *OPERAND(scan);
270 else if (OP(scan) == BOL)
271 r->reganch++;
272
273 /*
274 * If there's something expensive in the r.e., find the
275 * longest literal string that must appear and make it the
276 * regmust. Resolve ties in favor of later strings, since
277 * the regstart check works with the beginning of the r.e.
278 * and avoiding duplication strengthens checking. Not a
279 * strong reason, but sufficient in the absence of others.
280 */
281 if (flags&SPSTART) {
282 longest = NULL;
283 len = 0;
284 for (; scan != NULL; scan = regnext(scan))
285 if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
286 longest = OPERAND(scan);
287 len = strlen(OPERAND(scan));
288 }
289 r->regmust = longest;
290 r->regmlen = len;
291 }
292 }
293
294 return(r);
295 }
296
297 /*
298 - reg - regular expression, i.e. main body or parenthesized thing
299 *
300 * Caller must absorb opening parenthesis.
301 *
302 * Combining parenthesis handling with the base level of regular expression
303 * is a trifle forced, but the need to tie the tails of the branches to what
304 * follows makes it hard to avoid.
305 */
306 static char *
reg(int paren,int * flagp)307 reg(
308 int paren, /* Parenthesized? */
309 int *flagp )
310 {
311 register char *ret;
312 register char *br;
313 register char *ender;
314 register int parno = 0; /* TNB */
315 int flags;
316
317 *flagp = HASWIDTH; /* Tentatively. */
318
319 /* Make an OPEN node, if parenthesized. */
320 if (paren) {
321 if (regnpar >= NSUBEXP)
322 FAIL("too many ()");
323 parno = regnpar;
324 regnpar++;
325 ret = regnode(OPEN+parno);
326 } else
327 ret = NULL;
328
329 /* Pick up the branches, linking them together. */
330 br = regbranch(&flags);
331 if (br == NULL)
332 return(NULL);
333 if (ret != NULL)
334 regtail(ret, br); /* OPEN -> first. */
335 else
336 ret = br;
337 if (!(flags&HASWIDTH))
338 *flagp &= ~HASWIDTH;
339 *flagp |= flags&SPSTART;
340 while (*regparse == '|' || *regparse == '\n') {
341 regparse++;
342 br = regbranch(&flags);
343 if (br == NULL)
344 return(NULL);
345 regtail(ret, br); /* BRANCH -> BRANCH. */
346 if (!(flags&HASWIDTH))
347 *flagp &= ~HASWIDTH;
348 *flagp |= flags&SPSTART;
349 }
350
351 /* Make a closing node, and hook it on the end. */
352 ender = regnode((paren) ? CLOSE+parno : END);
353 regtail(ret, ender);
354
355 /* Hook the tails of the branches to the closing node. */
356 for (br = ret; br != NULL; br = regnext(br))
357 regoptail(br, ender);
358
359 /* Check for proper termination. */
360 if (paren && *regparse++ != ')') {
361 FAIL("unmatched ()");
362 } else if (!paren && *regparse != '\0') {
363 if (*regparse == ')') {
364 FAIL("unmatched ()");
365 } else
366 FAIL("junk on end"); /* "Can't happen". */
367 /* NOTREACHED */
368 }
369
370 return(ret);
371 }
372
373 /*
374 - regbranch - one alternative of an | operator
375 *
376 * Implements the concatenation operator.
377 */
378 static char *
regbranch(int * flagp)379 regbranch( int *flagp )
380 {
381 register char *ret;
382 register char *chain;
383 register char *latest;
384 int flags;
385
386 *flagp = WORST; /* Tentatively. */
387
388 ret = regnode(BRANCH);
389 chain = NULL;
390 while (*regparse != '\0' && *regparse != ')' &&
391 *regparse != '\n' && *regparse != '|') {
392 latest = regpiece(&flags);
393 if (latest == NULL)
394 return(NULL);
395 *flagp |= flags&HASWIDTH;
396 if (chain == NULL) /* First piece. */
397 *flagp |= flags&SPSTART;
398 else
399 regtail(chain, latest);
400 chain = latest;
401 }
402 if (chain == NULL) /* Loop ran zero times. */
403 (void) regnode(NOTHING);
404
405 return(ret);
406 }
407
408 /*
409 - regpiece - something followed by possible [*+?]
410 *
411 * Note that the branching code sequences used for ? and the general cases
412 * of * and + are somewhat optimized: they use the same NOTHING node as
413 * both the endmarker for their branch list and the body of the last branch.
414 * It might seem that this node could be dispensed with entirely, but the
415 * endmarker role is not redundant.
416 */
417 static char *
regpiece(int * flagp)418 regpiece( int *flagp )
419 {
420 register char *ret;
421 register char op;
422 register char *next;
423 int flags;
424
425 ret = regatom(&flags);
426 if (ret == NULL)
427 return(NULL);
428
429 op = *regparse;
430 if (!ISMULT(op)) {
431 *flagp = flags;
432 return(ret);
433 }
434
435 if (!(flags&HASWIDTH) && op != '?')
436 FAIL("*+ operand could be empty");
437 *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
438
439 if (op == '*' && (flags&SIMPLE))
440 reginsert(STAR, ret);
441 else if (op == '*') {
442 /* Emit x* as (x&|), where & means "self". */
443 reginsert(BRANCH, ret); /* Either x */
444 regoptail(ret, regnode(BACK)); /* and loop */
445 regoptail(ret, ret); /* back */
446 regtail(ret, regnode(BRANCH)); /* or */
447 regtail(ret, regnode(NOTHING)); /* null. */
448 } else if (op == '+' && (flags&SIMPLE))
449 reginsert(PLUS, ret);
450 else if (op == '+') {
451 /* Emit x+ as x(&|), where & means "self". */
452 next = regnode(BRANCH); /* Either */
453 regtail(ret, next);
454 regtail(regnode(BACK), ret); /* loop back */
455 regtail(next, regnode(BRANCH)); /* or */
456 regtail(ret, regnode(NOTHING)); /* null. */
457 } else if (op == '?') {
458 /* Emit x? as (x|) */
459 reginsert(BRANCH, ret); /* Either x */
460 regtail(ret, regnode(BRANCH)); /* or */
461 next = regnode(NOTHING); /* null. */
462 regtail(ret, next);
463 regoptail(ret, next);
464 }
465 regparse++;
466 if (ISMULT(*regparse))
467 FAIL("nested *?+");
468
469 return(ret);
470 }
471
472 /*
473 - regatom - the lowest level
474 *
475 * Optimization: gobbles an entire sequence of ordinary characters so that
476 * it can turn them into a single node, which is smaller to store and
477 * faster to run. Backslashed characters are exceptions, each becoming a
478 * separate node; the code is simpler that way and it's not worth fixing.
479 */
480 static char *
regatom(int * flagp)481 regatom( int *flagp )
482 {
483 register char *ret;
484 int flags;
485
486 *flagp = WORST; /* Tentatively. */
487
488 switch (*regparse++) {
489 /* FIXME: these chars only have meaning at beg/end of pat? */
490 case '^':
491 ret = regnode(BOL);
492 break;
493 case '$':
494 ret = regnode(EOL);
495 break;
496 case '.':
497 ret = regnode(ANY);
498 *flagp |= HASWIDTH|SIMPLE;
499 break;
500 case '[': {
501 register int classr;
502 register int classend;
503
504 if (*regparse == '^') { /* Complement of range. */
505 ret = regnode(ANYBUT);
506 regparse++;
507 } else
508 ret = regnode(ANYOF);
509 if (*regparse == ']' || *regparse == '-')
510 regc(*regparse++);
511 while (*regparse != '\0' && *regparse != ']') {
512 if (*regparse == '-') {
513 regparse++;
514 if (*regparse == ']' || *regparse == '\0')
515 regc('-');
516 else {
517 classr = UCHARAT(regparse-2)+1;
518 classend = UCHARAT(regparse);
519 if (classr > classend+1)
520 FAIL("invalid [] range");
521 for (; classr <= classend; classr++)
522 regc(classr);
523 regparse++;
524 }
525 } else
526 regc(*regparse++);
527 }
528 regc('\0');
529 if (*regparse != ']')
530 FAIL("unmatched []");
531 regparse++;
532 *flagp |= HASWIDTH|SIMPLE;
533 }
534 break;
535 case '(':
536 ret = reg(1, &flags);
537 if (ret == NULL)
538 return(NULL);
539 *flagp |= flags&(HASWIDTH|SPSTART);
540 break;
541 case '\0':
542 case '|':
543 case '\n':
544 case ')':
545 FAIL("internal urp"); /* Supposed to be caught earlier. */
546 break;
547 case '?':
548 case '+':
549 case '*':
550 FAIL("?+* follows nothing");
551 break;
552 case '\\':
553 switch (*regparse++) {
554 case '\0':
555 FAIL("trailing \\");
556 break;
557 case '<':
558 ret = regnode(WORDA);
559 break;
560 case '>':
561 ret = regnode(WORDZ);
562 break;
563 /* FIXME: Someday handle \1, \2, ... */
564 default:
565 /* Handle general quoted chars in exact-match routine */
566 goto de_fault;
567 }
568 break;
569 de_fault:
570 default:
571 /*
572 * Encode a string of characters to be matched exactly.
573 *
574 * This is a bit tricky due to quoted chars and due to
575 * '*', '+', and '?' taking the SINGLE char previous
576 * as their operand.
577 *
578 * On entry, the char at regparse[-1] is going to go
579 * into the string, no matter what it is. (It could be
580 * following a \ if we are entered from the '\' case.)
581 *
582 * Basic idea is to pick up a good char in ch and
583 * examine the next char. If it's *+? then we twiddle.
584 * If it's \ then we frozzle. If it's other magic char
585 * we push ch and terminate the string. If none of the
586 * above, we push ch on the string and go around again.
587 *
588 * regprev is used to remember where "the current char"
589 * starts in the string, if due to a *+? we need to back
590 * up and put the current char in a separate, 1-char, string.
591 * When regprev is NULL, ch is the only char in the
592 * string; this is used in *+? handling, and in setting
593 * flags |= SIMPLE at the end.
594 */
595 {
596 char *regprev;
597 register char ch;
598
599 regparse--; /* Look at cur char */
600 ret = regnode(EXACTLY);
601 for ( regprev = 0 ; ; ) {
602 ch = *regparse++; /* Get current char */
603 switch (*regparse) { /* look at next one */
604
605 default:
606 regc(ch); /* Add cur to string */
607 break;
608
609 case '.': case '[': case '(':
610 case ')': case '|': case '\n':
611 case '$': case '^':
612 case '\0':
613 /* FIXME, $ and ^ should not always be magic */
614 magic:
615 regc(ch); /* dump cur char */
616 goto done; /* and we are done */
617
618 case '?': case '+': case '*':
619 if (!regprev) /* If just ch in str, */
620 goto magic; /* use it */
621 /* End mult-char string one early */
622 regparse = regprev; /* Back up parse */
623 goto done;
624
625 case '\\':
626 regc(ch); /* Cur char OK */
627 switch (regparse[1]){ /* Look after \ */
628 case '\0':
629 case '<':
630 case '>':
631 /* FIXME: Someday handle \1, \2, ... */
632 goto done; /* Not quoted */
633 default:
634 /* Backup point is \, scan * point is after it. */
635 regprev = regparse;
636 regparse++;
637 continue; /* NOT break; */
638 }
639 }
640 regprev = regparse; /* Set backup point */
641 }
642 done:
643 regc('\0');
644 *flagp |= HASWIDTH;
645 if (!regprev) /* One char? */
646 *flagp |= SIMPLE;
647 }
648 break;
649 }
650
651 return(ret);
652 }
653
654 /*
655 - regnode - emit a node
656 */
657 static char * /* Location. */
regnode(int op)658 regnode( int op )
659 {
660 register char *ret;
661 register char *ptr;
662
663 ret = regcode;
664 if (ret == ®dummy) {
665 regsize += 3;
666 return(ret);
667 }
668
669 ptr = ret;
670 *ptr++ = op;
671 *ptr++ = '\0'; /* Null "next" pointer. */
672 *ptr++ = '\0';
673 regcode = ptr;
674
675 return(ret);
676 }
677
678 /*
679 - regc - emit (if appropriate) a byte of code
680 */
681 static void
regc(int b)682 regc( int b )
683 {
684 if (regcode != ®dummy)
685 *regcode++ = b;
686 else
687 regsize++;
688 }
689
690 /*
691 - reginsert - insert an operator in front of already-emitted operand
692 *
693 * Means relocating the operand.
694 */
695 static void
reginsert(char op,char * opnd)696 reginsert(
697 char op,
698 char *opnd )
699 {
700 register char *src;
701 register char *dst;
702 register char *place;
703
704 if (regcode == ®dummy) {
705 regsize += 3;
706 return;
707 }
708
709 src = regcode;
710 regcode += 3;
711 dst = regcode;
712 while (src > opnd)
713 *--dst = *--src;
714
715 place = opnd; /* Op node, where operand used to be. */
716 *place++ = op;
717 *place++ = '\0';
718 *place++ = '\0';
719 }
720
721 /*
722 - regtail - set the next-pointer at the end of a node chain
723 */
724 static void
regtail(char * p,char * val)725 regtail(
726 char *p,
727 char *val )
728 {
729 register char *scan;
730 register char *temp;
731 register int offset;
732
733 if (p == ®dummy)
734 return;
735
736 /* Find last node. */
737 scan = p;
738 for (;;) {
739 temp = regnext(scan);
740 if (temp == NULL)
741 break;
742 scan = temp;
743 }
744
745 if (OP(scan) == BACK)
746 offset = scan - val;
747 else
748 offset = val - scan;
749 *(scan+1) = (offset>>8)&0377;
750 *(scan+2) = offset&0377;
751 }
752
753 /*
754 - regoptail - regtail on operand of first argument; nop if operandless
755 */
756
757 static void
regoptail(char * p,char * val)758 regoptail(
759 char *p,
760 char *val )
761 {
762 /* "Operandless" and "op != BRANCH" are synonymous in practice. */
763 if (p == NULL || p == ®dummy || OP(p) != BRANCH)
764 return;
765 regtail(OPERAND(p), val);
766 }
767
768 /*
769 * regexec and friends
770 */
771
772 /*
773 * Global work variables for regexec().
774 */
775 static const char *reginput; /* String-input pointer. */
776 static char *regbol; /* Beginning of input, for ^ check. */
777 static const char **regstartp; /* Pointer to startp array. */
778 static const char **regendp; /* Ditto for endp. */
779
780 /*
781 * Forwards.
782 */
783 STATIC int regtry( regexp *prog, const char *string );
784 STATIC int regmatch( char *prog );
785 STATIC int regrepeat( char *p );
786
787 #ifdef DEBUG
788 int regnarrate = 0;
789 void regdump();
790 STATIC char *regprop();
791 #endif
792
793 /*
794 - regexec - match a regexp against a string
795 */
796 int
my_regexec(register regexp * prog,register const char * string)797 my_regexec(
798 register regexp *prog,
799 register const char *string )
800 {
801 register char *s;
802
803 /* Be paranoid... */
804 if (prog == NULL || string == NULL) {
805 my_regerror("NULL parameter");
806 return(0);
807 }
808
809 /* Check validity of program. */
810 if (UCHARAT(prog->program) != MAGIC) {
811 my_regerror("corrupted program");
812 return(0);
813 }
814
815 /* If there is a "must appear" string, look for it. */
816 if (prog->regmust != NULL) {
817 s = (char *)string;
818 while ((s = strchr(s, prog->regmust[0])) != NULL) {
819 if (strncmp(s, prog->regmust, prog->regmlen) == 0)
820 break; /* Found it. */
821 s++;
822 }
823 if (s == NULL) /* Not present. */
824 return(0);
825 }
826
827 /* Mark beginning of line for ^ . */
828 regbol = (char *)string;
829
830 /* Simplest case: anchored match need be tried only once. */
831 if (prog->reganch)
832 return(regtry(prog, string));
833
834 /* Messy cases: unanchored match. */
835 s = (char *)string;
836 if (prog->regstart != '\0')
837 /* We know what char it must start with. */
838 while ((s = strchr(s, prog->regstart)) != NULL) {
839 if (regtry(prog, s))
840 return(1);
841 s++;
842 }
843 else
844 /* We don't -- general case. */
845 do {
846 if (regtry(prog, s))
847 return(1);
848 } while (*s++ != '\0');
849
850 /* Failure. */
851 return(0);
852 }
853
854 /*
855 - regtry - try match at specific point
856 */
857 static int /* 0 failure, 1 success */
regtry(regexp * prog,const char * string)858 regtry(
859 regexp *prog,
860 const char *string )
861 {
862 register int i;
863 register const char **sp;
864 register const char **ep;
865
866 reginput = string;
867 regstartp = prog->startp;
868 regendp = prog->endp;
869
870 sp = prog->startp;
871 ep = prog->endp;
872 for (i = NSUBEXP; i > 0; i--) {
873 *sp++ = NULL;
874 *ep++ = NULL;
875 }
876 if (regmatch(prog->program + 1)) {
877 prog->startp[0] = string;
878 prog->endp[0] = reginput;
879 return(1);
880 } else
881 return(0);
882 }
883
884 /*
885 - regmatch - main matching routine
886 *
887 * Conceptually the strategy is simple: check to see whether the current
888 * node matches, call self recursively to see whether the rest matches,
889 * and then act accordingly. In practice we make some effort to avoid
890 * recursion, in particular by going through "ordinary" nodes (that don't
891 * need to know whether the rest of the match failed) by a loop instead of
892 * by recursion.
893 */
894 static int /* 0 failure, 1 success */
regmatch(char * prog)895 regmatch( char *prog )
896 {
897 register char *scan; /* Current node. */
898 char *next; /* Next node. */
899
900 scan = prog;
901 #ifdef DEBUG
902 if (scan != NULL && regnarrate)
903 fprintf(stderr, "%s(\n", regprop(scan));
904 #endif
905 while (scan != NULL) {
906 #ifdef DEBUG
907 if (regnarrate)
908 fprintf(stderr, "%s...\n", regprop(scan));
909 #endif
910 next = regnext(scan);
911
912 switch (OP(scan)) {
913 case BOL:
914 if (reginput != regbol)
915 return(0);
916 break;
917 case EOL:
918 if (*reginput != '\0')
919 return(0);
920 break;
921 case WORDA:
922 /* Must be looking at a letter, digit, or _ */
923 if ((!isalnum(*reginput)) && *reginput != '_')
924 return(0);
925 /* Prev must be BOL or nonword */
926 if (reginput > regbol &&
927 (isalnum(reginput[-1]) || reginput[-1] == '_'))
928 return(0);
929 break;
930 case WORDZ:
931 /* Must be looking at non letter, digit, or _ */
932 if (isalnum(*reginput) || *reginput == '_')
933 return(0);
934 /* We don't care what the previous char was */
935 break;
936 case ANY:
937 if (*reginput == '\0')
938 return(0);
939 reginput++;
940 break;
941 case EXACTLY: {
942 register int len;
943 register char *opnd;
944
945 opnd = OPERAND(scan);
946 /* Inline the first character, for speed. */
947 if (*opnd != *reginput)
948 return(0);
949 len = strlen(opnd);
950 if (len > 1 && strncmp(opnd, reginput, len) != 0)
951 return(0);
952 reginput += len;
953 }
954 break;
955 case ANYOF:
956 if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL)
957 return(0);
958 reginput++;
959 break;
960 case ANYBUT:
961 if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL)
962 return(0);
963 reginput++;
964 break;
965 case NOTHING:
966 break;
967 case BACK:
968 break;
969 case OPEN+1:
970 case OPEN+2:
971 case OPEN+3:
972 case OPEN+4:
973 case OPEN+5:
974 case OPEN+6:
975 case OPEN+7:
976 case OPEN+8:
977 case OPEN+9: {
978 register int no;
979 register const char *save;
980
981 no = OP(scan) - OPEN;
982 save = reginput;
983
984 if (regmatch(next)) {
985 /*
986 * Don't set startp if some later
987 * invocation of the same parentheses
988 * already has.
989 */
990 if (regstartp[no] == NULL)
991 regstartp[no] = save;
992 return(1);
993 } else
994 return(0);
995 }
996 break;
997 case CLOSE+1:
998 case CLOSE+2:
999 case CLOSE+3:
1000 case CLOSE+4:
1001 case CLOSE+5:
1002 case CLOSE+6:
1003 case CLOSE+7:
1004 case CLOSE+8:
1005 case CLOSE+9: {
1006 register int no;
1007 register const char *save;
1008
1009 no = OP(scan) - CLOSE;
1010 save = reginput;
1011
1012 if (regmatch(next)) {
1013 /*
1014 * Don't set endp if some later
1015 * invocation of the same parentheses
1016 * already has.
1017 */
1018 if (regendp[no] == NULL)
1019 regendp[no] = save;
1020 return(1);
1021 } else
1022 return(0);
1023 }
1024 break;
1025 case BRANCH: {
1026 register const char *save;
1027
1028 if (OP(next) != BRANCH) /* No choice. */
1029 next = OPERAND(scan); /* Avoid recursion. */
1030 else {
1031 do {
1032 save = reginput;
1033 if (regmatch(OPERAND(scan)))
1034 return(1);
1035 reginput = save;
1036 scan = regnext(scan);
1037 } while (scan != NULL && OP(scan) == BRANCH);
1038 return(0);
1039 /* NOTREACHED */
1040 }
1041 }
1042 break;
1043 case STAR:
1044 case PLUS: {
1045 register char nextch;
1046 register int no;
1047 register const char *save;
1048 register int min;
1049
1050 /*
1051 * Lookahead to avoid useless match attempts
1052 * when we know what character comes next.
1053 */
1054 nextch = '\0';
1055 if (OP(next) == EXACTLY)
1056 nextch = *OPERAND(next);
1057 min = (OP(scan) == STAR) ? 0 : 1;
1058 save = reginput;
1059 no = regrepeat(OPERAND(scan));
1060 while (no >= min) {
1061 /* If it could work, try it. */
1062 if (nextch == '\0' || *reginput == nextch)
1063 if (regmatch(next))
1064 return(1);
1065 /* Couldn't or didn't -- back up. */
1066 no--;
1067 reginput = save + no;
1068 }
1069 return(0);
1070 }
1071 break;
1072 case END:
1073 return(1); /* Success! */
1074 break;
1075 default:
1076 my_regerror("memory corruption");
1077 return(0);
1078 break;
1079 }
1080
1081 scan = next;
1082 }
1083
1084 /*
1085 * We get here only if there's trouble -- normally "case END" is
1086 * the terminating point.
1087 */
1088 my_regerror("corrupted pointers");
1089 return(0);
1090 }
1091
1092 /*
1093 - regrepeat - repeatedly match something simple, report how many
1094 */
1095 static int
regrepeat(char * p)1096 regrepeat( char *p )
1097 {
1098 register int count = 0;
1099 register const char *scan;
1100 register char *opnd;
1101
1102 scan = reginput;
1103 opnd = OPERAND(p);
1104 switch (OP(p)) {
1105 case ANY:
1106 count = strlen(scan);
1107 scan += count;
1108 break;
1109 case EXACTLY:
1110 while (*opnd == *scan) {
1111 count++;
1112 scan++;
1113 }
1114 break;
1115 case ANYOF:
1116 while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
1117 count++;
1118 scan++;
1119 }
1120 break;
1121 case ANYBUT:
1122 while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
1123 count++;
1124 scan++;
1125 }
1126 break;
1127 default: /* Oh dear. Called inappropriately. */
1128 my_regerror("internal foulup");
1129 count = 0; /* Best compromise. */
1130 break;
1131 }
1132 reginput = scan;
1133
1134 return(count);
1135 }
1136
1137 /*
1138 - regnext - dig the "next" pointer out of a node
1139 */
1140 static char *
regnext(register char * p)1141 regnext( register char *p )
1142 {
1143 register int offset;
1144
1145 if (p == ®dummy)
1146 return(NULL);
1147
1148 offset = NEXT(p);
1149 if (offset == 0)
1150 return(NULL);
1151
1152 if (OP(p) == BACK)
1153 return(p-offset);
1154 else
1155 return(p+offset);
1156 }
1157
1158 #ifdef DEBUG
1159
1160 STATIC char *regprop();
1161
1162 /*
1163 - regdump - dump a regexp onto stdout in vaguely comprehensible form
1164 */
1165 void
regdump(regexp * r)1166 regdump( regexp *r )
1167 {
1168 register char *s;
1169 register char op = EXACTLY; /* Arbitrary non-END op. */
1170 register char *next;
1171
1172
1173 s = r->program + 1;
1174 while (op != END) { /* While that wasn't END last time... */
1175 op = OP(s);
1176 printf("%2d%s", s-r->program, regprop(s)); /* Where, what. */
1177 next = regnext(s);
1178 if (next == NULL) /* Next ptr. */
1179 printf("(0)");
1180 else
1181 printf("(%d)", (s-r->program)+(next-s));
1182 s += 3;
1183 if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
1184 /* Literal string, where present. */
1185 while (*s != '\0') {
1186 putchar(*s);
1187 s++;
1188 }
1189 s++;
1190 }
1191 putchar('\n');
1192 }
1193
1194 /* Header fields of interest. */
1195 if (r->regstart != '\0')
1196 printf("start `%c' ", r->regstart);
1197 if (r->reganch)
1198 printf("anchored ");
1199 if (r->regmust != NULL)
1200 printf("must have \"%s\"", r->regmust);
1201 printf("\n");
1202 }
1203
1204 /*
1205 - regprop - printable representation of opcode
1206 */
1207 static char *
regprop(char * op)1208 regprop( char *op )
1209 {
1210 register char *p;
1211 static char buf[50];
1212
1213 (void) strcpy(buf, ":");
1214
1215 switch (OP(op)) {
1216 case BOL:
1217 p = "BOL";
1218 break;
1219 case EOL:
1220 p = "EOL";
1221 break;
1222 case ANY:
1223 p = "ANY";
1224 break;
1225 case ANYOF:
1226 p = "ANYOF";
1227 break;
1228 case ANYBUT:
1229 p = "ANYBUT";
1230 break;
1231 case BRANCH:
1232 p = "BRANCH";
1233 break;
1234 case EXACTLY:
1235 p = "EXACTLY";
1236 break;
1237 case NOTHING:
1238 p = "NOTHING";
1239 break;
1240 case BACK:
1241 p = "BACK";
1242 break;
1243 case END:
1244 p = "END";
1245 break;
1246 case OPEN+1:
1247 case OPEN+2:
1248 case OPEN+3:
1249 case OPEN+4:
1250 case OPEN+5:
1251 case OPEN+6:
1252 case OPEN+7:
1253 case OPEN+8:
1254 case OPEN+9:
1255 sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
1256 p = NULL;
1257 break;
1258 case CLOSE+1:
1259 case CLOSE+2:
1260 case CLOSE+3:
1261 case CLOSE+4:
1262 case CLOSE+5:
1263 case CLOSE+6:
1264 case CLOSE+7:
1265 case CLOSE+8:
1266 case CLOSE+9:
1267 sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1268 p = NULL;
1269 break;
1270 case STAR:
1271 p = "STAR";
1272 break;
1273 case PLUS:
1274 p = "PLUS";
1275 break;
1276 case WORDA:
1277 p = "WORDA";
1278 break;
1279 case WORDZ:
1280 p = "WORDZ";
1281 break;
1282 default:
1283 my_regerror("corrupted opcode");
1284 break;
1285 }
1286 if (p != NULL)
1287 (void) strcat(buf, p);
1288 return(buf);
1289 }
1290 #endif
1291
1292 /*
1293 * The following is provided for those people who do not have strcspn() in
1294 * their C libraries. They should get off their butts and do something
1295 * about it; at least one public-domain implementation of those (highly
1296 * useful) string routines has been published on Usenet.
1297 */
1298 #ifdef STRCSPN
1299 /*
1300 * strcspn - find length of initial segment of s1 consisting entirely
1301 * of characters not from s2
1302 */
1303
1304 static int
strcspn(char * s1,char * s2)1305 strcspn(
1306 char *s1,
1307 char *s2 )
1308 {
1309 register char *scan1;
1310 register char *scan2;
1311 register int count;
1312
1313 count = 0;
1314 for (scan1 = s1; *scan1 != '\0'; scan1++) {
1315 for (scan2 = s2; *scan2 != '\0';) /* ++ moved down. */
1316 if (*scan1 == *scan2++)
1317 return(count);
1318 count++;
1319 }
1320 return(count);
1321 }
1322 #endif
1323
1324 void
my_regerror(const char * s)1325 my_regerror( const char *s )
1326 {
1327 printf( "re error %s\n", s );
1328 }
1329
1330 /* TNB */
1331 void
my_redone(regexp * re)1332 my_redone(regexp *re)
1333 {
1334 if (re)
1335 free((char *) re);
1336 }
1337