grep.c 43.7 KB
Newer Older
1 2
#include "cache.h"
#include "grep.h"
3
#include "userdiff.h"
4
#include "xdiff-interface.h"
J
Jeff King 已提交
5 6
#include "diff.h"
#include "diffcore.h"
7
#include "commit.h"
8
#include "quote.h"
9

10 11 12
static int grep_source_load(struct grep_source *gs);
static int grep_source_is_binary(struct grep_source *gs);

13 14
static struct grep_opt grep_defaults;

15 16 17 18 19
static void std_output(struct grep_opt *opt, const void *buf, size_t size)
{
	fwrite(buf, size, 1, stdout);
}

20 21 22 23 24 25 26 27
/*
 * Initialize the grep_defaults template with hardcoded defaults.
 * We could let the compiler do this, but without C99 initializers
 * the code gets unwieldy and unreadable, so...
 */
void init_grep_defaults(void)
{
	struct grep_opt *opt = &grep_defaults;
28 29 30 31 32
	static int run_once;

	if (run_once)
		return;
	run_once++;
33 34 35 36 37 38 39 40

	memset(opt, 0, sizeof(*opt));
	opt->relative = 1;
	opt->pathname = 1;
	opt->regflags = REG_NEWLINE;
	opt->max_depth = -1;
	opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
	opt->extended_regexp_option = 0;
41 42 43 44 45 46 47 48
	color_set(opt->color_context, "");
	color_set(opt->color_filename, "");
	color_set(opt->color_function, "");
	color_set(opt->color_lineno, "");
	color_set(opt->color_match_context, GIT_COLOR_BOLD_RED);
	color_set(opt->color_match_selected, GIT_COLOR_BOLD_RED);
	color_set(opt->color_selected, "");
	color_set(opt->color_sep, GIT_COLOR_CYAN);
49
	opt->color = -1;
50
	opt->output = std_output;
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
}

static int parse_pattern_type_arg(const char *opt, const char *arg)
{
	if (!strcmp(arg, "default"))
		return GREP_PATTERN_TYPE_UNSPECIFIED;
	else if (!strcmp(arg, "basic"))
		return GREP_PATTERN_TYPE_BRE;
	else if (!strcmp(arg, "extended"))
		return GREP_PATTERN_TYPE_ERE;
	else if (!strcmp(arg, "fixed"))
		return GREP_PATTERN_TYPE_FIXED;
	else if (!strcmp(arg, "perl"))
		return GREP_PATTERN_TYPE_PCRE;
	die("bad %s argument: %s", opt, arg);
}

/*
 * Read the configuration file once and store it in
 * the grep_defaults template.
 */
int grep_config(const char *var, const char *value, void *cb)
{
	struct grep_opt *opt = &grep_defaults;
	char *color = NULL;

	if (userdiff_config(var, value) < 0)
		return -1;

	if (!strcmp(var, "grep.extendedregexp")) {
		if (git_config_bool(var, value))
			opt->extended_regexp_option = 1;
		else
			opt->extended_regexp_option = 0;
		return 0;
	}

	if (!strcmp(var, "grep.patterntype")) {
		opt->pattern_type_option = parse_pattern_type_arg(var, value);
		return 0;
	}

	if (!strcmp(var, "grep.linenumber")) {
		opt->linenum = git_config_bool(var, value);
		return 0;
	}

98 99 100 101 102
	if (!strcmp(var, "grep.fullname")) {
		opt->relative = !git_config_bool(var, value);
		return 0;
	}

103 104 105 106 107 108 109 110 111 112
	if (!strcmp(var, "color.grep"))
		opt->color = git_config_colorbool(var, value);
	else if (!strcmp(var, "color.grep.context"))
		color = opt->color_context;
	else if (!strcmp(var, "color.grep.filename"))
		color = opt->color_filename;
	else if (!strcmp(var, "color.grep.function"))
		color = opt->color_function;
	else if (!strcmp(var, "color.grep.linenumber"))
		color = opt->color_lineno;
113 114 115 116
	else if (!strcmp(var, "color.grep.matchcontext"))
		color = opt->color_match_context;
	else if (!strcmp(var, "color.grep.matchselected"))
		color = opt->color_match_selected;
117 118 119 120
	else if (!strcmp(var, "color.grep.selected"))
		color = opt->color_selected;
	else if (!strcmp(var, "color.grep.separator"))
		color = opt->color_sep;
121 122 123 124
	else if (!strcmp(var, "color.grep.match")) {
		int rc = 0;
		if (!value)
			return config_error_nonbool(var);
125 126
		rc |= color_parse(value, opt->color_match_context);
		rc |= color_parse(value, opt->color_match_selected);
127 128
		return rc;
	}
129 130 131 132

	if (color) {
		if (!value)
			return config_error_nonbool(var);
133
		return color_parse(value, color);
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
	}
	return 0;
}

/*
 * Initialize one instance of grep_opt and copy the
 * default values from the template we read the configuration
 * information in an earlier call to git_config(grep_config).
 */
void grep_init(struct grep_opt *opt, const char *prefix)
{
	struct grep_opt *def = &grep_defaults;

	memset(opt, 0, sizeof(*opt));
	opt->prefix = prefix;
	opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
	opt->pattern_tail = &opt->pattern_list;
	opt->header_tail = &opt->header_list;

	opt->color = def->color;
	opt->extended_regexp_option = def->extended_regexp_option;
	opt->pattern_type_option = def->pattern_type_option;
	opt->linenum = def->linenum;
	opt->max_depth = def->max_depth;
	opt->pathname = def->pathname;
	opt->regflags = def->regflags;
	opt->relative = def->relative;
161
	opt->output = def->output;
162

163 164 165 166 167 168 169 170
	color_set(opt->color_context, def->color_context);
	color_set(opt->color_filename, def->color_filename);
	color_set(opt->color_function, def->color_function);
	color_set(opt->color_lineno, def->color_lineno);
	color_set(opt->color_match_context, def->color_match_context);
	color_set(opt->color_match_selected, def->color_match_selected);
	color_set(opt->color_selected, def->color_selected);
	color_set(opt->color_sep, def->color_sep);
171
}
172

173
static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
174 175 176 177 178 179 180
{
	switch (pattern_type) {
	case GREP_PATTERN_TYPE_UNSPECIFIED:
		/* fall through */

	case GREP_PATTERN_TYPE_BRE:
		opt->fixed = 0;
181
		opt->pcre1 = 0;
182 183 184 185
		break;

	case GREP_PATTERN_TYPE_ERE:
		opt->fixed = 0;
186
		opt->pcre1 = 0;
187 188 189 190 191
		opt->regflags |= REG_EXTENDED;
		break;

	case GREP_PATTERN_TYPE_FIXED:
		opt->fixed = 1;
192
		opt->pcre1 = 0;
193 194 195 196
		break;

	case GREP_PATTERN_TYPE_PCRE:
		opt->fixed = 0;
197
		opt->pcre1 = 1;
198 199 200 201
		break;
	}
}

202 203 204 205 206 207 208 209 210 211
void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
{
	if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
		grep_set_pattern_type_option(pattern_type, opt);
	else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
		grep_set_pattern_type_option(opt->pattern_type_option, opt);
	else if (opt->extended_regexp_option)
		grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
}

212 213 214 215
static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
					const char *origin, int no,
					enum grep_pat_token t,
					enum grep_header_field field)
216 217
{
	struct grep_pat *p = xcalloc(1, sizeof(*p));
218
	p->pattern = xmemdupz(pat, patlen);
219 220 221 222
	p->patternlen = patlen;
	p->origin = origin;
	p->no = no;
	p->token = t;
223
	p->field = field;
224 225 226
	return p;
}

