home *** CD-ROM | disk | FTP | other *** search
/ ARM Club 3 / TheARMClub_PDCD3.iso / hensa / textprocess / grep_2 / release / c / dfa < prev    next >
Text File  |  1998-09-23  |  70KB  |  2,230 lines

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