home *** CD-ROM | disk | FTP | other *** search
/ Atari FTP / ATARI_FTP_0693.zip / ATARI_FTP_0693 / Mint / mntlib32.zoo / regexp.c < prev    next >
C/C++ Source or Header  |  1993-01-30  |  28KB  |  1,079 lines

  1. /* MODIFIED VERSION -- see below */
  2.  
  3. /* regcomp and regexec -- regsub and regerror are elsewhere
  4.  *
  5.  *    Copyright (c) 1986 by University of Toronto.
  6.  *    Written by Henry Spencer.  Not derived from licensed software.
  7.  *
  8.  *    Permission is granted to anyone to use this software for any
  9.  *    purpose on any computer system, and to redistribute it freely,
  10.  *    subject to the following restrictions:
  11.  *
  12.  *    1. The author is not responsible for the consequences of use of
  13.  *        this software, no matter how awful, even if they arise
  14.  *        from defects in it.
  15.  *
  16.  *    2. The origin of this software must not be misrepresented, either
  17.  *        by explicit claim or by omission.
  18.  *
  19.  *    3. Altered versions must be plainly marked as such, and must not
  20.  *        be misrepresented as being the original software.
  21.  *
  22.  * Beware that some of this code is subtly aware of the way operator
  23.  * precedence is structured in regular expressions.  Serious changes in
  24.  * regular-expression syntax might require a total rethink.
  25.  *
  26.  *    The third parameter to regexec was added by Martin C. Atkins.
  27.  *    Andy Tanenbaum also made some changes.
  28.  *      Eric Smith modified it a bit to compile with the MiNT library
  29.  */
  30.  
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #include <regexp.h>
  34. #include <stdio.h>
  35. #ifdef __TURBOC__
  36. # include <sys\types.h>
  37. #else
  38. # include <sys/types.h>
  39. #endif
  40. #ifndef _COMPILER_H
  41. #include <compiler.h>
  42. #endif
  43.  
  44. /* The first byte of the regexp internal "program" is actually this magic
  45.  * number; the start node begins in the second byte.
  46.  */
  47. #define    MAGIC    0234
  48.  
  49. /* The "internal use only" fields in regexp.h are present to pass info from
  50.  * compile to execute that permits the execute phase to run lots faster on
  51.  * simple cases.  They are:
  52.  *
  53.  * regstart    char that must begin a match; '\0' if none obvious
  54.  * reganch    is the match anchored (at beginning-of-line only)?
  55.  * regmust    string (pointer into program) that match must include, or NULL
  56.  * regmlen    length of regmust string
  57.  *
  58.  * Regstart and reganch permit very fast decisions on suitable starting points
  59.  * for a match, cutting down the work a lot.  Regmust permits fast rejection
  60.  * of lines that cannot possibly match.  The regmust tests are costly enough
  61.  * that regcomp() supplies a regmust only if the r.e. contains something
  62.  * potentially expensive (at present, the only such thing detected is * or +
  63.  * at the start of the r.e., which can involve a lot of backup).  Regmlen is
  64.  * supplied because the test in regexec() needs it and regcomp() is computing
  65.  * it anyway.
  66.  */
  67.  
  68. /* Structure for regexp "program".  This is essentially a linear encoding
  69.  * of a nondeterministic finite-state machine (aka syntax charts or
  70.  * "railroad normal form" in parsing technology).  Each node is an opcode
  71.  * plus a "next" pointer, possibly plus an operand.  "Next" pointers of
  72.  * all nodes except BRANCH implement concatenation; a "next" pointer with
  73.  * a BRANCH on both ends of it is connecting two alternatives.  (Here we
  74.  * have one of the subtle syntax dependencies:  an individual BRANCH (as
  75.  * opposed to a collection of them) is never concatenated with anything
  76.  * because of operator precedence.)  The operand of some types of node is
  77.  * a literal string; for others, it is a node leading into a sub-FSM.  In
  78.  * particular, the operand of a BRANCH node is the first node of the branch.
  79.  * (NB this is *not* a tree structure:  the tail of the branch connects
  80.  * to the thing following the set of BRANCHes.)  The opcodes are:
  81.  */
  82.  
  83. /* Definition    number    opnd?    meaning */
  84. #define    END    0        /* no    End of program. */
  85. #define    BOL    1        /* no    Match "" at beginning of line. */
  86. #define    EOL    2        /* no    Match "" at end of line. */
  87. #define    ANY    3        /* no    Match any one character. */
  88. #define    ANYOF    4        /* str    Match any character in this string. */
  89. #define    ANYBUT    5        /* str    Match any character not in this
  90.              * string. */
  91. #define    BRANCH    6        /* node    Match this alternative, or the
  92.              * next... */
  93. #define    BACK    7        /* no    Match "", "next" ptr points backward. */
  94. #define    EXACTLY    8        /* str    Match this string. */
  95. #define    NOTHING    9        /* no    Match empty string. */
  96. #define    STAR    10        /* node    Match this (simple) thing 0 or more
  97.              * times. */
  98. #define    PLUS    11        /* node    Match this (simple) thing 1 or more
  99.              * times. */
  100. #define    OPEN    20        /* no    Mark this point in input as start of
  101.              * #n. */
  102.  /* OPEN+1 is number 1, etc. */
  103. #define    CLOSE    30        /* no    Analogous to OPEN. */
  104.  
  105. /* Opcode notes:
  106.  *
  107.  * BRANCH    The set of branches constituting a single choice are hooked
  108.  *        together with their "next" pointers, since precedence prevents
  109.  *        anything being concatenated to any individual branch.  The
  110.  *        "next" pointer of the last BRANCH in a choice points to the
  111.  *        thing following the whole choice.  This is also where the
  112.  *        final "next" pointer of each individual branch points; each
  113.  *        branch starts with the operand node of a BRANCH node.
  114.  *
  115.  * BACK        Normal "next" pointers all implicitly point forward; BACK
  116.  *        exists to make loop structures possible.
  117.  *
  118.  * STAR,PLUS    '?', and complex '*' and '+', are implemented as circular
  119.  *        BRANCH structures using BACK.  Simple cases (one character
  120.  *        per match) are implemented with STAR and PLUS for speed
  121.  *        and to minimize recursive plunges.
  122.  *
  123.  * OPEN,CLOSE    ...are numbered at compile time.
  124.  */
  125.  
  126. /* A node is one char of opcode followed by two chars of "next" pointer.
  127.  * "Next" pointers are stored as two 8-bit pieces, high order first.  The
  128.  * value is a positive offset from the opcode of the node containing it.
  129.  * An operand, if any, simply follows the node.  (Note that much of the
  130.  * code generation knows about this implicit relationship.)
  131.  *
  132.  * Using two bytes for the "next" pointer is vast overkill for most things,
  133.  * but allows patterns to get big without disasters.
  134.  */
  135. #define    OP(p)    (*(p))
  136. #define    NEXT(p)    (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
  137. #define    OPERAND(p)    ((p) + 3)
  138.  
  139. /* Utility definitions.
  140.  */
  141. #ifndef CHARBITS
  142. #define    UCHARAT(p)    ((int)*(unsigned char *)(p))
  143. #else
  144. #define    UCHARAT(p)    ((int)*(p)&CHARBITS)
  145. #endif
  146.  
  147. #define    CFAIL(m)    { regerror(m); return((char *)NULL); }
  148. #define    RFAIL(m)    { regerror(m); return((regexp *)NULL); }
  149. #define    ISMULT(c)    ((c) == '*' || (c) == '+' || (c) == '?')
  150. #define    META    "^$.[()|?+*\\"
  151.  
  152. /* Flags to be passed up and down.
  153.  */
  154. #define    HASWIDTH    01    /* Known never to match null string. */
  155. #define    SIMPLE        02    /* Simple enough to be STAR/PLUS operand. */
  156. #define    SPSTART        04    /* Starts with * or +. */
  157. #define    WORST        0    /* Worst case. */
  158.  
  159. /* Global work variables for regcomp().
  160.  */
  161. static char *regparse;        /* Input-scan pointer. */
  162. static int regnpar;        /* () count. */
  163. static char regdummy;
  164. static char *regcode;        /* Code-emit pointer; ®dummy = don't. */
  165. static long regsize;        /* Code size. */
  166.  
  167. /* Forward declarations for regcomp()'s friends.
  168.  */
  169. static char *reg __PROTO((int paren, int *flagp));
  170. static char *regbranch __PROTO((int *flagp));
  171. static char *regpiece __PROTO((int *flagp));
  172. static char *regatom __PROTO((int *flagp));
  173. static char *regnode __PROTO((int op));
  174. static void regc __PROTO((int b));
  175. static void reginsert __PROTO((int op, char *opnd));
  176. static void regtail __PROTO((char *p, char *val));
  177. static void regoptail __PROTO((char *p, char *val));
  178. static int regtry __PROTO((regexp *prog, char *string));
  179. static int regmatch __PROTO((char *prog));
  180. static size_t regrepeat __PROTO((char *p));
  181. static char *regnext __PROTO((char *p));
  182. #ifdef DEBUG
  183. static char *regprop __PROTO((char *op));
  184. #endif
  185.  
  186. /*
  187.  - regcomp - compile a regular expression into internal code
  188.  *
  189.  * We can't allocate space until we know how big the compiled form will be,
  190.  * but we can't compile it (and thus know how big it is) until we've got a
  191.  * place to put the code.  So we cheat:  we compile it twice, once with code
  192.  * generation turned off and size counting turned on, and once "for real".
  193.  * This also means that we don't allocate space until we are sure that the
  194.  * thing really will compile successfully, and we never have to move the
  195.  * code and thus invalidate pointers into it.  (Note that it has to be in
  196.  * one piece because free() must be able to free it all.)
  197.  *
  198.  * Beware that the optimization-preparation code in here knows about some
  199.  * of the structure of the compiled regexp.
  200.  */
  201. regexp *regcomp(exp)
  202. char *exp;
  203. {
  204.   register regexp *r;
  205.   register char *scan;
  206.   register char *longest;
  207.   register size_t len;
  208.   int flags;
  209.  
  210.   if (exp == (char *)NULL) RFAIL("NULL argument");
  211.  
  212.   /* First pass: determine size, legality. */
  213.   regparse = exp;
  214.   regnpar = 1;
  215.   regsize = 0L;
  216.   regcode = ®dummy;
  217.   regc(MAGIC);
  218.   if (reg(0, &flags) == (char *)NULL) return((regexp *)NULL);
  219.  
  220.   /* Small enough for pointer-storage convention? */
  221.   if (regsize >= 32767L)    /* Probably could be 65535L. */
  222.     RFAIL("regexp too big");
  223.  
  224.   /* Allocate space. */
  225.   r = (regexp *) malloc(sizeof(regexp) + (size_t) regsize);
  226.   if (r == (regexp *)NULL) RFAIL("out of space");
  227.  
  228.   /* Second pass: emit code. */
  229.   regparse = exp;
  230.   regnpar = 1;
  231.   regcode = r->program;
  232.   regc(MAGIC);
  233.   if (reg(0, &flags) == (char *)NULL) return((regexp *)NULL);
  234.  
  235.   /* Dig out information for optimizations. */
  236.   r->regstart = '\0';        /* Worst-case defaults. */
  237.   r->reganch = 0;
  238.   r->regmust = (char *)NULL;
  239.   r->regmlen = 0;
  240.   scan = r->program + 1;    /* First BRANCH. */
  241.   if (OP(regnext(scan)) == END) {    /* Only one top-level choice. */
  242.     scan = OPERAND(scan);
  243.  
  244.     /* Starting-point info. */
  245.     if (OP(scan) == EXACTLY)
  246.         r->regstart = *OPERAND(scan);
  247.     else if (OP(scan) == BOL)
  248.         r->reganch++;
  249.  
  250.     /* If there's something expensive in the r.e., find the
  251.      * longest literal string that must appear and make it the
  252.      * regmust.  Resolve ties in favor of later strings, since
  253.      * the regstart check works with the beginning of the r.e.
  254.      * and avoiding duplication strengthens checking.  Not a
  255.      * strong reason, but sufficient in the absence of others. */
  256.     if (flags & SPSTART) {
  257.         longest = (char *)NULL;
  258.         len = 0;
  259.         for (; scan != (char *)NULL; scan = regnext(scan))
  260.             if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
  261.                 longest = OPERAND(scan);
  262.                 len = strlen(OPERAND(scan));
  263.             }
  264.         r->regmust = longest;
  265.         r->regmlen = len;
  266.     }
  267.   }
  268.   return(r);
  269. }
  270.  
  271. /*
  272.  - reg - regular expression, i.e. main body or parenthesized thing
  273.  *
  274.  * Caller must absorb opening parenthesis.
  275.  *
  276.  * Combining parenthesis handling with the base level of regular expression
  277.  * is a trifle forced, but the need to tie the tails of the branches to what
  278.  * follows makes it hard to avoid.
  279.  */
  280. static char *reg(paren, flagp)
  281. int paren;            /* Parenthesized? */
  282. int *flagp;
  283. {
  284.   register char *ret;
  285.   register char *br;
  286.   register char *ender;
  287.   register int parno;
  288.   int flags;
  289.  
  290.   *flagp = HASWIDTH;        /* Tentatively. */
  291.  
  292.   /* Make an OPEN node, if parenthesized. */
  293.   if (paren) {
  294.     if (regnpar >= NSUBEXP) CFAIL("too many ()");
  295.     parno = regnpar;
  296.     regnpar++;
  297.     ret = regnode(OPEN + parno);
  298.   } else {
  299.     parno = 0;        /* not actually used, keep compiler quiet */
  300.     ret = (char *)NULL;
  301.   }
  302.  
  303.   /* Pick up the branches, linking them together. */
  304.   br = regbranch(&flags);
  305.   if (br == (char *)NULL) return((char *)NULL);
  306.   if (ret != (char *)NULL)
  307.     regtail(ret, br);    /* OPEN -> first. */
  308.   else
  309.     ret = br;
  310.   if (!(flags & HASWIDTH)) *flagp &= ~HASWIDTH;
  311.   *flagp |= flags & SPSTART;
  312.   while (*regparse == '|') {
  313.     regparse++;
  314.     br = regbranch(&flags);
  315.     if (br == (char *)NULL) return((char *)NULL);
  316.     regtail(ret, br);    /* BRANCH -> BRANCH. */
  317.     if (!(flags & HASWIDTH)) *flagp &= ~HASWIDTH;
  318.     *flagp |= flags & SPSTART;
  319.   }
  320.  
  321.   /* Make a closing node, and hook it on the end. */
  322.   ender = regnode((paren) ? CLOSE + parno : END);
  323.   regtail(ret, ender);
  324.  
  325.   /* Hook the tails of the branches to the closing node. */
  326.   for (br = ret; br != (char *)NULL; br = regnext(br)) regoptail(br, ender);
  327.  
  328.   /* Check for proper termination. */
  329.   if (paren && *regparse++ != ')') {
  330.     CFAIL("unmatched ()");
  331.   } else if (!paren && *regparse != '\0') {
  332.     if (*regparse == ')') {
  333.         CFAIL("unmatched ()");
  334.     } else
  335.         CFAIL("junk on end");    /* "Can't happen". */
  336.     /* NOTREACHED */
  337.   }
  338.   return(ret);
  339. }
  340.  
  341. /*
  342.  - regbranch - one alternative of an | operator
  343.  *
  344.  * Implements the concatenation operator.
  345.  */
  346. static char *regbranch(flagp)
  347. int *flagp;
  348. {
  349.   register char *ret;
  350.   register char *chain;
  351.   register char *latest;
  352.   int flags;
  353.  
  354.   *flagp = WORST;        /* Tentatively. */
  355.  
  356.   ret = regnode(BRANCH);
  357.   chain = (char *)NULL;
  358.   while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
  359.     latest = regpiece(&flags);
  360.     if (latest == (char *)NULL) return((char *)NULL);
  361.     *flagp |= flags & HASWIDTH;
  362.     if (chain == (char *)NULL)    /* First piece. */
  363.         *flagp |= flags & SPSTART;
  364.     else
  365.         regtail(chain, latest);
  366.     chain = latest;
  367.   }
  368.   if (chain == (char *)NULL)        /* Loop ran zero times. */
  369.     regnode(NOTHING);
  370.  
  371.   return(ret);
  372. }
  373.  
  374. /*
  375.  - regpiece - something followed by possible [*+?]
  376.  *
  377.  * Note that the branching code sequences used for ? and the general cases
  378.  * of * and + are somewhat optimized:  they use the same NOTHING node as
  379.  * both the endmarker for their branch list and the body of the last branch.
  380.  * It might seem that this node could be dispensed with entirely, but the
  381.  * endmarker role is not redundant.
  382.  */
  383. static char *regpiece(flagp)
  384. int *flagp;
  385. {
  386.   register char *ret;
  387.   register char op;
  388.   register char *next;
  389.   int flags;
  390.  
  391.   ret = regatom(&flags);
  392.   if (ret == (char *)NULL) return((char *)NULL);
  393.  
  394.   op = *regparse;
  395.   if (!ISMULT(op)) {
  396.     *flagp = flags;
  397.     return(ret);
  398.   }
  399.   if (!(flags & HASWIDTH) && op != '?') CFAIL("*+ operand could be empty");
  400.   *flagp = (op != '+') ? (WORST | SPSTART) : (WORST | HASWIDTH);
  401.  
  402.   if (op == '*' && (flags & SIMPLE))
  403.     reginsert(STAR, ret);
  404.   else if (op == '*') {
  405.     /* Emit x* as (x&|), where & means "self". */
  406.     reginsert(BRANCH, ret);    /* Either x */
  407.     regoptail(ret, regnode(BACK));    /* and loop */
  408.     regoptail(ret, ret);    /* back */
  409.     regtail(ret, regnode(BRANCH));    /* or */
  410.     regtail(ret, regnode(NOTHING));    /* null. */
  411.   } else if (op == '+' && (flags & SIMPLE))
  412.     reginsert(PLUS, ret);
  413.   else if (op == '+') {
  414.     /* Emit x+ as x(&|), where & means "self". */
  415.     next = regnode(BRANCH);    /* Either */
  416.     regtail(ret, next);
  417.     regtail(regnode(BACK), ret);    /* loop back */
  418.     regtail(next, regnode(BRANCH));    /* or */
  419.     regtail(ret, regnode(NOTHING));    /* null. */
  420.   } else if (op == '?') {
  421.     /* Emit x? as (x|) */
  422.     reginsert(BRANCH, ret);    /* Either x */
  423.     regtail(ret, regnode(BRANCH));    /* or */
  424.     next = regnode(NOTHING);/* null. */
  425.     regtail(ret, next);
  426.     regoptail(ret, next);
  427.   }
  428.   regparse++;
  429.   if (ISMULT(*regparse)) CFAIL("nested *?+");
  430.  
  431.   return(ret);
  432. }
  433.  
  434. /*
  435.  - regatom - the lowest level
  436.  *
  437.  * Optimization:  gobbles an entire sequence of ordinary characters so that
  438.  * it can turn them into a single node, which is smaller to store and
  439.  * faster to run.  Backslashed characters are exceptions, each becoming a
  440.  * separate node; the code is simpler that way and it's not worth fixing.
  441.  */
  442. static char *regatom(flagp)
  443. int *flagp;
  444. {
  445.   register char *ret;
  446.   int flags;
  447.  
  448.   *flagp = WORST;        /* Tentatively. */
  449.  
  450.   switch (*regparse++) {
  451.       case '^':    ret = regnode(BOL);          break;
  452.       case '$':    ret = regnode(EOL);          break;
  453.       case '.':
  454.     ret = regnode(ANY);
  455.     *flagp |= HASWIDTH | SIMPLE;
  456.     break;
  457.       case '[':{
  458.         register int class;
  459.         register int classend;
  460.  
  461.         if (*regparse == '^') {    /* Complement of range. */
  462.             ret = regnode(ANYBUT);
  463.             regparse++;
  464.         } else
  465.             ret = regnode(ANYOF);
  466.         if (*regparse == ']' || *regparse == '-') regc(*regparse++);
  467.         while (*regparse != '\0' && *regparse != ']') {
  468.             if (*regparse == '-') {
  469.                 regparse++;
  470.                 if (*regparse == ']' || *regparse == '\0')
  471.                     regc('-');
  472.                 else {
  473.                     class = UCHARAT(regparse - 2) + 1;
  474.                     classend = UCHARAT(regparse);
  475.                     if (class > classend + 1)
  476.                         CFAIL("invalid [] range");
  477.                     for (; class <= classend; class++)
  478.                         regc(class);
  479.                     regparse++;
  480.                 }
  481.             } else
  482.                 regc(*regparse++);
  483.         }
  484.         regc('\0');
  485.         if (*regparse != ']') CFAIL("unmatched []");
  486.         regparse++;
  487.         *flagp |= HASWIDTH | SIMPLE;
  488.     }
  489.     break;
  490.       case '(':
  491.     ret = reg(1, &flags);
  492.     if (ret == (char *)NULL) return((char *)NULL);
  493.     *flagp |= flags & (HASWIDTH | SPSTART);
  494.     break;
  495.       case '\0':
  496.       case '|':
  497.       case ')':
  498.     CFAIL("internal urp");    /* Supposed to be caught earlier. */
  499.     break;
  500.       case '?':
  501.       case '+':
  502.       case '*':    CFAIL("?+* follows nothing");          break;
  503.       case '\\':
  504.     if (*regparse == '\0') CFAIL("trailing \\");
  505.     ret = regnode(EXACTLY);
  506.     regc(*regparse++);
  507.     regc('\0');
  508.     *flagp |= HASWIDTH | SIMPLE;
  509.     break;
  510.       default:{
  511.         register size_t len;
  512.         register char ender;
  513.  
  514.         regparse--;
  515.         len = strcspn(regparse, META);
  516.         if (len <= 0) CFAIL("internal disaster");
  517.         ender = *(regparse + len);
  518.         if (len > 1 && ISMULT(ender))
  519.             len--;    /* Back off clear of ?+* operand. */
  520.         *flagp |= HASWIDTH;
  521.         if (len == 1) *flagp |= SIMPLE;
  522.         ret = regnode(EXACTLY);
  523.         while (len > 0) {
  524.             regc(*regparse++);
  525.             len--;
  526.         }
  527.         regc('\0');
  528.     }
  529.     break;
  530.   }
  531.  
  532.   return(ret);
  533. }
  534.  
  535. /*
  536.  - regnode - emit a node
  537.  */
  538. static char *regnode(op)
  539. int op;
  540. {
  541.   register char *ret;
  542.   register char *ptr;
  543.  
  544.   ret = regcode;
  545.   if (ret == ®dummy) {
  546.     regsize += 3;
  547.     return(ret);
  548.   }
  549.   ptr = ret;
  550.   *ptr++ = op;
  551.   *ptr++ = '\0';        /* Null "next" pointer. */
  552.   *ptr++ = '\0';
  553.   regcode = ptr;
  554.  
  555.   return(ret);
  556. }
  557.  
  558. /*
  559.  - regc - emit (if appropriate) a byte of code
  560.  */
  561. static void regc(b)
  562. int b;
  563. {
  564.   if (regcode != ®dummy)
  565.     *regcode++ = b;
  566.   else
  567.     regsize++;
  568. }
  569.  
  570. /*
  571.  - reginsert - insert an operator in front of already-emitted operand
  572.  *
  573.  * Means relocating the operand.
  574.  */
  575. static void reginsert(op, opnd)
  576. int op;
  577. char *opnd;
  578. {
  579.   register char *src;
  580.   register char *dst;
  581.   register char *place;
  582.  
  583.   if (regcode == ®dummy) {
  584.     regsize += 3;
  585.     return;
  586.   }
  587.   src = regcode;
  588.   regcode += 3;
  589.   dst = regcode;
  590.   while (src > opnd) *--dst = *--src;
  591.  
  592.   place = opnd;            /* Op node, where operand used to be. */
  593.   *place++ = op;
  594.   *place++ = '\0';
  595.   *place++ = '\0';
  596. }
  597.  
  598. /*
  599.  - regtail - set the next-pointer at the end of a node chain
  600.  */
  601. static void regtail(p, val)
  602. char *p;
  603. char *val;
  604. {
  605.   register char *scan;
  606.   register char *temp;
  607.   register long offset;
  608.  
  609.   if (p == ®dummy) return;
  610.  
  611.   /* Find last node. */
  612.   scan = p;
  613.   for (;;) {
  614.     temp = regnext(scan);
  615.     if (temp == (char *)NULL) break;
  616.     scan = temp;
  617.   }
  618.  
  619.   if (OP(scan) == BACK)
  620.     offset = scan - val;
  621.   else
  622.     offset = val - scan;
  623.   *(scan + 1) = (offset >> 8) & 0377;
  624.   *(scan + 2) = offset & 0377;
  625. }
  626.  
  627. /*
  628.  - regoptail - regtail on operand of first argument; nop if operandless
  629.  */
  630. static void regoptail(p, val)
  631. char *p;
  632. char *val;
  633. {
  634.   /* "Operandless" and "op != BRANCH" are synonymous in practice. */
  635.   if (p == (char *)NULL || p == ®dummy || OP(p) != BRANCH) return;
  636.   regtail(OPERAND(p), val);
  637. }
  638.  
  639. /* regexec and friends
  640.  */
  641.  
  642. /* Global work variables for regexec().
  643.  */
  644. static char *reginput;        /* String-input pointer. */
  645. static char *regbol;        /* Beginning of input, for ^ check. */
  646. static char **regstartp;    /* Pointer to startp array. */
  647. static char **regendp;        /* Ditto for endp. */
  648.  
  649. #ifdef DEBUG
  650. int regnarrate = 0;
  651. #endif
  652.  
  653. /*
  654.  - regexec - match a regexp against a string
  655.  */
  656. int regexec(prog, string, bolflag)
  657. register regexp *prog;
  658. register char *string;
  659. int bolflag;
  660. {
  661.   register char *s;
  662.  
  663.   /* Be paranoid... */
  664.   if (prog == (regexp *)NULL || string == (char *)NULL) {
  665.     regerror("NULL parameter");
  666.     return(0);
  667.   }
  668.  
  669.   /* Check validity of program. */
  670.   if (UCHARAT(prog->program) != MAGIC) {
  671.     regerror("corrupted program");
  672.     return(0);
  673.   }
  674.  
  675.   /* If there is a "must appear" string, look for it. */
  676.   if (prog->regmust != (char *)NULL) {
  677.     s = string;
  678.     while ((s = strchr(s, prog->regmust[0])) != (char *)NULL) {
  679.         if (strncmp(s, prog->regmust, prog->regmlen) == 0)
  680.             break;    /* Found it. */
  681.         s++;
  682.     }
  683.     if (s == (char *)NULL)        /* Not present. */
  684.         return(0);
  685.   }
  686.  
  687.   /* Mark beginning of line for ^ . */
  688.   if (bolflag)
  689.     regbol = string;
  690.   else
  691.     regbol = (char *)NULL;
  692.  
  693.   /* Simplest case:  anchored match need be tried only once. */
  694.   if (prog->reganch) return(regtry(prog, string));
  695.  
  696.   /* Messy cases:  unanchored match. */
  697.   s = string;
  698.   if (prog->regstart != '\0')     /* We know what char it must start with. */
  699.     while ((s = strchr(s, prog->regstart)) != (char *)NULL) {
  700.         if (regtry(prog, s)) return(1);
  701.         s++;
  702.     }
  703.   else
  704.     /* We don't -- general case. */
  705.     do {
  706.         if (regtry(prog, s)) return(1);
  707.     } while (*s++ != '\0');
  708.  
  709.   /* Failure. */
  710.   return(0);
  711. }
  712.  
  713. /*
  714.  - regtry - try match at specific point
  715.  */
  716. static int regtry(prog, string)   /* 0 failure, 1 success */
  717. regexp *prog;
  718. char *string;
  719. {
  720.   register int i;
  721.   register char **sp;
  722.   register char **ep;
  723.  
  724.   reginput = string;
  725.   regstartp = prog->startp;
  726.   regendp = prog->endp;
  727.  
  728.   sp = prog->startp;
  729.   ep = prog->endp;
  730.   for (i = NSUBEXP; i > 0; i--) {
  731.     *sp++ = (char *)NULL;
  732.     *ep++ = (char *)NULL;
  733.   }
  734.   if (regmatch(prog->program + 1)) {
  735.     prog->startp[0] = string;
  736.     prog->endp[0] = reginput;
  737.     return(1);
  738.   } else
  739.     return(0);
  740. }
  741.  
  742. /*
  743.  - regmatch - main matching routine
  744.  *
  745.  * Conceptually the strategy is simple:  check to see whether the current
  746.  * node matches, call self recursively to see whether the rest matches,
  747.  * and then act accordingly.  In practice we make some effort to avoid
  748.  * recursion, in particular by going through "ordinary" nodes (that don't
  749.  * need to know whether the rest of the match failed) by a loop instead of
  750.  * by recursion.
  751.  */
  752. static int regmatch(prog)    /* 0 failure, 1 success */ 
  753. char *prog;
  754. {
  755.   register char *scan;        /* Current node. */
  756.   char *next;            /* Next node. */
  757.  
  758.   scan = prog;
  759. #ifdef DEBUG
  760.   if (scan != (char *)NULL && regnarrate) fprintf(stderr, "%s(\n", regprop(scan));
  761. #endif
  762.   while (scan != (char *)NULL) {
  763. #ifdef DEBUG
  764.     if (regnarrate) fprintf(stderr, "%s...\n", regprop(scan));
  765. #endif
  766.     next = regnext(scan);
  767.  
  768.     switch (OP(scan)) {
  769.         case BOL:
  770.         if (reginput != regbol) return(0);
  771.         break;
  772.         case EOL:
  773.         if (*reginput != '\0') return(0);
  774.         break;
  775.         case ANY:
  776.         if (*reginput == '\0') return(0);
  777.         reginput++;
  778.         break;
  779.         case EXACTLY:{
  780.             register size_t len;
  781.             register char *opnd;
  782.  
  783.             opnd = OPERAND(scan);
  784.             /* Inline the first character, for speed. */
  785.             if (*opnd != *reginput) return(0);
  786.             len = strlen(opnd);
  787.             if (len > 1 && strncmp(opnd, reginput, len) != 0)
  788.                 return(0);
  789.             reginput += len;
  790.         }
  791.         break;
  792.         case ANYOF:
  793.         if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == (char *)NULL)
  794.             return(0);
  795.         reginput++;
  796.         break;
  797.         case ANYBUT:
  798.         if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != (char *)NULL)
  799.             return(0);
  800.         reginput++;
  801.         break;
  802.         case NOTHING:
  803.         break;
  804.         case BACK:
  805.         break;
  806.         case OPEN + 1:
  807.         case OPEN + 2:
  808.         case OPEN + 3:
  809.         case OPEN + 4:
  810.         case OPEN + 5:
  811.         case OPEN + 6:
  812.         case OPEN + 7:
  813.         case OPEN + 8:
  814.         case OPEN + 9:{
  815.             register int no;
  816.             register char *save;
  817.  
  818.             no = OP(scan) - OPEN;
  819.             save = reginput;
  820.  
  821.             if (regmatch(next)) {
  822.                 /* Don't set startp if some later
  823.                  * invocation of the same parentheses
  824.                  * already has. */
  825.                 if (regstartp[no] == (char *)NULL)
  826.                     regstartp[no] = save;
  827.                 return(1);
  828.             } else
  829.                 return(0);
  830.         }
  831.         break;
  832.         case CLOSE + 1:
  833.         case CLOSE + 2:
  834.         case CLOSE + 3:
  835.         case CLOSE + 4:
  836.         case CLOSE + 5:
  837.         case CLOSE + 6:
  838.         case CLOSE + 7:
  839.         case CLOSE + 8:
  840.         case CLOSE + 9:{
  841.             register int no;
  842.             register char *save;
  843.  
  844.             no = OP(scan) - CLOSE;
  845.             save = reginput;
  846.  
  847.             if (regmatch(next)) {
  848.                 /* Don't set endp if some later
  849.                  * invocation of the same parentheses
  850.                  * already has. */
  851.                 if (regendp[no] == (char *)NULL) regendp[no] = save;
  852.                 return(1);
  853.             } else
  854.                 return(0);
  855.         }
  856.         break;
  857.         case BRANCH:{
  858.             register char *save;
  859.  
  860.             if (OP(next) != BRANCH)    /* No choice. */
  861.                 next = OPERAND(scan);    /* Avoid recursion. */
  862.             else {
  863.                 do {
  864.                     save = reginput;
  865.                     if (regmatch(OPERAND(scan)))
  866.                         return(1);
  867.                     reginput = save;
  868.                     scan = regnext(scan);
  869.                 } while (scan != (char *)NULL && OP(scan) == BRANCH);
  870.                 return(0);
  871.                 /* NOTREACHED */
  872.             }
  873.         }
  874.         break;
  875.         case STAR:
  876.         case PLUS:{
  877.             register char nextch;
  878.             register long no;
  879.             register char *save;
  880.             register long min;
  881.  
  882.             /* Lookahead to avoid useless match attempts
  883.              * when we know what character comes next. */
  884.             nextch = '\0';
  885.             if (OP(next) == EXACTLY) nextch = *OPERAND(next);
  886.             min = (OP(scan) == STAR) ? 0 : 1;
  887.             save = reginput;
  888.             no = regrepeat(OPERAND(scan));
  889.             while (no >= min) {
  890.                 /* If it could work, try it. */
  891.                 if (nextch == '\0' || *reginput == nextch)
  892.                     if (regmatch(next)) return(1);
  893.                 /* Couldn't or didn't -- back up. */
  894.                 no--;
  895.                 reginput = save + no;
  896.             }
  897.             return(0);
  898.         }
  899.         break;
  900.         case END:
  901.         return(1);    /* Success! */
  902.         break;
  903.         default:
  904.         regerror("memory corruption");
  905.         return(0);
  906.         break;
  907.     }
  908.  
  909.     scan = next;
  910.   }
  911.  
  912.   /* We get here only if there's trouble -- normally "case END" is the
  913.    * terminating point. */
  914.   regerror("corrupted pointers");
  915.   return(0);
  916. }
  917.  
  918. /*
  919.  - regrepeat - repeatedly match something simple, report how many
  920.  */
  921. static size_t regrepeat(p)
  922. char *p;
  923. {
  924.   register size_t count = 0;
  925.   register char *scan;
  926.   register char *opnd;
  927.  
  928.   scan = reginput;
  929.   opnd = OPERAND(p);
  930.   switch (OP(p)) {
  931.       case ANY:
  932.     count = strlen(scan);
  933.     scan += count;
  934.     break;
  935.       case EXACTLY:
  936.     while (*opnd == *scan) {
  937.         count++;
  938.         scan++;
  939.     }
  940.     break;
  941.       case ANYOF:
  942.     while (*scan != '\0' && strchr(opnd, *scan) != (char *)NULL) {
  943.         count++;
  944.         scan++;
  945.     }
  946.     break;
  947.       case ANYBUT:
  948.     while (*scan != '\0' && strchr(opnd, *scan) == (char *)NULL) {
  949.         count++;
  950.         scan++;
  951.     }
  952.     break;
  953.       default:            /* Oh dear.  Called inappropriately. */
  954.     regerror("internal foulup");
  955.     count = 0;        /* Best compromise. */
  956.     break;
  957.   }
  958.   reginput = scan;
  959.  
  960.   return(count);
  961. }
  962.  
  963. /*
  964.  - regnext - dig the "next" pointer out of a node
  965.  */
  966. static char *regnext(p)
  967. register char *p;
  968. {
  969.   register int offset;
  970.  
  971.   if (p == ®dummy) return((char *)NULL);
  972.  
  973.   offset = NEXT(p);
  974.   if (offset == 0) return((char *)NULL);
  975.  
  976.   if (OP(p) == BACK)
  977.     return(p - offset);
  978.   else
  979.     return(p + offset);
  980. }
  981.  
  982. #ifdef DEBUG
  983.  
  984. static char *regprop();
  985.  
  986. /*
  987.  - regdump - dump a regexp onto stdout in vaguely comprehensible form
  988.  */
  989. void regdump(r)
  990. regexp *r;
  991. {
  992.   register char *s;
  993.   register char op = EXACTLY;    /* Arbitrary non-END op. */
  994.   register char *next;
  995.  
  996.   s = r->program + 1;
  997.   while (op != END) {        /* While that wasn't END last time... */
  998.     op = OP(s);
  999.     printf("%2d%s", (int) (s - r->program), regprop(s));    /* Where, what. */
  1000.     next = regnext(s);
  1001.     if (next == (char *)NULL)    /* Next ptr. */
  1002.         printf("(0)");
  1003.     else
  1004.         printf("(%d)", (int) (s - r->program) + (int) (next - s));
  1005.     s += 3;
  1006.     if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
  1007.         /* Literal string, where present. */
  1008.         while (*s != '\0') {
  1009.             putchar(*s);
  1010.             s++;
  1011.         }
  1012.         s++;
  1013.     }
  1014.     putchar('\n');
  1015.   }
  1016.  
  1017.   /* Header fields of interest. */
  1018.   if (r->regstart != '\0') printf("start `%c' ", r->regstart);
  1019.   if (r->reganch) printf("anchored ");
  1020.   if (r->regmust != (char *)NULL) printf("must have \"%s\"", r->regmust);
  1021.   printf("\n");
  1022. }
  1023.  
  1024. /*
  1025.  - regprop - printable representation of opcode
  1026.  */
  1027. static char *regprop(op)
  1028. char *op;
  1029. {
  1030.   register char *p;
  1031.   static char buf[50];
  1032.  
  1033.   (void) strcpy(buf, ":");
  1034.  
  1035.   switch (OP(op)) {
  1036.       case BOL:    p = "BOL";          break;
  1037.       case EOL:    p = "EOL";          break;
  1038.       case ANY:    p = "ANY";          break;
  1039.       case ANYOF:    p = "ANYOF";          break;
  1040.       case ANYBUT:    p = "ANYBUT";          break;
  1041.       case BRANCH:    p = "BRANCH";          break;
  1042.       case EXACTLY:    p = "EXACTLY";          break;
  1043.       case NOTHING:    p = "NOTHING";          break;
  1044.       case BACK:    p = "BACK";          break;
  1045.       case END:    p = "END";          break;
  1046.       case OPEN + 1:
  1047.       case OPEN + 2:
  1048.       case OPEN + 3:
  1049.       case OPEN + 4:
  1050.       case OPEN + 5:
  1051.       case OPEN + 6:
  1052.       case OPEN + 7:
  1053.       case OPEN + 8:
  1054.       case OPEN + 9:
  1055.     sprintf(buf + strlen(buf), "OPEN%d", OP(op) - OPEN);
  1056.     p = (char *)NULL;
  1057.     break;
  1058.       case CLOSE + 1:
  1059.       case CLOSE + 2:
  1060.       case CLOSE + 3:
  1061.       case CLOSE + 4:
  1062.       case CLOSE + 5:
  1063.       case CLOSE + 6:
  1064.       case CLOSE + 7:
  1065.       case CLOSE + 8:
  1066.       case CLOSE + 9:
  1067.     sprintf(buf + strlen(buf), "CLOSE%d", OP(op) - CLOSE);
  1068.     p = (char *)NULL;
  1069.     break;
  1070.       case STAR:    p = "STAR";          break;
  1071.       case PLUS:    p = "PLUS";          break;
  1072.       default:    regerror("corrupted opcode"); p = (char *) NULL; break;
  1073.   }
  1074.   if (p != (char *)NULL) (void) strcat(buf, p);
  1075.   return(buf);
  1076. }
  1077.  
  1078. #endif
  1079.