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