Use void* alloca, not char*. The latter lost on convexOS.
[gnulib.git] / lib / regex.c
index 8c853ba..e1d5066 100644 (file)
@@ -3,7 +3,7 @@
    (Implements POSIX draft P10003.2/D11.2, except for
    internationalization features.)
 
-   Copyright (C) 1993 Free Software Foundation, Inc.
+   Copyright (C) 1993, 1994, 1995 Free Software Foundation, Inc.
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
 #define _GNU_SOURCE
 
 #ifdef HAVE_CONFIG_H
-#if defined (emacs) || defined (CONFIG_BROKETS)
-/* We use <config.h> instead of "config.h" so that a compilation
-   using -I. -I$srcdir will use ./config.h rather than $srcdir/config.h
-   (which it would do because it found this file in $srcdir).  */
 #include <config.h>
-#else
-#include "config.h"
-#endif
 #endif
 
 /* We need this for `regex.h', and perhaps for the Emacs include files.  */
 #include <sys/types.h>
 
+/* This is for other GNU distributions with internationalized messages.  */
+#if HAVE_LIBINTL_H || defined (_LIBC)
+# include <libintl.h>
+#else
+# define gettext(msgid) (msgid)
+#endif
+
 /* The `emacs' switch turns on certain matching commands
    that make sense only in Emacs. */
 #ifdef emacs
 #include "buffer.h"
 #include "syntax.h"
 
-/* Emacs uses `NULL' as a predicate.  */
-#undef NULL
-
 #else  /* not emacs */
 
-#ifdef STDC_HEADERS
+/* If we are not linking with Emacs proper,
+   we can't use the relocating allocator
+   even if config.h says that we can.  */
+#undef REL_ALLOC
+
+#if defined (STDC_HEADERS) || defined (_LIBC)
 #include <stdlib.h>
 #else
 char *malloc ();
 char *realloc ();
 #endif
 
-
 /* We used to test for `BSTRING' here, but only GCC and Emacs define
    `BSTRING', as far as I know, and neither of them use this code.  */
 #ifndef INHIBIT_STRING_HEADER
-#if HAVE_STRING_H || STDC_HEADERS
+#if HAVE_STRING_H || STDC_HEADERS || defined (_LIBC)
 #include <string.h>
 #ifndef bcmp
 #define bcmp(s1, s2, n)        memcmp ((s1), (s2), (n))
@@ -88,6 +89,12 @@ char *realloc ();
 #define Sword 1
 #endif
 
+#ifdef SWITCH_ENUM_BUG
+#define SWITCH_ENUM_CAST(x) ((int)(x))
+#else
+#define SWITCH_ENUM_CAST(x) (x)
+#endif
+
 #ifdef SYNTAX_TABLE
 
 extern char *re_syntax_table;
@@ -176,7 +183,7 @@ init_syntax_once ()
 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
 
 #ifndef NULL
-#define NULL 0
+#define NULL (void *)0
 #endif
 
 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
@@ -205,6 +212,7 @@ init_syntax_once ()
 
 #define REGEX_ALLOCATE malloc
 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
+#define REGEX_FREE free
 
 #else /* not REGEX_MALLOC  */
 
@@ -219,7 +227,7 @@ init_syntax_once ()
 #include <alloca.h>
 #else /* not __GNUC__ or HAVE_ALLOCA_H */
 #ifndef _AIX /* Already did AIX, up at the top.  */
-char *alloca ();
+void *alloca ();
 #endif /* not _AIX */
 #endif /* not HAVE_ALLOCA_H */ 
 #endif /* not __GNUC__ */
@@ -234,8 +242,41 @@ char *alloca ();
    bcopy (source, destination, osize),                                 \
    destination)
 
+/* No need to do anything to free, after alloca.  */
+#define REGEX_FREE(arg) ((void)0) /* Do nothing!  But inhibit gcc warning.  */
+
 #endif /* not REGEX_MALLOC */
 
+/* Define how to allocate the failure stack.  */
+
+#ifdef REL_ALLOC
+#define REGEX_ALLOCATE_STACK(size)                             \
+  r_alloc (&failure_stack_ptr, (size))
+#define REGEX_REALLOCATE_STACK(source, osize, nsize)           \
+  r_re_alloc (&failure_stack_ptr, (nsize))
+#define REGEX_FREE_STACK(ptr)                                  \
+  r_alloc_free (&failure_stack_ptr)
+
+#else /* not REL_ALLOC */
+
+#ifdef REGEX_MALLOC
+
+#define REGEX_ALLOCATE_STACK malloc
+#define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
+#define REGEX_FREE_STACK free
+
+#else /* not REGEX_MALLOC */
+
+#define REGEX_ALLOCATE_STACK alloca
+
+#define REGEX_REALLOCATE_STACK(source, osize, nsize)                   \
+   REGEX_REALLOCATE (source, osize, nsize)
+/* No need to explicitly free anything.  */
+#define REGEX_FREE_STACK(arg)
+
+#endif /* not REGEX_MALLOC */
+#endif /* not REL_ALLOC */
+
 
 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
    `string1' or just past its end.  This works if PTR is NULL, which is
@@ -268,18 +309,17 @@ static int re_match_2_internal ();
 /* These are the command codes that appear in compiled regular
    expressions.  Some opcodes are followed by argument bytes.  A
    command code can specify any interpretation whatsoever for its
-   arguments.  Zero bytes may appear in the compiled regular expression.
-
-   The value of `exactn' is needed in search.c (search_buffer) in Emacs.
-   So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
-   `exactn' we use here must also be 1.  */
+   arguments.  Zero bytes may appear in the compiled regular expression.  */
 
 typedef enum
 {
   no_op = 0,
 
+  /* Succeed right away--no more backtracking.  */
+  succeed,
+
         /* Followed by one byte giving n, then by n literal bytes.  */
-  exactn = 1,
+  exactn,
 
         /* Matches any (more or less) character.  */
   anychar,
@@ -506,8 +546,6 @@ static int debug = 0;
   if (debug) print_double_string (w, s1, sz1, s2, sz2)
 
 
-extern void printchar ();
-
 /* Print the fastmap in human-readable form.  */
 
 void
@@ -522,7 +560,7 @@ print_fastmap (fastmap)
       if (fastmap[i++])
        {
          was_a_range = 0;
-          printchar (i - 1);
+          putchar (i - 1);
           while (i < (1 << BYTEWIDTH)  &&  fastmap[i])
             {
               was_a_range = 1;
@@ -531,7 +569,7 @@ print_fastmap (fastmap)
          if (was_a_range)
             {
               printf ("-");
-              printchar (i - 1);
+              putchar (i - 1);
             }
         }
     }
@@ -574,7 +612,7 @@ print_partial_compiled_pattern (start, end)
           do
            {
               putchar ('/');
-             printchar (*p++);
+             putchar (*p++);
             }
           while (--mcnt);
           break;
@@ -621,18 +659,18 @@ print_partial_compiled_pattern (start, end)
                  /* Have we broken a range?  */
                  else if (last + 1 != c && in_range)
               {
-                     printchar (last);
+                     putchar (last);
                      in_range = 0;
                    }
                 
                  if (! in_range)
-                   printchar (c);
+                   putchar (c);
 
                  last = c;
               }
 
            if (in_range)
-             printchar (last);
+             putchar (last);
 
            putchar (']');
 
@@ -780,7 +818,7 @@ print_compiled_pattern (bufp)
   unsigned char *buffer = bufp->buffer;
 
   print_partial_compiled_pattern (buffer, buffer + bufp->used);
-  printf ("%ld bytes used/%ld bytes allocated.\n", bufp->used, bufp->allocated);
+  printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
 
   if (bufp->fastmap_accurate && bufp->fastmap)
     {
@@ -817,13 +855,13 @@ print_double_string (where, string1, size1, string2, size2)
       if (FIRST_STRING_P (where))
         {
           for (this_char = where - string1; this_char < size1; this_char++)
-            printchar (string1[this_char]);
+            putchar (string1[this_char]);
 
           where = string2;    
         }
 
       for (this_char = where - string2; this_char < size2; this_char++)
-        printchar (string2[this_char]);
+        putchar (string2[this_char]);
     }
 }
 
@@ -845,7 +883,9 @@ print_double_string (where, string1, size1, string2, size2)
 /* Set by `re_set_syntax' to the current regexp syntax to recognize.  Can
    also be assigned to arbitrarily: each pattern buffer stores its own
    syntax, so it can be changed between regex compilations.  */