227 228 229 230
static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
{
	**tail = p;
	*tail = &p->next;
231
	p->next = NULL;
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

	switch (p->token) {
	case GREP_PATTERN: /* atom */
	case GREP_PATTERN_HEAD:
	case GREP_PATTERN_BODY:
		for (;;) {
			struct grep_pat *new_pat;
			size_t len = 0;
			char *cp = p->pattern + p->patternlen, *nl = NULL;
			while (++len <= p->patternlen) {
				if (*(--cp) == '\n') {
					nl = cp;
					break;
				}
			}
			if (!nl)
				break;
			new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
						  p->no, p->token, p->field);
			new_pat->next = p->next;
			if (!p->next)
				*tail = &new_pat->next;
			p->next = new_pat;
			*nl = '\0';
			p->patternlen -= len;
		}
		break;
	default:
		break;
	}
262 263
}

264 265 266 267 268
void append_header_grep_pattern(struct grep_opt *opt,
				enum grep_header_field field, const char *pat)
{
	struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
					     GREP_PATTERN_HEAD, field);
269 270
	if (field == GREP_HEADER_REFLOG)
		opt->use_reflog_filter = 1;
271
	do_append_grep_pat(&opt->header_tail, p);
272 273
}

274 275
void append_grep_pattern(struct grep_opt *opt, const char *pat,
			 const char *origin, int no, enum grep_pat_token t)
276 277 278 279 280 281
{
	append_grep_pat(opt, pat, strlen(pat), origin, no, t);
}

void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
		     const char *origin, int no, enum grep_pat_token t)
282
{
283
	struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
284
	do_append_grep_pat(&opt->pattern_tail, p);
285 286
}

F
Fredrik Kuivinen 已提交
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
{
	struct grep_pat *pat;
	struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
	*ret = *opt;

	ret->pattern_list = NULL;
	ret->pattern_tail = &ret->pattern_list;

	for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
	{
		if(pat->token == GREP_PATTERN_HEAD)
			append_header_grep_pattern(ret, pat->field,
						   pat->pattern);
		else
302 303
			append_grep_pat(ret, pat->pattern, pat->patternlen,
					pat->origin, pat->no, pat->token);
F
Fredrik Kuivinen 已提交
304 305 306 307 308
	}

	return ret;
}

309 310 311 312 313 314
static NORETURN void compile_regexp_failed(const struct grep_pat *p,
		const char *error)
{
	char where[1024];

	if (p->no)
315
		xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
316
	else if (p->origin)
317
		xsnprintf(where, sizeof(where), "%s, ", p->origin);
318 319 320 321 322 323
	else
		where[0] = 0;

	die("%s'%s': %s", where, p->pattern, error);
}

324 325 326 327 328 329 330 331 332 333 334 335
static int is_fixed(const char *s, size_t len)
{
	size_t i;

	for (i = 0; i < len; i++) {
		if (is_regex_special(s[i]))
			return 0;
	}

	return 1;
}

336 337 338 339 340 341 342 343 344 345 346 347
static int has_null(const char *s, size_t len)
{
	/*
	 * regcomp cannot accept patterns with NULs so when using it
	 * we consider any pattern containing a NUL fixed.
	 */
	if (memchr(s, 0, len))
		return 1;

	return 0;
}

348
#ifdef USE_LIBPCRE1
349
static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
M
Michał Kiedrowicz 已提交
350 351 352
{
	const char *error;
	int erroffset;
353
	int options = PCRE_MULTILINE;
M
Michał Kiedrowicz 已提交
354

355 356
	if (opt->ignore_case) {
		if (has_non_ascii(p->pattern))
357
			p->pcre1_tables = pcre_maketables();
M
Michał Kiedrowicz 已提交
358
		options |= PCRE_CASELESS;
359
	}
360 361
	if (is_utf8_locale() && has_non_ascii(p->pattern))
		options |= PCRE_UTF8;
M
Michał Kiedrowicz 已提交
362

363 364 365
	p->pcre1_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
				      p->pcre1_tables);
	if (!p->pcre1_regexp)
M
Michał Kiedrowicz 已提交
366 367
		compile_regexp_failed(p, error);

368 369
	p->pcre1_extra_info = pcre_study(p->pcre1_regexp, 0, &error);
	if (!p->pcre1_extra_info && error)
M
Michał Kiedrowicz 已提交
370 371 372
		die("%s", error);
}

373
static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
M
Michał Kiedrowicz 已提交
374 375 376 377 378 379 380
		regmatch_t *match, int eflags)
{
	int ovector[30], ret, flags = 0;

	if (eflags & REG_NOTBOL)
		flags |= PCRE_NOTBOL;

381
	ret = pcre_exec(p->pcre1_regexp, p->pcre1_extra_info, line, eol - line,
M
Michał Kiedrowicz 已提交
382 383 384 385 386 387 388 389 390 391 392 393
			0, flags, ovector, ARRAY_SIZE(ovector));
	if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
		die("pcre_exec failed with error code %d", ret);
	if (ret > 0) {
		ret = 0;
		match->rm_so = ovector[0];
		match->rm_eo = ovector[1];
	}

	return ret;
}

394
static void free_pcre1_regexp(struct grep_pat *p)
M
Michał Kiedrowicz 已提交
395
{
396 397 398
	pcre_free(p->pcre1_regexp);
	pcre_free(p->pcre1_extra_info);
	pcre_free((void *)p->pcre1_tables);
M
Michał Kiedrowicz 已提交
399
}
400
#else /* !USE_LIBPCRE1 */
401
static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
M
Michał Kiedrowicz 已提交
402 403 404 405
{
	die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
}

406
static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
M
Michał Kiedrowicz 已提交
407 408 409 410 411
		regmatch_t *match, int eflags)
{
	return 1;
}

412
static void free_pcre1_regexp(struct grep_pat *p)
M
Michał Kiedrowicz 已提交
413 414
{
}
415
#endif /* !USE_LIBPCRE1 */
M
Michał Kiedrowicz 已提交
416

417 418 419 420
static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
{
	struct strbuf sb = STRBUF_INIT;
	int err;
421
	int regflags = opt->regflags;
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437

	basic_regex_quote_buf(&sb, p->pattern);
	if (opt->ignore_case)
		regflags |= REG_ICASE;
	err = regcomp(&p->regexp, sb.buf, regflags);
	if (opt->debug)
		fprintf(stderr, "fixed %s\n", sb.buf);
	strbuf_release(&sb);
	if (err) {
		char errbuf[1024];
		regerror(err, &p->regexp, errbuf, sizeof(errbuf));
		regfree(&p->regexp);
		compile_regexp_failed(p, errbuf);
	}
}

