c20977cd9658ad35583b3a2839adff6f815f069e
[gnulib.git] / lib / regex.c
1 /* Extended regular expression matching and search library,
2    version 0.12.
3    (Implements POSIX draft P1003.2/D11.2, except for some of the
4    internationalization features.)
5    Copyright (C) 1993-1999, 2000, 2001 Free Software Foundation, Inc.
6    This file is part of the GNU C Library.
7
8    The GNU C Library is free software; you can redistribute it and/or
9    modify it under the terms of the GNU Lesser General Public
10    License as published by the Free Software Foundation; either
11    version 2.1 of the License, or (at your option) any later version.
12
13    The GNU C Library is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16    Lesser General Public License for more details.
17
18    You should have received a copy of the GNU Lesser General Public
19    License along with the GNU C Library; if not, write to the Free
20    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21    02111-1307 USA.  */
22
23 /* AIX requires this to be the first thing in the file. */
24 #if defined _AIX && !defined REGEX_MALLOC
25   #pragma alloca
26 #endif
27
28 #undef  _GNU_SOURCE
29 #define _GNU_SOURCE
30
31 #ifdef HAVE_CONFIG_H
32 # include <config.h>
33 #endif
34
35 #ifndef PARAMS
36 # if defined __GNUC__ || (defined __STDC__ && __STDC__)
37 #  define PARAMS(args) args
38 # else
39 #  define PARAMS(args) ()
40 # endif  /* GCC.  */
41 #endif  /* Not PARAMS.  */
42
43 #ifndef INSIDE_RECURSION
44
45 # if defined STDC_HEADERS && !defined emacs
46 #  include <stddef.h>
47 # else
48 /* We need this for `regex.h', and perhaps for the Emacs include files.  */
49 #  include <sys/types.h>
50 # endif
51
52 # define WIDE_CHAR_SUPPORT (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC)
53
54 /* For platform which support the ISO C amendement 1 functionality we
55    support user defined character classes.  */
56 # if defined _LIBC || WIDE_CHAR_SUPPORT
57 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>.  */
58 #  include <wchar.h>
59 #  include <wctype.h>
60 # endif
61
62 # ifdef _LIBC
63 /* We have to keep the namespace clean.  */
64 #  define regfree(preg) __regfree (preg)
65 #  define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
66 #  define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
67 #  define regerror(errcode, preg, errbuf, errbuf_size) \
68         __regerror(errcode, preg, errbuf, errbuf_size)
69 #  define re_set_registers(bu, re, nu, st, en) \
70         __re_set_registers (bu, re, nu, st, en)
71 #  define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
72         __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
73 #  define re_match(bufp, string, size, pos, regs) \
74         __re_match (bufp, string, size, pos, regs)
75 #  define re_search(bufp, string, size, startpos, range, regs) \
76         __re_search (bufp, string, size, startpos, range, regs)
77 #  define re_compile_pattern(pattern, length, bufp) \
78         __re_compile_pattern (pattern, length, bufp)
79 #  define re_set_syntax(syntax) __re_set_syntax (syntax)
80 #  define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
81         __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
82 #  define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
83
84 #  define btowc __btowc
85
86 /* We are also using some library internals.  */
87 #  include <locale/localeinfo.h>
88 #  include <locale/elem-hash.h>
89 #  include <langinfo.h>
90 #  include <locale/coll-lookup.h>
91 # endif
92
93 /* This is for other GNU distributions with internationalized messages.  */
94 # if HAVE_LIBINTL_H || defined _LIBC
95 #  include <libintl.h>
96 #  ifdef _LIBC
97 #   undef gettext
98 #   define gettext(msgid) __dcgettext ("libc", msgid, LC_MESSAGES)
99 #  endif
100 # else
101 #  define gettext(msgid) (msgid)
102 # endif
103
104 # ifndef gettext_noop
105 /* This define is so xgettext can find the internationalizable
106    strings.  */
107 #  define gettext_noop(String) String
108 # endif
109
110 /* The `emacs' switch turns on certain matching commands
111    that make sense only in Emacs. */
112 # ifdef emacs
113
114 #  include "lisp.h"
115 #  include "buffer.h"
116 #  include "syntax.h"
117
118 # else  /* not emacs */
119
120 /* If we are not linking with Emacs proper,
121    we can't use the relocating allocator
122    even if config.h says that we can.  */
123 #  undef REL_ALLOC
124
125 #  if defined STDC_HEADERS || defined _LIBC
126 #   include <stdlib.h>
127 #  else
128 char *malloc ();
129 char *realloc ();
130 #  endif
131
132 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
133    If nothing else has been done, use the method below.  */
134 #  ifdef INHIBIT_STRING_HEADER
135 #   if !(defined HAVE_BZERO && defined HAVE_BCOPY)
136 #    if !defined bzero && !defined bcopy
137 #     undef INHIBIT_STRING_HEADER
138 #    endif
139 #   endif
140 #  endif
141
142 /* This is the normal way of making sure we have a bcopy and a bzero.
143    This is used in most programs--a few other programs avoid this
144    by defining INHIBIT_STRING_HEADER.  */
145 #  ifndef INHIBIT_STRING_HEADER
146 #   if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
147 #    include <string.h>
148 #    ifndef bzero
149 #     ifndef _LIBC
150 #      define bzero(s, n)       (memset (s, '\0', n), (s))
151 #     else
152 #      define bzero(s, n)       __bzero (s, n)
153 #     endif
154 #    endif
155 #   else
156 #    include <strings.h>
157 #    ifndef memcmp
158 #     define memcmp(s1, s2, n)  bcmp (s1, s2, n)
159 #    endif
160 #    ifndef memcpy
161 #     define memcpy(d, s, n)    (bcopy (s, d, n), (d))
162 #    endif
163 #   endif
164 #  endif
165
166 /* Define the syntax stuff for \<, \>, etc.  */
167
168 /* This must be nonzero for the wordchar and notwordchar pattern
169    commands in re_match_2.  */
170 #  ifndef Sword
171 #   define Sword 1
172 #  endif
173
174 #  ifdef SWITCH_ENUM_BUG
175 #   define SWITCH_ENUM_CAST(x) ((int)(x))
176 #  else
177 #   define SWITCH_ENUM_CAST(x) (x)
178 #  endif
179
180 # endif /* not emacs */
181
182 # if defined _LIBC || HAVE_LIMITS_H
183 #  include <limits.h>
184 # endif
185
186 # ifndef MB_LEN_MAX
187 #  define MB_LEN_MAX 1
188 # endif
189 \f
190 /* Get the interface, including the syntax bits.  */
191 # include <regex.h>
192
193 /* isalpha etc. are used for the character classes.  */
194 # include <ctype.h>
195
196 /* Jim Meyering writes:
197
198    "... Some ctype macros are valid only for character codes that
199    isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
200    using /bin/cc or gcc but without giving an ansi option).  So, all
201    ctype uses should be through macros like ISPRINT...  If
202    STDC_HEADERS is defined, then autoconf has verified that the ctype
203    macros don't need to be guarded with references to isascii. ...
204    Defining isascii to 1 should let any compiler worth its salt
205    eliminate the && through constant folding."
206    Solaris defines some of these symbols so we must undefine them first.  */
207
208 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
209 #  define IN_CTYPE_DOMAIN(c) 1
210 # else
211 #  define IN_CTYPE_DOMAIN(c) isascii(c)
212 # endif
213
214 # ifdef isblank
215 #  define ISBLANK(c) (IN_CTYPE_DOMAIN (c) && isblank (c))
216 # else
217 #  define ISBLANK(c) ((c) == ' ' || (c) == '\t')
218 # endif
219 # ifdef isgraph
220 #  define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isgraph (c))
221 # else
222 #  define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isprint (c) && !isspace (c))
223 # endif
224
225 # undef ISPRINT
226 # define ISPRINT(c) (IN_CTYPE_DOMAIN (c) && isprint (c))
227 # define ISDIGIT(c) (IN_CTYPE_DOMAIN (c) && isdigit (c))
228 # define ISALNUM(c) (IN_CTYPE_DOMAIN (c) && isalnum (c))
229 # define ISALPHA(c) (IN_CTYPE_DOMAIN (c) && isalpha (c))
230 # define ISCNTRL(c) (IN_CTYPE_DOMAIN (c) && iscntrl (c))
231 # define ISLOWER(c) (IN_CTYPE_DOMAIN (c) && islower (c))
232 # define ISPUNCT(c) (IN_CTYPE_DOMAIN (c) && ispunct (c))
233 # define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c))
234 # define ISUPPER(c) (IN_CTYPE_DOMAIN (c) && isupper (c))
235 # define ISXDIGIT(c) (IN_CTYPE_DOMAIN (c) && isxdigit (c))
236
237 # ifdef _tolower
238 #  define TOLOWER(c) _tolower(c)
239 # else
240 #  define TOLOWER(c) tolower(c)
241 # endif
242
243 # ifndef NULL
244 #  define NULL (void *)0
245 # endif
246
247 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
248    since ours (we hope) works properly with all combinations of
249    machines, compilers, `char' and `unsigned char' argument types.
250    (Per Bothner suggested the basic approach.)  */
251 # undef SIGN_EXTEND_CHAR
252 # if __STDC__
253 #  define SIGN_EXTEND_CHAR(c) ((signed char) (c))
254 # else  /* not __STDC__ */
255 /* As in Harbison and Steele.  */
256 #  define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
257 # endif
258 \f
259 # ifndef emacs
260 /* How many characters in the character set.  */
261 #  define CHAR_SET_SIZE 256
262
263 #  ifdef SYNTAX_TABLE
264
265 extern char *re_syntax_table;
266
267 #  else /* not SYNTAX_TABLE */
268
269 static char re_syntax_table[CHAR_SET_SIZE];
270
271 static void init_syntax_once PARAMS ((void));
272
273 static void
274 init_syntax_once ()
275 {
276    register int c;
277    static int done = 0;
278
279    if (done)
280      return;
281    bzero (re_syntax_table, sizeof re_syntax_table);
282
283    for (c = 0; c < CHAR_SET_SIZE; ++c)
284      if (ISALNUM (c))
285         re_syntax_table[c] = Sword;
286
287    re_syntax_table['_'] = Sword;
288
289    done = 1;
290 }
291
292 #  endif /* not SYNTAX_TABLE */
293
294 #  define SYNTAX(c) re_syntax_table[(unsigned char) (c)]
295
296 # endif /* emacs */
297 \f
298 /* Integer type for pointers.  */
299 # if !defined _LIBC
300 typedef unsigned long int uintptr_t;
301 # endif
302
303 /* Should we use malloc or alloca?  If REGEX_MALLOC is not defined, we
304    use `alloca' instead of `malloc'.  This is because using malloc in
305    re_search* or re_match* could cause memory leaks when C-g is used in
306    Emacs; also, malloc is slower and causes storage fragmentation.  On
307    the other hand, malloc is more portable, and easier to debug.
308
309    Because we sometimes use alloca, some routines have to be macros,
310    not functions -- `alloca'-allocated space disappears at the end of the
311    function it is called in.  */
312
313 # ifdef REGEX_MALLOC
314
315 #  define REGEX_ALLOCATE malloc
316 #  define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
317 #  define REGEX_FREE free
318
319 # else /* not REGEX_MALLOC  */
320
321 /* Emacs already defines alloca, sometimes.  */
322 #  ifndef alloca
323
324 /* Make alloca work the best possible way.  */
325 #   ifdef __GNUC__
326 #    define alloca __builtin_alloca
327 #   else /* not __GNUC__ */
328 #    if HAVE_ALLOCA_H
329 #     include <alloca.h>
330 #    endif /* HAVE_ALLOCA_H */
331 #   endif /* not __GNUC__ */
332
333 #  endif /* not alloca */
334
335 #  define REGEX_ALLOCATE alloca
336
337 /* Assumes a `char *destination' variable.  */
338 #  define REGEX_REALLOCATE(source, osize, nsize)                        \
339   (destination = (char *) alloca (nsize),                               \
340    memcpy (destination, source, osize))
341
342 /* No need to do anything to free, after alloca.  */
343 #  define REGEX_FREE(arg) ((void)0) /* Do nothing!  But inhibit gcc warning.  */
344
345 # endif /* not REGEX_MALLOC */
346
347 /* Define how to allocate the failure stack.  */
348
349 # if defined REL_ALLOC && defined REGEX_MALLOC
350
351 #  define REGEX_ALLOCATE_STACK(size)                            \
352   r_alloc (&failure_stack_ptr, (size))
353 #  define REGEX_REALLOCATE_STACK(source, osize, nsize)          \
354   r_re_alloc (&failure_stack_ptr, (nsize))
355 #  define REGEX_FREE_STACK(ptr)                                 \
356   r_alloc_free (&failure_stack_ptr)
357
358 # else /* not using relocating allocator */
359
360 #  ifdef REGEX_MALLOC
361
362 #   define REGEX_ALLOCATE_STACK malloc
363 #   define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
364 #   define REGEX_FREE_STACK free
365
366 #  else /* not REGEX_MALLOC */
367
368 #   define REGEX_ALLOCATE_STACK alloca
369
370 #   define REGEX_REALLOCATE_STACK(source, osize, nsize)                 \
371    REGEX_REALLOCATE (source, osize, nsize)
372 /* No need to explicitly free anything.  */
373 #   define REGEX_FREE_STACK(arg)
374
375 #  endif /* not REGEX_MALLOC */
376 # endif /* not using relocating allocator */
377
378
379 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
380    `string1' or just past its end.  This works if PTR is NULL, which is
381    a good thing.  */
382 # define FIRST_STRING_P(ptr)                                    \
383   (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
384
385 /* (Re)Allocate N items of type T using malloc, or fail.  */
386 # define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
387 # define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
388 # define RETALLOC_IF(addr, n, t) \
389   if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
390 # define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
391
392 # define BYTEWIDTH 8 /* In bits.  */
393
394 # define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
395
396 # undef MAX
397 # undef MIN
398 # define MAX(a, b) ((a) > (b) ? (a) : (b))
399 # define MIN(a, b) ((a) < (b) ? (a) : (b))
400
401 typedef char boolean;
402 # define false 0
403 # define true 1
404
405 static reg_errcode_t byte_regex_compile _RE_ARGS ((const char *pattern, size_t size,
406                                                    reg_syntax_t syntax,
407                                                    struct re_pattern_buffer *bufp));
408 static reg_errcode_t wcs_regex_compile _RE_ARGS ((const char *pattern, size_t size,
409                                                    reg_syntax_t syntax,
410                                                    struct re_pattern_buffer *bufp));
411
412 static int byte_re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
413                                              const char *string1, int size1,
414                                              const char *string2, int size2,
415                                              int pos,
416                                              struct re_registers *regs,
417                                              int stop));
418 static int wcs_re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
419                                             const char *cstring1, int csize1,
420                                             const char *cstring2, int csize2,
421                                             int pos,
422                                             struct re_registers *regs,
423                                             int stop,
424                                             wchar_t *string1, int size1,
425                                             wchar_t *string2, int size2,
426                                             int *mbs_offset1, int *mbs_offset2));
427 static int byte_re_search_2 PARAMS ((struct re_pattern_buffer *bufp,
428                                      const char *string1, int size1,
429                                      const char *string2, int size2,
430                                      int startpos, int range,
431                                      struct re_registers *regs, int stop));
432 static int wcs_re_search_2 PARAMS ((struct re_pattern_buffer *bufp,
433                                     const char *string1, int size1,
434                                     const char *string2, int size2,
435                                     int startpos, int range,
436                                     struct re_registers *regs, int stop));
437 static int byte_re_compile_fastmap PARAMS ((struct re_pattern_buffer *bufp));
438 static int wcs_re_compile_fastmap PARAMS ((struct re_pattern_buffer *bufp));
439
440 \f
441 /* These are the command codes that appear in compiled regular
442    expressions.  Some opcodes are followed by argument bytes.  A
443    command code can specify any interpretation whatsoever for its
444    arguments.  Zero bytes may appear in the compiled regular expression.  */
445
446 typedef enum
447 {
448   no_op = 0,
449
450   /* Succeed right away--no more backtracking.  */
451   succeed,
452
453         /* Followed by one byte giving n, then by n literal bytes.  */
454   exactn,
455
456 # ifdef MBS_SUPPORT
457         /* Same as exactn, but contains binary data.  */
458   exactn_bin,
459 # endif
460
461         /* Matches any (more or less) character.  */
462   anychar,
463
464         /* Matches any one char belonging to specified set.  First
465            following byte is number of bitmap bytes.  Then come bytes
466            for a bitmap saying which chars are in.  Bits in each byte
467            are ordered low-bit-first.  A character is in the set if its
468            bit is 1.  A character too large to have a bit in the map is
469            automatically not in the set.  */
470         /* ifdef MBS_SUPPORT, following element is length of character
471            classes, length of collating symbols, length of equivalence
472            classes, length of character ranges, and length of characters.
473            Next, character class element, collating symbols elements,
474            equivalence class elements, range elements, and character
475            elements follow.
476            See regex_compile function.  */
477   charset,
478
479         /* Same parameters as charset, but match any character that is
480            not one of those specified.  */
481   charset_not,
482
483         /* Start remembering the text that is matched, for storing in a
484            register.  Followed by one byte with the register number, in
485            the range 0 to one less than the pattern buffer's re_nsub
486            field.  Then followed by one byte with the number of groups
487            inner to this one.  (This last has to be part of the
488            start_memory only because we need it in the on_failure_jump
489            of re_match_2.)  */
490   start_memory,
491
492         /* Stop remembering the text that is matched and store it in a
493            memory register.  Followed by one byte with the register
494            number, in the range 0 to one less than `re_nsub' in the
495            pattern buffer, and one byte with the number of inner groups,
496            just like `start_memory'.  (We need the number of inner
497            groups here because we don't have any easy way of finding the
498            corresponding start_memory when we're at a stop_memory.)  */
499   stop_memory,
500
501         /* Match a duplicate of something remembered. Followed by one
502            byte containing the register number.  */
503   duplicate,
504
505         /* Fail unless at beginning of line.  */
506   begline,
507
508         /* Fail unless at end of line.  */
509   endline,
510
511         /* Succeeds if at beginning of buffer (if emacs) or at beginning
512            of string to be matched (if not).  */
513   begbuf,
514
515         /* Analogously, for end of buffer/string.  */
516   endbuf,
517
518         /* Followed by two byte relative address to which to jump.  */
519   jump,
520
521         /* Same as jump, but marks the end of an alternative.  */
522   jump_past_alt,
523
524         /* Followed by two-byte relative address of place to resume at
525            in case of failure.  */
526         /* ifdef MBS_SUPPORT, the size of address is 1.  */
527   on_failure_jump,
528
529         /* Like on_failure_jump, but pushes a placeholder instead of the
530            current string position when executed.  */
531   on_failure_keep_string_jump,
532
533         /* Throw away latest failure point and then jump to following
534            two-byte relative address.  */
535         /* ifdef MBS_SUPPORT, the size of address is 1.  */
536   pop_failure_jump,
537
538         /* Change to pop_failure_jump if know won't have to backtrack to
539            match; otherwise change to jump.  This is used to jump
540            back to the beginning of a repeat.  If what follows this jump
541            clearly won't match what the repeat does, such that we can be
542            sure that there is no use backtracking out of repetitions
543            already matched, then we change it to a pop_failure_jump.
544            Followed by two-byte address.  */
545         /* ifdef MBS_SUPPORT, the size of address is 1.  */
546   maybe_pop_jump,
547
548         /* Jump to following two-byte address, and push a dummy failure
549            point. This failure point will be thrown away if an attempt
550            is made to use it for a failure.  A `+' construct makes this
551            before the first repeat.  Also used as an intermediary kind
552            of jump when compiling an alternative.  */
553         /* ifdef MBS_SUPPORT, the size of address is 1.  */
554   dummy_failure_jump,
555
556         /* Push a dummy failure point and continue.  Used at the end of
557            alternatives.  */
558   push_dummy_failure,
559
560         /* Followed by two-byte relative address and two-byte number n.
561            After matching N times, jump to the address upon failure.  */
562         /* ifdef MBS_SUPPORT, the size of address is 1.  */
563   succeed_n,
564
565         /* Followed by two-byte relative address, and two-byte number n.
566            Jump to the address N times, then fail.  */
567         /* ifdef MBS_SUPPORT, the size of address is 1.  */
568   jump_n,
569
570         /* Set the following two-byte relative address to the
571            subsequent two-byte number.  The address *includes* the two
572            bytes of number.  */
573         /* ifdef MBS_SUPPORT, the size of address is 1.  */
574   set_number_at,
575
576   wordchar,     /* Matches any word-constituent character.  */
577   notwordchar,  /* Matches any char that is not a word-constituent.  */
578
579   wordbeg,      /* Succeeds if at word beginning.  */
580   wordend,      /* Succeeds if at word end.  */
581
582   wordbound,    /* Succeeds if at a word boundary.  */
583   notwordbound  /* Succeeds if not at a word boundary.  */
584
585 # ifdef emacs
586   ,before_dot,  /* Succeeds if before point.  */
587   at_dot,       /* Succeeds if at point.  */
588   after_dot,    /* Succeeds if after point.  */
589
590         /* Matches any character whose syntax is specified.  Followed by
591            a byte which contains a syntax code, e.g., Sword.  */
592   syntaxspec,
593
594         /* Matches any character whose syntax is not that specified.  */
595   notsyntaxspec
596 # endif /* emacs */
597 } re_opcode_t;
598 #endif /* not INSIDE_RECURSION */
599 \f
600
601 #ifdef BYTE
602 # define CHAR_T char
603 # define UCHAR_T unsigned char
604 # define COMPILED_BUFFER_VAR bufp->buffer
605 # define OFFSET_ADDRESS_SIZE 2
606 # define PREFIX(name) byte_##name
607 # define ARG_PREFIX(name) name
608 # define PUT_CHAR(c) putchar (c)
609 #elif defined WCHAR
610 # define CHAR_T wchar_t
611 # define UCHAR_T wchar_t
612 # define COMPILED_BUFFER_VAR wc_buffer
613 # define OFFSET_ADDRESS_SIZE 1 /* the size which STORE_NUMBER macro use */
614 # define CHAR_CLASS_SIZE ((__alignof__(wctype_t)+sizeof(wctype_t))/sizeof(CHAR_T)+1)
615 # define PREFIX(name) wcs_##name
616 # define ARG_PREFIX(name) c##name
617 /* Should we use wide stream??  */
618 # define PUT_CHAR(c) printf ("%C", c);
619 # define TRUE 1
620 # define FALSE 0
621 #else
622 # ifdef MBS_SUPPORT
623 #  define WCHAR
624 #  define INSIDE_RECURSION
625 #  include "regex.c"
626 #  undef INSIDE_RECURSION
627 # endif
628 # define BYTE
629 # define INSIDE_RECURSION
630 # include "regex.c"
631 # undef INSIDE_RECURSION
632 #endif
633
634 #ifdef INSIDE_RECURSION
635 /* Common operations on the compiled pattern.  */
636
637 /* Store NUMBER in two contiguous bytes starting at DESTINATION.  */
638 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element.  */
639
640 # ifdef WCHAR
641 #  define STORE_NUMBER(destination, number)                             \
642   do {                                                                  \
643     *(destination) = (UCHAR_T)(number);                         \
644   } while (0)
645 # else /* BYTE */
646 #  define STORE_NUMBER(destination, number)                             \
647   do {                                                                  \
648     (destination)[0] = (number) & 0377;                                 \
649     (destination)[1] = (number) >> 8;                                   \
650   } while (0)
651 # endif /* WCHAR */
652
653 /* Same as STORE_NUMBER, except increment DESTINATION to
654    the byte after where the number is stored.  Therefore, DESTINATION
655    must be an lvalue.  */
656 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element.  */
657
658 # define STORE_NUMBER_AND_INCR(destination, number)                     \
659   do {                                                                  \
660     STORE_NUMBER (destination, number);                                 \
661     (destination) += OFFSET_ADDRESS_SIZE;                               \
662   } while (0)
663
664 /* Put into DESTINATION a number stored in two contiguous bytes starting
665    at SOURCE.  */
666 /* ifdef MBS_SUPPORT, we store NUMBER in 1 element.  */
667
668 # ifdef WCHAR
669 #  define EXTRACT_NUMBER(destination, source)                           \
670   do {                                                                  \
671     (destination) = *(source);                                          \
672   } while (0)
673 # else /* BYTE */
674 #  define EXTRACT_NUMBER(destination, source)                           \
675   do {                                                                  \
676     (destination) = *(source) & 0377;                                   \
677     (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8;           \
678   } while (0)
679 # endif
680
681 # ifdef DEBUG
682 static void PREFIX(extract_number) _RE_ARGS ((int *dest, UCHAR_T *source));
683 static void
684 PREFIX(extract_number) (dest, source)
685     int *dest;
686     UCHAR_T *source;
687 {
688 #  ifdef WCHAR
689   *dest = *source;
690 #  else /* BYTE */
691   int temp = SIGN_EXTEND_CHAR (*(source + 1));
692   *dest = *source & 0377;
693   *dest += temp << 8;
694 #  endif
695 }
696
697 #  ifndef EXTRACT_MACROS /* To debug the macros.  */
698 #   undef EXTRACT_NUMBER
699 #   define EXTRACT_NUMBER(dest, src) PREFIX(extract_number) (&dest, src)
700 #  endif /* not EXTRACT_MACROS */
701
702 # endif /* DEBUG */
703
704 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
705    SOURCE must be an lvalue.  */
706
707 # define EXTRACT_NUMBER_AND_INCR(destination, source)                   \
708   do {                                                                  \
709     EXTRACT_NUMBER (destination, source);                               \
710     (source) += OFFSET_ADDRESS_SIZE;                                    \
711   } while (0)
712
713 # ifdef DEBUG
714 static void PREFIX(extract_number_and_incr) _RE_ARGS ((int *destination,
715                                                        UCHAR_T **source));
716 static void
717 PREFIX(extract_number_and_incr) (destination, source)
718     int *destination;
719     UCHAR_T **source;
720 {
721   PREFIX(extract_number) (destination, *source);
722   *source += OFFSET_ADDRESS_SIZE;
723 }
724
725 #  ifndef EXTRACT_MACROS
726 #   undef EXTRACT_NUMBER_AND_INCR
727 #   define EXTRACT_NUMBER_AND_INCR(dest, src) \
728   PREFIX(extract_number_and_incr) (&dest, &src)
729 #  endif /* not EXTRACT_MACROS */
730
731 # endif /* DEBUG */
732
733 \f
734
735 /* If DEBUG is defined, Regex prints many voluminous messages about what
736    it is doing (if the variable `debug' is nonzero).  If linked with the
737    main program in `iregex.c', you can enter patterns and strings
738    interactively.  And if linked with the main program in `main.c' and
739    the other test files, you can run the already-written tests.  */
740
741 # ifdef DEBUG
742
743 #  ifndef DEFINED_ONCE
744
745 /* We use standard I/O for debugging.  */
746 #   include <stdio.h>
747
748 /* It is useful to test things that ``must'' be true when debugging.  */
749 #   include <assert.h>
750
751 static int debug;
752
753 #   define DEBUG_STATEMENT(e) e
754 #   define DEBUG_PRINT1(x) if (debug) printf (x)
755 #   define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
756 #   define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
757 #   define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
758 #  endif /* not DEFINED_ONCE */
759
760 #  define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)                         \
761   if (debug) PREFIX(print_partial_compiled_pattern) (s, e)
762 #  define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)                \
763   if (debug) PREFIX(print_double_string) (w, s1, sz1, s2, sz2)
764
765
766 /* Print the fastmap in human-readable form.  */
767
768 #  ifndef DEFINED_ONCE
769 void
770 print_fastmap (fastmap)
771     char *fastmap;
772 {
773   unsigned was_a_range = 0;
774   unsigned i = 0;
775
776   while (i < (1 << BYTEWIDTH))
777     {
778       if (fastmap[i++])
779         {
780           was_a_range = 0;
781           putchar (i - 1);
782           while (i < (1 << BYTEWIDTH)  &&  fastmap[i])
783             {
784               was_a_range = 1;
785               i++;
786             }
787           if (was_a_range)
788             {
789               printf ("-");
790               putchar (i - 1);
791             }
792         }
793     }
794   putchar ('\n');
795 }
796 #  endif /* not DEFINED_ONCE */
797
798
799 /* Print a compiled pattern string in human-readable form, starting at
800    the START pointer into it and ending just before the pointer END.  */
801
802 void
803 PREFIX(print_partial_compiled_pattern) (start, end)
804     UCHAR_T *start;
805     UCHAR_T *end;
806 {
807   int mcnt, mcnt2;
808   UCHAR_T *p1;
809   UCHAR_T *p = start;
810   UCHAR_T *pend = end;
811
812   if (start == NULL)
813     {
814       printf ("(null)\n");
815       return;
816     }
817
818   /* Loop over pattern commands.  */
819   while (p < pend)
820     {
821 #  ifdef _LIBC
822       printf ("%td:\t", p - start);
823 #  else
824       printf ("%ld:\t", (long int) (p - start));
825 #  endif
826
827       switch ((re_opcode_t) *p++)
828         {
829         case no_op:
830           printf ("/no_op");
831           break;
832
833         case exactn:
834           mcnt = *p++;
835           printf ("/exactn/%d", mcnt);
836           do
837             {
838               putchar ('/');
839               PUT_CHAR (*p++);
840             }
841           while (--mcnt);
842           break;
843
844 #  ifdef MBS_SUPPORT
845         case exactn_bin:
846           mcnt = *p++;
847           printf ("/exactn_bin/%d", mcnt);
848           do
849             {
850               printf("/%lx", (long int) *p++);
851             }
852           while (--mcnt);
853           break;
854 #  endif /* MBS_SUPPORT */
855
856         case start_memory:
857           mcnt = *p++;
858           printf ("/start_memory/%d/%ld", mcnt, (long int) *p++);
859           break;
860
861         case stop_memory:
862           mcnt = *p++;
863           printf ("/stop_memory/%d/%ld", mcnt, (long int) *p++);
864           break;
865
866         case duplicate:
867           printf ("/duplicate/%ld", (long int) *p++);
868           break;
869
870         case anychar:
871           printf ("/anychar");
872           break;
873
874         case charset:
875         case charset_not:
876           {
877 #  ifdef WCHAR
878             int i, length;
879             wchar_t *workp = p;
880             printf ("/charset [%s",
881                     (re_opcode_t) *(workp - 1) == charset_not ? "^" : "");
882             p += 5;
883             length = *workp++; /* the length of char_classes */
884             for (i=0 ; i<length ; i++)
885               printf("[:%lx:]", (long int) *p++);
886             length = *workp++; /* the length of collating_symbol */
887             for (i=0 ; i<length ;)
888               {
889                 printf("[.");
890                 while(*p != 0)
891                   PUT_CHAR((i++,*p++));
892                 i++,p++;
893                 printf(".]");
894               }
895             length = *workp++; /* the length of equivalence_class */
896             for (i=0 ; i<length ;)
897               {
898                 printf("[=");
899                 while(*p != 0)
900                   PUT_CHAR((i++,*p++));
901                 i++,p++;
902                 printf("=]");
903               }
904             length = *workp++; /* the length of char_range */
905             for (i=0 ; i<length ; i++)
906               {
907                 wchar_t range_start = *p++;
908                 wchar_t range_end = *p++;
909                 printf("%C-%C", range_start, range_end);
910               }
911             length = *workp++; /* the length of char */
912             for (i=0 ; i<length ; i++)
913               printf("%C", *p++);
914             putchar (']');
915 #  else
916             register int c, last = -100;
917             register int in_range = 0;
918
919             printf ("/charset [%s",
920                     (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
921
922             assert (p + *p < pend);
923
924             for (c = 0; c < 256; c++)
925               if (c / 8 < *p
926                   && (p[1 + (c/8)] & (1 << (c % 8))))
927                 {
928                   /* Are we starting a range?  */
929                   if (last + 1 == c && ! in_range)
930                     {
931                       putchar ('-');
932                       in_range = 1;
933                     }
934                   /* Have we broken a range?  */
935                   else if (last + 1 != c && in_range)
936               {
937                       putchar (last);
938                       in_range = 0;
939                     }
940
941                   if (! in_range)
942                     putchar (c);
943
944                   last = c;
945               }
946
947             if (in_range)
948               putchar (last);
949
950             putchar (']');
951
952             p += 1 + *p;
953 #  endif /* WCHAR */
954           }
955           break;
956
957         case begline:
958           printf ("/begline");
959           break;
960
961         case endline:
962           printf ("/endline");
963           break;
964
965         case on_failure_jump:
966           PREFIX(extract_number_and_incr) (&mcnt, &p);
967 #  ifdef _LIBC
968           printf ("/on_failure_jump to %td", p + mcnt - start);
969 #  else
970           printf ("/on_failure_jump to %ld", (long int) (p + mcnt - start));
971 #  endif
972           break;
973
974         case on_failure_keep_string_jump:
975           PREFIX(extract_number_and_incr) (&mcnt, &p);
976 #  ifdef _LIBC
977           printf ("/on_failure_keep_string_jump to %td", p + mcnt - start);
978 #  else
979           printf ("/on_failure_keep_string_jump to %ld",
980                   (long int) (p + mcnt - start));
981 #  endif
982           break;
983
984         case dummy_failure_jump:
985           PREFIX(extract_number_and_incr) (&mcnt, &p);
986 #  ifdef _LIBC
987           printf ("/dummy_failure_jump to %td", p + mcnt - start);
988 #  else
989           printf ("/dummy_failure_jump to %ld", (long int) (p + mcnt - start));
990 #  endif
991           break;
992
993         case push_dummy_failure:
994           printf ("/push_dummy_failure");
995           break;
996
997         case maybe_pop_jump:
998           PREFIX(extract_number_and_incr) (&mcnt, &p);
999 #  ifdef _LIBC
1000           printf ("/maybe_pop_jump to %td", p + mcnt - start);
1001 #  else
1002           printf ("/maybe_pop_jump to %ld", (long int) (p + mcnt - start));
1003 #  endif
1004           break;
1005
1006         case pop_failure_jump:
1007           PREFIX(extract_number_and_incr) (&mcnt, &p);
1008 #  ifdef _LIBC
1009           printf ("/pop_failure_jump to %td", p + mcnt - start);
1010 #  else
1011           printf ("/pop_failure_jump to %ld", (long int) (p + mcnt - start));
1012 #  endif
1013           break;
1014
1015         case jump_past_alt:
1016           PREFIX(extract_number_and_incr) (&mcnt, &p);
1017 #  ifdef _LIBC
1018           printf ("/jump_past_alt to %td", p + mcnt - start);
1019 #  else
1020           printf ("/jump_past_alt to %ld", (long int) (p + mcnt - start));
1021 #  endif
1022           break;
1023
1024         case jump:
1025           PREFIX(extract_number_and_incr) (&mcnt, &p);
1026 #  ifdef _LIBC
1027           printf ("/jump to %td", p + mcnt - start);
1028 #  else
1029           printf ("/jump to %ld", (long int) (p + mcnt - start));
1030 #  endif
1031           break;
1032
1033         case succeed_n:
1034           PREFIX(extract_number_and_incr) (&mcnt, &p);
1035           p1 = p + mcnt;
1036           PREFIX(extract_number_and_incr) (&mcnt2, &p);
1037 #  ifdef _LIBC
1038           printf ("/succeed_n to %td, %d times", p1 - start, mcnt2);
1039 #  else
1040           printf ("/succeed_n to %ld, %d times",
1041                   (long int) (p1 - start), mcnt2);
1042 #  endif
1043           break;
1044
1045         case jump_n:
1046           PREFIX(extract_number_and_incr) (&mcnt, &p);
1047           p1 = p + mcnt;
1048           PREFIX(extract_number_and_incr) (&mcnt2, &p);
1049           printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
1050           break;
1051
1052         case set_number_at:
1053           PREFIX(extract_number_and_incr) (&mcnt, &p);
1054           p1 = p + mcnt;
1055           PREFIX(extract_number_and_incr) (&mcnt2, &p);
1056 #  ifdef _LIBC
1057           printf ("/set_number_at location %td to %d", p1 - start, mcnt2);
1058 #  else
1059           printf ("/set_number_at location %ld to %d",
1060                   (long int) (p1 - start), mcnt2);
1061 #  endif
1062           break;
1063
1064         case wordbound:
1065           printf ("/wordbound");
1066           break;
1067
1068         case notwordbound:
1069           printf ("/notwordbound");
1070           break;
1071
1072         case wordbeg:
1073           printf ("/wordbeg");
1074           break;
1075
1076         case wordend:
1077           printf ("/wordend");
1078           break;
1079
1080 #  ifdef emacs
1081         case before_dot:
1082           printf ("/before_dot");
1083           break;
1084
1085         case at_dot:
1086           printf ("/at_dot");
1087           break;
1088
1089         case after_dot:
1090           printf ("/after_dot");
1091           break;
1092
1093         case syntaxspec:
1094           printf ("/syntaxspec");
1095           mcnt = *p++;
1096           printf ("/%d", mcnt);
1097           break;
1098
1099         case notsyntaxspec:
1100           printf ("/notsyntaxspec");
1101           mcnt = *p++;
1102           printf ("/%d", mcnt);
1103           break;
1104 #  endif /* emacs */
1105
1106         case wordchar:
1107           printf ("/wordchar");
1108           break;
1109
1110         case notwordchar:
1111           printf ("/notwordchar");
1112           break;
1113
1114         case begbuf:
1115           printf ("/begbuf");
1116           break;
1117
1118         case endbuf:
1119           printf ("/endbuf");
1120           break;
1121
1122         default:
1123           printf ("?%ld", (long int) *(p-1));
1124         }
1125
1126       putchar ('\n');
1127     }
1128
1129 #  ifdef _LIBC
1130   printf ("%td:\tend of pattern.\n", p - start);
1131 #  else
1132   printf ("%ld:\tend of pattern.\n", (long int) (p - start));
1133 #  endif
1134 }
1135
1136
1137 void
1138 PREFIX(print_compiled_pattern) (bufp)
1139     struct re_pattern_buffer *bufp;
1140 {
1141   UCHAR_T *buffer = (UCHAR_T*) bufp->buffer;
1142
1143   PREFIX(print_partial_compiled_pattern) (buffer, buffer
1144                                   + bufp->used / sizeof(UCHAR_T));
1145   printf ("%ld bytes used/%ld bytes allocated.\n",
1146           bufp->used, bufp->allocated);
1147
1148   if (bufp->fastmap_accurate && bufp->fastmap)
1149     {
1150       printf ("fastmap: ");
1151       print_fastmap (bufp->fastmap);
1152     }
1153
1154 #  ifdef _LIBC
1155   printf ("re_nsub: %Zd\t", bufp->re_nsub);
1156 #  else
1157   printf ("re_nsub: %ld\t", (long int) bufp->re_nsub);
1158 #  endif
1159   printf ("regs_alloc: %d\t", bufp->regs_allocated);
1160   printf ("can_be_null: %d\t", bufp->can_be_null);
1161   printf ("newline_anchor: %d\n", bufp->newline_anchor);
1162   printf ("no_sub: %d\t", bufp->no_sub);
1163   printf ("not_bol: %d\t", bufp->not_bol);
1164   printf ("not_eol: %d\t", bufp->not_eol);
1165   printf ("syntax: %lx\n", bufp->syntax);
1166   /* Perhaps we should print the translate table?  */
1167 }
1168
1169
1170 void
1171 PREFIX(print_double_string) (where, string1, size1, string2, size2)
1172     const CHAR_T *where;
1173     const CHAR_T *string1;
1174     const CHAR_T *string2;
1175     int size1;
1176     int size2;
1177 {
1178   int this_char;
1179
1180   if (where == NULL)
1181     printf ("(null)");
1182   else
1183     {
1184       int cnt;
1185
1186       if (FIRST_STRING_P (where))
1187         {
1188           for (this_char = where - string1; this_char < size1; this_char++)
1189             PUT_CHAR (string1[this_char]);
1190
1191           where = string2;
1192         }
1193
1194       cnt = 0;
1195       for (this_char = where - string2; this_char < size2; this_char++)
1196         {
1197           PUT_CHAR (string2[this_char]);
1198           if (++cnt > 100)
1199             {
1200               fputs ("...", stdout);
1201               break;
1202             }
1203         }
1204     }
1205 }
1206
1207 #  ifndef DEFINED_ONCE
1208 void
1209 printchar (c)
1210      int c;
1211 {
1212   putc (c, stderr);
1213 }
1214 #  endif
1215
1216 # else /* not DEBUG */
1217
1218 #  ifndef DEFINED_ONCE
1219 #   undef assert
1220 #   define assert(e)
1221
1222 #   define DEBUG_STATEMENT(e)
1223 #   define DEBUG_PRINT1(x)
1224 #   define DEBUG_PRINT2(x1, x2)
1225 #   define DEBUG_PRINT3(x1, x2, x3)
1226 #   define DEBUG_PRINT4(x1, x2, x3, x4)
1227 #  endif /* not DEFINED_ONCE */
1228 #  define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1229 #  define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1230
1231 # endif /* not DEBUG */
1232
1233 \f
1234
1235 # ifdef WCHAR
1236 /* This  convert a multibyte string to a wide character string.
1237    And write their correspondances to offset_buffer(see below)
1238    and write whether each wchar_t is binary data to is_binary.
1239    This assume invalid multibyte sequences as binary data.
1240    We assume offset_buffer and is_binary is already allocated
1241    enough space.  */
1242
1243 static size_t convert_mbs_to_wcs (CHAR_T *dest, const unsigned char* src,
1244                                   size_t len, int *offset_buffer,
1245                                   char *is_binary);
1246 static size_t
1247 convert_mbs_to_wcs (dest, src, len, offset_buffer, is_binary)
1248      CHAR_T *dest;
1249      const unsigned char* src;
1250      size_t len; /* the length of multibyte string.  */
1251
1252      /* It hold correspondances between src(char string) and
1253         dest(wchar_t string) for optimization.
1254         e.g. src  = "xxxyzz"
1255              dest = {'X', 'Y', 'Z'}
1256               (each "xxx", "y" and "zz" represent one multibyte character
1257                corresponding to 'X', 'Y' and 'Z'.)
1258           offset_buffer = {0, 0+3("xxx"), 0+3+1("y"), 0+3+1+2("zz")}
1259                         = {0, 3, 4, 6}
1260      */
1261      int *offset_buffer;
1262      char *is_binary;
1263 {
1264   wchar_t *pdest = dest;
1265   const unsigned char *psrc = src;
1266   size_t wc_count = 0;
1267
1268   mbstate_t mbs;
1269   int i, consumed;
1270   size_t mb_remain = len;
1271   size_t mb_count = 0;
1272
1273   /* Initialize the conversion state.  */
1274   memset (&mbs, 0, sizeof (mbstate_t));
1275
1276   offset_buffer[0] = 0;
1277   for( ; mb_remain > 0 ; ++wc_count, ++pdest, mb_remain -= consumed,
1278          psrc += consumed)
1279     {
1280       consumed = mbrtowc (pdest, psrc, mb_remain, &mbs);
1281
1282       if (consumed <= 0)
1283         /* failed to convert. maybe src contains binary data.
1284            So we consume 1 byte manualy.  */
1285         {
1286           *pdest = *psrc;
1287           consumed = 1;
1288           is_binary[wc_count] = TRUE;
1289         }
1290       else
1291         is_binary[wc_count] = FALSE;
1292       /* In sjis encoding, we use yen sign as escape character in
1293          place of reverse solidus. So we convert 0x5c(yen sign in
1294          sjis) to not 0xa5(yen sign in UCS2) but 0x5c(reverse
1295          solidus in UCS2).  */
1296       if (consumed == 1 && (int) *psrc == 0x5c && (int) *pdest == 0xa5)
1297         *pdest = (wchar_t) *psrc;
1298
1299       offset_buffer[wc_count + 1] = mb_count += consumed;
1300     }
1301
1302   /* Fill remain of the buffer with sentinel.  */
1303   for (i = wc_count + 1 ; i <= len ; i++)
1304     offset_buffer[i] = mb_count + 1;
1305
1306   return wc_count;
1307 }
1308
1309 # endif /* WCHAR */
1310
1311 #else /* not INSIDE_RECURSION */
1312
1313 /* Set by `re_set_syntax' to the current regexp syntax to recognize.  Can
1314    also be assigned to arbitrarily: each pattern buffer stores its own
1315    syntax, so it can be changed between regex compilations.  */
1316 /* This has no initializer because initialized variables in Emacs
1317    become read-only after dumping.  */
1318 reg_syntax_t re_syntax_options;
1319
1320
1321 /* Specify the precise syntax of regexps for compilation.  This provides
1322    for compatibility for various utilities which historically have
1323    different, incompatible syntaxes.
1324
1325    The argument SYNTAX is a bit mask comprised of the various bits
1326    defined in regex.h.  We return the old syntax.  */
1327
1328 reg_syntax_t
1329 re_set_syntax (syntax)
1330     reg_syntax_t syntax;
1331 {
1332   reg_syntax_t ret = re_syntax_options;
1333
1334   re_syntax_options = syntax;
1335 # ifdef DEBUG
1336   if (syntax & RE_DEBUG)
1337     debug = 1;
1338   else if (debug) /* was on but now is not */
1339     debug = 0;
1340 # endif /* DEBUG */
1341   return ret;
1342 }
1343 # ifdef _LIBC
1344 weak_alias (__re_set_syntax, re_set_syntax)
1345 # endif
1346 \f
1347 /* This table gives an error message for each of the error codes listed
1348    in regex.h.  Obviously the order here has to be same as there.
1349    POSIX doesn't require that we do anything for REG_NOERROR,
1350    but why not be nice?  */
1351
1352 static const char re_error_msgid[] =
1353   {
1354 # define REG_NOERROR_IDX        0
1355     gettext_noop ("Success")    /* REG_NOERROR */
1356     "\0"
1357 # define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
1358     gettext_noop ("No match")   /* REG_NOMATCH */
1359     "\0"
1360 # define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
1361     gettext_noop ("Invalid regular expression") /* REG_BADPAT */
1362     "\0"
1363 # define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
1364     gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
1365     "\0"
1366 # define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
1367     gettext_noop ("Invalid character class name") /* REG_ECTYPE */
1368     "\0"
1369 # define REG_EESCAPE_IDX        (REG_ECTYPE_IDX + sizeof "Invalid character class name")
1370     gettext_noop ("Trailing backslash") /* REG_EESCAPE */
1371     "\0"
1372 # define REG_ESUBREG_IDX        (REG_EESCAPE_IDX + sizeof "Trailing backslash")
1373     gettext_noop ("Invalid back reference") /* REG_ESUBREG */
1374     "\0"
1375 # define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
1376     gettext_noop ("Unmatched [ or [^")  /* REG_EBRACK */
1377     "\0"
1378 # define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
1379     gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
1380     "\0"
1381 # define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
1382     gettext_noop ("Unmatched \\{") /* REG_EBRACE */
1383     "\0"
1384 # define REG_BADBR_IDX  (REG_EBRACE_IDX + sizeof "Unmatched \\{")
1385     gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
1386     "\0"
1387 # define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
1388     gettext_noop ("Invalid range end")  /* REG_ERANGE */
1389     "\0"
1390 # define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
1391     gettext_noop ("Memory exhausted") /* REG_ESPACE */
1392     "\0"
1393 # define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
1394     gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
1395     "\0"
1396 # define REG_EEND_IDX   (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
1397     gettext_noop ("Premature end of regular expression") /* REG_EEND */
1398     "\0"
1399 # define REG_ESIZE_IDX  (REG_EEND_IDX + sizeof "Premature end of regular expression")
1400     gettext_noop ("Regular expression too big") /* REG_ESIZE */
1401     "\0"
1402 # define REG_ERPAREN_IDX        (REG_ESIZE_IDX + sizeof "Regular expression too big")
1403     gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
1404   };
1405
1406 static const size_t re_error_msgid_idx[] =
1407   {
1408     REG_NOERROR_IDX,
1409     REG_NOMATCH_IDX,
1410     REG_BADPAT_IDX,
1411     REG_ECOLLATE_IDX,
1412     REG_ECTYPE_IDX,
1413     REG_EESCAPE_IDX,
1414     REG_ESUBREG_IDX,
1415     REG_EBRACK_IDX,
1416     REG_EPAREN_IDX,
1417     REG_EBRACE_IDX,
1418     REG_BADBR_IDX,
1419     REG_ERANGE_IDX,
1420     REG_ESPACE_IDX,
1421     REG_BADRPT_IDX,
1422     REG_EEND_IDX,
1423     REG_ESIZE_IDX,
1424     REG_ERPAREN_IDX
1425   };
1426 \f
1427 #endif /* INSIDE_RECURSION */
1428
1429 #ifndef DEFINED_ONCE
1430 /* Avoiding alloca during matching, to placate r_alloc.  */
1431
1432 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1433    searching and matching functions should not call alloca.  On some
1434    systems, alloca is implemented in terms of malloc, and if we're
1435    using the relocating allocator routines, then malloc could cause a
1436    relocation, which might (if the strings being searched are in the
1437    ralloc heap) shift the data out from underneath the regexp
1438    routines.
1439
1440    Here's another reason to avoid allocation: Emacs
1441    processes input from X in a signal handler; processing X input may
1442    call malloc; if input arrives while a matching routine is calling
1443    malloc, then we're scrod.  But Emacs can't just block input while
1444    calling matching routines; then we don't notice interrupts when
1445    they come in.  So, Emacs blocks input around all regexp calls
1446    except the matching calls, which it leaves unprotected, in the
1447    faith that they will not malloc.  */
1448
1449 /* Normally, this is fine.  */
1450 # define MATCH_MAY_ALLOCATE
1451
1452 /* When using GNU C, we are not REALLY using the C alloca, no matter
1453    what config.h may say.  So don't take precautions for it.  */
1454 # ifdef __GNUC__
1455 #  undef C_ALLOCA
1456 # endif
1457
1458 /* The match routines may not allocate if (1) they would do it with malloc
1459    and (2) it's not safe for them to use malloc.
1460    Note that if REL_ALLOC is defined, matching would not use malloc for the
1461    failure stack, but we would still use it for the register vectors;
1462    so REL_ALLOC should not affect this.  */
1463 # if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1464 #  undef MATCH_MAY_ALLOCATE
1465 # endif
1466 #endif /* not DEFINED_ONCE */
1467 \f
1468 #ifdef INSIDE_RECURSION
1469 /* Failure stack declarations and macros; both re_compile_fastmap and
1470    re_match_2 use a failure stack.  These have to be macros because of
1471    REGEX_ALLOCATE_STACK.  */
1472
1473
1474 /* Number of failure points for which to initially allocate space
1475    when matching.  If this number is exceeded, we allocate more
1476    space, so it is not a hard limit.  */
1477 # ifndef INIT_FAILURE_ALLOC
1478 #  define INIT_FAILURE_ALLOC 5
1479 # endif
1480
1481 /* Roughly the maximum number of failure points on the stack.  Would be
1482    exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1483    This is a variable only so users of regex can assign to it; we never
1484    change it ourselves.  */
1485
1486 # ifdef INT_IS_16BIT
1487
1488 #  ifndef DEFINED_ONCE
1489 #   if defined MATCH_MAY_ALLOCATE
1490 /* 4400 was enough to cause a crash on Alpha OSF/1,
1491    whose default stack limit is 2mb.  */
1492 long int re_max_failures = 4000;
1493 #   else
1494 long int re_max_failures = 2000;
1495 #   endif
1496 #  endif
1497
1498 union PREFIX(fail_stack_elt)
1499 {
1500   UCHAR_T *pointer;
1501   long int integer;
1502 };
1503
1504 typedef union PREFIX(fail_stack_elt) PREFIX(fail_stack_elt_t);
1505
1506 typedef struct
1507 {
1508   PREFIX(fail_stack_elt_t) *stack;
1509   unsigned long int size;
1510   unsigned long int avail;              /* Offset of next open position.  */
1511 } PREFIX(fail_stack_type);
1512
1513 # else /* not INT_IS_16BIT */
1514
1515 #  ifndef DEFINED_ONCE
1516 #   if defined MATCH_MAY_ALLOCATE
1517 /* 4400 was enough to cause a crash on Alpha OSF/1,
1518    whose default stack limit is 2mb.  */
1519 int re_max_failures = 4000;
1520 #   else
1521 int re_max_failures = 2000;
1522 #   endif
1523 #  endif
1524
1525 union PREFIX(fail_stack_elt)
1526 {
1527   UCHAR_T *pointer;
1528   int integer;
1529 };
1530
1531 typedef union PREFIX(fail_stack_elt) PREFIX(fail_stack_elt_t);
1532
1533 typedef struct
1534 {
1535   PREFIX(fail_stack_elt_t) *stack;
1536   unsigned size;
1537   unsigned avail;                       /* Offset of next open position.  */
1538 } PREFIX(fail_stack_type);
1539
1540 # endif /* INT_IS_16BIT */
1541
1542 # ifndef DEFINED_ONCE
1543 #  define FAIL_STACK_EMPTY()     (fail_stack.avail == 0)
1544 #  define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1545 #  define FAIL_STACK_FULL()      (fail_stack.avail == fail_stack.size)
1546 # endif
1547
1548
1549 /* Define macros to initialize and free the failure stack.
1550    Do `return -2' if the alloc fails.  */
1551
1552 # ifdef MATCH_MAY_ALLOCATE
1553 #  define INIT_FAIL_STACK()                                             \
1554   do {                                                                  \
1555     fail_stack.stack = (PREFIX(fail_stack_elt_t) *)             \
1556       REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (PREFIX(fail_stack_elt_t))); \
1557                                                                         \
1558     if (fail_stack.stack == NULL)                               \
1559       return -2;                                                        \
1560                                                                         \
1561     fail_stack.size = INIT_FAILURE_ALLOC;                       \
1562     fail_stack.avail = 0;                                       \
1563   } while (0)
1564
1565 #  define RESET_FAIL_STACK()  REGEX_FREE_STACK (fail_stack.stack)
1566 # else
1567 #  define INIT_FAIL_STACK()                                             \
1568   do {                                                                  \
1569     fail_stack.avail = 0;                                       \
1570   } while (0)
1571
1572 #  define RESET_FAIL_STACK()
1573 # endif
1574
1575
1576 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1577
1578    Return 1 if succeeds, and 0 if either ran out of memory
1579    allocating space for it or it was already too large.
1580
1581    REGEX_REALLOCATE_STACK requires `destination' be declared.   */
1582
1583 # define DOUBLE_FAIL_STACK(fail_stack)                                  \
1584   ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
1585    ? 0                                                                  \
1586    : ((fail_stack).stack = (PREFIX(fail_stack_elt_t) *)                 \
1587         REGEX_REALLOCATE_STACK ((fail_stack).stack,                     \
1588           (fail_stack).size * sizeof (PREFIX(fail_stack_elt_t)),        \
1589           ((fail_stack).size << 1) * sizeof (PREFIX(fail_stack_elt_t))),\
1590                                                                         \
1591       (fail_stack).stack == NULL                                        \
1592       ? 0                                                               \
1593       : ((fail_stack).size <<= 1,                                       \
1594          1)))
1595
1596
1597 /* Push pointer POINTER on FAIL_STACK.
1598    Return 1 if was able to do so and 0 if ran out of memory allocating
1599    space to do so.  */
1600 # define PUSH_PATTERN_OP(POINTER, FAIL_STACK)                           \
1601   ((FAIL_STACK_FULL ()                                                  \
1602     && !DOUBLE_FAIL_STACK (FAIL_STACK))                                 \
1603    ? 0                                                                  \
1604    : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER,       \
1605       1))
1606
1607 /* Push a pointer value onto the failure stack.
1608    Assumes the variable `fail_stack'.  Probably should only
1609    be called from within `PUSH_FAILURE_POINT'.  */
1610 # define PUSH_FAILURE_POINTER(item)                                     \
1611   fail_stack.stack[fail_stack.avail++].pointer = (UCHAR_T *) (item)
1612
1613 /* This pushes an integer-valued item onto the failure stack.
1614    Assumes the variable `fail_stack'.  Probably should only
1615    be called from within `PUSH_FAILURE_POINT'.  */
1616 # define PUSH_FAILURE_INT(item)                                 \
1617   fail_stack.stack[fail_stack.avail++].integer = (item)
1618
1619 /* Push a fail_stack_elt_t value onto the failure stack.
1620    Assumes the variable `fail_stack'.  Probably should only
1621    be called from within `PUSH_FAILURE_POINT'.  */
1622 # define PUSH_FAILURE_ELT(item)                                 \
1623   fail_stack.stack[fail_stack.avail++] =  (item)
1624
1625 /* These three POP... operations complement the three PUSH... operations.
1626    All assume that `fail_stack' is nonempty.  */
1627 # define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1628 # define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1629 # define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1630
1631 /* Used to omit pushing failure point id's when we're not debugging.  */
1632 # ifdef DEBUG
1633 #  define DEBUG_PUSH PUSH_FAILURE_INT
1634 #  define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1635 # else
1636 #  define DEBUG_PUSH(item)
1637 #  define DEBUG_POP(item_addr)
1638 # endif
1639
1640
1641 /* Push the information about the state we will need
1642    if we ever fail back to it.
1643
1644    Requires variables fail_stack, regstart, regend, reg_info, and
1645    num_regs_pushed be declared.  DOUBLE_FAIL_STACK requires `destination'
1646    be declared.
1647
1648    Does `return FAILURE_CODE' if runs out of memory.  */
1649
1650 # define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code)  \
1651   do {                                                                  \
1652     char *destination;                                                  \
1653     /* Must be int, so when we don't save any registers, the arithmetic \
1654        of 0 + -1 isn't done as unsigned.  */                            \
1655     /* Can't be int, since there is not a shred of a guarantee that int \
1656        is wide enough to hold a value of something to which pointer can \
1657        be assigned */                                                   \
1658     active_reg_t this_reg;                                              \
1659                                                                         \
1660     DEBUG_STATEMENT (failure_id++);                                     \
1661     DEBUG_STATEMENT (nfailure_points_pushed++);                         \
1662     DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id);           \
1663     DEBUG_PRINT2 ("  Before push, next avail: %d\n", (fail_stack).avail);\
1664     DEBUG_PRINT2 ("                     size: %d\n", (fail_stack).size);\
1665                                                                         \
1666     DEBUG_PRINT2 ("  slots needed: %ld\n", NUM_FAILURE_ITEMS);          \
1667     DEBUG_PRINT2 ("     available: %d\n", REMAINING_AVAIL_SLOTS);       \
1668                                                                         \
1669     /* Ensure we have enough space allocated for what we will push.  */ \
1670     while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS)                   \
1671       {                                                                 \
1672         if (!DOUBLE_FAIL_STACK (fail_stack))                            \
1673           return failure_code;                                          \
1674                                                                         \
1675         DEBUG_PRINT2 ("\n  Doubled stack; size now: %d\n",              \
1676                        (fail_stack).size);                              \
1677         DEBUG_PRINT2 ("  slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1678       }                                                                 \
1679                                                                         \
1680     /* Push the info, starting with the registers.  */                  \
1681     DEBUG_PRINT1 ("\n");                                                \
1682                                                                         \
1683     if (1)                                                              \
1684       for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1685            this_reg++)                                                  \
1686         {                                                               \
1687           DEBUG_PRINT2 ("  Pushing reg: %lu\n", this_reg);              \
1688           DEBUG_STATEMENT (num_regs_pushed++);                          \
1689                                                                         \
1690           DEBUG_PRINT2 ("    start: %p\n", regstart[this_reg]);         \
1691           PUSH_FAILURE_POINTER (regstart[this_reg]);                    \
1692                                                                         \
1693           DEBUG_PRINT2 ("    end: %p\n", regend[this_reg]);             \
1694           PUSH_FAILURE_POINTER (regend[this_reg]);                      \
1695                                                                         \
1696           DEBUG_PRINT2 ("    info: %p\n      ",                         \
1697                         reg_info[this_reg].word.pointer);               \
1698           DEBUG_PRINT2 (" match_null=%d",                               \
1699                         REG_MATCH_NULL_STRING_P (reg_info[this_reg]));  \
1700           DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg]));  \
1701           DEBUG_PRINT2 (" matched_something=%d",                        \
1702                         MATCHED_SOMETHING (reg_info[this_reg]));        \
1703           DEBUG_PRINT2 (" ever_matched=%d",                             \
1704                         EVER_MATCHED_SOMETHING (reg_info[this_reg]));   \
1705           DEBUG_PRINT1 ("\n");                                          \
1706           PUSH_FAILURE_ELT (reg_info[this_reg].word);                   \
1707         }                                                               \
1708                                                                         \
1709     DEBUG_PRINT2 ("  Pushing  low active reg: %ld\n", lowest_active_reg);\
1710     PUSH_FAILURE_INT (lowest_active_reg);                               \
1711                                                                         \
1712     DEBUG_PRINT2 ("  Pushing high active reg: %ld\n", highest_active_reg);\
1713     PUSH_FAILURE_INT (highest_active_reg);                              \
1714                                                                         \
1715     DEBUG_PRINT2 ("  Pushing pattern %p:\n", pattern_place);            \
1716     DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend);           \
1717     PUSH_FAILURE_POINTER (pattern_place);                               \
1718                                                                         \
1719     DEBUG_PRINT2 ("  Pushing string %p: `", string_place);              \
1720     DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2,   \
1721                                  size2);                                \
1722     DEBUG_PRINT1 ("'\n");                                               \
1723     PUSH_FAILURE_POINTER (string_place);                                \
1724                                                                         \
1725     DEBUG_PRINT2 ("  Pushing failure id: %u\n", failure_id);            \
1726     DEBUG_PUSH (failure_id);                                            \
1727   } while (0)
1728
1729 # ifndef DEFINED_ONCE
1730 /* This is the number of items that are pushed and popped on the stack
1731    for each register.  */
1732 #  define NUM_REG_ITEMS  3
1733
1734 /* Individual items aside from the registers.  */
1735 #  ifdef DEBUG
1736 #   define NUM_NONREG_ITEMS 5 /* Includes failure point id.  */
1737 #  else
1738 #   define NUM_NONREG_ITEMS 4
1739 #  endif
1740
1741 /* We push at most this many items on the stack.  */
1742 /* We used to use (num_regs - 1), which is the number of registers
1743    this regexp will save; but that was changed to 5
1744    to avoid stack overflow for a regexp with lots of parens.  */
1745 #  define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1746
1747 /* We actually push this many items.  */
1748 #  define NUM_FAILURE_ITEMS                             \
1749   (((0                                                  \
1750      ? 0 : highest_active_reg - lowest_active_reg + 1)  \
1751     * NUM_REG_ITEMS)                                    \
1752    + NUM_NONREG_ITEMS)
1753
1754 /* How many items can still be added to the stack without overflowing it.  */
1755 #  define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1756 # endif /* not DEFINED_ONCE */
1757
1758
1759 /* Pops what PUSH_FAIL_STACK pushes.
1760
1761    We restore into the parameters, all of which should be lvalues:
1762      STR -- the saved data position.
1763      PAT -- the saved pattern position.
1764      LOW_REG, HIGH_REG -- the highest and lowest active registers.
1765      REGSTART, REGEND -- arrays of string positions.
1766      REG_INFO -- array of information about each subexpression.
1767
1768    Also assumes the variables `fail_stack' and (if debugging), `bufp',
1769    `pend', `string1', `size1', `string2', and `size2'.  */
1770 # define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1771 {                                                                       \
1772   DEBUG_STATEMENT (unsigned failure_id;)                                \
1773   active_reg_t this_reg;                                                \
1774   const UCHAR_T *string_temp;                                           \
1775                                                                         \
1776   assert (!FAIL_STACK_EMPTY ());                                        \
1777                                                                         \
1778   /* Remove failure points and point to how many regs pushed.  */       \
1779   DEBUG_PRINT1 ("POP_FAILURE_POINT:\n");                                \
1780   DEBUG_PRINT2 ("  Before pop, next avail: %d\n", fail_stack.avail);    \
1781   DEBUG_PRINT2 ("                    size: %d\n", fail_stack.size);     \
1782                                                                         \
1783   assert (fail_stack.avail >= NUM_NONREG_ITEMS);                        \
1784                                                                         \
1785   DEBUG_POP (&failure_id);                                              \
1786   DEBUG_PRINT2 ("  Popping failure id: %u\n", failure_id);              \
1787                                                                         \
1788   /* If the saved string location is NULL, it came from an              \
1789      on_failure_keep_string_jump opcode, and we want to throw away the  \
1790      saved NULL, thus retaining our current position in the string.  */ \
1791   string_temp = POP_FAILURE_POINTER ();                                 \
1792   if (string_temp != NULL)                                              \
1793     str = (const CHAR_T *) string_temp;                                 \
1794                                                                         \
1795   DEBUG_PRINT2 ("  Popping string %p: `", str);                         \
1796   DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2);      \
1797   DEBUG_PRINT1 ("'\n");                                                 \
1798                                                                         \
1799   pat = (UCHAR_T *) POP_FAILURE_POINTER ();                             \
1800   DEBUG_PRINT2 ("  Popping pattern %p:\n", pat);                        \
1801   DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend);                       \
1802                                                                         \
1803   /* Restore register info.  */                                         \
1804   high_reg = (active_reg_t) POP_FAILURE_INT ();                         \
1805   DEBUG_PRINT2 ("  Popping high active reg: %ld\n", high_reg);          \
1806                                                                         \
1807   low_reg = (active_reg_t) POP_FAILURE_INT ();                          \
1808   DEBUG_PRINT2 ("  Popping  low active reg: %ld\n", low_reg);           \
1809                                                                         \
1810   if (1)                                                                \
1811     for (this_reg = high_reg; this_reg >= low_reg; this_reg--)          \
1812       {                                                                 \
1813         DEBUG_PRINT2 ("    Popping reg: %ld\n", this_reg);              \
1814                                                                         \
1815         reg_info[this_reg].word = POP_FAILURE_ELT ();                   \
1816         DEBUG_PRINT2 ("      info: %p\n",                               \
1817                       reg_info[this_reg].word.pointer);                 \
1818                                                                         \
1819         regend[this_reg] = (const CHAR_T *) POP_FAILURE_POINTER ();     \
1820         DEBUG_PRINT2 ("      end: %p\n", regend[this_reg]);             \
1821                                                                         \
1822         regstart[this_reg] = (const CHAR_T *) POP_FAILURE_POINTER ();   \
1823         DEBUG_PRINT2 ("      start: %p\n", regstart[this_reg]);         \
1824       }                                                                 \
1825   else                                                                  \
1826     {                                                                   \
1827       for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1828         {                                                               \
1829           reg_info[this_reg].word.integer = 0;                          \
1830           regend[this_reg] = 0;                                         \
1831           regstart[this_reg] = 0;                                       \
1832         }                                                               \
1833       highest_active_reg = high_reg;                                    \
1834     }                                                                   \
1835                                                                         \
1836   set_regs_matched_done = 0;                                            \
1837   DEBUG_STATEMENT (nfailure_points_popped++);                           \
1838 } /* POP_FAILURE_POINT */
1839 \f
1840 /* Structure for per-register (a.k.a. per-group) information.
1841    Other register information, such as the
1842    starting and ending positions (which are addresses), and the list of
1843    inner groups (which is a bits list) are maintained in separate
1844    variables.
1845
1846    We are making a (strictly speaking) nonportable assumption here: that
1847    the compiler will pack our bit fields into something that fits into
1848    the type of `word', i.e., is something that fits into one item on the
1849    failure stack.  */
1850
1851
1852 /* Declarations and macros for re_match_2.  */
1853
1854 typedef union
1855 {
1856   PREFIX(fail_stack_elt_t) word;
1857   struct
1858   {
1859       /* This field is one if this group can match the empty string,
1860          zero if not.  If not yet determined,  `MATCH_NULL_UNSET_VALUE'.  */
1861 # define MATCH_NULL_UNSET_VALUE 3
1862     unsigned match_null_string_p : 2;
1863     unsigned is_active : 1;
1864     unsigned matched_something : 1;
1865     unsigned ever_matched_something : 1;
1866   } bits;
1867 } PREFIX(register_info_type);
1868
1869 # ifndef DEFINED_ONCE
1870 #  define REG_MATCH_NULL_STRING_P(R)  ((R).bits.match_null_string_p)
1871 #  define IS_ACTIVE(R)  ((R).bits.is_active)
1872 #  define MATCHED_SOMETHING(R)  ((R).bits.matched_something)
1873 #  define EVER_MATCHED_SOMETHING(R)  ((R).bits.ever_matched_something)
1874
1875
1876 /* Call this when have matched a real character; it sets `matched' flags
1877    for the subexpressions which we are currently inside.  Also records
1878    that those subexprs have matched.  */
1879 #  define SET_REGS_MATCHED()                                            \
1880   do                                                                    \
1881     {                                                                   \
1882       if (!set_regs_matched_done)                                       \
1883         {                                                               \
1884           active_reg_t r;                                               \
1885           set_regs_matched_done = 1;                                    \
1886           for (r = lowest_active_reg; r <= highest_active_reg; r++)     \
1887             {                                                           \
1888               MATCHED_SOMETHING (reg_info[r])                           \
1889                 = EVER_MATCHED_SOMETHING (reg_info[r])                  \
1890                 = 1;                                                    \
1891             }                                                           \
1892         }                                                               \
1893     }                                                                   \
1894   while (0)
1895 # endif /* not DEFINED_ONCE */
1896
1897 /* Registers are set to a sentinel when they haven't yet matched.  */
1898 static CHAR_T PREFIX(reg_unset_dummy);
1899 # define REG_UNSET_VALUE (&PREFIX(reg_unset_dummy))
1900 # define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1901
1902 /* Subroutine declarations and macros for regex_compile.  */
1903 static void PREFIX(store_op1) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc, int arg));
1904 static void PREFIX(store_op2) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc,
1905                                  int arg1, int arg2));
1906 static void PREFIX(insert_op1) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc,
1907                                   int arg, UCHAR_T *end));
1908 static void PREFIX(insert_op2) _RE_ARGS ((re_opcode_t op, UCHAR_T *loc,
1909                                   int arg1, int arg2, UCHAR_T *end));
1910 static boolean PREFIX(at_begline_loc_p) _RE_ARGS ((const CHAR_T *pattern,
1911                                            const CHAR_T *p,
1912                                            reg_syntax_t syntax));
1913 static boolean PREFIX(at_endline_loc_p) _RE_ARGS ((const CHAR_T *p,
1914                                            const CHAR_T *pend,
1915                                            reg_syntax_t syntax));
1916 # ifdef WCHAR
1917 static reg_errcode_t wcs_compile_range _RE_ARGS ((CHAR_T range_start,
1918                                                   const CHAR_T **p_ptr,
1919                                                   const CHAR_T *pend,
1920                                                   char *translate,
1921                                                   reg_syntax_t syntax,
1922                                                   UCHAR_T *b,
1923                                                   CHAR_T *char_set));
1924 static void insert_space _RE_ARGS ((int num, CHAR_T *loc, CHAR_T *end));
1925 # else /* BYTE */
1926 static reg_errcode_t byte_compile_range _RE_ARGS ((unsigned int range_start,
1927                                                    const char **p_ptr,
1928                                                    const char *pend,
1929                                                    char *translate,
1930                                                    reg_syntax_t syntax,
1931                                                    unsigned char *b));
1932 # endif /* WCHAR */
1933
1934 /* Fetch the next character in the uncompiled pattern---translating it
1935    if necessary.  Also cast from a signed character in the constant
1936    string passed to us by the user to an unsigned char that we can use
1937    as an array index (in, e.g., `translate').  */
1938 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1939    because it is impossible to allocate 4GB array for some encodings
1940    which have 4 byte character_set like UCS4.  */
1941 # ifndef PATFETCH
1942 #  ifdef WCHAR
1943 #   define PATFETCH(c)                                                  \
1944   do {if (p == pend) return REG_EEND;                                   \
1945     c = (UCHAR_T) *p++;                                                 \
1946     if (translate && (c <= 0xff)) c = (UCHAR_T) translate[c];           \
1947   } while (0)
1948 #  else /* BYTE */
1949 #   define PATFETCH(c)                                                  \
1950   do {if (p == pend) return REG_EEND;                                   \
1951     c = (unsigned char) *p++;                                           \
1952     if (translate) c = (unsigned char) translate[c];                    \
1953   } while (0)
1954 #  endif /* WCHAR */
1955 # endif
1956
1957 /* Fetch the next character in the uncompiled pattern, with no
1958    translation.  */
1959 # define PATFETCH_RAW(c)                                                \
1960   do {if (p == pend) return REG_EEND;                                   \
1961     c = (UCHAR_T) *p++;                                                 \
1962   } while (0)
1963
1964 /* Go backwards one character in the pattern.  */
1965 # define PATUNFETCH p--
1966
1967
1968 /* If `translate' is non-null, return translate[D], else just D.  We
1969    cast the subscript to translate because some data is declared as
1970    `char *', to avoid warnings when a string constant is passed.  But
1971    when we use a character as a subscript we must make it unsigned.  */
1972 /* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1973    because it is impossible to allocate 4GB array for some encodings
1974    which have 4 byte character_set like UCS4.  */
1975
1976 # ifndef TRANSLATE
1977 #  ifdef WCHAR
1978 #   define TRANSLATE(d) \
1979   ((translate && ((UCHAR_T) (d)) <= 0xff) \
1980    ? (char) translate[(unsigned char) (d)] : (d))
1981 # else /* BYTE */
1982 #   define TRANSLATE(d) \
1983   (translate ? (char) translate[(unsigned char) (d)] : (d))
1984 #  endif /* WCHAR */
1985 # endif
1986
1987
1988 /* Macros for outputting the compiled pattern into `buffer'.  */
1989
1990 /* If the buffer isn't allocated when it comes in, use this.  */
1991 # define INIT_BUF_SIZE  (32 * sizeof(UCHAR_T))
1992
1993 /* Make sure we have at least N more bytes of space in buffer.  */
1994 # ifdef WCHAR
1995 #  define GET_BUFFER_SPACE(n)                                           \
1996     while (((unsigned long)b - (unsigned long)COMPILED_BUFFER_VAR       \
1997             + (n)*sizeof(CHAR_T)) > bufp->allocated)                    \
1998       EXTEND_BUFFER ()
1999 # else /* BYTE */
2000 #  define GET_BUFFER_SPACE(n)                                           \
2001     while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated)  \
2002       EXTEND_BUFFER ()
2003 # endif /* WCHAR */
2004
2005 /* Make sure we have one more byte of buffer space and then add C to it.  */
2006 # define BUF_PUSH(c)                                                    \
2007   do {                                                                  \
2008     GET_BUFFER_SPACE (1);                                               \
2009     *b++ = (UCHAR_T) (c);                                               \
2010   } while (0)
2011
2012
2013 /* Ensure we have two more bytes of buffer space and then append C1 and C2.  */
2014 # define BUF_PUSH_2(c1, c2)                                             \
2015   do {                                                                  \
2016     GET_BUFFER_SPACE (2);                                               \
2017     *b++ = (UCHAR_T) (c1);                                              \
2018     *b++ = (UCHAR_T) (c2);                                              \
2019   } while (0)
2020
2021
2022 /* As with BUF_PUSH_2, except for three bytes.  */
2023 # define BUF_PUSH_3(c1, c2, c3)                                         \
2024   do {                                                                  \
2025     GET_BUFFER_SPACE (3);                                               \
2026     *b++ = (UCHAR_T) (c1);                                              \
2027     *b++ = (UCHAR_T) (c2);                                              \
2028     *b++ = (UCHAR_T) (c3);                                              \
2029   } while (0)
2030
2031 /* Store a jump with opcode OP at LOC to location TO.  We store a
2032    relative address offset by the three bytes the jump itself occupies.  */
2033 # define STORE_JUMP(op, loc, to) \
2034  PREFIX(store_op1) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)))
2035
2036 /* Likewise, for a two-argument jump.  */
2037 # define STORE_JUMP2(op, loc, to, arg) \
2038   PREFIX(store_op2) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), arg)
2039
2040 /* Like `STORE_JUMP', but for inserting.  Assume `b' is the buffer end.  */
2041 # define INSERT_JUMP(op, loc, to) \
2042   PREFIX(insert_op1) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), b)
2043
2044 /* Like `STORE_JUMP2', but for inserting.  Assume `b' is the buffer end.  */
2045 # define INSERT_JUMP2(op, loc, to, arg) \
2046   PREFIX(insert_op2) (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)),\
2047               arg, b)
2048
2049 /* This is not an arbitrary limit: the arguments which represent offsets
2050    into the pattern are two bytes long.  So if 2^16 bytes turns out to
2051    be too small, many things would have to change.  */
2052 /* Any other compiler which, like MSC, has allocation limit below 2^16
2053    bytes will have to use approach similar to what was done below for
2054    MSC and drop MAX_BUF_SIZE a bit.  Otherwise you may end up
2055    reallocating to 0 bytes.  Such thing is not going to work too well.
2056    You have been warned!!  */
2057 # ifndef DEFINED_ONCE
2058 #  if defined _MSC_VER  && !defined WIN32
2059 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
2060    The REALLOC define eliminates a flurry of conversion warnings,
2061    but is not required. */
2062 #   define MAX_BUF_SIZE  65500L
2063 #   define REALLOC(p,s) realloc ((p), (size_t) (s))
2064 #  else
2065 #   define MAX_BUF_SIZE (1L << 16)
2066 #   define REALLOC(p,s) realloc ((p), (s))
2067 #  endif
2068
2069 /* Extend the buffer by twice its current size via realloc and
2070    reset the pointers that pointed into the old block to point to the
2071    correct places in the new one.  If extending the buffer results in it
2072    being larger than MAX_BUF_SIZE, then flag memory exhausted.  */
2073 #  if __BOUNDED_POINTERS__
2074 #   define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
2075 #   define MOVE_BUFFER_POINTER(P) \
2076   (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
2077 #   define ELSE_EXTEND_BUFFER_HIGH_BOUND        \
2078   else                                          \
2079     {                                           \
2080       SET_HIGH_BOUND (b);                       \
2081       SET_HIGH_BOUND (begalt);                  \
2082       if (fixup_alt_jump)                       \
2083         SET_HIGH_BOUND (fixup_alt_jump);        \
2084       if (laststart)                            \
2085         SET_HIGH_BOUND (laststart);             \
2086       if (pending_exact)                        \
2087         SET_HIGH_BOUND (pending_exact);         \
2088     }
2089 #  else
2090 #   define MOVE_BUFFER_POINTER(P) (P) += incr
2091 #   define ELSE_EXTEND_BUFFER_HIGH_BOUND
2092 #  endif
2093 # endif /* not DEFINED_ONCE */
2094
2095 # ifdef WCHAR
2096 #  define EXTEND_BUFFER()                                               \
2097   do {                                                                  \
2098     UCHAR_T *old_buffer = COMPILED_BUFFER_VAR;                          \
2099     int wchar_count;                                                    \
2100     if (bufp->allocated + sizeof(UCHAR_T) > MAX_BUF_SIZE)               \
2101       return REG_ESIZE;                                                 \
2102     bufp->allocated <<= 1;                                              \
2103     if (bufp->allocated > MAX_BUF_SIZE)                                 \
2104       bufp->allocated = MAX_BUF_SIZE;                                   \
2105     /* How many characters the new buffer can have?  */                 \
2106     wchar_count = bufp->allocated / sizeof(UCHAR_T);                    \
2107     if (wchar_count == 0) wchar_count = 1;                              \
2108     /* Truncate the buffer to CHAR_T align.  */                 \
2109     bufp->allocated = wchar_count * sizeof(UCHAR_T);                    \
2110     RETALLOC (COMPILED_BUFFER_VAR, wchar_count, UCHAR_T);               \
2111     bufp->buffer = (char*)COMPILED_BUFFER_VAR;                          \
2112     if (COMPILED_BUFFER_VAR == NULL)                                    \
2113       return REG_ESPACE;                                                \
2114     /* If the buffer moved, move all the pointers into it.  */          \
2115     if (old_buffer != COMPILED_BUFFER_VAR)                              \
2116       {                                                                 \
2117         int incr = COMPILED_BUFFER_VAR - old_buffer;                    \
2118         MOVE_BUFFER_POINTER (b);                                        \
2119         MOVE_BUFFER_POINTER (begalt);                                   \
2120         if (fixup_alt_jump)                                             \
2121           MOVE_BUFFER_POINTER (fixup_alt_jump);                         \
2122         if (laststart)                                                  \
2123           MOVE_BUFFER_POINTER (laststart);                              \
2124         if (pending_exact)                                              \
2125           MOVE_BUFFER_POINTER (pending_exact);                          \
2126       }                                                                 \
2127     ELSE_EXTEND_BUFFER_HIGH_BOUND                                       \
2128   } while (0)
2129 # else /* BYTE */
2130 #  define EXTEND_BUFFER()                                               \
2131   do {                                                                  \
2132     UCHAR_T *old_buffer = COMPILED_BUFFER_VAR;                          \
2133     if (bufp->allocated == MAX_BUF_SIZE)                                \
2134       return REG_ESIZE;                                                 \
2135     bufp->allocated <<= 1;                                              \
2136     if (bufp->allocated > MAX_BUF_SIZE)                                 \
2137       bufp->allocated = MAX_BUF_SIZE;                                   \
2138     bufp->buffer = (UCHAR_T *) REALLOC (COMPILED_BUFFER_VAR,            \
2139                                                 bufp->allocated);       \
2140     if (COMPILED_BUFFER_VAR == NULL)                                    \
2141       return REG_ESPACE;                                                \
2142     /* If the buffer moved, move all the pointers into it.  */          \
2143     if (old_buffer != COMPILED_BUFFER_VAR)                              \
2144       {                                                                 \
2145         int incr = COMPILED_BUFFER_VAR - old_buffer;                    \
2146         MOVE_BUFFER_POINTER (b);                                        \
2147         MOVE_BUFFER_POINTER (begalt);                                   \
2148         if (fixup_alt_jump)                                             \
2149           MOVE_BUFFER_POINTER (fixup_alt_jump);                         \
2150         if (laststart)                                                  \
2151           MOVE_BUFFER_POINTER (laststart);                              \
2152         if (pending_exact)                                              \
2153           MOVE_BUFFER_POINTER (pending_exact);                          \
2154       }                                                                 \
2155     ELSE_EXTEND_BUFFER_HIGH_BOUND                                       \
2156   } while (0)
2157 # endif /* WCHAR */
2158
2159 # ifndef DEFINED_ONCE
2160 /* Since we have one byte reserved for the register number argument to
2161    {start,stop}_memory, the maximum number of groups we can report
2162    things about is what fits in that byte.  */
2163 #  define MAX_REGNUM 255
2164
2165 /* But patterns can have more than `MAX_REGNUM' registers.  We just
2166    ignore the excess.  */
2167 typedef unsigned regnum_t;
2168
2169
2170 /* Macros for the compile stack.  */
2171
2172 /* Since offsets can go either forwards or backwards, this type needs to
2173    be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1.  */
2174 /* int may be not enough when sizeof(int) == 2.  */
2175 typedef long pattern_offset_t;
2176
2177 typedef struct
2178 {
2179   pattern_offset_t begalt_offset;
2180   pattern_offset_t fixup_alt_jump;
2181   pattern_offset_t inner_group_offset;
2182   pattern_offset_t laststart_offset;
2183   regnum_t regnum;
2184 } compile_stack_elt_t;
2185
2186
2187 typedef struct
2188 {
2189   compile_stack_elt_t *stack;
2190   unsigned size;
2191   unsigned avail;                       /* Offset of next open position.  */
2192 } compile_stack_type;
2193
2194
2195 #  define INIT_COMPILE_STACK_SIZE 32
2196
2197 #  define COMPILE_STACK_EMPTY  (compile_stack.avail == 0)
2198 #  define COMPILE_STACK_FULL  (compile_stack.avail == compile_stack.size)
2199
2200 /* The next available element.  */
2201 #  define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
2202
2203 # endif /* not DEFINED_ONCE */
2204
2205 /* Set the bit for character C in a list.  */
2206 # ifndef DEFINED_ONCE
2207 #  define SET_LIST_BIT(c)                               \
2208   (b[((unsigned char) (c)) / BYTEWIDTH]               \
2209    |= 1 << (((unsigned char) c) % BYTEWIDTH))
2210 # endif /* DEFINED_ONCE */
2211
2212 /* Get the next unsigned number in the uncompiled pattern.  */
2213 # define GET_UNSIGNED_NUMBER(num) \
2214   {                                                                     \
2215     while (p != pend)                                                   \
2216       {                                                                 \
2217         PATFETCH (c);                                                   \
2218         if (c < '0' || c > '9')                                         \
2219           break;                                                        \
2220         if (num <= RE_DUP_MAX)                                          \
2221           {                                                             \
2222             if (num < 0)                                                \
2223               num = 0;                                                  \
2224             num = num * 10 + c - '0';                                   \
2225           }                                                             \
2226       }                                                                 \
2227   }
2228
2229 # ifndef DEFINED_ONCE
2230 #  if defined _LIBC || WIDE_CHAR_SUPPORT
2231 /* The GNU C library provides support for user-defined character classes
2232    and the functions from ISO C amendement 1.  */
2233 #   ifdef CHARCLASS_NAME_MAX
2234 #    define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
2235 #   else
2236 /* This shouldn't happen but some implementation might still have this
2237    problem.  Use a reasonable default value.  */
2238 #    define CHAR_CLASS_MAX_LENGTH 256
2239 #   endif
2240
2241 #   ifdef _LIBC
2242 #    define IS_CHAR_CLASS(string) __wctype (string)
2243 #   else
2244 #    define IS_CHAR_CLASS(string) wctype (string)
2245 #   endif
2246 #  else
2247 #   define CHAR_CLASS_MAX_LENGTH  6 /* Namely, `xdigit'.  */
2248
2249 #   define IS_CHAR_CLASS(string)                                        \
2250    (STREQ (string, "alpha") || STREQ (string, "upper")                  \
2251     || STREQ (string, "lower") || STREQ (string, "digit")               \
2252     || STREQ (string, "alnum") || STREQ (string, "xdigit")              \
2253     || STREQ (string, "space") || STREQ (string, "print")               \
2254     || STREQ (string, "punct") || STREQ (string, "graph")               \
2255     || STREQ (string, "cntrl") || STREQ (string, "blank"))
2256 #  endif
2257 # endif /* DEFINED_ONCE */
2258 \f
2259 # ifndef MATCH_MAY_ALLOCATE
2260
2261 /* If we cannot allocate large objects within re_match_2_internal,
2262    we make the fail stack and register vectors global.
2263    The fail stack, we grow to the maximum size when a regexp
2264    is compiled.
2265    The register vectors, we adjust in size each time we
2266    compile a regexp, according to the number of registers it needs.  */
2267
2268 static PREFIX(fail_stack_type) fail_stack;
2269
2270 /* Size with which the following vectors are currently allocated.
2271    That is so we can make them bigger as needed,
2272    but never make them smaller.  */
2273 #  ifdef DEFINED_ONCE
2274 static int regs_allocated_size;
2275
2276 static const char **     regstart, **     regend;
2277 static const char ** old_regstart, ** old_regend;
2278 static const char **best_regstart, **best_regend;
2279 static const char **reg_dummy;
2280 #  endif /* DEFINED_ONCE */
2281
2282 static PREFIX(register_info_type) *PREFIX(reg_info);
2283 static PREFIX(register_info_type) *PREFIX(reg_info_dummy);
2284
2285 /* Make the register vectors big enough for NUM_REGS registers,
2286    but don't make them smaller.  */
2287
2288 static void
2289 PREFIX(regex_grow_registers) (num_regs)
2290      int num_regs;
2291 {
2292   if (num_regs > regs_allocated_size)
2293     {
2294       RETALLOC_IF (regstart,     num_regs, const char *);
2295       RETALLOC_IF (regend,       num_regs, const char *);
2296       RETALLOC_IF (old_regstart, num_regs, const char *);
2297       RETALLOC_IF (old_regend,   num_regs, const char *);
2298       RETALLOC_IF (best_regstart, num_regs, const char *);
2299       RETALLOC_IF (best_regend,  num_regs, const char *);
2300       RETALLOC_IF (PREFIX(reg_info), num_regs, PREFIX(register_info_type));
2301       RETALLOC_IF (reg_dummy,    num_regs, const char *);
2302       RETALLOC_IF (PREFIX(reg_info_dummy), num_regs, PREFIX(register_info_type));
2303
2304       regs_allocated_size = num_regs;
2305     }
2306 }
2307
2308 # endif /* not MATCH_MAY_ALLOCATE */
2309 \f
2310 # ifndef DEFINED_ONCE
2311 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2312                                                  compile_stack,
2313                                                  regnum_t regnum));
2314 # endif /* not DEFINED_ONCE */
2315
2316 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2317    Returns one of error codes defined in `regex.h', or zero for success.
2318
2319    Assumes the `allocated' (and perhaps `buffer') and `translate'
2320    fields are set in BUFP on entry.
2321
2322    If it succeeds, results are put in BUFP (if it returns an error, the
2323    contents of BUFP are undefined):
2324      `buffer' is the compiled pattern;
2325      `syntax' is set to SYNTAX;
2326      `used' is set to the length of the compiled pattern;
2327      `fastmap_accurate' is zero;
2328      `re_nsub' is the number of subexpressions in PATTERN;
2329      `not_bol' and `not_eol' are zero;
2330
2331    The `fastmap' and `newline_anchor' fields are neither
2332    examined nor set.  */
2333
2334 /* Return, freeing storage we allocated.  */
2335 # ifdef WCHAR
2336 #  define FREE_STACK_RETURN(value)              \
2337   return (free(pattern), free(mbs_offset), free(is_binary), free (compile_stack.stack), value)
2338 # else
2339 #  define FREE_STACK_RETURN(value)              \
2340   return (free (compile_stack.stack), value)
2341 # endif /* WCHAR */
2342
2343 static reg_errcode_t
2344 PREFIX(regex_compile) (ARG_PREFIX(pattern), ARG_PREFIX(size), syntax, bufp)
2345      const char *ARG_PREFIX(pattern);
2346      size_t ARG_PREFIX(size);
2347      reg_syntax_t syntax;
2348      struct re_pattern_buffer *bufp;
2349 {
2350   /* We fetch characters from PATTERN here.  Even though PATTERN is
2351      `char *' (i.e., signed), we declare these variables as unsigned, so
2352      they can be reliably used as array indices.  */
2353   register UCHAR_T c, c1;
2354
2355 #ifdef WCHAR
2356   /* A temporary space to keep wchar_t pattern and compiled pattern.  */
2357   CHAR_T *pattern, *COMPILED_BUFFER_VAR;
2358   size_t size;
2359   /* offset buffer for optimization. See convert_mbs_to_wc.  */
2360   int *mbs_offset = NULL;
2361   /* It hold whether each wchar_t is binary data or not.  */
2362   char *is_binary = NULL;
2363   /* A flag whether exactn is handling binary data or not.  */
2364   char is_exactn_bin = FALSE;
2365 #endif /* WCHAR */
2366
2367   /* A random temporary spot in PATTERN.  */
2368   const CHAR_T *p1;
2369
2370   /* Points to the end of the buffer, where we should append.  */
2371   register UCHAR_T *b;
2372
2373   /* Keeps track of unclosed groups.  */
2374   compile_stack_type compile_stack;
2375
2376   /* Points to the current (ending) position in the pattern.  */
2377 #ifdef WCHAR
2378   const CHAR_T *p;
2379   const CHAR_T *pend;
2380 #else /* BYTE */
2381   const CHAR_T *p = pattern;
2382   const CHAR_T *pend = pattern + size;
2383 #endif /* WCHAR */
2384
2385   /* How to translate the characters in the pattern.  */
2386   RE_TRANSLATE_TYPE translate = bufp->translate;
2387
2388   /* Address of the count-byte of the most recently inserted `exactn'
2389      command.  This makes it possible to tell if a new exact-match
2390      character can be added to that command or if the character requires
2391      a new `exactn' command.  */
2392   UCHAR_T *pending_exact = 0;
2393
2394   /* Address of start of the most recently finished expression.
2395      This tells, e.g., postfix * where to find the start of its
2396      operand.  Reset at the beginning of groups and alternatives.  */
2397   UCHAR_T *laststart = 0;
2398
2399   /* Address of beginning of regexp, or inside of last group.  */
2400   UCHAR_T *begalt;
2401
2402   /* Address of the place where a forward jump should go to the end of
2403      the containing expression.  Each alternative of an `or' -- except the
2404      last -- ends with a forward jump of this sort.  */
2405   UCHAR_T *fixup_alt_jump = 0;
2406
2407   /* Counts open-groups as they are encountered.  Remembered for the
2408      matching close-group on the compile stack, so the same register
2409      number is put in the stop_memory as the start_memory.  */
2410   regnum_t regnum = 0;
2411
2412 #ifdef WCHAR
2413   /* Initialize the wchar_t PATTERN and offset_buffer.  */
2414   p = pend = pattern = TALLOC(csize + 1, CHAR_T);
2415   mbs_offset = TALLOC(csize + 1, int);
2416   is_binary = TALLOC(csize + 1, char);
2417   if (pattern == NULL || mbs_offset == NULL || is_binary == NULL)
2418     {
2419       free(pattern);
2420       free(mbs_offset);
2421       free(is_binary);
2422       return REG_ESPACE;
2423     }
2424   pattern[csize] = L'\0';       /* sentinel */
2425   size = convert_mbs_to_wcs(pattern, cpattern, csize, mbs_offset, is_binary);
2426   pend = p + size;
2427   if (size < 0)
2428     {
2429       free(pattern);
2430       free(mbs_offset);
2431       free(is_binary);
2432       return REG_BADPAT;
2433     }
2434 #endif
2435
2436 #ifdef DEBUG
2437   DEBUG_PRINT1 ("\nCompiling pattern: ");
2438   if (debug)
2439     {
2440       unsigned debug_count;
2441
2442       for (debug_count = 0; debug_count < size; debug_count++)
2443         PUT_CHAR (pattern[debug_count]);
2444       putchar ('\n');
2445     }
2446 #endif /* DEBUG */
2447
2448   /* Initialize the compile stack.  */
2449   compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2450   if (compile_stack.stack == NULL)
2451     {
2452 #ifdef WCHAR
2453       free(pattern);
2454       free(mbs_offset);
2455       free(is_binary);
2456 #endif
2457       return REG_ESPACE;
2458     }
2459
2460   compile_stack.size = INIT_COMPILE_STACK_SIZE;
2461   compile_stack.avail = 0;
2462
2463   /* Initialize the pattern buffer.  */
2464   bufp->syntax = syntax;
2465   bufp->fastmap_accurate = 0;
2466   bufp->not_bol = bufp->not_eol = 0;
2467
2468   /* Set `used' to zero, so that if we return an error, the pattern
2469      printer (for debugging) will think there's no pattern.  We reset it
2470      at the end.  */
2471   bufp->used = 0;
2472
2473   /* Always count groups, whether or not bufp->no_sub is set.  */
2474   bufp->re_nsub = 0;
2475
2476 #if !defined emacs && !defined SYNTAX_TABLE
2477   /* Initialize the syntax table.  */
2478    init_syntax_once ();
2479 #endif
2480
2481   if (bufp->allocated == 0)
2482     {
2483       if (bufp->buffer)
2484         { /* If zero allocated, but buffer is non-null, try to realloc
2485              enough space.  This loses if buffer's address is bogus, but
2486              that is the user's responsibility.  */
2487 #ifdef WCHAR
2488           /* Free bufp->buffer and allocate an array for wchar_t pattern
2489              buffer.  */
2490           free(bufp->buffer);
2491           COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE/sizeof(UCHAR_T),
2492                                         UCHAR_T);
2493 #else
2494           RETALLOC (COMPILED_BUFFER_VAR, INIT_BUF_SIZE, UCHAR_T);
2495 #endif /* WCHAR */
2496         }
2497       else
2498         { /* Caller did not allocate a buffer.  Do it for them.  */
2499           COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE / sizeof(UCHAR_T),
2500                                         UCHAR_T);
2501         }
2502
2503       if (!COMPILED_BUFFER_VAR) FREE_STACK_RETURN (REG_ESPACE);
2504 #ifdef WCHAR
2505       bufp->buffer = (char*)COMPILED_BUFFER_VAR;
2506 #endif /* WCHAR */
2507       bufp->allocated = INIT_BUF_SIZE;
2508     }
2509 #ifdef WCHAR
2510   else
2511     COMPILED_BUFFER_VAR = (UCHAR_T*) bufp->buffer;
2512 #endif
2513
2514   begalt = b = COMPILED_BUFFER_VAR;
2515
2516   /* Loop through the uncompiled pattern until we're at the end.  */
2517   while (p != pend)
2518     {
2519       PATFETCH (c);
2520
2521       switch (c)
2522         {
2523         case '^':
2524           {
2525             if (   /* If at start of pattern, it's an operator.  */
2526                    p == pattern + 1
2527                    /* If context independent, it's an operator.  */
2528                 || syntax & RE_CONTEXT_INDEP_ANCHORS
2529                    /* Otherwise, depends on what's come before.  */
2530                 || PREFIX(at_begline_loc_p) (pattern, p, syntax))
2531               BUF_PUSH (begline);
2532             else
2533               goto normal_char;
2534           }
2535           break;
2536
2537
2538         case '$':
2539           {
2540             if (   /* If at end of pattern, it's an operator.  */
2541                    p == pend
2542                    /* If context independent, it's an operator.  */
2543                 || syntax & RE_CONTEXT_INDEP_ANCHORS
2544                    /* Otherwise, depends on what's next.  */
2545                 || PREFIX(at_endline_loc_p) (p, pend, syntax))
2546                BUF_PUSH (endline);
2547              else
2548                goto normal_char;
2549            }
2550            break;
2551
2552
2553         case '+':
2554         case '?':
2555           if ((syntax & RE_BK_PLUS_QM)
2556               || (syntax & RE_LIMITED_OPS))
2557             goto normal_char;
2558         handle_plus:
2559         case '*':
2560           /* If there is no previous pattern... */
2561           if (!laststart)
2562             {
2563               if (syntax & RE_CONTEXT_INVALID_OPS)
2564                 FREE_STACK_RETURN (REG_BADRPT);
2565               else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2566                 goto normal_char;
2567             }
2568
2569           {
2570             /* Are we optimizing this jump?  */
2571             boolean keep_string_p = false;
2572
2573             /* 1 means zero (many) matches is allowed.  */
2574             char zero_times_ok = 0, many_times_ok = 0;
2575
2576             /* If there is a sequence of repetition chars, collapse it
2577                down to just one (the right one).  We can't combine
2578                interval operators with these because of, e.g., `a{2}*',
2579                which should only match an even number of `a's.  */
2580
2581             for (;;)
2582               {
2583                 zero_times_ok |= c != '+';
2584                 many_times_ok |= c != '?';
2585
2586                 if (p == pend)
2587                   break;
2588
2589                 PATFETCH (c);
2590
2591                 if (c == '*'
2592                     || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2593                   ;
2594
2595                 else if (syntax & RE_BK_PLUS_QM  &&  c == '\\')
2596                   {
2597                     if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2598
2599                     PATFETCH (c1);
2600                     if (!(c1 == '+' || c1 == '?'))
2601                       {
2602                         PATUNFETCH;
2603                         PATUNFETCH;
2604                         break;
2605                       }
2606
2607                     c = c1;
2608                   }
2609                 else
2610                   {
2611                     PATUNFETCH;
2612                     break;
2613                   }
2614
2615                 /* If we get here, we found another repeat character.  */
2616                }
2617
2618             /* Star, etc. applied to an empty pattern is equivalent
2619                to an empty pattern.  */
2620             if (!laststart)
2621               break;
2622
2623             /* Now we know whether or not zero matches is allowed
2624                and also whether or not two or more matches is allowed.  */
2625             if (many_times_ok)
2626               { /* More than one repetition is allowed, so put in at the
2627                    end a backward relative jump from `b' to before the next
2628                    jump we're going to put in below (which jumps from
2629                    laststart to after this jump).
2630
2631                    But if we are at the `*' in the exact sequence `.*\n',
2632                    insert an unconditional jump backwards to the .,
2633                    instead of the beginning of the loop.  This way we only
2634                    push a failure point once, instead of every time
2635                    through the loop.  */
2636                 assert (p - 1 > pattern);
2637
2638                 /* Allocate the space for the jump.  */
2639                 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2640
2641                 /* We know we are not at the first character of the pattern,
2642                    because laststart was nonzero.  And we've already
2643                    incremented `p', by the way, to be the character after
2644                    the `*'.  Do we have to do something analogous here
2645                    for null bytes, because of RE_DOT_NOT_NULL?  */
2646                 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2647                     && zero_times_ok
2648                     && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2649                     && !(syntax & RE_DOT_NEWLINE))
2650                   { /* We have .*\n.  */
2651                     STORE_JUMP (jump, b, laststart);
2652                     keep_string_p = true;
2653                   }
2654                 else
2655                   /* Anything else.  */
2656                   STORE_JUMP (maybe_pop_jump, b, laststart -
2657                               (1 + OFFSET_ADDRESS_SIZE));
2658
2659                 /* We've added more stuff to the buffer.  */
2660                 b += 1 + OFFSET_ADDRESS_SIZE;
2661               }
2662
2663             /* On failure, jump from laststart to b + 3, which will be the
2664                end of the buffer after this jump is inserted.  */
2665             /* ifdef WCHAR, 'b + 1 + OFFSET_ADDRESS_SIZE' instead of
2666                'b + 3'.  */
2667             GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2668             INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2669                                        : on_failure_jump,
2670                          laststart, b + 1 + OFFSET_ADDRESS_SIZE);
2671             pending_exact = 0;
2672             b += 1 + OFFSET_ADDRESS_SIZE;
2673
2674             if (!zero_times_ok)
2675               {
2676                 /* At least one repetition is required, so insert a
2677                    `dummy_failure_jump' before the initial
2678                    `on_failure_jump' instruction of the loop. This
2679                    effects a skip over that instruction the first time
2680                    we hit that loop.  */
2681                 GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2682                 INSERT_JUMP (dummy_failure_jump, laststart, laststart +
2683                              2 + 2 * OFFSET_ADDRESS_SIZE);
2684                 b += 1 + OFFSET_ADDRESS_SIZE;
2685               }
2686             }
2687           break;
2688
2689
2690         case '.':
2691           laststart = b;
2692           BUF_PUSH (anychar);
2693           break;
2694
2695
2696         case '[':
2697           {
2698             boolean had_char_class = false;
2699 #ifdef WCHAR
2700             CHAR_T range_start = 0xffffffff;
2701 #else
2702             unsigned int range_start = 0xffffffff;
2703 #endif
2704             if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2705
2706 #ifdef WCHAR
2707             /* We assume a charset(_not) structure as a wchar_t array.
2708                charset[0] = (re_opcode_t) charset(_not)
2709                charset[1] = l (= length of char_classes)
2710                charset[2] = m (= length of collating_symbols)
2711                charset[3] = n (= length of equivalence_classes)
2712                charset[4] = o (= length of char_ranges)
2713                charset[5] = p (= length of chars)
2714
2715                charset[6] = char_class (wctype_t)
2716                charset[6+CHAR_CLASS_SIZE] = char_class (wctype_t)
2717                          ...
2718                charset[l+5]  = char_class (wctype_t)
2719
2720                charset[l+6]  = collating_symbol (wchar_t)
2721                             ...
2722                charset[l+m+5]  = collating_symbol (wchar_t)
2723                                         ifdef _LIBC we use the index if
2724                                         _NL_COLLATE_SYMB_EXTRAMB instead of
2725                                         wchar_t string.
2726
2727                charset[l+m+6]  = equivalence_classes (wchar_t)
2728                               ...
2729                charset[l+m+n+5]  = equivalence_classes (wchar_t)
2730                                         ifdef _LIBC we use the index in
2731                                         _NL_COLLATE_WEIGHT instead of
2732                                         wchar_t string.
2733
2734                charset[l+m+n+6] = range_start
2735                charset[l+m+n+7] = range_end
2736                                ...
2737                charset[l+m+n+2o+4] = range_start
2738                charset[l+m+n+2o+5] = range_end
2739                                         ifdef _LIBC we use the value looked up
2740                                         in _NL_COLLATE_COLLSEQ instead of
2741                                         wchar_t character.
2742
2743                charset[l+m+n+2o+6] = char
2744                                   ...
2745                charset[l+m+n+2o+p+5] = char
2746
2747              */
2748
2749             /* We need at least 6 spaces: the opcode, the length of
2750                char_classes, the length of collating_symbols, the length of
2751                equivalence_classes, the length of char_ranges, the length of
2752                chars.  */
2753             GET_BUFFER_SPACE (6);
2754
2755             /* Save b as laststart. And We use laststart as the pointer
2756                to the first element of the charset here.
2757                In other words, laststart[i] indicates charset[i].  */
2758             laststart = b;
2759
2760             /* We test `*p == '^' twice, instead of using an if
2761                statement, so we only need one BUF_PUSH.  */
2762             BUF_PUSH (*p == '^' ? charset_not : charset);
2763             if (*p == '^')
2764               p++;
2765
2766             /* Push the length of char_classes, the length of
2767                collating_symbols, the length of equivalence_classes, the
2768                length of char_ranges and the length of chars.  */
2769             BUF_PUSH_3 (0, 0, 0);
2770             BUF_PUSH_2 (0, 0);
2771
2772             /* Remember the first position in the bracket expression.  */
2773             p1 = p;
2774
2775             /* charset_not matches newline according to a syntax bit.  */
2776             if ((re_opcode_t) b[-6] == charset_not
2777                 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2778               {
2779                 BUF_PUSH('\n');
2780                 laststart[5]++; /* Update the length of characters  */
2781               }
2782
2783             /* Read in characters and ranges, setting map bits.  */
2784             for (;;)
2785               {
2786                 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2787
2788                 PATFETCH (c);
2789
2790                 /* \ might escape characters inside [...] and [^...].  */
2791                 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2792                   {
2793                     if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2794
2795                     PATFETCH (c1);
2796                     BUF_PUSH(c1);
2797                     laststart[5]++; /* Update the length of chars  */
2798                     range_start = c1;
2799                     continue;
2800                   }
2801
2802                 /* Could be the end of the bracket expression.  If it's
2803                    not (i.e., when the bracket expression is `[]' so
2804                    far), the ']' character bit gets set way below.  */
2805                 if (c == ']' && p != p1 + 1)
2806                   break;
2807
2808                 /* Look ahead to see if it's a range when the last thing
2809                    was a character class.  */
2810                 if (had_char_class && c == '-' && *p != ']')
2811                   FREE_STACK_RETURN (REG_ERANGE);
2812
2813                 /* Look ahead to see if it's a range when the last thing
2814                    was a character: if this is a hyphen not at the
2815                    beginning or the end of a list, then it's the range
2816                    operator.  */
2817                 if (c == '-'
2818                     && !(p - 2 >= pattern && p[-2] == '[')
2819                     && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2820                     && *p != ']')
2821                   {
2822                     reg_errcode_t ret;
2823                     /* Allocate the space for range_start and range_end.  */
2824                     GET_BUFFER_SPACE (2);
2825                     /* Update the pointer to indicate end of buffer.  */
2826                     b += 2;
2827                     ret = wcs_compile_range (range_start, &p, pend, translate,
2828                                          syntax, b, laststart);
2829                     if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2830                     range_start = 0xffffffff;
2831                   }
2832                 else if (p[0] == '-' && p[1] != ']')
2833                   { /* This handles ranges made up of characters only.  */
2834                     reg_errcode_t ret;
2835
2836                     /* Move past the `-'.  */
2837                     PATFETCH (c1);
2838                     /* Allocate the space for range_start and range_end.  */
2839                     GET_BUFFER_SPACE (2);
2840                     /* Update the pointer to indicate end of buffer.  */
2841                     b += 2;
2842                     ret = wcs_compile_range (c, &p, pend, translate, syntax, b,
2843                                          laststart);
2844                     if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2845                     range_start = 0xffffffff;
2846                   }
2847
2848                 /* See if we're at the beginning of a possible character
2849                    class.  */
2850                 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2851                   { /* Leave room for the null.  */
2852                     char str[CHAR_CLASS_MAX_LENGTH + 1];
2853
2854                     PATFETCH (c);
2855                     c1 = 0;
2856
2857                     /* If pattern is `[[:'.  */
2858                     if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2859
2860                     for (;;)
2861                       {
2862                         PATFETCH (c);
2863                         if ((c == ':' && *p == ']') || p == pend)
2864                           break;
2865                         if (c1 < CHAR_CLASS_MAX_LENGTH)
2866                           str[c1++] = c;
2867                         else
2868                           /* This is in any case an invalid class name.  */
2869                           str[0] = '\0';
2870                       }
2871                     str[c1] = '\0';
2872
2873                     /* If isn't a word bracketed by `[:' and `:]':
2874                        undo the ending character, the letters, and leave
2875                        the leading `:' and `[' (but store them as character).  */
2876                     if (c == ':' && *p == ']')
2877                       {
2878                         wctype_t wt;
2879                         uintptr_t alignedp;
2880
2881                         /* Query the character class as wctype_t.  */
2882                         wt = IS_CHAR_CLASS (str);
2883                         if (wt == 0)
2884                           FREE_STACK_RETURN (REG_ECTYPE);
2885
2886                         /* Throw away the ] at the end of the character
2887                            class.  */
2888                         PATFETCH (c);
2889
2890                         if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2891
2892                         /* Allocate the space for character class.  */
2893                         GET_BUFFER_SPACE(CHAR_CLASS_SIZE);
2894                         /* Update the pointer to indicate end of buffer.  */
2895                         b += CHAR_CLASS_SIZE;
2896                         /* Move data which follow character classes
2897                             not to violate the data.  */
2898                         insert_space(CHAR_CLASS_SIZE,
2899                                      laststart + 6 + laststart[1],
2900                                      b - 1);
2901                         alignedp = ((uintptr_t)(laststart + 6 + laststart[1])
2902                                     + __alignof__(wctype_t) - 1)
2903                                     & ~(uintptr_t)(__alignof__(wctype_t) - 1);
2904                         /* Store the character class.  */
2905                         *((wctype_t*)alignedp) = wt;
2906                         /* Update length of char_classes */
2907                         laststart[1] += CHAR_CLASS_SIZE;
2908
2909                         had_char_class = true;
2910                       }
2911                     else
2912                       {
2913                         c1++;
2914                         while (c1--)
2915                           PATUNFETCH;
2916                         BUF_PUSH ('[');
2917                         BUF_PUSH (':');
2918                         laststart[5] += 2; /* Update the length of characters  */
2919                         range_start = ':';
2920                         had_char_class = false;
2921                       }
2922                   }
2923                 else if (syntax & RE_CHAR_CLASSES && c == '[' && (*p == '='
2924                                                           || *p == '.'))
2925                   {
2926                     CHAR_T str[128];    /* Should be large enough.  */
2927                     CHAR_T delim = *p; /* '=' or '.'  */
2928 # ifdef _LIBC
2929                     uint32_t nrules =
2930                       _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2931 # endif
2932                     PATFETCH (c);
2933                     c1 = 0;
2934
2935                     /* If pattern is `[[=' or '[[.'.  */
2936                     if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2937
2938                     for (;;)
2939                       {
2940                         PATFETCH (c);
2941                         if ((c == delim && *p == ']') || p == pend)
2942                           break;
2943                         if (c1 < sizeof (str) - 1)
2944                           str[c1++] = c;
2945                         else
2946                           /* This is in any case an invalid class name.  */
2947                           str[0] = '\0';
2948                       }
2949                     str[c1] = '\0';
2950
2951                     if (c == delim && *p == ']' && str[0] != '\0')
2952                       {
2953                         unsigned int i, offset;
2954                         /* If we have no collation data we use the default
2955                            collation in which each character is in a class
2956                            by itself.  It also means that ASCII is the
2957                            character set and therefore we cannot have character
2958                            with more than one byte in the multibyte
2959                            representation.  */
2960
2961                         /* If not defined _LIBC, we push the name and
2962                            `\0' for the sake of matching performance.  */
2963                         int datasize = c1 + 1;
2964
2965 # ifdef _LIBC
2966                         int32_t idx = 0;
2967                         if (nrules == 0)
2968 # endif
2969                           {
2970                             if (c1 != 1)
2971                               FREE_STACK_RETURN (REG_ECOLLATE);
2972                           }
2973 # ifdef _LIBC
2974                         else
2975                           {
2976                             const int32_t *table;
2977                             const int32_t *weights;
2978                             const int32_t *extra;
2979                             const int32_t *indirect;
2980                             wint_t *cp;
2981
2982                             /* This #include defines a local function!  */
2983 #  include <locale/weightwc.h>
2984
2985                             if(delim == '=')
2986                               {
2987                                 /* We push the index for equivalence class.  */
2988                                 cp = (wint_t*)str;
2989
2990                                 table = (const int32_t *)
2991                                   _NL_CURRENT (LC_COLLATE,
2992                                                _NL_COLLATE_TABLEWC);
2993                                 weights = (const int32_t *)
2994                                   _NL_CURRENT (LC_COLLATE,
2995                                                _NL_COLLATE_WEIGHTWC);
2996                                 extra = (const int32_t *)
2997                                   _NL_CURRENT (LC_COLLATE,
2998                                                _NL_COLLATE_EXTRAWC);
2999                                 indirect = (const int32_t *)
3000                                   _NL_CURRENT (LC_COLLATE,
3001                                                _NL_COLLATE_INDIRECTWC);
3002
3003                                 idx = findidx ((const wint_t**)&cp);
3004                                 if (idx == 0 || cp < (wint_t*) str + c1)
3005                                   /* This is no valid character.  */
3006                                   FREE_STACK_RETURN (REG_ECOLLATE);
3007
3008                                 str[0] = (wchar_t)idx;
3009                               }
3010                             else /* delim == '.' */
3011                               {
3012                                 /* We push collation sequence value
3013                                    for collating symbol.  */
3014                                 int32_t table_size;
3015                                 const int32_t *symb_table;
3016                                 const unsigned char *extra;
3017                                 int32_t idx;
3018                                 int32_t elem;
3019                                 int32_t second;
3020                                 int32_t hash;
3021                                 char char_str[c1];
3022
3023                                 /* We have to convert the name to a single-byte
3024                                    string.  This is possible since the names
3025                                    consist of ASCII characters and the internal
3026                                    representation is UCS4.  */
3027                                 for (i = 0; i < c1; ++i)
3028                                   char_str[i] = str[i];
3029
3030                                 table_size =
3031                                   _NL_CURRENT_WORD (LC_COLLATE,
3032                                                     _NL_COLLATE_SYMB_HASH_SIZEMB);
3033                                 symb_table = (const int32_t *)
3034                                   _NL_CURRENT (LC_COLLATE,
3035                                                _NL_COLLATE_SYMB_TABLEMB);
3036                                 extra = (const unsigned char *)
3037                                   _NL_CURRENT (LC_COLLATE,
3038                                                _NL_COLLATE_SYMB_EXTRAMB);
3039
3040                                 /* Locate the character in the hashing table.  */
3041                                 hash = elem_hash (char_str, c1);
3042
3043                                 idx = 0;
3044                                 elem = hash % table_size;
3045                                 second = hash % (table_size - 2);
3046                                 while (symb_table[2 * elem] != 0)
3047                                   {
3048                                     /* First compare the hashing value.  */
3049                                     if (symb_table[2 * elem] == hash
3050                                         && c1 == extra[symb_table[2 * elem + 1]]
3051                                         && memcmp (str,
3052                                                    &extra[symb_table[2 * elem + 1]
3053                                                          + 1], c1) == 0)
3054                                       {
3055                                         /* Yep, this is the entry.  */
3056                                         idx = symb_table[2 * elem + 1];
3057                                         idx += 1 + extra[idx];
3058                                         break;
3059                                       }
3060
3061                                     /* Next entry.  */
3062                                     elem += second;
3063                                   }
3064
3065                                 if (symb_table[2 * elem] != 0)
3066                                   {
3067                                     /* Compute the index of the byte sequence
3068                                        in the table.  */
3069                                     idx += 1 + extra[idx];
3070                                     /* Adjust for the alignment.  */
3071                                     idx = (idx + 3) & ~4;
3072
3073                                     str[0] = (wchar_t) idx + 4;
3074                                   }
3075                                 else if (symb_table[2 * elem] == 0 && c1 == 1)
3076                                   {
3077                                     /* No valid character.  Match it as a
3078                                        single byte character.  */
3079                                     had_char_class = false;
3080                                     BUF_PUSH(str[0]);
3081                                     /* Update the length of characters  */
3082                                     laststart[5]++;
3083                                     range_start = str[0];
3084
3085                                     /* Throw away the ] at the end of the
3086                                        collating symbol.  */
3087                                     PATFETCH (c);
3088                                     /* exit from the switch block.  */
3089                                     continue;
3090                                   }
3091                                 else
3092                                   FREE_STACK_RETURN (REG_ECOLLATE);
3093                               }
3094                             datasize = 1;
3095                           }
3096 # endif
3097                         /* Throw away the ] at the end of the equivalence
3098                            class (or collating symbol).  */
3099                         PATFETCH (c);
3100
3101                         /* Allocate the space for the equivalence class
3102                            (or collating symbol) (and '\0' if needed).  */
3103                         GET_BUFFER_SPACE(datasize);
3104                         /* Update the pointer to indicate end of buffer.  */
3105                         b += datasize;
3106
3107                         if (delim == '=')
3108                           { /* equivalence class  */
3109                             /* Calculate the offset of char_ranges,
3110                                which is next to equivalence_classes.  */
3111                             offset = laststart[1] + laststart[2]
3112                               + laststart[3] +6;
3113                             /* Insert space.  */
3114                             insert_space(datasize, laststart + offset, b - 1);
3115
3116                             /* Write the equivalence_class and \0.  */
3117                             for (i = 0 ; i < datasize ; i++)
3118                               laststart[offset + i] = str[i];
3119
3120                             /* Update the length of equivalence_classes.  */
3121                             laststart[3] += datasize;
3122                             had_char_class = true;
3123                           }
3124                         else /* delim == '.' */
3125                           { /* collating symbol  */
3126                             /* Calculate the offset of the equivalence_classes,
3127                                which is next to collating_symbols.  */
3128                             offset = laststart[1] + laststart[2] + 6;
3129                             /* Insert space and write the collationg_symbol
3130                                and \0.  */
3131                             insert_space(datasize, laststart + offset, b-1);
3132                             for (i = 0 ; i < datasize ; i++)
3133                               laststart[offset + i] = str[i];
3134
3135                             /* In re_match_2_internal if range_start < -1, we
3136                                assume -range_start is the offset of the
3137                                collating symbol which is specified as
3138                                the character of the range start.  So we assign
3139                                -(laststart[1] + laststart[2] + 6) to
3140                                range_start.  */
3141                             range_start = -(laststart[1] + laststart[2] + 6);
3142                             /* Update the length of collating_symbol.  */
3143                             laststart[2] += datasize;
3144                             had_char_class = false;
3145                           }
3146                       }
3147                     else
3148                       {
3149                         c1++;
3150                         while (c1--)
3151                           PATUNFETCH;
3152                         BUF_PUSH ('[');
3153                         BUF_PUSH (delim);
3154                         laststart[5] += 2; /* Update the length of characters  */
3155                         range_start = delim;
3156                         had_char_class = false;
3157                       }
3158                   }
3159                 else
3160                   {
3161                     had_char_class = false;
3162                     BUF_PUSH(c);
3163                     laststart[5]++;  /* Update the length of characters  */
3164                     range_start = c;
3165                   }
3166               }
3167
3168 #else /* BYTE */
3169             /* Ensure that we have enough space to push a charset: the
3170                opcode, the length count, and the bitset; 34 bytes in all.  */
3171             GET_BUFFER_SPACE (34);
3172
3173             laststart = b;
3174
3175             /* We test `*p == '^' twice, instead of using an if
3176                statement, so we only need one BUF_PUSH.  */
3177             BUF_PUSH (*p == '^' ? charset_not : charset);
3178             if (*p == '^')
3179               p++;
3180
3181             /* Remember the first position in the bracket expression.  */
3182             p1 = p;
3183
3184             /* Push the number of bytes in the bitmap.  */
3185             BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
3186
3187             /* Clear the whole map.  */
3188             bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
3189
3190             /* charset_not matches newline according to a syntax bit.  */
3191             if ((re_opcode_t) b[-2] == charset_not
3192                 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
3193               SET_LIST_BIT ('\n');
3194
3195             /* Read in characters and ranges, setting map bits.  */
3196             for (;;)
3197               {
3198                 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3199
3200                 PATFETCH (c);
3201
3202                 /* \ might escape characters inside [...] and [^...].  */
3203                 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
3204                   {
3205                     if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3206
3207                     PATFETCH (c1);
3208                     SET_LIST_BIT (c1);
3209                     range_start = c1;
3210                     continue;
3211                   }
3212
3213                 /* Could be the end of the bracket expression.  If it's
3214                    not (i.e., when the bracket expression is `[]' so
3215                    far), the ']' character bit gets set way below.  */
3216                 if (c == ']' && p != p1 + 1)
3217                   break;
3218
3219                 /* Look ahead to see if it's a range when the last thing
3220                    was a character class.  */
3221                 if (had_char_class && c == '-' && *p != ']')
3222                   FREE_STACK_RETURN (REG_ERANGE);
3223
3224                 /* Look ahead to see if it's a range when the last thing
3225                    was a character: if this is a hyphen not at the
3226                    beginning or the end of a list, then it's the range
3227                    operator.  */
3228                 if (c == '-'
3229                     && !(p - 2 >= pattern && p[-2] == '[')
3230                     && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
3231                     && *p != ']')
3232                   {
3233                     reg_errcode_t ret
3234                       = byte_compile_range (range_start, &p, pend, translate,
3235                                             syntax, b);
3236                     if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3237                     range_start = 0xffffffff;
3238                   }
3239
3240                 else if (p[0] == '-' && p[1] != ']')
3241                   { /* This handles ranges made up of characters only.  */
3242                     reg_errcode_t ret;
3243
3244                     /* Move past the `-'.  */
3245                     PATFETCH (c1);
3246
3247                     ret = byte_compile_range (c, &p, pend, translate, syntax, b);
3248                     if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3249                     range_start = 0xffffffff;
3250                   }
3251
3252                 /* See if we're at the beginning of a possible character
3253                    class.  */
3254
3255                 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
3256                   { /* Leave room for the null.  */
3257                     char str[CHAR_CLASS_MAX_LENGTH + 1];
3258
3259                     PATFETCH (c);
3260                     c1 = 0;
3261
3262                     /* If pattern is `[[:'.  */
3263                     if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3264
3265                     for (;;)
3266                       {
3267                         PATFETCH (c);
3268                         if ((c == ':' && *p == ']') || p == pend)
3269                           break;
3270                         if (c1 < CHAR_CLASS_MAX_LENGTH)
3271                           str[c1++] = c;
3272                         else
3273                           /* This is in any case an invalid class name.  */
3274                           str[0] = '\0';
3275                       }
3276                     str[c1] = '\0';
3277
3278                     /* If isn't a word bracketed by `[:' and `:]':
3279                        undo the ending character, the letters, and leave
3280                        the leading `:' and `[' (but set bits for them).  */
3281                     if (c == ':' && *p == ']')
3282                       {
3283 # if defined _LIBC || WIDE_CHAR_SUPPORT
3284                         boolean is_lower = STREQ (str, "lower");
3285                         boolean is_upper = STREQ (str, "upper");
3286                         wctype_t wt;
3287                         int ch;
3288
3289                         wt = IS_CHAR_CLASS (str);
3290                         if (wt == 0)
3291                           FREE_STACK_RETURN (REG_ECTYPE);
3292
3293                         /* Throw away the ] at the end of the character
3294                            class.  */
3295                         PATFETCH (c);
3296
3297                         if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3298
3299                         for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
3300                           {
3301 #  ifdef _LIBC
3302                             if (__iswctype (__btowc (ch), wt))
3303                               SET_LIST_BIT (ch);
3304 #  else
3305                             if (iswctype (btowc (ch), wt))
3306                               SET_LIST_BIT (ch);
3307 #  endif
3308
3309                             if (translate && (is_upper || is_lower)
3310                                 && (ISUPPER (ch) || ISLOWER (ch)))
3311                               SET_LIST_BIT (ch);
3312                           }
3313
3314                         had_char_class = true;
3315 # else
3316                         int ch;
3317                         boolean is_alnum = STREQ (str, "alnum");
3318                         boolean is_alpha = STREQ (str, "alpha");
3319                         boolean is_blank = STREQ (str, "blank");
3320                         boolean is_cntrl = STREQ (str, "cntrl");
3321                         boolean is_digit = STREQ (str, "digit");
3322                         boolean is_graph = STREQ (str, "graph");
3323                         boolean is_lower = STREQ (str, "lower");
3324                         boolean is_print = STREQ (str, "print");
3325                         boolean is_punct = STREQ (str, "punct");
3326                         boolean is_space = STREQ (str, "space");
3327                         boolean is_upper = STREQ (str, "upper");
3328                         boolean is_xdigit = STREQ (str, "xdigit");
3329
3330                         if (!IS_CHAR_CLASS (str))
3331                           FREE_STACK_RETURN (REG_ECTYPE);
3332
3333                         /* Throw away the ] at the end of the character
3334                            class.  */
3335                         PATFETCH (c);
3336
3337                         if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3338
3339                         for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
3340                           {
3341                             /* This was split into 3 if's to
3342                                avoid an arbitrary limit in some compiler.  */
3343                             if (   (is_alnum  && ISALNUM (ch))
3344                                 || (is_alpha  && ISALPHA (ch))
3345                                 || (is_blank  && ISBLANK (ch))
3346                                 || (is_cntrl  && ISCNTRL (ch)))
3347                               SET_LIST_BIT (ch);
3348                             if (   (is_digit  && ISDIGIT (ch))
3349                                 || (is_graph  && ISGRAPH (ch))
3350                                 || (is_lower  && ISLOWER (ch))
3351                                 || (is_print  && ISPRINT (ch)))
3352                               SET_LIST_BIT (ch);
3353                             if (   (is_punct  && ISPUNCT (ch))
3354                                 || (is_space  && ISSPACE (ch))
3355                                 || (is_upper  && ISUPPER (ch))
3356                                 || (is_xdigit && ISXDIGIT (ch)))
3357                               SET_LIST_BIT (ch);
3358                             if (   translate && (is_upper || is_lower)
3359                                 && (ISUPPER (ch) || ISLOWER (ch)))
3360                               SET_LIST_BIT (ch);
3361                           }
3362                         had_char_class = true;
3363 # endif /* libc || wctype.h */
3364                       }
3365                     else
3366                       {
3367                         c1++;
3368                         while (c1--)
3369                           PATUNFETCH;
3370                         SET_LIST_BIT ('[');
3371                         SET_LIST_BIT (':');
3372                         range_start = ':';
3373                         had_char_class = false;
3374                       }
3375                   }
3376                 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '=')
3377                   {
3378                     unsigned char str[MB_LEN_MAX + 1];
3379 # ifdef _LIBC
3380                     uint32_t nrules =
3381                       _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3382 # endif
3383
3384                     PATFETCH (c);
3385                     c1 = 0;
3386
3387                     /* If pattern is `[[='.  */
3388                     if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3389
3390                     for (;;)
3391                       {
3392                         PATFETCH (c);
3393                         if ((c == '=' && *p == ']') || p == pend)
3394                           break;
3395                         if (c1 < MB_LEN_MAX)
3396                           str[c1++] = c;
3397                         else
3398                           /* This is in any case an invalid class name.  */
3399                           str[0] = '\0';
3400                       }
3401                     str[c1] = '\0';
3402
3403                     if (c == '=' && *p == ']' && str[0] != '\0')
3404                       {
3405                         /* If we have no collation data we use the default
3406                            collation in which each character is in a class
3407                            by itself.  It also means that ASCII is the
3408                            character set and therefore we cannot have character
3409                            with more than one byte in the multibyte
3410                            representation.  */
3411 # ifdef _LIBC
3412                         if (nrules == 0)
3413 # endif
3414                           {
3415                             if (c1 != 1)
3416                               FREE_STACK_RETURN (REG_ECOLLATE);
3417
3418                             /* Throw away the ] at the end of the equivalence
3419                                class.  */
3420                             PATFETCH (c);
3421
3422                             /* Set the bit for the character.  */
3423                             SET_LIST_BIT (str[0]);
3424                           }
3425 # ifdef _LIBC
3426                         else
3427                           {
3428                             /* Try to match the byte sequence in `str' against
3429                                those known to the collate implementation.
3430                                First find out whether the bytes in `str' are
3431                                actually from exactly one character.  */
3432                             const int32_t *table;
3433                             const unsigned char *weights;
3434                             const unsigned char *extra;
3435                             const int32_t *indirect;
3436                             int32_t idx;
3437                             const unsigned char *cp = str;
3438                             int ch;
3439
3440                             /* This #include defines a local function!  */
3441 #  include <locale/weight.h>
3442
3443                             table = (const int32_t *)
3444                               _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
3445                             weights = (const unsigned char *)
3446                               _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
3447                             extra = (const unsigned char *)
3448                               _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
3449                             indirect = (const int32_t *)
3450                               _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
3451
3452                             idx = findidx (&cp);
3453                             if (idx == 0 || cp < str + c1)
3454                               /* This is no valid character.  */
3455                               FREE_STACK_RETURN (REG_ECOLLATE);
3456
3457                             /* Throw away the ] at the end of the equivalence
3458                                class.  */
3459                             PATFETCH (c);
3460
3461                             /* Now we have to go throught the whole table
3462                                and find all characters which have the same
3463                                first level weight.
3464
3465                                XXX Note that this is not entirely correct.
3466                                we would have to match multibyte sequences
3467                                but this is not possible with the current
3468                                implementation.  */
3469                             for (ch = 1; ch < 256; ++ch)
3470                               /* XXX This test would have to be changed if we
3471                                  would allow matching multibyte sequences.  */
3472                               if (table[ch] > 0)
3473                                 {
3474                                   int32_t idx2 = table[ch];
3475                                   size_t len = weights[idx2];
3476
3477                                   /* Test whether the lenghts match.  */
3478                                   if (weights[idx] == len)
3479                                     {
3480                                       /* They do.  New compare the bytes of
3481                                          the weight.  */
3482                                       size_t cnt = 0;
3483
3484                                       while (cnt < len
3485                                              && (weights[idx + 1 + cnt]
3486                                                  == weights[idx2 + 1 + cnt]))
3487                                         ++cnt;
3488
3489                                       if (cnt == len)
3490                                         /* They match.  Mark the character as
3491                                            acceptable.  */
3492                                         SET_LIST_BIT (ch);
3493                                     }
3494                                 }
3495                           }
3496 # endif
3497                         had_char_class = true;
3498                       }
3499                     else
3500                       {
3501                         c1++;
3502                         while (c1--)
3503                           PATUNFETCH;
3504                         SET_LIST_BIT ('[');
3505                         SET_LIST_BIT ('=');
3506                         range_start = '=';
3507                         had_char_class = false;
3508                       }
3509                   }
3510                 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '.')
3511                   {
3512                     unsigned char str[128];     /* Should be large enough.  */
3513 # ifdef _LIBC
3514                     uint32_t nrules =
3515                       _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3516 # endif
3517
3518                     PATFETCH (c);
3519                     c1 = 0;
3520
3521                     /* If pattern is `[[.'.  */
3522                     if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3523
3524                     for (;;)
3525                       {
3526                         PATFETCH (c);
3527                         if ((c == '.' && *p == ']') || p == pend)
3528                           break;
3529                         if (c1 < sizeof (str))
3530                           str[c1++] = c;
3531                         else
3532                           /* This is in any case an invalid class name.  */
3533                           str[0] = '\0';
3534                       }
3535                     str[c1] = '\0';
3536
3537                     if (c == '.' && *p == ']' && str[0] != '\0')
3538                       {
3539                         /* If we have no collation data we use the default
3540                            collation in which each character is the name
3541                            for its own class which contains only the one
3542                            character.  It also means that ASCII is the
3543                            character set and therefore we cannot have character
3544                            with more than one byte in the multibyte
3545                            representation.  */
3546 # ifdef _LIBC
3547                         if (nrules == 0)
3548 # endif
3549                           {
3550                             if (c1 != 1)
3551                               FREE_STACK_RETURN (REG_ECOLLATE);
3552
3553                             /* Throw away the ] at the end of the equivalence
3554                                class.  */
3555                             PATFETCH (c);
3556
3557                             /* Set the bit for the character.  */
3558                             SET_LIST_BIT (str[0]);
3559                             range_start = ((const unsigned char *) str)[0];
3560                           }
3561 # ifdef _LIBC
3562                         else
3563                           {
3564                             /* Try to match the byte sequence in `str' against
3565                                those known to the collate implementation.
3566                                First find out whether the bytes in `str' are
3567                                actually from exactly one character.  */
3568                             int32_t table_size;
3569                             const int32_t *symb_table;
3570                             const unsigned char *extra;
3571                             int32_t idx;
3572                             int32_t elem;
3573                             int32_t second;
3574                             int32_t hash;
3575
3576                             table_size =
3577                               _NL_CURRENT_WORD (LC_COLLATE,
3578                                                 _NL_COLLATE_SYMB_HASH_SIZEMB);
3579                             symb_table = (const int32_t *)
3580                               _NL_CURRENT (LC_COLLATE,
3581                                            _NL_COLLATE_SYMB_TABLEMB);
3582                             extra = (const unsigned char *)
3583                               _NL_CURRENT (LC_COLLATE,
3584                                            _NL_COLLATE_SYMB_EXTRAMB);
3585
3586                             /* Locate the character in the hashing table.  */
3587                             hash = elem_hash (str, c1);
3588
3589                             idx = 0;
3590                             elem = hash % table_size;
3591                             second = hash % (table_size - 2);
3592                             while (symb_table[2 * elem] != 0)
3593                               {
3594                                 /* First compare the hashing value.  */
3595                                 if (symb_table[2 * elem] == hash
3596                                     && c1 == extra[symb_table[2 * elem + 1]]
3597                                     && memcmp (str,
3598                                                &extra[symb_table[2 * elem + 1]
3599                                                      + 1],
3600                                                c1) == 0)
3601                                   {
3602                                     /* Yep, this is the entry.  */
3603                                     idx = symb_table[2 * elem + 1];
3604                                     idx += 1 + extra[idx];
3605                                     break;
3606                                   }
3607
3608                                 /* Next entry.  */
3609                                 elem += second;
3610                               }
3611
3612                             if (symb_table[2 * elem] == 0)
3613                               /* This is no valid character.  */
3614                               FREE_STACK_RETURN (REG_ECOLLATE);
3615
3616                             /* Throw away the ] at the end of the equivalence
3617                                class.  */
3618                             PATFETCH (c);
3619
3620                             /* Now add the multibyte character(s) we found
3621                                to the accept list.
3622
3623                                XXX Note that this is not entirely correct.
3624                                we would have to match multibyte sequences
3625                                but this is not possible with the current
3626                                implementation.  Also, we have to match
3627                                collating symbols, which expand to more than
3628                                one file, as a whole and not allow the
3629                                individual bytes.  */
3630                             c1 = extra[idx++];
3631                             if (c1 == 1)
3632                               range_start = extra[idx];
3633                             while (c1-- > 0)
3634                               {
3635                                 SET_LIST_BIT (extra[idx]);
3636                                 ++idx;
3637                               }
3638                           }
3639 # endif
3640                         had_char_class = false;
3641                       }
3642                     else
3643                       {
3644                         c1++;
3645                         while (c1--)
3646                           PATUNFETCH;
3647                         SET_LIST_BIT ('[');
3648                         SET_LIST_BIT ('.');
3649                         range_start = '.';
3650                         had_char_class = false;
3651                       }
3652                   }
3653                 else
3654                   {
3655                     had_char_class = false;
3656                     SET_LIST_BIT (c);
3657                     range_start = c;
3658                   }
3659               }
3660
3661             /* Discard any (non)matching list bytes that are all 0 at the
3662                end of the map.  Decrease the map-length byte too.  */
3663             while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3664               b[-1]--;
3665             b += b[-1];
3666 #endif /* WCHAR */
3667           }
3668           break;
3669
3670
3671         case '(':
3672           if (syntax & RE_NO_BK_PARENS)
3673             goto handle_open;
3674           else
3675             goto normal_char;
3676
3677
3678         case ')':
3679           if (syntax & RE_NO_BK_PARENS)
3680             goto handle_close;
3681           else
3682             goto normal_char;
3683
3684
3685         case '\n':
3686           if (syntax & RE_NEWLINE_ALT)
3687             goto handle_alt;
3688           else
3689             goto normal_char;
3690
3691
3692         case '|':
3693           if (syntax & RE_NO_BK_VBAR)
3694             goto handle_alt;
3695           else
3696             goto normal_char;
3697
3698
3699         case '{':
3700            if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3701              goto handle_interval;
3702            else
3703              goto normal_char;
3704
3705
3706         case '\\':
3707           if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3708
3709           /* Do not translate the character after the \, so that we can
3710              distinguish, e.g., \B from \b, even if we normally would
3711              translate, e.g., B to b.  */
3712           PATFETCH_RAW (c);
3713
3714           switch (c)
3715             {
3716             case '(':
3717               if (syntax & RE_NO_BK_PARENS)
3718                 goto normal_backslash;
3719
3720             handle_open:
3721               bufp->re_nsub++;
3722               regnum++;
3723
3724               if (COMPILE_STACK_FULL)
3725                 {
3726                   RETALLOC (compile_stack.stack, compile_stack.size << 1,
3727                             compile_stack_elt_t);
3728                   if (compile_stack.stack == NULL) return REG_ESPACE;
3729
3730                   compile_stack.size <<= 1;
3731                 }
3732
3733               /* These are the values to restore when we hit end of this
3734                  group.  They are all relative offsets, so that if the
3735                  whole pattern moves because of realloc, they will still
3736                  be valid.  */
3737               COMPILE_STACK_TOP.begalt_offset = begalt - COMPILED_BUFFER_VAR;
3738               COMPILE_STACK_TOP.fixup_alt_jump
3739                 = fixup_alt_jump ? fixup_alt_jump - COMPILED_BUFFER_VAR + 1 : 0;
3740               COMPILE_STACK_TOP.laststart_offset = b - COMPILED_BUFFER_VAR;
3741               COMPILE_STACK_TOP.regnum = regnum;
3742
3743               /* We will eventually replace the 0 with the number of
3744                  groups inner to this one.  But do not push a
3745                  start_memory for groups beyond the last one we can
3746                  represent in the compiled pattern.  */
3747               if (regnum <= MAX_REGNUM)
3748                 {
3749                   COMPILE_STACK_TOP.inner_group_offset = b
3750                     - COMPILED_BUFFER_VAR + 2;
3751                   BUF_PUSH_3 (start_memory, regnum, 0);
3752                 }
3753
3754               compile_stack.avail++;
3755
3756               fixup_alt_jump = 0;
3757               laststart = 0;
3758               begalt = b;
3759               /* If we've reached MAX_REGNUM groups, then this open
3760                  won't actually generate any code, so we'll have to
3761                  clear pending_exact explicitly.  */
3762               pending_exact = 0;
3763               break;
3764
3765
3766             case ')':
3767               if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3768
3769               if (COMPILE_STACK_EMPTY)
3770                 {
3771                   if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3772                     goto normal_backslash;
3773                   else
3774                     FREE_STACK_RETURN (REG_ERPAREN);
3775                 }
3776
3777             handle_close:
3778               if (fixup_alt_jump)
3779                 { /* Push a dummy failure point at the end of the
3780                      alternative for a possible future
3781                      `pop_failure_jump' to pop.  See comments at
3782                      `push_dummy_failure' in `re_match_2'.  */
3783                   BUF_PUSH (push_dummy_failure);
3784
3785                   /* We allocated space for this jump when we assigned
3786                      to `fixup_alt_jump', in the `handle_alt' case below.  */
3787                   STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
3788                 }
3789
3790               /* See similar code for backslashed left paren above.  */
3791               if (COMPILE_STACK_EMPTY)
3792                 {
3793                   if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3794                     goto normal_char;
3795                   else
3796                     FREE_STACK_RETURN (REG_ERPAREN);
3797                 }
3798
3799               /* Since we just checked for an empty stack above, this
3800                  ``can't happen''.  */
3801               assert (compile_stack.avail != 0);
3802               {
3803                 /* We don't just want to restore into `regnum', because
3804                    later groups should continue to be numbered higher,
3805                    as in `(ab)c(de)' -- the second group is #2.  */
3806                 regnum_t this_group_regnum;
3807
3808                 compile_stack.avail--;
3809                 begalt = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.begalt_offset;
3810                 fixup_alt_jump
3811                   = COMPILE_STACK_TOP.fixup_alt_jump
3812                     ? COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.fixup_alt_jump - 1
3813                     : 0;
3814                 laststart = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.laststart_offset;
3815                 this_group_regnum = COMPILE_STACK_TOP.regnum;
3816                 /* If we've reached MAX_REGNUM groups, then this open
3817                    won't actually generate any code, so we'll have to
3818                    clear pending_exact explicitly.  */
3819                 pending_exact = 0;
3820
3821                 /* We're at the end of the group, so now we know how many
3822                    groups were inside this one.  */
3823                 if (this_group_regnum <= MAX_REGNUM)
3824                   {
3825                     UCHAR_T *inner_group_loc
3826                       = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.inner_group_offset;
3827
3828                     *inner_group_loc = regnum - this_group_regnum;
3829                     BUF_PUSH_3 (stop_memory, this_group_regnum,
3830                                 regnum - this_group_regnum);
3831                   }
3832               }
3833               break;
3834
3835
3836             case '|':                                   /* `\|'.  */
3837               if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3838                 goto normal_backslash;
3839             handle_alt:
3840               if (syntax & RE_LIMITED_OPS)
3841                 goto normal_char;
3842
3843               /* Insert before the previous alternative a jump which
3844                  jumps to this alternative if the former fails.  */
3845               GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3846               INSERT_JUMP (on_failure_jump, begalt,
3847                            b + 2 + 2 * OFFSET_ADDRESS_SIZE);
3848               pending_exact = 0;
3849               b += 1 + OFFSET_ADDRESS_SIZE;
3850
3851               /* The alternative before this one has a jump after it
3852                  which gets executed if it gets matched.  Adjust that
3853                  jump so it will jump to this alternative's analogous
3854                  jump (put in below, which in turn will jump to the next
3855                  (if any) alternative's such jump, etc.).  The last such
3856                  jump jumps to the correct final destination.  A picture:
3857                           _____ _____
3858                           |   | |   |
3859                           |   v |   v
3860                          a | b   | c
3861
3862                  If we are at `b', then fixup_alt_jump right now points to a
3863                  three-byte space after `a'.  We'll put in the jump, set
3864                  fixup_alt_jump to right after `b', and leave behind three
3865                  bytes which we'll fill in when we get to after `c'.  */
3866
3867               if (fixup_alt_jump)
3868                 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3869
3870               /* Mark and leave space for a jump after this alternative,
3871                  to be filled in later either by next alternative or
3872                  when know we're at the end of a series of alternatives.  */
3873               fixup_alt_jump = b;
3874               GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3875               b += 1 + OFFSET_ADDRESS_SIZE;
3876
3877               laststart = 0;
3878               begalt = b;
3879               break;
3880
3881
3882             case '{':
3883               /* If \{ is a literal.  */
3884               if (!(syntax & RE_INTERVALS)
3885                      /* If we're at `\{' and it's not the open-interval
3886                         operator.  */
3887                   || (syntax & RE_NO_BK_BRACES))
3888                 goto normal_backslash;
3889
3890             handle_interval:
3891               {
3892                 /* If got here, then the syntax allows intervals.  */
3893
3894                 /* At least (most) this many matches must be made.  */
3895                 int lower_bound = -1, upper_bound = -1;
3896
3897                 /* Place in the uncompiled pattern (i.e., just after
3898                    the '{') to go back to if the interval is invalid.  */
3899                 const CHAR_T *beg_interval = p;
3900
3901                 if (p == pend)
3902                   goto invalid_interval;
3903
3904                 GET_UNSIGNED_NUMBER (lower_bound);
3905
3906                 if (c == ',')
3907                   {
3908                     GET_UNSIGNED_NUMBER (upper_bound);
3909                     if (upper_bound < 0)
3910                       upper_bound = RE_DUP_MAX;
3911                   }
3912                 else
3913                   /* Interval such as `{1}' => match exactly once. */
3914                   upper_bound = lower_bound;
3915
3916                 if (! (0 <= lower_bound && lower_bound <= upper_bound))
3917                   goto invalid_interval;
3918
3919                 if (!(syntax & RE_NO_BK_BRACES))
3920                   {
3921                     if (c != '\\' || p == pend)
3922                       goto invalid_interval;
3923                     PATFETCH (c);
3924                   }
3925
3926                 if (c != '}')
3927                   goto invalid_interval;
3928
3929                 /* If it's invalid to have no preceding re.  */
3930                 if (!laststart)
3931                   {
3932                     if (syntax & RE_CONTEXT_INVALID_OPS
3933                         && !(syntax & RE_INVALID_INTERVAL_ORD))
3934                       FREE_STACK_RETURN (REG_BADRPT);
3935                     else if (syntax & RE_CONTEXT_INDEP_OPS)
3936                       laststart = b;
3937                     else
3938                       goto unfetch_interval;
3939                   }
3940
3941                 /* We just parsed a valid interval.  */
3942
3943                 if (RE_DUP_MAX < upper_bound)
3944                   FREE_STACK_RETURN (REG_BADBR);
3945
3946                 /* If the upper bound is zero, don't want to succeed at
3947                    all; jump from `laststart' to `b + 3', which will be
3948                    the end of the buffer after we insert the jump.  */
3949                 /* ifdef WCHAR, 'b + 1 + OFFSET_ADDRESS_SIZE'
3950                    instead of 'b + 3'.  */
3951                  if (upper_bound == 0)
3952                    {
3953                      GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3954                      INSERT_JUMP (jump, laststart, b + 1
3955                                   + OFFSET_ADDRESS_SIZE);
3956                      b += 1 + OFFSET_ADDRESS_SIZE;
3957                    }
3958
3959                  /* Otherwise, we have a nontrivial interval.  When
3960                     we're all done, the pattern will look like:
3961                       set_number_at <jump count> <upper bound>
3962                       set_number_at <succeed_n count> <lower bound>
3963                       succeed_n <after jump addr> <succeed_n count>
3964                       <body of loop>
3965                       jump_n <succeed_n addr> <jump count>
3966                     (The upper bound and `jump_n' are omitted if
3967                     `upper_bound' is 1, though.)  */
3968                  else
3969                    { /* If the upper bound is > 1, we need to insert
3970                         more at the end of the loop.  */
3971                      unsigned nbytes = 2 + 4 * OFFSET_ADDRESS_SIZE +
3972                        (upper_bound > 1) * (2 + 4 * OFFSET_ADDRESS_SIZE);
3973
3974                      GET_BUFFER_SPACE (nbytes);
3975
3976                      /* Initialize lower bound of the `succeed_n', even
3977                         though it will be set during matching by its
3978                         attendant `set_number_at' (inserted next),
3979                         because `re_compile_fastmap' needs to know.
3980                         Jump to the `jump_n' we might insert below.  */
3981                      INSERT_JUMP2 (succeed_n, laststart,
3982                                    b + 1 + 2 * OFFSET_ADDRESS_SIZE
3983                                    + (upper_bound > 1) * (1 + 2 * OFFSET_ADDRESS_SIZE)
3984                                    , lower_bound);
3985                      b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3986
3987                      /* Code to initialize the lower bound.  Insert
3988                         before the `succeed_n'.  The `5' is the last two
3989                         bytes of this `set_number_at', plus 3 bytes of
3990                         the following `succeed_n'.  */
3991                      /* ifdef WCHAR, The '1+2*OFFSET_ADDRESS_SIZE'
3992                         is the 'set_number_at', plus '1+OFFSET_ADDRESS_SIZE'
3993                         of the following `succeed_n'.  */
3994                      PREFIX(insert_op2) (set_number_at, laststart, 1
3995                                  + 2 * OFFSET_ADDRESS_SIZE, lower_bound, b);
3996                      b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3997
3998                      if (upper_bound > 1)
3999                        { /* More than one repetition is allowed, so
4000                             append a backward jump to the `succeed_n'
4001                             that starts this interval.
4002
4003                             When we've reached this during matching,
4004                             we'll have matched the interval once, so
4005                             jump back only `upper_bound - 1' times.  */
4006                          STORE_JUMP2 (jump_n, b, laststart
4007                                       + 2 * OFFSET_ADDRESS_SIZE + 1,
4008                                       upper_bound - 1);
4009                          b += 1 + 2 * OFFSET_ADDRESS_SIZE;
4010
4011                          /* The location we want to set is the second
4012                             parameter of the `jump_n'; that is `b-2' as
4013                             an absolute address.  `laststart' will be
4014                             the `set_number_at' we're about to insert;
4015                             `laststart+3' the number to set, the source
4016                             for the relative address.  But we are
4017                             inserting into the middle of the pattern --
4018                             so everything is getting moved up by 5.
4019                             Conclusion: (b - 2) - (laststart + 3) + 5,
4020                             i.e., b - laststart.
4021
4022                             We insert this at the beginning of the loop
4023                             so that if we fail during matching, we'll
4024                             reinitialize the bounds.  */
4025                          PREFIX(insert_op2) (set_number_at, laststart,
4026                                              b - laststart,
4027                                              upper_bound - 1, b);
4028                          b += 1 + 2 * OFFSET_ADDRESS_SIZE;
4029                        }
4030                    }
4031                 pending_exact = 0;
4032                 break;
4033
4034               invalid_interval:
4035                 if (!(syntax & RE_INVALID_INTERVAL_ORD))
4036                   FREE_STACK_RETURN (p == pend ? REG_EBRACE : REG_BADBR);
4037               unfetch_interval:
4038                 /* Match the characters as literals.  */
4039                 p = beg_interval;
4040                 c = '{';
4041                 if (syntax & RE_NO_BK_BRACES)
4042                   goto normal_char;
4043                 else
4044                   goto normal_backslash;
4045               }
4046
4047 #ifdef emacs
4048             /* There is no way to specify the before_dot and after_dot
4049                operators.  rms says this is ok.  --karl  */
4050             case '=':
4051               BUF_PUSH (at_dot);
4052               break;
4053
4054             case 's':
4055               laststart = b;
4056               PATFETCH (c);
4057               BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
4058               break;
4059
4060             case 'S':
4061               laststart = b;
4062               PATFETCH (c);
4063               BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
4064               break;
4065 #endif /* emacs */
4066
4067
4068             case 'w':
4069               if (syntax & RE_NO_GNU_OPS)
4070                 goto normal_char;
4071               laststart = b;
4072               BUF_PUSH (wordchar);
4073               break;
4074
4075
4076             case 'W':
4077               if (syntax & RE_NO_GNU_OPS)
4078                 goto normal_char;
4079               laststart = b;
4080               BUF_PUSH (notwordchar);
4081               break;
4082
4083
4084             case '<':
4085               if (syntax & RE_NO_GNU_OPS)
4086                 goto normal_char;
4087               BUF_PUSH (wordbeg);
4088               break;
4089
4090             case '>':
4091               if (syntax & RE_NO_GNU_OPS)
4092                 goto normal_char;
4093               BUF_PUSH (wordend);
4094               break;
4095
4096             case 'b':
4097               if (syntax & RE_NO_GNU_OPS)
4098                 goto normal_char;
4099               BUF_PUSH (wordbound);
4100               break;
4101
4102             case 'B':
4103               if (syntax & RE_NO_GNU_OPS)
4104                 goto normal_char;
4105               BUF_PUSH (notwordbound);
4106               break;
4107
4108             case '`':
4109               if (syntax & RE_NO_GNU_OPS)
4110                 goto normal_char;
4111               BUF_PUSH (begbuf);
4112               break;
4113
4114             case '\'':
4115               if (syntax & RE_NO_GNU_OPS)
4116                 goto normal_char;
4117               BUF_PUSH (endbuf);
4118               break;
4119
4120             case '1': case '2': case '3': case '4': case '5':
4121             case '6': case '7': case '8': case '9':
4122               if (syntax & RE_NO_BK_REFS)
4123                 goto normal_char;
4124
4125               c1 = c - '0';
4126
4127               if (c1 > regnum)
4128                 FREE_STACK_RETURN (REG_ESUBREG);
4129
4130               /* Can't back reference to a subexpression if inside of it.  */
4131               if (group_in_compile_stack (compile_stack, (regnum_t) c1))
4132                 goto normal_char;
4133
4134               laststart = b;
4135               BUF_PUSH_2 (duplicate, c1);
4136               break;
4137
4138
4139             case '+':
4140             case '?':
4141               if (syntax & RE_BK_PLUS_QM)
4142                 goto handle_plus;
4143               else
4144                 goto normal_backslash;
4145
4146             default:
4147             normal_backslash:
4148               /* You might think it would be useful for \ to mean
4149                  not to translate; but if we don't translate it
4150                  it will never match anything.  */
4151               c = TRANSLATE (c);
4152               goto normal_char;
4153             }
4154           break;
4155
4156
4157         default:
4158         /* Expects the character in `c'.  */
4159         normal_char:
4160               /* If no exactn currently being built.  */
4161           if (!pending_exact
4162 #ifdef WCHAR
4163               /* If last exactn handle binary(or character) and
4164                  new exactn handle character(or binary).  */
4165               || is_exactn_bin != is_binary[p - 1 - pattern]
4166 #endif /* WCHAR */
4167
4168               /* If last exactn not at current position.  */
4169               || pending_exact + *pending_exact + 1 != b
4170
4171               /* We have only one byte following the exactn for the count.  */
4172               || *pending_exact == (1 << BYTEWIDTH) - 1
4173
4174               /* If followed by a repetition operator.  */
4175               || *p == '*' || *p == '^'
4176               || ((syntax & RE_BK_PLUS_QM)
4177                   ? *p == '\\' && (p[1] == '+' || p[1] == '?')
4178                   : (*p == '+' || *p == '?'))
4179               || ((syntax & RE_INTERVALS)
4180                   && ((syntax & RE_NO_BK_BRACES)
4181                       ? *p == '{'
4182                       : (p[0] == '\\' && p[1] == '{'))))
4183             {
4184               /* Start building a new exactn.  */
4185
4186               laststart = b;
4187
4188 #ifdef WCHAR
4189               /* Is this exactn binary data or character? */
4190               is_exactn_bin = is_binary[p - 1 - pattern];
4191               if (is_exactn_bin)
4192                   BUF_PUSH_2 (exactn_bin, 0);
4193               else
4194                   BUF_PUSH_2 (exactn, 0);
4195 #else
4196               BUF_PUSH_2 (exactn, 0);
4197 #endif /* WCHAR */
4198               pending_exact = b - 1;
4199             }
4200
4201           BUF_PUSH (c);
4202           (*pending_exact)++;
4203           break;
4204         } /* switch (c) */
4205     } /* while p != pend */
4206
4207
4208   /* Through the pattern now.  */
4209
4210   if (fixup_alt_jump)
4211     STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
4212
4213   if (!COMPILE_STACK_EMPTY)
4214     FREE_STACK_RETURN (REG_EPAREN);
4215
4216   /* If we don't want backtracking, force success
4217      the first time we reach the end of the compiled pattern.  */
4218   if (syntax & RE_NO_POSIX_BACKTRACKING)
4219     BUF_PUSH (succeed);
4220
4221 #ifdef WCHAR
4222   free (pattern);
4223   free (mbs_offset);
4224   free (is_binary);
4225 #endif
4226   free (compile_stack.stack);
4227
4228   /* We have succeeded; set the length of the buffer.  */
4229 #ifdef WCHAR
4230   bufp->used = (uintptr_t) b - (uintptr_t) COMPILED_BUFFER_VAR;
4231 #else
4232   bufp->used = b - bufp->buffer;
4233 #endif
4234
4235 #ifdef DEBUG
4236   if (debug)
4237     {
4238       DEBUG_PRINT1 ("\nCompiled pattern: \n");
4239       PREFIX(print_compiled_pattern) (bufp);
4240     }
4241 #endif /* DEBUG */
4242
4243 #ifndef MATCH_MAY_ALLOCATE
4244   /* Initialize the failure stack to the largest possible stack.  This
4245      isn't necessary unless we're trying to avoid calling alloca in
4246      the search and match routines.  */
4247   {
4248     int num_regs = bufp->re_nsub + 1;
4249
4250     /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
4251        is strictly greater than re_max_failures, the largest possible stack
4252        is 2 * re_max_failures failure points.  */
4253     if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
4254       {
4255         fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
4256
4257 # ifdef emacs
4258         if (! fail_stack.stack)
4259           fail_stack.stack
4260             = (PREFIX(fail_stack_elt_t) *) xmalloc (fail_stack.size
4261                                     * sizeof (PREFIX(fail_stack_elt_t)));
4262         else
4263           fail_stack.stack
4264             = (PREFIX(fail_stack_elt_t) *) xrealloc (fail_stack.stack,
4265                                      (fail_stack.size
4266                                       * sizeof (PREFIX(fail_stack_elt_t))));
4267 # else /* not emacs */
4268         if (! fail_stack.stack)
4269           fail_stack.stack
4270             = (PREFIX(fail_stack_elt_t) *) malloc (fail_stack.size
4271                                    * sizeof (PREFIX(fail_stack_elt_t)));
4272         else
4273           fail_stack.stack
4274             = (PREFIX(fail_stack_elt_t) *) realloc (fail_stack.stack,
4275                                             (fail_stack.size
4276                                      * sizeof (PREFIX(fail_stack_elt_t))));
4277 # endif /* not emacs */
4278       }
4279
4280    PREFIX(regex_grow_registers) (num_regs);
4281   }
4282 #endif /* not MATCH_MAY_ALLOCATE */
4283
4284   return REG_NOERROR;
4285 } /* regex_compile */
4286
4287 /* Subroutines for `regex_compile'.  */
4288
4289 /* Store OP at LOC followed by two-byte integer parameter ARG.  */
4290 /* ifdef WCHAR, integer parameter is 1 wchar_t.  */
4291
4292 static void
4293 PREFIX(store_op1) (op, loc, arg)
4294     re_opcode_t op;
4295     UCHAR_T *loc;
4296     int arg;
4297 {
4298   *loc = (UCHAR_T) op;
4299   STORE_NUMBER (loc + 1, arg);
4300 }
4301
4302
4303 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2.  */
4304 /* ifdef WCHAR, integer parameter is 1 wchar_t.  */
4305
4306 static void
4307 PREFIX(store_op2) (op, loc, arg1, arg2)
4308     re_opcode_t op;
4309     UCHAR_T *loc;
4310     int arg1, arg2;
4311 {
4312   *loc = (UCHAR_T) op;
4313   STORE_NUMBER (loc + 1, arg1);
4314   STORE_NUMBER (loc + 1 + OFFSET_ADDRESS_SIZE, arg2);
4315 }
4316
4317
4318 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
4319    for OP followed by two-byte integer parameter ARG.  */
4320 /* ifdef WCHAR, integer parameter is 1 wchar_t.  */
4321
4322 static void
4323 PREFIX(insert_op1) (op, loc, arg, end)
4324     re_opcode_t op;
4325     UCHAR_T *loc;
4326     int arg;
4327     UCHAR_T *end;
4328 {
4329   register UCHAR_T *pfrom = end;
4330   register UCHAR_T *pto = end + 1 + OFFSET_ADDRESS_SIZE;
4331
4332   while (pfrom != loc)
4333     *--pto = *--pfrom;
4334
4335   PREFIX(store_op1) (op, loc, arg);
4336 }
4337
4338
4339 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2.  */
4340 /* ifdef WCHAR, integer parameter is 1 wchar_t.  */
4341
4342 static void
4343 PREFIX(insert_op2) (op, loc, arg1, arg2, end)
4344     re_opcode_t op;
4345     UCHAR_T *loc;
4346     int arg1, arg2;
4347     UCHAR_T *end;
4348 {
4349   register UCHAR_T *pfrom = end;
4350   register UCHAR_T *pto = end + 1 + 2 * OFFSET_ADDRESS_SIZE;
4351
4352   while (pfrom != loc)
4353     *--pto = *--pfrom;
4354
4355   PREFIX(store_op2) (op, loc, arg1, arg2);
4356 }
4357
4358
4359 /* P points to just after a ^ in PATTERN.  Return true if that ^ comes
4360    after an alternative or a begin-subexpression.  We assume there is at
4361    least one character before the ^.  */
4362
4363 static boolean
4364 PREFIX(at_begline_loc_p) (pattern, p, syntax)
4365     const CHAR_T *pattern, *p;
4366     reg_syntax_t syntax;
4367 {
4368   const CHAR_T *prev = p - 2;
4369   boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
4370
4371   return
4372        /* After a subexpression?  */
4373        (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
4374        /* After an alternative?  */
4375     || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
4376 }
4377
4378
4379 /* The dual of at_begline_loc_p.  This one is for $.  We assume there is
4380    at least one character after the $, i.e., `P < PEND'.  */
4381
4382 static boolean
4383 PREFIX(at_endline_loc_p) (p, pend, syntax)
4384     const CHAR_T *p, *pend;
4385     reg_syntax_t syntax;
4386 {
4387   const CHAR_T *next = p;
4388   boolean next_backslash = *next == '\\';
4389   const CHAR_T *next_next = p + 1 < pend ? p + 1 : 0;
4390
4391   return
4392        /* Before a subexpression?  */
4393        (syntax & RE_NO_BK_PARENS ? *next == ')'
4394         : next_backslash && next_next && *next_next == ')')
4395        /* Before an alternative?  */
4396     || (syntax & RE_NO_BK_VBAR ? *next == '|'
4397         : next_backslash && next_next && *next_next == '|');
4398 }
4399
4400 #else /* not INSIDE_RECURSION */
4401
4402 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
4403    false if it's not.  */
4404
4405 static boolean
4406 group_in_compile_stack (compile_stack, regnum)
4407     compile_stack_type compile_stack;
4408     regnum_t regnum;
4409 {
4410   int this_element;
4411
4412   for (this_element = compile_stack.avail - 1;
4413        this_element >= 0;
4414        this_element--)
4415     if (compile_stack.stack[this_element].regnum == regnum)
4416       return true;
4417
4418   return false;
4419 }
4420 #endif /* not INSIDE_RECURSION */
4421
4422 #ifdef INSIDE_RECURSION
4423
4424 #ifdef WCHAR
4425 /* This insert space, which size is "num", into the pattern at "loc".
4426    "end" must point the end of the allocated buffer.  */
4427 static void
4428 insert_space (num, loc, end)
4429      int num;
4430      CHAR_T *loc;
4431      CHAR_T *end;
4432 {
4433   register CHAR_T *pto = end;
4434   register CHAR_T *pfrom = end - num;
4435
4436   while (pfrom >= loc)
4437     *pto-- = *pfrom--;
4438 }
4439 #endif /* WCHAR */
4440
4441 #ifdef WCHAR
4442 static reg_errcode_t
4443 wcs_compile_range (range_start_char, p_ptr, pend, translate, syntax, b,
4444                    char_set)
4445      CHAR_T range_start_char;
4446      const CHAR_T **p_ptr, *pend;
4447      CHAR_T *char_set, *b;
4448      RE_TRANSLATE_TYPE translate;
4449      reg_syntax_t syntax;
4450 {
4451   const CHAR_T *p = *p_ptr;
4452   CHAR_T range_start, range_end;
4453   reg_errcode_t ret;
4454 # ifdef _LIBC
4455   uint32_t nrules;
4456   uint32_t start_val, end_val;
4457 # endif
4458   if (p == pend)
4459     return REG_ERANGE;
4460
4461 # ifdef _LIBC
4462   nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
4463   if (nrules != 0)
4464     {
4465       const char *collseq = (const char *) _NL_CURRENT(LC_COLLATE,
4466                                                        _NL_COLLATE_COLLSEQWC);
4467       const unsigned char *extra = (const unsigned char *)
4468         _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
4469
4470       if (range_start_char < -1)
4471         {
4472           /* range_start is a collating symbol.  */
4473           int32_t *wextra;
4474           /* Retreive the index and get collation sequence value.  */
4475           wextra = (int32_t*)(extra + char_set[-range_start_char]);
4476           start_val = wextra[1 + *wextra];
4477         }
4478       else
4479         start_val = collseq_table_lookup(collseq, TRANSLATE(range_start_char));
4480
4481       end_val = collseq_table_lookup (collseq, TRANSLATE (p[0]));
4482
4483       /* Report an error if the range is empty and the syntax prohibits
4484          this.  */
4485       ret = ((syntax & RE_NO_EMPTY_RANGES)
4486              && (start_val > end_val))? REG_ERANGE : REG_NOERROR;
4487
4488       /* Insert space to the end of the char_ranges.  */
4489       insert_space(2, b - char_set[5] - 2, b - 1);
4490       *(b - char_set[5] - 2) = (wchar_t)start_val;
4491       *(b - char_set[5] - 1) = (wchar_t)end_val;
4492       char_set[4]++; /* ranges_index */
4493     }
4494   else
4495 # endif
4496     {
4497       range_start = (range_start_char >= 0)? TRANSLATE (range_start_char):
4498         range_start_char;
4499       range_end = TRANSLATE (p[0]);
4500       /* Report an error if the range is empty and the syntax prohibits
4501          this.  */
4502       ret = ((syntax & RE_NO_EMPTY_RANGES)
4503              && (range_start > range_end))? REG_ERANGE : REG_NOERROR;
4504
4505       /* Insert space to the end of the char_ranges.  */
4506       insert_space(2, b - char_set[5] - 2, b - 1);
4507       *(b - char_set[5] - 2) = range_start;
4508       *(b - char_set[5] - 1) = range_end;
4509       char_set[4]++; /* ranges_index */
4510     }
4511   /* Have to increment the pointer into the pattern string, so the
4512      caller isn't still at the ending character.  */
4513   (*p_ptr)++;
4514
4515   return ret;
4516 }
4517 #else /* BYTE */
4518 /* Read the ending character of a range (in a bracket expression) from the
4519    uncompiled pattern *P_PTR (which ends at PEND).  We assume the
4520    starting character is in `P[-2]'.  (`P[-1]' is the character `-'.)
4521    Then we set the translation of all bits between the starting and
4522    ending characters (inclusive) in the compiled pattern B.
4523
4524    Return an error code.
4525
4526    We use these short variable names so we can use the same macros as
4527    `regex_compile' itself.  */
4528
4529 static reg_errcode_t
4530 byte_compile_range (range_start_char, p_ptr, pend, translate, syntax, b)
4531      unsigned int range_start_char;
4532      const char **p_ptr, *pend;
4533      RE_TRANSLATE_TYPE translate;
4534      reg_syntax_t syntax;
4535      unsigned char *b;
4536 {
4537   unsigned this_char;
4538   const char *p = *p_ptr;
4539   reg_errcode_t ret;
4540 # if _LIBC
4541   const unsigned char *collseq;
4542   unsigned int start_colseq;
4543   unsigned int end_colseq;
4544 # else
4545   unsigned end_char;
4546 # endif
4547
4548   if (p == pend)
4549     return REG_ERANGE;
4550
4551   /* Have to increment the pointer into the pattern string, so the
4552      caller isn't still at the ending character.  */
4553   (*p_ptr)++;
4554
4555   /* Report an error if the range is empty and the syntax prohibits this.  */
4556   ret = syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
4557
4558 # if _LIBC
4559   collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
4560                                                  _NL_COLLATE_COLLSEQMB);
4561
4562   start_colseq = collseq[(unsigned char) TRANSLATE (range_start_char)];
4563   end_colseq = collseq[(unsigned char) TRANSLATE (p[0])];
4564   for (this_char = 0; this_char <= (unsigned char) -1; ++this_char)
4565     {
4566       unsigned int this_colseq = collseq[(unsigned char) TRANSLATE (this_char)];
4567
4568       if (start_colseq <= this_colseq && this_colseq <= end_colseq)
4569         {
4570           SET_LIST_BIT (TRANSLATE (this_char));
4571           ret = REG_NOERROR;
4572         }
4573     }
4574 # else
4575   /* Here we see why `this_char' has to be larger than an `unsigned
4576      char' -- we would otherwise go into an infinite loop, since all
4577      characters <= 0xff.  */
4578   range_start_char = TRANSLATE (range_start_char);
4579   /* TRANSLATE(p[0]) is casted to char (not unsigned char) in TRANSLATE,
4580      and some compilers cast it to int implicitly, so following for_loop
4581      may fall to (almost) infinite loop.
4582      e.g. If translate[p[0]] = 0xff, end_char may equals to 0xffffffff.
4583      To avoid this, we cast p[0] to unsigned int and truncate it.  */
4584   end_char = ((unsigned)TRANSLATE(p[0]) & ((1 << BYTEWIDTH) - 1));
4585
4586   for (this_char = range_start_char; this_char <= end_char; ++this_char)
4587     {
4588       SET_LIST_BIT (TRANSLATE (this_char));
4589       ret = REG_NOERROR;
4590     }
4591 # endif
4592
4593   return ret;
4594 }
4595 #endif /* WCHAR */
4596 \f
4597 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4598    BUFP.  A fastmap records which of the (1 << BYTEWIDTH) possible
4599    characters can start a string that matches the pattern.  This fastmap
4600    is used by re_search to skip quickly over impossible starting points.
4601
4602    The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4603    area as BUFP->fastmap.
4604
4605    We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4606    the pattern buffer.
4607
4608    Returns 0 if we succeed, -2 if an internal error.   */
4609
4610 #ifdef WCHAR
4611 /* local function for re_compile_fastmap.
4612    truncate wchar_t character to char.  */
4613 static unsigned char truncate_wchar (CHAR_T c);
4614
4615 static unsigned char
4616 truncate_wchar (c)
4617      CHAR_T c;
4618 {
4619   unsigned char buf[MB_LEN_MAX];
4620   int retval = wctomb(buf, c);
4621   return retval > 0 ? buf[0] : (unsigned char)c;
4622 }
4623 #endif /* WCHAR */
4624
4625 static int
4626 PREFIX(re_compile_fastmap) (bufp)
4627      struct re_pattern_buffer *bufp;
4628 {
4629   int j, k;
4630 #ifdef MATCH_MAY_ALLOCATE
4631   PREFIX(fail_stack_type) fail_stack;
4632 #endif
4633 #ifndef REGEX_MALLOC
4634   char *destination;
4635 #endif
4636
4637   register char *fastmap = bufp->fastmap;
4638
4639 #ifdef WCHAR
4640   /* We need to cast pattern to (wchar_t*), because we casted this compiled
4641      pattern to (char*) in regex_compile.  */
4642   UCHAR_T *pattern = (UCHAR_T*)bufp->buffer;
4643   register UCHAR_T *pend = (UCHAR_T*) (bufp->buffer + bufp->used);
4644 #else /* BYTE */
4645   UCHAR_T *pattern = bufp->buffer;
4646   register UCHAR_T *pend = pattern + bufp->used;
4647 #endif /* WCHAR */
4648   UCHAR_T *p = pattern;
4649
4650 #ifdef REL_ALLOC
4651   /* This holds the pointer to the failure stack, when
4652      it is allocated relocatably.  */
4653   fail_stack_elt_t *failure_stack_ptr;
4654 #endif
4655
4656   /* Assume that each path through the pattern can be null until
4657      proven otherwise.  We set this false at the bottom of switch
4658      statement, to which we get only if a particular path doesn't
4659      match the empty string.  */
4660   boolean path_can_be_null = true;
4661
4662   /* We aren't doing a `succeed_n' to begin with.  */
4663   boolean succeed_n_p = false;
4664
4665   assert (fastmap != NULL && p != NULL);
4666
4667   INIT_FAIL_STACK ();
4668   bzero (fastmap, 1 << BYTEWIDTH);  /* Assume nothing's valid.  */
4669   bufp->fastmap_accurate = 1;       /* It will be when we're done.  */
4670   bufp->can_be_null = 0;
4671
4672   while (1)
4673     {
4674       if (p == pend || *p == succeed)
4675         {
4676           /* We have reached the (effective) end of pattern.  */
4677           if (!FAIL_STACK_EMPTY ())
4678             {
4679               bufp->can_be_null |= path_can_be_null;
4680
4681               /* Reset for next path.  */
4682               path_can_be_null = true;
4683
4684               p = fail_stack.stack[--fail_stack.avail].pointer;
4685
4686               continue;
4687             }
4688           else
4689             break;
4690         }
4691
4692       /* We should never be about to go beyond the end of the pattern.  */
4693       assert (p < pend);
4694
4695       switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4696         {
4697
4698         /* I guess the idea here is to simply not bother with a fastmap
4699            if a backreference is used, since it's too hard to figure out
4700            the fastmap for the corresponding group.  Setting
4701            `can_be_null' stops `re_search_2' from using the fastmap, so
4702            that is all we do.  */
4703         case duplicate:
4704           bufp->can_be_null = 1;
4705           goto done;
4706
4707
4708       /* Following are the cases which match a character.  These end
4709          with `break'.  */
4710
4711 #ifdef WCHAR
4712         case exactn:
4713           fastmap[truncate_wchar(p[1])] = 1;
4714           break;
4715 #else /* BYTE */
4716         case exactn:
4717           fastmap[p[1]] = 1;
4718           break;
4719 #endif /* WCHAR */
4720 #ifdef MBS_SUPPORT
4721         case exactn_bin:
4722           fastmap[p[1]] = 1;
4723           break;
4724 #endif
4725
4726 #ifdef WCHAR
4727         /* It is hard to distinguish fastmap from (multi byte) characters
4728            which depends on current locale.  */
4729         case charset:
4730         case charset_not:
4731         case wordchar:
4732         case notwordchar:
4733           bufp->can_be_null = 1;
4734           goto done;
4735 #else /* BYTE */
4736         case charset:
4737           for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4738             if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
4739               fastmap[j] = 1;
4740           break;
4741
4742
4743         case charset_not:
4744           /* Chars beyond end of map must be allowed.  */
4745           for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
4746             fastmap[j] = 1;
4747
4748           for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4749             if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
4750               fastmap[j] = 1;
4751           break;
4752
4753
4754         case wordchar:
4755           for (j = 0; j < (1 << BYTEWIDTH); j++)
4756             if (SYNTAX (j) == Sword)
4757               fastmap[j] = 1;
4758           break;
4759
4760
4761         case notwordchar:
4762           for (j = 0; j < (1 << BYTEWIDTH); j++)
4763             if (SYNTAX (j) != Sword)
4764               fastmap[j] = 1;
4765           break;
4766 #endif /* WCHAR */
4767
4768         case anychar:
4769           {
4770             int fastmap_newline = fastmap['\n'];
4771
4772             /* `.' matches anything ...  */
4773             for (j = 0; j < (1 << BYTEWIDTH); j++)
4774               fastmap[j] = 1;
4775
4776             /* ... except perhaps newline.  */
4777             if (!(bufp->syntax & RE_DOT_NEWLINE))
4778               fastmap['\n'] = fastmap_newline;
4779
4780             /* Return if we have already set `can_be_null'; if we have,
4781                then the fastmap is irrelevant.  Something's wrong here.  */
4782             else if (bufp->can_be_null)
4783               goto done;
4784
4785             /* Otherwise, have to check alternative paths.  */
4786             break;
4787           }
4788
4789 #ifdef emacs
4790         case syntaxspec:
4791           k = *p++;
4792           for (j = 0; j < (1 << BYTEWIDTH); j++)
4793             if (SYNTAX (j) == (enum syntaxcode) k)
4794               fastmap[j] = 1;
4795           break;
4796
4797
4798         case notsyntaxspec:
4799           k = *p++;
4800           for (j = 0; j < (1 << BYTEWIDTH); j++)
4801             if (SYNTAX (j) != (enum syntaxcode) k)
4802               fastmap[j] = 1;
4803           break;
4804
4805
4806       /* All cases after this match the empty string.  These end with
4807          `continue'.  */
4808
4809
4810         case before_dot:
4811         case at_dot:
4812         case after_dot:
4813           continue;
4814 #endif /* emacs */
4815
4816
4817         case no_op:
4818         case begline:
4819         case endline:
4820         case begbuf:
4821         case endbuf:
4822         case wordbound:
4823         case notwordbound:
4824         case wordbeg:
4825         case wordend:
4826         case push_dummy_failure:
4827           continue;
4828
4829
4830         case jump_n:
4831         case pop_failure_jump:
4832         case maybe_pop_jump:
4833         case jump:
4834         case jump_past_alt:
4835         case dummy_failure_jump:
4836           EXTRACT_NUMBER_AND_INCR (j, p);
4837           p += j;
4838           if (j > 0)
4839             continue;
4840
4841           /* Jump backward implies we just went through the body of a
4842              loop and matched nothing.  Opcode jumped to should be
4843              `on_failure_jump' or `succeed_n'.  Just treat it like an
4844              ordinary jump.  For a * loop, it has pushed its failure
4845              point already; if so, discard that as redundant.  */
4846           if ((re_opcode_t) *p != on_failure_jump
4847               && (re_opcode_t) *p != succeed_n)
4848             continue;
4849
4850           p++;
4851           EXTRACT_NUMBER_AND_INCR (j, p);
4852           p += j;
4853
4854           /* If what's on the stack is where we are now, pop it.  */
4855           if (!FAIL_STACK_EMPTY ()
4856               && fail_stack.stack[fail_stack.avail - 1].pointer == p)
4857             fail_stack.avail--;
4858
4859           continue;
4860
4861
4862         case on_failure_jump:
4863         case on_failure_keep_string_jump:
4864         handle_on_failure_jump:
4865           EXTRACT_NUMBER_AND_INCR (j, p);
4866
4867           /* For some patterns, e.g., `(a?)?', `p+j' here points to the
4868              end of the pattern.  We don't want to push such a point,
4869              since when we restore it above, entering the switch will
4870              increment `p' past the end of the pattern.  We don't need
4871              to push such a point since we obviously won't find any more
4872              fastmap entries beyond `pend'.  Such a pattern can match
4873              the null string, though.  */
4874           if (p + j < pend)
4875             {
4876               if (!PUSH_PATTERN_OP (p + j, fail_stack))
4877                 {
4878                   RESET_FAIL_STACK ();
4879                   return -2;
4880                 }
4881             }
4882           else
4883             bufp->can_be_null = 1;
4884
4885           if (succeed_n_p)
4886             {
4887               EXTRACT_NUMBER_AND_INCR (k, p);   /* Skip the n.  */
4888               succeed_n_p = false;
4889             }
4890
4891           continue;
4892
4893
4894         case succeed_n:
4895           /* Get to the number of times to succeed.  */
4896           p += OFFSET_ADDRESS_SIZE;
4897
4898           /* Increment p past the n for when k != 0.  */
4899           EXTRACT_NUMBER_AND_INCR (k, p);
4900           if (k == 0)
4901             {
4902               p -= 2 * OFFSET_ADDRESS_SIZE;
4903               succeed_n_p = true;  /* Spaghetti code alert.  */
4904               goto handle_on_failure_jump;
4905             }
4906           continue;
4907
4908
4909         case set_number_at:
4910           p += 2 * OFFSET_ADDRESS_SIZE;
4911           continue;
4912
4913
4914         case start_memory:
4915         case stop_memory:
4916           p += 2;
4917           continue;
4918
4919
4920         default:
4921           abort (); /* We have listed all the cases.  */
4922         } /* switch *p++ */
4923
4924       /* Getting here means we have found the possible starting
4925          characters for one path of the pattern -- and that the empty
4926          string does not match.  We need not follow this path further.
4927          Instead, look at the next alternative (remembered on the
4928          stack), or quit if no more.  The test at the top of the loop
4929          does these things.  */
4930       path_can_be_null = false;
4931       p = pend;
4932     } /* while p */
4933
4934   /* Set `can_be_null' for the last path (also the first path, if the
4935      pattern is empty).  */
4936   bufp->can_be_null |= path_can_be_null;
4937
4938  done:
4939   RESET_FAIL_STACK ();
4940   return 0;
4941 }
4942
4943 #else /* not INSIDE_RECURSION */
4944
4945 int
4946 re_compile_fastmap (bufp)
4947      struct re_pattern_buffer *bufp;
4948 {
4949 # ifdef MBS_SUPPORT
4950   if (MB_CUR_MAX != 1)
4951     return wcs_re_compile_fastmap(bufp);
4952   else
4953 # endif
4954     return byte_re_compile_fastmap(bufp);
4955 } /* re_compile_fastmap */
4956 #ifdef _LIBC
4957 weak_alias (__re_compile_fastmap, re_compile_fastmap)
4958 #endif
4959 \f
4960
4961 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4962    ENDS.  Subsequent matches using PATTERN_BUFFER and REGS will use
4963    this memory for recording register information.  STARTS and ENDS
4964    must be allocated using the malloc library routine, and must each
4965    be at least NUM_REGS * sizeof (regoff_t) bytes long.
4966
4967    If NUM_REGS == 0, then subsequent matches should allocate their own
4968    register data.
4969
4970    Unless this function is called, the first search or match using
4971    PATTERN_BUFFER will allocate its own register data, without
4972    freeing the old data.  */
4973
4974 void
4975 re_set_registers (bufp, regs, num_regs, starts, ends)
4976     struct re_pattern_buffer *bufp;
4977     struct re_registers *regs;
4978     unsigned num_regs;
4979     regoff_t *starts, *ends;
4980 {
4981   if (num_regs)
4982     {
4983       bufp->regs_allocated = REGS_REALLOCATE;
4984       regs->num_regs = num_regs;
4985       regs->start = starts;
4986       regs->end = ends;
4987     }
4988   else
4989     {
4990       bufp->regs_allocated = REGS_UNALLOCATED;
4991       regs->num_regs = 0;
4992       regs->start = regs->end = (regoff_t *) 0;
4993     }
4994 }
4995 #ifdef _LIBC
4996 weak_alias (__re_set_registers, re_set_registers)
4997 #endif
4998 \f
4999 /* Searching routines.  */
5000
5001 /* Like re_search_2, below, but only one string is specified, and
5002    doesn't let you say where to stop matching.  */
5003
5004 int
5005 re_search (bufp, string, size, startpos, range, regs)
5006      struct re_pattern_buffer *bufp;
5007      const char *string;
5008      int size, startpos, range;
5009      struct re_registers *regs;
5010 {
5011   return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
5012                       regs, size);
5013 }
5014 #ifdef _LIBC
5015 weak_alias (__re_search, re_search)
5016 #endif
5017
5018
5019 /* Using the compiled pattern in BUFP->buffer, first tries to match the
5020    virtual concatenation of STRING1 and STRING2, starting first at index
5021    STARTPOS, then at STARTPOS + 1, and so on.
5022
5023    STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
5024
5025    RANGE is how far to scan while trying to match.  RANGE = 0 means try
5026    only at STARTPOS; in general, the last start tried is STARTPOS +
5027    RANGE.
5028
5029    In REGS, return the indices of the virtual concatenation of STRING1
5030    and STRING2 that matched the entire BUFP->buffer and its contained
5031    subexpressions.
5032
5033    Do not consider matching one past the index STOP in the virtual
5034    concatenation of STRING1 and STRING2.
5035
5036    We return either the position in the strings at which the match was
5037    found, -1 if no match, or -2 if error (such as failure
5038    stack overflow).  */
5039
5040 int
5041 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
5042      struct re_pattern_buffer *bufp;
5043      const char *string1, *string2;
5044      int size1, size2;
5045      int startpos;
5046      int range;
5047      struct re_registers *regs;
5048      int stop;
5049 {
5050 # ifdef MBS_SUPPORT
5051   if (MB_CUR_MAX != 1)
5052     return wcs_re_search_2 (bufp, string1, size1, string2, size2, startpos,
5053                             range, regs, stop);
5054   else
5055 # endif
5056     return byte_re_search_2 (bufp, string1, size1, string2, size2, startpos,
5057                              range, regs, stop);
5058 } /* re_search_2 */
5059 #ifdef _LIBC
5060 weak_alias (__re_search_2, re_search_2)
5061 #endif
5062
5063 #endif /* not INSIDE_RECURSION */
5064
5065 #ifdef INSIDE_RECURSION
5066
5067 #ifdef MATCH_MAY_ALLOCATE
5068 # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
5069 #else
5070 # define FREE_VAR(var) if (var) free (var); var = NULL
5071 #endif
5072
5073 #ifdef WCHAR
5074 # define FREE_WCS_BUFFERS()    \
5075   do {                         \
5076     FREE_VAR (string1);                \
5077     FREE_VAR (string2);                \
5078     FREE_VAR (mbs_offset1);    \
5079     FREE_VAR (mbs_offset2);    \
5080   } while (0)
5081
5082 #endif
5083
5084 static int
5085 PREFIX(re_search_2) (bufp, string1, size1, string2, size2, startpos, range,
5086                      regs, stop)
5087      struct re_pattern_buffer *bufp;
5088      const char *string1, *string2;
5089      int size1, size2;
5090      int startpos;
5091      int range;
5092      struct re_registers *regs;
5093      int stop;
5094 {
5095   int val;
5096   register char *fastmap = bufp->fastmap;
5097   register RE_TRANSLATE_TYPE translate = bufp->translate;
5098   int total_size = size1 + size2;
5099   int endpos = startpos + range;
5100 #ifdef WCHAR
5101   /* We need wchar_t* buffers correspond to cstring1, cstring2.  */
5102   wchar_t *wcs_string1 = NULL, *wcs_string2 = NULL;
5103   /* We need the size of wchar_t buffers correspond to csize1, csize2.  */
5104   int wcs_size1 = 0, wcs_size2 = 0;
5105   /* offset buffer for optimizatoin. See convert_mbs_to_wc.  */
5106   int *mbs_offset1 = NULL, *mbs_offset2 = NULL;
5107   /* They hold whether each wchar_t is binary data or not.  */
5108   char *is_binary = NULL;
5109 #endif /* WCHAR */
5110
5111   /* Check for out-of-range STARTPOS.  */
5112   if (startpos < 0 || startpos > total_size)
5113     return -1;
5114
5115   /* Fix up RANGE if it might eventually take us outside
5116      the virtual concatenation of STRING1 and STRING2.
5117      Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE.  */
5118   if (endpos < 0)
5119     range = 0 - startpos;
5120   else if (endpos > total_size)
5121     range = total_size - startpos;
5122
5123   /* If the search isn't to be a backwards one, don't waste time in a
5124      search for a pattern that must be anchored.  */
5125   if (bufp->used > 0 && range > 0
5126       && ((re_opcode_t) bufp->buffer[0] == begbuf
5127           /* `begline' is like `begbuf' if it cannot match at newlines.  */
5128           || ((re_opcode_t) bufp->buffer[0] == begline
5129               && !bufp->newline_anchor)))
5130     {
5131       if (startpos > 0)
5132         return -1;
5133       else
5134         range = 1;
5135     }
5136
5137 #ifdef emacs
5138   /* In a forward search for something that starts with \=.
5139      don't keep searching past point.  */
5140   if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
5141     {
5142       range = PT - startpos;
5143       if (range <= 0)
5144         return -1;
5145     }
5146 #endif /* emacs */
5147
5148   /* Update the fastmap now if not correct already.  */
5149   if (fastmap && !bufp->fastmap_accurate)
5150     if (re_compile_fastmap (bufp) == -2)
5151       return -2;
5152
5153 #ifdef WCHAR
5154   /* Allocate wchar_t array for wcs_string1 and wcs_string2 and
5155      fill them with converted string.  */
5156   if (size1 != 0)
5157     {
5158       wcs_string1 = REGEX_TALLOC (size1 + 1, CHAR_T);
5159       mbs_offset1 = REGEX_TALLOC (size1 + 1, int);
5160       is_binary = REGEX_TALLOC (size1 + 1, char);
5161       if (!wcs_string1 || !mbs_offset1 || !is_binary)
5162         {
5163           FREE_VAR (wcs_string1);
5164           FREE_VAR (mbs_offset1);
5165           FREE_VAR (is_binary);
5166           return -2;
5167         }
5168       wcs_size1 = convert_mbs_to_wcs(wcs_string1, string1, size1,
5169                                      mbs_offset1, is_binary);
5170       wcs_string1[wcs_size1] = L'\0'; /* for a sentinel  */
5171       FREE_VAR (is_binary);
5172     }
5173   if (size2 != 0)
5174     {
5175       wcs_string2 = REGEX_TALLOC (size2 + 1, CHAR_T);
5176       mbs_offset2 = REGEX_TALLOC (size2 + 1, int);
5177       is_binary = REGEX_TALLOC (size2 + 1, char);
5178       if (!wcs_string2 || !mbs_offset2 || !is_binary)
5179         {
5180           FREE_WCS_BUFFERS ();
5181           FREE_VAR (is_binary);
5182           return -2;
5183         }
5184       wcs_size2 = convert_mbs_to_wcs(wcs_string2, string2, size2,
5185                                      mbs_offset2, is_binary);
5186       wcs_string2[wcs_size2] = L'\0'; /* for a sentinel  */
5187       FREE_VAR (is_binary);
5188     }
5189 #endif /* WCHAR */
5190
5191
5192   /* Loop through the string, looking for a place to start matching.  */
5193   for (;;)
5194     {
5195       /* If a fastmap is supplied, skip quickly over characters that
5196          cannot be the start of a match.  If the pattern can match the
5197          null string, however, we don't need to skip characters; we want
5198          the first null string.  */
5199       if (fastmap && startpos < total_size && !bufp->can_be_null)
5200         {
5201           if (range > 0)        /* Searching forwards.  */
5202             {
5203               register const char *d;
5204               register int lim = 0;
5205               int irange = range;
5206
5207               if (startpos < size1 && startpos + range >= size1)
5208                 lim = range - (size1 - startpos);
5209
5210               d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
5211
5212               /* Written out as an if-else to avoid testing `translate'
5213                  inside the loop.  */
5214               if (translate)
5215                 while (range > lim
5216                        && !fastmap[(unsigned char)
5217                                    translate[(unsigned char) *d++]])
5218                   range--;
5219               else
5220                 while (range > lim && !fastmap[(unsigned char) *d++])
5221                   range--;
5222
5223               startpos += irange - range;
5224             }
5225           else                          /* Searching backwards.  */
5226             {
5227               register CHAR_T c = (size1 == 0 || startpos >= size1
5228                                       ? string2[startpos - size1]
5229                                       : string1[startpos]);
5230
5231               if (!fastmap[(unsigned char) TRANSLATE (c)])
5232                 goto advance;
5233             }
5234         }
5235
5236       /* If can't match the null string, and that's all we have left, fail.  */
5237       if (range >= 0 && startpos == total_size && fastmap
5238           && !bufp->can_be_null)
5239        {
5240 #ifdef WCHAR
5241          FREE_WCS_BUFFERS ();
5242 #endif
5243          return -1;
5244        }
5245
5246 #ifdef WCHAR
5247       val = wcs_re_match_2_internal (bufp, string1, size1, string2,
5248                                      size2, startpos, regs, stop,
5249                                      wcs_string1, wcs_size1,
5250                                      wcs_string2, wcs_size2,
5251                                      mbs_offset1, mbs_offset2);
5252 #else /* BYTE */
5253       val = byte_re_match_2_internal (bufp, string1, size1, string2,
5254                                       size2, startpos, regs, stop);
5255 #endif /* BYTE */
5256
5257 #ifndef REGEX_MALLOC
5258 # ifdef C_ALLOCA
5259       alloca (0);
5260 # endif
5261 #endif
5262
5263       if (val >= 0)
5264         {
5265 #ifdef WCHAR
5266           FREE_WCS_BUFFERS ();
5267 #endif
5268           return startpos;
5269         }
5270
5271       if (val == -2)
5272         {
5273 #ifdef WCHAR
5274           FREE_WCS_BUFFERS ();
5275 #endif
5276           return -2;
5277         }
5278
5279     advance:
5280       if (!range)
5281         break;
5282       else if (range > 0)
5283         {
5284           range--;
5285           startpos++;
5286         }
5287       else
5288         {
5289           range++;
5290           startpos--;
5291         }
5292     }
5293 #ifdef WCHAR
5294   FREE_WCS_BUFFERS ();
5295 #endif
5296   return -1;
5297 }
5298
5299 #ifdef WCHAR
5300 /* This converts PTR, a pointer into one of the search wchar_t strings
5301    `string1' and `string2' into an multibyte string offset from the
5302    beginning of that string. We use mbs_offset to optimize.
5303    See convert_mbs_to_wcs.  */
5304 # define POINTER_TO_OFFSET(ptr)                                         \
5305   (FIRST_STRING_P (ptr)                                                 \
5306    ? ((regoff_t)(mbs_offset1 != NULL? mbs_offset1[(ptr)-string1] : 0))  \
5307    : ((regoff_t)((mbs_offset2 != NULL? mbs_offset2[(ptr)-string2] : 0)  \
5308                  + csize1)))
5309 #else /* BYTE */
5310 /* This converts PTR, a pointer into one of the search strings `string1'
5311    and `string2' into an offset from the beginning of that string.  */
5312 # define POINTER_TO_OFFSET(ptr)                 \
5313   (FIRST_STRING_P (ptr)                         \
5314    ? ((regoff_t) ((ptr) - string1))             \
5315    : ((regoff_t) ((ptr) - string2 + size1)))
5316 #endif /* WCHAR */
5317
5318 /* Macros for dealing with the split strings in re_match_2.  */
5319
5320 #define MATCHING_IN_FIRST_STRING  (dend == end_match_1)
5321
5322 /* Call before fetching a character with *d.  This switches over to
5323    string2 if necessary.  */
5324 #define PREFETCH()                                                      \
5325   while (d == dend)                                                     \
5326     {                                                                   \
5327       /* End of string2 => fail.  */                                    \
5328       if (dend == end_match_2)                                          \
5329         goto fail;                                                      \
5330       /* End of string1 => advance to string2.  */                      \
5331       d = string2;                                                      \
5332       dend = end_match_2;                                               \
5333     }
5334
5335 /* Test if at very beginning or at very end of the virtual concatenation
5336    of `string1' and `string2'.  If only one string, it's `string2'.  */
5337 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
5338 #define AT_STRINGS_END(d) ((d) == end2)
5339
5340
5341 /* Test if D points to a character which is word-constituent.  We have
5342    two special cases to check for: if past the end of string1, look at
5343    the first character in string2; and if before the beginning of
5344    string2, look at the last character in string1.  */
5345 #ifdef WCHAR
5346 /* Use internationalized API instead of SYNTAX.  */
5347 # define WORDCHAR_P(d)                                                  \
5348   (iswalnum ((wint_t)((d) == end1 ? *string2                            \
5349            : (d) == string2 - 1 ? *(end1 - 1) : *(d))) != 0)
5350 #else /* BYTE */
5351 # define WORDCHAR_P(d)                                                  \
5352   (SYNTAX ((d) == end1 ? *string2                                       \
5353            : (d) == string2 - 1 ? *(end1 - 1) : *(d))                   \
5354    == Sword)
5355 #endif /* WCHAR */
5356
5357 /* Disabled due to a compiler bug -- see comment at case wordbound */
5358 #if 0
5359 /* Test if the character before D and the one at D differ with respect
5360    to being word-constituent.  */
5361 #define AT_WORD_BOUNDARY(d)                                             \
5362   (AT_STRINGS_BEG (d) || AT_STRINGS_END (d)                             \
5363    || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
5364 #endif
5365
5366 /* Free everything we malloc.  */
5367 #ifdef MATCH_MAY_ALLOCATE
5368 # ifdef WCHAR
5369 #  define FREE_VARIABLES()                                              \
5370   do {                                                                  \
5371     REGEX_FREE_STACK (fail_stack.stack);                                \
5372     FREE_VAR (regstart);                                                \
5373     FREE_VAR (regend);                                                  \
5374     FREE_VAR (old_regstart);                                            \
5375     FREE_VAR (old_regend);                                              \
5376     FREE_VAR (best_regstart);                                           \
5377     FREE_VAR (best_regend);                                             \
5378     FREE_VAR (reg_info);                                                \
5379     FREE_VAR (reg_dummy);                                               \
5380     FREE_VAR (reg_info_dummy);                                          \
5381     if (!cant_free_wcs_buf)                                             \
5382       {                                                                 \
5383         FREE_VAR (string1);                                             \
5384         FREE_VAR (string2);                                             \
5385         FREE_VAR (mbs_offset1);                                         \
5386         FREE_VAR (mbs_offset2);                                         \
5387       }                                                                 \
5388   } while (0)
5389 # else /* BYTE */
5390 #  define FREE_VARIABLES()                                              \
5391   do {                                                                  \
5392     REGEX_FREE_STACK (fail_stack.stack);                                \
5393     FREE_VAR (regstart);                                                \
5394     FREE_VAR (regend);                                                  \
5395     FREE_VAR (old_regstart);                                            \
5396     FREE_VAR (old_regend);                                              \
5397     FREE_VAR (best_regstart);                                           \
5398     FREE_VAR (best_regend);                                             \
5399     FREE_VAR (reg_info);                                                \
5400     FREE_VAR (reg_dummy);                                               \
5401     FREE_VAR (reg_info_dummy);                                          \
5402   } while (0)
5403 # endif /* WCHAR */
5404 #else
5405 # ifdef WCHAR
5406 #  define FREE_VARIABLES()                                              \
5407   do {                                                                  \
5408     if (!cant_free_wcs_buf)                                             \
5409       {                                                                 \
5410         FREE_VAR (string1);                                             \
5411         FREE_VAR (string2);                                             \
5412         FREE_VAR (mbs_offset1);                                         \
5413         FREE_VAR (mbs_offset2);                                         \
5414       }                                                                 \
5415   } while (0)
5416 # else /* BYTE */
5417 #  define FREE_VARIABLES() ((void)0) /* Do nothing!  But inhibit gcc warning. */
5418 # endif /* WCHAR */
5419 #endif /* not MATCH_MAY_ALLOCATE */
5420
5421 /* These values must meet several constraints.  They must not be valid
5422    register values; since we have a limit of 255 registers (because
5423    we use only one byte in the pattern for the register number), we can
5424    use numbers larger than 255.  They must differ by 1, because of
5425    NUM_FAILURE_ITEMS above.  And the value for the lowest register must
5426    be larger than the value for the highest register, so we do not try
5427    to actually save any registers when none are active.  */
5428 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
5429 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
5430 \f
5431 #else /* not INSIDE_RECURSION */
5432 /* Matching routines.  */
5433
5434 #ifndef emacs   /* Emacs never uses this.  */
5435 /* re_match is like re_match_2 except it takes only a single string.  */
5436
5437 int
5438 re_match (bufp, string, size, pos, regs)
5439      struct re_pattern_buffer *bufp;
5440      const char *string;
5441      int size, pos;
5442      struct re_registers *regs;
5443 {
5444   int result;
5445 # ifdef MBS_SUPPORT
5446   if (MB_CUR_MAX != 1)
5447     result = wcs_re_match_2_internal (bufp, NULL, 0, string, size,
5448                                       pos, regs, size,
5449                                       NULL, 0, NULL, 0, NULL, NULL);
5450   else
5451 # endif
5452     result = byte_re_match_2_internal (bufp, NULL, 0, string, size,
5453                                   pos, regs, size);
5454 # ifndef REGEX_MALLOC
5455 #  ifdef C_ALLOCA
5456   alloca (0);
5457 #  endif
5458 # endif
5459   return result;
5460 }
5461 # ifdef _LIBC
5462 weak_alias (__re_match, re_match)
5463 # endif
5464 #endif /* not emacs */
5465
5466 #endif /* not INSIDE_RECURSION */
5467
5468 #ifdef INSIDE_RECURSION
5469 static boolean PREFIX(group_match_null_string_p) _RE_ARGS ((UCHAR_T **p,
5470                                                     UCHAR_T *end,
5471                                         PREFIX(register_info_type) *reg_info));
5472 static boolean PREFIX(alt_match_null_string_p) _RE_ARGS ((UCHAR_T *p,
5473                                                   UCHAR_T *end,
5474                                         PREFIX(register_info_type) *reg_info));
5475 static boolean PREFIX(common_op_match_null_string_p) _RE_ARGS ((UCHAR_T **p,
5476                                                         UCHAR_T *end,
5477                                         PREFIX(register_info_type) *reg_info));
5478 static int PREFIX(bcmp_translate) _RE_ARGS ((const CHAR_T *s1, const CHAR_T *s2,
5479                                      int len, char *translate));
5480 #else /* not INSIDE_RECURSION */
5481
5482 /* re_match_2 matches the compiled pattern in BUFP against the
5483    the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
5484    and SIZE2, respectively).  We start matching at POS, and stop
5485    matching at STOP.
5486
5487    If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
5488    store offsets for the substring each group matched in REGS.  See the
5489    documentation for exactly how many groups we fill.
5490
5491    We return -1 if no match, -2 if an internal error (such as the
5492    failure stack overflowing).  Otherwise, we return the length of the
5493    matched substring.  */
5494
5495 int
5496 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
5497      struct re_pattern_buffer *bufp;
5498      const char *string1, *string2;
5499      int size1, size2;
5500      int pos;
5501      struct re_registers *regs;
5502      int stop;
5503 {
5504   int result;
5505 # ifdef MBS_SUPPORT
5506   if (MB_CUR_MAX != 1)
5507     result = wcs_re_match_2_internal (bufp, string1, size1, string2, size2,
5508                                       pos, regs, stop,
5509                                       NULL, 0, NULL, 0, NULL, NULL);
5510   else
5511 # endif
5512     result = byte_re_match_2_internal (bufp, string1, size1, string2, size2,
5513                                   pos, regs, stop);
5514
5515 #ifndef REGEX_MALLOC
5516 # ifdef C_ALLOCA
5517   alloca (0);
5518 # endif
5519 #endif
5520   return result;
5521 }
5522 #ifdef _LIBC
5523 weak_alias (__re_match_2, re_match_2)
5524 #endif
5525
5526 #endif /* not INSIDE_RECURSION */
5527
5528 #ifdef INSIDE_RECURSION
5529
5530 #ifdef WCHAR
5531 static int count_mbs_length PARAMS ((int *, int));
5532
5533 /* This check the substring (from 0, to length) of the multibyte string,
5534    to which offset_buffer correspond. And count how many wchar_t_characters
5535    the substring occupy. We use offset_buffer to optimization.
5536    See convert_mbs_to_wcs.  */
5537
5538 static int
5539 count_mbs_length(offset_buffer, length)
5540      int *offset_buffer;
5541      int length;
5542 {
5543   int upper, lower;
5544
5545   /* Check whether the size is valid.  */
5546   if (length < 0)
5547     return -1;
5548
5549   if (offset_buffer == NULL)
5550     return 0;
5551
5552   /* If there are no multibyte character, offset_buffer[i] == i.
5553    Optmize for this case.  */
5554   if (offset_buffer[length] == length)
5555     return length;
5556
5557   /* Set up upper with length. (because for all i, offset_buffer[i] >= i)  */
5558   upper = length;
5559   lower = 0;
5560
5561   while (true)
5562     {
5563       int middle = (lower + upper) / 2;
5564       if (middle == lower || middle == upper)
5565         break;
5566       if (offset_buffer[middle] > length)
5567         upper = middle;
5568       else if (offset_buffer[middle] < length)
5569         lower = middle;
5570       else
5571         return middle;
5572     }
5573
5574   return -1;
5575 }
5576 #endif /* WCHAR */
5577
5578 /* This is a separate function so that we can force an alloca cleanup
5579    afterwards.  */
5580 #ifdef WCHAR
5581 static int
5582 wcs_re_match_2_internal (bufp, cstring1, csize1, cstring2, csize2, pos,
5583                          regs, stop, string1, size1, string2, size2,
5584                          mbs_offset1, mbs_offset2)
5585      struct re_pattern_buffer *bufp;
5586      const char *cstring1, *cstring2;
5587      int csize1, csize2;
5588      int pos;
5589      struct re_registers *regs;
5590      int stop;
5591      /* string1 == string2 == NULL means string1/2, size1/2 and
5592         mbs_offset1/2 need seting up in this function.  */
5593      /* We need wchar_t* buffers correspond to cstring1, cstring2.  */
5594      wchar_t *string1, *string2;
5595      /* We need the size of wchar_t buffers correspond to csize1, csize2.  */
5596      int size1, size2;
5597      /* offset buffer for optimizatoin. See convert_mbs_to_wc.  */
5598      int *mbs_offset1, *mbs_offset2;
5599 #else /* BYTE */
5600 static int
5601 byte_re_match_2_internal (bufp, string1, size1,string2, size2, pos,
5602                           regs, stop)
5603      struct re_pattern_buffer *bufp;
5604      const char *string1, *string2;
5605      int size1, size2;
5606      int pos;
5607      struct re_registers *regs;
5608      int stop;
5609 #endif /* BYTE */
5610 {
5611   /* General temporaries.  */
5612   int mcnt;
5613   UCHAR_T *p1;
5614 #ifdef WCHAR
5615   /* They hold whether each wchar_t is binary data or not.  */
5616   char *is_binary = NULL;
5617   /* If true, we can't free string1/2, mbs_offset1/2.  */
5618   int cant_free_wcs_buf = 1;
5619 #endif /* WCHAR */
5620
5621   /* Just past the end of the corresponding string.  */
5622   const CHAR_T *end1, *end2;
5623
5624   /* Pointers into string1 and string2, just past the last characters in
5625      each to consider matching.  */
5626   const CHAR_T *end_match_1, *end_match_2;
5627
5628   /* Where we are in the data, and the end of the current string.  */
5629   const CHAR_T *d, *dend;
5630
5631   /* Where we are in the pattern, and the end of the pattern.  */
5632 #ifdef WCHAR
5633   UCHAR_T *pattern, *p;
5634   register UCHAR_T *pend;
5635 #else /* BYTE */
5636   UCHAR_T *p = bufp->buffer;
5637   register UCHAR_T *pend = p + bufp->used;
5638 #endif /* WCHAR */
5639
5640   /* Mark the opcode just after a start_memory, so we can test for an
5641      empty subpattern when we get to the stop_memory.  */
5642   UCHAR_T *just_past_start_mem = 0;
5643
5644   /* We use this to map every character in the string.  */
5645   RE_TRANSLATE_TYPE translate = bufp->translate;
5646
5647   /* Failure point stack.  Each place that can handle a failure further
5648      down the line pushes a failure point on this stack.  It consists of
5649      restart, regend, and reg_info for all registers corresponding to
5650      the subexpressions we're currently inside, plus the number of such
5651      registers, and, finally, two char *'s.  The first char * is where
5652      to resume scanning the pattern; the second one is where to resume
5653      scanning the strings.  If the latter is zero, the failure point is
5654      a ``dummy''; if a failure happens and the failure point is a dummy,
5655      it gets discarded and the next next one is tried.  */
5656 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global.  */
5657   PREFIX(fail_stack_type) fail_stack;
5658 #endif
5659 #ifdef DEBUG
5660   static unsigned failure_id;
5661   unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5662 #endif
5663
5664 #ifdef REL_ALLOC
5665   /* This holds the pointer to the failure stack, when
5666      it is allocated relocatably.  */
5667   fail_stack_elt_t *failure_stack_ptr;
5668 #endif
5669
5670   /* We fill all the registers internally, independent of what we
5671      return, for use in backreferences.  The number here includes
5672      an element for register zero.  */
5673   size_t num_regs = bufp->re_nsub + 1;
5674
5675   /* The currently active registers.  */
5676   active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
5677   active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
5678
5679   /* Information on the contents of registers. These are pointers into
5680      the input strings; they record just what was matched (on this
5681      attempt) by a subexpression part of the pattern, that is, the
5682      regnum-th regstart pointer points to where in the pattern we began
5683      matching and the regnum-th regend points to right after where we
5684      stopped matching the regnum-th subexpression.  (The zeroth register
5685      keeps track of what the whole pattern matches.)  */
5686 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
5687   const CHAR_T **regstart, **regend;
5688 #endif
5689
5690   /* If a group that's operated upon by a repetition operator fails to
5691      match anything, then the register for its start will need to be
5692      restored because it will have been set to wherever in the string we
5693      are when we last see its open-group operator.  Similarly for a
5694      register's end.  */
5695 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
5696   const CHAR_T **old_regstart, **old_regend;
5697 #endif
5698
5699   /* The is_active field of reg_info helps us keep track of which (possibly
5700      nested) subexpressions we are currently in. The matched_something
5701      field of reg_info[reg_num] helps us tell whether or not we have
5702      matched any of the pattern so far this time through the reg_num-th
5703      subexpression.  These two fields get reset each time through any
5704      loop their register is in.  */
5705 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global.  */
5706   PREFIX(register_info_type) *reg_info;
5707 #endif
5708
5709   /* The following record the register info as found in the above
5710      variables when we find a match better than any we've seen before.
5711      This happens as we backtrack through the failure points, which in
5712      turn happens only if we have not yet matched the entire string. */
5713   unsigned best_regs_set = false;
5714 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
5715   const CHAR_T **best_regstart, **best_regend;
5716 #endif
5717
5718   /* Logically, this is `best_regend[0]'.  But we don't want to have to
5719      allocate space for that if we're not allocating space for anything
5720      else (see below).  Also, we never need info about register 0 for
5721      any of the other register vectors, and it seems rather a kludge to
5722      treat `best_regend' differently than the rest.  So we keep track of
5723      the end of the best match so far in a separate variable.  We
5724      initialize this to NULL so that when we backtrack the first time
5725      and need to test it, it's not garbage.  */
5726   const CHAR_T *match_end = NULL;
5727
5728   /* This helps SET_REGS_MATCHED avoid doing redundant work.  */
5729   int set_regs_matched_done = 0;
5730
5731   /* Used when we pop values we don't care about.  */
5732 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
5733   const CHAR_T **reg_dummy;
5734   PREFIX(register_info_type) *reg_info_dummy;
5735 #endif
5736
5737 #ifdef DEBUG
5738   /* Counts the total number of registers pushed.  */
5739   unsigned num_regs_pushed = 0;
5740 #endif
5741
5742   DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5743
5744   INIT_FAIL_STACK ();
5745
5746 #ifdef MATCH_MAY_ALLOCATE
5747   /* Do not bother to initialize all the register variables if there are
5748      no groups in the pattern, as it takes a fair amount of time.  If
5749      there are groups, we include space for register 0 (the whole
5750      pattern), even though we never use it, since it simplifies the
5751      array indexing.  We should fix this.  */
5752   if (bufp->re_nsub)
5753     {
5754       regstart = REGEX_TALLOC (num_regs, const CHAR_T *);
5755       regend = REGEX_TALLOC (num_regs, const CHAR_T *);
5756       old_regstart = REGEX_TALLOC (num_regs, const CHAR_T *);
5757       old_regend = REGEX_TALLOC (num_regs, const CHAR_T *);
5758       best_regstart = REGEX_TALLOC (num_regs, const CHAR_T *);
5759       best_regend = REGEX_TALLOC (num_regs, const CHAR_T *);
5760       reg_info = REGEX_TALLOC (num_regs, PREFIX(register_info_type));
5761       reg_dummy = REGEX_TALLOC (num_regs, const CHAR_T *);
5762       reg_info_dummy = REGEX_TALLOC (num_regs, PREFIX(register_info_type));
5763
5764       if (!(regstart && regend && old_regstart && old_regend && reg_info
5765             && best_regstart && best_regend && reg_dummy && reg_info_dummy))
5766         {
5767           FREE_VARIABLES ();
5768           return -2;
5769         }
5770     }
5771   else
5772     {
5773       /* We must initialize all our variables to NULL, so that
5774          `FREE_VARIABLES' doesn't try to free them.  */
5775       regstart = regend = old_regstart = old_regend = best_regstart
5776         = best_regend = reg_dummy = NULL;
5777       reg_info = reg_info_dummy = (PREFIX(register_info_type) *) NULL;
5778     }
5779 #endif /* MATCH_MAY_ALLOCATE */
5780
5781   /* The starting position is bogus.  */
5782 #ifdef WCHAR
5783   if (pos < 0 || pos > csize1 + csize2)
5784 #else /* BYTE */
5785   if (pos < 0 || pos > size1 + size2)
5786 #endif
5787     {
5788       FREE_VARIABLES ();
5789       return -1;
5790     }
5791
5792 #ifdef WCHAR
5793   /* Allocate wchar_t array for string1 and string2 and
5794      fill them with converted string.  */
5795   if (string1 == NULL && string2 == NULL)
5796     {
5797       /* We need seting up buffers here.  */
5798
5799       /* We must free wcs buffers in this function.  */
5800       cant_free_wcs_buf = 0;
5801
5802       if (csize1 != 0)
5803         {
5804           string1 = REGEX_TALLOC (csize1 + 1, CHAR_T);
5805           mbs_offset1 = REGEX_TALLOC (csize1 + 1, int);
5806           is_binary = REGEX_TALLOC (csize1 + 1, char);
5807           if (!string1 || !mbs_offset1 || !is_binary)
5808             {
5809               FREE_VAR (string1);
5810               FREE_VAR (mbs_offset1);
5811               FREE_VAR (is_binary);
5812               return -2;
5813             }
5814         }
5815       if (csize2 != 0)
5816         {
5817           string2 = REGEX_TALLOC (csize2 + 1, CHAR_T);
5818           mbs_offset2 = REGEX_TALLOC (csize2 + 1, int);
5819           is_binary = REGEX_TALLOC (csize2 + 1, char);
5820           if (!string2 || !mbs_offset2 || !is_binary)
5821             {
5822               FREE_VAR (string1);
5823               FREE_VAR (mbs_offset1);
5824               FREE_VAR (string2);
5825               FREE_VAR (mbs_offset2);
5826               FREE_VAR (is_binary);
5827               return -2;
5828             }
5829           size2 = convert_mbs_to_wcs(string2, cstring2, csize2,
5830                                      mbs_offset2, is_binary);
5831           string2[size2] = L'\0'; /* for a sentinel  */
5832           FREE_VAR (is_binary);
5833         }
5834     }
5835
5836   /* We need to cast pattern to (wchar_t*), because we casted this compiled
5837      pattern to (char*) in regex_compile.  */
5838   p = pattern = (CHAR_T*)bufp->buffer;
5839   pend = (CHAR_T*)(bufp->buffer + bufp->used);
5840
5841 #endif /* WCHAR */
5842
5843   /* Initialize subexpression text positions to -1 to mark ones that no
5844      start_memory/stop_memory has been seen for. Also initialize the
5845      register information struct.  */
5846   for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5847     {
5848       regstart[mcnt] = regend[mcnt]
5849         = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
5850
5851       REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
5852       IS_ACTIVE (reg_info[mcnt]) = 0;
5853       MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5854       EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5855     }
5856
5857   /* We move `string1' into `string2' if the latter's empty -- but not if
5858      `string1' is null.  */
5859   if (size2 == 0 && string1 != NULL)
5860     {
5861       string2 = string1;
5862       size2 = size1;
5863       string1 = 0;
5864       size1 = 0;
5865 #ifdef WCHAR
5866       mbs_offset2 = mbs_offset1;
5867       csize2 = csize1;
5868       mbs_offset1 = NULL;
5869       csize1 = 0;
5870 #endif
5871     }
5872   end1 = string1 + size1;
5873   end2 = string2 + size2;
5874
5875   /* Compute where to stop matching, within the two strings.  */
5876 #ifdef WCHAR
5877   if (stop <= csize1)
5878     {
5879       mcnt = count_mbs_length(mbs_offset1, stop);
5880       end_match_1 = string1 + mcnt;
5881       end_match_2 = string2;
5882     }
5883   else
5884     {
5885       if (stop > csize1 + csize2)
5886         stop = csize1 + csize2;
5887       end_match_1 = end1;
5888       mcnt = count_mbs_length(mbs_offset2, stop-csize1);
5889       end_match_2 = string2 + mcnt;
5890     }
5891   if (mcnt < 0)
5892     { /* count_mbs_length return error.  */
5893       FREE_VARIABLES ();
5894       return -1;
5895     }
5896 #else
5897   if (stop <= size1)
5898     {
5899       end_match_1 = string1 + stop;
5900       end_match_2 = string2;
5901     }
5902   else
5903     {
5904       end_match_1 = end1;
5905       end_match_2 = string2 + stop - size1;
5906     }
5907 #endif /* WCHAR */
5908
5909   /* `p' scans through the pattern as `d' scans through the data.
5910      `dend' is the end of the input string that `d' points within.  `d'
5911      is advanced into the following input string whenever necessary, but
5912      this happens before fetching; therefore, at the beginning of the
5913      loop, `d' can be pointing at the end of a string, but it cannot
5914      equal `string2'.  */
5915 #ifdef WCHAR
5916   if (size1 > 0 && pos <= csize1)
5917     {
5918       mcnt = count_mbs_length(mbs_offset1, pos);
5919       d = string1 + mcnt;
5920       dend = end_match_1;
5921     }
5922   else
5923     {
5924       mcnt = count_mbs_length(mbs_offset2, pos-csize1);
5925       d = string2 + mcnt;
5926       dend = end_match_2;
5927     }
5928
5929   if (mcnt < 0)
5930     { /* count_mbs_length return error.  */
5931       FREE_VARIABLES ();
5932       return -1;
5933     }
5934 #else
5935   if (size1 > 0 && pos <= size1)
5936     {
5937       d = string1 + pos;
5938       dend = end_match_1;
5939     }
5940   else
5941     {
5942       d = string2 + pos - size1;
5943       dend = end_match_2;
5944     }
5945 #endif /* WCHAR */
5946
5947   DEBUG_PRINT1 ("The compiled pattern is:\n");
5948   DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5949   DEBUG_PRINT1 ("The string to match is: `");
5950   DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5951   DEBUG_PRINT1 ("'\n");
5952
5953   /* This loops over pattern commands.  It exits by returning from the
5954      function if the match is complete, or it drops through if the match
5955      fails at this starting point in the input data.  */
5956   for (;;)
5957     {
5958 #ifdef _LIBC
5959       DEBUG_PRINT2 ("\n%p: ", p);
5960 #else
5961       DEBUG_PRINT2 ("\n0x%x: ", p);
5962 #endif
5963
5964       if (p == pend)
5965         { /* End of pattern means we might have succeeded.  */
5966           DEBUG_PRINT1 ("end of pattern ... ");
5967
5968           /* If we haven't matched the entire string, and we want the
5969              longest match, try backtracking.  */
5970           if (d != end_match_2)
5971             {
5972               /* 1 if this match ends in the same string (string1 or string2)
5973                  as the best previous match.  */
5974               boolean same_str_p = (FIRST_STRING_P (match_end)
5975                                     == MATCHING_IN_FIRST_STRING);
5976               /* 1 if this match is the best seen so far.  */
5977               boolean best_match_p;
5978
5979               /* AIX compiler got confused when this was combined
5980                  with the previous declaration.  */
5981               if (same_str_p)
5982                 best_match_p = d > match_end;
5983               else
5984                 best_match_p = !MATCHING_IN_FIRST_STRING;
5985
5986               DEBUG_PRINT1 ("backtracking.\n");
5987
5988               if (!FAIL_STACK_EMPTY ())
5989                 { /* More failure points to try.  */
5990
5991                   /* If exceeds best match so far, save it.  */
5992                   if (!best_regs_set || best_match_p)
5993                     {
5994                       best_regs_set = true;
5995                       match_end = d;
5996
5997                       DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5998
5999                       for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
6000                         {
6001                           best_regstart[mcnt] = regstart[mcnt];
6002                           best_regend[mcnt] = regend[mcnt];
6003                         }
6004                     }
6005                   goto fail;
6006                 }
6007
6008               /* If no failure points, don't restore garbage.  And if
6009                  last match is real best match, don't restore second
6010                  best one. */
6011               else if (best_regs_set && !best_match_p)
6012                 {
6013                 restore_best_regs:
6014                   /* Restore best match.  It may happen that `dend ==
6015                      end_match_1' while the restored d is in string2.
6016                      For example, the pattern `x.*y.*z' against the
6017                      strings `x-' and `y-z-', if the two strings are
6018                      not consecutive in memory.  */
6019                   DEBUG_PRINT1 ("Restoring best registers.\n");
6020
6021                   d = match_end;
6022                   dend = ((d >= string1 && d <= end1)
6023                            ? end_match_1 : end_match_2);
6024
6025                   for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
6026                     {
6027                       regstart[mcnt] = best_regstart[mcnt];
6028                       regend[mcnt] = best_regend[mcnt];
6029                     }
6030                 }
6031             } /* d != end_match_2 */
6032
6033         succeed_label:
6034           DEBUG_PRINT1 ("Accepting match.\n");
6035           /* If caller wants register contents data back, do it.  */
6036           if (regs && !bufp->no_sub)
6037             {
6038               /* Have the register data arrays been allocated?  */
6039               if (bufp->regs_allocated == REGS_UNALLOCATED)
6040                 { /* No.  So allocate them with malloc.  We need one
6041                      extra element beyond `num_regs' for the `-1' marker
6042                      GNU code uses.  */
6043                   regs->num_regs = MAX (RE_NREGS, num_regs + 1);
6044                   regs->start = TALLOC (regs->num_regs, regoff_t);
6045                   regs->end = TALLOC (regs->num_regs, regoff_t);
6046                   if (regs->start == NULL || regs->end == NULL)
6047                     {
6048                       FREE_VARIABLES ();
6049                       return -2;
6050                     }
6051                   bufp->regs_allocated = REGS_REALLOCATE;
6052                 }
6053               else if (bufp->regs_allocated == REGS_REALLOCATE)
6054                 { /* Yes.  If we need more elements than were already
6055                      allocated, reallocate them.  If we need fewer, just
6056                      leave it alone.  */
6057                   if (regs->num_regs < num_regs + 1)
6058                     {
6059                       regs->num_regs = num_regs + 1;
6060                       RETALLOC (regs->start, regs->num_regs, regoff_t);
6061                       RETALLOC (regs->end, regs->num_regs, regoff_t);
6062                       if (regs->start == NULL || regs->end == NULL)
6063                         {
6064                           FREE_VARIABLES ();
6065                           return -2;
6066                         }
6067                     }
6068                 }
6069               else
6070                 {
6071                   /* These braces fend off a "empty body in an else-statement"
6072                      warning under GCC when assert expands to nothing.  */
6073                   assert (bufp->regs_allocated == REGS_FIXED);
6074                 }
6075
6076               /* Convert the pointer data in `regstart' and `regend' to
6077                  indices.  Register zero has to be set differently,
6078                  since we haven't kept track of any info for it.  */
6079               if (regs->num_regs > 0)
6080                 {
6081                   regs->start[0] = pos;
6082 #ifdef WCHAR
6083                   if (MATCHING_IN_FIRST_STRING)
6084                     regs->end[0] = mbs_offset1 != NULL ?
6085                                         mbs_offset1[d-string1] : 0;
6086                   else
6087                     regs->end[0] = csize1 + (mbs_offset2 != NULL ?
6088                                              mbs_offset2[d-string2] : 0);
6089 #else
6090                   regs->end[0] = (MATCHING_IN_FIRST_STRING
6091                                   ? ((regoff_t) (d - string1))
6092                                   : ((regoff_t) (d - string2 + size1)));
6093 #endif /* WCHAR */
6094                 }
6095
6096               /* Go through the first `min (num_regs, regs->num_regs)'
6097                  registers, since that is all we initialized.  */
6098               for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
6099                    mcnt++)
6100                 {
6101                   if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
6102                     regs->start[mcnt] = regs->end[mcnt] = -1;
6103                   else
6104                     {
6105                       regs->start[mcnt]
6106                         = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
6107                       regs->end[mcnt]
6108                         = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
6109                     }
6110                 }
6111
6112               /* If the regs structure we return has more elements than
6113                  were in the pattern, set the extra elements to -1.  If
6114                  we (re)allocated the registers, this is the case,
6115                  because we always allocate enough to have at least one
6116                  -1 at the end.  */
6117               for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
6118                 regs->start[mcnt] = regs->end[mcnt] = -1;
6119             } /* regs && !bufp->no_sub */
6120
6121           DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
6122                         nfailure_points_pushed, nfailure_points_popped,
6123                         nfailure_points_pushed - nfailure_points_popped);
6124           DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
6125
6126 #ifdef WCHAR
6127           if (MATCHING_IN_FIRST_STRING)
6128             mcnt = mbs_offset1 != NULL ? mbs_offset1[d-string1] : 0;
6129           else
6130             mcnt = (mbs_offset2 != NULL ? mbs_offset2[d-string2] : 0) +
6131                         csize1;
6132           mcnt -= pos;
6133 #else
6134           mcnt = d - pos - (MATCHING_IN_FIRST_STRING
6135                             ? string1
6136                             : string2 - size1);
6137 #endif /* WCHAR */
6138
6139           DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
6140
6141           FREE_VARIABLES ();
6142           return mcnt;
6143         }
6144
6145       /* Otherwise match next pattern command.  */
6146       switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
6147         {
6148         /* Ignore these.  Used to ignore the n of succeed_n's which
6149            currently have n == 0.  */
6150         case no_op:
6151           DEBUG_PRINT1 ("EXECUTING no_op.\n");
6152           break;
6153
6154         case succeed:
6155           DEBUG_PRINT1 ("EXECUTING succeed.\n");
6156           goto succeed_label;
6157
6158         /* Match the next n pattern characters exactly.  The following
6159            byte in the pattern defines n, and the n bytes after that
6160            are the characters to match.  */
6161         case exactn:
6162 #ifdef MBS_SUPPORT
6163         case exactn_bin:
6164 #endif
6165           mcnt = *p++;
6166           DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
6167
6168           /* This is written out as an if-else so we don't waste time
6169              testing `translate' inside the loop.  */
6170           if (translate)
6171             {
6172               do
6173                 {
6174                   PREFETCH ();
6175 #ifdef WCHAR
6176                   if (*d <= 0xff)
6177                     {
6178                       if ((UCHAR_T) translate[(unsigned char) *d++]
6179                           != (UCHAR_T) *p++)
6180                         goto fail;
6181                     }
6182                   else
6183                     {
6184                       if (*d++ != (CHAR_T) *p++)
6185                         goto fail;
6186                     }
6187 #else
6188                   if ((UCHAR_T) translate[(unsigned char) *d++]
6189                       != (UCHAR_T) *p++)
6190                     goto fail;
6191 #endif /* WCHAR */
6192                 }
6193               while (--mcnt);
6194             }
6195           else
6196             {
6197               do
6198                 {
6199                   PREFETCH ();
6200                   if (*d++ != (CHAR_T) *p++) goto fail;
6201                 }
6202               while (--mcnt);
6203             }
6204           SET_REGS_MATCHED ();
6205           break;
6206
6207
6208         /* Match any character except possibly a newline or a null.  */
6209         case anychar:
6210           DEBUG_PRINT1 ("EXECUTING anychar.\n");
6211
6212           PREFETCH ();
6213
6214           if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
6215               || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
6216             goto fail;
6217
6218           SET_REGS_MATCHED ();
6219           DEBUG_PRINT2 ("  Matched `%ld'.\n", (long int) *d);
6220           d++;
6221           break;
6222
6223
6224         case charset:
6225         case charset_not:
6226           {
6227             register UCHAR_T c;
6228 #ifdef WCHAR
6229             unsigned int i, char_class_length, coll_symbol_length,
6230               equiv_class_length, ranges_length, chars_length, length;
6231             CHAR_T *workp, *workp2, *charset_top;
6232 #define WORK_BUFFER_SIZE 128
6233             CHAR_T str_buf[WORK_BUFFER_SIZE];
6234 # ifdef _LIBC
6235             uint32_t nrules;
6236 # endif /* _LIBC */
6237 #endif /* WCHAR */
6238             boolean not = (re_opcode_t) *(p - 1) == charset_not;
6239
6240             DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
6241             PREFETCH ();
6242             c = TRANSLATE (*d); /* The character to match.  */
6243 #ifdef WCHAR
6244 # ifdef _LIBC
6245             nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
6246 # endif /* _LIBC */
6247             charset_top = p - 1;
6248             char_class_length = *p++;
6249             coll_symbol_length = *p++;
6250             equiv_class_length = *p++;
6251             ranges_length = *p++;
6252             chars_length = *p++;
6253             /* p points charset[6], so the address of the next instruction
6254                (charset[l+m+n+2o+k+p']) equals p[l+m+n+2*o+p'],
6255                where l=length of char_classes, m=length of collating_symbol,
6256                n=equivalence_class, o=length of char_range,
6257                p'=length of character.  */
6258             workp = p;
6259             /* Update p to indicate the next instruction.  */
6260             p += char_class_length + coll_symbol_length+ equiv_class_length +
6261               2*ranges_length + chars_length;
6262
6263             /* match with char_class?  */
6264             for (i = 0; i < char_class_length ; i += CHAR_CLASS_SIZE)
6265               {
6266                 wctype_t wctype;
6267                 uintptr_t alignedp = ((uintptr_t)workp
6268                                       + __alignof__(wctype_t) - 1)
6269                                       & ~(uintptr_t)(__alignof__(wctype_t) - 1);
6270                 wctype = *((wctype_t*)alignedp);
6271                 workp += CHAR_CLASS_SIZE;
6272                 if (iswctype((wint_t)c, wctype))
6273                   goto char_set_matched;
6274               }
6275
6276             /* match with collating_symbol?  */
6277 # ifdef _LIBC
6278             if (nrules != 0)
6279               {
6280                 const unsigned char *extra = (const unsigned char *)
6281                   _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
6282
6283                 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;
6284                      workp++)
6285                   {
6286                     int32_t *wextra;
6287                     wextra = (int32_t*)(extra + *workp++);
6288                     for (i = 0; i < *wextra; ++i)
6289                       if (TRANSLATE(d[i]) != wextra[1 + i])
6290                         break;
6291
6292                     if (i == *wextra)
6293                       {
6294                         /* Update d, however d will be incremented at
6295                            char_set_matched:, we decrement d here.  */
6296                         d += i - 1;
6297                         goto char_set_matched;
6298                       }
6299                   }
6300               }
6301             else /* (nrules == 0) */
6302 # endif
6303               /* If we can't look up collation data, we use wcscoll
6304                  instead.  */
6305               {
6306                 for (workp2 = workp + coll_symbol_length ; workp < workp2 ;)
6307                   {
6308                     const CHAR_T *backup_d = d, *backup_dend = dend;
6309                     length = wcslen(workp);
6310
6311                     /* If wcscoll(the collating symbol, whole string) > 0,
6312                        any substring of the string never match with the
6313                        collating symbol.  */
6314                     if (wcscoll(workp, d) > 0)
6315                       {
6316                         workp += length + 1;
6317                         continue;
6318                       }
6319
6320                     /* First, we compare the collating symbol with
6321                        the first character of the string.
6322                        If it don't match, we add the next character to
6323                        the compare buffer in turn.  */
6324                     for (i = 0 ; i < WORK_BUFFER_SIZE-1 ; i++, d++)
6325                       {
6326                         int match;
6327                         if (d == dend)
6328                           {
6329                             if (dend == end_match_2)
6330                               break;
6331                             d = string2;
6332                             dend = end_match_2;
6333                           }
6334
6335                         /* add next character to the compare buffer.  */
6336                         str_buf[i] = TRANSLATE(*d);
6337                         str_buf[i+1] = '\0';
6338
6339                         match = wcscoll(workp, str_buf);
6340                         if (match == 0)
6341                           goto char_set_matched;
6342
6343                         if (match < 0)
6344                           /* (str_buf > workp) indicate (str_buf + X > workp),
6345                              because for all X (str_buf + X > str_buf).
6346                              So we don't need continue this loop.  */
6347                           break;
6348
6349                         /* Otherwise(str_buf < workp),
6350                            (str_buf+next_character) may equals (workp).
6351                            So we continue this loop.  */
6352                       }
6353                     /* not matched */
6354                     d = backup_d;
6355                     dend = backup_dend;
6356                     workp += length + 1;
6357                   }
6358               }
6359             /* match with equivalence_class?  */
6360 # ifdef _LIBC
6361             if (nrules != 0)
6362               {
6363                 const CHAR_T *backup_d = d, *backup_dend = dend;
6364                 /* Try to match the equivalence class against
6365                    those known to the collate implementation.  */
6366                 const int32_t *table;
6367                 const int32_t *weights;
6368                 const int32_t *extra;
6369                 const int32_t *indirect;
6370                 int32_t idx, idx2;
6371                 wint_t *cp;
6372                 size_t len;
6373
6374                 /* This #include defines a local function!  */
6375 #  include <locale/weightwc.h>
6376
6377                 table = (const int32_t *)
6378                   _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
6379                 weights = (const wint_t *)
6380                   _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
6381                 extra = (const wint_t *)
6382                   _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
6383                 indirect = (const int32_t *)
6384                   _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
6385
6386                 /* Write 1 collating element to str_buf, and
6387                    get its index.  */
6388                 idx2 = 0;
6389
6390                 for (i = 0 ; idx2 == 0 && i < WORK_BUFFER_SIZE - 1; i++)
6391                   {
6392                     cp = (wint_t*)str_buf;
6393                     if (d == dend)
6394                       {
6395                         if (dend == end_match_2)
6396                           break;
6397                         d = string2;
6398                         dend = end_match_2;
6399                       }
6400                     str_buf[i] = TRANSLATE(*(d+i));
6401                     str_buf[i+1] = '\0'; /* sentinel */
6402                     idx2 = findidx ((const wint_t**)&cp);
6403                   }
6404
6405                 /* Update d, however d will be incremented at
6406                    char_set_matched:, we decrement d here.  */
6407                 d = backup_d + ((wchar_t*)cp - (wchar_t*)str_buf - 1);
6408                 if (d >= dend)
6409                   {
6410                     if (dend == end_match_2)
6411                         d = dend;
6412                     else
6413                       {
6414                         d = string2;
6415                         dend = end_match_2;
6416                       }
6417                   }
6418
6419                 len = weights[idx2];
6420
6421                 for (workp2 = workp + equiv_class_length ; workp < workp2 ;
6422                      workp++)
6423                   {
6424                     idx = (int32_t)*workp;
6425                     /* We already checked idx != 0 in regex_compile. */
6426
6427                     if (idx2 != 0 && len == weights[idx])
6428                       {
6429                         int cnt = 0;
6430                         while (cnt < len && (weights[idx + 1 + cnt]
6431                                              == weights[idx2 + 1 + cnt]))
6432                           ++cnt;
6433
6434                         if (cnt == len)
6435                           goto char_set_matched;
6436                       }
6437                   }
6438                 /* not matched */
6439                 d = backup_d;
6440                 dend = backup_dend;
6441               }
6442             else /* (nrules == 0) */
6443 # endif
6444               /* If we can't look up collation data, we use wcscoll
6445                  instead.  */
6446               {
6447                 for (workp2 = workp + equiv_class_length ; workp < workp2 ;)
6448                   {
6449                     const CHAR_T *backup_d = d, *backup_dend = dend;
6450                     length = wcslen(workp);
6451
6452                     /* If wcscoll(the collating symbol, whole string) > 0,
6453                        any substring of the string never match with the
6454                        collating symbol.  */
6455                     if (wcscoll(workp, d) > 0)
6456                       {
6457                         workp += length + 1;
6458                         break;
6459                       }
6460
6461                     /* First, we compare the equivalence class with
6462                        the first character of the string.
6463                        If it don't match, we add the next character to
6464                        the compare buffer in turn.  */
6465                     for (i = 0 ; i < WORK_BUFFER_SIZE - 1 ; i++, d++)
6466                       {
6467                         int match;
6468                         if (d == dend)
6469                           {
6470                             if (dend == end_match_2)
6471                               break;
6472                             d = string2;
6473                             dend = end_match_2;
6474                           }
6475
6476                         /* add next character to the compare buffer.  */
6477                         str_buf[i] = TRANSLATE(*d);
6478                         str_buf[i+1] = '\0';
6479
6480                         match = wcscoll(workp, str_buf);
6481
6482                         if (match == 0)
6483                           goto char_set_matched;
6484
6485                         if (match < 0)
6486                         /* (str_buf > workp) indicate (str_buf + X > workp),
6487                            because for all X (str_buf + X > str_buf).
6488                            So we don't need continue this loop.  */
6489                           break;
6490
6491                         /* Otherwise(str_buf < workp),
6492                            (str_buf+next_character) may equals (workp).
6493                            So we continue this loop.  */
6494                       }
6495                     /* not matched */
6496                     d = backup_d;
6497                     dend = backup_dend;
6498                     workp += length + 1;
6499                   }
6500               }
6501
6502             /* match with char_range?  */
6503 #ifdef _LIBC
6504             if (nrules != 0)
6505               {
6506                 uint32_t collseqval;
6507                 const char *collseq = (const char *)
6508                   _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQWC);
6509
6510                 collseqval = collseq_table_lookup (collseq, c);
6511
6512                 for (; workp < p - chars_length ;)
6513                   {
6514                     uint32_t start_val, end_val;
6515
6516                     /* We already compute the collation sequence value
6517                        of the characters (or collating symbols).  */
6518                     start_val = (uint32_t) *workp++; /* range_start */
6519                     end_val = (uint32_t) *workp++; /* range_end */
6520
6521                     if (start_val <= collseqval && collseqval <= end_val)
6522                       goto char_set_matched;
6523                   }
6524               }
6525             else
6526 #endif
6527               {
6528                 /* We set range_start_char at str_buf[0], range_end_char
6529                    at str_buf[4], and compared char at str_buf[2].  */
6530                 str_buf[1] = 0;
6531                 str_buf[2] = c;
6532                 str_buf[3] = 0;
6533                 str_buf[5] = 0;
6534                 for (; workp < p - chars_length ;)
6535                   {
6536                     wchar_t *range_start_char, *range_end_char;
6537
6538                     /* match if (range_start_char <= c <= range_end_char).  */
6539
6540                     /* If range_start(or end) < 0, we assume -range_start(end)
6541                        is the offset of the collating symbol which is specified
6542                        as the character of the range start(end).  */
6543
6544                     /* range_start */
6545                     if (*workp < 0)
6546                       range_start_char = charset_top - (*workp++);
6547                     else
6548                       {
6549                         str_buf[0] = *workp++;
6550                         range_start_char = str_buf;
6551                       }
6552
6553                     /* range_end */
6554                     if (*workp < 0)
6555                       range_end_char = charset_top - (*workp++);
6556                     else
6557                       {
6558                         str_buf[4] = *workp++;
6559                         range_end_char = str_buf + 4;
6560                       }
6561
6562                     if (wcscoll(range_start_char, str_buf+2) <= 0 &&
6563                         wcscoll(str_buf+2, range_end_char) <= 0)
6564
6565                       goto char_set_matched;
6566                   }
6567               }
6568
6569             /* match with char?  */
6570             for (; workp < p ; workp++)
6571               if (c == *workp)
6572                 goto char_set_matched;
6573
6574             not = !not;
6575
6576           char_set_matched:
6577             if (not) goto fail;
6578 #else
6579             /* Cast to `unsigned' instead of `unsigned char' in case the
6580                bit list is a full 32 bytes long.  */
6581             if (c < (unsigned) (*p * BYTEWIDTH)
6582                 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6583               not = !not;
6584
6585             p += 1 + *p;
6586
6587             if (!not) goto fail;
6588 #undef WORK_BUFFER_SIZE
6589 #endif /* WCHAR */
6590             SET_REGS_MATCHED ();
6591             d++;
6592             break;
6593           }
6594
6595
6596         /* The beginning of a group is represented by start_memory.
6597            The arguments are the register number in the next byte, and the
6598            number of groups inner to this one in the next.  The text
6599            matched within the group is recorded (in the internal
6600            registers data structure) under the register number.  */
6601         case start_memory:
6602           DEBUG_PRINT3 ("EXECUTING start_memory %ld (%ld):\n",
6603                         (long int) *p, (long int) p[1]);
6604
6605           /* Find out if this group can match the empty string.  */
6606           p1 = p;               /* To send to group_match_null_string_p.  */
6607
6608           if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
6609             REG_MATCH_NULL_STRING_P (reg_info[*p])
6610               = PREFIX(group_match_null_string_p) (&p1, pend, reg_info);
6611
6612           /* Save the position in the string where we were the last time
6613              we were at this open-group operator in case the group is
6614              operated upon by a repetition operator, e.g., with `(a*)*b'
6615              against `ab'; then we want to ignore where we are now in
6616              the string in case this attempt to match fails.  */
6617           old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6618                              ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
6619                              : regstart[*p];
6620           DEBUG_PRINT2 ("  old_regstart: %d\n",
6621                          POINTER_TO_OFFSET (old_regstart[*p]));
6622
6623           regstart[*p] = d;
6624           DEBUG_PRINT2 ("  regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
6625
6626           IS_ACTIVE (reg_info[*p]) = 1;
6627           MATCHED_SOMETHING (reg_info[*p]) = 0;
6628
6629           /* Clear this whenever we change the register activity status.  */
6630           set_regs_matched_done = 0;
6631
6632           /* This is the new highest active register.  */
6633           highest_active_reg = *p;
6634
6635           /* If nothing was active before, this is the new lowest active
6636              register.  */
6637           if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6638             lowest_active_reg = *p;
6639
6640           /* Move past the register number and inner group count.  */
6641           p += 2;
6642           just_past_start_mem = p;
6643
6644           break;
6645
6646
6647         /* The stop_memory opcode represents the end of a group.  Its
6648            arguments are the same as start_memory's: the register
6649            number, and the number of inner groups.  */
6650         case stop_memory:
6651           DEBUG_PRINT3 ("EXECUTING stop_memory %ld (%ld):\n",
6652                         (long int) *p, (long int) p[1]);
6653
6654           /* We need to save the string position the last time we were at
6655              this close-group operator in case the group is operated
6656              upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
6657              against `aba'; then we want to ignore where we are now in
6658              the string in case this attempt to match fails.  */
6659           old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6660                            ? REG_UNSET (regend[*p]) ? d : regend[*p]
6661                            : regend[*p];
6662           DEBUG_PRINT2 ("      old_regend: %d\n",
6663                          POINTER_TO_OFFSET (old_regend[*p]));
6664
6665           regend[*p] = d;
6666           DEBUG_PRINT2 ("      regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
6667
6668           /* This register isn't active anymore.  */
6669           IS_ACTIVE (reg_info[*p]) = 0;
6670
6671           /* Clear this whenever we change the register activity status.  */
6672           set_regs_matched_done = 0;
6673
6674           /* If this was the only register active, nothing is active
6675              anymore.  */
6676           if (lowest_active_reg == highest_active_reg)
6677             {
6678               lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6679               highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6680             }
6681           else
6682             { /* We must scan for the new highest active register, since
6683                  it isn't necessarily one less than now: consider
6684                  (a(b)c(d(e)f)g).  When group 3 ends, after the f), the
6685                  new highest active register is 1.  */
6686               UCHAR_T r = *p - 1;
6687               while (r > 0 && !IS_ACTIVE (reg_info[r]))
6688                 r--;
6689
6690               /* If we end up at register zero, that means that we saved
6691                  the registers as the result of an `on_failure_jump', not
6692                  a `start_memory', and we jumped to past the innermost
6693                  `stop_memory'.  For example, in ((.)*) we save
6694                  registers 1 and 2 as a result of the *, but when we pop
6695                  back to the second ), we are at the stop_memory 1.
6696                  Thus, nothing is active.  */
6697               if (r == 0)
6698                 {
6699                   lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6700                   highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6701                 }
6702               else
6703                 highest_active_reg = r;
6704             }
6705
6706           /* If just failed to match something this time around with a
6707              group that's operated on by a repetition operator, try to
6708              force exit from the ``loop'', and restore the register
6709              information for this group that we had before trying this
6710              last match.  */
6711           if ((!MATCHED_SOMETHING (reg_info[*p])
6712                || just_past_start_mem == p - 1)
6713               && (p + 2) < pend)
6714             {
6715               boolean is_a_jump_n = false;
6716
6717               p1 = p + 2;
6718               mcnt = 0;
6719               switch ((re_opcode_t) *p1++)
6720                 {
6721                   case jump_n:
6722                     is_a_jump_n = true;
6723                   case pop_failure_jump:
6724                   case maybe_pop_jump:
6725                   case jump:
6726                   case dummy_failure_jump:
6727                     EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6728                     if (is_a_jump_n)
6729                       p1 += OFFSET_ADDRESS_SIZE;
6730                     break;
6731
6732                   default:
6733                     /* do nothing */ ;
6734                 }
6735               p1 += mcnt;
6736
6737               /* If the next operation is a jump backwards in the pattern
6738                  to an on_failure_jump right before the start_memory
6739                  corresponding to this stop_memory, exit from the loop
6740                  by forcing a failure after pushing on the stack the
6741                  on_failure_jump's jump in the pattern, and d.  */
6742               if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
6743                   && (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == start_memory
6744                   && p1[2+OFFSET_ADDRESS_SIZE] == *p)
6745                 {
6746                   /* If this group ever matched anything, then restore
6747                      what its registers were before trying this last
6748                      failed match, e.g., with `(a*)*b' against `ab' for
6749                      regstart[1], and, e.g., with `((a*)*(b*)*)*'
6750                      against `aba' for regend[3].
6751
6752                      Also restore the registers for inner groups for,
6753                      e.g., `((a*)(b*))*' against `aba' (register 3 would
6754                      otherwise get trashed).  */
6755
6756                   if (EVER_MATCHED_SOMETHING (reg_info[*p]))
6757                     {
6758                       unsigned r;
6759
6760                       EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
6761
6762                       /* Restore this and inner groups' (if any) registers.  */
6763                       for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
6764                            r++)
6765                         {
6766                           regstart[r] = old_regstart[r];
6767
6768                           /* xx why this test?  */
6769                           if (old_regend[r] >= regstart[r])
6770                             regend[r] = old_regend[r];
6771                         }
6772                     }
6773                   p1++;
6774                   EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6775                   PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
6776
6777                   goto fail;
6778                 }
6779             }
6780
6781           /* Move past the register number and the inner group count.  */
6782           p += 2;
6783           break;
6784
6785
6786         /* \<digit> has been turned into a `duplicate' command which is
6787            followed by the numeric value of <digit> as the register number.  */
6788         case duplicate:
6789           {
6790             register const CHAR_T *d2, *dend2;
6791             int regno = *p++;   /* Get which register to match against.  */
6792             DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
6793
6794             /* Can't back reference a group which we've never matched.  */
6795             if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
6796               goto fail;
6797
6798             /* Where in input to try to start matching.  */
6799             d2 = regstart[regno];
6800
6801             /* Where to stop matching; if both the place to start and
6802                the place to stop matching are in the same string, then
6803                set to the place to stop, otherwise, for now have to use
6804                the end of the first string.  */
6805
6806             dend2 = ((FIRST_STRING_P (regstart[regno])
6807                       == FIRST_STRING_P (regend[regno]))
6808                      ? regend[regno] : end_match_1);
6809             for (;;)
6810               {
6811                 /* If necessary, advance to next segment in register
6812                    contents.  */
6813                 while (d2 == dend2)
6814                   {
6815                     if (dend2 == end_match_2) break;
6816                     if (dend2 == regend[regno]) break;
6817
6818                     /* End of string1 => advance to string2. */
6819                     d2 = string2;
6820                     dend2 = regend[regno];
6821                   }
6822                 /* At end of register contents => success */
6823                 if (d2 == dend2) break;
6824
6825                 /* If necessary, advance to next segment in data.  */
6826                 PREFETCH ();
6827
6828                 /* How many characters left in this segment to match.  */
6829                 mcnt = dend - d;
6830
6831                 /* Want how many consecutive characters we can match in
6832                    one shot, so, if necessary, adjust the count.  */
6833                 if (mcnt > dend2 - d2)
6834                   mcnt = dend2 - d2;
6835
6836                 /* Compare that many; failure if mismatch, else move
6837                    past them.  */
6838                 if (translate
6839                     ? PREFIX(bcmp_translate) (d, d2, mcnt, translate)
6840                     : memcmp (d, d2, mcnt*sizeof(UCHAR_T)))
6841                   goto fail;
6842                 d += mcnt, d2 += mcnt;
6843
6844                 /* Do this because we've match some characters.  */
6845                 SET_REGS_MATCHED ();
6846               }
6847           }
6848           break;
6849
6850
6851         /* begline matches the empty string at the beginning of the string
6852            (unless `not_bol' is set in `bufp'), and, if
6853            `newline_anchor' is set, after newlines.  */
6854         case begline:
6855           DEBUG_PRINT1 ("EXECUTING begline.\n");
6856
6857           if (AT_STRINGS_BEG (d))
6858             {
6859               if (!bufp->not_bol) break;
6860             }
6861           else if (d[-1] == '\n' && bufp->newline_anchor)
6862             {
6863               break;
6864             }
6865           /* In all other cases, we fail.  */
6866           goto fail;
6867
6868
6869         /* endline is the dual of begline.  */
6870         case endline:
6871           DEBUG_PRINT1 ("EXECUTING endline.\n");
6872
6873           if (AT_STRINGS_END (d))
6874             {
6875               if (!bufp->not_eol) break;
6876             }
6877
6878           /* We have to ``prefetch'' the next character.  */
6879           else if ((d == end1 ? *string2 : *d) == '\n'
6880                    && bufp->newline_anchor)
6881             {
6882               break;
6883             }
6884           goto fail;
6885
6886
6887         /* Match at the very beginning of the data.  */
6888         case begbuf:
6889           DEBUG_PRINT1 ("EXECUTING begbuf.\n");
6890           if (AT_STRINGS_BEG (d))
6891             break;
6892           goto fail;
6893
6894
6895         /* Match at the very end of the data.  */
6896         case endbuf:
6897           DEBUG_PRINT1 ("EXECUTING endbuf.\n");
6898           if (AT_STRINGS_END (d))
6899             break;
6900           goto fail;
6901
6902
6903         /* on_failure_keep_string_jump is used to optimize `.*\n'.  It
6904            pushes NULL as the value for the string on the stack.  Then
6905            `pop_failure_point' will keep the current value for the
6906            string, instead of restoring it.  To see why, consider
6907            matching `foo\nbar' against `.*\n'.  The .* matches the foo;
6908            then the . fails against the \n.  But the next thing we want
6909            to do is match the \n against the \n; if we restored the
6910            string value, we would be back at the foo.
6911
6912            Because this is used only in specific cases, we don't need to
6913            check all the things that `on_failure_jump' does, to make
6914            sure the right things get saved on the stack.  Hence we don't
6915            share its code.  The only reason to push anything on the
6916            stack at all is that otherwise we would have to change
6917            `anychar's code to do something besides goto fail in this
6918            case; that seems worse than this.  */
6919         case on_failure_keep_string_jump:
6920           DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
6921
6922           EXTRACT_NUMBER_AND_INCR (mcnt, p);
6923 #ifdef _LIBC
6924           DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
6925 #else
6926           DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
6927 #endif
6928
6929           PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
6930           break;
6931
6932
6933         /* Uses of on_failure_jump:
6934
6935            Each alternative starts with an on_failure_jump that points
6936            to the beginning of the next alternative.  Each alternative
6937            except the last ends with a jump that in effect jumps past
6938            the rest of the alternatives.  (They really jump to the
6939            ending jump of the following alternative, because tensioning
6940            these jumps is a hassle.)
6941
6942            Repeats start with an on_failure_jump that points past both
6943            the repetition text and either the following jump or
6944            pop_failure_jump back to this on_failure_jump.  */
6945         case on_failure_jump:
6946         on_failure:
6947           DEBUG_PRINT1 ("EXECUTING on_failure_jump");
6948
6949           EXTRACT_NUMBER_AND_INCR (mcnt, p);
6950 #ifdef _LIBC
6951           DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
6952 #else
6953           DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
6954 #endif
6955
6956           /* If this on_failure_jump comes right before a group (i.e.,
6957              the original * applied to a group), save the information
6958              for that group and all inner ones, so that if we fail back
6959              to this point, the group's information will be correct.
6960              For example, in \(a*\)*\1, we need the preceding group,
6961              and in \(zz\(a*\)b*\)\2, we need the inner group.  */
6962
6963           /* We can't use `p' to check ahead because we push
6964              a failure point to `p + mcnt' after we do this.  */
6965           p1 = p;
6966
6967           /* We need to skip no_op's before we look for the
6968              start_memory in case this on_failure_jump is happening as
6969              the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
6970              against aba.  */
6971           while (p1 < pend && (re_opcode_t) *p1 == no_op)
6972             p1++;
6973
6974           if (p1 < pend && (re_opcode_t) *p1 == start_memory)
6975             {
6976               /* We have a new highest active register now.  This will
6977                  get reset at the start_memory we are about to get to,
6978                  but we will have saved all the registers relevant to
6979                  this repetition op, as described above.  */
6980               highest_active_reg = *(p1 + 1) + *(p1 + 2);
6981               if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6982                 lowest_active_reg = *(p1 + 1);
6983             }
6984
6985           DEBUG_PRINT1 (":\n");
6986           PUSH_FAILURE_POINT (p + mcnt, d, -2);
6987           break;
6988
6989
6990         /* A smart repeat ends with `maybe_pop_jump'.
6991            We change it to either `pop_failure_jump' or `jump'.  */
6992         case maybe_pop_jump:
6993           EXTRACT_NUMBER_AND_INCR (mcnt, p);
6994           DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
6995           {
6996             register UCHAR_T *p2 = p;
6997
6998             /* Compare the beginning of the repeat with what in the
6999                pattern follows its end. If we can establish that there
7000                is nothing that they would both match, i.e., that we
7001                would have to backtrack because of (as in, e.g., `a*a')
7002                then we can change to pop_failure_jump, because we'll
7003                never have to backtrack.
7004
7005                This is not true in the case of alternatives: in
7006                `(a|ab)*' we do need to backtrack to the `ab' alternative
7007                (e.g., if the string was `ab').  But instead of trying to
7008                detect that here, the alternative has put on a dummy
7009                failure point which is what we will end up popping.  */
7010
7011             /* Skip over open/close-group commands.
7012                If what follows this loop is a ...+ construct,
7013                look at what begins its body, since we will have to
7014                match at least one of that.  */
7015             while (1)
7016               {
7017                 if (p2 + 2 < pend
7018                     && ((re_opcode_t) *p2 == stop_memory
7019                         || (re_opcode_t) *p2 == start_memory))
7020                   p2 += 3;
7021                 else if (p2 + 2 + 2 * OFFSET_ADDRESS_SIZE < pend
7022                          && (re_opcode_t) *p2 == dummy_failure_jump)
7023                   p2 += 2 + 2 * OFFSET_ADDRESS_SIZE;
7024                 else
7025                   break;
7026               }
7027
7028             p1 = p + mcnt;
7029             /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
7030                to the `maybe_finalize_jump' of this case.  Examine what
7031                follows.  */
7032
7033             /* If we're at the end of the pattern, we can change.  */
7034             if (p2 == pend)
7035               {
7036                 /* Consider what happens when matching ":\(.*\)"
7037                    against ":/".  I don't really understand this code
7038                    yet.  */
7039                 p[-(1+OFFSET_ADDRESS_SIZE)] = (UCHAR_T)
7040                   pop_failure_jump;
7041                 DEBUG_PRINT1
7042                   ("  End of pattern: change to `pop_failure_jump'.\n");
7043               }
7044
7045             else if ((re_opcode_t) *p2 == exactn
7046 #ifdef MBS_SUPPORT
7047                      || (re_opcode_t) *p2 == exactn_bin
7048 #endif
7049                      || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
7050               {
7051                 register UCHAR_T c
7052                   = *p2 == (UCHAR_T) endline ? '\n' : p2[2];
7053
7054                 if (((re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn
7055 #ifdef MBS_SUPPORT
7056                      || (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn_bin
7057 #endif
7058                     ) && p1[3+OFFSET_ADDRESS_SIZE] != c)
7059                   {
7060                     p[-(1+OFFSET_ADDRESS_SIZE)] = (UCHAR_T)
7061                       pop_failure_jump;
7062 #ifdef WCHAR
7063                       DEBUG_PRINT3 ("  %C != %C => pop_failure_jump.\n",
7064                                     (wint_t) c,
7065                                     (wint_t) p1[3+OFFSET_ADDRESS_SIZE]);
7066 #else
7067                       DEBUG_PRINT3 ("  %c != %c => pop_failure_jump.\n",
7068                                     (char) c,
7069                                     (char) p1[3+OFFSET_ADDRESS_SIZE]);
7070 #endif
7071                   }
7072
7073 #ifndef WCHAR
7074                 else if ((re_opcode_t) p1[3] == charset
7075                          || (re_opcode_t) p1[3] == charset_not)
7076                   {
7077                     int not = (re_opcode_t) p1[3] == charset_not;
7078
7079                     if (c < (unsigned) (p1[4] * BYTEWIDTH)
7080                         && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
7081                       not = !not;
7082
7083                     /* `not' is equal to 1 if c would match, which means
7084                         that we can't change to pop_failure_jump.  */
7085                     if (!not)
7086                       {
7087                         p[-3] = (unsigned char) pop_failure_jump;
7088                         DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
7089                       }
7090                   }
7091 #endif /* not WCHAR */
7092               }
7093 #ifndef WCHAR
7094             else if ((re_opcode_t) *p2 == charset)
7095               {
7096                 /* We win if the first character of the loop is not part
7097                    of the charset.  */
7098                 if ((re_opcode_t) p1[3] == exactn
7099                     && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
7100                           && (p2[2 + p1[5] / BYTEWIDTH]
7101                               & (1 << (p1[5] % BYTEWIDTH)))))
7102                   {
7103                     p[-3] = (unsigned char) pop_failure_jump;
7104                     DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
7105                   }
7106
7107                 else if ((re_opcode_t) p1[3] == charset_not)
7108                   {
7109                     int idx;
7110                     /* We win if the charset_not inside the loop
7111                        lists every character listed in the charset after.  */
7112                     for (idx = 0; idx < (int) p2[1]; idx++)
7113                       if (! (p2[2 + idx] == 0
7114                              || (idx < (int) p1[4]
7115                                  && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
7116                         break;
7117
7118                     if (idx == p2[1])
7119                       {
7120                         p[-3] = (unsigned char) pop_failure_jump;
7121                         DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
7122                       }
7123                   }
7124                 else if ((re_opcode_t) p1[3] == charset)
7125                   {
7126                     int idx;
7127                     /* We win if the charset inside the loop
7128                        has no overlap with the one after the loop.  */
7129                     for (idx = 0;
7130                          idx < (int) p2[1] && idx < (int) p1[4];
7131                          idx++)
7132                       if ((p2[2 + idx] & p1[5 + idx]) != 0)
7133                         break;
7134
7135                     if (idx == p2[1] || idx == p1[4])
7136                       {
7137                         p[-3] = (unsigned char) pop_failure_jump;
7138                         DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
7139                       }
7140                   }
7141               }
7142 #endif /* not WCHAR */
7143           }
7144           p -= OFFSET_ADDRESS_SIZE;     /* Point at relative address again.  */
7145           if ((re_opcode_t) p[-1] != pop_failure_jump)
7146             {
7147               p[-1] = (UCHAR_T) jump;
7148               DEBUG_PRINT1 ("  Match => jump.\n");
7149               goto unconditional_jump;
7150             }
7151         /* Note fall through.  */
7152
7153
7154         /* The end of a simple repeat has a pop_failure_jump back to
7155            its matching on_failure_jump, where the latter will push a
7156            failure point.  The pop_failure_jump takes off failure
7157            points put on by this pop_failure_jump's matching
7158            on_failure_jump; we got through the pattern to here from the
7159            matching on_failure_jump, so didn't fail.  */
7160         case pop_failure_jump:
7161           {
7162             /* We need to pass separate storage for the lowest and
7163                highest registers, even though we don't care about the
7164                actual values.  Otherwise, we will restore only one
7165                register from the stack, since lowest will == highest in
7166                `pop_failure_point'.  */
7167             active_reg_t dummy_low_reg, dummy_high_reg;
7168             UCHAR_T *pdummy = NULL;
7169             const CHAR_T *sdummy = NULL;
7170
7171             DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
7172             POP_FAILURE_POINT (sdummy, pdummy,
7173                                dummy_low_reg, dummy_high_reg,
7174                                reg_dummy, reg_dummy, reg_info_dummy);
7175           }
7176           /* Note fall through.  */
7177
7178         unconditional_jump:
7179 #ifdef _LIBC
7180           DEBUG_PRINT2 ("\n%p: ", p);
7181 #else
7182           DEBUG_PRINT2 ("\n0x%x: ", p);
7183 #endif
7184           /* Note fall through.  */
7185
7186         /* Unconditionally jump (without popping any failure points).  */
7187         case jump:
7188           EXTRACT_NUMBER_AND_INCR (mcnt, p);    /* Get the amount to jump.  */
7189           DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
7190           p += mcnt;                            /* Do the jump.  */
7191 #ifdef _LIBC
7192           DEBUG_PRINT2 ("(to %p).\n", p);
7193 #else
7194           DEBUG_PRINT2 ("(to 0x%x).\n", p);
7195 #endif
7196           break;
7197
7198
7199         /* We need this opcode so we can detect where alternatives end
7200            in `group_match_null_string_p' et al.  */
7201         case jump_past_alt:
7202           DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
7203           goto unconditional_jump;
7204
7205
7206         /* Normally, the on_failure_jump pushes a failure point, which
7207            then gets popped at pop_failure_jump.  We will end up at
7208            pop_failure_jump, also, and with a pattern of, say, `a+', we
7209            are skipping over the on_failure_jump, so we have to push
7210            something meaningless for pop_failure_jump to pop.  */
7211         case dummy_failure_jump:
7212           DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
7213           /* It doesn't matter what we push for the string here.  What
7214              the code at `fail' tests is the value for the pattern.  */
7215           PUSH_FAILURE_POINT (NULL, NULL, -2);
7216           goto unconditional_jump;
7217
7218
7219         /* At the end of an alternative, we need to push a dummy failure
7220            point in case we are followed by a `pop_failure_jump', because
7221            we don't want the failure point for the alternative to be
7222            popped.  For example, matching `(a|ab)*' against `aab'
7223            requires that we match the `ab' alternative.  */
7224         case push_dummy_failure:
7225           DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
7226           /* See comments just above at `dummy_failure_jump' about the
7227              two zeroes.  */
7228           PUSH_FAILURE_POINT (NULL, NULL, -2);
7229           break;
7230
7231         /* Have to succeed matching what follows at least n times.
7232            After that, handle like `on_failure_jump'.  */
7233         case succeed_n:
7234           EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
7235           DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
7236
7237           assert (mcnt >= 0);
7238           /* Originally, this is how many times we HAVE to succeed.  */
7239           if (mcnt > 0)
7240             {
7241                mcnt--;
7242                p += OFFSET_ADDRESS_SIZE;
7243                STORE_NUMBER_AND_INCR (p, mcnt);
7244 #ifdef _LIBC
7245                DEBUG_PRINT3 ("  Setting %p to %d.\n", p - OFFSET_ADDRESS_SIZE
7246                              , mcnt);
7247 #else
7248                DEBUG_PRINT3 ("  Setting 0x%x to %d.\n", p - OFFSET_ADDRESS_SIZE
7249                              , mcnt);
7250 #endif
7251             }
7252           else if (mcnt == 0)
7253             {
7254 #ifdef _LIBC
7255               DEBUG_PRINT2 ("  Setting two bytes from %p to no_op.\n",
7256                             p + OFFSET_ADDRESS_SIZE);
7257 #else
7258               DEBUG_PRINT2 ("  Setting two bytes from 0x%x to no_op.\n",
7259                             p + OFFSET_ADDRESS_SIZE);
7260 #endif /* _LIBC */
7261
7262 #ifdef WCHAR
7263               p[1] = (UCHAR_T) no_op;
7264 #else
7265               p[2] = (UCHAR_T) no_op;
7266               p[3] = (UCHAR_T) no_op;
7267 #endif /* WCHAR */
7268               goto on_failure;
7269             }
7270           break;
7271
7272         case jump_n:
7273           EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
7274           DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
7275
7276           /* Originally, this is how many times we CAN jump.  */
7277           if (mcnt)
7278             {
7279                mcnt--;
7280                STORE_NUMBER (p + OFFSET_ADDRESS_SIZE, mcnt);
7281
7282 #ifdef _LIBC
7283                DEBUG_PRINT3 ("  Setting %p to %d.\n", p + OFFSET_ADDRESS_SIZE,
7284                              mcnt);
7285 #else
7286                DEBUG_PRINT3 ("  Setting 0x%x to %d.\n", p + OFFSET_ADDRESS_SIZE,
7287                              mcnt);
7288 #endif /* _LIBC */
7289                goto unconditional_jump;
7290             }
7291           /* If don't have to jump any more, skip over the rest of command.  */
7292           else
7293             p += 2 * OFFSET_ADDRESS_SIZE;
7294           break;
7295
7296         case set_number_at:
7297           {
7298             DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
7299
7300             EXTRACT_NUMBER_AND_INCR (mcnt, p);
7301             p1 = p + mcnt;
7302             EXTRACT_NUMBER_AND_INCR (mcnt, p);
7303 #ifdef _LIBC
7304             DEBUG_PRINT3 ("  Setting %p to %d.\n", p1, mcnt);
7305 #else
7306             DEBUG_PRINT3 ("  Setting 0x%x to %d.\n", p1, mcnt);
7307 #endif
7308             STORE_NUMBER (p1, mcnt);
7309             break;
7310           }
7311
7312 #if 0
7313         /* The DEC Alpha C compiler 3.x generates incorrect code for the
7314            test  WORDCHAR_P (d - 1) != WORDCHAR_P (d)  in the expansion of
7315            AT_WORD_BOUNDARY, so this code is disabled.  Expanding the
7316            macro and introducing temporary variables works around the bug.  */
7317
7318         case wordbound:
7319           DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7320           if (AT_WORD_BOUNDARY (d))
7321             break;
7322           goto fail;
7323
7324         case notwordbound:
7325           DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7326           if (AT_WORD_BOUNDARY (d))
7327             goto fail;
7328           break;
7329 #else
7330         case wordbound:
7331         {
7332           boolean prevchar, thischar;
7333
7334           DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7335           if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7336             break;
7337
7338           prevchar = WORDCHAR_P (d - 1);
7339           thischar = WORDCHAR_P (d);
7340           if (prevchar != thischar)
7341             break;
7342           goto fail;
7343         }
7344
7345       case notwordbound:
7346         {
7347           boolean prevchar, thischar;
7348
7349           DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7350           if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7351             goto fail;
7352
7353           prevchar = WORDCHAR_P (d - 1);
7354           thischar = WORDCHAR_P (d);
7355           if (prevchar != thischar)
7356             goto fail;
7357           break;
7358         }
7359 #endif
7360
7361         case wordbeg:
7362           DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
7363           if (!AT_STRINGS_END (d) && WORDCHAR_P (d)
7364               && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
7365             break;
7366           goto fail;
7367
7368         case wordend:
7369           DEBUG_PRINT1 ("EXECUTING wordend.\n");
7370           if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
7371               && (AT_STRINGS_END (d) || !WORDCHAR_P (d)))
7372             break;
7373           goto fail;
7374
7375 #ifdef emacs
7376         case before_dot:
7377           DEBUG_PRINT1 ("EXECUTING before_dot.\n");
7378           if (PTR_CHAR_POS ((unsigned char *) d) >= point)
7379             goto fail;
7380           break;
7381
7382         case at_dot:
7383           DEBUG_PRINT1 ("EXECUTING at_dot.\n");
7384           if (PTR_CHAR_POS ((unsigned char *) d) != point)
7385             goto fail;
7386           break;
7387
7388         case after_dot:
7389           DEBUG_PRINT1 ("EXECUTING after_dot.\n");
7390           if (PTR_CHAR_POS ((unsigned char *) d) <= point)
7391             goto fail;
7392           break;
7393
7394         case syntaxspec:
7395           DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
7396           mcnt = *p++;
7397           goto matchsyntax;
7398
7399         case wordchar:
7400           DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
7401           mcnt = (int) Sword;
7402         matchsyntax:
7403           PREFETCH ();
7404           /* Can't use *d++ here; SYNTAX may be an unsafe macro.  */
7405           d++;
7406           if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
7407             goto fail;
7408           SET_REGS_MATCHED ();
7409           break;
7410
7411         case notsyntaxspec:
7412           DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
7413           mcnt = *p++;
7414           goto matchnotsyntax;
7415
7416         case notwordchar:
7417           DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
7418           mcnt = (int) Sword;
7419         matchnotsyntax:
7420           PREFETCH ();
7421           /* Can't use *d++ here; SYNTAX may be an unsafe macro.  */
7422           d++;
7423           if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
7424             goto fail;
7425           SET_REGS_MATCHED ();
7426           break;
7427
7428 #else /* not emacs */
7429         case wordchar:
7430           DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
7431           PREFETCH ();
7432           if (!WORDCHAR_P (d))
7433             goto fail;
7434           SET_REGS_MATCHED ();
7435           d++;
7436           break;
7437
7438         case notwordchar:
7439           DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
7440           PREFETCH ();
7441           if (WORDCHAR_P (d))
7442             goto fail;
7443           SET_REGS_MATCHED ();
7444           d++;
7445           break;
7446 #endif /* not emacs */
7447
7448         default:
7449           abort ();
7450         }
7451       continue;  /* Successfully executed one pattern command; keep going.  */
7452
7453
7454     /* We goto here if a matching operation fails. */
7455     fail:
7456       if (!FAIL_STACK_EMPTY ())
7457         { /* A restart point is known.  Restore to that state.  */
7458           DEBUG_PRINT1 ("\nFAIL:\n");
7459           POP_FAILURE_POINT (d, p,
7460                              lowest_active_reg, highest_active_reg,
7461                              regstart, regend, reg_info);
7462
7463           /* If this failure point is a dummy, try the next one.  */
7464           if (!p)
7465             goto fail;
7466
7467           /* If we failed to the end of the pattern, don't examine *p.  */
7468           assert (p <= pend);
7469           if (p < pend)
7470             {
7471               boolean is_a_jump_n = false;
7472
7473               /* If failed to a backwards jump that's part of a repetition
7474                  loop, need to pop this failure point and use the next one.  */
7475               switch ((re_opcode_t) *p)
7476                 {
7477                 case jump_n:
7478                   is_a_jump_n = true;
7479                 case maybe_pop_jump:
7480                 case pop_failure_jump:
7481                 case jump:
7482                   p1 = p + 1;
7483                   EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7484                   p1 += mcnt;
7485
7486                   if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
7487                       || (!is_a_jump_n
7488                           && (re_opcode_t) *p1 == on_failure_jump))
7489                     goto fail;
7490                   break;
7491                 default:
7492                   /* do nothing */ ;
7493                 }
7494             }
7495
7496           if (d >= string1 && d <= end1)
7497             dend = end_match_1;
7498         }
7499       else
7500         break;   /* Matching at this starting point really fails.  */
7501     } /* for (;;) */
7502
7503   if (best_regs_set)
7504     goto restore_best_regs;
7505
7506   FREE_VARIABLES ();
7507
7508   return -1;                            /* Failure to match.  */
7509 } /* re_match_2 */
7510 \f
7511 /* Subroutine definitions for re_match_2.  */
7512
7513
7514 /* We are passed P pointing to a register number after a start_memory.
7515
7516    Return true if the pattern up to the corresponding stop_memory can
7517    match the empty string, and false otherwise.
7518
7519    If we find the matching stop_memory, sets P to point to one past its number.
7520    Otherwise, sets P to an undefined byte less than or equal to END.
7521
7522    We don't handle duplicates properly (yet).  */
7523
7524 static boolean
7525 PREFIX(group_match_null_string_p) (p, end, reg_info)
7526     UCHAR_T **p, *end;
7527     PREFIX(register_info_type) *reg_info;
7528 {
7529   int mcnt;
7530   /* Point to after the args to the start_memory.  */
7531   UCHAR_T *p1 = *p + 2;
7532
7533   while (p1 < end)
7534     {
7535       /* Skip over opcodes that can match nothing, and return true or
7536          false, as appropriate, when we get to one that can't, or to the
7537          matching stop_memory.  */
7538
7539       switch ((re_opcode_t) *p1)
7540         {
7541         /* Could be either a loop or a series of alternatives.  */
7542         case on_failure_jump:
7543           p1++;
7544           EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7545
7546           /* If the next operation is not a jump backwards in the
7547              pattern.  */
7548
7549           if (mcnt >= 0)
7550             {
7551               /* Go through the on_failure_jumps of the alternatives,
7552                  seeing if any of the alternatives cannot match nothing.
7553                  The last alternative starts with only a jump,
7554                  whereas the rest start with on_failure_jump and end
7555                  with a jump, e.g., here is the pattern for `a|b|c':
7556
7557                  /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
7558                  /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
7559                  /exactn/1/c
7560
7561                  So, we have to first go through the first (n-1)
7562                  alternatives and then deal with the last one separately.  */
7563
7564
7565               /* Deal with the first (n-1) alternatives, which start
7566                  with an on_failure_jump (see above) that jumps to right
7567                  past a jump_past_alt.  */
7568
7569               while ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] ==
7570                      jump_past_alt)
7571                 {
7572                   /* `mcnt' holds how many bytes long the alternative
7573                      is, including the ending `jump_past_alt' and
7574                      its number.  */
7575
7576                   if (!PREFIX(alt_match_null_string_p) (p1, p1 + mcnt -
7577                                                 (1 + OFFSET_ADDRESS_SIZE),
7578                                                 reg_info))
7579                     return false;
7580
7581                   /* Move to right after this alternative, including the
7582                      jump_past_alt.  */
7583                   p1 += mcnt;
7584
7585                   /* Break if it's the beginning of an n-th alternative
7586                      that doesn't begin with an on_failure_jump.  */
7587                   if ((re_opcode_t) *p1 != on_failure_jump)
7588                     break;
7589
7590                   /* Still have to check that it's not an n-th
7591                      alternative that starts with an on_failure_jump.  */
7592                   p1++;
7593                   EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7594                   if ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] !=
7595                       jump_past_alt)
7596                     {
7597                       /* Get to the beginning of the n-th alternative.  */
7598                       p1 -= 1 + OFFSET_ADDRESS_SIZE;
7599                       break;
7600                     }
7601                 }
7602
7603               /* Deal with the last alternative: go back and get number
7604                  of the `jump_past_alt' just before it.  `mcnt' contains
7605                  the length of the alternative.  */
7606               EXTRACT_NUMBER (mcnt, p1 - OFFSET_ADDRESS_SIZE);
7607
7608               if (!PREFIX(alt_match_null_string_p) (p1, p1 + mcnt, reg_info))
7609                 return false;
7610
7611               p1 += mcnt;       /* Get past the n-th alternative.  */
7612             } /* if mcnt > 0 */
7613           break;
7614
7615
7616         case stop_memory:
7617           assert (p1[1] == **p);
7618           *p = p1 + 2;
7619           return true;
7620
7621
7622         default:
7623           if (!PREFIX(common_op_match_null_string_p) (&p1, end, reg_info))
7624             return false;
7625         }
7626     } /* while p1 < end */
7627
7628   return false;
7629 } /* group_match_null_string_p */
7630
7631
7632 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
7633    It expects P to be the first byte of a single alternative and END one
7634    byte past the last. The alternative can contain groups.  */
7635
7636 static boolean
7637 PREFIX(alt_match_null_string_p) (p, end, reg_info)
7638     UCHAR_T *p, *end;
7639     PREFIX(register_info_type) *reg_info;
7640 {
7641   int mcnt;
7642   UCHAR_T *p1 = p;
7643
7644   while (p1 < end)
7645     {
7646       /* Skip over opcodes that can match nothing, and break when we get
7647          to one that can't.  */
7648
7649       switch ((re_opcode_t) *p1)
7650         {
7651         /* It's a loop.  */
7652         case on_failure_jump:
7653           p1++;
7654           EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7655           p1 += mcnt;
7656           break;
7657
7658         default:
7659           if (!PREFIX(common_op_match_null_string_p) (&p1, end, reg_info))
7660             return false;
7661         }
7662     }  /* while p1 < end */
7663
7664   return true;
7665 } /* alt_match_null_string_p */
7666
7667
7668 /* Deals with the ops common to group_match_null_string_p and
7669    alt_match_null_string_p.
7670
7671    Sets P to one after the op and its arguments, if any.  */
7672
7673 static boolean
7674 PREFIX(common_op_match_null_string_p) (p, end, reg_info)
7675     UCHAR_T **p, *end;
7676     PREFIX(register_info_type) *reg_info;
7677 {
7678   int mcnt;
7679   boolean ret;
7680   int reg_no;
7681   UCHAR_T *p1 = *p;
7682
7683   switch ((re_opcode_t) *p1++)
7684     {
7685     case no_op:
7686     case begline:
7687     case endline:
7688     case begbuf:
7689     case endbuf:
7690     case wordbeg:
7691     case wordend:
7692     case wordbound:
7693     case notwordbound:
7694 #ifdef emacs
7695     case before_dot:
7696     case at_dot:
7697     case after_dot:
7698 #endif
7699       break;
7700
7701     case start_memory:
7702       reg_no = *p1;
7703       assert (reg_no > 0 && reg_no <= MAX_REGNUM);
7704       ret = PREFIX(group_match_null_string_p) (&p1, end, reg_info);
7705
7706       /* Have to set this here in case we're checking a group which
7707          contains a group and a back reference to it.  */
7708
7709       if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
7710         REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
7711
7712       if (!ret)
7713         return false;
7714       break;
7715
7716     /* If this is an optimized succeed_n for zero times, make the jump.  */
7717     case jump:
7718       EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7719       if (mcnt >= 0)
7720         p1 += mcnt;
7721       else
7722         return false;
7723       break;
7724
7725     case succeed_n:
7726       /* Get to the number of times to succeed.  */
7727       p1 += OFFSET_ADDRESS_SIZE;
7728       EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7729
7730       if (mcnt == 0)
7731         {
7732           p1 -= 2 * OFFSET_ADDRESS_SIZE;
7733           EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7734           p1 += mcnt;
7735         }
7736       else
7737         return false;
7738       break;
7739
7740     case duplicate:
7741       if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
7742         return false;
7743       break;
7744
7745     case set_number_at:
7746       p1 += 2 * OFFSET_ADDRESS_SIZE;
7747
7748     default:
7749       /* All other opcodes mean we cannot match the empty string.  */
7750       return false;
7751   }
7752
7753   *p = p1;
7754   return true;
7755 } /* common_op_match_null_string_p */
7756
7757
7758 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
7759    bytes; nonzero otherwise.  */
7760
7761 static int
7762 PREFIX(bcmp_translate) (s1, s2, len, translate)
7763      const CHAR_T *s1, *s2;
7764      register int len;
7765      RE_TRANSLATE_TYPE translate;
7766 {
7767   register const UCHAR_T *p1 = (const UCHAR_T *) s1;
7768   register const UCHAR_T *p2 = (const UCHAR_T *) s2;
7769   while (len)
7770     {
7771 #ifdef WCHAR
7772       if (((*p1<=0xff)?translate[*p1++]:*p1++)
7773           != ((*p2<=0xff)?translate[*p2++]:*p2++))
7774         return 1;
7775 #else /* BYTE */
7776       if (translate[*p1++] != translate[*p2++]) return 1;
7777 #endif /* WCHAR */
7778       len--;
7779     }
7780   return 0;
7781 }
7782 \f
7783
7784 #else /* not INSIDE_RECURSION */
7785
7786 /* Entry points for GNU code.  */
7787
7788 /* re_compile_pattern is the GNU regular expression compiler: it
7789    compiles PATTERN (of length SIZE) and puts the result in BUFP.
7790    Returns 0 if the pattern was valid, otherwise an error string.
7791
7792    Assumes the `allocated' (and perhaps `buffer') and `translate' fields
7793    are set in BUFP on entry.
7794
7795    We call regex_compile to do the actual compilation.  */
7796
7797 const char *
7798 re_compile_pattern (pattern, length, bufp)
7799      const char *pattern;
7800      size_t length;
7801      struct re_pattern_buffer *bufp;
7802 {
7803   reg_errcode_t ret;
7804
7805   /* GNU code is written to assume at least RE_NREGS registers will be set
7806      (and at least one extra will be -1).  */
7807   bufp->regs_allocated = REGS_UNALLOCATED;
7808
7809   /* And GNU code determines whether or not to get register information
7810      by passing null for the REGS argument to re_match, etc., not by
7811      setting no_sub.  */
7812   bufp->no_sub = 0;
7813
7814   /* Match anchors at newline.  */
7815   bufp->newline_anchor = 1;
7816
7817 # ifdef MBS_SUPPORT
7818   if (MB_CUR_MAX != 1)
7819     ret = wcs_regex_compile (pattern, length, re_syntax_options, bufp);
7820   else
7821 # endif
7822     ret = byte_regex_compile (pattern, length, re_syntax_options, bufp);
7823
7824   if (!ret)
7825     return NULL;
7826   return gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7827 }
7828 #ifdef _LIBC
7829 weak_alias (__re_compile_pattern, re_compile_pattern)
7830 #endif
7831 \f
7832 /* Entry points compatible with 4.2 BSD regex library.  We don't define
7833    them unless specifically requested.  */
7834
7835 #if defined _REGEX_RE_COMP || defined _LIBC
7836
7837 /* BSD has one and only one pattern buffer.  */
7838 static struct re_pattern_buffer re_comp_buf;
7839
7840 char *
7841 #ifdef _LIBC
7842 /* Make these definitions weak in libc, so POSIX programs can redefine
7843    these names if they don't use our functions, and still use
7844    regcomp/regexec below without link errors.  */
7845 weak_function
7846 #endif
7847 re_comp (s)
7848     const char *s;
7849 {
7850   reg_errcode_t ret;
7851
7852   if (!s)
7853     {
7854       if (!re_comp_buf.buffer)
7855         return gettext ("No previous regular expression");
7856       return 0;
7857     }
7858
7859   if (!re_comp_buf.buffer)
7860     {
7861       re_comp_buf.buffer = (unsigned char *) malloc (200);
7862       if (re_comp_buf.buffer == NULL)
7863         return (char *) gettext (re_error_msgid
7864                                  + re_error_msgid_idx[(int) REG_ESPACE]);
7865       re_comp_buf.allocated = 200;
7866
7867       re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
7868       if (re_comp_buf.fastmap == NULL)
7869         return (char *) gettext (re_error_msgid
7870                                  + re_error_msgid_idx[(int) REG_ESPACE]);
7871     }
7872
7873   /* Since `re_exec' always passes NULL for the `regs' argument, we
7874      don't need to initialize the pattern buffer fields which affect it.  */
7875
7876   /* Match anchors at newlines.  */
7877   re_comp_buf.newline_anchor = 1;
7878
7879 # ifdef MBS_SUPPORT
7880   if (MB_CUR_MAX != 1)
7881     ret = wcs_regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7882   else
7883 # endif
7884     ret = byte_regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7885
7886   if (!ret)
7887     return NULL;
7888
7889   /* Yes, we're discarding `const' here if !HAVE_LIBINTL.  */
7890   return (char *) gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7891 }
7892
7893
7894 int
7895 #ifdef _LIBC
7896 weak_function
7897 #endif
7898 re_exec (s)
7899     const char *s;
7900 {
7901   const int len = strlen (s);
7902   return
7903     0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
7904 }
7905
7906 #endif /* _REGEX_RE_COMP */
7907 \f
7908 /* POSIX.2 functions.  Don't define these for Emacs.  */
7909
7910 #ifndef emacs
7911
7912 /* regcomp takes a regular expression as a string and compiles it.
7913
7914    PREG is a regex_t *.  We do not expect any fields to be initialized,
7915    since POSIX says we shouldn't.  Thus, we set
7916
7917      `buffer' to the compiled pattern;
7918      `used' to the length of the compiled pattern;
7919      `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
7920        REG_EXTENDED bit in CFLAGS is set; otherwise, to
7921        RE_SYNTAX_POSIX_BASIC;
7922      `newline_anchor' to REG_NEWLINE being set in CFLAGS;
7923      `fastmap' to an allocated space for the fastmap;
7924      `fastmap_accurate' to zero;
7925      `re_nsub' to the number of subexpressions in PATTERN.
7926
7927    PATTERN is the address of the pattern string.
7928
7929    CFLAGS is a series of bits which affect compilation.
7930
7931      If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
7932      use POSIX basic syntax.
7933
7934      If REG_NEWLINE is set, then . and [^...] don't match newline.
7935      Also, regexec will try a match beginning after every newline.
7936
7937      If REG_ICASE is set, then we considers upper- and lowercase
7938      versions of letters to be equivalent when matching.
7939
7940      If REG_NOSUB is set, then when PREG is passed to regexec, that
7941      routine will report only success or failure, and nothing about the
7942      registers.
7943
7944    It returns 0 if it succeeds, nonzero if it doesn't.  (See regex.h for
7945    the return codes and their meanings.)  */
7946
7947 int
7948 regcomp (preg, pattern, cflags)
7949     regex_t *preg;
7950     const char *pattern;
7951     int cflags;
7952 {
7953   reg_errcode_t ret;
7954   reg_syntax_t syntax
7955     = (cflags & REG_EXTENDED) ?
7956       RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
7957
7958   /* regex_compile will allocate the space for the compiled pattern.  */
7959   preg->buffer = 0;
7960   preg->allocated = 0;
7961   preg->used = 0;
7962
7963   /* Try to allocate space for the fastmap.  */
7964   preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
7965
7966   if (cflags & REG_ICASE)
7967     {
7968       unsigned i;
7969
7970       preg->translate
7971         = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
7972                                       * sizeof (*(RE_TRANSLATE_TYPE)0));
7973       if (preg->translate == NULL)
7974         return (int) REG_ESPACE;
7975
7976       /* Map uppercase characters to corresponding lowercase ones.  */
7977       for (i = 0; i < CHAR_SET_SIZE; i++)
7978         preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
7979     }
7980   else
7981     preg->translate = NULL;
7982
7983   /* If REG_NEWLINE is set, newlines are treated differently.  */
7984   if (cflags & REG_NEWLINE)
7985     { /* REG_NEWLINE implies neither . nor [^...] match newline.  */
7986       syntax &= ~RE_DOT_NEWLINE;
7987       syntax |= RE_HAT_LISTS_NOT_NEWLINE;
7988       /* It also changes the matching behavior.  */
7989       preg->newline_anchor = 1;
7990     }
7991   else
7992     preg->newline_anchor = 0;
7993
7994   preg->no_sub = !!(cflags & REG_NOSUB);
7995
7996   /* POSIX says a null character in the pattern terminates it, so we
7997      can use strlen here in compiling the pattern.  */
7998 # ifdef MBS_SUPPORT
7999   if (MB_CUR_MAX != 1)
8000     ret = wcs_regex_compile (pattern, strlen (pattern), syntax, preg);
8001   else
8002 # endif
8003     ret = byte_regex_compile (pattern, strlen (pattern), syntax, preg);
8004
8005   /* POSIX doesn't distinguish between an unmatched open-group and an
8006      unmatched close-group: both are REG_EPAREN.  */
8007   if (ret == REG_ERPAREN) ret = REG_EPAREN;
8008
8009   if (ret == REG_NOERROR && preg->fastmap)
8010     {
8011       /* Compute the fastmap now, since regexec cannot modify the pattern
8012          buffer.  */
8013       if (re_compile_fastmap (preg) == -2)
8014         {
8015           /* Some error occurred while computing the fastmap, just forget
8016              about it.  */
8017           free (preg->fastmap);
8018           preg->fastmap = NULL;
8019         }
8020     }
8021
8022   return (int) ret;
8023 }
8024 #ifdef _LIBC
8025 weak_alias (__regcomp, regcomp)
8026 #endif
8027
8028
8029 /* regexec searches for a given pattern, specified by PREG, in the
8030    string STRING.
8031
8032    If NMATCH is zero or REG_NOSUB was set in the cflags argument to
8033    `regcomp', we ignore PMATCH.  Otherwise, we assume PMATCH has at
8034    least NMATCH elements, and we set them to the offsets of the
8035    corresponding matched substrings.
8036
8037    EFLAGS specifies `execution flags' which affect matching: if
8038    REG_NOTBOL is set, then ^ does not match at the beginning of the
8039    string; if REG_NOTEOL is set, then $ does not match at the end.
8040
8041    We return 0 if we find a match and REG_NOMATCH if not.  */
8042
8043 int
8044 regexec (preg, string, nmatch, pmatch, eflags)
8045     const regex_t *preg;
8046     const char *string;
8047     size_t nmatch;
8048     regmatch_t pmatch[];
8049     int eflags;
8050 {
8051   int ret;
8052   struct re_registers regs;
8053   regex_t private_preg;
8054   int len = strlen (string);
8055   boolean want_reg_info = !preg->no_sub && nmatch > 0;
8056
8057   private_preg = *preg;
8058
8059   private_preg.not_bol = !!(eflags & REG_NOTBOL);
8060   private_preg.not_eol = !!(eflags & REG_NOTEOL);
8061
8062   /* The user has told us exactly how many registers to return
8063      information about, via `nmatch'.  We have to pass that on to the
8064      matching routines.  */
8065   private_preg.regs_allocated = REGS_FIXED;
8066
8067   if (want_reg_info)
8068     {
8069       regs.num_regs = nmatch;
8070       regs.start = TALLOC (nmatch * 2, regoff_t);
8071       if (regs.start == NULL)
8072         return (int) REG_NOMATCH;
8073       regs.end = regs.start + nmatch;
8074     }
8075
8076   /* Perform the searching operation.  */
8077   ret = re_search (&private_preg, string, len,
8078                    /* start: */ 0, /* range: */ len,
8079                    want_reg_info ? &regs : (struct re_registers *) 0);
8080
8081   /* Copy the register information to the POSIX structure.  */
8082   if (want_reg_info)
8083     {
8084       if (ret >= 0)
8085         {
8086           unsigned r;
8087
8088           for (r = 0; r < nmatch; r++)
8089             {
8090               pmatch[r].rm_so = regs.start[r];
8091               pmatch[r].rm_eo = regs.end[r];
8092             }
8093         }
8094
8095       /* If we needed the temporary register info, free the space now.  */
8096       free (regs.start);
8097     }
8098
8099   /* We want zero return to mean success, unlike `re_search'.  */
8100   return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
8101 }
8102 #ifdef _LIBC
8103 weak_alias (__regexec, regexec)
8104 #endif
8105
8106
8107 /* Returns a message corresponding to an error code, ERRCODE, returned
8108    from either regcomp or regexec.   We don't use PREG here.  */
8109
8110 size_t
8111 regerror (errcode, preg, errbuf, errbuf_size)
8112     int errcode;
8113     const regex_t *preg;
8114     char *errbuf;
8115     size_t errbuf_size;
8116 {
8117   const char *msg;
8118   size_t msg_size;
8119
8120   if (errcode < 0
8121       || errcode >= (int) (sizeof (re_error_msgid_idx)
8122                            / sizeof (re_error_msgid_idx[0])))
8123     /* Only error codes returned by the rest of the code should be passed
8124        to this routine.  If we are given anything else, or if other regex
8125        code generates an invalid error code, then the program has a bug.
8126        Dump core so we can fix it.  */
8127     abort ();
8128
8129   msg = gettext (re_error_msgid + re_error_msgid_idx[errcode]);
8130
8131   msg_size = strlen (msg) + 1; /* Includes the null.  */
8132
8133   if (errbuf_size != 0)
8134     {
8135       if (msg_size > errbuf_size)
8136         {
8137 #if defined HAVE_MEMPCPY || defined _LIBC
8138           *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
8139 #else
8140           memcpy (errbuf, msg, errbuf_size - 1);
8141           errbuf[errbuf_size - 1] = 0;
8142 #endif
8143         }
8144       else
8145         memcpy (errbuf, msg, msg_size);
8146     }
8147
8148   return msg_size;
8149 }
8150 #ifdef _LIBC
8151 weak_alias (__regerror, regerror)
8152 #endif
8153
8154
8155 /* Free dynamically allocated space used by PREG.  */
8156
8157 void
8158 regfree (preg)
8159     regex_t *preg;
8160 {
8161   if (preg->buffer != NULL)
8162     free (preg->buffer);
8163   preg->buffer = NULL;
8164
8165   preg->allocated = 0;
8166   preg->used = 0;
8167
8168   if (preg->fastmap != NULL)
8169     free (preg->fastmap);
8170   preg->fastmap = NULL;
8171   preg->fastmap_accurate = 0;
8172
8173   if (preg->translate != NULL)
8174     free (preg->translate);
8175   preg->translate = NULL;
8176 }
8177 #ifdef _LIBC
8178 weak_alias (__regfree, regfree)
8179 #endif
8180
8181 #endif /* not emacs  */
8182
8183 #endif /* not INSIDE_RECURSION */
8184
8185 \f
8186 #undef STORE_NUMBER
8187 #undef STORE_NUMBER_AND_INCR
8188 #undef EXTRACT_NUMBER
8189 #undef EXTRACT_NUMBER_AND_INCR
8190
8191 #undef DEBUG_PRINT_COMPILED_PATTERN
8192 #undef DEBUG_PRINT_DOUBLE_STRING
8193
8194 #undef INIT_FAIL_STACK
8195 #undef RESET_FAIL_STACK
8196 #undef DOUBLE_FAIL_STACK
8197 #undef PUSH_PATTERN_OP
8198 #undef PUSH_FAILURE_POINTER
8199 #undef PUSH_FAILURE_INT
8200 #undef PUSH_FAILURE_ELT
8201 #undef POP_FAILURE_POINTER
8202 #undef POP_FAILURE_INT
8203 #undef POP_FAILURE_ELT
8204 #undef DEBUG_PUSH
8205 #undef DEBUG_POP
8206 #undef PUSH_FAILURE_POINT
8207 #undef POP_FAILURE_POINT
8208
8209 #undef REG_UNSET_VALUE
8210 #undef REG_UNSET
8211
8212 #undef PATFETCH
8213 #undef PATFETCH_RAW
8214 #undef PATUNFETCH
8215 #undef TRANSLATE
8216
8217 #undef INIT_BUF_SIZE
8218 #undef GET_BUFFER_SPACE
8219 #undef BUF_PUSH
8220 #undef BUF_PUSH_2
8221 #undef BUF_PUSH_3
8222 #undef STORE_JUMP
8223 #undef STORE_JUMP2
8224 #undef INSERT_JUMP
8225 #undef INSERT_JUMP2
8226 #undef EXTEND_BUFFER
8227 #undef GET_UNSIGNED_NUMBER
8228 #undef FREE_STACK_RETURN
8229
8230 # undef POINTER_TO_OFFSET
8231 # undef MATCHING_IN_FRST_STRING
8232 # undef PREFETCH
8233 # undef AT_STRINGS_BEG
8234 # undef AT_STRINGS_END
8235 # undef WORDCHAR_P
8236 # undef FREE_VAR
8237 # undef FREE_VARIABLES
8238 # undef NO_HIGHEST_ACTIVE_REG
8239 # undef NO_LOWEST_ACTIVE_REG
8240
8241 # undef CHAR_T
8242 # undef UCHAR_T
8243 # undef COMPILED_BUFFER_VAR
8244 # undef OFFSET_ADDRESS_SIZE
8245 # undef CHAR_CLASS_SIZE
8246 # undef PREFIX
8247 # undef ARG_PREFIX
8248 # undef PUT_CHAR
8249 # undef BYTE
8250 # undef WCHAR
8251
8252 # define DEFINED_ONCE