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