grep.c 26.2 KB
Newer Older
1 2
#include "cache.h"
#include "grep.h"
3
#include "userdiff.h"
4
#include "xdiff-interface.h"
5

6 7 8 9
void append_header_grep_pattern(struct grep_opt *opt, enum grep_header_field field, const char *pat)
{
	struct grep_pat *p = xcalloc(1, sizeof(*p));
	p->pattern = pat;
10
	p->patternlen = strlen(pat);
11 12 13 14
	p->origin = "header";
	p->no = 0;
	p->token = GREP_PATTERN_HEAD;
	p->field = field;
15 16
	*opt->header_tail = p;
	opt->header_tail = &p->next;
17 18 19
	p->next = NULL;
}

20 21
void append_grep_pattern(struct grep_opt *opt, const char *pat,
			 const char *origin, int no, enum grep_pat_token t)
22 23 24 25 26 27
{
	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)
28 29 30
{
	struct grep_pat *p = xcalloc(1, sizeof(*p));
	p->pattern = pat;
31
	p->patternlen = patlen;
32 33 34 35 36 37 38 39
	p->origin = origin;
	p->no = no;
	p->token = t;
	*opt->pattern_tail = p;
	opt->pattern_tail = &p->next;
	p->next = NULL;
}

F
Fredrik Kuivinen 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
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
55 56
			append_grep_pat(ret, pat->pattern, pat->patternlen,
					pat->origin, pat->no, pat->token);
F
Fredrik Kuivinen 已提交
57 58 59 60 61
	}

	return ret;
}

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
static NORETURN void compile_regexp_failed(const struct grep_pat *p,
		const char *error)
{
	char where[1024];

	if (p->no)
		sprintf(where, "In '%s' at %d, ", p->origin, p->no);
	else if (p->origin)
		sprintf(where, "%s, ", p->origin);
	else
		where[0] = 0;

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

M
Michał Kiedrowicz 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
#ifdef USE_LIBPCRE
static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
{
	const char *error;
	int erroffset;
	int options = 0;

	if (opt->ignore_case)
		options |= PCRE_CASELESS;

	p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
			NULL);
	if (!p->pcre_regexp)
		compile_regexp_failed(p, error);

	p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
	if (!p->pcre_extra_info && error)
		die("%s", error);
}

static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
		regmatch_t *match, int eflags)
{
	int ovector[30], ret, flags = 0;

	if (eflags & REG_NOTBOL)
		flags |= PCRE_NOTBOL;

	ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
			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;
}

static void free_pcre_regexp(struct grep_pat *p)
{
	pcre_free(p->pcre_regexp);
	pcre_free(p->pcre_extra_info);
}
#else /* !USE_LIBPCRE */
static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
{
	die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
}

static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
		regmatch_t *match, int eflags)
{
	return 1;
}

static void free_pcre_regexp(struct grep_pat *p)
{
}
#endif /* !USE_LIBPCRE */

140 141
static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
{
142 143
	int err;

144
	p->word_regexp = opt->word_regexp;
145
	p->ignore_case = opt->ignore_case;
146
	p->fixed = opt->fixed;
147

148 149 150
	if (p->fixed)
		return;

M
Michał Kiedrowicz 已提交
151 152 153 154 155
	if (opt->pcre) {
		compile_pcre_regexp(p, opt);
		return;
	}

156
	err = regcomp(&p->regexp, p->pattern, opt->regflags);
157 158 159 160
	if (err) {
		char errbuf[1024];
		regerror(err, &p->regexp, errbuf, 1024);
		regfree(&p->regexp);
161
		compile_regexp_failed(p, errbuf);
162 163 164
	}
}

J
Junio C Hamano 已提交
165
static struct grep_expr *compile_pattern_or(struct grep_pat **);
166 167 168 169 170 171
static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
{
	struct grep_pat *p;
	struct grep_expr *x;

	p = *list;
172 173
	if (!p)
		return NULL;
174 175
	switch (p->token) {
	case GREP_PATTERN: /* atom */
176 177
	case GREP_PATTERN_HEAD:
	case GREP_PATTERN_BODY:
178 179 180 181 182 183 184
		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 已提交
185
		x = compile_pattern_or(list);
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
		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;
201 202
	if (!p)
		return NULL;
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 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 262 263 264 265 266
	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);
}

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
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;
}

