home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / prgramer / rcs / sources / grep.c < prev    next >
C/C++ Source or Header  |  1992-01-19  |  31KB  |  1,081 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. #include <memory.h>
  112. #include <string.h>
  113. #else
  114. #include <strings.h>
  115. #endif
  116. #include "dfa.h"
  117. #include "regex.h"
  118.  
  119. #ifdef __STDC__
  120. extern getopt(int, char **, const char *);
  121. extern read(int, void *, int);
  122. extern open(const char *, int, ...);
  123. extern void close();
  124. #else
  125. extern char *strrchr();
  126. #endif
  127.  
  128. extern char *optarg;
  129. extern optind, opterr;
  130. #ifndef OS2
  131. extern errno;
  132. extern char *sys_errlist[];
  133. #endif
  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.       exit(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.       exit(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.           --match_count;        /* debugged by kaoru.  August 15, 1990. */
  379.           ++line_count;        /* debugged by kaoru.  August 15, 1990. */
  380.           resume = next_line;
  381.           if (resume == search_limit)
  382.         break;
  383.           else
  384.         continue;
  385.         }
  386.  
  387.       /* Print leftover lines from last time.  If nonmatching_lines is
  388.          turned on, print these as if they were matching lines. */
  389.       while (resume < matching_line && pending_lines)
  390.         {
  391.           resume += print_line(resume, initial_line_count++,
  392.                    nonmatching_lines);
  393.           --pending_lines;
  394.         }
  395.  
  396.       /* Print out the matching or nonmatching lines as necessary. */
  397.       if (! nonmatching_lines)
  398.         {
  399.           /* Back up over leading context if necessary. */
  400.           for (i = leading_context; matching_line > printed_limit
  401.            && i; --i)
  402.         {
  403.           while (matching_line > printed_limit
  404.              && (--matching_line)[-1] != '\n')
  405.             ;
  406.           --line_count;
  407.         }
  408.  
  409.           /* If context is enabled, we may have to print a separator. */
  410.           if ((leading_context || trailing_context) && !silent
  411.           && !first_match && (printed_limit_fake || matching_line
  412.                       > printed_limit))
  413.         printf("----------\n");
  414.           first_match = 0;
  415.  
  416.           /* Print the matching line and its leading context. */
  417.           while (matching_line < real_matching_line)
  418.         matching_line += print_line(matching_line, line_count++, 0);
  419.           matching_line += print_line(matching_line, line_count++, 1);
  420.  
  421.           /* If there's trailing context, leave some lines pending until
  422.          next time. */
  423.           pending_lines = trailing_context;
  424.         }
  425.       else if (matching_line > resume)
  426.         {
  427.           char *real_resume = resume;
  428.  
  429.           /* Back up over leading context if necessary. */
  430.           for (i = leading_context; resume > printed_limit && i; --i)
  431.         {
  432.           while (resume > printed_limit && (--resume)[-1] != '\n')
  433.             ;
  434.           --initial_line_count;
  435.         }
  436.  
  437.           /* If context is enabled, we may have to print a separator. */
  438.           if ((leading_context || trailing_context) && !silent
  439.           && !first_match && (printed_limit_fake || resume
  440.                       > printed_limit))
  441.         printf("----------\n");
  442.           first_match = 0;
  443.  
  444.           /* Print out the presumably matching leading context. */
  445.           while (resume < real_resume)
  446.         resume += print_line(resume, initial_line_count++, 0);
  447.  
  448.           /* Print out the nonmatching lines prior to the matching line. */
  449.           while (resume < matching_line)
  450.         resume += print_line(resume, initial_line_count++, 1);
  451.  
  452.           /* Deal with trailing context. */
  453.           if (trailing_context)
  454.         {
  455.           print_line(matching_line, line_count, 0);
  456.           pending_lines = trailing_context - 1;
  457.         }
  458.  
  459.           /* Count the current line. */
  460.           ++line_count;
  461.         }
  462.       else
  463.         {
  464.           /* The line immediately after a matching line has to be printed
  465.          because it was pending. */
  466.           if (pending_lines > 0)
  467.         {
  468.           --pending_lines;
  469.           print_line(matching_line, line_count, 0);
  470.         }
  471.           ++line_count;
  472.         }
  473.  
  474.       /* Resume searching at the beginning of the next line. */
  475.       initial_line_count = line_count;
  476.       resume = next_line;
  477.  
  478.       if (resume == search_limit)
  479.         break;
  480.     }
  481.  
  482.       /* Restore the saved character. */
  483.       *search_limit = saved_char;
  484.  
  485.       if (! nonmatching_lines)
  486.     {
  487.       while (resume < search_limit && pending_lines)
  488.         {
  489.           resume += print_line(resume, initial_line_count++, 0);
  490.           --pending_lines;
  491.         }
  492.     }
  493.       else if (search_limit > resume)
  494.     {
  495.       char *initial_resume = resume;
  496.  
  497.       /* Back up over leading context if necessary. */
  498.       for (i = leading_context; resume > printed_limit && i; --i)
  499.         {
  500.           while (resume > printed_limit && (--resume)[-1] != '\n')
  501.         ;
  502.           --initial_line_count;
  503.         }
  504.  
  505.       /* If context is enabled, we may have to print a separator. */
  506.       if ((leading_context || trailing_context) && !silent
  507.           && !first_match && (printed_limit_fake || resume
  508.                   > printed_limit))
  509.         printf("----------\n");
  510.       first_match = 0;
  511.  
  512.       /* Print out all the nonmatching lines up to the search limit. */
  513.       while (resume < initial_resume)
  514.         resume += print_line(resume, initial_line_count++, 0);
  515.       while (resume < search_limit)
  516.         resume += print_line(resume, initial_line_count++, 1);
  517.  
  518.       pending_lines = trailing_context;
  519.       resume_index = 0;
  520.       retain = bufbytes - (search_limit - buffer);
  521.       continue;
  522.     }
  523.  
  524.       /* Save the trailing end of the buffer for possible use as leading
  525.      context in the future. */
  526.       i = leading_context;
  527.       tmp = search_limit;
  528.       while (tmp > printed_limit && i--)
  529.     while (tmp > printed_limit && (--tmp)[-1] != '\n')
  530.       ;
  531.       resume_index = search_limit - tmp;
  532.       retain = bufbytes - (tmp - buffer);
  533.       if (tmp > printed_limit)
  534.     printed_limit_fake = 1;
  535.     }
  536.  
  537.   return nonmatching_lines ? (line_count - 1) - match_count : match_count;
  538. }
  539.  
  540.  
  541. #ifdef EGREP
  542. static char version[] = "GNU egrep, version 1.5";
  543. #else
  544. static char version[] = "GNU grep, version 1.5";
  545. #endif
  546.  
  547. void
  548. usage_and_die()
  549. {
  550.   printf("\n%s\n", version);
  551.   printf("\nUsage: %s [-CVbchilnsvwx] [-<num>] [-AB <num>]"
  552.                     " [-f file] [-e] expr [files]\n\n", prog);
  553.   printf(
  554.   "  -A <num>  print <num> lines of context after every matching line\n"
  555.   "  -B <num>  print <num> lines of context before every matching line\n"
  556.   "  -C        print 2 lines of context on each side of every match\n"
  557.   "  -<num>    print <num> lines of context on each side\n"
  558.   "  -V        print the version number on stderr\n"
  559.   );
  560.   printf(
  561.   "  -b        print every match preceded by its byte offset\n"
  562.   "  -c        print a total count of matching lines only\n"
  563.   "  -e <expr> search for <expr>; useful if <expr> begins with -\n"
  564.   "  -f <file> take <expr> from the given <file>\n"
  565.   "  -h        don't display filenames on matches\n"
  566.   "  -i        ignore case difference when comparing strings\n"
  567.   );
  568.   printf(
  569.   "  -l        list files containing matches only\n"
  570.   "  -n        print each match preceded by its line number\n"
  571.   "  -s        run silently producing no output except error messages\n"
  572.   "  -v        print only lines that contain no matches for the <expr>\n"
  573.   "  -w        print only lines where the match is a complete word\n"
  574.   "  -x        print only lines where the match is a whole line\n");
  575.  
  576.   exit(ERROR);
  577. }
  578.  
  579. main(argc, argv)
  580.      int argc;
  581.      char **argv;
  582. {
  583.   int c;
  584.   int ignore_case = 0;        /* Compile the regexp to ignore case. */
  585.   char *the_regexp = 0;        /* The regular expression. */
  586.   int regexp_len;        /* Length of the regular expression. */
  587.   char *regexp_file = 0;    /* File containing parallel regexps. */
  588.   int count_lines = 0;        /* Display only a count of matching lines. */
  589.   int list_files = 0;        /* Display only the names of matching files. */
  590.   int whole_word = 0;        /* Insist that the regexp match a word only. */
  591.   int whole_line = 0;        /* Insist on matching only whole lines. */
  592.   int line_count = 0;        /* Count of matching lines for a file. */
  593.   int matches_found = 0;    /* True if matches were found. */
  594.   char *regex_errmesg;        /* Error message from regex routines. */
  595.   char translate[_NOTCHAR];    /* Translate table for case conversion
  596.                    (needed by the backtracking matcher). */
  597.  
  598.   if (prog = strrchr(argv[0], '/'))
  599.     ++prog;
  600.   else
  601.     prog = argv[0];
  602.  
  603.   opterr = 0;
  604.   while ((c = getopt(argc, argv, "0123456789A:B:CVbce:f:hilnsvwx")) != EOF)
  605.     switch (c)
  606.       {
  607.       case '?':
  608.     usage_and_die();
  609.     break;
  610.  
  611.       case '0':
  612.       case '1':
  613.       case '2':
  614.       case '3':
  615.       case '4':
  616.       case '5':
  617.       case '6':
  618.       case '7':
  619.       case '8':
  620.       case '9':
  621.     trailing_context = 10 * trailing_context + c - '0';
  622.     leading_context = 10 * leading_context + c - '0';
  623.     break;
  624.  
  625.       case 'A':
  626.     if (! sscanf(optarg, "%d", &trailing_context)
  627.         || trailing_context < 0)
  628.       usage_and_die();
  629.     break;
  630.  
  631.       case 'B':
  632.     if (! sscanf(optarg, "%d", &leading_context)
  633.         || leading_context < 0)
  634.       usage_and_die();
  635.     break;
  636.  
  637.       case 'C':
  638.     trailing_context = leading_context = 2;
  639.     break;
  640.  
  641.       case 'V':
  642.         fprintf(stderr, "\n%s\n", version);
  643.         exit(ERROR);
  644.     break;
  645.  
  646.       case 'b':
  647.     byte_count = 1;
  648.     break;
  649.  
  650.       case 'c':
  651.     count_lines = 1;
  652.     silent = 1;
  653.     break;
  654.  
  655.       case 'e':
  656.     /* It doesn't make sense to mix -f and -e. */
  657.     if (regexp_file)
  658.       usage_and_die();
  659.     the_regexp = optarg;
  660.     break;
  661.  
  662.       case 'f':
  663.     /* It doesn't make sense to mix -f and -e. */
  664.     if (the_regexp)
  665.       usage_and_die();
  666.     regexp_file = optarg;
  667.     break;
  668.  
  669.       case 'h':
  670.     no_filenames = 1;
  671.     break;
  672.  
  673.       case 'i':
  674.     ignore_case = 1;
  675.     for (c = 0; c < _NOTCHAR; ++c)
  676.       if (isupper(c))
  677.         translate[c] = tolower(c);
  678.       else
  679.         translate[c] = c;
  680.     regex.translate = translate;
  681.     break;
  682.  
  683.       case 'l':
  684.     list_files = 1;
  685.     silent = 1;
  686.     break;
  687.  
  688.       case 'n':
  689.     line_numbers = 1;
  690.     break;
  691.  
  692.       case 's':
  693.     silent = 1;
  694.     break;
  695.  
  696.       case 'v':
  697.     nonmatching_lines = 1;
  698.     break;
  699.  
  700.       case 'w':
  701.     whole_word = 1;
  702.     break;
  703.  
  704.       case 'x':
  705.     whole_line = 1;
  706.     break;
  707.  
  708.       default:
  709.     /* This can't happen. */
  710.     fprintf(stderr, "%s: getopt(3) let one by!\n", prog);
  711.     usage_and_die();
  712.     break;
  713.       }
  714.  
  715.   /* Set the syntax depending on whether we are EGREP or not. */
  716. #ifdef EGREP
  717.   regsyntax(RE_SYNTAX_EGREP, ignore_case);
  718.   re_set_syntax(RE_SYNTAX_EGREP);
  719. #else
  720.   regsyntax(RE_SYNTAX_GREP, ignore_case);
  721.   re_set_syntax(RE_SYNTAX_GREP);
  722. #endif
  723.  
  724.   /* Compile the regexp according to all the options. */
  725.   if (regexp_file)
  726.     {
  727.       FILE *fp = fopen(regexp_file, "r");
  728.       int len = 256;
  729.       int i = 0;
  730.  
  731.       if (! fp)
  732.     {
  733.       fprintf(stderr, "%s: %s: %s\n", prog, regexp_file,
  734.           sys_errlist[errno]);
  735.       exit(ERROR);
  736.     }
  737.  
  738.       the_regexp = malloc(len);
  739.       while ((c = getc(fp)) != EOF)
  740.     {
  741.       the_regexp[i++] = c;
  742.       if (i == len)
  743.         the_regexp = realloc(the_regexp, len *= 2);
  744.     }
  745.       fclose(fp);
  746.       /* Nuke the concluding newline so we won't match the empty string. */
  747.       if (i > 0 && the_regexp[i - 1] == '\n')
  748.     --i;
  749.       regexp_len = i;
  750.     }
  751.   else if (! the_regexp)
  752.     {
  753.       if (optind >= argc)
  754.     usage_and_die();
  755.       the_regexp = argv[optind++];
  756.       regexp_len = strlen(the_regexp);
  757.     }
  758.   else
  759.     regexp_len = strlen(the_regexp);
  760.  
  761.   if (whole_word || whole_line)
  762.     {
  763.       char *n = malloc(regexp_len + 8);
  764.       int i = 0;
  765.  
  766.       if (whole_line)
  767.     n[i++] = '^';
  768.       else
  769.     n[i++] = '\\', n[i++] = '<';
  770. #ifndef EGREP
  771.       n[i++] = '\\';
  772. #endif
  773.       n[i++] = '(';
  774.       memcpy(n + i, the_regexp, regexp_len);
  775.       i += regexp_len;
  776. #ifndef EGREP
  777.       n[i++] = '\\';
  778. #endif
  779.       n[i++] = ')';
  780.       if (whole_line)
  781.     n[i++] = '$';
  782.       else
  783.     n[i++] = '\\', n[i++] = '>';
  784.       the_regexp = n;
  785.       regexp_len = i;
  786.     }
  787.  
  788.   regcompile(the_regexp, regexp_len, ®, 1);
  789.  
  790.   if (regex_errmesg = re_compile_pattern(the_regexp, regexp_len, ®ex))
  791.     regerror(regex_errmesg);
  792.  
  793.   /*
  794.     Find the longest metacharacter-free string which must occur in the
  795.     regexpr, before short-circuiting regexecute() with Boyer-Moore-Gosper.
  796.     (Conjecture:  The problem in general is NP-complete.)  If there is no
  797.     such string (like for many alternations), then default to full automaton
  798.     search.  regmust() code and heuristics [see dfa.c] courtesy
  799.     Arthur David Olson.
  800.     */
  801.   if (line_numbers == 0 && nonmatching_lines == 0)
  802.     {
  803.       if (reg.mustn == 0 || reg.mustn == MUST_MAX ||
  804.         strchr(reg.must, '\0') != reg.must + reg.mustn)
  805.     bmgexec = 0;
  806.       else
  807.     {
  808.       reg.must[reg.mustn] = '\0';
  809.       if (getenv("MUSTDEBUG") != NULL)
  810.         (void) printf("must have: \"%s\"\n", reg.must);
  811.       bmg_setup(reg.must, ignore_case);
  812.       bmgexec = 1;
  813.     }
  814.     }
  815.  
  816.   if (argc - optind < 2)
  817.     no_filenames = 1;
  818.  
  819.   initialize_buffer();
  820.  
  821.   if (argc > optind)
  822.     while (optind < argc)
  823.       {
  824.     bufprev = eof = 0;
  825.     filename = argv[optind++];
  826.     fd = open(filename, 0, 0);
  827.     if (fd < 0)
  828.       {
  829.         fprintf(stderr, "%s: %s: %s\n", prog, filename,
  830.             sys_errlist[errno]);
  831.         error = 1;
  832.         continue;
  833.       }
  834.     if (line_count = grep())
  835.       matches_found = 1;
  836.     close(fd);
  837.     if (count_lines)
  838.       if (!no_filenames)
  839.         printf("%s:%d\n", filename, line_count);
  840.       else
  841.         printf("%d\n", line_count);
  842.     else if (list_files && line_count)
  843.       printf("%s\n", filename);
  844.       }
  845.   else
  846.     {
  847.       if (line_count = grep())
  848.     matches_found = 1;
  849.       if (count_lines)
  850.     printf("%d\n", line_count);
  851.       else if (list_files && line_count)
  852.     printf("<stdin>\n");
  853.     }
  854.  
  855.   if (error)
  856.     exit(ERROR);
  857.   if (matches_found)
  858.     exit(MATCHES_FOUND);
  859.   exit(NO_MATCHES_FOUND);
  860. }
  861.  
  862. /* Needed by the regexp routines.  This could be fancier, especially when
  863.    dealing with parallel regexps in files. */
  864. void
  865. regerror(s)
  866.      const char *s;
  867. {
  868.   fprintf(stderr, "%s: %s\n", prog, s);
  869.   exit(ERROR);
  870. }
  871.  
  872. /*
  873.    bmg_setup() and bmg_search() adapted from:
  874.      Boyer/Moore/Gosper-assisted 'egrep' search, with delta0 table as in
  875.      original paper (CACM, October, 1977).  No delta1 or delta2.  According to
  876.      experiment (Horspool, Soft. Prac. Exp., 1982), delta2 is of minimal
  877.      practical value.  However, to improve for worst case input, integrating
  878.      the improved Galil strategies (Apostolico/Giancarlo, Siam. J. Comput.,
  879.      February 1986) deserves consideration.
  880.  
  881.      James A. Woods                Copyleft (C) 1986, 1988
  882.      NASA Ames Research Center
  883. */
  884.  
  885. char *
  886. execute(r, begin, end, newline, count, try_backref)
  887.   struct regexp *r;
  888.   char *begin;
  889.   char *end;
  890.   int newline;
  891.   int *count;
  892.   int *try_backref;
  893. {
  894.   register char *p, *s;
  895.   char *match;
  896.   char *start = begin;
  897.   char save;            /* regexecute() sentinel */
  898.   int len;
  899.   char *bmg_search();
  900.  
  901.   if (!bmgexec)            /* full automaton search */
  902.     return(regexecute(r, begin, end, newline, count, try_backref));
  903.   else
  904.     {
  905.       len = end - begin;
  906.       while ((match = bmg_search((unsigned char *) start, len)) != NULL)
  907.     {
  908.       p = match;        /* narrow search range to submatch line */
  909.       while (p > begin && *p != '\n')
  910.         p--;
  911.       s = match;
  912.       while (s < end && *s != '\n')
  913.         s++;
  914.       s++;
  915.  
  916.       save = *s;
  917.       *s = '\0';
  918.       match = regexecute(r, p, s, newline, count, try_backref);
  919.       *s = save;
  920.  
  921.       if (match != NULL)
  922.         return((char *) match);
  923.       else
  924.         {
  925.           start = s;
  926.           len = end - start;
  927.         }
  928.     }
  929.       return(NULL);
  930.     }
  931. }
  932.  
  933. #include <ctype.h>
  934. int        delta0[256];
  935. unsigned char   cmap[256];        /* (un)folded characters */
  936. unsigned char    pattern[5000];
  937. int        patlen;
  938.  
  939. char *
  940. bmg_search(buffer, buflen)
  941.   unsigned char *buffer;
  942.   int buflen;
  943. {
  944.   register unsigned char *k, *strend, *s, *buflim;
  945.   register int t;
  946.   int j;
  947.  
  948.   if (patlen > buflen)
  949.     return NULL;
  950.  
  951.   buflim = buffer + buflen;
  952.   if (buflen > patlen * 4)
  953.     strend = buflim - patlen * 4;
  954.   else
  955.     strend = buffer;
  956.  
  957.   s = buffer;
  958.   k = buffer + patlen - 1;
  959.  
  960.   for (;;)
  961.     {
  962.       /* The dreaded inner loop, revisited. */
  963.       while (k < strend && (t = delta0[*k]))
  964.     {
  965.       k += t;
  966.       k += delta0[*k];
  967.       k += delta0[*k];
  968.     }
  969.       while (k < buflim && delta0[*k])
  970.     ++k;
  971.       if (k == buflim)
  972.     break;
  973.  
  974.       j = patlen - 1;
  975.       s = k;
  976.       while (--j >= 0 && cmap[*--s] == pattern[j])
  977.     ;
  978.       /*
  979.     delta-less shortcut for literati, but
  980.     short shrift for genetic engineers.
  981.       */
  982.       if (j >= 0)
  983.     k++;
  984.       else         /* submatch */
  985.     return ((char *)k);
  986.     }
  987.   return(NULL);
  988. }
  989.  
  990. bmg_setup(pat, folded)            /* compute "boyer-moore" delta table */
  991.   char *pat;
  992.   int folded;
  993. {                    /* ... HAKMEM lives ... */
  994.   int j;
  995.  
  996.   patlen = strlen(pat);
  997.  
  998.   if (folded)                 /* fold case while saving pattern */
  999.     for (j = 0; j < patlen; j++)
  1000.       pattern[j] = (isupper((int) pat[j]) ?
  1001.     (char) tolower((int) pat[j]) : pat[j]);
  1002.   else
  1003.       memcpy(pattern, pat, patlen);
  1004.  
  1005.   for (j = 0; j < 256; j++)
  1006.     {
  1007.       delta0[j] = patlen;
  1008.       cmap[j] = (char) j;        /* could be done at compile time */
  1009.     }
  1010.   for (j = 0; j < patlen - 1; j++)
  1011.     delta0[pattern[j]] = patlen - j - 1;
  1012.   delta0[pattern[patlen - 1]] = 0;
  1013.  
  1014.   if (folded)
  1015.     {
  1016.       for (j = 0; j < patlen - 1; j++)
  1017.     if (islower((int) pattern[j]))
  1018.       delta0[toupper((int) pattern[j])] = patlen - j - 1;
  1019.     if (islower((int) pattern[patlen - 1]))
  1020.       delta0[toupper((int) pattern[patlen - 1])] = 0;
  1021.       for (j = 'A'; j <= 'Z'; j++)
  1022.     cmap[j] = (char) tolower((int) j);
  1023.     }
  1024. }
  1025.  
  1026. #ifndef USG
  1027.  
  1028. /* (groan) compatibility */
  1029.  
  1030. char *
  1031. strchr(s, c)
  1032.      char *s;
  1033. {
  1034.   return index(s, c);
  1035. }
  1036.  
  1037. char *
  1038. strrchr(s, c)
  1039.      char *s;
  1040. {
  1041.   return rindex(s, c);
  1042. }
  1043.  
  1044. char *
  1045. memcpy(d, s, n)
  1046.      char *d, *s;
  1047. {
  1048.   return bcopy(s, d, n);
  1049. }
  1050.  
  1051. #else
  1052.  
  1053. char *
  1054. index(s, c)
  1055.      char *s;
  1056. {
  1057.   return strchr(s, c);
  1058. }
  1059.  
  1060. char *
  1061. bcopy(s, d, n)
  1062.      char *s, *d;
  1063. {
  1064.   return memcpy(d, s, n);
  1065. }
  1066.  
  1067. char *
  1068. bzero(s, n)
  1069.      char *s;
  1070. {
  1071.   return memset(s, 0, n);
  1072. }
  1073.  
  1074. bcmp(s, t, n)
  1075.      char *s, *t;
  1076. {
  1077.   return memcmp(s, t, n);
  1078. }
  1079.  
  1080. #endif
  1081.