Merge branch 'jn/gitweb-unspecified-action' into maint-1.7.8
[git/debian.git] / grep.c
blob9c5e1cd950c8d1d97290a047fb3780482f8eb8b7
1 #include "cache.h"
2 #include "grep.h"
3 #include "userdiff.h"
4 #include "xdiff-interface.h"
6 void append_header_grep_pattern(struct grep_opt *opt, enum grep_header_field field, const char *pat)
8 struct grep_pat *p = xcalloc(1, sizeof(*p));
9 p->pattern = pat;
10 p->patternlen = strlen(pat);
11 p->origin = "header";
12 p->no = 0;
13 p->token = GREP_PATTERN_HEAD;
14 p->field = field;
15 *opt->header_tail = p;
16 opt->header_tail = &p->next;
17 p->next = NULL;
20 void append_grep_pattern(struct grep_opt *opt, const char *pat,
21 const char *origin, int no, enum grep_pat_token t)
23 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
26 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
27 const char *origin, int no, enum grep_pat_token t)
29 struct grep_pat *p = xcalloc(1, sizeof(*p));
30 p->pattern = pat;
31 p->patternlen = patlen;
32 p->origin = origin;
33 p->no = no;
34 p->token = t;
35 *opt->pattern_tail = p;
36 opt->pattern_tail = &p->next;
37 p->next = NULL;
40 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
42 struct grep_pat *pat;
43 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
44 *ret = *opt;
46 ret->pattern_list = NULL;
47 ret->pattern_tail = &ret->pattern_list;
49 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
51 if(pat->token == GREP_PATTERN_HEAD)
52 append_header_grep_pattern(ret, pat->field,
53 pat->pattern);
54 else
55 append_grep_pat(ret, pat->pattern, pat->patternlen,
56 pat->origin, pat->no, pat->token);
59 return ret;
62 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
63 const char *error)
65 char where[1024];
67 if (p->no)
68 sprintf(where, "In '%s' at %d, ", p->origin, p->no);
69 else if (p->origin)
70 sprintf(where, "%s, ", p->origin);
71 else
72 where[0] = 0;
74 die("%s'%s': %s", where, p->pattern, error);
77 #ifdef USE_LIBPCRE
78 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
80 const char *error;
81 int erroffset;
82 int options = PCRE_MULTILINE;
84 if (opt->ignore_case)
85 options |= PCRE_CASELESS;
87 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
88 NULL);
89 if (!p->pcre_regexp)
90 compile_regexp_failed(p, error);
92 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
93 if (!p->pcre_extra_info && error)
94 die("%s", error);
97 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
98 regmatch_t *match, int eflags)
100 int ovector[30], ret, flags = 0;
102 if (eflags & REG_NOTBOL)
103 flags |= PCRE_NOTBOL;
105 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
106 0, flags, ovector, ARRAY_SIZE(ovector));
107 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
108 die("pcre_exec failed with error code %d", ret);
109 if (ret > 0) {
110 ret = 0;
111 match->rm_so = ovector[0];
112 match->rm_eo = ovector[1];
115 return ret;
118 static void free_pcre_regexp(struct grep_pat *p)
120 pcre_free(p->pcre_regexp);
121 pcre_free(p->pcre_extra_info);
123 #else /* !USE_LIBPCRE */
124 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
126 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
129 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
130 regmatch_t *match, int eflags)
132 return 1;
135 static void free_pcre_regexp(struct grep_pat *p)
138 #endif /* !USE_LIBPCRE */
140 static int is_fixed(const char *s, size_t len)
142 size_t i;
144 /* regcomp cannot accept patterns with NULs so we
145 * consider any pattern containing a NUL fixed.
147 if (memchr(s, 0, len))
148 return 1;
150 for (i = 0; i < len; i++) {
151 if (is_regex_special(s[i]))
152 return 0;
155 return 1;
158 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
160 int err;
162 p->word_regexp = opt->word_regexp;
163 p->ignore_case = opt->ignore_case;
165 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
166 p->fixed = 1;
167 else
168 p->fixed = 0;
170 if (p->fixed) {
171 if (opt->regflags & REG_ICASE || p->ignore_case) {
172 static char trans[256];
173 int i;
174 for (i = 0; i < 256; i++)
175 trans[i] = tolower(i);
176 p->kws = kwsalloc(trans);
177 } else {
178 p->kws = kwsalloc(NULL);
180 kwsincr(p->kws, p->pattern, p->patternlen);
181 kwsprep(p->kws);
182 return;
185 if (opt->pcre) {
186 compile_pcre_regexp(p, opt);
187 return;
190 err = regcomp(&p->regexp, p->pattern, opt->regflags);
191 if (err) {
192 char errbuf[1024];
193 regerror(err, &p->regexp, errbuf, 1024);
194 regfree(&p->regexp);
195 compile_regexp_failed(p, errbuf);
199 static struct grep_expr *compile_pattern_or(struct grep_pat **);
200 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
202 struct grep_pat *p;
203 struct grep_expr *x;
205 p = *list;
206 if (!p)
207 return NULL;
208 switch (p->token) {
209 case GREP_PATTERN: /* atom */
210 case GREP_PATTERN_HEAD:
211 case GREP_PATTERN_BODY:
212 x = xcalloc(1, sizeof (struct grep_expr));
213 x->node = GREP_NODE_ATOM;
214 x->u.atom = p;
215 *list = p->next;
216 return x;
217 case GREP_OPEN_PAREN:
218 *list = p->next;
219 x = compile_pattern_or(list);
220 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
221 die("unmatched parenthesis");
222 *list = (*list)->next;
223 return x;
224 default:
225 return NULL;
229 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
231 struct grep_pat *p;
232 struct grep_expr *x;
234 p = *list;
235 if (!p)
236 return NULL;
237 switch (p->token) {
238 case GREP_NOT:
239 if (!p->next)
240 die("--not not followed by pattern expression");
241 *list = p->next;
242 x = xcalloc(1, sizeof (struct grep_expr));
243 x->node = GREP_NODE_NOT;
244 x->u.unary = compile_pattern_not(list);
245 if (!x->u.unary)
246 die("--not followed by non pattern expression");
247 return x;
248 default:
249 return compile_pattern_atom(list);
253 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
255 struct grep_pat *p;
256 struct grep_expr *x, *y, *z;
258 x = compile_pattern_not(list);
259 p = *list;
260 if (p && p->token == GREP_AND) {
261 if (!p->next)
262 die("--and not followed by pattern expression");
263 *list = p->next;
264 y = compile_pattern_and(list);
265 if (!y)
266 die("--and not followed by pattern expression");
267 z = xcalloc(1, sizeof (struct grep_expr));
268 z->node = GREP_NODE_AND;
269 z->u.binary.left = x;
270 z->u.binary.right = y;
271 return z;
273 return x;
276 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
278 struct grep_pat *p;
279 struct grep_expr *x, *y, *z;
281 x = compile_pattern_and(list);
282 p = *list;
283 if (x && p && p->token != GREP_CLOSE_PAREN) {
284 y = compile_pattern_or(list);
285 if (!y)
286 die("not a pattern expression %s", p->pattern);
287 z = xcalloc(1, sizeof (struct grep_expr));
288 z->node = GREP_NODE_OR;
289 z->u.binary.left = x;
290 z->u.binary.right = y;
291 return z;
293 return x;
296 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
298 return compile_pattern_or(list);
301 static struct grep_expr *grep_true_expr(void)
303 struct grep_expr *z = xcalloc(1, sizeof(*z));
304 z->node = GREP_NODE_TRUE;
305 return z;
308 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
310 struct grep_expr *z = xcalloc(1, sizeof(*z));
311 z->node = GREP_NODE_OR;
312 z->u.binary.left = left;
313 z->u.binary.right = right;
314 return z;
317 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
319 struct grep_pat *p;
320 struct grep_expr *header_expr;
321 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
322 enum grep_header_field fld;
324 if (!opt->header_list)
325 return NULL;
326 p = opt->header_list;
327 for (p = opt->header_list; p; p = p->next) {
328 if (p->token != GREP_PATTERN_HEAD)
329 die("bug: a non-header pattern in grep header list.");
330 if (p->field < 0 || GREP_HEADER_FIELD_MAX <= p->field)
331 die("bug: unknown header field %d", p->field);
332 compile_regexp(p, opt);
335 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
336 header_group[fld] = NULL;
338 for (p = opt->header_list; p; p = p->next) {
339 struct grep_expr *h;
340 struct grep_pat *pp = p;
342 h = compile_pattern_atom(&pp);
343 if (!h || pp != p->next)
344 die("bug: malformed header expr");
345 if (!header_group[p->field]) {
346 header_group[p->field] = h;
347 continue;
349 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
352 header_expr = NULL;
354 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
355 if (!header_group[fld])
356 continue;
357 if (!header_expr)
358 header_expr = grep_true_expr();
359 header_expr = grep_or_expr(header_group[fld], header_expr);
361 return header_expr;
364 void compile_grep_patterns(struct grep_opt *opt)
366 struct grep_pat *p;
367 struct grep_expr *header_expr = prep_header_patterns(opt);
369 for (p = opt->pattern_list; p; p = p->next) {
370 switch (p->token) {
371 case GREP_PATTERN: /* atom */
372 case GREP_PATTERN_HEAD:
373 case GREP_PATTERN_BODY:
374 compile_regexp(p, opt);
375 break;
376 default:
377 opt->extended = 1;
378 break;
382 if (opt->all_match || header_expr)
383 opt->extended = 1;
384 else if (!opt->extended)
385 return;
387 p = opt->pattern_list;
388 if (p)
389 opt->pattern_expression = compile_pattern_expr(&p);
390 if (p)
391 die("incomplete pattern expression: %s", p->pattern);
393 if (!header_expr)
394 return;
396 if (!opt->pattern_expression)
397 opt->pattern_expression = header_expr;
398 else
399 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
400 header_expr);
401 opt->all_match = 1;
404 static void free_pattern_expr(struct grep_expr *x)
406 switch (x->node) {
407 case GREP_NODE_TRUE:
408 case GREP_NODE_ATOM:
409 break;
410 case GREP_NODE_NOT:
411 free_pattern_expr(x->u.unary);
412 break;
413 case GREP_NODE_AND:
414 case GREP_NODE_OR:
415 free_pattern_expr(x->u.binary.left);
416 free_pattern_expr(x->u.binary.right);
417 break;
419 free(x);
422 void free_grep_patterns(struct grep_opt *opt)
424 struct grep_pat *p, *n;
426 for (p = opt->pattern_list; p; p = n) {
427 n = p->next;
428 switch (p->token) {
429 case GREP_PATTERN: /* atom */
430 case GREP_PATTERN_HEAD:
431 case GREP_PATTERN_BODY:
432 if (p->kws)
433 kwsfree(p->kws);
434 else if (p->pcre_regexp)
435 free_pcre_regexp(p);
436 else
437 regfree(&p->regexp);
438 break;
439 default:
440 break;
442 free(p);
445 if (!opt->extended)
446 return;
447 free_pattern_expr(opt->pattern_expression);
450 static char *end_of_line(char *cp, unsigned long *left)
452 unsigned long l = *left;
453 while (l && *cp != '\n') {
454 l--;
455 cp++;
457 *left = l;
458 return cp;
461 static int word_char(char ch)
463 return isalnum(ch) || ch == '_';
466 static void output_color(struct grep_opt *opt, const void *data, size_t size,
467 const char *color)
469 if (want_color(opt->color) && color && color[0]) {
470 opt->output(opt, color, strlen(color));
471 opt->output(opt, data, size);
472 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
473 } else
474 opt->output(opt, data, size);
477 static void output_sep(struct grep_opt *opt, char sign)
479 if (opt->null_following_name)
480 opt->output(opt, "\0", 1);
481 else
482 output_color(opt, &sign, 1, opt->color_sep);
485 static void show_name(struct grep_opt *opt, const char *name)
487 output_color(opt, name, strlen(name), opt->color_filename);
488 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
491 static int fixmatch(struct grep_pat *p, char *line, char *eol,
492 regmatch_t *match)
494 struct kwsmatch kwsm;
495 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
496 if (offset == -1) {
497 match->rm_so = match->rm_eo = -1;
498 return REG_NOMATCH;
499 } else {
500 match->rm_so = offset;
501 match->rm_eo = match->rm_so + kwsm.size[0];
502 return 0;
506 static int regmatch(const regex_t *preg, char *line, char *eol,
507 regmatch_t *match, int eflags)
509 #ifdef REG_STARTEND
510 match->rm_so = 0;
511 match->rm_eo = eol - line;
512 eflags |= REG_STARTEND;
513 #endif
514 return regexec(preg, line, 1, match, eflags);
517 static int patmatch(struct grep_pat *p, char *line, char *eol,
518 regmatch_t *match, int eflags)
520 int hit;
522 if (p->fixed)
523 hit = !fixmatch(p, line, eol, match);
524 else if (p->pcre_regexp)
525 hit = !pcrematch(p, line, eol, match, eflags);
526 else
527 hit = !regmatch(&p->regexp, line, eol, match, eflags);
529 return hit;
532 static int strip_timestamp(char *bol, char **eol_p)
534 char *eol = *eol_p;
535 int ch;
537 while (bol < --eol) {
538 if (*eol != '>')
539 continue;
540 *eol_p = ++eol;
541 ch = *eol;
542 *eol = '\0';
543 return ch;
545 return 0;
548 static struct {
549 const char *field;
550 size_t len;
551 } header_field[] = {
552 { "author ", 7 },
553 { "committer ", 10 },
556 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
557 enum grep_context ctx,
558 regmatch_t *pmatch, int eflags)
560 int hit = 0;
561 int saved_ch = 0;
562 const char *start = bol;
564 if ((p->token != GREP_PATTERN) &&
565 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
566 return 0;
568 if (p->token == GREP_PATTERN_HEAD) {
569 const char *field;
570 size_t len;
571 assert(p->field < ARRAY_SIZE(header_field));
572 field = header_field[p->field].field;
573 len = header_field[p->field].len;
574 if (strncmp(bol, field, len))
575 return 0;
576 bol += len;
577 saved_ch = strip_timestamp(bol, &eol);
580 again:
581 hit = patmatch(p, bol, eol, pmatch, eflags);
583 if (hit && p->word_regexp) {
584 if ((pmatch[0].rm_so < 0) ||
585 (eol - bol) < pmatch[0].rm_so ||
586 (pmatch[0].rm_eo < 0) ||
587 (eol - bol) < pmatch[0].rm_eo)
588 die("regexp returned nonsense");
590 /* Match beginning must be either beginning of the
591 * line, or at word boundary (i.e. the last char must
592 * not be a word char). Similarly, match end must be
593 * either end of the line, or at word boundary
594 * (i.e. the next char must not be a word char).
596 if ( ((pmatch[0].rm_so == 0) ||
597 !word_char(bol[pmatch[0].rm_so-1])) &&
598 ((pmatch[0].rm_eo == (eol-bol)) ||
599 !word_char(bol[pmatch[0].rm_eo])) )
601 else
602 hit = 0;
604 /* Words consist of at least one character. */
605 if (pmatch->rm_so == pmatch->rm_eo)
606 hit = 0;
608 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
609 /* There could be more than one match on the
610 * line, and the first match might not be
611 * strict word match. But later ones could be!
612 * Forward to the next possible start, i.e. the
613 * next position following a non-word char.
615 bol = pmatch[0].rm_so + bol + 1;
616 while (word_char(bol[-1]) && bol < eol)
617 bol++;
618 eflags |= REG_NOTBOL;
619 if (bol < eol)
620 goto again;
623 if (p->token == GREP_PATTERN_HEAD && saved_ch)
624 *eol = saved_ch;
625 if (hit) {
626 pmatch[0].rm_so += bol - start;
627 pmatch[0].rm_eo += bol - start;
629 return hit;
632 static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
633 enum grep_context ctx, int collect_hits)
635 int h = 0;
636 regmatch_t match;
638 if (!x)
639 die("Not a valid grep expression");
640 switch (x->node) {
641 case GREP_NODE_TRUE:
642 h = 1;
643 break;
644 case GREP_NODE_ATOM:
645 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
646 break;
647 case GREP_NODE_NOT:
648 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
649 break;
650 case GREP_NODE_AND:
651 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
652 return 0;
653 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
654 break;
655 case GREP_NODE_OR:
656 if (!collect_hits)
657 return (match_expr_eval(x->u.binary.left,
658 bol, eol, ctx, 0) ||
659 match_expr_eval(x->u.binary.right,
660 bol, eol, ctx, 0));
661 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
662 x->u.binary.left->hit |= h;
663 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
664 break;
665 default:
666 die("Unexpected node type (internal error) %d", x->node);
668 if (collect_hits)
669 x->hit |= h;
670 return h;
673 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
674 enum grep_context ctx, int collect_hits)
676 struct grep_expr *x = opt->pattern_expression;
677 return match_expr_eval(x, bol, eol, ctx, collect_hits);
680 static int match_line(struct grep_opt *opt, char *bol, char *eol,
681 enum grep_context ctx, int collect_hits)
683 struct grep_pat *p;
684 regmatch_t match;
686 if (opt->extended)
687 return match_expr(opt, bol, eol, ctx, collect_hits);
689 /* we do not call with collect_hits without being extended */
690 for (p = opt->pattern_list; p; p = p->next) {
691 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
692 return 1;
694 return 0;
697 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
698 enum grep_context ctx,
699 regmatch_t *pmatch, int eflags)
701 regmatch_t match;
703 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
704 return 0;
705 if (match.rm_so < 0 || match.rm_eo < 0)
706 return 0;
707 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
708 if (match.rm_so > pmatch->rm_so)
709 return 1;
710 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
711 return 1;
713 pmatch->rm_so = match.rm_so;
714 pmatch->rm_eo = match.rm_eo;
715 return 1;
718 static int next_match(struct grep_opt *opt, char *bol, char *eol,
719 enum grep_context ctx, regmatch_t *pmatch, int eflags)
721 struct grep_pat *p;
722 int hit = 0;
724 pmatch->rm_so = pmatch->rm_eo = -1;
725 if (bol < eol) {
726 for (p = opt->pattern_list; p; p = p->next) {
727 switch (p->token) {
728 case GREP_PATTERN: /* atom */
729 case GREP_PATTERN_HEAD:
730 case GREP_PATTERN_BODY:
731 hit |= match_next_pattern(p, bol, eol, ctx,
732 pmatch, eflags);
733 break;
734 default:
735 break;
739 return hit;
742 static void show_line(struct grep_opt *opt, char *bol, char *eol,
743 const char *name, unsigned lno, char sign)
745 int rest = eol - bol;
746 char *line_color = NULL;
748 if (opt->file_break && opt->last_shown == 0) {
749 if (opt->show_hunk_mark)
750 opt->output(opt, "\n", 1);
751 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
752 if (opt->last_shown == 0) {
753 if (opt->show_hunk_mark) {
754 output_color(opt, "--", 2, opt->color_sep);
755 opt->output(opt, "\n", 1);
757 } else if (lno > opt->last_shown + 1) {
758 output_color(opt, "--", 2, opt->color_sep);
759 opt->output(opt, "\n", 1);
762 if (opt->heading && opt->last_shown == 0) {
763 output_color(opt, name, strlen(name), opt->color_filename);
764 opt->output(opt, "\n", 1);
766 opt->last_shown = lno;
768 if (!opt->heading && opt->pathname) {
769 output_color(opt, name, strlen(name), opt->color_filename);
770 output_sep(opt, sign);
772 if (opt->linenum) {
773 char buf[32];
774 snprintf(buf, sizeof(buf), "%d", lno);
775 output_color(opt, buf, strlen(buf), opt->color_lineno);
776 output_sep(opt, sign);
778 if (opt->color) {
779 regmatch_t match;
780 enum grep_context ctx = GREP_CONTEXT_BODY;
781 int ch = *eol;
782 int eflags = 0;
784 if (sign == ':')
785 line_color = opt->color_selected;
786 else if (sign == '-')
787 line_color = opt->color_context;
788 else if (sign == '=')
789 line_color = opt->color_function;
790 *eol = '\0';
791 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
792 if (match.rm_so == match.rm_eo)
793 break;
795 output_color(opt, bol, match.rm_so, line_color);
796 output_color(opt, bol + match.rm_so,
797 match.rm_eo - match.rm_so,
798 opt->color_match);
799 bol += match.rm_eo;
800 rest -= match.rm_eo;
801 eflags = REG_NOTBOL;
803 *eol = ch;
805 output_color(opt, bol, rest, line_color);
806 opt->output(opt, "\n", 1);
809 static int match_funcname(struct grep_opt *opt, char *bol, char *eol)
811 xdemitconf_t *xecfg = opt->priv;
812 if (xecfg && xecfg->find_func) {
813 char buf[1];
814 return xecfg->find_func(bol, eol - bol, buf, 1,
815 xecfg->find_func_priv) >= 0;
818 if (bol == eol)
819 return 0;
820 if (isalpha(*bol) || *bol == '_' || *bol == '$')
821 return 1;
822 return 0;
825 static void show_funcname_line(struct grep_opt *opt, const char *name,
826 char *buf, char *bol, unsigned lno)
828 while (bol > buf) {
829 char *eol = --bol;
831 while (bol > buf && bol[-1] != '\n')
832 bol--;
833 lno--;
835 if (lno <= opt->last_shown)
836 break;
838 if (match_funcname(opt, bol, eol)) {
839 show_line(opt, bol, eol, name, lno, '=');
840 break;
845 static void show_pre_context(struct grep_opt *opt, const char *name, char *buf,
846 char *bol, char *end, unsigned lno)
848 unsigned cur = lno, from = 1, funcname_lno = 0;
849 int funcname_needed = !!opt->funcname;
851 if (opt->funcbody && !match_funcname(opt, bol, end))
852 funcname_needed = 2;
854 if (opt->pre_context < lno)
855 from = lno - opt->pre_context;
856 if (from <= opt->last_shown)
857 from = opt->last_shown + 1;
859 /* Rewind. */
860 while (bol > buf &&
861 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
862 char *eol = --bol;
864 while (bol > buf && bol[-1] != '\n')
865 bol--;
866 cur--;
867 if (funcname_needed && match_funcname(opt, bol, eol)) {
868 funcname_lno = cur;
869 funcname_needed = 0;
873 /* We need to look even further back to find a function signature. */
874 if (opt->funcname && funcname_needed)
875 show_funcname_line(opt, name, buf, bol, cur);
877 /* Back forward. */
878 while (cur < lno) {
879 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
881 while (*eol != '\n')
882 eol++;
883 show_line(opt, bol, eol, name, cur, sign);
884 bol = eol + 1;
885 cur++;
889 static int should_lookahead(struct grep_opt *opt)
891 struct grep_pat *p;
893 if (opt->extended)
894 return 0; /* punt for too complex stuff */
895 if (opt->invert)
896 return 0;
897 for (p = opt->pattern_list; p; p = p->next) {
898 if (p->token != GREP_PATTERN)
899 return 0; /* punt for "header only" and stuff */
901 return 1;
904 static int look_ahead(struct grep_opt *opt,
905 unsigned long *left_p,
906 unsigned *lno_p,
907 char **bol_p)
909 unsigned lno = *lno_p;
910 char *bol = *bol_p;
911 struct grep_pat *p;
912 char *sp, *last_bol;
913 regoff_t earliest = -1;
915 for (p = opt->pattern_list; p; p = p->next) {
916 int hit;
917 regmatch_t m;
919 hit = patmatch(p, bol, bol + *left_p, &m, 0);
920 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
921 continue;
922 if (earliest < 0 || m.rm_so < earliest)
923 earliest = m.rm_so;
926 if (earliest < 0) {
927 *bol_p = bol + *left_p;
928 *left_p = 0;
929 return 1;
931 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
932 ; /* find the beginning of the line */
933 last_bol = sp;
935 for (sp = bol; sp < last_bol; sp++) {
936 if (*sp == '\n')
937 lno++;
939 *left_p -= last_bol - bol;
940 *bol_p = last_bol;
941 *lno_p = lno;
942 return 0;
945 int grep_threads_ok(const struct grep_opt *opt)
947 /* If this condition is true, then we may use the attribute
948 * machinery in grep_buffer_1. The attribute code is not
949 * thread safe, so we disable the use of threads.
951 if (opt->funcname && !opt->unmatch_name_only && !opt->status_only &&
952 !opt->name_only)
953 return 0;
955 return 1;
958 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
960 fwrite(buf, size, 1, stdout);
963 static int grep_buffer_1(struct grep_opt *opt, const char *name,
964 char *buf, unsigned long size, int collect_hits)
966 char *bol = buf;
967 unsigned long left = size;
968 unsigned lno = 1;
969 unsigned last_hit = 0;
970 int binary_match_only = 0;
971 unsigned count = 0;
972 int try_lookahead = 0;
973 int show_function = 0;
974 enum grep_context ctx = GREP_CONTEXT_HEAD;
975 xdemitconf_t xecfg;
977 if (!opt->output)
978 opt->output = std_output;
980 if (opt->pre_context || opt->post_context || opt->file_break ||
981 opt->funcbody) {
982 /* Show hunk marks, except for the first file. */
983 if (opt->last_shown)
984 opt->show_hunk_mark = 1;
986 * If we're using threads then we can't easily identify
987 * the first file. Always put hunk marks in that case
988 * and skip the very first one later in work_done().
990 if (opt->output != std_output)
991 opt->show_hunk_mark = 1;
993 opt->last_shown = 0;
995 switch (opt->binary) {
996 case GREP_BINARY_DEFAULT:
997 if (buffer_is_binary(buf, size))
998 binary_match_only = 1;
999 break;
1000 case GREP_BINARY_NOMATCH:
1001 if (buffer_is_binary(buf, size))
1002 return 0; /* Assume unmatch */
1003 break;
1004 case GREP_BINARY_TEXT:
1005 break;
1006 default:
1007 die("bug: unknown binary handling mode");
1010 memset(&xecfg, 0, sizeof(xecfg));
1011 if (opt->funcname && !opt->unmatch_name_only && !opt->status_only &&
1012 !opt->name_only && !binary_match_only && !collect_hits) {
1013 struct userdiff_driver *drv = userdiff_find_by_path(name);
1014 if (drv && drv->funcname.pattern) {
1015 const struct userdiff_funcname *pe = &drv->funcname;
1016 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1017 opt->priv = &xecfg;
1020 try_lookahead = should_lookahead(opt);
1022 while (left) {
1023 char *eol, ch;
1024 int hit;
1027 * look_ahead() skips quickly to the line that possibly
1028 * has the next hit; don't call it if we need to do
1029 * something more than just skipping the current line
1030 * in response to an unmatch for the current line. E.g.
1031 * inside a post-context window, we will show the current
1032 * line as a context around the previous hit when it
1033 * doesn't hit.
1035 if (try_lookahead
1036 && !(last_hit
1037 && (show_function ||
1038 lno <= last_hit + opt->post_context))
1039 && look_ahead(opt, &left, &lno, &bol))
1040 break;
1041 eol = end_of_line(bol, &left);
1042 ch = *eol;
1043 *eol = 0;
1045 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1046 ctx = GREP_CONTEXT_BODY;
1048 hit = match_line(opt, bol, eol, ctx, collect_hits);
1049 *eol = ch;
1051 if (collect_hits)
1052 goto next_line;
1054 /* "grep -v -e foo -e bla" should list lines
1055 * that do not have either, so inversion should
1056 * be done outside.
1058 if (opt->invert)
1059 hit = !hit;
1060 if (opt->unmatch_name_only) {
1061 if (hit)
1062 return 0;
1063 goto next_line;
1065 if (hit) {
1066 count++;
1067 if (opt->status_only)
1068 return 1;
1069 if (opt->name_only) {
1070 show_name(opt, name);
1071 return 1;
1073 if (opt->count)
1074 goto next_line;
1075 if (binary_match_only) {
1076 opt->output(opt, "Binary file ", 12);
1077 output_color(opt, name, strlen(name),
1078 opt->color_filename);
1079 opt->output(opt, " matches\n", 9);
1080 return 1;
1082 /* Hit at this line. If we haven't shown the
1083 * pre-context lines, we would need to show them.
1085 if (opt->pre_context || opt->funcbody)
1086 show_pre_context(opt, name, buf, bol, eol, lno);
1087 else if (opt->funcname)
1088 show_funcname_line(opt, name, buf, bol, lno);
1089 show_line(opt, bol, eol, name, lno, ':');
1090 last_hit = lno;
1091 if (opt->funcbody)
1092 show_function = 1;
1093 goto next_line;
1095 if (show_function && match_funcname(opt, bol, eol))
1096 show_function = 0;
1097 if (show_function ||
1098 (last_hit && lno <= last_hit + opt->post_context)) {
1099 /* If the last hit is within the post context,
1100 * we need to show this line.
1102 show_line(opt, bol, eol, name, lno, '-');
1105 next_line:
1106 bol = eol + 1;
1107 if (!left)
1108 break;
1109 left--;
1110 lno++;
1113 if (collect_hits)
1114 return 0;
1116 if (opt->status_only)
1117 return 0;
1118 if (opt->unmatch_name_only) {
1119 /* We did not see any hit, so we want to show this */
1120 show_name(opt, name);
1121 return 1;
1124 xdiff_clear_find_func(&xecfg);
1125 opt->priv = NULL;
1127 /* NEEDSWORK:
1128 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1129 * which feels mostly useless but sometimes useful. Maybe
1130 * make it another option? For now suppress them.
1132 if (opt->count && count) {
1133 char buf[32];
1134 output_color(opt, name, strlen(name), opt->color_filename);
1135 output_sep(opt, ':');
1136 snprintf(buf, sizeof(buf), "%u\n", count);
1137 opt->output(opt, buf, strlen(buf));
1138 return 1;
1140 return !!last_hit;
1143 static void clr_hit_marker(struct grep_expr *x)
1145 /* All-hit markers are meaningful only at the very top level
1146 * OR node.
1148 while (1) {
1149 x->hit = 0;
1150 if (x->node != GREP_NODE_OR)
1151 return;
1152 x->u.binary.left->hit = 0;
1153 x = x->u.binary.right;
1157 static int chk_hit_marker(struct grep_expr *x)
1159 /* Top level nodes have hit markers. See if they all are hits */
1160 while (1) {
1161 if (x->node != GREP_NODE_OR)
1162 return x->hit;
1163 if (!x->u.binary.left->hit)
1164 return 0;
1165 x = x->u.binary.right;
1169 int grep_buffer(struct grep_opt *opt, const char *name, char *buf, unsigned long size)
1172 * we do not have to do the two-pass grep when we do not check
1173 * buffer-wide "all-match".
1175 if (!opt->all_match)
1176 return grep_buffer_1(opt, name, buf, size, 0);
1178 /* Otherwise the toplevel "or" terms hit a bit differently.
1179 * We first clear hit markers from them.
1181 clr_hit_marker(opt->pattern_expression);
1182 grep_buffer_1(opt, name, buf, size, 1);
1184 if (!chk_hit_marker(opt->pattern_expression))
1185 return 0;
1187 return grep_buffer_1(opt, name, buf, size, 0);