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