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