Home | History | Annotate | Line # | Download | only in make
cond.c revision 1.138
      1 /*	$NetBSD: cond.c,v 1.138 2020/09/12 17:14:40 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.138 2020/09/12 17:14:40 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.138 2020/09/12 17:14:40 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 	/* The PARSE_FATAL is done as a follow-up by Cond_EvalExpression. */
    285 	return 0;
    286     }
    287 
    288     *linePtr = cp;
    289     return argLen;
    290 }
    291 
    292 /* Test whether the given variable is defined. */
    293 static Boolean
    294 FuncDefined(int argLen MAKE_ATTR_UNUSED, const char *arg)
    295 {
    296     char *freeIt;
    297     Boolean result = Var_Value(arg, VAR_CMD, &freeIt) != NULL;
    298     bmake_free(freeIt);
    299     return result;
    300 }
    301 
    302 /* Wrapper around Str_Match, to be used by Lst_Find. */
    303 static Boolean
    304 CondFindStrMatch(const void *string, const void *pattern)
    305 {
    306     return Str_Match(string, pattern);
    307 }
    308 
    309 /* See if the given target is being made. */
    310 static Boolean
    311 FuncMake(int argLen MAKE_ATTR_UNUSED, const char *arg)
    312 {
    313     return Lst_Find(create, CondFindStrMatch, arg) != NULL;
    314 }
    315 
    316 /* See if the given file exists. */
    317 static Boolean
    318 FuncExists(int argLen MAKE_ATTR_UNUSED, const char *arg)
    319 {
    320     Boolean result;
    321     char *path;
    322 
    323     path = Dir_FindFile(arg, dirSearchPath);
    324     if (DEBUG(COND)) {
    325 	fprintf(debug_file, "exists(%s) result is \"%s\"\n",
    326 		arg, path ? path : "");
    327     }
    328     if (path != NULL) {
    329 	result = TRUE;
    330 	free(path);
    331     } else {
    332 	result = FALSE;
    333     }
    334     return result;
    335 }
    336 
    337 /* See if the given node exists and is an actual target. */
    338 static Boolean
    339 FuncTarget(int argLen MAKE_ATTR_UNUSED, const char *arg)
    340 {
    341     GNode *gn;
    342 
    343     gn = Targ_FindNode(arg, TARG_NOCREATE);
    344     return gn != NULL && !OP_NOP(gn->type);
    345 }
    346 
    347 /* See if the given node exists and is an actual target with commands
    348  * associated with it. */
    349 static Boolean
    350 FuncCommands(int argLen MAKE_ATTR_UNUSED, const char *arg)
    351 {
    352     GNode *gn;
    353 
    354     gn = Targ_FindNode(arg, TARG_NOCREATE);
    355     return gn != NULL && !OP_NOP(gn->type) && !Lst_IsEmpty(gn->commands);
    356 }
    357 
    358 /*-
    359  * Convert the given number into a double.
    360  * We try a base 10 or 16 integer conversion first, if that fails
    361  * then we try a floating point conversion instead.
    362  *
    363  * Results:
    364  *	Sets 'value' to double value of string.
    365  *	Returns TRUE if the conversion succeeded.
    366  */
    367 static Boolean
    368 TryParseNumber(const char *str, double *value)
    369 {
    370     char *eptr, ech;
    371     unsigned long l_val;
    372     double d_val;
    373 
    374     errno = 0;
    375     if (!*str) {
    376 	*value = (double)0;
    377 	return TRUE;
    378     }
    379     l_val = strtoul(str, &eptr, str[1] == 'x' ? 16 : 10);
    380     ech = *eptr;
    381     if (ech == 0 && errno != ERANGE) {
    382 	d_val = str[0] == '-' ? -(double)-l_val : (double)l_val;
    383     } else {
    384 	if (ech != 0 && ech != '.' && ech != 'e' && ech != 'E')
    385 	    return FALSE;
    386 	d_val = strtod(str, &eptr);
    387 	if (*eptr)
    388 	    return FALSE;
    389     }
    390 
    391     *value = d_val;
    392     return TRUE;
    393 }
    394 
    395 /*-
    396  * Parse a string from a variable reference or an optionally quoted
    397  * string.  This is called for the lhs and rhs of string comparisons.
    398  *
    399  * Results:
    400  *	Returns the string, absent any quotes, or NULL on error.
    401  *	Sets quoted if the string was quoted.
    402  *	Sets freeIt if needed.
    403  */
    404 /* coverity:[+alloc : arg-*3] */
    405 static const char *
    406 CondParser_String(CondParser *par, Boolean doEval, Boolean strictLHS,
    407 		  Boolean *quoted, void **freeIt)
    408 {
    409     Buffer buf;
    410     const char *str;
    411     int len;
    412     Boolean qt;
    413     const char *start;
    414     VarEvalFlags eflags;
    415 
    416     Buf_Init(&buf, 0);
    417     str = NULL;
    418     *freeIt = NULL;
    419     *quoted = qt = par->p[0] == '"' ? 1 : 0;
    420     if (qt)
    421 	par->p++;
    422     start = par->p;
    423     while (par->p[0] && str == NULL) {
    424 	switch (par->p[0]) {
    425 	case '\\':
    426 	    par->p++;
    427 	    if (par->p[0] != '\0') {
    428 		Buf_AddByte(&buf, par->p[0]);
    429 		par->p++;
    430 	    }
    431 	    continue;
    432 	case '"':
    433 	    if (qt) {
    434 		par->p++;	/* we don't want the quotes */
    435 		goto got_str;
    436 	    }
    437 	    Buf_AddByte(&buf, par->p[0]); /* likely? */
    438 	    par->p++;
    439 	    continue;
    440 	case ')':
    441 	case '!':
    442 	case '=':
    443 	case '>':
    444 	case '<':
    445 	case ' ':
    446 	case '\t':
    447 	    if (!qt)
    448 		goto got_str;
    449 	    Buf_AddByte(&buf, par->p[0]);
    450 	    par->p++;
    451 	    continue;
    452 	case '$':
    453 	    /* if we are in quotes, then an undefined variable is ok */
    454 	    eflags = ((!qt && doEval) ? VARE_UNDEFERR : 0) |
    455 		     (doEval ? VARE_WANTRES : 0);
    456 	    str = Var_Parse(par->p, VAR_CMD, eflags, &len, freeIt);
    457 	    if (str == var_Error) {
    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 += len;
    470 	    /*
    471 	     * If the '$' was first char (no quotes), and we are
    472 	     * followed by space, the operator or end of expression,
    473 	     * we are done.
    474 	     */
    475 	    if ((par->p == start + len) &&
    476 		(par->p[0] == '\0' ||
    477 		 ch_isspace(par->p[0]) ||
    478 		 strchr("!=><)", par->p[0]))) {
    479 		goto cleanup;
    480 	    }
    481 
    482 	    Buf_AddStr(&buf, str);
    483 	    if (*freeIt) {
    484 		free(*freeIt);
    485 		*freeIt = NULL;
    486 	    }
    487 	    str = NULL;		/* not finished yet */
    488 	    continue;
    489 	default:
    490 	    if (strictLHS && !qt && *start != '$' && !ch_isdigit(*start)) {
    491 		/* lhs must be quoted, a variable reference or number */
    492 		if (*freeIt) {
    493 		    free(*freeIt);
    494 		    *freeIt = NULL;
    495 		}
    496 		str = NULL;
    497 		goto cleanup;
    498 	    }
    499 	    Buf_AddByte(&buf, par->p[0]);
    500 	    par->p++;
    501 	    continue;
    502 	}
    503     }
    504 got_str:
    505     *freeIt = Buf_GetAll(&buf, NULL);
    506     str = *freeIt;
    507 cleanup:
    508     Buf_Destroy(&buf, FALSE);
    509     return str;
    510 }
    511 
    512 /* The different forms of .if directives. */
    513 static const struct If {
    514     const char *form;		/* Form of if */
    515     size_t formlen;		/* Length of form */
    516     Boolean doNot;		/* TRUE if default function should be negated */
    517     Boolean (*defProc)(int, const char *); /* Default function to apply */
    518 } ifs[] = {
    519     { "def",   3, FALSE, FuncDefined },
    520     { "ndef",  4, TRUE,  FuncDefined },
    521     { "make",  4, FALSE, FuncMake },
    522     { "nmake", 5, TRUE,  FuncMake },
    523     { "",      0, FALSE, FuncDefined },
    524     { NULL,    0, FALSE, NULL }
    525 };
    526 
    527 /* Evaluate a "comparison without operator", such as in ".if ${VAR}" or
    528  * ".if 0". */
    529 static Token
    530 EvalNotEmpty(CondParser *par, const char *lhs, Boolean lhsQuoted)
    531 {
    532     double left;
    533 
    534     /* For .ifxxx "..." check for non-empty string. */
    535     if (lhsQuoted)
    536 	return lhs[0] != '\0';
    537 
    538     /* For .ifxxx <number> compare against zero */
    539     if (TryParseNumber(lhs, &left))
    540 	return left != 0.0;
    541 
    542     /* For .if ${...} check for non-empty string (defProc is ifdef). */
    543     if (par->if_info->form[0] == '\0')
    544 	return lhs[0] != 0;
    545 
    546     /* Otherwise action default test ... */
    547     return par->if_info->defProc(strlen(lhs), lhs) != par->if_info->doNot;
    548 }
    549 
    550 /* Evaluate a numerical comparison, such as in ".if ${VAR} >= 9". */
    551 static Token
    552 EvalCompareNum(double lhs, const char *op, double rhs)
    553 {
    554     if (DEBUG(COND))
    555 	fprintf(debug_file, "lhs = %f, rhs = %f, op = %.2s\n", lhs, rhs, op);
    556 
    557     switch (op[0]) {
    558     case '!':
    559 	if (op[1] != '=') {
    560 	    Parse_Error(PARSE_WARNING, "Unknown operator");
    561 	    /* The PARSE_FATAL is done as a follow-up by Cond_EvalExpression. */
    562 	    return TOK_ERROR;
    563 	}
    564 	return lhs != rhs;
    565     case '=':
    566 	if (op[1] != '=') {
    567 	    Parse_Error(PARSE_WARNING, "Unknown operator");
    568 	    /* The PARSE_FATAL is done as a follow-up by Cond_EvalExpression. */
    569 	    return TOK_ERROR;
    570 	}
    571 	return lhs == rhs;
    572     case '<':
    573 	return op[1] == '=' ? lhs <= rhs : lhs < rhs;
    574     case '>':
    575 	return op[1] == '=' ? lhs >= rhs : lhs > rhs;
    576     }
    577     return TOK_ERROR;
    578 }
    579 
    580 static Token
    581 EvalCompareStr(const char *lhs, const char *op, const char *rhs)
    582 {
    583     if (!((op[0] == '!' || op[0] == '=') && op[1] == '=')) {
    584 	Parse_Error(PARSE_WARNING,
    585 		    "String comparison operator must be either == or !=");
    586 	/* The PARSE_FATAL is done as a follow-up by Cond_EvalExpression. */
    587 	return TOK_ERROR;
    588     }
    589 
    590     if (DEBUG(COND)) {
    591 	fprintf(debug_file, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
    592 		lhs, rhs, op);
    593     }
    594     return (*op == '=') == (strcmp(lhs, rhs) == 0);
    595 }
    596 
    597 /* Evaluate a comparison, such as "${VAR} == 12345". */
    598 static Token
    599 EvalCompare(const char *lhs, Boolean lhsQuoted, const char *op,
    600 	    const char *rhs, Boolean rhsQuoted)
    601 {
    602     double left, right;
    603 
    604     if (!rhsQuoted && !lhsQuoted)
    605 	if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
    606 	    return EvalCompareNum(left, op, right);
    607 
    608     return EvalCompareStr(lhs, op, rhs);
    609 }
    610 
    611 /* Parse a comparison condition such as:
    612  *
    613  *	0
    614  *	${VAR:Mpattern}
    615  *	${VAR} == value
    616  *	${VAR:U0} < 12345
    617  */
    618 static Token
    619 CondParser_Comparison(CondParser *par, Boolean doEval)
    620 {
    621     Token t = TOK_ERROR;
    622     const char *lhs, *op, *rhs;
    623     void *lhsFree, *rhsFree;
    624     Boolean lhsQuoted, rhsQuoted;
    625 
    626     rhs = NULL;
    627     lhsFree = rhsFree = NULL;
    628     lhsQuoted = rhsQuoted = FALSE;
    629 
    630     /*
    631      * Parse the variable spec and skip over it, saving its
    632      * value in lhs.
    633      */
    634     lhs = CondParser_String(par, doEval, lhsStrict, &lhsQuoted, &lhsFree);
    635     if (!lhs)
    636 	goto done;
    637 
    638     CondParser_SkipWhitespace(par);
    639 
    640     /*
    641      * Make sure the operator is a valid one. If it isn't a
    642      * known relational operator, pretend we got a
    643      * != 0 comparison.
    644      */
    645     op = par->p;
    646     switch (par->p[0]) {
    647     case '!':
    648     case '=':
    649     case '<':
    650     case '>':
    651 	if (par->p[1] == '=') {
    652 	    par->p += 2;
    653 	} else {
    654 	    par->p += 1;
    655 	}
    656 	break;
    657     default:
    658 	t = doEval ? EvalNotEmpty(par, lhs, lhsQuoted) : TOK_FALSE;
    659 	goto done;
    660     }
    661 
    662     CondParser_SkipWhitespace(par);
    663 
    664     if (par->p[0] == '\0') {
    665 	Parse_Error(PARSE_WARNING, "Missing right-hand-side of operator");
    666 	/* The PARSE_FATAL is done as a follow-up by Cond_EvalExpression. */
    667 	goto done;
    668     }
    669 
    670     rhs = CondParser_String(par, doEval, FALSE, &rhsQuoted, &rhsFree);
    671     if (rhs == NULL)
    672 	goto done;
    673 
    674     if (!doEval) {
    675 	t = TOK_FALSE;
    676 	goto done;
    677     }
    678 
    679     t = EvalCompare(lhs, lhsQuoted, op, rhs, rhsQuoted);
    680 
    681 done:
    682     free(lhsFree);
    683     free(rhsFree);
    684     return t;
    685 }
    686 
    687 static int
    688 ParseEmptyArg(const char **linePtr, Boolean doEval,
    689 	      const char *func MAKE_ATTR_UNUSED, char **argPtr)
    690 {
    691     void *val_freeIt;
    692     const char *val;
    693     int magic_res;
    694 
    695     /* We do all the work here and return the result as the length */
    696     *argPtr = NULL;
    697 
    698     (*linePtr)--;		/* Make (*linePtr)[1] point to the '('. */
    699     val = Var_ParsePP(linePtr, VAR_CMD, doEval ? VARE_WANTRES : 0, &val_freeIt);
    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 CondEvalResult
   1015 Cond_EvalExpression(const struct If *info, const char *cond, Boolean *value,
   1016 		    int 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 
   1040     rval = CondParser_Eval(&par, value);
   1041 
   1042     if (rval == COND_INVALID && eprint)
   1043 	Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", cond);
   1044 
   1045     return rval;
   1046 }
   1047 
   1048 
   1049 /* Evaluate the conditional in the passed line. The line looks like this:
   1050  *	.<cond-type> <expr>
   1051  * In this line, <cond-type> is any of if, ifmake, ifnmake, ifdef, ifndef,
   1052  * elif, elifmake, elifnmake, elifdef, elifndef.
   1053  * In this line, <expr> consists of &&, ||, !, function(arg), comparisons
   1054  * and parenthetical groupings thereof.
   1055  *
   1056  * Note that the states IF_ACTIVE and ELSE_ACTIVE are only different in order
   1057  * to detect spurious .else lines (as are SKIP_TO_ELSE and SKIP_TO_ENDIF),
   1058  * otherwise .else could be treated as '.elif 1'.
   1059  *
   1060  * Results:
   1061  *	COND_PARSE	to continue parsing the lines after the conditional
   1062  *			(when .if or .else returns TRUE)
   1063  *	COND_SKIP	to skip the lines after the conditional
   1064  *			(when .if or .elif returns FALSE, or when a previous
   1065  *			branch has already been taken)
   1066  *	COND_INVALID  	if the conditional was not valid, either because of
   1067  *			a syntax error or because some variable was undefined
   1068  *			or because the condition could not be evaluated
   1069  */
   1070 CondEvalResult
   1071 Cond_Eval(const char *line)
   1072 {
   1073     enum { MAXIF = 128 };	/* maximum depth of .if'ing */
   1074     enum { MAXIF_BUMP = 32 };	/* how much to grow by */
   1075     enum if_states {
   1076 	IF_ACTIVE,		/* .if or .elif part active */
   1077 	ELSE_ACTIVE,		/* .else part active */
   1078 	SEARCH_FOR_ELIF,	/* searching for .elif/else to execute */
   1079 	SKIP_TO_ELSE,		/* has been true, but not seen '.else' */
   1080 	SKIP_TO_ENDIF		/* nothing else to execute */
   1081     };
   1082     static enum if_states *cond_state = NULL;
   1083     static unsigned int max_if_depth = MAXIF;
   1084 
   1085     const struct If *ifp;
   1086     Boolean isElif;
   1087     Boolean value;
   1088     enum if_states state;
   1089 
   1090     if (!cond_state) {
   1091 	cond_state = bmake_malloc(max_if_depth * sizeof(*cond_state));
   1092 	cond_state[0] = IF_ACTIVE;
   1093     }
   1094     /* skip leading character (the '.') and any whitespace */
   1095     for (line++; *line == ' ' || *line == '\t'; line++)
   1096 	continue;
   1097 
   1098     /* Find what type of if we're dealing with.  */
   1099     if (line[0] == 'e') {
   1100 	if (line[1] != 'l') {
   1101 	    if (!is_token(line + 1, "ndif", 4))
   1102 		return COND_INVALID;
   1103 	    /* End of conditional section */
   1104 	    if (cond_depth == cond_min_depth) {
   1105 		Parse_Error(PARSE_FATAL, "if-less endif");
   1106 		return COND_PARSE;
   1107 	    }
   1108 	    /* Return state for previous conditional */
   1109 	    cond_depth--;
   1110 	    return cond_state[cond_depth] <= ELSE_ACTIVE
   1111 		   ? COND_PARSE : COND_SKIP;
   1112 	}
   1113 
   1114 	/* Quite likely this is 'else' or 'elif' */
   1115 	line += 2;
   1116 	if (is_token(line, "se", 2)) {
   1117 	    /* It is else... */
   1118 	    if (cond_depth == cond_min_depth) {
   1119 		Parse_Error(PARSE_FATAL, "if-less else");
   1120 		return COND_PARSE;
   1121 	    }
   1122 
   1123 	    state = cond_state[cond_depth];
   1124 	    switch (state) {
   1125 	    case SEARCH_FOR_ELIF:
   1126 		state = ELSE_ACTIVE;
   1127 		break;
   1128 	    case ELSE_ACTIVE:
   1129 	    case SKIP_TO_ENDIF:
   1130 		Parse_Error(PARSE_WARNING, "extra else");
   1131 		/* FALLTHROUGH */
   1132 	    default:
   1133 	    case IF_ACTIVE:
   1134 	    case SKIP_TO_ELSE:
   1135 		state = SKIP_TO_ENDIF;
   1136 		break;
   1137 	    }
   1138 	    cond_state[cond_depth] = state;
   1139 	    return state <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
   1140 	}
   1141 	/* Assume for now it is an elif */
   1142 	isElif = TRUE;
   1143     } else
   1144 	isElif = FALSE;
   1145 
   1146     if (line[0] != 'i' || line[1] != 'f')
   1147 	/* Not an ifxxx or elifxxx line */
   1148 	return COND_INVALID;
   1149 
   1150     /*
   1151      * Figure out what sort of conditional it is -- what its default
   1152      * function is, etc. -- by looking in the table of valid "ifs"
   1153      */
   1154     line += 2;
   1155     for (ifp = ifs;; ifp++) {
   1156 	if (ifp->form == NULL)
   1157 	    return COND_INVALID;
   1158 	if (is_token(ifp->form, line, ifp->formlen)) {
   1159 	    line += ifp->formlen;
   1160 	    break;
   1161 	}
   1162     }
   1163 
   1164     /* Now we know what sort of 'if' it is... */
   1165 
   1166     if (isElif) {
   1167 	if (cond_depth == cond_min_depth) {
   1168 	    Parse_Error(PARSE_FATAL, "if-less elif");
   1169 	    return COND_PARSE;
   1170 	}
   1171 	state = cond_state[cond_depth];
   1172 	if (state == SKIP_TO_ENDIF || state == ELSE_ACTIVE) {
   1173 	    Parse_Error(PARSE_WARNING, "extra elif");
   1174 	    cond_state[cond_depth] = SKIP_TO_ENDIF;
   1175 	    return COND_SKIP;
   1176 	}
   1177 	if (state != SEARCH_FOR_ELIF) {
   1178 	    /* Either just finished the 'true' block, or already SKIP_TO_ELSE */
   1179 	    cond_state[cond_depth] = SKIP_TO_ELSE;
   1180 	    return COND_SKIP;
   1181 	}
   1182     } else {
   1183 	/* Normal .if */
   1184 	if (cond_depth + 1 >= max_if_depth) {
   1185 	    /*
   1186 	     * This is rare, but not impossible.
   1187 	     * In meta mode, dirdeps.mk (only runs at level 0)
   1188 	     * can need more than the default.
   1189 	     */
   1190 	    max_if_depth += MAXIF_BUMP;
   1191 	    cond_state = bmake_realloc(cond_state,
   1192 				       max_if_depth * sizeof(*cond_state));
   1193 	}
   1194 	state = cond_state[cond_depth];
   1195 	cond_depth++;
   1196 	if (state > ELSE_ACTIVE) {
   1197 	    /* If we aren't parsing the data, treat as always false */
   1198 	    cond_state[cond_depth] = SKIP_TO_ELSE;
   1199 	    return COND_SKIP;
   1200 	}
   1201     }
   1202 
   1203     /* And evaluate the conditional expression */
   1204     if (Cond_EvalExpression(ifp, line, &value, 1, TRUE) == COND_INVALID) {
   1205 	/* Syntax error in conditional, error message already output. */
   1206 	/* Skip everything to matching .endif */
   1207 	cond_state[cond_depth] = SKIP_TO_ELSE;
   1208 	return COND_SKIP;
   1209     }
   1210 
   1211     if (!value) {
   1212 	cond_state[cond_depth] = SEARCH_FOR_ELIF;
   1213 	return COND_SKIP;
   1214     }
   1215     cond_state[cond_depth] = IF_ACTIVE;
   1216     return COND_PARSE;
   1217 }
   1218 
   1219 void
   1220 Cond_restore_depth(unsigned int saved_depth)
   1221 {
   1222     int open_conds = cond_depth - cond_min_depth;
   1223 
   1224     if (open_conds != 0 || saved_depth > cond_depth) {
   1225 	Parse_Error(PARSE_FATAL, "%d open conditional%s", open_conds,
   1226 		    open_conds == 1 ? "" : "s");
   1227 	cond_depth = cond_min_depth;
   1228     }
   1229 
   1230     cond_min_depth = saved_depth;
   1231 }
   1232 
   1233 unsigned int
   1234 Cond_save_depth(void)
   1235 {
   1236     int depth = cond_min_depth;
   1237 
   1238     cond_min_depth = cond_depth;
   1239     return depth;
   1240 }
   1241