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