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