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