1 /* $NetBSD: cond.c,v 1.256 2021/02/05 05:15:12 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
73 * Handling of conditionals in a makefile.
76 * Cond_EvalLine Evaluate the conditional directive, such as
77 * '.if <cond>', '.elifnmake <cond>', '.else', '.endif'.
80 * Evaluate the conditional, which is either the argument
81 * of one of the .if directives or the condition in a
82 * ':?then:else' variable modifier.
86 * Save and restore the nesting of the conditions, at
87 * the start and end of including another makefile, to
88 * ensure that in each makefile the conditional
89 * directives are well-balanced.
97 /* "@(#)cond.c 8.2 (Berkeley) 1/2/94" */
98 MAKE_RCSID("$NetBSD: cond.c,v 1.256 2021/02/05 05:15:12 rillig Exp $");
101 * The parsing of conditional expressions is based on this grammar:
104 * And -> Term '&&' And
106 * Term -> Function '(' Argument ')'
107 * Term -> Leaf Operator Leaf
113 * Leaf -> VariableExpression
115 * Operator -> '==' | '!=' | '>' | '<' | '>=' | '<='
117 * 'Symbol' is an unquoted string literal to which the default function is
120 * The tokens are scanned by CondToken, which returns:
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
132 TOK_FALSE, TOK_TRUE, TOK_AND, TOK_OR, TOK_NOT,
133 TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
136 typedef enum CondResult {
137 CR_FALSE, CR_TRUE, CR_ERROR
140 typedef enum ComparisonOp {
141 LT, LE, GT, GE, EQ, NE
144 typedef struct CondParser {
147 * The plain '.if ${VAR}' evaluates to true if the value of the
148 * expression has length > 0. The other '.if' variants delegate
149 * to evalBare instead.
153 /* The function to apply on unquoted bare words. */
154 Boolean (*evalBare)(size_t, const char *);
155 Boolean negateEvalBare;
157 const char *p; /* The remaining condition to parse */
158 Token curr; /* Single push-back token used in parsing */
161 * Whether an error message has already been printed for this
162 * condition. The first available error message is usually the most
163 * specific one, therefore it makes sense to suppress the standard
164 * "Malformed conditional" message.
166 Boolean printedError;
169 static CondResult CondParser_Or(CondParser *par, Boolean);
171 static unsigned int cond_depth = 0; /* current .if nesting level */
172 static unsigned int cond_min_depth = 0; /* depth at makefile open */
174 static const char *opname[] = { "<", "<=", ">", ">=", "==", "!=" };
177 * Indicate when we should be strict about lhs of comparisons.
178 * In strict mode, the lhs must be a variable expression or a string literal
179 * in quotes. In non-strict mode it may also be an unquoted string literal.
181 * TRUE when CondEvalExpression is called from Cond_EvalLine (.if etc)
182 * FALSE when CondEvalExpression is called from ApplyModifier_IfElse
183 * since lhs is already expanded, and at that point we cannot tell if
184 * it was a variable reference or not.
186 static Boolean lhsStrict;
189 is_token(const char *str, const char *tok, size_t len)
191 return strncmp(str, tok, len) == 0 && !ch_isalpha(str[len]);
195 ToToken(Boolean cond)
197 return cond ? TOK_TRUE : TOK_FALSE;
200 /* Push back the most recent token read. We only need one level of this. */
202 CondParser_PushBack(CondParser *par, Token t)
204 assert(par->curr == TOK_NONE);
205 assert(t != TOK_NONE);
211 CondParser_SkipWhitespace(CondParser *par)
213 cpp_skip_whitespace(&par->p);
217 * Parse the argument of a built-in function.
220 * *pp initially points at the '(',
221 * upon successful return it points right after the ')'.
223 * *out_arg receives the argument as string.
225 * func says whether the argument belongs to an actual function, or
226 * whether the parsed argument is passed to the default function.
228 * Return the length of the argument, or 0 on error.
231 ParseFuncArg(CondParser *par, const char **pp, Boolean doEval, const char *func,
240 p++; /* Skip opening '(' - verified by caller */
243 *out_arg = NULL; /* Missing closing parenthesis: */
244 return 0; /* .if defined( */
249 Buf_InitSize(&argBuf, 16);
254 if (ch == '\0' || ch == ' ' || ch == '\t')
256 if ((ch == '&' || ch == '|') && paren_depth == 0)
260 * Parse the variable expression and install it as
261 * part of the argument if it's valid. We tell
262 * Var_Parse to complain on an undefined variable,
263 * (XXX: but Var_Parse ignores that request)
264 * so we don't need to do it. Nor do we return an
265 * error, though perhaps we should.
267 VarEvalFlags eflags = doEval
268 ? VARE_WANTRES | VARE_UNDEFERR
271 (void)Var_Parse(&p, SCOPE_CMDLINE, eflags, &nestedVal);
272 /* TODO: handle errors */
273 Buf_AddStr(&argBuf, nestedVal.str);
274 FStr_Done(&nestedVal);
279 else if (ch == ')' && --paren_depth < 0)
281 Buf_AddByte(&argBuf, *p);
286 *out_arg = Buf_DoneData(&argBuf);
290 if (func != NULL && *p++ != ')') {
291 Parse_Error(PARSE_FATAL,
292 "Missing closing parenthesis for %s()", func);
293 par->printedError = TRUE;
301 /* Test whether the given variable is defined. */
304 FuncDefined(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
306 FStr value = Var_Value(SCOPE_CMDLINE, arg);
307 Boolean result = value.str != NULL;
312 /* See if the given target is being made. */
315 FuncMake(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
319 for (ln = opts.create.first; ln != NULL; ln = ln->next)
320 if (Str_Match(ln->datum, arg))
325 /* See if the given file exists. */
328 FuncExists(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
333 path = Dir_FindFile(arg, &dirSearchPath);
334 DEBUG2(COND, "exists(%s) result is \"%s\"\n",
335 arg, path != NULL ? path : "");
336 result = path != NULL;
341 /* See if the given node exists and is an actual target. */
344 FuncTarget(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
346 GNode *gn = Targ_FindNode(arg);
347 return gn != NULL && GNode_IsTarget(gn);
351 * See if the given node exists and is an actual target with commands
352 * associated with it.
356 FuncCommands(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
358 GNode *gn = Targ_FindNode(arg);
359 return gn != NULL && GNode_IsTarget(gn) && !Lst_IsEmpty(&gn->commands);
363 * Convert the given number into a double.
364 * We try a base 10 or 16 integer conversion first, if that fails
365 * then we try a floating point conversion instead.
368 * Returns TRUE if the conversion succeeded.
369 * Sets 'out_value' to the converted number.
372 TryParseNumber(const char *str, double *out_value)
375 unsigned long ul_val;
379 if (str[0] == '\0') { /* XXX: why is an empty string a number? */
384 ul_val = strtoul(str, &end, str[1] == 'x' ? 16 : 10);
385 if (*end == '\0' && errno != ERANGE) {
386 *out_value = str[0] == '-' ? -(double)-ul_val : (double)ul_val;
390 if (*end != '\0' && *end != '.' && *end != 'e' && *end != 'E')
391 return FALSE; /* skip the expensive strtod call */
392 dbl_val = strtod(str, &end);
396 *out_value = dbl_val;
401 is_separator(char ch)
403 return ch == '\0' || ch_isspace(ch) || strchr("!=><)", ch) != NULL;
407 * In a quoted or unquoted string literal or a number, parse a variable
410 * Example: .if x${CENTER}y == "${PREFIX}${SUFFIX}" || 0x${HEX}
413 CondParser_StringExpr(CondParser *par, const char *start,
414 Boolean const doEval, Boolean const quoted,
415 Buffer *buf, FStr *const inout_str)
418 const char *nested_p;
420 VarParseResult parseResult;
422 /* if we are in quotes, an undefined variable is ok */
423 eflags = doEval && !quoted ? VARE_WANTRES | VARE_UNDEFERR
424 : doEval ? VARE_WANTRES
428 atStart = nested_p == start;
429 parseResult = Var_Parse(&nested_p, SCOPE_CMDLINE, eflags, inout_str);
430 /* TODO: handle errors */
431 if (inout_str->str == var_Error) {
432 if (parseResult == VPR_ERR) {
434 * FIXME: Even if an error occurs, there is no
435 * guarantee that it is reported.
437 * See cond-token-plain.mk $$$$$$$$.
439 par->printedError = TRUE;
442 * XXX: Can there be any situation in which a returned
443 * var_Error requires freeIt?
445 FStr_Done(inout_str);
447 * Even if !doEval, we still report syntax errors, which is
448 * what getting var_Error back with !doEval means.
450 *inout_str = FStr_InitRefer(NULL);
456 * If the '$' started the string literal (which means no quotes), and
457 * the variable expression is followed by a space, looks like a
458 * comparison operator or is the end of the expression, we are done.
460 if (atStart && is_separator(par->p[0]))
463 Buf_AddStr(buf, inout_str->str);
464 FStr_Done(inout_str);
465 *inout_str = FStr_InitRefer(NULL); /* not finished yet */
470 * Parse a string from a variable reference or an optionally quoted
471 * string. This is called for the lhs and rhs of string comparisons.
474 * Returns the string, absent any quotes, or NULL on error.
475 * Sets out_quoted if the string was quoted.
479 CondParser_String(CondParser *par, Boolean doEval, Boolean strictLHS,
480 FStr *out_str, Boolean *out_quoted)
488 str = FStr_InitRefer(NULL);
489 *out_quoted = quoted = par->p[0] == '"';
494 while (par->p[0] != '\0' && str.str == NULL) {
498 if (par->p[0] != '\0') {
499 Buf_AddByte(&buf, par->p[0]);
506 goto got_str; /* skip the closing quote */
507 Buf_AddByte(&buf, '"');
509 case ')': /* see is_separator */
518 Buf_AddByte(&buf, par->p[0]);
522 if (!CondParser_StringExpr(par,
523 start, doEval, quoted, &buf, &str))
527 if (strictLHS && !quoted && *start != '$' &&
528 !ch_isdigit(*start)) {
530 * The left-hand side must be quoted,
531 * a variable reference or a number.
533 str = FStr_InitRefer(NULL);
536 Buf_AddByte(&buf, par->p[0]);
542 str = FStr_InitOwn(buf.data);
549 If_Eval(const CondParser *par, const char *arg, size_t arglen)
551 Boolean res = par->evalBare(arglen, arg);
552 return par->negateEvalBare ? !res : res;
556 * Evaluate a "comparison without operator", such as in ".if ${VAR}" or
560 EvalNotEmpty(CondParser *par, const char *value, Boolean quoted)
564 /* For .ifxxx "...", check for non-empty string. */
566 return value[0] != '\0';
568 /* For .ifxxx <number>, compare against zero */
569 if (TryParseNumber(value, &num))
572 /* For .if ${...}, check for non-empty string. This is different from
573 * the evaluation function from that .if variant, which would test
574 * whether a variable of the given name were defined. */
575 /* XXX: Whitespace should count as empty, just as in ParseEmptyArg. */
577 return value[0] != '\0';
579 return If_Eval(par, value, strlen(value));
582 /* Evaluate a numerical comparison, such as in ".if ${VAR} >= 9". */
584 EvalCompareNum(double lhs, ComparisonOp op, double rhs)
586 DEBUG3(COND, "lhs = %f, rhs = %f, op = %.2s\n", lhs, rhs, opname[op]);
605 EvalCompareStr(CondParser *par, const char *lhs,
606 ComparisonOp op, const char *rhs)
608 if (op != EQ && op != NE) {
609 Parse_Error(PARSE_FATAL,
610 "String comparison operator must be either == or !=");
611 par->printedError = TRUE;
615 DEBUG3(COND, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
616 lhs, rhs, opname[op]);
617 return ToToken((op == EQ) == (strcmp(lhs, rhs) == 0));
620 /* Evaluate a comparison, such as "${VAR} == 12345". */
622 EvalCompare(CondParser *par, const char *lhs, Boolean lhsQuoted,
623 ComparisonOp op, const char *rhs, Boolean rhsQuoted)
627 if (!rhsQuoted && !lhsQuoted)
628 if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
629 return ToToken(EvalCompareNum(left, op, right));
631 return EvalCompareStr(par, lhs, op, rhs);
635 CondParser_ComparisonOp(CondParser *par, ComparisonOp *out_op)
637 const char *p = par->p;
639 if (p[0] == '<' && p[1] == '=') {
642 } else if (p[0] == '<') {
645 } else if (p[0] == '>' && p[1] == '=') {
648 } else if (p[0] == '>') {
651 } else if (p[0] == '=' && p[1] == '=') {
654 } else if (p[0] == '!' && p[1] == '=') {
669 * Parse a comparison condition such as:
677 CondParser_Comparison(CondParser *par, Boolean doEval)
682 Boolean lhsQuoted, rhsQuoted;
685 * Parse the variable spec and skip over it, saving its
688 CondParser_String(par, doEval, lhsStrict, &lhs, &lhsQuoted);
692 CondParser_SkipWhitespace(par);
694 if (!CondParser_ComparisonOp(par, &op)) {
695 /* Unknown operator, compare against an empty string or 0. */
696 t = ToToken(doEval && EvalNotEmpty(par, lhs.str, lhsQuoted));
700 CondParser_SkipWhitespace(par);
702 if (par->p[0] == '\0') {
703 Parse_Error(PARSE_FATAL,
704 "Missing right-hand-side of operator '%s'", opname[op]);
705 par->printedError = TRUE;
709 CondParser_String(par, doEval, FALSE, &rhs, &rhsQuoted);
718 t = EvalCompare(par, lhs.str, lhsQuoted, op, rhs.str, rhsQuoted);
728 * The argument to empty() is a variable name, optionally followed by
729 * variable modifiers.
733 ParseEmptyArg(CondParser *par MAKE_ATTR_UNUSED, const char **pp,
734 Boolean doEval, const char *func MAKE_ATTR_UNUSED,
740 /* We do all the work here and return the result as the length */
743 (*pp)--; /* Make (*pp)[1] point to the '('. */
744 (void)Var_Parse(pp, SCOPE_CMDLINE, doEval ? VARE_WANTRES : VARE_NONE,
746 /* TODO: handle errors */
747 /* If successful, *pp points beyond the closing ')' now. */
749 if (val.str == var_Error) {
755 * A variable is empty when it just contains spaces...
758 cpp_skip_whitespace(&val.str);
761 * For consistency with the other functions we can't generate the
764 magic_res = val.str[0] != '\0' ? 2 : 1;
771 FuncEmpty(size_t arglen, const char *arg MAKE_ATTR_UNUSED)
773 /* Magic values ahead, see ParseEmptyArg. */
778 CondParser_Func(CondParser *par, Boolean doEval, Token *out_token)
780 static const struct fn_def {
783 size_t (*fn_parse)(CondParser *, const char **, Boolean,
784 const char *, char **);
785 Boolean (*fn_eval)(size_t, const char *);
787 { "defined", 7, ParseFuncArg, FuncDefined },
788 { "make", 4, ParseFuncArg, FuncMake },
789 { "exists", 6, ParseFuncArg, FuncExists },
790 { "empty", 5, ParseEmptyArg, FuncEmpty },
791 { "target", 6, ParseFuncArg, FuncTarget },
792 { "commands", 8, ParseFuncArg, FuncCommands }
794 const struct fn_def *fn;
797 const char *cp = par->p;
798 const struct fn_def *fns_end = fns + sizeof fns / sizeof fns[0];
800 for (fn = fns; fn != fns_end; fn++) {
801 if (!is_token(cp, fn->fn_name, fn->fn_name_len))
804 cp += fn->fn_name_len;
805 cpp_skip_whitespace(&cp);
809 arglen = fn->fn_parse(par, &cp, doEval, fn->fn_name, &arg);
810 if (arglen == 0 || arglen == (size_t)-1) {
812 *out_token = arglen == 0 ? TOK_FALSE : TOK_ERROR;
816 /* Evaluate the argument using the required function. */
817 *out_token = ToToken(!doEval || fn->fn_eval(arglen, arg));
827 * Parse a function call, a number, a variable expression or a string
831 CondParser_LeafToken(CondParser *par, Boolean doEval)
839 if (CondParser_Func(par, doEval, &t))
842 /* Push anything numeric through the compare expression */
844 if (ch_isdigit(cp[0]) || cp[0] == '-' || cp[0] == '+')
845 return CondParser_Comparison(par, doEval);
848 * Most likely we have a naked token to apply the default function to.
849 * However ".if a == b" gets here when the "a" is unquoted and doesn't
850 * start with a '$'. This surprises people.
851 * If what follows the function argument is a '=' or '!' then the
852 * syntax would be invalid if we did "defined(a)" - so instead treat
855 arglen = ParseFuncArg(par, &cp, doEval, NULL, &arg);
857 cpp_skip_whitespace(&cp1);
858 if (*cp1 == '=' || *cp1 == '!')
859 return CondParser_Comparison(par, doEval);
863 * Evaluate the argument using the default function.
864 * This path always treats .if as .ifdef. To get here, the character
865 * after .if must have been taken literally, so the argument cannot
866 * be empty - even if it contained a variable expansion.
868 t = ToToken(!doEval || If_Eval(par, arg, arglen));
873 /* Return the next token or comparison result from the parser. */
875 CondParser_Token(CondParser *par, Boolean doEval)
881 par->curr = TOK_NONE;
885 cpp_skip_hspace(&par->p);
899 if (par->p[0] == '|')
901 else if (opts.strict) {
902 Parse_Error(PARSE_FATAL, "Unknown operator '|'");
903 par->printedError = TRUE;
910 if (par->p[0] == '&')
912 else if (opts.strict) {
913 Parse_Error(PARSE_FATAL, "Unknown operator '&'");
914 par->printedError = TRUE;
923 case '#': /* XXX: see unit-tests/cond-token-plain.mk */
924 case '\n': /* XXX: why should this end the condition? */
925 /* Probably obsolete now, from 1993-03-21. */
931 return CondParser_Comparison(par, doEval);
934 return CondParser_LeafToken(par, doEval);
941 * Term -> Leaf Operator Leaf
945 CondParser_Term(CondParser *par, Boolean doEval)
950 t = CondParser_Token(par, doEval);
956 if (t == TOK_LPAREN) {
957 res = CondParser_Or(par, doEval);
960 if (CondParser_Token(par, doEval) != TOK_RPAREN)
966 res = CondParser_Term(par, doEval);
969 else if (res == CR_FALSE)
978 * And -> Term '&&' And
982 CondParser_And(CondParser *par, Boolean doEval)
987 res = CondParser_Term(par, doEval);
991 op = CondParser_Token(par, doEval);
994 return CondParser_And(par, doEval);
995 if (CondParser_And(par, FALSE) == CR_ERROR)
1000 CondParser_PushBack(par, op);
1009 CondParser_Or(CondParser *par, Boolean doEval)
1014 res = CondParser_And(par, doEval);
1015 if (res == CR_ERROR)
1018 op = CondParser_Token(par, doEval);
1020 if (res == CR_FALSE)
1021 return CondParser_Or(par, doEval);
1022 if (CondParser_Or(par, FALSE) == CR_ERROR)
1027 CondParser_PushBack(par, op);
1031 static CondEvalResult
1032 CondParser_Eval(CondParser *par, Boolean *out_value)
1036 DEBUG1(COND, "CondParser_Eval: %s\n", par->p);
1038 res = CondParser_Or(par, TRUE);
1039 if (res == CR_ERROR)
1040 return COND_INVALID;
1042 if (CondParser_Token(par, FALSE) != TOK_EOF)
1043 return COND_INVALID;
1045 *out_value = res == CR_TRUE;
1050 * Evaluate the condition, including any side effects from the variable
1051 * expressions in the condition. The condition consists of &&, ||, !,
1052 * function(arg), comparisons and parenthetical groupings thereof.
1055 * COND_PARSE if the condition was valid grammatically
1056 * COND_INVALID if not a valid conditional.
1058 * (*value) is set to the boolean value of the condition
1060 static CondEvalResult
1061 CondEvalExpression(const char *cond, Boolean *out_value, Boolean plain,
1062 Boolean (*evalBare)(size_t, const char *), Boolean negate,
1063 Boolean eprint, Boolean strictLHS)
1066 CondEvalResult rval;
1068 lhsStrict = strictLHS;
1070 cpp_skip_hspace(&cond);
1073 par.evalBare = evalBare;
1074 par.negateEvalBare = negate;
1076 par.curr = TOK_NONE;
1077 par.printedError = FALSE;
1079 rval = CondParser_Eval(&par, out_value);
1081 if (rval == COND_INVALID && eprint && !par.printedError)
1082 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", cond);
1088 * Evaluate a condition in a :? modifier, such as
1089 * ${"${VAR}" == value:?yes:no}.
1092 Cond_EvalCondition(const char *cond, Boolean *out_value)
1094 return CondEvalExpression(cond, out_value, TRUE,
1095 FuncDefined, FALSE, FALSE, FALSE);
1099 IsEndif(const char *p)
1101 return p[0] == 'e' && p[1] == 'n' && p[2] == 'd' &&
1102 p[3] == 'i' && p[4] == 'f' && !ch_isalpha(p[5]);
1106 DetermineKindOfConditional(const char **pp, Boolean *out_plain,
1107 Boolean (**out_evalBare)(size_t, const char *),
1108 Boolean *out_negate)
1110 const char *p = *pp;
1114 *out_evalBare = FuncDefined;
1115 *out_negate = FALSE;
1120 if (is_token(p, "def", 3)) { /* .ifdef and .ifndef */
1122 } else if (is_token(p, "make", 4)) { /* .ifmake and .ifnmake */
1124 *out_evalBare = FuncMake;
1125 } else if (is_token(p, "", 0) && !*out_negate) { /* plain .if */
1129 * TODO: Add error message about unknown directive,
1130 * since there is no other known directive that starts
1131 * with 'el' or 'if'.
1133 * Example: .elifx 123
1143 * Evaluate the conditional directive in the line, which is one of:
1158 * In these directives, <cond> consists of &&, ||, !, function(arg),
1159 * comparisons, expressions, bare words, numbers and strings, and
1160 * parenthetical groupings thereof.
1163 * COND_PARSE to continue parsing the lines that follow the
1164 * conditional (when <cond> evaluates to TRUE)
1165 * COND_SKIP to skip the lines after the conditional
1166 * (when <cond> evaluates to FALSE, or when a previous
1167 * branch has already been taken)
1168 * COND_INVALID if the conditional was not valid, either because of
1169 * a syntax error or because some variable was undefined
1170 * or because the condition could not be evaluated
1173 Cond_EvalLine(const char *line)
1175 typedef enum IfState {
1177 /* None of the previous <cond> evaluated to TRUE. */
1180 /* The previous <cond> evaluated to TRUE.
1181 * The lines following this condition are interpreted. */
1182 IFS_ACTIVE = 1 << 0,
1184 /* The previous directive was an '.else'. */
1185 IFS_SEEN_ELSE = 1 << 1,
1187 /* One of the previous <cond> evaluated to TRUE. */
1188 IFS_WAS_ACTIVE = 1 << 2
1192 static enum IfState *cond_states = NULL;
1193 static unsigned int cond_states_cap = 128;
1196 Boolean (*evalBare)(size_t, const char *);
1201 const char *p = line;
1203 if (cond_states == NULL) {
1204 cond_states = bmake_malloc(
1205 cond_states_cap * sizeof *cond_states);
1206 cond_states[0] = IFS_ACTIVE;
1209 p++; /* skip the leading '.' */
1210 cpp_skip_hspace(&p);
1212 if (IsEndif(p)) { /* It is an '.endif'. */
1214 Parse_Error(PARSE_FATAL,
1215 "The .endif directive does not take arguments.");
1218 if (cond_depth == cond_min_depth) {
1219 Parse_Error(PARSE_FATAL, "if-less endif");
1223 /* Return state for previous conditional */
1225 return cond_states[cond_depth] & IFS_ACTIVE
1226 ? COND_PARSE : COND_SKIP;
1229 /* Parse the name of the directive, such as 'if', 'elif', 'endif'. */
1233 * Unknown directive. It might still be a
1234 * transformation rule like '.elisp.scm',
1235 * therefore no error message here.
1237 return COND_INVALID;
1240 /* Quite likely this is 'else' or 'elif' */
1242 if (is_token(p, "se", 2)) { /* It is an 'else'. */
1245 Parse_Error(PARSE_FATAL,
1246 "The .else directive "
1247 "does not take arguments.");
1249 if (cond_depth == cond_min_depth) {
1250 Parse_Error(PARSE_FATAL, "if-less else");
1254 state = cond_states[cond_depth];
1255 if (state == IFS_INITIAL) {
1256 state = IFS_ACTIVE | IFS_SEEN_ELSE;
1258 if (state & IFS_SEEN_ELSE)
1259 Parse_Error(PARSE_WARNING,
1261 state = IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1263 cond_states[cond_depth] = state;
1265 return state & IFS_ACTIVE ? COND_PARSE : COND_SKIP;
1267 /* Assume for now it is an elif */
1272 if (p[0] != 'i' || p[1] != 'f') {
1274 * Unknown directive. It might still be a transformation rule
1275 * like '.elisp.scm', therefore no error message here.
1277 return COND_INVALID; /* Not an ifxxx or elifxxx line */
1280 if (!DetermineKindOfConditional(&p, &plain, &evalBare, &negate))
1281 return COND_INVALID;
1284 if (cond_depth == cond_min_depth) {
1285 Parse_Error(PARSE_FATAL, "if-less elif");
1288 state = cond_states[cond_depth];
1289 if (state & IFS_SEEN_ELSE) {
1290 Parse_Error(PARSE_WARNING, "extra elif");
1291 cond_states[cond_depth] =
1292 IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1295 if (state != IFS_INITIAL) {
1296 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1301 if (cond_depth + 1 >= cond_states_cap) {
1303 * This is rare, but not impossible.
1304 * In meta mode, dirdeps.mk (only runs at level 0)
1305 * can need more than the default.
1307 cond_states_cap += 32;
1308 cond_states = bmake_realloc(cond_states,
1310 sizeof *cond_states);
1312 state = cond_states[cond_depth];
1314 if (!(state & IFS_ACTIVE)) {
1316 * If we aren't parsing the data,
1317 * treat as always false.
1319 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1324 /* And evaluate the conditional expression */
1325 if (CondEvalExpression(p, &value, plain, evalBare, negate,
1326 TRUE, TRUE) == COND_INVALID) {
1327 /* Syntax error in conditional, error message already output. */
1328 /* Skip everything to matching .endif */
1329 /* XXX: An extra '.else' is not detected in this case. */
1330 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1335 cond_states[cond_depth] = IFS_INITIAL;
1338 cond_states[cond_depth] = IFS_ACTIVE;
1343 Cond_restore_depth(unsigned int saved_depth)
1345 unsigned int open_conds = cond_depth - cond_min_depth;
1347 if (open_conds != 0 || saved_depth > cond_depth) {
1348 Parse_Error(PARSE_FATAL, "%u open conditional%s",
1349 open_conds, open_conds == 1 ? "" : "s");
1350 cond_depth = cond_min_depth;
1353 cond_min_depth = saved_depth;
1357 Cond_save_depth(void)
1359 unsigned int depth = cond_min_depth;
1361 cond_min_depth = cond_depth;