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