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