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