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