Merge branch 'jt/connectivity-check-after-unshallow'
[alt-git.git] / grep.c
blob2b26cee08d559ceba6dd5a83ae90aaa0155ebca8
1 #include "cache.h"
2 #include "config.h"
3 #include "grep.h"
4 #include "object-store.h"
5 #include "userdiff.h"
6 #include "xdiff-interface.h"
7 #include "diff.h"
8 #include "diffcore.h"
9 #include "commit.h"
10 #include "quote.h"
11 #include "help.h"
13 static int grep_source_load(struct grep_source *gs);
14 static int grep_source_is_binary(struct grep_source *gs);
16 static struct grep_opt grep_defaults;
18 static const char *color_grep_slots[] = {
19 [GREP_COLOR_CONTEXT] = "context",
20 [GREP_COLOR_FILENAME] = "filename",
21 [GREP_COLOR_FUNCTION] = "function",
22 [GREP_COLOR_LINENO] = "lineNumber",
23 [GREP_COLOR_COLUMNNO] = "column",
24 [GREP_COLOR_MATCH_CONTEXT] = "matchContext",
25 [GREP_COLOR_MATCH_SELECTED] = "matchSelected",
26 [GREP_COLOR_SELECTED] = "selected",
27 [GREP_COLOR_SEP] = "separator",
30 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
32 fwrite(buf, size, 1, stdout);
35 static void color_set(char *dst, const char *color_bytes)
37 xsnprintf(dst, COLOR_MAXLEN, "%s", color_bytes);
41 * Initialize the grep_defaults template with hardcoded defaults.
42 * We could let the compiler do this, but without C99 initializers
43 * the code gets unwieldy and unreadable, so...
45 void init_grep_defaults(void)
47 struct grep_opt *opt = &grep_defaults;
48 static int run_once;
50 if (run_once)
51 return;
52 run_once++;
54 memset(opt, 0, sizeof(*opt));
55 opt->relative = 1;
56 opt->pathname = 1;
57 opt->max_depth = -1;
58 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
59 color_set(opt->colors[GREP_COLOR_CONTEXT], "");
60 color_set(opt->colors[GREP_COLOR_FILENAME], "");
61 color_set(opt->colors[GREP_COLOR_FUNCTION], "");
62 color_set(opt->colors[GREP_COLOR_LINENO], "");
63 color_set(opt->colors[GREP_COLOR_COLUMNNO], "");
64 color_set(opt->colors[GREP_COLOR_MATCH_CONTEXT], GIT_COLOR_BOLD_RED);
65 color_set(opt->colors[GREP_COLOR_MATCH_SELECTED], GIT_COLOR_BOLD_RED);
66 color_set(opt->colors[GREP_COLOR_SELECTED], "");
67 color_set(opt->colors[GREP_COLOR_SEP], GIT_COLOR_CYAN);
68 opt->only_matching = 0;
69 opt->color = -1;
70 opt->output = std_output;
73 static int parse_pattern_type_arg(const char *opt, const char *arg)
75 if (!strcmp(arg, "default"))
76 return GREP_PATTERN_TYPE_UNSPECIFIED;
77 else if (!strcmp(arg, "basic"))
78 return GREP_PATTERN_TYPE_BRE;
79 else if (!strcmp(arg, "extended"))
80 return GREP_PATTERN_TYPE_ERE;
81 else if (!strcmp(arg, "fixed"))
82 return GREP_PATTERN_TYPE_FIXED;
83 else if (!strcmp(arg, "perl"))
84 return GREP_PATTERN_TYPE_PCRE;
85 die("bad %s argument: %s", opt, arg);
88 define_list_config_array_extra(color_grep_slots, {"match"});
91 * Read the configuration file once and store it in
92 * the grep_defaults template.
94 int grep_config(const char *var, const char *value, void *cb)
96 struct grep_opt *opt = &grep_defaults;
97 const char *slot;
99 if (userdiff_config(var, value) < 0)
100 return -1;
102 if (!strcmp(var, "grep.extendedregexp")) {
103 opt->extended_regexp_option = git_config_bool(var, value);
104 return 0;
107 if (!strcmp(var, "grep.patterntype")) {
108 opt->pattern_type_option = parse_pattern_type_arg(var, value);
109 return 0;
112 if (!strcmp(var, "grep.linenumber")) {
113 opt->linenum = git_config_bool(var, value);
114 return 0;
116 if (!strcmp(var, "grep.column")) {
117 opt->columnnum = git_config_bool(var, value);
118 return 0;
121 if (!strcmp(var, "grep.fullname")) {
122 opt->relative = !git_config_bool(var, value);
123 return 0;
126 if (!strcmp(var, "color.grep"))
127 opt->color = git_config_colorbool(var, value);
128 if (!strcmp(var, "color.grep.match")) {
129 if (grep_config("color.grep.matchcontext", value, cb) < 0)
130 return -1;
131 if (grep_config("color.grep.matchselected", value, cb) < 0)
132 return -1;
133 } else if (skip_prefix(var, "color.grep.", &slot)) {
134 int i = LOOKUP_CONFIG(color_grep_slots, slot);
135 char *color;
137 if (i < 0)
138 return -1;
139 color = opt->colors[i];
140 if (!value)
141 return config_error_nonbool(var);
142 return color_parse(value, color);
144 return 0;
148 * Initialize one instance of grep_opt and copy the
149 * default values from the template we read the configuration
150 * information in an earlier call to git_config(grep_config).
152 void grep_init(struct grep_opt *opt, const char *prefix)
154 struct grep_opt *def = &grep_defaults;
155 int i;
157 memset(opt, 0, sizeof(*opt));
158 opt->prefix = prefix;
159 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
160 opt->pattern_tail = &opt->pattern_list;
161 opt->header_tail = &opt->header_list;
163 opt->only_matching = def->only_matching;
164 opt->color = def->color;
165 opt->extended_regexp_option = def->extended_regexp_option;
166 opt->pattern_type_option = def->pattern_type_option;
167 opt->linenum = def->linenum;
168 opt->columnnum = def->columnnum;
169 opt->max_depth = def->max_depth;
170 opt->pathname = def->pathname;
171 opt->relative = def->relative;
172 opt->output = def->output;
174 for (i = 0; i < NR_GREP_COLORS; i++)
175 color_set(opt->colors[i], def->colors[i]);
178 static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
181 * When committing to the pattern type by setting the relevant
182 * fields in grep_opt it's generally not necessary to zero out
183 * the fields we're not choosing, since they won't have been
184 * set by anything. The extended_regexp_option field is the
185 * only exception to this.
187 * This is because in the process of parsing grep.patternType
188 * & grep.extendedRegexp we set opt->pattern_type_option and
189 * opt->extended_regexp_option, respectively. We then
190 * internally use opt->extended_regexp_option to see if we're
191 * compiling an ERE. It must be unset if that's not actually
192 * the case.
194 if (pattern_type != GREP_PATTERN_TYPE_ERE &&
195 opt->extended_regexp_option)
196 opt->extended_regexp_option = 0;
198 switch (pattern_type) {
199 case GREP_PATTERN_TYPE_UNSPECIFIED:
200 /* fall through */
202 case GREP_PATTERN_TYPE_BRE:
203 break;
205 case GREP_PATTERN_TYPE_ERE:
206 opt->extended_regexp_option = 1;
207 break;
209 case GREP_PATTERN_TYPE_FIXED:
210 opt->fixed = 1;
211 break;
213 case GREP_PATTERN_TYPE_PCRE:
214 #ifdef USE_LIBPCRE2
215 opt->pcre2 = 1;
216 #else
218 * It's important that pcre1 always be assigned to
219 * even when there's no USE_LIBPCRE* defined. We still
220 * call the PCRE stub function, it just dies with
221 * "cannot use Perl-compatible regexes[...]".
223 opt->pcre1 = 1;
224 #endif
225 break;
229 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
231 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
232 grep_set_pattern_type_option(pattern_type, opt);
233 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
234 grep_set_pattern_type_option(opt->pattern_type_option, opt);
235 else if (opt->extended_regexp_option)
237 * This branch *must* happen after setting from the
238 * opt->pattern_type_option above, we don't want
239 * grep.extendedRegexp to override grep.patternType!
241 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
244 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
245 const char *origin, int no,
246 enum grep_pat_token t,
247 enum grep_header_field field)
249 struct grep_pat *p = xcalloc(1, sizeof(*p));
250 p->pattern = xmemdupz(pat, patlen);
251 p->patternlen = patlen;
252 p->origin = origin;
253 p->no = no;
254 p->token = t;
255 p->field = field;
256 return p;
259 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
261 **tail = p;
262 *tail = &p->next;
263 p->next = NULL;
265 switch (p->token) {
266 case GREP_PATTERN: /* atom */
267 case GREP_PATTERN_HEAD:
268 case GREP_PATTERN_BODY:
269 for (;;) {
270 struct grep_pat *new_pat;
271 size_t len = 0;
272 char *cp = p->pattern + p->patternlen, *nl = NULL;
273 while (++len <= p->patternlen) {
274 if (*(--cp) == '\n') {
275 nl = cp;
276 break;
279 if (!nl)
280 break;
281 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
282 p->no, p->token, p->field);
283 new_pat->next = p->next;
284 if (!p->next)
285 *tail = &new_pat->next;
286 p->next = new_pat;
287 *nl = '\0';
288 p->patternlen -= len;
290 break;
291 default:
292 break;
296 void append_header_grep_pattern(struct grep_opt *opt,
297 enum grep_header_field field, const char *pat)
299 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
300 GREP_PATTERN_HEAD, field);
301 if (field == GREP_HEADER_REFLOG)
302 opt->use_reflog_filter = 1;
303 do_append_grep_pat(&opt->header_tail, p);
306 void append_grep_pattern(struct grep_opt *opt, const char *pat,
307 const char *origin, int no, enum grep_pat_token t)
309 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
312 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
313 const char *origin, int no, enum grep_pat_token t)
315 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
316 do_append_grep_pat(&opt->pattern_tail, p);
319 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
321 struct grep_pat *pat;
322 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
323 *ret = *opt;
325 ret->pattern_list = NULL;
326 ret->pattern_tail = &ret->pattern_list;
328 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
330 if(pat->token == GREP_PATTERN_HEAD)
331 append_header_grep_pattern(ret, pat->field,
332 pat->pattern);
333 else
334 append_grep_pat(ret, pat->pattern, pat->patternlen,
335 pat->origin, pat->no, pat->token);
338 return ret;
341 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
342 const char *error)
344 char where[1024];
346 if (p->no)
347 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
348 else if (p->origin)
349 xsnprintf(where, sizeof(where), "%s, ", p->origin);
350 else
351 where[0] = 0;
353 die("%s'%s': %s", where, p->pattern, error);
356 static int is_fixed(const char *s, size_t len)
358 size_t i;
360 for (i = 0; i < len; i++) {
361 if (is_regex_special(s[i]))
362 return 0;
365 return 1;
368 static int has_null(const char *s, size_t len)
371 * regcomp cannot accept patterns with NULs so when using it
372 * we consider any pattern containing a NUL fixed.
374 if (memchr(s, 0, len))
375 return 1;
377 return 0;
380 #ifdef USE_LIBPCRE1
381 static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
383 const char *error;
384 int erroffset;
385 int options = PCRE_MULTILINE;
387 if (opt->ignore_case) {
388 if (has_non_ascii(p->pattern))
389 p->pcre1_tables = pcre_maketables();
390 options |= PCRE_CASELESS;
392 if (is_utf8_locale() && has_non_ascii(p->pattern))
393 options |= PCRE_UTF8;
395 p->pcre1_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
396 p->pcre1_tables);
397 if (!p->pcre1_regexp)
398 compile_regexp_failed(p, error);
400 p->pcre1_extra_info = pcre_study(p->pcre1_regexp, GIT_PCRE_STUDY_JIT_COMPILE, &error);
401 if (!p->pcre1_extra_info && error)
402 die("%s", error);
404 #ifdef GIT_PCRE1_USE_JIT
405 pcre_config(PCRE_CONFIG_JIT, &p->pcre1_jit_on);
406 if (p->pcre1_jit_on == 1) {
407 p->pcre1_jit_stack = pcre_jit_stack_alloc(1, 1024 * 1024);
408 if (!p->pcre1_jit_stack)
409 die("Couldn't allocate PCRE JIT stack");
410 pcre_assign_jit_stack(p->pcre1_extra_info, NULL, p->pcre1_jit_stack);
411 } else if (p->pcre1_jit_on != 0) {
412 BUG("The pcre1_jit_on variable should be 0 or 1, not %d",
413 p->pcre1_jit_on);
415 #endif
418 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
419 regmatch_t *match, int eflags)
421 int ovector[30], ret, flags = 0;
423 if (eflags & REG_NOTBOL)
424 flags |= PCRE_NOTBOL;
426 #ifdef GIT_PCRE1_USE_JIT
427 if (p->pcre1_jit_on) {
428 ret = pcre_jit_exec(p->pcre1_regexp, p->pcre1_extra_info, line,
429 eol - line, 0, flags, ovector,
430 ARRAY_SIZE(ovector), p->pcre1_jit_stack);
431 } else
432 #endif
434 ret = pcre_exec(p->pcre1_regexp, p->pcre1_extra_info, line,
435 eol - line, 0, flags, ovector,
436 ARRAY_SIZE(ovector));
439 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
440 die("pcre_exec failed with error code %d", ret);
441 if (ret > 0) {
442 ret = 0;
443 match->rm_so = ovector[0];
444 match->rm_eo = ovector[1];
447 return ret;
450 static void free_pcre1_regexp(struct grep_pat *p)
452 pcre_free(p->pcre1_regexp);
453 #ifdef GIT_PCRE1_USE_JIT
454 if (p->pcre1_jit_on) {
455 pcre_free_study(p->pcre1_extra_info);
456 pcre_jit_stack_free(p->pcre1_jit_stack);
457 } else
458 #endif
460 pcre_free(p->pcre1_extra_info);
462 pcre_free((void *)p->pcre1_tables);
464 #else /* !USE_LIBPCRE1 */
465 static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
467 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
470 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
471 regmatch_t *match, int eflags)
473 return 1;
476 static void free_pcre1_regexp(struct grep_pat *p)
479 #endif /* !USE_LIBPCRE1 */
481 #ifdef USE_LIBPCRE2
482 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
484 int error;
485 PCRE2_UCHAR errbuf[256];
486 PCRE2_SIZE erroffset;
487 int options = PCRE2_MULTILINE;
488 const uint8_t *character_tables = NULL;
489 int jitret;
490 int patinforet;
491 size_t jitsizearg;
493 assert(opt->pcre2);
495 p->pcre2_compile_context = NULL;
497 if (opt->ignore_case) {
498 if (has_non_ascii(p->pattern)) {
499 character_tables = pcre2_maketables(NULL);
500 p->pcre2_compile_context = pcre2_compile_context_create(NULL);
501 pcre2_set_character_tables(p->pcre2_compile_context, character_tables);
503 options |= PCRE2_CASELESS;
505 if (is_utf8_locale() && has_non_ascii(p->pattern))
506 options |= PCRE2_UTF;
508 p->pcre2_pattern = pcre2_compile((PCRE2_SPTR)p->pattern,
509 p->patternlen, options, &error, &erroffset,
510 p->pcre2_compile_context);
512 if (p->pcre2_pattern) {
513 p->pcre2_match_data = pcre2_match_data_create_from_pattern(p->pcre2_pattern, NULL);
514 if (!p->pcre2_match_data)
515 die("Couldn't allocate PCRE2 match data");
516 } else {
517 pcre2_get_error_message(error, errbuf, sizeof(errbuf));
518 compile_regexp_failed(p, (const char *)&errbuf);
521 pcre2_config(PCRE2_CONFIG_JIT, &p->pcre2_jit_on);
522 if (p->pcre2_jit_on == 1) {
523 jitret = pcre2_jit_compile(p->pcre2_pattern, PCRE2_JIT_COMPLETE);
524 if (jitret)
525 die("Couldn't JIT the PCRE2 pattern '%s', got '%d'\n", p->pattern, jitret);
528 * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
529 * tells us whether the library itself supports JIT,
530 * but to see whether we're going to be actually using
531 * JIT we need to extract PCRE2_INFO_JITSIZE from the
532 * pattern *after* we do pcre2_jit_compile() above.
534 * This is because if the pattern contains the
535 * (*NO_JIT) verb (see pcre2syntax(3))
536 * pcre2_jit_compile() will exit early with 0. If we
537 * then proceed to call pcre2_jit_match() further down
538 * the line instead of pcre2_match() we'll either
539 * segfault (pre PCRE 10.31) or run into a fatal error
540 * (post PCRE2 10.31)
542 patinforet = pcre2_pattern_info(p->pcre2_pattern, PCRE2_INFO_JITSIZE, &jitsizearg);
543 if (patinforet)
544 BUG("pcre2_pattern_info() failed: %d", patinforet);
545 if (jitsizearg == 0) {
546 p->pcre2_jit_on = 0;
547 return;
550 p->pcre2_jit_stack = pcre2_jit_stack_create(1, 1024 * 1024, NULL);
551 if (!p->pcre2_jit_stack)
552 die("Couldn't allocate PCRE2 JIT stack");
553 p->pcre2_match_context = pcre2_match_context_create(NULL);
554 if (!p->pcre2_match_context)
555 die("Couldn't allocate PCRE2 match context");
556 pcre2_jit_stack_assign(p->pcre2_match_context, NULL, p->pcre2_jit_stack);
557 } else if (p->pcre2_jit_on != 0) {
558 BUG("The pcre2_jit_on variable should be 0 or 1, not %d",
559 p->pcre1_jit_on);
563 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
564 regmatch_t *match, int eflags)
566 int ret, flags = 0;
567 PCRE2_SIZE *ovector;
568 PCRE2_UCHAR errbuf[256];
570 if (eflags & REG_NOTBOL)
571 flags |= PCRE2_NOTBOL;
573 if (p->pcre2_jit_on)
574 ret = pcre2_jit_match(p->pcre2_pattern, (unsigned char *)line,
575 eol - line, 0, flags, p->pcre2_match_data,
576 NULL);
577 else
578 ret = pcre2_match(p->pcre2_pattern, (unsigned char *)line,
579 eol - line, 0, flags, p->pcre2_match_data,
580 NULL);
582 if (ret < 0 && ret != PCRE2_ERROR_NOMATCH) {
583 pcre2_get_error_message(ret, errbuf, sizeof(errbuf));
584 die("%s failed with error code %d: %s",
585 (p->pcre2_jit_on ? "pcre2_jit_match" : "pcre2_match"), ret,
586 errbuf);
588 if (ret > 0) {
589 ovector = pcre2_get_ovector_pointer(p->pcre2_match_data);
590 ret = 0;
591 match->rm_so = (int)ovector[0];
592 match->rm_eo = (int)ovector[1];
595 return ret;
598 static void free_pcre2_pattern(struct grep_pat *p)
600 pcre2_compile_context_free(p->pcre2_compile_context);
601 pcre2_code_free(p->pcre2_pattern);
602 pcre2_match_data_free(p->pcre2_match_data);
603 pcre2_jit_stack_free(p->pcre2_jit_stack);
604 pcre2_match_context_free(p->pcre2_match_context);
606 #else /* !USE_LIBPCRE2 */
607 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
610 * Unreachable until USE_LIBPCRE2 becomes synonymous with
611 * USE_LIBPCRE. See the sibling comment in
612 * grep_set_pattern_type_option().
614 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
617 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
618 regmatch_t *match, int eflags)
620 return 1;
623 static void free_pcre2_pattern(struct grep_pat *p)
626 #endif /* !USE_LIBPCRE2 */
628 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
630 struct strbuf sb = STRBUF_INIT;
631 int err;
632 int regflags = 0;
634 basic_regex_quote_buf(&sb, p->pattern);
635 if (opt->ignore_case)
636 regflags |= REG_ICASE;
637 err = regcomp(&p->regexp, sb.buf, regflags);
638 if (opt->debug)
639 fprintf(stderr, "fixed %s\n", sb.buf);
640 strbuf_release(&sb);
641 if (err) {
642 char errbuf[1024];
643 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
644 compile_regexp_failed(p, errbuf);
648 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
650 int ascii_only;
651 int err;
652 int regflags = REG_NEWLINE;
654 p->word_regexp = opt->word_regexp;
655 p->ignore_case = opt->ignore_case;
656 ascii_only = !has_non_ascii(p->pattern);
659 * Even when -F (fixed) asks us to do a non-regexp search, we
660 * may not be able to correctly case-fold when -i
661 * (ignore-case) is asked (in which case, we'll synthesize a
662 * regexp to match the pattern that matches regexp special
663 * characters literally, while ignoring case differences). On
664 * the other hand, even without -F, if the pattern does not
665 * have any regexp special characters and there is no need for
666 * case-folding search, we can internally turn it into a
667 * simple string match using kws. p->fixed tells us if we
668 * want to use kws.
670 if (opt->fixed ||
671 has_null(p->pattern, p->patternlen) ||
672 is_fixed(p->pattern, p->patternlen))
673 p->fixed = !p->ignore_case || ascii_only;
675 if (p->fixed) {
676 p->kws = kwsalloc(p->ignore_case ? tolower_trans_tbl : NULL);
677 kwsincr(p->kws, p->pattern, p->patternlen);
678 kwsprep(p->kws);
679 return;
680 } else if (opt->fixed) {
682 * We come here when the pattern has the non-ascii
683 * characters we cannot case-fold, and asked to
684 * ignore-case.
686 compile_fixed_regexp(p, opt);
687 return;
690 if (opt->pcre2) {
691 compile_pcre2_pattern(p, opt);
692 return;
695 if (opt->pcre1) {
696 compile_pcre1_regexp(p, opt);
697 return;
700 if (p->ignore_case)
701 regflags |= REG_ICASE;
702 if (opt->extended_regexp_option)
703 regflags |= REG_EXTENDED;
704 err = regcomp(&p->regexp, p->pattern, regflags);
705 if (err) {
706 char errbuf[1024];
707 regerror(err, &p->regexp, errbuf, 1024);
708 compile_regexp_failed(p, errbuf);
712 static struct grep_expr *compile_pattern_or(struct grep_pat **);
713 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
715 struct grep_pat *p;
716 struct grep_expr *x;
718 p = *list;
719 if (!p)
720 return NULL;
721 switch (p->token) {
722 case GREP_PATTERN: /* atom */
723 case GREP_PATTERN_HEAD:
724 case GREP_PATTERN_BODY:
725 x = xcalloc(1, sizeof (struct grep_expr));
726 x->node = GREP_NODE_ATOM;
727 x->u.atom = p;
728 *list = p->next;
729 return x;
730 case GREP_OPEN_PAREN:
731 *list = p->next;
732 x = compile_pattern_or(list);
733 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
734 die("unmatched parenthesis");
735 *list = (*list)->next;
736 return x;
737 default:
738 return NULL;
742 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
744 struct grep_pat *p;
745 struct grep_expr *x;
747 p = *list;
748 if (!p)
749 return NULL;
750 switch (p->token) {
751 case GREP_NOT:
752 if (!p->next)
753 die("--not not followed by pattern expression");
754 *list = p->next;
755 x = xcalloc(1, sizeof (struct grep_expr));
756 x->node = GREP_NODE_NOT;
757 x->u.unary = compile_pattern_not(list);
758 if (!x->u.unary)
759 die("--not followed by non pattern expression");
760 return x;
761 default:
762 return compile_pattern_atom(list);
766 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
768 struct grep_pat *p;
769 struct grep_expr *x, *y, *z;
771 x = compile_pattern_not(list);
772 p = *list;
773 if (p && p->token == GREP_AND) {
774 if (!p->next)
775 die("--and not followed by pattern expression");
776 *list = p->next;
777 y = compile_pattern_and(list);
778 if (!y)
779 die("--and not followed by pattern expression");
780 z = xcalloc(1, sizeof (struct grep_expr));
781 z->node = GREP_NODE_AND;
782 z->u.binary.left = x;
783 z->u.binary.right = y;
784 return z;
786 return x;
789 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
791 struct grep_pat *p;
792 struct grep_expr *x, *y, *z;
794 x = compile_pattern_and(list);
795 p = *list;
796 if (x && p && p->token != GREP_CLOSE_PAREN) {
797 y = compile_pattern_or(list);
798 if (!y)
799 die("not a pattern expression %s", p->pattern);
800 z = xcalloc(1, sizeof (struct grep_expr));
801 z->node = GREP_NODE_OR;
802 z->u.binary.left = x;
803 z->u.binary.right = y;
804 return z;
806 return x;
809 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
811 return compile_pattern_or(list);
814 static void indent(int in)
816 while (in-- > 0)
817 fputc(' ', stderr);
820 static void dump_grep_pat(struct grep_pat *p)
822 switch (p->token) {
823 case GREP_AND: fprintf(stderr, "*and*"); break;
824 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
825 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
826 case GREP_NOT: fprintf(stderr, "*not*"); break;
827 case GREP_OR: fprintf(stderr, "*or*"); break;
829 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
830 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
831 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
834 switch (p->token) {
835 default: break;
836 case GREP_PATTERN_HEAD:
837 fprintf(stderr, "<head %d>", p->field); break;
838 case GREP_PATTERN_BODY:
839 fprintf(stderr, "<body>"); break;
841 switch (p->token) {
842 default: break;
843 case GREP_PATTERN_HEAD:
844 case GREP_PATTERN_BODY:
845 case GREP_PATTERN:
846 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
847 break;
849 fputc('\n', stderr);
852 static void dump_grep_expression_1(struct grep_expr *x, int in)
854 indent(in);
855 switch (x->node) {
856 case GREP_NODE_TRUE:
857 fprintf(stderr, "true\n");
858 break;
859 case GREP_NODE_ATOM:
860 dump_grep_pat(x->u.atom);
861 break;
862 case GREP_NODE_NOT:
863 fprintf(stderr, "(not\n");
864 dump_grep_expression_1(x->u.unary, in+1);
865 indent(in);
866 fprintf(stderr, ")\n");
867 break;
868 case GREP_NODE_AND:
869 fprintf(stderr, "(and\n");
870 dump_grep_expression_1(x->u.binary.left, in+1);
871 dump_grep_expression_1(x->u.binary.right, in+1);
872 indent(in);
873 fprintf(stderr, ")\n");
874 break;
875 case GREP_NODE_OR:
876 fprintf(stderr, "(or\n");
877 dump_grep_expression_1(x->u.binary.left, in+1);
878 dump_grep_expression_1(x->u.binary.right, in+1);
879 indent(in);
880 fprintf(stderr, ")\n");
881 break;
885 static void dump_grep_expression(struct grep_opt *opt)
887 struct grep_expr *x = opt->pattern_expression;
889 if (opt->all_match)
890 fprintf(stderr, "[all-match]\n");
891 dump_grep_expression_1(x, 0);
892 fflush(NULL);
895 static struct grep_expr *grep_true_expr(void)
897 struct grep_expr *z = xcalloc(1, sizeof(*z));
898 z->node = GREP_NODE_TRUE;
899 return z;
902 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
904 struct grep_expr *z = xcalloc(1, sizeof(*z));
905 z->node = GREP_NODE_OR;
906 z->u.binary.left = left;
907 z->u.binary.right = right;
908 return z;
911 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
913 struct grep_pat *p;
914 struct grep_expr *header_expr;
915 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
916 enum grep_header_field fld;
918 if (!opt->header_list)
919 return NULL;
921 for (p = opt->header_list; p; p = p->next) {
922 if (p->token != GREP_PATTERN_HEAD)
923 BUG("a non-header pattern in grep header list.");
924 if (p->field < GREP_HEADER_FIELD_MIN ||
925 GREP_HEADER_FIELD_MAX <= p->field)
926 BUG("unknown header field %d", p->field);
927 compile_regexp(p, opt);
930 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
931 header_group[fld] = NULL;
933 for (p = opt->header_list; p; p = p->next) {
934 struct grep_expr *h;
935 struct grep_pat *pp = p;
937 h = compile_pattern_atom(&pp);
938 if (!h || pp != p->next)
939 BUG("malformed header expr");
940 if (!header_group[p->field]) {
941 header_group[p->field] = h;
942 continue;
944 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
947 header_expr = NULL;
949 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
950 if (!header_group[fld])
951 continue;
952 if (!header_expr)
953 header_expr = grep_true_expr();
954 header_expr = grep_or_expr(header_group[fld], header_expr);
956 return header_expr;
959 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
961 struct grep_expr *z = x;
963 while (x) {
964 assert(x->node == GREP_NODE_OR);
965 if (x->u.binary.right &&
966 x->u.binary.right->node == GREP_NODE_TRUE) {
967 x->u.binary.right = y;
968 break;
970 x = x->u.binary.right;
972 return z;
975 static void compile_grep_patterns_real(struct grep_opt *opt)
977 struct grep_pat *p;
978 struct grep_expr *header_expr = prep_header_patterns(opt);
980 for (p = opt->pattern_list; p; p = p->next) {
981 switch (p->token) {
982 case GREP_PATTERN: /* atom */
983 case GREP_PATTERN_HEAD:
984 case GREP_PATTERN_BODY:
985 compile_regexp(p, opt);
986 break;
987 default:
988 opt->extended = 1;
989 break;
993 if (opt->all_match || header_expr)
994 opt->extended = 1;
995 else if (!opt->extended && !opt->debug)
996 return;
998 p = opt->pattern_list;
999 if (p)
1000 opt->pattern_expression = compile_pattern_expr(&p);
1001 if (p)
1002 die("incomplete pattern expression: %s", p->pattern);
1004 if (!header_expr)
1005 return;
1007 if (!opt->pattern_expression)
1008 opt->pattern_expression = header_expr;
1009 else if (opt->all_match)
1010 opt->pattern_expression = grep_splice_or(header_expr,
1011 opt->pattern_expression);
1012 else
1013 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
1014 header_expr);
1015 opt->all_match = 1;
1018 void compile_grep_patterns(struct grep_opt *opt)
1020 compile_grep_patterns_real(opt);
1021 if (opt->debug)
1022 dump_grep_expression(opt);
1025 static void free_pattern_expr(struct grep_expr *x)
1027 switch (x->node) {
1028 case GREP_NODE_TRUE:
1029 case GREP_NODE_ATOM:
1030 break;
1031 case GREP_NODE_NOT:
1032 free_pattern_expr(x->u.unary);
1033 break;
1034 case GREP_NODE_AND:
1035 case GREP_NODE_OR:
1036 free_pattern_expr(x->u.binary.left);
1037 free_pattern_expr(x->u.binary.right);
1038 break;
1040 free(x);
1043 void free_grep_patterns(struct grep_opt *opt)
1045 struct grep_pat *p, *n;
1047 for (p = opt->pattern_list; p; p = n) {
1048 n = p->next;
1049 switch (p->token) {
1050 case GREP_PATTERN: /* atom */
1051 case GREP_PATTERN_HEAD:
1052 case GREP_PATTERN_BODY:
1053 if (p->kws)
1054 kwsfree(p->kws);
1055 else if (p->pcre1_regexp)
1056 free_pcre1_regexp(p);
1057 else if (p->pcre2_pattern)
1058 free_pcre2_pattern(p);
1059 else
1060 regfree(&p->regexp);
1061 free(p->pattern);
1062 break;
1063 default:
1064 break;
1066 free(p);
1069 if (!opt->extended)
1070 return;
1071 free_pattern_expr(opt->pattern_expression);
1074 static char *end_of_line(char *cp, unsigned long *left)
1076 unsigned long l = *left;
1077 while (l && *cp != '\n') {
1078 l--;
1079 cp++;
1081 *left = l;
1082 return cp;
1085 static int word_char(char ch)
1087 return isalnum(ch) || ch == '_';
1090 static void output_color(struct grep_opt *opt, const void *data, size_t size,
1091 const char *color)
1093 if (want_color(opt->color) && color && color[0]) {
1094 opt->output(opt, color, strlen(color));
1095 opt->output(opt, data, size);
1096 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
1097 } else
1098 opt->output(opt, data, size);
1101 static void output_sep(struct grep_opt *opt, char sign)
1103 if (opt->null_following_name)
1104 opt->output(opt, "\0", 1);
1105 else
1106 output_color(opt, &sign, 1, opt->colors[GREP_COLOR_SEP]);
1109 static void show_name(struct grep_opt *opt, const char *name)
1111 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1112 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
1115 static int fixmatch(struct grep_pat *p, char *line, char *eol,
1116 regmatch_t *match)
1118 struct kwsmatch kwsm;
1119 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
1120 if (offset == -1) {
1121 match->rm_so = match->rm_eo = -1;
1122 return REG_NOMATCH;
1123 } else {
1124 match->rm_so = offset;
1125 match->rm_eo = match->rm_so + kwsm.size[0];
1126 return 0;
1130 static int patmatch(struct grep_pat *p, char *line, char *eol,
1131 regmatch_t *match, int eflags)
1133 int hit;
1135 if (p->fixed)
1136 hit = !fixmatch(p, line, eol, match);
1137 else if (p->pcre1_regexp)
1138 hit = !pcre1match(p, line, eol, match, eflags);
1139 else if (p->pcre2_pattern)
1140 hit = !pcre2match(p, line, eol, match, eflags);
1141 else
1142 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
1143 eflags);
1145 return hit;
1148 static int strip_timestamp(char *bol, char **eol_p)
1150 char *eol = *eol_p;
1151 int ch;
1153 while (bol < --eol) {
1154 if (*eol != '>')
1155 continue;
1156 *eol_p = ++eol;
1157 ch = *eol;
1158 *eol = '\0';
1159 return ch;
1161 return 0;
1164 static struct {
1165 const char *field;
1166 size_t len;
1167 } header_field[] = {
1168 { "author ", 7 },
1169 { "committer ", 10 },
1170 { "reflog ", 7 },
1173 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
1174 enum grep_context ctx,
1175 regmatch_t *pmatch, int eflags)
1177 int hit = 0;
1178 int saved_ch = 0;
1179 const char *start = bol;
1181 if ((p->token != GREP_PATTERN) &&
1182 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
1183 return 0;
1185 if (p->token == GREP_PATTERN_HEAD) {
1186 const char *field;
1187 size_t len;
1188 assert(p->field < ARRAY_SIZE(header_field));
1189 field = header_field[p->field].field;
1190 len = header_field[p->field].len;
1191 if (strncmp(bol, field, len))
1192 return 0;
1193 bol += len;
1194 switch (p->field) {
1195 case GREP_HEADER_AUTHOR:
1196 case GREP_HEADER_COMMITTER:
1197 saved_ch = strip_timestamp(bol, &eol);
1198 break;
1199 default:
1200 break;
1204 again:
1205 hit = patmatch(p, bol, eol, pmatch, eflags);
1207 if (hit && p->word_regexp) {
1208 if ((pmatch[0].rm_so < 0) ||
1209 (eol - bol) < pmatch[0].rm_so ||
1210 (pmatch[0].rm_eo < 0) ||
1211 (eol - bol) < pmatch[0].rm_eo)
1212 die("regexp returned nonsense");
1214 /* Match beginning must be either beginning of the
1215 * line, or at word boundary (i.e. the last char must
1216 * not be a word char). Similarly, match end must be
1217 * either end of the line, or at word boundary
1218 * (i.e. the next char must not be a word char).
1220 if ( ((pmatch[0].rm_so == 0) ||
1221 !word_char(bol[pmatch[0].rm_so-1])) &&
1222 ((pmatch[0].rm_eo == (eol-bol)) ||
1223 !word_char(bol[pmatch[0].rm_eo])) )
1225 else
1226 hit = 0;
1228 /* Words consist of at least one character. */
1229 if (pmatch->rm_so == pmatch->rm_eo)
1230 hit = 0;
1232 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1233 /* There could be more than one match on the
1234 * line, and the first match might not be
1235 * strict word match. But later ones could be!
1236 * Forward to the next possible start, i.e. the
1237 * next position following a non-word char.
1239 bol = pmatch[0].rm_so + bol + 1;
1240 while (word_char(bol[-1]) && bol < eol)
1241 bol++;
1242 eflags |= REG_NOTBOL;
1243 if (bol < eol)
1244 goto again;
1247 if (p->token == GREP_PATTERN_HEAD && saved_ch)
1248 *eol = saved_ch;
1249 if (hit) {
1250 pmatch[0].rm_so += bol - start;
1251 pmatch[0].rm_eo += bol - start;
1253 return hit;
1256 static int match_expr_eval(struct grep_opt *opt, struct grep_expr *x, char *bol,
1257 char *eol, enum grep_context ctx, ssize_t *col,
1258 ssize_t *icol, int collect_hits)
1260 int h = 0;
1262 if (!x)
1263 die("Not a valid grep expression");
1264 switch (x->node) {
1265 case GREP_NODE_TRUE:
1266 h = 1;
1267 break;
1268 case GREP_NODE_ATOM:
1270 regmatch_t tmp;
1271 h = match_one_pattern(x->u.atom, bol, eol, ctx,
1272 &tmp, 0);
1273 if (h && (*col < 0 || tmp.rm_so < *col))
1274 *col = tmp.rm_so;
1276 break;
1277 case GREP_NODE_NOT:
1279 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1281 h = !match_expr_eval(opt, x->u.unary, bol, eol, ctx, icol, col,
1283 break;
1284 case GREP_NODE_AND:
1285 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1286 icol, 0);
1287 if (h || opt->columnnum) {
1289 * Don't short-circuit AND when given --column, since a
1290 * NOT earlier in the tree may turn this into an OR. In
1291 * this case, see the below comment.
1293 h &= match_expr_eval(opt, x->u.binary.right, bol, eol,
1294 ctx, col, icol, 0);
1296 break;
1297 case GREP_NODE_OR:
1298 if (!(collect_hits || opt->columnnum)) {
1300 * Don't short-circuit OR when given --column (or
1301 * collecting hits) to ensure we don't skip a later
1302 * child that would produce an earlier match.
1304 return (match_expr_eval(opt, x->u.binary.left, bol, eol,
1305 ctx, col, icol, 0) ||
1306 match_expr_eval(opt, x->u.binary.right, bol,
1307 eol, ctx, col, icol, 0));
1309 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1310 icol, 0);
1311 if (collect_hits)
1312 x->u.binary.left->hit |= h;
1313 h |= match_expr_eval(opt, x->u.binary.right, bol, eol, ctx, col,
1314 icol, collect_hits);
1315 break;
1316 default:
1317 die("Unexpected node type (internal error) %d", x->node);
1319 if (collect_hits)
1320 x->hit |= h;
1321 return h;
1324 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1325 enum grep_context ctx, ssize_t *col,
1326 ssize_t *icol, int collect_hits)
1328 struct grep_expr *x = opt->pattern_expression;
1329 return match_expr_eval(opt, x, bol, eol, ctx, col, icol, collect_hits);
1332 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1333 ssize_t *col, ssize_t *icol,
1334 enum grep_context ctx, int collect_hits)
1336 struct grep_pat *p;
1337 int hit = 0;
1339 if (opt->extended)
1340 return match_expr(opt, bol, eol, ctx, col, icol,
1341 collect_hits);
1343 /* we do not call with collect_hits without being extended */
1344 for (p = opt->pattern_list; p; p = p->next) {
1345 regmatch_t tmp;
1346 if (match_one_pattern(p, bol, eol, ctx, &tmp, 0)) {
1347 hit |= 1;
1348 if (!opt->columnnum) {
1350 * Without --column, any single match on a line
1351 * is enough to know that it needs to be
1352 * printed. With --column, scan _all_ patterns
1353 * to find the earliest.
1355 break;
1357 if (*col < 0 || tmp.rm_so < *col)
1358 *col = tmp.rm_so;
1361 return hit;
1364 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1365 enum grep_context ctx,
1366 regmatch_t *pmatch, int eflags)
1368 regmatch_t match;
1370 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1371 return 0;
1372 if (match.rm_so < 0 || match.rm_eo < 0)
1373 return 0;
1374 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1375 if (match.rm_so > pmatch->rm_so)
1376 return 1;
1377 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1378 return 1;
1380 pmatch->rm_so = match.rm_so;
1381 pmatch->rm_eo = match.rm_eo;
1382 return 1;
1385 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1386 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1388 struct grep_pat *p;
1389 int hit = 0;
1391 pmatch->rm_so = pmatch->rm_eo = -1;
1392 if (bol < eol) {
1393 for (p = opt->pattern_list; p; p = p->next) {
1394 switch (p->token) {
1395 case GREP_PATTERN: /* atom */
1396 case GREP_PATTERN_HEAD:
1397 case GREP_PATTERN_BODY:
1398 hit |= match_next_pattern(p, bol, eol, ctx,
1399 pmatch, eflags);
1400 break;
1401 default:
1402 break;
1406 return hit;
1409 static void show_line_header(struct grep_opt *opt, const char *name,
1410 unsigned lno, ssize_t cno, char sign)
1412 if (opt->heading && opt->last_shown == 0) {
1413 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1414 opt->output(opt, "\n", 1);
1416 opt->last_shown = lno;
1418 if (!opt->heading && opt->pathname) {
1419 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1420 output_sep(opt, sign);
1422 if (opt->linenum) {
1423 char buf[32];
1424 xsnprintf(buf, sizeof(buf), "%d", lno);
1425 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_LINENO]);
1426 output_sep(opt, sign);
1429 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1430 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1431 * being called with a context line.
1433 if (opt->columnnum && cno) {
1434 char buf[32];
1435 xsnprintf(buf, sizeof(buf), "%"PRIuMAX, (uintmax_t)cno);
1436 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_COLUMNNO]);
1437 output_sep(opt, sign);
1441 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1442 const char *name, unsigned lno, ssize_t cno, char sign)
1444 int rest = eol - bol;
1445 const char *match_color = NULL;
1446 const char *line_color = NULL;
1448 if (opt->file_break && opt->last_shown == 0) {
1449 if (opt->show_hunk_mark)
1450 opt->output(opt, "\n", 1);
1451 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1452 if (opt->last_shown == 0) {
1453 if (opt->show_hunk_mark) {
1454 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1455 opt->output(opt, "\n", 1);
1457 } else if (lno > opt->last_shown + 1) {
1458 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1459 opt->output(opt, "\n", 1);
1462 if (!opt->only_matching) {
1464 * In case the line we're being called with contains more than
1465 * one match, leave printing each header to the loop below.
1467 show_line_header(opt, name, lno, cno, sign);
1469 if (opt->color || opt->only_matching) {
1470 regmatch_t match;
1471 enum grep_context ctx = GREP_CONTEXT_BODY;
1472 int ch = *eol;
1473 int eflags = 0;
1475 if (opt->color) {
1476 if (sign == ':')
1477 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
1478 else
1479 match_color = opt->colors[GREP_COLOR_MATCH_CONTEXT];
1480 if (sign == ':')
1481 line_color = opt->colors[GREP_COLOR_SELECTED];
1482 else if (sign == '-')
1483 line_color = opt->colors[GREP_COLOR_CONTEXT];
1484 else if (sign == '=')
1485 line_color = opt->colors[GREP_COLOR_FUNCTION];
1487 *eol = '\0';
1488 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1489 if (match.rm_so == match.rm_eo)
1490 break;
1492 if (opt->only_matching)
1493 show_line_header(opt, name, lno, cno, sign);
1494 else
1495 output_color(opt, bol, match.rm_so, line_color);
1496 output_color(opt, bol + match.rm_so,
1497 match.rm_eo - match.rm_so, match_color);
1498 if (opt->only_matching)
1499 opt->output(opt, "\n", 1);
1500 bol += match.rm_eo;
1501 cno += match.rm_eo;
1502 rest -= match.rm_eo;
1503 eflags = REG_NOTBOL;
1505 *eol = ch;
1507 if (!opt->only_matching) {
1508 output_color(opt, bol, rest, line_color);
1509 opt->output(opt, "\n", 1);
1513 #ifndef NO_PTHREADS
1514 int grep_use_locks;
1517 * This lock protects access to the gitattributes machinery, which is
1518 * not thread-safe.
1520 pthread_mutex_t grep_attr_mutex;
1522 static inline void grep_attr_lock(void)
1524 if (grep_use_locks)
1525 pthread_mutex_lock(&grep_attr_mutex);
1528 static inline void grep_attr_unlock(void)
1530 if (grep_use_locks)
1531 pthread_mutex_unlock(&grep_attr_mutex);
1535 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1537 pthread_mutex_t grep_read_mutex;
1539 #else
1540 #define grep_attr_lock()
1541 #define grep_attr_unlock()
1542 #endif
1544 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1546 xdemitconf_t *xecfg = opt->priv;
1547 if (xecfg && !xecfg->find_func) {
1548 grep_source_load_driver(gs);
1549 if (gs->driver->funcname.pattern) {
1550 const struct userdiff_funcname *pe = &gs->driver->funcname;
1551 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1552 } else {
1553 xecfg = opt->priv = NULL;
1557 if (xecfg) {
1558 char buf[1];
1559 return xecfg->find_func(bol, eol - bol, buf, 1,
1560 xecfg->find_func_priv) >= 0;
1563 if (bol == eol)
1564 return 0;
1565 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1566 return 1;
1567 return 0;
1570 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1571 char *bol, unsigned lno)
1573 while (bol > gs->buf) {
1574 char *eol = --bol;
1576 while (bol > gs->buf && bol[-1] != '\n')
1577 bol--;
1578 lno--;
1580 if (lno <= opt->last_shown)
1581 break;
1583 if (match_funcname(opt, gs, bol, eol)) {
1584 show_line(opt, bol, eol, gs->name, lno, 0, '=');
1585 break;
1590 static int is_empty_line(const char *bol, const char *eol);
1592 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1593 char *bol, char *end, unsigned lno)
1595 unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
1596 int funcname_needed = !!opt->funcname, comment_needed = 0;
1598 if (opt->pre_context < lno)
1599 from = lno - opt->pre_context;
1600 if (from <= opt->last_shown)
1601 from = opt->last_shown + 1;
1602 orig_from = from;
1603 if (opt->funcbody) {
1604 if (match_funcname(opt, gs, bol, end))
1605 comment_needed = 1;
1606 else
1607 funcname_needed = 1;
1608 from = opt->last_shown + 1;
1611 /* Rewind. */
1612 while (bol > gs->buf && cur > from) {
1613 char *next_bol = bol;
1614 char *eol = --bol;
1616 while (bol > gs->buf && bol[-1] != '\n')
1617 bol--;
1618 cur--;
1619 if (comment_needed && (is_empty_line(bol, eol) ||
1620 match_funcname(opt, gs, bol, eol))) {
1621 comment_needed = 0;
1622 from = orig_from;
1623 if (cur < from) {
1624 cur++;
1625 bol = next_bol;
1626 break;
1629 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1630 funcname_lno = cur;
1631 funcname_needed = 0;
1632 if (opt->funcbody)
1633 comment_needed = 1;
1634 else
1635 from = orig_from;
1639 /* We need to look even further back to find a function signature. */
1640 if (opt->funcname && funcname_needed)
1641 show_funcname_line(opt, gs, bol, cur);
1643 /* Back forward. */
1644 while (cur < lno) {
1645 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1647 while (*eol != '\n')
1648 eol++;
1649 show_line(opt, bol, eol, gs->name, cur, 0, sign);
1650 bol = eol + 1;
1651 cur++;
1655 static int should_lookahead(struct grep_opt *opt)
1657 struct grep_pat *p;
1659 if (opt->extended)
1660 return 0; /* punt for too complex stuff */
1661 if (opt->invert)
1662 return 0;
1663 for (p = opt->pattern_list; p; p = p->next) {
1664 if (p->token != GREP_PATTERN)
1665 return 0; /* punt for "header only" and stuff */
1667 return 1;
1670 static int look_ahead(struct grep_opt *opt,
1671 unsigned long *left_p,
1672 unsigned *lno_p,
1673 char **bol_p)
1675 unsigned lno = *lno_p;
1676 char *bol = *bol_p;
1677 struct grep_pat *p;
1678 char *sp, *last_bol;
1679 regoff_t earliest = -1;
1681 for (p = opt->pattern_list; p; p = p->next) {
1682 int hit;
1683 regmatch_t m;
1685 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1686 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1687 continue;
1688 if (earliest < 0 || m.rm_so < earliest)
1689 earliest = m.rm_so;
1692 if (earliest < 0) {
1693 *bol_p = bol + *left_p;
1694 *left_p = 0;
1695 return 1;
1697 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1698 ; /* find the beginning of the line */
1699 last_bol = sp;
1701 for (sp = bol; sp < last_bol; sp++) {
1702 if (*sp == '\n')
1703 lno++;
1705 *left_p -= last_bol - bol;
1706 *bol_p = last_bol;
1707 *lno_p = lno;
1708 return 0;
1711 static int fill_textconv_grep(struct userdiff_driver *driver,
1712 struct grep_source *gs)
1714 struct diff_filespec *df;
1715 char *buf;
1716 size_t size;
1718 if (!driver || !driver->textconv)
1719 return grep_source_load(gs);
1722 * The textconv interface is intimately tied to diff_filespecs, so we
1723 * have to pretend to be one. If we could unify the grep_source
1724 * and diff_filespec structs, this mess could just go away.
1726 df = alloc_filespec(gs->path);
1727 switch (gs->type) {
1728 case GREP_SOURCE_OID:
1729 fill_filespec(df, gs->identifier, 1, 0100644);
1730 break;
1731 case GREP_SOURCE_FILE:
1732 fill_filespec(df, &null_oid, 0, 0100644);
1733 break;
1734 default:
1735 BUG("attempt to textconv something without a path?");
1739 * fill_textconv is not remotely thread-safe; it may load objects
1740 * behind the scenes, and it modifies the global diff tempfile
1741 * structure.
1743 grep_read_lock();
1744 size = fill_textconv(driver, df, &buf);
1745 grep_read_unlock();
1746 free_filespec(df);
1749 * The normal fill_textconv usage by the diff machinery would just keep
1750 * the textconv'd buf separate from the diff_filespec. But much of the
1751 * grep code passes around a grep_source and assumes that its "buf"
1752 * pointer is the beginning of the thing we are searching. So let's
1753 * install our textconv'd version into the grep_source, taking care not
1754 * to leak any existing buffer.
1756 grep_source_clear_data(gs);
1757 gs->buf = buf;
1758 gs->size = size;
1760 return 0;
1763 static int is_empty_line(const char *bol, const char *eol)
1765 while (bol < eol && isspace(*bol))
1766 bol++;
1767 return bol == eol;
1770 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1772 char *bol;
1773 char *peek_bol = NULL;
1774 unsigned long left;
1775 unsigned lno = 1;
1776 unsigned last_hit = 0;
1777 int binary_match_only = 0;
1778 unsigned count = 0;
1779 int try_lookahead = 0;
1780 int show_function = 0;
1781 struct userdiff_driver *textconv = NULL;
1782 enum grep_context ctx = GREP_CONTEXT_HEAD;
1783 xdemitconf_t xecfg;
1785 if (!opt->output)
1786 opt->output = std_output;
1788 if (opt->pre_context || opt->post_context || opt->file_break ||
1789 opt->funcbody) {
1790 /* Show hunk marks, except for the first file. */
1791 if (opt->last_shown)
1792 opt->show_hunk_mark = 1;
1794 * If we're using threads then we can't easily identify
1795 * the first file. Always put hunk marks in that case
1796 * and skip the very first one later in work_done().
1798 if (opt->output != std_output)
1799 opt->show_hunk_mark = 1;
1801 opt->last_shown = 0;
1803 if (opt->allow_textconv) {
1804 grep_source_load_driver(gs);
1806 * We might set up the shared textconv cache data here, which
1807 * is not thread-safe.
1809 grep_attr_lock();
1810 textconv = userdiff_get_textconv(gs->driver);
1811 grep_attr_unlock();
1815 * We know the result of a textconv is text, so we only have to care
1816 * about binary handling if we are not using it.
1818 if (!textconv) {
1819 switch (opt->binary) {
1820 case GREP_BINARY_DEFAULT:
1821 if (grep_source_is_binary(gs))
1822 binary_match_only = 1;
1823 break;
1824 case GREP_BINARY_NOMATCH:
1825 if (grep_source_is_binary(gs))
1826 return 0; /* Assume unmatch */
1827 break;
1828 case GREP_BINARY_TEXT:
1829 break;
1830 default:
1831 BUG("unknown binary handling mode");
1835 memset(&xecfg, 0, sizeof(xecfg));
1836 opt->priv = &xecfg;
1838 try_lookahead = should_lookahead(opt);
1840 if (fill_textconv_grep(textconv, gs) < 0)
1841 return 0;
1843 bol = gs->buf;
1844 left = gs->size;
1845 while (left) {
1846 char *eol, ch;
1847 int hit;
1848 ssize_t cno;
1849 ssize_t col = -1, icol = -1;
1852 * look_ahead() skips quickly to the line that possibly
1853 * has the next hit; don't call it if we need to do
1854 * something more than just skipping the current line
1855 * in response to an unmatch for the current line. E.g.
1856 * inside a post-context window, we will show the current
1857 * line as a context around the previous hit when it
1858 * doesn't hit.
1860 if (try_lookahead
1861 && !(last_hit
1862 && (show_function ||
1863 lno <= last_hit + opt->post_context))
1864 && look_ahead(opt, &left, &lno, &bol))
1865 break;
1866 eol = end_of_line(bol, &left);
1867 ch = *eol;
1868 *eol = 0;
1870 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1871 ctx = GREP_CONTEXT_BODY;
1873 hit = match_line(opt, bol, eol, &col, &icol, ctx, collect_hits);
1874 *eol = ch;
1876 if (collect_hits)
1877 goto next_line;
1879 /* "grep -v -e foo -e bla" should list lines
1880 * that do not have either, so inversion should
1881 * be done outside.
1883 if (opt->invert)
1884 hit = !hit;
1885 if (opt->unmatch_name_only) {
1886 if (hit)
1887 return 0;
1888 goto next_line;
1890 if (hit) {
1891 count++;
1892 if (opt->status_only)
1893 return 1;
1894 if (opt->name_only) {
1895 show_name(opt, gs->name);
1896 return 1;
1898 if (opt->count)
1899 goto next_line;
1900 if (binary_match_only) {
1901 opt->output(opt, "Binary file ", 12);
1902 output_color(opt, gs->name, strlen(gs->name),
1903 opt->colors[GREP_COLOR_FILENAME]);
1904 opt->output(opt, " matches\n", 9);
1905 return 1;
1907 /* Hit at this line. If we haven't shown the
1908 * pre-context lines, we would need to show them.
1910 if (opt->pre_context || opt->funcbody)
1911 show_pre_context(opt, gs, bol, eol, lno);
1912 else if (opt->funcname)
1913 show_funcname_line(opt, gs, bol, lno);
1914 cno = opt->invert ? icol : col;
1915 if (cno < 0) {
1917 * A negative cno indicates that there was no
1918 * match on the line. We are thus inverted and
1919 * being asked to show all lines that _don't_
1920 * match a given expression. Therefore, set cno
1921 * to 0 to suggest the whole line matches.
1923 cno = 0;
1925 show_line(opt, bol, eol, gs->name, lno, cno + 1, ':');
1926 last_hit = lno;
1927 if (opt->funcbody)
1928 show_function = 1;
1929 goto next_line;
1931 if (show_function && (!peek_bol || peek_bol < bol)) {
1932 unsigned long peek_left = left;
1933 char *peek_eol = eol;
1936 * Trailing empty lines are not interesting.
1937 * Peek past them to see if they belong to the
1938 * body of the current function.
1940 peek_bol = bol;
1941 while (is_empty_line(peek_bol, peek_eol)) {
1942 peek_bol = peek_eol + 1;
1943 peek_eol = end_of_line(peek_bol, &peek_left);
1946 if (match_funcname(opt, gs, peek_bol, peek_eol))
1947 show_function = 0;
1949 if (show_function ||
1950 (last_hit && lno <= last_hit + opt->post_context)) {
1951 /* If the last hit is within the post context,
1952 * we need to show this line.
1954 show_line(opt, bol, eol, gs->name, lno, col + 1, '-');
1957 next_line:
1958 bol = eol + 1;
1959 if (!left)
1960 break;
1961 left--;
1962 lno++;
1965 if (collect_hits)
1966 return 0;
1968 if (opt->status_only)
1969 return opt->unmatch_name_only;
1970 if (opt->unmatch_name_only) {
1971 /* We did not see any hit, so we want to show this */
1972 show_name(opt, gs->name);
1973 return 1;
1976 xdiff_clear_find_func(&xecfg);
1977 opt->priv = NULL;
1979 /* NEEDSWORK:
1980 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1981 * which feels mostly useless but sometimes useful. Maybe
1982 * make it another option? For now suppress them.
1984 if (opt->count && count) {
1985 char buf[32];
1986 if (opt->pathname) {
1987 output_color(opt, gs->name, strlen(gs->name),
1988 opt->colors[GREP_COLOR_FILENAME]);
1989 output_sep(opt, ':');
1991 xsnprintf(buf, sizeof(buf), "%u\n", count);
1992 opt->output(opt, buf, strlen(buf));
1993 return 1;
1995 return !!last_hit;
1998 static void clr_hit_marker(struct grep_expr *x)
2000 /* All-hit markers are meaningful only at the very top level
2001 * OR node.
2003 while (1) {
2004 x->hit = 0;
2005 if (x->node != GREP_NODE_OR)
2006 return;
2007 x->u.binary.left->hit = 0;
2008 x = x->u.binary.right;
2012 static int chk_hit_marker(struct grep_expr *x)
2014 /* Top level nodes have hit markers. See if they all are hits */
2015 while (1) {
2016 if (x->node != GREP_NODE_OR)
2017 return x->hit;
2018 if (!x->u.binary.left->hit)
2019 return 0;
2020 x = x->u.binary.right;
2024 int grep_source(struct grep_opt *opt, struct grep_source *gs)
2027 * we do not have to do the two-pass grep when we do not check
2028 * buffer-wide "all-match".
2030 if (!opt->all_match)
2031 return grep_source_1(opt, gs, 0);
2033 /* Otherwise the toplevel "or" terms hit a bit differently.
2034 * We first clear hit markers from them.
2036 clr_hit_marker(opt->pattern_expression);
2037 grep_source_1(opt, gs, 1);
2039 if (!chk_hit_marker(opt->pattern_expression))
2040 return 0;
2042 return grep_source_1(opt, gs, 0);
2045 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
2047 struct grep_source gs;
2048 int r;
2050 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
2051 gs.buf = buf;
2052 gs.size = size;
2054 r = grep_source(opt, &gs);
2056 grep_source_clear(&gs);
2057 return r;
2060 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
2061 const char *name, const char *path,
2062 const void *identifier)
2064 gs->type = type;
2065 gs->name = xstrdup_or_null(name);
2066 gs->path = xstrdup_or_null(path);
2067 gs->buf = NULL;
2068 gs->size = 0;
2069 gs->driver = NULL;
2071 switch (type) {
2072 case GREP_SOURCE_FILE:
2073 gs->identifier = xstrdup(identifier);
2074 break;
2075 case GREP_SOURCE_OID:
2076 gs->identifier = oiddup(identifier);
2077 break;
2078 case GREP_SOURCE_BUF:
2079 gs->identifier = NULL;
2080 break;
2084 void grep_source_clear(struct grep_source *gs)
2086 FREE_AND_NULL(gs->name);
2087 FREE_AND_NULL(gs->path);
2088 FREE_AND_NULL(gs->identifier);
2089 grep_source_clear_data(gs);
2092 void grep_source_clear_data(struct grep_source *gs)
2094 switch (gs->type) {
2095 case GREP_SOURCE_FILE:
2096 case GREP_SOURCE_OID:
2097 FREE_AND_NULL(gs->buf);
2098 gs->size = 0;
2099 break;
2100 case GREP_SOURCE_BUF:
2101 /* leave user-provided buf intact */
2102 break;
2106 static int grep_source_load_oid(struct grep_source *gs)
2108 enum object_type type;
2110 grep_read_lock();
2111 gs->buf = read_object_file(gs->identifier, &type, &gs->size);
2112 grep_read_unlock();
2114 if (!gs->buf)
2115 return error(_("'%s': unable to read %s"),
2116 gs->name,
2117 oid_to_hex(gs->identifier));
2118 return 0;
2121 static int grep_source_load_file(struct grep_source *gs)
2123 const char *filename = gs->identifier;
2124 struct stat st;
2125 char *data;
2126 size_t size;
2127 int i;
2129 if (lstat(filename, &st) < 0) {
2130 err_ret:
2131 if (errno != ENOENT)
2132 error_errno(_("failed to stat '%s'"), filename);
2133 return -1;
2135 if (!S_ISREG(st.st_mode))
2136 return -1;
2137 size = xsize_t(st.st_size);
2138 i = open(filename, O_RDONLY);
2139 if (i < 0)
2140 goto err_ret;
2141 data = xmallocz(size);
2142 if (st.st_size != read_in_full(i, data, size)) {
2143 error_errno(_("'%s': short read"), filename);
2144 close(i);
2145 free(data);
2146 return -1;
2148 close(i);
2150 gs->buf = data;
2151 gs->size = size;
2152 return 0;
2155 static int grep_source_load(struct grep_source *gs)
2157 if (gs->buf)
2158 return 0;
2160 switch (gs->type) {
2161 case GREP_SOURCE_FILE:
2162 return grep_source_load_file(gs);
2163 case GREP_SOURCE_OID:
2164 return grep_source_load_oid(gs);
2165 case GREP_SOURCE_BUF:
2166 return gs->buf ? 0 : -1;
2168 BUG("invalid grep_source type to load");
2171 void grep_source_load_driver(struct grep_source *gs)
2173 if (gs->driver)
2174 return;
2176 grep_attr_lock();
2177 if (gs->path)
2178 gs->driver = userdiff_find_by_path(gs->path);
2179 if (!gs->driver)
2180 gs->driver = userdiff_find_by_name("default");
2181 grep_attr_unlock();
2184 static int grep_source_is_binary(struct grep_source *gs)
2186 grep_source_load_driver(gs);
2187 if (gs->driver->binary != -1)
2188 return gs->driver->binary;
2190 if (!grep_source_load(gs))
2191 return buffer_is_binary(gs->buf, gs->size);
2193 return 0;