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