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