grep.con commit Threaded grep (5b594f4)
   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                        hit = !regexec(&p->regexp, bol, 1, &m, 0);
 680                if (!hit || m.rm_so < 0 || m.rm_eo < 0)
 681                        continue;
 682                if (earliest < 0 || m.rm_so < earliest)
 683                        earliest = m.rm_so;
 684        }
 685
 686        if (earliest < 0) {
 687                *bol_p = bol + *left_p;
 688                *left_p = 0;
 689                return 1;
 690        }
 691        for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
 692                ; /* find the beginning of the line */
 693        last_bol = sp;
 694
 695        for (sp = bol; sp < last_bol; sp++) {
 696                if (*sp == '\n')
 697                        lno++;
 698        }
 699        *left_p -= last_bol - bol;
 700        *bol_p = last_bol;
 701        *lno_p = lno;
 702        return 0;
 703}
 704
 705int grep_threads_ok(const struct grep_opt *opt)
 706{
 707        /* If this condition is true, then we may use the attribute
 708         * machinery in grep_buffer_1. The attribute code is not
 709         * thread safe, so we disable the use of threads.
 710         */
 711        if (opt->funcname && !opt->unmatch_name_only && !opt->status_only &&
 712            !opt->name_only)
 713                return 0;
 714
 715        /* If we are showing hunk marks, we should not do it for the
 716         * first match. The synchronization problem we get for this
 717         * constraint is not yet solved, so we disable threading in
 718         * this case.
 719         */
 720        if (opt->pre_context || opt->post_context)
 721                return 0;
 722
 723        return 1;
 724}
 725
 726static void std_output(struct grep_opt *opt, const void *buf, size_t size)
 727{
 728        fwrite(buf, size, 1, stdout);
 729}
 730
 731static int grep_buffer_1(struct grep_opt *opt, const char *name,
 732                         char *buf, unsigned long size, int collect_hits)
 733{
 734        char *bol = buf;
 735        unsigned long left = size;
 736        unsigned lno = 1;
 737        unsigned last_hit = 0;
 738        int binary_match_only = 0;
 739        unsigned count = 0;
 740        int try_lookahead = 0;
 741        enum grep_context ctx = GREP_CONTEXT_HEAD;
 742        xdemitconf_t xecfg;
 743
 744        opt->last_shown = 0;
 745
 746        if (!opt->output)
 747                opt->output = std_output;
 748
 749        if (buffer_is_binary(buf, size)) {
 750                switch (opt->binary) {
 751                case GREP_BINARY_DEFAULT:
 752                        binary_match_only = 1;
 753                        break;
 754                case GREP_BINARY_NOMATCH:
 755                        return 0; /* Assume unmatch */
 756                        break;
 757                default:
 758                        break;
 759                }
 760        }
 761
 762        memset(&xecfg, 0, sizeof(xecfg));
 763        if (opt->funcname && !opt->unmatch_name_only && !opt->status_only &&
 764            !opt->name_only && !binary_match_only && !collect_hits) {
 765                struct userdiff_driver *drv = userdiff_find_by_path(name);
 766                if (drv && drv->funcname.pattern) {
 767                        const struct userdiff_funcname *pe = &drv->funcname;
 768                        xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
 769                        opt->priv = &xecfg;
 770                }
 771        }
 772        try_lookahead = should_lookahead(opt);
 773
 774        while (left) {
 775                char *eol, ch;
 776                int hit;
 777
 778                /*
 779                 * look_ahead() skips quicly to the line that possibly
 780                 * has the next hit; don't call it if we need to do
 781                 * something more than just skipping the current line
 782                 * in response to an unmatch for the current line.  E.g.
 783                 * inside a post-context window, we will show the current
 784                 * line as a context around the previous hit when it
 785                 * doesn't hit.
 786                 */
 787                if (try_lookahead
 788                    && !(last_hit
 789                         && lno <= last_hit + opt->post_context)
 790                    && look_ahead(opt, &left, &lno, &bol))
 791                        break;
 792                eol = end_of_line(bol, &left);
 793                ch = *eol;
 794                *eol = 0;
 795
 796                if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
 797                        ctx = GREP_CONTEXT_BODY;
 798
 799                hit = match_line(opt, bol, eol, ctx, collect_hits);
 800                *eol = ch;
 801
 802                if (collect_hits)
 803                        goto next_line;
 804
 805                /* "grep -v -e foo -e bla" should list lines
 806                 * that do not have either, so inversion should
 807                 * be done outside.
 808                 */
 809                if (opt->invert)
 810                        hit = !hit;
 811                if (opt->unmatch_name_only) {
 812                        if (hit)
 813                                return 0;
 814                        goto next_line;
 815                }
 816                if (hit) {
 817                        count++;
 818                        if (opt->status_only)
 819                                return 1;
 820                        if (binary_match_only) {
 821                                opt->output(opt, "Binary file ", 12);
 822                                opt->output(opt, name, strlen(name));
 823                                opt->output(opt, " matches\n", 9);
 824                                return 1;
 825                        }
 826                        if (opt->name_only) {
 827                                show_name(opt, name);
 828                                return 1;
 829                        }
 830                        /* Hit at this line.  If we haven't shown the
 831                         * pre-context lines, we would need to show them.
 832                         * When asked to do "count", this still show
 833                         * the context which is nonsense, but the user
 834                         * deserves to get that ;-).
 835                         */
 836                        if (opt->pre_context)
 837                                show_pre_context(opt, name, buf, bol, lno);
 838                        else if (opt->funcname)
 839                                show_funcname_line(opt, name, buf, bol, lno);
 840                        if (!opt->count)
 841                                show_line(opt, bol, eol, name, lno, ':');
 842                        last_hit = lno;
 843                }
 844                else if (last_hit &&
 845                         lno <= last_hit + opt->post_context) {
 846                        /* If the last hit is within the post context,
 847                         * we need to show this line.
 848                         */
 849                        show_line(opt, bol, eol, name, lno, '-');
 850                }
 851
 852        next_line:
 853                bol = eol + 1;
 854                if (!left)
 855                        break;
 856                left--;
 857                lno++;
 858        }
 859
 860        if (collect_hits)
 861                return 0;
 862
 863        if (opt->status_only)
 864                return 0;
 865        if (opt->unmatch_name_only) {
 866                /* We did not see any hit, so we want to show this */
 867                show_name(opt, name);
 868                return 1;
 869        }
 870
 871        xdiff_clear_find_func(&xecfg);
 872        opt->priv = NULL;
 873
 874        /* NEEDSWORK:
 875         * The real "grep -c foo *.c" gives many "bar.c:0" lines,
 876         * which feels mostly useless but sometimes useful.  Maybe
 877         * make it another option?  For now suppress them.
 878         */
 879        if (opt->count && count) {
 880                char buf[32];
 881                opt->output(opt, name, strlen(name));
 882                snprintf(buf, sizeof(buf), "%c%u\n",
 883                         opt->null_following_name ? '\0' : ':', count);
 884                opt->output(opt, buf, strlen(buf));
 885        }
 886        return !!last_hit;
 887}
 888
 889static void clr_hit_marker(struct grep_expr *x)
 890{
 891        /* All-hit markers are meaningful only at the very top level
 892         * OR node.
 893         */
 894        while (1) {
 895                x->hit = 0;
 896                if (x->node != GREP_NODE_OR)
 897                        return;
 898                x->u.binary.left->hit = 0;
 899                x = x->u.binary.right;
 900        }
 901}
 902
 903static int chk_hit_marker(struct grep_expr *x)
 904{
 905        /* Top level nodes have hit markers.  See if they all are hits */
 906        while (1) {
 907                if (x->node != GREP_NODE_OR)
 908                        return x->hit;
 909                if (!x->u.binary.left->hit)
 910                        return 0;
 911                x = x->u.binary.right;
 912        }
 913}
 914
 915int grep_buffer(struct grep_opt *opt, const char *name, char *buf, unsigned long size)
 916{
 917        /*
 918         * we do not have to do the two-pass grep when we do not check
 919         * buffer-wide "all-match".
 920         */
 921        if (!opt->all_match)
 922                return grep_buffer_1(opt, name, buf, size, 0);
 923
 924        /* Otherwise the toplevel "or" terms hit a bit differently.
 925         * We first clear hit markers from them.
 926         */
 927        clr_hit_marker(opt->pattern_expression);
 928        grep_buffer_1(opt, name, buf, size, 1);
 929
 930        if (!chk_hit_marker(opt->pattern_expression))
 931                return 0;
 932
 933        return grep_buffer_1(opt, name, buf, size, 0);
 934}