-reg_syntax_t re_syntax_options = RE_SYNTAX_EMACS;
+/* This has no initializer because initialized variables in Emacs
+   become read-only after dumping.  */
+reg_syntax_t re_syntax_options;
 
 
 /* Specify the precise syntax of regexps for compilation.  This provides
@@ -866,10 +906,12 @@ re_set_syntax (syntax)
 }
 \f
 /* This table gives an error message for each of the error codes listed
-   in regex.h.  Obviously the order here has to be same as there.  */
+   in regex.h.  Obviously the order here has to be same as there.
+   POSIX doesn't require that we do anything for REG_NOERROR,
+   but why not be nice?  */
 
-static const char *re_error_msg[] =
-  { NULL,                                      /* REG_NOERROR */
+static const char *re_error_msgid[] =
+  { "Success",                                 /* REG_NOERROR */
     "No match",                                        /* REG_NOMATCH */
     "Invalid regular expression",              /* REG_BADPAT */
     "Invalid collation character",             /* REG_ECOLLATE */
@@ -898,8 +940,8 @@ static const char *re_error_msg[] =
    ralloc heap) shift the data out from underneath the regexp
    routines.
 
-   Here's another reason to avoid allocation: Emacs insists on
-   processing input from X in a signal handler; processing X input may
+   Here's another reason to avoid allocation: Emacs 
+   processes input from X in a signal handler; processing X input may
    call malloc; if input arrives while a matching routine is calling
    malloc, then we're scrod.  But Emacs can't just block input while
    calling matching routines; then we don't notice interrupts when
@@ -910,15 +952,25 @@ static const char *re_error_msg[] =
 /* Normally, this is fine.  */
 #define MATCH_MAY_ALLOCATE
 
-/* But under some circumstances, it's not.  */
-#if defined (emacs) || (defined (REL_ALLOC) && defined (C_ALLOCA))
+/* When using GNU C, we are not REALLY using the C alloca, no matter
+   what config.h may say.  So don't take precautions for it.  */
+#ifdef __GNUC__
+#undef C_ALLOCA
+#endif
+
+/* The match routines may not allocate if (1) they would do it with malloc
+   and (2) it's not safe for them to use malloc.
+   Note that if REL_ALLOC is defined, matching would not use malloc for the
+   failure stack, but we would still use it for the register vectors;
+   so REL_ALLOC should not affect this.  */
+#if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
 #undef MATCH_MAY_ALLOCATE
 #endif
 
 \f
 /* Failure stack declarations and macros; both re_compile_fastmap and
    re_match_2 use a failure stack.  These have to be macros because of
-   REGEX_ALLOCATE.  */
+   REGEX_ALLOCATE_STACK.  */
    
 
 /* Number of failure points for which to initially allocate space
@@ -932,9 +984,19 @@ static const char *re_error_msg[] =
    exactly that if always used MAX_FAILURE_SPACE each time we failed.
    This is a variable only so users of regex can assign to it; we never
    change it ourselves.  */
+#if defined (MATCH_MAY_ALLOCATE)
+int re_max_failures = 200000;
+#else
 int re_max_failures = 2000;
+#endif
+
+union fail_stack_elt
+{
+  unsigned char *pointer;
+  int integer;
+};
 
-typedef unsigned char *fail_stack_elt_t;
+typedef union fail_stack_elt fail_stack_elt_t;
 
 typedef struct
 {
@@ -946,16 +1008,16 @@ typedef struct
 #define FAIL_STACK_EMPTY()     (fail_stack.avail == 0)
 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
 #define FAIL_STACK_FULL()      (fail_stack.avail == fail_stack.size)
-#define FAIL_STACK_TOP()       (fail_stack.stack[fail_stack.avail])
 
 
-/* Initialize `fail_stack'.  Do `return -2' if the alloc fails.  */
+/* Define macros to initialize and free the failure stack.
+   Do `return -2' if the alloc fails.  */
 
 #ifdef MATCH_MAY_ALLOCATE
 #define INIT_FAIL_STACK()                                              \
   do {                                                                 \
     fail_stack.stack = (fail_stack_elt_t *)                            \
-      REGEX_ALLOCATE (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
+      REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t));   \
                                                                        \
     if (fail_stack.stack == NULL)                                      \
       return -2;                                                       \
@@ -963,11 +1025,15 @@ typedef struct
     fail_stack.size = INIT_FAILURE_ALLOC;                              \
     fail_stack.avail = 0;                                              \
   } while (0)
+
+#define RESET_FAIL_STACK()  REGEX_FREE_STACK (fail_stack.stack)
 #else
 #define INIT_FAIL_STACK()                                              \
   do {                                                                 \
     fail_stack.avail = 0;                                              \
   } while (0)
+
+#define RESET_FAIL_STACK()
 #endif
 
 
@@ -976,13 +1042,13 @@ typedef struct
    Return 1 if succeeds, and 0 if either ran out of memory
    allocating space for it or it was already too large.  
    
-   REGEX_REALLOCATE requires `destination' be declared.   */
+   REGEX_REALLOCATE_STACK requires `destination' be declared.   */
 
 #define DOUBLE_FAIL_STACK(fail_stack)                                  \
   ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS             \
    ? 0                                                                 \
    : ((fail_stack).stack = (fail_stack_elt_t *)                                \
-        REGEX_REALLOCATE ((fail_stack).stack,                          \
+        REGEX_REALLOCATE_STACK ((fail_stack).stack,                    \
           (fail_stack).size * sizeof (fail_stack_elt_t),               \
           ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)),       \
                                                                        \
@@ -992,34 +1058,44 @@ typedef struct
          1)))
 
 
