xref: /freebsd/contrib/bmake/cond.c (revision 4b330699f819a81d8e34d471225143ffeb321855)
1 /*	$NetBSD: cond.c,v 1.75 2017/04/16 20:59:04 riastradh 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.75 2017/04/16 20:59:04 riastradh 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.75 2017/04/16 20:59:04 riastradh 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    <assert.h>
95 #include    <ctype.h>
96 #include    <errno.h>    /* For strtoul() error checking */
97 
98 #include    "make.h"
99 #include    "hash.h"
100 #include    "dir.h"
101 #include    "buf.h"
102 
103 /*
104  * The parsing of conditional expressions is based on this grammar:
105  *	E -> F || E
106  *	E -> F
107  *	F -> T && F
108  *	F -> T
109  *	T -> defined(variable)
110  *	T -> make(target)
111  *	T -> exists(file)
112  *	T -> empty(varspec)
113  *	T -> target(name)
114  *	T -> commands(name)
115  *	T -> symbol
116  *	T -> $(varspec) op value
117  *	T -> $(varspec) == "string"
118  *	T -> $(varspec) != "string"
119  *	T -> "string"
120  *	T -> ( E )
121  *	T -> ! T
122  *	op -> == | != | > | < | >= | <=
123  *
124  * 'symbol' is some other symbol to which the default function (condDefProc)
125  * is applied.
126  *
127  * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
128  * will return TOK_AND for '&' and '&&', TOK_OR for '|' and '||',
129  * TOK_NOT for '!', TOK_LPAREN for '(', TOK_RPAREN for ')' and will evaluate
130  * the other terminal symbols, using either the default function or the
131  * function given in the terminal, and return the result as either TOK_TRUE
132  * or TOK_FALSE.
133  *
134  * TOK_FALSE is 0 and TOK_TRUE 1 so we can directly assign C comparisons.
135  *
136  * All Non-Terminal functions (CondE, CondF and CondT) return TOK_ERROR on
137  * error.
138  */
139 typedef enum {
140     TOK_FALSE = 0, TOK_TRUE = 1, TOK_AND, TOK_OR, TOK_NOT,
141     TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
142 } Token;
143 
144 /*-
145  * Structures to handle elegantly the different forms of #if's. The
146  * last two fields are stored in condInvert and condDefProc, respectively.
147  */
148 static void CondPushBack(Token);
149 static int CondGetArg(char **, char **, const char *);
150 static Boolean CondDoDefined(int, const char *);
151 static int CondStrMatch(const void *, const void *);
152 static Boolean CondDoMake(int, const char *);
153 static Boolean CondDoExists(int, const char *);
154 static Boolean CondDoTarget(int, const char *);
155 static Boolean CondDoCommands(int, const char *);
156 static Boolean CondCvtArg(char *, double *);
157 static Token CondToken(Boolean);
158 static Token CondT(Boolean);
159 static Token CondF(Boolean);
160 static Token CondE(Boolean);
161 static int do_Cond_EvalExpression(Boolean *);
162 
163 static const struct If {
164     const char	*form;	      /* Form of if */
165     int		formlen;      /* Length of form */
166     Boolean	doNot;	      /* TRUE if default function should be negated */
167     Boolean	(*defProc)(int, const char *); /* Default function to apply */
168 } ifs[] = {
169     { "def",	  3,	  FALSE,  CondDoDefined },
170     { "ndef",	  4,	  TRUE,	  CondDoDefined },
171     { "make",	  4,	  FALSE,  CondDoMake },
172     { "nmake",	  5,	  TRUE,	  CondDoMake },
173     { "",	  0,	  FALSE,  CondDoDefined },
174     { NULL,	  0,	  FALSE,  NULL }
175 };
176 
177 static const struct If *if_info;        /* Info for current statement */
178 static char 	  *condExpr;	    	/* The expression to parse */
179 static Token	  condPushBack=TOK_NONE;	/* Single push-back token used in
180 					 * parsing */
181 
182 static unsigned int	cond_depth = 0;  	/* current .if nesting level */
183 static unsigned int	cond_min_depth = 0;  	/* depth at makefile open */
184 
185 /*
186  * Indicate when we should be strict about lhs of comparisons.
187  * TRUE when Cond_EvalExpression is called from Cond_Eval (.if etc)
188  * FALSE when Cond_EvalExpression is called from var.c:ApplyModifiers
189  * since lhs is already expanded and we cannot tell if
190  * it was a variable reference or not.
191  */
192 static Boolean lhsStrict;
193 
194 static int
195 istoken(const char *str, const char *tok, size_t len)
196 {
197 	return strncmp(str, tok, len) == 0 && !isalpha((unsigned char)str[len]);
198 }
199 
200 /*-
201  *-----------------------------------------------------------------------
202  * CondPushBack --
203  *	Push back the most recent token read. We only need one level of
204  *	this, so the thing is just stored in 'condPushback'.
205  *
206  * Input:
207  *	t		Token to push back into the "stream"
208  *
209  * Results:
210  *	None.
211  *
212  * Side Effects:
213  *	condPushback is overwritten.
214  *
215  *-----------------------------------------------------------------------
216  */
217 static void
218 CondPushBack(Token t)
219 {
220     condPushBack = t;
221 }
222 
223 /*-
224  *-----------------------------------------------------------------------
225  * CondGetArg --
226  *	Find the argument of a built-in function.
227  *
228  * Input:
229  *	parens		TRUE if arg should be bounded by parens
230  *
231  * Results:
232  *	The length of the argument and the address of the argument.
233  *
234  * Side Effects:
235  *	The pointer is set to point to the closing parenthesis of the
236  *	function call.
237  *
238  *-----------------------------------------------------------------------
239  */
240 static int
241 CondGetArg(char **linePtr, char **argPtr, const char *func)
242 {
243     char	  *cp;
244     int	    	  argLen;
245     Buffer	  buf;
246     int           paren_depth;
247     char          ch;
248 
249     cp = *linePtr;
250     if (func != NULL)
251 	/* Skip opening '(' - verfied by caller */
252 	cp++;
253 
254     if (*cp == '\0') {
255 	/*
256 	 * No arguments whatsoever. Because 'make' and 'defined' aren't really
257 	 * "reserved words", we don't print a message. I think this is better
258 	 * than hitting the user with a warning message every time s/he uses
259 	 * the word 'make' or 'defined' at the beginning of a symbol...
260 	 */
261 	*argPtr = NULL;
262 	return (0);
263     }
264 
265     while (*cp == ' ' || *cp == '\t') {
266 	cp++;
267     }
268 
269     /*
270      * Create a buffer for the argument and start it out at 16 characters
271      * long. Why 16? Why not?
272      */
273     Buf_Init(&buf, 16);
274 
275     paren_depth = 0;
276     for (;;) {
277 	ch = *cp;
278 	if (ch == 0 || ch == ' ' || ch == '\t')
279 	    break;
280 	if ((ch == '&' || ch == '|') && paren_depth == 0)
281 	    break;
282 	if (*cp == '$') {
283 	    /*
284 	     * Parse the variable spec and install it as part of the argument
285 	     * if it's valid. We tell Var_Parse to complain on an undefined
286 	     * variable, so we don't do it too. Nor do we return an error,
287 	     * though perhaps we should...
288 	     */
289 	    char  	*cp2;
290 	    int		len;
291 	    void	*freeIt;
292 
293 	    cp2 = Var_Parse(cp, VAR_CMD, VARF_UNDEFERR|VARF_WANTRES,
294 			    &len, &freeIt);
295 	    Buf_AddBytes(&buf, strlen(cp2), cp2);
296 	    free(freeIt);
297 	    cp += len;
298 	    continue;
299 	}
300 	if (ch == '(')
301 	    paren_depth++;
302 	else
303 	    if (ch == ')' && --paren_depth < 0)
304 		break;
305 	Buf_AddByte(&buf, *cp);
306 	cp++;
307     }
308 
309     *argPtr = Buf_GetAll(&buf, &argLen);
310     Buf_Destroy(&buf, FALSE);
311 
312     while (*cp == ' ' || *cp == '\t') {
313 	cp++;
314     }
315 
316     if (func != NULL && *cp++ != ')') {
317 	Parse_Error(PARSE_WARNING, "Missing closing parenthesis for %s()",
318 		     func);
319 	return (0);
320     }
321 
322     *linePtr = cp;
323     return (argLen);
324 }
325 
326 /*-
327  *-----------------------------------------------------------------------
328  * CondDoDefined --
329  *	Handle the 'defined' function for conditionals.
330  *
331  * Results:
332  *	TRUE if the given variable is defined.
333  *
334  * Side Effects:
335  *	None.
336  *
337  *-----------------------------------------------------------------------
338  */
339 static Boolean
340 CondDoDefined(int argLen MAKE_ATTR_UNUSED, const char *arg)
341 {
342     char    *p1;
343     Boolean result;
344 
345     if (Var_Value(arg, VAR_CMD, &p1) != NULL) {
346 	result = TRUE;
347     } else {
348 	result = FALSE;
349     }
350 
351     free(p1);
352     return (result);
353 }
354 
355 /*-
356  *-----------------------------------------------------------------------
357  * CondStrMatch --
358  *	Front-end for Str_Match so it returns 0 on match and non-zero
359  *	on mismatch. Callback function for CondDoMake via Lst_Find
360  *
361  * Results:
362  *	0 if string matches pattern
363  *
364  * Side Effects:
365  *	None
366  *
367  *-----------------------------------------------------------------------
368  */
369 static int
370 CondStrMatch(const void *string, const void *pattern)
371 {
372     return(!Str_Match(string, pattern));
373 }
374 
375 /*-
376  *-----------------------------------------------------------------------
377  * CondDoMake --
378  *	Handle the 'make' function for conditionals.
379  *
380  * Results:
381  *	TRUE if the given target is being made.
382  *
383  * Side Effects:
384  *	None.
385  *
386  *-----------------------------------------------------------------------
387  */
388 static Boolean
389 CondDoMake(int argLen MAKE_ATTR_UNUSED, const char *arg)
390 {
391     return Lst_Find(create, arg, CondStrMatch) != NULL;
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 MAKE_ATTR_UNUSED, const char *arg)
409 {
410     Boolean result;
411     char    *path;
412 
413     path = Dir_FindFile(arg, dirSearchPath);
414     if (DEBUG(COND)) {
415 	fprintf(debug_file, "exists(%s) result is \"%s\"\n",
416 	       arg, path ? path : "");
417     }
418     if (path != NULL) {
419 	result = TRUE;
420 	free(path);
421     } else {
422 	result = FALSE;
423     }
424     return (result);
425 }
426 
427 /*-
428  *-----------------------------------------------------------------------
429  * CondDoTarget --
430  *	See if the given node exists and is an actual target.
431  *
432  * Results:
433  *	TRUE if the node exists as a target and FALSE if it does not.
434  *
435  * Side Effects:
436  *	None.
437  *
438  *-----------------------------------------------------------------------
439  */
440 static Boolean
441 CondDoTarget(int argLen MAKE_ATTR_UNUSED, const char *arg)
442 {
443     GNode   *gn;
444 
445     gn = Targ_FindNode(arg, TARG_NOCREATE);
446     return (gn != NULL) && !OP_NOP(gn->type);
447 }
448 
449 /*-
450  *-----------------------------------------------------------------------
451  * CondDoCommands --
452  *	See if the given node exists and is an actual target with commands
453  *	associated with it.
454  *
455  * Results:
456  *	TRUE if the node exists as a target and has commands associated with
457  *	it and FALSE if it does not.
458  *
459  * Side Effects:
460  *	None.
461  *
462  *-----------------------------------------------------------------------
463  */
464 static Boolean
465 CondDoCommands(int argLen MAKE_ATTR_UNUSED, const char *arg)
466 {
467     GNode   *gn;
468 
469     gn = Targ_FindNode(arg, TARG_NOCREATE);
470     return (gn != NULL) && !OP_NOP(gn->type) && !Lst_IsEmpty(gn->commands);
471 }
472 
473 /*-
474  *-----------------------------------------------------------------------
475  * CondCvtArg --
476  *	Convert the given number into a double.
477  *	We try a base 10 or 16 integer conversion first, if that fails
478  *	then we try a floating point conversion instead.
479  *
480  * Results:
481  *	Sets 'value' to double value of string.
482  *	Returns 'true' if the convertion suceeded
483  *
484  *-----------------------------------------------------------------------
485  */
486 static Boolean
487 CondCvtArg(char *str, double *value)
488 {
489     char *eptr, ech;
490     unsigned long l_val;
491     double d_val;
492 
493     errno = 0;
494     if (!*str) {
495 	*value = (double)0;
496 	return TRUE;
497     }
498     l_val = strtoul(str, &eptr, str[1] == 'x' ? 16 : 10);
499     ech = *eptr;
500     if (ech == 0 && errno != ERANGE) {
501 	d_val = str[0] == '-' ? -(double)-l_val : (double)l_val;
502     } else {
503 	if (ech != 0 && ech != '.' && ech != 'e' && ech != 'E')
504 	    return FALSE;
505 	d_val = strtod(str, &eptr);
506 	if (*eptr)
507 	    return FALSE;
508     }
509 
510     *value = d_val;
511     return TRUE;
512 }
513 
514 /*-
515  *-----------------------------------------------------------------------
516  * CondGetString --
517  *	Get a string from a variable reference or an optionally quoted
518  *	string.  This is called for the lhs and rhs of string compares.
519  *
520  * Results:
521  *	Sets freeIt if needed,
522  *	Sets quoted if string was quoted,
523  *	Returns NULL on error,
524  *	else returns string - absent any quotes.
525  *
526  * Side Effects:
527  *	Moves condExpr to end of this token.
528  *
529  *
530  *-----------------------------------------------------------------------
531  */
532 /* coverity:[+alloc : arg-*2] */
533 static char *
534 CondGetString(Boolean doEval, Boolean *quoted, void **freeIt, Boolean strictLHS)
535 {
536     Buffer buf;
537     char *cp;
538     char *str;
539     int	len;
540     int qt;
541     char *start;
542 
543     Buf_Init(&buf, 0);
544     str = NULL;
545     *freeIt = NULL;
546     *quoted = qt = *condExpr == '"' ? 1 : 0;
547     if (qt)
548 	condExpr++;
549     for (start = condExpr; *condExpr && str == NULL; condExpr++) {
550 	switch (*condExpr) {
551 	case '\\':
552 	    if (condExpr[1] != '\0') {
553 		condExpr++;
554 		Buf_AddByte(&buf, *condExpr);
555 	    }
556 	    break;
557 	case '"':
558 	    if (qt) {
559 		condExpr++;		/* we don't want the quotes */
560 		goto got_str;
561 	    } else
562 		Buf_AddByte(&buf, *condExpr); /* likely? */
563 	    break;
564 	case ')':
565 	case '!':
566 	case '=':
567 	case '>':
568 	case '<':
569 	case ' ':
570 	case '\t':
571 	    if (!qt)
572 		goto got_str;
573 	    else
574 		Buf_AddByte(&buf, *condExpr);
575 	    break;
576 	case '$':
577 	    /* if we are in quotes, then an undefined variable is ok */
578 	    str = Var_Parse(condExpr, VAR_CMD,
579 			    ((!qt && doEval) ? VARF_UNDEFERR : 0) |
580 			    VARF_WANTRES, &len, freeIt);
581 	    if (str == var_Error) {
582 		if (*freeIt) {
583 		    free(*freeIt);
584 		    *freeIt = NULL;
585 		}
586 		/*
587 		 * Even if !doEval, we still report syntax errors, which
588 		 * is what getting var_Error back with !doEval means.
589 		 */
590 		str = NULL;
591 		goto cleanup;
592 	    }
593 	    condExpr += len;
594 	    /*
595 	     * If the '$' was first char (no quotes), and we are
596 	     * followed by space, the operator or end of expression,
597 	     * we are done.
598 	     */
599 	    if ((condExpr == start + len) &&
600 		(*condExpr == '\0' ||
601 		 isspace((unsigned char) *condExpr) ||
602 		 strchr("!=><)", *condExpr))) {
603 		goto cleanup;
604 	    }
605 	    /*
606 	     * Nope, we better copy str to buf
607 	     */
608 	    for (cp = str; *cp; cp++) {
609 		Buf_AddByte(&buf, *cp);
610 	    }
611 	    if (*freeIt) {
612 		free(*freeIt);
613 		*freeIt = NULL;
614 	    }
615 	    str = NULL;			/* not finished yet */
616 	    condExpr--;			/* don't skip over next char */
617 	    break;
618 	default:
619 	    if (strictLHS && !qt && *start != '$' &&
620 		!isdigit((unsigned char) *start)) {
621 		/* lhs must be quoted, a variable reference or number */
622 		if (*freeIt) {
623 		    free(*freeIt);
624 		    *freeIt = NULL;
625 		}
626 		str = NULL;
627 		goto cleanup;
628 	    }
629 	    Buf_AddByte(&buf, *condExpr);
630 	    break;
631 	}
632     }
633  got_str:
634     str = Buf_GetAll(&buf, NULL);
635     *freeIt = str;
636  cleanup:
637     Buf_Destroy(&buf, FALSE);
638     return str;
639 }
640 
641 /*-
642  *-----------------------------------------------------------------------
643  * CondToken --
644  *	Return the next token from the input.
645  *
646  * Results:
647  *	A Token for the next lexical token in the stream.
648  *
649  * Side Effects:
650  *	condPushback will be set back to TOK_NONE if it is used.
651  *
652  *-----------------------------------------------------------------------
653  */
654 static Token
655 compare_expression(Boolean doEval)
656 {
657     Token	t;
658     char	*lhs;
659     char	*rhs;
660     char	*op;
661     void	*lhsFree;
662     void	*rhsFree;
663     Boolean lhsQuoted;
664     Boolean rhsQuoted;
665     double  	left, right;
666 
667     t = TOK_ERROR;
668     rhs = NULL;
669     lhsFree = rhsFree = FALSE;
670     lhsQuoted = rhsQuoted = FALSE;
671 
672     /*
673      * Parse the variable spec and skip over it, saving its
674      * value in lhs.
675      */
676     lhs = CondGetString(doEval, &lhsQuoted, &lhsFree, lhsStrict);
677     if (!lhs)
678 	goto done;
679 
680     /*
681      * Skip whitespace to get to the operator
682      */
683     while (isspace((unsigned char) *condExpr))
684 	condExpr++;
685 
686     /*
687      * Make sure the operator is a valid one. If it isn't a
688      * known relational operator, pretend we got a
689      * != 0 comparison.
690      */
691     op = condExpr;
692     switch (*condExpr) {
693 	case '!':
694 	case '=':
695 	case '<':
696 	case '>':
697 	    if (condExpr[1] == '=') {
698 		condExpr += 2;
699 	    } else {
700 		condExpr += 1;
701 	    }
702 	    break;
703 	default:
704 	    if (!doEval) {
705 		t = TOK_FALSE;
706 		goto done;
707 	    }
708 	    /* For .ifxxx "..." check for non-empty string. */
709 	    if (lhsQuoted) {
710 		t = lhs[0] != 0;
711 		goto done;
712 	    }
713 	    /* For .ifxxx <number> compare against zero */
714 	    if (CondCvtArg(lhs, &left)) {
715 		t = left != 0.0;
716 		goto done;
717 	    }
718 	    /* For .if ${...} check for non-empty string (defProc is ifdef). */
719 	    if (if_info->form[0] == 0) {
720 		t = lhs[0] != 0;
721 		goto done;
722 	    }
723 	    /* Otherwise action default test ... */
724 	    t = if_info->defProc(strlen(lhs), lhs) != if_info->doNot;
725 	    goto done;
726     }
727 
728     while (isspace((unsigned char)*condExpr))
729 	condExpr++;
730 
731     if (*condExpr == '\0') {
732 	Parse_Error(PARSE_WARNING,
733 		    "Missing right-hand-side of operator");
734 	goto done;
735     }
736 
737     rhs = CondGetString(doEval, &rhsQuoted, &rhsFree, FALSE);
738     if (!rhs)
739 	goto done;
740 
741     if (rhsQuoted || lhsQuoted) {
742 do_string_compare:
743 	if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
744 	    Parse_Error(PARSE_WARNING,
745     "String comparison operator should be either == or !=");
746 	    goto done;
747 	}
748 
749 	if (DEBUG(COND)) {
750 	    fprintf(debug_file, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
751 		   lhs, rhs, op);
752 	}
753 	/*
754 	 * Null-terminate rhs and perform the comparison.
755 	 * t is set to the result.
756 	 */
757 	if (*op == '=') {
758 	    t = strcmp(lhs, rhs) == 0;
759 	} else {
760 	    t = strcmp(lhs, rhs) != 0;
761 	}
762     } else {
763 	/*
764 	 * rhs is either a float or an integer. Convert both the
765 	 * lhs and the rhs to a double and compare the two.
766 	 */
767 
768 	if (!CondCvtArg(lhs, &left) || !CondCvtArg(rhs, &right))
769 	    goto do_string_compare;
770 
771 	if (DEBUG(COND)) {
772 	    fprintf(debug_file, "left = %f, right = %f, op = %.2s\n", left,
773 		   right, op);
774 	}
775 	switch(op[0]) {
776 	case '!':
777 	    if (op[1] != '=') {
778 		Parse_Error(PARSE_WARNING,
779 			    "Unknown operator");
780 		goto done;
781 	    }
782 	    t = (left != right);
783 	    break;
784 	case '=':
785 	    if (op[1] != '=') {
786 		Parse_Error(PARSE_WARNING,
787 			    "Unknown operator");
788 		goto done;
789 	    }
790 	    t = (left == right);
791 	    break;
792 	case '<':
793 	    if (op[1] == '=') {
794 		t = (left <= right);
795 	    } else {
796 		t = (left < right);
797 	    }
798 	    break;
799 	case '>':
800 	    if (op[1] == '=') {
801 		t = (left >= right);
802 	    } else {
803 		t = (left > right);
804 	    }
805 	    break;
806 	}
807     }
808 
809 done:
810     free(lhsFree);
811     free(rhsFree);
812     return t;
813 }
814 
815 static int
816 get_mpt_arg(char **linePtr, char **argPtr, const char *func MAKE_ATTR_UNUSED)
817 {
818     /*
819      * Use Var_Parse to parse the spec in parens and return
820      * TOK_TRUE if the resulting string is empty.
821      */
822     int	    length;
823     void    *freeIt;
824     char    *val;
825     char    *cp = *linePtr;
826 
827     /* We do all the work here and return the result as the length */
828     *argPtr = NULL;
829 
830     val = Var_Parse(cp - 1, VAR_CMD, VARF_WANTRES, &length, &freeIt);
831     /*
832      * Advance *linePtr to beyond the closing ). Note that
833      * we subtract one because 'length' is calculated from 'cp - 1'.
834      */
835     *linePtr = cp - 1 + length;
836 
837     if (val == var_Error) {
838 	free(freeIt);
839 	return -1;
840     }
841 
842     /* A variable is empty when it just contains spaces... 4/15/92, christos */
843     while (isspace(*(unsigned char *)val))
844 	val++;
845 
846     /*
847      * For consistency with the other functions we can't generate the
848      * true/false here.
849      */
850     length = *val ? 2 : 1;
851     free(freeIt);
852     return length;
853 }
854 
855 static Boolean
856 CondDoEmpty(int arglen, const char *arg MAKE_ATTR_UNUSED)
857 {
858     return arglen == 1;
859 }
860 
861 static Token
862 compare_function(Boolean doEval)
863 {
864     static const struct fn_def {
865 	const char  *fn_name;
866 	int         fn_name_len;
867         int         (*fn_getarg)(char **, char **, const char *);
868 	Boolean     (*fn_proc)(int, const char *);
869     } fn_defs[] = {
870 	{ "defined",   7, CondGetArg, CondDoDefined },
871 	{ "make",      4, CondGetArg, CondDoMake },
872 	{ "exists",    6, CondGetArg, CondDoExists },
873 	{ "empty",     5, get_mpt_arg, CondDoEmpty },
874 	{ "target",    6, CondGetArg, CondDoTarget },
875 	{ "commands",  8, CondGetArg, CondDoCommands },
876 	{ NULL,        0, NULL, NULL },
877     };
878     const struct fn_def *fn_def;
879     Token	t;
880     char	*arg = NULL;
881     int	arglen;
882     char *cp = condExpr;
883     char *cp1;
884 
885     for (fn_def = fn_defs; fn_def->fn_name != NULL; fn_def++) {
886 	if (!istoken(cp, fn_def->fn_name, fn_def->fn_name_len))
887 	    continue;
888 	cp += fn_def->fn_name_len;
889 	/* There can only be whitespace before the '(' */
890 	while (isspace(*(unsigned char *)cp))
891 	    cp++;
892 	if (*cp != '(')
893 	    break;
894 
895 	arglen = fn_def->fn_getarg(&cp, &arg, fn_def->fn_name);
896 	if (arglen <= 0) {
897 	    condExpr = cp;
898 	    return arglen < 0 ? TOK_ERROR : TOK_FALSE;
899 	}
900 	/* Evaluate the argument using the required function. */
901 	t = !doEval || fn_def->fn_proc(arglen, arg);
902 	free(arg);
903 	condExpr = cp;
904 	return t;
905     }
906 
907     /* Push anything numeric through the compare expression */
908     cp = condExpr;
909     if (isdigit((unsigned char)cp[0]) || strchr("+-", cp[0]))
910 	return compare_expression(doEval);
911 
912     /*
913      * Most likely we have a naked token to apply the default function to.
914      * However ".if a == b" gets here when the "a" is unquoted and doesn't
915      * start with a '$'. This surprises people.
916      * If what follows the function argument is a '=' or '!' then the syntax
917      * would be invalid if we did "defined(a)" - so instead treat as an
918      * expression.
919      */
920     arglen = CondGetArg(&cp, &arg, NULL);
921     for (cp1 = cp; isspace(*(unsigned char *)cp1); cp1++)
922 	continue;
923     if (*cp1 == '=' || *cp1 == '!')
924 	return compare_expression(doEval);
925     condExpr = cp;
926 
927     /*
928      * Evaluate the argument using the default function.
929      * This path always treats .if as .ifdef. To get here the character
930      * after .if must have been taken literally, so the argument cannot
931      * be empty - even if it contained a variable expansion.
932      */
933     t = !doEval || if_info->defProc(arglen, arg) != if_info->doNot;
934     free(arg);
935     return t;
936 }
937 
938 static Token
939 CondToken(Boolean doEval)
940 {
941     Token t;
942 
943     t = condPushBack;
944     if (t != TOK_NONE) {
945 	condPushBack = TOK_NONE;
946 	return t;
947     }
948 
949     while (*condExpr == ' ' || *condExpr == '\t') {
950 	condExpr++;
951     }
952 
953     switch (*condExpr) {
954 
955     case '(':
956 	condExpr++;
957 	return TOK_LPAREN;
958 
959     case ')':
960 	condExpr++;
961 	return TOK_RPAREN;
962 
963     case '|':
964 	if (condExpr[1] == '|') {
965 	    condExpr++;
966 	}
967 	condExpr++;
968 	return TOK_OR;
969 
970     case '&':
971 	if (condExpr[1] == '&') {
972 	    condExpr++;
973 	}
974 	condExpr++;
975 	return TOK_AND;
976 
977     case '!':
978 	condExpr++;
979 	return TOK_NOT;
980 
981     case '#':
982     case '\n':
983     case '\0':
984 	return TOK_EOF;
985 
986     case '"':
987     case '$':
988 	return compare_expression(doEval);
989 
990     default:
991 	return compare_function(doEval);
992     }
993 }
994 
995 /*-
996  *-----------------------------------------------------------------------
997  * CondT --
998  *	Parse a single term in the expression. This consists of a terminal
999  *	symbol or TOK_NOT and a terminal symbol (not including the binary
1000  *	operators):
1001  *	    T -> defined(variable) | make(target) | exists(file) | symbol
1002  *	    T -> ! T | ( E )
1003  *
1004  * Results:
1005  *	TOK_TRUE, TOK_FALSE or TOK_ERROR.
1006  *
1007  * Side Effects:
1008  *	Tokens are consumed.
1009  *
1010  *-----------------------------------------------------------------------
1011  */
1012 static Token
1013 CondT(Boolean doEval)
1014 {
1015     Token   t;
1016 
1017     t = CondToken(doEval);
1018 
1019     if (t == TOK_EOF) {
1020 	/*
1021 	 * If we reached the end of the expression, the expression
1022 	 * is malformed...
1023 	 */
1024 	t = TOK_ERROR;
1025     } else if (t == TOK_LPAREN) {
1026 	/*
1027 	 * T -> ( E )
1028 	 */
1029 	t = CondE(doEval);
1030 	if (t != TOK_ERROR) {
1031 	    if (CondToken(doEval) != TOK_RPAREN) {
1032 		t = TOK_ERROR;
1033 	    }
1034 	}
1035     } else if (t == TOK_NOT) {
1036 	t = CondT(doEval);
1037 	if (t == TOK_TRUE) {
1038 	    t = TOK_FALSE;
1039 	} else if (t == TOK_FALSE) {
1040 	    t = TOK_TRUE;
1041 	}
1042     }
1043     return (t);
1044 }
1045 
1046 /*-
1047  *-----------------------------------------------------------------------
1048  * CondF --
1049  *	Parse a conjunctive factor (nice name, wot?)
1050  *	    F -> T && F | T
1051  *
1052  * Results:
1053  *	TOK_TRUE, TOK_FALSE or TOK_ERROR
1054  *
1055  * Side Effects:
1056  *	Tokens are consumed.
1057  *
1058  *-----------------------------------------------------------------------
1059  */
1060 static Token
1061 CondF(Boolean doEval)
1062 {
1063     Token   l, o;
1064 
1065     l = CondT(doEval);
1066     if (l != TOK_ERROR) {
1067 	o = CondToken(doEval);
1068 
1069 	if (o == TOK_AND) {
1070 	    /*
1071 	     * F -> T && F
1072 	     *
1073 	     * If T is TOK_FALSE, the whole thing will be TOK_FALSE, but we have to
1074 	     * parse the r.h.s. anyway (to throw it away).
1075 	     * If T is TOK_TRUE, the result is the r.h.s., be it an TOK_ERROR or no.
1076 	     */
1077 	    if (l == TOK_TRUE) {
1078 		l = CondF(doEval);
1079 	    } else {
1080 		(void)CondF(FALSE);
1081 	    }
1082 	} else {
1083 	    /*
1084 	     * F -> T
1085 	     */
1086 	    CondPushBack(o);
1087 	}
1088     }
1089     return (l);
1090 }
1091 
1092 /*-
1093  *-----------------------------------------------------------------------
1094  * CondE --
1095  *	Main expression production.
1096  *	    E -> F || E | F
1097  *
1098  * Results:
1099  *	TOK_TRUE, TOK_FALSE or TOK_ERROR.
1100  *
1101  * Side Effects:
1102  *	Tokens are, of course, consumed.
1103  *
1104  *-----------------------------------------------------------------------
1105  */
1106 static Token
1107 CondE(Boolean doEval)
1108 {
1109     Token   l, o;
1110 
1111     l = CondF(doEval);
1112     if (l != TOK_ERROR) {
1113 	o = CondToken(doEval);
1114 
1115 	if (o == TOK_OR) {
1116 	    /*
1117 	     * E -> F || E
1118 	     *
1119 	     * A similar thing occurs for ||, except that here we make sure
1120 	     * the l.h.s. is TOK_FALSE before we bother to evaluate the r.h.s.
1121 	     * Once again, if l is TOK_FALSE, the result is the r.h.s. and once
1122 	     * again if l is TOK_TRUE, we parse the r.h.s. to throw it away.
1123 	     */
1124 	    if (l == TOK_FALSE) {
1125 		l = CondE(doEval);
1126 	    } else {
1127 		(void)CondE(FALSE);
1128 	    }
1129 	} else {
1130 	    /*
1131 	     * E -> F
1132 	     */
1133 	    CondPushBack(o);
1134 	}
1135     }
1136     return (l);
1137 }
1138 
1139 /*-
1140  *-----------------------------------------------------------------------
1141  * Cond_EvalExpression --
1142  *	Evaluate an expression in the passed line. The expression
1143  *	consists of &&, ||, !, make(target), defined(variable)
1144  *	and parenthetical groupings thereof.
1145  *
1146  * Results:
1147  *	COND_PARSE	if the condition was valid grammatically
1148  *	COND_INVALID  	if not a valid conditional.
1149  *
1150  *	(*value) is set to the boolean value of the condition
1151  *
1152  * Side Effects:
1153  *	None.
1154  *
1155  *-----------------------------------------------------------------------
1156  */
1157 int
1158 Cond_EvalExpression(const struct If *info, char *line, Boolean *value, int eprint, Boolean strictLHS)
1159 {
1160     static const struct If *dflt_info;
1161     const struct If *sv_if_info = if_info;
1162     char *sv_condExpr = condExpr;
1163     Token sv_condPushBack = condPushBack;
1164     int rval;
1165 
1166     lhsStrict = strictLHS;
1167 
1168     while (*line == ' ' || *line == '\t')
1169 	line++;
1170 
1171     if (info == NULL && (info = dflt_info) == NULL) {
1172 	/* Scan for the entry for .if - it can't be first */
1173 	for (info = ifs; ; info++)
1174 	    if (info->form[0] == 0)
1175 		break;
1176 	dflt_info = info;
1177     }
1178     assert(info != NULL);
1179 
1180     if_info = info;
1181     condExpr = line;
1182     condPushBack = TOK_NONE;
1183 
1184     rval = do_Cond_EvalExpression(value);
1185 
1186     if (rval == COND_INVALID && eprint)
1187 	Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", line);
1188 
1189     if_info = sv_if_info;
1190     condExpr = sv_condExpr;
1191     condPushBack = sv_condPushBack;
1192 
1193     return rval;
1194 }
1195 
1196 static int
1197 do_Cond_EvalExpression(Boolean *value)
1198 {
1199 
1200     switch (CondE(TRUE)) {
1201     case TOK_TRUE:
1202 	if (CondToken(TRUE) == TOK_EOF) {
1203 	    *value = TRUE;
1204 	    return COND_PARSE;
1205 	}
1206 	break;
1207     case TOK_FALSE:
1208 	if (CondToken(TRUE) == TOK_EOF) {
1209 	    *value = FALSE;
1210 	    return COND_PARSE;
1211 	}
1212 	break;
1213     default:
1214     case TOK_ERROR:
1215 	break;
1216     }
1217 
1218     return COND_INVALID;
1219 }
1220 
1221 
1222 /*-
1223  *-----------------------------------------------------------------------
1224  * Cond_Eval --
1225  *	Evaluate the conditional in the passed line. The line
1226  *	looks like this:
1227  *	    .<cond-type> <expr>
1228  *	where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1229  *	ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1230  *	and <expr> consists of &&, ||, !, make(target), defined(variable)
1231  *	and parenthetical groupings thereof.
1232  *
1233  * Input:
1234  *	line		Line to parse
1235  *
1236  * Results:
1237  *	COND_PARSE	if should parse lines after the conditional
1238  *	COND_SKIP	if should skip lines after the conditional
1239  *	COND_INVALID  	if not a valid conditional.
1240  *
1241  * Side Effects:
1242  *	None.
1243  *
1244  * Note that the states IF_ACTIVE and ELSE_ACTIVE are only different in order
1245  * to detect splurious .else lines (as are SKIP_TO_ELSE and SKIP_TO_ENDIF)
1246  * otherwise .else could be treated as '.elif 1'.
1247  *
1248  *-----------------------------------------------------------------------
1249  */
1250 int
1251 Cond_Eval(char *line)
1252 {
1253 #define	    MAXIF      128	/* maximum depth of .if'ing */
1254 #define	    MAXIF_BUMP  32	/* how much to grow by */
1255     enum if_states {
1256 	IF_ACTIVE,		/* .if or .elif part active */
1257 	ELSE_ACTIVE,		/* .else part active */
1258 	SEARCH_FOR_ELIF,	/* searching for .elif/else to execute */
1259 	SKIP_TO_ELSE,           /* has been true, but not seen '.else' */
1260 	SKIP_TO_ENDIF		/* nothing else to execute */
1261     };
1262     static enum if_states *cond_state = NULL;
1263     static unsigned int max_if_depth = MAXIF;
1264 
1265     const struct If *ifp;
1266     Boolean 	    isElif;
1267     Boolean 	    value;
1268     int	    	    level;  	/* Level at which to report errors. */
1269     enum if_states  state;
1270 
1271     level = PARSE_FATAL;
1272     if (!cond_state) {
1273 	cond_state = bmake_malloc(max_if_depth * sizeof(*cond_state));
1274 	cond_state[0] = IF_ACTIVE;
1275     }
1276     /* skip leading character (the '.') and any whitespace */
1277     for (line++; *line == ' ' || *line == '\t'; line++)
1278 	continue;
1279 
1280     /* Find what type of if we're dealing with.  */
1281     if (line[0] == 'e') {
1282 	if (line[1] != 'l') {
1283 	    if (!istoken(line + 1, "ndif", 4))
1284 		return COND_INVALID;
1285 	    /* End of conditional section */
1286 	    if (cond_depth == cond_min_depth) {
1287 		Parse_Error(level, "if-less endif");
1288 		return COND_PARSE;
1289 	    }
1290 	    /* Return state for previous conditional */
1291 	    cond_depth--;
1292 	    return cond_state[cond_depth] <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1293 	}
1294 
1295 	/* Quite likely this is 'else' or 'elif' */
1296 	line += 2;
1297 	if (istoken(line, "se", 2)) {
1298 	    /* It is else... */
1299 	    if (cond_depth == cond_min_depth) {
1300 		Parse_Error(level, "if-less else");
1301 		return COND_PARSE;
1302 	    }
1303 
1304 	    state = cond_state[cond_depth];
1305 	    switch (state) {
1306 	    case SEARCH_FOR_ELIF:
1307 		state = ELSE_ACTIVE;
1308 		break;
1309 	    case ELSE_ACTIVE:
1310 	    case SKIP_TO_ENDIF:
1311 		Parse_Error(PARSE_WARNING, "extra else");
1312 		/* FALLTHROUGH */
1313 	    default:
1314 	    case IF_ACTIVE:
1315 	    case SKIP_TO_ELSE:
1316 		state = SKIP_TO_ENDIF;
1317 		break;
1318 	    }
1319 	    cond_state[cond_depth] = state;
1320 	    return state <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1321 	}
1322 	/* Assume for now it is an elif */
1323 	isElif = TRUE;
1324     } else
1325 	isElif = FALSE;
1326 
1327     if (line[0] != 'i' || line[1] != 'f')
1328 	/* Not an ifxxx or elifxxx line */
1329 	return COND_INVALID;
1330 
1331     /*
1332      * Figure out what sort of conditional it is -- what its default
1333      * function is, etc. -- by looking in the table of valid "ifs"
1334      */
1335     line += 2;
1336     for (ifp = ifs; ; ifp++) {
1337 	if (ifp->form == NULL)
1338 	    return COND_INVALID;
1339 	if (istoken(ifp->form, line, ifp->formlen)) {
1340 	    line += ifp->formlen;
1341 	    break;
1342 	}
1343     }
1344 
1345     /* Now we know what sort of 'if' it is... */
1346 
1347     if (isElif) {
1348 	if (cond_depth == cond_min_depth) {
1349 	    Parse_Error(level, "if-less elif");
1350 	    return COND_PARSE;
1351 	}
1352 	state = cond_state[cond_depth];
1353 	if (state == SKIP_TO_ENDIF || state == ELSE_ACTIVE) {
1354 	    Parse_Error(PARSE_WARNING, "extra elif");
1355 	    cond_state[cond_depth] = SKIP_TO_ENDIF;
1356 	    return COND_SKIP;
1357 	}
1358 	if (state != SEARCH_FOR_ELIF) {
1359 	    /* Either just finished the 'true' block, or already SKIP_TO_ELSE */
1360 	    cond_state[cond_depth] = SKIP_TO_ELSE;
1361 	    return COND_SKIP;
1362 	}
1363     } else {
1364 	/* Normal .if */
1365 	if (cond_depth + 1 >= max_if_depth) {
1366 	    /*
1367 	     * This is rare, but not impossible.
1368 	     * In meta mode, dirdeps.mk (only runs at level 0)
1369 	     * can need more than the default.
1370 	     */
1371 	    max_if_depth += MAXIF_BUMP;
1372 	    cond_state = bmake_realloc(cond_state, max_if_depth *
1373 		sizeof(*cond_state));
1374 	}
1375 	state = cond_state[cond_depth];
1376 	cond_depth++;
1377 	if (state > ELSE_ACTIVE) {
1378 	    /* If we aren't parsing the data, treat as always false */
1379 	    cond_state[cond_depth] = SKIP_TO_ELSE;
1380 	    return COND_SKIP;
1381 	}
1382     }
1383 
1384     /* And evaluate the conditional expresssion */
1385     if (Cond_EvalExpression(ifp, line, &value, 1, TRUE) == COND_INVALID) {
1386 	/* Syntax error in conditional, error message already output. */
1387 	/* Skip everything to matching .endif */
1388 	cond_state[cond_depth] = SKIP_TO_ELSE;
1389 	return COND_SKIP;
1390     }
1391 
1392     if (!value) {
1393 	cond_state[cond_depth] = SEARCH_FOR_ELIF;
1394 	return COND_SKIP;
1395     }
1396     cond_state[cond_depth] = IF_ACTIVE;
1397     return COND_PARSE;
1398 }
1399 
1400 
1401 
1402 /*-
1403  *-----------------------------------------------------------------------
1404  * Cond_End --
1405  *	Make sure everything's clean at the end of a makefile.
1406  *
1407  * Results:
1408  *	None.
1409  *
1410  * Side Effects:
1411  *	Parse_Error will be called if open conditionals are around.
1412  *
1413  *-----------------------------------------------------------------------
1414  */
1415 void
1416 Cond_restore_depth(unsigned int saved_depth)
1417 {
1418     int open_conds = cond_depth - cond_min_depth;
1419 
1420     if (open_conds != 0 || saved_depth > cond_depth) {
1421 	Parse_Error(PARSE_FATAL, "%d open conditional%s", open_conds,
1422 		    open_conds == 1 ? "" : "s");
1423 	cond_depth = cond_min_depth;
1424     }
1425 
1426     cond_min_depth = saved_depth;
1427 }
1428 
1429 unsigned int
1430 Cond_save_depth(void)
1431 {
1432     int depth = cond_min_depth;
1433 
1434     cond_min_depth = cond_depth;
1435     return depth;
1436 }
1437