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