Import grep-2.7
[dragonfly.git] / contrib / grep / src / dfa.c
1 /* dfa.c - deterministic extended regexp routines for GNU
2    Copyright (C) 1988, 1998, 2000, 2002, 2004, 2005, 2007-2010 Free Software
3    Foundation, Inc.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc.,
18    51 Franklin Street - Fifth Floor, Boston, MA  02110-1301, USA */
19
20 /* Written June, 1988 by Mike Haertel
21    Modified July, 1988 by Arthur David Olson to assist BMG speedups  */
22
23 #include <config.h>
24 #include <assert.h>
25 #include <ctype.h>
26 #include <stdio.h>
27 #include <sys/types.h>
28 #include <stddef.h>
29 #include <stdlib.h>
30 #include <limits.h>
31 #include <string.h>
32 #include <locale.h>
33
34 #define STREQ(a, b) (strcmp (a, b) == 0)
35
36 /* ISASCIIDIGIT differs from isdigit, as follows:
37    - Its arg may be any int or unsigned int; it need not be an unsigned char.
38    - It's guaranteed to evaluate its argument exactly once.
39    - It's typically faster.
40    Posix 1003.2-1992 section 2.5.2.1 page 50 lines 1556-1558 says that
41    only '0' through '9' are digits.  Prefer ISASCIIDIGIT to isdigit unless
42    it's important to use the locale's definition of `digit' even when the
43    host does not conform to Posix.  */
44 #define ISASCIIDIGIT(c) ((unsigned) (c) - '0' <= 9)
45
46 /* gettext.h ensures that we don't use gettext if ENABLE_NLS is not defined */
47 #include "gettext.h"
48 #define _(str) gettext (str)
49
50 #include "mbsupport.h"  /* defines MBS_SUPPORT if appropriate */
51 #include <wchar.h>
52 #include <wctype.h>
53
54 #if HAVE_LANGINFO_CODESET
55 # include <langinfo.h>
56 #endif
57
58 #include "regex.h"
59 #include "dfa.h"
60 #include "hard-locale.h"
61 #include "xalloc.h"
62
63 /* HPUX, define those as macros in sys/param.h */
64 #ifdef setbit
65 # undef setbit
66 #endif
67 #ifdef clrbit
68 # undef clrbit
69 #endif
70
71 /* Number of bits in an unsigned char. */
72 #ifndef CHARBITS
73 # define CHARBITS 8
74 #endif
75
76 /* First integer value that is greater than any character code. */
77 #define NOTCHAR (1 << CHARBITS)
78
79 /* INTBITS need not be exact, just a lower bound. */
80 #ifndef INTBITS
81 # define INTBITS (CHARBITS * sizeof (int))
82 #endif
83
84 /* Number of ints required to hold a bit for every character. */
85 #define CHARCLASS_INTS ((NOTCHAR + INTBITS - 1) / INTBITS)
86
87 /* Sets of unsigned characters are stored as bit vectors in arrays of ints. */
88 typedef int charclass[CHARCLASS_INTS];
89
90 /* Sometimes characters can only be matched depending on the surrounding
91    context.  Such context decisions depend on what the previous character
92    was, and the value of the current (lookahead) character.  Context
93    dependent constraints are encoded as 8 bit integers.  Each bit that
94    is set indicates that the constraint succeeds in the corresponding
95    context.
96
97    bit 7 - previous and current are newlines
98    bit 6 - previous was newline, current isn't
99    bit 5 - previous wasn't newline, current is
100    bit 4 - neither previous nor current is a newline
101    bit 3 - previous and current are word-constituents
102    bit 2 - previous was word-constituent, current isn't
103    bit 1 - previous wasn't word-constituent, current is
104    bit 0 - neither previous nor current is word-constituent
105
106    Word-constituent characters are those that satisfy isalnum().
107
108    The macro SUCCEEDS_IN_CONTEXT determines whether a a given constraint
109    succeeds in a particular context.  Prevn is true if the previous character
110    was a newline, currn is true if the lookahead character is a newline.
111    Prevl and currl similarly depend upon whether the previous and current
112    characters are word-constituent letters. */
113 #define MATCHES_NEWLINE_CONTEXT(constraint, prevn, currn) \
114   ((constraint) & 1 << (((prevn) ? 2 : 0) + ((currn) ? 1 : 0) + 4))
115 #define MATCHES_LETTER_CONTEXT(constraint, prevl, currl) \
116   ((constraint) & 1 << (((prevl) ? 2 : 0) + ((currl) ? 1 : 0)))
117 #define SUCCEEDS_IN_CONTEXT(constraint, prevn, currn, prevl, currl) \
118   (MATCHES_NEWLINE_CONTEXT(constraint, prevn, currn)                 \
119    && MATCHES_LETTER_CONTEXT(constraint, prevl, currl))
120
121 /* The following macros give information about what a constraint depends on. */
122 #define PREV_NEWLINE_DEPENDENT(constraint) \
123   (((constraint) & 0xc0) >> 2 != ((constraint) & 0x30))
124 #define PREV_LETTER_DEPENDENT(constraint) \
125   (((constraint) & 0x0c) >> 2 != ((constraint) & 0x03))
126
127 /* Tokens that match the empty string subject to some constraint actually
128    work by applying that constraint to determine what may follow them,
129    taking into account what has gone before.  The following values are
130    the constraints corresponding to the special tokens previously defined. */
131 #define NO_CONSTRAINT 0xff
132 #define BEGLINE_CONSTRAINT 0xcf
133 #define ENDLINE_CONSTRAINT 0xaf
134 #define BEGWORD_CONSTRAINT 0xf2
135 #define ENDWORD_CONSTRAINT 0xf4
136 #define LIMWORD_CONSTRAINT 0xf6
137 #define NOTLIMWORD_CONSTRAINT 0xf9
138
139 /* The regexp is parsed into an array of tokens in postfix form.  Some tokens
140    are operators and others are terminal symbols.  Most (but not all) of these
141    codes are returned by the lexical analyzer. */
142 typedef enum
143 {
144   END = -1,                     /* END is a terminal symbol that matches the
145                                    end of input; any value of END or less in
146                                    the parse tree is such a symbol.  Accepting
147                                    states of the DFA are those that would have
148                                    a transition on END. */
149
150   /* Ordinary character values are terminal symbols that match themselves. */
151
152   EMPTY = NOTCHAR,              /* EMPTY is a terminal symbol that matches
153                                    the empty string. */
154
155   BACKREF,                      /* BACKREF is generated by \<digit>; it
156                                    it not completely handled.  If the scanner
157                                    detects a transition on backref, it returns
158                                    a kind of "semi-success" indicating that
159                                    the match will have to be verified with
160                                    a backtracking matcher. */
161
162   BEGLINE,                      /* BEGLINE is a terminal symbol that matches
163                                    the empty string if it is at the beginning
164                                    of a line. */
165
166   ENDLINE,                      /* ENDLINE is a terminal symbol that matches
167                                    the empty string if it is at the end of
168                                    a line. */
169
170   BEGWORD,                      /* BEGWORD is a terminal symbol that matches
171                                    the empty string if it is at the beginning
172                                    of a word. */
173
174   ENDWORD,                      /* ENDWORD is a terminal symbol that matches
175                                    the empty string if it is at the end of
176                                    a word. */
177
178   LIMWORD,                      /* LIMWORD is a terminal symbol that matches
179                                    the empty string if it is at the beginning
180                                    or the end of a word. */
181
182   NOTLIMWORD,                   /* NOTLIMWORD is a terminal symbol that
183                                    matches the empty string if it is not at
184                                    the beginning or end of a word. */
185
186   QMARK,                        /* QMARK is an operator of one argument that
187                                    matches zero or one occurences of its
188                                    argument. */
189
190   STAR,                         /* STAR is an operator of one argument that
191                                    matches the Kleene closure (zero or more
192                                    occurrences) of its argument. */
193
194   PLUS,                         /* PLUS is an operator of one argument that
195                                    matches the positive closure (one or more
196                                    occurrences) of its argument. */
197
198   REPMN,                        /* REPMN is a lexical token corresponding
199                                    to the {m,n} construct.  REPMN never
200                                    appears in the compiled token vector. */
201
202   CAT,                          /* CAT is an operator of two arguments that
203                                    matches the concatenation of its
204                                    arguments.  CAT is never returned by the
205                                    lexical analyzer. */
206
207   OR,                           /* OR is an operator of two arguments that
208                                    matches either of its arguments. */
209
210   LPAREN,                       /* LPAREN never appears in the parse tree,
211                                    it is only a lexeme. */
212
213   RPAREN,                       /* RPAREN never appears in the parse tree. */
214
215   ANYCHAR,                     /* ANYCHAR is a terminal symbol that matches
216                                   any multibyte (or single byte) characters.
217                                   It is used only if MB_CUR_MAX > 1.  */
218
219   MBCSET,                       /* MBCSET is similar to CSET, but for
220                                    multibyte characters.  */
221
222   WCHAR,                        /* Only returned by lex.  wctok contains
223                                    the wide character representation.  */
224
225   CSET                          /* CSET and (and any value greater) is a
226                                    terminal symbol that matches any of a
227                                    class of characters. */
228 } token;
229
230
231 /* States of the recognizer correspond to sets of positions in the parse
232    tree, together with the constraints under which they may be matched.
233    So a position is encoded as an index into the parse tree together with
234    a constraint. */
235 typedef struct
236 {
237   unsigned int index;           /* Index into the parse array. */
238   unsigned int constraint;      /* Constraint for matching this position. */
239 } position;
240
241 /* Sets of positions are stored as arrays. */
242 typedef struct
243 {
244   position *elems;              /* Elements of this position set. */
245   int nelem;                    /* Number of elements in this set. */
246 } position_set;
247
248 /* A state of the dfa consists of a set of positions, some flags,
249    and the token value of the lowest-numbered position of the state that
250    contains an END token. */
251 typedef struct
252 {
253   int hash;                     /* Hash of the positions of this state. */
254   position_set elems;           /* Positions this state could match. */
255   char newline;                 /* True if previous state matched newline. */
256   char letter;                  /* True if previous state matched a letter. */
257   char backref;                 /* True if this state matches a \<digit>. */
258   unsigned char constraint;     /* Constraint for this state to accept. */
259   int first_end;                /* Token value of the first END in elems. */
260 #if MBS_SUPPORT
261   position_set mbps;           /* Positions which can match multibyte
262                                   characters.  e.g. period.
263                                   These staff are used only if
264                                   MB_CUR_MAX > 1.  */
265 #endif
266 } dfa_state;
267
268 #if MBS_SUPPORT
269 /* A bracket operator.
270    e.g. [a-c], [[:alpha:]], etc.  */
271 struct mb_char_classes
272 {
273   int cset;
274   int invert;
275   wchar_t *chars;               /* Normal characters.  */
276   int nchars;
277   wctype_t *ch_classes;         /* Character classes.  */
278   int nch_classes;
279   wchar_t *range_sts;           /* Range characters (start of the range).  */
280   wchar_t *range_ends;          /* Range characters (end of the range).  */
281   int nranges;
282   char **equivs;                /* Equivalent classes.  */
283   int nequivs;
284   char **coll_elems;
285   int ncoll_elems;              /* Collating elements.  */
286 };
287 #endif
288
289 /* A compiled regular expression. */
290 struct dfa
291 {
292   /* Fields filled by the scanner. */
293   charclass *charclasses;       /* Array of character sets for CSET tokens. */
294   int cindex;                   /* Index for adding new charclasses. */
295   int calloc;                   /* Number of charclasses currently allocated. */
296
297   /* Fields filled by the parser. */
298   token *tokens;                /* Postfix parse array. */
299   int tindex;                   /* Index for adding new tokens. */
300   int talloc;                   /* Number of tokens currently allocated. */
301   int depth;                    /* Depth required of an evaluation stack
302                                    used for depth-first traversal of the
303                                    parse tree. */
304   int nleaves;                  /* Number of leaves on the parse tree. */
305   int nregexps;                 /* Count of parallel regexps being built
306                                    with dfaparse(). */
307   unsigned int mb_cur_max;      /* Cached value of MB_CUR_MAX.  */
308   int utf8_anychar_classes[5];  /* To lower ANYCHAR in UTF-8 locales.  */
309
310   /* The following are used only if MB_CUR_MAX > 1.  */
311
312   /* The value of multibyte_prop[i] is defined by following rule.
313        if tokens[i] < NOTCHAR
314          bit 0 : tokens[i] is the first byte of a character, including
315                  single-byte characters.
316          bit 1 : tokens[i] is the last byte of a character, including
317                  single-byte characters.
318
319        if tokens[i] = MBCSET
320          ("the index of mbcsets correspnd to this operator" << 2) + 3
321
322      e.g.
323      tokens
324         = 'single_byte_a', 'multi_byte_A', single_byte_b'
325         = 'sb_a', 'mb_A(1st byte)', 'mb_A(2nd byte)', 'mb_A(3rd byte)', 'sb_b'
326      multibyte_prop
327         = 3     , 1               ,  0              ,  2              , 3
328   */
329   int nmultibyte_prop;
330   int *multibyte_prop;
331
332   /* Array of the bracket expression in the DFA.  */
333   struct mb_char_classes *mbcsets;
334   int nmbcsets;
335   int mbcsets_alloc;
336
337   /* Fields filled by the state builder. */
338   dfa_state *states;            /* States of the dfa. */
339   int sindex;                   /* Index for adding new states. */
340   int salloc;                   /* Number of states currently allocated. */
341
342   /* Fields filled by the parse tree->NFA conversion. */
343   position_set *follows;        /* Array of follow sets, indexed by position
344                                    index.  The follow of a position is the set
345                                    of positions containing characters that
346                                    could conceivably follow a character
347                                    matching the given position in a string
348                                    matching the regexp.  Allocated to the
349                                    maximum possible position index. */
350   int searchflag;               /* True if we are supposed to build a searching
351                                    as opposed to an exact matcher.  A searching
352                                    matcher finds the first and shortest string
353                                    matching a regexp anywhere in the buffer,
354                                    whereas an exact matcher finds the longest
355                                    string matching, but anchored to the
356                                    beginning of the buffer. */
357
358   /* Fields filled by dfaexec. */
359   int tralloc;                  /* Number of transition tables that have
360                                    slots so far. */
361   int trcount;                  /* Number of transition tables that have
362                                    actually been built. */
363   int **trans;                  /* Transition tables for states that can
364                                    never accept.  If the transitions for a
365                                    state have not yet been computed, or the
366                                    state could possibly accept, its entry in
367                                    this table is NULL. */
368   int **realtrans;              /* Trans always points to realtrans + 1; this
369                                    is so trans[-1] can contain NULL. */
370   int **fails;                  /* Transition tables after failing to accept
371                                    on a state that potentially could do so. */
372   int *success;                 /* Table of acceptance conditions used in
373                                    dfaexec and computed in build_state. */
374   int *newlines;                /* Transitions on newlines.  The entry for a
375                                    newline in any transition table is always
376                                    -1 so we can count lines without wasting
377                                    too many cycles.  The transition for a
378                                    newline is stored separately and handled
379                                    as a special case.  Newline is also used
380                                    as a sentinel at the end of the buffer. */
381   struct dfamust *musts;        /* List of strings, at least one of which
382                                    is known to appear in any r.e. matching
383                                    the dfa. */
384 };
385
386 /* Some macros for user access to dfa internals. */
387
388 /* ACCEPTING returns true if s could possibly be an accepting state of r. */
389 #define ACCEPTING(s, r) ((r).states[s].constraint)
390
391 /* ACCEPTS_IN_CONTEXT returns true if the given state accepts in the
392    specified context. */
393 #define ACCEPTS_IN_CONTEXT(prevn, currn, prevl, currl, state, dfa) \
394   SUCCEEDS_IN_CONTEXT((dfa).states[state].constraint,              \
395                        prevn, currn, prevl, currl)
396
397 static void dfamust (struct dfa *dfa);
398 static void regexp (void);
399
400 #define CALLOC(p, t, n) ((p) = xcalloc((size_t)(n), sizeof (t)))
401 #define MALLOC(p, t, n) ((p) = xmalloc((n) * sizeof (t)))
402 #define REALLOC(p, t, n) ((p) = xrealloc((p), (n) * sizeof (t)))
403
404 /* Reallocate an array of type t if nalloc is too small for index. */
405 #define REALLOC_IF_NECESSARY(p, t, nalloc, index) \
406   if ((index) >= (nalloc))                        \
407     {                                             \
408       do                                          \
409         (nalloc) *= 2;                            \
410       while ((index) >= (nalloc));                \
411       REALLOC(p, t, nalloc);                      \
412     }
413
414
415 #ifdef DEBUG
416
417 static void
418 prtok (token t)
419 {
420   char const *s;
421
422   if (t < 0)
423     fprintf(stderr, "END");
424   else if (t < NOTCHAR)
425     fprintf(stderr, "%c", t);
426   else
427     {
428       switch (t)
429         {
430         case EMPTY: s = "EMPTY"; break;
431         case BACKREF: s = "BACKREF"; break;
432         case BEGLINE: s = "BEGLINE"; break;
433         case ENDLINE: s = "ENDLINE"; break;
434         case BEGWORD: s = "BEGWORD"; break;
435         case ENDWORD: s = "ENDWORD"; break;
436         case LIMWORD: s = "LIMWORD"; break;
437         case NOTLIMWORD: s = "NOTLIMWORD"; break;
438         case QMARK: s = "QMARK"; break;
439         case STAR: s = "STAR"; break;
440         case PLUS: s = "PLUS"; break;
441         case CAT: s = "CAT"; break;
442         case OR: s = "OR"; break;
443         case LPAREN: s = "LPAREN"; break;
444         case RPAREN: s = "RPAREN"; break;
445 #if MBS_SUPPORT
446         case ANYCHAR: s = "ANYCHAR"; break;
447         case MBCSET: s = "MBCSET"; break;
448 #endif /* MBS_SUPPORT */
449         default: s = "CSET"; break;
450         }
451       fprintf(stderr, "%s", s);
452     }
453 }
454 #endif /* DEBUG */
455
456 /* Stuff pertaining to charclasses. */
457
458 static int
459 tstbit (unsigned int b, charclass const c)
460 {
461   return c[b / INTBITS] & 1 << b % INTBITS;
462 }
463
464 static void
465 setbit (unsigned int b, charclass c)
466 {
467   c[b / INTBITS] |= 1 << b % INTBITS;
468 }
469
470 static void
471 clrbit (unsigned int b, charclass c)
472 {
473   c[b / INTBITS] &= ~(1 << b % INTBITS);
474 }
475
476 static void
477 copyset (charclass const src, charclass dst)
478 {
479   memcpy (dst, src, sizeof (charclass));
480 }
481
482 static void
483 zeroset (charclass s)
484 {
485   memset (s, 0, sizeof (charclass));
486 }
487
488 static void
489 notset (charclass s)
490 {
491   int i;
492
493   for (i = 0; i < CHARCLASS_INTS; ++i)
494     s[i] = ~s[i];
495 }
496
497 static int
498 equal (charclass const s1, charclass const s2)
499 {
500   return memcmp (s1, s2, sizeof (charclass)) == 0;
501 }
502
503 /* A pointer to the current dfa is kept here during parsing. */
504 static struct dfa *dfa;
505
506 /* Find the index of charclass s in dfa->charclasses, or allocate a new charclass. */
507 static int
508 charclass_index (charclass const s)
509 {
510   int i;
511
512   for (i = 0; i < dfa->cindex; ++i)
513     if (equal(s, dfa->charclasses[i]))
514       return i;
515   REALLOC_IF_NECESSARY(dfa->charclasses, charclass, dfa->calloc, dfa->cindex);
516   ++dfa->cindex;
517   copyset(s, dfa->charclasses[i]);
518   return i;
519 }
520
521 /* Syntax bits controlling the behavior of the lexical analyzer. */
522 static reg_syntax_t syntax_bits, syntax_bits_set;
523
524 /* Flag for case-folding letters into sets. */
525 static int case_fold;
526
527 /* End-of-line byte in data.  */
528 static unsigned char eolbyte;
529
530 /* Entry point to set syntax options. */
531 void
532 dfasyntax (reg_syntax_t bits, int fold, unsigned char eol)
533 {
534   syntax_bits_set = 1;
535   syntax_bits = bits;
536   case_fold = fold;
537   eolbyte = eol;
538 }
539
540 /* Like setbit, but if case is folded, set both cases of a letter.
541    For MB_CUR_MAX > 1, one or both of the two cases may not be set,
542    so the resulting charset may only be used as an optimization.  */
543 static void
544 setbit_case_fold (
545 #if MBS_SUPPORT
546                   wint_t b,
547 #else
548                   unsigned int b,
549 #endif
550                   charclass c)
551 {
552   if (case_fold)
553     {
554 #if MBS_SUPPORT
555       if (MB_CUR_MAX > 1)
556         {
557           wint_t b1 = iswupper(b) ? towlower(b) : b;
558           wint_t b2 = iswlower(b) ? towupper(b) : b;
559           if (wctob ((unsigned char)b1) == b1)
560             setbit (b1, c);
561           if (b2 != b1 && wctob ((unsigned char)b2) == b2)
562             setbit (b2, c);
563         }
564       else
565 #endif
566         {
567           unsigned char b1 = isupper(b) ? tolower(b) : b;
568           unsigned char b2 = islower(b) ? toupper(b) : b;
569           setbit (b1, c);
570           if (b2 != b1)
571             setbit (b2, c);
572         }
573     }
574   else
575     {
576 #if MBS_SUPPORT
577       if (wctob ((unsigned char)b) == b)
578 #endif
579         setbit (b, c);
580     }
581 }
582
583
584 /* UTF-8 encoding allows some optimizations that we can't otherwise
585    assume in a multibyte encoding. */
586 static inline int
587 using_utf8 (void)
588 {
589   static int utf8 = -1;
590   if (utf8 == -1)
591     {
592 #if defined HAVE_LANGINFO_CODESET && defined MBS_SUPPORT
593       utf8 = (STREQ (nl_langinfo (CODESET), "UTF-8"));
594 #else
595       utf8 = 0;
596 #endif
597     }
598
599   return utf8;
600 }
601
602 /* Lexical analyzer.  All the dross that deals with the obnoxious
603    GNU Regex syntax bits is located here.  The poor, suffering
604    reader is referred to the GNU Regex documentation for the
605    meaning of the @#%!@#%^!@ syntax bits. */
606
607 static char const *lexptr;      /* Pointer to next input character. */
608 static int lexleft;             /* Number of characters remaining. */
609 static token lasttok;           /* Previous token returned; initially END. */
610 static int laststart;           /* True if we're separated from beginning or (, |
611                                    only by zero-width characters. */
612 static int parens;              /* Count of outstanding left parens. */
613 static int minrep, maxrep;      /* Repeat counts for {m,n}. */
614 static int hard_LC_COLLATE;     /* Nonzero if LC_COLLATE is hard.  */
615
616 static int cur_mb_len = 1;      /* Length of the multibyte representation of
617                                    wctok.  */
618 #if MBS_SUPPORT
619 /* These variables are used only if (MB_CUR_MAX > 1).  */
620 static mbstate_t mbs;           /* Mbstate for mbrlen().  */
621 static wchar_t wctok;           /* Wide character representation of the current
622                                    multibyte character.  */
623 static unsigned char *mblen_buf;/* Correspond to the input buffer in dfaexec().
624                                    Each element store the amount of remain
625                                    byte of corresponding multibyte character
626                                    in the input string.  A element's value
627                                    is 0 if corresponding character is a
628                                    single byte chracter.
629                                    e.g. input : 'a', <mb(0)>, <mb(1)>, <mb(2)>
630                                     mblen_buf :   0,       3,       2,       1
631                                 */
632 static wchar_t *inputwcs;       /* Wide character representation of input
633                                    string in dfaexec().
634                                    The length of this array is same as
635                                    the length of input string(char array).
636                                    inputstring[i] is a single-byte char,
637                                    or 1st byte of a multibyte char.
638                                    And inputwcs[i] is the codepoint.  */
639 static unsigned char const *buf_begin;  /* reference to begin in dfaexec().  */
640 static unsigned char const *buf_end;    /* reference to end in dfaexec().  */
641 #endif /* MBS_SUPPORT  */
642
643
644 #if MBS_SUPPORT
645 /* Note that characters become unsigned here. */
646 # define FETCH_WC(c, wc, eoferr)                \
647   do {                                          \
648     if (! lexleft)                              \
649       {                                         \
650         if ((eoferr) != 0)                      \
651           dfaerror (eoferr);                    \
652         else                                    \
653           return lasttok = END;                 \
654       }                                         \
655     else                                        \
656       {                                         \
657         wchar_t _wc;                            \
658         cur_mb_len = mbrtowc(&_wc, lexptr, lexleft, &mbs); \
659         if (cur_mb_len <= 0)                    \
660           {                                     \
661             cur_mb_len = 1;                     \
662             --lexleft;                          \
663             (wc) = (c) = (unsigned char) *lexptr++; \
664           }                                     \
665         else                                    \
666           {                                     \
667             lexptr += cur_mb_len;               \
668             lexleft -= cur_mb_len;              \
669             (wc) = _wc;                         \
670             (c) = wctob(wc);                    \
671           }                                     \
672       }                                         \
673   } while(0)
674
675 # define FETCH(c, eoferr)                       \
676   do {                                          \
677     wint_t wc;                                  \
678     FETCH_WC(c, wc, eoferr);                    \
679   } while(0)
680
681 #else
682 /* Note that characters become unsigned here. */
683 # define FETCH(c, eoferr)             \
684   do {                                \
685     if (! lexleft)                    \
686       {                               \
687         if ((eoferr) != 0)            \
688           dfaerror (eoferr);          \
689         else                          \
690           return lasttok = END;       \
691       }                               \
692     (c) = (unsigned char) *lexptr++;  \
693     --lexleft;                        \
694   } while(0)
695
696 # define FETCH_WC(c, unused, eoferr) FETCH (c, eoferr)
697
698 #endif /* MBS_SUPPORT */
699
700 static int
701 in_coll_range (char ch, char from, char to)
702 {
703   char c[6] = { from, 0, ch, 0, to, 0 };
704   return strcoll (&c[0], &c[2]) <= 0 && strcoll (&c[2], &c[4]) <= 0;
705 }
706
707 typedef int predicate (int);
708
709 /* The following list maps the names of the Posix named character classes
710    to predicate functions that determine whether a given character is in
711    the class.  The leading [ has already been eaten by the lexical analyzer. */
712 struct dfa_ctype {
713   const char *name;
714   predicate *func;
715   bool single_byte_only;
716 };
717
718 static const struct dfa_ctype prednames[] = {
719   { "alpha", isalpha, false },
720   { "upper", isupper, false },
721   { "lower", islower, false },
722   { "digit", isdigit, true },
723   { "xdigit", isxdigit, true },
724   { "space", isspace, false },
725   { "punct", ispunct, false },
726   { "alnum", isalnum, false },
727   { "print", isprint, false },
728   { "graph", isgraph, false },
729   { "cntrl", iscntrl, false },
730   { "blank", isblank, false },
731   { NULL, NULL, false }
732 };
733
734 static const struct dfa_ctype *
735 find_pred (const char *str)
736 {
737   unsigned int i;
738   for (i = 0; prednames[i].name; ++i)
739     if (STREQ (str, prednames[i].name))
740       break;
741
742   return &prednames[i];
743 }
744
745 /* Multibyte character handling sub-routine for lex.
746    This function  parse a bracket expression and build a struct
747    mb_char_classes.  */
748 static token
749 parse_bracket_exp (void)
750 {
751   int invert;
752   int c, c1, c2;
753   charclass ccl;
754
755   /* Used to warn about [:space:].
756      Bit 0 = first character is a colon.
757      Bit 1 = last character is a colon.
758      Bit 2 = includes any other character but a colon.
759      Bit 3 = includes ranges, char/equiv classes or collation elements.  */
760   int colon_warning_state;
761
762 #if MBS_SUPPORT
763   wint_t wc, wc1, wc2;
764
765   /* Work area to build a mb_char_classes.  */
766   struct mb_char_classes *work_mbc;
767   int chars_al, range_sts_al, range_ends_al, ch_classes_al,
768     equivs_al, coll_elems_al;
769
770   chars_al = 1;
771   range_sts_al = range_ends_al = 0;
772   ch_classes_al = equivs_al = coll_elems_al = 0;
773   if (MB_CUR_MAX > 1)
774     {
775       REALLOC_IF_NECESSARY(dfa->mbcsets, struct mb_char_classes,
776                            dfa->mbcsets_alloc, dfa->nmbcsets + 1);
777
778       /* dfa->multibyte_prop[] hold the index of dfa->mbcsets.
779          We will update dfa->multibyte_prop[] in addtok(), because we can't
780          decide the index in dfa->tokens[].  */
781
782       /* Initialize work area.  */
783       work_mbc = &(dfa->mbcsets[dfa->nmbcsets++]);
784       memset (work_mbc, 0, sizeof *work_mbc);
785     }
786   else
787     work_mbc = NULL;
788 #endif
789
790   memset (ccl, 0, sizeof ccl);
791   FETCH_WC (c, wc, _("unbalanced ["));
792   if (c == '^')
793     {
794       FETCH_WC (c, wc, _("unbalanced ["));
795       invert = 1;
796     }
797   else
798     invert = 0;
799
800   colon_warning_state = (c == ':');
801   do
802     {
803       c1 = EOF; /* mark c1 is not initialized".  */
804       colon_warning_state &= ~2;
805
806       /* Note that if we're looking at some other [:...:] construct,
807          we just treat it as a bunch of ordinary characters.  We can do
808          this because we assume regex has checked for syntax errors before
809          dfa is ever called. */
810       if (c == '[' && (syntax_bits & RE_CHAR_CLASSES))
811         {
812 #define BRACKET_BUFFER_SIZE 128
813           char str[BRACKET_BUFFER_SIZE];
814           FETCH_WC (c1, wc1, _("unbalanced ["));
815
816           /* If pattern contains `[[:', `[[.', or `[[='.  */
817           if (c1 == ':'
818 #if MBS_SUPPORT
819               /* TODO: handle `[[.' and `[[=' also for MB_CUR_MAX == 1.  */
820               || (MB_CUR_MAX > 1 && (c1 == '.' || c1 == '='))
821 #endif
822               )
823             {
824               size_t len = 0;
825               for (;;)
826                 {
827                   FETCH_WC (c, wc, _("unbalanced ["));
828                   if ((c == c1 && *lexptr == ']') || lexleft == 0)
829                     break;
830                   if (len < BRACKET_BUFFER_SIZE)
831                     str[len++] = c;
832                   else
833                     /* This is in any case an invalid class name.  */
834                     str[0] = '\0';
835                 }
836               str[len] = '\0';
837
838               /* Fetch bracket.  */
839               FETCH_WC (c, wc, _("unbalanced ["));
840               if (c1 == ':')
841                 /* build character class.  */
842                 {
843                   char const *class
844                     = (case_fold && (STREQ  (str, "upper")
845                                      || STREQ  (str, "lower"))
846                                        ? "alpha"
847                                        : str);
848                   const struct dfa_ctype *pred = find_pred (class);
849                   if (!pred)
850                     dfaerror(_("invalid character class"));
851
852 #if MBS_SUPPORT
853                   if (MB_CUR_MAX > 1 && !pred->single_byte_only)
854                     {
855                       /* Store the character class as wctype_t.  */
856                       wctype_t wt = wctype (class);
857
858                       if (ch_classes_al == 0)
859                         MALLOC(work_mbc->ch_classes, wctype_t, ++ch_classes_al);
860                       REALLOC_IF_NECESSARY(work_mbc->ch_classes, wctype_t,
861                                            ch_classes_al,
862                                            work_mbc->nch_classes + 1);
863                       work_mbc->ch_classes[work_mbc->nch_classes++] = wt;
864                     }
865 #endif
866
867                   for (c2 = 0; c2 < NOTCHAR; ++c2)
868                     if (pred->func(c2))
869                       setbit_case_fold (c2, ccl);
870                 }
871
872 #if MBS_SUPPORT
873               else if (c1 == '=' || c1 == '.')
874                 {
875                   char *elem;
876                   MALLOC(elem, char, len + 1);
877                   strncpy(elem, str, len + 1);
878
879                   if (c1 == '=')
880                     /* build equivalent class.  */
881                     {
882                       if (equivs_al == 0)
883                         MALLOC(work_mbc->equivs, char*, ++equivs_al);
884                       REALLOC_IF_NECESSARY(work_mbc->equivs, char*,
885                                            equivs_al,
886                                            work_mbc->nequivs + 1);
887                       work_mbc->equivs[work_mbc->nequivs++] = elem;
888                     }
889
890                   if (c1 == '.')
891                     /* build collating element.  */
892                     {
893                       if (coll_elems_al == 0)
894                         MALLOC(work_mbc->coll_elems, char*, ++coll_elems_al);
895                       REALLOC_IF_NECESSARY(work_mbc->coll_elems, char*,
896                                            coll_elems_al,
897                                            work_mbc->ncoll_elems + 1);
898                       work_mbc->coll_elems[work_mbc->ncoll_elems++] = elem;
899                     }
900                 }
901 #endif
902               colon_warning_state |= 8;
903
904               /* Fetch new lookahead character.  */
905               FETCH_WC (c1, wc1, _("unbalanced ["));
906               continue;
907             }
908
909           /* We treat '[' as a normal character here.  c/c1/wc/wc1
910              are already set up.  */
911         }
912
913       if (c == '\\' && (syntax_bits & RE_BACKSLASH_ESCAPE_IN_LISTS))
914         FETCH_WC(c, wc, _("unbalanced ["));
915
916       if (c1 == EOF)
917         FETCH_WC(c1, wc1, _("unbalanced ["));
918
919       if (c1 == '-')
920         /* build range characters.  */
921         {
922           FETCH_WC(c2, wc2, _("unbalanced ["));
923           if (c2 == ']')
924             {
925               /* In the case [x-], the - is an ordinary hyphen,
926                  which is left in c1, the lookahead character. */
927               lexptr -= cur_mb_len;
928               lexleft += cur_mb_len;
929             }
930         }
931
932       if (c1 == '-' && c2 != ']')
933         {
934           if (c2 == '\\'
935               && (syntax_bits & RE_BACKSLASH_ESCAPE_IN_LISTS))
936             FETCH_WC(c2, wc2, _("unbalanced ["));
937
938 #if MBS_SUPPORT
939           if (MB_CUR_MAX > 1)
940             {
941               /* When case folding map a range, say [m-z] (or even [M-z])
942                  to the pair of ranges, [m-z] [M-Z].  */
943               if (range_sts_al == 0)
944                 {
945                   MALLOC(work_mbc->range_sts, wchar_t, ++range_sts_al);
946                   MALLOC(work_mbc->range_ends, wchar_t, ++range_ends_al);
947                 }
948               REALLOC_IF_NECESSARY(work_mbc->range_sts, wchar_t,
949                                    range_sts_al, work_mbc->nranges + 1);
950               REALLOC_IF_NECESSARY(work_mbc->range_ends, wchar_t,
951                                    range_ends_al, work_mbc->nranges + 1);
952               work_mbc->range_sts[work_mbc->nranges] =
953                 case_fold ? towlower(wc) : (wchar_t)wc;
954               work_mbc->range_ends[work_mbc->nranges++] =
955                 case_fold ? towlower(wc2) : (wchar_t)wc2;
956
957 #ifndef GREP
958               if (case_fold && (iswalpha(wc) || iswalpha(wc2)))
959                 {
960                   REALLOC_IF_NECESSARY(work_mbc->range_sts, wchar_t,
961                                        range_sts_al, work_mbc->nranges + 1);
962                   work_mbc->range_sts[work_mbc->nranges] = towupper(wc);
963                   REALLOC_IF_NECESSARY(work_mbc->range_ends, wchar_t,
964                                        range_ends_al, work_mbc->nranges + 1);
965                   work_mbc->range_ends[work_mbc->nranges++] = towupper(wc2);
966                 }
967 #endif
968             }
969           else
970 #endif
971             {
972               c1 = c;
973               if (case_fold)
974                 {
975                   c1 = tolower (c1);
976                   c2 = tolower (c2);
977                 }
978               if (!hard_LC_COLLATE)
979                 for (c = c1; c <= c2; c++)
980                   setbit_case_fold (c, ccl);
981               else
982                 for (c = 0; c < NOTCHAR; ++c)
983                   if (!(case_fold && isupper (c))
984                       && in_coll_range (c, c1, c2))
985                     setbit_case_fold (c, ccl);
986             }
987
988           colon_warning_state |= 8;
989           FETCH_WC(c1, wc1, _("unbalanced ["));
990           continue;
991         }
992
993       colon_warning_state |= (c == ':') ? 2 : 4;
994
995 #if MBS_SUPPORT
996       /* Build normal characters.  */
997       setbit_case_fold (wc, ccl);
998       if (MB_CUR_MAX > 1)
999         {
1000           if (case_fold && iswalpha(wc))
1001             {
1002               wc = towlower(wc);
1003               c = wctob(wc);
1004               if (c == EOF || (wint_t)c != (wint_t)wc)
1005                 {
1006                   REALLOC_IF_NECESSARY(work_mbc->chars, wchar_t, chars_al,
1007                                        work_mbc->nchars + 1);
1008                   work_mbc->chars[work_mbc->nchars++] = wc;
1009                 }
1010 #ifdef GREP
1011               continue;
1012 #else
1013               wc = towupper(wc);
1014               c = wctob(wc);
1015 #endif
1016             }
1017           if (c == EOF || (wint_t)c != (wint_t)wc)
1018             {
1019               REALLOC_IF_NECESSARY(work_mbc->chars, wchar_t, chars_al,
1020                                    work_mbc->nchars + 1);
1021               work_mbc->chars[work_mbc->nchars++] = wc;
1022             }
1023         }
1024 #else
1025       setbit_case_fold (c, ccl);
1026 #endif
1027     }
1028   while ((
1029 #if MBS_SUPPORT
1030          wc = wc1,
1031 #endif
1032          (c = c1) != ']'));
1033
1034   if (colon_warning_state == 7)
1035     dfawarn (_("character class syntax is [[:space:]], not [:space:]"));
1036
1037 #if MBS_SUPPORT
1038   if (MB_CUR_MAX > 1
1039       && (!using_utf8()
1040           || invert
1041           || work_mbc->nchars != 0
1042           || work_mbc->nch_classes != 0
1043           || work_mbc->nranges != 0
1044           || work_mbc->nequivs != 0
1045           || work_mbc->ncoll_elems != 0))
1046     {
1047       static charclass zeroclass;
1048       work_mbc->invert = invert;
1049       work_mbc->cset = equal(ccl, zeroclass) ? -1 : charclass_index(ccl);
1050       return MBCSET;
1051     }
1052 #endif
1053
1054   if (invert)
1055     {
1056 #if MBS_SUPPORT
1057       assert(MB_CUR_MAX == 1);
1058 #endif
1059       notset(ccl);
1060       if (syntax_bits & RE_HAT_LISTS_NOT_NEWLINE)
1061         clrbit(eolbyte, ccl);
1062     }
1063
1064   return CSET + charclass_index(ccl);
1065 }
1066
1067 /* Return non-zero if C is a `word-constituent' byte; zero otherwise.  */
1068 #define IS_WORD_CONSTITUENT(C) (isalnum(C) || (C) == '_')
1069
1070 static token
1071 lex (void)
1072 {
1073   unsigned int c, c2;
1074   int backslash = 0;
1075   charclass ccl;
1076   int i;
1077
1078   /* Basic plan: We fetch a character.  If it's a backslash,
1079      we set the backslash flag and go through the loop again.
1080      On the plus side, this avoids having a duplicate of the
1081      main switch inside the backslash case.  On the minus side,
1082      it means that just about every case begins with
1083      "if (backslash) ...".  */
1084   for (i = 0; i < 2; ++i)
1085     {
1086 #if MBS_SUPPORT
1087       if (MB_CUR_MAX > 1)
1088         {
1089           FETCH_WC (c, wctok, NULL);
1090           if ((int)c == EOF)
1091             goto normal_char;
1092         }
1093       else
1094 #endif /* MBS_SUPPORT  */
1095         FETCH(c, NULL);
1096
1097       switch (c)
1098         {
1099         case '\\':
1100           if (backslash)
1101             goto normal_char;
1102           if (lexleft == 0)
1103             dfaerror(_("unfinished \\ escape"));
1104           backslash = 1;
1105           break;
1106
1107         case '^':
1108           if (backslash)
1109             goto normal_char;
1110           if (syntax_bits & RE_CONTEXT_INDEP_ANCHORS
1111               || lasttok == END
1112               || lasttok == LPAREN
1113               || lasttok == OR)
1114             return lasttok = BEGLINE;
1115           goto normal_char;
1116
1117         case '$':
1118           if (backslash)
1119             goto normal_char;
1120           if (syntax_bits & RE_CONTEXT_INDEP_ANCHORS
1121               || lexleft == 0
1122               || (syntax_bits & RE_NO_BK_PARENS
1123                   ? lexleft > 0 && *lexptr == ')'
1124                   : lexleft > 1 && lexptr[0] == '\\' && lexptr[1] == ')')
1125               || (syntax_bits & RE_NO_BK_VBAR
1126                   ? lexleft > 0 && *lexptr == '|'
1127                   : lexleft > 1 && lexptr[0] == '\\' && lexptr[1] == '|')
1128               || ((syntax_bits & RE_NEWLINE_ALT)
1129                   && lexleft > 0 && *lexptr == '\n'))
1130             return lasttok = ENDLINE;
1131           goto normal_char;
1132
1133         case '1':
1134         case '2':
1135         case '3':
1136         case '4':
1137         case '5':
1138         case '6':
1139         case '7':
1140         case '8':
1141         case '9':
1142           if (backslash && !(syntax_bits & RE_NO_BK_REFS))
1143             {
1144               laststart = 0;
1145               return lasttok = BACKREF;
1146             }
1147           goto normal_char;
1148
1149         case '`':
1150           if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
1151             return lasttok = BEGLINE;   /* FIXME: should be beginning of string */
1152           goto normal_char;
1153
1154         case '\'':
1155           if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
1156             return lasttok = ENDLINE;   /* FIXME: should be end of string */
1157           goto normal_char;
1158
1159         case '<':
1160           if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
1161             return lasttok = BEGWORD;
1162           goto normal_char;
1163
1164         case '>':
1165           if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
1166             return lasttok = ENDWORD;
1167           goto normal_char;
1168
1169         case 'b':
1170           if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
1171             return lasttok = LIMWORD;
1172           goto normal_char;
1173
1174         case 'B':
1175           if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
1176             return lasttok = NOTLIMWORD;
1177           goto normal_char;
1178
1179         case '?':
1180           if (syntax_bits & RE_LIMITED_OPS)
1181             goto normal_char;
1182           if (backslash != ((syntax_bits & RE_BK_PLUS_QM) != 0))
1183             goto normal_char;
1184           if (!(syntax_bits & RE_CONTEXT_INDEP_OPS) && laststart)
1185             goto normal_char;
1186           return lasttok = QMARK;
1187
1188         case '*':
1189           if (backslash)
1190             goto normal_char;
1191           if (!(syntax_bits & RE_CONTEXT_INDEP_OPS) && laststart)
1192             goto normal_char;
1193           return lasttok = STAR;
1194
1195         case '+':
1196           if (syntax_bits & RE_LIMITED_OPS)
1197             goto normal_char;
1198           if (backslash != ((syntax_bits & RE_BK_PLUS_QM) != 0))
1199             goto normal_char;
1200           if (!(syntax_bits & RE_CONTEXT_INDEP_OPS) && laststart)
1201             goto normal_char;
1202           return lasttok = PLUS;
1203
1204         case '{':
1205           if (!(syntax_bits & RE_INTERVALS))
1206             goto normal_char;
1207           if (backslash != ((syntax_bits & RE_NO_BK_BRACES) == 0))
1208             goto normal_char;
1209           if (!(syntax_bits & RE_CONTEXT_INDEP_OPS) && laststart)
1210             goto normal_char;
1211
1212           if (syntax_bits & RE_NO_BK_BRACES)
1213             {
1214               /* Scan ahead for a valid interval; if it's not valid,
1215                  treat it as a literal '{'.  */
1216               int lo = -1, hi = -1;
1217               char const *p = lexptr;
1218               char const *lim = p + lexleft;
1219               for (;  p != lim && ISASCIIDIGIT (*p);  p++)
1220                 lo = (lo < 0 ? 0 : lo * 10) + *p - '0';
1221               if (p != lim && *p == ',')
1222                 while (++p != lim && ISASCIIDIGIT (*p))
1223                   hi = (hi < 0 ? 0 : hi * 10) + *p - '0';
1224               else
1225                 hi = lo;
1226               if (p == lim || *p != '}'
1227                   || lo < 0 || RE_DUP_MAX < hi || (0 <= hi && hi < lo))
1228                 goto normal_char;
1229             }
1230
1231           minrep = 0;
1232           /* Cases:
1233              {M} - exact count
1234              {M,} - minimum count, maximum is infinity
1235              {M,N} - M through N */
1236           FETCH(c, _("unfinished repeat count"));
1237           if (ISASCIIDIGIT (c))
1238             {
1239               minrep = c - '0';
1240               for (;;)
1241                 {
1242                   FETCH(c, _("unfinished repeat count"));
1243                   if (! ISASCIIDIGIT (c))
1244                     break;
1245                   minrep = 10 * minrep + c - '0';
1246                 }
1247             }
1248           else
1249             dfaerror(_("malformed repeat count"));
1250           if (c == ',')
1251             {
1252               FETCH (c, _("unfinished repeat count"));
1253               if (! ISASCIIDIGIT (c))
1254                 maxrep = -1;
1255               else
1256                 {
1257                   maxrep = c - '0';
1258                   for (;;)
1259                     {
1260                       FETCH (c, _("unfinished repeat count"));
1261                       if (! ISASCIIDIGIT (c))
1262                         break;
1263                       maxrep = 10 * maxrep + c - '0';
1264                     }
1265                   if (0 <= maxrep && maxrep < minrep)
1266                     dfaerror (_("malformed repeat count"));
1267                 }
1268             }
1269           else
1270             maxrep = minrep;
1271           if (!(syntax_bits & RE_NO_BK_BRACES))
1272             {
1273               if (c != '\\')
1274                 dfaerror(_("malformed repeat count"));
1275               FETCH(c, _("unfinished repeat count"));
1276             }
1277           if (c != '}')
1278             dfaerror(_("malformed repeat count"));
1279           laststart = 0;
1280           return lasttok = REPMN;
1281
1282         case '|':
1283           if (syntax_bits & RE_LIMITED_OPS)
1284             goto normal_char;
1285           if (backslash != ((syntax_bits & RE_NO_BK_VBAR) == 0))
1286             goto normal_char;
1287           laststart = 1;
1288           return lasttok = OR;
1289
1290         case '\n':
1291           if (syntax_bits & RE_LIMITED_OPS
1292               || backslash
1293               || !(syntax_bits & RE_NEWLINE_ALT))
1294             goto normal_char;
1295           laststart = 1;
1296           return lasttok = OR;
1297
1298         case '(':
1299           if (backslash != ((syntax_bits & RE_NO_BK_PARENS) == 0))
1300             goto normal_char;
1301           ++parens;
1302           laststart = 1;
1303           return lasttok = LPAREN;
1304
1305         case ')':
1306           if (backslash != ((syntax_bits & RE_NO_BK_PARENS) == 0))
1307             goto normal_char;
1308           if (parens == 0 && syntax_bits & RE_UNMATCHED_RIGHT_PAREN_ORD)
1309             goto normal_char;
1310           --parens;
1311           laststart = 0;
1312           return lasttok = RPAREN;
1313
1314         case '.':
1315           if (backslash)
1316             goto normal_char;
1317 #if MBS_SUPPORT
1318           if (MB_CUR_MAX > 1)
1319             {
1320               /* In multibyte environment period must match with a single
1321                  character not a byte.  So we use ANYCHAR.  */
1322               laststart = 0;
1323               return lasttok = ANYCHAR;
1324             }
1325 #endif /* MBS_SUPPORT */
1326           zeroset(ccl);
1327           notset(ccl);
1328           if (!(syntax_bits & RE_DOT_NEWLINE))
1329             clrbit(eolbyte, ccl);
1330           if (syntax_bits & RE_DOT_NOT_NULL)
1331             clrbit('\0', ccl);
1332           laststart = 0;
1333           return lasttok = CSET + charclass_index(ccl);
1334
1335 #ifndef GAWK
1336         case 's':
1337         case 'S':
1338           if (!backslash || (syntax_bits & RE_NO_GNU_OPS))
1339             goto normal_char;
1340           zeroset(ccl);
1341           for (c2 = 0; c2 < NOTCHAR; ++c2)
1342             if (isspace(c2))
1343               setbit(c2, ccl);
1344           if (c == 'S')
1345             notset(ccl);
1346           laststart = 0;
1347           return lasttok = CSET + charclass_index(ccl);
1348 #endif
1349
1350         case 'w':
1351         case 'W':
1352           if (!backslash || (syntax_bits & RE_NO_GNU_OPS))
1353             goto normal_char;
1354           zeroset(ccl);
1355           for (c2 = 0; c2 < NOTCHAR; ++c2)
1356             if (IS_WORD_CONSTITUENT(c2))
1357               setbit(c2, ccl);
1358           if (c == 'W')
1359             notset(ccl);
1360           laststart = 0;
1361           return lasttok = CSET + charclass_index(ccl);
1362
1363         case '[':
1364           if (backslash)
1365             goto normal_char;
1366           laststart = 0;
1367           return lasttok = parse_bracket_exp();
1368
1369         default:
1370         normal_char:
1371           laststart = 0;
1372 #if MBS_SUPPORT
1373           /* For multibyte character sets, folding is done in atom.  Always
1374              return WCHAR.  */
1375           if (MB_CUR_MAX > 1)
1376             return lasttok = WCHAR;
1377 #endif
1378
1379           if (case_fold && isalpha(c))
1380             {
1381               zeroset(ccl);
1382               setbit_case_fold (c, ccl);
1383               return lasttok = CSET + charclass_index(ccl);
1384             }
1385
1386           return lasttok = c;
1387         }
1388     }
1389
1390   /* The above loop should consume at most a backslash
1391      and some other character. */
1392   abort();
1393   return END;   /* keeps pedantic compilers happy. */
1394 }
1395
1396 /* Recursive descent parser for regular expressions. */
1397
1398 static token tok;               /* Lookahead token. */
1399 static int depth;               /* Current depth of a hypothetical stack
1400                                    holding deferred productions.  This is
1401                                    used to determine the depth that will be
1402                                    required of the real stack later on in
1403                                    dfaanalyze(). */
1404
1405 static void
1406 addtok_mb (token t, int mbprop)
1407 {
1408 #if MBS_SUPPORT
1409   if (MB_CUR_MAX > 1)
1410     {
1411       REALLOC_IF_NECESSARY(dfa->multibyte_prop, int, dfa->nmultibyte_prop,
1412                            dfa->tindex);
1413       dfa->multibyte_prop[dfa->tindex] = mbprop;
1414     }
1415 #else
1416   (void) mbprop;
1417 #endif
1418
1419   REALLOC_IF_NECESSARY(dfa->tokens, token, dfa->talloc, dfa->tindex);
1420   dfa->tokens[dfa->tindex++] = t;
1421
1422   switch (t)
1423     {
1424     case QMARK:
1425     case STAR:
1426     case PLUS:
1427       break;
1428
1429     case CAT:
1430     case OR:
1431       --depth;
1432       break;
1433
1434     default:
1435       ++dfa->nleaves;
1436     case EMPTY:
1437       ++depth;
1438       break;
1439     }
1440   if (depth > dfa->depth)
1441     dfa->depth = depth;
1442 }
1443
1444 /* Add the given token to the parse tree, maintaining the depth count and
1445    updating the maximum depth if necessary. */
1446 static void
1447 addtok (token t)
1448 {
1449 #if MBS_SUPPORT
1450   if (MB_CUR_MAX > 1 && t == MBCSET)
1451     addtok_mb (MBCSET, ((dfa->nmbcsets - 1) << 2) + 3);
1452   else
1453 #endif
1454     addtok_mb (t, 3);
1455 }
1456
1457 #if MBS_SUPPORT
1458 /* We treat a multibyte character as a single atom, so that DFA
1459    can treat a multibyte character as a single expression.
1460
1461    e.g. We construct following tree from "<mb1><mb2>".
1462    <mb1(1st-byte)><mb1(2nd-byte)><CAT><mb1(3rd-byte)><CAT>
1463    <mb2(1st-byte)><mb2(2nd-byte)><CAT><mb2(3rd-byte)><CAT><CAT> */
1464 static void
1465 addtok_wc (wint_t wc)
1466 {
1467   unsigned char buf[MB_LEN_MAX];
1468   mbstate_t s;
1469   int i;
1470   memset (&s, 0, sizeof s);
1471   cur_mb_len = wcrtomb ((char *) buf, wc, &s);
1472
1473   /* This is merely stop-gap.  When cur_mb_len is 0 or negative,
1474      buf[0] is undefined, yet skipping the addtok_mb call altogether
1475      can result in heap corruption.  */
1476   if (cur_mb_len <= 0)
1477     buf[0] = 0;
1478
1479   addtok_mb(buf[0], cur_mb_len == 1 ? 3 : 1);
1480   for (i = 1; i < cur_mb_len; i++)
1481     {
1482       addtok_mb(buf[i], i == cur_mb_len - 1 ? 2 : 0);
1483       addtok(CAT);
1484     }
1485 }
1486 #endif
1487
1488 static void
1489 add_utf8_anychar (void)
1490 {
1491   static const charclass utf8_classes[5] = {
1492       {  0,  0,  0,  0, ~0, ~0, 0, 0 },            /* 80-bf: non-lead bytes */
1493       { ~0, ~0, ~0, ~0, 0, 0, 0, 0 },              /* 00-7f: 1-byte sequence */
1494       {  0,  0,  0,  0,  0,  0, 0xfffffffcU, 0 },  /* c2-df: 2-byte sequence */
1495       {  0,  0,  0,  0,  0,  0,  0, 0xffff },      /* e0-ef: 3-byte sequence */
1496       {  0,  0,  0,  0,  0,  0,  0, 0xff0000 }     /* f0-f7: 4-byte sequence */
1497   };
1498   const unsigned int n = sizeof (utf8_classes) / sizeof (utf8_classes[0]);
1499   unsigned int i;
1500
1501   /* Define the five character classes that are needed below.  */
1502   if (dfa->utf8_anychar_classes[0] == 0)
1503     for (i = 0; i < n; i++)
1504       {
1505         charclass c;
1506         memcpy (c, utf8_classes[i], sizeof c);
1507         if (i == 1)
1508           {
1509             if (!(syntax_bits & RE_DOT_NEWLINE))
1510               clrbit (eolbyte, c);
1511             if (syntax_bits & RE_DOT_NOT_NULL)
1512               clrbit ('\0', c);
1513           }
1514         dfa->utf8_anychar_classes[i] = CSET + charclass_index(c);
1515       }
1516
1517   /* A valid UTF-8 character is
1518
1519           ([0x00-0x7f]
1520            |[0xc2-0xdf][0x80-0xbf]
1521            |[0xe0-0xef[0x80-0xbf][0x80-0xbf]
1522            |[0xf0-f7][0x80-0xbf][0x80-0xbf][0x80-0xbf])
1523
1524      which I'll write more concisely "B|CA|DAA|EAAA".  Factor the [0x00-0x7f]
1525      and you get "B|(C|(D|EA)A)A".  And since the token buffer is in reverse
1526      Polish notation, you get "B C D E A CAT OR A CAT OR A CAT OR".  */
1527   for (i = 1; i < n; i++)
1528     addtok (dfa->utf8_anychar_classes[i]);
1529   while (--i > 1)
1530     {
1531       addtok (dfa->utf8_anychar_classes[0]);
1532       addtok (CAT);
1533       addtok (OR);
1534     }
1535 }
1536
1537 /* The grammar understood by the parser is as follows.
1538
1539    regexp:
1540      regexp OR branch
1541      branch
1542
1543    branch:
1544      branch closure
1545      closure
1546
1547    closure:
1548      closure QMARK
1549      closure STAR
1550      closure PLUS
1551      closure REPMN
1552      atom
1553
1554    atom:
1555      <normal character>
1556      <multibyte character>
1557      ANYCHAR
1558      MBCSET
1559      CSET
1560      BACKREF
1561      BEGLINE
1562      ENDLINE
1563      BEGWORD
1564      ENDWORD
1565      LIMWORD
1566      NOTLIMWORD
1567      LPAREN regexp RPAREN
1568      <empty>
1569
1570    The parser builds a parse tree in postfix form in an array of tokens. */
1571
1572 static void
1573 atom (void)
1574 {
1575   if (0)
1576     {
1577       /* empty */
1578     }
1579 #if MBS_SUPPORT
1580   else if (tok == WCHAR)
1581     {
1582       addtok_wc (case_fold ? towlower(wctok) : wctok);
1583 #ifndef GREP
1584       if (case_fold && iswalpha(wctok))
1585         {
1586           addtok_wc (towupper(wctok));
1587           addtok (OR);
1588         }
1589 #endif
1590
1591       tok = lex();
1592     }
1593
1594   else if (tok == ANYCHAR && using_utf8())
1595     {
1596       /* For UTF-8 expand the period to a series of CSETs that define a valid
1597          UTF-8 character.  This avoids using the slow multibyte path.  I'm
1598          pretty sure it would be both profitable and correct to do it for
1599          any encoding; however, the optimization must be done manually as
1600          it is done above in add_utf8_anychar.  So, let's start with
1601          UTF-8: it is the most used, and the structure of the encoding
1602          makes the correctness more obvious.  */
1603       add_utf8_anychar();
1604       tok = lex();
1605     }
1606 #endif /* MBS_SUPPORT  */
1607
1608   else if ((tok >= 0 && tok < NOTCHAR) || tok >= CSET || tok == BACKREF
1609            || tok == BEGLINE || tok == ENDLINE || tok == BEGWORD
1610 #if MBS_SUPPORT
1611            || tok == ANYCHAR || tok == MBCSET
1612 #endif /* MBS_SUPPORT */
1613            || tok == ENDWORD || tok == LIMWORD || tok == NOTLIMWORD)
1614     {
1615       addtok(tok);
1616       tok = lex();
1617     }
1618   else if (tok == LPAREN)
1619     {
1620       tok = lex();
1621       regexp();
1622       if (tok != RPAREN)
1623         dfaerror(_("unbalanced ("));
1624       tok = lex();
1625     }
1626   else
1627     addtok(EMPTY);
1628 }
1629
1630 /* Return the number of tokens in the given subexpression. */
1631 static int
1632 nsubtoks (int tindex)
1633 {
1634   int ntoks1;
1635
1636   switch (dfa->tokens[tindex - 1])
1637     {
1638     default:
1639       return 1;
1640     case QMARK:
1641     case STAR:
1642     case PLUS:
1643       return 1 + nsubtoks(tindex - 1);
1644     case CAT:
1645     case OR:
1646       ntoks1 = nsubtoks(tindex - 1);
1647       return 1 + ntoks1 + nsubtoks(tindex - 1 - ntoks1);
1648     }
1649 }
1650
1651 /* Copy the given subexpression to the top of the tree. */
1652 static void
1653 copytoks (int tindex, int ntokens)
1654 {
1655   int i;
1656
1657   for (i = 0; i < ntokens; ++i)
1658     {
1659       addtok(dfa->tokens[tindex + i]);
1660 #if MBS_SUPPORT
1661       /* Update index into multibyte csets.  */
1662       if (MB_CUR_MAX > 1 && dfa->tokens[tindex + i] == MBCSET)
1663         dfa->multibyte_prop[dfa->tindex - 1] = dfa->multibyte_prop[tindex + i];
1664 #endif
1665     }
1666 }
1667
1668 static void
1669 closure (void)
1670 {
1671   int tindex, ntokens, i;
1672
1673   atom();
1674   while (tok == QMARK || tok == STAR || tok == PLUS || tok == REPMN)
1675     if (tok == REPMN && (minrep || maxrep))
1676       {
1677         ntokens = nsubtoks(dfa->tindex);
1678         tindex = dfa->tindex - ntokens;
1679         if (maxrep < 0)
1680           addtok(PLUS);
1681         if (minrep == 0)
1682           addtok(QMARK);
1683         for (i = 1; i < minrep; ++i)
1684           {
1685             copytoks(tindex, ntokens);
1686             addtok(CAT);
1687           }
1688         for (; i < maxrep; ++i)
1689           {
1690             copytoks(tindex, ntokens);
1691             addtok(QMARK);
1692             addtok(CAT);
1693           }
1694         tok = lex();
1695       }
1696     else if (tok == REPMN)
1697       {
1698         dfa->tindex -= nsubtoks(dfa->tindex);
1699         tok = lex();
1700         closure();
1701       }
1702     else
1703       {
1704         addtok(tok);
1705         tok = lex();
1706       }
1707 }
1708
1709 static void
1710 branch (void)
1711 {
1712   closure();
1713   while (tok != RPAREN && tok != OR && tok >= 0)
1714     {
1715       closure();
1716       addtok(CAT);
1717     }
1718 }
1719
1720 static void
1721 regexp (void)
1722 {
1723   branch();
1724   while (tok == OR)
1725     {
1726       tok = lex();
1727       branch();
1728       addtok(OR);
1729     }
1730 }
1731
1732 /* Main entry point for the parser.  S is a string to be parsed, len is the
1733    length of the string, so s can include NUL characters.  D is a pointer to
1734    the struct dfa to parse into. */
1735 void
1736 dfaparse (char const *s, size_t len, struct dfa *d)
1737 {
1738   dfa = d;
1739   lexptr = s;
1740   lexleft = len;
1741   lasttok = END;
1742   laststart = 1;
1743   parens = 0;
1744 #ifdef LC_COLLATE
1745   hard_LC_COLLATE = hard_locale (LC_COLLATE);
1746 #endif
1747 #if MBS_SUPPORT
1748   if (MB_CUR_MAX > 1)
1749     {
1750       cur_mb_len = 0;
1751       memset(&mbs, 0, sizeof mbs);
1752     }
1753 #endif /* MBS_SUPPORT  */
1754
1755   if (! syntax_bits_set)
1756     dfaerror(_("no syntax specified"));
1757
1758   tok = lex();
1759   depth = d->depth;
1760
1761   regexp();
1762
1763   if (tok != END)
1764     dfaerror(_("unbalanced )"));
1765
1766   addtok(END - d->nregexps);
1767   addtok(CAT);
1768
1769   if (d->nregexps)
1770     addtok(OR);
1771
1772   ++d->nregexps;
1773 }
1774
1775 /* Some primitives for operating on sets of positions. */
1776
1777 /* Copy one set to another; the destination must be large enough. */
1778 static void
1779 copy (position_set const *src, position_set *dst)
1780 {
1781   int i;
1782
1783   for (i = 0; i < src->nelem; ++i)
1784     dst->elems[i] = src->elems[i];
1785   dst->nelem = src->nelem;
1786 }
1787
1788 /* Insert a position in a set.  Position sets are maintained in sorted
1789    order according to index.  If position already exists in the set with
1790    the same index then their constraints are logically or'd together.
1791    S->elems must point to an array large enough to hold the resulting set. */
1792 static void
1793 insert (position p, position_set *s)
1794 {
1795   int count = s->nelem;
1796   int lo = 0, hi = count;
1797   while (lo < hi)
1798     {
1799       int mid = ((unsigned) lo + (unsigned) hi) >> 1;
1800       if (s->elems[mid].index < p.index)
1801         lo = mid + 1;
1802       else
1803         hi = mid;
1804     }
1805
1806   if (lo < count && p.index == s->elems[lo].index)
1807     s->elems[lo].constraint |= p.constraint;
1808   else
1809     {
1810       int i;
1811       for (i = count; i > lo; i--)
1812         s->elems[i] = s->elems[i - 1];
1813       s->elems[lo] = p;
1814       ++s->nelem;
1815     }
1816 }
1817
1818 /* Merge two sets of positions into a third.  The result is exactly as if
1819    the positions of both sets were inserted into an initially empty set. */
1820 static void
1821 merge (position_set const *s1, position_set const *s2, position_set *m)
1822 {
1823   int i = 0, j = 0;
1824
1825   m->nelem = 0;
1826   while (i < s1->nelem && j < s2->nelem)
1827     if (s1->elems[i].index > s2->elems[j].index)
1828       m->elems[m->nelem++] = s1->elems[i++];
1829     else if (s1->elems[i].index < s2->elems[j].index)
1830       m->elems[m->nelem++] = s2->elems[j++];
1831     else
1832       {
1833         m->elems[m->nelem] = s1->elems[i++];
1834         m->elems[m->nelem++].constraint |= s2->elems[j++].constraint;
1835       }
1836   while (i < s1->nelem)
1837     m->elems[m->nelem++] = s1->elems[i++];
1838   while (j < s2->nelem)
1839     m->elems[m->nelem++] = s2->elems[j++];
1840 }
1841
1842 /* Delete a position from a set. */
1843 static void
1844 delete (position p, position_set *s)
1845 {
1846   int i;
1847
1848   for (i = 0; i < s->nelem; ++i)
1849     if (p.index == s->elems[i].index)
1850       break;
1851   if (i < s->nelem)
1852     for (--s->nelem; i < s->nelem; ++i)
1853       s->elems[i] = s->elems[i + 1];
1854 }
1855
1856 /* Find the index of the state corresponding to the given position set with
1857    the given preceding context, or create a new state if there is no such
1858    state.  Newline and letter tell whether we got here on a newline or
1859    letter, respectively. */
1860 static int
1861 state_index (struct dfa *d, position_set const *s, int newline, int letter)
1862 {
1863   int hash = 0;
1864   int constraint;
1865   int i, j;
1866
1867   newline = newline ? 1 : 0;
1868   letter = letter ? 1 : 0;
1869
1870   for (i = 0; i < s->nelem; ++i)
1871     hash ^= s->elems[i].index + s->elems[i].constraint;
1872
1873   /* Try to find a state that exactly matches the proposed one. */
1874   for (i = 0; i < d->sindex; ++i)
1875     {
1876       if (hash != d->states[i].hash || s->nelem != d->states[i].elems.nelem
1877           || newline != d->states[i].newline || letter != d->states[i].letter)
1878         continue;
1879       for (j = 0; j < s->nelem; ++j)
1880         if (s->elems[j].constraint
1881             != d->states[i].elems.elems[j].constraint
1882             || s->elems[j].index != d->states[i].elems.elems[j].index)
1883           break;
1884       if (j == s->nelem)
1885         return i;
1886     }
1887
1888   /* We'll have to create a new state. */
1889   REALLOC_IF_NECESSARY(d->states, dfa_state, d->salloc, d->sindex);
1890   d->states[i].hash = hash;
1891   MALLOC(d->states[i].elems.elems, position, s->nelem);
1892   copy(s, &d->states[i].elems);
1893   d->states[i].newline = newline;
1894   d->states[i].letter = letter;
1895   d->states[i].backref = 0;
1896   d->states[i].constraint = 0;
1897   d->states[i].first_end = 0;
1898 #if MBS_SUPPORT
1899   d->states[i].mbps.nelem = 0;
1900   d->states[i].mbps.elems = NULL;
1901 #endif
1902   for (j = 0; j < s->nelem; ++j)
1903     if (d->tokens[s->elems[j].index] < 0)
1904       {
1905         constraint = s->elems[j].constraint;
1906         if (SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 0)
1907             || SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 1)
1908             || SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 0)
1909             || SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 1))
1910           d->states[i].constraint |= constraint;
1911         if (! d->states[i].first_end)
1912           d->states[i].first_end = d->tokens[s->elems[j].index];
1913       }
1914     else if (d->tokens[s->elems[j].index] == BACKREF)
1915       {
1916         d->states[i].constraint = NO_CONSTRAINT;
1917         d->states[i].backref = 1;
1918       }
1919
1920   ++d->sindex;
1921
1922   return i;
1923 }
1924
1925 /* Find the epsilon closure of a set of positions.  If any position of the set
1926    contains a symbol that matches the empty string in some context, replace
1927    that position with the elements of its follow labeled with an appropriate
1928    constraint.  Repeat exhaustively until no funny positions are left.
1929    S->elems must be large enough to hold the result. */
1930 static void
1931 epsclosure (position_set *s, struct dfa const *d)
1932 {
1933   int i, j;
1934   char *visited;        /* array of booleans, enough to use char, not int */
1935   position p, old;
1936
1937   CALLOC(visited, char, d->tindex);
1938
1939   for (i = 0; i < s->nelem; ++i)
1940     if (d->tokens[s->elems[i].index] >= NOTCHAR
1941         && d->tokens[s->elems[i].index] != BACKREF
1942 #if MBS_SUPPORT
1943         && d->tokens[s->elems[i].index] != ANYCHAR
1944         && d->tokens[s->elems[i].index] != MBCSET
1945 #endif
1946         && d->tokens[s->elems[i].index] < CSET)
1947       {
1948         old = s->elems[i];
1949         p.constraint = old.constraint;
1950         delete(s->elems[i], s);
1951         if (visited[old.index])
1952           {
1953             --i;
1954             continue;
1955           }
1956         visited[old.index] = 1;
1957         switch (d->tokens[old.index])
1958           {
1959           case BEGLINE:
1960             p.constraint &= BEGLINE_CONSTRAINT;
1961             break;
1962           case ENDLINE:
1963             p.constraint &= ENDLINE_CONSTRAINT;
1964             break;
1965           case BEGWORD:
1966             p.constraint &= BEGWORD_CONSTRAINT;
1967             break;
1968           case ENDWORD:
1969             p.constraint &= ENDWORD_CONSTRAINT;
1970             break;
1971           case LIMWORD:
1972             p.constraint &= LIMWORD_CONSTRAINT;
1973             break;
1974           case NOTLIMWORD:
1975             p.constraint &= NOTLIMWORD_CONSTRAINT;
1976             break;
1977           default:
1978             break;
1979           }
1980         for (j = 0; j < d->follows[old.index].nelem; ++j)
1981           {
1982             p.index = d->follows[old.index].elems[j].index;
1983             insert(p, s);
1984           }
1985         /* Force rescan to start at the beginning. */
1986         i = -1;
1987       }
1988
1989   free(visited);
1990 }
1991
1992 /* Perform bottom-up analysis on the parse tree, computing various functions.
1993    Note that at this point, we're pretending constructs like \< are real
1994    characters rather than constraints on what can follow them.
1995
1996    Nullable:  A node is nullable if it is at the root of a regexp that can
1997    match the empty string.
1998    *  EMPTY leaves are nullable.
1999    * No other leaf is nullable.
2000    * A QMARK or STAR node is nullable.
2001    * A PLUS node is nullable if its argument is nullable.
2002    * A CAT node is nullable if both its arguments are nullable.
2003    * An OR node is nullable if either argument is nullable.
2004
2005    Firstpos:  The firstpos of a node is the set of positions (nonempty leaves)
2006    that could correspond to the first character of a string matching the
2007    regexp rooted at the given node.
2008    * EMPTY leaves have empty firstpos.
2009    * The firstpos of a nonempty leaf is that leaf itself.
2010    * The firstpos of a QMARK, STAR, or PLUS node is the firstpos of its
2011      argument.
2012    * The firstpos of a CAT node is the firstpos of the left argument, union
2013      the firstpos of the right if the left argument is nullable.
2014    * The firstpos of an OR node is the union of firstpos of each argument.
2015
2016    Lastpos:  The lastpos of a node is the set of positions that could
2017    correspond to the last character of a string matching the regexp at
2018    the given node.
2019    * EMPTY leaves have empty lastpos.
2020    * The lastpos of a nonempty leaf is that leaf itself.
2021    * The lastpos of a QMARK, STAR, or PLUS node is the lastpos of its
2022      argument.
2023    * The lastpos of a CAT node is the lastpos of its right argument, union
2024      the lastpos of the left if the right argument is nullable.
2025    * The lastpos of an OR node is the union of the lastpos of each argument.
2026
2027    Follow:  The follow of a position is the set of positions that could
2028    correspond to the character following a character matching the node in
2029    a string matching the regexp.  At this point we consider special symbols
2030    that match the empty string in some context to be just normal characters.
2031    Later, if we find that a special symbol is in a follow set, we will
2032    replace it with the elements of its follow, labeled with an appropriate
2033    constraint.
2034    * Every node in the firstpos of the argument of a STAR or PLUS node is in
2035      the follow of every node in the lastpos.
2036    * Every node in the firstpos of the second argument of a CAT node is in
2037      the follow of every node in the lastpos of the first argument.
2038
2039    Because of the postfix representation of the parse tree, the depth-first
2040    analysis is conveniently done by a linear scan with the aid of a stack.
2041    Sets are stored as arrays of the elements, obeying a stack-like allocation
2042    scheme; the number of elements in each set deeper in the stack can be
2043    used to determine the address of a particular set's array. */
2044 void
2045 dfaanalyze (struct dfa *d, int searchflag)
2046 {
2047   int *nullable;                /* Nullable stack. */
2048   int *nfirstpos;               /* Element count stack for firstpos sets. */
2049   position *firstpos;           /* Array where firstpos elements are stored. */
2050   int *nlastpos;                /* Element count stack for lastpos sets. */
2051   position *lastpos;            /* Array where lastpos elements are stored. */
2052   int *nalloc;                  /* Sizes of arrays allocated to follow sets. */
2053   position_set tmp;             /* Temporary set for merging sets. */
2054   position_set merged;          /* Result of merging sets. */
2055   int wants_newline;            /* True if some position wants newline info. */
2056   int *o_nullable;
2057   int *o_nfirst, *o_nlast;
2058   position *o_firstpos, *o_lastpos;
2059   int i, j;
2060   position *pos;
2061
2062 #ifdef DEBUG
2063   fprintf(stderr, "dfaanalyze:\n");
2064   for (i = 0; i < d->tindex; ++i)
2065     {
2066       fprintf(stderr, " %d:", i);
2067       prtok(d->tokens[i]);
2068     }
2069   putc('\n', stderr);
2070 #endif
2071
2072   d->searchflag = searchflag;
2073
2074   MALLOC(nullable, int, d->depth);
2075   o_nullable = nullable;
2076   MALLOC(nfirstpos, int, d->depth);
2077   o_nfirst = nfirstpos;
2078   MALLOC(firstpos, position, d->nleaves);
2079   o_firstpos = firstpos, firstpos += d->nleaves;
2080   MALLOC(nlastpos, int, d->depth);
2081   o_nlast = nlastpos;
2082   MALLOC(lastpos, position, d->nleaves);
2083   o_lastpos = lastpos, lastpos += d->nleaves;
2084   CALLOC(nalloc, int, d->tindex);
2085   MALLOC(merged.elems, position, d->nleaves);
2086
2087   CALLOC(d->follows, position_set, d->tindex);
2088
2089   for (i = 0; i < d->tindex; ++i)
2090 #ifdef DEBUG
2091     {                           /* Nonsyntactic #ifdef goo... */
2092 #endif
2093     switch (d->tokens[i])
2094       {
2095       case EMPTY:
2096         /* The empty set is nullable. */
2097         *nullable++ = 1;
2098
2099         /* The firstpos and lastpos of the empty leaf are both empty. */
2100         *nfirstpos++ = *nlastpos++ = 0;
2101         break;
2102
2103       case STAR:
2104       case PLUS:
2105         /* Every element in the firstpos of the argument is in the follow
2106            of every element in the lastpos. */
2107         tmp.nelem = nfirstpos[-1];
2108         tmp.elems = firstpos;
2109         pos = lastpos;
2110         for (j = 0; j < nlastpos[-1]; ++j)
2111           {
2112             merge(&tmp, &d->follows[pos[j].index], &merged);
2113             REALLOC_IF_NECESSARY(d->follows[pos[j].index].elems, position,
2114                                  nalloc[pos[j].index], merged.nelem - 1);
2115             copy(&merged, &d->follows[pos[j].index]);
2116           }
2117
2118       case QMARK:
2119         /* A QMARK or STAR node is automatically nullable. */
2120         if (d->tokens[i] != PLUS)
2121           nullable[-1] = 1;
2122         break;
2123
2124       case CAT:
2125         /* Every element in the firstpos of the second argument is in the
2126            follow of every element in the lastpos of the first argument. */
2127         tmp.nelem = nfirstpos[-1];
2128         tmp.elems = firstpos;
2129         pos = lastpos + nlastpos[-1];
2130         for (j = 0; j < nlastpos[-2]; ++j)
2131           {
2132             merge(&tmp, &d->follows[pos[j].index], &merged);
2133             REALLOC_IF_NECESSARY(d->follows[pos[j].index].elems, position,
2134                                  nalloc[pos[j].index], merged.nelem - 1);
2135             copy(&merged, &d->follows[pos[j].index]);
2136           }
2137
2138         /* The firstpos of a CAT node is the firstpos of the first argument,
2139            union that of the second argument if the first is nullable. */
2140         if (nullable[-2])
2141           nfirstpos[-2] += nfirstpos[-1];
2142         else
2143           firstpos += nfirstpos[-1];
2144         --nfirstpos;
2145
2146         /* The lastpos of a CAT node is the lastpos of the second argument,
2147            union that of the first argument if the second is nullable. */
2148         if (nullable[-1])
2149           nlastpos[-2] += nlastpos[-1];
2150         else
2151           {
2152             pos = lastpos + nlastpos[-2];
2153             for (j = nlastpos[-1] - 1; j >= 0; --j)
2154               pos[j] = lastpos[j];
2155             lastpos += nlastpos[-2];
2156             nlastpos[-2] = nlastpos[-1];
2157           }
2158         --nlastpos;
2159
2160         /* A CAT node is nullable if both arguments are nullable. */
2161         nullable[-2] = nullable[-1] && nullable[-2];
2162         --nullable;
2163         break;
2164
2165       case OR:
2166         /* The firstpos is the union of the firstpos of each argument. */
2167         nfirstpos[-2] += nfirstpos[-1];
2168         --nfirstpos;
2169
2170         /* The lastpos is the union of the lastpos of each argument. */
2171         nlastpos[-2] += nlastpos[-1];
2172         --nlastpos;
2173
2174         /* An OR node is nullable if either argument is nullable. */
2175         nullable[-2] = nullable[-1] || nullable[-2];
2176         --nullable;
2177         break;
2178
2179       default:
2180         /* Anything else is a nonempty position.  (Note that special
2181            constructs like \< are treated as nonempty strings here;
2182            an "epsilon closure" effectively makes them nullable later.
2183            Backreferences have to get a real position so we can detect
2184            transitions on them later.  But they are nullable. */
2185         *nullable++ = d->tokens[i] == BACKREF;
2186
2187         /* This position is in its own firstpos and lastpos. */
2188         *nfirstpos++ = *nlastpos++ = 1;
2189         --firstpos, --lastpos;
2190         firstpos->index = lastpos->index = i;
2191         firstpos->constraint = lastpos->constraint = NO_CONSTRAINT;
2192
2193         /* Allocate the follow set for this position. */
2194         nalloc[i] = 1;
2195         MALLOC(d->follows[i].elems, position, nalloc[i]);
2196         break;
2197       }
2198 #ifdef DEBUG
2199     /* ... balance the above nonsyntactic #ifdef goo... */
2200       fprintf(stderr, "node %d:", i);
2201       prtok(d->tokens[i]);
2202       putc('\n', stderr);
2203       fprintf(stderr, nullable[-1] ? " nullable: yes\n" : " nullable: no\n");
2204       fprintf(stderr, " firstpos:");
2205       for (j = nfirstpos[-1] - 1; j >= 0; --j)
2206         {
2207           fprintf(stderr, " %d:", firstpos[j].index);
2208           prtok(d->tokens[firstpos[j].index]);
2209         }
2210       fprintf(stderr, "\n lastpos:");
2211       for (j = nlastpos[-1] - 1; j >= 0; --j)
2212         {
2213           fprintf(stderr, " %d:", lastpos[j].index);
2214           prtok(d->tokens[lastpos[j].index]);
2215         }
2216       putc('\n', stderr);
2217     }
2218 #endif
2219
2220   /* For each follow set that is the follow set of a real position, replace
2221      it with its epsilon closure. */
2222   for (i = 0; i < d->tindex; ++i)
2223     if (d->tokens[i] < NOTCHAR || d->tokens[i] == BACKREF
2224 #if MBS_SUPPORT
2225         || d->tokens[i] == ANYCHAR
2226         || d->tokens[i] == MBCSET
2227 #endif
2228         || d->tokens[i] >= CSET)
2229       {
2230 #ifdef DEBUG
2231         fprintf(stderr, "follows(%d:", i);
2232         prtok(d->tokens[i]);
2233         fprintf(stderr, "):");
2234         for (j = d->follows[i].nelem - 1; j >= 0; --j)
2235           {
2236             fprintf(stderr, " %d:", d->follows[i].elems[j].index);
2237             prtok(d->tokens[d->follows[i].elems[j].index]);
2238           }
2239         putc('\n', stderr);
2240 #endif
2241         copy(&d->follows[i], &merged);
2242         epsclosure(&merged, d);
2243         if (d->follows[i].nelem < merged.nelem)
2244           REALLOC(d->follows[i].elems, position, merged.nelem);
2245         copy(&merged, &d->follows[i]);
2246       }
2247
2248   /* Get the epsilon closure of the firstpos of the regexp.  The result will
2249      be the set of positions of state 0. */
2250   merged.nelem = 0;
2251   for (i = 0; i < nfirstpos[-1]; ++i)
2252     insert(firstpos[i], &merged);
2253   epsclosure(&merged, d);
2254
2255   /* Check if any of the positions of state 0 will want newline context. */
2256   wants_newline = 0;
2257   for (i = 0; i < merged.nelem; ++i)
2258     if (PREV_NEWLINE_DEPENDENT(merged.elems[i].constraint))
2259       wants_newline = 1;
2260
2261   /* Build the initial state. */
2262   d->salloc = 1;
2263   d->sindex = 0;
2264   MALLOC(d->states, dfa_state, d->salloc);
2265   state_index(d, &merged, wants_newline, 0);
2266
2267   free(o_nullable);
2268   free(o_nfirst);
2269   free(o_firstpos);
2270   free(o_nlast);
2271   free(o_lastpos);
2272   free(nalloc);
2273   free(merged.elems);
2274 }
2275
2276 /* Find, for each character, the transition out of state s of d, and store
2277    it in the appropriate slot of trans.
2278
2279    We divide the positions of s into groups (positions can appear in more
2280    than one group).  Each group is labeled with a set of characters that
2281    every position in the group matches (taking into account, if necessary,
2282    preceding context information of s).  For each group, find the union
2283    of the its elements' follows.  This set is the set of positions of the
2284    new state.  For each character in the group's label, set the transition
2285    on this character to be to a state corresponding to the set's positions,
2286    and its associated backward context information, if necessary.
2287
2288    If we are building a searching matcher, we include the positions of state
2289    0 in every state.
2290
2291    The collection of groups is constructed by building an equivalence-class
2292    partition of the positions of s.
2293
2294    For each position, find the set of characters C that it matches.  Eliminate
2295    any characters from C that fail on grounds of backward context.
2296
2297    Search through the groups, looking for a group whose label L has nonempty
2298    intersection with C.  If L - C is nonempty, create a new group labeled
2299    L - C and having the same positions as the current group, and set L to
2300    the intersection of L and C.  Insert the position in this group, set
2301    C = C - L, and resume scanning.
2302
2303    If after comparing with every group there are characters remaining in C,
2304    create a new group labeled with the characters of C and insert this
2305    position in that group. */
2306 void
2307 dfastate (int s, struct dfa *d, int trans[])
2308 {
2309   position_set *grps;           /* As many as will ever be needed. */
2310   charclass *labels;            /* Labels corresponding to the groups. */
2311   int ngrps = 0;                /* Number of groups actually used. */
2312   position pos;                 /* Current position being considered. */
2313   charclass matches;            /* Set of matching characters. */
2314   int matchesf;                 /* True if matches is nonempty. */
2315   charclass intersect;          /* Intersection with some label set. */
2316   int intersectf;               /* True if intersect is nonempty. */
2317   charclass leftovers;          /* Stuff in the label that didn't match. */
2318   int leftoversf;               /* True if leftovers is nonempty. */
2319   static charclass letters;     /* Set of characters considered letters. */
2320   static charclass newline;     /* Set of characters that aren't newline. */
2321   position_set follows;         /* Union of the follows of some group. */
2322   position_set tmp;             /* Temporary space for merging sets. */
2323   int state;                    /* New state. */
2324   int wants_newline;            /* New state wants to know newline context. */
2325   int state_newline;            /* New state on a newline transition. */
2326   int wants_letter;             /* New state wants to know letter context. */
2327   int state_letter;             /* New state on a letter transition. */
2328   static int initialized;       /* Flag for static initialization. */
2329 #if MBS_SUPPORT
2330   int next_isnt_1st_byte = 0;   /* Flag if we can't add state0.  */
2331 #endif
2332   int i, j, k;
2333
2334   grps = xnmalloc (NOTCHAR, sizeof *grps);
2335   labels = xnmalloc (NOTCHAR, sizeof *labels);
2336
2337   /* Initialize the set of letters, if necessary. */
2338   if (! initialized)
2339     {
2340       initialized = 1;
2341       for (i = 0; i < NOTCHAR; ++i)
2342         if (IS_WORD_CONSTITUENT(i))
2343           setbit(i, letters);
2344       setbit(eolbyte, newline);
2345     }
2346
2347   zeroset(matches);
2348
2349   for (i = 0; i < d->states[s].elems.nelem; ++i)
2350     {
2351       pos = d->states[s].elems.elems[i];
2352       if (d->tokens[pos.index] >= 0 && d->tokens[pos.index] < NOTCHAR)
2353         setbit(d->tokens[pos.index], matches);
2354       else if (d->tokens[pos.index] >= CSET)
2355         copyset(d->charclasses[d->tokens[pos.index] - CSET], matches);
2356 #if MBS_SUPPORT
2357       else if (d->tokens[pos.index] == ANYCHAR
2358                || d->tokens[pos.index] == MBCSET)
2359       /* MB_CUR_MAX > 1  */
2360         {
2361           /* ANYCHAR and MBCSET must match with a single character, so we
2362              must put it to d->states[s].mbps, which contains the positions
2363              which can match with a single character not a byte.  */
2364           if (d->states[s].mbps.nelem == 0)
2365             {
2366               MALLOC(d->states[s].mbps.elems, position,
2367                      d->states[s].elems.nelem);
2368             }
2369           insert(pos, &(d->states[s].mbps));
2370           continue;
2371         }
2372 #endif /* MBS_SUPPORT */
2373       else
2374         continue;
2375
2376       /* Some characters may need to be eliminated from matches because
2377          they fail in the current context. */
2378       if (pos.constraint != 0xFF)
2379         {
2380           if (! MATCHES_NEWLINE_CONTEXT(pos.constraint,
2381                                          d->states[s].newline, 1))
2382             clrbit(eolbyte, matches);
2383           if (! MATCHES_NEWLINE_CONTEXT(pos.constraint,
2384                                          d->states[s].newline, 0))
2385             for (j = 0; j < CHARCLASS_INTS; ++j)
2386               matches[j] &= newline[j];
2387           if (! MATCHES_LETTER_CONTEXT(pos.constraint,
2388                                         d->states[s].letter, 1))
2389             for (j = 0; j < CHARCLASS_INTS; ++j)
2390               matches[j] &= ~letters[j];
2391           if (! MATCHES_LETTER_CONTEXT(pos.constraint,
2392                                         d->states[s].letter, 0))
2393             for (j = 0; j < CHARCLASS_INTS; ++j)
2394               matches[j] &= letters[j];
2395
2396           /* If there are no characters left, there's no point in going on. */
2397           for (j = 0; j < CHARCLASS_INTS && !matches[j]; ++j)
2398             continue;
2399           if (j == CHARCLASS_INTS)
2400             continue;
2401         }
2402
2403       for (j = 0; j < ngrps; ++j)
2404         {
2405           /* If matches contains a single character only, and the current
2406              group's label doesn't contain that character, go on to the
2407              next group. */
2408           if (d->tokens[pos.index] >= 0 && d->tokens[pos.index] < NOTCHAR
2409               && !tstbit(d->tokens[pos.index], labels[j]))
2410             continue;
2411
2412           /* Check if this group's label has a nonempty intersection with
2413              matches. */
2414           intersectf = 0;
2415           for (k = 0; k < CHARCLASS_INTS; ++k)
2416             (intersect[k] = matches[k] & labels[j][k]) ? (intersectf = 1) : 0;
2417           if (! intersectf)
2418             continue;
2419
2420           /* It does; now find the set differences both ways. */
2421           leftoversf = matchesf = 0;
2422           for (k = 0; k < CHARCLASS_INTS; ++k)
2423             {
2424               /* Even an optimizing compiler can't know this for sure. */
2425               int match = matches[k], label = labels[j][k];
2426
2427               (leftovers[k] = ~match & label) ? (leftoversf = 1) : 0;
2428               (matches[k] = match & ~label) ? (matchesf = 1) : 0;
2429             }
2430
2431           /* If there were leftovers, create a new group labeled with them. */
2432           if (leftoversf)
2433             {
2434               copyset(leftovers, labels[ngrps]);
2435               copyset(intersect, labels[j]);
2436               MALLOC(grps[ngrps].elems, position, d->nleaves);
2437               copy(&grps[j], &grps[ngrps]);
2438               ++ngrps;
2439             }
2440
2441           /* Put the position in the current group.  Note that there is no
2442              reason to call insert() here. */
2443           grps[j].elems[grps[j].nelem++] = pos;
2444
2445           /* If every character matching the current position has been
2446              accounted for, we're done. */
2447           if (! matchesf)
2448             break;
2449         }
2450
2451       /* If we've passed the last group, and there are still characters
2452          unaccounted for, then we'll have to create a new group. */
2453       if (j == ngrps)
2454         {
2455           copyset(matches, labels[ngrps]);
2456           zeroset(matches);
2457           MALLOC(grps[ngrps].elems, position, d->nleaves);
2458           grps[ngrps].nelem = 1;
2459           grps[ngrps].elems[0] = pos;
2460           ++ngrps;
2461         }
2462     }
2463
2464   MALLOC(follows.elems, position, d->nleaves);
2465   MALLOC(tmp.elems, position, d->nleaves);
2466
2467   /* If we are a searching matcher, the default transition is to a state
2468      containing the positions of state 0, otherwise the default transition
2469      is to fail miserably. */
2470   if (d->searchflag)
2471     {
2472       wants_newline = 0;
2473       wants_letter = 0;
2474       for (i = 0; i < d->states[0].elems.nelem; ++i)
2475         {
2476           if (PREV_NEWLINE_DEPENDENT(d->states[0].elems.elems[i].constraint))
2477             wants_newline = 1;
2478           if (PREV_LETTER_DEPENDENT(d->states[0].elems.elems[i].constraint))
2479             wants_letter = 1;
2480         }
2481       copy(&d->states[0].elems, &follows);
2482       state = state_index(d, &follows, 0, 0);
2483       if (wants_newline)
2484         state_newline = state_index(d, &follows, 1, 0);
2485       else
2486         state_newline = state;
2487       if (wants_letter)
2488         state_letter = state_index(d, &follows, 0, 1);
2489       else
2490         state_letter = state;
2491       for (i = 0; i < NOTCHAR; ++i)
2492         trans[i] = (IS_WORD_CONSTITUENT(i)) ? state_letter : state;
2493       trans[eolbyte] = state_newline;
2494     }
2495   else
2496     for (i = 0; i < NOTCHAR; ++i)
2497       trans[i] = -1;
2498
2499   for (i = 0; i < ngrps; ++i)
2500     {
2501       follows.nelem = 0;
2502
2503       /* Find the union of the follows of the positions of the group.
2504          This is a hideously inefficient loop.  Fix it someday. */
2505       for (j = 0; j < grps[i].nelem; ++j)
2506         for (k = 0; k < d->follows[grps[i].elems[j].index].nelem; ++k)
2507           insert(d->follows[grps[i].elems[j].index].elems[k], &follows);
2508
2509 #if MBS_SUPPORT
2510       if (d->mb_cur_max > 1)
2511         {
2512           /* If a token in follows.elems is not 1st byte of a multibyte
2513              character, or the states of follows must accept the bytes
2514              which are not 1st byte of the multibyte character.
2515              Then, if a state of follows encounter a byte, it must not be
2516              a 1st byte of a multibyte character nor single byte character.
2517              We cansel to add state[0].follows to next state, because
2518              state[0] must accept 1st-byte
2519
2520              For example, we assume <sb a> is a certain single byte
2521              character, <mb A> is a certain multibyte character, and the
2522              codepoint of <sb a> equals the 2nd byte of the codepoint of
2523              <mb A>.
2524              When state[0] accepts <sb a>, state[i] transit to state[i+1]
2525              by accepting accepts 1st byte of <mb A>, and state[i+1]
2526              accepts 2nd byte of <mb A>, if state[i+1] encounter the
2527              codepoint of <sb a>, it must not be <sb a> but 2nd byte of
2528              <mb A>, so we can not add state[0].  */
2529
2530           next_isnt_1st_byte = 0;
2531           for (j = 0; j < follows.nelem; ++j)
2532             {
2533               if (!(d->multibyte_prop[follows.elems[j].index] & 1))
2534                 {
2535                   next_isnt_1st_byte = 1;
2536                   break;
2537                 }
2538             }
2539         }
2540 #endif
2541
2542       /* If we are building a searching matcher, throw in the positions
2543          of state 0 as well. */
2544 #if MBS_SUPPORT
2545       if (d->searchflag && (d->mb_cur_max == 1 || !next_isnt_1st_byte))
2546 #else
2547       if (d->searchflag)
2548 #endif
2549         for (j = 0; j < d->states[0].elems.nelem; ++j)
2550           insert(d->states[0].elems.elems[j], &follows);
2551
2552       /* Find out if the new state will want any context information. */
2553       wants_newline = 0;
2554       if (tstbit(eolbyte, labels[i]))
2555         for (j = 0; j < follows.nelem; ++j)
2556           if (PREV_NEWLINE_DEPENDENT(follows.elems[j].constraint))
2557             wants_newline = 1;
2558
2559       wants_letter = 0;
2560       for (j = 0; j < CHARCLASS_INTS; ++j)
2561         if (labels[i][j] & letters[j])
2562           break;
2563       if (j < CHARCLASS_INTS)
2564         for (j = 0; j < follows.nelem; ++j)
2565           if (PREV_LETTER_DEPENDENT(follows.elems[j].constraint))
2566             wants_letter = 1;
2567
2568       /* Find the state(s) corresponding to the union of the follows. */
2569       state = state_index(d, &follows, 0, 0);
2570       if (wants_newline)
2571         state_newline = state_index(d, &follows, 1, 0);
2572       else
2573         state_newline = state;
2574       if (wants_letter)
2575         state_letter = state_index(d, &follows, 0, 1);
2576       else
2577         state_letter = state;
2578
2579       /* Set the transitions for each character in the current label. */
2580       for (j = 0; j < CHARCLASS_INTS; ++j)
2581         for (k = 0; k < INTBITS; ++k)
2582           if (labels[i][j] & 1 << k)
2583             {
2584               int c = j * INTBITS + k;
2585
2586               if (c == eolbyte)
2587                 trans[c] = state_newline;
2588               else if (IS_WORD_CONSTITUENT(c))
2589                 trans[c] = state_letter;
2590               else if (c < NOTCHAR)
2591                 trans[c] = state;
2592             }
2593     }
2594
2595   for (i = 0; i < ngrps; ++i)
2596     free(grps[i].elems);
2597   free(follows.elems);
2598   free(tmp.elems);
2599   free(grps);
2600   free(labels);
2601 }
2602
2603 /* Some routines for manipulating a compiled dfa's transition tables.
2604    Each state may or may not have a transition table; if it does, and it
2605    is a non-accepting state, then d->trans[state] points to its table.
2606    If it is an accepting state then d->fails[state] points to its table.
2607    If it has no table at all, then d->trans[state] is NULL.
2608    TODO: Improve this comment, get rid of the unnecessary redundancy. */
2609
2610 static void
2611 build_state (int s, struct dfa *d)
2612 {
2613   int *trans;                   /* The new transition table. */
2614   int i;
2615
2616   /* Set an upper limit on the number of transition tables that will ever
2617      exist at once.  1024 is arbitrary.  The idea is that the frequently
2618      used transition tables will be quickly rebuilt, whereas the ones that
2619      were only needed once or twice will be cleared away. */
2620   if (d->trcount >= 1024)
2621     {
2622       for (i = 0; i < d->tralloc; ++i)
2623         {
2624           free(d->trans[i]);
2625           free(d->fails[i]);
2626           d->trans[i] = d->fails[i] = NULL;
2627         }
2628       d->trcount = 0;
2629     }
2630
2631   ++d->trcount;
2632
2633   /* Set up the success bits for this state. */
2634   d->success[s] = 0;
2635   if (ACCEPTS_IN_CONTEXT(d->states[s].newline, 1, d->states[s].letter, 0,
2636       s, *d))
2637     d->success[s] |= 4;
2638   if (ACCEPTS_IN_CONTEXT(d->states[s].newline, 0, d->states[s].letter, 1,
2639       s, *d))
2640     d->success[s] |= 2;
2641   if (ACCEPTS_IN_CONTEXT(d->states[s].newline, 0, d->states[s].letter, 0,
2642       s, *d))
2643     d->success[s] |= 1;
2644
2645   MALLOC(trans, int, NOTCHAR);
2646   dfastate(s, d, trans);
2647
2648   /* Now go through the new transition table, and make sure that the trans
2649      and fail arrays are allocated large enough to hold a pointer for the
2650      largest state mentioned in the table. */
2651   for (i = 0; i < NOTCHAR; ++i)
2652     if (trans[i] >= d->tralloc)
2653       {
2654         int oldalloc = d->tralloc;
2655
2656         while (trans[i] >= d->tralloc)
2657           d->tralloc *= 2;
2658         REALLOC(d->realtrans, int *, d->tralloc + 1);
2659         d->trans = d->realtrans + 1;
2660         REALLOC(d->fails, int *, d->tralloc);
2661         REALLOC(d->success, int, d->tralloc);
2662         REALLOC(d->newlines, int, d->tralloc);
2663         while (oldalloc < d->tralloc)
2664           {
2665             d->trans[oldalloc] = NULL;
2666             d->fails[oldalloc++] = NULL;
2667           }
2668       }
2669
2670   /* Keep the newline transition in a special place so we can use it as
2671      a sentinel. */
2672   d->newlines[s] = trans[eolbyte];
2673   trans[eolbyte] = -1;
2674
2675   if (ACCEPTING(s, *d))
2676     d->fails[s] = trans;
2677   else
2678     d->trans[s] = trans;
2679 }
2680
2681 static void
2682 build_state_zero (struct dfa *d)
2683 {
2684   d->tralloc = 1;
2685   d->trcount = 0;
2686   CALLOC(d->realtrans, int *, d->tralloc + 1);
2687   d->trans = d->realtrans + 1;
2688   CALLOC(d->fails, int *, d->tralloc);
2689   MALLOC(d->success, int, d->tralloc);
2690   MALLOC(d->newlines, int, d->tralloc);
2691   build_state(0, d);
2692 }
2693
2694 #if MBS_SUPPORT
2695 /* Multibyte character handling sub-routines for dfaexec.  */
2696
2697 /* Initial state may encounter the byte which is not a single byte character
2698    nor 1st byte of a multibyte character.  But it is incorrect for initial
2699    state to accept such a byte.
2700    For example, in sjis encoding the regular expression like "\\" accepts
2701    the codepoint 0x5c, but should not accept the 2nd byte of the codepoint
2702    0x815c. Then Initial state must skip the bytes which are not a single byte
2703    character nor 1st byte of a multibyte character.  */
2704 #define SKIP_REMAINS_MB_IF_INITIAL_STATE(s, p)          \
2705   if (s == 0)                                           \
2706     {                                                   \
2707       while (inputwcs[p - buf_begin] == 0               \
2708             && mblen_buf[p - buf_begin] > 0             \
2709             && (unsigned char const *) p < buf_end)     \
2710         ++p;                                            \
2711       if ((char *) p >= end)                            \
2712         {                                               \
2713           free(mblen_buf);                              \
2714           free(inputwcs);                               \
2715           *end = saved_end;                             \
2716           return NULL;                                  \
2717         }                                               \
2718     }
2719
2720 static void
2721 realloc_trans_if_necessary(struct dfa *d, int new_state)
2722 {
2723   /* Make sure that the trans and fail arrays are allocated large enough
2724      to hold a pointer for the new state. */
2725   if (new_state >= d->tralloc)
2726     {
2727       int oldalloc = d->tralloc;
2728
2729       while (new_state >= d->tralloc)
2730         d->tralloc *= 2;
2731       REALLOC(d->realtrans, int *, d->tralloc + 1);
2732       d->trans = d->realtrans + 1;
2733       REALLOC(d->fails, int *, d->tralloc);
2734       REALLOC(d->success, int, d->tralloc);
2735       REALLOC(d->newlines, int, d->tralloc);
2736       while (oldalloc < d->tralloc)
2737         {
2738           d->trans[oldalloc] = NULL;
2739           d->fails[oldalloc++] = NULL;
2740         }
2741     }
2742 }
2743
2744 /* Return values of transit_state_singlebyte(), and
2745    transit_state_consume_1char.  */
2746 typedef enum
2747 {
2748   TRANSIT_STATE_IN_PROGRESS,    /* State transition has not finished.  */
2749   TRANSIT_STATE_DONE,           /* State transition has finished.  */
2750   TRANSIT_STATE_END_BUFFER      /* Reach the end of the buffer.  */
2751 } status_transit_state;
2752
2753 /* Consume a single byte and transit state from 's' to '*next_state'.
2754    This function is almost same as the state transition routin in dfaexec().
2755    But state transition is done just once, otherwise matching succeed or
2756    reach the end of the buffer.  */
2757 static status_transit_state
2758 transit_state_singlebyte (struct dfa *d, int s, unsigned char const *p,
2759                                   int *next_state)
2760 {
2761   int *t;
2762   int works = s;
2763
2764   status_transit_state rval = TRANSIT_STATE_IN_PROGRESS;
2765
2766   while (rval == TRANSIT_STATE_IN_PROGRESS)
2767     {
2768       if ((t = d->trans[works]) != NULL)
2769         {
2770           works = t[*p];
2771           rval = TRANSIT_STATE_DONE;
2772           if (works < 0)
2773             works = 0;
2774         }
2775       else if (works < 0)
2776         {
2777           if (p == buf_end)
2778             {
2779               /* At the moment, it must not happen.  */
2780               abort ();
2781             }
2782           works = 0;
2783         }
2784       else if (d->fails[works])
2785         {
2786           works = d->fails[works][*p];
2787           rval = TRANSIT_STATE_DONE;
2788         }
2789       else
2790         {
2791           build_state(works, d);
2792         }
2793     }
2794   *next_state = works;
2795   return rval;
2796 }
2797
2798 /* Check whether period can match or not in the current context.  If it can,
2799    return the amount of the bytes with which period can match, otherwise
2800    return 0.
2801    `pos' is the position of the period.  `idx' is the index from the
2802    buf_begin, and it is the current position in the buffer.  */
2803 static int
2804 match_anychar (struct dfa *d, int s, position pos, int idx)
2805 {
2806   int newline = 0;
2807   int letter = 0;
2808   wchar_t wc;
2809   int mbclen;
2810
2811   wc = inputwcs[idx];
2812   mbclen = (mblen_buf[idx] == 0)? 1 : mblen_buf[idx];
2813
2814   /* Check context.  */
2815   if (wc == (wchar_t)eolbyte)
2816     {
2817       if (!(syntax_bits & RE_DOT_NEWLINE))
2818         return 0;
2819       newline = 1;
2820     }
2821   else if (wc == (wchar_t)'\0')
2822     {
2823       if (syntax_bits & RE_DOT_NOT_NULL)
2824         return 0;
2825       newline = 1;
2826     }
2827
2828   if (iswalnum(wc) || wc == L'_')
2829     letter = 1;
2830
2831   if (!SUCCEEDS_IN_CONTEXT(pos.constraint, d->states[s].newline,
2832                            newline, d->states[s].letter, letter))
2833     return 0;
2834
2835   return mbclen;
2836 }
2837
2838 /* Check whether bracket expression can match or not in the current context.
2839    If it can, return the amount of the bytes with which expression can match,
2840    otherwise return 0.
2841    `pos' is the position of the bracket expression.  `idx' is the index
2842    from the buf_begin, and it is the current position in the buffer.  */
2843 static int
2844 match_mb_charset (struct dfa *d, int s, position pos, int idx)
2845 {
2846   int i;
2847   int match;            /* Flag which represent that matching succeed.  */
2848   int match_len;        /* Length of the character (or collating element)
2849                            with which this operator match.  */
2850   int op_len;           /* Length of the operator.  */
2851   char buffer[128];
2852   wchar_t wcbuf[6];
2853
2854   /* Pointer to the structure to which we are currently refering.  */
2855   struct mb_char_classes *work_mbc;
2856
2857   int newline = 0;
2858   int letter = 0;
2859   wchar_t wc;           /* Current refering character.  */
2860
2861   wc = inputwcs[idx];
2862
2863   /* Check context.  */
2864   if (wc == (wchar_t)eolbyte)
2865     {
2866       if (!(syntax_bits & RE_DOT_NEWLINE))
2867         return 0;
2868       newline = 1;
2869     }
2870   else if (wc == (wchar_t)'\0')
2871     {
2872       if (syntax_bits & RE_DOT_NOT_NULL)
2873         return 0;
2874       newline = 1;
2875     }
2876   if (iswalnum(wc) || wc == L'_')
2877     letter = 1;
2878   if (!SUCCEEDS_IN_CONTEXT(pos.constraint, d->states[s].newline,
2879                            newline, d->states[s].letter, letter))
2880     return 0;
2881
2882   /* Assign the current refering operator to work_mbc.  */
2883   work_mbc = &(d->mbcsets[(d->multibyte_prop[pos.index]) >> 2]);
2884   match = !work_mbc->invert;
2885   match_len = (mblen_buf[idx] == 0)? 1 : mblen_buf[idx];
2886
2887   /* Match in range 0-255?  */
2888   if (wc < NOTCHAR && work_mbc->cset != -1
2889       && tstbit((unsigned char)wc, d->charclasses[work_mbc->cset]))
2890     goto charset_matched;
2891
2892   /* match with a character class?  */
2893   for (i = 0; i<work_mbc->nch_classes; i++)
2894     {
2895       if (iswctype((wint_t)wc, work_mbc->ch_classes[i]))
2896         goto charset_matched;
2897     }
2898
2899   strncpy(buffer, (char const *) buf_begin + idx, match_len);
2900   buffer[match_len] = '\0';
2901
2902   /* match with an equivalent class?  */
2903   for (i = 0; i<work_mbc->nequivs; i++)
2904     {
2905       op_len = strlen(work_mbc->equivs[i]);
2906       strncpy(buffer, (char const *) buf_begin + idx, op_len);
2907       buffer[op_len] = '\0';
2908       if (strcoll(work_mbc->equivs[i], buffer) == 0)
2909         {
2910           match_len = op_len;
2911           goto charset_matched;
2912         }
2913     }
2914
2915   /* match with a collating element?  */
2916   for (i = 0; i<work_mbc->ncoll_elems; i++)
2917     {
2918       op_len = strlen(work_mbc->coll_elems[i]);
2919       strncpy(buffer, (char const *) buf_begin + idx, op_len);
2920       buffer[op_len] = '\0';
2921
2922       if (strcoll(work_mbc->coll_elems[i], buffer) == 0)
2923         {
2924           match_len = op_len;
2925           goto charset_matched;
2926         }
2927     }
2928
2929   wcbuf[0] = wc;
2930   wcbuf[1] = wcbuf[3] = wcbuf[5] = '\0';
2931
2932   /* match with a range?  */
2933   for (i = 0; i<work_mbc->nranges; i++)
2934     {
2935       wcbuf[2] = work_mbc->range_sts[i];
2936       wcbuf[4] = work_mbc->range_ends[i];
2937
2938       if (wcscoll(wcbuf, wcbuf+2) >= 0 &&
2939           wcscoll(wcbuf+4, wcbuf) >= 0)
2940         goto charset_matched;
2941     }
2942
2943   /* match with a character?  */
2944   for (i = 0; i<work_mbc->nchars; i++)
2945     {
2946       if (wc == work_mbc->chars[i])
2947         goto charset_matched;
2948     }
2949
2950   match = !match;
2951
2952  charset_matched:
2953   return match ? match_len : 0;
2954 }
2955
2956 /* Check each of `d->states[s].mbps.elem' can match or not. Then return the
2957    array which corresponds to `d->states[s].mbps.elem' and each element of
2958    the array contains the amount of the bytes with which the element can
2959    match.
2960    `idx' is the index from the buf_begin, and it is the current position
2961    in the buffer.
2962    Caller MUST free the array which this function return.  */
2963 static int*
2964 check_matching_with_multibyte_ops (struct dfa *d, int s, int idx)
2965 {
2966   int i;
2967   int* rarray;
2968
2969   MALLOC(rarray, int, d->states[s].mbps.nelem);
2970   for (i = 0; i < d->states[s].mbps.nelem; ++i)
2971     {
2972       position pos = d->states[s].mbps.elems[i];
2973       switch(d->tokens[pos.index])
2974         {
2975         case ANYCHAR:
2976           rarray[i] = match_anychar(d, s, pos, idx);
2977           break;
2978         case MBCSET:
2979           rarray[i] = match_mb_charset(d, s, pos, idx);
2980           break;
2981         default:
2982           break; /* can not happen.  */
2983         }
2984     }
2985   return rarray;
2986 }
2987
2988 /* Consume a single character and enumerate all of the positions which can
2989    be next position from the state `s'.
2990    `match_lens' is the input. It can be NULL, but it can also be the output
2991    of check_matching_with_multibyte_ops() for optimization.
2992    `mbclen' and `pps' are the output.  `mbclen' is the length of the
2993    character consumed, and `pps' is the set this function enumerate.  */
2994 static status_transit_state
2995 transit_state_consume_1char (struct dfa *d, int s, unsigned char const **pp,
2996                              int *match_lens, int *mbclen, position_set *pps)
2997 {
2998   int i, j;
2999   int s1, s2;
3000   int* work_mbls;
3001   status_transit_state rs = TRANSIT_STATE_DONE;
3002
3003   /* Calculate the length of the (single/multi byte) character
3004      to which p points.  */
3005   *mbclen = (mblen_buf[*pp - buf_begin] == 0)? 1
3006     : mblen_buf[*pp - buf_begin];
3007
3008   /* Calculate the state which can be reached from the state `s' by
3009      consuming `*mbclen' single bytes from the buffer.  */
3010   s1 = s;
3011   for (i = 0; i < *mbclen; i++)
3012     {
3013       s2 = s1;
3014       rs = transit_state_singlebyte(d, s2, (*pp)++, &s1);
3015     }
3016   /* Copy the positions contained by `s1' to the set `pps'.  */
3017   copy(&(d->states[s1].elems), pps);
3018
3019   /* Check (inputed)match_lens, and initialize if it is NULL.  */
3020   if (match_lens == NULL && d->states[s].mbps.nelem != 0)
3021     work_mbls = check_matching_with_multibyte_ops(d, s, *pp - buf_begin);
3022   else
3023     work_mbls = match_lens;
3024
3025   /* Add all of the positions which can be reached from `s' by consuming
3026      a single character.  */
3027   for (i = 0; i < d->states[s].mbps.nelem ; i++)
3028    {
3029       if (work_mbls[i] == *mbclen)
3030         for (j = 0; j < d->follows[d->states[s].mbps.elems[i].index].nelem;
3031              j++)
3032           insert(d->follows[d->states[s].mbps.elems[i].index].elems[j],
3033                  pps);
3034     }
3035
3036   if (match_lens == NULL && work_mbls != NULL)
3037     free(work_mbls);
3038   return rs;
3039 }
3040
3041 /* Transit state from s, then return new state and update the pointer of the
3042    buffer.  This function is for some operator which can match with a multi-
3043    byte character or a collating element (which may be multi characters).  */
3044 static int
3045 transit_state (struct dfa *d, int s, unsigned char const **pp)
3046 {
3047   int s1;
3048   int mbclen;           /* The length of current input multibyte character. */
3049   int maxlen = 0;
3050   int i, j;
3051   int *match_lens = NULL;
3052   int nelem = d->states[s].mbps.nelem; /* Just a alias.  */
3053   position_set follows;
3054   unsigned char const *p1 = *pp;
3055   wchar_t wc;
3056
3057   if (nelem > 0)
3058     /* This state has (a) multibyte operator(s).
3059        We check whether each of them can match or not.  */
3060     {
3061       /* Note: caller must free the return value of this function.  */
3062       match_lens = check_matching_with_multibyte_ops(d, s, *pp - buf_begin);
3063
3064       for (i = 0; i < nelem; i++)
3065         /* Search the operator which match the longest string,
3066            in this state.  */
3067         {
3068           if (match_lens[i] > maxlen)
3069             maxlen = match_lens[i];
3070         }
3071     }
3072
3073   if (nelem == 0 || maxlen == 0)
3074     /* This state has no multibyte operator which can match.
3075        We need to check only one single byte character.  */
3076     {
3077       status_transit_state rs;
3078       rs = transit_state_singlebyte(d, s, *pp, &s1);
3079
3080       /* We must update the pointer if state transition succeeded.  */
3081       if (rs == TRANSIT_STATE_DONE)
3082         ++*pp;
3083
3084       free(match_lens);
3085       return s1;
3086     }
3087
3088   /* This state has some operators which can match a multibyte character.  */
3089   follows.nelem = 0;
3090   MALLOC(follows.elems, position, d->nleaves);
3091
3092   /* `maxlen' may be longer than the length of a character, because it may
3093      not be a character but a (multi character) collating element.
3094      We enumerate all of the positions which `s' can reach by consuming
3095      `maxlen' bytes.  */
3096   transit_state_consume_1char(d, s, pp, match_lens, &mbclen, &follows);
3097
3098   wc = inputwcs[*pp - mbclen - buf_begin];
3099   s1 = state_index(d, &follows, wc == L'\n', iswalnum(wc));
3100   realloc_trans_if_necessary(d, s1);
3101
3102   while (*pp - p1 < maxlen)
3103     {
3104       follows.nelem = 0;
3105       transit_state_consume_1char(d, s1, pp, NULL, &mbclen, &follows);
3106
3107       for (i = 0; i < nelem ; i++)
3108         {
3109           if (match_lens[i] == *pp - p1)
3110             for (j = 0;
3111                  j < d->follows[d->states[s1].mbps.elems[i].index].nelem; j++)
3112               insert(d->follows[d->states[s1].mbps.elems[i].index].elems[j],
3113                      &follows);
3114         }
3115
3116       wc = inputwcs[*pp - mbclen - buf_begin];
3117       s1 = state_index(d, &follows, wc == L'\n', iswalnum(wc));
3118       realloc_trans_if_necessary(d, s1);
3119     }
3120   free(match_lens);
3121   free(follows.elems);
3122   return s1;
3123 }
3124
3125 #endif /* MBS_SUPPORT */
3126
3127 /* Initialize mblen_buf and inputwcs with data from the next line.  */
3128
3129 static void
3130 prepare_wc_buf (const char *begin, const char *end)
3131 {
3132   unsigned char eol = eolbyte;
3133   size_t remain_bytes, i;
3134
3135   buf_begin = (unsigned char *) begin;
3136
3137   remain_bytes = 0;
3138   for (i = 0; i < end - begin + 1; i++)
3139     {
3140       if (remain_bytes == 0)
3141         {
3142           remain_bytes
3143             = mbrtowc(inputwcs + i, begin + i, end - begin - i + 1, &mbs);
3144           if (remain_bytes < 1
3145               || remain_bytes == (size_t) -1
3146               || remain_bytes == (size_t) -2
3147               || (remain_bytes == 1 && inputwcs[i] == (wchar_t)begin[i]))
3148             {
3149               remain_bytes = 0;
3150               inputwcs[i] = (wchar_t)begin[i];
3151               mblen_buf[i] = 0;
3152               if (begin[i] == eol)
3153                 break;
3154             }
3155           else
3156             {
3157               mblen_buf[i] = remain_bytes;
3158               remain_bytes--;
3159             }
3160         }
3161       else
3162         {
3163           mblen_buf[i] = remain_bytes;
3164           inputwcs[i] = 0;
3165           remain_bytes--;
3166         }
3167     }
3168
3169   buf_end = (unsigned char *) (begin + i);
3170   mblen_buf[i] = 0;
3171   inputwcs[i] = 0; /* sentinel */
3172 }
3173
3174 /* Search through a buffer looking for a match to the given struct dfa.
3175    Find the first occurrence of a string matching the regexp in the
3176    buffer, and the shortest possible version thereof.  Return a pointer to
3177    the first character after the match, or NULL if none is found.  BEGIN
3178    points to the beginning of the buffer, and END points to the first byte
3179    after its end.  Note however that we store a sentinel byte (usually
3180    newline) in *END, so the actual buffer must be one byte longer.
3181    When NEWLINE is nonzero, newlines may appear in the matching string.
3182    If COUNT is non-NULL, increment *COUNT once for each newline processed.
3183    Finally, if BACKREF is non-NULL set *BACKREF to indicate whether we
3184    encountered a back-reference (1) or not (0).  The caller may use this
3185    to decide whether to fall back on a backtracking matcher. */
3186 char *
3187 dfaexec (struct dfa *d, char const *begin, char *end,
3188          int newline, int *count, int *backref)
3189 {
3190   int s, s1, tmp;       /* Current state. */
3191   unsigned char const *p; /* Current input character. */
3192   int **trans, *t;      /* Copy of d->trans so it can be optimized
3193                                    into a register. */
3194   unsigned char eol = eolbyte;  /* Likewise for eolbyte.  */
3195   unsigned char saved_end;
3196   static int sbit[NOTCHAR];     /* Table for anding with d->success. */
3197   static int sbit_init;
3198
3199   if (! sbit_init)
3200     {
3201       unsigned int i;
3202
3203       sbit_init = 1;
3204       for (i = 0; i < NOTCHAR; ++i)
3205         sbit[i] = (IS_WORD_CONSTITUENT(i)) ? 2 : 1;
3206       sbit[eol] = 4;
3207     }
3208
3209   if (! d->tralloc)
3210     build_state_zero(d);
3211
3212   s = s1 = 0;
3213   p = (unsigned char const *) begin;
3214   trans = d->trans;
3215   saved_end = *(unsigned char *) end;
3216   *end = eol;
3217
3218 #if MBS_SUPPORT
3219   if (d->mb_cur_max > 1)
3220     {
3221       MALLOC(mblen_buf, unsigned char, end - begin + 2);
3222       MALLOC(inputwcs, wchar_t, end - begin + 2);
3223       memset(&mbs, 0, sizeof(mbstate_t));
3224       prepare_wc_buf ((const char *) p, end);
3225     }
3226 #endif /* MBS_SUPPORT */
3227
3228   for (;;)
3229     {
3230 #if MBS_SUPPORT
3231       if (d->mb_cur_max > 1)
3232         while ((t = trans[s]))
3233           {
3234             if (p > buf_end)
3235               break;
3236             s1 = s;
3237             SKIP_REMAINS_MB_IF_INITIAL_STATE(s, p);
3238
3239             if (d->states[s].mbps.nelem == 0)
3240               {
3241                 s = t[*p++];
3242                 continue;
3243               }
3244
3245             /* Falling back to the glibc matcher in this case gives
3246                better performance (up to 25% better on [a-z], for
3247                example) and enables support for collating symbols and
3248                equivalence classes.  */
3249             if (backref)
3250               {
3251                 *backref = 1;
3252                 free(mblen_buf);
3253                 free(inputwcs);
3254                 *end = saved_end;
3255                 return (char *) p;
3256               }
3257
3258             /* Can match with a multibyte character (and multi character
3259                collating element).  Transition table might be updated.  */
3260             s = transit_state(d, s, &p);
3261             trans = d->trans;
3262           }
3263       else
3264 #endif /* MBS_SUPPORT */
3265       while ((t = trans[s]) != 0) { /* hand-optimized loop */
3266         s1 = t[*p++];
3267         if ((t = trans[s1]) == 0) {
3268           tmp = s ; s = s1 ; s1 = tmp ; /* swap */
3269           break;
3270         }
3271         s = t[*p++];
3272       }
3273
3274       if (s >= 0 && (char *) p <= end && d->fails[s])
3275         {
3276           if (d->success[s] & sbit[*p])
3277             {
3278               if (backref)
3279                 *backref = (d->states[s].backref != 0);
3280 #if MBS_SUPPORT
3281               if (d->mb_cur_max > 1)
3282                 {
3283                   free(mblen_buf);
3284                   free(inputwcs);
3285                 }
3286 #endif /* MBS_SUPPORT */
3287               *end = saved_end;
3288               return (char *) p;
3289             }
3290
3291           s1 = s;
3292 #if MBS_SUPPORT
3293           if (d->mb_cur_max > 1)
3294             {
3295               /* Can match with a multibyte character (and multicharacter
3296                  collating element).  Transition table might be updated.  */
3297               s = transit_state(d, s, &p);
3298               trans = d->trans;
3299             }
3300           else
3301 #endif /* MBS_SUPPORT */
3302           s = d->fails[s][*p++];
3303           continue;
3304         }
3305
3306       /* If the previous character was a newline, count it. */
3307       if ((char *) p <= end && p[-1] == eol)
3308         {
3309           if (count)
3310             ++*count;
3311
3312 #if MBS_SUPPORT
3313           if (d->mb_cur_max > 1)
3314             prepare_wc_buf ((const char *) p, end);
3315 #endif
3316         }
3317
3318       /* Check if we've run off the end of the buffer. */
3319       if ((char *) p > end)
3320         {
3321 #if MBS_SUPPORT
3322           if (d->mb_cur_max > 1)
3323             {
3324               free(mblen_buf);
3325               free(inputwcs);
3326             }
3327 #endif /* MBS_SUPPORT */
3328           *end = saved_end;
3329           return NULL;
3330         }
3331
3332       if (s >= 0)
3333         {
3334           build_state(s, d);
3335           trans = d->trans;
3336           continue;
3337         }
3338
3339       if (p[-1] == eol && newline)
3340         {
3341           s = d->newlines[s1];
3342           continue;
3343         }
3344
3345       s = 0;
3346     }
3347 }
3348
3349 #if MBS_SUPPORT
3350 static void
3351 free_mbdata (struct dfa *d)
3352 {
3353   unsigned int i;
3354
3355   free(d->multibyte_prop);
3356   d->multibyte_prop = NULL;
3357
3358   for (i = 0; i < d->nmbcsets; ++i)
3359     {
3360       unsigned int j;
3361       struct mb_char_classes *p = &(d->mbcsets[i]);
3362       free(p->chars);
3363       free(p->ch_classes);
3364       free(p->range_sts);
3365       free(p->range_ends);
3366
3367       for (j = 0; j < p->nequivs; ++j)
3368         free(p->equivs[j]);
3369       free(p->equivs);
3370
3371       for (j = 0; j < p->ncoll_elems; ++j)
3372         free(p->coll_elems[j]);
3373       free(p->coll_elems);
3374     }
3375
3376   free(d->mbcsets);
3377   d->mbcsets = NULL;
3378   d->nmbcsets = 0;
3379 }
3380 #endif
3381
3382 /* Initialize the components of a dfa that the other routines don't
3383    initialize for themselves. */
3384 void
3385 dfainit (struct dfa *d)
3386 {
3387   memset (d, 0, sizeof *d);
3388
3389   d->calloc = 1;
3390   MALLOC(d->charclasses, charclass, d->calloc);
3391
3392   d->talloc = 1;
3393   MALLOC(d->tokens, token, d->talloc);
3394
3395 #if MBS_SUPPORT
3396   d->mb_cur_max = MB_CUR_MAX;
3397   if (d->mb_cur_max > 1)
3398     {
3399       d->nmultibyte_prop = 1;
3400       MALLOC(d->multibyte_prop, int, d->nmultibyte_prop);
3401       d->mbcsets_alloc = 1;
3402       MALLOC(d->mbcsets, struct mb_char_classes, d->mbcsets_alloc);
3403     }
3404 #endif
3405 }
3406
3407 #if MBS_SUPPORT
3408 static void
3409 dfaoptimize (struct dfa *d)
3410 {
3411   unsigned int i;
3412   if (!using_utf8())
3413     return;
3414
3415   for (i = 0; i < d->tindex; ++i)
3416     {
3417       switch(d->tokens[i])
3418         {
3419         case ANYCHAR:
3420           /* Lowered.  */
3421           abort ();
3422         case MBCSET:
3423           /* Requires multi-byte algorithm.  */
3424           return;
3425         default:
3426           break;
3427         }
3428     }
3429
3430   free_mbdata (d);
3431   d->mb_cur_max = 1;
3432 }
3433 #endif
3434
3435 /* Parse and analyze a single string of the given length. */
3436 void
3437 dfacomp (char const *s, size_t len, struct dfa *d, int searchflag)
3438 {
3439   dfainit(d);
3440   dfaparse(s, len, d);
3441   dfamust(d);
3442 #if MBS_SUPPORT
3443   dfaoptimize(d);
3444 #endif
3445   dfaanalyze(d, searchflag);
3446 }
3447
3448 /* Free the storage held by the components of a dfa. */
3449 void
3450 dfafree (struct dfa *d)
3451 {
3452   int i;
3453   struct dfamust *dm, *ndm;
3454
3455   free(d->charclasses);
3456   free(d->tokens);
3457
3458 #if MBS_SUPPORT
3459   if (d->mb_cur_max > 1)
3460     free_mbdata(d);
3461 #endif /* MBS_SUPPORT */
3462
3463   for (i = 0; i < d->sindex; ++i) {
3464     free(d->states[i].elems.elems);
3465 #if MBS_SUPPORT
3466     free(d->states[i].mbps.elems);
3467 #endif /* MBS_SUPPORT */
3468   }
3469   free(d->states);
3470   for (i = 0; i < d->tindex; ++i)
3471     free(d->follows[i].elems);
3472   free(d->follows);
3473   for (i = 0; i < d->tralloc; ++i)
3474     {
3475       free(d->trans[i]);
3476       free(d->fails[i]);
3477     }
3478   free(d->realtrans);
3479   free(d->fails);
3480   free(d->newlines);
3481   free(d->success);
3482   for (dm = d->musts; dm; dm = ndm)
3483     {
3484       ndm = dm->next;
3485       free(dm->must);
3486       free(dm);
3487     }
3488 }
3489
3490 /* Having found the postfix representation of the regular expression,
3491    try to find a long sequence of characters that must appear in any line
3492    containing the r.e.
3493    Finding a "longest" sequence is beyond the scope here;
3494    we take an easy way out and hope for the best.
3495    (Take "(ab|a)b"--please.)
3496
3497    We do a bottom-up calculation of sequences of characters that must appear
3498    in matches of r.e.'s represented by trees rooted at the nodes of the postfix
3499    representation:
3500         sequences that must appear at the left of the match ("left")
3501         sequences that must appear at the right of the match ("right")
3502         lists of sequences that must appear somewhere in the match ("in")
3503         sequences that must constitute the match ("is")
3504
3505    When we get to the root of the tree, we use one of the longest of its
3506    calculated "in" sequences as our answer.  The sequence we find is returned in
3507    d->must (where "d" is the single argument passed to "dfamust");
3508    the length of the sequence is returned in d->mustn.
3509
3510    The sequences calculated for the various types of node (in pseudo ANSI c)
3511    are shown below.  "p" is the operand of unary operators (and the left-hand
3512    operand of binary operators); "q" is the right-hand operand of binary
3513    operators.
3514
3515    "ZERO" means "a zero-length sequence" below.
3516
3517         Type    left            right           is              in
3518         ----    ----            -----           --              --
3519         char c  # c             # c             # c             # c
3520
3521         ANYCHAR ZERO            ZERO            ZERO            ZERO
3522
3523         MBCSET  ZERO            ZERO            ZERO            ZERO
3524
3525         CSET    ZERO            ZERO            ZERO            ZERO
3526
3527         STAR    ZERO            ZERO            ZERO            ZERO
3528
3529         QMARK   ZERO            ZERO            ZERO            ZERO
3530
3531         PLUS    p->left         p->right        ZERO            p->in
3532
3533         CAT     (p->is==ZERO)?  (q->is==ZERO)?  (p->is!=ZERO && p->in plus
3534                 p->left :       q->right :      q->is!=ZERO) ?  q->in plus
3535                 p->is##q->left  p->right##q->is p->is##q->is :  p->right##q->left
3536                                                 ZERO
3537
3538         OR      longest common  longest common  (do p->is and   substrings common to
3539                 leading         trailing        q->is have same p->in and q->in
3540                 (sub)sequence   (sub)sequence   length and
3541                 of p->left      of p->right     content) ?
3542                 and q->left     and q->right    p->is : NULL
3543
3544    If there's anything else we recognize in the tree, all four sequences get set
3545    to zero-length sequences.  If there's something we don't recognize in the tree,
3546    we just return a zero-length sequence.
3547
3548    Break ties in favor of infrequent letters (choosing 'zzz' in preference to
3549    'aaa')?
3550
3551    And. . .is it here or someplace that we might ponder "optimizations" such as
3552         egrep 'psi|epsilon'     ->      egrep 'psi'
3553         egrep 'pepsi|epsilon'   ->      egrep 'epsi'
3554                                         (Yes, we now find "epsi" as a "string
3555                                         that must occur", but we might also
3556                                         simplify the *entire* r.e. being sought)
3557         grep '[c]'              ->      grep 'c'
3558         grep '(ab|a)b'          ->      grep 'ab'
3559         grep 'ab*'              ->      grep 'a'
3560         grep 'a*b'              ->      grep 'b'
3561
3562    There are several issues:
3563
3564    Is optimization easy (enough)?
3565
3566    Does optimization actually accomplish anything,
3567    or is the automaton you get from "psi|epsilon" (for example)
3568    the same as the one you get from "psi" (for example)?
3569
3570    Are optimizable r.e.'s likely to be used in real-life situations
3571    (something like 'ab*' is probably unlikely; something like is
3572    'psi|epsilon' is likelier)? */
3573
3574 static char *
3575 icatalloc (char const *old, char const *new)
3576 {
3577   char *result;
3578   size_t oldsize, newsize;
3579
3580   newsize = (new == NULL) ? 0 : strlen(new);
3581   if (old == NULL)
3582     oldsize = 0;
3583   else if (newsize == 0)
3584     return (char *) old;
3585   else  oldsize = strlen(old);
3586   if (old == NULL)
3587     result = malloc(newsize + 1);
3588   else
3589     result = realloc((void *) old, oldsize + newsize + 1);
3590   if (result != NULL && new != NULL)
3591     (void) strcpy(result + oldsize, new);
3592   return result;
3593 }
3594
3595 static char *
3596 icpyalloc (char const *string)
3597 {
3598   return icatalloc (NULL, string);
3599 }
3600
3601 static char *
3602 istrstr (char const *lookin, char const *lookfor)
3603 {
3604   char const *cp;
3605   size_t len;
3606
3607   len = strlen(lookfor);
3608   for (cp = lookin; *cp != '\0'; ++cp)
3609     if (strncmp(cp, lookfor, len) == 0)
3610       return (char *) cp;
3611   return NULL;
3612 }
3613
3614 static void
3615 freelist (char **cpp)
3616 {
3617   int i;
3618
3619   if (cpp == NULL)
3620     return;
3621   for (i = 0; cpp[i] != NULL; ++i)
3622     {
3623       free(cpp[i]);
3624       cpp[i] = NULL;
3625     }
3626 }
3627
3628 static char **
3629 enlist (char **cpp, char *new, size_t len)
3630 {
3631   int i, j;
3632
3633   if (cpp == NULL)
3634     return NULL;
3635   if ((new = icpyalloc(new)) == NULL)
3636     {
3637       freelist(cpp);
3638       return NULL;
3639     }
3640   new[len] = '\0';
3641   /* Is there already something in the list that's new (or longer)? */
3642   for (i = 0; cpp[i] != NULL; ++i)
3643     if (istrstr(cpp[i], new) != NULL)
3644       {
3645         free(new);
3646         return cpp;
3647       }
3648   /* Eliminate any obsoleted strings. */
3649   j = 0;
3650   while (cpp[j] != NULL)
3651     if (istrstr(new, cpp[j]) == NULL)
3652       ++j;
3653     else
3654       {
3655         free(cpp[j]);
3656         if (--i == j)
3657           break;
3658         cpp[j] = cpp[i];
3659         cpp[i] = NULL;
3660       }
3661   /* Add the new string. */
3662   cpp = realloc((char *) cpp, (i + 2) * sizeof *cpp);
3663   if (cpp == NULL)
3664     return NULL;
3665   cpp[i] = new;
3666   cpp[i + 1] = NULL;
3667   return cpp;
3668 }
3669
3670 /* Given pointers to two strings, return a pointer to an allocated
3671    list of their distinct common substrings. Return NULL if something
3672    seems wild. */
3673 static char **
3674 comsubs (char *left, char const *right)
3675 {
3676   char **cpp;
3677   char *lcp;
3678   char *rcp;
3679   size_t i, len;
3680
3681   if (left == NULL || right == NULL)
3682     return NULL;
3683   cpp = malloc(sizeof *cpp);
3684   if (cpp == NULL)
3685     return NULL;
3686   cpp[0] = NULL;
3687   for (lcp = left; *lcp != '\0'; ++lcp)
3688     {
3689       len = 0;
3690       rcp = strchr (right, *lcp);
3691       while (rcp != NULL)
3692         {
3693           for (i = 1; lcp[i] != '\0' && lcp[i] == rcp[i]; ++i)
3694             continue;
3695           if (i > len)
3696             len = i;
3697           rcp = strchr (rcp + 1, *lcp);
3698         }
3699       if (len == 0)
3700         continue;
3701       if ((cpp = enlist(cpp, lcp, len)) == NULL)
3702         break;
3703     }
3704   return cpp;
3705 }
3706
3707 static char **
3708 addlists (char **old, char **new)
3709 {
3710   int i;
3711
3712   if (old == NULL || new == NULL)
3713     return NULL;
3714   for (i = 0; new[i] != NULL; ++i)
3715     {
3716       old = enlist(old, new[i], strlen(new[i]));
3717       if (old == NULL)
3718         break;
3719     }
3720   return old;
3721 }
3722
3723 /* Given two lists of substrings, return a new list giving substrings
3724    common to both. */
3725 static char **
3726 inboth (char **left, char **right)
3727 {
3728   char **both;
3729   char **temp;
3730   int lnum, rnum;
3731
3732   if (left == NULL || right == NULL)
3733     return NULL;
3734   both = malloc(sizeof *both);
3735   if (both == NULL)
3736     return NULL;
3737   both[0] = NULL;
3738   for (lnum = 0; left[lnum] != NULL; ++lnum)
3739     {
3740       for (rnum = 0; right[rnum] != NULL; ++rnum)
3741         {
3742           temp = comsubs(left[lnum], right[rnum]);
3743           if (temp == NULL)
3744             {
3745               freelist(both);
3746               return NULL;
3747             }
3748           both = addlists(both, temp);
3749           freelist(temp);
3750           free(temp);
3751           if (both == NULL)
3752             return NULL;
3753         }
3754     }
3755   return both;
3756 }
3757
3758 typedef struct
3759 {
3760   char **in;
3761   char *left;
3762   char *right;
3763   char *is;
3764 } must;
3765
3766 static void
3767 resetmust (must *mp)
3768 {
3769   mp->left[0] = mp->right[0] = mp->is[0] = '\0';
3770   freelist(mp->in);
3771 }
3772
3773 static void
3774 dfamust (struct dfa *d)
3775 {
3776   must *musts;
3777   must *mp;
3778   char *result;
3779   int ri;
3780   int i;
3781   int exact;
3782   token t;
3783   static must must0;
3784   struct dfamust *dm;
3785   static char empty_string[] = "";
3786
3787   result = empty_string;
3788   exact = 0;
3789   musts = malloc((d->tindex + 1) * sizeof *musts);
3790   if (musts == NULL)
3791     return;
3792   mp = musts;
3793   for (i = 0; i <= d->tindex; ++i)
3794     mp[i] = must0;
3795   for (i = 0; i <= d->tindex; ++i)
3796     {
3797       mp[i].in = malloc(sizeof *mp[i].in);
3798       mp[i].left = malloc(2);
3799       mp[i].right = malloc(2);
3800       mp[i].is = malloc(2);
3801       if (mp[i].in == NULL || mp[i].left == NULL ||
3802           mp[i].right == NULL || mp[i].is == NULL)
3803         goto done;
3804       mp[i].left[0] = mp[i].right[0] = mp[i].is[0] = '\0';
3805       mp[i].in[0] = NULL;
3806     }
3807 #ifdef DEBUG
3808   fprintf(stderr, "dfamust:\n");
3809   for (i = 0; i < d->tindex; ++i)
3810     {
3811       fprintf(stderr, " %d:", i);
3812       prtok(d->tokens[i]);
3813     }
3814   putc('\n', stderr);
3815 #endif
3816   for (ri = 0; ri < d->tindex; ++ri)
3817     {
3818       switch (t = d->tokens[ri])
3819         {
3820         case LPAREN:
3821         case RPAREN:
3822           assert (!"neither LPAREN nor RPAREN may appear here");
3823         case EMPTY:
3824         case BEGLINE:
3825         case ENDLINE:
3826         case BEGWORD:
3827         case ENDWORD:
3828         case LIMWORD:
3829         case NOTLIMWORD:
3830         case BACKREF:
3831           resetmust(mp);
3832           break;
3833         case STAR:
3834         case QMARK:
3835           assert (musts < mp);
3836           --mp;
3837           resetmust(mp);
3838           break;
3839         case OR:
3840           assert (&musts[2] <= mp);
3841           {
3842             char **new;
3843             must *lmp;
3844             must *rmp;
3845             int j, ln, rn, n;
3846
3847             rmp = --mp;
3848             lmp = --mp;
3849             /* Guaranteed to be.  Unlikely, but. . . */
3850             if (!STREQ (lmp->is, rmp->is))
3851               lmp->is[0] = '\0';
3852             /* Left side--easy */
3853             i = 0;
3854             while (lmp->left[i] != '\0' && lmp->left[i] == rmp->left[i])
3855               ++i;
3856             lmp->left[i] = '\0';
3857             /* Right side */
3858             ln = strlen(lmp->right);
3859             rn = strlen(rmp->right);
3860             n = ln;
3861             if (n > rn)
3862               n = rn;
3863             for (i = 0; i < n; ++i)
3864               if (lmp->right[ln - i - 1] != rmp->right[rn - i - 1])
3865                 break;
3866             for (j = 0; j < i; ++j)
3867               lmp->right[j] = lmp->right[(ln - i) + j];
3868             lmp->right[j] = '\0';
3869             new = inboth(lmp->in, rmp->in);
3870             if (new == NULL)
3871               goto done;
3872             freelist(lmp->in);
3873             free(lmp->in);
3874             lmp->in = new;
3875           }
3876           break;
3877         case PLUS:
3878           assert (musts < mp);
3879           --mp;
3880           mp->is[0] = '\0';
3881           break;
3882         case END:
3883           assert (mp == &musts[1]);
3884           for (i = 0; musts[0].in[i] != NULL; ++i)
3885             if (strlen(musts[0].in[i]) > strlen(result))
3886               result = musts[0].in[i];
3887           if (STREQ (result, musts[0].is))
3888             exact = 1;
3889           goto done;
3890         case CAT:
3891           assert (&musts[2] <= mp);
3892           {
3893             must *lmp;
3894             must *rmp;
3895
3896             rmp = --mp;
3897             lmp = --mp;
3898             /* In.  Everything in left, plus everything in
3899                right, plus catenation of
3900                left's right and right's left. */
3901             lmp->in = addlists(lmp->in, rmp->in);
3902             if (lmp->in == NULL)
3903               goto done;
3904             if (lmp->right[0] != '\0' &&
3905                 rmp->left[0] != '\0')
3906               {
3907                 char *tp;
3908
3909                 tp = icpyalloc(lmp->right);
3910                 if (tp == NULL)
3911                   goto done;
3912                 tp = icatalloc(tp, rmp->left);
3913                 if (tp == NULL)
3914                   goto done;
3915                 lmp->in = enlist(lmp->in, tp,
3916                                  strlen(tp));
3917                 free(tp);
3918                 if (lmp->in == NULL)
3919                   goto done;
3920               }
3921             /* Left-hand */
3922             if (lmp->is[0] != '\0')
3923               {
3924                 lmp->left = icatalloc(lmp->left,
3925                                       rmp->left);
3926                 if (lmp->left == NULL)
3927                   goto done;
3928               }
3929             /* Right-hand */
3930             if (rmp->is[0] == '\0')
3931               lmp->right[0] = '\0';
3932             lmp->right = icatalloc(lmp->right, rmp->right);
3933             if (lmp->right == NULL)
3934               goto done;
3935             /* Guaranteed to be */
3936             if (lmp->is[0] != '\0' && rmp->is[0] != '\0')
3937               {
3938                 lmp->is = icatalloc(lmp->is, rmp->is);
3939                 if (lmp->is == NULL)
3940                   goto done;
3941               }
3942             else
3943               lmp->is[0] = '\0';
3944           }
3945           break;
3946         default:
3947           if (t < END)
3948             {
3949               assert (!"oops! t >= END");
3950             }
3951           else if (t == '\0')
3952             {
3953               /* not on *my* shift */
3954               goto done;
3955             }
3956           else if (t >= CSET
3957 #if MBS_SUPPORT
3958                    || t == ANYCHAR
3959                    || t == MBCSET
3960 #endif /* MBS_SUPPORT */
3961                    )
3962             {
3963               /* easy enough */
3964               resetmust(mp);
3965             }
3966           else
3967             {
3968               /* plain character */
3969               resetmust(mp);
3970               mp->is[0] = mp->left[0] = mp->right[0] = t;
3971               mp->is[1] = mp->left[1] = mp->right[1] = '\0';
3972               mp->in = enlist(mp->in, mp->is, (size_t)1);
3973               if (mp->in == NULL)
3974                 goto done;
3975             }
3976           break;
3977         }
3978 #ifdef DEBUG
3979       fprintf(stderr, " node: %d:", ri);
3980       prtok(d->tokens[ri]);
3981       fprintf(stderr, "\n  in:");
3982       for (i = 0; mp->in[i]; ++i)
3983         fprintf(stderr, " \"%s\"", mp->in[i]);
3984       fprintf(stderr, "\n  is: \"%s\"\n", mp->is);
3985       fprintf(stderr, "  left: \"%s\"\n", mp->left);
3986       fprintf(stderr, "  right: \"%s\"\n", mp->right);
3987 #endif
3988       ++mp;
3989     }
3990  done:
3991   if (strlen(result))
3992     {
3993       MALLOC(dm, struct dfamust, 1);
3994       dm->exact = exact;
3995       MALLOC(dm->must, char, strlen(result) + 1);
3996       strcpy(dm->must, result);
3997       dm->next = d->musts;
3998       d->musts = dm;
3999     }
4000   mp = musts;
4001   for (i = 0; i <= d->tindex; ++i)
4002     {
4003       freelist(mp[i].in);
4004       free(mp[i].in);
4005       free(mp[i].left);
4006       free(mp[i].right);
4007       free(mp[i].is);
4008     }
4009   free(mp);
4010 }
4011
4012 struct dfa *
4013 dfaalloc (void)
4014 {
4015   return xmalloc (sizeof (struct dfa));
4016 }
4017
4018 struct dfamust *
4019 dfamusts (struct dfa const *d)
4020 {
4021   return d->musts;
4022 }
4023
4024 /* vim:set shiftwidth=2: */