home *** CD-ROM | disk | FTP | other *** search
/ Club Amiga de Montreal - CAM / CAM_CD_1.iso / files / 419b.lha / GNU_Awk_v2.10_Beta / regex.c < prev    next >
C/C++ Source or Header  |  1990-10-01  |  52KB  |  1,876 lines

  1. /* Extended regular expression matching and search.
  2.    Copyright (C) 1985 Free Software Foundation, Inc.
  3.  
  4.                NO WARRANTY
  5.  
  6.   BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
  7. NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
  8. WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
  9. RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
  10. WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
  11. BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
  13. AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE
  14. DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
  15. CORRECTION.
  16.  
  17.  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
  18. STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
  19. WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
  20. LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
  21. OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
  22. USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
  23. DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
  24. A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
  25. PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
  26. DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
  27.  
  28.         GENERAL PUBLIC LICENSE TO COPY
  29.  
  30.   1. You may copy and distribute verbatim copies of this source file
  31. as you receive it, in any medium, provided that you conspicuously and
  32. appropriately publish on each copy a valid copyright notice "Copyright
  33. (C) 1985 Free Software Foundation, Inc."; and include following the
  34. copyright notice a verbatim copy of the above disclaimer of warranty
  35. and of this License.  You may charge a distribution fee for the
  36. physical act of transferring a copy.
  37.  
  38.   2. You may modify your copy or copies of this source file or
  39. any portion of it, and copy and distribute such modifications under
  40. the terms of Paragraph 1 above, provided that you also do the following:
  41.  
  42.     a) cause the modified files to carry prominent notices stating
  43.     that you changed the files and the date of any change; and
  44.  
  45.     b) cause the whole of any work that you distribute or publish,
  46.     that in whole or in part contains or is a derivative of this
  47.     program or any part thereof, to be licensed at no charge to all
  48.     third parties on terms identical to those contained in this
  49.     License Agreement (except that you may choose to grant more extensive
  50.     warranty protection to some or all third parties, at your option).
  51.  
  52.     c) You may charge a distribution fee for the physical act of
  53.     transferring a copy, and you may at your option offer warranty
  54.     protection in exchange for a fee.
  55.  
  56. Mere aggregation of another unrelated program with this program (or its
  57. derivative) on a volume of a storage or distribution medium does not bring
  58. the other program under the scope of these terms.
  59.  
  60.   3. You may copy and distribute this program (or a portion or derivative
  61. of it, under Paragraph 2) in object code or executable form under the terms
  62. of Paragraphs 1 and 2 above provided that you also do one of the following:
  63.  
  64.     a) accompany it with the complete corresponding machine-readable
  65.     source code, which must be distributed under the terms of
  66.     Paragraphs 1 and 2 above; or,
  67.  
  68.     b) accompany it with a written offer, valid for at least three
  69.     years, to give any third party free (except for a nominal
  70.     shipping charge) a complete machine-readable copy of the
  71.     corresponding source code, to be distributed under the terms of
  72.     Paragraphs 1 and 2 above; or,
  73.  
  74.     c) accompany it with the information you received as to where the
  75.     corresponding source code may be obtained.  (This alternative is
  76.     allowed only for noncommercial distribution and only if you
  77.     received the program in object code or executable form alone.)
  78.  
  79. For an executable file, complete source code means all the source code for
  80. all modules it contains; but, as a special exception, it need not include
  81. source code for modules which are standard libraries that accompany the
  82. operating system on which the executable file runs.
  83.  
  84.   4. You may not copy, sublicense, distribute or transfer this program
  85. except as expressly provided under this License Agreement.  Any attempt
  86. otherwise to copy, sublicense, distribute or transfer this program is void and
  87. your rights to use the program under this License agreement shall be
  88. automatically terminated.  However, parties who have received computer
  89. software programs from you with this License Agreement will not have
  90. their licenses terminated so long as such parties remain in full compliance.
  91.  
  92.   5. If you wish to incorporate parts of this program into other free
  93. programs whose distribution conditions are different, write to the Free
  94. Software Foundation at 675 Mass Ave, Cambridge, MA 02139.  We have not yet
  95. worked out a simple rule that can be stated here, but we will often permit
  96. this.  We will be guided by the two goals of preserving the free status of
  97. all derivatives of our free software and of promoting the sharing and reuse of
  98. software.
  99.  
  100.  
  101. In other words, you are welcome to use, share and improve this program.
  102. You are forbidden to forbid anyone else to use, share and improve
  103. what you give them.   Help stamp out software-hoarding!  */
  104.  
  105. #ifdef MSDOS
  106. #include <malloc.h>
  107. static  void init_syntax_once(void );
  108. extern  int re_set_syntax(int syntax);
  109. extern  char *re_compile_pattern(char *pattern,int size,struct re_pattern_buffer *bufp);
  110. static  int store_jump(char *from,char opcode,char *to);
  111. static  int insert_jump(char op,char *from,char *to,char *current_end);
  112. extern  void re_compile_fastmap(struct re_pattern_buffer *bufp);
  113. extern  int re_search(struct re_pattern_buffer *pbufp,char *string,int size,int startpos,int range,struct re_registers *regs);
  114. extern  int re_search_2(struct re_pattern_buffer *pbufp,char *string1,int size1,char *string2,int size2,int startpos,int range,struct re_registers *regs,int mstop);
  115. extern  int re_match(struct re_pattern_buffer *pbufp,char *string,int size,int pos,struct re_registers *regs);
  116. extern  int re_match_2(struct re_pattern_buffer *pbufp,unsigned char *string1,int size1,unsigned char *string2,int size2,int pos,struct re_registers *regs,int mstop);
  117. static  int bcmp_translate(unsigned char *s1,unsigned char *s2,int len,unsigned char *translate);
  118. extern  char *re_comp(char *s);
  119. extern  int re_exec(char *s);
  120. #endif
  121.  
  122. /* To test, compile with -Dtest.
  123.  This Dtestable feature turns this into a self-contained program
  124.  which reads a pattern, describes how it compiles,
  125.  then reads a string and searches for it.  */
  126.  
  127. #ifdef emacs
  128.  
  129. /* The `emacs' switch turns on certain special matching commands
  130.  that make sense only in emacs. */
  131.  
  132. #include "config.h"
  133. #include "lisp.h"
  134. #include "buffer.h"
  135. #include "syntax.h"
  136.  
  137. #else  /* not emacs */
  138.  
  139. #if defined(USG) || defined(MSDOS)
  140. #define bcopy(s,d,n)    memcpy(d,s,n)
  141. #define bcmp(s1,s2,n)    memcmp(s1,s2,n)
  142. #define bzero(s,n)    memset(s,0,n)
  143. #ifdef MSDOS
  144. #include <malloc.h>
  145. #endif
  146. #endif
  147.  
  148. /* Make alloca work the best possible way.  */
  149. #ifdef __GNUC__
  150. #define alloca __builtin_alloca
  151. #else
  152. #ifdef sparc
  153. #include <alloca.h>
  154. #endif
  155. #endif
  156.  
  157. /*
  158.  * Define the syntax stuff, so we can do the \<...\> things.
  159.  */
  160.  
  161. #ifndef Sword /* must be non-zero in some of the tests below... */
  162. #define Sword 1
  163. #endif
  164.  
  165. #define SYNTAX(c) re_syntax_table[c]
  166.  
  167. #ifdef SYNTAX_TABLE
  168.  
  169. char *re_syntax_table;
  170.  
  171. #else
  172.  
  173. static char re_syntax_table[256];
  174.  
  175. static void
  176. init_syntax_once ()
  177. {
  178.    register int c;
  179.    static int done = 0;
  180.  
  181.    if (done)
  182.      return;
  183.  
  184.    bzero (re_syntax_table, sizeof re_syntax_table);
  185.  
  186.    for (c = 'a'; c <= 'z'; c++)
  187.      re_syntax_table[c] = Sword;
  188.  
  189.    for (c = 'A'; c <= 'Z'; c++)
  190.      re_syntax_table[c] = Sword;
  191.  
  192.    for (c = '0'; c <= '9'; c++)
  193.      re_syntax_table[c] = Sword;
  194.  
  195.    done = 1;
  196. }
  197.  
  198. #endif /* SYNTAX_TABLE */
  199. #endif /* not emacs */
  200.  
  201. #include "regex.h"
  202.  
  203. /* Number of failure points to allocate space for initially,
  204.  when matching.  If this number is exceeded, more space is allocated,
  205.  so it is not a hard limit.  */
  206.  
  207. #ifndef NFAILURES
  208. #define NFAILURES 80
  209. #endif /* NFAILURES */
  210.  
  211. /* width of a byte in bits */
  212.  
  213. #define BYTEWIDTH 8
  214.  
  215. #ifndef SIGN_EXTEND_CHAR
  216. #define SIGN_EXTEND_CHAR(x) (x)
  217. #endif
  218.  
  219. static int obscure_syntax = 0;
  220.  
  221. /* Specify the precise syntax of regexp for compilation.
  222.    This provides for compatibility for various utilities
  223.    which historically have different, incompatible syntaxes.
  224.  
  225.    The argument SYNTAX is a bit-mask containing the two bits
  226.    RE_NO_BK_PARENS and RE_NO_BK_VBAR.  */
  227.  
  228. int
  229. re_set_syntax (syntax)
  230. {
  231.   int ret;
  232.  
  233.   ret = obscure_syntax;
  234.   obscure_syntax = syntax;
  235.   return ret;
  236. }
  237.  
  238. /* re_compile_pattern takes a regular-expression string
  239.    and converts it into a buffer full of byte commands for matching.
  240.  
  241.   PATTERN   is the address of the pattern string
  242.   SIZE      is the length of it.
  243.   BUFP        is a  struct re_pattern_buffer *  which points to the info
  244.         on where to store the byte commands.
  245.         This structure contains a  char *  which points to the
  246.         actual space, which should have been obtained with malloc.
  247.         re_compile_pattern may use  realloc  to grow the buffer space.
  248.  
  249.   The number of bytes of commands can be found out by looking in
  250.   the  struct re_pattern_buffer  that bufp pointed to,
  251.   after re_compile_pattern returns.
  252. */
  253.  
  254. #define PATPUSH(ch) (*b++ = (char) (ch))
  255.  
  256. #define PATFETCH(c) \
  257.  {if (p == pend) goto end_of_pattern; \
  258.   c = * (unsigned char *) p++; \
  259.   if (translate) c = translate[c]; }
  260.  
  261. #define PATFETCH_RAW(c) \
  262.  {if (p == pend) goto end_of_pattern; \
  263.   c = * (unsigned char *) p++; }
  264.  
  265. #define PATUNFETCH p--
  266.  
  267. #ifdef MSDOS
  268. #define MaxAllocation (1<<14)
  269. #else
  270. #define MaxAllocation (1<<16)
  271. #endif
  272. /* The pointer math version is inappropriate for large model, as realloc
  273.    could move stuff off into a different segment somewhere, in which case
  274.    the pointer offsets would be wrong.  At least that's how I think I
  275.    understand it - ADR. */
  276. #ifndef M_I86LM
  277. #define EXTEND_BUFFER \
  278.   { char *old_buffer = bufp->buffer; \
  279.     if (bufp->allocated == MaxAllocation) goto too_big; \
  280.     bufp->allocated *= 2; \
  281.     if (bufp->allocated > MaxAllocation) bufp->allocated = MaxAllocation; \
  282.     if (!(bufp->buffer = (char *) realloc (bufp->buffer, bufp->allocated))) \
  283.       goto memory_exhausted; \
  284.     c = bufp->buffer - old_buffer; \
  285.     b += c; \
  286.     if (fixup_jump) \
  287.       fixup_jump += c; \
  288.     if (laststart) \
  289.       laststart += c; \
  290.     begalt += c; \
  291.     if (pending_exact) \
  292.       pending_exact += c; \
  293.   }
  294. #else
  295. #define EXTEND_BUFFER \
  296.   { unsigned b_off = b - bufp->buffer, \
  297.              f_off, l_off, p_off, \
  298.                 beg_off = begalt - bufp->buffer; \
  299.     if (fixup_jump) \
  300.        f_off = fixup_jump - bufp->buffer; \
  301.     if (laststart) \
  302.        l_off = laststart - bufp->buffer; \
  303.     if (pending_exact) \
  304.        p_off = pending_exact - bufp->buffer; \
  305.     if (bufp->allocated == MaxAllocation) goto too_big; \
  306.     bufp->allocated *= 2; \
  307.     if (bufp->allocated > MaxAllocation) bufp->allocated = MaxAllocation; \
  308.     if (!(bufp->buffer = (char *) realloc (bufp->buffer, bufp->allocated))) \
  309.       goto memory_exhausted; \
  310.     b = bufp->buffer + b_off; \
  311.     if (fixup_jump) \
  312.       fixup_jump = bufp->buffer + f_off; \
  313.     if (laststart) \
  314.       laststart = bufp->buffer + l_off; \
  315.     begalt = bufp->buffer + beg_off; \
  316.     if (pending_exact) \
  317.       pending_exact = bufp->buffer + p_off; \
  318.   }
  319. #endif
  320. static int store_jump (), insert_jump ();
  321.  
  322. char *
  323. re_compile_pattern (pattern, size, bufp)
  324.      char *pattern;
  325.      int size;
  326.      struct re_pattern_buffer *bufp;
  327. {
  328.   register char *b = bufp->buffer;
  329.   register char *p = pattern;
  330.   char *pend = pattern + size;
  331.   register unsigned c, c1;
  332.   char *p1;
  333.   unsigned char *translate = (unsigned char *) bufp->translate;
  334.  
  335.   /* address of the count-byte of the most recently inserted "exactn" command.
  336.     This makes it possible to tell whether a new exact-match character
  337.     can be added to that command or requires a new "exactn" command. */
  338.      
  339.   char *pending_exact = 0;
  340.  
  341.   /* address of the place where a forward-jump should go
  342.     to the end of the containing expression.
  343.     Each alternative of an "or", except the last, ends with a forward-jump
  344.     of this sort. */
  345.  
  346.   char *fixup_jump = 0;
  347.  
  348.   /* address of start of the most recently finished expression.
  349.     This tells postfix * where to find the start of its operand. */
  350.  
  351.   char *laststart = 0;
  352.  
  353.   /* In processing a repeat, 1 means zero matches is allowed */
  354.  
  355.   char zero_times_ok;
  356.  
  357.   /* In processing a repeat, 1 means many matches is allowed */
  358.  
  359.   char many_times_ok;
  360.  
  361.   /* address of beginning of regexp, or inside of last \( */
  362.  
  363.   char *begalt = b;
  364.  
  365.   /* Stack of information saved by \( and restored by \).
  366.      Four stack elements are pushed by each \(:
  367.        First, the value of b.
  368.        Second, the value of fixup_jump.
  369.        Third, the value of regnum.
  370.        Fourth, the value of begalt.  */
  371.  
  372.   int stackb[40];
  373.   int *stackp = stackb;
  374.   int *stacke = stackb + 40;
  375.   int *stackt;
  376.  
  377.   /* Counts \('s as they are encountered.  Remembered for the matching \),
  378.      where it becomes the "register number" to put in the stop_memory command */
  379.  
  380.   int regnum = 1;
  381.  
  382.   bufp->fastmap_accurate = 0;
  383.  
  384. #ifndef emacs
  385. #ifndef SYNTAX_TABLE
  386.   /*
  387.    * Initialize the syntax table.
  388.    */
  389.    init_syntax_once();
  390. #endif
  391. #endif
  392.  
  393.   if (bufp->allocated == 0)
  394.     {
  395.       bufp->allocated = 28;
  396.       if (bufp->buffer)
  397.     /* EXTEND_BUFFER loses when bufp->allocated is 0 */
  398.     bufp->buffer = (char *) realloc (bufp->buffer, 28);
  399.       else
  400.     /* Caller did not allocate a buffer.  Do it for him */
  401.     bufp->buffer = (char *) malloc (28);
  402.       if (!bufp->buffer) goto memory_exhausted;
  403.       begalt = b = bufp->buffer;
  404.     }
  405.  
  406.   while (p != pend)
  407.     {
  408.       if (b - bufp->buffer > bufp->allocated - 10)
  409.     /* Note that EXTEND_BUFFER clobbers c */
  410.     EXTEND_BUFFER;
  411.  
  412.       PATFETCH (c);
  413.  
  414.       switch (c)
  415.     {
  416.     case '$':
  417.       if (obscure_syntax & RE_TIGHT_VBAR)
  418.         {
  419.           if (! (obscure_syntax & RE_CONTEXT_INDEP_OPS) && p != pend)
  420.         goto normal_char;
  421.           /* Make operand of last vbar end before this `$'.  */
  422.           if (fixup_jump)
  423.         store_jump (fixup_jump, jump, b);
  424.           fixup_jump = 0;
  425.           PATPUSH (endline);
  426.           break;
  427.         }
  428.  
  429.       /* $ means succeed if at end of line, but only in special contexts.
  430.         If randomly in the middle of a pattern, it is a normal character. */
  431.       if (p == pend || *p == '\n'
  432.           || (obscure_syntax & RE_CONTEXT_INDEP_OPS)
  433.           || (obscure_syntax & RE_NO_BK_PARENS
  434.           ? *p == ')'
  435.           : *p == '\\' && p[1] == ')')
  436.           || (obscure_syntax & RE_NO_BK_VBAR
  437.           ? *p == '|'
  438.           : *p == '\\' && p[1] == '|'))
  439.         {
  440.           PATPUSH (endline);
  441.           break;
  442.         }
  443.       goto normal_char;
  444.  
  445.     case '^':
  446.       /* ^ means succeed if at beg of line, but only if no preceding pattern. */
  447.  
  448.       if (laststart && p[-2] != '\n'
  449.           && ! (obscure_syntax & RE_CONTEXT_INDEP_OPS))
  450.         goto normal_char;
  451.       if (obscure_syntax & RE_TIGHT_VBAR)
  452.         {
  453.           if (p != pattern + 1
  454.           && ! (obscure_syntax & RE_CONTEXT_INDEP_OPS))
  455.         goto normal_char;
  456.           PATPUSH (begline);
  457.           begalt = b;
  458.         }
  459.       else
  460.         PATPUSH (begline);
  461.       break;
  462.  
  463.     case '+':
  464.     case '?':
  465.       if (obscure_syntax & RE_BK_PLUS_QM)
  466.         goto normal_char;
  467.     handle_plus:
  468.     case '*':
  469.       /* If there is no previous pattern, char not special. */
  470.       if (!laststart && ! (obscure_syntax & RE_CONTEXT_INDEP_OPS))
  471.         goto normal_char;
  472.       /* If there is a sequence of repetition chars,
  473.          collapse it down to equivalent to just one.  */
  474.       zero_times_ok = 0;
  475.       many_times_ok = 0;
  476.       while (1)
  477.         {
  478.           zero_times_ok |= c != '+';
  479.           many_times_ok |= c != '?';
  480.           if (p == pend)
  481.         break;
  482.           PATFETCH (c);
  483.           if (c == '*')
  484.         ;
  485.           else if (!(obscure_syntax & RE_BK_PLUS_QM)
  486.                && (c == '+' || c == '?'))
  487.         ;
  488.           else if ((obscure_syntax & RE_BK_PLUS_QM)
  489.                && c == '\\')
  490.         {
  491.           int c1;
  492.           PATFETCH (c1);
  493.           if (!(c1 == '+' || c1 == '?'))
  494.             {
  495.               PATUNFETCH;
  496.               PATUNFETCH;
  497.               break;
  498.             }
  499.           c = c1;
  500.         }
  501.           else
  502.         {
  503.           PATUNFETCH;
  504.           break;
  505.         }
  506.         }
  507.  
  508.       /* Star, etc. applied to an empty pattern is equivalent
  509.          to an empty pattern.  */
  510.       if (!laststart)
  511.         break;
  512.  
  513.       /* Now we know whether 0 matches is allowed,
  514.          and whether 2 or more matches is allowed.  */
  515.       if (many_times_ok)
  516.         {
  517.           /* If more than one repetition is allowed,
  518.          put in a backward jump at the end.  */
  519.           store_jump (b, maybe_finalize_jump, laststart - 3);
  520.           b += 3;
  521.         }
  522.       insert_jump (on_failure_jump, laststart, b + 3, b);
  523.       pending_exact = 0;
  524.       b += 3;
  525.       if (!zero_times_ok)
  526.         {
  527.           /* At least one repetition required: insert before the loop
  528.          a skip over the initial on-failure-jump instruction */
  529.           insert_jump (dummy_failure_jump, laststart, laststart + 6, b);
  530.           b += 3;
  531.         }
  532.       break;
  533.  
  534.     case '.':
  535.       laststart = b;
  536.       PATPUSH (anychar);
  537.       break;
  538.  
  539.     case '[':
  540.       while (b - bufp->buffer
  541.          > bufp->allocated - 3 - (1 << BYTEWIDTH) / BYTEWIDTH)
  542.         /* Note that EXTEND_BUFFER clobbers c */
  543.         EXTEND_BUFFER;
  544.  
  545.       laststart = b;
  546.       if (*p == '^')
  547.         PATPUSH (charset_not), p++;
  548.       else
  549.         PATPUSH (charset);
  550.       p1 = p;
  551.  
  552.       PATPUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
  553.       /* Clear the whole map */
  554.       bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
  555.       /* Read in characters and ranges, setting map bits */
  556.       while (1)
  557.         {
  558.           PATFETCH (c);
  559.  
  560.           /* If awk, \ escapes a ] when inside [...].  */
  561.           if ((obscure_syntax & RE_AWK_CLASS_HACK)
  562.               && c == '\\' && *p == ']')
  563.             {
  564.               PATFETCH(c1);
  565.               b[c1 / BYTEWIDTH] |= 1 << (c1 % BYTEWIDTH);
  566.               continue;
  567.             }
  568.  
  569.           if (c == ']' && p != p1 + 1) break;
  570.           if (*p == '-' && p[1] != ']')
  571.         {
  572.           PATFETCH (c1);
  573.           PATFETCH (c1);
  574.           while (c <= c1)
  575.             b[c / BYTEWIDTH] |= 1 << (c % BYTEWIDTH), c++;
  576.         }
  577.           else
  578.         {
  579.           b[c / BYTEWIDTH] |= 1 << (c % BYTEWIDTH);
  580.         }
  581.         }
  582.       /* Discard any bitmap bytes that are all 0 at the end of the map.
  583.          Decrement the map-length byte too. */
  584.       while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
  585.         b[-1]--;
  586.       b += b[-1];
  587.       break;
  588.  
  589.     case '(':
  590.       if (! (obscure_syntax & RE_NO_BK_PARENS))
  591.         goto normal_char;
  592.       else
  593.         goto handle_open;
  594.  
  595.     case ')':
  596.       if (! (obscure_syntax & RE_NO_BK_PARENS))
  597.         goto normal_char;
  598.       else
  599.         goto handle_close;
  600.  
  601.     case '\n':
  602.       if (! (obscure_syntax & RE_NEWLINE_OR))
  603.         goto normal_char;
  604.       else
  605.         goto handle_bar;
  606.  
  607.     case '|':
  608.       if (! (obscure_syntax & RE_NO_BK_VBAR))
  609.         goto normal_char;
  610.       else
  611.         goto handle_bar;
  612.  
  613.         case '\\':
  614.       if (p == pend) goto invalid_pattern;
  615.       PATFETCH_RAW (c);
  616.       switch (c)
  617.         {
  618.         case '(':
  619.           if (obscure_syntax & RE_NO_BK_PARENS)
  620.         goto normal_backsl;
  621.         handle_open:
  622.           if (stackp == stacke) goto nesting_too_deep;
  623.           if (regnum < RE_NREGS)
  624.             {
  625.           PATPUSH (start_memory);
  626.           PATPUSH (regnum);
  627.             }
  628.           *stackp++ = b - bufp->buffer;
  629.           *stackp++ = fixup_jump ? fixup_jump - bufp->buffer + 1 : 0;
  630.           *stackp++ = regnum++;
  631.           *stackp++ = begalt - bufp->buffer;
  632.           fixup_jump = 0;
  633.           laststart = 0;
  634.           begalt = b;
  635.           break;
  636.  
  637.         case ')':
  638.           if (obscure_syntax & RE_NO_BK_PARENS)
  639.         goto normal_backsl;
  640.         handle_close:
  641.           if (stackp == stackb) goto unmatched_close;
  642.           begalt = *--stackp + bufp->buffer;
  643.           if (fixup_jump)
  644.         store_jump (fixup_jump, jump, b);
  645.           if (stackp[-1] < RE_NREGS)
  646.         {
  647.           PATPUSH (stop_memory);
  648.           PATPUSH (stackp[-1]);
  649.         }
  650.           stackp -= 2;
  651.           fixup_jump = 0;
  652.           if (*stackp)
  653.         fixup_jump = *stackp + bufp->buffer - 1;
  654.           laststart = *--stackp + bufp->buffer;
  655.           break;
  656.  
  657.         case '|':
  658.           if (obscure_syntax & RE_NO_BK_VBAR)
  659.         goto normal_backsl;
  660.         handle_bar:
  661.           insert_jump (on_failure_jump, begalt, b + 6, b);
  662.           pending_exact = 0;
  663.           b += 3;
  664.           if (fixup_jump)
  665.         store_jump (fixup_jump, jump, b);
  666.           fixup_jump = b;
  667.           b += 3;
  668.           laststart = 0;
  669.           begalt = b;
  670.           break;
  671.  
  672. #ifdef emacs
  673.         case '=':
  674.           PATPUSH (at_dot);
  675.           break;
  676.  
  677.         case 's':    
  678.           laststart = b;
  679.           PATPUSH (syntaxspec);
  680.           PATFETCH (c);
  681.           PATPUSH (syntax_spec_code[c]);
  682.           break;
  683.  
  684.         case 'S':
  685.           laststart = b;
  686.           PATPUSH (notsyntaxspec);
  687.           PATFETCH (c);
  688.           PATPUSH (syntax_spec_code[c]);
  689.           break;
  690. #endif /* emacs */
  691.  
  692.         case 'w':
  693.           laststart = b;
  694.           PATPUSH (wordchar);
  695.           break;
  696.  
  697.         case 'W':
  698.           laststart = b;
  699.           PATPUSH (notwordchar);
  700.           break;
  701.  
  702.         case '<':
  703.           PATPUSH (wordbeg);
  704.           break;
  705.  
  706.         case '>':
  707.           PATPUSH (wordend);
  708.           break;
  709.  
  710.         case 'b':
  711.           PATPUSH (wordbound);
  712.           break;
  713.  
  714.         case 'B':
  715.           PATPUSH (notwordbound);
  716.           break;
  717.  
  718.         case '`':
  719.           PATPUSH (begbuf);
  720.           break;
  721.  
  722.         case '\'':
  723.           PATPUSH (endbuf);
  724.           break;
  725.  
  726.         case '1':
  727.         case '2':
  728.         case '3':
  729.         case '4':
  730.         case '5':
  731.         case '6':
  732.         case '7':
  733.         case '8':
  734.         case '9':
  735.           c1 = c - '0';
  736.           if (c1 >= regnum)
  737.         goto normal_char;
  738.           for (stackt = stackp - 2;  stackt > stackb;  stackt -= 4)
  739.          if (*stackt == c1)
  740.           goto normal_char;
  741.           laststart = b;
  742.           PATPUSH (duplicate);
  743.           PATPUSH (c1);
  744.           break;
  745.  
  746.         case '+':
  747.         case '?':
  748.           if (obscure_syntax & RE_BK_PLUS_QM)
  749.         goto handle_plus;
  750.  
  751.         default:
  752.         normal_backsl:
  753.           /* You might think it would be useful for \ to mean
  754.          not to translate; but if we don't translate it
  755.          it will never match anything.  */
  756.           if (translate) c = translate[c];
  757.           goto normal_char;
  758.         }
  759.       break;
  760.  
  761.     default:
  762.     normal_char:
  763.       if (!pending_exact || pending_exact + *pending_exact + 1 != b
  764.           || *pending_exact == 0177 || *p == '*' || *p == '^'
  765.           || ((obscure_syntax & RE_BK_PLUS_QM)
  766.           ? *p == '\\' && (p[1] == '+' || p[1] == '?')
  767.           : (*p == '+' || *p == '?')))
  768.         {
  769.           laststart = b;
  770.           PATPUSH (exactn);
  771.           pending_exact = b;
  772.           PATPUSH (0);
  773.         }
  774.       PATPUSH (c);
  775.       (*pending_exact)++;
  776.     }
  777.     }
  778.  
  779.   if (fixup_jump)
  780.     store_jump (fixup_jump, jump, b);
  781.  
  782.   if (stackp != stackb) goto unmatched_open;
  783.  
  784.   bufp->used = b - bufp->buffer;
  785.   return 0;
  786.  
  787.  invalid_pattern:
  788.   return "Invalid regular expression";
  789.  
  790.  unmatched_open:
  791.   return "Unmatched \\(";
  792.  
  793.  unmatched_close:
  794.   return "Unmatched \\)";
  795.  
  796.  end_of_pattern:
  797.   return "Premature end of regular expression";
  798.  
  799.  nesting_too_deep:
  800.   return "Nesting too deep";
  801.  
  802.  too_big:
  803.   return "Regular expression too big";
  804.  
  805.  memory_exhausted:
  806.   return "Memory exhausted";
  807. }
  808.  
  809. /* Store where `from' points a jump operation to jump to where `to' points.
  810.   `opcode' is the opcode to store. */
  811.  
  812. static int
  813. store_jump (from, opcode, to)
  814.      char *from, *to;
  815.      char opcode;
  816. {
  817.   from[0] = opcode;
  818.   from[1] = (to - (from + 3)) & 0377;
  819.   from[2] = (to - (from + 3)) >> 8;
  820. }
  821.  
  822. /* Open up space at char FROM, and insert there a jump to TO.
  823.    CURRENT_END gives te end of the storage no in use,
  824.    so we know how much data to copy up.
  825.    OP is the opcode of the jump to insert.
  826.  
  827.    If you call this function, you must zero out pending_exact.  */
  828.  
  829. static int
  830. insert_jump (op, from, to, current_end)
  831.      char op;
  832.      char *from, *to, *current_end;
  833. {
  834.   register char *pto = current_end + 3;
  835.   register char *pfrom = current_end;
  836.   while (pfrom != from)
  837.     *--pto = *--pfrom;
  838.   store_jump (from, op, to);
  839. }
  840.  
  841. /* Given a pattern, compute a fastmap from it.
  842.  The fastmap records which of the (1 << BYTEWIDTH) possible characters
  843.  can start a string that matches the pattern.
  844.  This fastmap is used by re_search to skip quickly over totally implausible text.
  845.  
  846.  The caller must supply the address of a (1 << BYTEWIDTH)-byte data area
  847.  as bufp->fastmap.
  848.  The other components of bufp describe the pattern to be used.  */
  849.  
  850. void
  851. re_compile_fastmap (bufp)
  852.      struct re_pattern_buffer *bufp;
  853. {
  854.   unsigned char *pattern = (unsigned char *) bufp->buffer;
  855.   int size = bufp->used;
  856.   register char *fastmap = bufp->fastmap;
  857.   register unsigned char *p = pattern;
  858.   register unsigned char *pend = pattern + size;
  859.   register int j, k;
  860.   unsigned char *translate = (unsigned char *) bufp->translate;
  861.  
  862.   unsigned char *stackb[NFAILURES];
  863.   unsigned char **stackp = stackb;
  864.  
  865.   bzero (fastmap, (1 << BYTEWIDTH));
  866.   bufp->fastmap_accurate = 1;
  867.   bufp->can_be_null = 0;
  868.       
  869.   while (p)
  870.     {
  871.       if (p == pend)
  872.     {
  873.       bufp->can_be_null = 1;
  874.       break;
  875.     }
  876. #ifdef SWITCH_ENUM_BUG
  877.       switch ((int) ((enum regexpcode) *p++))
  878. #else
  879.       switch ((enum regexpcode) *p++)
  880. #endif
  881.     {
  882.     case exactn:
  883.       if (translate)
  884.         fastmap[translate[p[1]]] = 1;
  885.       else
  886.         fastmap[p[1]] = 1;
  887.       break;
  888.  
  889.         case begline:
  890.         case before_dot:
  891.     case at_dot:
  892.     case after_dot:
  893.     case begbuf:
  894.     case endbuf:
  895.     case wordbound:
  896.     case notwordbound:
  897.     case wordbeg:
  898.     case wordend:
  899.       continue;
  900.  
  901.     case endline:
  902.       if (translate)
  903.         fastmap[translate['\n']] = 1;
  904.       else
  905.         fastmap['\n'] = 1;
  906.       if (bufp->can_be_null != 1)
  907.         bufp->can_be_null = 2;
  908.       break;
  909.  
  910.     case finalize_jump:
  911.     case maybe_finalize_jump:
  912.     case jump:
  913.     case dummy_failure_jump:
  914.       bufp->can_be_null = 1;
  915.       j = *p++ & 0377;
  916.       j += SIGN_EXTEND_CHAR (*(char *)p) << 8;
  917.       p += j + 1;        /* The 1 compensates for missing ++ above */
  918.       if (j > 0)
  919.         continue;
  920.       /* Jump backward reached implies we just went through
  921.          the body of a loop and matched nothing.
  922.          Opcode jumped to should be an on_failure_jump.
  923.          Just treat it like an ordinary jump.
  924.          For a * loop, it has pushed its failure point already;
  925.          if so, discard that as redundant.  */
  926.       if ((enum regexpcode) *p != on_failure_jump)
  927.         continue;
  928.       p++;
  929.       j = *p++ & 0377;
  930.       j += SIGN_EXTEND_CHAR (*(char *)p) << 8;
  931.       p += j + 1;        /* The 1 compensates for missing ++ above */
  932.       if (stackp != stackb && *stackp == p)
  933.         stackp--;
  934.       continue;
  935.       
  936.     case on_failure_jump:
  937.       j = *p++ & 0377;
  938.       j += SIGN_EXTEND_CHAR (*(char *)p) << 8;
  939.       p++;
  940.       *++stackp = p + j;
  941.       continue;
  942.  
  943.     case start_memory:
  944.     case stop_memory:
  945.       p++;
  946.       continue;
  947.  
  948.     case duplicate:
  949.       bufp->can_be_null = 1;
  950.       fastmap['\n'] = 1;
  951.     case anychar:
  952.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  953.         if (j != '\n')
  954.           fastmap[j] = 1;
  955.       if (bufp->can_be_null)
  956.         return;
  957.       /* Don't return; check the alternative paths
  958.          so we can set can_be_null if appropriate.  */
  959.       break;
  960.  
  961.     case wordchar:
  962.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  963.         if (SYNTAX (j) == Sword)
  964.           fastmap[j] = 1;
  965.       break;
  966.  
  967.     case notwordchar:
  968.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  969.         if (SYNTAX (j) != Sword)
  970.           fastmap[j] = 1;
  971.       break;
  972.  
  973. #ifdef emacs
  974.     case syntaxspec:
  975.       k = *p++;
  976.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  977.         if (SYNTAX (j) == (enum syntaxcode) k)
  978.           fastmap[j] = 1;
  979.       break;
  980.  
  981.     case notsyntaxspec:
  982.       k = *p++;
  983.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  984.         if (SYNTAX (j) != (enum syntaxcode) k)
  985.           fastmap[j] = 1;
  986.       break;
  987. #endif /* emacs */
  988.  
  989.     case charset:
  990.       for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
  991.         if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
  992.           {
  993.         if (translate)
  994.           fastmap[translate[j]] = 1;
  995.         else
  996.           fastmap[j] = 1;
  997.           }
  998.       break;
  999.  
  1000.     case charset_not:
  1001.       /* Chars beyond end of map must be allowed */
  1002.       for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
  1003.         if (translate)
  1004.           fastmap[translate[j]] = 1;
  1005.         else
  1006.           fastmap[j] = 1;
  1007.  
  1008.       for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
  1009.         if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
  1010.           {
  1011.         if (translate)
  1012.           fastmap[translate[j]] = 1;
  1013.         else
  1014.           fastmap[j] = 1;
  1015.           }
  1016.       break;
  1017.     }
  1018.  
  1019.       /* Get here means we have successfully found the possible starting characters
  1020.      of one path of the pattern.  We need not follow this path any farther.
  1021.      Instead, look at the next alternative remembered in the stack. */
  1022.       if (stackp != stackb)
  1023.     p = *stackp--;
  1024.       else
  1025.     break;
  1026.     }
  1027. }
  1028.  
  1029. /* Like re_search_2, below, but only one string is specified. */
  1030.  
  1031. int
  1032. re_search (pbufp, string, size, startpos, range, regs)
  1033.      struct re_pattern_buffer *pbufp;
  1034.      char *string;
  1035.      int size, startpos, range;
  1036.      struct re_registers *regs;
  1037. {
  1038.   return re_search_2 (pbufp, 0, 0, string, size, startpos, range, regs, size);
  1039. }
  1040.  
  1041. /* Like re_match_2 but tries first a match starting at index STARTPOS,
  1042.    then at STARTPOS + 1, and so on.
  1043.    RANGE is the number of places to try before giving up.
  1044.    If RANGE is negative, the starting positions tried are
  1045.     STARTPOS, STARTPOS - 1, etc.
  1046.    It is up to the caller to make sure that range is not so large
  1047.    as to take the starting position outside of the input strings.
  1048.  
  1049. The value returned is the position at which the match was found,
  1050.  or -1 if no match was found,
  1051.  or -2 if error (such as failure stack overflow).  */
  1052.  
  1053. int
  1054. re_search_2 (pbufp, string1, size1, string2, size2, startpos, range, regs, mstop)
  1055.      struct re_pattern_buffer *pbufp;
  1056.      char *string1, *string2;
  1057.      int size1, size2;
  1058.      int startpos;
  1059.      register int range;
  1060.      struct re_registers *regs;
  1061.      int mstop;
  1062. {
  1063.   register char *fastmap = pbufp->fastmap;
  1064.   register unsigned char *translate = (unsigned char *) pbufp->translate;
  1065.   int total = size1 + size2;
  1066.   int val;
  1067.  
  1068.   /* Update the fastmap now if not correct already */
  1069.   if (fastmap && !pbufp->fastmap_accurate)
  1070.     re_compile_fastmap (pbufp);
  1071.   
  1072.   /* Don't waste time in a long search for a pattern
  1073.      that says it is anchored.  */
  1074.   if (pbufp->used > 0 && (enum regexpcode) pbufp->buffer[0] == begbuf
  1075.       && range > 0)
  1076.     {
  1077.       if (startpos > 0)
  1078.     return -1;
  1079.       else
  1080.     range = 1;
  1081.     }
  1082.  
  1083.   while (1)
  1084.     {
  1085.       /* If a fastmap is supplied, skip quickly over characters
  1086.      that cannot possibly be the start of a match.
  1087.      Note, however, that if the pattern can possibly match
  1088.      the null string, we must test it at each starting point
  1089.      so that we take the first null string we get.  */
  1090.  
  1091.       if (fastmap && startpos < total && pbufp->can_be_null != 1)
  1092.     {
  1093.       if (range > 0)
  1094.         {
  1095.           register int lim = 0;
  1096.           register unsigned char *p;
  1097.           int irange = range;
  1098.           if (startpos < size1 && startpos + range >= size1)
  1099.         lim = range - (size1 - startpos);
  1100.  
  1101.           p = ((unsigned char *)
  1102.            &(startpos >= size1 ? string2 - size1 : string1)[startpos]);
  1103.  
  1104.           if (translate)
  1105.         {
  1106.           while (range > lim && !fastmap[translate[*p++]])
  1107.             range--;
  1108.         }
  1109.           else
  1110.         {
  1111.           while (range > lim && !fastmap[*p++])
  1112.             range--;
  1113.         }
  1114.           startpos += irange - range;
  1115.         }
  1116.       else
  1117.         {
  1118.           register unsigned char c;
  1119.           if (startpos >= size1)
  1120.         c = string2[startpos - size1];
  1121.           else
  1122.         c = string1[startpos];
  1123.           c &= 0xff;
  1124.           if (translate ? !fastmap[translate[c]] : !fastmap[c])
  1125.         goto advance;
  1126.         }
  1127.     }
  1128.  
  1129.       if (range >= 0 && startpos == total
  1130.       && fastmap && pbufp->can_be_null == 0)
  1131.     return -1;
  1132.  
  1133.       val = re_match_2 (pbufp, string1, size1, string2, size2, startpos, regs, mstop);
  1134.       if (0 <= val)
  1135.     {
  1136.       if (val == -2)
  1137.         return -2;
  1138.       return startpos;
  1139.     }
  1140.  
  1141. #ifdef C_ALLOCA
  1142.       alloca (0);
  1143. #endif /* C_ALLOCA */
  1144.  
  1145.     advance:
  1146.       if (!range) break;
  1147.       if (range > 0) range--, startpos++; else range++, startpos--;
  1148.     }
  1149.   return -1;
  1150. }
  1151.  
  1152. #ifndef emacs   /* emacs never uses this */
  1153. int
  1154. re_match (pbufp, string, size, pos, regs)
  1155.      struct re_pattern_buffer *pbufp;
  1156.      char *string;
  1157.      int size, pos;
  1158.      struct re_registers *regs;
  1159. {
  1160.   return re_match_2 (pbufp, 0, 0, string, size, pos, regs, size);
  1161. }
  1162. #endif /* emacs */
  1163.  
  1164. /* Maximum size of failure stack.  Beyond this, overflow is an error.  */
  1165.  
  1166. int re_max_failures = 2000;
  1167.  
  1168. static int bcmp_translate();
  1169. /* Match the pattern described by PBUFP
  1170.    against data which is the virtual concatenation of STRING1 and STRING2.
  1171.    SIZE1 and SIZE2 are the sizes of the two data strings.
  1172.    Start the match at position POS.
  1173.    Do not consider matching past the position MSTOP.
  1174.  
  1175.    If pbufp->fastmap is nonzero, then it had better be up to date.
  1176.  
  1177.    The reason that the data to match are specified as two components
  1178.    which are to be regarded as concatenated
  1179.    is so this function can be used directly on the contents of an Emacs buffer.
  1180.  
  1181.    -1 is returned if there is no match.  -2 is returned if there is
  1182.    an error (such as match stack overflow).  Otherwise the value is the length
  1183.    of the substring which was matched.  */
  1184.  
  1185. int
  1186. re_match_2 (pbufp, string1, size1, string2, size2, pos, regs, mstop)
  1187.      struct re_pattern_buffer *pbufp;
  1188.      unsigned char *string1, *string2;
  1189.      int size1, size2;
  1190.      int pos;
  1191.      struct re_registers *regs;
  1192.      int mstop;
  1193. {
  1194.   register unsigned char *p = (unsigned char *) pbufp->buffer;
  1195.   register unsigned char *pend = p + pbufp->used;
  1196.   /* End of first string */
  1197.   unsigned char *end1;
  1198.   /* End of second string */
  1199.   unsigned char *end2;
  1200.   /* Pointer just past last char to consider matching */
  1201.   unsigned char *end_match_1, *end_match_2;
  1202.   register unsigned char *d, *dend;
  1203.   register int mcnt;
  1204.   unsigned char *translate = (unsigned char *) pbufp->translate;
  1205.  
  1206.  /* Failure point stack.  Each place that can handle a failure further down the line
  1207.     pushes a failure point on this stack.  It consists of two char *'s.
  1208.     The first one pushed is where to resume scanning the pattern;
  1209.     the second pushed is where to resume scanning the strings.
  1210.     If the latter is zero, the failure point is a "dummy".
  1211.     If a failure happens and the innermost failure point is dormant,
  1212.     it discards that failure point and tries the next one. */
  1213.  
  1214.   unsigned char *initial_stack[2 * NFAILURES];
  1215.   unsigned char **stackb = initial_stack;
  1216.   unsigned char **stackp = stackb, **stacke = &stackb[2 * NFAILURES];
  1217.  
  1218.   /* Information on the "contents" of registers.
  1219.      These are pointers into the input strings; they record
  1220.      just what was matched (on this attempt) by some part of the pattern.
  1221.      The start_memory command stores the start of a register's contents
  1222.      and the stop_memory command stores the end.
  1223.  
  1224.      At that point, regstart[regnum] points to the first character in the register,
  1225.      regend[regnum] points to the first character beyond the end of the register,
  1226.      regstart_seg1[regnum] is true iff regstart[regnum] points into string1,
  1227.      and regend_seg1[regnum] is true iff regend[regnum] points into string1.  */
  1228.  
  1229.   unsigned char *regstart[RE_NREGS];
  1230.   unsigned char *regend[RE_NREGS];
  1231.   unsigned char regstart_seg1[RE_NREGS], regend_seg1[RE_NREGS];
  1232.  
  1233.   /* Set up pointers to ends of strings.
  1234.      Don't allow the second string to be empty unless both are empty.  */
  1235.   if (!size2)
  1236.     {
  1237.       string2 = string1;
  1238.       size2 = size1;
  1239.       string1 = 0;
  1240.       size1 = 0;
  1241.     }
  1242.   end1 = string1 + size1;
  1243.   end2 = string2 + size2;
  1244.  
  1245.   /* Compute where to stop matching, within the two strings */
  1246.   if (mstop <= size1)
  1247.     {
  1248.       end_match_1 = string1 + mstop;
  1249.       end_match_2 = string2;
  1250.     }
  1251.   else
  1252.     {
  1253.       end_match_1 = end1;
  1254.       end_match_2 = string2 + mstop - size1;
  1255.     }
  1256.  
  1257.   /* Initialize \) text positions to -1
  1258.      to mark ones that no \( or \) has been seen for.  */
  1259.  
  1260.   for (mcnt = 0; mcnt < sizeof (regend) / sizeof (*regend); mcnt++)
  1261.     regend[mcnt] = (unsigned char *) -1;
  1262.  
  1263.   /* `p' scans through the pattern as `d' scans through the data.
  1264.      `dend' is the end of the input string that `d' points within.
  1265.      `d' is advanced into the following input string whenever necessary,
  1266.      but this happens before fetching;
  1267.      therefore, at the beginning of the loop,
  1268.      `d' can be pointing at the end of a string,
  1269.      but it cannot equal string2.  */
  1270.  
  1271.   if (pos <= size1)
  1272.     d = string1 + pos, dend = end_match_1;
  1273.   else
  1274.     d = string2 + pos - size1, dend = end_match_2;
  1275.  
  1276. /* Write PREFETCH; just before fetching a character with *d.  */
  1277. #define PREFETCH \
  1278.  while (d == dend)                            \
  1279.   { if (dend == end_match_2) goto fail;  /* end of string2 => failure */   \
  1280.     d = string2;  /* end of string1 => advance to string2. */       \
  1281.     dend = end_match_2; }
  1282.  
  1283.   /* This loop loops over pattern commands.
  1284.      It exits by returning from the function if match is complete,
  1285.      or it drops through if match fails at this starting point in the input data. */
  1286.  
  1287.   while (1)
  1288.     {
  1289.       if (p == pend)
  1290.     /* End of pattern means we have succeeded! */
  1291.     {
  1292.       /* If caller wants register contents data back, convert it to indices */
  1293.       if (regs)
  1294.         {
  1295.            regs->start[0] = pos;
  1296.            if (dend == end_match_1)
  1297.          regs->end[0] = d - string1;
  1298.            else
  1299.          regs->end[0] = d - string2 + size1;
  1300.            for (mcnt = 1; mcnt < RE_NREGS; mcnt++)
  1301.         {
  1302.           if (regend[mcnt] == (unsigned char *) -1)
  1303.             {
  1304.               regs->start[mcnt] = -1;
  1305.               regs->end[mcnt] = -1;
  1306.               continue;
  1307.             }
  1308.            if (regstart_seg1[mcnt])
  1309.             regs->start[mcnt] = regstart[mcnt] - string1;
  1310.           else
  1311.             regs->start[mcnt] = regstart[mcnt] - string2 + size1;
  1312.            if (regend_seg1[mcnt])
  1313.             regs->end[mcnt] = regend[mcnt] - string1;
  1314.           else
  1315.             regs->end[mcnt] = regend[mcnt] - string2 + size1;
  1316.         }
  1317.         }
  1318.        if (dend == end_match_1)
  1319.         return (d - string1 - pos);
  1320.       else
  1321.         return d - string2 + size1 - pos;
  1322.     }
  1323.  
  1324.       /* Otherwise match next pattern command */
  1325. #ifdef SWITCH_ENUM_BUG
  1326.       switch ((int) ((enum regexpcode) *p++))
  1327. #else
  1328.       switch ((enum regexpcode) *p++)
  1329. #endif
  1330.     {
  1331.  
  1332.     /* \( is represented by a start_memory, \) by a stop_memory.
  1333.         Both of those commands contain a "register number" argument.
  1334.         The text matched within the \( and \) is recorded under that number.
  1335.         Then, \<digit> turns into a `duplicate' command which
  1336.         is followed by the numeric value of <digit> as the register number. */
  1337.  
  1338.     case start_memory:
  1339.       regstart[*p] = d;
  1340.        regstart_seg1[*p++] = (dend == end_match_1);
  1341.       break;
  1342.  
  1343.     case stop_memory:
  1344.       regend[*p] = d;
  1345.        regend_seg1[*p++] = (dend == end_match_1);
  1346.       break;
  1347.  
  1348.     case duplicate:
  1349.       {
  1350.         int regno = *p++;   /* Get which register to match against */
  1351.         register unsigned char *d2, *dend2;
  1352.  
  1353.         d2 = regstart[regno];
  1354.          dend2 = ((regstart_seg1[regno] == regend_seg1[regno])
  1355.              ? regend[regno] : end_match_1);
  1356.         while (1)
  1357.           {
  1358.         /* Advance to next segment in register contents, if necessary */
  1359.         while (d2 == dend2)
  1360.           {
  1361.             if (dend2 == end_match_2) break;
  1362.             if (dend2 == regend[regno]) break;
  1363.             d2 = string2, dend2 = regend[regno];  /* end of string1 => advance to string2. */
  1364.           }
  1365.         /* At end of register contents => success */
  1366.         if (d2 == dend2) break;
  1367.  
  1368.         /* Advance to next segment in data being matched, if necessary */
  1369.         PREFETCH;
  1370.  
  1371.         /* mcnt gets # consecutive chars to compare */
  1372.         mcnt = dend - d;
  1373.         if (mcnt > dend2 - d2)
  1374.           mcnt = dend2 - d2;
  1375.         /* Compare that many; failure if mismatch, else skip them. */
  1376.         if (translate ? bcmp_translate (d, d2, mcnt, translate) : bcmp (d, d2, mcnt))
  1377.           goto fail;
  1378.         d += mcnt, d2 += mcnt;
  1379.           }
  1380.       }
  1381.       break;
  1382.  
  1383.     case anychar:
  1384.       /* fetch a data character */
  1385.       PREFETCH;
  1386.       /* Match anything but a newline.  */
  1387.       if ((translate ? translate[*d++] : *d++) == '\n')
  1388.         goto fail;
  1389.       break;
  1390.  
  1391.     case charset:
  1392.     case charset_not:
  1393.       {
  1394.         /* Nonzero for charset_not */
  1395.         int not = 0;
  1396.         register int c;
  1397.         if (*(p - 1) == (unsigned char) charset_not)
  1398.           not = 1;
  1399.  
  1400.         /* fetch a data character */
  1401.         PREFETCH;
  1402.  
  1403.         if (translate)
  1404.           c = translate [*d];
  1405.         else
  1406.           c = *d;
  1407.  
  1408.         if (c < *p * BYTEWIDTH
  1409.         && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
  1410.           not = !not;
  1411.  
  1412.         p += 1 + *p;
  1413.  
  1414.         if (!not) goto fail;
  1415.         d++;
  1416.         break;
  1417.       }
  1418.  
  1419.     case begline:
  1420.       if (d == string1 || d[-1] == '\n')
  1421.         break;
  1422.       goto fail;
  1423.  
  1424.     case endline:
  1425.       if (d == end2
  1426.           || (d == end1 ? (size2 == 0 || *string2 == '\n') : *d == '\n'))
  1427.         break;
  1428.       goto fail;
  1429.  
  1430.     /* "or" constructs ("|") are handled by starting each alternative
  1431.         with an on_failure_jump that points to the start of the next alternative.
  1432.         Each alternative except the last ends with a jump to the joining point.
  1433.         (Actually, each jump except for the last one really jumps
  1434.          to the following jump, because tensioning the jumps is a hassle.) */
  1435.  
  1436.     /* The start of a stupid repeat has an on_failure_jump that points
  1437.        past the end of the repeat text.
  1438.        This makes a failure point so that, on failure to match a repetition,
  1439.        matching restarts past as many repetitions have been found
  1440.        with no way to fail and look for another one.  */
  1441.  
  1442.     /* A smart repeat is similar but loops back to the on_failure_jump
  1443.        so that each repetition makes another failure point. */
  1444.  
  1445.     case on_failure_jump:
  1446.       if (stackp == stacke)
  1447.         {
  1448.           unsigned char **stackx;
  1449.           if (stacke - stackb > re_max_failures * 2)
  1450.         return -2;
  1451.           stackx = (unsigned char **) alloca (2 * (stacke - stackb)
  1452.                      * sizeof (char *));
  1453.           bcopy (stackb, stackx, (stacke - stackb) * sizeof (char *));
  1454.           stackp = stackx + (stackp - stackb);
  1455.           stacke = stackx + 2 * (stacke - stackb);
  1456.           stackb = stackx;
  1457.         }
  1458.       mcnt = *p++ & 0377;
  1459.       mcnt += SIGN_EXTEND_CHAR (*(char *)p) << 8;
  1460.       p++;
  1461.       *stackp++ = mcnt + p;
  1462.       *stackp++ = d;
  1463.       break;
  1464.  
  1465.     /* The end of a smart repeat has an maybe_finalize_jump back.
  1466.        Change it either to a finalize_jump or an ordinary jump. */
  1467.  
  1468.     case maybe_finalize_jump:
  1469.       mcnt = *p++ & 0377;
  1470.       mcnt += SIGN_EXTEND_CHAR (*(char *)p) << 8;
  1471.       p++;
  1472.       {
  1473.         register unsigned char *p2 = p;
  1474.         /* Compare what follows with the begining of the repeat.
  1475.            If we can establish that there is nothing that they would
  1476.            both match, we can change to finalize_jump */
  1477.         while (p2 != pend
  1478.            && (*p2 == (unsigned char) stop_memory
  1479.                || *p2 == (unsigned char) start_memory))
  1480.           p2++;
  1481.         if (p2 == pend)
  1482.           p[-3] = (unsigned char) finalize_jump;
  1483.         else if (*p2 == (unsigned char) exactn
  1484.              || *p2 == (unsigned char) endline)
  1485.           {
  1486.         register int c = *p2 == (unsigned char) endline ? '\n' : p2[2];
  1487.         register unsigned char *p1 = p + mcnt;
  1488.         /* p1[0] ... p1[2] are an on_failure_jump.
  1489.            Examine what follows that */
  1490.         if (p1[3] == (unsigned char) exactn && p1[5] != c)
  1491.           p[-3] = (unsigned char) finalize_jump;
  1492.         else if (p1[3] == (unsigned char) charset
  1493.              || p1[3] == (unsigned char) charset_not)
  1494.           {
  1495.             int not = p1[3] == (unsigned char) charset_not;
  1496.             if (c < p1[4] * BYTEWIDTH
  1497.             && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
  1498.               not = !not;
  1499.             /* not is 1 if c would match */
  1500.             /* That means it is not safe to finalize */
  1501.             if (!not)
  1502.               p[-3] = (unsigned char) finalize_jump;
  1503.           }
  1504.           }
  1505.       }
  1506.       p -= 2;
  1507.       if (p[-1] != (unsigned char) finalize_jump)
  1508.         {
  1509.           p[-1] = (unsigned char) jump;
  1510.           goto nofinalize;
  1511.         }
  1512.  
  1513.     /* The end of a stupid repeat has a finalize-jump
  1514.        back to the start, where another failure point will be made
  1515.        which will point after all the repetitions found so far. */
  1516.  
  1517.     case finalize_jump:
  1518.       stackp -= 2;
  1519.  
  1520.     case jump:
  1521.     nofinalize:
  1522.       mcnt = *p++ & 0377;
  1523.       mcnt += SIGN_EXTEND_CHAR (*(char *)p) << 8;
  1524.       p += mcnt + 1;    /* The 1 compensates for missing ++ above */
  1525.       break;
  1526.  
  1527.     case dummy_failure_jump:
  1528.       if (stackp == stacke)
  1529.         {
  1530.           unsigned char **stackx
  1531.         = (unsigned char **) alloca (2 * (stacke - stackb)
  1532.                          * sizeof (char *));
  1533.           bcopy (stackb, stackx, (stacke - stackb) * sizeof (char *));
  1534.           stackp = stackx + (stackp - stackb);
  1535.           stacke = stackx + 2 * (stacke - stackb);
  1536.           stackb = stackx;
  1537.         }
  1538.       *stackp++ = 0;
  1539.       *stackp++ = 0;
  1540.       goto nofinalize;
  1541.  
  1542.     case wordbound:
  1543.       if (d == string1  /* Points to first char */
  1544.           || d == end2  /* Points to end */
  1545.           || (d == end1 && size2 == 0)) /* Points to end */
  1546.         break;
  1547.       if ((SYNTAX (d[-1]) == Sword)
  1548.           != (SYNTAX (d == end1 ? *string2 : *d) == Sword))
  1549.         break;
  1550.       goto fail;
  1551.  
  1552.     case notwordbound:
  1553.       if (d == string1  /* Points to first char */
  1554.           || d == end2  /* Points to end */
  1555.           || (d == end1 && size2 == 0)) /* Points to end */
  1556.         goto fail;
  1557.       if ((SYNTAX (d[-1]) == Sword)
  1558.           != (SYNTAX (d == end1 ? *string2 : *d) == Sword))
  1559.         goto fail;
  1560.       break;
  1561.  
  1562.     case wordbeg:
  1563.       if (d == end2  /* Points to end */
  1564.           || (d == end1 && size2 == 0) /* Points to end */
  1565.           || SYNTAX (* (d == end1 ? string2 : d)) != Sword) /* Next char not a letter */
  1566.         goto fail;
  1567.       if (d == string1  /* Points to first char */
  1568.           || SYNTAX (d[-1]) != Sword)  /* prev char not letter */
  1569.         break;
  1570.       goto fail;
  1571.  
  1572.     case wordend:
  1573.       if (d == string1  /* Points to first char */
  1574.           || SYNTAX (d[-1]) != Sword)  /* prev char not letter */
  1575.         goto fail;
  1576.       if (d == end2  /* Points to end */
  1577.           || (d == end1 && size2 == 0) /* Points to end */
  1578.           || SYNTAX (d == end1 ? *string2 : *d) != Sword) /* Next char not a letter */
  1579.         break;
  1580.       goto fail;
  1581.  
  1582. #ifdef emacs
  1583.     case before_dot:
  1584.       if (((d - string2 <= (unsigned) size2)
  1585.            ? d - bf_p2 : d - bf_p1)
  1586.           <= point)
  1587.         goto fail;
  1588.       break;
  1589.  
  1590.     case at_dot:
  1591.       if (((d - string2 <= (unsigned) size2)
  1592.            ? d - bf_p2 : d - bf_p1)
  1593.           == point)
  1594.         goto fail;
  1595.       break;
  1596.  
  1597.     case after_dot:
  1598.       if (((d - string2 <= (unsigned) size2)
  1599.            ? d - bf_p2 : d - bf_p1)
  1600.           >= point)
  1601.         goto fail;
  1602.       break;
  1603.  
  1604.     case wordchar:
  1605.       mcnt = (int) Sword;
  1606.       goto matchsyntax;
  1607.  
  1608.     case syntaxspec:
  1609.       mcnt = *p++;
  1610.     matchsyntax:
  1611.       PREFETCH;
  1612.       if (SYNTAX (*d++) != (enum syntaxcode) mcnt) goto fail;
  1613.       break;
  1614.       
  1615.     case notwordchar:
  1616.       mcnt = (int) Sword;
  1617.       goto matchnotsyntax;
  1618.  
  1619.     case notsyntaxspec:
  1620.       mcnt = *p++;
  1621.     matchnotsyntax:
  1622.       PREFETCH;
  1623.       if (SYNTAX (*d++) == (enum syntaxcode) mcnt) goto fail;
  1624.       break;
  1625. #else
  1626.     case wordchar:
  1627.       PREFETCH;
  1628.       if (SYNTAX (*d++) == 0) goto fail;
  1629.       break;
  1630.       
  1631.     case notwordchar:
  1632.       PREFETCH;
  1633.       if (SYNTAX (*d++) != 0) goto fail;
  1634.       break;
  1635. #endif /* not emacs */
  1636.  
  1637.     case begbuf:
  1638.       if (d == string1)    /* Note, d cannot equal string2 */
  1639.         break;        /* unless string1 == string2.  */
  1640.       goto fail;
  1641.  
  1642.     case endbuf:
  1643.       if (d == end2 || (d == end1 && size2 == 0))
  1644.         break;
  1645.       goto fail;
  1646.  
  1647.     case exactn:
  1648.       /* Match the next few pattern characters exactly.
  1649.          mcnt is how many characters to match. */
  1650.       mcnt = *p++;
  1651.       if (translate)
  1652.         {
  1653.           do
  1654.         {
  1655.           PREFETCH;
  1656.           if (translate[*d++] != *p++) goto fail;
  1657.         }
  1658.           while (--mcnt);
  1659.         }
  1660.       else
  1661.         {
  1662.           do
  1663.         {
  1664.           PREFETCH;
  1665.           if (*d++ != *p++) goto fail;
  1666.         }
  1667.           while (--mcnt);
  1668.         }
  1669.       break;
  1670.     }
  1671.       continue;    /* Successfully matched one pattern command; keep matching */
  1672.  
  1673.       /* Jump here if any matching operation fails. */
  1674.     fail:
  1675.       if (stackp != stackb)
  1676.     /* A restart point is known.  Restart there and pop it. */
  1677.     {
  1678.       if (!stackp[-2])
  1679.         {   /* If innermost failure point is dormant, flush it and keep looking */
  1680.           stackp -= 2;
  1681.           goto fail;
  1682.         }
  1683.       d = *--stackp;
  1684.       p = *--stackp;
  1685.       if (d >= string1 && d <= end1)
  1686.         dend = end_match_1;
  1687.     }
  1688.       else break;   /* Matching at this starting point really fails! */
  1689.     }
  1690.   return -1;         /* Failure to match */
  1691. }
  1692.  
  1693. static int
  1694. bcmp_translate (s1, s2, len, translate)
  1695.      unsigned char *s1, *s2;
  1696.      register int len;
  1697.      unsigned char *translate;
  1698. {
  1699.   register unsigned char *p1 = s1, *p2 = s2;
  1700.   while (len)
  1701.     {
  1702.       if (translate [*p1++] != translate [*p2++]) return 1;
  1703.       len--;
  1704.     }
  1705.   return 0;
  1706. }
  1707.  
  1708. /* Entry points compatible with bsd4.2 regex library */
  1709.  
  1710. #ifndef emacs
  1711.  
  1712. static struct re_pattern_buffer re_comp_buf;
  1713.  
  1714. char *
  1715. re_comp (s)
  1716.      char *s;
  1717. {
  1718.   if (!s)
  1719.     {
  1720.       if (!re_comp_buf.buffer)
  1721.     return "No previous regular expression";
  1722.       return 0;
  1723.     }
  1724.  
  1725.   if (!re_comp_buf.buffer)
  1726.     {
  1727.       if (!(re_comp_buf.buffer = (char *) malloc (200)))
  1728.     return "Memory exhausted";
  1729.       re_comp_buf.allocated = 200;
  1730.       if (!(re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH)))
  1731.     return "Memory exhausted";
  1732.     }
  1733.   return re_compile_pattern (s, strlen (s), &re_comp_buf);
  1734. }
  1735.  
  1736. int
  1737. re_exec (s)
  1738.      char *s;
  1739. {
  1740.   int len = strlen (s);
  1741.   return 0 <= re_search (&re_comp_buf, s, len, 0, len, 0);
  1742. }
  1743.  
  1744. #endif /* emacs */
  1745.  
  1746. #ifdef test
  1747.  
  1748. #include <stdio.h>
  1749.  
  1750. /* Indexed by a character, gives the upper case equivalent of the character */
  1751.  
  1752. static char upcase[0400] = 
  1753.   { 000, 001, 002, 003, 004, 005, 006, 007,
  1754.     010, 011, 012, 013, 014, 015, 016, 017,
  1755.     020, 021, 022, 023, 024, 025, 026, 027,
  1756.     030, 031, 032, 033, 034, 035, 036, 037,
  1757.     040, 041, 042, 043, 044, 045, 046, 047,
  1758.     050, 051, 052, 053, 054, 055, 056, 057,
  1759.     060, 061, 062, 063, 064, 065, 066, 067,
  1760.     070, 071, 072, 073, 074, 075, 076, 077,
  1761.     0100, 0101, 0102, 0103, 0104, 0105, 0106, 0107,
  1762.     0110, 0111, 0112, 0113, 0114, 0115, 0116, 0117,
  1763.     0120, 0121, 0122, 0123, 0124, 0125, 0126, 0127,
  1764.     0130, 0131, 0132, 0133, 0134, 0135, 0136, 0137,
  1765.     0140, 0101, 0102, 0103, 0104, 0105, 0106, 0107,
  1766.     0110, 0111, 0112, 0113, 0114, 0115, 0116, 0117,
  1767.     0120, 0121, 0122, 0123, 0124, 0125, 0126, 0127,
  1768.     0130, 0131, 0132, 0173, 0174, 0175, 0176, 0177,
  1769.     0200, 0201, 0202, 0203, 0204, 0205, 0206, 0207,
  1770.     0210, 0211, 0212, 0213, 0214, 0215, 0216, 0217,
  1771.     0220, 0221, 0222, 0223, 0224, 0225, 0226, 0227,
  1772.     0230, 0231, 0232, 0233, 0234, 0235, 0236, 0237,
  1773.     0240, 0241, 0242, 0243, 0244, 0245, 0246, 0247,
  1774.     0250, 0251, 0252, 0253, 0254, 0255, 0256, 0257,
  1775.     0260, 0261, 0262, 0263, 0264, 0265, 0266, 0267,
  1776.     0270, 0271, 0272, 0273, 0274, 0275, 0276, 0277,
  1777.     0300, 0301, 0302, 0303, 0304, 0305, 0306, 0307,
  1778.     0310, 0311, 0312, 0313, 0314, 0315, 0316, 0317,
  1779.     0320, 0321, 0322, 0323, 0324, 0325, 0326, 0327,
  1780.     0330, 0331, 0332, 0333, 0334, 0335, 0336, 0337,
  1781.     0340, 0341, 0342, 0343, 0344, 0345, 0346, 0347,
  1782.     0350, 0351, 0352, 0353, 0354, 0355, 0356, 0357,
  1783.     0360, 0361, 0362, 0363, 0364, 0365, 0366, 0367,
  1784.     0370, 0371, 0372, 0373, 0374, 0375, 0376, 0377
  1785.   };
  1786.  
  1787. main (argc, argv)
  1788.      int argc;
  1789.      char **argv;
  1790. {
  1791.   char pat[80];
  1792.   struct re_pattern_buffer buf;
  1793.   int i;
  1794.   char c;
  1795.   char fastmap[(1 << BYTEWIDTH)];
  1796.  
  1797.   /* Allow a command argument to specify the style of syntax.  */
  1798.   if (argc > 1)
  1799.     obscure_syntax = atoi (argv[1]);
  1800.  
  1801.   buf.allocated = 40;
  1802.   buf.buffer = (char *) malloc (buf.allocated);
  1803.   buf.fastmap = fastmap;
  1804.   buf.translate = upcase;
  1805.  
  1806.   while (1)
  1807.     {
  1808.       gets (pat);
  1809.  
  1810.       if (*pat)
  1811.     {
  1812.           re_compile_pattern (pat, strlen(pat), &buf);
  1813.  
  1814.       for (i = 0; i < buf.used; i++)
  1815.         printchar (buf.buffer[i]);
  1816.  
  1817.       putchar ('\n');
  1818.  
  1819.       printf ("%d allocated, %d used.\n", buf.allocated, buf.used);
  1820.  
  1821.       re_compile_fastmap (&buf);
  1822.       printf ("Allowed by fastmap: ");
  1823.       for (i = 0; i < (1 << BYTEWIDTH); i++)
  1824.         if (fastmap[i]) printchar (i);
  1825.       putchar ('\n');
  1826.     }
  1827.  
  1828.       gets (pat);    /* Now read the string to match against */
  1829.  
  1830.       i = re_match (&buf, pat, strlen (pat), 0, 0);
  1831.       printf ("Match value %d.\n", i);
  1832.     }
  1833. }
  1834.  
  1835. #ifdef NOTDEF
  1836. print_buf (bufp)
  1837.      struct re_pattern_buffer *bufp;
  1838. {
  1839.   int i;
  1840.  
  1841.   printf ("buf is :\n----------------\n");
  1842.   for (i = 0; i < bufp->used; i++)
  1843.     printchar (bufp->buffer[i]);
  1844.   
  1845.   printf ("\n%d allocated, %d used.\n", bufp->allocated, bufp->used);
  1846.   
  1847.   printf ("Allowed by fastmap: ");
  1848.   for (i = 0; i < (1 << BYTEWIDTH); i++)
  1849.     if (bufp->fastmap[i])
  1850.       printchar (i);
  1851.   printf ("\nAllowed by translate: ");
  1852.   if (bufp->translate)
  1853.     for (i = 0; i < (1 << BYTEWIDTH); i++)
  1854.       if (bufp->translate[i])
  1855.     printchar (i);
  1856.   printf ("\nfastmap is%s accurate\n", bufp->fastmap_accurate ? "" : "n't");
  1857.   printf ("can %s be null\n----------", bufp->can_be_null ? "" : "not");
  1858. }
  1859. #endif
  1860.  
  1861. printchar (c)
  1862.      char c;
  1863. {
  1864.   if (c < 041 || c >= 0177)
  1865.     {
  1866.       putchar ('\\');
  1867.       putchar (((c >> 6) & 3) + '0');
  1868.       putchar (((c >> 3) & 7) + '0');
  1869.       putchar ((c & 7) + '0');
  1870.     }
  1871.   else
  1872.     putchar (c);
  1873. }
  1874.  
  1875. #endif /* test */
  1876.