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