home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / id-utils-3.2-src.tgz / tar.out / fsf / id-utils / lib / regex.c < prev    next >
C/C++ Source or Header  |  1996-09-28  |  177KB  |  5,489 lines

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