-/* Push PATTERN_OP on FAIL_STACK. 
-
+/* Push pointer POINTER on FAIL_STACK. 
    Return 1 if was able to do so and 0 if ran out of memory allocating
    space to do so.  */
-#define PUSH_PATTERN_OP(pattern_op, fail_stack)                                \
+#define PUSH_PATTERN_OP(POINTER, FAIL_STACK)                           \
   ((FAIL_STACK_FULL ()                                                 \
-    && !DOUBLE_FAIL_STACK (fail_stack))                                        \
-    ? 0                                                                        \
-    : ((fail_stack).stack[(fail_stack).avail++] = pattern_op,          \
-       1))
-
-/* This pushes an item onto the failure stack.  sizeof(ITEM) must be no
-   larger than sizeof (unsigned char *).  Assumes the variable `fail_stack'.
-   Probably should only be called from within `PUSH_FAILURE_POINT'.  */
-#define PUSH_FAILURE_ITEM(item)                                                \
-  do                                                                   \
-    {                                                                  \
-      fail_stack.stack[fail_stack.avail++] = (fail_stack_elt_t) item;  \
-    }                                                                  \
-  while (0)                                                            \
-
-/* The complement operation.  Assumes `fail_stack' is nonempty.  */
-#define POP_FAILURE_ITEM() fail_stack.stack[--fail_stack.avail]
+    && !DOUBLE_FAIL_STACK (FAIL_STACK))                                        \
+   ? 0                                                                 \
+   : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER,      \
+      1))
+
+/* Push a pointer value onto the failure stack.
+   Assumes the variable `fail_stack'.  Probably should only
+   be called from within `PUSH_FAILURE_POINT'.  */
+#define PUSH_FAILURE_POINTER(item)                                     \
+  fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
+
+/* This pushes an integer-valued item onto the failure stack.
+   Assumes the variable `fail_stack'.  Probably should only
+   be called from within `PUSH_FAILURE_POINT'.  */
+#define PUSH_FAILURE_INT(item)                                 \
+  fail_stack.stack[fail_stack.avail++].integer = (item)
+
+/* Push a fail_stack_elt_t value onto the failure stack.
+   Assumes the variable `fail_stack'.  Probably should only
+   be called from within `PUSH_FAILURE_POINT'.  */
+#define PUSH_FAILURE_ELT(item)                                 \
+  fail_stack.stack[fail_stack.avail++] =  (item)
+
+/* These three POP... operations complement the three PUSH... operations.
+   All assume that `fail_stack' is nonempty.  */
+#define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
+#define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
+#define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
 
 /* Used to omit pushing failure point id's when we're not debugging.  */
 #ifdef DEBUG
-#define DEBUG_PUSH PUSH_FAILURE_ITEM
-#define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_ITEM ()
+#define DEBUG_PUSH PUSH_FAILURE_INT
+#define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
 #else
 #define DEBUG_PUSH(item)
 #define DEBUG_POP(item_addr)
@@ -1054,7 +1130,7 @@ typedef struct
     /* Ensure we have enough space allocated for what we will push.  */        \
     while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS)                  \
       {                                                                        \
-        if (!DOUBLE_FAIL_STACK (fail_stack))                   \
+        if (!DOUBLE_FAIL_STACK (fail_stack))                           \
           return failure_code;                                         \
                                                                        \
         DEBUG_PRINT2 ("\n  Doubled stack; size now: %d\n",             \
@@ -1072,10 +1148,10 @@ typedef struct
         DEBUG_STATEMENT (num_regs_pushed++);                           \
                                                                        \
        DEBUG_PRINT2 ("    start: 0x%x\n", regstart[this_reg]);         \
-        PUSH_FAILURE_ITEM (regstart[this_reg]);                                \
+        PUSH_FAILURE_POINTER (regstart[this_reg]);                     \
                                                                         \
        DEBUG_PRINT2 ("    end: 0x%x\n", regend[this_reg]);             \
-        PUSH_FAILURE_ITEM (regend[this_reg]);                          \
+        PUSH_FAILURE_POINTER (regend[this_reg]);                       \
                                                                        \
        DEBUG_PRINT2 ("    info: 0x%x\n      ", reg_info[this_reg]);    \
         DEBUG_PRINT2 (" match_null=%d",                                        \
@@ -1086,24 +1162,24 @@ typedef struct
         DEBUG_PRINT2 (" ever_matched=%d",                              \
                       EVER_MATCHED_SOMETHING (reg_info[this_reg]));    \
        DEBUG_PRINT1 ("\n");                                            \
-        PUSH_FAILURE_ITEM (reg_info[this_reg].word);                   \
+        PUSH_FAILURE_ELT (reg_info[this_reg].word);                    \
       }                                                                        \
                                                                        \
     DEBUG_PRINT2 ("  Pushing  low active reg: %d\n", lowest_active_reg);\
-    PUSH_FAILURE_ITEM (lowest_active_reg);                             \
+    PUSH_FAILURE_INT (lowest_active_reg);                              \
                                                                        \
     DEBUG_PRINT2 ("  Pushing high active reg: %d\n", highest_active_reg);\
-    PUSH_FAILURE_ITEM (highest_active_reg);                            \
+    PUSH_FAILURE_INT (highest_active_reg);                             \
                                                                        \
     DEBUG_PRINT2 ("  Pushing pattern 0x%x: ", pattern_place);          \
     DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend);          \
-    PUSH_FAILURE_ITEM (pattern_place);                                 \
+    PUSH_FAILURE_POINTER (pattern_place);                              \
                                                                        \
     DEBUG_PRINT2 ("  Pushing string 0x%x: `", string_place);           \
     DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2,   \
                                 size2);                                \
     DEBUG_PRINT1 ("'\n");                                              \
-    PUSH_FAILURE_ITEM (string_place);                                  \
+    PUSH_FAILURE_POINTER (string_place);                               \
                                                                        \
     DEBUG_PRINT2 ("  Pushing failure id: %u\n", failure_id);           \
     DEBUG_PUSH (failure_id);                                           \
@@ -1165,7 +1241,7 @@ typedef struct
   /* If the saved string location is NULL, it came from an             \
      on_failure_keep_string_jump opcode, and we want to throw away the \
      saved NULL, thus retaining our current position in the string.  */        \
-  string_temp = POP_FAILURE_ITEM ();                                   \
+  string_temp = POP_FAILURE_POINTER ();                                        \
   if (string_temp != NULL)                                             \
     str = (const char *) string_temp;                                  \
                                                                        \
@@ -1173,39 +1249,39 @@ typedef struct
   DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2);     \
   DEBUG_PRINT1 ("'\n");                                                        \
                                                                        \
-  pat = (unsigned char *) POP_FAILURE_ITEM ();                         \
+  pat = (unsigned char *) POP_FAILURE_POINTER ();                      \
   DEBUG_PRINT2 ("  Popping pattern 0x%x: ", pat);                      \
   DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend);                      \
                                                                        \
   /* Restore register info.  */                                                \
