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