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