-  high_reg = (unsigned long) POP_FAILURE_ITEM ();                      \
+  high_reg = (unsigned) POP_FAILURE_INT ();                            \
   DEBUG_PRINT2 ("  Popping high active reg: %d\n", high_reg);          \
                                                                        \
-  low_reg = (unsigned long) POP_FAILURE_ITEM ();                       \
+  low_reg = (unsigned) POP_FAILURE_INT ();                             \
   DEBUG_PRINT2 ("  Popping  low active reg: %d\n", low_reg);           \
                                                                        \
   for (this_reg = high_reg; this_reg >= low_reg; this_reg--)           \
     {                                                                  \
       DEBUG_PRINT2 ("    Popping reg: %d\n", this_reg);                        \
                                                                        \
-      reg_info[this_reg].word = POP_FAILURE_ITEM ();                   \
+      reg_info[this_reg].word = POP_FAILURE_ELT ();                    \
       DEBUG_PRINT2 ("      info: 0x%x\n", reg_info[this_reg]);         \
                                                                        \
-      regend[this_reg] = (const char *) POP_FAILURE_ITEM ();           \
+      regend[this_reg] = (const char *) POP_FAILURE_POINTER ();                \
       DEBUG_PRINT2 ("      end: 0x%x\n", regend[this_reg]);            \
                                                                        \
-      regstart[this_reg] = (const char *) POP_FAILURE_ITEM ();         \
+      regstart[this_reg] = (const char *) POP_FAILURE_POINTER ();      \
       DEBUG_PRINT2 ("      start: 0x%x\n", regstart[this_reg]);                \
     }                                                                  \
                                                                        \
+  set_regs_matched_done = 0;                                           \
   DEBUG_STATEMENT (nfailure_points_popped++);                          \
 } /* POP_FAILURE_POINT */
 
 
 \f
 /* Structure for per-register (a.k.a. per-group) information.
-   This must not be longer than one word, because we push this value
-   onto the failure stack.  Other register information, such as the
+   Other register information, such as the
    starting and ending positions (which are addresses), and the list of
    inner groups (which is a bits list) are maintained in separate
    variables.  
@@ -1214,6 +1290,7 @@ typedef struct
    the compiler will pack our bit fields into something that fits into
    the type of `word', i.e., is something that fits into one item on the
    failure stack.  */
+
 typedef union
 {
   fail_stack_elt_t word;
@@ -1241,37 +1318,24 @@ typedef union
 #define SET_REGS_MATCHED()                                             \
   do                                                                   \
     {                                                                  \
-      unsigned r;                                                      \
-      for (r = lowest_active_reg; r <= highest_active_reg; r++)                \
-        {                                                              \
-          MATCHED_SOMETHING (reg_info[r])                              \
-            = EVER_MATCHED_SOMETHING (reg_info[r])                     \
-            = 1;                                                       \
-        }                                                              \
+      if (!set_regs_matched_done)                                      \
+       {                                                               \
+         unsigned r;                                                   \
+         set_regs_matched_done = 1;                                    \
+         for (r = lowest_active_reg; r <= highest_active_reg; r++)     \
+           {                                                           \
+             MATCHED_SOMETHING (reg_info[r])                           \
+               = EVER_MATCHED_SOMETHING (reg_info[r])                  \
+               = 1;                                                    \
+           }                                                           \
+       }                                                               \
     }                                                                  \
   while (0)
 
-
 /* Registers are set to a sentinel when they haven't yet matched.  */
-#define REG_UNSET_VALUE ((char *) -1)
+static char reg_unset_dummy;
+#define REG_UNSET_VALUE (&reg_unset_dummy)
 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
-
-
-\f
-/* How do we implement a missing MATCH_MAY_ALLOCATE?
-   We make the fail stack a global thing, and then grow it to
-   re_max_failures when we compile.  */
-#ifndef MATCH_MAY_ALLOCATE
-static fail_stack_type fail_stack;
-
-static const char **     regstart, **     regend;
-static const char ** old_regstart, ** old_regend;
-static const char **best_regstart, **best_regend;
-static register_info_type *reg_info; 
-static const char **reg_dummy;
-static register_info_type *reg_info_dummy;
-#endif
-
 \f
 /* Subroutine declarations and macros for regex_compile.  */
 
@@ -1476,6 +1540,54 @@ typedef struct
     || STREQ (string, "punct") || STREQ (string, "graph")              \
     || STREQ (string, "cntrl") || STREQ (string, "blank"))
 \f
+#ifndef MATCH_MAY_ALLOCATE
+
+/* If we cannot allocate large objects within re_match_2_internal,
+   we make the fail stack and register vectors global.
+   The fail stack, we grow to the maximum size when a regexp
+   is compiled.
+   The register vectors, we adjust in size each time we
+   compile a regexp, according to the number of registers it needs.  */
+
+static fail_stack_type fail_stack;
+
+/* Size with which the following vectors are currently allocated.
+   That is so we can make them bigger as needed,
+   but never make them smaller.  */
+static int regs_allocated_size;
+
+static const char **     regstart, **     regend;
+static const char ** old_regstart, ** old_regend;
+static const char **best_regstart, **best_regend;
+static register_info_type *reg_info; 
+static const char **reg_dummy;
+static register_info_type *reg_info_dummy;
+
+/* Make the register vectors big enough for NUM_REGS registers,
+   but don't make them smaller.  */
+
+static
+regex_grow_registers (num_regs)
+     int num_regs;
+{
+  if (num_regs > regs_allocated_size)
+    {
+      RETALLOC_IF (regstart,    num_regs, const char *);
+      RETALLOC_IF (regend,      num_regs, const char *);
+      RETALLOC_IF (old_regstart, num_regs, const char *);
+      RETALLOC_IF (old_regend,  num_regs, const char *);
+      RETALLOC_IF (best_regstart, num_regs, const char *);
+      RETALLOC_IF (best_regend,         num_regs, const char *);
+      RETALLOC_IF (reg_info,    num_regs, register_info_type);
+      RETALLOC_IF (reg_dummy,   num_regs, const char *);
+      RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
+
+      regs_allocated_size = num_regs;
+    }
+}
+
+#endif /* not MATCH_MAY_ALLOCATE */
+\f
 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
    Returns one of error codes defined in `regex.h', or zero for success.
 
@@ -1494,6 +1606,10 @@ typedef struct
    The `fastmap' and `newline_anchor' fields are neither
    examined nor set.  */
 
+/* Return, freeing storage we allocated.  */
+#define FREE_STACK_RETURN(value)               \
+  return (free (compile_stack.stack), value)
+
 static reg_errcode_t
 regex_compile (pattern, size, syntax, bufp)
      const char *pattern;
@@ -1557,7 +1673,7 @@ regex_compile (pattern, size, syntax, bufp)
       unsigned debug_count;
       
       for (debug_count = 0; debug_count < size; debug_count++)
