Home | History | Annotate | Line # | Download | only in make
cond.c revision 1.266
      1 /*	$NetBSD: cond.c,v 1.266 2021/06/11 14:42:52 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_save_depth
     85  *	Cond_restore_depth
     86  *			Save and restore the nesting of the conditions, at
     87  *			the start and end of including another makefile, to
     88  *			ensure that in each makefile the conditional
     89  *			directives are well-balanced.
     90  */
     91 
     92 #include <errno.h>
     93 
     94 #include "make.h"
     95 #include "dir.h"
     96 
     97 /*	"@(#)cond.c	8.2 (Berkeley) 1/2/94"	*/
     98 MAKE_RCSID("$NetBSD: cond.c,v 1.266 2021/06/11 14:42:52 rillig Exp $");
     99 
    100 /*
    101  * The parsing of conditional expressions is based on this grammar:
    102  *	Or -> And '||' Or
    103  *	Or -> And
    104  *	And -> Term '&&' And
    105  *	And -> Term
    106  *	Term -> Function '(' Argument ')'
    107  *	Term -> Leaf Operator Leaf
    108  *	Term -> Leaf
    109  *	Term -> '(' Or ')'
    110  *	Term -> '!' Term
    111  *	Leaf -> "string"
    112  *	Leaf -> Number
    113  *	Leaf -> VariableExpression
    114  *	Leaf -> Symbol
    115  *	Operator -> '==' | '!=' | '>' | '<' | '>=' | '<='
    116  *
    117  * 'Symbol' is an unquoted string literal to which the default function is
    118  * applied.
    119  *
    120  * The tokens are scanned by CondToken, which returns:
    121  *	TOK_AND		for '&&'
    122  *	TOK_OR		for '||'
    123  *	TOK_NOT		for '!'
    124  *	TOK_LPAREN	for '('
    125  *	TOK_RPAREN	for ')'
    126  *
    127  * Other terminal symbols are evaluated using either the default function or
    128  * the function given in the terminal, they return either TOK_TRUE or
    129  * TOK_FALSE.
    130  */
    131 typedef enum Token {
    132 	TOK_FALSE, TOK_TRUE, TOK_AND, TOK_OR, TOK_NOT,
    133 	TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
    134 } Token;
    135 
    136 typedef enum CondResult {
    137 	CR_FALSE, CR_TRUE, CR_ERROR
    138 } CondResult;
    139 
    140 typedef enum ComparisonOp {
    141 	LT, LE, GT, GE, EQ, NE
    142 } ComparisonOp;
    143 
    144 typedef struct CondParser {
    145 
    146 	/*
    147 	 * The plain '.if ${VAR}' evaluates to true if the value of the
    148 	 * expression has length > 0.  The other '.if' variants delegate
    149 	 * to evalBare instead.
    150 	 */
    151 	bool plain;
    152 
    153 	/* The function to apply on unquoted bare words. */
    154 	bool (*evalBare)(size_t, const char *);
    155 	bool negateEvalBare;
    156 
    157 	const char *p;		/* The remaining condition to parse */
    158 	Token curr;		/* Single push-back token used in parsing */
    159 
    160 	/*
    161 	 * Whether an error message has already been printed for this
    162 	 * condition. The first available error message is usually the most
    163 	 * specific one, therefore it makes sense to suppress the standard
    164 	 * "Malformed conditional" message.
    165 	 */
    166 	bool printedError;
    167 } CondParser;
    168 
    169 static CondResult CondParser_Or(CondParser *par, bool);
    170 
    171 static unsigned int cond_depth = 0;	/* current .if nesting level */
    172 static unsigned int cond_min_depth = 0;	/* depth at makefile open */
    173 
    174 static const char *opname[] = { "<", "<=", ">", ">=", "==", "!=" };
    175 
    176 /*
    177  * Indicate when we should be strict about lhs of comparisons.
    178  * In strict mode, the lhs must be a variable expression or a string literal
    179  * in quotes. In non-strict mode it may also be an unquoted string literal.
    180  *
    181  * True when CondEvalExpression is called from Cond_EvalLine (.if etc).
    182  * False when CondEvalExpression is called from ApplyModifier_IfElse
    183  * since lhs is already expanded, and at that point we cannot tell if
    184  * it was a variable reference or not.
    185  */
    186 static bool lhsStrict;
    187 
    188 static bool
    189 is_token(const char *str, const char *tok, size_t len)
    190 {
    191 	return strncmp(str, tok, len) == 0 && !ch_isalpha(str[len]);
    192 }
    193 
    194 static Token
    195 ToToken(bool cond)
    196 {
    197 	return cond ? TOK_TRUE : TOK_FALSE;
    198 }
    199 
    200 /* Push back the most recent token read. We only need one level of this. */
    201 static void
    202 CondParser_PushBack(CondParser *par, Token t)
    203 {
    204 	assert(par->curr == TOK_NONE);
    205 	assert(t != TOK_NONE);
    206 
    207 	par->curr = t;
    208 }
    209 
    210 static void
    211 CondParser_SkipWhitespace(CondParser *par)
    212 {
    213 	cpp_skip_whitespace(&par->p);
    214 }
    215 
    216 /*
    217  * Parse the argument of a built-in function.
    218  *
    219  * Arguments:
    220  *	*pp initially points at the '(',
    221  *	upon successful return it points right after the ')'.
    222  *
    223  *	*out_arg receives the argument as string.
    224  *
    225  *	func says whether the argument belongs to an actual function, or
    226  *	whether the parsed argument is passed to the default function.
    227  *
    228  * Return the length of the argument, or 0 on error.
    229  */
    230 static size_t
    231 ParseFuncArg(CondParser *par, const char **pp, bool doEval, const char *func,
    232 	     char **out_arg)
    233 {
    234 	const char *p = *pp;
    235 	Buffer argBuf;
    236 	int paren_depth;
    237 	size_t argLen;
    238 
    239 	if (func != NULL)
    240 		p++;		/* Skip opening '(' - verified by caller */
    241 
    242 	if (*p == '\0') {
    243 		*out_arg = NULL; /* Missing closing parenthesis: */
    244 		return 0;	/* .if defined( */
    245 	}
    246 
    247 	cpp_skip_hspace(&p);
    248 
    249 	Buf_InitSize(&argBuf, 16);
    250 
    251 	paren_depth = 0;
    252 	for (;;) {
    253 		char ch = *p;
    254 		if (ch == '\0' || ch == ' ' || ch == '\t')
    255 			break;
    256 		if ((ch == '&' || ch == '|') && paren_depth == 0)
    257 			break;
    258 		if (*p == '$') {
    259 			/*
    260 			 * Parse the variable expression and install it as
    261 			 * part of the argument if it's valid. We tell
    262 			 * Var_Parse to complain on an undefined variable,
    263 			 * (XXX: but Var_Parse ignores that request)
    264 			 * so we don't need to do it. Nor do we return an
    265 			 * error, though perhaps we should.
    266 			 */
    267 			VarEvalMode emode = doEval
    268 			    ? VARE_UNDEFERR
    269 			    : VARE_PARSE_ONLY;
    270 			FStr nestedVal;
    271 			(void)Var_Parse(&p, SCOPE_CMDLINE, emode, &nestedVal);
    272 			/* TODO: handle errors */
    273 			Buf_AddStr(&argBuf, nestedVal.str);
    274 			FStr_Done(&nestedVal);
    275 			continue;
    276 		}
    277 		if (ch == '(')
    278 			paren_depth++;
    279 		else if (ch == ')' && --paren_depth < 0)
    280 			break;
    281 		Buf_AddByte(&argBuf, *p);
    282 		p++;
    283 	}
    284 
    285 	argLen = argBuf.len;
    286 	*out_arg = Buf_DoneData(&argBuf);
    287 
    288 	cpp_skip_hspace(&p);
    289 
    290 	if (func != NULL && *p++ != ')') {
    291 		Parse_Error(PARSE_FATAL,
    292 		    "Missing closing parenthesis for %s()", func);
    293 		par->printedError = true;
    294 		return 0;
    295 	}
    296 
    297 	*pp = p;
    298 	return argLen;
    299 }
    300 
    301 /* Test whether the given variable is defined. */
    302 /*ARGSUSED*/
    303 static bool
    304 FuncDefined(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
    305 {
    306 	FStr value = Var_Value(SCOPE_CMDLINE, arg);
    307 	bool result = value.str != NULL;
    308 	FStr_Done(&value);
    309 	return result;
    310 }
    311 
    312 /* See if the given target is being made. */
    313 /*ARGSUSED*/
    314 static bool
    315 FuncMake(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
    316 {
    317 	StringListNode *ln;
    318 
    319 	for (ln = opts.create.first; ln != NULL; ln = ln->next)
    320 		if (Str_Match(ln->datum, arg))
    321 			return true;
    322 	return false;
    323 }
    324 
    325 /* See if the given file exists. */
    326 /*ARGSUSED*/
    327 static bool
    328 FuncExists(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
    329 {
    330 	bool result;
    331 	char *path;
    332 
    333 	path = Dir_FindFile(arg, &dirSearchPath);
    334 	DEBUG2(COND, "exists(%s) result is \"%s\"\n",
    335 	       arg, path != NULL ? path : "");
    336 	result = path != NULL;
    337 	free(path);
    338 	return result;
    339 }
    340 
    341 /* See if the given node exists and is an actual target. */
    342 /*ARGSUSED*/
    343 static bool
    344 FuncTarget(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
    345 {
    346 	GNode *gn = Targ_FindNode(arg);
    347 	return gn != NULL && GNode_IsTarget(gn);
    348 }
    349 
    350 /*
    351  * See if the given node exists and is an actual target with commands
    352  * associated with it.
    353  */
    354 /*ARGSUSED*/
    355 static bool
    356 FuncCommands(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
    357 {
    358 	GNode *gn = Targ_FindNode(arg);
    359 	return gn != NULL && GNode_IsTarget(gn) && !Lst_IsEmpty(&gn->commands);
    360 }
    361 
    362 /*
    363  * Convert the given number into a double.
    364  * We try a base 10 or 16 integer conversion first, if that fails
    365  * then we try a floating point conversion instead.
    366  *
    367  * Results:
    368  *	Returns true if the conversion succeeded.
    369  *	Sets 'out_value' to the converted number.
    370  */
    371 static bool
    372 TryParseNumber(const char *str, double *out_value)
    373 {
    374 	char *end;
    375 	unsigned long ul_val;
    376 	double dbl_val;
    377 
    378 	errno = 0;
    379 	if (str[0] == '\0') {	/* XXX: why is an empty string a number? */
    380 		*out_value = 0.0;
    381 		return true;
    382 	}
    383 
    384 	ul_val = strtoul(str, &end, str[1] == 'x' ? 16 : 10);
    385 	if (*end == '\0' && errno != ERANGE) {
    386 		*out_value = str[0] == '-' ? -(double)-ul_val : (double)ul_val;
    387 		return true;
    388 	}
    389 
    390 	if (*end != '\0' && *end != '.' && *end != 'e' && *end != 'E')
    391 		return false;	/* skip the expensive strtod call */
    392 	dbl_val = strtod(str, &end);
    393 	if (*end != '\0')
    394 		return false;
    395 
    396 	*out_value = dbl_val;
    397 	return true;
    398 }
    399 
    400 static bool
    401 is_separator(char ch)
    402 {
    403 	return ch == '\0' || ch_isspace(ch) || strchr("!=><)", ch) != NULL;
    404 }
    405 
    406 /*
    407  * In a quoted or unquoted string literal or a number, parse a variable
    408  * expression.
    409  *
    410  * Example: .if x${CENTER}y == "${PREFIX}${SUFFIX}" || 0x${HEX}
    411  */
    412 static bool
    413 CondParser_StringExpr(CondParser *par, const char *start,
    414 		      bool const doEval, bool const quoted,
    415 		      Buffer *buf, FStr *const inout_str)
    416 {
    417 	VarEvalMode emode;
    418 	const char *nested_p;
    419 	bool atStart;
    420 	VarParseResult parseResult;
    421 
    422 	/* if we are in quotes, an undefined variable is ok */
    423 	emode = doEval && !quoted ? VARE_UNDEFERR
    424 	    : doEval ? VARE_WANTRES
    425 	    : VARE_PARSE_ONLY;
    426 
    427 	nested_p = par->p;
    428 	atStart = nested_p == start;
    429 	parseResult = Var_Parse(&nested_p, SCOPE_CMDLINE, emode, inout_str);
    430 	/* TODO: handle errors */
    431 	if (inout_str->str == var_Error) {
    432 		if (parseResult == VPR_ERR) {
    433 			/*
    434 			 * FIXME: Even if an error occurs, there is no
    435 			 *  guarantee that it is reported.
    436 			 *
    437 			 * See cond-token-plain.mk $$$$$$$$.
    438 			 */
    439 			par->printedError = true;
    440 		}
    441 		/*
    442 		 * XXX: Can there be any situation in which a returned
    443 		 * var_Error needs to be freed?
    444 		 */
    445 		FStr_Done(inout_str);
    446 		/*
    447 		 * Even if !doEval, we still report syntax errors, which is
    448 		 * what getting var_Error back with !doEval means.
    449 		 */
    450 		*inout_str = FStr_InitRefer(NULL);
    451 		return false;
    452 	}
    453 	par->p = nested_p;
    454 
    455 	/*
    456 	 * If the '$' started the string literal (which means no quotes), and
    457 	 * the variable expression is followed by a space, looks like a
    458 	 * comparison operator or is the end of the expression, we are done.
    459 	 */
    460 	if (atStart && is_separator(par->p[0]))
    461 		return false;
    462 
    463 	Buf_AddStr(buf, inout_str->str);
    464 	FStr_Done(inout_str);
    465 	*inout_str = FStr_InitRefer(NULL); /* not finished yet */
    466 	return true;
    467 }
    468 
    469 /*
    470  * Parse a string from a variable expression or an optionally quoted
    471  * string.  This is called for the left-hand and right-hand sides of
    472  * comparisons.
    473  *
    474  * Results:
    475  *	Returns the string, absent any quotes, or NULL on error.
    476  *	Sets out_quoted if the leaf was a quoted string literal.
    477  */
    478 static void
    479 CondParser_Leaf(CondParser *par, bool doEval, bool strictLHS,
    480 		  FStr *out_str, bool *out_quoted)
    481 {
    482 	Buffer buf;
    483 	FStr str;
    484 	bool quoted;
    485 	const char *start;
    486 
    487 	Buf_Init(&buf);
    488 	str = FStr_InitRefer(NULL);
    489 	*out_quoted = quoted = par->p[0] == '"';
    490 	start = par->p;
    491 	if (quoted)
    492 		par->p++;
    493 
    494 	while (par->p[0] != '\0' && str.str == NULL) {
    495 		switch (par->p[0]) {
    496 		case '\\':
    497 			par->p++;
    498 			if (par->p[0] != '\0') {
    499 				Buf_AddByte(&buf, par->p[0]);
    500 				par->p++;
    501 			}
    502 			continue;
    503 		case '"':
    504 			par->p++;
    505 			if (quoted)
    506 				goto got_str;	/* skip the closing quote */
    507 			Buf_AddByte(&buf, '"');
    508 			continue;
    509 		case ')':	/* see is_separator */
    510 		case '!':
    511 		case '=':
    512 		case '>':
    513 		case '<':
    514 		case ' ':
    515 		case '\t':
    516 			if (!quoted)
    517 				goto got_str;
    518 			Buf_AddByte(&buf, par->p[0]);
    519 			par->p++;
    520 			continue;
    521 		case '$':
    522 			if (!CondParser_StringExpr(par,
    523 			    start, doEval, quoted, &buf, &str))
    524 				goto cleanup;
    525 			continue;
    526 		default:
    527 			if (strictLHS && !quoted && *start != '$' &&
    528 			    !ch_isdigit(*start)) {
    529 				/*
    530 				 * The left-hand side must be quoted,
    531 				 * a variable reference or a number.
    532 				 */
    533 				str = FStr_InitRefer(NULL);
    534 				goto cleanup;
    535 			}
    536 			Buf_AddByte(&buf, par->p[0]);
    537 			par->p++;
    538 			continue;
    539 		}
    540 	}
    541 got_str:
    542 	str = FStr_InitOwn(buf.data);
    543 cleanup:
    544 	Buf_DoneData(&buf);	/* XXX: memory leak on failure? */
    545 	*out_str = str;
    546 }
    547 
    548 static bool
    549 EvalBare(const CondParser *par, const char *arg, size_t arglen)
    550 {
    551 	bool res = par->evalBare(arglen, arg);
    552 	return par->negateEvalBare ? !res : res;
    553 }
    554 
    555 /*
    556  * Evaluate a "comparison without operator", such as in ".if ${VAR}" or
    557  * ".if 0".
    558  */
    559 static bool
    560 EvalNotEmpty(CondParser *par, const char *value, bool quoted)
    561 {
    562 	double num;
    563 
    564 	/* For .ifxxx "...", check for non-empty string. */
    565 	if (quoted)
    566 		return value[0] != '\0';
    567 
    568 	/* For .ifxxx <number>, compare against zero */
    569 	if (TryParseNumber(value, &num))
    570 		return num != 0.0;
    571 
    572 	/* For .if ${...}, check for non-empty string.  This is different from
    573 	 * the evaluation function from that .if variant, which would test
    574 	 * whether a variable of the given name were defined. */
    575 	/* XXX: Whitespace should count as empty, just as in ParseEmptyArg. */
    576 	if (par->plain)
    577 		return value[0] != '\0';
    578 
    579 	return EvalBare(par, value, strlen(value));
    580 }
    581 
    582 /* Evaluate a numerical comparison, such as in ".if ${VAR} >= 9". */
    583 static bool
    584 EvalCompareNum(double lhs, ComparisonOp op, double rhs)
    585 {
    586 	DEBUG3(COND, "lhs = %f, rhs = %f, op = %.2s\n", lhs, rhs, opname[op]);
    587 
    588 	switch (op) {
    589 	case LT:
    590 		return lhs < rhs;
    591 	case LE:
    592 		return lhs <= rhs;
    593 	case GT:
    594 		return lhs > rhs;
    595 	case GE:
    596 		return lhs >= rhs;
    597 	case NE:
    598 		return lhs != rhs;
    599 	default:
    600 		return lhs == rhs;
    601 	}
    602 }
    603 
    604 static Token
    605 EvalCompareStr(CondParser *par, const char *lhs,
    606 	       ComparisonOp op, const char *rhs)
    607 {
    608 	if (op != EQ && op != NE) {
    609 		Parse_Error(PARSE_FATAL,
    610 		    "String comparison operator must be either == or !=");
    611 		par->printedError = true;
    612 		return TOK_ERROR;
    613 	}
    614 
    615 	DEBUG3(COND, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
    616 	    lhs, rhs, opname[op]);
    617 	return ToToken((op == EQ) == (strcmp(lhs, rhs) == 0));
    618 }
    619 
    620 /* Evaluate a comparison, such as "${VAR} == 12345". */
    621 static Token
    622 EvalCompare(CondParser *par, const char *lhs, bool lhsQuoted,
    623 	    ComparisonOp op, const char *rhs, bool rhsQuoted)
    624 {
    625 	double left, right;
    626 
    627 	if (!rhsQuoted && !lhsQuoted)
    628 		if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
    629 			return ToToken(EvalCompareNum(left, op, right));
    630 
    631 	return EvalCompareStr(par, lhs, op, rhs);
    632 }
    633 
    634 static bool
    635 CondParser_ComparisonOp(CondParser *par, ComparisonOp *out_op)
    636 {
    637 	const char *p = par->p;
    638 
    639 	if (p[0] == '<' && p[1] == '=') {
    640 		*out_op = LE;
    641 		goto length_2;
    642 	} else if (p[0] == '<') {
    643 		*out_op = LT;
    644 		goto length_1;
    645 	} else if (p[0] == '>' && p[1] == '=') {
    646 		*out_op = GE;
    647 		goto length_2;
    648 	} else if (p[0] == '>') {
    649 		*out_op = GT;
    650 		goto length_1;
    651 	} else if (p[0] == '=' && p[1] == '=') {
    652 		*out_op = EQ;
    653 		goto length_2;
    654 	} else if (p[0] == '!' && p[1] == '=') {
    655 		*out_op = NE;
    656 		goto length_2;
    657 	}
    658 	return false;
    659 
    660 length_2:
    661 	par->p = p + 2;
    662 	return true;
    663 length_1:
    664 	par->p = p + 1;
    665 	return true;
    666 }
    667 
    668 /*
    669  * Parse a comparison condition such as:
    670  *
    671  *	0
    672  *	${VAR:Mpattern}
    673  *	${VAR} == value
    674  *	${VAR:U0} < 12345
    675  */
    676 static Token
    677 CondParser_Comparison(CondParser *par, bool doEval)
    678 {
    679 	Token t = TOK_ERROR;
    680 	FStr lhs, rhs;
    681 	ComparisonOp op;
    682 	bool lhsQuoted, rhsQuoted;
    683 
    684 	/*
    685 	 * Parse the variable spec and skip over it, saving its
    686 	 * value in lhs.
    687 	 */
    688 	CondParser_Leaf(par, doEval, lhsStrict, &lhs, &lhsQuoted);
    689 	if (lhs.str == NULL)
    690 		goto done_lhs;
    691 
    692 	CondParser_SkipWhitespace(par);
    693 
    694 	if (!CondParser_ComparisonOp(par, &op)) {
    695 		/* Unknown operator, compare against an empty string or 0. */
    696 		t = ToToken(doEval && EvalNotEmpty(par, lhs.str, lhsQuoted));
    697 		goto done_lhs;
    698 	}
    699 
    700 	CondParser_SkipWhitespace(par);
    701 
    702 	if (par->p[0] == '\0') {
    703 		Parse_Error(PARSE_FATAL,
    704 		    "Missing right-hand-side of operator '%s'", opname[op]);
    705 		par->printedError = true;
    706 		goto done_lhs;
    707 	}
    708 
    709 	CondParser_Leaf(par, doEval, false, &rhs, &rhsQuoted);
    710 	if (rhs.str == NULL)
    711 		goto done_rhs;
    712 
    713 	if (!doEval) {
    714 		t = TOK_FALSE;
    715 		goto done_rhs;
    716 	}
    717 
    718 	t = EvalCompare(par, lhs.str, lhsQuoted, op, rhs.str, rhsQuoted);
    719 
    720 done_rhs:
    721 	FStr_Done(&rhs);
    722 done_lhs:
    723 	FStr_Done(&lhs);
    724 	return t;
    725 }
    726 
    727 /*
    728  * The argument to empty() is a variable name, optionally followed by
    729  * variable modifiers.
    730  */
    731 /*ARGSUSED*/
    732 static size_t
    733 ParseEmptyArg(CondParser *par MAKE_ATTR_UNUSED, const char **pp,
    734 	      bool doEval, const char *func MAKE_ATTR_UNUSED,
    735 	      char **out_arg)
    736 {
    737 	FStr val;
    738 	size_t magic_res;
    739 
    740 	/* We do all the work here and return the result as the length */
    741 	*out_arg = NULL;
    742 
    743 	(*pp)--;		/* Make (*pp)[1] point to the '('. */
    744 	(void)Var_Parse(pp, SCOPE_CMDLINE,
    745 	    doEval ? VARE_WANTRES : VARE_PARSE_ONLY, &val);
    746 	/* TODO: handle errors */
    747 	/* If successful, *pp points beyond the closing ')' now. */
    748 
    749 	if (val.str == var_Error) {
    750 		FStr_Done(&val);
    751 		return (size_t)-1;
    752 	}
    753 
    754 	/*
    755 	 * A variable is empty when it just contains spaces...
    756 	 * 4/15/92, christos
    757 	 */
    758 	cpp_skip_whitespace(&val.str);
    759 
    760 	/*
    761 	 * For consistency with the other functions we can't generate the
    762 	 * true/false here.
    763 	 */
    764 	magic_res = val.str[0] != '\0' ? 2 : 1;
    765 	FStr_Done(&val);
    766 	return magic_res;
    767 }
    768 
    769 /*ARGSUSED*/
    770 static bool
    771 FuncEmpty(size_t arglen, const char *arg MAKE_ATTR_UNUSED)
    772 {
    773 	/* Magic values ahead, see ParseEmptyArg. */
    774 	return arglen == 1;
    775 }
    776 
    777 /* Parse a function call expression, such as 'defined(${file})'. */
    778 static bool
    779 CondParser_FuncCall(CondParser *par, bool doEval, Token *out_token)
    780 {
    781 	static const struct fn_def {
    782 		const char *fn_name;
    783 		size_t fn_name_len;
    784 		size_t (*fn_parse)(CondParser *, const char **, bool,
    785 				   const char *, char **);
    786 		bool (*fn_eval)(size_t, const char *);
    787 	} fns[] = {
    788 		{ "defined",  7, ParseFuncArg,  FuncDefined },
    789 		{ "make",     4, ParseFuncArg,  FuncMake },
    790 		{ "exists",   6, ParseFuncArg,  FuncExists },
    791 		{ "empty",    5, ParseEmptyArg, FuncEmpty },
    792 		{ "target",   6, ParseFuncArg,  FuncTarget },
    793 		{ "commands", 8, ParseFuncArg,  FuncCommands }
    794 	};
    795 	const struct fn_def *fn;
    796 	char *arg = NULL;
    797 	size_t arglen;
    798 	const char *cp = par->p;
    799 	const struct fn_def *fns_end = fns + sizeof fns / sizeof fns[0];
    800 
    801 	for (fn = fns; fn != fns_end; fn++) {
    802 		if (!is_token(cp, fn->fn_name, fn->fn_name_len))
    803 			continue;
    804 
    805 		cp += fn->fn_name_len;
    806 		cpp_skip_whitespace(&cp);
    807 		if (*cp != '(')
    808 			break;
    809 
    810 		arglen = fn->fn_parse(par, &cp, doEval, fn->fn_name, &arg);
    811 		if (arglen == 0 || arglen == (size_t)-1) {
    812 			par->p = cp;
    813 			*out_token = arglen == 0 ? TOK_FALSE : TOK_ERROR;
    814 			return true;
    815 		}
    816 
    817 		/* Evaluate the argument using the required function. */
    818 		*out_token = ToToken(!doEval || fn->fn_eval(arglen, arg));
    819 		free(arg);
    820 		par->p = cp;
    821 		return true;
    822 	}
    823 
    824 	return false;
    825 }
    826 
    827 /*
    828  * Parse a comparison such as '${VAR} == "value"', or a simple leaf without
    829  * operator, which is a number, a variable expression or a string literal.
    830  */
    831 static Token
    832 CondParser_ComparisonOrLeaf(CondParser *par, bool doEval)
    833 {
    834 	Token t;
    835 	char *arg = NULL;
    836 	size_t arglen;
    837 	const char *cp;
    838 	const char *cp1;
    839 
    840 	/* Push anything numeric through the compare expression */
    841 	cp = par->p;
    842 	if (ch_isdigit(cp[0]) || cp[0] == '-' || cp[0] == '+')
    843 		return CondParser_Comparison(par, doEval);
    844 
    845 	/*
    846 	 * Most likely we have a naked token to apply the default function to.
    847 	 * However ".if a == b" gets here when the "a" is unquoted and doesn't
    848 	 * start with a '$'. This surprises people.
    849 	 * If what follows the function argument is a '=' or '!' then the
    850 	 * syntax would be invalid if we did "defined(a)" - so instead treat
    851 	 * as an expression.
    852 	 */
    853 	/*
    854 	 * XXX: Is it possible to have a variable expression evaluated twice
    855 	 *  at this point?
    856 	 */
    857 	arglen = ParseFuncArg(par, &cp, doEval, NULL, &arg);
    858 	cp1 = cp;
    859 	cpp_skip_whitespace(&cp1);
    860 	if (*cp1 == '=' || *cp1 == '!' || *cp1 == '<' || *cp1 == '>')
    861 		return CondParser_Comparison(par, doEval);
    862 	par->p = cp;
    863 
    864 	/*
    865 	 * Evaluate the argument using the default function.
    866 	 * This path always treats .if as .ifdef. To get here, the character
    867 	 * after .if must have been taken literally, so the argument cannot
    868 	 * be empty - even if it contained a variable expansion.
    869 	 */
    870 	t = ToToken(!doEval || EvalBare(par, arg, arglen));
    871 	free(arg);
    872 	return t;
    873 }
    874 
    875 /* Return the next token or comparison result from the parser. */
    876 static Token
    877 CondParser_Token(CondParser *par, bool doEval)
    878 {
    879 	Token t;
    880 
    881 	t = par->curr;
    882 	if (t != TOK_NONE) {
    883 		par->curr = TOK_NONE;
    884 		return t;
    885 	}
    886 
    887 	cpp_skip_hspace(&par->p);
    888 
    889 	switch (par->p[0]) {
    890 
    891 	case '(':
    892 		par->p++;
    893 		return TOK_LPAREN;
    894 
    895 	case ')':
    896 		par->p++;
    897 		return TOK_RPAREN;
    898 
    899 	case '|':
    900 		par->p++;
    901 		if (par->p[0] == '|')
    902 			par->p++;
    903 		else if (opts.strict) {
    904 			Parse_Error(PARSE_FATAL, "Unknown operator '|'");
    905 			par->printedError = true;
    906 			return TOK_ERROR;
    907 		}
    908 		return TOK_OR;
    909 
    910 	case '&':
    911 		par->p++;
    912 		if (par->p[0] == '&')
    913 			par->p++;
    914 		else if (opts.strict) {
    915 			Parse_Error(PARSE_FATAL, "Unknown operator '&'");
    916 			par->printedError = true;
    917 			return TOK_ERROR;
    918 		}
    919 		return TOK_AND;
    920 
    921 	case '!':
    922 		par->p++;
    923 		return TOK_NOT;
    924 
    925 	case '#':		/* XXX: see unit-tests/cond-token-plain.mk */
    926 	case '\n':		/* XXX: why should this end the condition? */
    927 		/* Probably obsolete now, from 1993-03-21. */
    928 	case '\0':
    929 		return TOK_EOF;
    930 
    931 	case '"':
    932 	case '$':
    933 		return CondParser_Comparison(par, doEval);
    934 
    935 	default:
    936 		if (CondParser_FuncCall(par, doEval, &t))
    937 			return t;
    938 		return CondParser_ComparisonOrLeaf(par, doEval);
    939 	}
    940 }
    941 
    942 /*
    943  * Term -> '(' Or ')'
    944  * Term -> '!' Term
    945  * Term -> Leaf Operator Leaf
    946  * Term -> Leaf
    947  */
    948 static CondResult
    949 CondParser_Term(CondParser *par, bool doEval)
    950 {
    951 	CondResult res;
    952 	Token t;
    953 
    954 	t = CondParser_Token(par, doEval);
    955 	if (t == TOK_TRUE)
    956 		return CR_TRUE;
    957 	if (t == TOK_FALSE)
    958 		return CR_FALSE;
    959 
    960 	if (t == TOK_LPAREN) {
    961 		res = CondParser_Or(par, doEval);
    962 		if (res == CR_ERROR)
    963 			return CR_ERROR;
    964 		if (CondParser_Token(par, doEval) != TOK_RPAREN)
    965 			return CR_ERROR;
    966 		return res;
    967 	}
    968 
    969 	if (t == TOK_NOT) {
    970 		res = CondParser_Term(par, doEval);
    971 		if (res == CR_TRUE)
    972 			res = CR_FALSE;
    973 		else if (res == CR_FALSE)
    974 			res = CR_TRUE;
    975 		return res;
    976 	}
    977 
    978 	return CR_ERROR;
    979 }
    980 
    981 /*
    982  * And -> Term '&&' And
    983  * And -> Term
    984  */
    985 static CondResult
    986 CondParser_And(CondParser *par, bool doEval)
    987 {
    988 	CondResult res;
    989 	Token op;
    990 
    991 	res = CondParser_Term(par, doEval);
    992 	if (res == CR_ERROR)
    993 		return CR_ERROR;
    994 
    995 	op = CondParser_Token(par, doEval);
    996 	if (op == TOK_AND) {
    997 		if (res == CR_TRUE)
    998 			return CondParser_And(par, doEval);
    999 		if (CondParser_And(par, false) == CR_ERROR)
   1000 			return CR_ERROR;
   1001 		return res;
   1002 	}
   1003 
   1004 	CondParser_PushBack(par, op);
   1005 	return res;
   1006 }
   1007 
   1008 /*
   1009  * Or -> And '||' Or
   1010  * Or -> And
   1011  */
   1012 static CondResult
   1013 CondParser_Or(CondParser *par, bool doEval)
   1014 {
   1015 	CondResult res;
   1016 	Token op;
   1017 
   1018 	res = CondParser_And(par, doEval);
   1019 	if (res == CR_ERROR)
   1020 		return CR_ERROR;
   1021 
   1022 	op = CondParser_Token(par, doEval);
   1023 	if (op == TOK_OR) {
   1024 		if (res == CR_FALSE)
   1025 			return CondParser_Or(par, doEval);
   1026 		if (CondParser_Or(par, false) == CR_ERROR)
   1027 			return CR_ERROR;
   1028 		return res;
   1029 	}
   1030 
   1031 	CondParser_PushBack(par, op);
   1032 	return res;
   1033 }
   1034 
   1035 static CondEvalResult
   1036 CondParser_Eval(CondParser *par, bool *out_value)
   1037 {
   1038 	CondResult res;
   1039 
   1040 	DEBUG1(COND, "CondParser_Eval: %s\n", par->p);
   1041 
   1042 	res = CondParser_Or(par, true);
   1043 	if (res == CR_ERROR)
   1044 		return COND_INVALID;
   1045 
   1046 	if (CondParser_Token(par, false) != TOK_EOF)
   1047 		return COND_INVALID;
   1048 
   1049 	*out_value = res == CR_TRUE;
   1050 	return COND_PARSE;
   1051 }
   1052 
   1053 /*
   1054  * Evaluate the condition, including any side effects from the variable
   1055  * expressions in the condition. The condition consists of &&, ||, !,
   1056  * function(arg), comparisons and parenthetical groupings thereof.
   1057  *
   1058  * Results:
   1059  *	COND_PARSE	if the condition was valid grammatically
   1060  *	COND_INVALID	if not a valid conditional.
   1061  *
   1062  *	(*value) is set to the boolean value of the condition
   1063  */
   1064 static CondEvalResult
   1065 CondEvalExpression(const char *cond, bool *out_value, bool plain,
   1066 		   bool (*evalBare)(size_t, const char *), bool negate,
   1067 		   bool eprint, bool strictLHS)
   1068 {
   1069 	CondParser par;
   1070 	CondEvalResult rval;
   1071 
   1072 	lhsStrict = strictLHS;
   1073 
   1074 	cpp_skip_hspace(&cond);
   1075 
   1076 	par.plain = plain;
   1077 	par.evalBare = evalBare;
   1078 	par.negateEvalBare = negate;
   1079 	par.p = cond;
   1080 	par.curr = TOK_NONE;
   1081 	par.printedError = false;
   1082 
   1083 	rval = CondParser_Eval(&par, out_value);
   1084 
   1085 	if (rval == COND_INVALID && eprint && !par.printedError)
   1086 		Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", cond);
   1087 
   1088 	return rval;
   1089 }
   1090 
   1091 /*
   1092  * Evaluate a condition in a :? modifier, such as
   1093  * ${"${VAR}" == value:?yes:no}.
   1094  */
   1095 CondEvalResult
   1096 Cond_EvalCondition(const char *cond, bool *out_value)
   1097 {
   1098 	return CondEvalExpression(cond, out_value, true,
   1099 	    FuncDefined, false, false, false);
   1100 }
   1101 
   1102 static bool
   1103 IsEndif(const char *p)
   1104 {
   1105 	return p[0] == 'e' && p[1] == 'n' && p[2] == 'd' &&
   1106 	       p[3] == 'i' && p[4] == 'f' && !ch_isalpha(p[5]);
   1107 }
   1108 
   1109 static bool
   1110 DetermineKindOfConditional(const char **pp, bool *out_plain,
   1111 			   bool (**out_evalBare)(size_t, const char *),
   1112 			   bool *out_negate)
   1113 {
   1114 	const char *p = *pp;
   1115 
   1116 	p += 2;
   1117 	*out_plain = false;
   1118 	*out_evalBare = FuncDefined;
   1119 	*out_negate = false;
   1120 	if (*p == 'n') {
   1121 		p++;
   1122 		*out_negate = true;
   1123 	}
   1124 	if (is_token(p, "def", 3)) {		/* .ifdef and .ifndef */
   1125 		p += 3;
   1126 	} else if (is_token(p, "make", 4)) {	/* .ifmake and .ifnmake */
   1127 		p += 4;
   1128 		*out_evalBare = FuncMake;
   1129 	} else if (is_token(p, "", 0) && !*out_negate) { /* plain .if */
   1130 		*out_plain = true;
   1131 	} else {
   1132 		/*
   1133 		 * TODO: Add error message about unknown directive,
   1134 		 * since there is no other known directive that starts
   1135 		 * with 'el' or 'if'.
   1136 		 *
   1137 		 * Example: .elifx 123
   1138 		 */
   1139 		return false;
   1140 	}
   1141 
   1142 	*pp = p;
   1143 	return true;
   1144 }
   1145 
   1146 /*
   1147  * Evaluate the conditional directive in the line, which is one of:
   1148  *
   1149  *	.if <cond>
   1150  *	.ifmake <cond>
   1151  *	.ifnmake <cond>
   1152  *	.ifdef <cond>
   1153  *	.ifndef <cond>
   1154  *	.elif <cond>
   1155  *	.elifmake <cond>
   1156  *	.elifnmake <cond>
   1157  *	.elifdef <cond>
   1158  *	.elifndef <cond>
   1159  *	.else
   1160  *	.endif
   1161  *
   1162  * In these directives, <cond> consists of &&, ||, !, function(arg),
   1163  * comparisons, expressions, bare words, numbers and strings, and
   1164  * parenthetical groupings thereof.
   1165  *
   1166  * Results:
   1167  *	COND_PARSE	to continue parsing the lines that follow the
   1168  *			conditional (when <cond> evaluates to true)
   1169  *	COND_SKIP	to skip the lines after the conditional
   1170  *			(when <cond> evaluates to false, or when a previous
   1171  *			branch has already been taken)
   1172  *	COND_INVALID	if the conditional was not valid, either because of
   1173  *			a syntax error or because some variable was undefined
   1174  *			or because the condition could not be evaluated
   1175  */
   1176 CondEvalResult
   1177 Cond_EvalLine(const char *line)
   1178 {
   1179 	typedef enum IfState {
   1180 
   1181 		/* None of the previous <cond> evaluated to true. */
   1182 		IFS_INITIAL	= 0,
   1183 
   1184 		/* The previous <cond> evaluated to true.
   1185 		 * The lines following this condition are interpreted. */
   1186 		IFS_ACTIVE	= 1 << 0,
   1187 
   1188 		/* The previous directive was an '.else'. */
   1189 		IFS_SEEN_ELSE	= 1 << 1,
   1190 
   1191 		/* One of the previous <cond> evaluated to true. */
   1192 		IFS_WAS_ACTIVE	= 1 << 2
   1193 
   1194 	} IfState;
   1195 
   1196 	static enum IfState *cond_states = NULL;
   1197 	static unsigned int cond_states_cap = 128;
   1198 
   1199 	bool plain;
   1200 	bool (*evalBare)(size_t, const char *);
   1201 	bool negate;
   1202 	bool isElif;
   1203 	bool value;
   1204 	IfState state;
   1205 	const char *p = line;
   1206 
   1207 	if (cond_states == NULL) {
   1208 		cond_states = bmake_malloc(
   1209 		    cond_states_cap * sizeof *cond_states);
   1210 		cond_states[0] = IFS_ACTIVE;
   1211 	}
   1212 
   1213 	p++;			/* skip the leading '.' */
   1214 	cpp_skip_hspace(&p);
   1215 
   1216 	if (IsEndif(p)) {	/* It is an '.endif'. */
   1217 		if (p[5] != '\0') {
   1218 			Parse_Error(PARSE_FATAL,
   1219 			    "The .endif directive does not take arguments.");
   1220 		}
   1221 
   1222 		if (cond_depth == cond_min_depth) {
   1223 			Parse_Error(PARSE_FATAL, "if-less endif");
   1224 			return COND_PARSE;
   1225 		}
   1226 
   1227 		/* Return state for previous conditional */
   1228 		cond_depth--;
   1229 		return cond_states[cond_depth] & IFS_ACTIVE
   1230 		    ? COND_PARSE : COND_SKIP;
   1231 	}
   1232 
   1233 	/* Parse the name of the directive, such as 'if', 'elif', 'endif'. */
   1234 	if (p[0] == 'e') {
   1235 		if (p[1] != 'l') {
   1236 			/*
   1237 			 * Unknown directive.  It might still be a
   1238 			 * transformation rule like '.elisp.scm',
   1239 			 * therefore no error message here.
   1240 			 */
   1241 			return COND_INVALID;
   1242 		}
   1243 
   1244 		/* Quite likely this is 'else' or 'elif' */
   1245 		p += 2;
   1246 		if (is_token(p, "se", 2)) {	/* It is an 'else'. */
   1247 
   1248 			if (p[2] != '\0')
   1249 				Parse_Error(PARSE_FATAL,
   1250 					    "The .else directive "
   1251 					    "does not take arguments.");
   1252 
   1253 			if (cond_depth == cond_min_depth) {
   1254 				Parse_Error(PARSE_FATAL, "if-less else");
   1255 				return COND_PARSE;
   1256 			}
   1257 
   1258 			state = cond_states[cond_depth];
   1259 			if (state == IFS_INITIAL) {
   1260 				state = IFS_ACTIVE | IFS_SEEN_ELSE;
   1261 			} else {
   1262 				if (state & IFS_SEEN_ELSE)
   1263 					Parse_Error(PARSE_WARNING,
   1264 						    "extra else");
   1265 				state = IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
   1266 			}
   1267 			cond_states[cond_depth] = state;
   1268 
   1269 			return state & IFS_ACTIVE ? COND_PARSE : COND_SKIP;
   1270 		}
   1271 		/* Assume for now it is an elif */
   1272 		isElif = true;
   1273 	} else
   1274 		isElif = false;
   1275 
   1276 	if (p[0] != 'i' || p[1] != 'f') {
   1277 		/*
   1278 		 * Unknown directive.  It might still be a transformation rule
   1279 		 * like '.elisp.scm', therefore no error message here.
   1280 		 */
   1281 		return COND_INVALID;	/* Not an ifxxx or elifxxx line */
   1282 	}
   1283 
   1284 	if (!DetermineKindOfConditional(&p, &plain, &evalBare, &negate))
   1285 		return COND_INVALID;
   1286 
   1287 	if (isElif) {
   1288 		if (cond_depth == cond_min_depth) {
   1289 			Parse_Error(PARSE_FATAL, "if-less elif");
   1290 			return COND_PARSE;
   1291 		}
   1292 		state = cond_states[cond_depth];
   1293 		if (state & IFS_SEEN_ELSE) {
   1294 			Parse_Error(PARSE_WARNING, "extra elif");
   1295 			cond_states[cond_depth] =
   1296 			    IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
   1297 			return COND_SKIP;
   1298 		}
   1299 		if (state != IFS_INITIAL) {
   1300 			cond_states[cond_depth] = IFS_WAS_ACTIVE;
   1301 			return COND_SKIP;
   1302 		}
   1303 	} else {
   1304 		/* Normal .if */
   1305 		if (cond_depth + 1 >= cond_states_cap) {
   1306 			/*
   1307 			 * This is rare, but not impossible.
   1308 			 * In meta mode, dirdeps.mk (only runs at level 0)
   1309 			 * can need more than the default.
   1310 			 */
   1311 			cond_states_cap += 32;
   1312 			cond_states = bmake_realloc(cond_states,
   1313 						    cond_states_cap *
   1314 						    sizeof *cond_states);
   1315 		}
   1316 		state = cond_states[cond_depth];
   1317 		cond_depth++;
   1318 		if (!(state & IFS_ACTIVE)) {
   1319 			/*
   1320 			 * If we aren't parsing the data,
   1321 			 * treat as always false.
   1322 			 */
   1323 			cond_states[cond_depth] = IFS_WAS_ACTIVE;
   1324 			return COND_SKIP;
   1325 		}
   1326 	}
   1327 
   1328 	/* And evaluate the conditional expression */
   1329 	if (CondEvalExpression(p, &value, plain, evalBare, negate,
   1330 	    true, true) == COND_INVALID) {
   1331 		/* Syntax error in conditional, error message already output. */
   1332 		/* Skip everything to matching .endif */
   1333 		/* XXX: An extra '.else' is not detected in this case. */
   1334 		cond_states[cond_depth] = IFS_WAS_ACTIVE;
   1335 		return COND_SKIP;
   1336 	}
   1337 
   1338 	if (!value) {
   1339 		cond_states[cond_depth] = IFS_INITIAL;
   1340 		return COND_SKIP;
   1341 	}
   1342 	cond_states[cond_depth] = IFS_ACTIVE;
   1343 	return COND_PARSE;
   1344 }
   1345 
   1346 void
   1347 Cond_restore_depth(unsigned int saved_depth)
   1348 {
   1349 	unsigned int open_conds = cond_depth - cond_min_depth;
   1350 
   1351 	if (open_conds != 0 || saved_depth > cond_depth) {
   1352 		Parse_Error(PARSE_FATAL, "%u open conditional%s",
   1353 			    open_conds, open_conds == 1 ? "" : "s");
   1354 		cond_depth = cond_min_depth;
   1355 	}
   1356 
   1357 	cond_min_depth = saved_depth;
   1358 }
   1359 
   1360 unsigned int
   1361 Cond_save_depth(void)
   1362 {
   1363 	unsigned int depth = cond_min_depth;
   1364 
   1365 	cond_min_depth = cond_depth;
   1366 	return depth;
   1367 }
   1368