home *** CD-ROM | disk | FTP | other *** search
/ Monster Media 1994 #1 / monster.zip / monster / PROG_C / GAWKNT.ZIP / SRC.ZIP / DFA.C < prev    next >
C/C++ Source or Header  |  1994-03-07  |  69KB  |  2,586 lines

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