home *** CD-ROM | disk | FTP | other *** search
/ DP Tool Club 31 / CDASC_31_1996_juillet_aout.iso / vrac / souper15.zip / SOURCE / REGEXP.C < prev    next >
C/C++ Source or Header  |  1996-05-18  |  29KB  |  1,234 lines

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