283
static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
284 285
{
	struct grep_pat *p;
286
	struct grep_expr *header_expr;
287 288
	struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
	enum grep_header_field fld;
289

290 291 292 293 294 295 296 297 298
	if (!opt->header_list)
		return NULL;
	p = opt->header_list;
	for (p = opt->header_list; p; p = p->next) {
		if (p->token != GREP_PATTERN_HEAD)
			die("bug: a non-header pattern in grep header list.");
		if (p->field < 0 || GREP_HEADER_FIELD_MAX <= p->field)
			die("bug: unknown header field %d", p->field);
		compile_regexp(p, opt);
299
	}
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326

	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)
			die("bug: malformed header expr");
		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);
	}
327 328 329 330 331 332 333
	return header_expr;
}

void compile_grep_patterns(struct grep_opt *opt)
{
	struct grep_pat *p;
	struct grep_expr *header_expr = prep_header_patterns(opt);
J
Junio C Hamano 已提交
334

335
	for (p = opt->pattern_list; p; p = p->next) {
336 337 338 339
		switch (p->token) {
		case GREP_PATTERN: /* atom */
		case GREP_PATTERN_HEAD:
		case GREP_PATTERN_BODY:
340
			compile_regexp(p, opt);
341 342
			break;
		default:
343
			opt->extended = 1;
344 345
			break;
		}
346 347
	}

348 349 350
	if (opt->all_match || header_expr)
		opt->extended = 1;
	else if (!opt->extended)
351 352 353
		return;

	p = opt->pattern_list;
354 355
	if (p)
		opt->pattern_expression = compile_pattern_expr(&p);
356 357
	if (p)
		die("incomplete pattern expression: %s", p->pattern);
358 359 360 361

	if (!header_expr)
		return;

362
	if (!opt->pattern_expression)
363
		opt->pattern_expression = header_expr;
364 365 366
	else
		opt->pattern_expression = grep_or_expr(opt->pattern_expression,
						       header_expr);
367
	opt->all_match = 1;
368 369
}

370 371 372
static void free_pattern_expr(struct grep_expr *x)
{
	switch (x->node) {
373
	case GREP_NODE_TRUE:
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
	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:
M
Michał Kiedrowicz 已提交
398 399 400 401
			if (p->pcre_regexp)
				free_pcre_regexp(p);
			else
				regfree(&p->regexp);
402 403 404 405 406 407 408 409 410 411 412 413
			break;
		default:
			break;
		}
		free(p);
	}

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

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
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 == '_';
}

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
static void output_color(struct grep_opt *opt, const void *data, size_t size,
			 const char *color)
{
	if (opt->color && color && color[0]) {
		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);
}

449 450
static void show_name(struct grep_opt *opt, const char *name)
{
451
	output_color(opt, name, strlen(name), opt->color_filename);
F
Fredrik Kuivinen 已提交
452
	opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
453 454
}

455 456
static int fixmatch(struct grep_pat *p, char *line, char *eol,
		    regmatch_t *match)
457
{
458
	char *hit;
459

460
	if (p->ignore_case) {
461 462
		char *s = line;
		do {
463
			hit = strcasestr(s, p->pattern);
464 465 466 467 468
			if (hit)
				break;
			s += strlen(s) + 1;
		} while (s < eol);
	} else
469
		hit = memmem(line, eol - line, p->pattern, p->patternlen);
470

471 472 473 474 475 476
	if (!hit) {
		match->rm_so = match->rm_eo = -1;
		return REG_NOMATCH;
	}
	else {
		match->rm_so = hit - line;
477
		match->rm_eo = match->rm_so + p->patternlen;
478 479 480 481
		return 0;
	}
}

