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