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