482 483 484 485 486 487 488 489 490 491 492
static int regmatch(const regex_t *preg, char *line, char *eol,
		    regmatch_t *match, int eflags)
{
#ifdef REG_STARTEND
	match->rm_so = 0;
	match->rm_eo = eol - line;
	eflags |= REG_STARTEND;
#endif
	return regexec(preg, line, 1, match, eflags);
}

493 494 495 496 497 498 499
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);
M
Michał Kiedrowicz 已提交
500 501
	else if (p->pcre_regexp)
		hit = !pcrematch(p, line, eol, match, eflags);
502 503 504 505 506 507
	else
		hit = !regmatch(&p->regexp, line, eol, match, eflags);

	return hit;
}

508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
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 },
};

532
static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
533 534
			     enum grep_context ctx,
			     regmatch_t *pmatch, int eflags)
535 536
{
	int hit = 0;
537
	int saved_ch = 0;
R
René Scharfe 已提交
538
	const char *start = bol;
539

540 541 542 543
	if ((p->token != GREP_PATTERN) &&
	    ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
		return 0;

544 545 546 547 548 549 550 551 552 553 554 555
	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;
		saved_ch = strip_timestamp(bol, &eol);
	}

556
 again:
557
	hit = patmatch(p, bol, eol, pmatch, eflags);
558

559
	if (hit && p->word_regexp) {
560
		if ((pmatch[0].rm_so < 0) ||
561
		    (eol - bol) < pmatch[0].rm_so ||
562 563 564 565 566 567 568 569 570 571
		    (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).
		 */
572
		if ( ((pmatch[0].rm_so == 0) ||
573 574 575 576 577 578 579
		      !word_char(bol[pmatch[0].rm_so-1])) &&
		     ((pmatch[0].rm_eo == (eol-bol)) ||
		      !word_char(bol[pmatch[0].rm_eo])) )
			;
		else
			hit = 0;

580 581 582 583
		/* Words consist of at least one character. */
		if (pmatch->rm_so == pmatch->rm_eo)
			hit = 0;

584 585 586 587
		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!
588 589
			 * Forward to the next possible start, i.e. the
			 * next position following a non-word char.
590 591
			 */
			bol = pmatch[0].rm_so + bol + 1;
592 593
			while (word_char(bol[-1]) && bol < eol)
				bol++;
594
			eflags |= REG_NOTBOL;
595 596
			if (bol < eol)
				goto again;
597 598
		}
	}
599 600
	if (p->token == GREP_PATTERN_HEAD && saved_ch)
		*eol = saved_ch;
R
René Scharfe 已提交
601 602 603 604
	if (hit) {
		pmatch[0].rm_so += bol - start;
		pmatch[0].rm_eo += bol - start;
	}
605 606 607
	return hit;
}

608 609
static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
			   enum grep_context ctx, int collect_hits)
610
{
J
Junio C Hamano 已提交
611
	int h = 0;
612
	regmatch_t match;
J
Junio C Hamano 已提交
613

614 615
	if (!x)
		die("Not a valid grep expression");
616
	switch (x->node) {
617 618 619
	case GREP_NODE_TRUE:
		h = 1;
		break;
620
	case GREP_NODE_ATOM:
621
		h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
622 623
		break;
	case GREP_NODE_NOT:
624
		h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
J
Junio C Hamano 已提交
625
		break;
626
	case GREP_NODE_AND:
627
		if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
628
			return 0;
629
		h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
J
Junio C Hamano 已提交
630
		break;
631
	case GREP_NODE_OR:
J
Junio C Hamano 已提交
632
		if (!collect_hits)
633
			return (match_expr_eval(x->u.binary.left,
J
Junio C Hamano 已提交
634
						bol, eol, ctx, 0) ||
635
				match_expr_eval(x->u.binary.right,
J
Junio C Hamano 已提交
636
						bol, eol, ctx, 0));
637
		h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
J
Junio C Hamano 已提交
638
		x->u.binary.left->hit |= h;
639
		h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
J
Junio C Hamano 已提交
640 641
		break;
	default:
642
		die("Unexpected node type (internal error) %d", x->node);
643
	}
J
Junio C Hamano 已提交
644 645 646
	if (collect_hits)
		x->hit |= h;
	return h;
647 648
}

