1 /* $NetBSD: cond.c,v 1.214 2020/11/13 09:01:59 rillig Exp $ */
4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
36 * Copyright (c) 1988, 1989 by Adam de Boor
37 * Copyright (c) 1989 by Berkeley Softworks
38 * All rights reserved.
40 * This code is derived from software contributed to Berkeley by
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
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.
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
72 /* Handling of conditionals in a makefile.
75 * Cond_EvalLine Evaluate the conditional directive, such as
76 * '.if <cond>', '.elifnmake <cond>', '.else', '.endif'.
79 * Evaluate the conditional, which is either the argument
80 * of one of the .if directives or the condition in a
81 * ':?then:else' variable modifier.
85 * Save and restore the nesting of the conditions, at
86 * the start and end of including another makefile, to
87 * ensure that in each makefile the conditional
88 * directives are well-balanced.
96 /* "@(#)cond.c 8.2 (Berkeley) 1/2/94" */
97 MAKE_RCSID("$NetBSD: cond.c,v 1.214 2020/11/13 09:01:59 rillig Exp $");
100 * The parsing of conditional expressions is based on this grammar:
105 * T -> defined(variable)
108 * T -> empty(varspec)
110 * T -> commands(name)
112 * T -> $(varspec) op value
113 * T -> $(varspec) == "string"
114 * T -> $(varspec) != "string"
118 * op -> == | != | > | < | >= | <=
120 * 'symbol' is some other symbol to which the default function is applied.
122 * The tokens are scanned by CondToken, which returns:
123 * TOK_AND for '&' or '&&'
124 * TOK_OR for '|' or '||'
128 * Other terminal symbols are evaluated using either the default function or
129 * the function given in the terminal, they return either TOK_TRUE or
132 * TOK_FALSE is 0 and TOK_TRUE 1 so we can directly assign C comparisons.
134 * All non-terminal functions (CondParser_Expr, CondParser_Factor and
135 * CondParser_Term) return either TOK_FALSE, TOK_TRUE, or TOK_ERROR on error.
138 TOK_FALSE = 0, TOK_TRUE = 1, TOK_AND, TOK_OR, TOK_NOT,
139 TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
142 typedef struct CondParser {
143 const struct If *if_info; /* Info for current statement */
144 const char *p; /* The remaining condition to parse */
145 Token curr; /* Single push-back token used in parsing */
147 /* Whether an error message has already been printed for this condition.
148 * The first available error message is usually the most specific one,
149 * therefore it makes sense to suppress the standard "Malformed
150 * conditional" message. */
151 Boolean printedError;
154 static Token CondParser_Expr(CondParser *par, Boolean);
156 static unsigned int cond_depth = 0; /* current .if nesting level */
157 static unsigned int cond_min_depth = 0; /* depth at makefile open */
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.
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 at that point we cannot tell if
167 * it was a variable reference or not.
169 static Boolean lhsStrict;
172 is_token(const char *str, const char *tok, size_t len)
174 return strncmp(str, tok, len) == 0 && !ch_isalpha(str[len]);
178 ToToken(Boolean cond)
180 return cond ? TOK_TRUE : TOK_FALSE;
183 /* Push back the most recent token read. We only need one level of this. */
185 CondParser_PushBack(CondParser *par, Token t)
187 assert(par->curr == TOK_NONE);
188 assert(t != TOK_NONE);
194 CondParser_SkipWhitespace(CondParser *par)
196 cpp_skip_whitespace(&par->p);
199 /* Parse the argument of a built-in function.
202 * *pp initially points at the '(',
203 * upon successful return it points right after the ')'.
205 * *out_arg receives the argument as string.
207 * func says whether the argument belongs to an actual function, or
208 * whether the parsed argument is passed to the default function.
210 * Return the length of the argument, or 0 on error. */
212 ParseFuncArg(const char **pp, Boolean doEval, const char *func,
220 p++; /* Skip opening '(' - verified by caller */
223 *out_arg = NULL; /* Missing closing parenthesis: */
224 return 0; /* .if defined( */
229 Buf_InitSize(&argBuf, 16);
234 if (ch == '\0' || ch == ' ' || ch == '\t')
236 if ((ch == '&' || ch == '|') && paren_depth == 0)
240 * Parse the variable spec and install it as part of the argument
241 * if it's valid. We tell Var_Parse to complain on an undefined
242 * variable, so we don't need to do it. Nor do we return an error,
243 * though perhaps we should...
245 void *nestedVal_freeIt;
246 VarEvalFlags eflags = doEval ? VARE_WANTRES | VARE_UNDEFERR
248 const char *nestedVal;
249 (void)Var_Parse(&p, VAR_CMDLINE, eflags, &nestedVal,
251 /* TODO: handle errors */
252 Buf_AddStr(&argBuf, nestedVal);
253 free(nestedVal_freeIt);
258 else if (ch == ')' && --paren_depth < 0)
260 Buf_AddByte(&argBuf, *p);
264 *out_arg = Buf_GetAll(&argBuf, &argLen);
265 Buf_Destroy(&argBuf, FALSE);
269 if (func != NULL && *p++ != ')') {
270 Parse_Error(PARSE_WARNING, "Missing closing parenthesis for %s()",
272 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
280 /* Test whether the given variable is defined. */
282 FuncDefined(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
285 Boolean result = Var_Value(arg, VAR_CMDLINE, &freeIt) != NULL;
290 /* See if the given target is being made. */
292 FuncMake(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
296 for (ln = opts.create->first; ln != NULL; ln = ln->next)
297 if (Str_Match(ln->datum, arg))
302 /* See if the given file exists. */
304 FuncExists(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
309 path = Dir_FindFile(arg, dirSearchPath);
310 DEBUG2(COND, "exists(%s) result is \"%s\"\n",
311 arg, path != NULL ? path : "");
312 result = path != NULL;
317 /* See if the given node exists and is an actual target. */
319 FuncTarget(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
321 GNode *gn = Targ_FindNode(arg);
322 return gn != NULL && GNode_IsTarget(gn);
325 /* See if the given node exists and is an actual target with commands
326 * associated with it. */
328 FuncCommands(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
330 GNode *gn = Targ_FindNode(arg);
331 return gn != NULL && GNode_IsTarget(gn) && !Lst_IsEmpty(gn->commands);
335 * Convert the given number into a double.
336 * We try a base 10 or 16 integer conversion first, if that fails
337 * then we try a floating point conversion instead.
340 * Returns TRUE if the conversion succeeded.
341 * Sets 'out_value' to the converted number.
344 TryParseNumber(const char *str, double *out_value)
347 unsigned long ul_val;
351 if (str[0] == '\0') { /* XXX: why is an empty string a number? */
356 ul_val = strtoul(str, &end, str[1] == 'x' ? 16 : 10);
357 if (*end == '\0' && errno != ERANGE) {
358 *out_value = str[0] == '-' ? -(double)-ul_val : (double)ul_val;
362 if (*end != '\0' && *end != '.' && *end != 'e' && *end != 'E')
363 return FALSE; /* skip the expensive strtod call */
364 dbl_val = strtod(str, &end);
368 *out_value = dbl_val;
373 is_separator(char ch)
375 return ch == '\0' || ch_isspace(ch) || strchr("!=><)", ch) != NULL;
379 * Parse a string from a variable reference or an optionally quoted
380 * string. This is called for the lhs and rhs of string comparisons.
383 * Returns the string, absent any quotes, or NULL on error.
384 * Sets out_quoted if the string was quoted.
387 /* coverity:[+alloc : arg-*4] */
389 CondParser_String(CondParser *par, Boolean doEval, Boolean strictLHS,
390 Boolean *out_quoted, void **out_freeIt)
395 const char *nested_p;
399 VarParseResult parseResult;
404 *out_quoted = quoted = par->p[0] == '"';
408 while (par->p[0] != '\0' && str == NULL) {
412 if (par->p[0] != '\0') {
413 Buf_AddByte(&buf, par->p[0]);
419 par->p++; /* skip the closing quote */
422 Buf_AddByte(&buf, par->p[0]); /* likely? */
425 case ')': /* see is_separator */
434 Buf_AddByte(&buf, par->p[0]);
438 /* if we are in quotes, an undefined variable is ok */
439 eflags = doEval && !quoted ? VARE_WANTRES | VARE_UNDEFERR :
440 doEval ? VARE_WANTRES :
444 atStart = nested_p == start;
445 parseResult = Var_Parse(&nested_p, VAR_CMDLINE, eflags, &str,
447 /* TODO: handle errors */
448 if (str == var_Error) {
449 if (parseResult & VPR_ANY_MSG)
450 par->printedError = TRUE;
451 if (*out_freeIt != NULL) {
452 /* XXX: Can there be any situation in which a returned
453 * var_Error requires freeIt? */
458 * Even if !doEval, we still report syntax errors, which
459 * is what getting var_Error back with !doEval means.
467 * If the '$' started the string literal (which means no quotes),
468 * and the variable expression is followed by a space, looks like
469 * a comparison operator or is the end of the expression, we are
472 if (atStart && is_separator(par->p[0]))
475 Buf_AddStr(&buf, str);
480 str = NULL; /* not finished yet */
483 if (strictLHS && !quoted && *start != '$' && !ch_isdigit(*start)) {
484 /* lhs must be quoted, a variable reference or number */
488 Buf_AddByte(&buf, par->p[0]);
494 *out_freeIt = Buf_GetAll(&buf, NULL);
497 Buf_Destroy(&buf, FALSE);
502 const char *form; /* Form of if */
503 size_t formlen; /* Length of form */
504 Boolean doNot; /* TRUE if default function should be negated */
505 Boolean (*defProc)(size_t, const char *); /* Default function to apply */
508 /* The different forms of .if directives. */
509 static const struct If ifs[] = {
510 { "def", 3, FALSE, FuncDefined },
511 { "ndef", 4, TRUE, FuncDefined },
512 { "make", 4, FALSE, FuncMake },
513 { "nmake", 5, TRUE, FuncMake },
514 { "", 0, FALSE, FuncDefined },
515 { NULL, 0, FALSE, NULL }
517 enum { PLAIN_IF_INDEX = 4 };
520 If_Eval(const struct If *if_info, const char *arg, size_t arglen)
522 Boolean res = if_info->defProc(arglen, arg);
523 return if_info->doNot ? !res : res;
526 /* Evaluate a "comparison without operator", such as in ".if ${VAR}" or
529 EvalNotEmpty(CondParser *par, const char *value, Boolean quoted)
533 /* For .ifxxx "...", check for non-empty string. */
535 return value[0] != '\0';
537 /* For .ifxxx <number>, compare against zero */
538 if (TryParseNumber(value, &num))
541 /* For .if ${...}, check for non-empty string. This is different from
542 * the evaluation function from that .if variant, which would test
543 * whether a variable of the given name were defined. */
544 /* XXX: Whitespace should count as empty, just as in ParseEmptyArg. */
545 if (par->if_info->form[0] == '\0')
546 return value[0] != '\0';
548 /* For the other variants of .ifxxx ${...}, use its default function. */
549 return If_Eval(par->if_info, value, strlen(value));
552 /* Evaluate a numerical comparison, such as in ".if ${VAR} >= 9". */
554 EvalCompareNum(double lhs, const char *op, double rhs)
556 DEBUG3(COND, "lhs = %f, rhs = %f, op = %.2s\n", lhs, rhs, op);
561 Parse_Error(PARSE_WARNING, "Unknown operator");
562 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
565 return ToToken(lhs != rhs);
568 Parse_Error(PARSE_WARNING, "Unknown operator");
569 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
572 return ToToken(lhs == rhs);
574 return ToToken(op[1] == '=' ? lhs <= rhs : lhs < rhs);
576 return ToToken(op[1] == '=' ? lhs >= rhs : lhs > rhs);
582 EvalCompareStr(const char *lhs, const char *op, const char *rhs)
584 if (!((op[0] == '!' || op[0] == '=') && op[1] == '=')) {
585 Parse_Error(PARSE_WARNING,
586 "String comparison operator must be either == or !=");
587 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
591 DEBUG3(COND, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n", lhs, rhs, op);
592 return ToToken((*op == '=') == (strcmp(lhs, rhs) == 0));
595 /* Evaluate a comparison, such as "${VAR} == 12345". */
597 EvalCompare(const char *lhs, Boolean lhsQuoted, const char *op,
598 const char *rhs, Boolean rhsQuoted)
602 if (!rhsQuoted && !lhsQuoted)
603 if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
604 return EvalCompareNum(left, op, right);
606 return EvalCompareStr(lhs, op, rhs);
609 /* Parse a comparison condition such as:
617 CondParser_Comparison(CondParser *par, Boolean doEval)
620 const char *lhs, *op, *rhs;
621 void *lhs_freeIt, *rhs_freeIt;
622 Boolean lhsQuoted, rhsQuoted;
625 * Parse the variable spec and skip over it, saving its
628 lhs = CondParser_String(par, doEval, lhsStrict, &lhsQuoted, &lhs_freeIt);
632 CondParser_SkipWhitespace(par);
640 if (par->p[1] == '=')
646 /* Unknown operator, compare against an empty string or 0. */
647 t = ToToken(doEval && EvalNotEmpty(par, lhs, lhsQuoted));
651 CondParser_SkipWhitespace(par);
653 if (par->p[0] == '\0') {
654 Parse_Error(PARSE_WARNING, "Missing right-hand-side of operator");
655 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
659 rhs = CondParser_String(par, doEval, FALSE, &rhsQuoted, &rhs_freeIt);
668 t = EvalCompare(lhs, lhsQuoted, op, rhs, rhsQuoted);
677 /* The argument to empty() is a variable name, optionally followed by
678 * variable modifiers. */
680 ParseEmptyArg(const char **pp, Boolean doEval,
681 const char *func MAKE_ATTR_UNUSED, char **out_arg)
687 /* We do all the work here and return the result as the length */
690 (*pp)--; /* Make (*pp)[1] point to the '('. */
691 (void)Var_Parse(pp, VAR_CMDLINE, doEval ? VARE_WANTRES : VARE_NONE,
693 /* TODO: handle errors */
694 /* If successful, *pp points beyond the closing ')' now. */
696 if (val == var_Error) {
701 /* A variable is empty when it just contains spaces... 4/15/92, christos */
702 cpp_skip_whitespace(&val);
705 * For consistency with the other functions we can't generate the
708 magic_res = *val != '\0' ? 2 : 1;
714 FuncEmpty(size_t arglen, const char *arg MAKE_ATTR_UNUSED)
716 /* Magic values ahead, see ParseEmptyArg. */
721 CondParser_Func(CondParser *par, Boolean doEval, Token *out_token)
723 static const struct fn_def {
726 size_t (*fn_parse)(const char **, Boolean, const char *, char **);
727 Boolean (*fn_eval)(size_t, const char *);
729 { "defined", 7, ParseFuncArg, FuncDefined },
730 { "make", 4, ParseFuncArg, FuncMake },
731 { "exists", 6, ParseFuncArg, FuncExists },
732 { "empty", 5, ParseEmptyArg, FuncEmpty },
733 { "target", 6, ParseFuncArg, FuncTarget },
734 { "commands", 8, ParseFuncArg, FuncCommands }
736 const struct fn_def *fn;
739 const char *cp = par->p;
740 const struct fn_def *fns_end = fns + sizeof fns / sizeof fns[0];
742 for (fn = fns; fn != fns_end; fn++) {
743 if (!is_token(cp, fn->fn_name, fn->fn_name_len))
746 cp += fn->fn_name_len;
747 cpp_skip_whitespace(&cp);
751 arglen = fn->fn_parse(&cp, doEval, fn->fn_name, &arg);
752 if (arglen == 0 || arglen == (size_t)-1) {
754 *out_token = arglen == 0 ? TOK_FALSE : TOK_ERROR;
758 /* Evaluate the argument using the required function. */
759 *out_token = ToToken(!doEval || fn->fn_eval(arglen, arg));
768 /* Parse a function call, a number, a variable expression or a string
771 CondParser_LeafToken(CondParser *par, Boolean doEval)
776 const char *cp = par->p;
779 if (CondParser_Func(par, doEval, &t))
782 /* Push anything numeric through the compare expression */
784 if (ch_isdigit(cp[0]) || cp[0] == '-' || cp[0] == '+')
785 return CondParser_Comparison(par, doEval);
788 * Most likely we have a naked token to apply the default function to.
789 * However ".if a == b" gets here when the "a" is unquoted and doesn't
790 * start with a '$'. This surprises people.
791 * If what follows the function argument is a '=' or '!' then the syntax
792 * would be invalid if we did "defined(a)" - so instead treat as an
795 arglen = ParseFuncArg(&cp, doEval, NULL, &arg);
797 cpp_skip_whitespace(&cp1);
798 if (*cp1 == '=' || *cp1 == '!')
799 return CondParser_Comparison(par, doEval);
803 * Evaluate the argument using the default function.
804 * This path always treats .if as .ifdef. To get here, the character
805 * after .if must have been taken literally, so the argument cannot
806 * be empty - even if it contained a variable expansion.
808 t = ToToken(!doEval || If_Eval(par->if_info, arg, arglen));
813 /* Return the next token or comparison result from the parser. */
815 CondParser_Token(CondParser *par, Boolean doEval)
821 par->curr = TOK_NONE;
825 cpp_skip_hspace(&par->p);
839 if (par->p[0] == '|')
841 else if (opts.lint) {
842 Parse_Error(PARSE_FATAL, "Unknown operator '|'");
843 par->printedError = TRUE;
850 if (par->p[0] == '&')
852 else if (opts.lint) {
853 Parse_Error(PARSE_FATAL, "Unknown operator '&'");
854 par->printedError = TRUE;
863 case '#': /* XXX: see unit-tests/cond-token-plain.mk */
864 case '\n': /* XXX: why should this end the condition? */
865 /* Probably obsolete now, from 1993-03-21. */
871 return CondParser_Comparison(par, doEval);
874 return CondParser_LeafToken(par, doEval);
878 /* Parse a single term in the expression. This consists of a terminal symbol
879 * or TOK_NOT and a term (not including the binary operators):
881 * T -> defined(variable) | make(target) | exists(file) | symbol
885 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
888 CondParser_Term(CondParser *par, Boolean doEval)
892 t = CondParser_Token(par, doEval);
896 * If we reached the end of the expression, the expression
900 } else if (t == TOK_LPAREN) {
904 t = CondParser_Expr(par, doEval);
905 if (t != TOK_ERROR) {
906 if (CondParser_Token(par, doEval) != TOK_RPAREN) {
910 } else if (t == TOK_NOT) {
911 t = CondParser_Term(par, doEval);
914 } else if (t == TOK_FALSE) {
921 /* Parse a conjunctive factor (nice name, wot?)
926 * TOK_TRUE, TOK_FALSE or TOK_ERROR
929 CondParser_Factor(CondParser *par, Boolean doEval)
933 l = CondParser_Term(par, doEval);
934 if (l != TOK_ERROR) {
935 o = CondParser_Token(par, doEval);
941 * If T is TOK_FALSE, the whole thing will be TOK_FALSE, but we
942 * have to parse the r.h.s. anyway (to throw it away).
943 * If T is TOK_TRUE, the result is the r.h.s., be it a TOK_ERROR
947 l = CondParser_Factor(par, doEval);
949 (void)CondParser_Factor(par, FALSE);
955 CondParser_PushBack(par, o);
961 /* Main expression production.
966 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
969 CondParser_Expr(CondParser *par, Boolean doEval)
973 l = CondParser_Factor(par, doEval);
974 if (l != TOK_ERROR) {
975 o = CondParser_Token(par, doEval);
981 * A similar thing occurs for ||, except that here we make sure
982 * the l.h.s. is TOK_FALSE before we bother to evaluate the r.h.s.
983 * Once again, if l is TOK_FALSE, the result is the r.h.s. and once
984 * again if l is TOK_TRUE, we parse the r.h.s. to throw it away.
986 if (l == TOK_FALSE) {
987 l = CondParser_Expr(par, doEval);
989 (void)CondParser_Expr(par, FALSE);
995 CondParser_PushBack(par, o);
1001 static CondEvalResult
1002 CondParser_Eval(CondParser *par, Boolean *value)
1006 DEBUG1(COND, "CondParser_Eval: %s\n", par->p);
1008 res = CondParser_Expr(par, TRUE);
1009 if (res != TOK_FALSE && res != TOK_TRUE)
1010 return COND_INVALID;
1012 if (CondParser_Token(par, TRUE /* XXX: Why TRUE? */) != TOK_EOF)
1013 return COND_INVALID;
1015 *value = res == TOK_TRUE;
1019 /* Evaluate the condition, including any side effects from the variable
1020 * expressions in the condition. The condition consists of &&, ||, !,
1021 * function(arg), comparisons and parenthetical groupings thereof.
1024 * COND_PARSE if the condition was valid grammatically
1025 * COND_INVALID if not a valid conditional.
1027 * (*value) is set to the boolean value of the condition
1029 static CondEvalResult
1030 CondEvalExpression(const struct If *info, const char *cond, Boolean *value,
1031 Boolean eprint, Boolean strictLHS)
1034 CondEvalResult rval;
1036 lhsStrict = strictLHS;
1038 cpp_skip_hspace(&cond);
1040 par.if_info = info != NULL ? info : ifs + PLAIN_IF_INDEX;
1042 par.curr = TOK_NONE;
1043 par.printedError = FALSE;
1045 rval = CondParser_Eval(&par, value);
1047 if (rval == COND_INVALID && eprint && !par.printedError)
1048 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", cond);
1053 /* Evaluate a condition in a :? modifier, such as
1054 * ${"${VAR}" == value:?yes:no}. */
1056 Cond_EvalCondition(const char *cond, Boolean *out_value)
1058 return CondEvalExpression(NULL, cond, out_value, FALSE, FALSE);
1061 /* Evaluate the conditional directive in the line, which is one of:
1076 * In these directives, <cond> consists of &&, ||, !, function(arg),
1077 * comparisons, expressions, bare words, numbers and strings, and
1078 * parenthetical groupings thereof.
1081 * COND_PARSE to continue parsing the lines that follow the
1082 * conditional (when <cond> evaluates to TRUE)
1083 * COND_SKIP to skip the lines after the conditional
1084 * (when <cond> evaluates to FALSE, or when a previous
1085 * branch has already been taken)
1086 * COND_INVALID if the conditional was not valid, either because of
1087 * a syntax error or because some variable was undefined
1088 * or because the condition could not be evaluated
1091 Cond_EvalLine(const char *const line)
1093 typedef enum IfState {
1095 /* None of the previous <cond> evaluated to TRUE. */
1098 /* The previous <cond> evaluated to TRUE.
1099 * The lines following this condition are interpreted. */
1100 IFS_ACTIVE = 1 << 0,
1102 /* The previous directive was an '.else'. */
1103 IFS_SEEN_ELSE = 1 << 1,
1105 /* One of the previous <cond> evaluated to TRUE. */
1106 IFS_WAS_ACTIVE = 1 << 2
1110 static enum IfState *cond_states = NULL;
1111 static unsigned int cond_states_cap = 128;
1113 const struct If *ifp;
1117 const char *p = line;
1119 if (cond_states == NULL) {
1120 cond_states = bmake_malloc(cond_states_cap * sizeof *cond_states);
1121 cond_states[0] = IFS_ACTIVE;
1124 p++; /* skip the leading '.' */
1125 cpp_skip_hspace(&p);
1127 /* Parse the name of the directive, such as 'if', 'elif', 'endif'. */
1130 if (!is_token(p + 1, "ndif", 4)) {
1131 /* Unknown directive. It might still be a transformation
1132 * rule like '.elisp.scm', therefore no error message here. */
1133 return COND_INVALID;
1136 /* It is an '.endif'. */
1137 /* TODO: check for extraneous <cond> */
1139 if (cond_depth == cond_min_depth) {
1140 Parse_Error(PARSE_FATAL, "if-less endif");
1144 /* Return state for previous conditional */
1146 return cond_states[cond_depth] & IFS_ACTIVE
1147 ? COND_PARSE : COND_SKIP;
1150 /* Quite likely this is 'else' or 'elif' */
1152 if (is_token(p, "se", 2)) { /* It is an 'else'. */
1154 if (opts.lint && p[2] != '\0')
1155 Parse_Error(PARSE_FATAL,
1156 "The .else directive does not take arguments.");
1158 if (cond_depth == cond_min_depth) {
1159 Parse_Error(PARSE_FATAL, "if-less else");
1163 state = cond_states[cond_depth];
1164 if (state == IFS_INITIAL) {
1165 state = IFS_ACTIVE | IFS_SEEN_ELSE;
1167 if (state & IFS_SEEN_ELSE)
1168 Parse_Error(PARSE_WARNING, "extra else");
1169 state = IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1171 cond_states[cond_depth] = state;
1173 return state & IFS_ACTIVE ? COND_PARSE : COND_SKIP;
1175 /* Assume for now it is an elif */
1180 if (p[0] != 'i' || p[1] != 'f') {
1181 /* Unknown directive. It might still be a transformation rule like
1182 * '.elisp.scm', therefore no error message here. */
1183 return COND_INVALID; /* Not an ifxxx or elifxxx line */
1187 * Figure out what sort of conditional it is -- what its default
1188 * function is, etc. -- by looking in the table of valid "ifs"
1191 for (ifp = ifs;; ifp++) {
1192 if (ifp->form == NULL) {
1193 /* TODO: Add error message about unknown directive,
1194 * since there is no other known directive that starts with 'el'
1196 * Example: .elifx 123 */
1197 return COND_INVALID;
1199 if (is_token(p, ifp->form, ifp->formlen)) {
1205 /* Now we know what sort of 'if' it is... */
1208 if (cond_depth == cond_min_depth) {
1209 Parse_Error(PARSE_FATAL, "if-less elif");
1212 state = cond_states[cond_depth];
1213 if (state & IFS_SEEN_ELSE) {
1214 Parse_Error(PARSE_WARNING, "extra elif");
1215 cond_states[cond_depth] = IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1218 if (state != IFS_INITIAL) {
1219 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1224 if (cond_depth + 1 >= cond_states_cap) {
1226 * This is rare, but not impossible.
1227 * In meta mode, dirdeps.mk (only runs at level 0)
1228 * can need more than the default.
1230 cond_states_cap += 32;
1231 cond_states = bmake_realloc(cond_states,
1232 cond_states_cap * sizeof *cond_states);
1234 state = cond_states[cond_depth];
1236 if (!(state & IFS_ACTIVE)) {
1237 /* If we aren't parsing the data, treat as always false */
1238 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1243 /* And evaluate the conditional expression */
1244 if (CondEvalExpression(ifp, p, &value, TRUE, TRUE) == COND_INVALID) {
1245 /* Syntax error in conditional, error message already output. */
1246 /* Skip everything to matching .endif */
1247 /* XXX: An extra '.else' is not detected in this case. */
1248 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1253 cond_states[cond_depth] = IFS_INITIAL;
1256 cond_states[cond_depth] = IFS_ACTIVE;
1261 Cond_restore_depth(unsigned int saved_depth)
1263 unsigned int open_conds = cond_depth - cond_min_depth;
1265 if (open_conds != 0 || saved_depth > cond_depth) {
1266 Parse_Error(PARSE_FATAL, "%u open conditional%s", open_conds,
1267 open_conds == 1 ? "" : "s");
1268 cond_depth = cond_min_depth;
1271 cond_min_depth = saved_depth;
1275 Cond_save_depth(void)
1277 unsigned int depth = cond_min_depth;
1279 cond_min_depth = cond_depth;