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