649
static int match_expr(struct grep_opt *opt, char *bol, char *eol,
J
Junio C Hamano 已提交
650
		      enum grep_context ctx, int collect_hits)
651 652
{
	struct grep_expr *x = opt->pattern_expression;
653
	return match_expr_eval(x, bol, eol, ctx, collect_hits);
654 655
}

656
static int match_line(struct grep_opt *opt, char *bol, char *eol,
J
Junio C Hamano 已提交
657
		      enum grep_context ctx, int collect_hits)
658 659
{
	struct grep_pat *p;
660 661
	regmatch_t match;

662
	if (opt->extended)
J
Junio C Hamano 已提交
663 664 665
		return match_expr(opt, bol, eol, ctx, collect_hits);

	/* we do not call with collect_hits without being extended */
666
	for (p = opt->pattern_list; p; p = p->next) {
667
		if (match_one_pattern(p, bol, eol, ctx, &match, 0))
668 669 670 671 672
			return 1;
	}
	return 0;
}

R
René Scharfe 已提交
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
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;
722
	char *line_color = NULL;
R
René Scharfe 已提交
723

R
René Scharfe 已提交
724 725 726 727
	if (opt->file_break && opt->last_shown == 0) {
		if (opt->show_hunk_mark)
			opt->output(opt, "\n", 1);
	} else if (opt->pre_context || opt->post_context) {
728
		if (opt->last_shown == 0) {
729 730 731
			if (opt->show_hunk_mark) {
				output_color(opt, "--", 2, opt->color_sep);
				opt->output(opt, "\n", 1);
732
			}
733 734 735 736
		} else if (lno > opt->last_shown + 1) {
			output_color(opt, "--", 2, opt->color_sep);
			opt->output(opt, "\n", 1);
		}
737
	}
R
René Scharfe 已提交
738 739 740 741
	if (opt->heading && opt->last_shown == 0) {
		output_color(opt, name, strlen(name), opt->color_filename);
		opt->output(opt, "\n", 1);
	}
742 743
	opt->last_shown = lno;

R
René Scharfe 已提交
744
	if (!opt->heading && opt->pathname) {
745 746
		output_color(opt, name, strlen(name), opt->color_filename);
		output_sep(opt, sign);
F
Fredrik Kuivinen 已提交
747 748 749 750
	}
	if (opt->linenum) {
		char buf[32];
		snprintf(buf, sizeof(buf), "%d", lno);
751 752
		output_color(opt, buf, strlen(buf), opt->color_lineno);
		output_sep(opt, sign);
F
Fredrik Kuivinen 已提交
753
	}
R
René Scharfe 已提交
754 755 756 757 758 759
	if (opt->color) {
		regmatch_t match;
		enum grep_context ctx = GREP_CONTEXT_BODY;
		int ch = *eol;
		int eflags = 0;

760 761 762 763 764 765
		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 已提交
766 767
		*eol = '\0';
		while (next_match(opt, bol, eol, ctx, &match, eflags)) {
768 769
			if (match.rm_so == match.rm_eo)
				break;
F
Fredrik Kuivinen 已提交
770

771
			output_color(opt, bol, match.rm_so, line_color);
772 773 774
			output_color(opt, bol + match.rm_so,
				     match.rm_eo - match.rm_so,
				     opt->color_match);
R
René Scharfe 已提交
775 776 777 778 779 780
			bol += match.rm_eo;
			rest -= match.rm_eo;
			eflags = REG_NOTBOL;
		}
		*eol = ch;
	}
781
	output_color(opt, bol, rest, line_color);
F
Fredrik Kuivinen 已提交
782
	opt->output(opt, "\n", 1);
R
René Scharfe 已提交
783 784
}

785
static int match_funcname(struct grep_opt *opt, char *bol, char *eol)
786
{
787 788 789 790 791 792 793
	xdemitconf_t *xecfg = opt->priv;
	if (xecfg && xecfg->find_func) {
		char buf[1];
		return xecfg->find_func(bol, eol - bol, buf, 1,
					xecfg->find_func_priv) >= 0;
	}

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
	if (bol == eol)
		return 0;
	if (isalpha(*bol) || *bol == '_' || *bol == '$')
		return 1;
	return 0;
}

