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