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