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