438 439
static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
{
440
	int icase, ascii_only;
441 442
	int err;

443
	p->word_regexp = opt->word_regexp;
444
	p->ignore_case = opt->ignore_case;
445 446
	icase	       = opt->regflags & REG_ICASE || p->ignore_case;
	ascii_only     = !has_non_ascii(p->pattern);
447

448 449 450 451 452 453 454 455 456 457 458 459
	/*
	 * Even when -F (fixed) asks us to do a non-regexp search, we
	 * may not be able to correctly case-fold when -i
	 * (ignore-case) is asked (in which case, we'll synthesize a
	 * regexp to match the pattern that matches regexp special
	 * characters literally, while ignoring case differences).  On
	 * the other hand, even without -F, if the pattern does not
	 * have any regexp special characters and there is no need for
	 * case-folding search, we can internally turn it into a
	 * simple string match using kws.  p->fixed tells us if we
	 * want to use kws.
	 */
460 461 462
	if (opt->fixed ||
	    has_null(p->pattern, p->patternlen) ||
	    is_fixed(p->pattern, p->patternlen))
463
		p->fixed = !icase || ascii_only;
F
Fredrik Kuivinen 已提交
464 465 466 467
	else
		p->fixed = 0;

	if (p->fixed) {
468
		p->kws = kwsalloc(icase ? tolower_trans_tbl : NULL);
F
Fredrik Kuivinen 已提交
469 470
		kwsincr(p->kws, p->pattern, p->patternlen);
		kwsprep(p->kws);
471
		return;
472 473 474 475 476 477 478 479
	} else if (opt->fixed) {
		/*
		 * We come here when the pattern has the non-ascii
		 * characters we cannot case-fold, and asked to
		 * ignore-case.
		 */
		compile_fixed_regexp(p, opt);
		return;
F
Fredrik Kuivinen 已提交
480
	}
481

482 483
	if (opt->pcre1) {
		compile_pcre1_regexp(p, opt);
M
Michał Kiedrowicz 已提交
484 485 486
		return;
	}

487
	err = regcomp(&p->regexp, p->pattern, opt->regflags);
488 489 490 491
	if (err) {
		char errbuf[1024];
		regerror(err, &p->regexp, errbuf, 1024);
		regfree(&p->regexp);
492
		compile_regexp_failed(p, errbuf);
493 494 495
	}
}

J
Junio C Hamano 已提交
496
static struct grep_expr *compile_pattern_or(struct grep_pat **);
497 498 499 500 501 502
static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
{
	struct grep_pat *p;
	struct grep_expr *x;

	p = *list;
503 504
	if (!p)
		return NULL;
505 506
	switch (p->token) {
	case GREP_PATTERN: /* atom */
507 508
	case GREP_PATTERN_HEAD:
	case GREP_PATTERN_BODY:
509 510 511 512 513 514 515
		x = xcalloc(1, sizeof (struct grep_expr));
		x->node = GREP_NODE_ATOM;
		x->u.atom = p;
		*list = p->next;
		return x;
	case GREP_OPEN_PAREN:
		*list = p->next;
J
Junio C Hamano 已提交
516
		x = compile_pattern_or(list);
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
		if (!*list || (*list)->token != GREP_CLOSE_PAREN)
			die("unmatched parenthesis");
		*list = (*list)->next;
		return x;
	default:
		return NULL;
	}
}

static struct grep_expr *compile_pattern_not(struct grep_pat **list)
{
	struct grep_pat *p;
	struct grep_expr *x;

	p = *list;
532 533
	if (!p)
		return NULL;
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
	switch (p->token) {
	case GREP_NOT:
		if (!p->next)
			die("--not not followed by pattern expression");
		*list = p->next;
		x = xcalloc(1, sizeof (struct grep_expr));
		x->node = GREP_NODE_NOT;
		x->u.unary = compile_pattern_not(list);
		if (!x->u.unary)
			die("--not followed by non pattern expression");
		return x;
	default:
		return compile_pattern_atom(list);
	}
}

static struct grep_expr *compile_pattern_and(struct grep_pat **list)
{
	struct grep_pat *p;
	struct grep_expr *x, *y, *z;

	x = compile_pattern_not(list);
	p = *list;
	if (p && p->token == GREP_AND) {
		if (!p->next)
			die("--and not followed by pattern expression");
		*list = p->next;
		y = compile_pattern_and(list);
		if (!y)
			die("--and not followed by pattern expression");
		z = xcalloc(1, sizeof (struct grep_expr));
		z->node = GREP_NODE_AND;
		z->u.binary.left = x;
		z->u.binary.right = y;
		return z;
	}
	return x;
}

static struct grep_expr *compile_pattern_or(struct grep_pat **list)
{
	struct grep_pat *p;
	struct grep_expr *x, *y, *z;

	x = compile_pattern_and(list);
	p = *list;
	if (x && p && p->token != GREP_CLOSE_PAREN) {
		y = compile_pattern_or(list);
		if (!y)
			die("not a pattern expression %s", p->pattern);
		z = xcalloc(1, sizeof (struct grep_expr));
		z->node = GREP_NODE_OR;
		z->u.binary.left = x;
		z->u.binary.right = y;
		return z;
	}
	return x;
}

static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
{
	return compile_pattern_or(list);
}

598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
static void indent(int in)
{
	while (in-- > 0)
		fputc(' ', stderr);
}

static void dump_grep_pat(struct grep_pat *p)
{
	switch (p->token) {
	case GREP_AND: fprintf(stderr, "*and*"); break;
	case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
	case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
	case GREP_NOT: fprintf(stderr, "*not*"); break;
	case GREP_OR: fprintf(stderr, "*or*"); break;

	case GREP_PATTERN: fprintf(stderr, "pattern"); break;
	case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
	case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
	}

	switch (p->token) {
	default: break;
	case GREP_PATTERN_HEAD:
		fprintf(stderr, "<head %d>", p->field); break;
	case GREP_PATTERN_BODY:
		fprintf(stderr, "<body>"); break;
	}
	switch (p->token) {
	default: break;
	case GREP_PATTERN_HEAD:
	case GREP_PATTERN_BODY:
	case GREP_PATTERN:
		fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
		break;
	}
	fputc('\n', stderr);
}

static void dump_grep_expression_1(struct grep_expr *x, int in)
{
	indent(in);
	switch (x->node) {
	case GREP_NODE_TRUE:
		fprintf(stderr, "true\n");
		break;
	case GREP_NODE_ATOM:
		dump_grep_pat(x->u.atom);
		break;
	case GREP_NODE_NOT:
		fprintf(stderr, "(not\n");
		dump_grep_expression_1(x->u.unary, in+1);
		indent(in);
		fprintf(stderr, ")\n");
		break;
	case GREP_NODE_AND:
		fprintf(stderr, "(and\n");
		dump_grep_expression_1(x->u.binary.left, in+1);
		dump_grep_expression_1(x->u.binary.right, in+1);
		indent(in);
		fprintf(stderr, ")\n");
		break;
	case GREP_NODE_OR:
		fprintf(stderr, "(or\n");
		dump_grep_expression_1(x->u.binary.left, in+1);
		dump_grep_expression_1(x->u.binary.right, in+1);
		indent(in);
		fprintf(stderr, ")\n");
		break;
	}
}

669
static void dump_grep_expression(struct grep_opt *opt)
670 671 672 673 674 675 676 677 678
{
	struct grep_expr *x = opt->pattern_expression;

	if (opt->all_match)
		fprintf(stderr, "[all-match]\n");
	dump_grep_expression_1(x, 0);
	fflush(NULL);
}

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
static struct grep_expr *grep_true_expr(void)
{
	struct grep_expr *z = xcalloc(1, sizeof(*z));
	z->node = GREP_NODE_TRUE;
	return z;
}

static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
{
	struct grep_expr *z = xcalloc(1, sizeof(*z));
	z->node = GREP_NODE_OR;
	z->u.binary.left = left;
	z->u.binary.right = right;
	return z;
}

