home *** CD-ROM | disk | FTP | other *** search
/ ARM Club 1 / ARM_CLUB_CD.iso / contents / apps / clib / progs / utilslib / Regex / C / Regex1 < prev    next >
Encoding:
Text File  |  1991-09-18  |  78.7 KB  |  2,773 lines

  1. /* Extended regular expression matching and search library.
  2.    Copyright (C) 1985, 1989-90 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18.  
  19. /* To test, compile with -Dtest.  This Dtestable feature turns this into
  20.    a self-contained program which reads a pattern, describes how it
  21.    compiles, then reads a string and searches for it.
  22.    
  23.    On the other hand, if you compile with both -Dtest and -Dcanned you
  24.    can run some tests we've already thought of.  */
  25.  
  26.  
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <limits.h>
  30. #include <stdio.h>
  31. #include <ctype.h>
  32.  
  33. /* Get the interface, including the syntax bits.  */
  34. #include "regex.h"
  35.  
  36. /* Allow BSD version of memory functions */
  37. #define bcopy(s,d,n)    memcpy((d),(s),(n))
  38. #define bcmp(s1,s2,n)    memcmp((s1),(s2),(n))
  39. #define bzero(s,n)    memset((s),0,(n))
  40.  
  41. /* Implemetataion limits */
  42. #define CHAR_NUM (1 << CHAR_BIT)        /* Number of characters */
  43. #define CHAR_ARR (CHAR_NUM / CHAR_BIT)        /* Size of a char bit array */
  44.  
  45. /* Define the syntax stuff, so we can do the \w, \s, etc.  */
  46. #define Sword    1
  47. #define Sdigit    2
  48. #define Sspace    4
  49.  
  50. static char re_syntax_table[CHAR_NUM];
  51.  
  52. #define HAS_SYNTAX(c,s) ((re_syntax_table[(c)] & s) != 0)
  53.  
  54. static void init_syntax_once (void)
  55. {
  56.   register int c;
  57.   register int syn;
  58.   static int done = 0;
  59.  
  60.   if (done)
  61.     return;
  62.  
  63.   for (c = 0; c < CHAR_NUM; c++)
  64.     {
  65.       syn = 0;
  66.       if (isalnum(c) || c == '_')
  67.     syn |= Sword;
  68.       if (isdigit(c))
  69.     syn |= Sdigit;
  70.       if (isspace(c))
  71.     syn |= Sspace;
  72.  
  73.       re_syntax_table[c] = syn;
  74.     }
  75.  
  76.   done = 1;
  77. }
  78.  
  79. /* These are the command codes that appear in compiled regular
  80.    expressions, one per byte.  Some command codes are followed by
  81.    argument bytes.  A command code can specify any interpretation
  82.    whatsoever for its arguments.  Zero-bytes may appear in the compiled
  83.    regular expression.
  84.    
  85.    The value of `exactn' is needed in search.c (search_buffer) in emacs.
  86.    So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
  87.    `exactn' we use here must also be 1.  */
  88.  
  89. enum regexpcode
  90.   {
  91.     unused=0,
  92.     exactn=1, /* Followed by one byte giving n, then by n literal bytes.  */
  93.     begline,  /* Fail unless at beginning of line.  */
  94.     endline,  /* Fail unless at end of line.  */
  95.     jump,     /* Followed by two bytes giving relative address to jump to.  */
  96.     on_failure_jump,     /* Followed by two bytes giving relative address of 
  97.                 place to resume at in case of failure.  */
  98.     finalize_jump,     /* Throw away latest failure point and then jump to 
  99.                 address.  */
  100.     maybe_finalize_jump, /* Like jump but finalize if safe to do so.
  101.                 This is used to jump back to the beginning
  102.                 of a repeat.  If the command that follows
  103.                 this jump is clearly incompatible with the
  104.                 one at the beginning of the repeat, such that
  105.                 we can be sure that there is no use backtracking
  106.                 out of repetitions already completed,
  107.                 then we finalize.  */
  108.     dummy_failure_jump,  /* Jump, and push a dummy failure point. This 
  109.                 failure point will be thrown away if an attempt 
  110.                             is made to use it for a failure. A + construct 
  111.                             makes this before the first repeat.  Also
  112.                             use it as an intermediary kind of jump when
  113.                             compiling an or construct.  */
  114.     succeed_n,     /* Used like on_failure_jump except has to succeed n times;
  115.             then gets turned into an on_failure_jump. The relative
  116.                     address following it is useless until then.  The
  117.                     address is followed by two bytes containing n.  */
  118.     jump_n,     /* Similar to jump, but jump n times only; also the relative
  119.             address following is in turn followed by yet two more bytes
  120.                     containing n.  */
  121.     set_number_at,    /* Set the following relative location to the
  122.                subsequent number.  */
  123.     anychar,      /* Matches any (more or less) one character.  */
  124.     charset,      /* Matches any one char belonging to specified set.
  125.              First following byte is number of bitmap bytes.
  126.              Then come bytes for a bitmap saying which chars are in.
  127.              Bits in each byte are ordered low-bit-first.
  128.              A character is in the set if its bit is 1.
  129.              A character too large to have a bit in the map
  130.              is automatically not in the set.  */
  131.     charset_not,  /* Same parameters as charset, but match any character
  132.                      that is not one of those specified.  */
  133.     start_memory, /* Start remembering the text that is matched, for
  134.              storing in a memory register.  Followed by one
  135.                      byte containing the register number.  Register numbers
  136.                      must be in the range 0 through RE_NREGS.  */
  137.     stop_memory,  /* Stop remembering the text that is matched
  138.              and store it in a memory register.  Followed by
  139.                      one byte containing the register number. Register
  140.                      numbers must be in the range 0 through RE_NREGS.  */
  141.     duplicate,    /* Match a duplicate of something remembered.
  142.              Followed by one byte containing the index of the memory 
  143.                      register.  */
  144.     begbuf,       /* Succeeds if at beginning of buffer.  */
  145.     endbuf,       /* Succeeds if at end of buffer.  */
  146.     wordchar,     /* Matches any word-constituent character.  */
  147.     notwordchar,  /* Matches any char that is not a word-constituent.  */
  148.     spacechar,    /* Matches any whitespace character */
  149.     notspacechar, /* Matches any non-whitespace character */
  150.     digit,        /* Matches any digit character */
  151.     notdigit,     /* Matches any non-digit character */
  152.     begword,      /* Succeeds if at beginning of word.  */
  153.     endword,      /* Succeeds if at end of word.  */
  154.     wordbound,    /* Succeeds if at a word boundary */
  155.     notwordbound  /* Succeeds if not at a word boundary */
  156.   };
  157.  
  158.  
  159. /* Number of failure points to allocate space for initially,
  160.    when matching.  If this number is exceeded, more space is allocated,
  161.    so it is not a hard limit.  */
  162.  
  163. #ifndef NFAILURES
  164. #define NFAILURES 80
  165. #endif
  166.  
  167. #define SIGN_EXTEND_CHAR(x) ((signed char)(x))
  168.  
  169. /* Store NUMBER in two contiguous bytes starting at DESTINATION.  */
  170. #define STORE_NUMBER(destination, number)                \
  171.   { (destination)[0] = (number) & 0377;                    \
  172.     (destination)[1] = ((number) >> 8) & 0377; }
  173.   
  174. /* Same as STORE_NUMBER, except increment the destination pointer to
  175.    the byte after where the number is stored.  Watch out that values for
  176.    DESTINATION such as p + 1 won't work, whereas p will.  */
  177. #define STORE_NUMBER_AND_INCR(destination, number)            \
  178.   { STORE_NUMBER(destination, number);                    \
  179.     (destination) += 2; }
  180.  
  181.  
  182. /* Put into DESTINATION a number stored in two contingous bytes starting
  183.    at SOURCE.  */
  184. #define EXTRACT_NUMBER(destination, source)                \
  185.   { (destination) = *(source) & 0377;                    \
  186.     (destination) += SIGN_EXTEND_CHAR (*(char *)((source) + 1)) << 8; }
  187.  
  188. /* Same as EXTRACT_NUMBER, except increment the pointer for source to
  189.    point to second byte of SOURCE.  Note that SOURCE has to be a value
  190.    such as p, not, e.g., p + 1. */
  191. #define EXTRACT_NUMBER_AND_INCR(destination, source)            \
  192.   { EXTRACT_NUMBER (destination, source);                \
  193.     (source) += 2; }
  194.  
  195.  
  196. #if 0
  197. /* This is only GNU compatibility. We kill it via a define in "regex.h" */
  198.  
  199. /* Specify the precise syntax of regexps for compilation.  This provides
  200.    for compatibility for various utilities which historically have
  201.    different, incompatible syntaxes.
  202.    
  203.    The argument SYNTAX is a bit-mask comprised of the various bits
  204.    defined in regex.h.  */
  205.  
  206. int re_set_syntax (int syntax)
  207. {
  208.   int ret;
  209.  
  210.   ret = obscure_syntax;
  211.   obscure_syntax = syntax;
  212.   return ret;
  213. }
  214.  
  215. /* Set by re_set_syntax to the current regexp syntax to recognize.  */
  216. int obscure_syntax = 0;
  217. #endif
  218.  
  219. /* Macros for re_compile_pattern, which is found below these definitions.  */
  220.  
  221. /* Fetch the next character in the uncompiled pattern, translating it if
  222.    necessary.  */
  223. #define PATFETCH(c)                            \
  224.   {if (p == pend) goto end_of_pattern;                    \
  225.   c = * (unsigned char *) p++;                        \
  226. fprintf(stderr,"%c",c);\
  227.   if (translate) c = translate[c]; }
  228.  
  229. /* Fetch the next character in the uncompiled pattern, with no
  230.    translation.  */
  231. #define PATFETCH_RAW(c)                            \
  232.  {if (p == pend) goto end_of_pattern;                    \
  233.   c = * (unsigned char *) p++; }
  234.  
  235. #define PATUNFETCH p--
  236.  
  237. /* If the buffer isn't allocated when it comes in, use this.  */
  238. #define INIT_BUF_SIZE  28
  239.  
  240. /* Make sure we have at least N more bytes of space in buffer.  */
  241. #define GET_BUFFER_SPACE(n)                        \
  242.   {                                        \
  243.     while (b - bufp->buffer + (size_t)(n) >= bufp->allocated)        \
  244.       EXTEND_BUFFER;                            \
  245.   }
  246.  
  247. /* Make sure we have one more byte of buffer space and then add CH to it.  */
  248. #define BUFPUSH(ch)                            \
  249.   {                                    \
  250.     GET_BUFFER_SPACE (1);                        \
  251.     *b++ = (char) (ch);                            \
  252.   }
  253.   
  254. /* Extend the buffer by twice its current size via reallociation and
  255.    reset the pointers that pointed into the old allocation to point to
  256.    the correct places in the new allocation.  */
  257. #define EXTEND_BUFFER                             \
  258.   if ((b = extend_buffer(b,bufp)) == 0)                        \
  259.     goto memory_exhausted;
  260.  
  261. /* Set the bit for character C in a character set list.  */
  262. #define SET_LIST_BIT(c)  (b[(c) / CHAR_BIT] |= 1 << ((c) % CHAR_BIT))
  263.  
  264. /* Get the next unsigned number in the uncompiled pattern.  */
  265. #define GET_UNSIGNED_NUMBER(num)                     \
  266.   { if (p != pend)                             \
  267.       {                                 \
  268.         PATFETCH (c);                             \
  269.     while (isdigit (c))                         \
  270.       {                                 \
  271.         if (num < 0)                         \
  272.            num = 0;                         \
  273.             num = num * 10 + c - '0';                     \
  274.         if (p == pend)                         \
  275.            break;                             \
  276.         PATFETCH (c);                         \
  277.       }                                 \
  278.         }                                 \
  279.   }
  280.  
  281. /* Subroutines for re_compile_pattern.  */
  282. static void store_jump (char *, char, char *);
  283. static void insert_jump (char, char *, char *, char *);
  284. static void store_jump_n (char *, char, char *, unsigned int);
  285. static void insert_jump_n (char, char *, char *, char *, unsigned int);
  286. static void insert_op_2 (char, char *, char *, int, int);
  287. static char *extend_buffer (char *, struct re_pattern_buffer *);
  288.  
  289. /* Static variables for re_compile_pattern */
  290.  
  291. /* Address of the count-byte of the most recently inserted `exactn'
  292.    command.  This makes it possible to tell whether a new exact-match
  293.    character can be added to that command or requires a new `exactn'
  294.    command.  */
  295.      
  296. static char *pending_exact;
  297.  
  298. /* Address of the place where a forward-jump should go to the end of
  299.    the containing expression.  Each alternative of an `or', except the
  300.    last, ends with a forward-jump of this sort.  */
  301.  
  302. static char *fixup_jump;
  303.  
  304. /* Address of start of the most recently finished expression.
  305.    This tells postfix * where to find the start of its operand.  */
  306.  
  307. static char *laststart;
  308.  
  309. /* Address of beginning of regexp, or inside of last (.  */
  310.  
  311. static char *begalt;
  312.  
  313. /* re_compile_pattern takes a regular-expression string
  314.    and converts it into a buffer full of byte commands for matching.
  315.  
  316.    PATTERN   is the address of the pattern string
  317.    SIZE      is the length of it.
  318.    BUFP        is a  struct re_pattern_buffer *  which points to the info
  319.          on where to store the byte commands.
  320.          This structure contains a  char *  which points to the
  321.          actual space, which should have been obtained with malloc.
  322.          re_compile_pattern may use realloc to grow the buffer space.
  323.  
  324.    The number of bytes of commands can be found out by looking in
  325.    the `struct re_pattern_buffer' that bufp pointed to, after
  326.    re_compile_pattern returns. */
  327.  
  328. char *re_compile_pattern (char *pattern, int size,
  329.               struct re_pattern_buffer *bufp)
  330. {
  331.   register char *b = bufp->buffer;
  332.   register char *p = pattern;
  333.   char *pend = pattern + size;
  334.   register unsigned c, c1;
  335.   char *p1;
  336.   unsigned char *translate = (unsigned char *) bufp->translate;
  337.  
  338.   /* In processing a repeat, 1 means zero matches is allowed.  */
  339.  
  340.   char zero_times_ok;
  341.  
  342.   /* In processing a repeat, 1 means many matches is allowed.  */
  343.  
  344.   char many_times_ok;
  345.  
  346.   /* In processing an interval, at least this many matches must be made.  */
  347.   int lower_bound;
  348.  
  349.   /* In processing an interval, at most this many matches can be made.  */
  350.   int upper_bound;
  351.  
  352.   /* Place in pattern (i.e., the {) to which to go back if the interval
  353.      is invalid.  */
  354.   char *beg_interval = 0;
  355.   
  356.   /* Stack of information saved by ( and restored by ).
  357.      Four stack elements are pushed by each (:
  358.        First, the value of b.
  359.        Second, the value of fixup_jump.
  360.        Third, the value of regnum.
  361.        Fourth, the value of begalt.  */
  362.  
  363.   int stackb[40];
  364.   int *stackp = stackb;
  365.   int *stacke = stackb + 40;
  366.   int *stackt;
  367.  
  368.   /* Counts ('s as they are encountered.  Remembered for the matching ),
  369.      where it becomes the register number to put in the stop_memory
  370.      command.  */
  371.  
  372.   int regnum = 1;
  373.  
  374.   /* Initialise our static variables, and parts of bufp */
  375.   pending_exact = 0;
  376.   fixup_jump = 0;
  377.   laststart = 0;
  378.   begalt = b;
  379.   bufp->fastmap_accurate = 0;
  380.  
  381.   /* Initialize the syntax table.  */
  382.   init_syntax_once();
  383.  
  384.   if (bufp->allocated == 0)
  385.     {
  386.       bufp->allocated = (size_t)INIT_BUF_SIZE;
  387.       if (bufp->buffer)
  388.     /* EXTEND_BUFFER loses when bufp->allocated is 0.  */
  389.     bufp->buffer = (char *) realloc (bufp->buffer, INIT_BUF_SIZE);
  390.       else
  391.     /* Caller did not allocate a buffer.  Do it for them.  */
  392.     bufp->buffer = (char *) malloc (INIT_BUF_SIZE);
  393.       if (!bufp->buffer) goto memory_exhausted;
  394.       begalt = b = bufp->buffer;
  395.     }
  396.  
  397.   while (p != pend)
  398.     {
  399.       PATFETCH (c);
  400.  
  401.       switch (c)
  402.     {
  403.     case '$':
  404.       BUFPUSH (endline);
  405.       break;
  406.     case '^':
  407.       BUFPUSH (begline);
  408.       break;
  409.     case '+':
  410.     case '?':
  411.     case '*':
  412.       /* If there is a sequence of repetition chars,
  413.          collapse it down to just one.  */
  414.       zero_times_ok = 0;
  415.       many_times_ok = 0;
  416.       while (1)
  417.         {
  418.           zero_times_ok |= c != '+';
  419.           many_times_ok |= c != '?';
  420.           if (p == pend)
  421.         break;
  422.           PATFETCH (c);
  423.           if (c != '*' && c != '+' && c != '?')
  424.         {
  425.           PATUNFETCH;
  426.           break;
  427.         }
  428.         }
  429.  
  430.       /* Star, etc. applied to an empty pattern is equivalent
  431.          to an empty pattern.  */
  432.       if (!laststart)  
  433.         break;
  434.  
  435.       /* Now we know whether or not zero matches is allowed
  436.          and also whether or not two or more matches is allowed.  */
  437.       if (many_times_ok)
  438.         {
  439.           /* If more than one repetition is allowed, put in at the
  440.                  end a backward relative jump from b to before the next
  441.                  jump we're going to put in below (which jumps from
  442.                  laststart to after this jump).  */
  443.               GET_BUFFER_SPACE (3);
  444.           store_jump (b, maybe_finalize_jump, laststart - 3);
  445.           b += 3;      /* Because store_jump put stuff here.  */
  446.         }
  447.           /* On failure, jump from laststart to b + 3, which will be the
  448.              end of the buffer after this jump is inserted.  */
  449.           GET_BUFFER_SPACE (3);
  450.       insert_jump (on_failure_jump, laststart, b + 3, b);
  451.       pending_exact = 0;
  452.       b += 3;
  453.       if (!zero_times_ok)
  454.         {
  455.           /* At least one repetition is required, so insert a
  456.                  dummy-failure before the initial on-failure-jump
  457.                  instruction of the loop. This effects a skip over that
  458.                  instruction the first time we hit that loop.  */
  459.               GET_BUFFER_SPACE (6);
  460.               insert_jump (dummy_failure_jump, laststart, laststart + 6, b);
  461.           b += 3;
  462.         }
  463.       break;
  464.  
  465.     case '.':
  466.       laststart = b;
  467.       BUFPUSH (anychar);
  468.       break;
  469.  
  470.         case '[':
  471.           if (p == pend)
  472.             goto invalid_pattern;
  473.       while (b - bufp->buffer > bufp->allocated - (CHAR_ARR + 3) )
  474.         EXTEND_BUFFER;
  475.  
  476.       laststart = b;
  477.       if (*p == '^')
  478.         {
  479.               BUFPUSH (charset_not); 
  480.               p++;
  481.             }
  482.       else
  483.         BUFPUSH (charset);
  484.       p1 = p;
  485.  
  486.       BUFPUSH (CHAR_ARR);
  487.       /* Clear the whole map */
  488.       bzero (b, CHAR_ARR);
  489.           
  490.       /* Read in characters and ranges, setting map bits.  */
  491.       while (1)
  492.         {
  493.           PATFETCH (c);
  494.  
  495.           /* Backslash indicates a special character class */
  496.           if (c == '\\')
  497.             {
  498.               PATFETCH_RAW(c);
  499.               switch (c)
  500.               {
  501.               /* Single character escapes */
  502.               case 'a':
  503.                 SET_LIST_BIT('\a');
  504.             continue;
  505.  
  506.               case 'b':
  507.                 SET_LIST_BIT('\b');
  508.             continue;
  509.  
  510.               case 'f':
  511.                 SET_LIST_BIT('\f');
  512.             continue;
  513.  
  514.               case 'n':
  515.                 SET_LIST_BIT('\n');
  516.             continue;
  517.  
  518.               case 'r':
  519.                 SET_LIST_BIT('\r');
  520.             continue;
  521.  
  522.               case 't':
  523.                 SET_LIST_BIT('\t');
  524.             continue;
  525.  
  526.               case 'v':
  527.                 SET_LIST_BIT('\v');
  528.             continue;
  529.  
  530.           /* Character class escapes */
  531.           case 'w':
  532.             for (c1 = 0; c1 < CHAR_NUM; ++c1)
  533.               {
  534.             if (HAS_SYNTAX(c1,Sword))
  535.               SET_LIST_BIT(c1);
  536.               }
  537.             continue;
  538.  
  539.           case 's':
  540.             for (c1 = 0; c1 < CHAR_NUM; ++c1)
  541.               {
  542.             if (HAS_SYNTAX(c1,Sspace))
  543.               SET_LIST_BIT(c1);
  544.               }
  545.             continue;
  546.  
  547.           case 'd':
  548.             for (c1 = 0; c1 < CHAR_NUM; ++c1)
  549.               {
  550.             if (HAS_SYNTAX(c1,Sdigit))
  551.               SET_LIST_BIT(c1);
  552.               }
  553.             continue;
  554.  
  555.           /* Hex or octal escapes */
  556.           case '0': case '1': case '2': case '3':
  557.           case '4': case '5': case '6': case '7':
  558.             {
  559.               int val = c - '0';
  560.  
  561.               if (0 <= *p && *p <= '7')
  562.             {
  563.               val <<= 3;
  564.               PATFETCH_RAW(c1);
  565.               val |= c1 - '0';
  566.  
  567.               if (0 <= *p && *p <= '7')
  568.                 {
  569.                   val <<= 3;
  570.                   PATFETCH_RAW(c1);
  571.                   val |= c1 - '0';
  572.                 }
  573.             }
  574.  
  575.               SET_LIST_BIT(val);
  576.             }
  577.             continue;
  578.  
  579.           case 'x':
  580.             if (isxdigit(*p))
  581.               {
  582.             int val;
  583.  
  584.             PATFETCH_RAW(c1);
  585.             if (isdigit(c1))
  586.               val = c1 - '0';
  587.             else if (islower(c1))
  588.               val = 10 + c1 - 'a';
  589.             else
  590.               val = 10 + c1 - 'A';
  591.  
  592.             if (isxdigit(*p))
  593.               {
  594.                 val <<= 4;
  595.                 PATFETCH_RAW(c1);
  596.                 if (isdigit(c1))
  597.                   val |= c1 - '0';
  598.                 else if (islower(c1))
  599.                   val |= 10 + c1 - 'a';
  600.                 else
  601.                   val |= 10 + c1 - 'A';
  602.               }
  603.  
  604.                 SET_LIST_BIT(val);
  605.                 continue;
  606.               }
  607.             /* Else, FALL THROUGH (not a hex escape!) */
  608.  
  609.           /* General: simple character */
  610.               default:
  611.                 if (translate) c = translate[c];
  612.                 SET_LIST_BIT(c);
  613.                 continue;
  614.               }
  615.             }
  616.  
  617.           /* Have we reached the end of the class yet? */
  618.               if (c == ']' && p != p1 + 1)
  619.                 break;
  620.  
  621.               /* Get a range.  */
  622.               if (p[0] == '-' && p[1] != ']')
  623.         {
  624.                   PATFETCH (c1);
  625.           PATFETCH (c1);
  626.  
  627.                   while (c <= c1)
  628.             {
  629.                       SET_LIST_BIT (c);
  630.                       c++;
  631.             }
  632.  
  633.           continue;
  634.                 }
  635.  
  636.                 /* Normal character */
  637.                 SET_LIST_BIT (c);
  638.         }
  639.  
  640.           /* Discard any character set/class bitmap bytes that are all
  641.              0 at the end of the map. Decrement the map-length byte too.  */
  642.           while ((int) b[-1] > 0 && b[b[-1] - 1] == 0) 
  643.             b[-1]--; 
  644.           b += b[-1];
  645.           break;
  646.  
  647.     case '(':
  648.       if (stackp == stacke) goto nesting_too_deep;
  649.  
  650.           /* Laststart should point to the start_memory that we are about
  651.              to push (unless the pattern has RE_NREGS or more ('s).  */
  652.           *stackp++ = b - bufp->buffer;    
  653.       if (regnum < RE_NREGS)
  654.         {
  655.           BUFPUSH (start_memory);
  656.           BUFPUSH (regnum);
  657.         }
  658.       *stackp++ = fixup_jump ? fixup_jump - bufp->buffer + 1 : 0;
  659.       *stackp++ = regnum++;
  660.       *stackp++ = begalt - bufp->buffer;
  661.       fixup_jump = 0;
  662.       laststart = 0;
  663.       begalt = b;
  664.       break;
  665.  
  666.     case ')':
  667.       if (stackp == stackb) goto unmatched_close;
  668.       begalt = *--stackp + bufp->buffer;
  669.       if (fixup_jump)
  670.         store_jump (fixup_jump, jump, b);
  671.       if (stackp[-1] < RE_NREGS)
  672.         {
  673.           BUFPUSH (stop_memory);
  674.           BUFPUSH (stackp[-1]);
  675.         }
  676.       stackp -= 2;
  677.           fixup_jump = *stackp ? *stackp + bufp->buffer - 1 : 0;
  678.           laststart = *--stackp + bufp->buffer;
  679.       break;
  680.  
  681.     case '|':
  682.       /* Insert before the previous alternative a jump which
  683.              jumps to this alternative if the former fails.  */
  684.           GET_BUFFER_SPACE (6);
  685.           insert_jump (on_failure_jump, begalt, b + 6, b);
  686.       pending_exact = 0;
  687.       b += 3;
  688.       /* The alternative before the previous alternative has a
  689.              jump after it which gets executed if it gets matched.
  690.              Adjust that jump so it will jump to the previous
  691.              alternative's analogous jump (put in below, which in
  692.              turn will jump to the next (if any) alternative's such
  693.              jump, etc.).  The last such jump jumps to the correct
  694.              final destination.  */
  695.           if (fixup_jump)
  696.         store_jump (fixup_jump, jump, b);
  697.  
  698.       /* Leave space for a jump after previous alternative---to be 
  699.              filled in later.  */
  700.           fixup_jump = b;
  701.           b += 3;
  702.  
  703.           laststart = 0;
  704.       begalt = b;
  705.       break;
  706.  
  707.     case '{':
  708.       beg_interval = p - 1;        /* The {.  */
  709.           /* If there is no previous pattern, this isn't an interval.  */
  710.       if (!laststart)
  711.             goto normal_char;
  712.  
  713.           /* It also isn't an interval if not preceded by an re
  714.              matching a single character or subexpression */
  715.           if (! (*laststart == anychar
  716.          || *laststart == wordchar
  717.          || *laststart == notwordchar
  718.          || *laststart == spacechar
  719.          || *laststart == notspacechar
  720.          || *laststart == digit
  721.          || *laststart == notdigit
  722.          || *laststart == charset
  723.          || *laststart == charset_not
  724.          || *laststart == start_memory
  725.          || *laststart == duplicate
  726.          || (*laststart == exactn && laststart[1] == 1)))
  727.             goto normal_char;
  728.  
  729.           lower_bound = -1;            /* So can see if are set.  */
  730.       upper_bound = -1;
  731.           GET_UNSIGNED_NUMBER (lower_bound);
  732.       if (c == ',')
  733.         {
  734.           GET_UNSIGNED_NUMBER (upper_bound);
  735.           if (upper_bound < 0)
  736.             upper_bound = RE_DUP_MAX;
  737.         }
  738.       if (upper_bound < 0)
  739.         upper_bound = lower_bound;
  740.  
  741.       if (c != '}' || lower_bound < 0 || upper_bound > RE_DUP_MAX
  742.           || lower_bound > upper_bound 
  743.               || (p != pend  && *p == '{'))
  744.             goto unfetch_interval;
  745.  
  746.       /* If upper_bound is zero, don't want to succeed at all; 
  747.           jump from laststart to b + 3, which will be the end of
  748.              the buffer after this jump is inserted.  */
  749.                  
  750.           if (upper_bound == 0)
  751.             {
  752.               GET_BUFFER_SPACE (3);
  753.               insert_jump (jump, laststart, b + 3, b);
  754.               b += 3;
  755.             }
  756.  
  757.           /* Otherwise, after lower_bound number of succeeds, jump
  758.              to after the jump_n which will be inserted at the end
  759.              of the buffer, and insert that jump_n.  */
  760.           else 
  761.         {
  762.           /* Set to 5 if only one repetition is allowed and
  763.              hence no jump_n is inserted at the current end of
  764.                  the buffer; then only space for the succeed_n is
  765.                  needed.  Otherwise, need space for both the
  766.                  succeed_n and the jump_n.  */
  767.                       
  768.               unsigned slots_needed = upper_bound == 1 ? 5 : 10;
  769.                      
  770.               GET_BUFFER_SPACE (slots_needed);
  771.               /* Initialize the succeed_n to n, even though it will
  772.                  be set by its attendant set_number_at, because
  773.                  re_compile_fastmap will need to know it.  Jump to
  774.                  what the end of buffer will be after inserting
  775.                  this succeed_n and possibly appending a jump_n.  */
  776.               insert_jump_n (succeed_n, laststart, b + slots_needed, 
  777.                          b, lower_bound);
  778.               b += 5;     /* Just increment for the succeed_n here.  */
  779.  
  780.           /* More than one repetition is allowed, so put in at
  781.              the end of the buffer a backward jump from b to the
  782.                  succeed_n we put in above.  By the time we've gotten
  783.                  to this jump when matching, we'll have matched once
  784.                  already, so jump back only upper_bound - 1 times.  */
  785.  
  786.               if (upper_bound > 1)
  787.                 {
  788.                   store_jump_n (b, jump_n, laststart, upper_bound - 1);
  789.                   b += 5;
  790.                   /* When hit this when matching, reset the
  791.                      preceding jump_n's n to upper_bound - 1.  */
  792.                   BUFPUSH (set_number_at);
  793.               GET_BUFFER_SPACE (4);
  794.                   STORE_NUMBER_AND_INCR (b, -5);
  795.                   STORE_NUMBER_AND_INCR (b, upper_bound - 1);
  796.                 }
  797.           /* When hit this when matching, set the succeed_n's n.  */
  798.               GET_BUFFER_SPACE (5);
  799.           insert_op_2 (set_number_at, laststart, b, 5, lower_bound);
  800.               b += 5;
  801.             }
  802.           pending_exact = 0;
  803.       beg_interval = 0;
  804.           break;
  805.  
  806.         unfetch_interval:
  807.           /* If an invalid interval, match the characters as literals.  */
  808.           if (beg_interval)
  809.             p = beg_interval;
  810.         else
  811.             {
  812.               fprintf (stderr, 
  813.              "regex: no interval beginning to which to backtrack.\n");
  814.           exit (1);
  815.             }
  816.                  
  817.           beg_interval = 0;
  818.           PATFETCH (c);        /* normal_char expects char in `c'.  */
  819.       goto normal_char;
  820.       break;
  821.  
  822.         case '\\':
  823.       if (p == pend) goto invalid_pattern;
  824.       PATFETCH_RAW (c);
  825.       switch (c)
  826.         {
  827.           /* Single character escapes */
  828.           case 'a':
  829.         c = '\a';
  830.         goto normal_backsl;
  831.  
  832.           case 'f':
  833.         c = '\f';
  834.         goto normal_backsl;
  835.  
  836.           case 'n':
  837.         c = '\n';
  838.         goto normal_backsl;
  839.  
  840.           case 'r':
  841.         c = '\r';
  842.         goto normal_backsl;
  843.  
  844.           case 't':
  845.         c = '\t';
  846.         goto normal_backsl;
  847.  
  848.           case 'v':
  849.         c = '\v';
  850.         goto normal_backsl;
  851.  
  852.           /* Hex or octal escapes */
  853.           case '0':
  854.         if (*p < '0' || *p > '7')
  855.           goto normal_backsl;
  856.  
  857.         PATFETCH_RAW(c1);
  858.         c = c1 - '0';
  859.  
  860.         if (0 <= *p && *p <= '7')
  861.           {
  862.             c <<= 3;
  863.             PATFETCH_RAW(c1);
  864.             c |= c1 - '0';
  865.  
  866.             if (0 <= *p && *p <= '7')
  867.               {
  868.             c <<= 3;
  869.             PATFETCH_RAW(c1);
  870.             c |= c1 - '0';
  871.               }
  872.           }
  873.  
  874.         goto normal_backsl;
  875.  
  876.           case 'x':
  877.         if (!isxdigit(*p))
  878.           goto normal_backsl;
  879.  
  880.         PATFETCH_RAW(c1);
  881.         if (isdigit(c1))
  882.           c = c1 - '0';
  883.         else if (islower(c1))
  884.           c = 10 + c1 - 'a';
  885.         else
  886.           c = 10 + c1 - 'A';
  887.  
  888.         if (isxdigit(*p))
  889.           {
  890.             c <<= 4;
  891.             PATFETCH_RAW(c1);
  892.             if (isdigit(c1))
  893.               c |= c1 - '0';
  894.             else if (islower(c1))
  895.               c |= 10 + c1 - 'a';
  896.             else
  897.               c |= 10 + c1 - 'A';
  898.           }
  899.  
  900.         goto normal_backsl;
  901.  
  902.         /* Character class escapes */
  903.         case 'w':
  904.           laststart = b;
  905.           BUFPUSH (wordchar);
  906.           break;
  907.  
  908.         case 'W':
  909.           laststart = b;
  910.           BUFPUSH (notwordchar);
  911.           break;
  912.  
  913.         case 's':
  914.           laststart = b;
  915.           BUFPUSH (spacechar);
  916.           break;
  917.  
  918.         case 'S':
  919.           laststart = b;
  920.           BUFPUSH (notspacechar);
  921.           break;
  922.  
  923.         case 'd':
  924.           laststart = b;
  925.           BUFPUSH (digit);
  926.           break;
  927.  
  928.         case 'D':
  929.           laststart = b;
  930.           BUFPUSH (notdigit);
  931.           break;
  932.  
  933.         /* Specific buffer positions */
  934.         case 'b':
  935.           BUFPUSH (wordbound);
  936.           break;
  937.  
  938.         case 'B':
  939.           BUFPUSH (notwordbound);
  940.           break;
  941.  
  942.         case '<':
  943.           BUFPUSH (begword);
  944.           break;
  945.  
  946.         case '>':
  947.           BUFPUSH (endword);
  948.           break;
  949.  
  950.         case '`':
  951.           BUFPUSH (begbuf);
  952.           break;
  953.  
  954.         case '\'':
  955.           BUFPUSH (endbuf);
  956.           break;
  957.  
  958.         /* Duplicates of previous matched strings */
  959.         case '1':
  960.         case '2':
  961.         case '3':
  962.         case '4':
  963.         case '5':
  964.         case '6':
  965.         case '7':
  966.         case '8':
  967.         case '9':
  968.               c1 = c - '0';
  969.           if (c1 >= regnum)
  970.                 goto normal_backsl;
  971.  
  972.               /* Can't back reference to a subexpression if inside of it.  */
  973.               for (stackt = stackp - 2;  stackt > stackb;  stackt -= 4)
  974.          if (*stackt == c1)
  975.           goto normal_backsl;
  976.           laststart = b;
  977.           BUFPUSH (duplicate);
  978.           BUFPUSH (c1);
  979.           break;
  980.  
  981.             default:
  982.         normal_backsl:
  983.           /* You might think it would be useful for \ to mean
  984.          not to translate; but if we don't translate it
  985.          it will never match anything.  */
  986.           if (translate) c = translate[c];
  987.           goto normal_char;
  988.         }
  989.       break;
  990.  
  991.     default:
  992.     normal_char:        /* Expects the character in `c'.  */
  993.       if (!pending_exact || pending_exact + *pending_exact + 1 != b
  994.           || *pending_exact == 0177 || *p == '^'
  995.           || *p == '*' || *p == '+' || *p == '?' || *p == '{')
  996.         {
  997.           laststart = b;
  998.           BUFPUSH (exactn);
  999.           pending_exact = b;
  1000.           BUFPUSH (0);
  1001.         }
  1002.       BUFPUSH (c);
  1003.       (*pending_exact)++;
  1004.     }
  1005.     }
  1006.  
  1007.   if (fixup_jump)
  1008.     store_jump (fixup_jump, jump, b);
  1009.  
  1010.   if (stackp != stackb) goto unmatched_open;
  1011.  
  1012.   bufp->used = b - bufp->buffer;
  1013.   return 0;
  1014.  
  1015.  invalid_pattern:
  1016.   return "Invalid regular expression";
  1017.  
  1018.  unmatched_open:
  1019.   return "Unmatched open parenthesis";
  1020.  
  1021.  unmatched_close:
  1022.   return "Unmatched close parenthesis";
  1023.  
  1024.  end_of_pattern:
  1025.   return "Premature end of regular expression";
  1026.  
  1027.  nesting_too_deep:
  1028.   return "Nesting too deep";
  1029.  
  1030.  memory_exhausted:
  1031.   return "Memory exhausted";
  1032. }
  1033.  
  1034. /* Extend the pattern buffer. The buffer allocated size is doubled. If
  1035.    memory is exhausted, a NULL pointer is returned, otherwise the new
  1036.    (relocated) buffer pointer b is returned. */
  1037.  
  1038. static char *extend_buffer (char *b, struct re_pattern_buffer *bufp)
  1039. {
  1040.   char *old_buffer = bufp->buffer;
  1041.  
  1042.   bufp->allocated *= 2;
  1043.   bufp->buffer = (char *) realloc (bufp->buffer, bufp->allocated);
  1044.   if (bufp->buffer == 0)
  1045.     return 0;
  1046.  
  1047.   b = (b - old_buffer) + bufp->buffer;
  1048.  
  1049.   if (fixup_jump)
  1050.     fixup_jump = (fixup_jump - old_buffer) + bufp->buffer;
  1051.   if (laststart)
  1052.     laststart = (laststart - old_buffer) + bufp->buffer;
  1053.   begalt = (begalt - old_buffer) + bufp->buffer;
  1054.   if (pending_exact)
  1055.     pending_exact = (pending_exact - old_buffer) + bufp->buffer;
  1056.  
  1057.   return b;
  1058. }
  1059.  
  1060. /* Store a jump of the form <OPCODE> <relative address>.
  1061.    Store in the location FROM a jump operation to jump to relative
  1062.    address FROM - TO.  OPCODE is the opcode to store.  */
  1063.  
  1064. static void store_jump (char *from, char opcode, char *to)
  1065. {
  1066.   from[0] = opcode;
  1067.   STORE_NUMBER(from + 1, to - (from + 3));
  1068. }
  1069.  
  1070.  
  1071. /* Open up space before char FROM, and insert there a jump to TO.
  1072.    CURRENT_END gives the end of the storage not in use, so we know 
  1073.    how much data to copy up. OP is the opcode of the jump to insert.
  1074.  
  1075.    If you call this function, you must zero out pending_exact.  */
  1076.  
  1077. static void insert_jump (char op, char *from, char *to, char *current_end)
  1078. {
  1079.   register char *pfrom = current_end;        /* Copy from here...  */
  1080.   register char *pto = current_end + 3;        /* ...to here.  */
  1081.  
  1082.   while (pfrom != from)                   
  1083.     *--pto = *--pfrom;
  1084.   store_jump (from, op, to);
  1085. }
  1086.  
  1087.  
  1088. /* Store a jump of the form <opcode> <relative address> <n> .
  1089.  
  1090.    Store in the location FROM a jump operation to jump to relative
  1091.    address FROM - TO.  OPCODE is the opcode to store, N is a number the
  1092.    jump uses, say, to decide how many times to jump.
  1093.    
  1094.    If you call this function, you must zero out pending_exact.  */
  1095.  
  1096. static void store_jump_n (char *from, char opcode, char *to, unsigned int n)
  1097. {
  1098.   from[0] = opcode;
  1099.   STORE_NUMBER (from + 1, to - (from + 3));
  1100.   STORE_NUMBER (from + 3, n);
  1101. }
  1102.  
  1103.  
  1104. /* Similar to insert_jump, but handles a jump which needs an extra
  1105.    number to handle minimum and maximum cases.  Open up space at
  1106.    location FROM, and insert there a jump to TO.  CURRENT_END gives the
  1107.    end of the storage in use, so we know how much data to copy up. OP is
  1108.    the opcode of the jump to insert.
  1109.  
  1110.    If you call this function, you must zero out pending_exact.  */
  1111.  
  1112. static void insert_jump_n (char op, char *from, char *to, char *current_end,
  1113.                unsigned int n)
  1114. {
  1115.   register char *pfrom = current_end;        /* Copy from here...  */
  1116.   register char *pto = current_end + 5;        /* ...to here.  */
  1117.  
  1118.   while (pfrom != from)                   
  1119.     *--pto = *--pfrom;
  1120.   store_jump_n (from, op, to, n);
  1121. }
  1122.  
  1123.  
  1124. /* Open up space at location THERE, and insert operation OP followed by
  1125.    NUM_1 and NUM_2.  CURRENT_END gives the end of the storage in use, so
  1126.    we know how much data to copy up.
  1127.  
  1128.    If you call this function, you must zero out pending_exact.  */
  1129.  
  1130. static void insert_op_2 (char op, char *there, char *current_end,
  1131.              int num_1, int num_2)
  1132. {
  1133.   register char *pfrom = current_end;        /* Copy from here...  */
  1134.   register char *pto = current_end + 5;        /* ...to here.  */
  1135.  
  1136.   while (pfrom != there)                   
  1137.     *--pto = *--pfrom;
  1138.   
  1139.   there[0] = op;
  1140.   STORE_NUMBER (there + 1, num_1);
  1141.   STORE_NUMBER (there + 3, num_2);
  1142. }
  1143.  
  1144. /* Given a pattern, compute a fastmap from it.  The fastmap records
  1145.    which of the CHAR_NUM possible characters can start a string
  1146.    that matches the pattern.  This fastmap is used by re_search to skip
  1147.    quickly over totally implausible text.
  1148.  
  1149.    The caller must supply the address of a CHAR_NUM-byte data 
  1150.    area as bufp->fastmap, or NULL (in which case, re_compile_fastmap
  1151.    will allocate an area, using malloc()).
  1152.    The other components of bufp describe the pattern to be used.  */
  1153.  
  1154. void re_compile_fastmap (struct re_pattern_buffer *bufp)
  1155. {
  1156.   unsigned char *pattern = (unsigned char *) bufp->buffer;
  1157.   size_t size = bufp->used;
  1158.   register char *fastmap = bufp->fastmap;
  1159.   register unsigned char *p = pattern;
  1160.   register unsigned char *pend = pattern + size;
  1161.   register int j, k;
  1162.   unsigned char *translate = (unsigned char *) bufp->translate;
  1163.  
  1164.   unsigned char *stackb[NFAILURES];
  1165.   unsigned char **stackp = stackb;
  1166.  
  1167.   unsigned is_a_succeed_n;
  1168.  
  1169.   bufp->fastmap_accurate = 1;
  1170.  
  1171.   if (fastmap == NULL)
  1172.     {
  1173.       fastmap = malloc(CHAR_NUM);
  1174.  
  1175.       /* If no luck, return without a fastmap (but with fastmap_accurate set,
  1176.      so that callers know we tried).  */
  1177.  
  1178.       if (fastmap == NULL)
  1179.     return;
  1180.  
  1181.       bufp->fastmap = fastmap;
  1182.     }
  1183.  
  1184.   bzero (fastmap, CHAR_NUM);
  1185.   bufp->can_be_null = 0;
  1186.       
  1187.   while (p)
  1188.     {
  1189.       is_a_succeed_n = 0;
  1190.       if (p == pend)
  1191.     {
  1192.       bufp->can_be_null = 1;
  1193.       break;
  1194.     }
  1195.  
  1196.       switch ((enum regexpcode) *p++)
  1197.     {
  1198.     case exactn:
  1199.       if (translate)
  1200.         fastmap[translate[p[1]]] = 1;
  1201.       else
  1202.         fastmap[p[1]] = 1;
  1203.       break;
  1204.  
  1205.         case begline:
  1206.     case begbuf:
  1207.     case endbuf:
  1208.     case begword:
  1209.     case endword:
  1210.     case wordbound:
  1211.     case notwordbound:
  1212.           continue;
  1213.  
  1214.     case endline:
  1215.       if (translate)
  1216.         fastmap[translate['\n']] = 1;
  1217.       else
  1218.         fastmap['\n'] = 1;
  1219.             
  1220.       if (bufp->can_be_null != 1)
  1221.         bufp->can_be_null = 2;
  1222.       break;
  1223.  
  1224.     case jump_n:
  1225.         case finalize_jump:
  1226.     case maybe_finalize_jump:
  1227.     case jump:
  1228.     case dummy_failure_jump:
  1229.           EXTRACT_NUMBER_AND_INCR (j, p);
  1230.       p += j;    
  1231.       if (j > 0)
  1232.         continue;
  1233.           /* Jump backward reached implies we just went through
  1234.          the body of a loop and matched nothing.
  1235.          Opcode jumped to should be an on_failure_jump.
  1236.          Just treat it like an ordinary jump.
  1237.          For a * loop, it has pushed its failure point already;
  1238.          If so, discard that as redundant.  */
  1239.  
  1240.           if ((enum regexpcode) *p != on_failure_jump
  1241.           && (enum regexpcode) *p != succeed_n)
  1242.         continue;
  1243.           p++;
  1244.           EXTRACT_NUMBER_AND_INCR (j, p);
  1245.           p += j;        
  1246.           if (stackp != stackb && *stackp == p)
  1247.             stackp--;
  1248.           continue;
  1249.       
  1250.         case on_failure_jump:
  1251.     handle_on_failure_jump:
  1252.           EXTRACT_NUMBER_AND_INCR (j, p);
  1253.           *++stackp = p + j;
  1254.       if (is_a_succeed_n)
  1255.             EXTRACT_NUMBER_AND_INCR (k, p);    /* Skip the n.  */
  1256.       continue;
  1257.  
  1258.     case succeed_n:
  1259.       is_a_succeed_n = 1;
  1260.           /* Get to the number of times to succeed.  */
  1261.           p += 2;        
  1262.       /* Increment p past the n for when k != 0.  */
  1263.           EXTRACT_NUMBER_AND_INCR (k, p);
  1264.           if (k == 0)
  1265.         {
  1266.               p -= 4;
  1267.               goto handle_on_failure_jump;
  1268.             }
  1269.           continue;
  1270.           
  1271.     case set_number_at:
  1272.           p += 4;
  1273.           continue;
  1274.  
  1275.         case start_memory:
  1276.     case stop_memory:
  1277.       p++;
  1278.       continue;
  1279.  
  1280.     case duplicate:
  1281.       bufp->can_be_null = 1;
  1282.       fastmap['\n'] = 1;
  1283.     case anychar:
  1284.       for (j = 0; j < CHAR_NUM; j++)
  1285.         if (j != '\n')
  1286.           fastmap[j] = 1;
  1287.       if (bufp->can_be_null)
  1288.         return;
  1289.       /* Don't return; check the alternative paths
  1290.          so we can set can_be_null if appropriate.  */
  1291.       break;
  1292.  
  1293.     case wordchar:
  1294.       for (j = 0; j < CHAR_NUM; j++)
  1295.         if (HAS_SYNTAX (j,Sword))
  1296.           fastmap[j] = 1;
  1297.       break;
  1298.  
  1299.     case notwordchar:
  1300.       for (j = 0; j < CHAR_NUM; j++)
  1301.         if (!HAS_SYNTAX (j,Sword))
  1302.           fastmap[j] = 1;
  1303.       break;
  1304.  
  1305.     case spacechar:
  1306.       for (j = 0; j < CHAR_NUM; j++)
  1307.         if (HAS_SYNTAX (j,Sspace))
  1308.           fastmap[j] = 1;
  1309.       break;
  1310.  
  1311.     case notspacechar:
  1312.       for (j = 0; j < CHAR_NUM; j++)
  1313.         if (!HAS_SYNTAX (j,Sspace))
  1314.           fastmap[j] = 1;
  1315.       break;
  1316.  
  1317.     case digit:
  1318.       for (j = 0; j < CHAR_NUM; j++)
  1319.         if (HAS_SYNTAX (j,Sdigit))
  1320.           fastmap[j] = 1;
  1321.       break;
  1322.  
  1323.     case notdigit:
  1324.       for (j = 0; j < CHAR_NUM; j++)
  1325.         if (!HAS_SYNTAX (j,Sdigit))
  1326.           fastmap[j] = 1;
  1327.       break;
  1328.  
  1329.     case charset:
  1330.       for (j = *p++ * CHAR_BIT - 1; j >= 0; j--)
  1331.         if (p[j / CHAR_BIT] & (1 << (j % CHAR_BIT)))
  1332.           {
  1333.         if (translate)
  1334.           fastmap[translate[j]] = 1;
  1335.         else
  1336.           fastmap[j] = 1;
  1337.           }
  1338.       break;
  1339.  
  1340.     case charset_not:
  1341.       /* Chars beyond end of map must be allowed */
  1342.       for (j = *p * CHAR_BIT; j < CHAR_NUM; j++)
  1343.         if (translate)
  1344.           fastmap[translate[j]] = 1;
  1345.         else
  1346.           fastmap[j] = 1;
  1347.  
  1348.       for (j = *p++ * CHAR_BIT - 1; j >= 0; j--)
  1349.         if (!(p[j / CHAR_BIT] & (1 << (j % CHAR_BIT))))
  1350.           {
  1351.         if (translate)
  1352.           fastmap[translate[j]] = 1;
  1353.         else
  1354.           fastmap[j] = 1;
  1355.           }
  1356.       break;
  1357.     }
  1358.  
  1359.       /* Get here means we have successfully found the possible starting
  1360.          characters of one path of the pattern.  We need not follow this
  1361.          path any farther.  Instead, look at the next alternative
  1362.          remembered in the stack.  */
  1363.    if (stackp != stackb)
  1364.     p = *stackp--;
  1365.       else
  1366.     break;
  1367.     }
  1368. }
  1369.  
  1370. #if 0
  1371. /* This is handled by a define in regex.h */
  1372.  
  1373. /* Like re_search_2, below, but only one string is specified, and
  1374.    doesn't let you say where to stop matching. */
  1375.  
  1376. int re_search (struct re_pattern_buffer *pbufp, char *string, int size,
  1377.            int startpos, int range, struct re_registers *regs)
  1378. {
  1379.   return re_search_2 (pbufp, (char *) 0, 0, string, size, startpos, range, 
  1380.               regs, size);
  1381. }
  1382.  
  1383. #endif
  1384.  
  1385. /* Using the compiled pattern in PBUFP->buffer, first tries to match the
  1386.    virtual concatenation of STRING1 and STRING2, starting first at index
  1387.    STARTPOS, then at STARTPOS + 1, and so on.  RANGE is the number of
  1388.    places to try before giving up.  If RANGE is negative, it searches
  1389.    backwards, i.e., the starting positions tried are STARTPOS, STARTPOS
  1390.    - 1, etc.  STRING1 and STRING2 are of SIZE1 and SIZE2, respectively.
  1391.    In REGS, return the indices of the virtual concatenation of STRING1
  1392.    and STRING2 that matched the entire PBUFP->buffer and its contained
  1393.    subexpressions.  Do not consider matching one past the index MSTOP in
  1394.    the virtual concatenation of STRING1 and STRING2.
  1395.  
  1396.    The value returned is the position in the strings at which the match
  1397.    was found, or -1 if no match was found, or -2 if error (such as
  1398.    failure stack overflow).  */
  1399.  
  1400. int re_search_2 (struct re_pattern_buffer *pbufp, char *string1, int size1,
  1401.          char *string2, int size2, int startpos, register int range,
  1402.          struct re_registers *regs, int mstop)
  1403. {
  1404.   register char *fastmap = pbufp->fastmap;
  1405.   register unsigned char *translate = (unsigned char *) pbufp->translate;
  1406.   int total_size = size1 + size2;
  1407.   int endpos = startpos + range;
  1408.   int val;
  1409.  
  1410.   /* Check for out-of-range starting position.  */
  1411.   if (startpos < 0  ||  startpos > total_size)
  1412.     return -1;
  1413.     
  1414.   /* A range of zero means "as far as possible" (use re_match for an
  1415.      anchored match).  */
  1416.   if (range == 0)
  1417.     range = total_size - startpos;
  1418.  
  1419.   /* Fix up range if it would eventually take startpos outside of the
  1420.      virtual concatenation of string1 and string2.  */
  1421.   if (endpos < -1)
  1422.     range = -1 - startpos;
  1423.   else if (endpos > total_size)
  1424.     range = total_size - startpos;
  1425.  
  1426.   /* Update the fastmap now if not correct already.  */
  1427.   if (!pbufp->fastmap_accurate)
  1428.     {
  1429.       re_compile_fastmap (pbufp);
  1430.       /* Re-assign fastmap, in case re_compile_fastmap() allocated it */
  1431.       fastmap = pbufp->fastmap;
  1432.     }
  1433.   
  1434.   /* If the search isn't to be a backwards one, don't waste time in a
  1435.      long search for a pattern that says it is anchored.  */
  1436.   if (pbufp->used > 0 && (enum regexpcode) pbufp->buffer[0] == begbuf
  1437.       && range > 0)
  1438.     {
  1439.       if (startpos > 0)
  1440.     return -1;
  1441.       else
  1442.     range = 1;
  1443.     }
  1444.  
  1445.   while (1)
  1446.     { 
  1447.       /* If a fastmap is supplied, skip quickly over characters that
  1448.          cannot possibly be the start of a match.  Note, however, that
  1449.          if the pattern can possibly match the null string, we must
  1450.          test it at each starting point so that we take the first null
  1451.          string we get.  */
  1452.  
  1453.       if (fastmap && startpos < total_size && pbufp->can_be_null != 1)
  1454.     {
  1455.       if (range > 0)    /* Searching forwards.  */
  1456.         {
  1457.           register int lim = 0;
  1458.           register unsigned char *p;
  1459.           int irange = range;
  1460.           if (startpos < size1 && startpos + range >= size1)
  1461.         lim = range - (size1 - startpos);
  1462.  
  1463.           p = ((unsigned char *)
  1464.            &(startpos >= size1 ? string2 - size1 : string1)[startpos]);
  1465.  
  1466.               while (range > lim && !fastmap[translate 
  1467.                                              ? translate[*p++]
  1468.                                              : *p++])
  1469.             range--;
  1470.           startpos += irange - range;
  1471.         }
  1472.       else                /* Searching backwards.  */
  1473.         {
  1474.           register unsigned char c;
  1475.  
  1476.               if (string1 == 0 || startpos >= size1)
  1477.         c = string2[startpos - size1];
  1478.           else 
  1479.         c = string1[startpos];
  1480.  
  1481.               c &= 0xff;
  1482.           if (translate ? !fastmap[translate[c]] : !fastmap[c])
  1483.         goto advance;
  1484.         }
  1485.     }
  1486.  
  1487.       if (range >= 0 && startpos == total_size
  1488.       && fastmap && pbufp->can_be_null == 0)
  1489.     return -1;
  1490.  
  1491.       val = re_match_2 (pbufp, string1, size1, string2, size2, startpos,
  1492.             regs, mstop);
  1493.       if (val >= 0)
  1494.     return startpos;
  1495.       if (val == -2)
  1496.     return -2;
  1497.  
  1498.     advance:
  1499.       if (!range) 
  1500.         break;
  1501.       else if (range > 0) 
  1502.         {
  1503.           range--; 
  1504.           startpos++;
  1505.         }
  1506.       else
  1507.         {
  1508.           range++; 
  1509.           startpos--;
  1510.         }
  1511.     }
  1512.   return -1;
  1513. }
  1514.  
  1515. #if 0
  1516. /* This is handled by a define in regex.h */
  1517.  
  1518. int re_match (struct re_pattern_buffer *pbufp, char *string, int size,
  1519.           int pos, struct re_registers *regs)
  1520. {
  1521.   return re_match_2 (pbufp, (char *) 0, 0, string, size, pos, regs, size); 
  1522. }
  1523.  
  1524. #endif
  1525.  
  1526. /* The following are used for re_match_2, defined below:  */
  1527.  
  1528. /* Roughly the maximum number of failure points on the stack.  Would be
  1529.    exactly that if always pushed MAX_NUM_FAILURE_ITEMS each time we failed.  */
  1530.    
  1531. int re_max_failures = 2000;
  1532.  
  1533. /* Routine used by re_match_2.  */
  1534. static int bcmp_translate (unsigned char *, unsigned char *, int,
  1535.                unsigned char *);
  1536.  
  1537. /* Structure and accessing macros used in re_match_2:  */
  1538.  
  1539. struct register_info
  1540. {
  1541.   unsigned is_active : 1;
  1542.   unsigned matched_something : 1;
  1543. };
  1544.  
  1545. #define IS_ACTIVE(R)  ((R).is_active)
  1546. #define MATCHED_SOMETHING(R)  ((R).matched_something)
  1547.  
  1548.  
  1549. /* Macros used by re_match_2:  */
  1550.  
  1551. /* I.e., regstart, regend, and reg_info.  */
  1552.  
  1553. #define NUM_REG_ITEMS  3
  1554.  
  1555. /* We push at most this many things on the stack whenever we
  1556.    fail.  The `+ 2' refers to PATTERN_PLACE and STRING_PLACE, which are
  1557.    arguments to the PUSH_FAILURE_POINT macro.  */
  1558.  
  1559. #define MAX_NUM_FAILURE_ITEMS   (RE_NREGS * NUM_REG_ITEMS + 2)
  1560.  
  1561.  
  1562. /* We push this many things on the stack whenever we fail.  */
  1563.  
  1564. #define NUM_FAILURE_ITEMS  (last_used_reg * NUM_REG_ITEMS + 2)
  1565.  
  1566.  
  1567. /* This pushes most of the information about the current state we will want
  1568.    if we ever fail back to it.  */
  1569.  
  1570. #define PUSH_FAILURE_POINT(pattern_place, string_place)            \
  1571.   {                                    \
  1572.     int last_used_reg, this_reg;                    \
  1573.                                     \
  1574.     /* Find out how many registers are active or have been matched.    \
  1575.        (Aside from register zero, which is only set at the end.)  */    \
  1576.     for (last_used_reg = RE_NREGS - 1; last_used_reg > 0; last_used_reg--)\
  1577.       if (regstart[last_used_reg] != (unsigned char *) -1)        \
  1578.         break;                                \
  1579.                                     \
  1580.     if (stacke - stackp < NUM_FAILURE_ITEMS)                \
  1581.       {                                    \
  1582.     void **stackx;                            \
  1583.     if (stacke - stackb > re_max_failures * MAX_NUM_FAILURE_ITEMS)    \
  1584.       {                                \
  1585.         free (stackb);                        \
  1586.         return -2;                            \
  1587.       }                                \
  1588.                                     \
  1589.         /* Roughly double the size of the stack.  */            \
  1590.         stackx = (void **) malloc (2 * MAX_NUM_FAILURE_ITEMS        \
  1591.                          * (stacke - stackb)        \
  1592.                                      * sizeof (void *));        \
  1593.     /* Only copy what is in use.  */                \
  1594.         bcopy (stackb, stackx, (stackp - stackb) * sizeof (void *));    \
  1595.     stackp = stackx + (stackp - stackb);                \
  1596.     free (stackb);                            \
  1597.     stackb = stackx;                        \
  1598.     stacke = stackb + 2 * MAX_NUM_FAILURE_ITEMS * (stacke - stackb);\
  1599.       }                                    \
  1600.                                     \
  1601.     /* Now push the info for each of those registers.  */        \
  1602.     for (this_reg = 1; this_reg <= last_used_reg; this_reg++)        \
  1603.       {                                    \
  1604.         *stackp++ = regstart[this_reg];                    \
  1605.         *stackp++ = regend[this_reg];                    \
  1606.         *stackp++ = ®_info[this_reg];                \
  1607.       }                                    \
  1608.                                     \
  1609.     /* Push how many registers we saved.  */                \
  1610.     stack_hack.num = last_used_reg;                    \
  1611.     *stackp++ = stack_hack.ptr;                        \
  1612.                                     \
  1613.     *stackp++ = pattern_place;                                          \
  1614.     *stackp++ = string_place;                                           \
  1615.   }
  1616.   
  1617.  
  1618. /* This pops what PUSH_FAILURE_POINT pushes.  */
  1619.  
  1620. #define POP_FAILURE_POINT()                        \
  1621.   {                                    \
  1622.     int temp;                                \
  1623.     stackp -= 2;        /* Remove failure points.  */        \
  1624.     stack_hack.ptr = *--stackp;                        \
  1625.     temp = stack_hack.num;    /* How many regs pushed.  */            \
  1626.     temp *= NUM_REG_ITEMS;    /* How much to take off the stack.  */    \
  1627.     stackp -= temp;         /* Remove the register info.  */    \
  1628.   }
  1629.  
  1630.  
  1631. #define MATCHING_IN_FIRST_STRING  (dend == end_match_1)
  1632.  
  1633. /* Is true if there is a first string and if PTR is pointing anywhere
  1634.    inside it or just past the end.  */
  1635.    
  1636. #define IS_IN_FIRST_STRING(ptr)                     \
  1637.     (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
  1638.  
  1639. /* Call before fetching a character with *d.  This switches over to
  1640.    string2 if necessary.  */
  1641.  
  1642. #define PREFETCH                            \
  1643.  while (d == dend)                                \
  1644.   {                                    \
  1645.     /* end of string2 => fail.  */                    \
  1646.     if (dend == end_match_2)                         \
  1647.       goto fail;                            \
  1648.     /* end of string1 => advance to string2.  */             \
  1649.     d = string2;                                \
  1650.     dend = end_match_2;                            \
  1651.   }
  1652.  
  1653.  
  1654. /* Call this when have matched something; it sets `matched' flags for the
  1655.    registers corresponding to the subexpressions of which we currently
  1656.    are inside.  */
  1657. #define SET_REGS_MATCHED                         \
  1658.   { unsigned this_reg;                             \
  1659.     for (this_reg = 0; this_reg < RE_NREGS; this_reg++)         \
  1660.       {                                 \
  1661.         if (IS_ACTIVE(reg_info[this_reg]))                \
  1662.           MATCHED_SOMETHING(reg_info[this_reg]) = 1;            \
  1663.         else                                \
  1664.           MATCHED_SOMETHING(reg_info[this_reg]) = 0;            \
  1665.       }                                 \
  1666.   }
  1667.  
  1668. /* Test if at very beginning or at very end of the virtual concatenation
  1669.    of string1 and string2.  If there is only one string, we've put it in
  1670.    string2.  */
  1671.  
  1672. #define AT_STRINGS_BEG  (d == (size1 ? string1 : string2)  ||  !size2)
  1673. #define AT_STRINGS_END  (d == end2)    
  1674.  
  1675. /* Test for a word boundary */
  1676.  
  1677. #define IS_A_LETTER(d)    \
  1678.   (HAS_SYNTAX (CURRENT_CHAR(d),Sword))
  1679.  
  1680. #define AT_WORD_BEG                            \
  1681.   (AT_STRINGS_BEG || (!IS_A_LETTER (d - 1) && IS_A_LETTER (d)))
  1682.  
  1683. #define AT_WORD_END                            \
  1684.   (AT_STRINGS_END || (IS_A_LETTER (d - 1) && !IS_A_LETTER (d)))
  1685.  
  1686. #define AT_WORD_BOUNDARY                        \
  1687.   (AT_STRINGS_BEG || AT_STRINGS_END || IS_A_LETTER (d - 1) != IS_A_LETTER (d))
  1688.  
  1689. /* We have two special cases to check for: 
  1690.      1) if we're past the end of string1, we have to look at the first
  1691.         character in string2;
  1692.      2) if we're before the beginning of string2, we have to look at the
  1693.         last character in string1; we assume there is a string1, so use
  1694.         this in conjunction with AT_STRINGS_BEG.  */
  1695.  
  1696. #define CURRENT_CHAR(d) \
  1697.   ((d) == end1 ? *string2 : (d) == string2 - 1 ? *(end1 - 1) : *(d))
  1698.  
  1699. /* Match the pattern described by PBUFP against the virtual
  1700.    concatenation of STRING1 and STRING2, which are of SIZE1 and SIZE2,
  1701.    respectively.  Start the match at index POS in the virtual
  1702.    concatenation of STRING1 and STRING2.  In REGS, return the indices of
  1703.    the virtual concatenation of STRING1 and STRING2 that matched the
  1704.    entire PBUFP->buffer and its contained subexpressions.  Do not
  1705.    consider matching one past the index MSTOP in the virtual
  1706.    concatenation of STRING1 and STRING2.
  1707.  
  1708.    If pbufp->fastmap is nonzero, then it had better be up to date.
  1709.  
  1710.    The reason that the data to match are specified as two components
  1711.    which are to be regarded as concatenated is so this function can be
  1712.    used directly on the contents of an Emacs buffer.
  1713.  
  1714.    -1 is returned if there is no match.  -2 is returned if there is an
  1715.    error (such as match stack overflow).  Otherwise the value is the
  1716.    length of the substring which was matched.  */
  1717.  
  1718. int re_match_2 (struct re_pattern_buffer *pbufp, char *string1_arg, int size1,
  1719.         char *string2_arg, int size2, int pos,
  1720.         struct re_registers *regs, int mstop)
  1721. {
  1722.   register unsigned char *p = (unsigned char *) pbufp->buffer;
  1723.  
  1724.   /* Pointer to beyond end of buffer.  */
  1725.   register unsigned char *pend = p + pbufp->used;
  1726.  
  1727.   unsigned char *string1 = (unsigned char *) string1_arg;
  1728.   unsigned char *string2 = (unsigned char *) string2_arg;
  1729.   unsigned char *end1;        /* Just past end of first string.  */
  1730.   unsigned char *end2;        /* Just past end of second string.  */
  1731.  
  1732.   /* Pointers into string1 and string2, just past the last characters in
  1733.      each to consider matching.  */
  1734.   unsigned char *end_match_1, *end_match_2;
  1735.  
  1736.   register unsigned char *d, *dend;
  1737.   register int mcnt;            /* Multipurpose.  */
  1738.   unsigned char *translate = (unsigned char *) pbufp->translate;
  1739.   unsigned is_a_jump_n = 0;
  1740.  
  1741.  /* Failure point stack.  Each place that can handle a failure further
  1742.     down the line pushes a failure point on this stack.  It consists of
  1743.     restart, regend, and reg_info for all registers corresponding to the
  1744.     subexpressions we're currently inside, plus the number of such
  1745.     registers, and, finally, two char *'s.  The first char * is where to
  1746.     resume scanning the pattern; the second one is where to resume
  1747.     scanning the strings.  If the latter is zero, the failure point is a
  1748.     ``dummy''; if a failure happens and the failure point is a dummy, it
  1749.     gets discarded and the next next one is tried.  */
  1750.  
  1751.   void **stackb;
  1752.   void **stackp;
  1753.   void **stacke;
  1754.  
  1755.  
  1756.   /* Information on the contents of registers. These are pointers into
  1757.      the input strings; they record just what was matched (on this
  1758.      attempt) by a subexpression part of the pattern, that is, the
  1759.      regnum-th regstart pointer points to where in the pattern we began
  1760.      matching and the regnum-th regend points to right after where we
  1761.      stopped matching the regnum-th subexpression.  (The zeroth register
  1762.      keeps track of what the whole pattern matches.)  */
  1763.      
  1764.   unsigned char *regstart[RE_NREGS];
  1765.   unsigned char *regend[RE_NREGS];
  1766.  
  1767.   /* The is_active field of reg_info helps us keep track of which (possibly
  1768.      nested) subexpressions we are currently in. The matched_something
  1769.      field of reg_info[reg_num] helps us tell whether or not we have
  1770.      matched any of the pattern so far this time through the reg_num-th
  1771.      subexpression.  These two fields get reset each time through any
  1772.      loop their register is in.  */
  1773.  
  1774.   struct register_info reg_info[RE_NREGS];
  1775.  
  1776.  
  1777.   /* The following record the register info as found in the above
  1778.      variables when we find a match better than any we've seen before. 
  1779.      This happens as we backtrack through the failure points, which in
  1780.      turn happens only if we have not yet matched the entire string.  */
  1781.  
  1782.   unsigned best_regs_set = 0;
  1783.   unsigned char *best_regstart[RE_NREGS];
  1784.   unsigned char *best_regend[RE_NREGS];
  1785.  
  1786.   /* The following union is a hack to allow us to push the number of registers
  1787.      used (last_used_reg) onto the stack. The stack could be a union, but this
  1788.      way is probably a bit clearer... */
  1789.  
  1790.   union
  1791.     {
  1792.       void *ptr;
  1793.       int num;
  1794.     }
  1795.   stack_hack;
  1796.  
  1797.   /* Initialise the failure point stack */
  1798.   stackb = malloc(MAX_NUM_FAILURE_ITEMS * NFAILURES * sizeof(void *));
  1799.   if (stackb == NULL)
  1800.     return -2;
  1801.  
  1802.   stackp = stackb;
  1803.   stacke = &stackb[MAX_NUM_FAILURE_ITEMS * NFAILURES];
  1804.  
  1805.   /* Initialize subexpression text positions to -1 to mark ones that no
  1806.      ( and ) has been seen for. Also set all registers to inactive
  1807.      and mark them as not having matched anything or ever failed */
  1808.   for (mcnt = 0; mcnt < RE_NREGS; mcnt++)
  1809.     {
  1810.       regstart[mcnt] = regend[mcnt] = (unsigned char *) -1;
  1811.       IS_ACTIVE (reg_info[mcnt]) = 0;
  1812.       MATCHED_SOMETHING (reg_info[mcnt]) = 0;
  1813.     }
  1814.   
  1815.   if (regs)
  1816.     for (mcnt = 0; mcnt < RE_NREGS; mcnt++)
  1817.       regs->start[mcnt] = regs->end[mcnt] = -1;
  1818.  
  1819.   /* Set up pointers to ends of strings.
  1820.      Don't allow the second string to be empty unless both are empty.  */
  1821.   if (size2 == 0)
  1822.     {
  1823.       string2 = string1;
  1824.       size2 = size1;
  1825.       string1 = 0;
  1826.       size1 = 0;
  1827.     }
  1828.   end1 = string1 + size1;
  1829.   end2 = string2 + size2;
  1830.  
  1831.   /* Compute where to stop matching, within the two strings.  */
  1832.   if (mstop <= size1)
  1833.     {
  1834.       end_match_1 = string1 + mstop;
  1835.       end_match_2 = string2;
  1836.     }
  1837.   else
  1838.     {
  1839.       end_match_1 = end1;
  1840.       end_match_2 = string2 + mstop - size1;
  1841.     }
  1842.  
  1843.   /* `p' scans through the pattern as `d' scans through the data. `dend'
  1844.      is the end of the input string that `d' points within. `d' is
  1845.      advanced into the following input string whenever necessary, but
  1846.      this happens before fetching; therefore, at the beginning of the
  1847.      loop, `d' can be pointing at the end of a string, but it cannot
  1848.      equal string2.  */
  1849.  
  1850.   if (size1 != 0 && pos <= size1)
  1851.     d = string1 + pos, dend = end_match_1;
  1852.   else
  1853.     d = string2 + pos - size1, dend = end_match_2;
  1854.  
  1855.  
  1856.   /* This loops over pattern commands.  It exits by returning from the
  1857.      function if match is complete, or it drops through if match fails
  1858.      at this starting point in the input data.  */
  1859.  
  1860.   while (1)
  1861.     {
  1862.       is_a_jump_n = 0;
  1863.       /* End of pattern means we might have succeeded.  */
  1864.       if (p == pend)
  1865.     {
  1866.       /* If not end of string, try backtracking.  Otherwise done.  */
  1867.           if (d != end_match_2)
  1868.         {
  1869.               if (stackp != stackb)
  1870.                 {
  1871.                   /* More failure points to try.  */
  1872.  
  1873.                   unsigned in_same_string = 
  1874.                           IS_IN_FIRST_STRING (best_regend[0]) 
  1875.                         == MATCHING_IN_FIRST_STRING;
  1876.  
  1877.                   /* If exceeds best match so far, save it.  */
  1878.                   if (! best_regs_set
  1879.                       || (in_same_string && d > best_regend[0])
  1880.                       || (! in_same_string && ! MATCHING_IN_FIRST_STRING))
  1881.                     {
  1882.                       best_regs_set = 1;
  1883.                       best_regend[0] = d;    /* Never use regstart[0].  */
  1884.                       
  1885.                       for (mcnt = 1; mcnt < RE_NREGS; mcnt++)
  1886.                         {
  1887.                           best_regstart[mcnt] = regstart[mcnt];
  1888.                           best_regend[mcnt] = regend[mcnt];
  1889.                         }
  1890.                     }
  1891.                   goto fail;           
  1892.                 }
  1893.               /* If no failure points, don't restore garbage.  */
  1894.               else if (best_regs_set)   
  1895.                 {
  1896.           restore_best_regs:
  1897.                   /* Restore best match.  */
  1898.                   d = best_regend[0];
  1899.                   
  1900.           for (mcnt = 0; mcnt < RE_NREGS; mcnt++)
  1901.             {
  1902.               regstart[mcnt] = best_regstart[mcnt];
  1903.               regend[mcnt] = best_regend[mcnt];
  1904.             }
  1905.                 }
  1906.             }
  1907.  
  1908.       /* If caller wants register contents data back, convert it 
  1909.          to indices.  */
  1910.       if (regs)
  1911.         {
  1912.           regs->start[0] = pos;
  1913.           if (MATCHING_IN_FIRST_STRING)
  1914.         regs->end[0] = d - string1;
  1915.           else
  1916.         regs->end[0] = d - string2 + size1;
  1917.           for (mcnt = 1; mcnt < RE_NREGS; mcnt++)
  1918.         {
  1919.           if (regend[mcnt] == (unsigned char *) -1)
  1920.             {
  1921.               regs->start[mcnt] = -1;
  1922.               regs->end[mcnt] = -1;
  1923.               continue;
  1924.             }
  1925.           if (IS_IN_FIRST_STRING (regstart[mcnt]))
  1926.             regs->start[mcnt] = regstart[mcnt] - string1;
  1927.           else
  1928.             regs->start[mcnt] = regstart[mcnt] - string2 + size1;
  1929.                     
  1930.           if (IS_IN_FIRST_STRING (regend[mcnt]))
  1931.             regs->end[mcnt] = regend[mcnt] - string1;
  1932.           else
  1933.             regs->end[mcnt] = regend[mcnt] - string2 + size1;
  1934.         }
  1935.         }
  1936.       free (stackb);
  1937.       return d - pos - (MATCHING_IN_FIRST_STRING 
  1938.                 ? string1 
  1939.                 : string2 - size1);
  1940.         }
  1941.  
  1942.       /* Otherwise match next pattern command.  */
  1943.       switch ((enum regexpcode) *p++)
  1944.     {
  1945.  
  1946.     /* ( is represented by start_memory, ) by stop_memory.  Both of
  1947.        those commands are followed by a register number in the next
  1948.        byte.  The text matched within the ( and ) is recorded under
  1949.        that number.  */
  1950.     case start_memory:
  1951.           regstart[*p] = d;
  1952.           IS_ACTIVE (reg_info[*p]) = 1;
  1953.           MATCHED_SOMETHING (reg_info[*p]) = 0;
  1954.           p++;
  1955.           break;
  1956.  
  1957.     case stop_memory:
  1958.           regend[*p] = d;
  1959.           IS_ACTIVE (reg_info[*p]) = 0;
  1960.  
  1961.           /* If just failed to match something this time around with a sub-
  1962.          expression that's in a loop, try to force exit from the loop.  */
  1963.           if ((! MATCHED_SOMETHING (reg_info[*p])
  1964.            || (enum regexpcode) p[-3] == start_memory)
  1965.           && (p + 1) != pend)              
  1966.             {
  1967.           register unsigned char *p2 = p + 1;
  1968.               mcnt = 0;
  1969.               switch (*p2++)
  1970.                 {
  1971.                   case jump_n:
  1972.             is_a_jump_n = 1;
  1973.                   case finalize_jump:
  1974.           case maybe_finalize_jump:
  1975.           case jump:
  1976.           case dummy_failure_jump:
  1977.                     EXTRACT_NUMBER_AND_INCR (mcnt, p2);
  1978.             if (is_a_jump_n)
  1979.               p2 += 2;
  1980.                     break;
  1981.                 }
  1982.           p2 += mcnt;
  1983.         
  1984.               /* If the next operation is a jump backwards in the pattern
  1985.              to an on_failure_jump, exit from the loop by forcing a
  1986.                  failure after pushing on the stack the on_failure_jump's 
  1987.                  jump in the pattern, and d.  */
  1988.           if (mcnt < 0 && (enum regexpcode) *p2++ == on_failure_jump)
  1989.         {
  1990.                   EXTRACT_NUMBER_AND_INCR (mcnt, p2);
  1991.                   PUSH_FAILURE_POINT (p2 + mcnt, d);
  1992.                   goto fail;
  1993.                 }
  1994.             }
  1995.           p++;
  1996.           break;
  1997.  
  1998.     /* \<digit> has been turned into a `duplicate' command which is
  1999.            followed by the numeric value of <digit> as the register number.  */
  2000.         case duplicate:
  2001.       {
  2002.         int regno = *p++;   /* Get which register to match against */
  2003.         register unsigned char *d2, *dend2;
  2004.  
  2005.         /* Where in input to try to start matching.  */
  2006.             d2 = regstart[regno];
  2007.             
  2008.             /* Where to stop matching; if both the place to start and
  2009.                the place to stop matching are in the same string, then
  2010.                set to the place to stop, otherwise, for now have to use
  2011.                the end of the first string.  */
  2012.  
  2013.             dend2 = ((IS_IN_FIRST_STRING (regstart[regno]) 
  2014.               == IS_IN_FIRST_STRING (regend[regno]))
  2015.              ? regend[regno] : end_match_1);
  2016.         while (1)
  2017.           {
  2018.         /* If necessary, advance to next segment in register
  2019.                    contents.  */
  2020.         while (d2 == dend2)
  2021.           {
  2022.             if (dend2 == end_match_2) break;
  2023.             if (dend2 == regend[regno]) break;
  2024.             d2 = string2, dend2 = regend[regno];  /* end of string1 => advance to string2. */
  2025.           }
  2026.         /* At end of register contents => success */
  2027.         if (d2 == dend2) break;
  2028.  
  2029.         /* If necessary, advance to next segment in data.  */
  2030.         PREFETCH;
  2031.  
  2032.         /* How many characters left in this segment to match.  */
  2033.         mcnt = dend - d;
  2034.                 
  2035.         /* Want how many consecutive characters we can match in
  2036.                    one shot, so, if necessary, adjust the count.  */
  2037.                 if (mcnt > dend2 - d2)
  2038.           mcnt = dend2 - d2;
  2039.                   
  2040.         /* Compare that many; failure if mismatch, else move
  2041.                    past them.  */
  2042.         if (translate 
  2043.                     ? bcmp_translate (d, d2, mcnt, translate) 
  2044.                     : bcmp (d, d2, mcnt))
  2045.           goto fail;
  2046.         d += mcnt, d2 += mcnt;
  2047.           }
  2048.       }
  2049.       break;
  2050.  
  2051.     case anychar:
  2052.       PREFETCH;      /* Fetch a data character. */
  2053.       /* Match anything but a newline, maybe even a null.  */
  2054.       if ((translate ? translate[*d] : *d) == '\n')
  2055.         goto fail;
  2056.       SET_REGS_MATCHED;
  2057.           d++;
  2058.       break;
  2059.  
  2060.     case charset:
  2061.     case charset_not:
  2062.       {
  2063.         int not = 0;        /* Nonzero for charset_not.  */
  2064.         register int c;
  2065.         if (*(p - 1) == (unsigned char) charset_not)
  2066.           not = 1;
  2067.  
  2068.         PREFETCH;        /* Fetch a data character. */
  2069.  
  2070.         if (translate)
  2071.           c = translate[*d];
  2072.         else
  2073.           c = *d;
  2074.  
  2075.         if (c < *p * CHAR_BIT
  2076.         && p[1 + c / CHAR_BIT] & (1 << (c % CHAR_BIT)))
  2077.           not = !not;
  2078.  
  2079.         p += 1 + *p;
  2080.  
  2081.         if (!not) goto fail;
  2082.         SET_REGS_MATCHED;
  2083.             d++;
  2084.         break;
  2085.       }
  2086.  
  2087.     case begline:
  2088.           if ((size1 != 0 && d == string1)
  2089.               || (size1 == 0 && size2 != 0 && d == string2)
  2090.               || (d && d[-1] == '\n')
  2091.               || (size1 == 0 && size2 == 0))
  2092.             break;
  2093.           else
  2094.             goto fail;
  2095.             
  2096.     case endline:
  2097.       if (d == end2
  2098.           || (d == end1 ? (size2 == 0 || *string2 == '\n') : *d == '\n'))
  2099.         break;
  2100.       goto fail;
  2101.  
  2102.     /* `or' constructs are handled by starting each alternative with
  2103.            an on_failure_jump that points to the start of the next
  2104.            alternative.  Each alternative except the last ends with a
  2105.            jump to the joining point.  (Actually, each jump except for
  2106.            the last one really jumps to the following jump, because
  2107.            tensioning the jumps is a hassle.)  */
  2108.  
  2109.     /* The start of a stupid repeat has an on_failure_jump that points
  2110.        past the end of the repeat text. This makes a failure point so 
  2111.            that on failure to match a repetition, matching restarts past
  2112.            as many repetitions have been found with no way to fail and
  2113.            look for another one.  */
  2114.  
  2115.     /* A smart repeat is similar but loops back to the on_failure_jump
  2116.        so that each repetition makes another failure point.  */
  2117.  
  2118.     case on_failure_jump:
  2119.         on_failure:
  2120.           EXTRACT_NUMBER_AND_INCR (mcnt, p);
  2121.           PUSH_FAILURE_POINT (p + mcnt, d);
  2122.           break;
  2123.  
  2124.     /* The end of a smart repeat has a maybe_finalize_jump back.
  2125.        Change it either to a finalize_jump or an ordinary jump.  */
  2126.     case maybe_finalize_jump:
  2127.           EXTRACT_NUMBER_AND_INCR (mcnt, p);
  2128.       {
  2129.         register unsigned char *p2 = p;
  2130.         /* Compare what follows with the beginning of the repeat.
  2131.            If we can establish that there is nothing that they would
  2132.            both match, we can change to finalize_jump.  */
  2133.         while (p2 + 1 != pend
  2134.            && (*p2 == (unsigned char) stop_memory
  2135.                || *p2 == (unsigned char) start_memory))
  2136.           p2 += 2;                /* Skip over reg number.  */
  2137.         if (p2 == pend)
  2138.           p[-3] = (unsigned char) finalize_jump;
  2139.         else if (*p2 == (unsigned char) exactn
  2140.              || *p2 == (unsigned char) endline)
  2141.           {
  2142.         register int c = *p2 == (unsigned char) endline ? '\n' : p2[2];
  2143.         register unsigned char *p1 = p + mcnt;
  2144.         /* p1[0] ... p1[2] are an on_failure_jump.
  2145.            Examine what follows that.  */
  2146.         if (p1[3] == (unsigned char) exactn && p1[5] != c)
  2147.           p[-3] = (unsigned char) finalize_jump;
  2148.         else if (p1[3] == (unsigned char) charset
  2149.              || p1[3] == (unsigned char) charset_not)
  2150.           {
  2151.             int not = p1[3] == (unsigned char) charset_not;
  2152.             if (c < p1[4] * CHAR_BIT
  2153.             && p1[5 + c / CHAR_BIT] & (1 << (c % CHAR_BIT)))
  2154.               not = !not;
  2155.             /* `not' is 1 if c would match.  */
  2156.             /* That means it is not safe to finalize.  */
  2157.             if (!not)
  2158.               p[-3] = (unsigned char) finalize_jump;
  2159.           }
  2160.           }
  2161.       }
  2162.       p -= 2;        /* Point at relative address again.  */
  2163.       if (p[-1] != (unsigned char) finalize_jump)
  2164.         {
  2165.           p[-1] = (unsigned char) jump;    
  2166.           goto nofinalize;
  2167.         }
  2168.         /* Note fall through.  */
  2169.  
  2170.     /* The end of a stupid repeat has a finalize_jump back to the
  2171.            start, where another failure point will be made which will
  2172.            point to after all the repetitions found so far.  */
  2173.  
  2174.         /* Take off failure points put on by matching on_failure_jump 
  2175.            because didn't fail.  Also remove the register information
  2176.            put on by the on_failure_jump.  */
  2177.         case finalize_jump:
  2178.           POP_FAILURE_POINT ();
  2179.         /* Note fall through.  */
  2180.         
  2181.     /* Jump without taking off any failure points.  */
  2182.         case jump:
  2183.     nofinalize:
  2184.       EXTRACT_NUMBER_AND_INCR (mcnt, p);
  2185.       p += mcnt;
  2186.       break;
  2187.  
  2188.         case dummy_failure_jump:
  2189.           /* Normally, the on_failure_jump pushes a failure point, which
  2190.              then gets popped at finalize_jump.  We will end up at
  2191.              finalize_jump, also, and with a pattern of, say, `a+', we
  2192.              are skipping over the on_failure_jump, so we have to push
  2193.              something meaningless for finalize_jump to pop.  */
  2194.           PUSH_FAILURE_POINT (0, 0);
  2195.           goto nofinalize;
  2196.  
  2197.  
  2198.         /* Have to succeed matching what follows at least n times.  Then
  2199.           just handle like an on_failure_jump.  */
  2200.         case succeed_n: 
  2201.           EXTRACT_NUMBER (mcnt, p + 2);
  2202.           /* Originally, this is how many times we HAVE to succeed.  */
  2203.           if (mcnt)
  2204.             {
  2205.                mcnt--;
  2206.            p += 2;
  2207.                STORE_NUMBER_AND_INCR (p, mcnt);
  2208.             }
  2209.       else if (mcnt == 0)
  2210.             {
  2211.           p[2] = unused;
  2212.               p[3] = unused;
  2213.               goto on_failure;
  2214.             }
  2215.           else
  2216.         { 
  2217.               fprintf (stderr, "regex: the succeed_n's n is not set.\n");
  2218.               exit (1);
  2219.         }
  2220.           break;
  2221.         
  2222.         case jump_n: 
  2223.           EXTRACT_NUMBER (mcnt, p + 2);
  2224.           /* Originally, this is how many times we CAN jump.  */
  2225.           if (mcnt)
  2226.             {
  2227.                mcnt--;
  2228.                STORE_NUMBER(p + 2, mcnt);
  2229.            goto nofinalize;         /* Do the jump without taking off
  2230.                             any failure points.  */
  2231.             }
  2232.           /* If don't have to jump any more, skip over the rest of command.  */
  2233.       else      
  2234.         p += 4;             
  2235.           break;
  2236.         
  2237.     case set_number_at:
  2238.       {
  2239.           register unsigned char *p1;
  2240.  
  2241.             EXTRACT_NUMBER_AND_INCR (mcnt, p);
  2242.             p1 = p + mcnt;
  2243.             EXTRACT_NUMBER_AND_INCR (mcnt, p);
  2244.         STORE_NUMBER (p1, mcnt);
  2245.             break;
  2246.           }
  2247.  
  2248.         /* Ignore these.  Used to ignore the n of succeed_n's which
  2249.            currently have n == 0.  */
  2250.         case unused:
  2251.           break;
  2252.  
  2253.         case wordbound:
  2254.       if (AT_WORD_BOUNDARY)
  2255.         break;
  2256.       goto fail;
  2257.  
  2258.     case notwordbound:
  2259.       if (AT_WORD_BOUNDARY)
  2260.         goto fail;
  2261.       break;
  2262.  
  2263.     case wordchar:
  2264.       PREFETCH;
  2265.           if (!HAS_SYNTAX (CURRENT_CHAR(d),Sword))
  2266.             goto fail;
  2267.       SET_REGS_MATCHED;
  2268.       d++;
  2269.       break;
  2270.       
  2271.     case notwordchar:
  2272.       PREFETCH;
  2273.       if (HAS_SYNTAX (CURRENT_CHAR(d),Sword))
  2274.             goto fail;
  2275.           SET_REGS_MATCHED;
  2276.       d++;
  2277.       break;
  2278.  
  2279.     case spacechar:
  2280.       PREFETCH;
  2281.           if (!HAS_SYNTAX (CURRENT_CHAR(d),Sspace))
  2282.             goto fail;
  2283.       SET_REGS_MATCHED;
  2284.       d++;
  2285.       break;
  2286.       
  2287.     case notspacechar:
  2288.       PREFETCH;
  2289.       if (HAS_SYNTAX (CURRENT_CHAR(d),Sspace))
  2290.             goto fail;
  2291.           SET_REGS_MATCHED;
  2292.       d++;
  2293.       break;
  2294.  
  2295.     case digit:
  2296.       PREFETCH;
  2297.           if (!HAS_SYNTAX (CURRENT_CHAR(d),Sdigit))
  2298.             goto fail;
  2299.       SET_REGS_MATCHED;
  2300.       d++;
  2301.       break;
  2302.       
  2303.     case notdigit:
  2304.       PREFETCH;
  2305.       if (HAS_SYNTAX (CURRENT_CHAR(d),Sdigit))
  2306.             goto fail;
  2307.           SET_REGS_MATCHED;
  2308.       d++;
  2309.       break;
  2310.  
  2311.     case begword:
  2312.           if (AT_WORD_BEG)
  2313.             break;
  2314.           goto fail;
  2315.  
  2316.         case endword:
  2317.       if (AT_WORD_END)
  2318.         break;
  2319.       goto fail;
  2320.  
  2321.     case begbuf:
  2322.           if (AT_STRINGS_BEG)
  2323.             break;
  2324.           goto fail;
  2325.  
  2326.         case endbuf:
  2327.       if (AT_STRINGS_END)
  2328.         break;
  2329.       goto fail;
  2330.  
  2331.     case exactn:
  2332.       /* Match the next few pattern characters exactly.
  2333.          mcnt is how many characters to match.  */
  2334.       mcnt = *p++;
  2335.       /* This is written out as an if-else so we don't waste time
  2336.              testing `translate' inside the loop.  */
  2337.           if (translate)
  2338.         {
  2339.           do
  2340.         {
  2341.           PREFETCH;
  2342.           if (translate[*d++] != *p++) goto fail;
  2343.         }
  2344.           while (--mcnt);
  2345.         }
  2346.       else
  2347.         {
  2348.           do
  2349.         {
  2350.           PREFETCH;
  2351.           if (*d++ != *p++) goto fail;
  2352.         }
  2353.           while (--mcnt);
  2354.         }
  2355.       SET_REGS_MATCHED;
  2356.           break;
  2357.     }
  2358.       continue;  /* Successfully executed one pattern command; keep going.  */
  2359.  
  2360.     /* Jump here if any matching operation fails. */
  2361.     fail:
  2362.       if (stackp != stackb)
  2363.     /* A restart point is known.  Restart there and pop it. */
  2364.     {
  2365.           short last_used_reg, this_reg;
  2366.           
  2367.           /* If this failure point is from a dummy_failure_point, just
  2368.              skip it.  */
  2369.       if (!stackp[-2])
  2370.             {
  2371.               POP_FAILURE_POINT ();
  2372.               goto fail;
  2373.             }
  2374.  
  2375.           d = *--stackp;
  2376.       p = *--stackp;
  2377.           if (d >= string1 && d <= end1)
  2378.         dend = end_match_1;
  2379.           /* Restore register info.  */
  2380.           stack_hack.ptr = *--stackp;
  2381.           last_used_reg = stack_hack.num;
  2382.           
  2383.           /* Make the ones that weren't saved -1 or 0 again.  */
  2384.           for (this_reg = RE_NREGS - 1; this_reg > last_used_reg; this_reg--)
  2385.             {
  2386.               regend[this_reg] = (unsigned char *) -1;
  2387.               regstart[this_reg] = (unsigned char *) -1;
  2388.               IS_ACTIVE (reg_info[this_reg]) = 0;
  2389.               MATCHED_SOMETHING (reg_info[this_reg]) = 0;
  2390.             }
  2391.           
  2392.           /* And restore the rest from the stack.  */
  2393.           for ( ; this_reg > 0; this_reg--)
  2394.             {
  2395.               reg_info[this_reg] = *(struct register_info *) *--stackp;
  2396.               regend[this_reg] = *--stackp;
  2397.               regstart[this_reg] = *--stackp;
  2398.             }
  2399.     }
  2400.       else
  2401.         break;   /* Matching at this starting point really fails.  */
  2402.     }
  2403.  
  2404.   if (best_regs_set)
  2405.     goto restore_best_regs;
  2406.  
  2407.   free (stackb);
  2408.   return -1;                     /* Failure to match.  */
  2409. }
  2410.  
  2411.  
  2412. static int bcmp_translate (unsigned char *s1, unsigned char *s2,
  2413.                register int len, unsigned char *translate)
  2414. {
  2415.   register unsigned char *p1 = s1, *p2 = s2;
  2416.   while (len)
  2417.     {
  2418.       if (translate [*p1++] != translate [*p2++]) return 1;
  2419.       len--;
  2420.     }
  2421.   return 0;
  2422. }
  2423.  
  2424. /* BSD compatibility functions */
  2425.  
  2426. static REGEX *re_comp_buf = NULL;
  2427.  
  2428. char *re_comp (char *s)
  2429. {
  2430.     if (s == NULL)
  2431.     {
  2432.         if (re_comp_buf == NULL)
  2433.             return "No previous regular expression";
  2434.  
  2435.         return 0;
  2436.     }
  2437.  
  2438.     if (re_comp_buf == NULL)
  2439.     {
  2440.         if ((re_comp_buf = re_create(0)) == NULL)
  2441.             return "Memory exhausted";
  2442.     }
  2443.  
  2444.     return re_compile_pattern (s, strlen (s), re_comp_buf);
  2445. }
  2446.  
  2447. int re_exec (char *s)
  2448. {
  2449.     int len = strlen (s);
  2450.     return (re_search (re_comp_buf, s, len, 0, len, NULL) >= 0);
  2451. }
  2452.  
  2453. /* REGEX buffer allocation and deallocation functions */
  2454.  
  2455. /* Set up a regular expression buffer.
  2456.  * The user can supply a translation table. If one is not required, NULL
  2457.  * should be passed. The function returns a pointer to the regex buffer,
  2458.  * or NULL if the allocation failed.
  2459.  */
  2460.  
  2461. REGEX *re_create (const char *translate)
  2462. {
  2463.     REGEX *re = malloc(sizeof(REGEX));
  2464.  
  2465.     if (re == NULL)
  2466.         return NULL;
  2467.  
  2468.     /* Initialise the fields (note that if we cannot allocate a fastmap,
  2469.      * we don't care as NULL is valid, signifying not to use a fastmap).
  2470.      */
  2471.  
  2472.     re->buffer = 0;            /* Allocate when needed */
  2473.     re->allocated = 0;        /* Not yet set up */
  2474.     re->used = 0;            /* Currently empty */
  2475.     re->translate = translate;    /* User supplied translation table */
  2476.     re->fastmap = malloc(CHAR_NUM);    /* Set up fastmap (if we can) */
  2477.     re->fastmap_accurate = 0;    /* Not accurate yet */
  2478.     re->can_be_null = 0;        /* We don't know yet */
  2479.  
  2480.     return re;
  2481. }
  2482.  
  2483. /* Delete a regular expression buffer.
  2484.  * Any memory allocated by the system for the regular expression buffer
  2485.  * will automatically be freed. A user-supplied translation table, if
  2486.  * supplied, must be cleared by the user if necessary.
  2487.  */
  2488.  
  2489. void re_free (REGEX *re)
  2490. {
  2491.     if (re->buffer)
  2492.         free(re->buffer);
  2493.  
  2494.     if (re->fastmap)
  2495.         free(re->fastmap);
  2496.  
  2497.     free(re);
  2498. }
  2499.  
  2500. #ifdef test
  2501.  
  2502. /* Indexed by a character, gives the upper case equivalent of the
  2503.    character.  */
  2504.  
  2505. char upcase[0400] = 
  2506.   { 000, 001, 002, 003, 004, 005, 006, 007,
  2507.     010, 011, 012, 013, 014, 015, 016, 017,
  2508.     020, 021, 022, 023, 024, 025, 026, 027,
  2509.     030, 031, 032, 033, 034, 035, 036, 037,
  2510.     040, 041, 042, 043, 044, 045, 046, 047,
  2511.     050, 051, 052, 053, 054, 055, 056, 057,
  2512.     060, 061, 062, 063, 064, 065, 066, 067,
  2513.     070, 071, 072, 073, 074, 075, 076, 077,
  2514.     0100, 0101, 0102, 0103, 0104, 0105, 0106, 0107,
  2515.     0110, 0111, 0112, 0113, 0114, 0115, 0116, 0117,
  2516.     0120, 0121, 0122, 0123, 0124, 0125, 0126, 0127,
  2517.     0130, 0131, 0132, 0133, 0134, 0135, 0136, 0137,
  2518.     0140, 0101, 0102, 0103, 0104, 0105, 0106, 0107,
  2519.     0110, 0111, 0112, 0113, 0114, 0115, 0116, 0117,
  2520.     0120, 0121, 0122, 0123, 0124, 0125, 0126, 0127,
  2521.     0130, 0131, 0132, 0173, 0174, 0175, 0176, 0177,
  2522.     0200, 0201, 0202, 0203, 0204, 0205, 0206, 0207,
  2523.     0210, 0211, 0212, 0213, 0214, 0215, 0216, 0217,
  2524.     0220, 0221, 0222, 0223, 0224, 0225, 0226, 0227,
  2525.     0230, 0231, 0232, 0233, 0234, 0235, 0236, 0237,
  2526.     0240, 0241, 0242, 0243, 0244, 0245, 0246, 0247,
  2527.     0250, 0251, 0252, 0253, 0254, 0255, 0256, 0257,
  2528.     0260, 0261, 0262, 0263, 0264, 0265, 0266, 0267,
  2529.     0270, 0271, 0272, 0273, 0274, 0275, 0276, 0277,
  2530.     0300, 0301, 0302, 0303, 0304, 0305, 0306, 0307,
  2531.     0310, 0311, 0312, 0313, 0314, 0315, 0316, 0317,
  2532.     0320, 0321, 0322, 0323, 0324, 0325, 0326, 0327,
  2533.     0330, 0331, 0332, 0333, 0334, 0335, 0336, 0337,
  2534.     0340, 0341, 0342, 0343, 0344, 0345, 0346, 0347,
  2535.     0350, 0351, 0352, 0353, 0354, 0355, 0356, 0357,
  2536.     0360, 0361, 0362, 0363, 0364, 0365, 0366, 0367,
  2537.     0370, 0371, 0372, 0373, 0374, 0375, 0376, 0377
  2538.   };
  2539.  
  2540. /* Routines for test program */
  2541. static void printchar (char);
  2542. static void dump_buffer (struct re_pattern_buffer *);
  2543.  
  2544. /* Use this to run interactive tests.  */
  2545. int main (void)
  2546. {
  2547.   char pat[80];
  2548.   struct re_pattern_buffer buf;
  2549.   struct re_registers regs;
  2550.   int i, j;
  2551.   char *p;
  2552.   char fastmap[CHAR_NUM];
  2553.  
  2554.   buf.allocated = 40;
  2555.   buf.buffer = (char *) malloc (buf.allocated);
  2556.   buf.fastmap = fastmap;
  2557.   buf.translate = upcase;
  2558.  
  2559.   while (1)
  2560.     {
  2561.       printf("Pat> ");
  2562.       fflush(stdout);
  2563.       gets (pat);
  2564.  
  2565.       if (*pat == 0)
  2566.         break;
  2567.  
  2568.       re_compile_pattern (pat, strlen(pat), &buf);
  2569.  
  2570.       printf("\n--------------------------------------------------\n");
  2571.       printf("Buffer: ");
  2572.       for (i = 0; i < buf.used; ++i)
  2573.         printchar(buf.buffer[i]);
  2574.       printf ("\n%d allocated, %d used.\n", buf.allocated, buf.used);
  2575.       printf("--------------------------------------------------\n");
  2576.       re_compile_fastmap (&buf);
  2577.       printf ("Allowed by fastmap: ");
  2578.       for (i = 0; i < CHAR_NUM; i++)
  2579.         if (fastmap[i]) printchar (i);
  2580.       printf("\n--------------------------------------------------\n");
  2581.       dump_buffer (&buf);
  2582.       printf("--------------------------------------------------\n\n");
  2583.  
  2584.       while (1)
  2585.     {
  2586.       printf("Str> ");
  2587.       fflush(stdout);
  2588.       gets (pat);    /* Now read the string to match against */
  2589.       if (*pat == 0)
  2590.         break;
  2591.  
  2592.       i = re_search (&buf, pat, strlen (pat), 0, 0, ®s);
  2593.       j = regs.end[0] - regs.start[0];
  2594.       p = pat + regs.start[0];
  2595.       printf ("Found \"%.*s\" at %d.\n", j, p, i);
  2596.     }
  2597.     }
  2598. }
  2599.  
  2600. static void dump_buffer (struct re_pattern_buffer *bufp)
  2601. {
  2602.   int op;
  2603.   int n, m;
  2604.   char *p = bufp->buffer;
  2605.   char *end = bufp->buffer + bufp->used;
  2606.  
  2607.   while (p < end)
  2608.   {
  2609.     printf("%.8X: ",(unsigned int)p);
  2610.     switch (op = *p++)
  2611.     {
  2612.     case unused:
  2613.       printf("Unused");
  2614.       break;
  2615.     case exactn:
  2616.       n = *p++;
  2617.       printf("Match ");
  2618.       while (n-- > 0)
  2619.     printchar(*p++);
  2620.       break;
  2621.     case begline:
  2622.       printf("Start of line");
  2623.       break;
  2624.     case endline:
  2625.       printf("End of line");
  2626.       break;
  2627.     case jump:
  2628.       EXTRACT_NUMBER_AND_INCR(n,p);
  2629.       printf("Jump to %.8X", (int)(p + n));
  2630.       break;
  2631.     case on_failure_jump:
  2632.       EXTRACT_NUMBER_AND_INCR(n,p);
  2633.       printf("Resume at %.8X on failure", (int)(p + n));
  2634.       break;
  2635.     case finalize_jump:
  2636.       EXTRACT_NUMBER_AND_INCR(n,p);
  2637.       printf("Finalise and jump to %.8X", (int)(p + n));
  2638.       break;
  2639.     case maybe_finalize_jump:
  2640.       EXTRACT_NUMBER_AND_INCR(n,p);
  2641.       printf("Jump to %.8X (finalise if possible)", (int)(p + n));
  2642.       break;
  2643.     case dummy_failure_jump:
  2644.       EXTRACT_NUMBER_AND_INCR(n,p);
  2645.       printf("Jump to %.8X and push a dummy failure", (int)(p + n));
  2646.       break;
  2647.     case succeed_n:
  2648.       EXTRACT_NUMBER_AND_INCR(n,p);
  2649.       EXTRACT_NUMBER_AND_INCR(m,p);
  2650.       printf("Succeed at least %d time%s, then resume at %.8X on failure",
  2651.           m, (m == 1 ? "" : "s"), (int)(p + n - 2));
  2652.       break;
  2653.     case jump_n:
  2654.       EXTRACT_NUMBER_AND_INCR(n,p);
  2655.       EXTRACT_NUMBER_AND_INCR(m,p);
  2656.       printf("Jump to %.8X, %d time%s", (int)(p + n - 2),
  2657.           m, (m == 1 ? "" : "s"));
  2658.       break;
  2659.     case set_number_at:
  2660.       EXTRACT_NUMBER_AND_INCR(n,p);
  2661.       EXTRACT_NUMBER_AND_INCR(m,p);
  2662.       printf("Set the number at %.8X to %d", (int)(p + n - 5), m);
  2663.       break;
  2664.     case anychar:
  2665.       printf("Any character");
  2666.       break;
  2667.     case charset:
  2668.       printf("Character set: ");
  2669.       for (n = *p++ * CHAR_BIT - 1; n >= 0; --n)
  2670.     if (p[n / CHAR_BIT] & (1 << (n % CHAR_BIT)))
  2671.       printchar(n);
  2672.       p += p[-1];
  2673.       break;
  2674.     case charset_not:
  2675.       printf("Negated character set: ");
  2676.       for (n = *p++ * CHAR_BIT - 1; n >= 0; --n)
  2677.     if (p[n / CHAR_BIT] & (1 << (n % CHAR_BIT)))
  2678.       printchar(n);
  2679.       p += p[-1];
  2680.       break;
  2681.     case start_memory:
  2682.       printf("Start memory (%d)", *p++);
  2683.       break;
  2684.     case stop_memory:
  2685.       printf("Stop memory (%d)", *p++);
  2686.       break;
  2687.     case duplicate:
  2688.       printf("Duplicate (%d)", *p++);
  2689.       break;
  2690.     case begword:
  2691.       printf("Start of word");
  2692.       break;
  2693.     case endword:
  2694.       printf("End of word");
  2695.       break;
  2696.     case begbuf:
  2697.       printf("Start of buffer");
  2698.       break;
  2699.     case endbuf:
  2700.       printf("End of buffer");
  2701.       break;
  2702.     case wordchar:
  2703.       printf("Word character");
  2704.       break;
  2705.     case notwordchar:
  2706.       printf("Not word character");
  2707.       break;
  2708.     case spacechar:
  2709.       printf("Space character");
  2710.       break;
  2711.     case notspacechar:
  2712.       printf("Not space character");
  2713.       break;
  2714.     case digit:
  2715.       printf("Digit");
  2716.       break;
  2717.     case notdigit:
  2718.       printf("Not digit");
  2719.       break;
  2720.     case wordbound:
  2721.       printf("Word boundary");
  2722.       break;
  2723.     case notwordbound:
  2724.       printf("Not word boundary");
  2725.       break;
  2726.     default:
  2727.       printf("Unknown code (0x%.2X)",op);
  2728.       break;
  2729.     }
  2730.     putchar('\n');
  2731.   }
  2732. }
  2733.  
  2734. static void printchar (char c)
  2735. {
  2736.     if (!isprint(c))
  2737.     {
  2738.         switch (c)
  2739.         {
  2740.         case '\0':
  2741.             printf("\\0");
  2742.             break;
  2743.         case '\a':
  2744.             printf("\\a");
  2745.             break;
  2746.         case '\b':
  2747.             printf("\\b");
  2748.             break;
  2749.         case '\f':
  2750.             printf("\\f");
  2751.             break;
  2752.         case '\n':
  2753.             printf("\\n");
  2754.             break;
  2755.         case '\r':
  2756.             printf("\\r");
  2757.             break;
  2758.         case '\t':
  2759.             printf("\\t");
  2760.             break;
  2761.         case '\v':
  2762.             printf("\\v");
  2763.             break;
  2764.         default:
  2765.             printf("\\x%.2X",c);
  2766.             break;
  2767.         }
  2768.     }
  2769.     else
  2770.         putchar (c);
  2771. }
  2772. #endif /* test */
  2773.