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