695
static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
696 697
{
	struct grep_pat *p;
698
	struct grep_expr *header_expr;
699 700
	struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
	enum grep_header_field fld;
701

702 703
	if (!opt->header_list)
		return NULL;
704

705 706
	for (p = opt->header_list; p; p = p->next) {
		if (p->token != GREP_PATTERN_HEAD)
707
			die("BUG: a non-header pattern in grep header list.");
708 709
		if (p->field < GREP_HEADER_FIELD_MIN ||
		    GREP_HEADER_FIELD_MAX <= p->field)
710
			die("BUG: unknown header field %d", p->field);
711
		compile_regexp(p, opt);
712
	}
713 714 715 716 717 718 719 720 721 722

	for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
		header_group[fld] = NULL;

	for (p = opt->header_list; p; p = p->next) {
		struct grep_expr *h;
		struct grep_pat *pp = p;

		h = compile_pattern_atom(&pp);
		if (!h || pp != p->next)
723
			die("BUG: malformed header expr");
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
		if (!header_group[p->field]) {
			header_group[p->field] = h;
			continue;
		}
		header_group[p->field] = grep_or_expr(h, header_group[p->field]);
	}

	header_expr = NULL;

	for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
		if (!header_group[fld])
			continue;
		if (!header_expr)
			header_expr = grep_true_expr();
		header_expr = grep_or_expr(header_group[fld], header_expr);
	}
740 741 742
	return header_expr;
}

743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
{
	struct grep_expr *z = x;

	while (x) {
		assert(x->node == GREP_NODE_OR);
		if (x->u.binary.right &&
		    x->u.binary.right->node == GREP_NODE_TRUE) {
			x->u.binary.right = y;
			break;
		}
		x = x->u.binary.right;
	}
	return z;
}

759
static void compile_grep_patterns_real(struct grep_opt *opt)
760 761 762
{
	struct grep_pat *p;
	struct grep_expr *header_expr = prep_header_patterns(opt);
J
Junio C Hamano 已提交
763

764
	for (p = opt->pattern_list; p; p = p->next) {
765 766 767 768
		switch (p->token) {
		case GREP_PATTERN: /* atom */
		case GREP_PATTERN_HEAD:
		case GREP_PATTERN_BODY:
769
			compile_regexp(p, opt);
770 771
			break;
		default:
772
			opt->extended = 1;
773 774
			break;
		}
775 776
	}

777 778
	if (opt->all_match || header_expr)
		opt->extended = 1;
779
	else if (!opt->extended && !opt->debug)
780 781 782
		return;

	p = opt->pattern_list;
783 784
	if (p)
		opt->pattern_expression = compile_pattern_expr(&p);
785 786
	if (p)
		die("incomplete pattern expression: %s", p->pattern);
787 788 789 790

	if (!header_expr)
		return;

791
	if (!opt->pattern_expression)
792
		opt->pattern_expression = header_expr;
793 794 795
	else if (opt->all_match)
		opt->pattern_expression = grep_splice_or(header_expr,
							 opt->pattern_expression);
796 797 798
	else
		opt->pattern_expression = grep_or_expr(opt->pattern_expression,
						       header_expr);
799
	opt->all_match = 1;
800 801
}

802 803 804 805 806 807 808
void compile_grep_patterns(struct grep_opt *opt)
{
	compile_grep_patterns_real(opt);
	if (opt->debug)
		dump_grep_expression(opt);
}

809 810 811
static void free_pattern_expr(struct grep_expr *x)
{
	switch (x->node) {
812
	case GREP_NODE_TRUE:
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
	case GREP_NODE_ATOM:
		break;
	case GREP_NODE_NOT:
		free_pattern_expr(x->u.unary);
		break;
	case GREP_NODE_AND:
	case GREP_NODE_OR:
		free_pattern_expr(x->u.binary.left);
		free_pattern_expr(x->u.binary.right);
		break;
	}
	free(x);
}

void free_grep_patterns(struct grep_opt *opt)
{
	struct grep_pat *p, *n;

	for (p = opt->pattern_list; p; p = n) {
		n = p->next;
		switch (p->token) {
		case GREP_PATTERN: /* atom */
		case GREP_PATTERN_HEAD:
		case GREP_PATTERN_BODY:
F
Fredrik Kuivinen 已提交
837 838
			if (p->kws)
				kwsfree(p->kws);
839 840
			else if (p->pcre1_regexp)
				free_pcre1_regexp(p);
M
Michał Kiedrowicz 已提交
841 842
			else
				regfree(&p->regexp);
843
			free(p->pattern);
844 845 846 847 848 849 850 851 852 853 854 855
			break;
		default:
			break;
		}
		free(p);
	}

	if (!opt->extended)
		return;
	free_pattern_expr(opt->pattern_expression);
}

856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
static char *end_of_line(char *cp, unsigned long *left)
{
	unsigned long l = *left;
	while (l && *cp != '\n') {
		l--;
		cp++;
	}
	*left = l;
	return cp;
}

static int word_char(char ch)
{
	return isalnum(ch) || ch == '_';
}

872 873 874
static void output_color(struct grep_opt *opt, const void *data, size_t size,
			 const char *color)
{
875
	if (want_color(opt->color) && color && color[0]) {
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
		opt->output(opt, color, strlen(color));
		opt->output(opt, data, size);
		opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
	} else
		opt->output(opt, data, size);
}

static void output_sep(struct grep_opt *opt, char sign)
{
	if (opt->null_following_name)
		opt->output(opt, "\0", 1);
	else
		output_color(opt, &sign, 1, opt->color_sep);
}

891 892
static void show_name(struct grep_opt *opt, const char *name)
{
893
	output_color(opt, name, strlen(name), opt->color_filename);
F
Fredrik Kuivinen 已提交
894
	opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
895 896
}

897 898
static int fixmatch(struct grep_pat *p, char *line, char *eol,
		    regmatch_t *match)
899
{
F
Fredrik Kuivinen 已提交
900 901 902
	struct kwsmatch kwsm;
	size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
	if (offset == -1) {
903 904
		match->rm_so = match->rm_eo = -1;
		return REG_NOMATCH;
F
Fredrik Kuivinen 已提交
905 906 907
	} else {
		match->rm_so = offset;
		match->rm_eo = match->rm_so + kwsm.size[0];
908 909 910 911
		return 0;
	}
}

912 913 914 915 916 917 918
static int patmatch(struct grep_pat *p, char *line, char *eol,
		    regmatch_t *match, int eflags)
{
	int hit;

	if (p->fixed)
		hit = !fixmatch(p, line, eol, match);
919 920
	else if (p->pcre1_regexp)
		hit = !pcre1match(p, line, eol, match, eflags);
921
	else
J
Johannes Schindelin 已提交
922 923
		hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
				   eflags);
924 925 926 927

	return hit;
}

928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
static int strip_timestamp(char *bol, char **eol_p)
{
	char *eol = *eol_p;
	int ch;

	while (bol < --eol) {
		if (*eol != '>')
			continue;
		*eol_p = ++eol;
		ch = *eol;
		*eol = '\0';
		return ch;
	}
	return 0;
}

static struct {
	const char *field;
	size_t len;
} header_field[] = {
	{ "author ", 7 },
	{ "committer ", 10 },
950
	{ "reflog ", 7 },
951 952
};

953
static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
954 955
			     enum grep_context ctx,
			     regmatch_t *pmatch, int eflags)
