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