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