956 957
{
	int hit = 0;
958
	int saved_ch = 0;
R
René Scharfe 已提交
959
	const char *start = bol;
960

961 962 963 964
	if ((p->token != GREP_PATTERN) &&
	    ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
		return 0;

965 966 967 968 969 970 971 972 973
	if (p->token == GREP_PATTERN_HEAD) {
		const char *field;
		size_t len;
		assert(p->field < ARRAY_SIZE(header_field));
		field = header_field[p->field].field;
		len = header_field[p->field].len;
		if (strncmp(bol, field, len))
			return 0;
		bol += len;
974 975 976 977 978 979 980 981
		switch (p->field) {
		case GREP_HEADER_AUTHOR:
		case GREP_HEADER_COMMITTER:
			saved_ch = strip_timestamp(bol, &eol);
			break;
		default:
			break;
		}
982 983
	}

984
 again:
985
	hit = patmatch(p, bol, eol, pmatch, eflags);
986

987
	if (hit && p->word_regexp) {
988
		if ((pmatch[0].rm_so < 0) ||
989
		    (eol - bol) < pmatch[0].rm_so ||
990 991 992 993 994 995 996 997 998 999
		    (pmatch[0].rm_eo < 0) ||
		    (eol - bol) < pmatch[0].rm_eo)
			die("regexp returned nonsense");

		/* Match beginning must be either beginning of the
		 * line, or at word boundary (i.e. the last char must
		 * not be a word char).  Similarly, match end must be
		 * either end of the line, or at word boundary
		 * (i.e. the next char must not be a word char).
		 */
1000
		if ( ((pmatch[0].rm_so == 0) ||
1001 1002 1003 1004 1005 1006 1007
		      !word_char(bol[pmatch[0].rm_so-1])) &&
		     ((pmatch[0].rm_eo == (eol-bol)) ||
		      !word_char(bol[pmatch[0].rm_eo])) )
			;
		else
			hit = 0;

1008 1009 1010 1011
		/* Words consist of at least one character. */
		if (pmatch->rm_so == pmatch->rm_eo)
			hit = 0;

1012 1013 1014 1015
		if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
			/* There could be more than one match on the
			 * line, and the first match might not be
			 * strict word match.  But later ones could be!
1016 1017
			 * Forward to the next possible start, i.e. the
			 * next position following a non-word char.
1018 1019
			 */
			bol = pmatch[0].rm_so + bol + 1;
1020 1021
			while (word_char(bol[-1]) && bol < eol)
				bol++;
1022
			eflags |= REG_NOTBOL;
1023 1024
			if (bol < eol)
				goto again;
1025 1026
		}
	}
1027 1028
	if (p->token == GREP_PATTERN_HEAD && saved_ch)
		*eol = saved_ch;
R
René Scharfe 已提交
1029 1030 1031 1032
	if (hit) {
		pmatch[0].rm_so += bol - start;
		pmatch[0].rm_eo += bol - start;
	}
1033 1034 1035
	return hit;
}

1036 1037
static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
			   enum grep_context ctx, int collect_hits)
1038
{
J
Junio C Hamano 已提交
1039
	int h = 0;
1040
	regmatch_t match;
J
Junio C Hamano 已提交
1041

1042 1043
	if (!x)
		die("Not a valid grep expression");
1044
	switch (x->node) {
1045 1046 1047
	case GREP_NODE_TRUE:
		h = 1;
		break;
1048
	case GREP_NODE_ATOM:
1049
		h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
1050 1051
		break;
	case GREP_NODE_NOT:
1052
		h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
J
Junio C Hamano 已提交
1053
		break;
1054
	case GREP_NODE_AND:
1055
		if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
1056
			return 0;
1057
		h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
J
Junio C Hamano 已提交
1058
		break;
1059
	case GREP_NODE_OR:
J
Junio C Hamano 已提交
1060
		if (!collect_hits)
1061
			return (match_expr_eval(x->u.binary.left,
J
Junio C Hamano 已提交
1062
						bol, eol, ctx, 0) ||
1063
				match_expr_eval(x->u.binary.right,
J
Junio C Hamano 已提交
1064
						bol, eol, ctx, 0));
1065
		h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
J
Junio C Hamano 已提交
1066
		x->u.binary.left->hit |= h;
1067
		h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
J
Junio C Hamano 已提交
1068 1069
		break;
	default:
1070
		die("Unexpected node type (internal error) %d", x->node);
1071
	}
J
Junio C Hamano 已提交
1072 1073 1074
	if (collect_hits)
		x->hit |= h;
	return h;
1075 1076
}

1077
static int match_expr(struct grep_opt *opt, char *bol, char *eol,
J
Junio C Hamano 已提交
1078
		      enum grep_context ctx, int collect_hits)
1079 1080
{
	struct grep_expr *x = opt->pattern_expression;
1081
	return match_expr_eval(x, bol, eol, ctx, collect_hits);
1082 1083
}

1084
static int match_line(struct grep_opt *opt, char *bol, char *eol,
J
Junio C Hamano 已提交
1085
		      enum grep_context ctx, int collect_hits)
1086 1087
{
	struct grep_pat *p;
1088 1089
	regmatch_t match;

1090
	if (opt->extended)
J
Junio C Hamano 已提交
1091 1092 1093
		return match_expr(opt, bol, eol, ctx, collect_hits);

	/* we do not call with collect_hits without being extended */
1094
	for (p = opt->pattern_list; p; p = p->next) {
1095
		if (match_one_pattern(p, bol, eol, ctx, &match, 0))
1096 1097 1098 1099 1100
			return 1;
	}
	return 0;
}

R
René Scharfe 已提交
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
			      enum grep_context ctx,
			      regmatch_t *pmatch, int eflags)
{
	regmatch_t match;

	if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
		return 0;
	if (match.rm_so < 0 || match.rm_eo < 0)
		return 0;
	if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
		if (match.rm_so > pmatch->rm_so)
			return 1;
		if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
			return 1;
	}
	pmatch->rm_so = match.rm_so;
	pmatch->rm_eo = match.rm_eo;
	return 1;
}

static int next_match(struct grep_opt *opt, char *bol, char *eol,
		      enum grep_context ctx, regmatch_t *pmatch, int eflags)
{
	struct grep_pat *p;
	int hit = 0;

	pmatch->rm_so = pmatch->rm_eo = -1;
	if (bol < eol) {
		for (p = opt->pattern_list; p; p = p->next) {
			switch (p->token) {
			case GREP_PATTERN: /* atom */
			case GREP_PATTERN_HEAD:
			case GREP_PATTERN_BODY:
				hit |= match_next_pattern(p, bol, eol, ctx,
							  pmatch, eflags);
				break;
			default:
				break;
			}
		}
	}
	return hit;
}

