xref: /dragonfly/contrib/bmake/cond.c (revision 7d3e9a5b)
1 /*	$NetBSD: cond.c,v 1.257 2021/02/22 23:21:33 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 /*
73  * Handling of conditionals in a makefile.
74  *
75  * Interface:
76  *	Cond_EvalLine   Evaluate the conditional directive, such as
77  *			'.if <cond>', '.elifnmake <cond>', '.else', '.endif'.
78  *
79  *	Cond_EvalCondition
80  *			Evaluate the conditional, which is either the argument
81  *			of one of the .if directives or the condition in a
82  *			':?then:else' variable modifier.
83  *
84  *	Cond_save_depth
85  *	Cond_restore_depth
86  *			Save and restore the nesting of the conditions, at
87  *			the start and end of including another makefile, to
88  *			ensure that in each makefile the conditional
89  *			directives are well-balanced.
90  */
91 
92 #include <errno.h>
93 
94 #include "make.h"
95 #include "dir.h"
96 
97 /*	"@(#)cond.c	8.2 (Berkeley) 1/2/94"	*/
98 MAKE_RCSID("$NetBSD: cond.c,v 1.257 2021/02/22 23:21:33 rillig Exp $");
99 
100 /*
101  * The parsing of conditional expressions is based on this grammar:
102  *	Or -> And '||' Or
103  *	Or -> And
104  *	And -> Term '&&' And
105  *	And -> Term
106  *	Term -> Function '(' Argument ')'
107  *	Term -> Leaf Operator Leaf
108  *	Term -> Leaf
109  *	Term -> '(' Or ')'
110  *	Term -> '!' Term
111  *	Leaf -> "string"
112  *	Leaf -> Number
113  *	Leaf -> VariableExpression
114  *	Leaf -> Symbol
115  *	Operator -> '==' | '!=' | '>' | '<' | '>=' | '<='
116  *
117  * 'Symbol' is an unquoted string literal to which the default function is
118  * applied.
119  *
120  * The tokens are scanned by CondToken, which returns:
121  *	TOK_AND		for '&&'
122  *	TOK_OR		for '||'
123  *	TOK_NOT		for '!'
124  *	TOK_LPAREN	for '('
125  *	TOK_RPAREN	for ')'
126  *
127  * Other terminal symbols are evaluated using either the default function or
128  * the function given in the terminal, they return either TOK_TRUE or
129  * TOK_FALSE.
130  */
131 typedef enum Token {
132 	TOK_FALSE, TOK_TRUE, TOK_AND, TOK_OR, TOK_NOT,
133 	TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
134 } Token;
135 
136 typedef enum CondResult {
137 	CR_FALSE, CR_TRUE, CR_ERROR
138 } CondResult;
139 
140 typedef enum ComparisonOp {
141 	LT, LE, GT, GE, EQ, NE
142 } ComparisonOp;
143 
144 typedef struct CondParser {
145 
146 	/*
147 	 * The plain '.if ${VAR}' evaluates to true if the value of the
148 	 * expression has length > 0.  The other '.if' variants delegate
149 	 * to evalBare instead.
150 	 */
151 	Boolean plain;
152 
153 	/* The function to apply on unquoted bare words. */
154 	Boolean (*evalBare)(size_t, const char *);
155 	Boolean negateEvalBare;
156 
157 	const char *p;		/* The remaining condition to parse */
158 	Token curr;		/* Single push-back token used in parsing */
159 
160 	/*
161 	 * Whether an error message has already been printed for this
162 	 * condition. The first available error message is usually the most
163 	 * specific one, therefore it makes sense to suppress the standard
164 	 * "Malformed conditional" message.
165 	 */
166 	Boolean printedError;
167 } CondParser;
168 
169 static CondResult CondParser_Or(CondParser *par, Boolean);
170 
171 static unsigned int cond_depth = 0;	/* current .if nesting level */
172 static unsigned int cond_min_depth = 0;	/* depth at makefile open */
173 
174 static const char *opname[] = { "<", "<=", ">", ">=", "==", "!=" };
175 
176 /*
177  * Indicate when we should be strict about lhs of comparisons.
178  * In strict mode, the lhs must be a variable expression or a string literal
179  * in quotes. In non-strict mode it may also be an unquoted string literal.
180  *
181  * TRUE when CondEvalExpression is called from Cond_EvalLine (.if etc)
182  * FALSE when CondEvalExpression is called from ApplyModifier_IfElse
183  * since lhs is already expanded, and at that point we cannot tell if
184  * it was a variable reference or not.
185  */
186 static Boolean lhsStrict;
187 
188 static Boolean
189 is_token(const char *str, const char *tok, size_t len)
190 {
191 	return strncmp(str, tok, len) == 0 && !ch_isalpha(str[len]);
192 }
193 
194 static Token
195 ToToken(Boolean cond)
196 {
197 	return cond ? TOK_TRUE : TOK_FALSE;
198 }
199 
200 /* Push back the most recent token read. We only need one level of this. */
201 static void
202 CondParser_PushBack(CondParser *par, Token t)
203 {
204 	assert(par->curr == TOK_NONE);
205 	assert(t != TOK_NONE);
206 
207 	par->curr = t;
208 }
209 
210 static void
211 CondParser_SkipWhitespace(CondParser *par)
212 {
213 	cpp_skip_whitespace(&par->p);
214 }
215 
216 /*
217  * Parse the argument of a built-in function.
218  *
219  * Arguments:
220  *	*pp initially points at the '(',
221  *	upon successful return it points right after the ')'.
222  *
223  *	*out_arg receives the argument as string.
224  *
225  *	func says whether the argument belongs to an actual function, or
226  *	whether the parsed argument is passed to the default function.
227  *
228  * Return the length of the argument, or 0 on error.
229  */
230 static size_t
231 ParseFuncArg(CondParser *par, const char **pp, Boolean doEval, const char *func,
232 	     char **out_arg)
233 {
234 	const char *p = *pp;
235 	Buffer argBuf;
236 	int paren_depth;
237 	size_t argLen;
238 
239 	if (func != NULL)
240 		p++;		/* Skip opening '(' - verified by caller */
241 
242 	if (*p == '\0') {
243 		*out_arg = NULL; /* Missing closing parenthesis: */
244 		return 0;	/* .if defined( */
245 	}
246 
247 	cpp_skip_hspace(&p);
248 
249 	Buf_InitSize(&argBuf, 16);
250 
251 	paren_depth = 0;
252 	for (;;) {
253 		char ch = *p;
254 		if (ch == '\0' || ch == ' ' || ch == '\t')
255 			break;
256 		if ((ch == '&' || ch == '|') && paren_depth == 0)
257 			break;
258 		if (*p == '$') {
259 			/*
260 			 * Parse the variable expression and install it as
261 			 * part of the argument if it's valid. We tell
262 			 * Var_Parse to complain on an undefined variable,
263 			 * (XXX: but Var_Parse ignores that request)
264 			 * so we don't need to do it. Nor do we return an
265 			 * error, though perhaps we should.
266 			 */
267 			VarEvalFlags eflags = doEval
268 			    ? VARE_WANTRES | VARE_UNDEFERR
269 			    : VARE_NONE;
270 			FStr nestedVal;
271 			(void)Var_Parse(&p, SCOPE_CMDLINE, eflags, &nestedVal);
272 			/* TODO: handle errors */
273 			Buf_AddStr(&argBuf, nestedVal.str);
274 			FStr_Done(&nestedVal);
275 			continue;
276 		}
277 		if (ch == '(')
278 			paren_depth++;
279 		else if (ch == ')' && --paren_depth < 0)
280 			break;
281 		Buf_AddByte(&argBuf, *p);
282 		p++;
283 	}
284 
285 	argLen = argBuf.len;
286 	*out_arg = Buf_DoneData(&argBuf);
287 
288 	cpp_skip_hspace(&p);
289 
290 	if (func != NULL && *p++ != ')') {
291 		Parse_Error(PARSE_FATAL,
292 		    "Missing closing parenthesis for %s()", func);
293 		par->printedError = TRUE;
294 		return 0;
295 	}
296 
297 	*pp = p;
298 	return argLen;
299 }
300 
301 /* Test whether the given variable is defined. */
302 /*ARGSUSED*/
303 static Boolean
304 FuncDefined(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
305 {
306 	FStr value = Var_Value(SCOPE_CMDLINE, arg);
307 	Boolean result = value.str != NULL;
308 	FStr_Done(&value);
309 	return result;
310 }
311 
312 /* See if the given target is being made. */
313 /*ARGSUSED*/
314 static Boolean
315 FuncMake(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
316 {
317 	StringListNode *ln;
318 
319 	for (ln = opts.create.first; ln != NULL; ln = ln->next)
320 		if (Str_Match(ln->datum, arg))
321 			return TRUE;
322 	return FALSE;
323 }
324 
325 /* See if the given file exists. */
326 /*ARGSUSED*/
327 static Boolean
328 FuncExists(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
329 {
330 	Boolean result;
331 	char *path;
332 
333 	path = Dir_FindFile(arg, &dirSearchPath);
334 	DEBUG2(COND, "exists(%s) result is \"%s\"\n",
335 	       arg, path != NULL ? path : "");
336 	result = path != NULL;
337 	free(path);
338 	return result;
339 }
340 
341 /* See if the given node exists and is an actual target. */
342 /*ARGSUSED*/
343 static Boolean
344 FuncTarget(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
345 {
346 	GNode *gn = Targ_FindNode(arg);
347 	return gn != NULL && GNode_IsTarget(gn);
348 }
349 
350 /*
351  * See if the given node exists and is an actual target with commands
352  * associated with it.
353  */
354 /*ARGSUSED*/
355 static Boolean
356 FuncCommands(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
357 {
358 	GNode *gn = Targ_FindNode(arg);
359 	return gn != NULL && GNode_IsTarget(gn) && !Lst_IsEmpty(&gn->commands);
360 }
361 
362 /*
363  * Convert the given number into a double.
364  * We try a base 10 or 16 integer conversion first, if that fails
365  * then we try a floating point conversion instead.
366  *
367  * Results:
368  *	Returns TRUE if the conversion succeeded.
369  *	Sets 'out_value' to the converted number.
370  */
371 static Boolean
372 TryParseNumber(const char *str, double *out_value)
373 {
374 	char *end;
375 	unsigned long ul_val;
376 	double dbl_val;
377 
378 	errno = 0;
379 	if (str[0] == '\0') {	/* XXX: why is an empty string a number? */
380 		*out_value = 0.0;
381 		return TRUE;
382 	}
383 
384 	ul_val = strtoul(str, &end, str[1] == 'x' ? 16 : 10);
385 	if (*end == '\0' && errno != ERANGE) {
386 		*out_value = str[0] == '-' ? -(double)-ul_val : (double)ul_val;
387 		return TRUE;
388 	}
389 
390 	if (*end != '\0' && *end != '.' && *end != 'e' && *end != 'E')
391 		return FALSE;	/* skip the expensive strtod call */
392 	dbl_val = strtod(str, &end);
393 	if (*end != '\0')
394 		return FALSE;
395 
396 	*out_value = dbl_val;
397 	return TRUE;
398 }
399 
400 static Boolean
401 is_separator(char ch)
402 {
403 	return ch == '\0' || ch_isspace(ch) || strchr("!=><)", ch) != NULL;
404 }
405 
406 /*
407  * In a quoted or unquoted string literal or a number, parse a variable
408  * expression.
409  *
410  * Example: .if x${CENTER}y == "${PREFIX}${SUFFIX}" || 0x${HEX}
411  */
412 static Boolean
413 CondParser_StringExpr(CondParser *par, const char *start,
414 		      Boolean const doEval, Boolean const quoted,
415 		      Buffer *buf, FStr *const inout_str)
416 {
417 	VarEvalFlags eflags;
418 	const char *nested_p;
419 	Boolean atStart;
420 	VarParseResult parseResult;
421 
422 	/* if we are in quotes, an undefined variable is ok */
423 	eflags = doEval && !quoted ? VARE_WANTRES | VARE_UNDEFERR
424 	    : doEval ? VARE_WANTRES
425 	    : VARE_NONE;
426 
427 	nested_p = par->p;
428 	atStart = nested_p == start;
429 	parseResult = Var_Parse(&nested_p, SCOPE_CMDLINE, eflags, inout_str);
430 	/* TODO: handle errors */
431 	if (inout_str->str == var_Error) {
432 		if (parseResult == VPR_ERR) {
433 			/*
434 			 * FIXME: Even if an error occurs, there is no
435 			 *  guarantee that it is reported.
436 			 *
437 			 * See cond-token-plain.mk $$$$$$$$.
438 			 */
439 			par->printedError = TRUE;
440 		}
441 		/*
442 		 * XXX: Can there be any situation in which a returned
443 		 * var_Error needs to be freed?
444 		 */
445 		FStr_Done(inout_str);
446 		/*
447 		 * Even if !doEval, we still report syntax errors, which is
448 		 * what getting var_Error back with !doEval means.
449 		 */
450 		*inout_str = FStr_InitRefer(NULL);
451 		return FALSE;
452 	}
453 	par->p = nested_p;
454 
455 	/*
456 	 * If the '$' started the string literal (which means no quotes), and
457 	 * the variable expression is followed by a space, looks like a
458 	 * comparison operator or is the end of the expression, we are done.
459 	 */
460 	if (atStart && is_separator(par->p[0]))
461 		return FALSE;
462 
463 	Buf_AddStr(buf, inout_str->str);
464 	FStr_Done(inout_str);
465 	*inout_str = FStr_InitRefer(NULL); /* not finished yet */
466 	return TRUE;
467 }
468 
469 /*
470  * Parse a string from a variable reference or an optionally quoted
471  * string.  This is called for the lhs and rhs of string comparisons.
472  *
473  * Results:
474  *	Returns the string, absent any quotes, or NULL on error.
475  *	Sets out_quoted if the string was quoted.
476  */
477 static void
478 CondParser_String(CondParser *par, Boolean doEval, Boolean strictLHS,
479 		  FStr *out_str, Boolean *out_quoted)
480 {
481 	Buffer buf;
482 	FStr str;
483 	Boolean quoted;
484 	const char *start;
485 
486 	Buf_Init(&buf);
487 	str = FStr_InitRefer(NULL);
488 	*out_quoted = quoted = par->p[0] == '"';
489 	start = par->p;
490 	if (quoted)
491 		par->p++;
492 
493 	while (par->p[0] != '\0' && str.str == NULL) {
494 		switch (par->p[0]) {
495 		case '\\':
496 			par->p++;
497 			if (par->p[0] != '\0') {
498 				Buf_AddByte(&buf, par->p[0]);
499 				par->p++;
500 			}
501 			continue;
502 		case '"':
503 			par->p++;
504 			if (quoted)
505 				goto got_str;	/* skip the closing quote */
506 			Buf_AddByte(&buf, '"');
507 			continue;
508 		case ')':	/* see is_separator */
509 		case '!':
510 		case '=':
511 		case '>':
512 		case '<':
513 		case ' ':
514 		case '\t':
515 			if (!quoted)
516 				goto got_str;
517 			Buf_AddByte(&buf, par->p[0]);
518 			par->p++;
519 			continue;
520 		case '$':
521 			if (!CondParser_StringExpr(par,
522 			    start, doEval, quoted, &buf, &str))
523 				goto cleanup;
524 			continue;
525 		default:
526 			if (strictLHS && !quoted && *start != '$' &&
527 			    !ch_isdigit(*start)) {
528 				/*
529 				 * The left-hand side must be quoted,
530 				 * a variable reference or a number.
531 				 */
532 				str = FStr_InitRefer(NULL);
533 				goto cleanup;
534 			}
535 			Buf_AddByte(&buf, par->p[0]);
536 			par->p++;
537 			continue;
538 		}
539 	}
540 got_str:
541 	str = FStr_InitOwn(buf.data);
542 cleanup:
543 	Buf_DoneData(&buf);
544 	*out_str = str;
545 }
546 
547 static Boolean
548 If_Eval(const CondParser *par, const char *arg, size_t arglen)
549 {
550 	Boolean res = par->evalBare(arglen, arg);
551 	return par->negateEvalBare ? !res : res;
552 }
553 
554 /*
555  * Evaluate a "comparison without operator", such as in ".if ${VAR}" or
556  * ".if 0".
557  */
558 static Boolean
559 EvalNotEmpty(CondParser *par, const char *value, Boolean quoted)
560 {
561 	double num;
562 
563 	/* For .ifxxx "...", check for non-empty string. */
564 	if (quoted)
565 		return value[0] != '\0';
566 
567 	/* For .ifxxx <number>, compare against zero */
568 	if (TryParseNumber(value, &num))
569 		return num != 0.0;
570 
571 	/* For .if ${...}, check for non-empty string.  This is different from
572 	 * the evaluation function from that .if variant, which would test
573 	 * whether a variable of the given name were defined. */
574 	/* XXX: Whitespace should count as empty, just as in ParseEmptyArg. */
575 	if (par->plain)
576 		return value[0] != '\0';
577 
578 	return If_Eval(par, value, strlen(value));
579 }
580 
581 /* Evaluate a numerical comparison, such as in ".if ${VAR} >= 9". */
582 static Boolean
583 EvalCompareNum(double lhs, ComparisonOp op, double rhs)
584 {
585 	DEBUG3(COND, "lhs = %f, rhs = %f, op = %.2s\n", lhs, rhs, opname[op]);
586 
587 	switch (op) {
588 	case LT:
589 		return lhs < rhs;
590 	case LE:
591 		return lhs <= rhs;
592 	case GT:
593 		return lhs > rhs;
594 	case GE:
595 		return lhs >= rhs;
596 	case NE:
597 		return lhs != rhs;
598 	default:
599 		return lhs == rhs;
600 	}
601 }
602 
603 static Token
604 EvalCompareStr(CondParser *par, const char *lhs,
605 	       ComparisonOp op, const char *rhs)
606 {
607 	if (op != EQ && op != NE) {
608 		Parse_Error(PARSE_FATAL,
609 		    "String comparison operator must be either == or !=");
610 		par->printedError = TRUE;
611 		return TOK_ERROR;
612 	}
613 
614 	DEBUG3(COND, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
615 	    lhs, rhs, opname[op]);
616 	return ToToken((op == EQ) == (strcmp(lhs, rhs) == 0));
617 }
618 
619 /* Evaluate a comparison, such as "${VAR} == 12345". */
620 static Token
621 EvalCompare(CondParser *par, const char *lhs, Boolean lhsQuoted,
622 	    ComparisonOp op, const char *rhs, Boolean rhsQuoted)
623 {
624 	double left, right;
625 
626 	if (!rhsQuoted && !lhsQuoted)
627 		if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
628 			return ToToken(EvalCompareNum(left, op, right));
629 
630 	return EvalCompareStr(par, lhs, op, rhs);
631 }
632 
633 static Boolean
634 CondParser_ComparisonOp(CondParser *par, ComparisonOp *out_op)
635 {
636 	const char *p = par->p;
637 
638 	if (p[0] == '<' && p[1] == '=') {
639 		*out_op = LE;
640 		goto length_2;
641 	} else if (p[0] == '<') {
642 		*out_op = LT;
643 		goto length_1;
644 	} else if (p[0] == '>' && p[1] == '=') {
645 		*out_op = GE;
646 		goto length_2;
647 	} else if (p[0] == '>') {
648 		*out_op = GT;
649 		goto length_1;
650 	} else if (p[0] == '=' && p[1] == '=') {
651 		*out_op = EQ;
652 		goto length_2;
653 	} else if (p[0] == '!' && p[1] == '=') {
654 		*out_op = NE;
655 		goto length_2;
656 	}
657 	return FALSE;
658 
659 length_2:
660 	par->p = p + 2;
661 	return TRUE;
662 length_1:
663 	par->p = p + 1;
664 	return TRUE;
665 }
666 
667 /*
668  * Parse a comparison condition such as:
669  *
670  *	0
671  *	${VAR:Mpattern}
672  *	${VAR} == value
673  *	${VAR:U0} < 12345
674  */
675 static Token
676 CondParser_Comparison(CondParser *par, Boolean doEval)
677 {
678 	Token t = TOK_ERROR;
679 	FStr lhs, rhs;
680 	ComparisonOp op;
681 	Boolean lhsQuoted, rhsQuoted;
682 
683 	/*
684 	 * Parse the variable spec and skip over it, saving its
685 	 * value in lhs.
686 	 */
687 	CondParser_String(par, doEval, lhsStrict, &lhs, &lhsQuoted);
688 	if (lhs.str == NULL)
689 		goto done_lhs;
690 
691 	CondParser_SkipWhitespace(par);
692 
693 	if (!CondParser_ComparisonOp(par, &op)) {
694 		/* Unknown operator, compare against an empty string or 0. */
695 		t = ToToken(doEval && EvalNotEmpty(par, lhs.str, lhsQuoted));
696 		goto done_lhs;
697 	}
698 
699 	CondParser_SkipWhitespace(par);
700 
701 	if (par->p[0] == '\0') {
702 		Parse_Error(PARSE_FATAL,
703 		    "Missing right-hand-side of operator '%s'", opname[op]);
704 		par->printedError = TRUE;
705 		goto done_lhs;
706 	}
707 
708 	CondParser_String(par, doEval, FALSE, &rhs, &rhsQuoted);
709 	if (rhs.str == NULL)
710 		goto done_rhs;
711 
712 	if (!doEval) {
713 		t = TOK_FALSE;
714 		goto done_rhs;
715 	}
716 
717 	t = EvalCompare(par, lhs.str, lhsQuoted, op, rhs.str, rhsQuoted);
718 
719 done_rhs:
720 	FStr_Done(&rhs);
721 done_lhs:
722 	FStr_Done(&lhs);
723 	return t;
724 }
725 
726 /*
727  * The argument to empty() is a variable name, optionally followed by
728  * variable modifiers.
729  */
730 /*ARGSUSED*/
731 static size_t
732 ParseEmptyArg(CondParser *par MAKE_ATTR_UNUSED, const char **pp,
733 	      Boolean doEval, const char *func MAKE_ATTR_UNUSED,
734 	      char **out_arg)
735 {
736 	FStr val;
737 	size_t magic_res;
738 
739 	/* We do all the work here and return the result as the length */
740 	*out_arg = NULL;
741 
742 	(*pp)--;		/* Make (*pp)[1] point to the '('. */
743 	(void)Var_Parse(pp, SCOPE_CMDLINE, doEval ? VARE_WANTRES : VARE_NONE,
744 	    &val);
745 	/* TODO: handle errors */
746 	/* If successful, *pp points beyond the closing ')' now. */
747 
748 	if (val.str == var_Error) {
749 		FStr_Done(&val);
750 		return (size_t)-1;
751 	}
752 
753 	/*
754 	 * A variable is empty when it just contains spaces...
755 	 * 4/15/92, christos
756 	 */
757 	cpp_skip_whitespace(&val.str);
758 
759 	/*
760 	 * For consistency with the other functions we can't generate the
761 	 * true/false here.
762 	 */
763 	magic_res = val.str[0] != '\0' ? 2 : 1;
764 	FStr_Done(&val);
765 	return magic_res;
766 }
767 
768 /*ARGSUSED*/
769 static Boolean
770 FuncEmpty(size_t arglen, const char *arg MAKE_ATTR_UNUSED)
771 {
772 	/* Magic values ahead, see ParseEmptyArg. */
773 	return arglen == 1;
774 }
775 
776 static Boolean
777 CondParser_Func(CondParser *par, Boolean doEval, Token *out_token)
778 {
779 	static const struct fn_def {
780 		const char *fn_name;
781 		size_t fn_name_len;
782 		size_t (*fn_parse)(CondParser *, const char **, Boolean,
783 				   const char *, char **);
784 		Boolean (*fn_eval)(size_t, const char *);
785 	} fns[] = {
786 		{ "defined",  7, ParseFuncArg,  FuncDefined },
787 		{ "make",     4, ParseFuncArg,  FuncMake },
788 		{ "exists",   6, ParseFuncArg,  FuncExists },
789 		{ "empty",    5, ParseEmptyArg, FuncEmpty },
790 		{ "target",   6, ParseFuncArg,  FuncTarget },
791 		{ "commands", 8, ParseFuncArg,  FuncCommands }
792 	};
793 	const struct fn_def *fn;
794 	char *arg = NULL;
795 	size_t arglen;
796 	const char *cp = par->p;
797 	const struct fn_def *fns_end = fns + sizeof fns / sizeof fns[0];
798 
799 	for (fn = fns; fn != fns_end; fn++) {
800 		if (!is_token(cp, fn->fn_name, fn->fn_name_len))
801 			continue;
802 
803 		cp += fn->fn_name_len;
804 		cpp_skip_whitespace(&cp);
805 		if (*cp != '(')
806 			break;
807 
808 		arglen = fn->fn_parse(par, &cp, doEval, fn->fn_name, &arg);
809 		if (arglen == 0 || arglen == (size_t)-1) {
810 			par->p = cp;
811 			*out_token = arglen == 0 ? TOK_FALSE : TOK_ERROR;
812 			return TRUE;
813 		}
814 
815 		/* Evaluate the argument using the required function. */
816 		*out_token = ToToken(!doEval || fn->fn_eval(arglen, arg));
817 		free(arg);
818 		par->p = cp;
819 		return TRUE;
820 	}
821 
822 	return FALSE;
823 }
824 
825 /*
826  * Parse a function call, a number, a variable expression or a string
827  * literal.
828  */
829 static Token
830 CondParser_LeafToken(CondParser *par, Boolean doEval)
831 {
832 	Token t;
833 	char *arg = NULL;
834 	size_t arglen;
835 	const char *cp;
836 	const char *cp1;
837 
838 	if (CondParser_Func(par, doEval, &t))
839 		return t;
840 
841 	/* Push anything numeric through the compare expression */
842 	cp = par->p;
843 	if (ch_isdigit(cp[0]) || cp[0] == '-' || cp[0] == '+')
844 		return CondParser_Comparison(par, doEval);
845 
846 	/*
847 	 * Most likely we have a naked token to apply the default function to.
848 	 * However ".if a == b" gets here when the "a" is unquoted and doesn't
849 	 * start with a '$'. This surprises people.
850 	 * If what follows the function argument is a '=' or '!' then the
851 	 * syntax would be invalid if we did "defined(a)" - so instead treat
852 	 * as an expression.
853 	 */
854 	arglen = ParseFuncArg(par, &cp, doEval, NULL, &arg);
855 	cp1 = cp;
856 	cpp_skip_whitespace(&cp1);
857 	if (*cp1 == '=' || *cp1 == '!')
858 		return CondParser_Comparison(par, doEval);
859 	par->p = cp;
860 
861 	/*
862 	 * Evaluate the argument using the default function.
863 	 * This path always treats .if as .ifdef. To get here, the character
864 	 * after .if must have been taken literally, so the argument cannot
865 	 * be empty - even if it contained a variable expansion.
866 	 */
867 	t = ToToken(!doEval || If_Eval(par, arg, arglen));
868 	free(arg);
869 	return t;
870 }
871 
872 /* Return the next token or comparison result from the parser. */
873 static Token
874 CondParser_Token(CondParser *par, Boolean doEval)
875 {
876 	Token t;
877 
878 	t = par->curr;
879 	if (t != TOK_NONE) {
880 		par->curr = TOK_NONE;
881 		return t;
882 	}
883 
884 	cpp_skip_hspace(&par->p);
885 
886 	switch (par->p[0]) {
887 
888 	case '(':
889 		par->p++;
890 		return TOK_LPAREN;
891 
892 	case ')':
893 		par->p++;
894 		return TOK_RPAREN;
895 
896 	case '|':
897 		par->p++;
898 		if (par->p[0] == '|')
899 			par->p++;
900 		else if (opts.strict) {
901 			Parse_Error(PARSE_FATAL, "Unknown operator '|'");
902 			par->printedError = TRUE;
903 			return TOK_ERROR;
904 		}
905 		return TOK_OR;
906 
907 	case '&':
908 		par->p++;
909 		if (par->p[0] == '&')
910 			par->p++;
911 		else if (opts.strict) {
912 			Parse_Error(PARSE_FATAL, "Unknown operator '&'");
913 			par->printedError = TRUE;
914 			return TOK_ERROR;
915 		}
916 		return TOK_AND;
917 
918 	case '!':
919 		par->p++;
920 		return TOK_NOT;
921 
922 	case '#':		/* XXX: see unit-tests/cond-token-plain.mk */
923 	case '\n':		/* XXX: why should this end the condition? */
924 		/* Probably obsolete now, from 1993-03-21. */
925 	case '\0':
926 		return TOK_EOF;
927 
928 	case '"':
929 	case '$':
930 		return CondParser_Comparison(par, doEval);
931 
932 	default:
933 		return CondParser_LeafToken(par, doEval);
934 	}
935 }
936 
937 /*
938  * Term -> '(' Or ')'
939  * Term -> '!' Term
940  * Term -> Leaf Operator Leaf
941  * Term -> Leaf
942  */
943 static CondResult
944 CondParser_Term(CondParser *par, Boolean doEval)
945 {
946 	CondResult res;
947 	Token t;
948 
949 	t = CondParser_Token(par, doEval);
950 	if (t == TOK_TRUE)
951 		return CR_TRUE;
952 	if (t == TOK_FALSE)
953 		return CR_FALSE;
954 
955 	if (t == TOK_LPAREN) {
956 		res = CondParser_Or(par, doEval);
957 		if (res == CR_ERROR)
958 			return CR_ERROR;
959 		if (CondParser_Token(par, doEval) != TOK_RPAREN)
960 			return CR_ERROR;
961 		return res;
962 	}
963 
964 	if (t == TOK_NOT) {
965 		res = CondParser_Term(par, doEval);
966 		if (res == CR_TRUE)
967 			res = CR_FALSE;
968 		else if (res == CR_FALSE)
969 			res = CR_TRUE;
970 		return res;
971 	}
972 
973 	return CR_ERROR;
974 }
975 
976 /*
977  * And -> Term '&&' And
978  * And -> Term
979  */
980 static CondResult
981 CondParser_And(CondParser *par, Boolean doEval)
982 {
983 	CondResult res;
984 	Token op;
985 
986 	res = CondParser_Term(par, doEval);
987 	if (res == CR_ERROR)
988 		return CR_ERROR;
989 
990 	op = CondParser_Token(par, doEval);
991 	if (op == TOK_AND) {
992 		if (res == CR_TRUE)
993 			return CondParser_And(par, doEval);
994 		if (CondParser_And(par, FALSE) == CR_ERROR)
995 			return CR_ERROR;
996 		return res;
997 	}
998 
999 	CondParser_PushBack(par, op);
1000 	return res;
1001 }
1002 
1003 /*
1004  * Or -> And '||' Or
1005  * Or -> And
1006  */
1007 static CondResult
1008 CondParser_Or(CondParser *par, Boolean doEval)
1009 {
1010 	CondResult res;
1011 	Token op;
1012 
1013 	res = CondParser_And(par, doEval);
1014 	if (res == CR_ERROR)
1015 		return CR_ERROR;
1016 
1017 	op = CondParser_Token(par, doEval);
1018 	if (op == TOK_OR) {
1019 		if (res == CR_FALSE)
1020 			return CondParser_Or(par, doEval);
1021 		if (CondParser_Or(par, FALSE) == CR_ERROR)
1022 			return CR_ERROR;
1023 		return res;
1024 	}
1025 
1026 	CondParser_PushBack(par, op);
1027 	return res;
1028 }
1029 
1030 static CondEvalResult
1031 CondParser_Eval(CondParser *par, Boolean *out_value)
1032 {
1033 	CondResult res;
1034 
1035 	DEBUG1(COND, "CondParser_Eval: %s\n", par->p);
1036 
1037 	res = CondParser_Or(par, TRUE);
1038 	if (res == CR_ERROR)
1039 		return COND_INVALID;
1040 
1041 	if (CondParser_Token(par, FALSE) != TOK_EOF)
1042 		return COND_INVALID;
1043 
1044 	*out_value = res == CR_TRUE;
1045 	return COND_PARSE;
1046 }
1047 
1048 /*
1049  * Evaluate the condition, including any side effects from the variable
1050  * expressions in the condition. The condition consists of &&, ||, !,
1051  * function(arg), comparisons and parenthetical groupings thereof.
1052  *
1053  * Results:
1054  *	COND_PARSE	if the condition was valid grammatically
1055  *	COND_INVALID	if not a valid conditional.
1056  *
1057  *	(*value) is set to the boolean value of the condition
1058  */
1059 static CondEvalResult
1060 CondEvalExpression(const char *cond, Boolean *out_value, Boolean plain,
1061 		   Boolean (*evalBare)(size_t, const char *), Boolean negate,
1062 		   Boolean eprint, Boolean strictLHS)
1063 {
1064 	CondParser par;
1065 	CondEvalResult rval;
1066 
1067 	lhsStrict = strictLHS;
1068 
1069 	cpp_skip_hspace(&cond);
1070 
1071 	par.plain = plain;
1072 	par.evalBare = evalBare;
1073 	par.negateEvalBare = negate;
1074 	par.p = cond;
1075 	par.curr = TOK_NONE;
1076 	par.printedError = FALSE;
1077 
1078 	rval = CondParser_Eval(&par, out_value);
1079 
1080 	if (rval == COND_INVALID && eprint && !par.printedError)
1081 		Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", cond);
1082 
1083 	return rval;
1084 }
1085 
1086 /*
1087  * Evaluate a condition in a :? modifier, such as
1088  * ${"${VAR}" == value:?yes:no}.
1089  */
1090 CondEvalResult
1091 Cond_EvalCondition(const char *cond, Boolean *out_value)
1092 {
1093 	return CondEvalExpression(cond, out_value, TRUE,
1094 	    FuncDefined, FALSE, FALSE, FALSE);
1095 }
1096 
1097 static Boolean
1098 IsEndif(const char *p)
1099 {
1100 	return p[0] == 'e' && p[1] == 'n' && p[2] == 'd' &&
1101 	       p[3] == 'i' && p[4] == 'f' && !ch_isalpha(p[5]);
1102 }
1103 
1104 static Boolean
1105 DetermineKindOfConditional(const char **pp, Boolean *out_plain,
1106 			   Boolean (**out_evalBare)(size_t, const char *),
1107 			   Boolean *out_negate)
1108 {
1109 	const char *p = *pp;
1110 
1111 	p += 2;
1112 	*out_plain = FALSE;
1113 	*out_evalBare = FuncDefined;
1114 	*out_negate = FALSE;
1115 	if (*p == 'n') {
1116 		p++;
1117 		*out_negate = TRUE;
1118 	}
1119 	if (is_token(p, "def", 3)) {		/* .ifdef and .ifndef */
1120 		p += 3;
1121 	} else if (is_token(p, "make", 4)) {	/* .ifmake and .ifnmake */
1122 		p += 4;
1123 		*out_evalBare = FuncMake;
1124 	} else if (is_token(p, "", 0) && !*out_negate) { /* plain .if */
1125 		*out_plain = TRUE;
1126 	} else {
1127 		/*
1128 		 * TODO: Add error message about unknown directive,
1129 		 * since there is no other known directive that starts
1130 		 * with 'el' or 'if'.
1131 		 *
1132 		 * Example: .elifx 123
1133 		 */
1134 		return FALSE;
1135 	}
1136 
1137 	*pp = p;
1138 	return TRUE;
1139 }
1140 
1141 /*
1142  * Evaluate the conditional directive in the line, which is one of:
1143  *
1144  *	.if <cond>
1145  *	.ifmake <cond>
1146  *	.ifnmake <cond>
1147  *	.ifdef <cond>
1148  *	.ifndef <cond>
1149  *	.elif <cond>
1150  *	.elifmake <cond>
1151  *	.elifnmake <cond>
1152  *	.elifdef <cond>
1153  *	.elifndef <cond>
1154  *	.else
1155  *	.endif
1156  *
1157  * In these directives, <cond> consists of &&, ||, !, function(arg),
1158  * comparisons, expressions, bare words, numbers and strings, and
1159  * parenthetical groupings thereof.
1160  *
1161  * Results:
1162  *	COND_PARSE	to continue parsing the lines that follow the
1163  *			conditional (when <cond> evaluates to TRUE)
1164  *	COND_SKIP	to skip the lines after the conditional
1165  *			(when <cond> evaluates to FALSE, or when a previous
1166  *			branch has already been taken)
1167  *	COND_INVALID	if the conditional was not valid, either because of
1168  *			a syntax error or because some variable was undefined
1169  *			or because the condition could not be evaluated
1170  */
1171 CondEvalResult
1172 Cond_EvalLine(const char *line)
1173 {
1174 	typedef enum IfState {
1175 
1176 		/* None of the previous <cond> evaluated to TRUE. */
1177 		IFS_INITIAL	= 0,
1178 
1179 		/* The previous <cond> evaluated to TRUE.
1180 		 * The lines following this condition are interpreted. */
1181 		IFS_ACTIVE	= 1 << 0,
1182 
1183 		/* The previous directive was an '.else'. */
1184 		IFS_SEEN_ELSE	= 1 << 1,
1185 
1186 		/* One of the previous <cond> evaluated to TRUE. */
1187 		IFS_WAS_ACTIVE	= 1 << 2
1188 
1189 	} IfState;
1190 
1191 	static enum IfState *cond_states = NULL;
1192 	static unsigned int cond_states_cap = 128;
1193 
1194 	Boolean plain;
1195 	Boolean (*evalBare)(size_t, const char *);
1196 	Boolean negate;
1197 	Boolean isElif;
1198 	Boolean value;
1199 	IfState state;
1200 	const char *p = line;
1201 
1202 	if (cond_states == NULL) {
1203 		cond_states = bmake_malloc(
1204 		    cond_states_cap * sizeof *cond_states);
1205 		cond_states[0] = IFS_ACTIVE;
1206 	}
1207 
1208 	p++;			/* skip the leading '.' */
1209 	cpp_skip_hspace(&p);
1210 
1211 	if (IsEndif(p)) {	/* It is an '.endif'. */
1212 		if (p[5] != '\0') {
1213 			Parse_Error(PARSE_FATAL,
1214 			    "The .endif directive does not take arguments.");
1215 		}
1216 
1217 		if (cond_depth == cond_min_depth) {
1218 			Parse_Error(PARSE_FATAL, "if-less endif");
1219 			return COND_PARSE;
1220 		}
1221 
1222 		/* Return state for previous conditional */
1223 		cond_depth--;
1224 		return cond_states[cond_depth] & IFS_ACTIVE
1225 		    ? COND_PARSE : COND_SKIP;
1226 	}
1227 
1228 	/* Parse the name of the directive, such as 'if', 'elif', 'endif'. */
1229 	if (p[0] == 'e') {
1230 		if (p[1] != 'l') {
1231 			/*
1232 			 * Unknown directive.  It might still be a
1233 			 * transformation rule like '.elisp.scm',
1234 			 * therefore no error message here.
1235 			 */
1236 			return COND_INVALID;
1237 		}
1238 
1239 		/* Quite likely this is 'else' or 'elif' */
1240 		p += 2;
1241 		if (is_token(p, "se", 2)) {	/* It is an 'else'. */
1242 
1243 			if (p[2] != '\0')
1244 				Parse_Error(PARSE_FATAL,
1245 					    "The .else directive "
1246 					    "does not take arguments.");
1247 
1248 			if (cond_depth == cond_min_depth) {
1249 				Parse_Error(PARSE_FATAL, "if-less else");
1250 				return COND_PARSE;
1251 			}
1252 
1253 			state = cond_states[cond_depth];
1254 			if (state == IFS_INITIAL) {
1255 				state = IFS_ACTIVE | IFS_SEEN_ELSE;
1256 			} else {
1257 				if (state & IFS_SEEN_ELSE)
1258 					Parse_Error(PARSE_WARNING,
1259 						    "extra else");
1260 				state = IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1261 			}
1262 			cond_states[cond_depth] = state;
1263 
1264 			return state & IFS_ACTIVE ? COND_PARSE : COND_SKIP;
1265 		}
1266 		/* Assume for now it is an elif */
1267 		isElif = TRUE;
1268 	} else
1269 		isElif = FALSE;
1270 
1271 	if (p[0] != 'i' || p[1] != 'f') {
1272 		/*
1273 		 * Unknown directive.  It might still be a transformation rule
1274 		 * like '.elisp.scm', therefore no error message here.
1275 		 */
1276 		return COND_INVALID;	/* Not an ifxxx or elifxxx line */
1277 	}
1278 
1279 	if (!DetermineKindOfConditional(&p, &plain, &evalBare, &negate))
1280 		return COND_INVALID;
1281 
1282 	if (isElif) {
1283 		if (cond_depth == cond_min_depth) {
1284 			Parse_Error(PARSE_FATAL, "if-less elif");
1285 			return COND_PARSE;
1286 		}
1287 		state = cond_states[cond_depth];
1288 		if (state & IFS_SEEN_ELSE) {
1289 			Parse_Error(PARSE_WARNING, "extra elif");
1290 			cond_states[cond_depth] =
1291 			    IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1292 			return COND_SKIP;
1293 		}
1294 		if (state != IFS_INITIAL) {
1295 			cond_states[cond_depth] = IFS_WAS_ACTIVE;
1296 			return COND_SKIP;
1297 		}
1298 	} else {
1299 		/* Normal .if */
1300 		if (cond_depth + 1 >= cond_states_cap) {
1301 			/*
1302 			 * This is rare, but not impossible.
1303 			 * In meta mode, dirdeps.mk (only runs at level 0)
1304 			 * can need more than the default.
1305 			 */
1306 			cond_states_cap += 32;
1307 			cond_states = bmake_realloc(cond_states,
1308 						    cond_states_cap *
1309 						    sizeof *cond_states);
1310 		}
1311 		state = cond_states[cond_depth];
1312 		cond_depth++;
1313 		if (!(state & IFS_ACTIVE)) {
1314 			/*
1315 			 * If we aren't parsing the data,
1316 			 * treat as always false.
1317 			 */
1318 			cond_states[cond_depth] = IFS_WAS_ACTIVE;
1319 			return COND_SKIP;
1320 		}
1321 	}
1322 
1323 	/* And evaluate the conditional expression */
1324 	if (CondEvalExpression(p, &value, plain, evalBare, negate,
1325 	    TRUE, TRUE) == COND_INVALID) {
1326 		/* Syntax error in conditional, error message already output. */
1327 		/* Skip everything to matching .endif */
1328 		/* XXX: An extra '.else' is not detected in this case. */
1329 		cond_states[cond_depth] = IFS_WAS_ACTIVE;
1330 		return COND_SKIP;
1331 	}
1332 
1333 	if (!value) {
1334 		cond_states[cond_depth] = IFS_INITIAL;
1335 		return COND_SKIP;
1336 	}
1337 	cond_states[cond_depth] = IFS_ACTIVE;
1338 	return COND_PARSE;
1339 }
1340 
1341 void
1342 Cond_restore_depth(unsigned int saved_depth)
1343 {
1344 	unsigned int open_conds = cond_depth - cond_min_depth;
1345 
1346 	if (open_conds != 0 || saved_depth > cond_depth) {
1347 		Parse_Error(PARSE_FATAL, "%u open conditional%s",
1348 			    open_conds, open_conds == 1 ? "" : "s");
1349 		cond_depth = cond_min_depth;
1350 	}
1351 
1352 	cond_min_depth = saved_depth;
1353 }
1354 
1355 unsigned int
1356 Cond_save_depth(void)
1357 {
1358 	unsigned int depth = cond_min_depth;
1359 
1360 	cond_min_depth = cond_depth;
1361 	return depth;
1362 }
1363