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