-        printchar (pattern[debug_count]);
+        putchar (pattern[debug_count]);
       putchar ('\n');
     }
 #endif /* DEBUG */
@@ -1600,7 +1716,7 @@ regex_compile (pattern, size, syntax, bufp)
         { /* Caller did not allocate a buffer.  Do it for them.  */
           bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
         }
-      if (!bufp->buffer) return REG_ESPACE;
+      if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
 
       bufp->allocated = INIT_BUF_SIZE;
     }
@@ -1655,7 +1771,7 @@ regex_compile (pattern, size, syntax, bufp)
           if (!laststart)
             {
               if (syntax & RE_CONTEXT_INVALID_OPS)
-                return REG_BADRPT;
+                FREE_STACK_RETURN (REG_BADRPT);
               else if (!(syntax & RE_CONTEXT_INDEP_OPS))
                 goto normal_char;
             }
@@ -1688,7 +1804,7 @@ regex_compile (pattern, size, syntax, bufp)
 
                 else if (syntax & RE_BK_PLUS_QM  &&  c == '\\')
                   {
-                    if (p == pend) return REG_EESCAPE;
+                    if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
 
                     PATFETCH (c1);
                     if (!(c1 == '+' || c1 == '?'))
@@ -1787,7 +1903,7 @@ regex_compile (pattern, size, syntax, bufp)
           {
             boolean had_char_class = false;
 
-            if (p == pend) return REG_EBRACK;
+            if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
 
             /* Ensure that we have enough space to push a charset: the
                opcode, the length count, and the bitset; 34 bytes in all.  */
@@ -1818,14 +1934,14 @@ regex_compile (pattern, size, syntax, bufp)
             /* Read in characters and ranges, setting map bits.  */
             for (;;)
               {
-                if (p == pend) return REG_EBRACK;
+                if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
 
                 PATFETCH (c);
 
                 /* \ might escape characters inside [...] and [^...].  */
                 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
                   {
-                    if (p == pend) return REG_EESCAPE;
+                    if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
 
                     PATFETCH (c1);
                     SET_LIST_BIT (c1);
@@ -1841,7 +1957,7 @@ regex_compile (pattern, size, syntax, bufp)
                 /* Look ahead to see if it's a range when the last thing
                    was a character class.  */
                 if (had_char_class && c == '-' && *p != ']')
-                  return REG_ERANGE;
+                  FREE_STACK_RETURN (REG_ERANGE);
 
                 /* Look ahead to see if it's a range when the last thing
                    was a character: if this is a hyphen not at the
@@ -1854,7 +1970,7 @@ regex_compile (pattern, size, syntax, bufp)
                   {
                     reg_errcode_t ret
                       = compile_range (&p, pend, translate, syntax, b);
-                    if (ret != REG_NOERROR) return ret;
+                    if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
                   }
 
                 else if (p[0] == '-' && p[1] != ']')
@@ -1865,7 +1981,7 @@ regex_compile (pattern, size, syntax, bufp)
                     PATFETCH (c1);
                     
                     ret = compile_range (&p, pend, translate, syntax, b);
-                    if (ret != REG_NOERROR) return ret;
+                    if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
                   }
 
                 /* See if we're at the beginning of a possible character
@@ -1879,7 +1995,7 @@ regex_compile (pattern, size, syntax, bufp)
                     c1 = 0;
 
                     /* If pattern is `[[:'.  */
-                    if (p == pend) return REG_EBRACK;
+                    if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
 
                     for (;;)
                       {
@@ -1910,29 +2026,34 @@ regex_compile (pattern, size, syntax, bufp)
                         boolean is_upper = STREQ (str, "upper");
                         boolean is_xdigit = STREQ (str, "xdigit");
                         
-                        if (!IS_CHAR_CLASS (str)) return REG_ECTYPE;
+                        if (!IS_CHAR_CLASS (str))
+                         FREE_STACK_RETURN (REG_ECTYPE);
 
                         /* Throw away the ] at the end of the character
                            class.  */
                         PATFETCH (c);                                  
 
-                        if (p == pend) return REG_EBRACK;
+                        if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
 
                         for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
                           {
+                           /* This was split into 3 if's to
+                              avoid an arbitrary limit in some compiler.  */
                             if (   (is_alnum  && ISALNUM (ch))
                                 || (is_alpha  && ISALPHA (ch))
                                 || (is_blank  && ISBLANK (ch))
-                                || (is_cntrl  && ISCNTRL (ch))
-                                || (is_digit  && ISDIGIT (ch))
+                                || (is_cntrl  && ISCNTRL (ch)))
+                             SET_LIST_BIT (ch);
+                           if (   (is_digit  && ISDIGIT (ch))
                                 || (is_graph  && ISGRAPH (ch))
                                 || (is_lower  && ISLOWER (ch))
-                                || (is_print  && ISPRINT (ch))
-                                || (is_punct  && ISPUNCT (ch))
+                                || (is_print  && ISPRINT (ch)))
+                             SET_LIST_BIT (ch);
+                           if (   (is_punct  && ISPUNCT (ch))
                                 || (is_space  && ISSPACE (ch))
                                 || (is_upper  && ISUPPER (ch))
                                 || (is_xdigit && ISXDIGIT (ch)))
-                            SET_LIST_BIT (ch);
+                             SET_LIST_BIT (ch);
                           }
                         had_char_class = true;
                       }
@@ -1998,7 +2119,7 @@ regex_compile (pattern, size, syntax, bufp)
 
 
         case '\\':
-          if (p == pend) return REG_EESCAPE;
+          if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
 
           /* Do not translate the character after the \, so that we can
              distinguish, e.g., \B from \b, even if we normally would
@@ -2063,7 +2184,7 @@ regex_compile (pattern, size, syntax, bufp)
                 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
                   goto normal_backslash;
                 else
-                  return REG_ERPAREN;
+                  FREE_STACK_RETURN (REG_ERPAREN);
 
             handle_close:
               if (fixup_alt_jump)
@@ -2083,7 +2204,7 @@ regex_compile (pattern, size, syntax, bufp)
                 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
                   goto normal_char;
                 else
-                  return REG_ERPAREN;
+                  FREE_STACK_RETURN (REG_ERPAREN);
 
               /* Since we just checked for an empty stack above, this
                  ``can't happen''.  */
@@ -2190,7 +2311,7 @@ regex_compile (pattern, size, syntax, bufp)
                     if (syntax & RE_NO_BK_BRACES)
                       goto unfetch_interval;
                     else
-                      return REG_EBRACE;
+                      FREE_STACK_RETURN (REG_EBRACE);
                   }
 
                 GET_UNSIGNED_NUMBER (lower_bound);
@@ -2210,12 +2331,12 @@ regex_compile (pattern, size, syntax, bufp)
                     if (syntax & RE_NO_BK_BRACES)
                       goto unfetch_interval;
                     else 
-                      return REG_BADBR;
+                      FREE_STACK_RETURN (REG_BADBR);
                   }
 
                 if (!(syntax & RE_NO_BK_BRACES)) 
                   {
-                    if (c != '\\') return REG_EBRACE;
+                    if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
 
                     PATFETCH (c);
                   }
@@ -2225,7 +2346,7 @@ regex_compile (pattern, size, syntax, bufp)
                     if (syntax & RE_NO_BK_BRACES)
                       goto unfetch_interval;
                     else 
-                      return REG_BADBR;
+                      FREE_STACK_RETURN (REG_BADBR);
                   }
 
                 /* We just parsed a valid interval.  */
@@ -2234,7 +2355,7 @@ regex_compile (pattern, size, syntax, bufp)
                 if (!laststart)
                   {
                     if (syntax & RE_CONTEXT_INVALID_OPS)
-                      return REG_BADRPT;
+                      FREE_STACK_RETURN (REG_BADRPT);
                     else if (syntax & RE_CONTEXT_INDEP_OPS)
                       laststart = b;
                     else
@@ -2401,7 +2522,7 @@ regex_compile (pattern, size, syntax, bufp)
               c1 = c - '0';
 
               if (c1 > regnum)
-                return REG_ESUBREG;
+                FREE_STACK_RETURN (REG_ESUBREG);
 
               /* Can't back reference to a subexpression if inside of it.  */
               if (group_in_compile_stack (compile_stack, c1))
@@ -2473,7 +2594,12 @@ regex_compile (pattern, size, syntax, bufp)
     STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
 
   if (!COMPILE_STACK_EMPTY) 
-    return REG_EPAREN;
+    FREE_STACK_RETURN (REG_EPAREN);
+
+  /* If we don't want backtracking, force success
+     the first time we reach the end of the compiled pattern.  */
+  if (syntax & RE_NO_POSIX_BACKTRACKING)
+    BUF_PUSH (succeed);
 
   free (compile_stack.stack);
 
@@ -2525,18 +2651,9 @@ regex_compile (pattern, size, syntax, bufp)
 #endif /* not emacs */
       }
 
-    /* Initialize some other variables the matcher uses.  */
-    RETALLOC_IF (regstart,      num_regs, const char *);
-    RETALLOC_IF (regend,        num_regs, const char *);
-    RETALLOC_IF (old_regstart,  num_regs, const char *);
-    RETALLOC_IF (old_regend,    num_regs, const char *);
-    RETALLOC_IF (best_regstart,  num_regs, const char *);
-    RETALLOC_IF (best_regend,   num_regs, const char *);
-    RETALLOC_IF (reg_info,      num_regs, register_info_type);
-    RETALLOC_IF (reg_dummy,     num_regs, const char *);
-    RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
+    regex_grow_registers (num_regs);
   }
