1 /* $NetBSD: cond.c,v 1.78 2020/07/03 08:13:23 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 static char rcsid[] = "$NetBSD: cond.c,v 1.78 2020/07/03 08:13:23 rillig Exp $";
75 #include <sys/cdefs.h>
78 static char sccsid[] = "@(#)cond.c 8.2 (Berkeley) 1/2/94";
80 __RCSID("$NetBSD: cond.c,v 1.78 2020/07/03 08:13:23 rillig Exp $");
87 * Functions to handle conditionals in a makefile.
90 * Cond_Eval Evaluate the conditional in the passed line.
96 #include <errno.h> /* For strtoul() error checking */
104 * The parsing of conditional expressions is based on this grammar:
109 * T -> defined(variable)
112 * T -> empty(varspec)
114 * T -> commands(name)
116 * T -> $(varspec) op value
117 * T -> $(varspec) == "string"
118 * T -> $(varspec) != "string"
122 * op -> == | != | > | < | >= | <=
124 * 'symbol' is some other symbol to which the default function (condDefProc)
127 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
128 * will return TOK_AND for '&' and '&&', TOK_OR for '|' and '||',
129 * TOK_NOT for '!', TOK_LPAREN for '(', TOK_RPAREN for ')' and will evaluate
130 * the other terminal symbols, using either the default function or the
131 * function given in the terminal, and return the result as either TOK_TRUE
134 * TOK_FALSE is 0 and TOK_TRUE 1 so we can directly assign C comparisons.
136 * All Non-Terminal functions (CondE, CondF and CondT) return TOK_ERROR on
140 TOK_FALSE = 0, TOK_TRUE = 1, TOK_AND, TOK_OR, TOK_NOT,
141 TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
145 * Structures to handle elegantly the different forms of #if's. The
146 * last two fields are stored in condInvert and condDefProc, respectively.
148 static void CondPushBack(Token);
149 static int CondGetArg(Boolean, char **, char **, const char *);
150 static Boolean CondDoDefined(int, const char *);
151 static int CondStrMatch(const void *, const void *);
152 static Boolean CondDoMake(int, const char *);
153 static Boolean CondDoExists(int, const char *);
154 static Boolean CondDoTarget(int, const char *);
155 static Boolean CondDoCommands(int, const char *);
156 static Boolean CondCvtArg(char *, double *);
157 static Token CondToken(Boolean);
158 static Token CondT(Boolean);
159 static Token CondF(Boolean);
160 static Token CondE(Boolean);
161 static int do_Cond_EvalExpression(Boolean *);
163 static const struct If {
164 const char *form; /* Form of if */
165 int formlen; /* Length of form */
166 Boolean doNot; /* TRUE if default function should be negated */
167 Boolean (*defProc)(int, const char *); /* Default function to apply */
169 { "def", 3, FALSE, CondDoDefined },
170 { "ndef", 4, TRUE, CondDoDefined },
171 { "make", 4, FALSE, CondDoMake },
172 { "nmake", 5, TRUE, CondDoMake },
173 { "", 0, FALSE, CondDoDefined },
174 { NULL, 0, FALSE, NULL }
177 static const struct If *if_info; /* Info for current statement */
178 static char *condExpr; /* The expression to parse */
179 static Token condPushBack=TOK_NONE; /* Single push-back token used in
182 static unsigned int cond_depth = 0; /* current .if nesting level */
183 static unsigned int cond_min_depth = 0; /* depth at makefile open */
186 * Indicate when we should be strict about lhs of comparisons.
187 * TRUE when Cond_EvalExpression is called from Cond_Eval (.if etc)
188 * FALSE when Cond_EvalExpression is called from var.c:ApplyModifiers
189 * since lhs is already expanded and we cannot tell if
190 * it was a variable reference or not.
192 static Boolean lhsStrict;
195 istoken(const char *str, const char *tok, size_t len)
197 return strncmp(str, tok, len) == 0 && !isalpha((unsigned char)str[len]);
201 *-----------------------------------------------------------------------
203 * Push back the most recent token read. We only need one level of
204 * this, so the thing is just stored in 'condPushback'.
207 * t Token to push back into the "stream"
213 * condPushback is overwritten.
215 *-----------------------------------------------------------------------
218 CondPushBack(Token t)
224 *-----------------------------------------------------------------------
226 * Find the argument of a built-in function.
229 * The length of the argument and the address of the argument.
232 * The pointer is set to point to the closing parenthesis of the
235 *-----------------------------------------------------------------------
238 CondGetArg(Boolean doEval, char **linePtr, char **argPtr, const char *func)
248 /* Skip opening '(' - verfied by caller */
253 * No arguments whatsoever. Because 'make' and 'defined' aren't really
254 * "reserved words", we don't print a message. I think this is better
255 * than hitting the user with a warning message every time s/he uses
256 * the word 'make' or 'defined' at the beginning of a symbol...
262 while (*cp == ' ' || *cp == '\t') {
267 * Create a buffer for the argument and start it out at 16 characters
268 * long. Why 16? Why not?
275 if (ch == 0 || ch == ' ' || ch == '\t')
277 if ((ch == '&' || ch == '|') && paren_depth == 0)
281 * Parse the variable spec and install it as part of the argument
282 * if it's valid. We tell Var_Parse to complain on an undefined
283 * variable, so we don't do it too. Nor do we return an error,
284 * though perhaps we should...
290 cp2 = Var_Parse(cp, VAR_CMD, VARF_UNDEFERR|
291 (doEval ? VARF_WANTRES : 0),
293 Buf_AddBytes(&buf, strlen(cp2), cp2);
301 if (ch == ')' && --paren_depth < 0)
303 Buf_AddByte(&buf, *cp);
307 *argPtr = Buf_GetAll(&buf, &argLen);
308 Buf_Destroy(&buf, FALSE);
310 while (*cp == ' ' || *cp == '\t') {
314 if (func != NULL && *cp++ != ')') {
315 Parse_Error(PARSE_WARNING, "Missing closing parenthesis for %s()",
325 *-----------------------------------------------------------------------
327 * Handle the 'defined' function for conditionals.
330 * TRUE if the given variable is defined.
335 *-----------------------------------------------------------------------
338 CondDoDefined(int argLen MAKE_ATTR_UNUSED, const char *arg)
343 if (Var_Value(arg, VAR_CMD, &p1) != NULL) {
354 *-----------------------------------------------------------------------
356 * Front-end for Str_Match so it returns 0 on match and non-zero
357 * on mismatch. Callback function for CondDoMake via Lst_Find
360 * 0 if string matches pattern
365 *-----------------------------------------------------------------------
368 CondStrMatch(const void *string, const void *pattern)
370 return !Str_Match(string, pattern);
374 *-----------------------------------------------------------------------
376 * Handle the 'make' function for conditionals.
379 * TRUE if the given target is being made.
384 *-----------------------------------------------------------------------
387 CondDoMake(int argLen MAKE_ATTR_UNUSED, const char *arg)
389 return Lst_Find(create, arg, CondStrMatch) != NULL;
393 *-----------------------------------------------------------------------
395 * See if the given file exists.
398 * TRUE if the file exists and FALSE if it does not.
403 *-----------------------------------------------------------------------
406 CondDoExists(int argLen MAKE_ATTR_UNUSED, const char *arg)
411 path = Dir_FindFile(arg, dirSearchPath);
413 fprintf(debug_file, "exists(%s) result is \"%s\"\n",
414 arg, path ? path : "");
426 *-----------------------------------------------------------------------
428 * See if the given node exists and is an actual target.
431 * TRUE if the node exists as a target and FALSE if it does not.
436 *-----------------------------------------------------------------------
439 CondDoTarget(int argLen MAKE_ATTR_UNUSED, const char *arg)
443 gn = Targ_FindNode(arg, TARG_NOCREATE);
444 return gn != NULL && !OP_NOP(gn->type);
448 *-----------------------------------------------------------------------
450 * See if the given node exists and is an actual target with commands
451 * associated with it.
454 * TRUE if the node exists as a target and has commands associated with
455 * it and FALSE if it does not.
460 *-----------------------------------------------------------------------
463 CondDoCommands(int argLen MAKE_ATTR_UNUSED, const char *arg)
467 gn = Targ_FindNode(arg, TARG_NOCREATE);
468 return gn != NULL && !OP_NOP(gn->type) && !Lst_IsEmpty(gn->commands);
472 *-----------------------------------------------------------------------
474 * Convert the given number into a double.
475 * We try a base 10 or 16 integer conversion first, if that fails
476 * then we try a floating point conversion instead.
479 * Sets 'value' to double value of string.
480 * Returns 'true' if the convertion suceeded
482 *-----------------------------------------------------------------------
485 CondCvtArg(char *str, double *value)
496 l_val = strtoul(str, &eptr, str[1] == 'x' ? 16 : 10);
498 if (ech == 0 && errno != ERANGE) {
499 d_val = str[0] == '-' ? -(double)-l_val : (double)l_val;
501 if (ech != 0 && ech != '.' && ech != 'e' && ech != 'E')
503 d_val = strtod(str, &eptr);
513 *-----------------------------------------------------------------------
515 * Get a string from a variable reference or an optionally quoted
516 * string. This is called for the lhs and rhs of string compares.
519 * Sets freeIt if needed,
520 * Sets quoted if string was quoted,
521 * Returns NULL on error,
522 * else returns string - absent any quotes.
525 * Moves condExpr to end of this token.
528 *-----------------------------------------------------------------------
530 /* coverity:[+alloc : arg-*2] */
532 CondGetString(Boolean doEval, Boolean *quoted, void **freeIt, Boolean strictLHS)
544 *quoted = qt = *condExpr == '"' ? 1 : 0;
547 for (start = condExpr; *condExpr && str == NULL; condExpr++) {
550 if (condExpr[1] != '\0') {
552 Buf_AddByte(&buf, *condExpr);
557 condExpr++; /* we don't want the quotes */
560 Buf_AddByte(&buf, *condExpr); /* likely? */
572 Buf_AddByte(&buf, *condExpr);
575 /* if we are in quotes, then an undefined variable is ok */
576 str = Var_Parse(condExpr, VAR_CMD,
577 ((!qt && doEval) ? VARF_UNDEFERR : 0) |
578 (doEval ? VARF_WANTRES : 0), &len, freeIt);
579 if (str == var_Error) {
585 * Even if !doEval, we still report syntax errors, which
586 * is what getting var_Error back with !doEval means.
593 * If the '$' was first char (no quotes), and we are
594 * followed by space, the operator or end of expression,
597 if ((condExpr == start + len) &&
598 (*condExpr == '\0' ||
599 isspace((unsigned char) *condExpr) ||
600 strchr("!=><)", *condExpr))) {
604 * Nope, we better copy str to buf
606 for (cp = str; *cp; cp++) {
607 Buf_AddByte(&buf, *cp);
613 str = NULL; /* not finished yet */
614 condExpr--; /* don't skip over next char */
617 if (strictLHS && !qt && *start != '$' &&
618 !isdigit((unsigned char) *start)) {
619 /* lhs must be quoted, a variable reference or number */
627 Buf_AddByte(&buf, *condExpr);
632 str = Buf_GetAll(&buf, NULL);
635 Buf_Destroy(&buf, FALSE);
640 *-----------------------------------------------------------------------
642 * Return the next token from the input.
645 * A Token for the next lexical token in the stream.
648 * condPushback will be set back to TOK_NONE if it is used.
650 *-----------------------------------------------------------------------
653 compare_expression(Boolean doEval)
667 lhsFree = rhsFree = FALSE;
668 lhsQuoted = rhsQuoted = FALSE;
671 * Parse the variable spec and skip over it, saving its
674 lhs = CondGetString(doEval, &lhsQuoted, &lhsFree, lhsStrict);
679 * Skip whitespace to get to the operator
681 while (isspace((unsigned char) *condExpr))
685 * Make sure the operator is a valid one. If it isn't a
686 * known relational operator, pretend we got a
695 if (condExpr[1] == '=') {
706 /* For .ifxxx "..." check for non-empty string. */
711 /* For .ifxxx <number> compare against zero */
712 if (CondCvtArg(lhs, &left)) {
716 /* For .if ${...} check for non-empty string (defProc is ifdef). */
717 if (if_info->form[0] == 0) {
721 /* Otherwise action default test ... */
722 t = if_info->defProc(strlen(lhs), lhs) != if_info->doNot;
726 while (isspace((unsigned char)*condExpr))
729 if (*condExpr == '\0') {
730 Parse_Error(PARSE_WARNING,
731 "Missing right-hand-side of operator");
735 rhs = CondGetString(doEval, &rhsQuoted, &rhsFree, FALSE);
739 if (rhsQuoted || lhsQuoted) {
741 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
742 Parse_Error(PARSE_WARNING,
743 "String comparison operator should be either == or !=");
748 fprintf(debug_file, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
752 * Null-terminate rhs and perform the comparison.
753 * t is set to the result.
756 t = strcmp(lhs, rhs) == 0;
758 t = strcmp(lhs, rhs) != 0;
762 * rhs is either a float or an integer. Convert both the
763 * lhs and the rhs to a double and compare the two.
766 if (!CondCvtArg(lhs, &left) || !CondCvtArg(rhs, &right))
767 goto do_string_compare;
770 fprintf(debug_file, "left = %f, right = %f, op = %.2s\n", left,
776 Parse_Error(PARSE_WARNING,
784 Parse_Error(PARSE_WARNING,
814 get_mpt_arg(Boolean doEval, char **linePtr, char **argPtr, const char *func MAKE_ATTR_UNUSED)
817 * Use Var_Parse to parse the spec in parens and return
818 * TOK_TRUE if the resulting string is empty.
825 /* We do all the work here and return the result as the length */
828 val = Var_Parse(cp - 1, VAR_CMD, doEval ? VARF_WANTRES : 0, &length, &freeIt);
830 * Advance *linePtr to beyond the closing ). Note that
831 * we subtract one because 'length' is calculated from 'cp - 1'.
833 *linePtr = cp - 1 + length;
835 if (val == var_Error) {
840 /* A variable is empty when it just contains spaces... 4/15/92, christos */
841 while (isspace(*(unsigned char *)val))
845 * For consistency with the other functions we can't generate the
848 length = *val ? 2 : 1;
854 CondDoEmpty(int arglen, const char *arg MAKE_ATTR_UNUSED)
860 compare_function(Boolean doEval)
862 static const struct fn_def {
865 int (*fn_getarg)(Boolean, char **, char **, const char *);
866 Boolean (*fn_proc)(int, const char *);
868 { "defined", 7, CondGetArg, CondDoDefined },
869 { "make", 4, CondGetArg, CondDoMake },
870 { "exists", 6, CondGetArg, CondDoExists },
871 { "empty", 5, get_mpt_arg, CondDoEmpty },
872 { "target", 6, CondGetArg, CondDoTarget },
873 { "commands", 8, CondGetArg, CondDoCommands },
874 { NULL, 0, NULL, NULL },
876 const struct fn_def *fn_def;
883 for (fn_def = fn_defs; fn_def->fn_name != NULL; fn_def++) {
884 if (!istoken(cp, fn_def->fn_name, fn_def->fn_name_len))
886 cp += fn_def->fn_name_len;
887 /* There can only be whitespace before the '(' */
888 while (isspace(*(unsigned char *)cp))
893 arglen = fn_def->fn_getarg(doEval, &cp, &arg, fn_def->fn_name);
896 return arglen < 0 ? TOK_ERROR : TOK_FALSE;
898 /* Evaluate the argument using the required function. */
899 t = !doEval || fn_def->fn_proc(arglen, arg);
905 /* Push anything numeric through the compare expression */
907 if (isdigit((unsigned char)cp[0]) || strchr("+-", cp[0]))
908 return compare_expression(doEval);
911 * Most likely we have a naked token to apply the default function to.
912 * However ".if a == b" gets here when the "a" is unquoted and doesn't
913 * start with a '$'. This surprises people.
914 * If what follows the function argument is a '=' or '!' then the syntax
915 * would be invalid if we did "defined(a)" - so instead treat as an
918 arglen = CondGetArg(doEval, &cp, &arg, NULL);
919 for (cp1 = cp; isspace(*(unsigned char *)cp1); cp1++)
921 if (*cp1 == '=' || *cp1 == '!')
922 return compare_expression(doEval);
926 * Evaluate the argument using the default function.
927 * This path always treats .if as .ifdef. To get here the character
928 * after .if must have been taken literally, so the argument cannot
929 * be empty - even if it contained a variable expansion.
931 t = !doEval || if_info->defProc(arglen, arg) != if_info->doNot;
937 CondToken(Boolean doEval)
943 condPushBack = TOK_NONE;
947 while (*condExpr == ' ' || *condExpr == '\t') {
962 if (condExpr[1] == '|') {
969 if (condExpr[1] == '&') {
986 return compare_expression(doEval);
989 return compare_function(doEval);
994 *-----------------------------------------------------------------------
996 * Parse a single term in the expression. This consists of a terminal
997 * symbol or TOK_NOT and a terminal symbol (not including the binary
999 * T -> defined(variable) | make(target) | exists(file) | symbol
1003 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
1006 * Tokens are consumed.
1008 *-----------------------------------------------------------------------
1011 CondT(Boolean doEval)
1015 t = CondToken(doEval);
1019 * If we reached the end of the expression, the expression
1023 } else if (t == TOK_LPAREN) {
1028 if (t != TOK_ERROR) {
1029 if (CondToken(doEval) != TOK_RPAREN) {
1033 } else if (t == TOK_NOT) {
1035 if (t == TOK_TRUE) {
1037 } else if (t == TOK_FALSE) {
1045 *-----------------------------------------------------------------------
1047 * Parse a conjunctive factor (nice name, wot?)
1051 * TOK_TRUE, TOK_FALSE or TOK_ERROR
1054 * Tokens are consumed.
1056 *-----------------------------------------------------------------------
1059 CondF(Boolean doEval)
1064 if (l != TOK_ERROR) {
1065 o = CondToken(doEval);
1071 * If T is TOK_FALSE, the whole thing will be TOK_FALSE, but we have to
1072 * parse the r.h.s. anyway (to throw it away).
1073 * If T is TOK_TRUE, the result is the r.h.s., be it an TOK_ERROR or no.
1075 if (l == TOK_TRUE) {
1091 *-----------------------------------------------------------------------
1093 * Main expression production.
1097 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
1100 * Tokens are, of course, consumed.
1102 *-----------------------------------------------------------------------
1105 CondE(Boolean doEval)
1110 if (l != TOK_ERROR) {
1111 o = CondToken(doEval);
1117 * A similar thing occurs for ||, except that here we make sure
1118 * the l.h.s. is TOK_FALSE before we bother to evaluate the r.h.s.
1119 * Once again, if l is TOK_FALSE, the result is the r.h.s. and once
1120 * again if l is TOK_TRUE, we parse the r.h.s. to throw it away.
1122 if (l == TOK_FALSE) {
1138 *-----------------------------------------------------------------------
1139 * Cond_EvalExpression --
1140 * Evaluate an expression in the passed line. The expression
1141 * consists of &&, ||, !, make(target), defined(variable)
1142 * and parenthetical groupings thereof.
1145 * COND_PARSE if the condition was valid grammatically
1146 * COND_INVALID if not a valid conditional.
1148 * (*value) is set to the boolean value of the condition
1153 *-----------------------------------------------------------------------
1156 Cond_EvalExpression(const struct If *info, char *line, Boolean *value, int eprint, Boolean strictLHS)
1158 static const struct If *dflt_info;
1159 const struct If *sv_if_info = if_info;
1160 char *sv_condExpr = condExpr;
1161 Token sv_condPushBack = condPushBack;
1164 lhsStrict = strictLHS;
1166 while (*line == ' ' || *line == '\t')
1169 if (info == NULL && (info = dflt_info) == NULL) {
1170 /* Scan for the entry for .if - it can't be first */
1171 for (info = ifs; ; info++)
1172 if (info->form[0] == 0)
1176 assert(info != NULL);
1180 condPushBack = TOK_NONE;
1182 rval = do_Cond_EvalExpression(value);
1184 if (rval == COND_INVALID && eprint)
1185 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", line);
1187 if_info = sv_if_info;
1188 condExpr = sv_condExpr;
1189 condPushBack = sv_condPushBack;
1195 do_Cond_EvalExpression(Boolean *value)
1198 switch (CondE(TRUE)) {
1200 if (CondToken(TRUE) == TOK_EOF) {
1206 if (CondToken(TRUE) == TOK_EOF) {
1216 return COND_INVALID;
1221 *-----------------------------------------------------------------------
1223 * Evaluate the conditional in the passed line. The line
1225 * .<cond-type> <expr>
1226 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1227 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1228 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1229 * and parenthetical groupings thereof.
1232 * line Line to parse
1235 * COND_PARSE if should parse lines after the conditional
1236 * COND_SKIP if should skip lines after the conditional
1237 * COND_INVALID if not a valid conditional.
1242 * Note that the states IF_ACTIVE and ELSE_ACTIVE are only different in order
1243 * to detect splurious .else lines (as are SKIP_TO_ELSE and SKIP_TO_ENDIF)
1244 * otherwise .else could be treated as '.elif 1'.
1246 *-----------------------------------------------------------------------
1249 Cond_Eval(char *line)
1251 #define MAXIF 128 /* maximum depth of .if'ing */
1252 #define MAXIF_BUMP 32 /* how much to grow by */
1254 IF_ACTIVE, /* .if or .elif part active */
1255 ELSE_ACTIVE, /* .else part active */
1256 SEARCH_FOR_ELIF, /* searching for .elif/else to execute */
1257 SKIP_TO_ELSE, /* has been true, but not seen '.else' */
1258 SKIP_TO_ENDIF /* nothing else to execute */
1260 static enum if_states *cond_state = NULL;
1261 static unsigned int max_if_depth = MAXIF;
1263 const struct If *ifp;
1266 int level; /* Level at which to report errors. */
1267 enum if_states state;
1269 level = PARSE_FATAL;
1271 cond_state = bmake_malloc(max_if_depth * sizeof(*cond_state));
1272 cond_state[0] = IF_ACTIVE;
1274 /* skip leading character (the '.') and any whitespace */
1275 for (line++; *line == ' ' || *line == '\t'; line++)
1278 /* Find what type of if we're dealing with. */
1279 if (line[0] == 'e') {
1280 if (line[1] != 'l') {
1281 if (!istoken(line + 1, "ndif", 4))
1282 return COND_INVALID;
1283 /* End of conditional section */
1284 if (cond_depth == cond_min_depth) {
1285 Parse_Error(level, "if-less endif");
1288 /* Return state for previous conditional */
1290 return cond_state[cond_depth] <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1293 /* Quite likely this is 'else' or 'elif' */
1295 if (istoken(line, "se", 2)) {
1297 if (cond_depth == cond_min_depth) {
1298 Parse_Error(level, "if-less else");
1302 state = cond_state[cond_depth];
1304 case SEARCH_FOR_ELIF:
1305 state = ELSE_ACTIVE;
1309 Parse_Error(PARSE_WARNING, "extra else");
1314 state = SKIP_TO_ENDIF;
1317 cond_state[cond_depth] = state;
1318 return state <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1320 /* Assume for now it is an elif */
1325 if (line[0] != 'i' || line[1] != 'f')
1326 /* Not an ifxxx or elifxxx line */
1327 return COND_INVALID;
1330 * Figure out what sort of conditional it is -- what its default
1331 * function is, etc. -- by looking in the table of valid "ifs"
1334 for (ifp = ifs; ; ifp++) {
1335 if (ifp->form == NULL)
1336 return COND_INVALID;
1337 if (istoken(ifp->form, line, ifp->formlen)) {
1338 line += ifp->formlen;
1343 /* Now we know what sort of 'if' it is... */
1346 if (cond_depth == cond_min_depth) {
1347 Parse_Error(level, "if-less elif");
1350 state = cond_state[cond_depth];
1351 if (state == SKIP_TO_ENDIF || state == ELSE_ACTIVE) {
1352 Parse_Error(PARSE_WARNING, "extra elif");
1353 cond_state[cond_depth] = SKIP_TO_ENDIF;
1356 if (state != SEARCH_FOR_ELIF) {
1357 /* Either just finished the 'true' block, or already SKIP_TO_ELSE */
1358 cond_state[cond_depth] = SKIP_TO_ELSE;
1363 if (cond_depth + 1 >= max_if_depth) {
1365 * This is rare, but not impossible.
1366 * In meta mode, dirdeps.mk (only runs at level 0)
1367 * can need more than the default.
1369 max_if_depth += MAXIF_BUMP;
1370 cond_state = bmake_realloc(cond_state, max_if_depth *
1371 sizeof(*cond_state));
1373 state = cond_state[cond_depth];
1375 if (state > ELSE_ACTIVE) {
1376 /* If we aren't parsing the data, treat as always false */
1377 cond_state[cond_depth] = SKIP_TO_ELSE;
1382 /* And evaluate the conditional expresssion */
1383 if (Cond_EvalExpression(ifp, line, &value, 1, TRUE) == COND_INVALID) {
1384 /* Syntax error in conditional, error message already output. */
1385 /* Skip everything to matching .endif */
1386 cond_state[cond_depth] = SKIP_TO_ELSE;
1391 cond_state[cond_depth] = SEARCH_FOR_ELIF;
1394 cond_state[cond_depth] = IF_ACTIVE;
1401 *-----------------------------------------------------------------------
1403 * Make sure everything's clean at the end of a makefile.
1409 * Parse_Error will be called if open conditionals are around.
1411 *-----------------------------------------------------------------------
1414 Cond_restore_depth(unsigned int saved_depth)
1416 int open_conds = cond_depth - cond_min_depth;
1418 if (open_conds != 0 || saved_depth > cond_depth) {
1419 Parse_Error(PARSE_FATAL, "%d open conditional%s", open_conds,
1420 open_conds == 1 ? "" : "s");
1421 cond_depth = cond_min_depth;
1424 cond_min_depth = saved_depth;
1428 Cond_save_depth(void)
1430 int depth = cond_min_depth;
1432 cond_min_depth = cond_depth;