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