home *** CD-ROM | disk | FTP | other *** search
/ ProfitPress Mega CDROM2 …eeware (MSDOS)(1992)(Eng) / ProfitPress-MegaCDROM2.B6I / MISC / GNU / GREP15AS.ZIP / DFA.C < prev    next >
Encoding:
C/C++ Source or Header  |  1992-02-22  |  57.5 KB  |  2,212 lines

  1. /* dfa.c - determinisitic extended regexp routines for GNU
  2.    Copyright (C) 1988 Free Software Foundation, Inc.
  3.                       Written June, 1988 by Mike Haertel
  4.               Modified July, 1988 by Arthur David Olson
  5.              to assist BMG speedups
  6.  
  7.    This program is free software; you can redistribute it and/or modify
  8.    it under the terms of the GNU General Public License as published by
  9.    the Free Software Foundation; either version 1, or (at your option)
  10.    any later version.
  11.  
  12.    This program is distributed in the hope that it will be useful,
  13.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15.    GNU General Public License for more details.
  16.  
  17.    You should have received a copy of the GNU General Public License
  18.    along with this program; if not, write to the Free Software
  19.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  20.  
  21. /* MS-DOS port (c) 1990 by Thorsten Ohl <ohl@gnu.ai.mit.edu>
  22.  
  23.    This port is also distributed under the terms of the
  24.    GNU General Public License as published by the
  25.    Free Software Foundation.
  26.  
  27.    Please note that this file is not identical to the
  28.    original GNU release, you should have received this
  29.    code as patch to the official release.
  30.  
  31.    $Header: e:/gnu/grep/RCS/dfa.c 1.5.0.4 90/09/21 11:48:02 tho Exp $   */
  32.  
  33. #include <stdio.h>
  34. #include <assert.h>
  35. #include <ctype.h>
  36. #include "dfa.h"
  37.  
  38. #ifdef __STDC__
  39. typedef void *ptr_t;
  40.  
  41. #ifdef MSDOS
  42. #include <stdlib.h>
  43. static void *xcalloc (int n, unsigned int s);
  44. static void *xmalloc (unsigned int n);
  45. static void *xrealloc (void *p, unsigned int n);
  46. static int tstbit (int b, int *c);
  47. static void setbit (int b, int *c);
  48. static void clrbit (int b, int *c);
  49. static void copyset (const _charset src, _charset dst);
  50. static void zeroset (int *s);
  51. static void notset (int *s);
  52. static int equal (const _charset s1, const _charset s2);
  53. static int charset_index (const _charset s);
  54. static void atom (void);
  55. static void closure (void);
  56. static void branch (void);
  57. static void regexp (void);
  58. static void build_state (int s, struct regexp * r);
  59. static void build_state_zero (struct regexp * r);
  60. static char *icatalloc (char *old, char *new);
  61. static char *icpyalloc (char *string);
  62. static char *istrstr (char *lookin, char *lookfor);
  63. static void ifree (char *cp);
  64. static void freelist (char **cpp);
  65. static char **enlist (char **cpp, char *new, int len);
  66. static char **comsubs (char *left, char *right);
  67. static char **addlists (char **old, char **new);
  68. static char **inboth (char **left, char **right);
  69. static void regmust (struct regexp * r);
  70. static void copy (_position_set const * src, _position_set * dst);
  71. static void insert (_position p, _position_set * s);
  72. static void merge (_position_set * s1, _position_set * s2, _position_set * m);
  73. static void delete (_position p, _position_set * s);
  74. static int state_index (struct regexp * r, _position_set * s,
  75.             int newline, int letter);
  76. static void epsclosure (_position_set * s, struct regexp * r);
  77. static void addtok (_token t);
  78. static _token lex (void);
  79. #endif /* MSDOS */
  80. #else /* not __STDC__ */
  81. typedef char *ptr_t;
  82. #endif /* not __STDC__ */
  83.  
  84. static void    regmust();
  85.  
  86. static ptr_t
  87. xcalloc(n, s)
  88.      int n;
  89.      size_t s;
  90. {
  91.   ptr_t r = calloc(n, s);
  92.  
  93.   if (r)
  94.     return r;
  95.   else
  96.     regerror("Memory exhausted");
  97. }
  98.  
  99. static ptr_t
  100. xmalloc(n)
  101.      size_t n;
  102. {
  103.   ptr_t r = malloc(n);
  104.  
  105.   assert(n != 0);
  106.   if (r)
  107.     return r;
  108.   else
  109.     regerror("Memory exhausted");
  110. }
  111.  
  112. static ptr_t
  113. xrealloc(p, n)
  114.      ptr_t p;
  115.      size_t n;
  116. {
  117.   ptr_t r = realloc(p, n);
  118.  
  119.   assert(n != 0);
  120.   if (r)
  121.     return r;
  122.   else
  123.     regerror("Memory exhausted");
  124. }
  125.  
  126. #define CALLOC(p, t, n) ((p) = (t *) xcalloc((n), sizeof (t)))
  127. #define MALLOC(p, t, n) ((p) = (t *) xmalloc((n) * sizeof (t)))
  128. #define REALLOC(p, t, n) ((p) = (t *) xrealloc((ptr_t) (p), (n) * sizeof (t)))
  129.  
  130. /* Reallocate an array of type t if nalloc is too small for index. */
  131. #define REALLOC_IF_NECESSARY(p, t, nalloc, index) \
  132.   if ((index) >= (nalloc))              \
  133.     {                          \
  134.       while ((index) >= (nalloc))          \
  135.     (nalloc) *= 2;                  \
  136.       REALLOC(p, t, nalloc);              \
  137.     }
  138.  
  139. /* Stuff pertaining to charsets. */
  140.  
  141. static
  142. tstbit(b, c)
  143.      int b;
  144.      _charset c;
  145. {
  146.   return c[b / INTBITS] & 1 << b % INTBITS;
  147. }
  148.  
  149. static void
  150. setbit(b, c)
  151.      int b;
  152.      _charset c;
  153. {
  154.   c[b / INTBITS] |= 1 << b % INTBITS;
  155. }
  156.  
  157. static void
  158. clrbit(b, c)
  159.      int b;
  160.      _charset c;
  161. {
  162.   c[b / INTBITS] &= ~(1 << b % INTBITS);
  163. }
  164.  
  165. static void
  166. copyset(src, dst)
  167.      const _charset src;
  168.      _charset dst;
  169. {
  170.   int i;
  171.  
  172.   for (i = 0; i < _CHARSET_INTS; ++i)
  173.     dst[i] = src[i];
  174. }
  175.  
  176. static void
  177. zeroset(s)
  178.      _charset s;
  179. {
  180.   int i;
  181.  
  182.   for (i = 0; i < _CHARSET_INTS; ++i)
  183.     s[i] = 0;
  184. }
  185.  
  186. static void
  187. notset(s)
  188.      _charset s;
  189. {
  190.   int i;
  191.  
  192.   for (i = 0; i < _CHARSET_INTS; ++i)
  193.     s[i] = ~s[i];
  194. }
  195.  
  196. static
  197. equal(s1, s2)
  198.      const _charset s1;
  199.      const _charset s2;
  200. {
  201.   int i;
  202.  
  203.   for (i = 0; i < _CHARSET_INTS; ++i)
  204.     if (s1[i] != s2[i])
  205.       return 0;
  206.   return 1;
  207. }
  208.  
  209. /* A pointer to the current regexp is kept here during parsing. */
  210. static struct regexp *reg;
  211.  
  212. /* Find the index of charset s in reg->charsets, or allocate a new charset. */
  213. static
  214. charset_index(s)
  215.      const _charset s;
  216. {
  217.   int i;
  218.  
  219.   for (i = 0; i < reg->cindex; ++i)
  220.     if (equal(s, reg->charsets[i]))
  221.       return i;
  222.   REALLOC_IF_NECESSARY(reg->charsets, _charset, reg->calloc, reg->cindex);
  223.   ++reg->cindex;
  224.   copyset(s, reg->charsets[i]);
  225.   return i;
  226. }
  227.  
  228. /* Syntax bits controlling the behavior of the lexical analyzer. */
  229. static LONG syntax_bits;
  230. static int syntax_bits_set;
  231.  
  232. /* Flag for case-folding letters into sets. */
  233. static case_fold;
  234.  
  235. /* Entry point to set syntax options. */
  236. void
  237. regsyntax(bits, fold)
  238.      LONG bits;
  239.      int fold;
  240. {
  241.   syntax_bits_set = 1;
  242.   syntax_bits = bits;
  243.   case_fold = fold;
  244. }
  245.  
  246. /* Lexical analyzer. */
  247. static const char *lexstart;    /* Pointer to beginning of input string. */
  248. static const char *lexptr;    /* Pointer to next input character. */
  249. static lexleft;            /* Number of characters remaining. */
  250. static caret_allowed;        /* True if backward context allows ^
  251.                    (meaningful only if RE_CONTEXT_INDEP_OPS
  252.                    is turned off). */
  253. static closure_allowed;        /* True if backward context allows closures
  254.                    (meaningful only if RE_CONTEXT_INDEP_OPS
  255.                    is turned off). */
  256.  
  257. /* Note that characters become unsigned here. */
  258. #define FETCH(c, eoferr)             \
  259.   {                         \
  260.     if (! lexleft)                 \
  261.       if (eoferr)                 \
  262.     regerror(eoferr);            \
  263.       else                     \
  264.     return _END;                 \
  265.     (c) = (unsigned char) *lexptr++;  \
  266.     --lexleft;                     \
  267.   }
  268.  
  269. static _token
  270. lex()
  271. {
  272.   _token c, c2;
  273.   int invert;
  274.   _charset cset;
  275.  
  276.   FETCH(c, (char *) 0);
  277.   switch (c)
  278.     {
  279.     case '^':
  280.       if (! (syntax_bits & RE_CONTEXT_INDEP_OPS)
  281.       && (!caret_allowed ||
  282.           (syntax_bits & RE_TIGHT_VBAR) && lexptr - 1 != lexstart))
  283.     goto normal_char;
  284.       caret_allowed = 0;
  285.       return syntax_bits & RE_TIGHT_VBAR ? _ALLBEGLINE : _BEGLINE;
  286.  
  287.     case '$':
  288.       if (syntax_bits & RE_CONTEXT_INDEP_OPS || !lexleft
  289.       || (! (syntax_bits & RE_TIGHT_VBAR)
  290.           && ((syntax_bits & RE_NO_BK_PARENS
  291.            ? lexleft > 0 && *lexptr == ')'
  292.            : lexleft > 1 && *lexptr == '\\' && lexptr[1] == ')')
  293.           || (syntax_bits & RE_NO_BK_VBAR
  294.               ? lexleft > 0 && *lexptr == '|'
  295.               : lexleft > 1 && *lexptr == '\\' && lexptr[1] == '|'))))
  296.     return syntax_bits & RE_TIGHT_VBAR ? _ALLENDLINE : _ENDLINE;
  297.       goto normal_char;
  298.  
  299.     case '\\':
  300.       FETCH(c, "Unfinished \\ quote");
  301.       switch (c)
  302.     {
  303.     case '1':
  304.     case '2':
  305.     case '3':
  306.     case '4':
  307.     case '5':
  308.     case '6':
  309.     case '7':
  310.     case '8':
  311.     case '9':
  312.       caret_allowed = 0;
  313.       closure_allowed = 1;
  314.       return _BACKREF;
  315.  
  316.     case '<':
  317.       caret_allowed = 0;
  318.       return _BEGWORD;
  319.  
  320.     case '>':
  321.       caret_allowed = 0;
  322.       return _ENDWORD;
  323.  
  324.     case 'b':
  325.       caret_allowed = 0;
  326.       return _LIMWORD;
  327.  
  328.     case 'B':
  329.       caret_allowed = 0;
  330.       return _NOTLIMWORD;
  331.  
  332.     case 'w':
  333.     case 'W':
  334.       zeroset(cset);
  335.       for (c2 = 0; c2 < _NOTCHAR; ++c2)
  336.         if (ISALNUM(c2))
  337.           setbit(c2, cset);
  338.       if (c == 'W')
  339.         notset(cset);
  340.       caret_allowed = 0;
  341.       closure_allowed = 1;
  342.       return _SET + charset_index(cset);
  343.  
  344.     case '?':
  345.       if (syntax_bits & RE_BK_PLUS_QM)
  346.         goto qmark;
  347.       goto normal_char;
  348.  
  349.     case '+':
  350.       if (syntax_bits & RE_BK_PLUS_QM)
  351.         goto plus;
  352.       goto normal_char;
  353.  
  354.     case '|':
  355.       if (! (syntax_bits & RE_NO_BK_VBAR))
  356.         goto or;
  357.       goto normal_char;
  358.  
  359.     case '(':
  360.       if (! (syntax_bits & RE_NO_BK_PARENS))
  361.         goto lparen;
  362.       goto normal_char;
  363.  
  364.     case ')':
  365.       if (! (syntax_bits & RE_NO_BK_PARENS))
  366.         goto rparen;
  367.       goto normal_char;
  368.  
  369.     default:
  370.       goto normal_char;
  371.     }
  372.  
  373.     case '?':
  374.       if (syntax_bits & RE_BK_PLUS_QM)
  375.     goto normal_char;
  376.     qmark:
  377.       if (! (syntax_bits & RE_CONTEXT_INDEP_OPS) && !closure_allowed)
  378.     goto normal_char;
  379.       return _QMARK;
  380.  
  381.     case '*':
  382.       if (! (syntax_bits & RE_CONTEXT_INDEP_OPS) && !closure_allowed)
  383.     goto normal_char;
  384.       return _STAR;
  385.  
  386.     case '+':
  387.       if (syntax_bits & RE_BK_PLUS_QM)
  388.     goto normal_char;
  389.     plus:
  390.       if (! (syntax_bits & RE_CONTEXT_INDEP_OPS) && !closure_allowed)
  391.     goto normal_char;
  392.       return _PLUS;
  393.  
  394.     case '|':
  395.       if (! (syntax_bits & RE_NO_BK_VBAR))
  396.     goto normal_char;
  397.     or:
  398.       caret_allowed = 1;
  399.       closure_allowed = 0;
  400.       return _OR;
  401.  
  402.     case '\n':
  403.       if (! (syntax_bits & RE_NEWLINE_OR))
  404.     goto normal_char;
  405.       goto or;
  406.  
  407.     case '(':
  408.       if (! (syntax_bits & RE_NO_BK_PARENS))
  409.     goto normal_char;
  410.     lparen:
  411.       caret_allowed = 1;
  412.       closure_allowed = 0;
  413.       return _LPAREN;
  414.  
  415.     case ')':
  416.       if (! (syntax_bits & RE_NO_BK_PARENS))
  417.     goto normal_char;
  418.     rparen:
  419.       caret_allowed = 0;
  420.       closure_allowed = 1;
  421.       return _RPAREN;
  422.  
  423.     case '.':
  424.       zeroset(cset);
  425.       notset(cset);
  426.       clrbit('\n', cset);
  427.       caret_allowed = 0;
  428.       closure_allowed = 1;
  429.       return _SET + charset_index(cset);
  430.  
  431.     case '[':
  432.       zeroset(cset);
  433.       FETCH(c, "Unbalanced [");
  434.       if (c == '^')
  435.     {
  436.       FETCH(c, "Unbalanced [");
  437.       invert = 1;
  438.     }
  439.       else
  440.     invert = 0;
  441.       do
  442.     {
  443.       FETCH(c2, "Unbalanced [");
  444.       if (c2 == '-')
  445.         {
  446.           FETCH(c2, "Unbalanced [");
  447.           while (c <= c2)
  448.           setbit(c++, cset);
  449.           FETCH(c, "Unbalanced [");
  450.         }
  451.       else
  452.         {
  453.           setbit(c, cset);
  454.           c = c2;
  455.         }
  456.     }
  457.       while (c != ']');
  458.       if (invert)
  459.     notset(cset);
  460.       caret_allowed = 0;
  461.       closure_allowed = 1;
  462.       return _SET + charset_index(cset);
  463.  
  464.     default:
  465.     normal_char:
  466.       caret_allowed = 0;
  467.       closure_allowed = 1;
  468.       if (case_fold && ISALPHA(c))
  469.     {
  470.       zeroset(cset);
  471.       if (isupper(c))
  472.         c = tolower(c);
  473.       setbit(c, cset);
  474.       setbit(toupper(c), cset);
  475.       return _SET + charset_index(cset);
  476.     }
  477.       return c;
  478.     }
  479. }
  480.  
  481. /* Recursive descent parser for regular expressions. */
  482.  
  483. static _token tok;        /* Lookahead token. */
  484. static depth;            /* Current depth of a hypothetical stack
  485.                    holding deferred productions.  This is
  486.                    used to determine the depth that will be
  487.                    required of the real stack later on in
  488.                    reganalyze(). */
  489.  
  490. /* Add the given token to the parse tree, maintaining the depth count and
  491.    updating the maximum depth if necessary. */
  492. static void
  493. addtok(t)
  494.      _token t;
  495. {
  496.   REALLOC_IF_NECESSARY(reg->tokens, _token, reg->talloc, reg->tindex);
  497.   reg->tokens[reg->tindex++] = t;
  498.  
  499.   switch (t)
  500.     {
  501.     case _QMARK:
  502.     case _STAR:
  503.     case _PLUS:
  504.       break;
  505.  
  506.     case _CAT:
  507.     case _OR:
  508.       --depth;
  509.       break;
  510.  
  511.     default:
  512.       ++reg->nleaves;
  513.     case _EMPTY:
  514.       ++depth;
  515.       break;
  516.     }
  517.   if (depth > reg->depth)
  518.     reg->depth = depth;
  519. }
  520.  
  521. /* The grammar understood by the parser is as follows.
  522.  
  523.    start:
  524.      regexp
  525.      _ALLBEGLINE regexp
  526.      regexp _ALLENDLINE
  527.      _ALLBEGLINE regexp _ALLENDLINE
  528.  
  529.    regexp:
  530.      regexp _OR branch
  531.      branch
  532.  
  533.    branch:
  534.      branch closure
  535.      closure
  536.  
  537.    closure:
  538.      closure _QMARK
  539.      closure _STAR
  540.      closure _PLUS
  541.      atom
  542.  
  543.    atom:
  544.      <normal character>
  545.      _SET
  546.      _BACKREF
  547.      _BEGLINE
  548.      _ENDLINE
  549.      _BEGWORD
  550.      _ENDWORD
  551.      _LIMWORD
  552.      _NOTLIMWORD
  553.      <empty>
  554.  
  555.    The parser builds a parse tree in postfix form in an array of tokens. */
  556.  
  557. #ifdef __STDC__
  558. static void regexp(void);
  559. #else
  560. static void regexp();
  561. #endif
  562.  
  563. static void
  564. atom()
  565. {
  566.   if (tok >= 0 && tok < _NOTCHAR || tok >= _SET || tok == _BACKREF
  567.       || tok == _BEGLINE || tok == _ENDLINE || tok == _BEGWORD
  568.       || tok == _ENDWORD || tok == _LIMWORD || tok == _NOTLIMWORD)
  569.     {
  570.       addtok(tok);
  571.       tok = lex();
  572.     }
  573.   else if (tok == _LPAREN)
  574.     {
  575.       tok = lex();
  576.       regexp();
  577.       if (tok != _RPAREN)
  578.     regerror("Unbalanced (");
  579.       tok = lex();
  580.     }
  581.   else
  582.     addtok(_EMPTY);
  583. }
  584.  
  585. static void
  586. closure()
  587. {
  588.   atom();
  589.   while (tok == _QMARK || tok == _STAR || tok == _PLUS)
  590.     {
  591.       addtok(tok);
  592.       tok = lex();
  593.     }
  594. }
  595.  
  596. static void
  597. branch()
  598. {
  599.   closure();
  600.   while (tok != _RPAREN && tok != _OR && tok != _ALLENDLINE && tok >= 0)
  601.     {
  602.       closure();
  603.       addtok(_CAT);
  604.     }
  605. }
  606.  
  607. static void
  608. regexp()
  609. {
  610.   branch();
  611.   while (tok == _OR)
  612.     {
  613.       tok = lex();
  614.       branch();
  615.       addtok(_OR);
  616.     }
  617. }
  618.  
  619. /* Main entry point for the parser.  S is a string to be parsed, len is the
  620.    length of the string, so s can include NUL characters.  R is a pointer to
  621.    the struct regexp to parse into. */
  622. void
  623. regparse(s, len, r)
  624.      const char *s;
  625.      size_t len;
  626.      struct regexp *r;
  627. {
  628.   reg = r;
  629.   lexstart = lexptr = s;
  630.   lexleft = len;
  631.   caret_allowed = 1;
  632.   closure_allowed = 0;
  633.  
  634.   if (! syntax_bits_set)
  635.     regerror("No syntax specified");
  636.  
  637.   tok = lex();
  638.   depth = r->depth;
  639.  
  640.   if (tok == _ALLBEGLINE)
  641.     {
  642.       addtok(_BEGLINE);
  643.       tok = lex();
  644.       regexp();
  645.       addtok(_CAT);
  646.     }
  647.   else
  648.     regexp();
  649.  
  650.   if (tok == _ALLENDLINE)
  651.     {
  652.       addtok(_ENDLINE);
  653.       addtok(_CAT);
  654.       tok = lex();
  655.     }
  656.  
  657.   if (tok != _END)
  658.     regerror("Unbalanced )");
  659.  
  660.   addtok(_END - r->nregexps);
  661.   addtok(_CAT);
  662.  
  663.   if (r->nregexps)
  664.     addtok(_OR);
  665.  
  666.   ++r->nregexps;
  667. }
  668.  
  669. /* Some primitives for operating on sets of positions. */
  670.  
  671. /* Copy one set to another; the destination must be large enough. */
  672. static void
  673. copy(src, dst)
  674.      const _position_set *src;
  675.      _position_set *dst;
  676. {
  677.   int i;
  678.  
  679.   for (i = 0; i < src->nelem; ++i)
  680.     dst->elems[i] = src->elems[i];
  681.   dst->nelem = src->nelem;
  682. }
  683.  
  684. /* Insert a position in a set.  Position sets are maintained in sorted
  685.    order according to index.  If position already exists in the set with
  686.    the same index then their constraints are logically or'd together.
  687.    S->elems must point to an array large enough to hold the resulting set. */
  688. static void
  689. insert(p, s)
  690.      _position p;
  691.      _position_set *s;
  692. {
  693.   int i;
  694.   _position t1, t2;
  695.  
  696.   for (i = 0; i < s->nelem && p.index < s->elems[i].index; ++i)
  697.     ;
  698.   if (i < s->nelem && p.index == s->elems[i].index)
  699.     s->elems[i].constraint |= p.constraint;
  700.   else
  701.     {
  702.       t1 = p;
  703.       ++s->nelem;
  704.       while (i < s->nelem)
  705.     {
  706.       t2 = s->elems[i];
  707.       s->elems[i++] = t1;
  708.       t1 = t2;
  709.     }
  710.     }
  711. }
  712.  
  713. /* Merge two sets of positions into a third.  The result is exactly as if
  714.    the positions of both sets were inserted into an initially empty set. */
  715. static void
  716. merge(s1, s2, m)
  717.      _position_set *s1;
  718.      _position_set *s2;
  719.      _position_set *m;
  720. {
  721.   int i = 0, j = 0;
  722.  
  723.   m->nelem = 0;
  724.   while (i < s1->nelem && j < s2->nelem)
  725.     if (s1->elems[i].index > s2->elems[j].index)
  726.       m->elems[m->nelem++] = s1->elems[i++];
  727.     else if (s1->elems[i].index < s2->elems[j].index)
  728.       m->elems[m->nelem++] = s2->elems[j++];
  729.     else
  730.       {
  731.     m->elems[m->nelem] = s1->elems[i++];
  732.     m->elems[m->nelem++].constraint |= s2->elems[j++].constraint;
  733.       }
  734.   while (i < s1->nelem)
  735.     m->elems[m->nelem++] = s1->elems[i++];
  736.   while (j < s2->nelem)
  737.     m->elems[m->nelem++] = s2->elems[j++];
  738. }
  739.  
  740. /* Delete a position from a set. */
  741. static void
  742. delete(p, s)
  743.      _position p;
  744.      _position_set *s;
  745. {
  746.   int i;
  747.  
  748.   for (i = 0; i < s->nelem; ++i)
  749.     if (p.index == s->elems[i].index)
  750.       break;
  751.   if (i < s->nelem)
  752.     for (--s->nelem; i < s->nelem; ++i)
  753.       s->elems[i] = s->elems[i + 1];
  754. }
  755.  
  756. /* Find the index of the state corresponding to the given position set with
  757.    the given preceding context, or create a new state if there is no such
  758.    state.  Newline and letter tell whether we got here on a newline or
  759.    letter, respectively. */
  760. static
  761. state_index(r, s, newline, letter)
  762.      struct regexp *r;
  763.      _position_set *s;
  764.      int newline;
  765.      int letter;
  766. {
  767.   int hash = 0;
  768.   int constraint;
  769.   int i, j;
  770.  
  771.   newline = newline ? 1 : 0;
  772.   letter = letter ? 1 : 0;
  773.  
  774.   for (i = 0; i < s->nelem; ++i)
  775.     hash ^= s->elems[i].index + s->elems[i].constraint;
  776.  
  777.   /* Try to find a state that exactly matches the proposed one. */
  778.   for (i = 0; i < r->sindex; ++i)
  779.     {
  780.       if (hash != r->states[i].hash || s->nelem != r->states[i].elems.nelem
  781.       || newline != r->states[i].newline || letter != r->states[i].letter)
  782.     continue;
  783.       for (j = 0; j < s->nelem; ++j)
  784.     if (s->elems[j].constraint
  785.         != r->states[i].elems.elems[j].constraint
  786.         || s->elems[j].index != r->states[i].elems.elems[j].index)
  787.       break;
  788.       if (j == s->nelem)
  789.     return i;
  790.     }
  791.  
  792.   /* We'll have to create a new state. */
  793.   REALLOC_IF_NECESSARY(r->states, _dfa_state, r->salloc, r->sindex);
  794.   r->states[i].hash = hash;
  795.   MALLOC(r->states[i].elems.elems, _position, s->nelem);
  796.   copy(s, &r->states[i].elems);
  797.   r->states[i].newline = newline;
  798.   r->states[i].letter = letter;
  799.   r->states[i].backref = 0;
  800.   r->states[i].constraint = 0;
  801.   r->states[i].first_end = 0;
  802.   for (j = 0; j < s->nelem; ++j)
  803.     if (r->tokens[s->elems[j].index] < 0)
  804.       {
  805.     constraint = s->elems[j].constraint;
  806.     if (_SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 0)
  807.         || _SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 1)
  808.         || _SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 0)
  809.         || _SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 1))
  810.       r->states[i].constraint |= constraint;
  811.     if (! r->states[i].first_end)
  812.       r->states[i].first_end = r->tokens[s->elems[j].index];
  813.       }
  814.     else if (r->tokens[s->elems[j].index] == _BACKREF)
  815.       {
  816.     r->states[i].constraint = _NO_CONSTRAINT;
  817.     r->states[i].backref = 1;
  818.       }
  819.  
  820.   ++r->sindex;
  821.  
  822.   return i;
  823. }
  824.  
  825. /* Find the epsilon closure of a set of positions.  If any position of the set
  826.    contains a symbol that matches the empty string in some context, replace
  827.    that position with the elements of its follow labeled with an appropriate
  828.    constraint.  Repeat exhaustively until no funny positions are left.
  829.    S->elems must be large enough to hold the result. */
  830. #ifdef MSDOS
  831. void
  832. #endif
  833. epsclosure(s, r)
  834.      _position_set *s;
  835.      struct regexp *r;
  836. {
  837.   int i, j;
  838.   int *visited;
  839.   _position p, old;
  840.  
  841.   MALLOC(visited, int, r->tindex);
  842.   for (i = 0; i < r->tindex; ++i)
  843.     visited[i] = 0;
  844.  
  845.   for (i = 0; i < s->nelem; ++i)
  846.     if (r->tokens[s->elems[i].index] >= _NOTCHAR
  847.     && r->tokens[s->elems[i].index] != _BACKREF
  848.     && r->tokens[s->elems[i].index] < _SET)
  849.       {
  850.     old = s->elems[i];
  851.     p.constraint = old.constraint;
  852.     delete(s->elems[i], s);
  853.     if (visited[old.index])
  854.       {
  855.         --i;
  856.         continue;
  857.       }
  858.     visited[old.index] = 1;
  859.     switch (r->tokens[old.index])
  860.       {
  861.       case _BEGLINE:
  862.         p.constraint &= _BEGLINE_CONSTRAINT;
  863.         break;
  864.       case _ENDLINE:
  865.         p.constraint &= _ENDLINE_CONSTRAINT;
  866.         break;
  867.       case _BEGWORD:
  868.         p.constraint &= _BEGWORD_CONSTRAINT;
  869.         break;
  870.       case _ENDWORD:
  871.         p.constraint &= _ENDWORD_CONSTRAINT;
  872.         break;
  873.       case _LIMWORD:
  874.         p.constraint &= _ENDWORD_CONSTRAINT;
  875.         break;
  876.       case _NOTLIMWORD:
  877.         p.constraint &= _NOTLIMWORD_CONSTRAINT;
  878.         break;
  879.       }
  880.     for (j = 0; j < r->follows[old.index].nelem; ++j)
  881.       {
  882.         p.index = r->follows[old.index].elems[j].index;
  883.         insert(p, s);
  884.       }
  885.     /* Force rescan to start at the beginning. */
  886.     i = -1;
  887.       }
  888.  
  889.   free(visited);
  890. }
  891.  
  892. /* Perform bottom-up analysis on the parse tree, computing various functions.
  893.    Note that at this point, we're pretending constructs like \< are real
  894.    characters rather than constraints on what can follow them.
  895.  
  896.    Nullable:  A node is nullable if it is at the root of a regexp that can
  897.    match the empty string.
  898.    *  _EMPTY leaves are nullable.
  899.    * No other leaf is nullable.
  900.    * A _QMARK or _STAR node is nullable.
  901.    * A _PLUS node is nullable if its argument is nullable.
  902.    * A _CAT node is nullable if both its arguments are nullable.
  903.    * An _OR node is nullable if either argument is nullable.
  904.  
  905.    Firstpos:  The firstpos of a node is the set of positions (nonempty leaves)
  906.    that could correspond to the first character of a string matching the
  907.    regexp rooted at the given node.
  908.    * _EMPTY leaves have empty firstpos.
  909.    * The firstpos of a nonempty leaf is that leaf itself.
  910.    * The firstpos of a _QMARK, _STAR, or _PLUS node is the firstpos of its
  911.      argument.
  912.    * The firstpos of a _CAT node is the firstpos of the left argument, union
  913.      the firstpos of the right if the left argument is nullable.
  914.    * The firstpos of an _OR node is the union of firstpos of each argument.
  915.  
  916.    Lastpos:  The lastpos of a node is the set of positions that could
  917.    correspond to the last character of a string matching the regexp at
  918.    the given node.
  919.    * _EMPTY leaves have empty lastpos.
  920.    * The lastpos of a nonempty leaf is that leaf itself.
  921.    * The lastpos of a _QMARK, _STAR, or _PLUS node is the lastpos of its
  922.      argument.
  923.    * The lastpos of a _CAT node is the lastpos of its right argument, union
  924.      the lastpos of the left if the right argument is nullable.
  925.    * The lastpos of an _OR node is the union of the lastpos of each argument.
  926.  
  927.    Follow:  The follow of a position is the set of positions that could
  928.    correspond to the character following a character matching the node in
  929.    a string matching the regexp.  At this point we consider special symbols
  930.    that match the empty string in some context to be just normal characters.
  931.    Later, if we find that a special symbol is in a follow set, we will
  932.    replace it with the elements of its follow, labeled with an appropriate
  933.    constraint.
  934.    * Every node in the firstpos of the argument of a _STAR or _PLUS node is in
  935.      the follow of every node in the lastpos.
  936.    * Every node in the firstpos of the second argument of a _CAT node is in
  937.      the follow of every node in the lastpos of the first argument.
  938.  
  939.    Because of the postfix representation of the parse tree, the depth-first
  940.    analysis is conveniently done by a linear scan with the aid of a stack.
  941.    Sets are stored as arrays of the elements, obeying a stack-like allocation
  942.    scheme; the number of elements in each set deeper in the stack can be
  943.    used to determine the address of a particular set's array. */
  944. void
  945. reganalyze(r, searchflag)
  946.      struct regexp *r;
  947.      int searchflag;
  948. {
  949.   int *nullable;        /* Nullable stack. */
  950.   int *nfirstpos;        /* Element count stack for firstpos sets. */
  951.   _position *firstpos;        /* Array where firstpos elements are stored. */
  952.   int *nlastpos;        /* Element count stack for lastpos sets. */
  953.   _position *lastpos;        /* Array where lastpos elements are stored. */
  954.   int *nalloc;            /* Sizes of arrays allocated to follow sets. */
  955.   _position_set tmp;        /* Temporary set for merging sets. */
  956.   _position_set merged;        /* Result of merging sets. */
  957.   int wants_newline;        /* True if some position wants newline info. */
  958.   int *o_nullable;
  959.   int *o_nfirst, *o_nlast;
  960.   _position *o_firstpos, *o_lastpos;
  961.   int i, j;
  962.   _position *pos;
  963.  
  964.   r->searchflag = searchflag;
  965.  
  966.   MALLOC(nullable, int, r->depth);
  967.   o_nullable = nullable;
  968.   MALLOC(nfirstpos, int, r->depth);
  969.   o_nfirst = nfirstpos;
  970.   MALLOC(firstpos, _position, r->nleaves);
  971.   o_firstpos = firstpos, firstpos += r->nleaves;
  972.   MALLOC(nlastpos, int, r->depth);
  973.   o_nlast = nlastpos;
  974.   MALLOC(lastpos, _position, r->nleaves);
  975.   o_lastpos = lastpos, lastpos += r->nleaves;
  976.   MALLOC(nalloc, int, r->tindex);
  977.   for (i = 0; i < r->tindex; ++i)
  978.     nalloc[i] = 0;
  979.   MALLOC(merged.elems, _position, r->nleaves);
  980.  
  981.   CALLOC(r->follows, _position_set, r->tindex);
  982.  
  983.   for (i = 0; i < r->tindex; ++i)
  984.     switch (r->tokens[i])
  985.       {
  986.       case _EMPTY:
  987.     /* The empty set is nullable. */
  988.     *nullable++ = 1;
  989.  
  990.     /* The firstpos and lastpos of the empty leaf are both empty. */
  991.     *nfirstpos++ = *nlastpos++ = 0;
  992.     break;
  993.  
  994.       case _STAR:
  995.       case _PLUS:
  996.     /* Every element in the firstpos of the argument is in the follow
  997.        of every element in the lastpos. */
  998.     tmp.nelem = nfirstpos[-1];
  999.     tmp.elems = firstpos;
  1000.     pos = lastpos;
  1001.     for (j = 0; j < nlastpos[-1]; ++j)
  1002.       {
  1003.         merge(&tmp, &r->follows[pos[j].index], &merged);
  1004.         REALLOC_IF_NECESSARY(r->follows[pos[j].index].elems, _position,
  1005.                  nalloc[pos[j].index], merged.nelem - 1);
  1006.         copy(&merged, &r->follows[pos[j].index]);
  1007.       }
  1008.  
  1009.       case _QMARK:
  1010.     /* A _QMARK or _STAR node is automatically nullable. */
  1011.     if (r->tokens[i] != _PLUS)
  1012.       nullable[-1] = 1;
  1013.     break;
  1014.  
  1015.       case _CAT:
  1016.     /* Every element in the firstpos of the second argument is in the
  1017.        follow of every element in the lastpos of the first argument. */
  1018.     tmp.nelem = nfirstpos[-1];
  1019.     tmp.elems = firstpos;
  1020.     pos = lastpos + nlastpos[-1];
  1021.     for (j = 0; j < nlastpos[-2]; ++j)
  1022.       {
  1023.         merge(&tmp, &r->follows[pos[j].index], &merged);
  1024.         REALLOC_IF_NECESSARY(r->follows[pos[j].index].elems, _position,
  1025.                  nalloc[pos[j].index], merged.nelem - 1);
  1026.         copy(&merged, &r->follows[pos[j].index]);
  1027.       }
  1028.  
  1029.     /* The firstpos of a _CAT node is the firstpos of the first argument,
  1030.        union that of the second argument if the first is nullable. */
  1031.     if (nullable[-2])
  1032.       nfirstpos[-2] += nfirstpos[-1];
  1033.     else
  1034.       firstpos += nfirstpos[-1];
  1035.     --nfirstpos;
  1036.  
  1037.     /* The lastpos of a _CAT node is the lastpos of the second argument,
  1038.        union that of the first argument if the second is nullable. */
  1039.     if (nullable[-1])
  1040.       nlastpos[-2] += nlastpos[-1];
  1041.     else
  1042.       {
  1043.         pos = lastpos + nlastpos[-2];
  1044.         for (j = nlastpos[-1] - 1; j >= 0; --j)
  1045.           pos[j] = lastpos[j];
  1046.         lastpos += nlastpos[-2];
  1047.         nlastpos[-2] = nlastpos[-1];
  1048.       }
  1049.     --nlastpos;
  1050.  
  1051.     /* A _CAT node is nullable if both arguments are nullable. */
  1052.     nullable[-2] = nullable[-1] && nullable[-2];
  1053.     --nullable;
  1054.     break;
  1055.  
  1056.       case _OR:
  1057.     /* The firstpos is the union of the firstpos of each argument. */
  1058.     nfirstpos[-2] += nfirstpos[-1];
  1059.     --nfirstpos;
  1060.  
  1061.     /* The lastpos is the union of the lastpos of each argument. */
  1062.     nlastpos[-2] += nlastpos[-1];
  1063.     --nlastpos;
  1064.  
  1065.     /* An _OR node is nullable if either argument is nullable. */
  1066.     nullable[-2] = nullable[-1] || nullable[-2];
  1067.     --nullable;
  1068.     break;
  1069.  
  1070.       default:
  1071.     /* Anything else is a nonempty position.  (Note that special
  1072.        constructs like \< are treated as nonempty strings here;
  1073.        an "epsilon closure" effectively makes them nullable later.
  1074.        Backreferences have to get a real position so we can detect
  1075.        transitions on them later.  But they are nullable. */
  1076.     *nullable++ = r->tokens[i] == _BACKREF;
  1077.  
  1078.     /* This position is in its own firstpos and lastpos. */
  1079.     *nfirstpos++ = *nlastpos++ = 1;
  1080.     --firstpos, --lastpos;
  1081.     firstpos->index = lastpos->index = i;
  1082.     firstpos->constraint = lastpos->constraint = _NO_CONSTRAINT;
  1083.  
  1084.     /* Allocate the follow set for this position. */
  1085.     nalloc[i] = 1;
  1086.     MALLOC(r->follows[i].elems, _position, nalloc[i]);
  1087.     break;
  1088.       }
  1089.  
  1090.   /* For each follow set that is the follow set of a real position, replace
  1091.      it with its epsilon closure. */
  1092.   for (i = 0; i < r->tindex; ++i)
  1093.     if (r->tokens[i] < _NOTCHAR || r->tokens[i] == _BACKREF
  1094.     || r->tokens[i] >= _SET)
  1095.       {
  1096.     copy(&r->follows[i], &merged);
  1097.     epsclosure(&merged, r);
  1098.     if (r->follows[i].nelem < merged.nelem)
  1099.       REALLOC(r->follows[i].elems, _position, merged.nelem);
  1100.     copy(&merged, &r->follows[i]);
  1101.       }
  1102.  
  1103.   /* Get the epsilon closure of the firstpos of the regexp.  The result will
  1104.      be the set of positions of state 0. */
  1105.   merged.nelem = 0;
  1106.   for (i = 0; i < nfirstpos[-1]; ++i)
  1107.     insert(firstpos[i], &merged);
  1108.   epsclosure(&merged, r);
  1109.  
  1110.   /* Check if any of the positions of state 0 will want newline context. */
  1111.   wants_newline = 0;
  1112.   for (i = 0; i < merged.nelem; ++i)
  1113.     if (_PREV_NEWLINE_DEPENDENT(merged.elems[i].constraint))
  1114.       wants_newline = 1;
  1115.  
  1116.   /* Build the initial state. */
  1117.   r->salloc = 1;
  1118.   r->sindex = 0;
  1119.   MALLOC(r->states, _dfa_state, r->salloc);
  1120.   state_index(r, &merged, wants_newline, 0);
  1121.  
  1122.   free(o_nullable);
  1123.   free(o_nfirst);
  1124.   free(o_firstpos);
  1125.   free(o_nlast);
  1126.   free(o_lastpos);
  1127.   free(nalloc);
  1128.   free(merged.elems);
  1129. }
  1130.  
  1131. /* Find, for each character, the transition out of state s of r, and store
  1132.    it in the appropriate slot of trans.
  1133.  
  1134.    We divide the positions of s into groups (positions can appear in more
  1135.    than one group).  Each group is labeled with a set of characters that
  1136.    every position in the group matches (taking into account, if necessary,
  1137.    preceding context information of s).  For each group, find the union
  1138.    of the its elements' follows.  This set is the set of positions of the
  1139.    new state.  For each character in the group's label, set the transition
  1140.    on this character to be to a state corresponding to the set's positions,
  1141.    and its associated backward context information, if necessary.
  1142.  
  1143.    If we are building a searching matcher, we include the positions of state
  1144.    0 in every state.
  1145.  
  1146.    The collection of groups is constructed by building an equivalence-class
  1147.    partition of the positions of s.
  1148.  
  1149.    For each position, find the set of characters C that it matches.  Eliminate
  1150.    any characters from C that fail on grounds of backward context.
  1151.  
  1152.    Search through the groups, looking for a group whose label L has nonempty
  1153.    intersection with C.  If L - C is nonempty, create a new group labeled
  1154.    L - C and having the same positions as the current group, and set L to
  1155.    the intersection of L and C.  Insert the position in this group, set
  1156.    C = C - L, and resume scanning.
  1157.  
  1158.    If after comparing with every group there are characters remaining in C,
  1159.    create a new group labeled with the characters of C and insert this
  1160.    position in that group. */
  1161. void
  1162. regstate(s, r, trans)
  1163.      int s;
  1164.      struct regexp *r;
  1165.      int trans[];
  1166. {
  1167.   _position_set grps[_NOTCHAR];    /* As many as will ever be needed. */
  1168.   _charset labels[_NOTCHAR];    /* Labels corresponding to the groups. */
  1169.   int ngrps = 0;        /* Number of groups actually used. */
  1170.   _position pos;        /* Current position being considered. */
  1171.   _charset matches;        /* Set of matching characters. */
  1172.   int matchesf;            /* True if matches is nonempty. */
  1173.   _charset intersect;        /* Intersection with some label set. */
  1174.   int intersectf;        /* True if intersect is nonempty. */
  1175.   _charset leftovers;        /* Stuff in the label that didn't match. */
  1176.   int leftoversf;        /* True if leftovers is nonempty. */
  1177.   static _charset letters;    /* Set of characters considered letters. */
  1178.   static _charset newline;    /* Set of characters that aren't newline. */
  1179.   _position_set follows;    /* Union of the follows of some group. */
  1180.   _position_set tmp;        /* Temporary space for merging sets. */
  1181.   int state;            /* New state. */
  1182.   int wants_newline;        /* New state wants to know newline context. */
  1183.   int state_newline;        /* New state on a newline transition. */
  1184.   int wants_letter;        /* New state wants to know letter context. */
  1185.   int state_letter;        /* New state on a letter transition. */
  1186.   static initialized;        /* Flag for static initialization. */
  1187.   int i, j, k;
  1188.  
  1189.   /* Initialize the set of letters, if necessary. */
  1190.   if (! initialized)
  1191.     {
  1192.       initialized = 1;
  1193.       for (i = 0; i < _NOTCHAR; ++i)
  1194.     if (ISALNUM(i))
  1195.       setbit(i, letters);
  1196.       setbit('\n', newline);
  1197.     }
  1198.  
  1199.   zeroset(matches);
  1200.  
  1201.   for (i = 0; i < r->states[s].elems.nelem; ++i)
  1202.     {
  1203.       pos = r->states[s].elems.elems[i];
  1204.       if (r->tokens[pos.index] >= 0 && r->tokens[pos.index] < _NOTCHAR)
  1205.     setbit(r->tokens[pos.index], matches);
  1206.       else if (r->tokens[pos.index] >= _SET)
  1207.     copyset(r->charsets[r->tokens[pos.index] - _SET], matches);
  1208.       else
  1209.     continue;
  1210.  
  1211.       /* Some characters may need to be climinated from matches because
  1212.      they fail in the current context. */
  1213.       if (pos.constraint != 0xff)
  1214.     {
  1215.       if (! _MATCHES_NEWLINE_CONTEXT(pos.constraint,
  1216.                      r->states[s].newline, 1))
  1217.         clrbit('\n', matches);
  1218.       if (! _MATCHES_NEWLINE_CONTEXT(pos.constraint,
  1219.                      r->states[s].newline, 0))
  1220.         for (j = 0; j < _CHARSET_INTS; ++j)
  1221.           matches[j] &= newline[j];
  1222.       if (! _MATCHES_LETTER_CONTEXT(pos.constraint,
  1223.                     r->states[s].letter, 1))
  1224.         for (j = 0; j < _CHARSET_INTS; ++j)
  1225.           matches[j] &= ~letters[j];
  1226.       if (! _MATCHES_LETTER_CONTEXT(pos.constraint,
  1227.                     r->states[s].letter, 0))
  1228.         for (j = 0; j < _CHARSET_INTS; ++j)
  1229.           matches[j] &= letters[j];
  1230.  
  1231.       /* If there are no characters left, there's no point in going on. */
  1232.       for (j = 0; j < _CHARSET_INTS && !matches[j]; ++j)
  1233.         ;
  1234.       if (j == _CHARSET_INTS)
  1235.         continue;
  1236.     }
  1237.  
  1238.       for (j = 0; j < ngrps; ++j)
  1239.     {
  1240.       /* If matches contains a single character only, and the current
  1241.          group's label doesn't contain that character, go on to the
  1242.          next group. */
  1243.       if (r->tokens[pos.index] >= 0 && r->tokens[pos.index] < _NOTCHAR
  1244.           && !tstbit(r->tokens[pos.index], labels[j]))
  1245.         continue;
  1246.  
  1247.       /* Check if this group's label has a nonempty intersection with
  1248.          matches. */
  1249.       intersectf = 0;
  1250.       for (k = 0; k < _CHARSET_INTS; ++k)
  1251.         (intersect[k] = matches[k] & labels[j][k]) ? intersectf = 1 : 0;
  1252.       if (! intersectf)
  1253.         continue;
  1254.  
  1255.       /* It does; now find the set differences both ways. */
  1256.       leftoversf = matchesf = 0;
  1257.       for (k = 0; k < _CHARSET_INTS; ++k)
  1258.         {
  1259.           /* Even an optimizing compiler can't know this for sure. */
  1260.           int match = matches[k], label = labels[j][k];
  1261.  
  1262.           (leftovers[k] = ~match & label) ? leftoversf = 1 : 0;
  1263.           (matches[k] = match & ~label) ? matchesf = 1 : 0;
  1264.         }
  1265.  
  1266.       /* If there were leftovers, create a new group labeled with them. */
  1267.       if (leftoversf)
  1268.         {
  1269.           copyset(leftovers, labels[ngrps]);
  1270.           copyset(intersect, labels[j]);
  1271.           MALLOC(grps[ngrps].elems, _position, r->nleaves);
  1272.           copy(&grps[j], &grps[ngrps]);
  1273.           ++ngrps;
  1274.         }
  1275.  
  1276.       /* Put the position in the current group.  Note that there is no
  1277.          reason to call insert() here. */
  1278.       grps[j].elems[grps[j].nelem++] = pos;
  1279.  
  1280.       /* If every character matching the current position has been
  1281.          accounted for, we're done. */
  1282.       if (! matchesf)
  1283.         break;
  1284.     }
  1285.  
  1286.       /* If we've passed the last group, and there are still characters
  1287.      unaccounted for, then we'll have to create a new group. */
  1288.       if (j == ngrps)
  1289.     {
  1290.       copyset(matches, labels[ngrps]);
  1291.       zeroset(matches);
  1292.       MALLOC(grps[ngrps].elems, _position, r->nleaves);
  1293.       grps[ngrps].nelem = 1;
  1294.       grps[ngrps].elems[0] = pos;
  1295.       ++ngrps;
  1296.     }
  1297.     }
  1298.  
  1299.   MALLOC(follows.elems, _position, r->nleaves);
  1300.   MALLOC(tmp.elems, _position, r->nleaves);
  1301.  
  1302.   /* If we are a searching matcher, the default transition is to a state
  1303.      containing the positions of state 0, otherwise the default transition
  1304.      is to fail miserably. */
  1305.   if (r->searchflag)
  1306.     {
  1307.       wants_newline = 0;
  1308.       wants_letter = 0;
  1309.       for (i = 0; i < r->states[0].elems.nelem; ++i)
  1310.     {
  1311.       if (_PREV_NEWLINE_DEPENDENT(r->states[0].elems.elems[i].constraint))
  1312.         wants_newline = 1;
  1313.       if (_PREV_LETTER_DEPENDENT(r->states[0].elems.elems[i].constraint))
  1314.         wants_letter = 1;
  1315.     }
  1316.       copy(&r->states[0].elems, &follows);
  1317.       state = state_index(r, &follows, 0, 0);
  1318.       if (wants_newline)
  1319.     state_newline = state_index(r, &follows, 1, 0);
  1320.       else
  1321.     state_newline = state;
  1322.       if (wants_letter)
  1323.     state_letter = state_index(r, &follows, 0, 1);
  1324.       else
  1325.     state_letter = state;
  1326.       for (i = 0; i < _NOTCHAR; ++i)
  1327.     if (i == '\n')
  1328.       trans[i] = state_newline;
  1329.     else if (ISALNUM(i))
  1330.       trans[i] = state_letter;
  1331.     else
  1332.       trans[i] = state;
  1333.     }
  1334.   else
  1335.     for (i = 0; i < _NOTCHAR; ++i)
  1336.       trans[i] = -1;
  1337.  
  1338.   for (i = 0; i < ngrps; ++i)
  1339.     {
  1340.       follows.nelem = 0;
  1341.  
  1342.       /* Find the union of the follows of the positions of the group.
  1343.      This is a hideously inefficient loop.  Fix it someday. */
  1344.       for (j = 0; j < grps[i].nelem; ++j)
  1345.     for (k = 0; k < r->follows[grps[i].elems[j].index].nelem; ++k)
  1346.       insert(r->follows[grps[i].elems[j].index].elems[k], &follows);
  1347.  
  1348.       /* If we are building a searching matcher, throw in the positions
  1349.      of state 0 as well. */
  1350.       if (r->searchflag)
  1351.     for (j = 0; j < r->states[0].elems.nelem; ++j)
  1352.       insert(r->states[0].elems.elems[j], &follows);
  1353.  
  1354.       /* Find out if the new state will want any context information. */
  1355.       wants_newline = 0;
  1356.       if (tstbit('\n', labels[i]))
  1357.     for (j = 0; j < follows.nelem; ++j)
  1358.       if (_PREV_NEWLINE_DEPENDENT(follows.elems[j].constraint))
  1359.         wants_newline = 1;
  1360.  
  1361.       wants_letter = 0;
  1362.       for (j = 0; j < _CHARSET_INTS; ++j)
  1363.     if (labels[i][j] & letters[j])
  1364.       break;
  1365.       if (j < _CHARSET_INTS)
  1366.     for (j = 0; j < follows.nelem; ++j)
  1367.       if (_PREV_LETTER_DEPENDENT(follows.elems[j].constraint))
  1368.         wants_letter = 1;
  1369.  
  1370.       /* Find the state(s) corresponding to the union of the follows. */
  1371.       state = state_index(r, &follows, 0, 0);
  1372.       if (wants_newline)
  1373.     state_newline = state_index(r, &follows, 1, 0);
  1374.       else
  1375.     state_newline = state;
  1376.       if (wants_letter)
  1377.     state_letter = state_index(r, &follows, 0, 1);
  1378.       else
  1379.     state_letter = state;
  1380.  
  1381.       /* Set the transitions for each character in the current label. */
  1382.       for (j = 0; j < _CHARSET_INTS; ++j)
  1383.     for (k = 0; k < INTBITS; ++k)
  1384.       if (labels[i][j] & 1 << k)
  1385.         {
  1386.           int c = j * INTBITS + k;
  1387.  
  1388.           if (c == '\n')
  1389.         trans[c] = state_newline;
  1390.           else if (ISALNUM(c))
  1391.         trans[c] = state_letter;
  1392.           else if (c < _NOTCHAR)
  1393.         trans[c] = state;
  1394.         }
  1395.     }
  1396.  
  1397.   for (i = 0; i < ngrps; ++i)
  1398.     free(grps[i].elems);
  1399.   free(follows.elems);
  1400.   free(tmp.elems);
  1401. }
  1402.  
  1403. /* Some routines for manipulating a compiled regexp's transition tables.
  1404.    Each state may or may not have a transition table; if it does, and it
  1405.    is a non-accepting state, then r->trans[state] points to its table.
  1406.    If it is an accepting state then r->fails[state] points to its table.
  1407.    If it has no table at all, then r->trans[state] is NULL.
  1408.    TODO: Improve this comment, get rid of the unnecessary redundancy. */
  1409.  
  1410. static void
  1411. build_state(s, r)
  1412.      int s;
  1413.      struct regexp *r;
  1414. {
  1415.   int *trans;            /* The new transition table. */
  1416.   int i;
  1417.  
  1418.   /* Set an upper limit on the number of transition tables that will ever
  1419.      exist at once.  1024 is arbitrary.  The idea is that the frequently
  1420.      used transition tables will be quickly rebuilt, whereas the ones that
  1421.      were only needed once or twice will be cleared away. */
  1422.   if (r->trcount >= 1024)
  1423.     {
  1424.       for (i = 0; i < r->tralloc; ++i)
  1425.     if (r->trans[i])
  1426.       {
  1427.         free((ptr_t) r->trans[i]);
  1428.         r->trans[i] = NULL;
  1429.       }
  1430.     else if (r->fails[i])
  1431.       {
  1432.         free((ptr_t) r->fails[i]);
  1433.         r->fails[i] = NULL;
  1434.       }
  1435.       r->trcount = 0;
  1436.     }
  1437.  
  1438.   ++r->trcount;
  1439.  
  1440.   /* Set up the success bits for this state. */
  1441.   r->success[s] = 0;
  1442.   if (ACCEPTS_IN_CONTEXT(r->states[s].newline, 1, r->states[s].letter, 0,
  1443.       s, *r))
  1444.     r->success[s] |= 4;
  1445.   if (ACCEPTS_IN_CONTEXT(r->states[s].newline, 0, r->states[s].letter, 1,
  1446.       s, *r))
  1447.     r->success[s] |= 2;
  1448.   if (ACCEPTS_IN_CONTEXT(r->states[s].newline, 0, r->states[s].letter, 0,
  1449.       s, *r))
  1450.     r->success[s] |= 1;
  1451.  
  1452.   MALLOC(trans, int, _NOTCHAR);
  1453.   regstate(s, r, trans);
  1454.  
  1455.   /* Now go through the new transition table, and make sure that the trans
  1456.      and fail arrays are allocated large enough to hold a pointer for the
  1457.      largest state mentioned in the table. */
  1458.   for (i = 0; i < _NOTCHAR; ++i)
  1459.     if (trans[i] >= r->tralloc)
  1460.       {
  1461.     int oldalloc = r->tralloc;
  1462.  
  1463.     while (trans[i] >= r->tralloc)
  1464.       r->tralloc *= 2;
  1465.     REALLOC(r->realtrans, int *, r->tralloc + 1);
  1466.     r->trans = r->realtrans + 1;
  1467.     REALLOC(r->fails, int *, r->tralloc);
  1468.     REALLOC(r->success, int, r->tralloc);
  1469.     REALLOC(r->newlines, int, r->tralloc);
  1470.     while (oldalloc < r->tralloc)
  1471.       {
  1472.         r->trans[oldalloc] = NULL;
  1473.         r->fails[oldalloc++] = NULL;
  1474.       }
  1475.       }
  1476.  
  1477.   /* Keep the newline transition in a special place so we can use it as
  1478.      a sentinel. */
  1479.   r->newlines[s] = trans['\n'];
  1480.   trans['\n'] = -1;
  1481.  
  1482.   if (ACCEPTING(s, *r))
  1483.     r->fails[s] = trans;
  1484.   else
  1485.     r->trans[s] = trans;
  1486. }
  1487.  
  1488. static void
  1489. build_state_zero(r)
  1490.      struct regexp *r;
  1491. {
  1492.   r->tralloc = 1;
  1493.   r->trcount = 0;
  1494.   CALLOC(r->realtrans, int *, r->tralloc + 1);
  1495.   r->trans = r->realtrans + 1;
  1496.   CALLOC(r->fails, int *, r->tralloc);
  1497.   MALLOC(r->success, int, r->tralloc);
  1498.   MALLOC(r->newlines, int, r->tralloc);
  1499.   build_state(0, r);
  1500. }
  1501.  
  1502. /* Search through a buffer looking for a match to the given struct regexp.
  1503.    Find the first occurrence of a string matching the regexp in the buffer,
  1504.    and the shortest possible version thereof.  Return a pointer to the first
  1505.    character after the match, or NULL if none is found.  Begin points to
  1506.    the beginning of the buffer, and end points to the first character after
  1507.    its end.  We store a newline in *end to act as a sentinel, so end had
  1508.    better point somewhere valid.  Newline is a flag indicating whether to
  1509.    allow newlines to be in the matching string.  If count is non-
  1510.    NULL it points to a place we're supposed to increment every time we
  1511.    see a newline.  Finally, if backref is non-NULL it points to a place
  1512.    where we're supposed to store a 1 if backreferencing happened and the
  1513.    match needs to be verified by a backtracking matcher.  Otherwise
  1514.    we store a 0 in *backref. */
  1515. char *
  1516. regexecute(r, begin, end, newline, count, backref)
  1517.      struct regexp *r;
  1518.      char *begin;
  1519.      char *end;
  1520.      int newline;
  1521.      int *count;
  1522.      int *backref;
  1523. {
  1524.   register s, s1, tmp;        /* Current state. */
  1525.   register unsigned char *p;    /* Current input character. */
  1526.   register **trans, *t;        /* Copy of r->trans so it can be optimized
  1527.                    into a register. */
  1528.   static sbit[_NOTCHAR];    /* Table for anding with r->success. */
  1529.   static sbit_init;
  1530.  
  1531.   if (! sbit_init)
  1532.     {
  1533.       int i;
  1534.  
  1535.       sbit_init = 1;
  1536.       for (i = 0; i < _NOTCHAR; ++i)
  1537.     if (i == '\n')
  1538.       sbit[i] = 4;
  1539.     else if (ISALNUM(i))
  1540.       sbit[i] = 2;
  1541.     else
  1542.       sbit[i] = 1;
  1543.     }
  1544.  
  1545.   if (! r->tralloc)
  1546.     build_state_zero(r);
  1547.  
  1548.   s = 0;
  1549.   p = (unsigned char *) begin;
  1550.   trans = r->trans;
  1551.   *end = '\n';
  1552.  
  1553.   for (;;)
  1554.     {
  1555.       /* The dreaded inner loop. */
  1556.       if (t = trans[s])
  1557.     do
  1558.       {
  1559.         s1 = t[*p++];
  1560.         if (! (t = trans[s1]))
  1561.           goto last_was_s;
  1562.         s = t[*p++];
  1563.       }
  1564.         while (t = trans[s]);
  1565.       goto last_was_s1;
  1566.     last_was_s:
  1567.       tmp = s, s = s1, s1 = tmp;
  1568.     last_was_s1:
  1569.  
  1570.       if (s >= 0 && p <= (unsigned char *) end && r->fails[s])
  1571.     {
  1572.       if (r->success[s] & sbit[*p])
  1573.         {
  1574.           if (backref)
  1575.         if (r->states[s].backref)
  1576.           *backref = 1;
  1577.         else
  1578.           *backref = 0;
  1579.           return (char *) p;
  1580.         }
  1581.  
  1582.       s1 = s;
  1583.       s = r->fails[s][*p++];
  1584.       continue;
  1585.     }
  1586.  
  1587.       /* If the previous character was a newline, count it. */
  1588.       if (count && (char *) p <= end && p[-1] == '\n')
  1589.     ++*count;
  1590.  
  1591.       /* Check if we've run off the end of the buffer. */
  1592.       if ((char *) p >= end)
  1593.     return NULL;
  1594.  
  1595.       if (s >= 0)
  1596.     {
  1597.       build_state(s, r);
  1598.       trans = r->trans;
  1599.       continue;
  1600.     }
  1601.  
  1602.       if (p[-1] == '\n' && newline)
  1603.     {
  1604.       s = r->newlines[s1];
  1605.       continue;
  1606.     }
  1607.  
  1608.       s = 0;
  1609.     }
  1610. }
  1611.  
  1612. /* Initialize the components of a regexp that the other routines don't
  1613.    initialize for themselves. */
  1614. void
  1615. reginit(r)
  1616.      struct regexp *r;
  1617. {
  1618.   r->calloc = 1;
  1619.   MALLOC(r->charsets, _charset, r->calloc);
  1620.   r->cindex = 0;
  1621.  
  1622.   r->talloc = 1;
  1623.   MALLOC(r->tokens, _token, r->talloc);
  1624.   r->tindex = r->depth = r->nleaves = r->nregexps = 0;
  1625.  
  1626.   r->searchflag = 0;
  1627.   r->tralloc = 0;
  1628. }
  1629.  
  1630. /* Parse and analyze a single string of the given length. */
  1631. void
  1632. regcompile(s, len, r, searchflag)
  1633.      const char *s;
  1634.      size_t len;
  1635.      struct regexp *r;
  1636.      int searchflag;
  1637. {
  1638.   if (case_fold)    /* dummy folding in service of regmust() */
  1639.     {
  1640.       char *copy;
  1641.       int i;
  1642.  
  1643.       copy = malloc(len);
  1644.       if (!copy)
  1645.     regerror("out of memory");
  1646.       
  1647.       /* This is a complete kludge and could potentially break
  1648.      \<letter> escapes . . . */
  1649.       case_fold = 0;
  1650.       for (i = 0; i < len; ++i)
  1651.     if (ISUPPER(s[i]))
  1652.       copy[i] = tolower(s[i]);
  1653.     else
  1654.       copy[i] = s[i];
  1655.  
  1656.       reginit(r);
  1657.       r->mustn = 0;
  1658.       r->must[0] = '\0';
  1659.       regparse(copy, len, r);
  1660.       free(copy);
  1661.       regmust(r);
  1662.       reganalyze(r, searchflag);
  1663.       case_fold = 1;
  1664.       reginit(r);
  1665.       regparse(s, len, r);
  1666.       reganalyze(r, searchflag);
  1667.     }
  1668.   else
  1669.     {
  1670.         reginit(r);
  1671.         regparse(s, len, r);
  1672.         regmust(r);
  1673.         reganalyze(r, searchflag);
  1674.     }
  1675. }
  1676.  
  1677. /* Free the storage held by the components of a regexp. */
  1678. void
  1679. regfree(r)
  1680.      struct regexp *r;
  1681. {
  1682.   int i;
  1683.  
  1684.   free((ptr_t) r->charsets);
  1685.   free((ptr_t) r->tokens);
  1686.   for (i = 0; i < r->sindex; ++i)
  1687.     free((ptr_t) r->states[i].elems.elems);
  1688.   free((ptr_t) r->states);
  1689.   for (i = 0; i < r->tindex; ++i)
  1690.     if (r->follows[i].elems)
  1691.       free((ptr_t) r->follows[i].elems);
  1692.   free((ptr_t) r->follows);
  1693.   for (i = 0; i < r->tralloc; ++i)
  1694.     if (r->trans[i])
  1695.       free((ptr_t) r->trans[i]);
  1696.     else if (r->fails[i])
  1697.       free((ptr_t) r->fails[i]);
  1698.   free((ptr_t) r->realtrans);
  1699.   free((ptr_t) r->fails);
  1700.   free((ptr_t) r->newlines);
  1701. }
  1702.  
  1703. /*
  1704. Having found the postfix representation of the regular expression,
  1705. try to find a long sequence of characters that must appear in any line
  1706. containing the r.e.
  1707. Finding a "longest" sequence is beyond the scope here;
  1708. we take an easy way out and hope for the best.
  1709. (Take "(ab|a)b"--please.)
  1710.  
  1711. We do a bottom-up calculation of sequences of characters that must appear
  1712. in matches of r.e.'s represented by trees rooted at the nodes of the postfix
  1713. representation:
  1714.     sequences that must appear at the left of the match ("left")
  1715.     sequences that must appear at the right of the match ("right")
  1716.     lists of sequences that must appear somewhere in the match ("in")
  1717.     sequences that must constitute the match ("is")
  1718. When we get to the root of the tree, we use one of the longest of its
  1719. calculated "in" sequences as our answer.  The sequence we find is returned in
  1720. r->must (where "r" is the single argument passed to "regmust");
  1721. the length of the sequence is returned in r->mustn.
  1722.  
  1723. The sequences calculated for the various types of node (in pseudo ANSI c)
  1724. are shown below.  "p" is the operand of unary operators (and the left-hand
  1725. operand of binary operators); "q" is the right-hand operand of binary operators
  1726. .
  1727. "ZERO" means "a zero-length sequence" below.
  1728.  
  1729. Type    left        right        is        in
  1730. ----    ----        -----        --        --
  1731. char c    # c        # c        # c        # c
  1732.  
  1733. SET    ZERO        ZERO        ZERO        ZERO
  1734.  
  1735. STAR    ZERO        ZERO        ZERO        ZERO
  1736.  
  1737. QMARK    ZERO        ZERO        ZERO        ZERO
  1738.  
  1739. PLUS    p->left        p->right    ZERO        p->in
  1740.  
  1741. CAT    (p->is==ZERO)?    (q->is==ZERO)?    (p->is!=ZERO &&    p->in plus
  1742.     p->left :    q->right :    q->is!=ZERO) ?    q->in plus
  1743.     p->is##q->left    p->right##q->is    p->is##q->is :    p->right##q->left
  1744.                     ZERO
  1745.  
  1746. OR    longest common    longest common    (do p->is and    substrings common to
  1747.     leading        trailing    q->is have same    p->in and q->in
  1748.     (sub)sequence    (sub)sequence    length and    
  1749.     of p->left    of p->right    content) ?    
  1750.     and q->left    and q->right    p->is : NULL    
  1751.  
  1752. If there's anything else we recognize in the tree, all four sequences get set
  1753. to zero-length sequences.  If there's something we don't recognize in the tree,
  1754. we just return a zero-length sequence.
  1755.  
  1756. Break ties in favor of infrequent letters (choosing 'zzz' in preference to
  1757. 'aaa')?
  1758.  
  1759. And. . .is it here or someplace that we might ponder "optimizations" such as
  1760.     egrep 'psi|epsilon'    ->    egrep 'psi'
  1761.     egrep 'pepsi|epsilon'    ->    egrep 'epsi'
  1762.                     (Yes, we now find "epsi" as a "string
  1763.                     that must occur", but we might also
  1764.                     simplify the *entire* r.e. being sought
  1765. )
  1766.     grep '[c]'        ->    grep 'c'
  1767.     grep '(ab|a)b'        ->    grep 'ab'
  1768.     grep 'ab*'        ->    grep 'a'
  1769.     grep 'a*b'        ->    grep 'b'
  1770. There are several issues:
  1771.     Is optimization easy (enough)?
  1772.  
  1773.     Does optimization actually accomplish anything,
  1774.     or is the automaton you get from "psi|epsilon" (for example)
  1775.     the same as the one you get from "psi" (for example)?
  1776.  
  1777.     Are optimizable r.e.'s likely to be used in real-life situations
  1778.     (something like 'ab*' is probably unlikely; something like is
  1779.     'psi|epsilon' is likelier)?
  1780. */
  1781.  
  1782. static char *
  1783. icatalloc(old, new)
  1784. char *    old;
  1785. char *    new;
  1786. {
  1787.     register char *    result;
  1788.     register int    oldsize, newsize;
  1789.  
  1790.     newsize = (new == NULL) ? 0 : strlen(new);
  1791.     if (old == NULL)
  1792.         oldsize = 0;
  1793.     else if (newsize == 0)
  1794.         return old;
  1795.     else    oldsize = strlen(old);
  1796.     if (old == NULL)
  1797.         result = (char *) malloc(newsize + 1);
  1798.     else    result = (char *) realloc((void *) old, oldsize + newsize + 1);
  1799.     if (result != NULL && new != NULL)
  1800.         (void) strcpy(result + oldsize, new);
  1801.     return result;
  1802. }
  1803.  
  1804. static char *
  1805. icpyalloc(string)
  1806. #ifdef MSDOS
  1807.       char *    string;
  1808. #else
  1809. const char *    string;
  1810. #endif
  1811. {
  1812.     return icatalloc((char *) NULL, string);
  1813. }
  1814.  
  1815. static char *
  1816. istrstr(lookin, lookfor)
  1817. char *        lookin;
  1818. register char *    lookfor;
  1819. {
  1820.     register char *    cp;
  1821.     register int    len;
  1822.  
  1823.     len = strlen(lookfor);
  1824.     for (cp = lookin; *cp != '\0'; ++cp)
  1825.         if (strncmp(cp, lookfor, len) == 0)
  1826.             return cp;
  1827.     return NULL;
  1828. }
  1829.  
  1830. static void
  1831. ifree(cp)
  1832. char *    cp;
  1833. {
  1834.     if (cp != NULL)
  1835.         free(cp);
  1836. }
  1837.  
  1838. static void
  1839. freelist(cpp)
  1840. register char **    cpp;
  1841. {
  1842.     register int    i;
  1843.  
  1844.     if (cpp == NULL)
  1845.         return;
  1846.     for (i = 0; cpp[i] != NULL; ++i) {
  1847.         free(cpp[i]);
  1848.         cpp[i] = NULL;
  1849.     }
  1850. }
  1851.  
  1852. static char **
  1853. enlist(cpp, new, len)
  1854. register char **    cpp;
  1855. register char *        new;
  1856. {
  1857.     register int    i, j;
  1858.  
  1859.     if (cpp == NULL)
  1860.         return NULL;
  1861.     if ((new = icpyalloc(new)) == NULL) {
  1862.         freelist(cpp);
  1863.         return NULL;
  1864.     }
  1865.     new[len] = '\0';
  1866.     /*
  1867.     ** Is there already something in the list that's new (or longer)?
  1868.     */
  1869.     for (i = 0; cpp[i] != NULL; ++i)
  1870.         if (istrstr(cpp[i], new) != NULL) {
  1871.             free(new);
  1872.             return cpp;
  1873.         }
  1874.     /*
  1875.     ** Eliminate any obsoleted strings.
  1876.     */
  1877.     j = 0;
  1878.     while (cpp[j] != NULL)
  1879.         if (istrstr(new, cpp[j]) == NULL)
  1880.             ++j;
  1881.         else {
  1882.             free(cpp[j]);
  1883.             if (--i == j)
  1884.                 break;
  1885.             cpp[j] = cpp[i];
  1886.         }
  1887.     /*
  1888.     ** Add the new string.
  1889.     */
  1890.     cpp = (char **) realloc((char *) cpp, (i + 2) * sizeof *cpp);
  1891.     if (cpp == NULL)
  1892.         return NULL;
  1893.     cpp[i] = new;
  1894.     cpp[i + 1] = NULL;
  1895.     return cpp;
  1896. }
  1897.  
  1898. /*
  1899. ** Given pointers to two strings,
  1900. ** return a pointer to an allocated list of their distinct common substrings.
  1901. ** Return NULL if something seems wild.
  1902. */
  1903.  
  1904. static char **
  1905. comsubs(left, right)
  1906. char *    left;
  1907. char *    right;
  1908. {
  1909.     register char **    cpp;
  1910.     register char *        lcp;
  1911.     register char *        rcp;
  1912.     register int        i, len;
  1913.  
  1914.     if (left == NULL || right == NULL)
  1915.         return NULL;
  1916.     cpp = (char **) malloc(sizeof *cpp);
  1917.     if (cpp == NULL)
  1918.         return NULL;
  1919.     cpp[0] = NULL;
  1920.     for (lcp = left; *lcp != '\0'; ++lcp) {
  1921.         len = 0;
  1922.         rcp = strchr(right, *lcp);
  1923.         while (rcp != NULL) {
  1924.             for (i = 1; lcp[i] != '\0' && lcp[i] == rcp[i]; ++i)
  1925.                 ;
  1926.             if (i > len)
  1927.                 len = i;
  1928.             rcp = strchr(rcp + 1, *lcp);
  1929.         }
  1930.         if (len == 0)
  1931.             continue;
  1932.         if ((cpp = enlist(cpp, lcp, len)) == NULL)
  1933.             break;
  1934.     }
  1935.     return cpp;
  1936. }
  1937.  
  1938. static char **
  1939. addlists(old, new)
  1940. char **    old;
  1941. char **    new;
  1942. {
  1943.     register int    i;
  1944.  
  1945.     if (old == NULL || new == NULL)
  1946.         return NULL;
  1947.     for (i = 0; new[i] != NULL; ++i) {
  1948.         old = enlist(old, new[i], strlen(new[i]));
  1949.         if (old == NULL)
  1950.             break;
  1951.     }
  1952.     return old;
  1953. }
  1954.  
  1955. /*
  1956. ** Given two lists of substrings,
  1957. ** return a new list giving substrings common to both.
  1958. */
  1959.  
  1960. static char **
  1961. inboth(left, right)
  1962. char **    left;
  1963. char **    right;
  1964. {
  1965.     register char **    both;
  1966.     register char **    temp;
  1967.     register int        lnum, rnum;
  1968.  
  1969.     if (left == NULL || right == NULL)
  1970.         return NULL;
  1971.     both = (char **) malloc(sizeof *both);
  1972.     if (both == NULL)
  1973.         return NULL;
  1974.     both[0] = NULL;
  1975.     for (lnum = 0; left[lnum] != NULL; ++lnum) {
  1976.         for (rnum = 0; right[rnum] != NULL; ++rnum) {
  1977.             temp = comsubs(left[lnum], right[rnum]);
  1978.             if (temp == NULL) {
  1979.                 freelist(both);
  1980.                 return NULL;
  1981.             }
  1982.             both = addlists(both, temp);
  1983.             freelist(temp);
  1984.             if (both == NULL)
  1985.                 return NULL;
  1986.         }
  1987.     }
  1988.     return both;
  1989. }
  1990.  
  1991. typedef struct {
  1992.     char **    in;
  1993.     char *    left;
  1994.     char *    right;
  1995.     char *    is;
  1996. } must;
  1997.  
  1998. #ifdef __STDC__
  1999. static void resetmust (must *mp);
  2000. #endif
  2001.  
  2002. static void
  2003. resetmust(mp)
  2004. register must *    mp;
  2005. {
  2006.     mp->left[0] = mp->right[0] = mp->is[0] = '\0';
  2007.     freelist(mp->in);
  2008. }
  2009.  
  2010. static void
  2011. regmust(r)
  2012. register struct regexp *    r;
  2013. {
  2014.     register must *        musts;
  2015.     register must *        mp;
  2016.     register char *        result;
  2017.     register int        ri;
  2018.     register int        i;
  2019.     register _token        t;
  2020.     static must        must0;
  2021.  
  2022.     reg->mustn = 0;
  2023.     reg->must[0] = '\0';
  2024.     musts = (must *) malloc((reg->tindex + 1) * sizeof *musts);
  2025.     if (musts == NULL)
  2026.         return;
  2027.     mp = musts;
  2028.     for (i = 0; i <= reg->tindex; ++i)
  2029.         mp[i] = must0;
  2030.     for (i = 0; i <= reg->tindex; ++i) {
  2031.         mp[i].in = (char **) malloc(sizeof *mp[i].in);
  2032.         mp[i].left = malloc(2);
  2033.         mp[i].right = malloc(2);
  2034.         mp[i].is = malloc(2);
  2035.         if (mp[i].in == NULL || mp[i].left == NULL ||
  2036.             mp[i].right == NULL || mp[i].is == NULL)
  2037.                 goto done;
  2038.         mp[i].left[0] = mp[i].right[0] = mp[i].is[0] = '\0';
  2039.         mp[i].in[0] = NULL;
  2040.     }
  2041.     result = "";
  2042.     for (ri = 0; ri < reg->tindex; ++ri) {
  2043.         switch (t = reg->tokens[ri]) {
  2044.         case _ALLBEGLINE:
  2045.         case _ALLENDLINE:
  2046.         case _LPAREN:
  2047.         case _RPAREN:
  2048.             goto done;        /* "cannot happen" */
  2049.         case _EMPTY:
  2050.         case _BEGLINE:
  2051.         case _ENDLINE:
  2052.         case _BEGWORD:
  2053.         case _ENDWORD:
  2054.         case _LIMWORD:
  2055.         case _NOTLIMWORD:
  2056.         case _BACKREF:
  2057.             resetmust(mp);
  2058.             break;
  2059.         case _STAR:
  2060.         case _QMARK:
  2061.             if (mp <= musts)
  2062.                 goto done;    /* "cannot happen" */
  2063.             --mp;
  2064.             resetmust(mp);
  2065.             break;
  2066.         case _OR:
  2067.             if (mp < &musts[2])
  2068.                 goto done;    /* "cannot happen" */
  2069.             {
  2070.                 register char **    new;
  2071.                 register must *        lmp;
  2072.                 register must *        rmp;
  2073.                 register int        j, ln, rn, n;
  2074.  
  2075.                 rmp = --mp;
  2076.                 lmp = --mp;
  2077.                 /* Guaranteed to be.  Unlikely, but. . . */
  2078.                 if (strcmp(lmp->is, rmp->is) != 0)
  2079.                     lmp->is[0] = '\0';
  2080.                 /* Left side--easy */
  2081.                 i = 0;
  2082.                 while (lmp->left[i] != '\0' &&
  2083.                     lmp->left[i] == rmp->left[i])
  2084.                         ++i;
  2085.                 lmp->left[i] = '\0';
  2086.                 /* Right side */
  2087.                 ln = strlen(lmp->right);
  2088.                 rn = strlen(rmp->right);
  2089.                 n = ln;
  2090.                 if (n > rn)
  2091.                     n = rn;
  2092.                 for (i = 0; i < n; ++i)
  2093.                     if (lmp->right[ln - i - 1] !=
  2094.                         rmp->right[rn - i - 1])
  2095.                         break;
  2096.                 for (j = 0; j < i; ++j)
  2097.                     lmp->right[j] =
  2098.                         lmp->right[(ln - i) + j];
  2099.                 lmp->right[j] = '\0';
  2100.                 new = inboth(lmp->in, rmp->in);
  2101.                 if (new == NULL)
  2102.                     goto done;
  2103.                 freelist(lmp->in);
  2104.                 free((char *) lmp->in);
  2105.                 lmp->in = new;
  2106.             }
  2107.             break;
  2108.         case _PLUS:
  2109.             if (mp <= musts)
  2110.                 goto done;    /* "cannot happen" */
  2111.             --mp;
  2112.             mp->is[0] = '\0';
  2113.             break;
  2114.         case _END:
  2115.             if (mp != &musts[1])
  2116.                 goto done;    /* "cannot happen" */
  2117.             for (i = 0; musts[0].in[i] != NULL; ++i)
  2118.                 if (strlen(musts[0].in[i]) > strlen(result))
  2119.                     result = musts[0].in[i];
  2120.             goto done;
  2121.         case _CAT:
  2122.             if (mp < &musts[2])
  2123.                 goto done;    /* "cannot happen" */
  2124.             {
  2125.                 register must *    lmp;
  2126.                 register must *    rmp;
  2127.  
  2128.                 rmp = --mp;
  2129.                 lmp = --mp;
  2130.                 /*
  2131.                 ** In.  Everything in left, plus everything in
  2132.                 ** right, plus catenation of
  2133.                 ** left's right and right's left.
  2134.                 */
  2135.                 lmp->in = addlists(lmp->in, rmp->in);
  2136.                 if (lmp->in == NULL)
  2137.                     goto done;
  2138.                 if (lmp->right[0] != '\0' &&
  2139.                     rmp->left[0] != '\0') {
  2140.                         register char *    tp;
  2141.  
  2142.                         tp = icpyalloc(lmp->right);
  2143.                         if (tp == NULL)
  2144.                             goto done;
  2145.                         tp = icatalloc(tp, rmp->left);
  2146.                         if (tp == NULL)
  2147.                             goto done;
  2148.                         lmp->in = enlist(lmp->in, tp,
  2149.                             strlen(tp));
  2150.                         free(tp);
  2151.                         if (lmp->in == NULL)
  2152.                             goto done;
  2153.                 }
  2154.                 /* Left-hand */
  2155.                 if (lmp->is[0] != '\0') {
  2156.                     lmp->left = icatalloc(lmp->left,
  2157.                         rmp->left);
  2158.                     if (lmp->left == NULL)
  2159.                         goto done;
  2160.                 }
  2161.                 /* Right-hand */
  2162.                 if (rmp->is[0] == '\0')
  2163.                     lmp->right[0] = '\0';
  2164.                 lmp->right = icatalloc(lmp->right, rmp->right);
  2165.                 if (lmp->right == NULL)
  2166.                     goto done;
  2167.                 /* Guaranteed to be */
  2168.                 if (lmp->is[0] != '\0' && rmp->is[0] != '\0') {
  2169.                     lmp->is = icatalloc(lmp->is, rmp->is);
  2170.                     if (lmp->is == NULL)
  2171.                         goto done;
  2172.                 }
  2173.             }
  2174.             break;
  2175.         default:
  2176.             if (t < _END) {
  2177.                 /* "cannot happen" */
  2178.                 goto done;
  2179.             } else if (t == '\0') {
  2180.                 /* not on *my* shift */
  2181.                 goto done;
  2182.             } else if (t >= _SET) {
  2183.                 /* easy enough */
  2184.                 resetmust(mp);
  2185.             } else {
  2186.                 /* plain character */
  2187.                 resetmust(mp);
  2188.                 mp->is[0] = mp->left[0] = mp->right[0] = t;
  2189.                 mp->is[1] = mp->left[1] = mp->right[1] = '\0';
  2190.                 mp->in = enlist(mp->in, mp->is, 1);
  2191.                 if (mp->in == NULL)
  2192.                     goto done;
  2193.             }
  2194.             break;
  2195.         }
  2196.         ++mp;
  2197.     }
  2198. done:
  2199.     (void) strncpy(reg->must, result, MUST_MAX - 1);
  2200.     reg->must[MUST_MAX - 1] = '\0';
  2201.     reg->mustn = strlen(reg->must);
  2202.     mp = musts;
  2203.     for (i = 0; i <= reg->tindex; ++i) {
  2204.         freelist(mp[i].in);
  2205.         ifree((char *) mp[i].in);
  2206.         ifree(mp[i].left);
  2207.         ifree(mp[i].right);
  2208.         ifree(mp[i].is);
  2209.     }
  2210.     free((char *) mp);
  2211. }
  2212.