static void show_funcname_line(struct grep_opt *opt, const char *name,
			       char *buf, char *bol, unsigned lno)
{
	while (bol > buf) {
		char *eol = --bol;

		while (bol > buf && bol[-1] != '\n')
			bol--;
		lno--;

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

814
		if (match_funcname(opt, bol, eol)) {
815 816 817 818 819 820
			show_line(opt, bol, eol, name, lno, '=');
			break;
		}
	}
}

821 822 823
static void show_pre_context(struct grep_opt *opt, const char *name, char *buf,
			     char *bol, unsigned lno)
{
824 825
	unsigned cur = lno, from = 1, funcname_lno = 0;
	int funcname_needed = opt->funcname;
826 827 828 829 830 831 832 833

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

	/* Rewind. */
	while (bol > buf && cur > from) {
834 835
		char *eol = --bol;

836 837 838
		while (bol > buf && bol[-1] != '\n')
			bol--;
		cur--;
839
		if (funcname_needed && match_funcname(opt, bol, eol)) {
840 841 842
			funcname_lno = cur;
			funcname_needed = 0;
		}
843 844
	}

845 846 847 848
	/* We need to look even further back to find a function signature. */
	if (opt->funcname && funcname_needed)
		show_funcname_line(opt, name, buf, bol, cur);

849 850
	/* Back forward. */
	while (cur < lno) {
851
		char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
852 853 854

		while (*eol != '\n')
			eol++;
855
		show_line(opt, bol, eol, name, cur, sign);
856 857 858 859 860
		bol = eol + 1;
		cur++;
	}
}

861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
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;

891
		hit = patmatch(p, bol, bol + *left_p, &m, 0);
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
		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;
}

F
Fredrik Kuivinen 已提交
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
int grep_threads_ok(const struct grep_opt *opt)
{
	/* If this condition is true, then we may use the attribute
	 * machinery in grep_buffer_1. The attribute code is not
	 * thread safe, so we disable the use of threads.
	 */
	if (opt->funcname && !opt->unmatch_name_only && !opt->status_only &&
	    !opt->name_only)
		return 0;

	return 1;
}

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

J
Junio C Hamano 已提交
935 936
static int grep_buffer_1(struct grep_opt *opt, const char *name,
			 char *buf, unsigned long size, int collect_hits)
