Home | History | Annotate | Line # | Download | only in make
cond.c revision 1.56
      1 /*	$NetBSD: cond.c,v 1.56 2009/01/28 21:38:12 dsl 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.56 2009/01/28 21:38:12 dsl 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.56 2009/01/28 21:38:12 dsl Exp $");
     81 #endif
     82 #endif /* not lint */
     83 #endif
     84 
     85 /*-
     86  * cond.c --
     87  *	Functions to handle conditionals in a makefile.
     88  *
     89  * Interface:
     90  *	Cond_Eval 	Evaluate the conditional in the passed line.
     91  *
     92  */
     93 
     94 #include    <ctype.h>
     95 #include    <errno.h>    /* For strtoul() error checking */
     96 
     97 #include    "make.h"
     98 #include    "hash.h"
     99 #include    "dir.h"
    100 #include    "buf.h"
    101 
    102 /*
    103  * The parsing of conditional expressions is based on this grammar:
    104  *	E -> F || E
    105  *	E -> F
    106  *	F -> T && F
    107  *	F -> T
    108  *	T -> defined(variable)
    109  *	T -> make(target)
    110  *	T -> exists(file)
    111  *	T -> empty(varspec)
    112  *	T -> target(name)
    113  *	T -> commands(name)
    114  *	T -> symbol
    115  *	T -> $(varspec) op value
    116  *	T -> $(varspec) == "string"
    117  *	T -> $(varspec) != "string"
    118  *	T -> "string"
    119  *	T -> ( E )
    120  *	T -> ! T
    121  *	op -> == | != | > | < | >= | <=
    122  *
    123  * 'symbol' is some other symbol to which the default function (condDefProc)
    124  * is applied.
    125  *
    126  * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
    127  * will return And for '&' and '&&', Or for '|' and '||', Not for '!',
    128  * LParen for '(', RParen for ')' and will evaluate the other terminal
    129  * symbols, using either the default function or the function given in the
    130  * terminal, and return the result as either True or False.
    131  *
    132  * All Non-Terminal functions (CondE, CondF and CondT) return Err on error.
    133  */
    134 typedef enum {
    135     And, Or, Not, True, False, LParen, RParen, EndOfFile, None, Err
    136 } Token;
    137 
    138 /*-
    139  * Structures to handle elegantly the different forms of #if's. The
    140  * last two fields are stored in condInvert and condDefProc, respectively.
    141  */
    142 static void CondPushBack(Token);
    143 static int CondGetArg(char **, char **, const char *);
    144 static Boolean CondDoDefined(int, const char *);
    145 static int CondStrMatch(const void *, const void *);
    146 static Boolean CondDoMake(int, const char *);
    147 static Boolean CondDoExists(int, const char *);
    148 static Boolean CondDoTarget(int, const char *);
    149 static Boolean CondDoCommands(int, const char *);
    150 static Boolean CondCvtArg(char *, double *);
    151 static Token CondToken(Boolean);
    152 static Token CondT(Boolean);
    153 static Token CondF(Boolean);
    154 static Token CondE(Boolean);
    155 static int do_Cond_EvalExpression(Boolean *);
    156 
    157 static const struct If {
    158     const char	*form;	      /* Form of if */
    159     int		formlen;      /* Length of form */
    160     Boolean	doNot;	      /* TRUE if default function should be negated */
    161     Boolean	(*defProc)(int, const char *); /* Default function to apply */
    162 } ifs[] = {
    163     { "def",	  3,	  FALSE,  CondDoDefined },
    164     { "ndef",	  4,	  TRUE,	  CondDoDefined },
    165     { "make",	  4,	  FALSE,  CondDoMake },
    166     { "nmake",	  5,	  TRUE,	  CondDoMake },
    167     { "",	  0,	  FALSE,  CondDoDefined },
    168     { NULL,	  0,	  FALSE,  NULL }
    169 };
    170 
    171 static const struct If *if_info;        /* Info for current statement */
    172 static char 	  *condExpr;	    	/* The expression to parse */
    173 static Token	  condPushBack=None;	/* Single push-back token used in
    174 					 * parsing */
    175 
    176 static unsigned int	cond_depth = 0;  	/* current .if nesting level */
    177 static unsigned int	cond_min_depth = 0;  	/* depth at makefile open */
    178 
    179 static int
    180 istoken(const char *str, const char *tok, size_t len)
    181 {
    182 	return strncmp(str, tok, len) == 0 && !isalpha((unsigned char)str[len]);
    183 }
    184 
    185 /*-
    186  *-----------------------------------------------------------------------
    187  * CondPushBack --
    188  *	Push back the most recent token read. We only need one level of
    189  *	this, so the thing is just stored in 'condPushback'.
    190  *
    191  * Input:
    192  *	t		Token to push back into the "stream"
    193  *
    194  * Results:
    195  *	None.
    196  *
    197  * Side Effects:
    198  *	condPushback is overwritten.
    199  *
    200  *-----------------------------------------------------------------------
    201  */
    202 static void
    203 CondPushBack(Token t)
    204 {
    205     condPushBack = t;
    206 }
    207 
    208 /*-
    210  *-----------------------------------------------------------------------
    211  * CondGetArg --
    212  *	Find the argument of a built-in function.
    213  *
    214  * Input:
    215  *	parens		TRUE if arg should be bounded by parens
    216  *
    217  * Results:
    218  *	The length of the argument and the address of the argument.
    219  *
    220  * Side Effects:
    221  *	The pointer is set to point to the closing parenthesis of the
    222  *	function call.
    223  *
    224  *-----------------------------------------------------------------------
    225  */
    226 static int
    227 CondGetArg(char **linePtr, char **argPtr, const char *func)
    228 {
    229     char	  *cp;
    230     int	    	  argLen;
    231     Buffer	  buf;
    232     int           paren_depth;
    233     char          ch;
    234 
    235     cp = *linePtr;
    236     if (func != NULL)
    237 	/* Skip opening '(' - verfied by caller */
    238 	cp++;
    239 
    240     if (*cp == '\0') {
    241 	/*
    242 	 * No arguments whatsoever. Because 'make' and 'defined' aren't really
    243 	 * "reserved words", we don't print a message. I think this is better
    244 	 * than hitting the user with a warning message every time s/he uses
    245 	 * the word 'make' or 'defined' at the beginning of a symbol...
    246 	 */
    247 	*argPtr = NULL;
    248 	return (0);
    249     }
    250 
    251     while (*cp == ' ' || *cp == '\t') {
    252 	cp++;
    253     }
    254 
    255     /*
    256      * Create a buffer for the argument and start it out at 16 characters
    257      * long. Why 16? Why not?
    258      */
    259     Buf_Init(&buf, 16);
    260 
    261     paren_depth = 0;
    262     for (;;) {
    263 	ch = *cp;
    264 	if (ch == 0 || ch == ' ' || ch == '\t')
    265 	    break;
    266 	if ((ch == '&' || ch == '|') && paren_depth == 0)
    267 	    break;
    268 	if (*cp == '$') {
    269 	    /*
    270 	     * Parse the variable spec and install it as part of the argument
    271 	     * if it's valid. We tell Var_Parse to complain on an undefined
    272 	     * variable, so we don't do it too. Nor do we return an error,
    273 	     * though perhaps we should...
    274 	     */
    275 	    char  	*cp2;
    276 	    int		len;
    277 	    void	*freeIt;
    278 
    279 	    cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &freeIt);
    280 	    Buf_AddBytes(&buf, strlen(cp2), cp2);
    281 	    if (freeIt)
    282 		free(freeIt);
    283 	    cp += len;
    284 	    continue;
    285 	}
    286 	if (ch == '(')
    287 	    paren_depth++;
    288 	else
    289 	    if (ch == ')' && --paren_depth < 0)
    290 		break;
    291 	Buf_AddByte(&buf, *cp);
    292 	cp++;
    293     }
    294 
    295     *argPtr = Buf_GetAll(&buf, &argLen);
    296     Buf_Destroy(&buf, FALSE);
    297 
    298     while (*cp == ' ' || *cp == '\t') {
    299 	cp++;
    300     }
    301 
    302     if (func != NULL && *cp++ != ')') {
    303 	Parse_Error(PARSE_WARNING, "Missing closing parenthesis for %s()",
    304 		     func);
    305 	return (0);
    306     }
    307 
    308     *linePtr = cp;
    309     return (argLen);
    310 }
    311 
    312 /*-
    314  *-----------------------------------------------------------------------
    315  * CondDoDefined --
    316  *	Handle the 'defined' function for conditionals.
    317  *
    318  * Results:
    319  *	TRUE if the given variable is defined.
    320  *
    321  * Side Effects:
    322  *	None.
    323  *
    324  *-----------------------------------------------------------------------
    325  */
    326 static Boolean
    327 CondDoDefined(int argLen, const char *arg)
    328 {
    329     char    *p1;
    330     Boolean result;
    331 
    332     if (Var_Value(arg, VAR_CMD, &p1) != NULL) {
    333 	result = TRUE;
    334     } else {
    335 	result = FALSE;
    336     }
    337     if (p1)
    338 	free(p1);
    339     return (result);
    340 }
    341 
    342 /*-
    344  *-----------------------------------------------------------------------
    345  * CondStrMatch --
    346  *	Front-end for Str_Match so it returns 0 on match and non-zero
    347  *	on mismatch. Callback function for CondDoMake via Lst_Find
    348  *
    349  * Results:
    350  *	0 if string matches pattern
    351  *
    352  * Side Effects:
    353  *	None
    354  *
    355  *-----------------------------------------------------------------------
    356  */
    357 static int
    358 CondStrMatch(const void *string, const void *pattern)
    359 {
    360     return(!Str_Match(string, pattern));
    361 }
    362 
    363 /*-
    365  *-----------------------------------------------------------------------
    366  * CondDoMake --
    367  *	Handle the 'make' function for conditionals.
    368  *
    369  * Results:
    370  *	TRUE if the given target is being made.
    371  *
    372  * Side Effects:
    373  *	None.
    374  *
    375  *-----------------------------------------------------------------------
    376  */
    377 static Boolean
    378 CondDoMake(int argLen, const char *arg)
    379 {
    380     return Lst_Find(create, arg, CondStrMatch) != NULL;
    381 }
    382 
    383 /*-
    385  *-----------------------------------------------------------------------
    386  * CondDoExists --
    387  *	See if the given file exists.
    388  *
    389  * Results:
    390  *	TRUE if the file exists and FALSE if it does not.
    391  *
    392  * Side Effects:
    393  *	None.
    394  *
    395  *-----------------------------------------------------------------------
    396  */
    397 static Boolean
    398 CondDoExists(int argLen, const char *arg)
    399 {
    400     Boolean result;
    401     char    *path;
    402 
    403     path = Dir_FindFile(arg, dirSearchPath);
    404     if (path != NULL) {
    405 	result = TRUE;
    406 	free(path);
    407     } else {
    408 	result = FALSE;
    409     }
    410     if (DEBUG(COND)) {
    411 	fprintf(debug_file, "exists(%s) result is \"%s\"\n",
    412 	       arg, path ? path : "");
    413     }
    414     return (result);
    415 }
    416 
    417 /*-
    419  *-----------------------------------------------------------------------
    420  * CondDoTarget --
    421  *	See if the given node exists and is an actual target.
    422  *
    423  * Results:
    424  *	TRUE if the node exists as a target and FALSE if it does not.
    425  *
    426  * Side Effects:
    427  *	None.
    428  *
    429  *-----------------------------------------------------------------------
    430  */
    431 static Boolean
    432 CondDoTarget(int argLen, const char *arg)
    433 {
    434     GNode   *gn;
    435 
    436     gn = Targ_FindNode(arg, TARG_NOCREATE);
    437     return (gn != NULL) && !OP_NOP(gn->type);
    438 }
    439 
    440 /*-
    441  *-----------------------------------------------------------------------
    442  * CondDoCommands --
    443  *	See if the given node exists and is an actual target with commands
    444  *	associated with it.
    445  *
    446  * Results:
    447  *	TRUE if the node exists as a target and has commands associated with
    448  *	it and FALSE if it does not.
    449  *
    450  * Side Effects:
    451  *	None.
    452  *
    453  *-----------------------------------------------------------------------
    454  */
    455 static Boolean
    456 CondDoCommands(int argLen, const char *arg)
    457 {
    458     GNode   *gn;
    459 
    460     gn = Targ_FindNode(arg, TARG_NOCREATE);
    461     return (gn != NULL) && !OP_NOP(gn->type) && !Lst_IsEmpty(gn->commands);
    462 }
    463 
    464 /*-
    466  *-----------------------------------------------------------------------
    467  * CondCvtArg --
    468  *	Convert the given number into a double.
    469  *	We try a base 10 or 16 integer conversion first, if that fails
    470  *	then we try a floating point conversion instead.
    471  *
    472  * Results:
    473  *	Sets 'value' to double value of string.
    474  *	Returns 'true' if the convertion suceeded
    475  *
    476  *-----------------------------------------------------------------------
    477  */
    478 static Boolean
    479 CondCvtArg(char *str, double *value)
    480 {
    481     char *eptr, ech;
    482     unsigned long l_val;
    483     double d_val;
    484 
    485     errno = 0;
    486     l_val = strtoul(str, &eptr, str[1] == 'x' ? 16 : 10);
    487     ech = *eptr;
    488     if (ech == 0 && errno != ERANGE) {
    489 	d_val = str[0] == '-' ? -(double)-l_val : (double)l_val;
    490     } else {
    491 	if (ech != 0 && ech != '.' && ech != 'e' && ech != 'E')
    492 	    return FALSE;
    493 	d_val = strtod(str, &eptr);
    494 	if (*eptr)
    495 	    return FALSE;
    496     }
    497 
    498     *value = d_val;
    499     return TRUE;
    500 }
    501 
    502 /*-
    503  *-----------------------------------------------------------------------
    504  * CondGetString --
    505  *	Get a string from a variable reference or an optionally quoted
    506  *	string.  This is called for the lhs and rhs of string compares.
    507  *
    508  * Results:
    509  *	Sets freeIt if needed,
    510  *	Sets quoted if string was quoted,
    511  *	Returns NULL on error,
    512  *	else returns string - absent any quotes.
    513  *
    514  * Side Effects:
    515  *	Moves condExpr to end of this token.
    516  *
    517  *
    518  *-----------------------------------------------------------------------
    519  */
    520 /* coverity:[+alloc : arg-*2] */
    521 static char *
    522 CondGetString(Boolean doEval, Boolean *quoted, void **freeIt)
    523 {
    524     Buffer buf;
    525     char *cp;
    526     char *str;
    527     int	len;
    528     int qt;
    529     char *start;
    530 
    531     Buf_Init(&buf, 0);
    532     str = NULL;
    533     *freeIt = NULL;
    534     *quoted = qt = *condExpr == '"' ? 1 : 0;
    535     if (qt)
    536 	condExpr++;
    537     for (start = condExpr; *condExpr && str == NULL; condExpr++) {
    538 	switch (*condExpr) {
    539 	case '\\':
    540 	    if (condExpr[1] != '\0') {
    541 		condExpr++;
    542 		Buf_AddByte(&buf, *condExpr);
    543 	    }
    544 	    break;
    545 	case '"':
    546 	    if (qt) {
    547 		condExpr++;		/* we don't want the quotes */
    548 		goto got_str;
    549 	    } else
    550 		Buf_AddByte(&buf, *condExpr); /* likely? */
    551 	    break;
    552 	case ')':
    553 	case '!':
    554 	case '=':
    555 	case '>':
    556 	case '<':
    557 	case ' ':
    558 	case '\t':
    559 	    if (!qt)
    560 		goto got_str;
    561 	    else
    562 		Buf_AddByte(&buf, *condExpr);
    563 	    break;
    564 	case '$':
    565 	    /* if we are in quotes, then an undefined variable is ok */
    566 	    str = Var_Parse(condExpr, VAR_CMD, (qt ? 0 : doEval),
    567 			    &len, freeIt);
    568 	    if (str == var_Error) {
    569 		if (*freeIt) {
    570 		    free(*freeIt);
    571 		    *freeIt = NULL;
    572 		}
    573 		/*
    574 		 * Even if !doEval, we still report syntax errors, which
    575 		 * is what getting var_Error back with !doEval means.
    576 		 */
    577 		str = NULL;
    578 		goto cleanup;
    579 	    }
    580 	    condExpr += len;
    581 	    /*
    582 	     * If the '$' was first char (no quotes), and we are
    583 	     * followed by space, the operator or end of expression,
    584 	     * we are done.
    585 	     */
    586 	    if ((condExpr == start + len) &&
    587 		(*condExpr == '\0' ||
    588 		 isspace((unsigned char) *condExpr) ||
    589 		 strchr("!=><)", *condExpr))) {
    590 		goto cleanup;
    591 	    }
    592 	    /*
    593 	     * Nope, we better copy str to buf
    594 	     */
    595 	    for (cp = str; *cp; cp++) {
    596 		Buf_AddByte(&buf, *cp);
    597 	    }
    598 	    if (*freeIt) {
    599 		free(*freeIt);
    600 		*freeIt = NULL;
    601 	    }
    602 	    str = NULL;			/* not finished yet */
    603 	    condExpr--;			/* don't skip over next char */
    604 	    break;
    605 	default:
    606 	    Buf_AddByte(&buf, *condExpr);
    607 	    break;
    608 	}
    609     }
    610  got_str:
    611     str = Buf_GetAll(&buf, NULL);
    612     *freeIt = str;
    613  cleanup:
    614     Buf_Destroy(&buf, FALSE);
    615     return str;
    616 }
    617 
    618 /*-
    620  *-----------------------------------------------------------------------
    621  * CondToken --
    622  *	Return the next token from the input.
    623  *
    624  * Results:
    625  *	A Token for the next lexical token in the stream.
    626  *
    627  * Side Effects:
    628  *	condPushback will be set back to None if it is used.
    629  *
    630  *-----------------------------------------------------------------------
    631  */
    632 static Token
    633 compare_expression(Boolean doEval)
    634 {
    635     Token	t;
    636     char	*lhs;
    637     char	*rhs;
    638     char	*op;
    639     void	*lhsFree;
    640     void	*rhsFree;
    641     Boolean lhsQuoted;
    642     Boolean rhsQuoted;
    643 
    644     rhs = NULL;
    645     lhsFree = rhsFree = FALSE;
    646     lhsQuoted = rhsQuoted = FALSE;
    647 
    648     /*
    649      * Parse the variable spec and skip over it, saving its
    650      * value in lhs.
    651      */
    652     t = Err;
    653     lhs = CondGetString(doEval, &lhsQuoted, &lhsFree);
    654     if (!lhs) {
    655 	if (lhsFree)
    656 	    free(lhsFree);
    657 	return Err;
    658     }
    659     /*
    660      * Skip whitespace to get to the operator
    661      */
    662     while (isspace((unsigned char) *condExpr))
    663 	condExpr++;
    664 
    665     /*
    666      * Make sure the operator is a valid one. If it isn't a
    667      * known relational operator, pretend we got a
    668      * != 0 comparison.
    669      */
    670     op = condExpr;
    671     switch (*condExpr) {
    672 	case '!':
    673 	case '=':
    674 	case '<':
    675 	case '>':
    676 	    if (condExpr[1] == '=') {
    677 		condExpr += 2;
    678 	    } else {
    679 		condExpr += 1;
    680 	    }
    681 	    break;
    682 	default:
    683 	    op = UNCONST("!=");
    684 	    if (lhsQuoted)
    685 		rhs = UNCONST("");
    686 	    else
    687 		rhs = UNCONST("0");
    688 
    689 	    goto do_compare;
    690     }
    691     while (isspace((unsigned char) *condExpr)) {
    692 	condExpr++;
    693     }
    694     if (*condExpr == '\0') {
    695 	Parse_Error(PARSE_WARNING,
    696 		    "Missing right-hand-side of operator");
    697 	goto error;
    698     }
    699     rhs = CondGetString(doEval, &rhsQuoted, &rhsFree);
    700     if (!rhs) {
    701 	if (lhsFree)
    702 	    free(lhsFree);
    703 	if (rhsFree)
    704 	    free(rhsFree);
    705 	return Err;
    706     }
    707 do_compare:
    708     if (rhsQuoted || lhsQuoted) {
    709 do_string_compare:
    710 	if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
    711 	    Parse_Error(PARSE_WARNING,
    712     "String comparison operator should be either == or !=");
    713 	    goto error;
    714 	}
    715 
    716 	if (DEBUG(COND)) {
    717 	    fprintf(debug_file, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
    718 		   lhs, rhs, op);
    719 	}
    720 	/*
    721 	 * Null-terminate rhs and perform the comparison.
    722 	 * t is set to the result.
    723 	 */
    724 	if (*op == '=') {
    725 	    t = strcmp(lhs, rhs) ? False : True;
    726 	} else {
    727 	    t = strcmp(lhs, rhs) ? True : False;
    728 	}
    729     } else {
    730 	/*
    731 	 * rhs is either a float or an integer. Convert both the
    732 	 * lhs and the rhs to a double and compare the two.
    733 	 */
    734 	double  	left, right;
    735 
    736 	if (!CondCvtArg(lhs, &left) || !CondCvtArg(rhs, &right))
    737 	    goto do_string_compare;
    738 
    739 	if (DEBUG(COND)) {
    740 	    fprintf(debug_file, "left = %f, right = %f, op = %.2s\n", left,
    741 		   right, op);
    742 	}
    743 	switch(op[0]) {
    744 	case '!':
    745 	    if (op[1] != '=') {
    746 		Parse_Error(PARSE_WARNING,
    747 			    "Unknown operator");
    748 		goto error;
    749 	    }
    750 	    t = (left != right ? True : False);
    751 	    break;
    752 	case '=':
    753 	    if (op[1] != '=') {
    754 		Parse_Error(PARSE_WARNING,
    755 			    "Unknown operator");
    756 		goto error;
    757 	    }
    758 	    t = (left == right ? True : False);
    759 	    break;
    760 	case '<':
    761 	    if (op[1] == '=') {
    762 		t = (left <= right ? True : False);
    763 	    } else {
    764 		t = (left < right ? True : False);
    765 	    }
    766 	    break;
    767 	case '>':
    768 	    if (op[1] == '=') {
    769 		t = (left >= right ? True : False);
    770 	    } else {
    771 		t = (left > right ? True : False);
    772 	    }
    773 	    break;
    774 	}
    775     }
    776 error:
    777     if (lhsFree)
    778 	free(lhsFree);
    779     if (rhsFree)
    780 	free(rhsFree);
    781     return t;
    782 }
    783 
    784 static int
    785 get_mpt_arg(char **linePtr, char **argPtr, const char *func)
    786 {
    787     /*
    788      * Use Var_Parse to parse the spec in parens and return
    789      * True if the resulting string is empty.
    790      */
    791     int	    length;
    792     void    *freeIt;
    793     char    *val;
    794     char    *cp = *linePtr;
    795 
    796     /* We do all the work here and return the result as the length */
    797     *argPtr = NULL;
    798 
    799     val = Var_Parse(cp - 1, VAR_CMD, FALSE, &length, &freeIt);
    800     /*
    801      * Advance *linePtr to beyond the closing ). Note that
    802      * we subtract one because 'length' is calculated from 'cp - 1'.
    803      */
    804     *linePtr = cp - 1 + length;
    805 
    806     if (val == var_Error) {
    807 	free(freeIt);
    808 	return -1;
    809     }
    810 
    811     /* A variable is empty when it just contains spaces... 4/15/92, christos */
    812     while (isspace(*(unsigned char *)val))
    813 	val++;
    814 
    815     /*
    816      * For consistency with the other functions we can't generate the
    817      * true/false here.
    818      */
    819     length = *val ? 2 : 1;
    820     if (freeIt)
    821 	free(freeIt);
    822     return length;
    823 }
    824 
    825 static Boolean
    826 CondDoEmpty(int arglen, const char *arg)
    827 {
    828     return arglen == 1;
    829 }
    830 
    831 static Token
    832 compare_function(Boolean doEval)
    833 {
    834     static const struct fn_def {
    835 	const char  *fn_name;
    836 	int         fn_name_len;
    837         int         (*fn_getarg)(char **, char **, const char *);
    838 	Boolean     (*fn_proc)(int, const char *);
    839     } fn_defs[] = {
    840 	{ "defined",   7, CondGetArg, CondDoDefined },
    841 	{ "make",      4, CondGetArg, CondDoMake },
    842 	{ "exists",    6, CondGetArg, CondDoExists },
    843 	{ "empty",     5, get_mpt_arg, CondDoEmpty },
    844 	{ "target",    6, CondGetArg, CondDoTarget },
    845 	{ "commands",  8, CondGetArg, CondDoCommands },
    846 	{ NULL,        0, NULL, NULL },
    847     };
    848     const struct fn_def *fn_def;
    849     Token	t;
    850     char	*arg = NULL;
    851     int	arglen;
    852     char *cp = condExpr;
    853     char *cp1;
    854 
    855     for (fn_def = fn_defs; fn_def->fn_name != NULL; fn_def++) {
    856 	if (!istoken(cp, fn_def->fn_name, fn_def->fn_name_len))
    857 	    continue;
    858 	cp += fn_def->fn_name_len;
    859 	/* There can only be whitespace before the '(' */
    860 	while (isspace(*(unsigned char *)cp))
    861 	    cp++;
    862 	if (*cp != '(')
    863 	    break;
    864 
    865 	arglen = fn_def->fn_getarg(&cp, &arg, fn_def->fn_name);
    866 	if (arglen <= 0) {
    867 	    condExpr = cp;
    868 	    return arglen < 0 ? Err : False;
    869 	}
    870 	/* Evaluate the argument using the required function. */
    871 	t = !doEval || fn_def->fn_proc(arglen, arg) ? True : False;
    872 	if (arg)
    873 	    free(arg);
    874 	condExpr = cp;
    875 	return t;
    876     }
    877 
    878     /* Push anything numeric through the compare expression */
    879     cp = condExpr;
    880     if (isdigit((unsigned char)cp[0]) || strchr("+-", cp[0]))
    881 	return compare_expression(doEval);
    882 
    883     /*
    884      * Most likely we have a naked token to apply the default function to.
    885      * However ".if a == b" gets here when the "a" is unquoted and doesn't
    886      * start with a '$'. This surprises people - especially given the way
    887      * that for loops get expanded.
    888      * If what follows the function argument is a '=' or '!' then the syntax
    889      * would be invalid if we did "defined(a)" - so instead treat as an
    890      * expression.
    891      */
    892     arglen = CondGetArg(&cp, &arg, NULL);
    893     for (cp1 = cp; isspace(*(unsigned char *)cp1); cp1++)
    894 	continue;
    895     if (*cp1 == '=' || *cp1 == '!')
    896 	return compare_expression(doEval);
    897     condExpr = cp;
    898 
    899     /*
    900      * Evaluate the argument using the default function. If invert
    901      * is TRUE, we invert the sense of the result.
    902      */
    903     t = !doEval || if_info->defProc(arglen, arg) != if_info->doNot ? True : False;
    904     if (arg)
    905 	free(arg);
    906     return t;
    907 }
    908 
    909 static Token
    910 CondToken(Boolean doEval)
    911 {
    912     Token t;
    913 
    914     t = condPushBack;
    915     if (t != None) {
    916 	condPushBack = None;
    917 	return t;
    918     }
    919 
    920     while (*condExpr == ' ' || *condExpr == '\t') {
    921 	condExpr++;
    922     }
    923 
    924     switch (*condExpr) {
    925 
    926     case '(':
    927 	condExpr++;
    928 	return LParen;
    929 
    930     case ')':
    931 	condExpr++;
    932 	return RParen;
    933 
    934     case '|':
    935 	if (condExpr[1] == '|') {
    936 	    condExpr++;
    937 	}
    938 	condExpr++;
    939 	return Or;
    940 
    941     case '&':
    942 	if (condExpr[1] == '&') {
    943 	    condExpr++;
    944 	}
    945 	condExpr++;
    946 	return And;
    947 
    948     case '!':
    949 	condExpr++;
    950 	return Not;
    951 
    952     case '#':
    953     case '\n':
    954     case '\0':
    955 	return EndOfFile;
    956 
    957     case '"':
    958     case '$':
    959 	return compare_expression(doEval);
    960 
    961     default:
    962 	return compare_function(doEval);
    963     }
    964 }
    965 
    966 /*-
    967  *-----------------------------------------------------------------------
    968  * CondT --
    969  *	Parse a single term in the expression. This consists of a terminal
    970  *	symbol or Not and a terminal symbol (not including the binary
    971  *	operators):
    972  *	    T -> defined(variable) | make(target) | exists(file) | symbol
    973  *	    T -> ! T | ( E )
    974  *
    975  * Results:
    976  *	True, False or Err.
    977  *
    978  * Side Effects:
    979  *	Tokens are consumed.
    980  *
    981  *-----------------------------------------------------------------------
    982  */
    983 static Token
    984 CondT(Boolean doEval)
    985 {
    986     Token   t;
    987 
    988     t = CondToken(doEval);
    989 
    990     if (t == EndOfFile) {
    991 	/*
    992 	 * If we reached the end of the expression, the expression
    993 	 * is malformed...
    994 	 */
    995 	t = Err;
    996     } else if (t == LParen) {
    997 	/*
    998 	 * T -> ( E )
    999 	 */
   1000 	t = CondE(doEval);
   1001 	if (t != Err) {
   1002 	    if (CondToken(doEval) != RParen) {
   1003 		t = Err;
   1004 	    }
   1005 	}
   1006     } else if (t == Not) {
   1007 	t = CondT(doEval);
   1008 	if (t == True) {
   1009 	    t = False;
   1010 	} else if (t == False) {
   1011 	    t = True;
   1012 	}
   1013     }
   1014     return (t);
   1015 }
   1016 
   1017 /*-
   1019  *-----------------------------------------------------------------------
   1020  * CondF --
   1021  *	Parse a conjunctive factor (nice name, wot?)
   1022  *	    F -> T && F | T
   1023  *
   1024  * Results:
   1025  *	True, False or Err
   1026  *
   1027  * Side Effects:
   1028  *	Tokens are consumed.
   1029  *
   1030  *-----------------------------------------------------------------------
   1031  */
   1032 static Token
   1033 CondF(Boolean doEval)
   1034 {
   1035     Token   l, o;
   1036 
   1037     l = CondT(doEval);
   1038     if (l != Err) {
   1039 	o = CondToken(doEval);
   1040 
   1041 	if (o == And) {
   1042 	    /*
   1043 	     * F -> T && F
   1044 	     *
   1045 	     * If T is False, the whole thing will be False, but we have to
   1046 	     * parse the r.h.s. anyway (to throw it away).
   1047 	     * If T is True, the result is the r.h.s., be it an Err or no.
   1048 	     */
   1049 	    if (l == True) {
   1050 		l = CondF(doEval);
   1051 	    } else {
   1052 		(void)CondF(FALSE);
   1053 	    }
   1054 	} else {
   1055 	    /*
   1056 	     * F -> T
   1057 	     */
   1058 	    CondPushBack(o);
   1059 	}
   1060     }
   1061     return (l);
   1062 }
   1063 
   1064 /*-
   1066  *-----------------------------------------------------------------------
   1067  * CondE --
   1068  *	Main expression production.
   1069  *	    E -> F || E | F
   1070  *
   1071  * Results:
   1072  *	True, False or Err.
   1073  *
   1074  * Side Effects:
   1075  *	Tokens are, of course, consumed.
   1076  *
   1077  *-----------------------------------------------------------------------
   1078  */
   1079 static Token
   1080 CondE(Boolean doEval)
   1081 {
   1082     Token   l, o;
   1083 
   1084     l = CondF(doEval);
   1085     if (l != Err) {
   1086 	o = CondToken(doEval);
   1087 
   1088 	if (o == Or) {
   1089 	    /*
   1090 	     * E -> F || E
   1091 	     *
   1092 	     * A similar thing occurs for ||, except that here we make sure
   1093 	     * the l.h.s. is False before we bother to evaluate the r.h.s.
   1094 	     * Once again, if l is False, the result is the r.h.s. and once
   1095 	     * again if l is True, we parse the r.h.s. to throw it away.
   1096 	     */
   1097 	    if (l == False) {
   1098 		l = CondE(doEval);
   1099 	    } else {
   1100 		(void)CondE(FALSE);
   1101 	    }
   1102 	} else {
   1103 	    /*
   1104 	     * E -> F
   1105 	     */
   1106 	    CondPushBack(o);
   1107 	}
   1108     }
   1109     return (l);
   1110 }
   1111 
   1112 /*-
   1113  *-----------------------------------------------------------------------
   1114  * Cond_EvalExpression --
   1115  *	Evaluate an expression in the passed line. The expression
   1116  *	consists of &&, ||, !, make(target), defined(variable)
   1117  *	and parenthetical groupings thereof.
   1118  *
   1119  * Results:
   1120  *	COND_PARSE	if the condition was valid grammatically
   1121  *	COND_INVALID  	if not a valid conditional.
   1122  *
   1123  *	(*value) is set to the boolean value of the condition
   1124  *
   1125  * Side Effects:
   1126  *	None.
   1127  *
   1128  *-----------------------------------------------------------------------
   1129  */
   1130 int
   1131 Cond_EvalExpression(const struct If *info, char *line, Boolean *value, int eprint)
   1132 {
   1133     static const struct If *dflt_info;
   1134     const struct If *sv_if_info = if_info;
   1135     char *sv_condExpr = condExpr;
   1136     Token sv_condPushBack = condPushBack;
   1137     int rval;
   1138 
   1139     while (*line == ' ' || *line == '\t')
   1140 	line++;
   1141 
   1142     if (info == NULL && (info = dflt_info) == NULL) {
   1143 	/* Scan for the entry for .if - it can't be first */
   1144 	for (info = ifs; ; info++)
   1145 	    if (ifs->form[0] == 0)
   1146 		break;
   1147 	dflt_info = info;
   1148     }
   1149 
   1150     if_info = info != NULL ? info : ifs + 4;
   1151     condExpr = line;
   1152     condPushBack = None;
   1153 
   1154     rval = do_Cond_EvalExpression(value);
   1155 
   1156     if (rval == COND_INVALID && eprint)
   1157 	Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", line);
   1158 
   1159     if_info = sv_if_info;
   1160     condExpr = sv_condExpr;
   1161     condPushBack = sv_condPushBack;
   1162 
   1163     return rval;
   1164 }
   1165 
   1166 static int
   1167 do_Cond_EvalExpression(Boolean *value)
   1168 {
   1169 
   1170     switch (CondE(TRUE)) {
   1171     case True:
   1172 	if (CondToken(TRUE) == EndOfFile) {
   1173 	    *value = TRUE;
   1174 	    return COND_PARSE;
   1175 	}
   1176 	break;
   1177     case False:
   1178 	if (CondToken(TRUE) == EndOfFile) {
   1179 	    *value = FALSE;
   1180 	    return COND_PARSE;
   1181 	}
   1182 	break;
   1183     default:
   1184     case Err:
   1185 	break;
   1186     }
   1187 
   1188     return COND_INVALID;
   1189 }
   1190 
   1191 
   1192 /*-
   1194  *-----------------------------------------------------------------------
   1195  * Cond_Eval --
   1196  *	Evaluate the conditional in the passed line. The line
   1197  *	looks like this:
   1198  *	    .<cond-type> <expr>
   1199  *	where <cond-type> is any of if, ifmake, ifnmake, ifdef,
   1200  *	ifndef, elif, elifmake, elifnmake, elifdef, elifndef
   1201  *	and <expr> consists of &&, ||, !, make(target), defined(variable)
   1202  *	and parenthetical groupings thereof.
   1203  *
   1204  * Input:
   1205  *	line		Line to parse
   1206  *
   1207  * Results:
   1208  *	COND_PARSE	if should parse lines after the conditional
   1209  *	COND_SKIP	if should skip lines after the conditional
   1210  *	COND_INVALID  	if not a valid conditional.
   1211  *
   1212  * Side Effects:
   1213  *	None.
   1214  *
   1215  * Note that the states IF_ACTIVE and ELSE_ACTIVE are only different in order
   1216  * to detect splurious .else lines (as are SKIP_TO_ELSE and SKIP_TO_ENDIF)
   1217  * otherwise .else could be treated as '.elif 1'.
   1218  *
   1219  *-----------------------------------------------------------------------
   1220  */
   1221 int
   1222 Cond_Eval(char *line)
   1223 {
   1224     #define	    MAXIF	64	/* maximum depth of .if'ing */
   1225     enum if_states {
   1226 	IF_ACTIVE,		/* .if or .elif part active */
   1227 	ELSE_ACTIVE,		/* .else part active */
   1228 	SEARCH_FOR_ELIF,	/* searching for .elif/else to execute */
   1229 	SKIP_TO_ELSE,           /* has been true, but not seen '.else' */
   1230 	SKIP_TO_ENDIF		/* nothing else to execute */
   1231     };
   1232     static enum if_states cond_state[MAXIF + 1] = { IF_ACTIVE };
   1233 
   1234     const struct If *ifp;
   1235     Boolean 	    isElif;
   1236     Boolean 	    value;
   1237     int	    	    level;  	/* Level at which to report errors. */
   1238     enum if_states  state;
   1239 
   1240     level = PARSE_FATAL;
   1241 
   1242     /* skip leading character (the '.') and any whitespace */
   1243     for (line++; *line == ' ' || *line == '\t'; line++)
   1244 	continue;
   1245 
   1246     /* Find what type of if we're dealing with.  */
   1247     if (line[0] == 'e') {
   1248 	if (line[1] != 'l') {
   1249 	    if (!istoken(line + 1, "ndif", 4))
   1250 		return COND_INVALID;
   1251 	    /* End of conditional section */
   1252 	    if (cond_depth == cond_min_depth) {
   1253 		Parse_Error(level, "if-less endif");
   1254 		return COND_PARSE;
   1255 	    }
   1256 	    /* Return state for previous conditional */
   1257 	    cond_depth--;
   1258 	    if (cond_depth > MAXIF)
   1259 		return COND_SKIP;
   1260 	    return cond_state[cond_depth] <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
   1261 	}
   1262 
   1263 	/* Quite likely this is 'else' or 'elif' */
   1264 	line += 2;
   1265 	if (istoken(line, "se", 2)) {
   1266 	    /* It is else... */
   1267 	    if (cond_depth == cond_min_depth) {
   1268 		Parse_Error(level, "if-less else");
   1269 		return COND_PARSE;
   1270 	    }
   1271 
   1272 	    if (cond_depth > MAXIF)
   1273 		return COND_SKIP;
   1274 	    state = cond_state[cond_depth];
   1275 	    switch (state) {
   1276 	    case SEARCH_FOR_ELIF:
   1277 		state = ELSE_ACTIVE;
   1278 		break;
   1279 	    case ELSE_ACTIVE:
   1280 	    case SKIP_TO_ENDIF:
   1281 		Parse_Error(PARSE_WARNING, "extra else");
   1282 		/* FALLTHROUGH */
   1283 	    default:
   1284 	    case IF_ACTIVE:
   1285 	    case SKIP_TO_ELSE:
   1286 		state = SKIP_TO_ENDIF;
   1287 		break;
   1288 	    }
   1289 	    cond_state[cond_depth] = state;
   1290 	    return state <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
   1291 	}
   1292 	/* Assume for now it is an elif */
   1293 	isElif = TRUE;
   1294     } else
   1295 	isElif = FALSE;
   1296 
   1297     if (line[0] != 'i' || line[1] != 'f')
   1298 	/* Not an ifxxx or elifxxx line */
   1299 	return COND_INVALID;
   1300 
   1301     /*
   1302      * Figure out what sort of conditional it is -- what its default
   1303      * function is, etc. -- by looking in the table of valid "ifs"
   1304      */
   1305     line += 2;
   1306     for (ifp = ifs; ; ifp++) {
   1307 	if (ifp->form == NULL)
   1308 	    return COND_INVALID;
   1309 	if (istoken(ifp->form, line, ifp->formlen)) {
   1310 	    line += ifp->formlen;
   1311 	    break;
   1312 	}
   1313     }
   1314 
   1315     /* Now we know what sort of 'if' it is... */
   1316 
   1317     if (isElif) {
   1318 	if (cond_depth == cond_min_depth) {
   1319 	    Parse_Error(level, "if-less elif");
   1320 	    return COND_PARSE;
   1321 	}
   1322 	if (cond_depth > MAXIF)
   1323 	    /* Error reported when we saw the .if ... */
   1324 	    return COND_SKIP;
   1325 	state = cond_state[cond_depth];
   1326 	if (state == SKIP_TO_ENDIF || state == ELSE_ACTIVE) {
   1327 	    Parse_Error(PARSE_WARNING, "extra elif");
   1328 	    cond_state[cond_depth] = SKIP_TO_ENDIF;
   1329 	    return COND_SKIP;
   1330 	}
   1331 	if (state != SEARCH_FOR_ELIF) {
   1332 	    /* Either just finished the 'true' block, or already SKIP_TO_ELSE */
   1333 	    cond_state[cond_depth] = SKIP_TO_ELSE;
   1334 	    return COND_SKIP;
   1335 	}
   1336     } else {
   1337 	/* Normal .if */
   1338 	if (cond_depth >= MAXIF) {
   1339 	    cond_depth++;
   1340 	    Parse_Error(PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
   1341 	    return COND_SKIP;
   1342 	}
   1343 	state = cond_state[cond_depth];
   1344 	cond_depth++;
   1345 	if (state > ELSE_ACTIVE) {
   1346 	    /* If we aren't parsing the data, treat as always false */
   1347 	    cond_state[cond_depth] = SKIP_TO_ELSE;
   1348 	    return COND_SKIP;
   1349 	}
   1350     }
   1351 
   1352     /* And evaluate the conditional expresssion */
   1353     if (Cond_EvalExpression(ifp, line, &value, 1) == COND_INVALID) {
   1354 	/* Syntax error in conditional, error message already output. */
   1355 	/* Skip everything to matching .endif */
   1356 	cond_state[cond_depth] = SKIP_TO_ELSE;
   1357 	return COND_SKIP;
   1358     }
   1359 
   1360     if (!value) {
   1361 	cond_state[cond_depth] = SEARCH_FOR_ELIF;
   1362 	return COND_SKIP;
   1363     }
   1364     cond_state[cond_depth] = IF_ACTIVE;
   1365     return COND_PARSE;
   1366 }
   1367 
   1368 
   1369 
   1370 /*-
   1372  *-----------------------------------------------------------------------
   1373  * Cond_End --
   1374  *	Make sure everything's clean at the end of a makefile.
   1375  *
   1376  * Results:
   1377  *	None.
   1378  *
   1379  * Side Effects:
   1380  *	Parse_Error will be called if open conditionals are around.
   1381  *
   1382  *-----------------------------------------------------------------------
   1383  */
   1384 void
   1385 Cond_restore_depth(unsigned int saved_depth)
   1386 {
   1387     int open_conds = cond_depth - cond_min_depth;
   1388 
   1389     if (open_conds != 0 || saved_depth > cond_depth) {
   1390 	Parse_Error(PARSE_FATAL, "%d open conditional%s", open_conds,
   1391 		    open_conds == 1 ? "" : "s");
   1392 	cond_depth = cond_min_depth;
   1393     }
   1394 
   1395     cond_min_depth = saved_depth;
   1396 }
   1397 
   1398 unsigned int
   1399 Cond_save_depth(void)
   1400 {
   1401     int depth = cond_min_depth;
   1402 
   1403     cond_min_depth = cond_depth;
   1404     return depth;
   1405 }
   1406