static void show_line(struct grep_opt *opt, char *bol, char *eol,
		      const char *name, unsigned lno, char sign)
{
	int rest = eol - bol;
1150
	const char *match_color, *line_color = NULL;
R
René Scharfe 已提交
1151

R
René Scharfe 已提交
1152 1153 1154
	if (opt->file_break && opt->last_shown == 0) {
		if (opt->show_hunk_mark)
			opt->output(opt, "\n", 1);
1155
	} else if (opt->pre_context || opt->post_context || opt->funcbody) {
1156
		if (opt->last_shown == 0) {
1157 1158 1159
			if (opt->show_hunk_mark) {
				output_color(opt, "--", 2, opt->color_sep);
				opt->output(opt, "\n", 1);
1160
			}
1161 1162 1163 1164
		} else if (lno > opt->last_shown + 1) {
			output_color(opt, "--", 2, opt->color_sep);
			opt->output(opt, "\n", 1);
		}
1165
	}
R
René Scharfe 已提交
1166 1167 1168 1169
	if (opt->heading && opt->last_shown == 0) {
		output_color(opt, name, strlen(name), opt->color_filename);
		opt->output(opt, "\n", 1);
	}
1170 1171
	opt->last_shown = lno;

R
René Scharfe 已提交
1172
	if (!opt->heading && opt->pathname) {
1173 1174
		output_color(opt, name, strlen(name), opt->color_filename);
		output_sep(opt, sign);
F
Fredrik Kuivinen 已提交
1175 1176 1177
	}
	if (opt->linenum) {
		char buf[32];
1178
		xsnprintf(buf, sizeof(buf), "%d", lno);
1179 1180
		output_color(opt, buf, strlen(buf), opt->color_lineno);
		output_sep(opt, sign);
F
Fredrik Kuivinen 已提交
1181
	}
R
René Scharfe 已提交
1182 1183 1184 1185 1186 1187
	if (opt->color) {
		regmatch_t match;
		enum grep_context ctx = GREP_CONTEXT_BODY;
		int ch = *eol;
		int eflags = 0;

1188 1189 1190 1191
		if (sign == ':')
			match_color = opt->color_match_selected;
		else
			match_color = opt->color_match_context;
1192 1193 1194 1195 1196 1197
		if (sign == ':')
			line_color = opt->color_selected;
		else if (sign == '-')
			line_color = opt->color_context;
		else if (sign == '=')
			line_color = opt->color_function;
R
René Scharfe 已提交
1198 1199
		*eol = '\0';
		while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1200 1201
			if (match.rm_so == match.rm_eo)
				break;
F
Fredrik Kuivinen 已提交
1202

1203
			output_color(opt, bol, match.rm_so, line_color);
1204
			output_color(opt, bol + match.rm_so,
1205
				     match.rm_eo - match.rm_so, match_color);
R
René Scharfe 已提交
1206 1207 1208 1209 1210 1211
			bol += match.rm_eo;
			rest -= match.rm_eo;
			eflags = REG_NOTBOL;
		}
		*eol = ch;
	}
1212
	output_color(opt, bol, rest, line_color);
F
Fredrik Kuivinen 已提交
1213
	opt->output(opt, "\n", 1);
R
René Scharfe 已提交
1214 1215
}

1216
#ifndef NO_PTHREADS
J
Jeff King 已提交
1217 1218
int grep_use_locks;

1219 1220 1221 1222 1223 1224
/*
 * This lock protects access to the gitattributes machinery, which is
 * not thread-safe.
 */
pthread_mutex_t grep_attr_mutex;

J
Jeff King 已提交
1225
static inline void grep_attr_lock(void)
1226
{
J
Jeff King 已提交
1227
	if (grep_use_locks)
1228 1229 1230
		pthread_mutex_lock(&grep_attr_mutex);
}

J
Jeff King 已提交
1231
static inline void grep_attr_unlock(void)
1232
{
J
Jeff King 已提交
1233
	if (grep_use_locks)
1234 1235
		pthread_mutex_unlock(&grep_attr_mutex);
}
1236 1237 1238 1239 1240 1241

/*
 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
 */
pthread_mutex_t grep_read_mutex;

1242
#else
J
Jeff King 已提交
1243 1244
#define grep_attr_lock()
#define grep_attr_unlock()
1245 1246
#endif

1247
static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1248
{
1249
	xdemitconf_t *xecfg = opt->priv;
1250
	if (xecfg && !xecfg->find_func) {
1251 1252 1253
		grep_source_load_driver(gs);
		if (gs->driver->funcname.pattern) {
			const struct userdiff_funcname *pe = &gs->driver->funcname;
1254 1255 1256 1257 1258 1259 1260
			xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
		} else {
			xecfg = opt->priv = NULL;
		}
	}

	if (xecfg) {
1261 1262 1263 1264 1265
		char buf[1];
		return xecfg->find_func(bol, eol - bol, buf, 1,
					xecfg->find_func_priv) >= 0;
	}

1266 1267 1268 1269 1270 1271 1272
	if (bol == eol)
		return 0;
	if (isalpha(*bol) || *bol == '_' || *bol == '$')
		return 1;
	return 0;
}

1273 1274
static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
			       char *bol, unsigned lno)
1275
{
1276
	while (bol > gs->buf) {
1277 1278
		char *eol = --bol;

1279
		while (bol > gs->buf && bol[-1] != '\n')
1280 1281 1282 1283 1284 1285
			bol--;
		lno--;

		if (lno <= opt->last_shown)
			break;

1286 1287
		if (match_funcname(opt, gs, bol, eol)) {
			show_line(opt, bol, eol, gs->name, lno, '=');
1288 1289 1290 1291 1292
			break;
		}
	}
}

1293
static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1294
			     char *bol, char *end, unsigned lno)
1295
{
1296
	unsigned cur = lno, from = 1, funcname_lno = 0;
1297 1298
	int funcname_needed = !!opt->funcname;

1299
	if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1300
		funcname_needed = 2;
1301 1302 1303 1304 1305 1306 1307

	if (opt->pre_context < lno)
		from = lno - opt->pre_context;
	if (from <= opt->last_shown)
		from = opt->last_shown + 1;

	/* Rewind. */
1308
	while (bol > gs->buf &&
1309
	       cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1310 1311
		char *eol = --bol;

1312
		while (bol > gs->buf && bol[-1] != '\n')
1313 1314
			bol--;
		cur--;
1315
		if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1316 1317 1318
			funcname_lno = cur;
			funcname_needed = 0;
		}
1319 1320
	}

1321 1322
	/* We need to look even further back to find a function signature. */
	if (opt->funcname && funcname_needed)
1323
		show_funcname_line(opt, gs, bol, cur);
1324

1325 1326
	/* Back forward. */
	while (cur < lno) {
1327
		char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1328 1329 1330

		while (*eol != '\n')
			eol++;
1331
		show_line(opt, bol, eol, gs->name, cur, sign);
1332 1333 1334 1335 1336
		bol = eol + 1;
		cur++;
	}
}

1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
static int should_lookahead(struct grep_opt *opt)
{
	struct grep_pat *p;

	if (opt->extended)
		return 0; /* punt for too complex stuff */
	if (opt->invert)
		return 0;
	for (p = opt->pattern_list; p; p = p->next) {
		if (p->token != GREP_PATTERN)
			return 0; /* punt for "header only" and stuff */
	}
	return 1;
}

static int look_ahead(struct grep_opt *opt,
		      unsigned long *left_p,
		      unsigned *lno_p,
		      char **bol_p)
{
	unsigned lno = *lno_p;
	char *bol = *bol_p;
	struct grep_pat *p;
	char *sp, *last_bol;
	regoff_t earliest = -1;

	for (p = opt->pattern_list; p; p = p->next) {
		int hit;
		regmatch_t m;

1367
		hit = patmatch(p, bol, bol + *left_p, &m, 0);
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
		if (!hit || m.rm_so < 0 || m.rm_eo < 0)
			continue;
		if (earliest < 0 || m.rm_so < earliest)
			earliest = m.rm_so;
	}

	if (earliest < 0) {
		*bol_p = bol + *left_p;
		*left_p = 0;
		return 1;
	}
	for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
		; /* find the beginning of the line */
	last_bol = sp;

	for (sp = bol; sp < last_bol; sp++) {
		if (*sp == '\n')
			lno++;
	}
	*left_p -= last_bol - bol;
	*bol_p = last_bol;
	*lno_p = lno;
	return 0;
}

J
Jeff King 已提交
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
static int fill_textconv_grep(struct userdiff_driver *driver,
			      struct grep_source *gs)
{
	struct diff_filespec *df;
	char *buf;
	size_t size;

	if (!driver || !driver->textconv)
		return grep_source_load(gs);

