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