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