	/*
	 * The textconv interface is intimately tied to diff_filespecs, so we
	 * have to pretend to be one. If we could unify the grep_source
	 * and diff_filespec structs, this mess could just go away.
	 */
	df = alloc_filespec(gs->path);
	switch (gs->type) {
	case GREP_SOURCE_SHA1:
		fill_filespec(df, gs->identifier, 1, 0100644);
		break;
	case GREP_SOURCE_FILE:
		fill_filespec(df, null_sha1, 0, 0100644);
		break;
	default:
		die("BUG: attempt to textconv something without a path?");
	}

	/*
	 * fill_textconv is not remotely thread-safe; it may load objects
	 * behind the scenes, and it modifies the global diff tempfile
	 * structure.
	 */
	grep_read_lock();
	size = fill_textconv(driver, df, &buf);
	grep_read_unlock();
	free_filespec(df);

	/*
	 * The normal fill_textconv usage by the diff machinery would just keep
	 * the textconv'd buf separate from the diff_filespec. But much of the
	 * grep code passes around a grep_source and assumes that its "buf"
	 * pointer is the beginning of the thing we are searching. So let's
	 * install our textconv'd version into the grep_source, taking care not
	 * to leak any existing buffer.
	 */
	grep_source_clear_data(gs);
	gs->buf = buf;
	gs->size = size;

	return 0;
}

1445 1446 1447 1448 1449 1450 1451
static int is_empty_line(const char *bol, const char *eol)
{
	while (bol < eol && isspace(*bol))
		bol++;
	return bol == eol;
}

1452
static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1453
{
1454
	char *bol;
1455
	char *peek_bol = NULL;
1456
	unsigned long left;
1457 1458 1459 1460
	unsigned lno = 1;
	unsigned last_hit = 0;
	int binary_match_only = 0;
	unsigned count = 0;
1461
	int try_lookahead = 0;
1462
	int show_function = 0;
J
Jeff King 已提交
1463
	struct userdiff_driver *textconv = NULL;
1464
	enum grep_context ctx = GREP_CONTEXT_HEAD;
1465
	xdemitconf_t xecfg;
1466

F
Fredrik Kuivinen 已提交
1467 1468 1469
	if (!opt->output)
		opt->output = std_output;

1470 1471
	if (opt->pre_context || opt->post_context || opt->file_break ||
	    opt->funcbody) {
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
		/* Show hunk marks, except for the first file. */
		if (opt->last_shown)
			opt->show_hunk_mark = 1;
		/*
		 * If we're using threads then we can't easily identify
		 * the first file.  Always put hunk marks in that case
		 * and skip the very first one later in work_done().
		 */
		if (opt->output != std_output)
			opt->show_hunk_mark = 1;
	}
1483 1484
	opt->last_shown = 0;

J
Jeff King 已提交
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
	if (opt->allow_textconv) {
		grep_source_load_driver(gs);
		/*
		 * We might set up the shared textconv cache data here, which
		 * is not thread-safe.
		 */
		grep_attr_lock();
		textconv = userdiff_get_textconv(gs->driver);
		grep_attr_unlock();
	}

	/*
	 * We know the result of a textconv is text, so we only have to care
	 * about binary handling if we are not using it.
	 */
	if (!textconv) {
		switch (opt->binary) {
		case GREP_BINARY_DEFAULT:
			if (grep_source_is_binary(gs))
				binary_match_only = 1;
			break;
		case GREP_BINARY_NOMATCH:
			if (grep_source_is_binary(gs))
				return 0; /* Assume unmatch */
			break;
		case GREP_BINARY_TEXT:
			break;
		default:
1513
			die("BUG: unknown binary handling mode");
J
Jeff King 已提交
1514
		}
1515 1516
	}

1517
	memset(&xecfg, 0, sizeof(xecfg));
1518 1519
	opt->priv = &xecfg;

1520
	try_lookahead = should_lookahead(opt);
1521

J
Jeff King 已提交
1522
	if (fill_textconv_grep(textconv, gs) < 0)
1523 1524
		return 0;

1525 1526
	bol = gs->buf;
	left = gs->size;
1527 1528
	while (left) {
		char *eol, ch;
J
Junio C Hamano 已提交
1529
		int hit;
1530

1531
		/*
1532
		 * look_ahead() skips quickly to the line that possibly
1533 1534 1535 1536 1537 1538 1539 1540 1541
		 * has the next hit; don't call it if we need to do
		 * something more than just skipping the current line
		 * in response to an unmatch for the current line.  E.g.
		 * inside a post-context window, we will show the current
		 * line as a context around the previous hit when it
		 * doesn't hit.
		 */
		if (try_lookahead
		    && !(last_hit
1542 1543
			 && (show_function ||
			     lno <= last_hit + opt->post_context))
1544 1545
		    && look_ahead(opt, &left, &lno, &bol))
			break;
1546 1547 1548 1549
		eol = end_of_line(bol, &left);
		ch = *eol;
		*eol = 0;

1550 1551 1552
		if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
			ctx = GREP_CONTEXT_BODY;

J
Junio C Hamano 已提交
1553
		hit = match_line(opt, bol, eol, ctx, collect_hits);
1554 1555
		*eol = ch;

J
Junio C Hamano 已提交
1556 1557 1558
		if (collect_hits)
			goto next_line;

1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
		/* "grep -v -e foo -e bla" should list lines
		 * that do not have either, so inversion should
		 * be done outside.
		 */
		if (opt->invert)
			hit = !hit;
		if (opt->unmatch_name_only) {
			if (hit)
				return 0;
			goto next_line;
		}
		if (hit) {
			count++;
			if (opt->status_only)
				return 1;
R
René Scharfe 已提交
1574
			if (opt->name_only) {
1575
				show_name(opt, gs->name);
R
René Scharfe 已提交
1576 1577
				return 1;
			}
R
René Scharfe 已提交
1578 1579
			if (opt->count)
				goto next_line;
1580
			if (binary_match_only) {
F
Fredrik Kuivinen 已提交
1581
				opt->output(opt, "Binary file ", 12);
1582
				output_color(opt, gs->name, strlen(gs->name),
1583
					     opt->color_filename);
F
Fredrik Kuivinen 已提交
1584
				opt->output(opt, " matches\n", 9);
1585 1586 1587 1588 1589
				return 1;
			}
			/* Hit at this line.  If we haven't shown the
			 * pre-context lines, we would need to show them.
			 */
1590
			if (opt->pre_context || opt->funcbody)
1591
				show_pre_context(opt, gs, bol, eol, lno);
1592
			else if (opt->funcname)
1593 1594
				show_funcname_line(opt, gs, bol, lno);
			show_line(opt, bol, eol, gs->name, lno, ':');
1595
			last_hit = lno;
1596 1597 1598
			if (opt->funcbody)
				show_function = 1;
			goto next_line;
1599
		}
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
		if (show_function && (!peek_bol || peek_bol < bol)) {
			unsigned long peek_left = left;
			char *peek_eol = eol;

			/*
			 * Trailing empty lines are not interesting.
			 * Peek past them to see if they belong to the
			 * body of the current function.
			 */
			peek_bol = bol;
			while (is_empty_line(peek_bol, peek_eol)) {
				peek_bol = peek_eol + 1;
				peek_eol = end_of_line(peek_bol, &peek_left);
			}

			if (match_funcname(opt, gs, peek_bol, peek_eol))
				show_function = 0;
		}
1618 1619
		if (show_function ||
		    (last_hit && lno <= last_hit + opt->post_context)) {
1620 1621 1622
			/* If the last hit is within the post context,
			 * we need to show this line.
			 */
1623
			show_line(opt, bol, eol, gs->name, lno, '-');
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
		}

	next_line:
		bol = eol + 1;
		if (!left)
			break;
		left--;
		lno++;
	}

J
Junio C Hamano 已提交
1634 1635
	if (collect_hits)
		return 0;
1636

1637 1638 1639 1640
	if (opt->status_only)
		return 0;
	if (opt->unmatch_name_only) {
		/* We did not see any hit, so we want to show this */
1641
		show_name(opt, gs->name);
1642 1643 1644
		return 1;
	}

1645 1646 1647
	xdiff_clear_find_func(&xecfg);
	opt->priv = NULL;

1648 1649 1650 1651 1652
	/* NEEDSWORK:
	 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
	 * which feels mostly useless but sometimes useful.  Maybe
	 * make it another option?  For now suppress them.
	 */
F
Fredrik Kuivinen 已提交
1653 1654
	if (opt->count && count) {
		char buf[32];
1655 1656 1657 1658 1659
		if (opt->pathname) {
			output_color(opt, gs->name, strlen(gs->name),
				     opt->color_filename);
			output_sep(opt, ':');
		}
1660
		xsnprintf(buf, sizeof(buf), "%u\n", count);
F
Fredrik Kuivinen 已提交
1661
		opt->output(opt, buf, strlen(buf));
R
René Scharfe 已提交
1662
		return 1;
F
Fredrik Kuivinen 已提交
1663
	}
1664 1665 1666
	return !!last_hit;
}

