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