home *** CD-ROM | disk | FTP | other *** search
/ The Fred Fish Collection 1.5 / ffcollection-1-5-1992-11.iso / ff_disks / 200-299 / ff204.lzh / GnuGrep / egrep.c < prev    next >
C/C++ Source or Header  |  1989-04-30  |  29KB  |  1,060 lines

  1. /* grep - print lines matching an extended regular expression
  2.    Copyright (C) 1988 Free Software Foundation, Inc.
  3.                       Written June, 1988 by Mike Haertel
  4.                   BMG speedups added July, 1988
  5.             by James A. Woods and Arthur David Olson
  6.  
  7.                NO WARRANTY
  8.  
  9.   BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
  10. NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
  11. WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
  12. RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
  13. WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
  14. BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  15. FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
  16. AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE
  17. DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
  18. CORRECTION.
  19.  
  20.  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
  21. STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
  22. WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
  23. LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
  24. OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
  25. USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
  26. DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
  27. A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
  28. PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
  29. DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
  30.  
  31.         GENERAL PUBLIC LICENSE TO COPY
  32.  
  33.   1. You may copy and distribute verbatim copies of this source file
  34. as you receive it, in any medium, provided that you conspicuously and
  35. appropriately publish on each copy a valid copyright notice "Copyright
  36.  (C) 1988 Free Software Foundation, Inc."; and include following the
  37. copyright notice a verbatim copy of the above disclaimer of warranty
  38. and of this License.  You may charge a distribution fee for the
  39. physical act of transferring a copy.
  40.  
  41.   2. You may modify your copy or copies of this source file or
  42. any portion of it, and copy and distribute such modifications under
  43. the terms of Paragraph 1 above, provided that you also do the following:
  44.  
  45.     a) cause the modified files to carry prominent notices stating
  46.     that you changed the files and the date of any change; and
  47.  
  48.     b) cause the whole of any work that you distribute or publish,
  49.     that in whole or in part contains or is a derivative of this
  50.     program or any part thereof, to be licensed at no charge to all
  51.     third parties on terms identical to those contained in this
  52.     License Agreement (except that you may choose to grant more extensive
  53.     warranty protection to some or all third parties, at your option).
  54.  
  55.     c) You may charge a distribution fee for the physical act of
  56.     transferring a copy, and you may at your option offer warranty
  57.     protection in exchange for a fee.
  58.  
  59. Mere aggregation of another unrelated program with this program (or its
  60. derivative) on a volume of a storage or distribution medium does not bring
  61. the other program under the scope of these terms.
  62.  
  63.   3. You may copy and distribute this program or any portion of it in
  64. compiled, executable or object code form under the terms of Paragraphs
  65. 1 and 2 above provided that you do the following:
  66.  
  67.     a) accompany it with the complete corresponding machine-readable
  68.     source code, which must be distributed under the terms of
  69.     Paragraphs 1 and 2 above; or,
  70.  
  71.     b) accompany it with a written offer, valid for at least three
  72.     years, to give any third party free (except for a nominal
  73.     shipping charge) a complete machine-readable copy of the
  74.     corresponding source code, to be distributed under the terms of
  75.     Paragraphs 1 and 2 above; or,
  76.  
  77.     c) accompany it with the information you received as to where the
  78.     corresponding source code may be obtained.  (This alternative is
  79.     allowed only for noncommercial distribution and only if you
  80.     received the program in object code or executable form alone.)
  81.  
  82. For an executable file, complete source code means all the source code for
  83. all modules it contains; but, as a special exception, it need not include
  84. source code for modules which are standard libraries that accompany the
  85. operating system on which the executable file runs.
  86.  
  87.   4. You may not copy, sublicense, distribute or transfer this program
  88. except as expressly provided under this License Agreement.  Any attempt
  89. otherwise to copy, sublicense, distribute or transfer this program is void and
  90. your rights to use the program under this License agreement shall be
  91. automatically terminated.  However, parties who have received computer
  92. software programs from you with this License Agreement will not have
  93. their licenses terminated so long as such parties remain in full compliance.
  94.  
  95.   5. If you wish to incorporate parts of this program into other free
  96. programs whose distribution conditions are different, write to the Free
  97. Software Foundation at 675 Mass Ave, Cambridge, MA 02139.  We have not yet
  98. worked out a simple rule that can be stated here, but we will often permit
  99. this.  We will be guided by the two goals of preserving the free status of
  100. all derivatives our free software and of promoting the sharing and reuse of
  101. software.
  102.  
  103.  
  104. In other words, you are welcome to use, share and improve this program.
  105. You are forbidden to forbid anyone else to use, share and improve
  106. what you give them.   Help stamp out software-hoarding!  */
  107.  
  108. #include <ctype.h>
  109. #include <stdio.h>
  110. #ifdef USG
  111. #ifndef AMIGA
  112. #include <memory.h>
  113. #endif
  114. #include <string.h>
  115. #else
  116. #include <strings.h>
  117. #endif
  118. #include "dfa.h"
  119. #include "regex.h"
  120.  
  121. #ifdef __STDC__
  122. extern getopt(int, char **, const char *);
  123. extern read(int, void *, int);
  124. extern open(const char *, int, ...);
  125. extern void close();
  126. #else
  127. extern char *strrchr();
  128. #endif
  129.  
  130. extern char *optarg;
  131. extern optind, opterr;
  132. extern errno;
  133. extern char *sys_errlist[];
  134.  
  135. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  136.  
  137. /* Exit status codes. */
  138. #define MATCHES_FOUND 0        /* Exit 0 if no errors and matches found. */
  139. #define NO_MATCHES_FOUND 1    /* Exit 1 if no matches were found. */
  140. #define ERROR 2            /* Exit 2 if some error occurred. */
  141.  
  142. /* Error is set true if something awful happened. */
  143. static int error;
  144.  
  145. /* The program name for error messages. */
  146. static char *prog;
  147.  
  148. /* We do all our own buffering by hand for efficiency. */
  149. static char *buffer;        /* The buffer itself, grown as needed. */
  150. static bufbytes;        /* Number of bytes in the buffer. */
  151. static size_t bufalloc;        /* Number of bytes allocated to the buffer. */
  152. static bufprev;            /* Number of bytes that have been forgotten.
  153.                    This is used to get byte offsets from the
  154.                    beginning of the file. */
  155. static bufread;            /* Number of bytes to get with each read(). */
  156.  
  157. static void
  158. initialize_buffer()
  159. {
  160.   bufread = 8192;
  161.   bufalloc = bufread + bufread / 2;
  162.   buffer = malloc(bufalloc);
  163.   if (! buffer)
  164.     {
  165.       fprintf(stderr, "%s: Memory exhausted (%s)\n", prog,
  166.           sys_errlist[errno]);
  167.       CleanExit(ERROR);
  168.     }
  169. }
  170.  
  171. /* The current input file. */
  172. static fd;
  173. static char *filename;
  174. static eof;
  175.  
  176. /* Fill the buffer retaining the last n bytes at the beginning of the
  177.    newly filled buffer (for backward context).  Returns the number of new
  178.    bytes read from disk. */
  179. static
  180. fill_buffer_retaining(n)
  181.      int n;
  182. {
  183.   char *p, *q;
  184.   int i;
  185.  
  186.   /* See if we need to grow the buffer. */
  187.   if (bufalloc - n <= bufread)
  188.     {
  189.       while (bufalloc - n <= bufread)
  190.     {
  191.       bufalloc *= 2;
  192.       bufread *= 2;
  193.     }
  194.       buffer = realloc(buffer, bufalloc);
  195.       if (! buffer)
  196.     {
  197.       fprintf(stderr, "%s: Memory exhausted (%s)\n", prog,
  198.           sys_errlist[errno]);
  199.       CleanExit(ERROR);
  200.     }
  201.     }
  202.  
  203.   bufprev += bufbytes - n;
  204.  
  205.   /* Shift stuff down. */
  206.   for (i = n, p = buffer, q = p + bufbytes - n; i--; )
  207.     *p++ = *q++;
  208.   bufbytes = n;
  209.  
  210.   if (eof)
  211.     return 0;
  212.  
  213.   /* Read in new stuff. */
  214.   i = read(fd, buffer + bufbytes, bufread);
  215.   if (i < 0)
  216.     {
  217.       fprintf(stderr, "%s: read on %s failed (%s)\n", prog,
  218.           filename ? filename : "<stdin>", sys_errlist[errno]);
  219.       error = 1;
  220.     }
  221.  
  222.   /* Kludge to pretend every nonempty file ends with a newline. */
  223.   if (i == 0 && bufbytes > 0 && buffer[bufbytes - 1] != '\n')
  224.     {
  225.       eof = i = 1;
  226.       buffer[bufbytes] = '\n';
  227.     }
  228.  
  229.   bufbytes += i;
  230.   return i;
  231. }
  232.  
  233. /* Various flags set according to the argument switches. */
  234. static trailing_context;    /* Lines of context to show after matches. */
  235. static leading_context;        /* Lines of context to show before matches. */
  236. static byte_count;        /* Precede output lines the byte count of the
  237.                    first character on the line. */
  238. static no_filenames;        /* Do not display filenames. */
  239. static line_numbers;        /* Precede output lines with line numbers. */
  240. static silent;            /* Produce no output at all.  This switch
  241.                    is bogus, ever hear of /dev/null? */
  242. static nonmatching_lines;    /* Print lines that don't match the regexp. */
  243.  
  244. static bmgexec;            /* Invoke Boyer-Moore-Gosper routines */
  245.  
  246. /* The compiled regular expression lives here. */
  247. static struct regexp reg;
  248.  
  249. /* The compiled regular expression for the backtracking matcher lives here. */
  250. static struct re_pattern_buffer regex;
  251.  
  252. /* Pointer in the buffer after the last character printed. */
  253. static char *printed_limit;
  254.  
  255. /* True when printed_limit has been artifically advanced without printing
  256.    anything. */
  257. static int printed_limit_fake;
  258.  
  259. /* Print a line at the given line number, returning the number of
  260.    characters actually printed.  Matching is true if the line is to
  261.    be considered a "matching line".  This is only meaningful if
  262.    surrounding context is turned on. */
  263. static
  264. print_line(p, number, matching)
  265.      char *p;
  266.      int number;
  267.      int matching;
  268. {
  269.   int count = 0;
  270.  
  271.   if (silent)
  272.     {
  273.       do
  274.     ++count;
  275.       while (*p++ != '\n');
  276.       printed_limit_fake = 0;
  277.       printed_limit = p;
  278.       return count;
  279.     }
  280.  
  281.   if (filename && !no_filenames)
  282.     printf("%s%c", filename, matching ? ':' : '-');
  283.   if (byte_count)
  284.     printf("%d%c", p - buffer + bufprev, matching ? ':' : '-');
  285.   if (line_numbers)
  286.     printf("%d%c", number, matching ? ':' : '-');
  287.   do
  288.     {
  289.       ++count;
  290.       putchar(*p);
  291.     }
  292.   while (*p++ != '\n');
  293.   printed_limit_fake = 0;
  294.   printed_limit = p;
  295.   return count;
  296. }
  297.  
  298. /* Print matching or nonmatching lines from the current file.  Returns a
  299.    count of matching or nonmatching lines. */
  300. static
  301. grep()
  302. {
  303.   int retain = 0;        /* Number of bytes to retain on next call
  304.                    to fill_buffer_retaining(). */
  305.   char *search_limit;        /* Pointer to the character after the last
  306.                    newline in the buffer. */
  307.   char saved_char;        /* Character after the last newline. */
  308.   char *resume;            /* Pointer to where to resume search. */
  309.   int resume_index = 0;        /* Count of characters to ignore after
  310.                    refilling the buffer. */
  311.   int line_count = 1;        /* Line number. */
  312.   int try_backref;        /* Set to true if we need to verify the
  313.                    match with a backtracking matcher. */
  314.   int initial_line_count;    /* Line count at beginning of last search. */
  315.   char *match;            /* Pointer to the first character after the
  316.                    string matching the regexp. */
  317.   int match_count = 0;        /* Count of matching lines. */
  318.   char *matching_line;        /* Pointer to first character of the matching
  319.                    line, or of the first line of context to
  320.                    print if context is turned on. */
  321.   char *real_matching_line;    /* Pointer to the first character of the
  322.                    real matching line. */
  323.   char *next_line;        /* Pointer to first character of the line
  324.                    following the matching line. */
  325.   int pending_lines = 0;    /* Lines of context left over from last match
  326.                    that we have to print. */
  327.   static first_match = 1;    /* True when nothing has been printed. */
  328.   int i;
  329.   char *tmp;
  330.   char *execute();
  331.  
  332.   printed_limit_fake = 0;
  333.   
  334.   while (fill_buffer_retaining(retain) > 0)
  335.     {
  336.       /* Find the last newline in the buffer. */
  337.       search_limit = buffer + bufbytes;
  338.       while (search_limit > buffer && search_limit[-1] != '\n')
  339.     --search_limit;
  340.       if (search_limit == buffer)
  341.     {
  342.       retain = bufbytes;
  343.       continue;
  344.     }
  345.  
  346.       /* Save the character after the last newline so regexecute can write
  347.      its own sentinel newline. */
  348.       saved_char = *search_limit;
  349.  
  350.       /* Search the buffer for a match. */
  351.       printed_limit = buffer;
  352.       resume = buffer + resume_index;
  353.       initial_line_count = line_count;
  354.  
  355.       while (match = execute(®, resume, search_limit, 0, &line_count, &try_backref))
  356.     {
  357.       ++match_count;
  358.  
  359.       /* Find the beginning of the matching line. */
  360.       matching_line = match;
  361.       while (matching_line > resume && matching_line[-1] != '\n')
  362.         --matching_line;
  363.       real_matching_line = matching_line;
  364.  
  365.       /* Find the beginning of the next line. */
  366.       next_line = match;
  367.       while (next_line < search_limit && *next_line++ != '\n')
  368.         ;
  369.  
  370.       /* If a potential backreference is indicated, try it out with
  371.          a backtracking matcher to make sure the line is a match. */
  372.       if (try_backref && re_search(®ex, matching_line,
  373.                        next_line - matching_line - 1,
  374.                        0,
  375.                        next_line - matching_line - 1,
  376.                        NULL) < 0)
  377.         {
  378.           resume = next_line;
  379.           if (resume == search_limit)
  380.         break;
  381.           else
  382.         continue;
  383.         }
  384.  
  385.       /* Print leftover lines from last time.  If nonmatching_lines is
  386.          turned on, print these as if they were matching lines. */
  387.       while (resume < matching_line && pending_lines)
  388.         {
  389.           resume += print_line(resume, initial_line_count++,
  390.                    nonmatching_lines);
  391.           --pending_lines;
  392.         }
  393.  
  394.       /* Print out the matching or nonmatching lines as necessary. */
  395.       if (! nonmatching_lines)
  396.         {
  397.           /* Back up over leading context if necessary. */
  398.           for (i = leading_context; matching_line > printed_limit
  399.            && i; --i)
  400.         {
  401.           while (matching_line > printed_limit
  402.              && (--matching_line)[-1] != '\n')
  403.             ;
  404.           --line_count;
  405.         }
  406.  
  407.           /* If context is enabled, we may have to print a separator. */
  408.           if ((leading_context || trailing_context) && !silent
  409.           && !first_match && (printed_limit_fake || matching_line
  410.                       > printed_limit))
  411.         printf("----------\n");
  412.           first_match = 0;
  413.  
  414.           /* Print the matching line and its leading context. */
  415.           while (matching_line < real_matching_line)
  416.         matching_line += print_line(matching_line, line_count++, 0);
  417.           matching_line += print_line(matching_line, line_count++, 1);
  418.  
  419.           /* If there's trailing context, leave some lines pending until
  420.          next time. */
  421.           pending_lines = trailing_context;
  422.         }
  423.       else if (matching_line > resume)
  424.         {
  425.           char *real_resume = resume;
  426.  
  427.           /* Back up over leading context if necessary. */
  428.           for (i = leading_context; resume > printed_limit && i; --i)
  429.         {
  430.           while (resume > printed_limit && (--resume)[-1] != '\n')
  431.             ;
  432.           --initial_line_count;
  433.         }
  434.  
  435.           /* If context is enabled, we may have to print a separator. */
  436.           if ((leading_context || trailing_context) && !silent
  437.           && !first_match && (printed_limit_fake || resume
  438.                       > printed_limit))
  439.         printf("----------\n");
  440.           first_match = 0;
  441.  
  442.           /* Print out the presumably matching leading context. */
  443.           while (resume < real_resume)
  444.         resume += print_line(resume, initial_line_count++, 0);
  445.  
  446.           /* Print out the nonmatching lines prior to the matching line. */
  447.           while (resume < matching_line)
  448.         resume += print_line(resume, initial_line_count++, 1);
  449.  
  450.           /* Deal with trailing context. */
  451.           if (trailing_context)
  452.         {
  453.           print_line(matching_line, line_count, 0);
  454.           pending_lines = trailing_context - 1;
  455.         }
  456.  
  457.           /* Count the current line. */
  458.           ++line_count;
  459.         }
  460.       else
  461.         {
  462.           /* The line immediately after a matching line has to be printed
  463.          because it was pending. */
  464.           if (pending_lines > 0)
  465.         {
  466.           --pending_lines;
  467.           print_line(matching_line, line_count, 0);
  468.         }
  469.           ++line_count;
  470.         }
  471.  
  472.       /* Resume searching at the beginning of the next line. */
  473.       initial_line_count = line_count;
  474.       resume = next_line;
  475.  
  476.       if (resume == search_limit)
  477.         break;
  478.     }
  479.  
  480.       /* Restore the saved character. */
  481.       *search_limit = saved_char;
  482.  
  483.       if (! nonmatching_lines)
  484.     {
  485.       while (resume < search_limit && pending_lines)
  486.         {
  487.           resume += print_line(resume, initial_line_count++, 0);
  488.           --pending_lines;
  489.         }
  490.     }
  491.       else if (search_limit > resume)
  492.     {
  493.       char *initial_resume = resume;
  494.  
  495.       /* Back up over leading context if necessary. */
  496.       for (i = leading_context; resume > printed_limit && i; --i)
  497.         {
  498.           while (resume > printed_limit && (--resume)[-1] != '\n')
  499.         ;
  500.           --initial_line_count;
  501.         }
  502.  
  503.       /* If context is enabled, we may have to print a separator. */
  504.       if ((leading_context || trailing_context) && !silent
  505.           && !first_match && (printed_limit_fake || resume
  506.                   > printed_limit))
  507.         printf("----------\n");
  508.       first_match = 0;
  509.  
  510.       /* Print out all the nonmatching lines up to the search limit. */
  511.       while (resume < initial_resume)
  512.         resume += print_line(resume, initial_line_count++, 0);
  513.       while (resume < search_limit)
  514.         resume += print_line(resume, initial_line_count++, 1);
  515.  
  516.       pending_lines = trailing_context;
  517.       resume_index = 0;
  518.       retain = bufbytes - (search_limit - buffer);
  519.       continue;
  520.     }
  521.       
  522.       /* Save the trailing end of the buffer for possible use as leading
  523.      context in the future. */
  524.       i = leading_context;
  525.       tmp = search_limit;
  526.       while (tmp > printed_limit && i--)
  527.     while (tmp > printed_limit && (--tmp)[-1] != '\n')
  528.       ;
  529.       resume_index = search_limit - tmp;
  530.       retain = bufbytes - (tmp - buffer);
  531.       if (tmp > printed_limit)
  532.     printed_limit_fake = 1;
  533.     }
  534.  
  535.   return nonmatching_lines ? line_count - match_count : match_count;
  536. }
  537.  
  538. void
  539. usage_and_die()
  540. {
  541.   fprintf(stderr,
  542. "usage: %s [-CVbchilnsvwx] [-<num>] [-AB <num>] [-f file] [-e] expr [files]\n",
  543.           prog);
  544.   CleanExit(ERROR);
  545. }
  546.  
  547. static char version[] = "GNU e?grep, version 1.3";
  548.  
  549. main(argc, argv)
  550.      int argc;
  551.      char **argv;
  552. {
  553.   int c;
  554.   int ignore_case = 0;        /* Compile the regexp to ignore case. */
  555.   char *the_regexp = 0;        /* The regular expression. */
  556.   int regexp_len;        /* Length of the regular expression. */
  557.   char *regexp_file = 0;    /* File containing parallel regexps. */
  558.   int count_lines = 0;        /* Display only a count of matching lines. */
  559.   int list_files = 0;        /* Display only the names of matching files. */
  560.   int whole_word = 0;        /* Insist that the regexp match a word only. */
  561.   int whole_line = 0;        /* Insist on matching only whole lines. */
  562.   int line_count = 0;        /* Count of matching lines for a file. */
  563.   int matches_found = 0;    /* True if matches were found. */
  564.   char *regex_errmesg;        /* Error message from regex routines. */
  565.   char translate[_NOTCHAR];    /* Translate table for case conversion
  566.                    (needed by the backtracking matcher). */
  567.  
  568.   if (prog = strrchr(argv[0], '/'))
  569.     ++prog;
  570.   else
  571.     prog = argv[0];
  572.  
  573.   opterr = 0;
  574.   while ((c = getopt(argc, argv, "0123456789A:B:CVbce:f:hilnsvwx")) != EOF)
  575.     switch (c)
  576.       {
  577.       case '?':
  578.     usage_and_die();
  579.     break;
  580.  
  581.       case '0':
  582.       case '1':
  583.       case '2':
  584.       case '3':
  585.       case '4':
  586.       case '5':
  587.       case '6':
  588.       case '7':
  589.       case '8':
  590.       case '9':
  591.     trailing_context = 10 * trailing_context + c - '0';
  592.     leading_context = 10 * leading_context + c - '0';
  593.     break;
  594.  
  595.       case 'A':
  596.     if (! sscanf(optarg, "%d", &trailing_context)
  597.         || trailing_context < 0)
  598.       usage_and_die();
  599.     break;
  600.  
  601.       case 'B':
  602.     if (! sscanf(optarg, "%d", &leading_context)
  603.         || leading_context < 0)
  604.       usage_and_die();
  605.     break;
  606.  
  607.       case 'C':
  608.     trailing_context = leading_context = 2;
  609.     break;
  610.  
  611.       case 'V':
  612.     fprintf(stderr, "%s\n", version);
  613.     break;
  614.  
  615.       case 'b':
  616.     byte_count = 1;
  617.     break;
  618.  
  619.       case 'c':
  620.     count_lines = 1;
  621.     silent = 1;
  622.     break;
  623.  
  624.       case 'e':
  625.     /* It doesn't make sense to mix -f and -e. */
  626.     if (regexp_file)
  627.       usage_and_die();
  628.     the_regexp = optarg;
  629.     break;
  630.  
  631.       case 'f':
  632.     /* It doesn't make sense to mix -f and -e. */
  633.     if (the_regexp)
  634.       usage_and_die();
  635.     regexp_file = optarg;
  636.     break;
  637.  
  638.       case 'h':
  639.     no_filenames = 1;
  640.     break;
  641.  
  642.       case 'i':
  643.     ignore_case = 1;
  644.     for (c = 0; c < _NOTCHAR; ++c)
  645.       if (isupper(c))
  646.         translate[c] = tolower(c);
  647.       else
  648.         translate[c] = c;
  649.     regex.translate = translate;
  650.     break;
  651.  
  652.       case 'l':
  653.     list_files = 1;
  654.     silent = 1;
  655.     break;
  656.  
  657.       case 'n':
  658.     line_numbers = 1;
  659.     break;
  660.  
  661.       case 's':
  662.     silent = 1;
  663.     break;
  664.  
  665.       case 'v':
  666.     nonmatching_lines = 1;
  667.     break;
  668.  
  669.       case 'w':
  670.     whole_word = 1;
  671.     break;
  672.  
  673.       case 'x':
  674.     whole_line = 1;
  675.     break;
  676.  
  677.       default:
  678.     /* This can't happen. */
  679.     fprintf(stderr, "%s: getopt(3) let one by!\n", prog);
  680.     usage_and_die();
  681.     break;
  682.       }
  683.  
  684.   /* Set the syntax depending on whether we are EGREP or not. */
  685. #ifdef EGREP
  686.   regsyntax(RE_SYNTAX_EGREP, ignore_case);
  687.   re_set_syntax(RE_SYNTAX_EGREP);
  688. #else
  689.   regsyntax(RE_SYNTAX_GREP, ignore_case);
  690.   re_set_syntax(RE_SYNTAX_GREP);
  691. #endif
  692.  
  693.   /* Compile the regexp according to all the options. */
  694.   if (regexp_file)
  695.     {
  696.       FILE *fp = fopen(regexp_file, "r");
  697.       int len = 256;
  698.       int i = 0;
  699.  
  700.       if (! fp)
  701.     {
  702.       fprintf(stderr, "%s: %s: %s\n", prog, regexp_file,
  703.           sys_errlist[errno]);
  704.       CleanExit(ERROR);
  705.     }
  706.  
  707.       the_regexp = malloc(len);
  708.       while ((c = getc(fp)) != EOF)
  709.     {
  710.       the_regexp[i++] = c;
  711.       if (i == len)
  712.         the_regexp = realloc(the_regexp, len *= 2);
  713.     }
  714.       fclose(fp);
  715.       /* Nuke the concluding newline so we won't match the empty string. */
  716.       if (i > 0 && the_regexp[i - 1] == '\n')
  717.     --i;
  718.       regexp_len = i;
  719.     }
  720.   else if (! the_regexp)
  721.     {
  722.       if (optind >= argc)
  723.     usage_and_die();
  724.       the_regexp = argv[optind++];
  725.       regexp_len = strlen(the_regexp);
  726.     }
  727.   else
  728.     regexp_len = strlen(the_regexp);
  729.   
  730.   if (whole_word || whole_line)
  731.     {
  732.       char *n = malloc(regexp_len + 8);
  733.       int i = 0;
  734.  
  735.       if (whole_line)
  736.     n[i++] = '^';
  737.       else
  738.     n[i++] = '\\', n[i++] = '<';
  739.       if (*prog != 'e')
  740.     n[i++] = '\\';
  741.       n[i++] = '(';
  742.       memcpy(n + i, the_regexp, regexp_len);
  743.       i += regexp_len;
  744.       if (*prog != 'e')
  745.     n[i++] = '\\';
  746.       n[i++] = ')';
  747.       if (whole_line)
  748.     n[i++] = '$';
  749.       else
  750.     n[i++] = '\\', n[i++] = '>';
  751.       the_regexp = n;
  752.       regexp_len = i;
  753.     }
  754.  
  755.   regcompile(the_regexp, regexp_len, ®, 1);
  756.   
  757.   if (regex_errmesg = re_compile_pattern(the_regexp, regexp_len, ®ex))
  758.     regerror(regex_errmesg);
  759.   
  760.   /*
  761.     Find the longest metacharacter-free string which must occur in the
  762.     regexpr, before short-circuiting regexecute() with Boyer-Moore-Gosper.
  763.     (Conjecture:  The problem in general is NP-complete.)  If there is no
  764.     such string (like for many alternations), then default to full automaton
  765.     search.  regmust() code and heuristics [see dfa.c] courtesy
  766.     Arthur David Olson.
  767.     */
  768.   if (line_numbers == 0 && nonmatching_lines == 0)
  769.     {
  770.       if (reg.mustn == 0 || reg.mustn == MUST_MAX ||
  771.         strchr(reg.must, '\0') != reg.must + reg.mustn)
  772.     bmgexec = 0;
  773.       else
  774.     {
  775.       reg.must[reg.mustn] = '\0';
  776.       if (getenv("MUSTDEBUG") != NULL)
  777.         (void) printf("must have: \"%s\"\n", reg.must);
  778.       bmg_setup(reg.must, ignore_case);
  779.       bmgexec = 1;
  780.     }
  781.     }
  782.   
  783.   if (argc - optind < 2)
  784.     no_filenames = 1;
  785.  
  786.   initialize_buffer();
  787.  
  788.   if (argc > optind)
  789.     while (optind < argc)
  790.       {
  791.     bufprev = eof = 0;
  792.     filename = argv[optind++];
  793.     fd = open(filename, 0, 0);
  794.     if (fd < 0)
  795.       {
  796.         fprintf(stderr, "%s: %s: %s\n", prog, filename,
  797.             sys_errlist[errno]);
  798.         error = 1;
  799.         continue;
  800.       }
  801.     if (line_count = grep())
  802.       matches_found = 1;
  803.     close(fd);
  804.     if (count_lines)
  805.       if (!no_filenames)
  806.         printf("%s:%d\n", filename, line_count);
  807.       else
  808.         printf("%d\n", line_count);
  809.     else if (list_files && line_count)
  810.       printf("%s\n", filename);
  811.       }
  812.   else
  813.     {
  814.       if (line_count = grep())
  815.     matches_found = 1;
  816.       if (count_lines)
  817.     printf("%d\n", line_count);
  818.       else if (list_files && line_count)
  819.     printf("<stdin>\n");
  820.     }
  821.  
  822.   if (error)
  823.     CleanExit(ERROR);
  824.   if (matches_found)
  825.     CleanExit(MATCHES_FOUND);
  826.   CleanExit(NO_MATCHES_FOUND);
  827. }
  828.  
  829. /* Needed by the regexp routines.  This could be fancier, especially when
  830.    dealing with parallel regexps in files. */
  831. void
  832. regerror(s)
  833.      const char *s;
  834. {
  835.   fprintf(stderr, "%s: %s\n", prog, s);
  836.   CleanExit(ERROR);
  837. }
  838.  
  839. /*
  840.    bmg_setup() and bmg_search() adapted from:
  841.      Boyer/Moore/Gosper-assisted 'egrep' search, with delta0 table as in
  842.      original paper (CACM, October, 1977).  No delta1 or delta2.  According to
  843.      experiment (Horspool, Soft. Prac. Exp., 1982), delta2 is of minimal
  844.      practical value.  However, to improve for worst case input, integrating
  845.      the improved Galil strategies (Apostolico/Giancarlo, Siam. J. Comput.,
  846.      February 1986) deserves consideration.
  847.  
  848.      James A. Woods                Copyleft (C) 1986, 1988
  849.      NASA Ames Research Center
  850. */
  851.  
  852. char *
  853. execute(r, begin, end, newline, count, try_backref)
  854.   struct regexp *r;
  855.   char *begin;
  856.   char *end;
  857.   int newline;
  858.   int *count;
  859.   int *try_backref;
  860. {
  861.   register char *p, *s;
  862.   char *match;
  863.   char *start = begin;
  864.   char save;            /* regexecute() sentinel */
  865.   int len;
  866.   char *bmg_search();
  867.  
  868.   if (!bmgexec)            /* full automaton search */
  869.     return(regexecute(r, begin, end, newline, count, try_backref));
  870.   else
  871.     {
  872.       len = end - begin; 
  873.       while ((match = bmg_search((unsigned char *) start, len)) != NULL)
  874.     {
  875.       p = match;        /* narrow search range to submatch line */
  876.       while (p > begin && *p != '\n')
  877.         p--;
  878.       s = match;
  879.       while (s < end && *s != '\n')
  880.         s++;
  881.       s++;
  882.  
  883.       save = *s;
  884.       *s = '\0';
  885.       match = regexecute(r, p, s, newline, count, try_backref);
  886.       *s = save;
  887.  
  888.       if (match != NULL)
  889.         return((char *) match);
  890.       else
  891.         {
  892.           start = s;
  893.           len = end - start;
  894.         }
  895.     }
  896.       return(NULL);
  897.     }
  898. }
  899.  
  900. #include <ctype.h>
  901. int        delta0[256];
  902. unsigned char   cmap[256];        /* (un)folded characters */
  903. unsigned char    pattern[5000];
  904. int        patlen;
  905.  
  906. char *
  907. bmg_search(buffer, buflen)
  908.   unsigned char *buffer;
  909.   int buflen;
  910. {
  911.   register unsigned char *k, *strend, *s, *buflim;
  912.   register int t;
  913.   int j;
  914.  
  915.   if (patlen > buflen)
  916.     return NULL;
  917.  
  918.   buflim = buffer + buflen;
  919.   if (buflen > patlen * 4)
  920.     strend = buflim - patlen * 4;
  921.   else
  922.     strend = buffer;
  923.  
  924.   s = buffer;
  925.   k = buffer + patlen - 1;
  926.  
  927.   for (;;)
  928.     {
  929.       /* The dreaded inner loop, revisited. */
  930.       while (k < strend && (t = delta0[*k]))
  931.     {
  932.       k += t;
  933.       k += delta0[*k];
  934.       k += delta0[*k];
  935.     }
  936.       while (k < buflim && delta0[*k])
  937.     ++k;
  938.       if (k == buflim)
  939.     break;
  940.     
  941.       j = patlen - 1;
  942.       s = k;
  943.       while (cmap[*--s] == pattern[--j])
  944.     ;
  945.       /* 
  946.     delta-less shortcut for literati, but 
  947.     short shrift for genetic engineers.
  948.       */
  949.       if (j >= 0)
  950.     k++;
  951.       else         /* submatch */
  952.     return ((char *)k);
  953.     }
  954.   return(NULL);
  955. }
  956.  
  957. bmg_setup(pat, folded)            /* compute "boyer-moore" delta table */
  958.   char *pat;
  959.   int folded;
  960. {                    /* ... HAKMEM lives ... */
  961.   int j;
  962.  
  963.   patlen = strlen(pat);
  964.  
  965.   if (folded)                 /* fold case while saving pattern */
  966.     for (j = 0; j < patlen; j++) 
  967.       pattern[j] = (isupper((int) pat[j]) ?
  968.     (char) tolower((int) pat[j]) : pat[j]);
  969.   else
  970.       memcpy(pattern, pat, patlen);
  971.  
  972.   for (j = 0; j < 256; j++)
  973.     {
  974.       delta0[j] = patlen;
  975.       cmap[j] = (char) j;        /* could be done at compile time */
  976.     }
  977.   for (j = 0; j < patlen - 1; j++)
  978.     delta0[pattern[j]] = patlen - j - 1;
  979.   delta0[pattern[patlen - 1]] = 0;
  980.  
  981.   if (folded)
  982.     {
  983.       for (j = 0; j < patlen - 1; j++)
  984.     if (islower((int) pattern[j]))
  985.       delta0[toupper((int) pattern[j])] = patlen - j - 1;
  986.     if (islower((int) pattern[patlen - 1]))
  987.       delta0[toupper((int) pattern[patlen - 1])] = 0;
  988.       for (j = 'A'; j <= 'Z'; j++)
  989.     cmap[j] = (char) tolower((int) j);
  990.     }
  991. }
  992.  
  993. #ifndef USG
  994.  
  995. /* (groan) compatibility */
  996.  
  997. char *
  998. strchr(s, c)
  999.      char *s;
  1000. {
  1001.   return index(s, c);
  1002. }
  1003.  
  1004. char *
  1005. strrchr(s, c)
  1006.      char *s;
  1007. {
  1008.   return rindex(s, c);
  1009. }
  1010.  
  1011. char *
  1012. memcpy(d, s, n)
  1013.      char *d, *s;
  1014. {
  1015.   return bcopy(s, d, n);
  1016. }
  1017.  
  1018. #else
  1019.  
  1020. char *
  1021. index(s, c)
  1022.      char *s;
  1023. {
  1024.   return strchr(s, c);
  1025. }
  1026.  
  1027. char *
  1028. bcopy(s, d, n)
  1029.      char *s, *d;
  1030. {
  1031.   return memcpy(d, s, n);
  1032. }
  1033.  
  1034. char *
  1035. bzero(s, n)
  1036.      char *s;
  1037. {
  1038.   return memset(s, 0, n);
  1039. }
  1040.  
  1041. bcmp(s, t, n)
  1042.      char *s, *t;
  1043. {
  1044.   return memcmp(s, t, n);
  1045. }
  1046.  
  1047. #endif
  1048.  
  1049. CleanExit(status)
  1050. {
  1051.     alloca(0);
  1052.     fclose(stdin);
  1053.     fclose(stdout);
  1054.     fclose(stderr);
  1055. #ifdef AMIGA
  1056.     rbrk(0);
  1057. #endif
  1058.     exit(status);
  1059. }
  1060.