-#endif
+#endif /* not MATCH_MAY_ALLOCATE */
 
   return REG_NOERROR;
 } /* regex_compile */
@@ -2639,7 +2756,7 @@ at_endline_loc_p (p, pend, syntax)
 {
   const char *next = p;
   boolean next_backslash = *next == '\\';
-  const char *next_next = p + 1 < pend ? p + 1 : NULL;
+  const char *next_next = p + 1 < pend ? p + 1 : 0;
   
   return
        /* Before a subexpression?  */
@@ -2704,8 +2821,9 @@ compile_range (p_ptr, pend, translate, syntax, b)
 
      We also want to fetch the endpoints without translating them; the 
      appropriate translation is done in the bit-setting loop below.  */
-  range_start = ((unsigned char *) p)[-2];
-  range_end   = ((unsigned char *) p)[0];
+  /* The SVR4 compiler on the 3B2 had trouble with unsigned const char *.  */
+  range_start = ((const unsigned char *) p)[-2];
+  range_end   = ((const unsigned char *) p)[0];
 
   /* Have to increment the pointer into the pattern string, so the
      caller isn't still at the ending character.  */
@@ -2760,6 +2878,12 @@ re_compile_fastmap (bufp)
   unsigned char *p = pattern;
   register unsigned char *pend = pattern + size;
 
+  /* This holds the pointer to the failure stack, when
+     it is allocated relocatably.  */
+#ifdef REL_ALLOC
+  fail_stack_elt_t *failure_stack_ptr;
+#endif
+
   /* Assume that each path through the pattern can be null until
      proven otherwise.  We set this false at the bottom of switch
      statement, to which we get only if a particular path doesn't
@@ -2776,26 +2900,30 @@ re_compile_fastmap (bufp)
   bufp->fastmap_accurate = 1;      /* It will be when we're done.  */
   bufp->can_be_null = 0;
       
-  while (p != pend || !FAIL_STACK_EMPTY ())
+  while (1)
     {
-      if (p == pend)
-        {
-          bufp->can_be_null |= path_can_be_null;
-          
-          /* Reset for next path.  */
-          path_can_be_null = true;
-          
-          p = fail_stack.stack[--fail_stack.avail];
+      if (p == pend || *p == succeed)
+       {
+         /* We have reached the (effective) end of pattern.  */
+         if (!FAIL_STACK_EMPTY ())
+           {
+             bufp->can_be_null |= path_can_be_null;
+
+             /* Reset for next path.  */
+             path_can_be_null = true;
+
+             p = fail_stack.stack[--fail_stack.avail].pointer;
+
+             continue;
+           }
+         else
+           break;
        }
 
       /* We should never be about to go beyond the end of the pattern.  */
       assert (p < pend);
       
-#ifdef SWITCH_ENUM_BUG
-      switch ((int) ((re_opcode_t) *p++))
-#else
-      switch ((re_opcode_t) *p++)
-#endif
+      switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
        {
 
         /* I guess the idea here is to simply not bother with a fastmap
@@ -2805,7 +2933,7 @@ re_compile_fastmap (bufp)
            that is all we do.  */
        case duplicate:
          bufp->can_be_null = 1;
-          return 0;
+          goto done;
 
 
       /* Following are the cases which match a character.  These end
@@ -2849,22 +2977,25 @@ re_compile_fastmap (bufp)
 
 
         case anychar:
-          /* `.' matches anything ...  */
-         for (j = 0; j < (1 << BYTEWIDTH); j++)
-            fastmap[j] = 1;
+         {
+           int fastmap_newline = fastmap['\n'];
 
-          /* ... except perhaps newline.  */
-          if (!(bufp->syntax & RE_DOT_NEWLINE))
-            fastmap['\n'] = 0;
+           /* `.' matches anything ...  */
+           for (j = 0; j < (1 << BYTEWIDTH); j++)
+             fastmap[j] = 1;
 
-          /* Return if we have already set `can_be_null'; if we have,
-             then the fastmap is irrelevant.  Something's wrong here.  */
-         else if (bufp->can_be_null)
-           return 0;
+           /* ... except perhaps newline.  */
+           if (!(bufp->syntax & RE_DOT_NEWLINE))
+             fastmap['\n'] = fastmap_newline;
 
-          /* Otherwise, have to check alternative paths.  */
-         break;
+           /* Return if we have already set `can_be_null'; if we have,
+              then the fastmap is irrelevant.  Something's wrong here.  */
+           else if (bufp->can_be_null)
+             goto done;
 
+           /* Otherwise, have to check alternative paths.  */
+           break;
+         }
 
 #ifdef emacs
         case syntaxspec:
@@ -2933,7 +3064,7 @@ re_compile_fastmap (bufp)
          
           /* If what's on the stack is where we are now, pop it.  */
           if (!FAIL_STACK_EMPTY () 
-             && fail_stack.stack[fail_stack.avail - 1] == p)
+             && fail_stack.stack[fail_stack.avail - 1].pointer == p)
             fail_stack.avail--;
 
           continue;
@@ -2954,7 +3085,10 @@ re_compile_fastmap (bufp)
           if (p + j < pend)
             {
               if (!PUSH_PATTERN_OP (p + j, fail_stack))
-                return -2;
+               {
+                 RESET_FAIL_STACK ();
+                 return -2;
+               }
             }
           else
             bufp->can_be_null = 1;
@@ -3011,6 +3145,9 @@ re_compile_fastmap (bufp)
   /* Set `can_be_null' for the last path (also the first path, if the
      pattern is empty).  */
   bufp->can_be_null |= path_can_be_null;
+
+ done:
+  RESET_FAIL_STACK ();
   return 0;
 } /* re_compile_fastmap */
 \f
@@ -3180,7 +3317,11 @@ re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
 
       val = re_match_2_internal (bufp, string1, size1, string2, size2,
                                 startpos, regs, stop);
+#ifndef REGEX_MALLOC
+#ifdef C_ALLOCA
       alloca (0);
+#endif
+#endif
 
       if (val >= 0)
        return startpos;
@@ -3261,11 +3402,10 @@ static boolean alt_match_null_string_p (),
 
 /* Free everything we malloc.  */
 #ifdef MATCH_MAY_ALLOCATE
-#ifdef REGEX_MALLOC
-#define FREE_VAR(var) if (var) free (var); var = NULL
+#define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
 #define FREE_VARIABLES()                                               \
   do {                                                                 \
-    FREE_VAR (fail_stack.stack);                                       \
+    REGEX_FREE_STACK (fail_stack.stack);                               \
     FREE_VAR (regstart);                                               \
     FREE_VAR (regend);                                                 \
     FREE_VAR (old_regstart);                                           \
@@ -3276,12 +3416,8 @@ static boolean alt_match_null_string_p (),
     FREE_VAR (reg_dummy);                                              \
     FREE_VAR (reg_info_dummy);                                         \
   } while (0)
-#else /* not REGEX_MALLOC */
-/* This used to do alloca (0), but now we do that in the caller.  */
-#define FREE_VARIABLES() /* Nothing */
-#endif /* not REGEX_MALLOC */
 #else
-#define FREE_VARIABLES() /* Do nothing!  */
+#define FREE_VARIABLES() ((void)0) /* Do nothing!  But inhibit gcc warning.  */
 #endif /* not MATCH_MAY_ALLOCATE */
 
 /* These values must meet several constraints.  They must not be valid
@@ -3395,6 +3531,12 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
   unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
 #endif
 
+  /* This holds the pointer to the failure stack, when
+     it is allocated relocatably.  */
+#ifdef REL_ALLOC
+  fail_stack_elt_t *failure_stack_ptr;
+#endif
+
   /* We fill all the registers internally, independent of what we
      return, for use in backreferences.  The number here includes
      an element for register zero.  */
@@ -3453,6 +3595,9 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
      and need to test it, it's not garbage.  */
   const char *match_end = NULL;
 
+  /* This helps SET_REGS_MATCHED avoid doing redundant work.  */
+  int set_regs_matched_done = 0;
+
   /* Used when we pop values we don't care about.  */
 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
   const char **reg_dummy;
@@ -3493,7 +3638,6 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
           return -2;
         }
     }
