Home | History | Annotate | Line # | Download | only in make
cond.c revision 1.19
      1 /*	$NetBSD: cond.c,v 1.19 2004/01/06 01:18:52 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.19 2004/01/06 01:18:52 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.19 2004/01/06 01:18:52 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 char * 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 NULL if string was fully consumed,
    502  *	else returns remaining input.
    503  *
    504  * Side Effects:
    505  *	Can change 'value' even if string is not a valid number.
    506  *
    507  *
    508  *-----------------------------------------------------------------------
    509  */
    510 static char *
    511 CondCvtArg(char *str, double *value)
    512 {
    513     if ((*str == '0') && (str[1] == 'x')) {
    514 	long i;
    515 
    516 	for (str += 2, i = 0; *str; str++) {
    517 	    int x;
    518 	    if (isdigit((unsigned char) *str))
    519 		x  = *str - '0';
    520 	    else if (isxdigit((unsigned char) *str))
    521 		x = 10 + *str - isupper((unsigned char) *str) ? 'A' : 'a';
    522 	    else
    523 		break;
    524 	    i = (i << 4) + x;
    525 	}
    526 	*value = (double) i;
    527 	return *str ? str : NULL;
    528     } else {
    529 	char *eptr;
    530 	*value = strtod(str, &eptr);
    531 	return *eptr ? eptr : NULL;
    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 			char *cp;
    780 
    781 			if ((cp = CondCvtArg(rhs, &right)) &&
    782 			    cp == rhs)
    783 			    goto do_string_compare;
    784 			if (rhs == condExpr) {
    785 			    /*
    786 			     * Skip over the right-hand side
    787 			     */
    788 			    if (cp)
    789 				condExpr = cp;
    790 			    else
    791 				condExpr = strchr(rhs, '\0');
    792 			}
    793 		    }
    794 
    795 		    if (DEBUG(COND)) {
    796 			printf("left = %f, right = %f, op = %.2s\n", left,
    797 			       right, op);
    798 		    }
    799 		    switch(op[0]) {
    800 		    case '!':
    801 			if (op[1] != '=') {
    802 			    Parse_Error(PARSE_WARNING,
    803 					"Unknown operator");
    804 			    goto error;
    805 			}
    806 			t = (left != right ? True : False);
    807 			break;
    808 		    case '=':
    809 			if (op[1] != '=') {
    810 			    Parse_Error(PARSE_WARNING,
    811 					"Unknown operator");
    812 			    goto error;
    813 			}
    814 			t = (left == right ? True : False);
    815 			break;
    816 		    case '<':
    817 			if (op[1] == '=') {
    818 			    t = (left <= right ? True : False);
    819 			} else {
    820 			    t = (left < right ? True : False);
    821 			}
    822 			break;
    823 		    case '>':
    824 			if (op[1] == '=') {
    825 			    t = (left >= right ? True : False);
    826 			} else {
    827 			    t = (left > right ? True : False);
    828 			}
    829 			break;
    830 		    }
    831 		}
    832 error:
    833 		if (doFree)
    834 		    free(lhs);
    835 		break;
    836 	    }
    837 	    default: {
    838 		Boolean (*evalProc)(int, char *);
    839 		Boolean invert = FALSE;
    840 		char	*arg;
    841 		int	arglen;
    842 
    843 		if (strncmp (condExpr, "defined", 7) == 0) {
    844 		    /*
    845 		     * Use CondDoDefined to evaluate the argument and
    846 		     * CondGetArg to extract the argument from the 'function
    847 		     * call'.
    848 		     */
    849 		    evalProc = CondDoDefined;
    850 		    condExpr += 7;
    851 		    arglen = CondGetArg (&condExpr, &arg, "defined", TRUE);
    852 		    if (arglen == 0) {
    853 			condExpr -= 7;
    854 			goto use_default;
    855 		    }
    856 		} else if (strncmp (condExpr, "make", 4) == 0) {
    857 		    /*
    858 		     * Use CondDoMake to evaluate the argument and
    859 		     * CondGetArg to extract the argument from the 'function
    860 		     * call'.
    861 		     */
    862 		    evalProc = CondDoMake;
    863 		    condExpr += 4;
    864 		    arglen = CondGetArg (&condExpr, &arg, "make", TRUE);
    865 		    if (arglen == 0) {
    866 			condExpr -= 4;
    867 			goto use_default;
    868 		    }
    869 		} else if (strncmp (condExpr, "exists", 6) == 0) {
    870 		    /*
    871 		     * Use CondDoExists to evaluate the argument and
    872 		     * CondGetArg to extract the argument from the
    873 		     * 'function call'.
    874 		     */
    875 		    evalProc = CondDoExists;
    876 		    condExpr += 6;
    877 		    arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
    878 		    if (arglen == 0) {
    879 			condExpr -= 6;
    880 			goto use_default;
    881 		    }
    882 		} else if (strncmp(condExpr, "empty", 5) == 0) {
    883 		    /*
    884 		     * Use Var_Parse to parse the spec in parens and return
    885 		     * True if the resulting string is empty.
    886 		     */
    887 		    int	    length;
    888 		    Boolean doFree;
    889 		    char    *val;
    890 
    891 		    condExpr += 5;
    892 
    893 		    for (arglen = 0;
    894 			 condExpr[arglen] != '(' && condExpr[arglen] != '\0';
    895 			 arglen += 1)
    896 			continue;
    897 
    898 		    if (condExpr[arglen] != '\0') {
    899 			val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
    900 					FALSE, &length, &doFree);
    901 			if (val == var_Error) {
    902 			    t = Err;
    903 			} else {
    904 			    /*
    905 			     * A variable is empty when it just contains
    906 			     * spaces... 4/15/92, christos
    907 			     */
    908 			    char *p;
    909 			    for (p = val; *p && isspace((unsigned char)*p); p++)
    910 				continue;
    911 			    t = (*p == '\0') ? True : False;
    912 			}
    913 			if (doFree) {
    914 			    free(val);
    915 			}
    916 			/*
    917 			 * Advance condExpr to beyond the closing ). Note that
    918 			 * we subtract one from arglen + length b/c length
    919 			 * is calculated from condExpr[arglen - 1].
    920 			 */
    921 			condExpr += arglen + length - 1;
    922 		    } else {
    923 			condExpr -= 5;
    924 			goto use_default;
    925 		    }
    926 		    break;
    927 		} else if (strncmp (condExpr, "target", 6) == 0) {
    928 		    /*
    929 		     * Use CondDoTarget to evaluate the argument and
    930 		     * CondGetArg to extract the argument from the
    931 		     * 'function call'.
    932 		     */
    933 		    evalProc = CondDoTarget;
    934 		    condExpr += 6;
    935 		    arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
    936 		    if (arglen == 0) {
    937 			condExpr -= 6;
    938 			goto use_default;
    939 		    }
    940 		} else if (strncmp (condExpr, "commands", 8) == 0) {
    941 		    /*
    942 		     * Use CondDoCommands to evaluate the argument and
    943 		     * CondGetArg to extract the argument from the
    944 		     * 'function call'.
    945 		     */
    946 		    evalProc = CondDoCommands;
    947 		    condExpr += 8;
    948 		    arglen = CondGetArg(&condExpr, &arg, "commands", TRUE);
    949 		    if (arglen == 0) {
    950 			condExpr -= 8;
    951 			goto use_default;
    952 		    }
    953 		} else {
    954 		    /*
    955 		     * The symbol is itself the argument to the default
    956 		     * function. We advance condExpr to the end of the symbol
    957 		     * by hand (the next whitespace, closing paren or
    958 		     * binary operator) and set to invert the evaluation
    959 		     * function if condInvert is TRUE.
    960 		     */
    961 		use_default:
    962 		    invert = condInvert;
    963 		    evalProc = condDefProc;
    964 		    arglen = CondGetArg(&condExpr, &arg, "", FALSE);
    965 		}
    966 
    967 		/*
    968 		 * Evaluate the argument using the set function. If invert
    969 		 * is TRUE, we invert the sense of the function.
    970 		 */
    971 		t = (!doEval || (* evalProc) (arglen, arg) ?
    972 		     (invert ? False : True) :
    973 		     (invert ? True : False));
    974 		free(arg);
    975 		break;
    976 	    }
    977 	}
    978     } else {
    979 	t = condPushBack;
    980 	condPushBack = None;
    981     }
    982     return (t);
    983 }
    984 
    985 /*-
    987  *-----------------------------------------------------------------------
    988  * CondT --
    989  *	Parse a single term in the expression. This consists of a terminal
    990  *	symbol or Not and a terminal symbol (not including the binary
    991  *	operators):
    992  *	    T -> defined(variable) | make(target) | exists(file) | symbol
    993  *	    T -> ! T | ( E )
    994  *
    995  * Results:
    996  *	True, False or Err.
    997  *
    998  * Side Effects:
    999  *	Tokens are consumed.
   1000  *
   1001  *-----------------------------------------------------------------------
   1002  */
   1003 static Token
   1004 CondT(Boolean doEval)
   1005 {
   1006     Token   t;
   1007 
   1008     t = CondToken(doEval);
   1009 
   1010     if (t == EndOfFile) {
   1011 	/*
   1012 	 * If we reached the end of the expression, the expression
   1013 	 * is malformed...
   1014 	 */
   1015 	t = Err;
   1016     } else if (t == LParen) {
   1017 	/*
   1018 	 * T -> ( E )
   1019 	 */
   1020 	t = CondE(doEval);
   1021 	if (t != Err) {
   1022 	    if (CondToken(doEval) != RParen) {
   1023 		t = Err;
   1024 	    }
   1025 	}
   1026     } else if (t == Not) {
   1027 	t = CondT(doEval);
   1028 	if (t == True) {
   1029 	    t = False;
   1030 	} else if (t == False) {
   1031 	    t = True;
   1032 	}
   1033     }
   1034     return (t);
   1035 }
   1036 
   1037 /*-
   1039  *-----------------------------------------------------------------------
   1040  * CondF --
   1041  *	Parse a conjunctive factor (nice name, wot?)
   1042  *	    F -> T && F | T
   1043  *
   1044  * Results:
   1045  *	True, False or Err
   1046  *
   1047  * Side Effects:
   1048  *	Tokens are consumed.
   1049  *
   1050  *-----------------------------------------------------------------------
   1051  */
   1052 static Token
   1053 CondF(Boolean doEval)
   1054 {
   1055     Token   l, o;
   1056 
   1057     l = CondT(doEval);
   1058     if (l != Err) {
   1059 	o = CondToken(doEval);
   1060 
   1061 	if (o == And) {
   1062 	    /*
   1063 	     * F -> T && F
   1064 	     *
   1065 	     * If T is False, the whole thing will be False, but we have to
   1066 	     * parse the r.h.s. anyway (to throw it away).
   1067 	     * If T is True, the result is the r.h.s., be it an Err or no.
   1068 	     */
   1069 	    if (l == True) {
   1070 		l = CondF(doEval);
   1071 	    } else {
   1072 		(void) CondF(FALSE);
   1073 	    }
   1074 	} else {
   1075 	    /*
   1076 	     * F -> T
   1077 	     */
   1078 	    CondPushBack (o);
   1079 	}
   1080     }
   1081     return (l);
   1082 }
   1083 
   1084 /*-
   1086  *-----------------------------------------------------------------------
   1087  * CondE --
   1088  *	Main expression production.
   1089  *	    E -> F || E | F
   1090  *
   1091  * Results:
   1092  *	True, False or Err.
   1093  *
   1094  * Side Effects:
   1095  *	Tokens are, of course, consumed.
   1096  *
   1097  *-----------------------------------------------------------------------
   1098  */
   1099 static Token
   1100 CondE(Boolean doEval)
   1101 {
   1102     Token   l, o;
   1103 
   1104     l = CondF(doEval);
   1105     if (l != Err) {
   1106 	o = CondToken(doEval);
   1107 
   1108 	if (o == Or) {
   1109 	    /*
   1110 	     * E -> F || E
   1111 	     *
   1112 	     * A similar thing occurs for ||, except that here we make sure
   1113 	     * the l.h.s. is False before we bother to evaluate the r.h.s.
   1114 	     * Once again, if l is False, the result is the r.h.s. and once
   1115 	     * again if l is True, we parse the r.h.s. to throw it away.
   1116 	     */
   1117 	    if (l == False) {
   1118 		l = CondE(doEval);
   1119 	    } else {
   1120 		(void) CondE(FALSE);
   1121 	    }
   1122 	} else {
   1123 	    /*
   1124 	     * E -> F
   1125 	     */
   1126 	    CondPushBack (o);
   1127 	}
   1128     }
   1129     return (l);
   1130 }
   1131 
   1132 /*-
   1133  *-----------------------------------------------------------------------
   1134  * Cond_EvalExpression --
   1135  *	Evaluate an expression in the passed line. The expression
   1136  *	consists of &&, ||, !, make(target), defined(variable)
   1137  *	and parenthetical groupings thereof.
   1138  *
   1139  * Results:
   1140  *	COND_PARSE	if the condition was valid grammatically
   1141  *	COND_INVALID  	if not a valid conditional.
   1142  *
   1143  *	(*value) is set to the boolean value of the condition
   1144  *
   1145  * Side Effects:
   1146  *	None.
   1147  *
   1148  *-----------------------------------------------------------------------
   1149  */
   1150 int
   1151 Cond_EvalExpression(int dosetup, char *line, Boolean *value, int eprint)
   1152 {
   1153     if (dosetup) {
   1154 	condDefProc = CondDoDefined;
   1155 	condInvert = 0;
   1156     }
   1157 
   1158     while (*line == ' ' || *line == '\t')
   1159 	line++;
   1160 
   1161     condExpr = line;
   1162     condPushBack = None;
   1163 
   1164     switch (CondE(TRUE)) {
   1165     case True:
   1166 	if (CondToken(TRUE) == EndOfFile) {
   1167 	    *value = TRUE;
   1168 	    break;
   1169 	}
   1170 	goto err;
   1171 	/*FALLTHRU*/
   1172     case False:
   1173 	if (CondToken(TRUE) == EndOfFile) {
   1174 	    *value = FALSE;
   1175 	    break;
   1176 	}
   1177 	/*FALLTHRU*/
   1178     case Err:
   1179 err:
   1180 	if (eprint)
   1181 	    Parse_Error (PARSE_FATAL, "Malformed conditional (%s)",
   1182 			 line);
   1183 	return (COND_INVALID);
   1184     default:
   1185 	break;
   1186     }
   1187 
   1188     return COND_PARSE;
   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  *-----------------------------------------------------------------------
   1216  */
   1217 int
   1218 Cond_Eval(char *line)
   1219 {
   1220     struct If	    *ifp;
   1221     Boolean 	    isElse;
   1222     Boolean 	    value = FALSE;
   1223     int	    	    level;  	/* Level at which to report errors. */
   1224 
   1225     level = PARSE_FATAL;
   1226 
   1227     for (line++; *line == ' ' || *line == '\t'; line++) {
   1228 	continue;
   1229     }
   1230 
   1231     /*
   1232      * Find what type of if we're dealing with. The result is left
   1233      * in ifp and isElse is set TRUE if it's an elif line.
   1234      */
   1235     if (line[0] == 'e' && line[1] == 'l') {
   1236 	line += 2;
   1237 	isElse = TRUE;
   1238     } else if (strncmp (line, "endif", 5) == 0) {
   1239 	/*
   1240 	 * End of a conditional section. If skipIfLevel is non-zero, that
   1241 	 * conditional was skipped, so lines following it should also be
   1242 	 * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
   1243 	 * was read so succeeding lines should be parsed (think about it...)
   1244 	 * so we return COND_PARSE, unless this endif isn't paired with
   1245 	 * a decent if.
   1246 	 */
   1247 	if (skipIfLevel != 0) {
   1248 	    skipIfLevel -= 1;
   1249 	    return (COND_SKIP);
   1250 	} else {
   1251 	    if (condTop == MAXIF) {
   1252 		Parse_Error (level, "if-less endif");
   1253 		return (COND_INVALID);
   1254 	    } else {
   1255 		skipLine = FALSE;
   1256 		condTop += 1;
   1257 		return (COND_PARSE);
   1258 	    }
   1259 	}
   1260     } else {
   1261 	isElse = FALSE;
   1262     }
   1263 
   1264     /*
   1265      * Figure out what sort of conditional it is -- what its default
   1266      * function is, etc. -- by looking in the table of valid "ifs"
   1267      */
   1268     for (ifp = ifs; ifp->form != (char *)0; ifp++) {
   1269 	if (strncmp (ifp->form, line, ifp->formlen) == 0) {
   1270 	    break;
   1271 	}
   1272     }
   1273 
   1274     if (ifp->form == (char *) 0) {
   1275 	/*
   1276 	 * Nothing fit. If the first word on the line is actually
   1277 	 * "else", it's a valid conditional whose value is the inverse
   1278 	 * of the previous if we parsed.
   1279 	 */
   1280 	if (isElse && (line[0] == 's') && (line[1] == 'e')) {
   1281 	    if (condTop == MAXIF) {
   1282 		Parse_Error (level, "if-less else");
   1283 		return (COND_INVALID);
   1284 	    } else if (skipIfLevel == 0) {
   1285 		value = !condStack[condTop];
   1286 	    } else {
   1287 		return (COND_SKIP);
   1288 	    }
   1289 	} else {
   1290 	    /*
   1291 	     * Not a valid conditional type. No error...
   1292 	     */
   1293 	    return (COND_INVALID);
   1294 	}
   1295     } else {
   1296 	if (isElse) {
   1297 	    if (condTop == MAXIF) {
   1298 		Parse_Error (level, "if-less elif");
   1299 		return (COND_INVALID);
   1300 	    } else if (skipIfLevel != 0) {
   1301 		/*
   1302 		 * If skipping this conditional, just ignore the whole thing.
   1303 		 * If we don't, the user might be employing a variable that's
   1304 		 * undefined, for which there's an enclosing ifdef that
   1305 		 * we're skipping...
   1306 		 */
   1307 		return(COND_SKIP);
   1308 	    }
   1309 	} else if (skipLine) {
   1310 	    /*
   1311 	     * Don't even try to evaluate a conditional that's not an else if
   1312 	     * we're skipping things...
   1313 	     */
   1314 	    skipIfLevel += 1;
   1315 	    return(COND_SKIP);
   1316 	}
   1317 
   1318 	/*
   1319 	 * Initialize file-global variables for parsing
   1320 	 */
   1321 	condDefProc = ifp->defProc;
   1322 	condInvert = ifp->doNot;
   1323 
   1324 	line += ifp->formlen;
   1325 	if (Cond_EvalExpression(0, line, &value, 1) == COND_INVALID)
   1326 		return COND_INVALID;
   1327     }
   1328     if (!isElse) {
   1329 	condTop -= 1;
   1330     } else if ((skipIfLevel != 0) || condStack[condTop]) {
   1331 	/*
   1332 	 * If this is an else-type conditional, it should only take effect
   1333 	 * if its corresponding if was evaluated and FALSE. If its if was
   1334 	 * TRUE or skipped, we return COND_SKIP (and start skipping in case
   1335 	 * we weren't already), leaving the stack unmolested so later elif's
   1336 	 * don't screw up...
   1337 	 */
   1338 	skipLine = TRUE;
   1339 	return (COND_SKIP);
   1340     }
   1341 
   1342     if (condTop < 0) {
   1343 	/*
   1344 	 * This is the one case where we can definitely proclaim a fatal
   1345 	 * error. If we don't, we're hosed.
   1346 	 */
   1347 	Parse_Error (PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
   1348 	return (COND_INVALID);
   1349     } else {
   1350 	condStack[condTop] = value;
   1351 	skipLine = !value;
   1352 	return (value ? COND_PARSE : COND_SKIP);
   1353     }
   1354 }
   1355 
   1356 
   1357 
   1358 /*-
   1360  *-----------------------------------------------------------------------
   1361  * Cond_End --
   1362  *	Make sure everything's clean at the end of a makefile.
   1363  *
   1364  * Results:
   1365  *	None.
   1366  *
   1367  * Side Effects:
   1368  *	Parse_Error will be called if open conditionals are around.
   1369  *
   1370  *-----------------------------------------------------------------------
   1371  */
   1372 void
   1373 Cond_End(void)
   1374 {
   1375     if (condTop != MAXIF) {
   1376 	Parse_Error(PARSE_FATAL, "%d open conditional%s", MAXIF-condTop,
   1377 		    MAXIF-condTop == 1 ? "" : "s");
   1378     }
   1379     condTop = MAXIF;
   1380 }
   1381