home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 22 gnu / 22-gnu.zip / grep20.zip / search.c < prev   
C/C++ Source or Header  |  1993-05-02  |  12KB  |  482 lines

  1. /* search.c - searching subroutines using dfa, kwset and regex for grep.
  2.    Copyright (C) 1992 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17.  
  18.    Written August 1992 by Mike Haertel. */
  19.  
  20. #include <ctype.h>
  21.  
  22. #ifdef STDC_HEADERS
  23. #include <limits.h>
  24. #include <stdlib.h>
  25. #else
  26. #define UCHAR_MAX 255
  27. #include <sys/types.h>
  28. extern char *malloc();
  29. #endif
  30.  
  31. #ifdef HAVE_MEMCHR
  32. #include <string.h>
  33. #ifdef NEED_MEMORY_H
  34. #include <memory.h>
  35. #endif
  36. #else
  37. #ifdef __STDC__
  38. extern void *memchr();
  39. #else
  40. extern char *memchr();
  41. #endif
  42. #endif
  43.  
  44. #if defined(HAVE_STRING_H) || defined(STDC_HEADERS)
  45. #undef bcopy
  46. #define bcopy(s, d, n) memcpy((d), (s), (n))
  47. #endif
  48.  
  49. #ifdef isascii
  50. #define ISALNUM(C) (isascii(C) && isalnum(C))
  51. #define ISUPPER(C) (isascii(C) && isupper(C))
  52. #else
  53. #define ISALNUM(C) isalnum(C)
  54. #define ISUPPER(C) isupper(C)
  55. #endif
  56.  
  57. #define TOLOWER(C) (ISUPPER(C) ? tolower(C) : (C))
  58.  
  59. #include "grep.h"
  60. #include "dfa.h"
  61. #include "kwset.h"
  62. #include "regex.h"
  63.  
  64. #define NCHAR (UCHAR_MAX + 1)
  65.  
  66. #if __STDC__
  67. static void Gcompile(char *, size_t);
  68. static void Ecompile(char *, size_t);
  69. static char *EGexecute(char *, size_t, char **);
  70. static void Fcompile(char *, size_t);
  71. static char *Fexecute(char *, size_t, char **);
  72. #else
  73. static void Gcompile();
  74. static void Ecompile();
  75. static char *EGexecute();
  76. static void Fcompile();
  77. static char *Fexecute();
  78. #endif
  79.  
  80. /* Here is the matchers vector for the main program. */
  81. struct matcher matchers[] = {
  82.   { "default", Gcompile, EGexecute },
  83.   { "grep", Gcompile, EGexecute },
  84.   { "ggrep", Gcompile, EGexecute },
  85.   { "egrep", Ecompile, EGexecute },
  86.   { "posix-egrep", Ecompile, EGexecute },
  87.   { "gegrep", Ecompile, EGexecute },
  88.   { "fgrep", Fcompile, Fexecute },
  89.   { "gfgrep", Fcompile, Fexecute },
  90.   { 0, 0, 0 },
  91. };
  92.  
  93. /* For -w, we also consider _ to be word constituent.  */
  94. #define WCHAR(C) (ISALNUM(C) || (C) == '_')
  95.  
  96. /* DFA compiled regexp. */
  97. static struct dfa dfa;
  98.  
  99. /* Regex compiled regexp. */
  100. static struct re_pattern_buffer regex;
  101.  
  102. /* KWset compiled pattern.  For Ecompile and Gcompile, we compile
  103.    a list of strings, at least one of which is known to occur in
  104.    any string matching the regexp. */
  105. static kwset_t kwset;
  106.  
  107. /* Last compiled fixed string known to exactly match the regexp.
  108.    If kwsexec() returns < lastexact, then we don't need to
  109.    call the regexp matcher at all. */
  110. static int lastexact;
  111.  
  112. void
  113. dfaerror(mesg)
  114.      char *mesg;
  115. {
  116.   fatal(mesg, 0);
  117. }
  118.  
  119. static void
  120. kwsinit()
  121. {
  122.   static char trans[NCHAR];
  123.   int i;
  124.  
  125.   if (match_icase)
  126.     for (i = 0; i < NCHAR; ++i)
  127.       trans[i] = TOLOWER(i);
  128.  
  129.   if (!(kwset = kwsalloc(match_icase ? trans : (char *) 0)))
  130.     fatal("memory exhausted", 0);
  131. }  
  132.  
  133. /* If the DFA turns out to have some set of fixed strings one of
  134.    which must occur in the match, then we build a kwset matcher
  135.    to find those strings, and thus quickly filter out impossible
  136.    matches. */
  137. static void
  138. kwsmusts()
  139. {
  140.   struct dfamust *dm;
  141.   char *err;
  142.  
  143.   if (dfa.musts)
  144.     {
  145.       kwsinit();
  146.       /* First, we compile in the substrings known to be exact
  147.      matches.  The kwset matcher will return the index
  148.      of the matching string that it chooses. */
  149.       for (dm = dfa.musts; dm; dm = dm->next)
  150.     {
  151.       if (!dm->exact)
  152.         continue;
  153.       ++lastexact;
  154.       if ((err = kwsincr(kwset, dm->must, strlen(dm->must))) != 0)
  155.         fatal(err, 0);
  156.     }
  157.       /* Now, we compile the substrings that will require
  158.      the use of the regexp matcher.  */
  159.       for (dm = dfa.musts; dm; dm = dm->next)
  160.     {
  161.       if (dm->exact)
  162.         continue;
  163.       if ((err = kwsincr(kwset, dm->must, strlen(dm->must))) != 0)
  164.         fatal(err, 0);
  165.     }
  166.       if ((err = kwsprep(kwset)) != 0)
  167.     fatal(err, 0);
  168.     }
  169. }
  170.  
  171. static void
  172. Gcompile(pattern, size)
  173.      char *pattern;
  174.      size_t size;
  175. {
  176. #ifdef __STDC__
  177.   const
  178. #endif
  179.   char *err;
  180.  
  181.   re_set_syntax(RE_SYNTAX_GREP | RE_HAT_LISTS_NOT_NEWLINE);
  182.   dfasyntax(RE_SYNTAX_GREP | RE_HAT_LISTS_NOT_NEWLINE, match_icase);
  183.  
  184.   if ((err = re_compile_pattern(pattern, size, ®ex)) != 0)
  185.     fatal(err, 0);
  186.  
  187.   dfainit(&dfa);
  188.  
  189.   /* In the match_words and match_lines cases, we use a different pattern
  190.      for the DFA matcher that will quickly throw out cases that won't work.
  191.      Then if DFA succeeds we do some hairy stuff using the regex matcher
  192.      to decide whether the match should really count. */
  193.   if (match_words || match_lines)
  194.     {
  195.       /* In the whole-word case, we use the pattern:
  196.      (^|[^A-Za-z_])(userpattern)([^A-Za-z_]|$).
  197.      In the whole-line case, we use the pattern:
  198.      ^(userpattern)$.
  199.      BUG: Using [A-Za-z_] is locale-dependent!  */
  200.  
  201.       char *n = malloc(size + 50);
  202.       int i = 0;
  203.  
  204.       strcpy(n, "");
  205.  
  206.       if (match_lines)
  207.     strcpy(n, "^\\(");
  208.       if (match_words)
  209.     strcpy(n, "\\(^\\|[^0-9A-Za-z_]\\)\\(");
  210.  
  211.       i = strlen(n);
  212.       bcopy(pattern, n + i, size);
  213.       i += size;
  214.  
  215.       if (match_words)
  216.     strcpy(n + i, "\\)\\([^0-9A-Za-z_]\\|$\\)");
  217.       if (match_lines)
  218.     strcpy(n + i, "\\)$");
  219.  
  220.       i += strlen(n + i);
  221.       dfacomp(n, i, &dfa, 1);
  222.     }
  223.   else
  224.     dfacomp(pattern, size, &dfa, 1);
  225.  
  226.   kwsmusts();
  227. }
  228.  
  229. static void
  230. Ecompile(pattern, size)
  231.      char *pattern;
  232.      size_t size;
  233. {
  234. #ifdef __STDC__
  235.   const
  236. #endif
  237.   char *err;
  238.  
  239.   if (strcmp(matcher, "posix-egrep") == 0)
  240.     {
  241.       re_set_syntax(RE_SYNTAX_POSIX_EGREP);
  242.       dfasyntax(RE_SYNTAX_POSIX_EGREP, match_icase);
  243.     }
  244.   else
  245.     {
  246.       re_set_syntax(RE_SYNTAX_EGREP);
  247.       dfasyntax(RE_SYNTAX_EGREP, match_icase);
  248.     }
  249.  
  250.   if ((err = re_compile_pattern(pattern, size, ®ex)) != 0)
  251.     fatal(err, 0);
  252.  
  253.   dfainit(&dfa);
  254.  
  255.   /* In the match_words and match_lines cases, we use a different pattern
  256.      for the DFA matcher that will quickly throw out cases that won't work.
  257.      Then if DFA succeeds we do some hairy stuff using the regex matcher
  258.      to decide whether the match should really count. */
  259.   if (match_words || match_lines)
  260.     {
  261.       /* In the whole-word case, we use the pattern:
  262.      (^|[^A-Za-z_])(userpattern)([^A-Za-z_]|$).
  263.      In the whole-line case, we use the pattern:
  264.      ^(userpattern)$.
  265.      BUG: Using [A-Za-z_] is locale-dependent!  */
  266.  
  267.       char *n = malloc(size + 50);
  268.       int i = 0;
  269.  
  270.       strcpy(n, "");
  271.  
  272.       if (match_lines)
  273.     strcpy(n, "^(");
  274.       if (match_words)
  275.     strcpy(n, "(^|[^0-9A-Za-z_])(");
  276.  
  277.       i = strlen(n);
  278.       bcopy(pattern, n + i, size);
  279.       i += size;
  280.  
  281.       if (match_words)
  282.     strcpy(n + i, ")([^0-9A-Za-z_]|$)");
  283.       if (match_lines)
  284.     strcpy(n + i, ")$");
  285.  
  286.       i += strlen(n + i);
  287.       dfacomp(n, i, &dfa, 1);
  288.     }
  289.   else
  290.     dfacomp(pattern, size, &dfa, 1);
  291.  
  292.   kwsmusts();
  293. }
  294.  
  295. static char *
  296. EGexecute(buf, size, endp)
  297.      char *buf;
  298.      size_t size;
  299.      char **endp;
  300. {
  301.   register char *buflim, *beg, *end, save;
  302.   int backref, start, len;
  303.   struct kwsmatch kwsm;
  304.   static struct re_registers regs; /* This is static on account of a BRAIN-DEAD
  305.                     Q@#%!# library interface in regex.c.  */
  306.  
  307.   buflim = buf + size;
  308.  
  309.   for (beg = end = buf; end < buflim; beg = end + 1)
  310.     {
  311.       if (kwset)
  312.     {
  313.       /* Find a possible match using the KWset matcher. */
  314.       beg = kwsexec(kwset, beg, buflim - beg, &kwsm);
  315.       if (!beg)
  316.         goto failure;
  317.       /* Narrow down to the line containing the candidate, and
  318.          run it through DFA. */
  319.       end = memchr(beg, '\n', buflim - beg);
  320.       if (!end)
  321.         end = buflim;
  322.       while (beg > buf && beg[-1] != '\n')
  323.         --beg;
  324.       save = *end;
  325.       if (kwsm.index < lastexact)
  326.         goto success;
  327.       if (!dfaexec(&dfa, beg, end, 0, (int *) 0, &backref))
  328.         {
  329.           *end = save;
  330.           continue;
  331.         }
  332.       *end = save;
  333.       /* Successful, no backreferences encountered. */
  334.       if (!backref)
  335.         goto success;
  336.     }
  337.       else
  338.     {
  339.       /* No good fixed strings; start with DFA. */
  340.       save = *buflim;
  341.       beg = dfaexec(&dfa, beg, buflim, 0, (int *) 0, &backref);
  342.       *buflim = save;
  343.       if (!beg)
  344.         goto failure;
  345.       /* Narrow down to the line we've found. */
  346.       end = memchr(beg, '\n', buflim - beg);
  347.       if (!end)
  348.         end = buflim;
  349.       while (beg > buf && beg[-1] != '\n')
  350.         --beg;
  351.       /* Successful, no backreferences encountered! */
  352.       if (!backref)
  353.         goto success;
  354.     }
  355.       /* If we've made it to this point, this means DFA has seen
  356.      a probable match, and we need to run it through Regex. */
  357.       regex.not_eol = 0;
  358.       if ((start = re_search(®ex, beg, end - beg, 0, end - beg, ®s)) >= 0)
  359.     {
  360.       len = regs.end[0] - start;
  361.       if (!match_lines && !match_words || match_lines && len == end - beg)
  362.         goto success;
  363.       /* If -w, check if the match aligns with word boundaries.
  364.          We do this iteratively because:
  365.          (a) the line may contain more than one occurence of the pattern, and
  366.          (b) Several alternatives in the pattern might be valid at a given
  367.          point, and we may need to consider a shorter one to find a word
  368.          boundary. */
  369.       if (match_words)
  370.         while (start >= 0)
  371.           {
  372.         if ((start == 0 || !WCHAR(beg[start - 1]))
  373.             && (len == end - beg || !WCHAR(beg[start + len])))
  374.           goto success;
  375.         if (len > 0)
  376.           {
  377.             /* Try a shorter length anchored at the same place. */
  378.             --len;
  379.             regex.not_eol = 1;
  380.             len = re_match(®ex, beg, start + len, start, ®s);
  381.           }
  382.         if (len <= 0)
  383.           {
  384.             /* Try looking further on. */
  385.             if (start == end - beg)
  386.               break;
  387.             ++start;
  388.             regex.not_eol = 0;
  389.             start = re_search(®ex, beg, end - beg,
  390.                       start, end - beg - start, ®s);
  391.             len = regs.end[0] - start;
  392.           }
  393.           }
  394.     }
  395.     }
  396.  
  397.  failure:
  398.   return 0;
  399.  
  400.  success:
  401.   *endp = end < buflim ? end + 1 : end;
  402.   return beg;
  403. }
  404.  
  405. static void
  406. Fcompile(pattern, size)
  407.      char *pattern;
  408.      size_t size;
  409. {
  410.   char *beg, *lim, *err;
  411.  
  412.   kwsinit();
  413.   beg = pattern;
  414.   do
  415.     {
  416.       for (lim = beg; lim < pattern + size && *lim != '\n'; ++lim)
  417.     ;
  418.       if ((err = kwsincr(kwset, beg, lim - beg)) != 0)
  419.     fatal(err, 0);
  420.       if (lim < pattern + size)
  421.     ++lim;
  422.       beg = lim;
  423.     }
  424.   while (beg < pattern + size);
  425.  
  426.   if ((err = kwsprep(kwset)) != 0)
  427.     fatal(err, 0);
  428. }
  429.  
  430. static char *
  431. Fexecute(buf, size, endp)
  432.      char *buf;
  433.      size_t size;
  434.      char **endp;
  435. {
  436.   register char *beg, *try, *end;
  437.   register size_t len;
  438.   struct kwsmatch kwsmatch;
  439.  
  440.   for (beg = buf; beg <= buf + size; ++beg)
  441.     {
  442.       if (!(beg = kwsexec(kwset, beg, buf + size - beg, &kwsmatch)))
  443.     return 0;
  444.       len = kwsmatch.size[0];
  445.       if (match_lines)
  446.     {
  447.       if (beg > buf && beg[-1] != '\n')
  448.         continue;
  449.       if (beg + len < buf + size && beg[len] != '\n')
  450.         continue;
  451.       goto success;
  452.     }
  453.       else if (match_words)
  454.     for (try = beg; len && try;)
  455.       {
  456.         if (try > buf && WCHAR((unsigned char) try[-1]))
  457.           break;
  458.         if (try + len < buf + size && WCHAR((unsigned char) try[len]))
  459.           {
  460.         try = kwsexec(kwset, beg, --len, &kwsmatch);
  461.         len = kwsmatch.size[0];
  462.           }
  463.         else
  464.           goto success;
  465.       }
  466.       else
  467.     goto success;
  468.     }
  469.  
  470.   return 0;
  471.  
  472.  success:
  473.   if ((end = memchr(beg + len, '\n', (buf + size) - (beg + len))) != 0)
  474.     ++end;
  475.   else
  476.     end = buf + size;
  477.   *endp = end;
  478.   while (beg > buf && beg[-1] != '\n')
  479.     --beg;
  480.   return beg;
  481. }
  482.