J
Junio C Hamano 已提交
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
static void clr_hit_marker(struct grep_expr *x)
{
	/* All-hit markers are meaningful only at the very top level
	 * OR node.
	 */
	while (1) {
		x->hit = 0;
		if (x->node != GREP_NODE_OR)
			return;
		x->u.binary.left->hit = 0;
		x = x->u.binary.right;
	}
}

static int chk_hit_marker(struct grep_expr *x)
{
	/* Top level nodes have hit markers.  See if they all are hits */
	while (1) {
		if (x->node != GREP_NODE_OR)
			return x->hit;
		if (!x->u.binary.left->hit)
			return 0;
		x = x->u.binary.right;
	}
}

1693
int grep_source(struct grep_opt *opt, struct grep_source *gs)
J
Junio C Hamano 已提交
1694 1695 1696 1697 1698 1699
{
	/*
	 * we do not have to do the two-pass grep when we do not check
	 * buffer-wide "all-match".
	 */
	if (!opt->all_match)
1700
		return grep_source_1(opt, gs, 0);
J
Junio C Hamano 已提交
1701 1702 1703 1704 1705

	/* Otherwise the toplevel "or" terms hit a bit differently.
	 * We first clear hit markers from them.
	 */
	clr_hit_marker(opt->pattern_expression);
1706
	grep_source_1(opt, gs, 1);
J
Junio C Hamano 已提交
1707 1708 1709 1710

	if (!chk_hit_marker(opt->pattern_expression))
		return 0;

1711 1712 1713
	return grep_source_1(opt, gs, 0);
}

1714
int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1715 1716 1717 1718
{
	struct grep_source gs;
	int r;

1719
	grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
	gs.buf = buf;
	gs.size = size;

	r = grep_source(opt, &gs);

	grep_source_clear(&gs);
	return r;
}

void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1730 1731
		      const char *name, const char *path,
		      const void *identifier)
1732 1733
{
	gs->type = type;
1734 1735
	gs->name = xstrdup_or_null(name);
	gs->path = xstrdup_or_null(path);
1736 1737
	gs->buf = NULL;
	gs->size = 0;
1738
	gs->driver = NULL;
1739 1740 1741 1742 1743

	switch (type) {
	case GREP_SOURCE_FILE:
		gs->identifier = xstrdup(identifier);
		break;
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
	case GREP_SOURCE_SUBMODULE:
		if (!identifier) {
			gs->identifier = NULL;
			break;
		}
		/*
		 * FALL THROUGH
		 * If the identifier is non-NULL (in the submodule case) it
		 * will be a SHA1 that needs to be copied.
		 */
1754 1755
	case GREP_SOURCE_SHA1:
		gs->identifier = xmalloc(20);
S
Sun He 已提交
1756
		hashcpy(gs->identifier, identifier);
1757 1758 1759
		break;
	case GREP_SOURCE_BUF:
		gs->identifier = NULL;
1760
		break;
1761 1762 1763 1764 1765 1766 1767
	}
}

void grep_source_clear(struct grep_source *gs)
{
	free(gs->name);
	gs->name = NULL;
1768 1769
	free(gs->path);
	gs->path = NULL;
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
	free(gs->identifier);
	gs->identifier = NULL;
	grep_source_clear_data(gs);
}

void grep_source_clear_data(struct grep_source *gs)
{
	switch (gs->type) {
	case GREP_SOURCE_FILE:
	case GREP_SOURCE_SHA1:
1780
	case GREP_SOURCE_SUBMODULE:
1781
		FREE_AND_NULL(gs->buf);
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
		gs->size = 0;
		break;
	case GREP_SOURCE_BUF:
		/* leave user-provided buf intact */
		break;
	}
}

static int grep_source_load_sha1(struct grep_source *gs)
{
	enum object_type type;

	grep_read_lock();
	gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
	grep_read_unlock();

	if (!gs->buf)
		return error(_("'%s': unable to read %s"),
			     gs->name,
			     sha1_to_hex(gs->identifier));
	return 0;
}

static int grep_source_load_file(struct grep_source *gs)
{
	const char *filename = gs->identifier;
	struct stat st;
	char *data;
	size_t size;
	int i;

	if (lstat(filename, &st) < 0) {
	err_ret:
		if (errno != ENOENT)
1816
			error_errno(_("failed to stat '%s'"), filename);
1817 1818 1819 1820 1821 1822 1823 1824
		return -1;
	}
	if (!S_ISREG(st.st_mode))
		return -1;
	size = xsize_t(st.st_size);
	i = open(filename, O_RDONLY);
	if (i < 0)
		goto err_ret;
1825
	data = xmallocz(size);
1826
	if (st.st_size != read_in_full(i, data, size)) {
1827
		error_errno(_("'%s': short read"), filename);
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
		close(i);
		free(data);
		return -1;
	}
	close(i);

	gs->buf = data;
	gs->size = size;
	return 0;
}

1839
static int grep_source_load(struct grep_source *gs)
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
{
	if (gs->buf)
		return 0;

	switch (gs->type) {
	case GREP_SOURCE_FILE:
		return grep_source_load_file(gs);
	case GREP_SOURCE_SHA1:
		return grep_source_load_sha1(gs);
	case GREP_SOURCE_BUF:
		return gs->buf ? 0 : -1;
1851 1852
	case GREP_SOURCE_SUBMODULE:
		break;
1853
	}
1854
	die("BUG: invalid grep_source type to load");
J
Junio C Hamano 已提交
1855
}
1856 1857 1858 1859 1860 1861 1862

void grep_source_load_driver(struct grep_source *gs)
{
	if (gs->driver)
		return;

	grep_attr_lock();
1863 1864
	if (gs->path)
		gs->driver = userdiff_find_by_path(gs->path);
1865 1866 1867 1868
	if (!gs->driver)
		gs->driver = userdiff_find_by_name("default");
	grep_attr_unlock();
}
1869

1870
static int grep_source_is_binary(struct grep_source *gs)
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
{
	grep_source_load_driver(gs);
	if (gs->driver->binary != -1)
		return gs->driver->binary;

	if (!grep_source_load(gs))
		return buffer_is_binary(gs->buf, gs->size);

	return 0;
}