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