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