-#if defined (REGEX_MALLOC)
   else
     {
       /* We must initialize all our variables to NULL, so that
@@ -3502,7 +3646,6 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
         = best_regend = reg_dummy = NULL;
       reg_info = reg_info_dummy = (register_info_type *) NULL;
     }
-#endif /* REGEX_MALLOC */
 #endif /* MATCH_MAY_ALLOCATE */
 
   /* The starting position is bogus.  */
@@ -3588,17 +3731,27 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
              longest match, try backtracking.  */
           if (d != end_match_2)
            {
+             /* 1 if this match ends in the same string (string1 or string2)
+                as the best previous match.  */
+             boolean same_str_p = (FIRST_STRING_P (match_end) 
+                                   == MATCHING_IN_FIRST_STRING);
+             /* 1 if this match is the best seen so far.  */
+             boolean best_match_p;
+
+             /* AIX compiler got confused when this was combined
+                with the previous declaration.  */
+             if (same_str_p)
+               best_match_p = d > match_end;
+             else
+               best_match_p = !MATCHING_IN_FIRST_STRING;
+
               DEBUG_PRINT1 ("backtracking.\n");
               
               if (!FAIL_STACK_EMPTY ())
                 { /* More failure points to try.  */
-                  boolean same_str_p = (FIRST_STRING_P (match_end) 
-                                       == MATCHING_IN_FIRST_STRING);
 
                   /* If exceeds best match so far, save it.  */
-                  if (!best_regs_set
-                      || (same_str_p && d > match_end)
-                      || (!same_str_p && !MATCHING_IN_FIRST_STRING))
+                  if (!best_regs_set || best_match_p)
                     {
                       best_regs_set = true;
                       match_end = d;
@@ -3614,8 +3767,10 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
                   goto fail;          
                 }
 
-              /* If no failure points, don't restore garbage.  */
-              else if (best_regs_set)   
+              /* If no failure points, don't restore garbage.  And if
+                 last match is real best match, don't restore second
+                 best one. */
+              else if (best_regs_set && !best_match_p)
                 {
                restore_best_regs:
                   /* Restore best match.  It may happen that `dend ==
@@ -3637,6 +3792,7 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
                 }
             } /* d != end_match_2 */
 
+       succeed_label:
           DEBUG_PRINT1 ("Accepting match.\n");
 
           /* If caller wants register contents data back, do it.  */
@@ -3651,7 +3807,10 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
                   regs->start = TALLOC (regs->num_regs, regoff_t);
                   regs->end = TALLOC (regs->num_regs, regoff_t);
                   if (regs->start == NULL || regs->end == NULL)
-                    return -2;
+                   {
+                     FREE_VARIABLES ();
+                     return -2;
+                   }
                   bufp->regs_allocated = REGS_REALLOCATE;
                 }
               else if (bufp->regs_allocated == REGS_REALLOCATE)
@@ -3664,7 +3823,10 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
                       RETALLOC (regs->start, regs->num_regs, regoff_t);
                       RETALLOC (regs->end, regs->num_regs, regoff_t);
                       if (regs->start == NULL || regs->end == NULL)
-                        return -2;
+                       {
+                         FREE_VARIABLES ();
+                         return -2;
+                       }
                     }
                 }
               else
@@ -3709,7 +3871,6 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
                 regs->start[mcnt] = regs->end[mcnt] = -1;
            } /* regs && !bufp->no_sub */
 
