grep.c: extract show_line_header()
[git.git] / grep.c
blob4ff8a73043b194dbeb5fc7bd011e5931ad734846
1 #include "cache.h"
2 #include "config.h"
3 #include "grep.h"
4 #include "userdiff.h"
5 #include "xdiff-interface.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "commit.h"
9 #include "quote.h"
11 static int grep_source_load(struct grep_source *gs);
12 static int grep_source_is_binary(struct grep_source *gs);
14 static struct grep_opt grep_defaults;
16 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
18 fwrite(buf, size, 1, stdout);
21 static void color_set(char *dst, const char *color_bytes)
23 xsnprintf(dst, COLOR_MAXLEN, "%s", color_bytes);
27 * Initialize the grep_defaults template with hardcoded defaults.
28 * We could let the compiler do this, but without C99 initializers
29 * the code gets unwieldy and unreadable, so...
31 void init_grep_defaults(void)
33 struct grep_opt *opt = &grep_defaults;
34 static int run_once;
36 if (run_once)
37 return;
38 run_once++;
40 memset(opt, 0, sizeof(*opt));
41 opt->relative = 1;
42 opt->pathname = 1;
43 opt->max_depth = -1;
44 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
45 color_set(opt->color_context, "");
46 color_set(opt->color_filename, "");
47 color_set(opt->color_function, "");
48 color_set(opt->color_lineno, "");
49 color_set(opt->color_columnno, "");
50 color_set(opt->color_match_context, GIT_COLOR_BOLD_RED);
51 color_set(opt->color_match_selected, GIT_COLOR_BOLD_RED);
52 color_set(opt->color_selected, "");
53 color_set(opt->color_sep, GIT_COLOR_CYAN);
54 opt->color = -1;
55 opt->output = std_output;
58 static int parse_pattern_type_arg(const char *opt, const char *arg)
60 if (!strcmp(arg, "default"))
61 return GREP_PATTERN_TYPE_UNSPECIFIED;
62 else if (!strcmp(arg, "basic"))
63 return GREP_PATTERN_TYPE_BRE;
64 else if (!strcmp(arg, "extended"))
65 return GREP_PATTERN_TYPE_ERE;
66 else if (!strcmp(arg, "fixed"))
67 return GREP_PATTERN_TYPE_FIXED;
68 else if (!strcmp(arg, "perl"))
69 return GREP_PATTERN_TYPE_PCRE;
70 die("bad %s argument: %s", opt, arg);
74 * Read the configuration file once and store it in
75 * the grep_defaults template.
77 int grep_config(const char *var, const char *value, void *cb)
79 struct grep_opt *opt = &grep_defaults;
80 char *color = NULL;
82 if (userdiff_config(var, value) < 0)
83 return -1;
85 if (!strcmp(var, "grep.extendedregexp")) {
86 opt->extended_regexp_option = git_config_bool(var, value);
87 return 0;
90 if (!strcmp(var, "grep.patterntype")) {
91 opt->pattern_type_option = parse_pattern_type_arg(var, value);
92 return 0;
95 if (!strcmp(var, "grep.linenumber")) {
96 opt->linenum = git_config_bool(var, value);
97 return 0;
99 if (!strcmp(var, "grep.column")) {
100 opt->columnnum = git_config_bool(var, value);
101 return 0;
104 if (!strcmp(var, "grep.fullname")) {
105 opt->relative = !git_config_bool(var, value);
106 return 0;
109 if (!strcmp(var, "color.grep"))
110 opt->color = git_config_colorbool(var, value);
111 else if (!strcmp(var, "color.grep.context"))
112 color = opt->color_context;
113 else if (!strcmp(var, "color.grep.filename"))
114 color = opt->color_filename;
115 else if (!strcmp(var, "color.grep.function"))
116 color = opt->color_function;
117 else if (!strcmp(var, "color.grep.linenumber"))
118 color = opt->color_lineno;
119 else if (!strcmp(var, "color.grep.column"))
120 color = opt->color_columnno;
121 else if (!strcmp(var, "color.grep.matchcontext"))
122 color = opt->color_match_context;
123 else if (!strcmp(var, "color.grep.matchselected"))
124 color = opt->color_match_selected;
125 else if (!strcmp(var, "color.grep.selected"))
126 color = opt->color_selected;
127 else if (!strcmp(var, "color.grep.separator"))
128 color = opt->color_sep;
129 else if (!strcmp(var, "color.grep.match")) {
130 int rc = 0;
131 if (!value)
132 return config_error_nonbool(var);
133 rc |= color_parse(value, opt->color_match_context);
134 rc |= color_parse(value, opt->color_match_selected);
135 return rc;
138 if (color) {
139 if (!value)
140 return config_error_nonbool(var);
141 return color_parse(value, color);
143 return 0;
147 * Initialize one instance of grep_opt and copy the
148 * default values from the template we read the configuration
149 * information in an earlier call to git_config(grep_config).
151 void grep_init(struct grep_opt *opt, const char *prefix)
153 struct grep_opt *def = &grep_defaults;
155 memset(opt, 0, sizeof(*opt));
156 opt->prefix = prefix;
157 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
158 opt->pattern_tail = &opt->pattern_list;
159 opt->header_tail = &opt->header_list;
161 opt->color = def->color;
162 opt->extended_regexp_option = def->extended_regexp_option;
163 opt->pattern_type_option = def->pattern_type_option;
164 opt->linenum = def->linenum;
165 opt->columnnum = def->columnnum;
166 opt->max_depth = def->max_depth;
167 opt->pathname = def->pathname;
168 opt->relative = def->relative;
169 opt->output = def->output;
171 color_set(opt->color_context, def->color_context);
172 color_set(opt->color_filename, def->color_filename);
173 color_set(opt->color_function, def->color_function);
174 color_set(opt->color_lineno, def->color_lineno);
175 color_set(opt->color_columnno, def->color_columnno);
176 color_set(opt->color_match_context, def->color_match_context);
177 color_set(opt->color_match_selected, def->color_match_selected);
178 color_set(opt->color_selected, def->color_selected);
179 color_set(opt->color_sep, def->color_sep);
182 static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
185 * When committing to the pattern type by setting the relevant
186 * fields in grep_opt it's generally not necessary to zero out
187 * the fields we're not choosing, since they won't have been
188 * set by anything. The extended_regexp_option field is the
189 * only exception to this.
191 * This is because in the process of parsing grep.patternType
192 * & grep.extendedRegexp we set opt->pattern_type_option and
193 * opt->extended_regexp_option, respectively. We then
194 * internally use opt->extended_regexp_option to see if we're
195 * compiling an ERE. It must be unset if that's not actually
196 * the case.
198 if (pattern_type != GREP_PATTERN_TYPE_ERE &&
199 opt->extended_regexp_option)
200 opt->extended_regexp_option = 0;
202 switch (pattern_type) {
203 case GREP_PATTERN_TYPE_UNSPECIFIED:
204 /* fall through */
206 case GREP_PATTERN_TYPE_BRE:
207 break;
209 case GREP_PATTERN_TYPE_ERE:
210 opt->extended_regexp_option = 1;
211 break;
213 case GREP_PATTERN_TYPE_FIXED:
214 opt->fixed = 1;
215 break;
217 case GREP_PATTERN_TYPE_PCRE:
218 #ifdef USE_LIBPCRE2
219 opt->pcre2 = 1;
220 #else
222 * It's important that pcre1 always be assigned to
223 * even when there's no USE_LIBPCRE* defined. We still
224 * call the PCRE stub function, it just dies with
225 * "cannot use Perl-compatible regexes[...]".
227 opt->pcre1 = 1;
228 #endif
229 break;
233 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
235 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
236 grep_set_pattern_type_option(pattern_type, opt);
237 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
238 grep_set_pattern_type_option(opt->pattern_type_option, opt);
239 else if (opt->extended_regexp_option)
241 * This branch *must* happen after setting from the
242 * opt->pattern_type_option above, we don't want
243 * grep.extendedRegexp to override grep.patternType!
245 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
248 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
249 const char *origin, int no,
250 enum grep_pat_token t,
251 enum grep_header_field field)
253 struct grep_pat *p = xcalloc(1, sizeof(*p));
254 p->pattern = xmemdupz(pat, patlen);
255 p->patternlen = patlen;
256 p->origin = origin;
257 p->no = no;
258 p->token = t;
259 p->field = field;
260 return p;
263 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
265 **tail = p;
266 *tail = &p->next;
267 p->next = NULL;
269 switch (p->token) {
270 case GREP_PATTERN: /* atom */
271 case GREP_PATTERN_HEAD:
272 case GREP_PATTERN_BODY:
273 for (;;) {
274 struct grep_pat *new_pat;
275 size_t len = 0;
276 char *cp = p->pattern + p->patternlen, *nl = NULL;
277 while (++len <= p->patternlen) {
278 if (*(--cp) == '\n') {
279 nl = cp;
280 break;
283 if (!nl)
284 break;
285 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
286 p->no, p->token, p->field);
287 new_pat->next = p->next;
288 if (!p->next)
289 *tail = &new_pat->next;
290 p->next = new_pat;
291 *nl = '\0';
292 p->patternlen -= len;
294 break;
295 default:
296 break;
300 void append_header_grep_pattern(struct grep_opt *opt,
301 enum grep_header_field field, const char *pat)
303 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
304 GREP_PATTERN_HEAD, field);
305 if (field == GREP_HEADER_REFLOG)
306 opt->use_reflog_filter = 1;
307 do_append_grep_pat(&opt->header_tail, p);
310 void append_grep_pattern(struct grep_opt *opt, const char *pat,
311 const char *origin, int no, enum grep_pat_token t)
313 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
316 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
317 const char *origin, int no, enum grep_pat_token t)
319 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
320 do_append_grep_pat(&opt->pattern_tail, p);
323 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
325 struct grep_pat *pat;
326 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
327 *ret = *opt;
329 ret->pattern_list = NULL;
330 ret->pattern_tail = &ret->pattern_list;
332 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
334 if(pat->token == GREP_PATTERN_HEAD)
335 append_header_grep_pattern(ret, pat->field,
336 pat->pattern);
337 else
338 append_grep_pat(ret, pat->pattern, pat->patternlen,
339 pat->origin, pat->no, pat->token);
342 return ret;
345 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
346 const char *error)
348 char where[1024];
350 if (p->no)
351 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
352 else if (p->origin)
353 xsnprintf(where, sizeof(where), "%s, ", p->origin);
354 else
355 where[0] = 0;
357 die("%s'%s': %s", where, p->pattern, error);
360 static int is_fixed(const char *s, size_t len)
362 size_t i;
364 for (i = 0; i < len; i++) {
365 if (is_regex_special(s[i]))
366 return 0;
369 return 1;
372 static int has_null(const char *s, size_t len)
375 * regcomp cannot accept patterns with NULs so when using it
376 * we consider any pattern containing a NUL fixed.
378 if (memchr(s, 0, len))
379 return 1;
381 return 0;
384 #ifdef USE_LIBPCRE1
385 static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
387 const char *error;
388 int erroffset;
389 int options = PCRE_MULTILINE;
391 if (opt->ignore_case) {
392 if (has_non_ascii(p->pattern))
393 p->pcre1_tables = pcre_maketables();
394 options |= PCRE_CASELESS;
396 if (is_utf8_locale() && has_non_ascii(p->pattern))
397 options |= PCRE_UTF8;
399 p->pcre1_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
400 p->pcre1_tables);
401 if (!p->pcre1_regexp)
402 compile_regexp_failed(p, error);
404 p->pcre1_extra_info = pcre_study(p->pcre1_regexp, GIT_PCRE_STUDY_JIT_COMPILE, &error);
405 if (!p->pcre1_extra_info && error)
406 die("%s", error);
408 #ifdef GIT_PCRE1_USE_JIT
409 pcre_config(PCRE_CONFIG_JIT, &p->pcre1_jit_on);
410 if (p->pcre1_jit_on == 1) {
411 p->pcre1_jit_stack = pcre_jit_stack_alloc(1, 1024 * 1024);
412 if (!p->pcre1_jit_stack)
413 die("Couldn't allocate PCRE JIT stack");
414 pcre_assign_jit_stack(p->pcre1_extra_info, NULL, p->pcre1_jit_stack);
415 } else if (p->pcre1_jit_on != 0) {
416 BUG("The pcre1_jit_on variable should be 0 or 1, not %d",
417 p->pcre1_jit_on);
419 #endif
422 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
423 regmatch_t *match, int eflags)
425 int ovector[30], ret, flags = 0;
427 if (eflags & REG_NOTBOL)
428 flags |= PCRE_NOTBOL;
430 #ifdef GIT_PCRE1_USE_JIT
431 if (p->pcre1_jit_on) {
432 ret = pcre_jit_exec(p->pcre1_regexp, p->pcre1_extra_info, line,
433 eol - line, 0, flags, ovector,
434 ARRAY_SIZE(ovector), p->pcre1_jit_stack);
435 } else
436 #endif
438 ret = pcre_exec(p->pcre1_regexp, p->pcre1_extra_info, line,
439 eol - line, 0, flags, ovector,
440 ARRAY_SIZE(ovector));
443 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
444 die("pcre_exec failed with error code %d", ret);
445 if (ret > 0) {
446 ret = 0;
447 match->rm_so = ovector[0];
448 match->rm_eo = ovector[1];
451 return ret;
454 static void free_pcre1_regexp(struct grep_pat *p)
456 pcre_free(p->pcre1_regexp);
457 #ifdef GIT_PCRE1_USE_JIT
458 if (p->pcre1_jit_on) {
459 pcre_free_study(p->pcre1_extra_info);
460 pcre_jit_stack_free(p->pcre1_jit_stack);
461 } else
462 #endif
464 pcre_free(p->pcre1_extra_info);
466 pcre_free((void *)p->pcre1_tables);
468 #else /* !USE_LIBPCRE1 */
469 static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
471 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
474 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
475 regmatch_t *match, int eflags)
477 return 1;
480 static void free_pcre1_regexp(struct grep_pat *p)
483 #endif /* !USE_LIBPCRE1 */
485 #ifdef USE_LIBPCRE2
486 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
488 int error;
489 PCRE2_UCHAR errbuf[256];
490 PCRE2_SIZE erroffset;
491 int options = PCRE2_MULTILINE;
492 const uint8_t *character_tables = NULL;
493 int jitret;
494 int patinforet;
495 size_t jitsizearg;
497 assert(opt->pcre2);
499 p->pcre2_compile_context = NULL;
501 if (opt->ignore_case) {
502 if (has_non_ascii(p->pattern)) {
503 character_tables = pcre2_maketables(NULL);
504 p->pcre2_compile_context = pcre2_compile_context_create(NULL);
505 pcre2_set_character_tables(p->pcre2_compile_context, character_tables);
507 options |= PCRE2_CASELESS;
509 if (is_utf8_locale() && has_non_ascii(p->pattern))
510 options |= PCRE2_UTF;
512 p->pcre2_pattern = pcre2_compile((PCRE2_SPTR)p->pattern,
513 p->patternlen, options, &error, &erroffset,
514 p->pcre2_compile_context);
516 if (p->pcre2_pattern) {
517 p->pcre2_match_data = pcre2_match_data_create_from_pattern(p->pcre2_pattern, NULL);
518 if (!p->pcre2_match_data)
519 die("Couldn't allocate PCRE2 match data");
520 } else {
521 pcre2_get_error_message(error, errbuf, sizeof(errbuf));
522 compile_regexp_failed(p, (const char *)&errbuf);
525 pcre2_config(PCRE2_CONFIG_JIT, &p->pcre2_jit_on);
526 if (p->pcre2_jit_on == 1) {
527 jitret = pcre2_jit_compile(p->pcre2_pattern, PCRE2_JIT_COMPLETE);
528 if (jitret)
529 die("Couldn't JIT the PCRE2 pattern '%s', got '%d'\n", p->pattern, jitret);
532 * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
533 * tells us whether the library itself supports JIT,
534 * but to see whether we're going to be actually using
535 * JIT we need to extract PCRE2_INFO_JITSIZE from the
536 * pattern *after* we do pcre2_jit_compile() above.
538 * This is because if the pattern contains the
539 * (*NO_JIT) verb (see pcre2syntax(3))
540 * pcre2_jit_compile() will exit early with 0. If we
541 * then proceed to call pcre2_jit_match() further down
542 * the line instead of pcre2_match() we'll either
543 * segfault (pre PCRE 10.31) or run into a fatal error
544 * (post PCRE2 10.31)
546 patinforet = pcre2_pattern_info(p->pcre2_pattern, PCRE2_INFO_JITSIZE, &jitsizearg);
547 if (patinforet)
548 BUG("pcre2_pattern_info() failed: %d", patinforet);
549 if (jitsizearg == 0) {
550 p->pcre2_jit_on = 0;
551 return;
554 p->pcre2_jit_stack = pcre2_jit_stack_create(1, 1024 * 1024, NULL);
555 if (!p->pcre2_jit_stack)
556 die("Couldn't allocate PCRE2 JIT stack");
557 p->pcre2_match_context = pcre2_match_context_create(NULL);
558 if (!p->pcre2_match_context)
559 die("Couldn't allocate PCRE2 match context");
560 pcre2_jit_stack_assign(p->pcre2_match_context, NULL, p->pcre2_jit_stack);
561 } else if (p->pcre2_jit_on != 0) {
562 BUG("The pcre2_jit_on variable should be 0 or 1, not %d",
563 p->pcre1_jit_on);
567 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
568 regmatch_t *match, int eflags)
570 int ret, flags = 0;
571 PCRE2_SIZE *ovector;
572 PCRE2_UCHAR errbuf[256];
574 if (eflags & REG_NOTBOL)
575 flags |= PCRE2_NOTBOL;
577 if (p->pcre2_jit_on)
578 ret = pcre2_jit_match(p->pcre2_pattern, (unsigned char *)line,
579 eol - line, 0, flags, p->pcre2_match_data,
580 NULL);
581 else
582 ret = pcre2_match(p->pcre2_pattern, (unsigned char *)line,
583 eol - line, 0, flags, p->pcre2_match_data,
584 NULL);
586 if (ret < 0 && ret != PCRE2_ERROR_NOMATCH) {
587 pcre2_get_error_message(ret, errbuf, sizeof(errbuf));
588 die("%s failed with error code %d: %s",
589 (p->pcre2_jit_on ? "pcre2_jit_match" : "pcre2_match"), ret,
590 errbuf);
592 if (ret > 0) {
593 ovector = pcre2_get_ovector_pointer(p->pcre2_match_data);
594 ret = 0;
595 match->rm_so = (int)ovector[0];
596 match->rm_eo = (int)ovector[1];
599 return ret;
602 static void free_pcre2_pattern(struct grep_pat *p)
604 pcre2_compile_context_free(p->pcre2_compile_context);
605 pcre2_code_free(p->pcre2_pattern);
606 pcre2_match_data_free(p->pcre2_match_data);
607 pcre2_jit_stack_free(p->pcre2_jit_stack);
608 pcre2_match_context_free(p->pcre2_match_context);
610 #else /* !USE_LIBPCRE2 */
611 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
614 * Unreachable until USE_LIBPCRE2 becomes synonymous with
615 * USE_LIBPCRE. See the sibling comment in
616 * grep_set_pattern_type_option().
618 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
621 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
622 regmatch_t *match, int eflags)
624 return 1;
627 static void free_pcre2_pattern(struct grep_pat *p)
630 #endif /* !USE_LIBPCRE2 */
632 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
634 struct strbuf sb = STRBUF_INIT;
635 int err;
636 int regflags = 0;
638 basic_regex_quote_buf(&sb, p->pattern);
639 if (opt->ignore_case)
640 regflags |= REG_ICASE;
641 err = regcomp(&p->regexp, sb.buf, regflags);
642 if (opt->debug)
643 fprintf(stderr, "fixed %s\n", sb.buf);
644 strbuf_release(&sb);
645 if (err) {
646 char errbuf[1024];
647 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
648 compile_regexp_failed(p, errbuf);
652 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
654 int ascii_only;
655 int err;
656 int regflags = REG_NEWLINE;
658 p->word_regexp = opt->word_regexp;
659 p->ignore_case = opt->ignore_case;
660 ascii_only = !has_non_ascii(p->pattern);
663 * Even when -F (fixed) asks us to do a non-regexp search, we
664 * may not be able to correctly case-fold when -i
665 * (ignore-case) is asked (in which case, we'll synthesize a
666 * regexp to match the pattern that matches regexp special
667 * characters literally, while ignoring case differences). On
668 * the other hand, even without -F, if the pattern does not
669 * have any regexp special characters and there is no need for
670 * case-folding search, we can internally turn it into a
671 * simple string match using kws. p->fixed tells us if we
672 * want to use kws.
674 if (opt->fixed ||
675 has_null(p->pattern, p->patternlen) ||
676 is_fixed(p->pattern, p->patternlen))
677 p->fixed = !p->ignore_case || ascii_only;
679 if (p->fixed) {
680 p->kws = kwsalloc(p->ignore_case ? tolower_trans_tbl : NULL);
681 kwsincr(p->kws, p->pattern, p->patternlen);
682 kwsprep(p->kws);
683 return;
684 } else if (opt->fixed) {
686 * We come here when the pattern has the non-ascii
687 * characters we cannot case-fold, and asked to
688 * ignore-case.
690 compile_fixed_regexp(p, opt);
691 return;
694 if (opt->pcre2) {
695 compile_pcre2_pattern(p, opt);
696 return;
699 if (opt->pcre1) {
700 compile_pcre1_regexp(p, opt);
701 return;
704 if (p->ignore_case)
705 regflags |= REG_ICASE;
706 if (opt->extended_regexp_option)
707 regflags |= REG_EXTENDED;
708 err = regcomp(&p->regexp, p->pattern, regflags);
709 if (err) {
710 char errbuf[1024];
711 regerror(err, &p->regexp, errbuf, 1024);
712 compile_regexp_failed(p, errbuf);
716 static struct grep_expr *compile_pattern_or(struct grep_pat **);
717 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
719 struct grep_pat *p;
720 struct grep_expr *x;
722 p = *list;
723 if (!p)
724 return NULL;
725 switch (p->token) {
726 case GREP_PATTERN: /* atom */
727 case GREP_PATTERN_HEAD:
728 case GREP_PATTERN_BODY:
729 x = xcalloc(1, sizeof (struct grep_expr));
730 x->node = GREP_NODE_ATOM;
731 x->u.atom = p;
732 *list = p->next;
733 return x;
734 case GREP_OPEN_PAREN:
735 *list = p->next;
736 x = compile_pattern_or(list);
737 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
738 die("unmatched parenthesis");
739 *list = (*list)->next;
740 return x;
741 default:
742 return NULL;
746 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
748 struct grep_pat *p;
749 struct grep_expr *x;
751 p = *list;
752 if (!p)
753 return NULL;
754 switch (p->token) {
755 case GREP_NOT:
756 if (!p->next)
757 die("--not not followed by pattern expression");
758 *list = p->next;
759 x = xcalloc(1, sizeof (struct grep_expr));
760 x->node = GREP_NODE_NOT;
761 x->u.unary = compile_pattern_not(list);
762 if (!x->u.unary)
763 die("--not followed by non pattern expression");
764 return x;
765 default:
766 return compile_pattern_atom(list);
770 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
772 struct grep_pat *p;
773 struct grep_expr *x, *y, *z;
775 x = compile_pattern_not(list);
776 p = *list;
777 if (p && p->token == GREP_AND) {
778 if (!p->next)
779 die("--and not followed by pattern expression");
780 *list = p->next;
781 y = compile_pattern_and(list);
782 if (!y)
783 die("--and not followed by pattern expression");
784 z = xcalloc(1, sizeof (struct grep_expr));
785 z->node = GREP_NODE_AND;
786 z->u.binary.left = x;
787 z->u.binary.right = y;
788 return z;
790 return x;
793 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
795 struct grep_pat *p;
796 struct grep_expr *x, *y, *z;
798 x = compile_pattern_and(list);
799 p = *list;
800 if (x && p && p->token != GREP_CLOSE_PAREN) {
801 y = compile_pattern_or(list);
802 if (!y)
803 die("not a pattern expression %s", p->pattern);
804 z = xcalloc(1, sizeof (struct grep_expr));
805 z->node = GREP_NODE_OR;
806 z->u.binary.left = x;
807 z->u.binary.right = y;
808 return z;
810 return x;
813 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
815 return compile_pattern_or(list);
818 static void indent(int in)
820 while (in-- > 0)
821 fputc(' ', stderr);
824 static void dump_grep_pat(struct grep_pat *p)
826 switch (p->token) {
827 case GREP_AND: fprintf(stderr, "*and*"); break;
828 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
829 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
830 case GREP_NOT: fprintf(stderr, "*not*"); break;
831 case GREP_OR: fprintf(stderr, "*or*"); break;
833 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
834 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
835 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
838 switch (p->token) {
839 default: break;
840 case GREP_PATTERN_HEAD:
841 fprintf(stderr, "<head %d>", p->field); break;
842 case GREP_PATTERN_BODY:
843 fprintf(stderr, "<body>"); break;
845 switch (p->token) {
846 default: break;
847 case GREP_PATTERN_HEAD:
848 case GREP_PATTERN_BODY:
849 case GREP_PATTERN:
850 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
851 break;
853 fputc('\n', stderr);
856 static void dump_grep_expression_1(struct grep_expr *x, int in)
858 indent(in);
859 switch (x->node) {
860 case GREP_NODE_TRUE:
861 fprintf(stderr, "true\n");
862 break;
863 case GREP_NODE_ATOM:
864 dump_grep_pat(x->u.atom);
865 break;
866 case GREP_NODE_NOT:
867 fprintf(stderr, "(not\n");
868 dump_grep_expression_1(x->u.unary, in+1);
869 indent(in);
870 fprintf(stderr, ")\n");
871 break;
872 case GREP_NODE_AND:
873 fprintf(stderr, "(and\n");
874 dump_grep_expression_1(x->u.binary.left, in+1);
875 dump_grep_expression_1(x->u.binary.right, in+1);
876 indent(in);
877 fprintf(stderr, ")\n");
878 break;
879 case GREP_NODE_OR:
880 fprintf(stderr, "(or\n");
881 dump_grep_expression_1(x->u.binary.left, in+1);
882 dump_grep_expression_1(x->u.binary.right, in+1);
883 indent(in);
884 fprintf(stderr, ")\n");
885 break;
889 static void dump_grep_expression(struct grep_opt *opt)
891 struct grep_expr *x = opt->pattern_expression;
893 if (opt->all_match)
894 fprintf(stderr, "[all-match]\n");
895 dump_grep_expression_1(x, 0);
896 fflush(NULL);
899 static struct grep_expr *grep_true_expr(void)
901 struct grep_expr *z = xcalloc(1, sizeof(*z));
902 z->node = GREP_NODE_TRUE;
903 return z;
906 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
908 struct grep_expr *z = xcalloc(1, sizeof(*z));
909 z->node = GREP_NODE_OR;
910 z->u.binary.left = left;
911 z->u.binary.right = right;
912 return z;
915 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
917 struct grep_pat *p;
918 struct grep_expr *header_expr;
919 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
920 enum grep_header_field fld;
922 if (!opt->header_list)
923 return NULL;
925 for (p = opt->header_list; p; p = p->next) {
926 if (p->token != GREP_PATTERN_HEAD)
927 BUG("a non-header pattern in grep header list.");
928 if (p->field < GREP_HEADER_FIELD_MIN ||
929 GREP_HEADER_FIELD_MAX <= p->field)
930 BUG("unknown header field %d", p->field);
931 compile_regexp(p, opt);
934 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
935 header_group[fld] = NULL;
937 for (p = opt->header_list; p; p = p->next) {
938 struct grep_expr *h;
939 struct grep_pat *pp = p;
941 h = compile_pattern_atom(&pp);
942 if (!h || pp != p->next)
943 BUG("malformed header expr");
944 if (!header_group[p->field]) {
945 header_group[p->field] = h;
946 continue;
948 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
951 header_expr = NULL;
953 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
954 if (!header_group[fld])
955 continue;
956 if (!header_expr)
957 header_expr = grep_true_expr();
958 header_expr = grep_or_expr(header_group[fld], header_expr);
960 return header_expr;
963 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
965 struct grep_expr *z = x;
967 while (x) {
968 assert(x->node == GREP_NODE_OR);
969 if (x->u.binary.right &&
970 x->u.binary.right->node == GREP_NODE_TRUE) {
971 x->u.binary.right = y;
972 break;
974 x = x->u.binary.right;
976 return z;
979 static void compile_grep_patterns_real(struct grep_opt *opt)
981 struct grep_pat *p;
982 struct grep_expr *header_expr = prep_header_patterns(opt);
984 for (p = opt->pattern_list; p; p = p->next) {
985 switch (p->token) {
986 case GREP_PATTERN: /* atom */
987 case GREP_PATTERN_HEAD:
988 case GREP_PATTERN_BODY:
989 compile_regexp(p, opt);
990 break;
991 default:
992 opt->extended = 1;
993 break;
997 if (opt->all_match || header_expr)
998 opt->extended = 1;
999 else if (!opt->extended && !opt->debug)
1000 return;
1002 p = opt->pattern_list;
1003 if (p)
1004 opt->pattern_expression = compile_pattern_expr(&p);
1005 if (p)
1006 die("incomplete pattern expression: %s", p->pattern);
1008 if (!header_expr)
1009 return;
1011 if (!opt->pattern_expression)
1012 opt->pattern_expression = header_expr;
1013 else if (opt->all_match)
1014 opt->pattern_expression = grep_splice_or(header_expr,
1015 opt->pattern_expression);
1016 else
1017 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
1018 header_expr);
1019 opt->all_match = 1;
1022 void compile_grep_patterns(struct grep_opt *opt)
1024 compile_grep_patterns_real(opt);
1025 if (opt->debug)
1026 dump_grep_expression(opt);
1029 static void free_pattern_expr(struct grep_expr *x)
1031 switch (x->node) {
1032 case GREP_NODE_TRUE:
1033 case GREP_NODE_ATOM:
1034 break;
1035 case GREP_NODE_NOT:
1036 free_pattern_expr(x->u.unary);
1037 break;
1038 case GREP_NODE_AND:
1039 case GREP_NODE_OR:
1040 free_pattern_expr(x->u.binary.left);
1041 free_pattern_expr(x->u.binary.right);
1042 break;
1044 free(x);
1047 void free_grep_patterns(struct grep_opt *opt)
1049 struct grep_pat *p, *n;
1051 for (p = opt->pattern_list; p; p = n) {
1052 n = p->next;
1053 switch (p->token) {
1054 case GREP_PATTERN: /* atom */
1055 case GREP_PATTERN_HEAD:
1056 case GREP_PATTERN_BODY:
1057 if (p->kws)
1058 kwsfree(p->kws);
1059 else if (p->pcre1_regexp)
1060 free_pcre1_regexp(p);
1061 else if (p->pcre2_pattern)
1062 free_pcre2_pattern(p);
1063 else
1064 regfree(&p->regexp);
1065 free(p->pattern);
1066 break;
1067 default:
1068 break;
1070 free(p);
1073 if (!opt->extended)
1074 return;
1075 free_pattern_expr(opt->pattern_expression);
1078 static char *end_of_line(char *cp, unsigned long *left)
1080 unsigned long l = *left;
1081 while (l && *cp != '\n') {
1082 l--;
1083 cp++;
1085 *left = l;
1086 return cp;
1089 static int word_char(char ch)
1091 return isalnum(ch) || ch == '_';
1094 static void output_color(struct grep_opt *opt, const void *data, size_t size,
1095 const char *color)
1097 if (want_color(opt->color) && color && color[0]) {
1098 opt->output(opt, color, strlen(color));
1099 opt->output(opt, data, size);
1100 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
1101 } else
1102 opt->output(opt, data, size);
1105 static void output_sep(struct grep_opt *opt, char sign)
1107 if (opt->null_following_name)
1108 opt->output(opt, "\0", 1);
1109 else
1110 output_color(opt, &sign, 1, opt->color_sep);
1113 static void show_name(struct grep_opt *opt, const char *name)
1115 output_color(opt, name, strlen(name), opt->color_filename);
1116 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
1119 static int fixmatch(struct grep_pat *p, char *line, char *eol,
1120 regmatch_t *match)
1122 struct kwsmatch kwsm;
1123 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
1124 if (offset == -1) {
1125 match->rm_so = match->rm_eo = -1;
1126 return REG_NOMATCH;
1127 } else {
1128 match->rm_so = offset;
1129 match->rm_eo = match->rm_so + kwsm.size[0];
1130 return 0;
1134 static int patmatch(struct grep_pat *p, char *line, char *eol,
1135 regmatch_t *match, int eflags)
1137 int hit;
1139 if (p->fixed)
1140 hit = !fixmatch(p, line, eol, match);
1141 else if (p->pcre1_regexp)
1142 hit = !pcre1match(p, line, eol, match, eflags);
1143 else if (p->pcre2_pattern)
1144 hit = !pcre2match(p, line, eol, match, eflags);
1145 else
1146 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
1147 eflags);
1149 return hit;
1152 static int strip_timestamp(char *bol, char **eol_p)
1154 char *eol = *eol_p;
1155 int ch;
1157 while (bol < --eol) {
1158 if (*eol != '>')
1159 continue;
1160 *eol_p = ++eol;
1161 ch = *eol;
1162 *eol = '\0';
1163 return ch;
1165 return 0;
1168 static struct {
1169 const char *field;
1170 size_t len;
1171 } header_field[] = {
1172 { "author ", 7 },
1173 { "committer ", 10 },
1174 { "reflog ", 7 },
1177 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
1178 enum grep_context ctx,
1179 regmatch_t *pmatch, int eflags)
1181 int hit = 0;
1182 int saved_ch = 0;
1183 const char *start = bol;
1185 if ((p->token != GREP_PATTERN) &&
1186 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
1187 return 0;
1189 if (p->token == GREP_PATTERN_HEAD) {
1190 const char *field;
1191 size_t len;
1192 assert(p->field < ARRAY_SIZE(header_field));
1193 field = header_field[p->field].field;
1194 len = header_field[p->field].len;
1195 if (strncmp(bol, field, len))
1196 return 0;
1197 bol += len;
1198 switch (p->field) {
1199 case GREP_HEADER_AUTHOR:
1200 case GREP_HEADER_COMMITTER:
1201 saved_ch = strip_timestamp(bol, &eol);
1202 break;
1203 default:
1204 break;
1208 again:
1209 hit = patmatch(p, bol, eol, pmatch, eflags);
1211 if (hit && p->word_regexp) {
1212 if ((pmatch[0].rm_so < 0) ||
1213 (eol - bol) < pmatch[0].rm_so ||
1214 (pmatch[0].rm_eo < 0) ||
1215 (eol - bol) < pmatch[0].rm_eo)
1216 die("regexp returned nonsense");
1218 /* Match beginning must be either beginning of the
1219 * line, or at word boundary (i.e. the last char must
1220 * not be a word char). Similarly, match end must be
1221 * either end of the line, or at word boundary
1222 * (i.e. the next char must not be a word char).
1224 if ( ((pmatch[0].rm_so == 0) ||
1225 !word_char(bol[pmatch[0].rm_so-1])) &&
1226 ((pmatch[0].rm_eo == (eol-bol)) ||
1227 !word_char(bol[pmatch[0].rm_eo])) )
1229 else
1230 hit = 0;
1232 /* Words consist of at least one character. */
1233 if (pmatch->rm_so == pmatch->rm_eo)
1234 hit = 0;
1236 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1237 /* There could be more than one match on the
1238 * line, and the first match might not be
1239 * strict word match. But later ones could be!
1240 * Forward to the next possible start, i.e. the
1241 * next position following a non-word char.
1243 bol = pmatch[0].rm_so + bol + 1;
1244 while (word_char(bol[-1]) && bol < eol)
1245 bol++;
1246 eflags |= REG_NOTBOL;
1247 if (bol < eol)
1248 goto again;
1251 if (p->token == GREP_PATTERN_HEAD && saved_ch)
1252 *eol = saved_ch;
1253 if (hit) {
1254 pmatch[0].rm_so += bol - start;
1255 pmatch[0].rm_eo += bol - start;
1257 return hit;
1260 static int match_expr_eval(struct grep_opt *opt, struct grep_expr *x, char *bol,
1261 char *eol, enum grep_context ctx, ssize_t *col,
1262 ssize_t *icol, int collect_hits)
1264 int h = 0;
1266 if (!x)
1267 die("Not a valid grep expression");
1268 switch (x->node) {
1269 case GREP_NODE_TRUE:
1270 h = 1;
1271 break;
1272 case GREP_NODE_ATOM:
1274 regmatch_t tmp;
1275 h = match_one_pattern(x->u.atom, bol, eol, ctx,
1276 &tmp, 0);
1277 if (h && (*col < 0 || tmp.rm_so < *col))
1278 *col = tmp.rm_so;
1280 break;
1281 case GREP_NODE_NOT:
1283 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1285 h = !match_expr_eval(opt, x->u.unary, bol, eol, ctx, icol, col,
1287 break;
1288 case GREP_NODE_AND:
1289 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1290 icol, 0);
1291 if (h || opt->columnnum) {
1293 * Don't short-circuit AND when given --column, since a
1294 * NOT earlier in the tree may turn this into an OR. In
1295 * this case, see the below comment.
1297 h &= match_expr_eval(opt, x->u.binary.right, bol, eol,
1298 ctx, col, icol, 0);
1300 break;
1301 case GREP_NODE_OR:
1302 if (!(collect_hits || opt->columnnum)) {
1304 * Don't short-circuit OR when given --column (or
1305 * collecting hits) to ensure we don't skip a later
1306 * child that would produce an earlier match.
1308 return (match_expr_eval(opt, x->u.binary.left, bol, eol,
1309 ctx, col, icol, 0) ||
1310 match_expr_eval(opt, x->u.binary.right, bol,
1311 eol, ctx, col, icol, 0));
1313 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1314 icol, 0);
1315 if (collect_hits)
1316 x->u.binary.left->hit |= h;
1317 h |= match_expr_eval(opt, x->u.binary.right, bol, eol, ctx, col,
1318 icol, collect_hits);
1319 break;
1320 default:
1321 die("Unexpected node type (internal error) %d", x->node);
1323 if (collect_hits)
1324 x->hit |= h;
1325 return h;
1328 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1329 enum grep_context ctx, ssize_t *col,
1330 ssize_t *icol, int collect_hits)
1332 struct grep_expr *x = opt->pattern_expression;
1333 return match_expr_eval(opt, x, bol, eol, ctx, col, icol, collect_hits);
1336 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1337 ssize_t *col, ssize_t *icol,
1338 enum grep_context ctx, int collect_hits)
1340 struct grep_pat *p;
1341 int hit = 0;
1343 if (opt->extended)
1344 return match_expr(opt, bol, eol, ctx, col, icol,
1345 collect_hits);
1347 /* we do not call with collect_hits without being extended */
1348 for (p = opt->pattern_list; p; p = p->next) {
1349 regmatch_t tmp;
1350 if (match_one_pattern(p, bol, eol, ctx, &tmp, 0)) {
1351 hit |= 1;
1352 if (!opt->columnnum) {
1354 * Without --column, any single match on a line
1355 * is enough to know that it needs to be
1356 * printed. With --column, scan _all_ patterns
1357 * to find the earliest.
1359 break;
1361 if (*col < 0 || tmp.rm_so < *col)
1362 *col = tmp.rm_so;
1365 return hit;
1368 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1369 enum grep_context ctx,
1370 regmatch_t *pmatch, int eflags)
1372 regmatch_t match;
1374 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1375 return 0;
1376 if (match.rm_so < 0 || match.rm_eo < 0)
1377 return 0;
1378 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1379 if (match.rm_so > pmatch->rm_so)
1380 return 1;
1381 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1382 return 1;
1384 pmatch->rm_so = match.rm_so;
1385 pmatch->rm_eo = match.rm_eo;
1386 return 1;
1389 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1390 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1392 struct grep_pat *p;
1393 int hit = 0;
1395 pmatch->rm_so = pmatch->rm_eo = -1;
1396 if (bol < eol) {
1397 for (p = opt->pattern_list; p; p = p->next) {
1398 switch (p->token) {
1399 case GREP_PATTERN: /* atom */
1400 case GREP_PATTERN_HEAD:
1401 case GREP_PATTERN_BODY:
1402 hit |= match_next_pattern(p, bol, eol, ctx,
1403 pmatch, eflags);
1404 break;
1405 default:
1406 break;
1410 return hit;
1413 static void show_line_header(struct grep_opt *opt, const char *name,
1414 unsigned lno, ssize_t cno, char sign)
1416 if (opt->heading && opt->last_shown == 0) {
1417 output_color(opt, name, strlen(name), opt->color_filename);
1418 opt->output(opt, "\n", 1);
1420 opt->last_shown = lno;
1422 if (!opt->heading && opt->pathname) {
1423 output_color(opt, name, strlen(name), opt->color_filename);
1424 output_sep(opt, sign);
1426 if (opt->linenum) {
1427 char buf[32];
1428 xsnprintf(buf, sizeof(buf), "%d", lno);
1429 output_color(opt, buf, strlen(buf), opt->color_lineno);
1430 output_sep(opt, sign);
1433 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1434 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1435 * being called with a context line.
1437 if (opt->columnnum && cno) {
1438 char buf[32];
1439 xsnprintf(buf, sizeof(buf), "%"PRIuMAX, (uintmax_t)cno);
1440 output_color(opt, buf, strlen(buf), opt->color_columnno);
1441 output_sep(opt, sign);
1445 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1446 const char *name, unsigned lno, ssize_t cno, char sign)
1448 int rest = eol - bol;
1449 const char *match_color, *line_color = NULL;
1451 if (opt->file_break && opt->last_shown == 0) {
1452 if (opt->show_hunk_mark)
1453 opt->output(opt, "\n", 1);
1454 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1455 if (opt->last_shown == 0) {
1456 if (opt->show_hunk_mark) {
1457 output_color(opt, "--", 2, opt->color_sep);
1458 opt->output(opt, "\n", 1);
1460 } else if (lno > opt->last_shown + 1) {
1461 output_color(opt, "--", 2, opt->color_sep);
1462 opt->output(opt, "\n", 1);
1465 show_line_header(opt, name, lno, cno, sign);
1466 if (opt->color) {
1467 regmatch_t match;
1468 enum grep_context ctx = GREP_CONTEXT_BODY;
1469 int ch = *eol;
1470 int eflags = 0;
1472 if (sign == ':')
1473 match_color = opt->color_match_selected;
1474 else
1475 match_color = opt->color_match_context;
1476 if (sign == ':')
1477 line_color = opt->color_selected;
1478 else if (sign == '-')
1479 line_color = opt->color_context;
1480 else if (sign == '=')
1481 line_color = opt->color_function;
1482 *eol = '\0';
1483 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1484 if (match.rm_so == match.rm_eo)
1485 break;
1487 output_color(opt, bol, match.rm_so, line_color);
1488 output_color(opt, bol + match.rm_so,
1489 match.rm_eo - match.rm_so, match_color);
1490 bol += match.rm_eo;
1491 rest -= match.rm_eo;
1492 eflags = REG_NOTBOL;
1494 *eol = ch;
1496 output_color(opt, bol, rest, line_color);
1497 opt->output(opt, "\n", 1);
1500 #ifndef NO_PTHREADS
1501 int grep_use_locks;
1504 * This lock protects access to the gitattributes machinery, which is
1505 * not thread-safe.
1507 pthread_mutex_t grep_attr_mutex;
1509 static inline void grep_attr_lock(void)
1511 if (grep_use_locks)
1512 pthread_mutex_lock(&grep_attr_mutex);
1515 static inline void grep_attr_unlock(void)
1517 if (grep_use_locks)
1518 pthread_mutex_unlock(&grep_attr_mutex);
1522 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1524 pthread_mutex_t grep_read_mutex;
1526 #else
1527 #define grep_attr_lock()
1528 #define grep_attr_unlock()
1529 #endif
1531 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1533 xdemitconf_t *xecfg = opt->priv;
1534 if (xecfg && !xecfg->find_func) {
1535 grep_source_load_driver(gs);
1536 if (gs->driver->funcname.pattern) {
1537 const struct userdiff_funcname *pe = &gs->driver->funcname;
1538 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1539 } else {
1540 xecfg = opt->priv = NULL;
1544 if (xecfg) {
1545 char buf[1];
1546 return xecfg->find_func(bol, eol - bol, buf, 1,
1547 xecfg->find_func_priv) >= 0;
1550 if (bol == eol)
1551 return 0;
1552 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1553 return 1;
1554 return 0;
1557 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1558 char *bol, unsigned lno)
1560 while (bol > gs->buf) {
1561 char *eol = --bol;
1563 while (bol > gs->buf && bol[-1] != '\n')
1564 bol--;
1565 lno--;
1567 if (lno <= opt->last_shown)
1568 break;
1570 if (match_funcname(opt, gs, bol, eol)) {
1571 show_line(opt, bol, eol, gs->name, lno, 0, '=');
1572 break;
1577 static int is_empty_line(const char *bol, const char *eol);
1579 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1580 char *bol, char *end, unsigned lno)
1582 unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
1583 int funcname_needed = !!opt->funcname, comment_needed = 0;
1585 if (opt->pre_context < lno)
1586 from = lno - opt->pre_context;
1587 if (from <= opt->last_shown)
1588 from = opt->last_shown + 1;
1589 orig_from = from;
1590 if (opt->funcbody) {
1591 if (match_funcname(opt, gs, bol, end))
1592 comment_needed = 1;
1593 else
1594 funcname_needed = 1;
1595 from = opt->last_shown + 1;
1598 /* Rewind. */
1599 while (bol > gs->buf && cur > from) {
1600 char *next_bol = bol;
1601 char *eol = --bol;
1603 while (bol > gs->buf && bol[-1] != '\n')
1604 bol--;
1605 cur--;
1606 if (comment_needed && (is_empty_line(bol, eol) ||
1607 match_funcname(opt, gs, bol, eol))) {
1608 comment_needed = 0;
1609 from = orig_from;
1610 if (cur < from) {
1611 cur++;
1612 bol = next_bol;
1613 break;
1616 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1617 funcname_lno = cur;
1618 funcname_needed = 0;
1619 if (opt->funcbody)
1620 comment_needed = 1;
1621 else
1622 from = orig_from;
1626 /* We need to look even further back to find a function signature. */
1627 if (opt->funcname && funcname_needed)
1628 show_funcname_line(opt, gs, bol, cur);
1630 /* Back forward. */
1631 while (cur < lno) {
1632 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1634 while (*eol != '\n')
1635 eol++;
1636 show_line(opt, bol, eol, gs->name, cur, 0, sign);
1637 bol = eol + 1;
1638 cur++;
1642 static int should_lookahead(struct grep_opt *opt)
1644 struct grep_pat *p;
1646 if (opt->extended)
1647 return 0; /* punt for too complex stuff */
1648 if (opt->invert)
1649 return 0;
1650 for (p = opt->pattern_list; p; p = p->next) {
1651 if (p->token != GREP_PATTERN)
1652 return 0; /* punt for "header only" and stuff */
1654 return 1;
1657 static int look_ahead(struct grep_opt *opt,
1658 unsigned long *left_p,
1659 unsigned *lno_p,
1660 char **bol_p)
1662 unsigned lno = *lno_p;
1663 char *bol = *bol_p;
1664 struct grep_pat *p;
1665 char *sp, *last_bol;
1666 regoff_t earliest = -1;
1668 for (p = opt->pattern_list; p; p = p->next) {
1669 int hit;
1670 regmatch_t m;
1672 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1673 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1674 continue;
1675 if (earliest < 0 || m.rm_so < earliest)
1676 earliest = m.rm_so;
1679 if (earliest < 0) {
1680 *bol_p = bol + *left_p;
1681 *left_p = 0;
1682 return 1;
1684 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1685 ; /* find the beginning of the line */
1686 last_bol = sp;
1688 for (sp = bol; sp < last_bol; sp++) {
1689 if (*sp == '\n')
1690 lno++;
1692 *left_p -= last_bol - bol;
1693 *bol_p = last_bol;
1694 *lno_p = lno;
1695 return 0;
1698 static int fill_textconv_grep(struct userdiff_driver *driver,
1699 struct grep_source *gs)
1701 struct diff_filespec *df;
1702 char *buf;
1703 size_t size;
1705 if (!driver || !driver->textconv)
1706 return grep_source_load(gs);
1709 * The textconv interface is intimately tied to diff_filespecs, so we
1710 * have to pretend to be one. If we could unify the grep_source
1711 * and diff_filespec structs, this mess could just go away.
1713 df = alloc_filespec(gs->path);
1714 switch (gs->type) {
1715 case GREP_SOURCE_OID:
1716 fill_filespec(df, gs->identifier, 1, 0100644);
1717 break;
1718 case GREP_SOURCE_FILE:
1719 fill_filespec(df, &null_oid, 0, 0100644);
1720 break;
1721 default:
1722 BUG("attempt to textconv something without a path?");
1726 * fill_textconv is not remotely thread-safe; it may load objects
1727 * behind the scenes, and it modifies the global diff tempfile
1728 * structure.
1730 grep_read_lock();
1731 size = fill_textconv(driver, df, &buf);
1732 grep_read_unlock();
1733 free_filespec(df);
1736 * The normal fill_textconv usage by the diff machinery would just keep
1737 * the textconv'd buf separate from the diff_filespec. But much of the
1738 * grep code passes around a grep_source and assumes that its "buf"
1739 * pointer is the beginning of the thing we are searching. So let's
1740 * install our textconv'd version into the grep_source, taking care not
1741 * to leak any existing buffer.
1743 grep_source_clear_data(gs);
1744 gs->buf = buf;
1745 gs->size = size;
1747 return 0;
1750 static int is_empty_line(const char *bol, const char *eol)
1752 while (bol < eol && isspace(*bol))
1753 bol++;
1754 return bol == eol;
1757 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1759 char *bol;
1760 char *peek_bol = NULL;
1761 unsigned long left;
1762 unsigned lno = 1;
1763 unsigned last_hit = 0;
1764 int binary_match_only = 0;
1765 unsigned count = 0;
1766 int try_lookahead = 0;
1767 int show_function = 0;
1768 struct userdiff_driver *textconv = NULL;
1769 enum grep_context ctx = GREP_CONTEXT_HEAD;
1770 xdemitconf_t xecfg;
1772 if (!opt->output)
1773 opt->output = std_output;
1775 if (opt->pre_context || opt->post_context || opt->file_break ||
1776 opt->funcbody) {
1777 /* Show hunk marks, except for the first file. */
1778 if (opt->last_shown)
1779 opt->show_hunk_mark = 1;
1781 * If we're using threads then we can't easily identify
1782 * the first file. Always put hunk marks in that case
1783 * and skip the very first one later in work_done().
1785 if (opt->output != std_output)
1786 opt->show_hunk_mark = 1;
1788 opt->last_shown = 0;
1790 if (opt->allow_textconv) {
1791 grep_source_load_driver(gs);
1793 * We might set up the shared textconv cache data here, which
1794 * is not thread-safe.
1796 grep_attr_lock();
1797 textconv = userdiff_get_textconv(gs->driver);
1798 grep_attr_unlock();
1802 * We know the result of a textconv is text, so we only have to care
1803 * about binary handling if we are not using it.
1805 if (!textconv) {
1806 switch (opt->binary) {
1807 case GREP_BINARY_DEFAULT:
1808 if (grep_source_is_binary(gs))
1809 binary_match_only = 1;
1810 break;
1811 case GREP_BINARY_NOMATCH:
1812 if (grep_source_is_binary(gs))
1813 return 0; /* Assume unmatch */
1814 break;
1815 case GREP_BINARY_TEXT:
1816 break;
1817 default:
1818 BUG("unknown binary handling mode");
1822 memset(&xecfg, 0, sizeof(xecfg));
1823 opt->priv = &xecfg;
1825 try_lookahead = should_lookahead(opt);
1827 if (fill_textconv_grep(textconv, gs) < 0)
1828 return 0;
1830 bol = gs->buf;
1831 left = gs->size;
1832 while (left) {
1833 char *eol, ch;
1834 int hit;
1835 ssize_t cno;
1836 ssize_t col = -1, icol = -1;
1839 * look_ahead() skips quickly to the line that possibly
1840 * has the next hit; don't call it if we need to do
1841 * something more than just skipping the current line
1842 * in response to an unmatch for the current line. E.g.
1843 * inside a post-context window, we will show the current
1844 * line as a context around the previous hit when it
1845 * doesn't hit.
1847 if (try_lookahead
1848 && !(last_hit
1849 && (show_function ||
1850 lno <= last_hit + opt->post_context))
1851 && look_ahead(opt, &left, &lno, &bol))
1852 break;
1853 eol = end_of_line(bol, &left);
1854 ch = *eol;
1855 *eol = 0;
1857 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1858 ctx = GREP_CONTEXT_BODY;
1860 hit = match_line(opt, bol, eol, &col, &icol, ctx, collect_hits);
1861 *eol = ch;
1863 if (collect_hits)
1864 goto next_line;
1866 /* "grep -v -e foo -e bla" should list lines
1867 * that do not have either, so inversion should
1868 * be done outside.
1870 if (opt->invert)
1871 hit = !hit;
1872 if (opt->unmatch_name_only) {
1873 if (hit)
1874 return 0;
1875 goto next_line;
1877 if (hit) {
1878 count++;
1879 if (opt->status_only)
1880 return 1;
1881 if (opt->name_only) {
1882 show_name(opt, gs->name);
1883 return 1;
1885 if (opt->count)
1886 goto next_line;
1887 if (binary_match_only) {
1888 opt->output(opt, "Binary file ", 12);
1889 output_color(opt, gs->name, strlen(gs->name),
1890 opt->color_filename);
1891 opt->output(opt, " matches\n", 9);
1892 return 1;
1894 /* Hit at this line. If we haven't shown the
1895 * pre-context lines, we would need to show them.
1897 if (opt->pre_context || opt->funcbody)
1898 show_pre_context(opt, gs, bol, eol, lno);
1899 else if (opt->funcname)
1900 show_funcname_line(opt, gs, bol, lno);
1901 cno = opt->invert ? icol : col;
1902 if (cno < 0) {
1904 * A negative cno indicates that there was no
1905 * match on the line. We are thus inverted and
1906 * being asked to show all lines that _don't_
1907 * match a given expression. Therefore, set cno
1908 * to 0 to suggest the whole line matches.
1910 cno = 0;
1912 show_line(opt, bol, eol, gs->name, lno, cno + 1, ':');
1913 last_hit = lno;
1914 if (opt->funcbody)
1915 show_function = 1;
1916 goto next_line;
1918 if (show_function && (!peek_bol || peek_bol < bol)) {
1919 unsigned long peek_left = left;
1920 char *peek_eol = eol;
1923 * Trailing empty lines are not interesting.
1924 * Peek past them to see if they belong to the
1925 * body of the current function.
1927 peek_bol = bol;
1928 while (is_empty_line(peek_bol, peek_eol)) {
1929 peek_bol = peek_eol + 1;
1930 peek_eol = end_of_line(peek_bol, &peek_left);
1933 if (match_funcname(opt, gs, peek_bol, peek_eol))
1934 show_function = 0;
1936 if (show_function ||
1937 (last_hit && lno <= last_hit + opt->post_context)) {
1938 /* If the last hit is within the post context,
1939 * we need to show this line.
1941 show_line(opt, bol, eol, gs->name, lno, col + 1, '-');
1944 next_line:
1945 bol = eol + 1;
1946 if (!left)
1947 break;
1948 left--;
1949 lno++;
1952 if (collect_hits)
1953 return 0;
1955 if (opt->status_only)
1956 return opt->unmatch_name_only;
1957 if (opt->unmatch_name_only) {
1958 /* We did not see any hit, so we want to show this */
1959 show_name(opt, gs->name);
1960 return 1;
1963 xdiff_clear_find_func(&xecfg);
1964 opt->priv = NULL;
1966 /* NEEDSWORK:
1967 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1968 * which feels mostly useless but sometimes useful. Maybe
1969 * make it another option? For now suppress them.
1971 if (opt->count && count) {
1972 char buf[32];
1973 if (opt->pathname) {
1974 output_color(opt, gs->name, strlen(gs->name),
1975 opt->color_filename);
1976 output_sep(opt, ':');
1978 xsnprintf(buf, sizeof(buf), "%u\n", count);
1979 opt->output(opt, buf, strlen(buf));
1980 return 1;
1982 return !!last_hit;
1985 static void clr_hit_marker(struct grep_expr *x)
1987 /* All-hit markers are meaningful only at the very top level
1988 * OR node.
1990 while (1) {
1991 x->hit = 0;
1992 if (x->node != GREP_NODE_OR)
1993 return;
1994 x->u.binary.left->hit = 0;
1995 x = x->u.binary.right;
1999 static int chk_hit_marker(struct grep_expr *x)
2001 /* Top level nodes have hit markers. See if they all are hits */
2002 while (1) {
2003 if (x->node != GREP_NODE_OR)
2004 return x->hit;
2005 if (!x->u.binary.left->hit)
2006 return 0;
2007 x = x->u.binary.right;
2011 int grep_source(struct grep_opt *opt, struct grep_source *gs)
2014 * we do not have to do the two-pass grep when we do not check
2015 * buffer-wide "all-match".
2017 if (!opt->all_match)
2018 return grep_source_1(opt, gs, 0);
2020 /* Otherwise the toplevel "or" terms hit a bit differently.
2021 * We first clear hit markers from them.
2023 clr_hit_marker(opt->pattern_expression);
2024 grep_source_1(opt, gs, 1);
2026 if (!chk_hit_marker(opt->pattern_expression))
2027 return 0;
2029 return grep_source_1(opt, gs, 0);
2032 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
2034 struct grep_source gs;
2035 int r;
2037 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
2038 gs.buf = buf;
2039 gs.size = size;
2041 r = grep_source(opt, &gs);
2043 grep_source_clear(&gs);
2044 return r;
2047 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
2048 const char *name, const char *path,
2049 const void *identifier)
2051 gs->type = type;
2052 gs->name = xstrdup_or_null(name);
2053 gs->path = xstrdup_or_null(path);
2054 gs->buf = NULL;
2055 gs->size = 0;
2056 gs->driver = NULL;
2058 switch (type) {
2059 case GREP_SOURCE_FILE:
2060 gs->identifier = xstrdup(identifier);
2061 break;
2062 case GREP_SOURCE_OID:
2063 gs->identifier = oiddup(identifier);
2064 break;
2065 case GREP_SOURCE_BUF:
2066 gs->identifier = NULL;
2067 break;
2071 void grep_source_clear(struct grep_source *gs)
2073 FREE_AND_NULL(gs->name);
2074 FREE_AND_NULL(gs->path);
2075 FREE_AND_NULL(gs->identifier);
2076 grep_source_clear_data(gs);
2079 void grep_source_clear_data(struct grep_source *gs)
2081 switch (gs->type) {
2082 case GREP_SOURCE_FILE:
2083 case GREP_SOURCE_OID:
2084 FREE_AND_NULL(gs->buf);
2085 gs->size = 0;
2086 break;
2087 case GREP_SOURCE_BUF:
2088 /* leave user-provided buf intact */
2089 break;
2093 static int grep_source_load_oid(struct grep_source *gs)
2095 enum object_type type;
2097 grep_read_lock();
2098 gs->buf = read_object_file(gs->identifier, &type, &gs->size);
2099 grep_read_unlock();
2101 if (!gs->buf)
2102 return error(_("'%s': unable to read %s"),
2103 gs->name,
2104 oid_to_hex(gs->identifier));
2105 return 0;
2108 static int grep_source_load_file(struct grep_source *gs)
2110 const char *filename = gs->identifier;
2111 struct stat st;
2112 char *data;
2113 size_t size;
2114 int i;
2116 if (lstat(filename, &st) < 0) {
2117 err_ret:
2118 if (errno != ENOENT)
2119 error_errno(_("failed to stat '%s'"), filename);
2120 return -1;
2122 if (!S_ISREG(st.st_mode))
2123 return -1;
2124 size = xsize_t(st.st_size);
2125 i = open(filename, O_RDONLY);
2126 if (i < 0)
2127 goto err_ret;
2128 data = xmallocz(size);
2129 if (st.st_size != read_in_full(i, data, size)) {
2130 error_errno(_("'%s': short read"), filename);
2131 close(i);
2132 free(data);
2133 return -1;
2135 close(i);
2137 gs->buf = data;
2138 gs->size = size;
2139 return 0;
2142 static int grep_source_load(struct grep_source *gs)
2144 if (gs->buf)
2145 return 0;
2147 switch (gs->type) {
2148 case GREP_SOURCE_FILE:
2149 return grep_source_load_file(gs);
2150 case GREP_SOURCE_OID:
2151 return grep_source_load_oid(gs);
2152 case GREP_SOURCE_BUF:
2153 return gs->buf ? 0 : -1;
2155 BUG("invalid grep_source type to load");
2158 void grep_source_load_driver(struct grep_source *gs)
2160 if (gs->driver)
2161 return;
2163 grep_attr_lock();
2164 if (gs->path)
2165 gs->driver = userdiff_find_by_path(gs->path);
2166 if (!gs->driver)
2167 gs->driver = userdiff_find_by_name("default");
2168 grep_attr_unlock();
2171 static int grep_source_is_binary(struct grep_source *gs)
2173 grep_source_load_driver(gs);
2174 if (gs->driver->binary != -1)
2175 return gs->driver->binary;
2177 if (!grep_source_load(gs))
2178 return buffer_is_binary(gs->buf, gs->size);
2180 return 0;