grep.con commit Merge branch 'ms/filter-branch-submodule' (4b7acc1)
   1#include "cache.h"
   2#include "grep.h"
   3#include "userdiff.h"
   4#include "xdiff-interface.h"
   5
   6void append_header_grep_pattern(struct grep_opt *opt, enum grep_header_field field, const char *pat)
   7{
   8        struct grep_pat *p = xcalloc(1, sizeof(*p));
   9        p->pattern = pat;
  10        p->origin = "header";
  11        p->no = 0;
  12        p->token = GREP_PATTERN_HEAD;
  13        p->field = field;
  14        *opt->pattern_tail = p;
  15        opt->pattern_tail = &p->next;
  16        p->next = NULL;
  17}
  18
  19void append_grep_pattern(struct grep_opt *opt, const char *pat,
  20                         const char *origin, int no, enum grep_pat_token t)
  21{
  22        struct grep_pat *p = xcalloc(1, sizeof(*p));
  23        p->pattern = pat;
  24        p->origin = origin;
  25        p->no = no;
  26        p->token = t;
  27        *opt->pattern_tail = p;
  28        opt->pattern_tail = &p->next;
  29        p->next = NULL;
  30}
  31
  32struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
  33{
  34        struct grep_pat *pat;
  35        struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
  36        *ret = *opt;
  37
  38        ret->pattern_list = NULL;
  39        ret->pattern_tail = &ret->pattern_list;
  40
  41        for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
  42        {
  43                if(pat->token == GREP_PATTERN_HEAD)
  44                        append_header_grep_pattern(ret, pat->field,
  45                                                   pat->pattern);
  46                else
  47                        append_grep_pattern(ret, pat->pattern, pat->origin,
  48                                            pat->no, pat->token);
  49        }
  50
  51        return ret;
  52}
  53
  54static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
  55{
  56        int err;
  57
  58        p->word_regexp = opt->word_regexp;
  59        p->ignore_case = opt->ignore_case;
  60
  61        if (opt->fixed)
  62                p->fixed = 1;
  63        if (opt->regflags & REG_ICASE)
  64                p->fixed = 0;
  65        if (p->fixed)
  66                return;
  67
  68        err = regcomp(&p->regexp, p->pattern, opt->regflags);
  69        if (err) {
  70                char errbuf[1024];
  71                char where[1024];
  72                if (p->no)
  73                        sprintf(where, "In '%s' at %d, ",
  74                                p->origin, p->no);
  75                else if (p->origin)
  76                        sprintf(where, "%s, ", p->origin);
  77                else
  78                        where[0] = 0;
  79                regerror(err, &p->regexp, errbuf, 1024);
  80                regfree(&p->regexp);
  81                die("%s'%s': %s", where, p->pattern, errbuf);
  82        }
  83}
  84
  85static struct grep_expr *compile_pattern_or(struct grep_pat **);
  86static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
  87{
  88        struct grep_pat *p;
  89        struct grep_expr *x;
  90
  91        p = *list;
  92        if (!p)
  93                return NULL;
  94        switch (p->token) {
  95        case GREP_PATTERN: /* atom */
  96        case GREP_PATTERN_HEAD:
  97        case GREP_PATTERN_BODY:
  98                x = xcalloc(1, sizeof (struct grep_expr));
  99                x->node = GREP_NODE_ATOM;
 100                x->u.atom = p;
 101                *list = p->next;
 102                return x;
 103        case GREP_OPEN_PAREN:
 104                *list = p->next;
 105                x = compile_pattern_or(list);
 106                if (!*list || (*list)->token != GREP_CLOSE_PAREN)
 107                        die("unmatched parenthesis");
 108                *list = (*list)->next;
 109                return x;
 110        default:
 111                return NULL;
 112        }
 113}
 114
 115static struct grep_expr *compile_pattern_not(struct grep_pat **list)
 116{
 117        struct grep_pat *p;
 118        struct grep_expr *x;
 119
 120        p = *list;
 121        if (!p)
 122                return NULL;
 123        switch (p->token) {
 124        case GREP_NOT:
 125                if (!p->next)
 126                        die("--not not followed by pattern expression");
 127                *list = p->next;
 128                x = xcalloc(1, sizeof (struct grep_expr));
 129                x->node = GREP_NODE_NOT;
 130                x->u.unary = compile_pattern_not(list);
 131                if (!x->u.unary)
 132                        die("--not followed by non pattern expression");
 133                return x;
 134        default:
 135                return compile_pattern_atom(list);
 136        }
 137}
 138
 139static struct grep_expr *compile_pattern_and(struct grep_pat **list)
 140{
 141        struct grep_pat *p;
 142        struct grep_expr *x, *y, *z;
 143
 144        x = compile_pattern_not(list);
 145        p = *list;
 146        if (p && p->token == GREP_AND) {
 147                if (!p->next)
 148                        die("--and not followed by pattern expression");
 149                *list = p->next;
 150                y = compile_pattern_and(list);
 151                if (!y)
 152                        die("--and not followed by pattern expression");
 153                z = xcalloc(1, sizeof (struct grep_expr));
 154                z->node = GREP_NODE_AND;
 155                z->u.binary.left = x;
 156                z->u.binary.right = y;
 157                return z;
 158        }
 159        return x;
 160}
 161
 162static struct grep_expr *compile_pattern_or(struct grep_pat **list)
 163{
 164        struct grep_pat *p;
 165        struct grep_expr *x, *y, *z;
 166
 167        x = compile_pattern_and(list);
 168        p = *list;
 169        if (x && p && p->token != GREP_CLOSE_PAREN) {
 170                y = compile_pattern_or(list);
 171                if (!y)
 172                        die("not a pattern expression %s", p->pattern);
 173                z = xcalloc(1, sizeof (struct grep_expr));
 174                z->node = GREP_NODE_OR;
 175                z->u.binary.left = x;
 176                z->u.binary.right = y;
 177                return z;
 178        }
 179        return x;
 180}
 181
 182static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
 183{
 184        return compile_pattern_or(list);
 185}
 186
 187void compile_grep_patterns(struct grep_opt *opt)
 188{
 189        struct grep_pat *p;
 190
 191        if (opt->all_match)
 192                opt->extended = 1;
 193
 194        for (p = opt->pattern_list; p; p = p->next) {
 195                switch (p->token) {
 196                case GREP_PATTERN: /* atom */
 197                case GREP_PATTERN_HEAD:
 198                case GREP_PATTERN_BODY:
 199                        compile_regexp(p, opt);
 200                        break;
 201                default:
 202                        opt->extended = 1;
 203                        break;
 204                }
 205        }
 206
 207        if (!opt->extended)
 208                return;
 209
 210        /* Then bundle them up in an expression.
 211         * A classic recursive descent parser would do.
 212         */
 213        p = opt->pattern_list;
 214        if (p)
 215                opt->pattern_expression = compile_pattern_expr(&p);
 216        if (p)
 217                die("incomplete pattern expression: %s", p->pattern);
 218}
 219
 220static void free_pattern_expr(struct grep_expr *x)
 221{
 222        switch (x->node) {
 223        case GREP_NODE_ATOM:
 224                break;
 225        case GREP_NODE_NOT:
 226                free_pattern_expr(x->u.unary);
 227                break;
 228        case GREP_NODE_AND:
 229        case GREP_NODE_OR:
 230                free_pattern_expr(x->u.binary.left);
 231                free_pattern_expr(x->u.binary.right);
 232                break;
 233        }
 234        free(x);
 235}
 236
 237void free_grep_patterns(struct grep_opt *opt)
 238{
 239        struct grep_pat *p, *n;
 240
 241        for (p = opt->pattern_list; p; p = n) {
 242                n = p->next;
 243                switch (p->token) {
 244                case GREP_PATTERN: /* atom */
 245                case GREP_PATTERN_HEAD:
 246                case GREP_PATTERN_BODY:
 247                        regfree(&p->regexp);
 248                        break;
 249                default:
 250                        break;
 251                }
 252                free(p);
 253        }
 254
 255        if (!opt->extended)
 256                return;
 257        free_pattern_expr(opt->pattern_expression);
 258}
 259
 260static char *end_of_line(char *cp, unsigned long *left)
 261{
 262        unsigned long l = *left;
 263        while (l && *cp != '\n') {
 264                l--;
 265                cp++;
 266        }
 267        *left = l;
 268        return cp;
 269}
 270
 271static int word_char(char ch)
 272{
 273        return isalnum(ch) || ch == '_';
 274}
 275
 276static void show_name(struct grep_opt *opt, const char *name)
 277{
 278        opt->output(opt, name, strlen(name));
 279        opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
 280}
 281
 282
 283static int fixmatch(const char *pattern, char *line, int ignore_case, regmatch_t *match)
 284{
 285        char *hit;
 286        if (ignore_case)
 287                hit = strcasestr(line, pattern);
 288        else
 289                hit = strstr(line, pattern);
 290
 291        if (!hit) {
 292                match->rm_so = match->rm_eo = -1;
 293                return REG_NOMATCH;
 294        }
 295        else {
 296                match->rm_so = hit - line;
 297                match->rm_eo = match->rm_so + strlen(pattern);
 298                return 0;
 299        }
 300}
 301
 302static int strip_timestamp(char *bol, char **eol_p)
 303{
 304        char *eol = *eol_p;
 305        int ch;
 306
 307        while (bol < --eol) {
 308                if (*eol != '>')
 309                        continue;
 310                *eol_p = ++eol;
 311                ch = *eol;
 312                *eol = '\0';
 313                return ch;
 314        }
 315        return 0;
 316}
 317
 318static struct {
 319        const char *field;
 320        size_t len;
 321} header_field[] = {
 322        { "author ", 7 },
 323        { "committer ", 10 },
 324};
 325
 326static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
 327                             enum grep_context ctx,
 328                             regmatch_t *pmatch, int eflags)
 329{
 330        int hit = 0;
 331        int saved_ch = 0;
 332        const char *start = bol;
 333
 334        if ((p->token != GREP_PATTERN) &&
 335            ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
 336                return 0;
 337
 338        if (p->token == GREP_PATTERN_HEAD) {
 339                const char *field;
 340                size_t len;
 341                assert(p->field < ARRAY_SIZE(header_field));
 342                field = header_field[p->field].field;
 343                len = header_field[p->field].len;
 344                if (strncmp(bol, field, len))
 345                        return 0;
 346                bol += len;
 347                saved_ch = strip_timestamp(bol, &eol);
 348        }
 349
 350 again:
 351        if (p->fixed)
 352                hit = !fixmatch(p->pattern, bol, p->ignore_case, pmatch);
 353        else
 354                hit = !regexec(&p->regexp, bol, 1, pmatch, eflags);
 355
 356        if (hit && p->word_regexp) {
 357                if ((pmatch[0].rm_so < 0) ||
 358                    (eol - bol) < pmatch[0].rm_so ||
 359                    (pmatch[0].rm_eo < 0) ||
 360                    (eol - bol) < pmatch[0].rm_eo)
 361                        die("regexp returned nonsense");
 362
 363                /* Match beginning must be either beginning of the
 364                 * line, or at word boundary (i.e. the last char must
 365                 * not be a word char).  Similarly, match end must be
 366                 * either end of the line, or at word boundary
 367                 * (i.e. the next char must not be a word char).
 368                 */
 369                if ( ((pmatch[0].rm_so == 0) ||
 370                      !word_char(bol[pmatch[0].rm_so-1])) &&
 371                     ((pmatch[0].rm_eo == (eol-bol)) ||
 372                      !word_char(bol[pmatch[0].rm_eo])) )
 373                        ;
 374                else
 375                        hit = 0;
 376
 377                /* Words consist of at least one character. */
 378                if (pmatch->rm_so == pmatch->rm_eo)
 379                        hit = 0;
 380
 381                if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
 382                        /* There could be more than one match on the
 383                         * line, and the first match might not be
 384                         * strict word match.  But later ones could be!
 385                         * Forward to the next possible start, i.e. the
 386                         * next position following a non-word char.
 387                         */
 388                        bol = pmatch[0].rm_so + bol + 1;
 389                        while (word_char(bol[-1]) && bol < eol)
 390                                bol++;
 391                        eflags |= REG_NOTBOL;
 392                        if (bol < eol)
 393                                goto again;
 394                }
 395        }
 396        if (p->token == GREP_PATTERN_HEAD && saved_ch)
 397                *eol = saved_ch;
 398        if (hit) {
 399                pmatch[0].rm_so += bol - start;
 400                pmatch[0].rm_eo += bol - start;
 401        }
 402        return hit;
 403}
 404
 405static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
 406                           enum grep_context ctx, int collect_hits)
 407{
 408        int h = 0;
 409        regmatch_t match;
 410
 411        if (!x)
 412                die("Not a valid grep expression");
 413        switch (x->node) {
 414        case GREP_NODE_ATOM:
 415                h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
 416                break;
 417        case GREP_NODE_NOT:
 418                h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
 419                break;
 420        case GREP_NODE_AND:
 421                if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
 422                        return 0;
 423                h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
 424                break;
 425        case GREP_NODE_OR:
 426                if (!collect_hits)
 427                        return (match_expr_eval(x->u.binary.left,
 428                                                bol, eol, ctx, 0) ||
 429                                match_expr_eval(x->u.binary.right,
 430                                                bol, eol, ctx, 0));
 431                h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
 432                x->u.binary.left->hit |= h;
 433                h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
 434                break;
 435        default:
 436                die("Unexpected node type (internal error) %d", x->node);
 437        }
 438        if (collect_hits)
 439                x->hit |= h;
 440        return h;
 441}
 442
 443static int match_expr(struct grep_opt *opt, char *bol, char *eol,
 444                      enum grep_context ctx, int collect_hits)
 445{
 446        struct grep_expr *x = opt->pattern_expression;
 447        return match_expr_eval(x, bol, eol, ctx, collect_hits);
 448}
 449
 450static int match_line(struct grep_opt *opt, char *bol, char *eol,
 451                      enum grep_context ctx, int collect_hits)
 452{
 453        struct grep_pat *p;
 454        regmatch_t match;
 455
 456        if (opt->extended)
 457                return match_expr(opt, bol, eol, ctx, collect_hits);
 458
 459        /* we do not call with collect_hits without being extended */
 460        for (p = opt->pattern_list; p; p = p->next) {
 461                if (match_one_pattern(p, bol, eol, ctx, &match, 0))
 462                        return 1;
 463        }
 464        return 0;
 465}
 466
 467static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
 468                              enum grep_context ctx,
 469                              regmatch_t *pmatch, int eflags)
 470{
 471        regmatch_t match;
 472
 473        if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
 474                return 0;
 475        if (match.rm_so < 0 || match.rm_eo < 0)
 476                return 0;
 477        if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
 478                if (match.rm_so > pmatch->rm_so)
 479                        return 1;
 480                if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
 481                        return 1;
 482        }
 483        pmatch->rm_so = match.rm_so;
 484        pmatch->rm_eo = match.rm_eo;
 485        return 1;
 486}
 487
 488static int next_match(struct grep_opt *opt, char *bol, char *eol,
 489                      enum grep_context ctx, regmatch_t *pmatch, int eflags)
 490{
 491        struct grep_pat *p;
 492        int hit = 0;
 493
 494        pmatch->rm_so = pmatch->rm_eo = -1;
 495        if (bol < eol) {
 496                for (p = opt->pattern_list; p; p = p->next) {
 497                        switch (p->token) {
 498                        case GREP_PATTERN: /* atom */
 499                        case GREP_PATTERN_HEAD:
 500                        case GREP_PATTERN_BODY:
 501                                hit |= match_next_pattern(p, bol, eol, ctx,
 502                                                          pmatch, eflags);
 503                                break;
 504                        default:
 505                                break;
 506                        }
 507                }
 508        }
 509        return hit;
 510}
 511
 512static void show_line(struct grep_opt *opt, char *bol, char *eol,
 513                      const char *name, unsigned lno, char sign)
 514{
 515        int rest = eol - bol;
 516        char sign_str[1];
 517
 518        sign_str[0] = sign;
 519        if (opt->pre_context || opt->post_context) {
 520                if (opt->last_shown == 0) {
 521                        if (opt->show_hunk_mark)
 522                                opt->output(opt, "--\n", 3);
 523                        else
 524                                opt->show_hunk_mark = 1;
 525                } else if (lno > opt->last_shown + 1)
 526                        opt->output(opt, "--\n", 3);
 527        }
 528        opt->last_shown = lno;
 529
 530        if (opt->null_following_name)
 531                sign_str[0] = '\0';
 532        if (opt->pathname) {
 533                opt->output(opt, name, strlen(name));
 534                opt->output(opt, sign_str, 1);
 535        }
 536        if (opt->linenum) {
 537                char buf[32];
 538                snprintf(buf, sizeof(buf), "%d", lno);
 539                opt->output(opt, buf, strlen(buf));
 540                opt->output(opt, sign_str, 1);
 541        }
 542        if (opt->color) {
 543                regmatch_t match;
 544                enum grep_context ctx = GREP_CONTEXT_BODY;
 545                int ch = *eol;
 546                int eflags = 0;
 547
 548                *eol = '\0';
 549                while (next_match(opt, bol, eol, ctx, &match, eflags)) {
 550                        if (match.rm_so == match.rm_eo)
 551                                break;
 552
 553                        opt->output(opt, bol, match.rm_so);
 554                        opt->output(opt, opt->color_match,
 555                                    strlen(opt->color_match));
 556                        opt->output(opt, bol + match.rm_so,
 557                                    (int)(match.rm_eo - match.rm_so));
 558                        opt->output(opt, GIT_COLOR_RESET,
 559                                    strlen(GIT_COLOR_RESET));
 560                        bol += match.rm_eo;
 561                        rest -= match.rm_eo;
 562                        eflags = REG_NOTBOL;
 563                }
 564                *eol = ch;
 565        }
 566        opt->output(opt, bol, rest);
 567        opt->output(opt, "\n", 1);
 568}
 569
 570static int match_funcname(struct grep_opt *opt, char *bol, char *eol)
 571{
 572        xdemitconf_t *xecfg = opt->priv;
 573        if (xecfg && xecfg->find_func) {
 574                char buf[1];
 575                return xecfg->find_func(bol, eol - bol, buf, 1,
 576                                        xecfg->find_func_priv) >= 0;
 577        }
 578
 579        if (bol == eol)
 580                return 0;
 581        if (isalpha(*bol) || *bol == '_' || *bol == '$')
 582                return 1;
 583        return 0;
 584}
 585
 586static void show_funcname_line(struct grep_opt *opt, const char *name,
 587                               char *buf, char *bol, unsigned lno)
 588{
 589        while (bol > buf) {
 590                char *eol = --bol;
 591
 592                while (bol > buf && bol[-1] != '\n')
 593                        bol--;
 594                lno--;
 595
 596                if (lno <= opt->last_shown)
 597                        break;
 598
 599                if (match_funcname(opt, bol, eol)) {
 600                        show_line(opt, bol, eol, name, lno, '=');
 601                        break;
 602                }
 603        }
 604}
 605
 606static void show_pre_context(struct grep_opt *opt, const char *name, char *buf,
 607                             char *bol, unsigned lno)
 608{
 609        unsigned cur = lno, from = 1, funcname_lno = 0;
 610        int funcname_needed = opt->funcname;
 611
 612        if (opt->pre_context < lno)
 613                from = lno - opt->pre_context;
 614        if (from <= opt->last_shown)
 615                from = opt->last_shown + 1;
 616
 617        /* Rewind. */
 618        while (bol > buf && cur > from) {
 619                char *eol = --bol;
 620
 621                while (bol > buf && bol[-1] != '\n')
 622                        bol--;
 623                cur--;
 624                if (funcname_needed && match_funcname(opt, bol, eol)) {
 625                        funcname_lno = cur;
 626                        funcname_needed = 0;
 627                }
 628        }
 629
 630        /* We need to look even further back to find a function signature. */
 631        if (opt->funcname && funcname_needed)
 632                show_funcname_line(opt, name, buf, bol, cur);
 633
 634        /* Back forward. */
 635        while (cur < lno) {
 636                char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
 637
 638                while (*eol != '\n')
 639                        eol++;
 640                show_line(opt, bol, eol, name, cur, sign);
 641                bol = eol + 1;
 642                cur++;
 643        }
 644}
 645
 646static int should_lookahead(struct grep_opt *opt)
 647{
 648        struct grep_pat *p;
 649
 650        if (opt->extended)
 651                return 0; /* punt for too complex stuff */
 652        if (opt->invert)
 653                return 0;
 654        for (p = opt->pattern_list; p; p = p->next) {
 655                if (p->token != GREP_PATTERN)
 656                        return 0; /* punt for "header only" and stuff */
 657        }
 658        return 1;
 659}
 660
 661static int look_ahead(struct grep_opt *opt,
 662                      unsigned long *left_p,
 663                      unsigned *lno_p,
 664                      char **bol_p)
 665{
 666        unsigned lno = *lno_p;
 667        char *bol = *bol_p;
 668        struct grep_pat *p;
 669        char *sp, *last_bol;
 670        regoff_t earliest = -1;
 671
 672        for (p = opt->pattern_list; p; p = p->next) {
 673                int hit;
 674                regmatch_t m;
 675
 676                if (p->fixed)
 677                        hit = !fixmatch(p->pattern, bol, p->ignore_case, &m);
 678                else {
 679#ifdef REG_STARTEND
 680                        m.rm_so = 0;
 681                        m.rm_eo = *left_p;
 682                        hit = !regexec(&p->regexp, bol, 1, &m, REG_STARTEND);
 683#else
 684                        hit = !regexec(&p->regexp, bol, 1, &m, 0);
 685#endif
 686                }
 687                if (!hit || m.rm_so < 0 || m.rm_eo < 0)
 688                        continue;
 689                if (earliest < 0 || m.rm_so < earliest)
 690                        earliest = m.rm_so;
 691        }
 692
 693        if (earliest < 0) {
 694                *bol_p = bol + *left_p;
 695                *left_p = 0;
 696                return 1;
 697        }
 698        for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
 699                ; /* find the beginning of the line */
 700        last_bol = sp;
 701
 702        for (sp = bol; sp < last_bol; sp++) {
 703                if (*sp == '\n')
 704                        lno++;
 705        }
 706        *left_p -= last_bol - bol;
 707        *bol_p = last_bol;
 708        *lno_p = lno;
 709        return 0;
 710}
 711
 712int grep_threads_ok(const struct grep_opt *opt)
 713{
 714        /* If this condition is true, then we may use the attribute
 715         * machinery in grep_buffer_1. The attribute code is not
 716         * thread safe, so we disable the use of threads.
 717         */
 718        if (opt->funcname && !opt->unmatch_name_only && !opt->status_only &&
 719            !opt->name_only)
 720                return 0;
 721
 722        /* If we are showing hunk marks, we should not do it for the
 723         * first match. The synchronization problem we get for this
 724         * constraint is not yet solved, so we disable threading in
 725         * this case.
 726         */
 727        if (opt->pre_context || opt->post_context)
 728                return 0;
 729
 730        return 1;
 731}
 732
 733static void std_output(struct grep_opt *opt, const void *buf, size_t size)
 734{
 735        fwrite(buf, size, 1, stdout);
 736}
 737
 738static int grep_buffer_1(struct grep_opt *opt, const char *name,
 739                         char *buf, unsigned long size, int collect_hits)
 740{
 741        char *bol = buf;
 742        unsigned long left = size;
 743        unsigned lno = 1;
 744        unsigned last_hit = 0;
 745        int binary_match_only = 0;
 746        unsigned count = 0;
 747        int try_lookahead = 0;
 748        enum grep_context ctx = GREP_CONTEXT_HEAD;
 749        xdemitconf_t xecfg;
 750
 751        opt->last_shown = 0;
 752
 753        if (!opt->output)
 754                opt->output = std_output;
 755
 756        if (buffer_is_binary(buf, size)) {
 757                switch (opt->binary) {
 758                case GREP_BINARY_DEFAULT:
 759                        binary_match_only = 1;
 760                        break;
 761                case GREP_BINARY_NOMATCH:
 762                        return 0; /* Assume unmatch */
 763                        break;
 764                default:
 765                        break;
 766                }
 767        }
 768
 769        memset(&xecfg, 0, sizeof(xecfg));
 770        if (opt->funcname && !opt->unmatch_name_only && !opt->status_only &&
 771            !opt->name_only && !binary_match_only && !collect_hits) {
 772                struct userdiff_driver *drv = userdiff_find_by_path(name);
 773                if (drv && drv->funcname.pattern) {
 774                        const struct userdiff_funcname *pe = &drv->funcname;
 775                        xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
 776                        opt->priv = &xecfg;
 777                }
 778        }
 779        try_lookahead = should_lookahead(opt);
 780
 781        while (left) {
 782                char *eol, ch;
 783                int hit;
 784
 785                /*
 786                 * look_ahead() skips quicly to the line that possibly
 787                 * has the next hit; don't call it if we need to do
 788                 * something more than just skipping the current line
 789                 * in response to an unmatch for the current line.  E.g.
 790                 * inside a post-context window, we will show the current
 791                 * line as a context around the previous hit when it
 792                 * doesn't hit.
 793                 */
 794                if (try_lookahead
 795                    && !(last_hit
 796                         && lno <= last_hit + opt->post_context)
 797                    && look_ahead(opt, &left, &lno, &bol))
 798                        break;
 799                eol = end_of_line(bol, &left);
 800                ch = *eol;
 801                *eol = 0;
 802
 803                if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
 804                        ctx = GREP_CONTEXT_BODY;
 805
 806                hit = match_line(opt, bol, eol, ctx, collect_hits);
 807                *eol = ch;
 808
 809                if (collect_hits)
 810                        goto next_line;
 811
 812                /* "grep -v -e foo -e bla" should list lines
 813                 * that do not have either, so inversion should
 814                 * be done outside.
 815                 */
 816                if (opt->invert)
 817                        hit = !hit;
 818                if (opt->unmatch_name_only) {
 819                        if (hit)
 820                                return 0;
 821                        goto next_line;
 822                }
 823                if (hit) {
 824                        count++;
 825                        if (opt->status_only)
 826                                return 1;
 827                        if (binary_match_only) {
 828                                opt->output(opt, "Binary file ", 12);
 829                                opt->output(opt, name, strlen(name));
 830                                opt->output(opt, " matches\n", 9);
 831                                return 1;
 832                        }
 833                        if (opt->name_only) {
 834                                show_name(opt, name);
 835                                return 1;
 836                        }
 837                        /* Hit at this line.  If we haven't shown the
 838                         * pre-context lines, we would need to show them.
 839                         * When asked to do "count", this still show
 840                         * the context which is nonsense, but the user
 841                         * deserves to get that ;-).
 842                         */
 843                        if (opt->pre_context)
 844                                show_pre_context(opt, name, buf, bol, lno);
 845                        else if (opt->funcname)
 846                                show_funcname_line(opt, name, buf, bol, lno);
 847                        if (!opt->count)
 848                                show_line(opt, bol, eol, name, lno, ':');
 849                        last_hit = lno;
 850                }
 851                else if (last_hit &&
 852                         lno <= last_hit + opt->post_context) {
 853                        /* If the last hit is within the post context,
 854                         * we need to show this line.
 855                         */
 856                        show_line(opt, bol, eol, name, lno, '-');
 857                }
 858
 859        next_line:
 860                bol = eol + 1;
 861                if (!left)
 862                        break;
 863                left--;
 864                lno++;
 865        }
 866
 867        if (collect_hits)
 868                return 0;
 869
 870        if (opt->status_only)
 871                return 0;
 872        if (opt->unmatch_name_only) {
 873                /* We did not see any hit, so we want to show this */
 874                show_name(opt, name);
 875                return 1;
 876        }
 877
 878        xdiff_clear_find_func(&xecfg);
 879        opt->priv = NULL;
 880
 881        /* NEEDSWORK:
 882         * The real "grep -c foo *.c" gives many "bar.c:0" lines,
 883         * which feels mostly useless but sometimes useful.  Maybe
 884         * make it another option?  For now suppress them.
 885         */
 886        if (opt->count && count) {
 887                char buf[32];
 888                opt->output(opt, name, strlen(name));
 889                snprintf(buf, sizeof(buf), "%c%u\n",
 890                         opt->null_following_name ? '\0' : ':', count);
 891                opt->output(opt, buf, strlen(buf));
 892        }
 893        return !!last_hit;
 894}
 895
 896static void clr_hit_marker(struct grep_expr *x)
 897{
 898        /* All-hit markers are meaningful only at the very top level
 899         * OR node.
 900         */
 901        while (1) {
 902                x->hit = 0;
 903                if (x->node != GREP_NODE_OR)
 904                        return;
 905                x->u.binary.left->hit = 0;
 906                x = x->u.binary.right;
 907        }
 908}
 909
 910static int chk_hit_marker(struct grep_expr *x)
 911{
 912        /* Top level nodes have hit markers.  See if they all are hits */
 913        while (1) {
 914                if (x->node != GREP_NODE_OR)
 915                        return x->hit;
 916                if (!x->u.binary.left->hit)
 917                        return 0;
 918                x = x->u.binary.right;
 919        }
 920}
 921
 922int grep_buffer(struct grep_opt *opt, const char *name, char *buf, unsigned long size)
 923{
 924        /*
 925         * we do not have to do the two-pass grep when we do not check
 926         * buffer-wide "all-match".
 927         */
 928        if (!opt->all_match)
 929                return grep_buffer_1(opt, name, buf, size, 0);
 930
 931        /* Otherwise the toplevel "or" terms hit a bit differently.
 932         * We first clear hit markers from them.
 933         */
 934        clr_hit_marker(opt->pattern_expression);
 935        grep_buffer_1(opt, name, buf, size, 1);
 936
 937        if (!chk_hit_marker(opt->pattern_expression))
 938                return 0;
 939
 940        return grep_buffer_1(opt, name, buf, size, 0);
 941}