-          FREE_VARIABLES ();
           DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
                         nfailure_points_pushed, nfailure_points_popped,
                         nfailure_points_pushed - nfailure_points_popped);
@@ -3721,15 +3882,12 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
 
           DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
 
+          FREE_VARIABLES ();
           return mcnt;
         }
 
       /* Otherwise match next pattern command.  */
-#ifdef SWITCH_ENUM_BUG
-      switch ((int) ((re_opcode_t) *p++))
-#else
-      switch ((re_opcode_t) *p++)
-#endif
+      switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
        {
         /* Ignore these.  Used to ignore the n of succeed_n's which
            currently have n == 0.  */
@@ -3737,6 +3895,9 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
           DEBUG_PRINT1 ("EXECUTING no_op.\n");
           break;
 
+       case succeed:
+          DEBUG_PRINT1 ("EXECUTING succeed.\n");
+         goto succeed_label;
 
         /* Match the next n pattern characters exactly.  The following
            byte in the pattern defines n, and the n bytes after that
@@ -3844,6 +4005,9 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
 
           IS_ACTIVE (reg_info[*p]) = 1;
           MATCHED_SOMETHING (reg_info[*p]) = 0;
+
+         /* Clear this whenever we change the register activity status.  */
+         set_regs_matched_done = 0;
           
           /* This is the new highest active register.  */
           highest_active_reg = *p;
@@ -3856,6 +4020,7 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
           /* Move past the register number and inner group count.  */
           p += 2;
          just_past_start_mem = p;
+
           break;
 
 
@@ -3881,7 +4046,10 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
 
           /* This register isn't active anymore.  */
           IS_ACTIVE (reg_info[*p]) = 0;
-          
+
+         /* Clear this whenever we change the register activity status.  */
+         set_regs_matched_done = 0;
+
           /* If this was the only register active, nothing is active
              anymore.  */
           if (lowest_active_reg == highest_active_reg)
@@ -4049,6 +4217,9 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
                     : bcmp (d, d2, mcnt))
                  goto fail;
                d += mcnt, d2 += mcnt;
+
+               /* Do this because we've match some characters.  */
+               SET_REGS_MATCHED ();
              }
          }
          break;
@@ -4278,7 +4449,7 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
 #endif
 
                 if ((re_opcode_t) p1[3] == exactn
-                   && ! (p2[1] * BYTEWIDTH > p1[4]
+                   && ! ((int) p2[1] * BYTEWIDTH > (int) p1[4]
                          && (p2[1 + p1[4] / BYTEWIDTH]
                              & (1 << (p1[4] % BYTEWIDTH)))))
                   {
@@ -4292,9 +4463,9 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
                    int idx;
                    /* We win if the charset_not inside the loop
                       lists every character listed in the charset after.  */
-                   for (idx = 0; idx < p2[1]; idx++)
+                   for (idx = 0; idx < (int) p2[1]; idx++)
                      if (! (p2[2 + idx] == 0
-                            || (idx < p1[4]
+                            || (idx < (int) p1[4]
                                 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
                        break;
 
@@ -4309,7 +4480,9 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
                    int idx;
                    /* We win if the charset inside the loop
                       has no overlap with the one after the loop.  */
-                   for (idx = 0; idx < p2[1] && idx < p1[4]; idx++)
+                   for (idx = 0;
+                        idx < (int) p2[1] && idx < (int) p1[4];
+                        idx++)
                      if ((p2[2 + idx] & p1[5 + idx]) != 0)
                        break;
 
@@ -4344,7 +4517,7 @@ re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
                actual values.  Otherwise, we will restore only one
                register from the stack, since lowest will == highest in
                `pop_failure_point'.  */
-            unsigned long dummy_low_reg, dummy_high_reg;
+            unsigned dummy_low_reg, dummy_high_reg;
             unsigned char *pdummy;
             const char *sdummy;
 
@@ -4913,13 +5086,15 @@ re_compile_pattern (pattern, length, bufp)
   
   ret = regex_compile (pattern, length, re_syntax_options, bufp);
 
-  return re_error_msg[(int) ret];
+  if (!ret)
+    return NULL;
+  return gettext (re_error_msgid[(int) ret]);
 }     
 \f
 /* Entry points compatible with 4.2 BSD regex library.  We don't define
-   them if this is an Emacs or POSIX compilation.  */
+   them unless specifically requested.  */
 
-#if !defined (emacs) && !defined (_POSIX_SOURCE)
+#ifdef _REGEX_RE_COMP
 
 /* BSD has one and only one pattern buffer.  */
 static struct re_pattern_buffer re_comp_buf;
@@ -4933,7 +5108,7 @@ re_comp (s)
   if (!s)
     {
       if (!re_comp_buf.buffer)
-       return "No previous regular expression";
+       return gettext ("No previous regular expression");
       return 0;
     }
 
@@ -4941,12 +5116,12 @@ re_comp (s)
     {
       re_comp_buf.buffer = (unsigned char *) malloc (200);
       if (re_comp_buf.buffer == NULL)
-        return "Memory exhausted";
+        return gettext (re_error_msgid[(int) REG_ESPACE]);
       re_comp_buf.allocated = 200;
 
       re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
       if (re_comp_buf.fastmap == NULL)
-       return "Memory exhausted";
+       return gettext (re_error_msgid[(int) REG_ESPACE]);
     }
 
   /* Since `re_exec' always passes NULL for the `regs' argument, we
@@ -4957,8 +5132,11 @@ re_comp (s)
 
   ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
   
-  /* Yes, we're discarding `const' here.  */
-  return (char *) re_error_msg[(int) ret];
+  if (!ret)
+    return NULL;
+
+  /* Yes, we're discarding `const' here if !HAVE_LIBINTL.  */
+  return (char *) gettext (re_error_msgid[(int) ret]);
 }
 
 
@@ -4970,7 +5148,7 @@ re_exec (s)
   return
     0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
 }
-#endif /* not emacs and not _POSIX_SOURCE */
+#endif /* _REGEX_RE_COMP */
 \f
 /* POSIX.2 functions.  Don't define these for Emacs.  */
 
@@ -5162,19 +5340,14 @@ regerror (errcode, preg, errbuf, errbuf_size)
   size_t msg_size;
 
   if (errcode < 0
-      || errcode >= (sizeof (re_error_msg) / sizeof (re_error_msg[0])))
+      || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
     /* Only error codes returned by the rest of the code should be passed 
        to this routine.  If we are given anything else, or if other regex
        code generates an invalid error code, then the program has a bug.
        Dump core so we can fix it.  */
     abort ();
 
-  msg = re_error_msg[errcode];
-
-  /* POSIX doesn't require that we do anything in this case, but why
-     not be nice.  */
-  if (! msg)
-    msg = "Success";
+  msg = gettext (re_error_msgid[errcode]);
 
   msg_size = strlen (msg) + 1; /* Includes the null.  */