937 938 939 940 941 942 943
{
	char *bol = buf;
	unsigned long left = size;
	unsigned lno = 1;
	unsigned last_hit = 0;
	int binary_match_only = 0;
	unsigned count = 0;
944
	int try_lookahead = 0;
945
	enum grep_context ctx = GREP_CONTEXT_HEAD;
946
	xdemitconf_t xecfg;
947

F
Fredrik Kuivinen 已提交
948 949 950
	if (!opt->output)
		opt->output = std_output;

R
René Scharfe 已提交
951
	if (opt->pre_context || opt->post_context || opt->file_break) {
952 953 954 955 956 957 958 959 960 961 962
		/* 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;
	}
963 964
	opt->last_shown = 0;

965 966 967
	switch (opt->binary) {
	case GREP_BINARY_DEFAULT:
		if (buffer_is_binary(buf, size))
968
			binary_match_only = 1;
969 970 971
		break;
	case GREP_BINARY_NOMATCH:
		if (buffer_is_binary(buf, size))
972
			return 0; /* Assume unmatch */
973 974 975 976 977
		break;
	case GREP_BINARY_TEXT:
		break;
	default:
		die("bug: unknown binary handling mode");
978 979
	}

980 981 982 983 984 985 986 987 988 989
	memset(&xecfg, 0, sizeof(xecfg));
	if (opt->funcname && !opt->unmatch_name_only && !opt->status_only &&
	    !opt->name_only && !binary_match_only && !collect_hits) {
		struct userdiff_driver *drv = userdiff_find_by_path(name);
		if (drv && drv->funcname.pattern) {
			const struct userdiff_funcname *pe = &drv->funcname;
			xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
			opt->priv = &xecfg;
		}
	}
990
	try_lookahead = should_lookahead(opt);
991

992 993
	while (left) {
		char *eol, ch;
J
Junio C Hamano 已提交
994
		int hit;
995

996
		/*
997
		 * look_ahead() skips quickly to the line that possibly
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
		 * 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
			 && lno <= last_hit + opt->post_context)
		    && look_ahead(opt, &left, &lno, &bol))
			break;
1010 1011 1012 1013
		eol = end_of_line(bol, &left);
		ch = *eol;
		*eol = 0;

1014 1015 1016
		if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
			ctx = GREP_CONTEXT_BODY;

J
Junio C Hamano 已提交
1017
		hit = match_line(opt, bol, eol, ctx, collect_hits);
1018 1019
		*eol = ch;

J
Junio C Hamano 已提交
1020 1021 1022
		if (collect_hits)
			goto next_line;

1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
		/* "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 已提交
1038 1039 1040 1041
			if (opt->name_only) {
				show_name(opt, name);
				return 1;
			}
R
René Scharfe 已提交
1042 1043
			if (opt->count)
				goto next_line;
1044
			if (binary_match_only) {
F
Fredrik Kuivinen 已提交
1045
				opt->output(opt, "Binary file ", 12);
1046 1047
				output_color(opt, name, strlen(name),
					     opt->color_filename);
F
Fredrik Kuivinen 已提交
1048
				opt->output(opt, " matches\n", 9);
1049 1050 1051 1052 1053
				return 1;
			}
			/* Hit at this line.  If we haven't shown the
			 * pre-context lines, we would need to show them.
			 */
1054 1055
			if (opt->pre_context)
				show_pre_context(opt, name, buf, bol, lno);
1056 1057
			else if (opt->funcname)
				show_funcname_line(opt, name, buf, bol, lno);
R
René Scharfe 已提交
1058
			show_line(opt, bol, eol, name, lno, ':');
1059
			last_hit = lno;
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
		}
		else if (last_hit &&
			 lno <= last_hit + opt->post_context) {
			/* If the last hit is within the post context,
			 * we need to show this line.
			 */
			show_line(opt, bol, eol, name, lno, '-');
		}

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

J
Junio C Hamano 已提交
1077 1078
	if (collect_hits)
		return 0;
1079

1080 1081 1082 1083
	if (opt->status_only)
		return 0;
	if (opt->unmatch_name_only) {
		/* We did not see any hit, so we want to show this */
1084
		show_name(opt, name);
1085 1086 1087
		return 1;
	}

1088 1089 1090
	xdiff_clear_find_func(&xecfg);
	opt->priv = NULL;

1091 1092 1093 1094 1095
	/* 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 已提交
1096 1097
	if (opt->count && count) {
		char buf[32];
1098 1099 1100
		output_color(opt, name, strlen(name), opt->color_filename);
		output_sep(opt, ':');
		snprintf(buf, sizeof(buf), "%u\n", count);
F
Fredrik Kuivinen 已提交
1101
		opt->output(opt, buf, strlen(buf));
R
René Scharfe 已提交
1102
		return 1;
F
Fredrik Kuivinen 已提交
1103
	}
1104 1105 1106
	return !!last_hit;
}

J
Junio C Hamano 已提交
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 1150 1151 1152
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;
	}
}

int grep_buffer(struct grep_opt *opt, const char *name, char *buf, unsigned long size)
{
	/*
	 * we do not have to do the two-pass grep when we do not check
	 * buffer-wide "all-match".
	 */
	if (!opt->all_match)
		return grep_buffer_1(opt, name, buf, size, 0);

	/* Otherwise the toplevel "or" terms hit a bit differently.
	 * We first clear hit markers from them.
	 */
	clr_hit_marker(opt->pattern_expression);
	grep_buffer_1(opt, name, buf, size, 1);

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

	return grep_buffer_1(opt, name, buf, size, 0);
}