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