home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 5 Edit / 05-Edit.zip / STVI369G.ZIP / REGEXP.C < prev    next >
C/C++ Source or Header  |  1990-05-01  |  30KB  |  1,295 lines

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