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