1 /* $NetBSD: cond.c,v 1.173 2020/10/30 20:30:44 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.
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.
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.
95 /* "@(#)cond.c 8.2 (Berkeley) 1/2/94" */
96 MAKE_RCSID("$NetBSD: cond.c,v 1.173 2020/10/30 20:30:44 rillig Exp $");
99 * The parsing of conditional expressions is based on this grammar:
104 * T -> defined(variable)
107 * T -> empty(varspec)
109 * T -> commands(name)
111 * T -> $(varspec) op value
112 * T -> $(varspec) == "string"
113 * T -> $(varspec) != "string"
117 * op -> == | != | > | < | >= | <=
119 * 'symbol' is some other symbol to which the default function is applied.
121 * The tokens are scanned by CondToken, which returns:
122 * TOK_AND for '&' or '&&'
123 * TOK_OR for '|' or '||'
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
131 * TOK_FALSE is 0 and TOK_TRUE 1 so we can directly assign C comparisons.
133 * All non-terminal functions (CondParser_Expr, CondParser_Factor and
134 * CondParser_Term) return either TOK_FALSE, TOK_TRUE, or TOK_ERROR on error.
137 TOK_FALSE = 0, TOK_TRUE = 1, TOK_AND, TOK_OR, TOK_NOT,
138 TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
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 */
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;
153 static Token CondParser_Expr(CondParser *par, Boolean);
155 static unsigned int cond_depth = 0; /* current .if nesting level */
156 static unsigned int cond_min_depth = 0; /* depth at makefile open */
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.
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 we cannot tell if
166 * it was a variable reference or not.
168 static Boolean lhsStrict;
171 is_token(const char *str, const char *tok, size_t len)
173 return strncmp(str, tok, len) == 0 && !ch_isalpha(str[len]);
176 /* Push back the most recent token read. We only need one level of this. */
178 CondParser_PushBack(CondParser *par, Token t)
180 assert(par->curr == TOK_NONE);
181 assert(t != TOK_NONE);
187 CondParser_SkipWhitespace(CondParser *par)
189 cpp_skip_whitespace(&par->p);
192 /* Parse the argument of a built-in function.
195 * *pp initially points at the '(',
196 * upon successful return it points right after the ')'.
198 * *out_arg receives the argument as string.
200 * func says whether the argument belongs to an actual function, or
201 * whether the parsed argument is passed to the default function.
203 * Return the length of the argument. */
205 ParseFuncArg(const char **pp, Boolean doEval, const char *func,
213 p++; /* Skip opening '(' - verified by caller */
217 * No arguments whatsoever. Because 'make' and 'defined' aren't really
218 * "reserved words", we don't print a message. I think this is better
219 * than hitting the user with a warning message every time s/he uses
220 * the word 'make' or 'defined' at the beginning of a symbol...
226 while (*p == ' ' || *p == '\t') {
230 Buf_Init(&argBuf, 16);
235 if (ch == 0 || ch == ' ' || ch == '\t')
237 if ((ch == '&' || ch == '|') && paren_depth == 0)
241 * Parse the variable spec and install it as part of the argument
242 * if it's valid. We tell Var_Parse to complain on an undefined
243 * variable, so we don't need to do it. Nor do we return an error,
244 * though perhaps we should...
246 void *nestedVal_freeIt;
247 VarEvalFlags eflags = VARE_UNDEFERR | (doEval ? VARE_WANTRES : 0);
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);
267 while (*p == ' ' || *p == '\t') {
271 if (func != NULL && *p++ != ')') {
272 Parse_Error(PARSE_WARNING, "Missing closing parenthesis for %s()",
274 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
282 /* Test whether the given variable is defined. */
284 FuncDefined(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
287 Boolean result = Var_Value(arg, VAR_CMDLINE, &freeIt) != NULL;
292 /* See if the given target is being made. */
294 FuncMake(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
298 for (ln = opts.create->first; ln != NULL; ln = ln->next)
299 if (Str_Match(ln->datum, arg))
304 /* See if the given file exists. */
306 FuncExists(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
311 path = Dir_FindFile(arg, dirSearchPath);
312 DEBUG2(COND, "exists(%s) result is \"%s\"\n", arg, path ? path : "");
322 /* See if the given node exists and is an actual target. */
324 FuncTarget(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
326 GNode *gn = Targ_FindNode(arg);
327 return gn != NULL && GNode_IsTarget(gn);
330 /* See if the given node exists and is an actual target with commands
331 * associated with it. */
333 FuncCommands(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
335 GNode *gn = Targ_FindNode(arg);
336 return gn != NULL && GNode_IsTarget(gn) && !Lst_IsEmpty(gn->commands);
340 * Convert the given number into a double.
341 * We try a base 10 or 16 integer conversion first, if that fails
342 * then we try a floating point conversion instead.
345 * Sets 'value' to double value of string.
346 * Returns TRUE if the conversion succeeded.
349 TryParseNumber(const char *str, double *value)
360 l_val = strtoul(str, &eptr, str[1] == 'x' ? 16 : 10);
362 if (ech == '\0' && errno != ERANGE) {
363 d_val = str[0] == '-' ? -(double)-l_val : (double)l_val;
365 if (ech != '\0' && ech != '.' && ech != 'e' && ech != 'E')
367 d_val = strtod(str, &eptr);
377 is_separator(char ch)
379 return ch == '\0' || ch_isspace(ch) || strchr("!=><)", ch) != NULL;
383 * Parse a string from a variable reference or an optionally quoted
384 * string. This is called for the lhs and rhs of string comparisons.
387 * Returns the string, absent any quotes, or NULL on error.
388 * Sets quoted if the string was quoted.
389 * Sets freeIt if needed.
391 /* coverity:[+alloc : arg-*4] */
393 CondParser_String(CondParser *par, Boolean doEval, Boolean strictLHS,
394 Boolean *quoted, void **freeIt)
399 const char *nested_p;
403 VarParseResult parseResult;
408 *quoted = qt = par->p[0] == '"' ? 1 : 0;
412 while (par->p[0] && str == NULL) {
416 if (par->p[0] != '\0') {
417 Buf_AddByte(&buf, par->p[0]);
423 par->p++; /* we don't want the quotes */
426 Buf_AddByte(&buf, par->p[0]); /* likely? */
438 Buf_AddByte(&buf, par->p[0]);
442 /* if we are in quotes, an undefined variable is ok */
443 eflags = ((!qt && doEval) ? VARE_UNDEFERR : 0) |
444 (doEval ? VARE_WANTRES : 0);
446 atStart = nested_p == start;
447 parseResult = Var_Parse(&nested_p, VAR_CMDLINE, eflags, &str,
449 /* TODO: handle errors */
450 if (str == var_Error) {
451 if (parseResult & VPR_ANY_MSG)
452 par->printedError = TRUE;
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 && !qt && *start != '$' && !ch_isdigit(*start)) {
484 /* lhs must be quoted, a variable reference or number */
492 Buf_AddByte(&buf, par->p[0]);
498 *freeIt = Buf_GetAll(&buf, NULL);
501 Buf_Destroy(&buf, FALSE);
505 /* The different forms of .if directives. */
506 static const struct If {
507 const char *form; /* Form of if */
508 size_t formlen; /* Length of form */
509 Boolean doNot; /* TRUE if default function should be negated */
510 Boolean (*defProc)(size_t, const char *); /* Default function to apply */
512 { "def", 3, FALSE, FuncDefined },
513 { "ndef", 4, TRUE, FuncDefined },
514 { "make", 4, FALSE, FuncMake },
515 { "nmake", 5, TRUE, FuncMake },
516 { "", 0, FALSE, FuncDefined },
517 { NULL, 0, FALSE, NULL }
520 /* Evaluate a "comparison without operator", such as in ".if ${VAR}" or
523 EvalNotEmpty(CondParser *par, const char *lhs, Boolean lhsQuoted)
527 /* For .ifxxx "..." check for non-empty string. */
529 return lhs[0] != '\0';
531 /* For .ifxxx <number> compare against zero */
532 if (TryParseNumber(lhs, &left))
535 /* For .if ${...} check for non-empty string (defProc is ifdef). */
536 if (par->if_info->form[0] == '\0')
539 /* Otherwise action default test ... */
540 return par->if_info->defProc(strlen(lhs), lhs) == !par->if_info->doNot;
543 /* Evaluate a numerical comparison, such as in ".if ${VAR} >= 9". */
545 EvalCompareNum(double lhs, const char *op, double rhs)
547 DEBUG3(COND, "lhs = %f, rhs = %f, op = %.2s\n", lhs, rhs, op);
552 Parse_Error(PARSE_WARNING, "Unknown operator");
553 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
559 Parse_Error(PARSE_WARNING, "Unknown operator");
560 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
565 return op[1] == '=' ? lhs <= rhs : lhs < rhs;
567 return op[1] == '=' ? lhs >= rhs : lhs > rhs;
573 EvalCompareStr(const char *lhs, const char *op, const char *rhs)
575 if (!((op[0] == '!' || op[0] == '=') && op[1] == '=')) {
576 Parse_Error(PARSE_WARNING,
577 "String comparison operator must be either == or !=");
578 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
582 DEBUG3(COND, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n", lhs, rhs, op);
583 return (*op == '=') == (strcmp(lhs, rhs) == 0);
586 /* Evaluate a comparison, such as "${VAR} == 12345". */
588 EvalCompare(const char *lhs, Boolean lhsQuoted, const char *op,
589 const char *rhs, Boolean rhsQuoted)
593 if (!rhsQuoted && !lhsQuoted)
594 if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
595 return EvalCompareNum(left, op, right);
597 return EvalCompareStr(lhs, op, rhs);
600 /* Parse a comparison condition such as:
608 CondParser_Comparison(CondParser *par, Boolean doEval)
611 const char *lhs, *op, *rhs;
612 void *lhsFree, *rhsFree;
613 Boolean lhsQuoted, rhsQuoted;
616 lhsFree = rhsFree = NULL;
617 lhsQuoted = rhsQuoted = FALSE;
620 * Parse the variable spec and skip over it, saving its
623 lhs = CondParser_String(par, doEval, lhsStrict, &lhsQuoted, &lhsFree);
627 CondParser_SkipWhitespace(par);
630 * Make sure the operator is a valid one. If it isn't a
631 * known relational operator, pretend we got a
640 if (par->p[1] == '=') {
647 t = doEval ? EvalNotEmpty(par, lhs, lhsQuoted) : TOK_FALSE;
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, &rhsFree);
668 t = EvalCompare(lhs, lhsQuoted, op, rhs, rhsQuoted);
677 ParseEmptyArg(const char **linePtr, Boolean doEval,
678 const char *func MAKE_ATTR_UNUSED, char **argPtr)
684 /* We do all the work here and return the result as the length */
687 (*linePtr)--; /* Make (*linePtr)[1] point to the '('. */
688 (void)Var_Parse(linePtr, VAR_CMDLINE, doEval ? VARE_WANTRES : 0,
690 /* TODO: handle errors */
691 /* If successful, *linePtr points beyond the closing ')' now. */
693 if (val == var_Error) {
698 /* A variable is empty when it just contains spaces... 4/15/92, christos */
699 cpp_skip_whitespace(&val);
702 * For consistency with the other functions we can't generate the
705 magic_res = *val != '\0' ? 2 : 1;
711 FuncEmpty(size_t arglen, const char *arg MAKE_ATTR_UNUSED)
713 /* Magic values ahead, see ParseEmptyArg. */
718 CondParser_Func(CondParser *par, Boolean doEval)
720 static const struct fn_def {
723 size_t (*fn_parse)(const char **, Boolean, const char *, char **);
724 Boolean (*fn_eval)(size_t, const char *);
726 { "defined", 7, ParseFuncArg, FuncDefined },
727 { "make", 4, ParseFuncArg, FuncMake },
728 { "exists", 6, ParseFuncArg, FuncExists },
729 { "empty", 5, ParseEmptyArg, FuncEmpty },
730 { "target", 6, ParseFuncArg, FuncTarget },
731 { "commands", 8, ParseFuncArg, FuncCommands },
732 { NULL, 0, NULL, NULL },
734 const struct fn_def *fn_def;
738 const char *cp = par->p;
741 for (fn_def = fn_defs; fn_def->fn_name != NULL; fn_def++) {
742 if (!is_token(cp, fn_def->fn_name, fn_def->fn_name_len))
744 cp += fn_def->fn_name_len;
745 /* There can only be whitespace before the '(' */
746 cpp_skip_whitespace(&cp);
750 arglen = fn_def->fn_parse(&cp, doEval, fn_def->fn_name, &arg);
751 if (arglen == 0 || arglen == (size_t)-1) {
753 return arglen == 0 ? TOK_FALSE : TOK_ERROR;
755 /* Evaluate the argument using the required function. */
756 t = !doEval || fn_def->fn_eval(arglen, arg);
762 /* Push anything numeric through the compare expression */
764 if (ch_isdigit(cp[0]) || strchr("+-", cp[0]))
765 return CondParser_Comparison(par, doEval);
768 * Most likely we have a naked token to apply the default function to.
769 * However ".if a == b" gets here when the "a" is unquoted and doesn't
770 * start with a '$'. This surprises people.
771 * If what follows the function argument is a '=' or '!' then the syntax
772 * would be invalid if we did "defined(a)" - so instead treat as an
775 arglen = ParseFuncArg(&cp, doEval, NULL, &arg);
777 cpp_skip_whitespace(&cp1);
778 if (*cp1 == '=' || *cp1 == '!')
779 return CondParser_Comparison(par, doEval);
783 * Evaluate the argument using the default function.
784 * This path always treats .if as .ifdef. To get here, the character
785 * after .if must have been taken literally, so the argument cannot
786 * be empty - even if it contained a variable expansion.
788 t = !doEval || par->if_info->defProc(arglen, arg) == !par->if_info->doNot;
793 /* Return the next token or comparison result from the parser. */
795 CondParser_Token(CondParser *par, Boolean doEval)
801 par->curr = TOK_NONE;
805 while (par->p[0] == ' ' || par->p[0] == '\t') {
821 if (par->p[0] == '|') {
828 if (par->p[0] == '&') {
844 return CondParser_Comparison(par, doEval);
847 return CondParser_Func(par, doEval);
851 /* Parse a single term in the expression. This consists of a terminal symbol
852 * or TOK_NOT and a term (not including the binary operators):
854 * T -> defined(variable) | make(target) | exists(file) | symbol
858 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
861 CondParser_Term(CondParser *par, Boolean doEval)
865 t = CondParser_Token(par, doEval);
869 * If we reached the end of the expression, the expression
873 } else if (t == TOK_LPAREN) {
877 t = CondParser_Expr(par, doEval);
878 if (t != TOK_ERROR) {
879 if (CondParser_Token(par, doEval) != TOK_RPAREN) {
883 } else if (t == TOK_NOT) {
884 t = CondParser_Term(par, doEval);
887 } else if (t == TOK_FALSE) {
894 /* Parse a conjunctive factor (nice name, wot?)
899 * TOK_TRUE, TOK_FALSE or TOK_ERROR
902 CondParser_Factor(CondParser *par, Boolean doEval)
906 l = CondParser_Term(par, doEval);
907 if (l != TOK_ERROR) {
908 o = CondParser_Token(par, doEval);
914 * If T is TOK_FALSE, the whole thing will be TOK_FALSE, but we
915 * have to parse the r.h.s. anyway (to throw it away).
916 * If T is TOK_TRUE, the result is the r.h.s., be it a TOK_ERROR
920 l = CondParser_Factor(par, doEval);
922 (void)CondParser_Factor(par, FALSE);
928 CondParser_PushBack(par, o);
934 /* Main expression production.
939 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
942 CondParser_Expr(CondParser *par, Boolean doEval)
946 l = CondParser_Factor(par, doEval);
947 if (l != TOK_ERROR) {
948 o = CondParser_Token(par, doEval);
954 * A similar thing occurs for ||, except that here we make sure
955 * the l.h.s. is TOK_FALSE before we bother to evaluate the r.h.s.
956 * Once again, if l is TOK_FALSE, the result is the r.h.s. and once
957 * again if l is TOK_TRUE, we parse the r.h.s. to throw it away.
959 if (l == TOK_FALSE) {
960 l = CondParser_Expr(par, doEval);
962 (void)CondParser_Expr(par, FALSE);
968 CondParser_PushBack(par, o);
974 static CondEvalResult
975 CondParser_Eval(CondParser *par, Boolean *value)
979 DEBUG1(COND, "CondParser_Eval: %s\n", par->p);
981 res = CondParser_Expr(par, TRUE);
982 if (res != TOK_FALSE && res != TOK_TRUE)
985 if (CondParser_Token(par, TRUE /* XXX: Why TRUE? */) != TOK_EOF)
988 *value = res == TOK_TRUE;
992 /* Evaluate the condition, including any side effects from the variable
993 * expressions in the condition. The condition consists of &&, ||, !,
994 * function(arg), comparisons and parenthetical groupings thereof.
997 * COND_PARSE if the condition was valid grammatically
998 * COND_INVALID if not a valid conditional.
1000 * (*value) is set to the boolean value of the condition
1002 static CondEvalResult
1003 CondEvalExpression(const struct If *info, const char *cond, Boolean *value,
1004 Boolean eprint, Boolean strictLHS)
1006 static const struct If *dflt_info;
1010 lhsStrict = strictLHS;
1012 while (*cond == ' ' || *cond == '\t')
1015 if (info == NULL && (info = dflt_info) == NULL) {
1016 /* Scan for the entry for .if - it can't be first */
1017 for (info = ifs;; info++)
1018 if (info->form[0] == 0)
1022 assert(info != NULL);
1026 par.curr = TOK_NONE;
1027 par.printedError = FALSE;
1029 rval = CondParser_Eval(&par, value);
1031 if (rval == COND_INVALID && eprint && !par.printedError)
1032 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", cond);
1038 Cond_EvalCondition(const char *cond, Boolean *out_value)
1040 return CondEvalExpression(NULL, cond, out_value, FALSE, FALSE);
1043 /* Evaluate the conditional in the passed line. The line looks like this:
1044 * .<cond-type> <expr>
1045 * In this line, <cond-type> is any of if, ifmake, ifnmake, ifdef, ifndef,
1046 * elif, elifmake, elifnmake, elifdef, elifndef.
1047 * In this line, <expr> consists of &&, ||, !, function(arg), comparisons
1048 * and parenthetical groupings thereof.
1050 * Note that the states IF_ACTIVE and ELSE_ACTIVE are only different in order
1051 * to detect spurious .else lines (as are SKIP_TO_ELSE and SKIP_TO_ENDIF),
1052 * otherwise .else could be treated as '.elif 1'.
1055 * COND_PARSE to continue parsing the lines after the conditional
1056 * (when .if or .else returns TRUE)
1057 * COND_SKIP to skip the lines after the conditional
1058 * (when .if or .elif returns FALSE, or when a previous
1059 * branch has already been taken)
1060 * COND_INVALID if the conditional was not valid, either because of
1061 * a syntax error or because some variable was undefined
1062 * or because the condition could not be evaluated
1065 Cond_EvalLine(const char *line)
1067 enum { MAXIF = 128 }; /* maximum depth of .if'ing */
1068 enum { MAXIF_BUMP = 32 }; /* how much to grow by */
1070 IF_ACTIVE, /* .if or .elif part active */
1071 ELSE_ACTIVE, /* .else part active */
1072 SEARCH_FOR_ELIF, /* searching for .elif/else to execute */
1073 SKIP_TO_ELSE, /* has been true, but not seen '.else' */
1074 SKIP_TO_ENDIF /* nothing else to execute */
1076 static enum if_states *cond_state = NULL;
1077 static unsigned int max_if_depth = MAXIF;
1079 const struct If *ifp;
1082 enum if_states state;
1085 cond_state = bmake_malloc(max_if_depth * sizeof(*cond_state));
1086 cond_state[0] = IF_ACTIVE;
1088 /* skip leading character (the '.') and any whitespace */
1089 for (line++; *line == ' ' || *line == '\t'; line++)
1092 /* Find what type of if we're dealing with. */
1093 if (line[0] == 'e') {
1094 if (line[1] != 'l') {
1095 if (!is_token(line + 1, "ndif", 4))
1096 return COND_INVALID;
1097 /* End of conditional section */
1098 if (cond_depth == cond_min_depth) {
1099 Parse_Error(PARSE_FATAL, "if-less endif");
1102 /* Return state for previous conditional */
1104 return cond_state[cond_depth] <= ELSE_ACTIVE
1105 ? COND_PARSE : COND_SKIP;
1108 /* Quite likely this is 'else' or 'elif' */
1110 if (is_token(line, "se", 2)) {
1112 if (cond_depth == cond_min_depth) {
1113 Parse_Error(PARSE_FATAL, "if-less else");
1117 state = cond_state[cond_depth];
1119 case SEARCH_FOR_ELIF:
1120 state = ELSE_ACTIVE;
1124 Parse_Error(PARSE_WARNING, "extra else");
1129 state = SKIP_TO_ENDIF;
1132 cond_state[cond_depth] = state;
1133 return state <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1135 /* Assume for now it is an elif */
1140 if (line[0] != 'i' || line[1] != 'f')
1141 /* Not an ifxxx or elifxxx line */
1142 return COND_INVALID;
1145 * Figure out what sort of conditional it is -- what its default
1146 * function is, etc. -- by looking in the table of valid "ifs"
1149 for (ifp = ifs;; ifp++) {
1150 if (ifp->form == NULL)
1151 return COND_INVALID;
1152 if (is_token(ifp->form, line, ifp->formlen)) {
1153 line += ifp->formlen;
1158 /* Now we know what sort of 'if' it is... */
1161 if (cond_depth == cond_min_depth) {
1162 Parse_Error(PARSE_FATAL, "if-less elif");
1165 state = cond_state[cond_depth];
1166 if (state == SKIP_TO_ENDIF || state == ELSE_ACTIVE) {
1167 Parse_Error(PARSE_WARNING, "extra elif");
1168 cond_state[cond_depth] = SKIP_TO_ENDIF;
1171 if (state != SEARCH_FOR_ELIF) {
1172 /* Either just finished the 'true' block, or already SKIP_TO_ELSE */
1173 cond_state[cond_depth] = SKIP_TO_ELSE;
1178 if (cond_depth + 1 >= max_if_depth) {
1180 * This is rare, but not impossible.
1181 * In meta mode, dirdeps.mk (only runs at level 0)
1182 * can need more than the default.
1184 max_if_depth += MAXIF_BUMP;
1185 cond_state = bmake_realloc(cond_state,
1186 max_if_depth * sizeof(*cond_state));
1188 state = cond_state[cond_depth];
1190 if (state > ELSE_ACTIVE) {
1191 /* If we aren't parsing the data, treat as always false */
1192 cond_state[cond_depth] = SKIP_TO_ELSE;
1197 /* And evaluate the conditional expression */
1198 if (CondEvalExpression(ifp, line, &value, TRUE, TRUE) == COND_INVALID) {
1199 /* Syntax error in conditional, error message already output. */
1200 /* Skip everything to matching .endif */
1201 cond_state[cond_depth] = SKIP_TO_ELSE;
1206 cond_state[cond_depth] = SEARCH_FOR_ELIF;
1209 cond_state[cond_depth] = IF_ACTIVE;
1214 Cond_restore_depth(unsigned int saved_depth)
1216 unsigned int open_conds = cond_depth - cond_min_depth;
1218 if (open_conds != 0 || saved_depth > cond_depth) {
1219 Parse_Error(PARSE_FATAL, "%u open conditional%s", open_conds,
1220 open_conds == 1 ? "" : "s");
1221 cond_depth = cond_min_depth;
1224 cond_min_depth = saved_depth;
1228 Cond_save_depth(void)
1230 unsigned int depth = cond_min_depth;
1232 cond_min_depth = cond_depth;