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