xref: /netbsd-src/usr.bin/make/cond.c (revision 3117ece4fc4a4ca4489ba793710b60b0d26bab6c)
1 /*	$NetBSD: cond.c,v 1.369 2024/08/07 05:48:45 rillig Exp $	*/
2 
3 /*
4  * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * Copyright (c) 1988, 1989 by Adam de Boor
37  * Copyright (c) 1989 by Berkeley Softworks
38  * All rights reserved.
39  *
40  * This code is derived from software contributed to Berkeley by
41  * Adam de Boor.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. All advertising materials mentioning features or use of this software
52  *    must display the following acknowledgement:
53  *	This product includes software developed by the University of
54  *	California, Berkeley and its contributors.
55  * 4. Neither the name of the University nor the names of its contributors
56  *    may be used to endorse or promote products derived from this software
57  *    without specific prior written permission.
58  *
59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69  * SUCH DAMAGE.
70  */
71 
72 /*
73  * Handling of conditionals in a makefile.
74  *
75  * Interface:
76  *	Cond_EvalLine   Evaluate the conditional directive, such as
77  *			'.if <cond>', '.elifnmake <cond>', '.else', '.endif'.
78  *
79  *	Cond_EvalCondition
80  *			Evaluate the conditional, which is either the argument
81  *			of one of the .if directives or the condition in a
82  *			':?then:else' variable modifier.
83  *
84  *	Cond_EndFile	At the end of reading a makefile, ensure that the
85  *			conditional directives are well-balanced.
86  */
87 
88 #include <errno.h>
89 
90 #include "make.h"
91 #include "dir.h"
92 
93 /*	"@(#)cond.c	8.2 (Berkeley) 1/2/94"	*/
94 MAKE_RCSID("$NetBSD: cond.c,v 1.369 2024/08/07 05:48:45 rillig Exp $");
95 
96 /*
97  * Conditional expressions conform to this grammar:
98  *	Or -> And ('||' And)*
99  *	And -> Term ('&&' Term)*
100  *	Term -> Function '(' Argument ')'
101  *	Term -> Leaf Operator Leaf
102  *	Term -> Leaf
103  *	Term -> '(' Or ')'
104  *	Term -> '!' Term
105  *	Leaf -> "string"
106  *	Leaf -> Number
107  *	Leaf -> VariableExpression
108  *	Leaf -> BareWord
109  *	Operator -> '==' | '!=' | '>' | '<' | '>=' | '<='
110  *
111  * BareWord is an unquoted string literal, its evaluation depends on the kind
112  * of '.if' directive.
113  *
114  * The tokens are scanned by CondParser_Token, which returns:
115  *	TOK_AND		for '&&'
116  *	TOK_OR		for '||'
117  *	TOK_NOT		for '!'
118  *	TOK_LPAREN	for '('
119  *	TOK_RPAREN	for ')'
120  *
121  * Other terminal symbols are evaluated using either the default function or
122  * the function given in the terminal, they return either TOK_TRUE, TOK_FALSE
123  * or TOK_ERROR.
124  */
125 typedef enum Token {
126 	TOK_FALSE, TOK_TRUE, TOK_AND, TOK_OR, TOK_NOT,
127 	TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
128 } Token;
129 
130 typedef enum ComparisonOp {
131 	LT, LE, GT, GE, EQ, NE
132 } ComparisonOp;
133 
134 typedef struct CondParser {
135 
136 	/*
137 	 * The plain '.if ${VAR}' evaluates to true if the value of the
138 	 * expression has length > 0 and is not numerically zero.  The other
139 	 * '.if' variants delegate to evalBare instead, for example '.ifdef
140 	 * ${VAR}' is equivalent to '.if defined(${VAR})', checking whether
141 	 * the variable named by the expression '${VAR}' is defined.
142 	 */
143 	bool plain;
144 
145 	/* The function to apply on unquoted bare words. */
146 	bool (*evalBare)(const char *);
147 	bool negateEvalBare;
148 
149 	/*
150 	 * Whether the left-hand side of a comparison may be an unquoted
151 	 * string.  This is allowed for expressions of the form
152 	 * ${condition:?:}, see ApplyModifier_IfElse.  Such a condition is
153 	 * expanded before it is evaluated, due to ease of implementation.
154 	 * This means that at the point where the condition is evaluated,
155 	 * make cannot know anymore whether the left-hand side had originally
156 	 * been an expression or a plain word.
157 	 *
158 	 * In conditional directives like '.if', the left-hand side must
159 	 * either be an expression, a quoted string or a number.
160 	 */
161 	bool leftUnquotedOK;
162 
163 	const char *p;		/* The remaining condition to parse */
164 	Token curr;		/* Single push-back token used in parsing */
165 
166 	/*
167 	 * Whether an error message has already been printed for this
168 	 * condition.
169 	 */
170 	bool printedError;
171 } CondParser;
172 
173 static CondResult CondParser_Or(CondParser *, bool);
174 
175 unsigned int cond_depth = 0;	/* current .if nesting level */
176 
177 /* Names for ComparisonOp. */
178 static const char opname[][3] = { "<", "<=", ">", ">=", "==", "!=" };
179 
180 MAKE_INLINE bool
181 skip_string(const char **pp, const char *str)
182 {
183 	size_t len = strlen(str);
184 	bool ok = strncmp(*pp, str, len) == 0;
185 	if (ok)
186 		*pp += len;
187 	return ok;
188 }
189 
190 static Token
191 ToToken(bool cond)
192 {
193 	return cond ? TOK_TRUE : TOK_FALSE;
194 }
195 
196 static void
197 CondParser_SkipWhitespace(CondParser *par)
198 {
199 	cpp_skip_whitespace(&par->p);
200 }
201 
202 /*
203  * Parse a single word, taking into account balanced parentheses as well as
204  * embedded expressions.  Used for the argument of a built-in function as
205  * well as for bare words, which are then passed to the default function.
206  */
207 static char *
208 ParseWord(const char **pp, bool doEval)
209 {
210 	const char *p = *pp;
211 	Buffer word;
212 	int depth;
213 
214 	Buf_Init(&word);
215 
216 	depth = 0;
217 	for (;;) {
218 		char ch = *p;
219 		if (ch == '\0' || ch == ' ' || ch == '\t')
220 			break;
221 		if ((ch == '&' || ch == '|') && depth == 0)
222 			break;
223 		if (ch == '$') {
224 			VarEvalMode emode = doEval
225 			    ? VARE_EVAL_DEFINED
226 			    : VARE_PARSE;
227 			/*
228 			 * TODO: make Var_Parse complain about undefined
229 			 * variables.
230 			 */
231 			FStr nestedVal = Var_Parse(&p, SCOPE_CMDLINE, emode);
232 			/* TODO: handle errors */
233 			Buf_AddStr(&word, nestedVal.str);
234 			FStr_Done(&nestedVal);
235 			continue;
236 		}
237 		if (ch == '(')
238 			depth++;
239 		else if (ch == ')' && --depth < 0)
240 			break;
241 		Buf_AddByte(&word, ch);
242 		p++;
243 	}
244 
245 	*pp = p;
246 
247 	return Buf_DoneData(&word);
248 }
249 
250 /* Parse the function argument, including the surrounding parentheses. */
251 static char *
252 ParseFuncArg(CondParser *par, const char **pp, bool doEval, const char *func)
253 {
254 	const char *p = *pp, *argStart, *argEnd;
255 	char *res;
256 
257 	p++;			/* skip the '(' */
258 	cpp_skip_hspace(&p);
259 	argStart = p;
260 	res = ParseWord(&p, doEval);
261 	argEnd = p;
262 	cpp_skip_hspace(&p);
263 
264 	if (*p++ != ')') {
265 		int len = 0;
266 		while (ch_isalpha(func[len]))
267 			len++;
268 
269 		Parse_Error(PARSE_FATAL,
270 		    "Missing ')' after argument '%.*s' for '%.*s'",
271 		    (int)(argEnd - argStart), argStart, len, func);
272 		par->printedError = true;
273 		free(res);
274 		return NULL;
275 	}
276 
277 	*pp = p;
278 	return res;
279 }
280 
281 /* See if the given variable is defined. */
282 static bool
283 FuncDefined(const char *var)
284 {
285 	return Var_Exists(SCOPE_CMDLINE, var);
286 }
287 
288 /* See if a target matching targetPattern is requested to be made. */
289 static bool
290 FuncMake(const char *targetPattern)
291 {
292 	StringListNode *ln;
293 	bool warned = false;
294 
295 	for (ln = opts.create.first; ln != NULL; ln = ln->next) {
296 		StrMatchResult res = Str_Match(ln->datum, targetPattern);
297 		if (res.error != NULL && !warned) {
298 			warned = true;
299 			Parse_Error(PARSE_WARNING,
300 			    "%s in pattern argument '%s' to function 'make'",
301 			    res.error, targetPattern);
302 		}
303 		if (res.matched)
304 			return true;
305 	}
306 	return false;
307 }
308 
309 /* See if the given file exists. */
310 static bool
311 FuncExists(const char *file)
312 {
313 	bool result;
314 	char *path;
315 
316 	path = Dir_FindFile(file, &dirSearchPath);
317 	DEBUG2(COND, "exists(%s) result is \"%s\"\n",
318 	    file, path != NULL ? path : "");
319 	result = path != NULL;
320 	free(path);
321 	return result;
322 }
323 
324 /* See if the given node exists and is an actual target. */
325 static bool
326 FuncTarget(const char *node)
327 {
328 	GNode *gn = Targ_FindNode(node);
329 	return gn != NULL && GNode_IsTarget(gn);
330 }
331 
332 /*
333  * See if the given node exists and is an actual target with commands
334  * associated with it.
335  */
336 static bool
337 FuncCommands(const char *node)
338 {
339 	GNode *gn = Targ_FindNode(node);
340 	return gn != NULL && GNode_IsTarget(gn) &&
341 	       !Lst_IsEmpty(&gn->commands);
342 }
343 
344 /*
345  * Convert the string to a floating point number.  Accepted formats are
346  * base-10 integer, base-16 integer and finite floating point numbers.
347  */
348 static bool
349 TryParseNumber(const char *str, double *out_value)
350 {
351 	char *end;
352 	unsigned long ul_val;
353 	double dbl_val;
354 
355 	if (str[0] == '\0') {	/* XXX: why is an empty string a number? */
356 		*out_value = 0.0;
357 		return true;
358 	}
359 
360 	errno = 0;
361 	ul_val = strtoul(str, &end, str[1] == 'x' ? 16 : 10);
362 	if (*end == '\0' && errno != ERANGE) {
363 		*out_value = str[0] == '-' ? -(double)-ul_val : (double)ul_val;
364 		return true;
365 	}
366 
367 	if (*end != '\0' && *end != '.' && *end != 'e' && *end != 'E')
368 		return false;	/* skip the expensive strtod call */
369 	dbl_val = strtod(str, &end);
370 	if (*end != '\0')
371 		return false;
372 
373 	*out_value = dbl_val;
374 	return true;
375 }
376 
377 static bool
378 is_separator(char ch)
379 {
380 	return ch == '\0' || ch_isspace(ch) || ch == '!' || ch == '=' ||
381 	       ch == '>' || ch == '<' || ch == ')' /* but not '(' */;
382 }
383 
384 /*
385  * In a quoted or unquoted string literal or a number, parse an
386  * expression and add its value to the buffer.
387  *
388  * Return whether to continue parsing the leaf.
389  *
390  * Example: .if x${CENTER}y == "${PREFIX}${SUFFIX}" || 0x${HEX}
391  */
392 static bool
393 CondParser_StringExpr(CondParser *par, const char *start,
394 		      bool doEval, bool quoted,
395 		      Buffer *buf, FStr *inout_str)
396 {
397 	VarEvalMode emode;
398 	const char *p;
399 	bool atStart;		/* true means an expression outside quotes */
400 
401 	emode = doEval && quoted ? VARE_EVAL
402 	    : doEval ? VARE_EVAL_DEFINED
403 	    : VARE_PARSE;
404 
405 	p = par->p;
406 	atStart = p == start;
407 	*inout_str = Var_Parse(&p, SCOPE_CMDLINE, emode);
408 	/* TODO: handle errors */
409 	if (inout_str->str == var_Error) {
410 		FStr_Done(inout_str);
411 		*inout_str = FStr_InitRefer(NULL);
412 		return false;
413 	}
414 	par->p = p;
415 
416 	if (atStart && is_separator(par->p[0]))
417 		return false;
418 
419 	Buf_AddStr(buf, inout_str->str);
420 	FStr_Done(inout_str);
421 	*inout_str = FStr_InitRefer(NULL);	/* not finished yet */
422 	return true;
423 }
424 
425 /*
426  * Parse a string from an expression or an optionally quoted string,
427  * on the left-hand and right-hand sides of comparisons.
428  *
429  * Return the string without any enclosing quotes, or NULL on error.
430  * Sets out_quoted if the leaf was a quoted string literal.
431  */
432 static FStr
433 CondParser_Leaf(CondParser *par, bool doEval, bool unquotedOK,
434 		bool *out_quoted)
435 {
436 	Buffer buf;
437 	FStr str;
438 	bool quoted;
439 	const char *start;
440 
441 	Buf_Init(&buf);
442 	str = FStr_InitRefer(NULL);
443 	*out_quoted = quoted = par->p[0] == '"';
444 	start = par->p;
445 	if (quoted)
446 		par->p++;
447 
448 	while (par->p[0] != '\0' && str.str == NULL) {
449 		switch (par->p[0]) {
450 		case '\\':
451 			par->p++;
452 			if (par->p[0] != '\0') {
453 				Buf_AddByte(&buf, par->p[0]);
454 				par->p++;
455 			}
456 			continue;
457 		case '"':
458 			par->p++;
459 			if (quoted)
460 				goto return_buf;	/* skip the closing quote */
461 			Buf_AddByte(&buf, '"');
462 			continue;
463 		case ')':	/* see is_separator */
464 		case '!':
465 		case '=':
466 		case '>':
467 		case '<':
468 		case ' ':
469 		case '\t':
470 			if (!quoted)
471 				goto return_buf;
472 			Buf_AddByte(&buf, par->p[0]);
473 			par->p++;
474 			continue;
475 		case '$':
476 			if (!CondParser_StringExpr(par,
477 			    start, doEval, quoted, &buf, &str))
478 				goto return_str;
479 			continue;
480 		default:
481 			if (!unquotedOK && !quoted && *start != '$' &&
482 			    !ch_isdigit(*start)) {
483 				str = FStr_InitRefer(NULL);
484 				goto return_str;
485 			}
486 			Buf_AddByte(&buf, par->p[0]);
487 			par->p++;
488 			continue;
489 		}
490 	}
491 return_buf:
492 	str = FStr_InitOwn(buf.data);
493 	buf.data = NULL;
494 return_str:
495 	Buf_Done(&buf);
496 	return str;
497 }
498 
499 /*
500  * Evaluate a "comparison without operator", such as in ".if ${VAR}" or
501  * ".if 0".
502  */
503 static bool
504 EvalTruthy(CondParser *par, const char *value, bool quoted)
505 {
506 	double num;
507 
508 	if (quoted)
509 		return value[0] != '\0';
510 	if (TryParseNumber(value, &num))
511 		return num != 0.0;
512 	if (par->plain)
513 		return value[0] != '\0';
514 	return par->evalBare(value) != par->negateEvalBare;
515 }
516 
517 /* Evaluate a numerical comparison, such as in ".if ${VAR} >= 9". */
518 static bool
519 EvalCompareNum(double lhs, ComparisonOp op, double rhs)
520 {
521 	DEBUG3(COND, "Comparing %f %s %f\n", lhs, opname[op], rhs);
522 
523 	switch (op) {
524 	case LT:
525 		return lhs < rhs;
526 	case LE:
527 		return lhs <= rhs;
528 	case GT:
529 		return lhs > rhs;
530 	case GE:
531 		return lhs >= rhs;
532 	case EQ:
533 		return lhs == rhs;
534 	default:
535 		return lhs != rhs;
536 	}
537 }
538 
539 static Token
540 EvalCompareStr(CondParser *par, const char *lhs,
541 	       ComparisonOp op, const char *rhs)
542 {
543 	if (op != EQ && op != NE) {
544 		Parse_Error(PARSE_FATAL,
545 		    "Comparison with '%s' requires both operands "
546 		    "'%s' and '%s' to be numeric",
547 		    opname[op], lhs, rhs);
548 		par->printedError = true;
549 		return TOK_ERROR;
550 	}
551 
552 	DEBUG3(COND, "Comparing \"%s\" %s \"%s\"\n", lhs, opname[op], rhs);
553 	return ToToken((op == EQ) == (strcmp(lhs, rhs) == 0));
554 }
555 
556 /* Evaluate a comparison, such as "${VAR} == 12345". */
557 static Token
558 EvalCompare(CondParser *par, const char *lhs, bool lhsQuoted,
559 	    ComparisonOp op, const char *rhs, bool rhsQuoted)
560 {
561 	double left, right;
562 
563 	if (!rhsQuoted && !lhsQuoted)
564 		if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
565 			return ToToken(EvalCompareNum(left, op, right));
566 
567 	return EvalCompareStr(par, lhs, op, rhs);
568 }
569 
570 static bool
571 CondParser_ComparisonOp(CondParser *par, ComparisonOp *out_op)
572 {
573 	const char *p = par->p;
574 
575 	if (p[0] == '<' && p[1] == '=')
576 		return par->p += 2, *out_op = LE, true;
577 	if (p[0] == '<')
578 		return par->p += 1, *out_op = LT, true;
579 	if (p[0] == '>' && p[1] == '=')
580 		return par->p += 2, *out_op = GE, true;
581 	if (p[0] == '>')
582 		return par->p += 1, *out_op = GT, true;
583 	if (p[0] == '=' && p[1] == '=')
584 		return par->p += 2, *out_op = EQ, true;
585 	if (p[0] == '!' && p[1] == '=')
586 		return par->p += 2, *out_op = NE, true;
587 	return false;
588 }
589 
590 /*
591  * Parse a comparison condition such as:
592  *
593  *	0
594  *	${VAR:Mpattern}
595  *	${VAR} == value
596  *	${VAR:U0} < 12345
597  */
598 static Token
599 CondParser_Comparison(CondParser *par, bool doEval)
600 {
601 	Token t = TOK_ERROR;
602 	FStr lhs, rhs;
603 	ComparisonOp op;
604 	bool lhsQuoted, rhsQuoted;
605 
606 	lhs = CondParser_Leaf(par, doEval, par->leftUnquotedOK, &lhsQuoted);
607 	if (lhs.str == NULL)
608 		goto done_lhs;
609 
610 	CondParser_SkipWhitespace(par);
611 
612 	if (!CondParser_ComparisonOp(par, &op)) {
613 		t = ToToken(doEval && EvalTruthy(par, lhs.str, lhsQuoted));
614 		goto done_lhs;
615 	}
616 
617 	CondParser_SkipWhitespace(par);
618 
619 	if (par->p[0] == '\0') {
620 		Parse_Error(PARSE_FATAL,
621 		    "Missing right-hand side of operator '%s'", opname[op]);
622 		par->printedError = true;
623 		goto done_lhs;
624 	}
625 
626 	rhs = CondParser_Leaf(par, doEval, true, &rhsQuoted);
627 	t = rhs.str == NULL ? TOK_ERROR
628 	    : !doEval ? TOK_FALSE
629 	    : EvalCompare(par, lhs.str, lhsQuoted, op, rhs.str, rhsQuoted);
630 	FStr_Done(&rhs);
631 
632 done_lhs:
633 	FStr_Done(&lhs);
634 	return t;
635 }
636 
637 /*
638  * The argument to empty() is a variable name, optionally followed by
639  * variable modifiers.
640  */
641 static bool
642 CondParser_FuncCallEmpty(CondParser *par, bool doEval, Token *out_token)
643 {
644 	const char *p = par->p;
645 	Token tok;
646 	FStr val;
647 
648 	if (!skip_string(&p, "empty"))
649 		return false;
650 
651 	cpp_skip_whitespace(&p);
652 	if (*p != '(')
653 		return false;
654 
655 	p--;			/* Make p[1] point to the '('. */
656 	val = Var_Parse(&p, SCOPE_CMDLINE, doEval ? VARE_EVAL : VARE_PARSE);
657 	/* TODO: handle errors */
658 
659 	if (val.str == var_Error)
660 		tok = TOK_ERROR;
661 	else {
662 		cpp_skip_whitespace(&val.str);
663 		tok = ToToken(doEval && val.str[0] == '\0');
664 	}
665 
666 	FStr_Done(&val);
667 	*out_token = tok;
668 	par->p = p;
669 	return true;
670 }
671 
672 /* Parse a function call expression, such as 'exists(${file})'. */
673 static bool
674 CondParser_FuncCall(CondParser *par, bool doEval, Token *out_token)
675 {
676 	char *arg;
677 	const char *p = par->p;
678 	bool (*fn)(const char *);
679 	const char *fn_name = p;
680 
681 	if (skip_string(&p, "defined"))
682 		fn = FuncDefined;
683 	else if (skip_string(&p, "make"))
684 		fn = FuncMake;
685 	else if (skip_string(&p, "exists"))
686 		fn = FuncExists;
687 	else if (skip_string(&p, "target"))
688 		fn = FuncTarget;
689 	else if (skip_string(&p, "commands"))
690 		fn = FuncCommands;
691 	else
692 		return false;
693 
694 	cpp_skip_whitespace(&p);
695 	if (*p != '(')
696 		return false;
697 
698 	arg = ParseFuncArg(par, &p, doEval, fn_name);
699 	*out_token = ToToken(doEval &&
700 	    arg != NULL && arg[0] != '\0' && fn(arg));
701 	free(arg);
702 
703 	par->p = p;
704 	return true;
705 }
706 
707 /*
708  * Parse a comparison that neither starts with '"' nor '$', such as the
709  * unusual 'bare == right' or '3 == ${VAR}', or a simple leaf without
710  * operator, which is a number, an expression or a string literal.
711  *
712  * TODO: Can this be merged into CondParser_Comparison?
713  */
714 static Token
715 CondParser_ComparisonOrLeaf(CondParser *par, bool doEval)
716 {
717 	Token t;
718 	char *arg;
719 	const char *p;
720 
721 	p = par->p;
722 	if (ch_isdigit(p[0]) || p[0] == '-' || p[0] == '+')
723 		return CondParser_Comparison(par, doEval);
724 
725 	/*
726 	 * Most likely we have a bare word to apply the default function to.
727 	 * However, ".if a == b" gets here when the "a" is unquoted and
728 	 * doesn't start with a '$'. This surprises people.
729 	 * If what follows the function argument is a '=' or '!' then the
730 	 * syntax would be invalid if we did "defined(a)" - so instead treat
731 	 * as an expression.
732 	 */
733 	/*
734 	 * XXX: In edge cases, an expression may be evaluated twice,
735 	 *  see cond-token-plain.mk, keyword 'twice'.
736 	 */
737 	arg = ParseWord(&p, doEval);
738 	assert(arg[0] != '\0');
739 	cpp_skip_hspace(&p);
740 
741 	if (*p == '=' || *p == '!' || *p == '<' || *p == '>') {
742 		free(arg);
743 		return CondParser_Comparison(par, doEval);
744 	}
745 	par->p = p;
746 
747 	/*
748 	 * Evaluate the argument using the default function.
749 	 * This path always treats .if as .ifdef. To get here, the character
750 	 * after .if must have been taken literally, so the argument cannot
751 	 * be empty - even if it contained an expression.
752 	 */
753 	t = ToToken(doEval && par->evalBare(arg) != par->negateEvalBare);
754 	free(arg);
755 	return t;
756 }
757 
758 /* Return the next token or comparison result from the parser. */
759 static Token
760 CondParser_Token(CondParser *par, bool doEval)
761 {
762 	Token t;
763 
764 	t = par->curr;
765 	if (t != TOK_NONE) {
766 		par->curr = TOK_NONE;
767 		return t;
768 	}
769 
770 	cpp_skip_hspace(&par->p);
771 
772 	switch (par->p[0]) {
773 
774 	case '(':
775 		par->p++;
776 		return TOK_LPAREN;
777 
778 	case ')':
779 		par->p++;
780 		return TOK_RPAREN;
781 
782 	case '|':
783 		par->p++;
784 		if (par->p[0] == '|')
785 			par->p++;
786 		else {
787 			Parse_Error(PARSE_FATAL, "Unknown operator '|'");
788 			par->printedError = true;
789 			return TOK_ERROR;
790 		}
791 		return TOK_OR;
792 
793 	case '&':
794 		par->p++;
795 		if (par->p[0] == '&')
796 			par->p++;
797 		else {
798 			Parse_Error(PARSE_FATAL, "Unknown operator '&'");
799 			par->printedError = true;
800 			return TOK_ERROR;
801 		}
802 		return TOK_AND;
803 
804 	case '!':
805 		par->p++;
806 		return TOK_NOT;
807 
808 	case '#':		/* XXX: see unit-tests/cond-token-plain.mk */
809 	case '\n':		/* XXX: why should this end the condition? */
810 		/* Probably obsolete now, from 1993-03-21. */
811 	case '\0':
812 		return TOK_EOF;
813 
814 	case '"':
815 	case '$':
816 		return CondParser_Comparison(par, doEval);
817 
818 	default:
819 		if (CondParser_FuncCallEmpty(par, doEval, &t))
820 			return t;
821 		if (CondParser_FuncCall(par, doEval, &t))
822 			return t;
823 		return CondParser_ComparisonOrLeaf(par, doEval);
824 	}
825 }
826 
827 /* Skip the next token if it equals t. */
828 static bool
829 CondParser_Skip(CondParser *par, Token t)
830 {
831 	Token actual;
832 
833 	actual = CondParser_Token(par, false);
834 	if (actual == t)
835 		return true;
836 
837 	assert(par->curr == TOK_NONE);
838 	assert(actual != TOK_NONE);
839 	par->curr = actual;
840 	return false;
841 }
842 
843 /*
844  * Term -> '(' Or ')'
845  * Term -> '!' Term
846  * Term -> Leaf Operator Leaf
847  * Term -> Leaf
848  */
849 static CondResult
850 CondParser_Term(CondParser *par, bool doEval)
851 {
852 	CondResult res;
853 	Token t;
854 	bool neg = false;
855 
856 	while ((t = CondParser_Token(par, doEval)) == TOK_NOT)
857 		neg = !neg;
858 
859 	if (t == TOK_TRUE || t == TOK_FALSE)
860 		return neg == (t == TOK_FALSE) ? CR_TRUE : CR_FALSE;
861 
862 	if (t == TOK_LPAREN) {
863 		res = CondParser_Or(par, doEval);
864 		if (res == CR_ERROR)
865 			return CR_ERROR;
866 		if (CondParser_Token(par, doEval) != TOK_RPAREN)
867 			return CR_ERROR;
868 		return neg == (res == CR_FALSE) ? CR_TRUE : CR_FALSE;
869 	}
870 
871 	return CR_ERROR;
872 }
873 
874 /*
875  * And -> Term ('&&' Term)*
876  */
877 static CondResult
878 CondParser_And(CondParser *par, bool doEval)
879 {
880 	CondResult res, rhs;
881 
882 	res = CR_TRUE;
883 	do {
884 		if ((rhs = CondParser_Term(par, doEval)) == CR_ERROR)
885 			return CR_ERROR;
886 		if (rhs == CR_FALSE) {
887 			res = CR_FALSE;
888 			doEval = false;
889 		}
890 	} while (CondParser_Skip(par, TOK_AND));
891 
892 	return res;
893 }
894 
895 /*
896  * Or -> And ('||' And)*
897  */
898 static CondResult
899 CondParser_Or(CondParser *par, bool doEval)
900 {
901 	CondResult res, rhs;
902 
903 	res = CR_FALSE;
904 	do {
905 		if ((rhs = CondParser_And(par, doEval)) == CR_ERROR)
906 			return CR_ERROR;
907 		if (rhs == CR_TRUE) {
908 			res = CR_TRUE;
909 			doEval = false;
910 		}
911 	} while (CondParser_Skip(par, TOK_OR));
912 
913 	return res;
914 }
915 
916 /*
917  * Evaluate the condition, including any side effects from the
918  * expressions in the condition. The condition consists of &&, ||, !,
919  * function(arg), comparisons and parenthetical groupings thereof.
920  */
921 static CondResult
922 CondEvalExpression(const char *cond, bool plain,
923 		   bool (*evalBare)(const char *), bool negate,
924 		   bool eprint, bool leftUnquotedOK)
925 {
926 	CondParser par;
927 	CondResult rval;
928 
929 	cpp_skip_hspace(&cond);
930 
931 	par.plain = plain;
932 	par.evalBare = evalBare;
933 	par.negateEvalBare = negate;
934 	par.leftUnquotedOK = leftUnquotedOK;
935 	par.p = cond;
936 	par.curr = TOK_NONE;
937 	par.printedError = false;
938 
939 	DEBUG1(COND, "CondParser_Eval: %s\n", par.p);
940 	rval = CondParser_Or(&par, true);
941 	if (par.curr != TOK_EOF)
942 		rval = CR_ERROR;
943 
944 	if (rval == CR_ERROR && eprint && !par.printedError)
945 		Parse_Error(PARSE_FATAL, "Malformed conditional '%s'", cond);
946 
947 	return rval;
948 }
949 
950 /*
951  * Evaluate a condition in a :? modifier, such as
952  * ${"${VAR}" == value:?yes:no}.
953  */
954 CondResult
955 Cond_EvalCondition(const char *cond)
956 {
957 	return CondEvalExpression(cond, true,
958 	    FuncDefined, false, false, true);
959 }
960 
961 static bool
962 IsEndif(const char *p)
963 {
964 	return p[0] == 'e' && p[1] == 'n' && p[2] == 'd' &&
965 	       p[3] == 'i' && p[4] == 'f' && !ch_isalpha(p[5]);
966 }
967 
968 static bool
969 DetermineKindOfConditional(const char **pp, bool *out_plain,
970 			   bool (**out_evalBare)(const char *),
971 			   bool *out_negate)
972 {
973 	const char *p = *pp + 2;
974 
975 	*out_plain = false;
976 	*out_evalBare = FuncDefined;
977 	*out_negate = skip_string(&p, "n");
978 
979 	if (skip_string(&p, "def")) {		/* .ifdef and .ifndef */
980 	} else if (skip_string(&p, "make"))	/* .ifmake and .ifnmake */
981 		*out_evalBare = FuncMake;
982 	else if (!*out_negate)			/* plain .if */
983 		*out_plain = true;
984 	else
985 		goto unknown_directive;
986 	if (ch_isalpha(*p))
987 		goto unknown_directive;
988 
989 	*pp = p;
990 	return true;
991 
992 unknown_directive:
993 	return false;
994 }
995 
996 /*
997  * Evaluate the conditional directive in the line, which is one of:
998  *
999  *	.if <cond>
1000  *	.ifmake <cond>
1001  *	.ifnmake <cond>
1002  *	.ifdef <cond>
1003  *	.ifndef <cond>
1004  *	.elif <cond>
1005  *	.elifmake <cond>
1006  *	.elifnmake <cond>
1007  *	.elifdef <cond>
1008  *	.elifndef <cond>
1009  *	.else
1010  *	.endif
1011  *
1012  * In these directives, <cond> consists of &&, ||, !, function(arg),
1013  * comparisons, expressions, bare words, numbers and strings, and
1014  * parenthetical groupings thereof.
1015  *
1016  * Results:
1017  *	CR_TRUE		to continue parsing the lines that follow the
1018  *			conditional (when <cond> evaluates to true)
1019  *	CR_FALSE	to skip the lines after the conditional
1020  *			(when <cond> evaluates to false, or when a previous
1021  *			branch was already taken)
1022  *	CR_ERROR	if the conditional was not valid, either because of
1023  *			a syntax error or because some variable was undefined
1024  *			or because the condition could not be evaluated
1025  */
1026 CondResult
1027 Cond_EvalLine(const char *line)
1028 {
1029 	typedef enum IfState {
1030 
1031 		/* None of the previous <cond> evaluated to true. */
1032 		IFS_INITIAL	= 0,
1033 
1034 		/*
1035 		 * The previous <cond> evaluated to true. The lines following
1036 		 * this condition are interpreted.
1037 		 */
1038 		IFS_ACTIVE	= 1 << 0,
1039 
1040 		/* The previous directive was an '.else'. */
1041 		IFS_SEEN_ELSE	= 1 << 1,
1042 
1043 		/* One of the previous <cond> evaluated to true. */
1044 		IFS_WAS_ACTIVE	= 1 << 2
1045 
1046 	} IfState;
1047 
1048 	static enum IfState *cond_states = NULL;
1049 	static unsigned int cond_states_cap = 128;
1050 
1051 	bool plain;
1052 	bool (*evalBare)(const char *);
1053 	bool negate;
1054 	bool isElif;
1055 	CondResult res;
1056 	IfState state;
1057 	const char *p = line;
1058 
1059 	if (cond_states == NULL) {
1060 		cond_states = bmake_malloc(
1061 		    cond_states_cap * sizeof *cond_states);
1062 		cond_states[0] = IFS_ACTIVE;
1063 	}
1064 
1065 	p++;			/* skip the leading '.' */
1066 	cpp_skip_hspace(&p);
1067 
1068 	if (IsEndif(p)) {
1069 		if (p[5] != '\0') {
1070 			Parse_Error(PARSE_FATAL,
1071 			    "The .endif directive does not take arguments");
1072 		}
1073 
1074 		if (cond_depth == CurFile_CondMinDepth()) {
1075 			Parse_Error(PARSE_FATAL, "if-less endif");
1076 			return CR_TRUE;
1077 		}
1078 
1079 		/* Return state for previous conditional */
1080 		cond_depth--;
1081 		Parse_GuardEndif();
1082 		return cond_states[cond_depth] & IFS_ACTIVE
1083 		    ? CR_TRUE : CR_FALSE;
1084 	}
1085 
1086 	/* Parse the name of the directive, such as 'if', 'elif', 'endif'. */
1087 	if (p[0] == 'e') {
1088 		if (p[1] != 'l')
1089 			return CR_ERROR;
1090 
1091 		/* Quite likely this is 'else' or 'elif' */
1092 		p += 2;
1093 		if (strncmp(p, "se", 2) == 0 && !ch_isalpha(p[2])) {
1094 			if (p[2] != '\0')
1095 				Parse_Error(PARSE_FATAL,
1096 				    "The .else directive "
1097 				    "does not take arguments");
1098 
1099 			if (cond_depth == CurFile_CondMinDepth()) {
1100 				Parse_Error(PARSE_FATAL, "if-less else");
1101 				return CR_TRUE;
1102 			}
1103 			Parse_GuardElse();
1104 
1105 			state = cond_states[cond_depth];
1106 			if (state == IFS_INITIAL) {
1107 				state = IFS_ACTIVE | IFS_SEEN_ELSE;
1108 			} else {
1109 				if (state & IFS_SEEN_ELSE)
1110 					Parse_Error(PARSE_WARNING,
1111 					    "extra else");
1112 				state = IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1113 			}
1114 			cond_states[cond_depth] = state;
1115 
1116 			return state & IFS_ACTIVE ? CR_TRUE : CR_FALSE;
1117 		}
1118 		/* Assume for now it is an elif */
1119 		isElif = true;
1120 	} else
1121 		isElif = false;
1122 
1123 	if (p[0] != 'i' || p[1] != 'f')
1124 		return CR_ERROR;
1125 
1126 	if (!DetermineKindOfConditional(&p, &plain, &evalBare, &negate))
1127 		return CR_ERROR;
1128 
1129 	if (isElif) {
1130 		if (cond_depth == CurFile_CondMinDepth()) {
1131 			Parse_Error(PARSE_FATAL, "if-less elif");
1132 			return CR_TRUE;
1133 		}
1134 		Parse_GuardElse();
1135 		state = cond_states[cond_depth];
1136 		if (state & IFS_SEEN_ELSE) {
1137 			Parse_Error(PARSE_WARNING, "extra elif");
1138 			cond_states[cond_depth] =
1139 			    IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1140 			return CR_FALSE;
1141 		}
1142 		if (state != IFS_INITIAL) {
1143 			cond_states[cond_depth] = IFS_WAS_ACTIVE;
1144 			return CR_FALSE;
1145 		}
1146 	} else {
1147 		/* Normal .if */
1148 		if (cond_depth + 1 >= cond_states_cap) {
1149 			/*
1150 			 * This is rare, but not impossible.
1151 			 * In meta mode, dirdeps.mk (only runs at level 0)
1152 			 * can need more than the default.
1153 			 */
1154 			cond_states_cap += 32;
1155 			cond_states = bmake_realloc(cond_states,
1156 			    cond_states_cap * sizeof *cond_states);
1157 		}
1158 		state = cond_states[cond_depth];
1159 		cond_depth++;
1160 		if (!(state & IFS_ACTIVE)) {
1161 			cond_states[cond_depth] = IFS_WAS_ACTIVE;
1162 			return CR_FALSE;
1163 		}
1164 	}
1165 
1166 	res = CondEvalExpression(p, plain, evalBare, negate, true, false);
1167 	if (res == CR_ERROR) {
1168 		/* Syntax error, error message already output. */
1169 		/* Skip everything to the matching '.endif'. */
1170 		/* An extra '.else' is not detected in this case. */
1171 		cond_states[cond_depth] = IFS_WAS_ACTIVE;
1172 		return CR_FALSE;
1173 	}
1174 
1175 	cond_states[cond_depth] = res == CR_TRUE ? IFS_ACTIVE : IFS_INITIAL;
1176 	return res;
1177 }
1178 
1179 static bool
1180 ParseVarnameGuard(const char **pp, const char **varname)
1181 {
1182 	const char *p = *pp;
1183 
1184 	if (ch_isalpha(*p) || *p == '_') {
1185 		while (ch_isalnum(*p) || *p == '_')
1186 			p++;
1187 		*varname = *pp;
1188 		*pp = p;
1189 		return true;
1190 	}
1191 	return false;
1192 }
1193 
1194 /* Extracts the multiple-inclusion guard from a conditional, if any. */
1195 Guard *
1196 Cond_ExtractGuard(const char *line)
1197 {
1198 	const char *p, *varname;
1199 	Substring dir;
1200 	Guard *guard;
1201 
1202 	p = line + 1;		/* skip the '.' */
1203 	cpp_skip_hspace(&p);
1204 
1205 	dir.start = p;
1206 	while (ch_isalpha(*p))
1207 		p++;
1208 	dir.end = p;
1209 	cpp_skip_hspace(&p);
1210 
1211 	if (Substring_Equals(dir, "if")) {
1212 		if (skip_string(&p, "!defined(")) {
1213 			if (ParseVarnameGuard(&p, &varname)
1214 			    && strcmp(p, ")") == 0)
1215 				goto found_variable;
1216 		} else if (skip_string(&p, "!target(")) {
1217 			const char *arg_p = p;
1218 			free(ParseWord(&p, false));
1219 			if (strcmp(p, ")") == 0) {
1220 				guard = bmake_malloc(sizeof(*guard));
1221 				guard->kind = GK_TARGET;
1222 				guard->name = ParseWord(&arg_p, true);
1223 				return guard;
1224 			}
1225 		}
1226 	} else if (Substring_Equals(dir, "ifndef")) {
1227 		if (ParseVarnameGuard(&p, &varname) && *p == '\0')
1228 			goto found_variable;
1229 	}
1230 	return NULL;
1231 
1232 found_variable:
1233 	guard = bmake_malloc(sizeof(*guard));
1234 	guard->kind = GK_VARIABLE;
1235 	guard->name = bmake_strsedup(varname, p);
1236 	return guard;
1237 }
1238 
1239 void
1240 Cond_EndFile(void)
1241 {
1242 	unsigned int open_conds = cond_depth - CurFile_CondMinDepth();
1243 
1244 	if (open_conds != 0) {
1245 		Parse_Error(PARSE_FATAL, "%u open conditional%s",
1246 		    open_conds, open_conds == 1 ? "" : "s");
1247 		cond_depth = CurFile_CondMinDepth();
1248 	}
1249 }
1250