grep: show --debug output only once
[git] / grep.c
1 #include "cache.h"
2 #include "grep.h"
3 #include "userdiff.h"
4 #include "xdiff-interface.h"
5
6 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
7                                         const char *origin, int no,
8                                         enum grep_pat_token t,
9                                         enum grep_header_field field)
10 {
11         struct grep_pat *p = xcalloc(1, sizeof(*p));
12         p->pattern = xmemdupz(pat, patlen);
13         p->patternlen = patlen;
14         p->origin = origin;
15         p->no = no;
16         p->token = t;
17         p->field = field;
18         return p;
19 }
20
21 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
22 {
23         **tail = p;
24         *tail = &p->next;
25         p->next = NULL;
26
27         switch (p->token) {
28         case GREP_PATTERN: /* atom */
29         case GREP_PATTERN_HEAD:
30         case GREP_PATTERN_BODY:
31                 for (;;) {
32                         struct grep_pat *new_pat;
33                         size_t len = 0;
34                         char *cp = p->pattern + p->patternlen, *nl = NULL;
35                         while (++len <= p->patternlen) {
36                                 if (*(--cp) == '\n') {
37                                         nl = cp;
38                                         break;
39                                 }
40                         }
41                         if (!nl)
42                                 break;
43                         new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
44                                                   p->no, p->token, p->field);
45                         new_pat->next = p->next;
46                         if (!p->next)
47                                 *tail = &new_pat->next;
48                         p->next = new_pat;
49                         *nl = '\0';
50                         p->patternlen -= len;
51                 }
52                 break;
53         default:
54                 break;
55         }
56 }
57
58 void append_header_grep_pattern(struct grep_opt *opt,
59                                 enum grep_header_field field, const char *pat)
60 {
61         struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
62                                              GREP_PATTERN_HEAD, field);
63         do_append_grep_pat(&opt->header_tail, p);
64 }
65
66 void append_grep_pattern(struct grep_opt *opt, const char *pat,
67                          const char *origin, int no, enum grep_pat_token t)
68 {
69         append_grep_pat(opt, pat, strlen(pat), origin, no, t);
70 }
71
72 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
73                      const char *origin, int no, enum grep_pat_token t)
74 {
75         struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
76         do_append_grep_pat(&opt->pattern_tail, p);
77 }
78
79 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
80 {
81         struct grep_pat *pat;
82         struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
83         *ret = *opt;
84
85         ret->pattern_list = NULL;
86         ret->pattern_tail = &ret->pattern_list;
87
88         for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
89         {
90                 if(pat->token == GREP_PATTERN_HEAD)
91                         append_header_grep_pattern(ret, pat->field,
92                                                    pat->pattern);
93                 else
94                         append_grep_pat(ret, pat->pattern, pat->patternlen,
95                                         pat->origin, pat->no, pat->token);
96         }
97
98         return ret;
99 }
100
101 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
102                 const char *error)
103 {
104         char where[1024];
105
106         if (p->no)
107                 sprintf(where, "In '%s' at %d, ", p->origin, p->no);
108         else if (p->origin)
109                 sprintf(where, "%s, ", p->origin);
110         else
111                 where[0] = 0;
112
113         die("%s'%s': %s", where, p->pattern, error);
114 }
115
116 #ifdef USE_LIBPCRE
117 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
118 {
119         const char *error;
120         int erroffset;
121         int options = PCRE_MULTILINE;
122
123         if (opt->ignore_case)
124                 options |= PCRE_CASELESS;
125
126         p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
127                         NULL);
128         if (!p->pcre_regexp)
129                 compile_regexp_failed(p, error);
130
131         p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
132         if (!p->pcre_extra_info && error)
133                 die("%s", error);
134 }
135
136 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
137                 regmatch_t *match, int eflags)
138 {
139         int ovector[30], ret, flags = 0;
140
141         if (eflags & REG_NOTBOL)
142                 flags |= PCRE_NOTBOL;
143
144         ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
145                         0, flags, ovector, ARRAY_SIZE(ovector));
146         if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
147                 die("pcre_exec failed with error code %d", ret);
148         if (ret > 0) {
149                 ret = 0;
150                 match->rm_so = ovector[0];
151                 match->rm_eo = ovector[1];
152         }
153
154         return ret;
155 }
156
157 static void free_pcre_regexp(struct grep_pat *p)
158 {
159         pcre_free(p->pcre_regexp);
160         pcre_free(p->pcre_extra_info);
161 }
162 #else /* !USE_LIBPCRE */
163 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
164 {
165         die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
166 }
167
168 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
169                 regmatch_t *match, int eflags)
170 {
171         return 1;
172 }
173
174 static void free_pcre_regexp(struct grep_pat *p)
175 {
176 }
177 #endif /* !USE_LIBPCRE */
178
179 static int is_fixed(const char *s, size_t len)
180 {
181         size_t i;
182
183         /* regcomp cannot accept patterns with NULs so we
184          * consider any pattern containing a NUL fixed.
185          */
186         if (memchr(s, 0, len))
187                 return 1;
188
189         for (i = 0; i < len; i++) {
190                 if (is_regex_special(s[i]))
191                         return 0;
192         }
193
194         return 1;
195 }
196
197 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
198 {
199         int err;
200
201         p->word_regexp = opt->word_regexp;
202         p->ignore_case = opt->ignore_case;
203
204         if (opt->fixed || is_fixed(p->pattern, p->patternlen))
205                 p->fixed = 1;
206         else
207                 p->fixed = 0;
208
209         if (p->fixed) {
210                 if (opt->regflags & REG_ICASE || p->ignore_case)
211                         p->kws = kwsalloc(tolower_trans_tbl);
212                 else
213                         p->kws = kwsalloc(NULL);
214                 kwsincr(p->kws, p->pattern, p->patternlen);
215                 kwsprep(p->kws);
216                 return;
217         }
218
219         if (opt->pcre) {
220                 compile_pcre_regexp(p, opt);
221                 return;
222         }
223
224         err = regcomp(&p->regexp, p->pattern, opt->regflags);
225         if (err) {
226                 char errbuf[1024];
227                 regerror(err, &p->regexp, errbuf, 1024);
228                 regfree(&p->regexp);
229                 compile_regexp_failed(p, errbuf);
230         }
231 }
232
233 static struct grep_expr *compile_pattern_or(struct grep_pat **);
234 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
235 {
236         struct grep_pat *p;
237         struct grep_expr *x;
238
239         p = *list;
240         if (!p)
241                 return NULL;
242         switch (p->token) {
243         case GREP_PATTERN: /* atom */
244         case GREP_PATTERN_HEAD:
245         case GREP_PATTERN_BODY:
246                 x = xcalloc(1, sizeof (struct grep_expr));
247                 x->node = GREP_NODE_ATOM;
248                 x->u.atom = p;
249                 *list = p->next;
250                 return x;
251         case GREP_OPEN_PAREN:
252                 *list = p->next;
253                 x = compile_pattern_or(list);
254                 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
255                         die("unmatched parenthesis");
256                 *list = (*list)->next;
257                 return x;
258         default:
259                 return NULL;
260         }
261 }
262
263 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
264 {
265         struct grep_pat *p;
266         struct grep_expr *x;
267
268         p = *list;
269         if (!p)
270                 return NULL;
271         switch (p->token) {
272         case GREP_NOT:
273                 if (!p->next)
274                         die("--not not followed by pattern expression");
275                 *list = p->next;
276                 x = xcalloc(1, sizeof (struct grep_expr));
277                 x->node = GREP_NODE_NOT;
278                 x->u.unary = compile_pattern_not(list);
279                 if (!x->u.unary)
280                         die("--not followed by non pattern expression");
281                 return x;
282         default:
283                 return compile_pattern_atom(list);
284         }
285 }
286
287 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
288 {
289         struct grep_pat *p;
290         struct grep_expr *x, *y, *z;
291
292         x = compile_pattern_not(list);
293         p = *list;
294         if (p && p->token == GREP_AND) {
295                 if (!p->next)
296                         die("--and not followed by pattern expression");
297                 *list = p->next;
298                 y = compile_pattern_and(list);
299                 if (!y)
300                         die("--and not followed by pattern expression");
301                 z = xcalloc(1, sizeof (struct grep_expr));
302                 z->node = GREP_NODE_AND;
303                 z->u.binary.left = x;
304                 z->u.binary.right = y;
305                 return z;
306         }
307         return x;
308 }
309
310 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
311 {
312         struct grep_pat *p;
313         struct grep_expr *x, *y, *z;
314
315         x = compile_pattern_and(list);
316         p = *list;
317         if (x && p && p->token != GREP_CLOSE_PAREN) {
318                 y = compile_pattern_or(list);
319                 if (!y)
320                         die("not a pattern expression %s", p->pattern);
321                 z = xcalloc(1, sizeof (struct grep_expr));
322                 z->node = GREP_NODE_OR;
323                 z->u.binary.left = x;
324                 z->u.binary.right = y;
325                 return z;
326         }
327         return x;
328 }
329
330 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
331 {
332         return compile_pattern_or(list);
333 }
334
335 static void indent(int in)
336 {
337         while (in-- > 0)
338                 fputc(' ', stderr);
339 }
340
341 static void dump_grep_pat(struct grep_pat *p)
342 {
343         switch (p->token) {
344         case GREP_AND: fprintf(stderr, "*and*"); break;
345         case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
346         case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
347         case GREP_NOT: fprintf(stderr, "*not*"); break;
348         case GREP_OR: fprintf(stderr, "*or*"); break;
349
350         case GREP_PATTERN: fprintf(stderr, "pattern"); break;
351         case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
352         case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
353         }
354
355         switch (p->token) {
356         default: break;
357         case GREP_PATTERN_HEAD:
358                 fprintf(stderr, "<head %d>", p->field); break;
359         case GREP_PATTERN_BODY:
360                 fprintf(stderr, "<body>"); break;
361         }
362         switch (p->token) {
363         default: break;
364         case GREP_PATTERN_HEAD:
365         case GREP_PATTERN_BODY:
366         case GREP_PATTERN:
367                 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
368                 break;
369         }
370         fputc('\n', stderr);
371 }
372
373 static void dump_grep_expression_1(struct grep_expr *x, int in)
374 {
375         indent(in);
376         switch (x->node) {
377         case GREP_NODE_TRUE:
378                 fprintf(stderr, "true\n");
379                 break;
380         case GREP_NODE_ATOM:
381                 dump_grep_pat(x->u.atom);
382                 break;
383         case GREP_NODE_NOT:
384                 fprintf(stderr, "(not\n");
385                 dump_grep_expression_1(x->u.unary, in+1);
386                 indent(in);
387                 fprintf(stderr, ")\n");
388                 break;
389         case GREP_NODE_AND:
390                 fprintf(stderr, "(and\n");
391                 dump_grep_expression_1(x->u.binary.left, in+1);
392                 dump_grep_expression_1(x->u.binary.right, in+1);
393                 indent(in);
394                 fprintf(stderr, ")\n");
395                 break;
396         case GREP_NODE_OR:
397                 fprintf(stderr, "(or\n");
398                 dump_grep_expression_1(x->u.binary.left, in+1);
399                 dump_grep_expression_1(x->u.binary.right, in+1);
400                 indent(in);
401                 fprintf(stderr, ")\n");
402                 break;
403         }
404 }
405
406 void dump_grep_expression(struct grep_opt *opt)
407 {
408         struct grep_expr *x = opt->pattern_expression;
409
410         if (opt->all_match)
411                 fprintf(stderr, "[all-match]\n");
412         dump_grep_expression_1(x, 0);
413         fflush(NULL);
414 }
415
416 static struct grep_expr *grep_true_expr(void)
417 {
418         struct grep_expr *z = xcalloc(1, sizeof(*z));
419         z->node = GREP_NODE_TRUE;
420         return z;
421 }
422
423 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
424 {
425         struct grep_expr *z = xcalloc(1, sizeof(*z));
426         z->node = GREP_NODE_OR;
427         z->u.binary.left = left;
428         z->u.binary.right = right;
429         return z;
430 }
431
432 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
433 {
434         struct grep_pat *p;
435         struct grep_expr *header_expr;
436         struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
437         enum grep_header_field fld;
438
439         if (!opt->header_list)
440                 return NULL;
441
442         for (p = opt->header_list; p; p = p->next) {
443                 if (p->token != GREP_PATTERN_HEAD)
444                         die("bug: a non-header pattern in grep header list.");
445                 if (p->field < 0 || GREP_HEADER_FIELD_MAX <= p->field)
446                         die("bug: unknown header field %d", p->field);
447                 compile_regexp(p, opt);
448         }
449
450         for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
451                 header_group[fld] = NULL;
452
453         for (p = opt->header_list; p; p = p->next) {
454                 struct grep_expr *h;
455                 struct grep_pat *pp = p;
456
457                 h = compile_pattern_atom(&pp);
458                 if (!h || pp != p->next)
459                         die("bug: malformed header expr");
460                 if (!header_group[p->field]) {
461                         header_group[p->field] = h;
462                         continue;
463                 }
464                 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
465         }
466
467         header_expr = NULL;
468
469         for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
470                 if (!header_group[fld])
471                         continue;
472                 if (!header_expr)
473                         header_expr = grep_true_expr();
474                 header_expr = grep_or_expr(header_group[fld], header_expr);
475         }
476         return header_expr;
477 }
478
479 static void compile_grep_patterns_real(struct grep_opt *opt)
480 {
481         struct grep_pat *p;
482         struct grep_expr *header_expr = prep_header_patterns(opt);
483
484         for (p = opt->pattern_list; p; p = p->next) {
485                 switch (p->token) {
486                 case GREP_PATTERN: /* atom */
487                 case GREP_PATTERN_HEAD:
488                 case GREP_PATTERN_BODY:
489                         compile_regexp(p, opt);
490                         break;
491                 default:
492                         opt->extended = 1;
493                         break;
494                 }
495         }
496
497         if (opt->all_match || header_expr)
498                 opt->extended = 1;
499         else if (!opt->extended && !opt->debug)
500                 return;
501
502         p = opt->pattern_list;
503         if (p)
504                 opt->pattern_expression = compile_pattern_expr(&p);
505         if (p)
506                 die("incomplete pattern expression: %s", p->pattern);
507
508         if (!header_expr)
509                 return;
510
511         if (!opt->pattern_expression)
512                 opt->pattern_expression = header_expr;
513         else
514                 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
515                                                        header_expr);
516         opt->all_match = 1;
517 }
518
519 void compile_grep_patterns(struct grep_opt *opt)
520 {
521         compile_grep_patterns_real(opt);
522         if (opt->debug)
523                 dump_grep_expression(opt);
524 }
525
526 static void free_pattern_expr(struct grep_expr *x)
527 {
528         switch (x->node) {
529         case GREP_NODE_TRUE:
530         case GREP_NODE_ATOM:
531                 break;
532         case GREP_NODE_NOT:
533                 free_pattern_expr(x->u.unary);
534                 break;
535         case GREP_NODE_AND:
536         case GREP_NODE_OR:
537                 free_pattern_expr(x->u.binary.left);
538                 free_pattern_expr(x->u.binary.right);
539                 break;
540         }
541         free(x);
542 }
543
544 void free_grep_patterns(struct grep_opt *opt)
545 {
546         struct grep_pat *p, *n;
547
548         for (p = opt->pattern_list; p; p = n) {
549                 n = p->next;
550                 switch (p->token) {
551                 case GREP_PATTERN: /* atom */
552                 case GREP_PATTERN_HEAD:
553                 case GREP_PATTERN_BODY:
554                         if (p->kws)
555                                 kwsfree(p->kws);
556                         else if (p->pcre_regexp)
557                                 free_pcre_regexp(p);
558                         else
559                                 regfree(&p->regexp);
560                         free(p->pattern);
561                         break;
562                 default:
563                         break;
564                 }
565                 free(p);
566         }
567
568         if (!opt->extended)
569                 return;
570         free_pattern_expr(opt->pattern_expression);
571 }
572
573 static char *end_of_line(char *cp, unsigned long *left)
574 {
575         unsigned long l = *left;
576         while (l && *cp != '\n') {
577                 l--;
578                 cp++;
579         }
580         *left = l;
581         return cp;
582 }
583
584 static int word_char(char ch)
585 {
586         return isalnum(ch) || ch == '_';
587 }
588
589 static void output_color(struct grep_opt *opt, const void *data, size_t size,
590                          const char *color)
591 {
592         if (want_color(opt->color) && color && color[0]) {
593                 opt->output(opt, color, strlen(color));
594                 opt->output(opt, data, size);
595                 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
596         } else
597                 opt->output(opt, data, size);
598 }
599
600 static void output_sep(struct grep_opt *opt, char sign)
601 {
602         if (opt->null_following_name)
603                 opt->output(opt, "\0", 1);
604         else
605                 output_color(opt, &sign, 1, opt->color_sep);
606 }
607
608 static void show_name(struct grep_opt *opt, const char *name)
609 {
610         output_color(opt, name, strlen(name), opt->color_filename);
611         opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
612 }
613
614 static int fixmatch(struct grep_pat *p, char *line, char *eol,
615                     regmatch_t *match)
616 {
617         struct kwsmatch kwsm;
618         size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
619         if (offset == -1) {
620                 match->rm_so = match->rm_eo = -1;
621                 return REG_NOMATCH;
622         } else {
623                 match->rm_so = offset;
624                 match->rm_eo = match->rm_so + kwsm.size[0];
625                 return 0;
626         }
627 }
628
629 static int regmatch(const regex_t *preg, char *line, char *eol,
630                     regmatch_t *match, int eflags)
631 {
632 #ifdef REG_STARTEND
633         match->rm_so = 0;
634         match->rm_eo = eol - line;
635         eflags |= REG_STARTEND;
636 #endif
637         return regexec(preg, line, 1, match, eflags);
638 }
639
640 static int patmatch(struct grep_pat *p, char *line, char *eol,
641                     regmatch_t *match, int eflags)
642 {
643         int hit;
644
645         if (p->fixed)
646                 hit = !fixmatch(p, line, eol, match);
647         else if (p->pcre_regexp)
648                 hit = !pcrematch(p, line, eol, match, eflags);
649         else
650                 hit = !regmatch(&p->regexp, line, eol, match, eflags);
651
652         return hit;
653 }
654
655 static int strip_timestamp(char *bol, char **eol_p)
656 {
657         char *eol = *eol_p;
658         int ch;
659
660         while (bol < --eol) {
661                 if (*eol != '>')
662                         continue;
663                 *eol_p = ++eol;
664                 ch = *eol;
665                 *eol = '\0';
666                 return ch;
667         }
668         return 0;
669 }
670
671 static struct {
672         const char *field;
673         size_t len;
674 } header_field[] = {
675         { "author ", 7 },
676         { "committer ", 10 },
677 };
678
679 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
680                              enum grep_context ctx,
681                              regmatch_t *pmatch, int eflags)
682 {
683         int hit = 0;
684         int saved_ch = 0;
685         const char *start = bol;
686
687         if ((p->token != GREP_PATTERN) &&
688             ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
689                 return 0;
690
691         if (p->token == GREP_PATTERN_HEAD) {
692                 const char *field;
693                 size_t len;
694                 assert(p->field < ARRAY_SIZE(header_field));
695                 field = header_field[p->field].field;
696                 len = header_field[p->field].len;
697                 if (strncmp(bol, field, len))
698                         return 0;
699                 bol += len;
700                 saved_ch = strip_timestamp(bol, &eol);
701         }
702
703  again:
704         hit = patmatch(p, bol, eol, pmatch, eflags);
705
706         if (hit && p->word_regexp) {
707                 if ((pmatch[0].rm_so < 0) ||
708                     (eol - bol) < pmatch[0].rm_so ||
709                     (pmatch[0].rm_eo < 0) ||
710                     (eol - bol) < pmatch[0].rm_eo)
711                         die("regexp returned nonsense");
712
713                 /* Match beginning must be either beginning of the
714                  * line, or at word boundary (i.e. the last char must
715                  * not be a word char).  Similarly, match end must be
716                  * either end of the line, or at word boundary
717                  * (i.e. the next char must not be a word char).
718                  */
719                 if ( ((pmatch[0].rm_so == 0) ||
720                       !word_char(bol[pmatch[0].rm_so-1])) &&
721                      ((pmatch[0].rm_eo == (eol-bol)) ||
722                       !word_char(bol[pmatch[0].rm_eo])) )
723                         ;
724                 else
725                         hit = 0;
726
727                 /* Words consist of at least one character. */
728                 if (pmatch->rm_so == pmatch->rm_eo)
729                         hit = 0;
730
731                 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
732                         /* There could be more than one match on the
733                          * line, and the first match might not be
734                          * strict word match.  But later ones could be!
735                          * Forward to the next possible start, i.e. the
736                          * next position following a non-word char.
737                          */
738                         bol = pmatch[0].rm_so + bol + 1;
739                         while (word_char(bol[-1]) && bol < eol)
740                                 bol++;
741                         eflags |= REG_NOTBOL;
742                         if (bol < eol)
743                                 goto again;
744                 }
745         }
746         if (p->token == GREP_PATTERN_HEAD && saved_ch)
747                 *eol = saved_ch;
748         if (hit) {
749                 pmatch[0].rm_so += bol - start;
750                 pmatch[0].rm_eo += bol - start;
751         }
752         return hit;
753 }
754
755 static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
756                            enum grep_context ctx, int collect_hits)
757 {
758         int h = 0;
759         regmatch_t match;
760
761         if (!x)
762                 die("Not a valid grep expression");
763         switch (x->node) {
764         case GREP_NODE_TRUE:
765                 h = 1;
766                 break;
767         case GREP_NODE_ATOM:
768                 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
769                 break;
770         case GREP_NODE_NOT:
771                 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
772                 break;
773         case GREP_NODE_AND:
774                 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
775                         return 0;
776                 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
777                 break;
778         case GREP_NODE_OR:
779                 if (!collect_hits)
780                         return (match_expr_eval(x->u.binary.left,
781                                                 bol, eol, ctx, 0) ||
782                                 match_expr_eval(x->u.binary.right,
783                                                 bol, eol, ctx, 0));
784                 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
785                 x->u.binary.left->hit |= h;
786                 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
787                 break;
788         default:
789                 die("Unexpected node type (internal error) %d", x->node);
790         }
791         if (collect_hits)
792                 x->hit |= h;
793         return h;
794 }
795
796 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
797                       enum grep_context ctx, int collect_hits)
798 {
799         struct grep_expr *x = opt->pattern_expression;
800         return match_expr_eval(x, bol, eol, ctx, collect_hits);
801 }
802
803 static int match_line(struct grep_opt *opt, char *bol, char *eol,
804                       enum grep_context ctx, int collect_hits)
805 {
806         struct grep_pat *p;
807         regmatch_t match;
808
809         if (opt->extended)
810                 return match_expr(opt, bol, eol, ctx, collect_hits);
811
812         /* we do not call with collect_hits without being extended */
813         for (p = opt->pattern_list; p; p = p->next) {
814                 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
815                         return 1;
816         }
817         return 0;
818 }
819
820 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
821                               enum grep_context ctx,
822                               regmatch_t *pmatch, int eflags)
823 {
824         regmatch_t match;
825
826         if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
827                 return 0;
828         if (match.rm_so < 0 || match.rm_eo < 0)
829                 return 0;
830         if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
831                 if (match.rm_so > pmatch->rm_so)
832                         return 1;
833                 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
834                         return 1;
835         }
836         pmatch->rm_so = match.rm_so;
837         pmatch->rm_eo = match.rm_eo;
838         return 1;
839 }
840
841 static int next_match(struct grep_opt *opt, char *bol, char *eol,
842                       enum grep_context ctx, regmatch_t *pmatch, int eflags)
843 {
844         struct grep_pat *p;
845         int hit = 0;
846
847         pmatch->rm_so = pmatch->rm_eo = -1;
848         if (bol < eol) {
849                 for (p = opt->pattern_list; p; p = p->next) {
850                         switch (p->token) {
851                         case GREP_PATTERN: /* atom */
852                         case GREP_PATTERN_HEAD:
853                         case GREP_PATTERN_BODY:
854                                 hit |= match_next_pattern(p, bol, eol, ctx,
855                                                           pmatch, eflags);
856                                 break;
857                         default:
858                                 break;
859                         }
860                 }
861         }
862         return hit;
863 }
864
865 static void show_line(struct grep_opt *opt, char *bol, char *eol,
866                       const char *name, unsigned lno, char sign)
867 {
868         int rest = eol - bol;
869         char *line_color = NULL;
870
871         if (opt->file_break && opt->last_shown == 0) {
872                 if (opt->show_hunk_mark)
873                         opt->output(opt, "\n", 1);
874         } else if (opt->pre_context || opt->post_context || opt->funcbody) {
875                 if (opt->last_shown == 0) {
876                         if (opt->show_hunk_mark) {
877                                 output_color(opt, "--", 2, opt->color_sep);
878                                 opt->output(opt, "\n", 1);
879                         }
880                 } else if (lno > opt->last_shown + 1) {
881                         output_color(opt, "--", 2, opt->color_sep);
882                         opt->output(opt, "\n", 1);
883                 }
884         }
885         if (opt->heading && opt->last_shown == 0) {
886                 output_color(opt, name, strlen(name), opt->color_filename);
887                 opt->output(opt, "\n", 1);
888         }
889         opt->last_shown = lno;
890
891         if (!opt->heading && opt->pathname) {
892                 output_color(opt, name, strlen(name), opt->color_filename);
893                 output_sep(opt, sign);
894         }
895         if (opt->linenum) {
896                 char buf[32];
897                 snprintf(buf, sizeof(buf), "%d", lno);
898                 output_color(opt, buf, strlen(buf), opt->color_lineno);
899                 output_sep(opt, sign);
900         }
901         if (opt->color) {
902                 regmatch_t match;
903                 enum grep_context ctx = GREP_CONTEXT_BODY;
904                 int ch = *eol;
905                 int eflags = 0;
906
907                 if (sign == ':')
908                         line_color = opt->color_selected;
909                 else if (sign == '-')
910                         line_color = opt->color_context;
911                 else if (sign == '=')
912                         line_color = opt->color_function;
913                 *eol = '\0';
914                 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
915                         if (match.rm_so == match.rm_eo)
916                                 break;
917
918                         output_color(opt, bol, match.rm_so, line_color);
919                         output_color(opt, bol + match.rm_so,
920                                      match.rm_eo - match.rm_so,
921                                      opt->color_match);
922                         bol += match.rm_eo;
923                         rest -= match.rm_eo;
924                         eflags = REG_NOTBOL;
925                 }
926                 *eol = ch;
927         }
928         output_color(opt, bol, rest, line_color);
929         opt->output(opt, "\n", 1);
930 }
931
932 #ifndef NO_PTHREADS
933 int grep_use_locks;
934
935 /*
936  * This lock protects access to the gitattributes machinery, which is
937  * not thread-safe.
938  */
939 pthread_mutex_t grep_attr_mutex;
940
941 static inline void grep_attr_lock(void)
942 {
943         if (grep_use_locks)
944                 pthread_mutex_lock(&grep_attr_mutex);
945 }
946
947 static inline void grep_attr_unlock(void)
948 {
949         if (grep_use_locks)
950                 pthread_mutex_unlock(&grep_attr_mutex);
951 }
952
953 /*
954  * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
955  */
956 pthread_mutex_t grep_read_mutex;
957
958 #else
959 #define grep_attr_lock()
960 #define grep_attr_unlock()
961 #endif
962
963 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
964 {
965         xdemitconf_t *xecfg = opt->priv;
966         if (xecfg && !xecfg->find_func) {
967                 grep_source_load_driver(gs);
968                 if (gs->driver->funcname.pattern) {
969                         const struct userdiff_funcname *pe = &gs->driver->funcname;
970                         xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
971                 } else {
972                         xecfg = opt->priv = NULL;
973                 }
974         }
975
976         if (xecfg) {
977                 char buf[1];
978                 return xecfg->find_func(bol, eol - bol, buf, 1,
979                                         xecfg->find_func_priv) >= 0;
980         }
981
982         if (bol == eol)
983                 return 0;
984         if (isalpha(*bol) || *bol == '_' || *bol == '$')
985                 return 1;
986         return 0;
987 }
988
989 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
990                                char *bol, unsigned lno)
991 {
992         while (bol > gs->buf) {
993                 char *eol = --bol;
994
995                 while (bol > gs->buf && bol[-1] != '\n')
996                         bol--;
997                 lno--;
998
999                 if (lno <= opt->last_shown)
1000                         break;
1001
1002                 if (match_funcname(opt, gs, bol, eol)) {
1003                         show_line(opt, bol, eol, gs->name, lno, '=');
1004                         break;
1005                 }
1006         }
1007 }
1008
1009 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1010                              char *bol, char *end, unsigned lno)
1011 {
1012         unsigned cur = lno, from = 1, funcname_lno = 0;
1013         int funcname_needed = !!opt->funcname;
1014
1015         if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1016                 funcname_needed = 2;
1017
1018         if (opt->pre_context < lno)
1019                 from = lno - opt->pre_context;
1020         if (from <= opt->last_shown)
1021                 from = opt->last_shown + 1;
1022
1023         /* Rewind. */
1024         while (bol > gs->buf &&
1025                cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1026                 char *eol = --bol;
1027
1028                 while (bol > gs->buf && bol[-1] != '\n')
1029                         bol--;
1030                 cur--;
1031                 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1032                         funcname_lno = cur;
1033                         funcname_needed = 0;
1034                 }
1035         }
1036
1037         /* We need to look even further back to find a function signature. */
1038         if (opt->funcname && funcname_needed)
1039                 show_funcname_line(opt, gs, bol, cur);
1040
1041         /* Back forward. */
1042         while (cur < lno) {
1043                 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1044
1045                 while (*eol != '\n')
1046                         eol++;
1047                 show_line(opt, bol, eol, gs->name, cur, sign);
1048                 bol = eol + 1;
1049                 cur++;
1050         }
1051 }
1052
1053 static int should_lookahead(struct grep_opt *opt)
1054 {
1055         struct grep_pat *p;
1056
1057         if (opt->extended)
1058                 return 0; /* punt for too complex stuff */
1059         if (opt->invert)
1060                 return 0;
1061         for (p = opt->pattern_list; p; p = p->next) {
1062                 if (p->token != GREP_PATTERN)
1063                         return 0; /* punt for "header only" and stuff */
1064         }
1065         return 1;
1066 }
1067
1068 static int look_ahead(struct grep_opt *opt,
1069                       unsigned long *left_p,
1070                       unsigned *lno_p,
1071                       char **bol_p)
1072 {
1073         unsigned lno = *lno_p;
1074         char *bol = *bol_p;
1075         struct grep_pat *p;
1076         char *sp, *last_bol;
1077         regoff_t earliest = -1;
1078
1079         for (p = opt->pattern_list; p; p = p->next) {
1080                 int hit;
1081                 regmatch_t m;
1082
1083                 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1084                 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1085                         continue;
1086                 if (earliest < 0 || m.rm_so < earliest)
1087                         earliest = m.rm_so;
1088         }
1089
1090         if (earliest < 0) {
1091                 *bol_p = bol + *left_p;
1092                 *left_p = 0;
1093                 return 1;
1094         }
1095         for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1096                 ; /* find the beginning of the line */
1097         last_bol = sp;
1098
1099         for (sp = bol; sp < last_bol; sp++) {
1100                 if (*sp == '\n')
1101                         lno++;
1102         }
1103         *left_p -= last_bol - bol;
1104         *bol_p = last_bol;
1105         *lno_p = lno;
1106         return 0;
1107 }
1108
1109 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
1110 {
1111         fwrite(buf, size, 1, stdout);
1112 }
1113
1114 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1115 {
1116         char *bol;
1117         unsigned long left;
1118         unsigned lno = 1;
1119         unsigned last_hit = 0;
1120         int binary_match_only = 0;
1121         unsigned count = 0;
1122         int try_lookahead = 0;
1123         int show_function = 0;
1124         enum grep_context ctx = GREP_CONTEXT_HEAD;
1125         xdemitconf_t xecfg;
1126
1127         if (!opt->output)
1128                 opt->output = std_output;
1129
1130         if (opt->pre_context || opt->post_context || opt->file_break ||
1131             opt->funcbody) {
1132                 /* Show hunk marks, except for the first file. */
1133                 if (opt->last_shown)
1134                         opt->show_hunk_mark = 1;
1135                 /*
1136                  * If we're using threads then we can't easily identify
1137                  * the first file.  Always put hunk marks in that case
1138                  * and skip the very first one later in work_done().
1139                  */
1140                 if (opt->output != std_output)
1141                         opt->show_hunk_mark = 1;
1142         }
1143         opt->last_shown = 0;
1144
1145         switch (opt->binary) {
1146         case GREP_BINARY_DEFAULT:
1147                 if (grep_source_is_binary(gs))
1148                         binary_match_only = 1;
1149                 break;
1150         case GREP_BINARY_NOMATCH:
1151                 if (grep_source_is_binary(gs))
1152                         return 0; /* Assume unmatch */
1153                 break;
1154         case GREP_BINARY_TEXT:
1155                 break;
1156         default:
1157                 die("bug: unknown binary handling mode");
1158         }
1159
1160         memset(&xecfg, 0, sizeof(xecfg));
1161         opt->priv = &xecfg;
1162
1163         try_lookahead = should_lookahead(opt);
1164
1165         if (grep_source_load(gs) < 0)
1166                 return 0;
1167
1168         bol = gs->buf;
1169         left = gs->size;
1170         while (left) {
1171                 char *eol, ch;
1172                 int hit;
1173
1174                 /*
1175                  * look_ahead() skips quickly to the line that possibly
1176                  * has the next hit; don't call it if we need to do
1177                  * something more than just skipping the current line
1178                  * in response to an unmatch for the current line.  E.g.
1179                  * inside a post-context window, we will show the current
1180                  * line as a context around the previous hit when it
1181                  * doesn't hit.
1182                  */
1183                 if (try_lookahead
1184                     && !(last_hit
1185                          && (show_function ||
1186                              lno <= last_hit + opt->post_context))
1187                     && look_ahead(opt, &left, &lno, &bol))
1188                         break;
1189                 eol = end_of_line(bol, &left);
1190                 ch = *eol;
1191                 *eol = 0;
1192
1193                 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1194                         ctx = GREP_CONTEXT_BODY;
1195
1196                 hit = match_line(opt, bol, eol, ctx, collect_hits);
1197                 *eol = ch;
1198
1199                 if (collect_hits)
1200                         goto next_line;
1201
1202                 /* "grep -v -e foo -e bla" should list lines
1203                  * that do not have either, so inversion should
1204                  * be done outside.
1205                  */
1206                 if (opt->invert)
1207                         hit = !hit;
1208                 if (opt->unmatch_name_only) {
1209                         if (hit)
1210                                 return 0;
1211                         goto next_line;
1212                 }
1213                 if (hit) {
1214                         count++;
1215                         if (opt->status_only)
1216                                 return 1;
1217                         if (opt->name_only) {
1218                                 show_name(opt, gs->name);
1219                                 return 1;
1220                         }
1221                         if (opt->count)
1222                                 goto next_line;
1223                         if (binary_match_only) {
1224                                 opt->output(opt, "Binary file ", 12);
1225                                 output_color(opt, gs->name, strlen(gs->name),
1226                                              opt->color_filename);
1227                                 opt->output(opt, " matches\n", 9);
1228                                 return 1;
1229                         }
1230                         /* Hit at this line.  If we haven't shown the
1231                          * pre-context lines, we would need to show them.
1232                          */
1233                         if (opt->pre_context || opt->funcbody)
1234                                 show_pre_context(opt, gs, bol, eol, lno);
1235                         else if (opt->funcname)
1236                                 show_funcname_line(opt, gs, bol, lno);
1237                         show_line(opt, bol, eol, gs->name, lno, ':');
1238                         last_hit = lno;
1239                         if (opt->funcbody)
1240                                 show_function = 1;
1241                         goto next_line;
1242                 }
1243                 if (show_function && match_funcname(opt, gs, bol, eol))
1244                         show_function = 0;
1245                 if (show_function ||
1246                     (last_hit && lno <= last_hit + opt->post_context)) {
1247                         /* If the last hit is within the post context,
1248                          * we need to show this line.
1249                          */
1250                         show_line(opt, bol, eol, gs->name, lno, '-');
1251                 }
1252
1253         next_line:
1254                 bol = eol + 1;
1255                 if (!left)
1256                         break;
1257                 left--;
1258                 lno++;
1259         }
1260
1261         if (collect_hits)
1262                 return 0;
1263
1264         if (opt->status_only)
1265                 return 0;
1266         if (opt->unmatch_name_only) {
1267                 /* We did not see any hit, so we want to show this */
1268                 show_name(opt, gs->name);
1269                 return 1;
1270         }
1271
1272         xdiff_clear_find_func(&xecfg);
1273         opt->priv = NULL;
1274
1275         /* NEEDSWORK:
1276          * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1277          * which feels mostly useless but sometimes useful.  Maybe
1278          * make it another option?  For now suppress them.
1279          */
1280         if (opt->count && count) {
1281                 char buf[32];
1282                 output_color(opt, gs->name, strlen(gs->name), opt->color_filename);
1283                 output_sep(opt, ':');
1284                 snprintf(buf, sizeof(buf), "%u\n", count);
1285                 opt->output(opt, buf, strlen(buf));
1286                 return 1;
1287         }
1288         return !!last_hit;
1289 }
1290
1291 static void clr_hit_marker(struct grep_expr *x)
1292 {
1293         /* All-hit markers are meaningful only at the very top level
1294          * OR node.
1295          */
1296         while (1) {
1297                 x->hit = 0;
1298                 if (x->node != GREP_NODE_OR)
1299                         return;
1300                 x->u.binary.left->hit = 0;
1301                 x = x->u.binary.right;
1302         }
1303 }
1304
1305 static int chk_hit_marker(struct grep_expr *x)
1306 {
1307         /* Top level nodes have hit markers.  See if they all are hits */
1308         while (1) {
1309                 if (x->node != GREP_NODE_OR)
1310                         return x->hit;
1311                 if (!x->u.binary.left->hit)
1312                         return 0;
1313                 x = x->u.binary.right;
1314         }
1315 }
1316
1317 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1318 {
1319         /*
1320          * we do not have to do the two-pass grep when we do not check
1321          * buffer-wide "all-match".
1322          */
1323         if (!opt->all_match)
1324                 return grep_source_1(opt, gs, 0);
1325
1326         /* Otherwise the toplevel "or" terms hit a bit differently.
1327          * We first clear hit markers from them.
1328          */
1329         clr_hit_marker(opt->pattern_expression);
1330         grep_source_1(opt, gs, 1);
1331
1332         if (!chk_hit_marker(opt->pattern_expression))
1333                 return 0;
1334
1335         return grep_source_1(opt, gs, 0);
1336 }
1337
1338 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1339 {
1340         struct grep_source gs;
1341         int r;
1342
1343         grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL);
1344         gs.buf = buf;
1345         gs.size = size;
1346
1347         r = grep_source(opt, &gs);
1348
1349         grep_source_clear(&gs);
1350         return r;
1351 }
1352
1353 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1354                       const char *name, const void *identifier)
1355 {
1356         gs->type = type;
1357         gs->name = name ? xstrdup(name) : NULL;
1358         gs->buf = NULL;
1359         gs->size = 0;
1360         gs->driver = NULL;
1361
1362         switch (type) {
1363         case GREP_SOURCE_FILE:
1364                 gs->identifier = xstrdup(identifier);
1365                 break;
1366         case GREP_SOURCE_SHA1:
1367                 gs->identifier = xmalloc(20);
1368                 memcpy(gs->identifier, identifier, 20);
1369                 break;
1370         case GREP_SOURCE_BUF:
1371                 gs->identifier = NULL;
1372         }
1373 }
1374
1375 void grep_source_clear(struct grep_source *gs)
1376 {
1377         free(gs->name);
1378         gs->name = NULL;
1379         free(gs->identifier);
1380         gs->identifier = NULL;
1381         grep_source_clear_data(gs);
1382 }
1383
1384 void grep_source_clear_data(struct grep_source *gs)
1385 {
1386         switch (gs->type) {
1387         case GREP_SOURCE_FILE:
1388         case GREP_SOURCE_SHA1:
1389                 free(gs->buf);
1390                 gs->buf = NULL;
1391                 gs->size = 0;
1392                 break;
1393         case GREP_SOURCE_BUF:
1394                 /* leave user-provided buf intact */
1395                 break;
1396         }
1397 }
1398
1399 static int grep_source_load_sha1(struct grep_source *gs)
1400 {
1401         enum object_type type;
1402
1403         grep_read_lock();
1404         gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1405         grep_read_unlock();
1406
1407         if (!gs->buf)
1408                 return error(_("'%s': unable to read %s"),
1409                              gs->name,
1410                              sha1_to_hex(gs->identifier));
1411         return 0;
1412 }
1413
1414 static int grep_source_load_file(struct grep_source *gs)
1415 {
1416         const char *filename = gs->identifier;
1417         struct stat st;
1418         char *data;
1419         size_t size;
1420         int i;
1421
1422         if (lstat(filename, &st) < 0) {
1423         err_ret:
1424                 if (errno != ENOENT)
1425                         error(_("'%s': %s"), filename, strerror(errno));
1426                 return -1;
1427         }
1428         if (!S_ISREG(st.st_mode))
1429                 return -1;
1430         size = xsize_t(st.st_size);
1431         i = open(filename, O_RDONLY);
1432         if (i < 0)
1433                 goto err_ret;
1434         data = xmalloc(size + 1);
1435         if (st.st_size != read_in_full(i, data, size)) {
1436                 error(_("'%s': short read %s"), filename, strerror(errno));
1437                 close(i);
1438                 free(data);
1439                 return -1;
1440         }
1441         close(i);
1442         data[size] = 0;
1443
1444         gs->buf = data;
1445         gs->size = size;
1446         return 0;
1447 }
1448
1449 int grep_source_load(struct grep_source *gs)
1450 {
1451         if (gs->buf)
1452                 return 0;
1453
1454         switch (gs->type) {
1455         case GREP_SOURCE_FILE:
1456                 return grep_source_load_file(gs);
1457         case GREP_SOURCE_SHA1:
1458                 return grep_source_load_sha1(gs);
1459         case GREP_SOURCE_BUF:
1460                 return gs->buf ? 0 : -1;
1461         }
1462         die("BUG: invalid grep_source type");
1463 }
1464
1465 void grep_source_load_driver(struct grep_source *gs)
1466 {
1467         if (gs->driver)
1468                 return;
1469
1470         grep_attr_lock();
1471         gs->driver = userdiff_find_by_path(gs->name);
1472         if (!gs->driver)
1473                 gs->driver = userdiff_find_by_name("default");
1474         grep_attr_unlock();
1475 }
1476
1477 int grep_source_is_binary(struct grep_source *gs)
1478 {
1479         grep_source_load_driver(gs);
1480         if (gs->driver->binary != -1)
1481                 return gs->driver->binary;
1482
1483         if (!grep_source_load(gs))
1484                 return buffer_is_binary(gs->buf, gs->size);
1485
1486         return 0;
1487 }