home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 22 gnu / 22-gnu.zip / GNUGRE.ZIP / grep / dfa.c < prev    next >
C/C++ Source or Header  |  1992-07-18  |  60KB  |  2,277 lines

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