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