grep: remove redundant regflags assignments
[git/git.git] / grep.c
CommitLineData
83b5d2f5 1#include "cache.h"
83b5d2f5 2#include "grep.h"
60ecac98 3#include "userdiff.h"
6bfce93e 4#include "xdiff-interface.h"
335ec3bf
JK
5#include "diff.h"
6#include "diffcore.h"
5c1ebcca 7#include "commit.h"
793dc676 8#include "quote.h"
83b5d2f5 9
07a7d656
JH
10static int grep_source_load(struct grep_source *gs);
11static int grep_source_is_binary(struct grep_source *gs);
12
7687a054
JH
13static struct grep_opt grep_defaults;
14
379642bc
BW
15static void std_output(struct grep_opt *opt, const void *buf, size_t size)
16{
17 fwrite(buf, size, 1, stdout);
18}
19
7687a054
JH
20/*
21 * Initialize the grep_defaults template with hardcoded defaults.
22 * We could let the compiler do this, but without C99 initializers
23 * the code gets unwieldy and unreadable, so...
24 */
25void init_grep_defaults(void)
26{
27 struct grep_opt *opt = &grep_defaults;
918d4e1c
JH
28 static int run_once;
29
30 if (run_once)
31 return;
32 run_once++;
7687a054
JH
33
34 memset(opt, 0, sizeof(*opt));
35 opt->relative = 1;
36 opt->pathname = 1;
37 opt->regflags = REG_NEWLINE;
38 opt->max_depth = -1;
39 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
40 opt->extended_regexp_option = 0;
7ce4fb94
JK
41 color_set(opt->color_context, "");
42 color_set(opt->color_filename, "");
43 color_set(opt->color_function, "");
44 color_set(opt->color_lineno, "");
45 color_set(opt->color_match_context, GIT_COLOR_BOLD_RED);
46 color_set(opt->color_match_selected, GIT_COLOR_BOLD_RED);
47 color_set(opt->color_selected, "");
48 color_set(opt->color_sep, GIT_COLOR_CYAN);
7687a054 49 opt->color = -1;
379642bc 50 opt->output = std_output;
7687a054
JH
51}
52
53static int parse_pattern_type_arg(const char *opt, const char *arg)
54{
55 if (!strcmp(arg, "default"))
56 return GREP_PATTERN_TYPE_UNSPECIFIED;
57 else if (!strcmp(arg, "basic"))
58 return GREP_PATTERN_TYPE_BRE;
59 else if (!strcmp(arg, "extended"))
60 return GREP_PATTERN_TYPE_ERE;
61 else if (!strcmp(arg, "fixed"))
62 return GREP_PATTERN_TYPE_FIXED;
63 else if (!strcmp(arg, "perl"))
64 return GREP_PATTERN_TYPE_PCRE;
65 die("bad %s argument: %s", opt, arg);
66}
67
68/*
69 * Read the configuration file once and store it in
70 * the grep_defaults template.
71 */
72int grep_config(const char *var, const char *value, void *cb)
73{
74 struct grep_opt *opt = &grep_defaults;
75 char *color = NULL;
76
77 if (userdiff_config(var, value) < 0)
78 return -1;
79
80 if (!strcmp(var, "grep.extendedregexp")) {
81 if (git_config_bool(var, value))
82 opt->extended_regexp_option = 1;
83 else
84 opt->extended_regexp_option = 0;
85 return 0;
86 }
87
88 if (!strcmp(var, "grep.patterntype")) {
89 opt->pattern_type_option = parse_pattern_type_arg(var, value);
90 return 0;
91 }
92
93 if (!strcmp(var, "grep.linenumber")) {
94 opt->linenum = git_config_bool(var, value);
95 return 0;
96 }
97
6453f7b3
AS
98 if (!strcmp(var, "grep.fullname")) {
99 opt->relative = !git_config_bool(var, value);
100 return 0;
101 }
102
7687a054
JH
103 if (!strcmp(var, "color.grep"))
104 opt->color = git_config_colorbool(var, value);
105 else if (!strcmp(var, "color.grep.context"))
106 color = opt->color_context;
107 else if (!strcmp(var, "color.grep.filename"))
108 color = opt->color_filename;
109 else if (!strcmp(var, "color.grep.function"))
110 color = opt->color_function;
111 else if (!strcmp(var, "color.grep.linenumber"))
112 color = opt->color_lineno;
79a77109
RS
113 else if (!strcmp(var, "color.grep.matchcontext"))
114 color = opt->color_match_context;
115 else if (!strcmp(var, "color.grep.matchselected"))
116 color = opt->color_match_selected;
7687a054
JH
117 else if (!strcmp(var, "color.grep.selected"))
118 color = opt->color_selected;
119 else if (!strcmp(var, "color.grep.separator"))
120 color = opt->color_sep;
79a77109
RS
121 else if (!strcmp(var, "color.grep.match")) {
122 int rc = 0;
123 if (!value)
124 return config_error_nonbool(var);
bf1f639e
JH
125 rc |= color_parse(value, opt->color_match_context);
126 rc |= color_parse(value, opt->color_match_selected);
79a77109
RS
127 return rc;
128 }
7687a054
JH
129
130 if (color) {
131 if (!value)
132 return config_error_nonbool(var);
f6c5a296 133 return color_parse(value, color);
7687a054
JH
134 }
135 return 0;
136}
137
138/*
139 * Initialize one instance of grep_opt and copy the
140 * default values from the template we read the configuration
141 * information in an earlier call to git_config(grep_config).
142 */
143void grep_init(struct grep_opt *opt, const char *prefix)
144{
145 struct grep_opt *def = &grep_defaults;
146
147 memset(opt, 0, sizeof(*opt));
148 opt->prefix = prefix;
149 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
150 opt->pattern_tail = &opt->pattern_list;
151 opt->header_tail = &opt->header_list;
152
153 opt->color = def->color;
154 opt->extended_regexp_option = def->extended_regexp_option;
155 opt->pattern_type_option = def->pattern_type_option;
156 opt->linenum = def->linenum;
157 opt->max_depth = def->max_depth;
158 opt->pathname = def->pathname;
159 opt->regflags = def->regflags;
160 opt->relative = def->relative;
379642bc 161 opt->output = def->output;
7687a054 162
7ce4fb94
JK
163 color_set(opt->color_context, def->color_context);
164 color_set(opt->color_filename, def->color_filename);
165 color_set(opt->color_function, def->color_function);
166 color_set(opt->color_lineno, def->color_lineno);
167 color_set(opt->color_match_context, def->color_match_context);
168 color_set(opt->color_match_selected, def->color_match_selected);
169 color_set(opt->color_selected, def->color_selected);
170 color_set(opt->color_sep, def->color_sep);
7687a054 171}
07a7d656 172
8465541e 173static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
c5c31d33
JH
174{
175 switch (pattern_type) {
176 case GREP_PATTERN_TYPE_UNSPECIFIED:
177 /* fall through */
178
179 case GREP_PATTERN_TYPE_BRE:
180 opt->fixed = 0;
181 opt->pcre = 0;
c5c31d33
JH
182 break;
183
184 case GREP_PATTERN_TYPE_ERE:
185 opt->fixed = 0;
186 opt->pcre = 0;
187 opt->regflags |= REG_EXTENDED;
188 break;
189
190 case GREP_PATTERN_TYPE_FIXED:
191 opt->fixed = 1;
192 opt->pcre = 0;
c5c31d33
JH
193 break;
194
195 case GREP_PATTERN_TYPE_PCRE:
196 opt->fixed = 0;
197 opt->pcre = 1;
c5c31d33
JH
198 break;
199 }
200}
201
8465541e
JH
202void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
203{
204 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
205 grep_set_pattern_type_option(pattern_type, opt);
206 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
207 grep_set_pattern_type_option(opt->pattern_type_option, opt);
208 else if (opt->extended_regexp_option)
209 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
210}
211
fc456751
RS
212static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
213 const char *origin, int no,
214 enum grep_pat_token t,
215 enum grep_header_field field)
a4d7d2c6
JH
216{
217 struct grep_pat *p = xcalloc(1, sizeof(*p));
526a858a 218 p->pattern = xmemdupz(pat, patlen);
fc456751
RS
219 p->patternlen = patlen;
220 p->origin = origin;
221 p->no = no;
222 p->token = t;
a4d7d2c6 223 p->field = field;
fc456751
RS
224 return p;
225}
226
2b3873ff
RS
227static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
228{
229 **tail = p;
230 *tail = &p->next;
a4d7d2c6 231 p->next = NULL;
526a858a
RS
232
233 switch (p->token) {
234 case GREP_PATTERN: /* atom */
235 case GREP_PATTERN_HEAD:
236 case GREP_PATTERN_BODY:
237 for (;;) {
238 struct grep_pat *new_pat;
239 size_t len = 0;
240 char *cp = p->pattern + p->patternlen, *nl = NULL;
241 while (++len <= p->patternlen) {
242 if (*(--cp) == '\n') {
243 nl = cp;
244 break;
245 }
246 }
247 if (!nl)
248 break;
249 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
250 p->no, p->token, p->field);
251 new_pat->next = p->next;
252 if (!p->next)
253 *tail = &new_pat->next;
254 p->next = new_pat;
255 *nl = '\0';
256 p->patternlen -= len;
257 }
258 break;
259 default:
260 break;
261 }
2b3873ff
RS
262}
263
fc456751
RS
264void append_header_grep_pattern(struct grep_opt *opt,
265 enum grep_header_field field, const char *pat)
266{
267 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
268 GREP_PATTERN_HEAD, field);
baa6378f
JH
269 if (field == GREP_HEADER_REFLOG)
270 opt->use_reflog_filter = 1;
2b3873ff 271 do_append_grep_pat(&opt->header_tail, p);
a4d7d2c6
JH
272}
273
83b5d2f5
JH
274void append_grep_pattern(struct grep_opt *opt, const char *pat,
275 const char *origin, int no, enum grep_pat_token t)
ed40a095
RS
276{
277 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
278}
279
280void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
281 const char *origin, int no, enum grep_pat_token t)
83b5d2f5 282{
fc456751 283 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
2b3873ff 284 do_append_grep_pat(&opt->pattern_tail, p);
83b5d2f5
JH
285}
286
5b594f45
FK
287struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
288{
289 struct grep_pat *pat;
290 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
291 *ret = *opt;
292
293 ret->pattern_list = NULL;
294 ret->pattern_tail = &ret->pattern_list;
295
296 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
297 {
298 if(pat->token == GREP_PATTERN_HEAD)
299 append_header_grep_pattern(ret, pat->field,
300 pat->pattern);
301 else
ed40a095
RS
302 append_grep_pat(ret, pat->pattern, pat->patternlen,
303 pat->origin, pat->no, pat->token);
5b594f45
FK
304 }
305
306 return ret;
307}
308
a30c148a
MK
309static NORETURN void compile_regexp_failed(const struct grep_pat *p,
310 const char *error)
311{
312 char where[1024];
313
314 if (p->no)
19bdd3e7 315 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
a30c148a 316 else if (p->origin)
19bdd3e7 317 xsnprintf(where, sizeof(where), "%s, ", p->origin);
a30c148a
MK
318 else
319 where[0] = 0;
320
321 die("%s'%s': %s", where, p->pattern, error);
322}
323
63e7e9d8
MK
324#ifdef USE_LIBPCRE
325static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
326{
327 const char *error;
328 int erroffset;
fba4f125 329 int options = PCRE_MULTILINE;
63e7e9d8 330
9d9babb8
NTND
331 if (opt->ignore_case) {
332 if (has_non_ascii(p->pattern))
333 p->pcre_tables = pcre_maketables();
63e7e9d8 334 options |= PCRE_CASELESS;
9d9babb8 335 }
18547aac
NTND
336 if (is_utf8_locale() && has_non_ascii(p->pattern))
337 options |= PCRE_UTF8;
63e7e9d8
MK
338
339 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
9d9babb8 340 p->pcre_tables);
63e7e9d8
MK
341 if (!p->pcre_regexp)
342 compile_regexp_failed(p, error);
343
344 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
345 if (!p->pcre_extra_info && error)
346 die("%s", error);
347}
348
349static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
350 regmatch_t *match, int eflags)
351{
352 int ovector[30], ret, flags = 0;
353
354 if (eflags & REG_NOTBOL)
355 flags |= PCRE_NOTBOL;
356
357 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
358 0, flags, ovector, ARRAY_SIZE(ovector));
359 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
360 die("pcre_exec failed with error code %d", ret);
361 if (ret > 0) {
362 ret = 0;
363 match->rm_so = ovector[0];
364 match->rm_eo = ovector[1];
365 }
366
367 return ret;
368}
369
370static void free_pcre_regexp(struct grep_pat *p)
371{
372 pcre_free(p->pcre_regexp);
373 pcre_free(p->pcre_extra_info);
9d9babb8 374 pcre_free((void *)p->pcre_tables);
63e7e9d8
MK
375}
376#else /* !USE_LIBPCRE */
377static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
378{
379 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
380}
381
382static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
383 regmatch_t *match, int eflags)
384{
385 return 1;
386}
387
388static void free_pcre_regexp(struct grep_pat *p)
389{
390}
391#endif /* !USE_LIBPCRE */
392
9eceddee
FK
393static int is_fixed(const char *s, size_t len)
394{
395 size_t i;
396
397 /* regcomp cannot accept patterns with NULs so we
398 * consider any pattern containing a NUL fixed.
399 */
400 if (memchr(s, 0, len))
401 return 1;
402
403 for (i = 0; i < len; i++) {
404 if (is_regex_special(s[i]))
405 return 0;
406 }
407
408 return 1;
409}
410
793dc676
NTND
411static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
412{
413 struct strbuf sb = STRBUF_INIT;
414 int err;
e0b9f8ae 415 int regflags = opt->regflags;
793dc676
NTND
416
417 basic_regex_quote_buf(&sb, p->pattern);
793dc676
NTND
418 if (opt->ignore_case)
419 regflags |= REG_ICASE;
420 err = regcomp(&p->regexp, sb.buf, regflags);
421 if (opt->debug)
422 fprintf(stderr, "fixed %s\n", sb.buf);
423 strbuf_release(&sb);
424 if (err) {
425 char errbuf[1024];
426 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
427 regfree(&p->regexp);
428 compile_regexp_failed(p, errbuf);
429 }
430}
431
83b5d2f5
JH
432static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
433{
5c1ebcca 434 int icase, ascii_only;
c822255c
RS
435 int err;
436
d7eb527d 437 p->word_regexp = opt->word_regexp;
5183bf67 438 p->ignore_case = opt->ignore_case;
5c1ebcca
NTND
439 icase = opt->regflags & REG_ICASE || p->ignore_case;
440 ascii_only = !has_non_ascii(p->pattern);
d7eb527d 441
793dc676
NTND
442 /*
443 * Even when -F (fixed) asks us to do a non-regexp search, we
444 * may not be able to correctly case-fold when -i
445 * (ignore-case) is asked (in which case, we'll synthesize a
446 * regexp to match the pattern that matches regexp special
447 * characters literally, while ignoring case differences). On
448 * the other hand, even without -F, if the pattern does not
449 * have any regexp special characters and there is no need for
450 * case-folding search, we can internally turn it into a
451 * simple string match using kws. p->fixed tells us if we
452 * want to use kws.
453 */
9eceddee 454 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
793dc676 455 p->fixed = !icase || ascii_only;
9eceddee
FK
456 else
457 p->fixed = 0;
458
459 if (p->fixed) {
695f95ba 460 p->kws = kwsalloc(icase ? tolower_trans_tbl : NULL);
9eceddee
FK
461 kwsincr(p->kws, p->pattern, p->patternlen);
462 kwsprep(p->kws);
c822255c 463 return;
793dc676
NTND
464 } else if (opt->fixed) {
465 /*
466 * We come here when the pattern has the non-ascii
467 * characters we cannot case-fold, and asked to
468 * ignore-case.
469 */
470 compile_fixed_regexp(p, opt);
471 return;
9eceddee 472 }
c822255c 473
63e7e9d8
MK
474 if (opt->pcre) {
475 compile_pcre_regexp(p, opt);
476 return;
477 }
478
c822255c 479 err = regcomp(&p->regexp, p->pattern, opt->regflags);
83b5d2f5
JH
480 if (err) {
481 char errbuf[1024];
83b5d2f5
JH
482 regerror(err, &p->regexp, errbuf, 1024);
483 regfree(&p->regexp);
a30c148a 484 compile_regexp_failed(p, errbuf);
83b5d2f5
JH
485 }
486}
487
0ab7befa 488static struct grep_expr *compile_pattern_or(struct grep_pat **);
83b5d2f5
JH
489static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
490{
491 struct grep_pat *p;
492 struct grep_expr *x;
493
494 p = *list;
c922b01f
LT
495 if (!p)
496 return NULL;
83b5d2f5
JH
497 switch (p->token) {
498 case GREP_PATTERN: /* atom */
480c1ca6
JH
499 case GREP_PATTERN_HEAD:
500 case GREP_PATTERN_BODY:
83b5d2f5
JH
501 x = xcalloc(1, sizeof (struct grep_expr));
502 x->node = GREP_NODE_ATOM;
503 x->u.atom = p;
504 *list = p->next;
505 return x;
506 case GREP_OPEN_PAREN:
507 *list = p->next;
0ab7befa 508 x = compile_pattern_or(list);
83b5d2f5
JH
509 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
510 die("unmatched parenthesis");
511 *list = (*list)->next;
512 return x;
513 default:
514 return NULL;
515 }
516}
517
518static struct grep_expr *compile_pattern_not(struct grep_pat **list)
519{
520 struct grep_pat *p;
521 struct grep_expr *x;
522
523 p = *list;
c922b01f
LT
524 if (!p)
525 return NULL;
83b5d2f5
JH
526 switch (p->token) {
527 case GREP_NOT:
528 if (!p->next)
529 die("--not not followed by pattern expression");
530 *list = p->next;
531 x = xcalloc(1, sizeof (struct grep_expr));
532 x->node = GREP_NODE_NOT;
533 x->u.unary = compile_pattern_not(list);
534 if (!x->u.unary)
535 die("--not followed by non pattern expression");
536 return x;
537 default:
538 return compile_pattern_atom(list);
539 }
540}
541
542static struct grep_expr *compile_pattern_and(struct grep_pat **list)
543{
544 struct grep_pat *p;
545 struct grep_expr *x, *y, *z;
546
547 x = compile_pattern_not(list);
548 p = *list;
549 if (p && p->token == GREP_AND) {
550 if (!p->next)
551 die("--and not followed by pattern expression");
552 *list = p->next;
553 y = compile_pattern_and(list);
554 if (!y)
555 die("--and not followed by pattern expression");
556 z = xcalloc(1, sizeof (struct grep_expr));
557 z->node = GREP_NODE_AND;
558 z->u.binary.left = x;
559 z->u.binary.right = y;
560 return z;
561 }
562 return x;
563}
564
565static struct grep_expr *compile_pattern_or(struct grep_pat **list)
566{
567 struct grep_pat *p;
568 struct grep_expr *x, *y, *z;
569
570 x = compile_pattern_and(list);
571 p = *list;
572 if (x && p && p->token != GREP_CLOSE_PAREN) {
573 y = compile_pattern_or(list);
574 if (!y)
575 die("not a pattern expression %s", p->pattern);
576 z = xcalloc(1, sizeof (struct grep_expr));
577 z->node = GREP_NODE_OR;
578 z->u.binary.left = x;
579 z->u.binary.right = y;
580 return z;
581 }
582 return x;
583}
584
585static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
586{
587 return compile_pattern_or(list);
588}
589
17bf35a3
JH
590static void indent(int in)
591{
592 while (in-- > 0)
593 fputc(' ', stderr);
594}
595
596static void dump_grep_pat(struct grep_pat *p)
597{
598 switch (p->token) {
599 case GREP_AND: fprintf(stderr, "*and*"); break;
600 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
601 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
602 case GREP_NOT: fprintf(stderr, "*not*"); break;
603 case GREP_OR: fprintf(stderr, "*or*"); break;
604
605 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
606 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
607 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
608 }
609
610 switch (p->token) {
611 default: break;
612 case GREP_PATTERN_HEAD:
613 fprintf(stderr, "<head %d>", p->field); break;
614 case GREP_PATTERN_BODY:
615 fprintf(stderr, "<body>"); break;
616 }
617 switch (p->token) {
618 default: break;
619 case GREP_PATTERN_HEAD:
620 case GREP_PATTERN_BODY:
621 case GREP_PATTERN:
622 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
623 break;
624 }
625 fputc('\n', stderr);
626}
627
628static void dump_grep_expression_1(struct grep_expr *x, int in)
629{
630 indent(in);
631 switch (x->node) {
632 case GREP_NODE_TRUE:
633 fprintf(stderr, "true\n");
634 break;
635 case GREP_NODE_ATOM:
636 dump_grep_pat(x->u.atom);
637 break;
638 case GREP_NODE_NOT:
639 fprintf(stderr, "(not\n");
640 dump_grep_expression_1(x->u.unary, in+1);
641 indent(in);
642 fprintf(stderr, ")\n");
643 break;
644 case GREP_NODE_AND:
645 fprintf(stderr, "(and\n");
646 dump_grep_expression_1(x->u.binary.left, in+1);
647 dump_grep_expression_1(x->u.binary.right, in+1);
648 indent(in);
649 fprintf(stderr, ")\n");
650 break;
651 case GREP_NODE_OR:
652 fprintf(stderr, "(or\n");
653 dump_grep_expression_1(x->u.binary.left, in+1);
654 dump_grep_expression_1(x->u.binary.right, in+1);
655 indent(in);
656 fprintf(stderr, ")\n");
657 break;
658 }
659}
660
07a7d656 661static void dump_grep_expression(struct grep_opt *opt)
17bf35a3
JH
662{
663 struct grep_expr *x = opt->pattern_expression;
664
665 if (opt->all_match)
666 fprintf(stderr, "[all-match]\n");
667 dump_grep_expression_1(x, 0);
668 fflush(NULL);
669}
670
5aaeb733
JH
671static struct grep_expr *grep_true_expr(void)
672{
673 struct grep_expr *z = xcalloc(1, sizeof(*z));
674 z->node = GREP_NODE_TRUE;
675 return z;
676}
677
678static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
679{
680 struct grep_expr *z = xcalloc(1, sizeof(*z));
681 z->node = GREP_NODE_OR;
682 z->u.binary.left = left;
683 z->u.binary.right = right;
684 return z;
685}
686
95ce9ce2 687static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
83b5d2f5
JH
688{
689 struct grep_pat *p;
95ce9ce2 690 struct grep_expr *header_expr;
5aaeb733
JH
691 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
692 enum grep_header_field fld;
83b5d2f5 693
95ce9ce2
JH
694 if (!opt->header_list)
695 return NULL;
2385f246 696
95ce9ce2
JH
697 for (p = opt->header_list; p; p = p->next) {
698 if (p->token != GREP_PATTERN_HEAD)
ef1177d1 699 die("BUG: a non-header pattern in grep header list.");
3ce3ffb8
AP
700 if (p->field < GREP_HEADER_FIELD_MIN ||
701 GREP_HEADER_FIELD_MAX <= p->field)
ef1177d1 702 die("BUG: unknown header field %d", p->field);
95ce9ce2 703 compile_regexp(p, opt);
80235ba7 704 }
5aaeb733
JH
705
706 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
707 header_group[fld] = NULL;
708
709 for (p = opt->header_list; p; p = p->next) {
710 struct grep_expr *h;
711 struct grep_pat *pp = p;
712
713 h = compile_pattern_atom(&pp);
714 if (!h || pp != p->next)
ef1177d1 715 die("BUG: malformed header expr");
5aaeb733
JH
716 if (!header_group[p->field]) {
717 header_group[p->field] = h;
718 continue;
719 }
720 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
721 }
722
723 header_expr = NULL;
724
725 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
726 if (!header_group[fld])
727 continue;
728 if (!header_expr)
729 header_expr = grep_true_expr();
730 header_expr = grep_or_expr(header_group[fld], header_expr);
731 }
95ce9ce2
JH
732 return header_expr;
733}
734
13e4fc7e
JH
735static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
736{
737 struct grep_expr *z = x;
738
739 while (x) {
740 assert(x->node == GREP_NODE_OR);
741 if (x->u.binary.right &&
742 x->u.binary.right->node == GREP_NODE_TRUE) {
743 x->u.binary.right = y;
744 break;
745 }
746 x = x->u.binary.right;
747 }
748 return z;
749}
750
17bf35a3 751static void compile_grep_patterns_real(struct grep_opt *opt)
95ce9ce2
JH
752{
753 struct grep_pat *p;
754 struct grep_expr *header_expr = prep_header_patterns(opt);
0ab7befa 755
83b5d2f5 756 for (p = opt->pattern_list; p; p = p->next) {
480c1ca6
JH
757 switch (p->token) {
758 case GREP_PATTERN: /* atom */
759 case GREP_PATTERN_HEAD:
760 case GREP_PATTERN_BODY:
c822255c 761 compile_regexp(p, opt);
480c1ca6
JH
762 break;
763 default:
83b5d2f5 764 opt->extended = 1;
480c1ca6
JH
765 break;
766 }
83b5d2f5
JH
767 }
768
80235ba7
JH
769 if (opt->all_match || header_expr)
770 opt->extended = 1;
17bf35a3 771 else if (!opt->extended && !opt->debug)
83b5d2f5
JH
772 return;
773
83b5d2f5 774 p = opt->pattern_list;
ba150a3f
MB
775 if (p)
776 opt->pattern_expression = compile_pattern_expr(&p);
83b5d2f5
JH
777 if (p)
778 die("incomplete pattern expression: %s", p->pattern);
80235ba7
JH
779
780 if (!header_expr)
781 return;
782
5aaeb733 783 if (!opt->pattern_expression)
80235ba7 784 opt->pattern_expression = header_expr;
13e4fc7e
JH
785 else if (opt->all_match)
786 opt->pattern_expression = grep_splice_or(header_expr,
787 opt->pattern_expression);
5aaeb733
JH
788 else
789 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
790 header_expr);
80235ba7 791 opt->all_match = 1;
83b5d2f5
JH
792}
793
17bf35a3
JH
794void compile_grep_patterns(struct grep_opt *opt)
795{
796 compile_grep_patterns_real(opt);
797 if (opt->debug)
798 dump_grep_expression(opt);
799}
800
b48fb5b6
JH
801static void free_pattern_expr(struct grep_expr *x)
802{
803 switch (x->node) {
5aaeb733 804 case GREP_NODE_TRUE:
b48fb5b6
JH
805 case GREP_NODE_ATOM:
806 break;
807 case GREP_NODE_NOT:
808 free_pattern_expr(x->u.unary);
809 break;
810 case GREP_NODE_AND:
811 case GREP_NODE_OR:
812 free_pattern_expr(x->u.binary.left);
813 free_pattern_expr(x->u.binary.right);
814 break;
815 }
816 free(x);
817}
818
819void free_grep_patterns(struct grep_opt *opt)
820{
821 struct grep_pat *p, *n;
822
823 for (p = opt->pattern_list; p; p = n) {
824 n = p->next;
825 switch (p->token) {
826 case GREP_PATTERN: /* atom */
827 case GREP_PATTERN_HEAD:
828 case GREP_PATTERN_BODY:
9eceddee
FK
829 if (p->kws)
830 kwsfree(p->kws);
831 else if (p->pcre_regexp)
63e7e9d8
MK
832 free_pcre_regexp(p);
833 else
834 regfree(&p->regexp);
526a858a 835 free(p->pattern);
b48fb5b6
JH
836 break;
837 default:
838 break;
839 }
840 free(p);
841 }
842
843 if (!opt->extended)
844 return;
845 free_pattern_expr(opt->pattern_expression);
846}
847
83b5d2f5
JH
848static char *end_of_line(char *cp, unsigned long *left)
849{
850 unsigned long l = *left;
851 while (l && *cp != '\n') {
852 l--;
853 cp++;
854 }
855 *left = l;
856 return cp;
857}
858
859static int word_char(char ch)
860{
861 return isalnum(ch) || ch == '_';
862}
863
55f638bd
ML
864static void output_color(struct grep_opt *opt, const void *data, size_t size,
865 const char *color)
866{
daa0c3d9 867 if (want_color(opt->color) && color && color[0]) {
55f638bd
ML
868 opt->output(opt, color, strlen(color));
869 opt->output(opt, data, size);
870 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
871 } else
872 opt->output(opt, data, size);
873}
874
875static void output_sep(struct grep_opt *opt, char sign)
876{
877 if (opt->null_following_name)
878 opt->output(opt, "\0", 1);
879 else
880 output_color(opt, &sign, 1, opt->color_sep);
881}
882
83caecca
RZ
883static void show_name(struct grep_opt *opt, const char *name)
884{
55f638bd 885 output_color(opt, name, strlen(name), opt->color_filename);
5b594f45 886 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
83caecca
RZ
887}
888
ed40a095
RS
889static int fixmatch(struct grep_pat *p, char *line, char *eol,
890 regmatch_t *match)
83b5d2f5 891{
9eceddee
FK
892 struct kwsmatch kwsm;
893 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
894 if (offset == -1) {
83b5d2f5
JH
895 match->rm_so = match->rm_eo = -1;
896 return REG_NOMATCH;
9eceddee
FK
897 } else {
898 match->rm_so = offset;
899 match->rm_eo = match->rm_so + kwsm.size[0];
83b5d2f5
JH
900 return 0;
901 }
902}
903
97e77784
MK
904static int patmatch(struct grep_pat *p, char *line, char *eol,
905 regmatch_t *match, int eflags)
906{
907 int hit;
908
909 if (p->fixed)
910 hit = !fixmatch(p, line, eol, match);
63e7e9d8
MK
911 else if (p->pcre_regexp)
912 hit = !pcrematch(p, line, eol, match, eflags);
97e77784 913 else
b7d36ffc
JS
914 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
915 eflags);
97e77784
MK
916
917 return hit;
918}
919
a4d7d2c6
JH
920static int strip_timestamp(char *bol, char **eol_p)
921{
922 char *eol = *eol_p;
923 int ch;
924
925 while (bol < --eol) {
926 if (*eol != '>')
927 continue;
928 *eol_p = ++eol;
929 ch = *eol;
930 *eol = '\0';
931 return ch;
932 }
933 return 0;
934}
935
936static struct {
937 const char *field;
938 size_t len;
939} header_field[] = {
940 { "author ", 7 },
941 { "committer ", 10 },
72fd13f7 942 { "reflog ", 7 },
a4d7d2c6
JH
943};
944
d7eb527d 945static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
79212772
RS
946 enum grep_context ctx,
947 regmatch_t *pmatch, int eflags)
83b5d2f5
JH
948{
949 int hit = 0;
a4d7d2c6 950 int saved_ch = 0;
e701fadb 951 const char *start = bol;
83b5d2f5 952
480c1ca6
JH
953 if ((p->token != GREP_PATTERN) &&
954 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
955 return 0;
956
a4d7d2c6
JH
957 if (p->token == GREP_PATTERN_HEAD) {
958 const char *field;
959 size_t len;
960 assert(p->field < ARRAY_SIZE(header_field));
961 field = header_field[p->field].field;
962 len = header_field[p->field].len;
963 if (strncmp(bol, field, len))
964 return 0;
965 bol += len;
ad4813b3
NTND
966 switch (p->field) {
967 case GREP_HEADER_AUTHOR:
968 case GREP_HEADER_COMMITTER:
969 saved_ch = strip_timestamp(bol, &eol);
970 break;
971 default:
972 break;
973 }
a4d7d2c6
JH
974 }
975
83b5d2f5 976 again:
97e77784 977 hit = patmatch(p, bol, eol, pmatch, eflags);
83b5d2f5 978
d7eb527d 979 if (hit && p->word_regexp) {
83b5d2f5 980 if ((pmatch[0].rm_so < 0) ||
84201eae 981 (eol - bol) < pmatch[0].rm_so ||
83b5d2f5
JH
982 (pmatch[0].rm_eo < 0) ||
983 (eol - bol) < pmatch[0].rm_eo)
984 die("regexp returned nonsense");
985
986 /* Match beginning must be either beginning of the
987 * line, or at word boundary (i.e. the last char must
988 * not be a word char). Similarly, match end must be
989 * either end of the line, or at word boundary
990 * (i.e. the next char must not be a word char).
991 */
fb62eb7f 992 if ( ((pmatch[0].rm_so == 0) ||
83b5d2f5
JH
993 !word_char(bol[pmatch[0].rm_so-1])) &&
994 ((pmatch[0].rm_eo == (eol-bol)) ||
995 !word_char(bol[pmatch[0].rm_eo])) )
996 ;
997 else
998 hit = 0;
999
84201eae
RS
1000 /* Words consist of at least one character. */
1001 if (pmatch->rm_so == pmatch->rm_eo)
1002 hit = 0;
1003
83b5d2f5
JH
1004 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1005 /* There could be more than one match on the
1006 * line, and the first match might not be
1007 * strict word match. But later ones could be!
fb62eb7f
RS
1008 * Forward to the next possible start, i.e. the
1009 * next position following a non-word char.
83b5d2f5
JH
1010 */
1011 bol = pmatch[0].rm_so + bol + 1;
fb62eb7f
RS
1012 while (word_char(bol[-1]) && bol < eol)
1013 bol++;
dbb6a4ad 1014 eflags |= REG_NOTBOL;
fb62eb7f
RS
1015 if (bol < eol)
1016 goto again;
83b5d2f5
JH
1017 }
1018 }
a4d7d2c6
JH
1019 if (p->token == GREP_PATTERN_HEAD && saved_ch)
1020 *eol = saved_ch;
e701fadb
RS
1021 if (hit) {
1022 pmatch[0].rm_so += bol - start;
1023 pmatch[0].rm_eo += bol - start;
1024 }
83b5d2f5
JH
1025 return hit;
1026}
1027
d7eb527d
RS
1028static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
1029 enum grep_context ctx, int collect_hits)
83b5d2f5 1030{
0ab7befa 1031 int h = 0;
79212772 1032 regmatch_t match;
0ab7befa 1033
c922b01f
LT
1034 if (!x)
1035 die("Not a valid grep expression");
83b5d2f5 1036 switch (x->node) {
5aaeb733
JH
1037 case GREP_NODE_TRUE:
1038 h = 1;
1039 break;
83b5d2f5 1040 case GREP_NODE_ATOM:
79212772 1041 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
83b5d2f5
JH
1042 break;
1043 case GREP_NODE_NOT:
d7eb527d 1044 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
0ab7befa 1045 break;
83b5d2f5 1046 case GREP_NODE_AND:
d7eb527d 1047 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
252d560d 1048 return 0;
d7eb527d 1049 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
0ab7befa 1050 break;
83b5d2f5 1051 case GREP_NODE_OR:
0ab7befa 1052 if (!collect_hits)
d7eb527d 1053 return (match_expr_eval(x->u.binary.left,
0ab7befa 1054 bol, eol, ctx, 0) ||
d7eb527d 1055 match_expr_eval(x->u.binary.right,
0ab7befa 1056 bol, eol, ctx, 0));
d7eb527d 1057 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
0ab7befa 1058 x->u.binary.left->hit |= h;
d7eb527d 1059 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
0ab7befa
JH
1060 break;
1061 default:
d7530708 1062 die("Unexpected node type (internal error) %d", x->node);
83b5d2f5 1063 }
0ab7befa
JH
1064 if (collect_hits)
1065 x->hit |= h;
1066 return h;
83b5d2f5
JH
1067}
1068
480c1ca6 1069static int match_expr(struct grep_opt *opt, char *bol, char *eol,
0ab7befa 1070 enum grep_context ctx, int collect_hits)
83b5d2f5
JH
1071{
1072 struct grep_expr *x = opt->pattern_expression;
d7eb527d 1073 return match_expr_eval(x, bol, eol, ctx, collect_hits);
83b5d2f5
JH
1074}
1075
480c1ca6 1076static int match_line(struct grep_opt *opt, char *bol, char *eol,
0ab7befa 1077 enum grep_context ctx, int collect_hits)
83b5d2f5
JH
1078{
1079 struct grep_pat *p;
79212772
RS
1080 regmatch_t match;
1081
83b5d2f5 1082 if (opt->extended)
0ab7befa
JH
1083 return match_expr(opt, bol, eol, ctx, collect_hits);
1084
1085 /* we do not call with collect_hits without being extended */
83b5d2f5 1086 for (p = opt->pattern_list; p; p = p->next) {
79212772 1087 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
83b5d2f5
JH
1088 return 1;
1089 }
1090 return 0;
1091}
1092
7e8f59d5
RS
1093static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1094 enum grep_context ctx,
1095 regmatch_t *pmatch, int eflags)
1096{
1097 regmatch_t match;
1098
1099 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1100 return 0;
1101 if (match.rm_so < 0 || match.rm_eo < 0)
1102 return 0;
1103 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1104 if (match.rm_so > pmatch->rm_so)
1105 return 1;
1106 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1107 return 1;
1108 }
1109 pmatch->rm_so = match.rm_so;
1110 pmatch->rm_eo = match.rm_eo;
1111 return 1;
1112}
1113
1114static int next_match(struct grep_opt *opt, char *bol, char *eol,
1115 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1116{
1117 struct grep_pat *p;
1118 int hit = 0;
1119
1120 pmatch->rm_so = pmatch->rm_eo = -1;
1121 if (bol < eol) {
1122 for (p = opt->pattern_list; p; p = p->next) {
1123 switch (p->token) {
1124 case GREP_PATTERN: /* atom */
1125 case GREP_PATTERN_HEAD:
1126 case GREP_PATTERN_BODY:
1127 hit |= match_next_pattern(p, bol, eol, ctx,
1128 pmatch, eflags);
1129 break;
1130 default:
1131 break;
1132 }
1133 }
1134 }
1135 return hit;
1136}
1137
1138static void show_line(struct grep_opt *opt, char *bol, char *eol,
1139 const char *name, unsigned lno, char sign)
1140{
1141 int rest = eol - bol;
79a77109 1142 const char *match_color, *line_color = NULL;
7e8f59d5 1143
a8f0e764
RS
1144 if (opt->file_break && opt->last_shown == 0) {
1145 if (opt->show_hunk_mark)
1146 opt->output(opt, "\n", 1);
ba8ea749 1147 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
046802d0 1148 if (opt->last_shown == 0) {
55f638bd
ML
1149 if (opt->show_hunk_mark) {
1150 output_color(opt, "--", 2, opt->color_sep);
1151 opt->output(opt, "\n", 1);
07b838f0 1152 }
55f638bd
ML
1153 } else if (lno > opt->last_shown + 1) {
1154 output_color(opt, "--", 2, opt->color_sep);
1155 opt->output(opt, "\n", 1);
1156 }
5dd06d38 1157 }
1d84f72e
RS
1158 if (opt->heading && opt->last_shown == 0) {
1159 output_color(opt, name, strlen(name), opt->color_filename);
1160 opt->output(opt, "\n", 1);
1161 }
5dd06d38
RS
1162 opt->last_shown = lno;
1163
1d84f72e 1164 if (!opt->heading && opt->pathname) {
55f638bd
ML
1165 output_color(opt, name, strlen(name), opt->color_filename);
1166 output_sep(opt, sign);
5b594f45
FK
1167 }
1168 if (opt->linenum) {
1169 char buf[32];
1a168e5c 1170 xsnprintf(buf, sizeof(buf), "%d", lno);
55f638bd
ML
1171 output_color(opt, buf, strlen(buf), opt->color_lineno);
1172 output_sep(opt, sign);
5b594f45 1173 }
7e8f59d5
RS
1174 if (opt->color) {
1175 regmatch_t match;
1176 enum grep_context ctx = GREP_CONTEXT_BODY;
1177 int ch = *eol;
1178 int eflags = 0;
1179
79a77109
RS
1180 if (sign == ':')
1181 match_color = opt->color_match_selected;
1182 else
1183 match_color = opt->color_match_context;
00588bb5
ML
1184 if (sign == ':')
1185 line_color = opt->color_selected;
1186 else if (sign == '-')
1187 line_color = opt->color_context;
1188 else if (sign == '=')
1189 line_color = opt->color_function;
7e8f59d5
RS
1190 *eol = '\0';
1191 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1f5b9cc4
RS
1192 if (match.rm_so == match.rm_eo)
1193 break;
5b594f45 1194
00588bb5 1195 output_color(opt, bol, match.rm_so, line_color);
55f638bd 1196 output_color(opt, bol + match.rm_so,
79a77109 1197 match.rm_eo - match.rm_so, match_color);
7e8f59d5
RS
1198 bol += match.rm_eo;
1199 rest -= match.rm_eo;
1200 eflags = REG_NOTBOL;
1201 }
1202 *eol = ch;
1203 }
00588bb5 1204 output_color(opt, bol, rest, line_color);
5b594f45 1205 opt->output(opt, "\n", 1);
7e8f59d5
RS
1206}
1207
0579f91d 1208#ifndef NO_PTHREADS
78db6ea9
JK
1209int grep_use_locks;
1210
0579f91d
TR
1211/*
1212 * This lock protects access to the gitattributes machinery, which is
1213 * not thread-safe.
1214 */
1215pthread_mutex_t grep_attr_mutex;
1216
78db6ea9 1217static inline void grep_attr_lock(void)
0579f91d 1218{
78db6ea9 1219 if (grep_use_locks)
0579f91d
TR
1220 pthread_mutex_lock(&grep_attr_mutex);
1221}
1222
78db6ea9 1223static inline void grep_attr_unlock(void)
0579f91d 1224{
78db6ea9 1225 if (grep_use_locks)
0579f91d
TR
1226 pthread_mutex_unlock(&grep_attr_mutex);
1227}
b3aeb285
JK
1228
1229/*
1230 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1231 */
1232pthread_mutex_t grep_read_mutex;
1233
0579f91d 1234#else
78db6ea9
JK
1235#define grep_attr_lock()
1236#define grep_attr_unlock()
0579f91d
TR
1237#endif
1238
e1327023 1239static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
2944e4e6 1240{
60ecac98 1241 xdemitconf_t *xecfg = opt->priv;
0579f91d 1242 if (xecfg && !xecfg->find_func) {
94ad9d9e
JK
1243 grep_source_load_driver(gs);
1244 if (gs->driver->funcname.pattern) {
1245 const struct userdiff_funcname *pe = &gs->driver->funcname;
0579f91d
TR
1246 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1247 } else {
1248 xecfg = opt->priv = NULL;
1249 }
1250 }
1251
1252 if (xecfg) {
60ecac98
RS
1253 char buf[1];
1254 return xecfg->find_func(bol, eol - bol, buf, 1,
1255 xecfg->find_func_priv) >= 0;
1256 }
1257
2944e4e6
RS
1258 if (bol == eol)
1259 return 0;
1260 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1261 return 1;
1262 return 0;
1263}
1264
e1327023
JK
1265static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1266 char *bol, unsigned lno)
2944e4e6 1267{
e1327023 1268 while (bol > gs->buf) {
2944e4e6
RS
1269 char *eol = --bol;
1270
e1327023 1271 while (bol > gs->buf && bol[-1] != '\n')
2944e4e6
RS
1272 bol--;
1273 lno--;
1274
1275 if (lno <= opt->last_shown)
1276 break;
1277
e1327023
JK
1278 if (match_funcname(opt, gs, bol, eol)) {
1279 show_line(opt, bol, eol, gs->name, lno, '=');
2944e4e6
RS
1280 break;
1281 }
1282 }
1283}
1284
e1327023 1285static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
ba8ea749 1286 char *bol, char *end, unsigned lno)
49de3216 1287{
2944e4e6 1288 unsigned cur = lno, from = 1, funcname_lno = 0;
ba8ea749
RS
1289 int funcname_needed = !!opt->funcname;
1290
e1327023 1291 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
ba8ea749 1292 funcname_needed = 2;
49de3216
RS
1293
1294 if (opt->pre_context < lno)
1295 from = lno - opt->pre_context;
1296 if (from <= opt->last_shown)
1297 from = opt->last_shown + 1;
1298
1299 /* Rewind. */
e1327023 1300 while (bol > gs->buf &&
ba8ea749 1301 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
2944e4e6
RS
1302 char *eol = --bol;
1303
e1327023 1304 while (bol > gs->buf && bol[-1] != '\n')
49de3216
RS
1305 bol--;
1306 cur--;
e1327023 1307 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
2944e4e6
RS
1308 funcname_lno = cur;
1309 funcname_needed = 0;
1310 }
49de3216
RS
1311 }
1312
2944e4e6
RS
1313 /* We need to look even further back to find a function signature. */
1314 if (opt->funcname && funcname_needed)
e1327023 1315 show_funcname_line(opt, gs, bol, cur);
2944e4e6 1316
49de3216
RS
1317 /* Back forward. */
1318 while (cur < lno) {
2944e4e6 1319 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
49de3216
RS
1320
1321 while (*eol != '\n')
1322 eol++;
e1327023 1323 show_line(opt, bol, eol, gs->name, cur, sign);
49de3216
RS
1324 bol = eol + 1;
1325 cur++;
1326 }
1327}
1328
a26345b6
JH
1329static int should_lookahead(struct grep_opt *opt)
1330{
1331 struct grep_pat *p;
1332
1333 if (opt->extended)
1334 return 0; /* punt for too complex stuff */
1335 if (opt->invert)
1336 return 0;
1337 for (p = opt->pattern_list; p; p = p->next) {
1338 if (p->token != GREP_PATTERN)
1339 return 0; /* punt for "header only" and stuff */
1340 }
1341 return 1;
1342}
1343
1344static int look_ahead(struct grep_opt *opt,
1345 unsigned long *left_p,
1346 unsigned *lno_p,
1347 char **bol_p)
1348{
1349 unsigned lno = *lno_p;
1350 char *bol = *bol_p;
1351 struct grep_pat *p;
1352 char *sp, *last_bol;
1353 regoff_t earliest = -1;
1354
1355 for (p = opt->pattern_list; p; p = p->next) {
1356 int hit;
1357 regmatch_t m;
1358
97e77784 1359 hit = patmatch(p, bol, bol + *left_p, &m, 0);
a26345b6
JH
1360 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1361 continue;
1362 if (earliest < 0 || m.rm_so < earliest)
1363 earliest = m.rm_so;
1364 }
1365
1366 if (earliest < 0) {
1367 *bol_p = bol + *left_p;
1368 *left_p = 0;
1369 return 1;
1370 }
1371 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1372 ; /* find the beginning of the line */
1373 last_bol = sp;
1374
1375 for (sp = bol; sp < last_bol; sp++) {
1376 if (*sp == '\n')
1377 lno++;
1378 }
1379 *left_p -= last_bol - bol;
1380 *bol_p = last_bol;
1381 *lno_p = lno;
1382 return 0;
1383}
1384
335ec3bf
JK
1385static int fill_textconv_grep(struct userdiff_driver *driver,
1386 struct grep_source *gs)
1387{
1388 struct diff_filespec *df;
1389 char *buf;
1390 size_t size;
1391
1392 if (!driver || !driver->textconv)
1393 return grep_source_load(gs);
1394
1395 /*
1396 * The textconv interface is intimately tied to diff_filespecs, so we
1397 * have to pretend to be one. If we could unify the grep_source
1398 * and diff_filespec structs, this mess could just go away.
1399 */
1400 df = alloc_filespec(gs->path);
1401 switch (gs->type) {
1402 case GREP_SOURCE_SHA1:
1403 fill_filespec(df, gs->identifier, 1, 0100644);
1404 break;
1405 case GREP_SOURCE_FILE:
1406 fill_filespec(df, null_sha1, 0, 0100644);
1407 break;
1408 default:
1409 die("BUG: attempt to textconv something without a path?");
1410 }
1411
1412 /*
1413 * fill_textconv is not remotely thread-safe; it may load objects
1414 * behind the scenes, and it modifies the global diff tempfile
1415 * structure.
1416 */
1417 grep_read_lock();
1418 size = fill_textconv(driver, df, &buf);
1419 grep_read_unlock();
1420 free_filespec(df);
1421
1422 /*
1423 * The normal fill_textconv usage by the diff machinery would just keep
1424 * the textconv'd buf separate from the diff_filespec. But much of the
1425 * grep code passes around a grep_source and assumes that its "buf"
1426 * pointer is the beginning of the thing we are searching. So let's
1427 * install our textconv'd version into the grep_source, taking care not
1428 * to leak any existing buffer.
1429 */
1430 grep_source_clear_data(gs);
1431 gs->buf = buf;
1432 gs->size = size;
1433
1434 return 0;
1435}
1436
4aa2c475
RS
1437static int is_empty_line(const char *bol, const char *eol)
1438{
1439 while (bol < eol && isspace(*bol))
1440 bol++;
1441 return bol == eol;
1442}
1443
e1327023 1444static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
83b5d2f5 1445{
e1327023 1446 char *bol;
4aa2c475 1447 char *peek_bol = NULL;
e1327023 1448 unsigned long left;
83b5d2f5 1449 unsigned lno = 1;
83b5d2f5 1450 unsigned last_hit = 0;
83b5d2f5 1451 int binary_match_only = 0;
83b5d2f5 1452 unsigned count = 0;
a26345b6 1453 int try_lookahead = 0;
ba8ea749 1454 int show_function = 0;
335ec3bf 1455 struct userdiff_driver *textconv = NULL;
480c1ca6 1456 enum grep_context ctx = GREP_CONTEXT_HEAD;
60ecac98 1457 xdemitconf_t xecfg;
83b5d2f5 1458
5b594f45
FK
1459 if (!opt->output)
1460 opt->output = std_output;
1461
ba8ea749
RS
1462 if (opt->pre_context || opt->post_context || opt->file_break ||
1463 opt->funcbody) {
08303c36
RS
1464 /* Show hunk marks, except for the first file. */
1465 if (opt->last_shown)
1466 opt->show_hunk_mark = 1;
1467 /*
1468 * If we're using threads then we can't easily identify
1469 * the first file. Always put hunk marks in that case
1470 * and skip the very first one later in work_done().
1471 */
1472 if (opt->output != std_output)
1473 opt->show_hunk_mark = 1;
1474 }
431d6e7b
RS
1475 opt->last_shown = 0;
1476
335ec3bf
JK
1477 if (opt->allow_textconv) {
1478 grep_source_load_driver(gs);
1479 /*
1480 * We might set up the shared textconv cache data here, which
1481 * is not thread-safe.
1482 */
1483 grep_attr_lock();
1484 textconv = userdiff_get_textconv(gs->driver);
1485 grep_attr_unlock();
1486 }
1487
1488 /*
1489 * We know the result of a textconv is text, so we only have to care
1490 * about binary handling if we are not using it.
1491 */
1492 if (!textconv) {
1493 switch (opt->binary) {
1494 case GREP_BINARY_DEFAULT:
1495 if (grep_source_is_binary(gs))
1496 binary_match_only = 1;
1497 break;
1498 case GREP_BINARY_NOMATCH:
1499 if (grep_source_is_binary(gs))
1500 return 0; /* Assume unmatch */
1501 break;
1502 case GREP_BINARY_TEXT:
1503 break;
1504 default:
ef1177d1 1505 die("BUG: unknown binary handling mode");
335ec3bf 1506 }
83b5d2f5
JH
1507 }
1508
60ecac98 1509 memset(&xecfg, 0, sizeof(xecfg));
0579f91d
TR
1510 opt->priv = &xecfg;
1511
a26345b6 1512 try_lookahead = should_lookahead(opt);
60ecac98 1513
335ec3bf 1514 if (fill_textconv_grep(textconv, gs) < 0)
08265798
JK
1515 return 0;
1516
e1327023
JK
1517 bol = gs->buf;
1518 left = gs->size;
83b5d2f5
JH
1519 while (left) {
1520 char *eol, ch;
0ab7befa 1521 int hit;
83b5d2f5 1522
a26345b6 1523 /*
8997da38 1524 * look_ahead() skips quickly to the line that possibly
a26345b6
JH
1525 * has the next hit; don't call it if we need to do
1526 * something more than just skipping the current line
1527 * in response to an unmatch for the current line. E.g.
1528 * inside a post-context window, we will show the current
1529 * line as a context around the previous hit when it
1530 * doesn't hit.
1531 */
1532 if (try_lookahead
1533 && !(last_hit
ba8ea749
RS
1534 && (show_function ||
1535 lno <= last_hit + opt->post_context))
a26345b6
JH
1536 && look_ahead(opt, &left, &lno, &bol))
1537 break;
83b5d2f5
JH
1538 eol = end_of_line(bol, &left);
1539 ch = *eol;
1540 *eol = 0;
1541
480c1ca6
JH
1542 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1543 ctx = GREP_CONTEXT_BODY;
1544
0ab7befa 1545 hit = match_line(opt, bol, eol, ctx, collect_hits);
83b5d2f5
JH
1546 *eol = ch;
1547
0ab7befa
JH
1548 if (collect_hits)
1549 goto next_line;
1550
83b5d2f5
JH
1551 /* "grep -v -e foo -e bla" should list lines
1552 * that do not have either, so inversion should
1553 * be done outside.
1554 */
1555 if (opt->invert)
1556 hit = !hit;
1557 if (opt->unmatch_name_only) {
1558 if (hit)
1559 return 0;
1560 goto next_line;
1561 }
1562 if (hit) {
1563 count++;
1564 if (opt->status_only)
1565 return 1;
321ffcc0 1566 if (opt->name_only) {
e1327023 1567 show_name(opt, gs->name);
321ffcc0
RS
1568 return 1;
1569 }
c30c10cf
RS
1570 if (opt->count)
1571 goto next_line;
83b5d2f5 1572 if (binary_match_only) {
5b594f45 1573 opt->output(opt, "Binary file ", 12);
e1327023 1574 output_color(opt, gs->name, strlen(gs->name),
55f638bd 1575 opt->color_filename);
5b594f45 1576 opt->output(opt, " matches\n", 9);
83b5d2f5
JH
1577 return 1;
1578 }
83b5d2f5
JH
1579 /* Hit at this line. If we haven't shown the
1580 * pre-context lines, we would need to show them.
83b5d2f5 1581 */
ba8ea749 1582 if (opt->pre_context || opt->funcbody)
e1327023 1583 show_pre_context(opt, gs, bol, eol, lno);
2944e4e6 1584 else if (opt->funcname)
e1327023
JK
1585 show_funcname_line(opt, gs, bol, lno);
1586 show_line(opt, bol, eol, gs->name, lno, ':');
5dd06d38 1587 last_hit = lno;
ba8ea749
RS
1588 if (opt->funcbody)
1589 show_function = 1;
1590 goto next_line;
83b5d2f5 1591 }
4aa2c475
RS
1592 if (show_function && (!peek_bol || peek_bol < bol)) {
1593 unsigned long peek_left = left;
1594 char *peek_eol = eol;
1595
1596 /*
1597 * Trailing empty lines are not interesting.
1598 * Peek past them to see if they belong to the
1599 * body of the current function.
1600 */
1601 peek_bol = bol;
1602 while (is_empty_line(peek_bol, peek_eol)) {
1603 peek_bol = peek_eol + 1;
1604 peek_eol = end_of_line(peek_bol, &peek_left);
1605 }
1606
1607 if (match_funcname(opt, gs, peek_bol, peek_eol))
1608 show_function = 0;
1609 }
ba8ea749
RS
1610 if (show_function ||
1611 (last_hit && lno <= last_hit + opt->post_context)) {
83b5d2f5
JH
1612 /* If the last hit is within the post context,
1613 * we need to show this line.
1614 */
e1327023 1615 show_line(opt, bol, eol, gs->name, lno, '-');
83b5d2f5 1616 }
83b5d2f5
JH
1617
1618 next_line:
1619 bol = eol + 1;
1620 if (!left)
1621 break;
1622 left--;
1623 lno++;
1624 }
1625
0ab7befa
JH
1626 if (collect_hits)
1627 return 0;
b48fb5b6 1628
83b5d2f5
JH
1629 if (opt->status_only)
1630 return 0;
1631 if (opt->unmatch_name_only) {
1632 /* We did not see any hit, so we want to show this */
e1327023 1633 show_name(opt, gs->name);
83b5d2f5
JH
1634 return 1;
1635 }
1636
60ecac98
RS
1637 xdiff_clear_find_func(&xecfg);
1638 opt->priv = NULL;
1639
83b5d2f5
JH
1640 /* NEEDSWORK:
1641 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1642 * which feels mostly useless but sometimes useful. Maybe
1643 * make it another option? For now suppress them.
1644 */
5b594f45
FK
1645 if (opt->count && count) {
1646 char buf[32];
f76d947a
RS
1647 if (opt->pathname) {
1648 output_color(opt, gs->name, strlen(gs->name),
1649 opt->color_filename);
1650 output_sep(opt, ':');
1651 }
1a168e5c 1652 xsnprintf(buf, sizeof(buf), "%u\n", count);
5b594f45 1653 opt->output(opt, buf, strlen(buf));
c30c10cf 1654 return 1;
5b594f45 1655 }
83b5d2f5
JH
1656 return !!last_hit;
1657}
1658
0ab7befa
JH
1659static void clr_hit_marker(struct grep_expr *x)
1660{
1661 /* All-hit markers are meaningful only at the very top level
1662 * OR node.
1663 */
1664 while (1) {
1665 x->hit = 0;
1666 if (x->node != GREP_NODE_OR)
1667 return;
1668 x->u.binary.left->hit = 0;
1669 x = x->u.binary.right;
1670 }
1671}
1672
1673static int chk_hit_marker(struct grep_expr *x)
1674{
1675 /* Top level nodes have hit markers. See if they all are hits */
1676 while (1) {
1677 if (x->node != GREP_NODE_OR)
1678 return x->hit;
1679 if (!x->u.binary.left->hit)
1680 return 0;
1681 x = x->u.binary.right;
1682 }
1683}
1684
e1327023 1685int grep_source(struct grep_opt *opt, struct grep_source *gs)
0ab7befa
JH
1686{
1687 /*
1688 * we do not have to do the two-pass grep when we do not check
1689 * buffer-wide "all-match".
1690 */
1691 if (!opt->all_match)
e1327023 1692 return grep_source_1(opt, gs, 0);
0ab7befa
JH
1693
1694 /* Otherwise the toplevel "or" terms hit a bit differently.
1695 * We first clear hit markers from them.
1696 */
1697 clr_hit_marker(opt->pattern_expression);
e1327023 1698 grep_source_1(opt, gs, 1);
0ab7befa
JH
1699
1700 if (!chk_hit_marker(opt->pattern_expression))
1701 return 0;
1702
e1327023
JK
1703 return grep_source_1(opt, gs, 0);
1704}
1705
c876d6da 1706int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
e1327023
JK
1707{
1708 struct grep_source gs;
1709 int r;
1710
55c61688 1711 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
e1327023
JK
1712 gs.buf = buf;
1713 gs.size = size;
1714
1715 r = grep_source(opt, &gs);
1716
1717 grep_source_clear(&gs);
1718 return r;
1719}
1720
1721void grep_source_init(struct grep_source *gs, enum grep_source_type type,
55c61688
NTND
1722 const char *name, const char *path,
1723 const void *identifier)
e1327023
JK
1724{
1725 gs->type = type;
8c53f071
JK
1726 gs->name = xstrdup_or_null(name);
1727 gs->path = xstrdup_or_null(path);
e1327023
JK
1728 gs->buf = NULL;
1729 gs->size = 0;
94ad9d9e 1730 gs->driver = NULL;
e1327023
JK
1731
1732 switch (type) {
1733 case GREP_SOURCE_FILE:
1734 gs->identifier = xstrdup(identifier);
1735 break;
4538eef5
BW
1736 case GREP_SOURCE_SUBMODULE:
1737 if (!identifier) {
1738 gs->identifier = NULL;
1739 break;
1740 }
1741 /*
1742 * FALL THROUGH
1743 * If the identifier is non-NULL (in the submodule case) it
1744 * will be a SHA1 that needs to be copied.
1745 */
e1327023
JK
1746 case GREP_SOURCE_SHA1:
1747 gs->identifier = xmalloc(20);
50546b15 1748 hashcpy(gs->identifier, identifier);
e1327023
JK
1749 break;
1750 case GREP_SOURCE_BUF:
1751 gs->identifier = NULL;
4538eef5 1752 break;
e1327023
JK
1753 }
1754}
1755
1756void grep_source_clear(struct grep_source *gs)
1757{
1758 free(gs->name);
1759 gs->name = NULL;
55c61688
NTND
1760 free(gs->path);
1761 gs->path = NULL;
e1327023
JK
1762 free(gs->identifier);
1763 gs->identifier = NULL;
1764 grep_source_clear_data(gs);
1765}
1766
1767void grep_source_clear_data(struct grep_source *gs)
1768{
1769 switch (gs->type) {
1770 case GREP_SOURCE_FILE:
1771 case GREP_SOURCE_SHA1:
4538eef5 1772 case GREP_SOURCE_SUBMODULE:
e1327023
JK
1773 free(gs->buf);
1774 gs->buf = NULL;
1775 gs->size = 0;
1776 break;
1777 case GREP_SOURCE_BUF:
1778 /* leave user-provided buf intact */
1779 break;
1780 }
1781}
1782
1783static int grep_source_load_sha1(struct grep_source *gs)
1784{
1785 enum object_type type;
1786
1787 grep_read_lock();
1788 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1789 grep_read_unlock();
1790
1791 if (!gs->buf)
1792 return error(_("'%s': unable to read %s"),
1793 gs->name,
1794 sha1_to_hex(gs->identifier));
1795 return 0;
1796}
1797
1798static int grep_source_load_file(struct grep_source *gs)
1799{
1800 const char *filename = gs->identifier;
1801 struct stat st;
1802 char *data;
1803 size_t size;
1804 int i;
1805
1806 if (lstat(filename, &st) < 0) {
1807 err_ret:
1808 if (errno != ENOENT)
7645d8f1 1809 error_errno(_("failed to stat '%s'"), filename);
e1327023
JK
1810 return -1;
1811 }
1812 if (!S_ISREG(st.st_mode))
1813 return -1;
1814 size = xsize_t(st.st_size);
1815 i = open(filename, O_RDONLY);
1816 if (i < 0)
1817 goto err_ret;
3733e694 1818 data = xmallocz(size);
e1327023 1819 if (st.st_size != read_in_full(i, data, size)) {
7645d8f1 1820 error_errno(_("'%s': short read"), filename);
e1327023
JK
1821 close(i);
1822 free(data);
1823 return -1;
1824 }
1825 close(i);
e1327023
JK
1826
1827 gs->buf = data;
1828 gs->size = size;
1829 return 0;
1830}
1831
3083301e 1832static int grep_source_load(struct grep_source *gs)
e1327023
JK
1833{
1834 if (gs->buf)
1835 return 0;
1836
1837 switch (gs->type) {
1838 case GREP_SOURCE_FILE:
1839 return grep_source_load_file(gs);
1840 case GREP_SOURCE_SHA1:
1841 return grep_source_load_sha1(gs);
1842 case GREP_SOURCE_BUF:
1843 return gs->buf ? 0 : -1;
4538eef5
BW
1844 case GREP_SOURCE_SUBMODULE:
1845 break;
e1327023 1846 }
4538eef5 1847 die("BUG: invalid grep_source type to load");
0ab7befa 1848}
94ad9d9e
JK
1849
1850void grep_source_load_driver(struct grep_source *gs)
1851{
1852 if (gs->driver)
1853 return;
1854
1855 grep_attr_lock();
55c61688
NTND
1856 if (gs->path)
1857 gs->driver = userdiff_find_by_path(gs->path);
94ad9d9e
JK
1858 if (!gs->driver)
1859 gs->driver = userdiff_find_by_name("default");
1860 grep_attr_unlock();
1861}
41b59bfc 1862
3083301e 1863static int grep_source_is_binary(struct grep_source *gs)
41b59bfc
JK
1864{
1865 grep_source_load_driver(gs);
1866 if (gs->driver->binary != -1)
1867 return gs->driver->binary;
1868
1869 if (!grep_source_load(gs))
1870 return buffer_is_binary(gs->buf, gs->size);
1871
1872 return 0;
1873}