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