1 /* $NetBSD: cond.c,v 1.67 2012/11/03 13:59:27 christos 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.67 2012/11/03 13:59:27 christos 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.67 2012/11/03 13:59:27 christos Exp $");
87 * Functions to handle conditionals in a makefile.
90 * Cond_Eval Evaluate the conditional in the passed line.
95 #include <errno.h> /* For strtoul() error checking */
103 * The parsing of conditional expressions is based on this grammar:
108 * T -> defined(variable)
111 * T -> empty(varspec)
113 * T -> commands(name)
115 * T -> $(varspec) op value
116 * T -> $(varspec) == "string"
117 * T -> $(varspec) != "string"
121 * op -> == | != | > | < | >= | <=
123 * 'symbol' is some other symbol to which the default function (condDefProc)
126 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
127 * will return TOK_AND for '&' and '&&', TOK_OR for '|' and '||',
128 * TOK_NOT for '!', TOK_LPAREN for '(', TOK_RPAREN for ')' and will evaluate
129 * the other terminal symbols, using either the default function or the
130 * function given in the terminal, and return the result as either TOK_TRUE
133 * TOK_FALSE is 0 and TOK_TRUE 1 so we can directly assign C comparisons.
135 * All Non-Terminal functions (CondE, CondF and CondT) return TOK_ERROR on
139 TOK_FALSE = 0, TOK_TRUE = 1, TOK_AND, TOK_OR, TOK_NOT,
140 TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
144 * Structures to handle elegantly the different forms of #if's. The
145 * last two fields are stored in condInvert and condDefProc, respectively.
147 static void CondPushBack(Token);
148 static int CondGetArg(char **, char **, const char *);
149 static Boolean CondDoDefined(int, const char *);
150 static int CondStrMatch(const void *, const void *);
151 static Boolean CondDoMake(int, const char *);
152 static Boolean CondDoExists(int, const char *);
153 static Boolean CondDoTarget(int, const char *);
154 static Boolean CondDoCommands(int, const char *);
155 static Boolean CondCvtArg(char *, double *);
156 static Token CondToken(Boolean);
157 static Token CondT(Boolean);
158 static Token CondF(Boolean);
159 static Token CondE(Boolean);
160 static int do_Cond_EvalExpression(Boolean *);
162 static const struct If {
163 const char *form; /* Form of if */
164 int formlen; /* Length of form */
165 Boolean doNot; /* TRUE if default function should be negated */
166 Boolean (*defProc)(int, const char *); /* Default function to apply */
168 { "def", 3, FALSE, CondDoDefined },
169 { "ndef", 4, TRUE, CondDoDefined },
170 { "make", 4, FALSE, CondDoMake },
171 { "nmake", 5, TRUE, CondDoMake },
172 { "", 0, FALSE, CondDoDefined },
173 { NULL, 0, FALSE, NULL }
176 static const struct If *if_info; /* Info for current statement */
177 static char *condExpr; /* The expression to parse */
178 static Token condPushBack=TOK_NONE; /* Single push-back token used in
181 static unsigned int cond_depth = 0; /* current .if nesting level */
182 static unsigned int cond_min_depth = 0; /* depth at makefile open */
185 istoken(const char *str, const char *tok, size_t len)
187 return strncmp(str, tok, len) == 0 && !isalpha((unsigned char)str[len]);
191 *-----------------------------------------------------------------------
193 * Push back the most recent token read. We only need one level of
194 * this, so the thing is just stored in 'condPushback'.
197 * t Token to push back into the "stream"
203 * condPushback is overwritten.
205 *-----------------------------------------------------------------------
208 CondPushBack(Token t)
214 *-----------------------------------------------------------------------
216 * Find the argument of a built-in function.
219 * parens TRUE if arg should be bounded by parens
222 * The length of the argument and the address of the argument.
225 * The pointer is set to point to the closing parenthesis of the
228 *-----------------------------------------------------------------------
231 CondGetArg(char **linePtr, char **argPtr, const char *func)
241 /* Skip opening '(' - verfied by caller */
246 * No arguments whatsoever. Because 'make' and 'defined' aren't really
247 * "reserved words", we don't print a message. I think this is better
248 * than hitting the user with a warning message every time s/he uses
249 * the word 'make' or 'defined' at the beginning of a symbol...
255 while (*cp == ' ' || *cp == '\t') {
260 * Create a buffer for the argument and start it out at 16 characters
261 * long. Why 16? Why not?
268 if (ch == 0 || ch == ' ' || ch == '\t')
270 if ((ch == '&' || ch == '|') && paren_depth == 0)
274 * Parse the variable spec and install it as part of the argument
275 * if it's valid. We tell Var_Parse to complain on an undefined
276 * variable, so we don't do it too. Nor do we return an error,
277 * though perhaps we should...
283 cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &freeIt);
284 Buf_AddBytes(&buf, strlen(cp2), cp2);
293 if (ch == ')' && --paren_depth < 0)
295 Buf_AddByte(&buf, *cp);
299 *argPtr = Buf_GetAll(&buf, &argLen);
300 Buf_Destroy(&buf, FALSE);
302 while (*cp == ' ' || *cp == '\t') {
306 if (func != NULL && *cp++ != ')') {
307 Parse_Error(PARSE_WARNING, "Missing closing parenthesis for %s()",
317 *-----------------------------------------------------------------------
319 * Handle the 'defined' function for conditionals.
322 * TRUE if the given variable is defined.
327 *-----------------------------------------------------------------------
330 CondDoDefined(int argLen MAKE_ATTR_UNUSED, const char *arg)
335 if (Var_Value(arg, VAR_CMD, &p1) != NULL) {
346 *-----------------------------------------------------------------------
348 * Front-end for Str_Match so it returns 0 on match and non-zero
349 * on mismatch. Callback function for CondDoMake via Lst_Find
352 * 0 if string matches pattern
357 *-----------------------------------------------------------------------
360 CondStrMatch(const void *string, const void *pattern)
362 return(!Str_Match(string, pattern));
366 *-----------------------------------------------------------------------
368 * Handle the 'make' function for conditionals.
371 * TRUE if the given target is being made.
376 *-----------------------------------------------------------------------
379 CondDoMake(int argLen MAKE_ATTR_UNUSED, const char *arg)
381 return Lst_Find(create, arg, CondStrMatch) != NULL;
385 *-----------------------------------------------------------------------
387 * See if the given file exists.
390 * TRUE if the file exists and FALSE if it does not.
395 *-----------------------------------------------------------------------
398 CondDoExists(int argLen MAKE_ATTR_UNUSED, const char *arg)
403 path = Dir_FindFile(arg, dirSearchPath);
405 fprintf(debug_file, "exists(%s) result is \"%s\"\n",
406 arg, path ? path : "");
418 *-----------------------------------------------------------------------
420 * See if the given node exists and is an actual target.
423 * TRUE if the node exists as a target and FALSE if it does not.
428 *-----------------------------------------------------------------------
431 CondDoTarget(int argLen MAKE_ATTR_UNUSED, const char *arg)
435 gn = Targ_FindNode(arg, TARG_NOCREATE);
436 return (gn != NULL) && !OP_NOP(gn->type);
440 *-----------------------------------------------------------------------
442 * See if the given node exists and is an actual target with commands
443 * associated with it.
446 * TRUE if the node exists as a target and has commands associated with
447 * it and FALSE if it does not.
452 *-----------------------------------------------------------------------
455 CondDoCommands(int argLen MAKE_ATTR_UNUSED, const char *arg)
459 gn = Targ_FindNode(arg, TARG_NOCREATE);
460 return (gn != NULL) && !OP_NOP(gn->type) && !Lst_IsEmpty(gn->commands);
464 *-----------------------------------------------------------------------
466 * Convert the given number into a double.
467 * We try a base 10 or 16 integer conversion first, if that fails
468 * then we try a floating point conversion instead.
471 * Sets 'value' to double value of string.
472 * Returns 'true' if the convertion suceeded
474 *-----------------------------------------------------------------------
477 CondCvtArg(char *str, double *value)
484 l_val = strtoul(str, &eptr, str[1] == 'x' ? 16 : 10);
486 if (ech == 0 && errno != ERANGE) {
487 d_val = str[0] == '-' ? -(double)-l_val : (double)l_val;
489 if (ech != 0 && ech != '.' && ech != 'e' && ech != 'E')
491 d_val = strtod(str, &eptr);
501 *-----------------------------------------------------------------------
503 * Get a string from a variable reference or an optionally quoted
504 * string. This is called for the lhs and rhs of string compares.
507 * Sets freeIt if needed,
508 * Sets quoted if string was quoted,
509 * Returns NULL on error,
510 * else returns string - absent any quotes.
513 * Moves condExpr to end of this token.
516 *-----------------------------------------------------------------------
518 /* coverity:[+alloc : arg-*2] */
520 CondGetString(Boolean doEval, Boolean *quoted, void **freeIt)
532 *quoted = qt = *condExpr == '"' ? 1 : 0;
535 for (start = condExpr; *condExpr && str == NULL; condExpr++) {
538 if (condExpr[1] != '\0') {
540 Buf_AddByte(&buf, *condExpr);
545 condExpr++; /* we don't want the quotes */
548 Buf_AddByte(&buf, *condExpr); /* likely? */
560 Buf_AddByte(&buf, *condExpr);
563 /* if we are in quotes, then an undefined variable is ok */
564 str = Var_Parse(condExpr, VAR_CMD, (qt ? 0 : doEval),
566 if (str == var_Error) {
572 * Even if !doEval, we still report syntax errors, which
573 * is what getting var_Error back with !doEval means.
580 * If the '$' was first char (no quotes), and we are
581 * followed by space, the operator or end of expression,
584 if ((condExpr == start + len) &&
585 (*condExpr == '\0' ||
586 isspace((unsigned char) *condExpr) ||
587 strchr("!=><)", *condExpr))) {
591 * Nope, we better copy str to buf
593 for (cp = str; *cp; cp++) {
594 Buf_AddByte(&buf, *cp);
600 str = NULL; /* not finished yet */
601 condExpr--; /* don't skip over next char */
604 Buf_AddByte(&buf, *condExpr);
609 str = Buf_GetAll(&buf, NULL);
612 Buf_Destroy(&buf, FALSE);
617 *-----------------------------------------------------------------------
619 * Return the next token from the input.
622 * A Token for the next lexical token in the stream.
625 * condPushback will be set back to TOK_NONE if it is used.
627 *-----------------------------------------------------------------------
630 compare_expression(Boolean doEval)
644 lhsFree = rhsFree = FALSE;
645 lhsQuoted = rhsQuoted = FALSE;
648 * Parse the variable spec and skip over it, saving its
651 lhs = CondGetString(doEval, &lhsQuoted, &lhsFree);
656 * Skip whitespace to get to the operator
658 while (isspace((unsigned char) *condExpr))
662 * Make sure the operator is a valid one. If it isn't a
663 * known relational operator, pretend we got a
672 if (condExpr[1] == '=') {
683 /* For .ifxxx "..." check for non-empty string. */
688 /* For .ifxxx <number> compare against zero */
689 if (CondCvtArg(lhs, &left)) {
693 /* For .if ${...} check for non-empty string (defProc is ifdef). */
694 if (if_info->form[0] == 0) {
698 /* Otherwise action default test ... */
699 t = if_info->defProc(strlen(lhs), lhs) != if_info->doNot;
703 while (isspace((unsigned char)*condExpr))
706 if (*condExpr == '\0') {
707 Parse_Error(PARSE_WARNING,
708 "Missing right-hand-side of operator");
712 rhs = CondGetString(doEval, &rhsQuoted, &rhsFree);
716 if (rhsQuoted || lhsQuoted) {
718 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
719 Parse_Error(PARSE_WARNING,
720 "String comparison operator should be either == or !=");
725 fprintf(debug_file, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
729 * Null-terminate rhs and perform the comparison.
730 * t is set to the result.
733 t = strcmp(lhs, rhs) == 0;
735 t = strcmp(lhs, rhs) != 0;
739 * rhs is either a float or an integer. Convert both the
740 * lhs and the rhs to a double and compare the two.
743 if (!CondCvtArg(lhs, &left) || !CondCvtArg(rhs, &right))
744 goto do_string_compare;
747 fprintf(debug_file, "left = %f, right = %f, op = %.2s\n", left,
753 Parse_Error(PARSE_WARNING,
761 Parse_Error(PARSE_WARNING,
793 get_mpt_arg(char **linePtr, char **argPtr, const char *func MAKE_ATTR_UNUSED)
796 * Use Var_Parse to parse the spec in parens and return
797 * TOK_TRUE if the resulting string is empty.
804 /* We do all the work here and return the result as the length */
807 val = Var_Parse(cp - 1, VAR_CMD, FALSE, &length, &freeIt);
809 * Advance *linePtr to beyond the closing ). Note that
810 * we subtract one because 'length' is calculated from 'cp - 1'.
812 *linePtr = cp - 1 + length;
814 if (val == var_Error) {
819 /* A variable is empty when it just contains spaces... 4/15/92, christos */
820 while (isspace(*(unsigned char *)val))
824 * For consistency with the other functions we can't generate the
827 length = *val ? 2 : 1;
834 CondDoEmpty(int arglen, const char *arg MAKE_ATTR_UNUSED)
840 compare_function(Boolean doEval)
842 static const struct fn_def {
845 int (*fn_getarg)(char **, char **, const char *);
846 Boolean (*fn_proc)(int, const char *);
848 { "defined", 7, CondGetArg, CondDoDefined },
849 { "make", 4, CondGetArg, CondDoMake },
850 { "exists", 6, CondGetArg, CondDoExists },
851 { "empty", 5, get_mpt_arg, CondDoEmpty },
852 { "target", 6, CondGetArg, CondDoTarget },
853 { "commands", 8, CondGetArg, CondDoCommands },
854 { NULL, 0, NULL, NULL },
856 const struct fn_def *fn_def;
863 for (fn_def = fn_defs; fn_def->fn_name != NULL; fn_def++) {
864 if (!istoken(cp, fn_def->fn_name, fn_def->fn_name_len))
866 cp += fn_def->fn_name_len;
867 /* There can only be whitespace before the '(' */
868 while (isspace(*(unsigned char *)cp))
873 arglen = fn_def->fn_getarg(&cp, &arg, fn_def->fn_name);
876 return arglen < 0 ? TOK_ERROR : TOK_FALSE;
878 /* Evaluate the argument using the required function. */
879 t = !doEval || fn_def->fn_proc(arglen, arg);
886 /* Push anything numeric through the compare expression */
888 if (isdigit((unsigned char)cp[0]) || strchr("+-", cp[0]))
889 return compare_expression(doEval);
892 * Most likely we have a naked token to apply the default function to.
893 * However ".if a == b" gets here when the "a" is unquoted and doesn't
894 * start with a '$'. This surprises people.
895 * If what follows the function argument is a '=' or '!' then the syntax
896 * would be invalid if we did "defined(a)" - so instead treat as an
899 arglen = CondGetArg(&cp, &arg, NULL);
900 for (cp1 = cp; isspace(*(unsigned char *)cp1); cp1++)
902 if (*cp1 == '=' || *cp1 == '!')
903 return compare_expression(doEval);
907 * Evaluate the argument using the default function.
908 * This path always treats .if as .ifdef. To get here the character
909 * after .if must have been taken literally, so the argument cannot
910 * be empty - even if it contained a variable expansion.
912 t = !doEval || if_info->defProc(arglen, arg) != if_info->doNot;
919 CondToken(Boolean doEval)
925 condPushBack = TOK_NONE;
929 while (*condExpr == ' ' || *condExpr == '\t') {
944 if (condExpr[1] == '|') {
951 if (condExpr[1] == '&') {
968 return compare_expression(doEval);
971 return compare_function(doEval);
976 *-----------------------------------------------------------------------
978 * Parse a single term in the expression. This consists of a terminal
979 * symbol or TOK_NOT and a terminal symbol (not including the binary
981 * T -> defined(variable) | make(target) | exists(file) | symbol
985 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
988 * Tokens are consumed.
990 *-----------------------------------------------------------------------
993 CondT(Boolean doEval)
997 t = CondToken(doEval);
1001 * If we reached the end of the expression, the expression
1005 } else if (t == TOK_LPAREN) {
1010 if (t != TOK_ERROR) {
1011 if (CondToken(doEval) != TOK_RPAREN) {
1015 } else if (t == TOK_NOT) {
1017 if (t == TOK_TRUE) {
1019 } else if (t == TOK_FALSE) {
1027 *-----------------------------------------------------------------------
1029 * Parse a conjunctive factor (nice name, wot?)
1033 * TOK_TRUE, TOK_FALSE or TOK_ERROR
1036 * Tokens are consumed.
1038 *-----------------------------------------------------------------------
1041 CondF(Boolean doEval)
1046 if (l != TOK_ERROR) {
1047 o = CondToken(doEval);
1053 * If T is TOK_FALSE, the whole thing will be TOK_FALSE, but we have to
1054 * parse the r.h.s. anyway (to throw it away).
1055 * If T is TOK_TRUE, the result is the r.h.s., be it an TOK_ERROR or no.
1057 if (l == TOK_TRUE) {
1073 *-----------------------------------------------------------------------
1075 * Main expression production.
1079 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
1082 * Tokens are, of course, consumed.
1084 *-----------------------------------------------------------------------
1087 CondE(Boolean doEval)
1092 if (l != TOK_ERROR) {
1093 o = CondToken(doEval);
1099 * A similar thing occurs for ||, except that here we make sure
1100 * the l.h.s. is TOK_FALSE before we bother to evaluate the r.h.s.
1101 * Once again, if l is TOK_FALSE, the result is the r.h.s. and once
1102 * again if l is TOK_TRUE, we parse the r.h.s. to throw it away.
1104 if (l == TOK_FALSE) {
1120 *-----------------------------------------------------------------------
1121 * Cond_EvalExpression --
1122 * Evaluate an expression in the passed line. The expression
1123 * consists of &&, ||, !, make(target), defined(variable)
1124 * and parenthetical groupings thereof.
1127 * COND_PARSE if the condition was valid grammatically
1128 * COND_INVALID if not a valid conditional.
1130 * (*value) is set to the boolean value of the condition
1135 *-----------------------------------------------------------------------
1138 Cond_EvalExpression(const struct If *info, char *line, Boolean *value, int eprint)
1140 static const struct If *dflt_info;
1141 const struct If *sv_if_info = if_info;
1142 char *sv_condExpr = condExpr;
1143 Token sv_condPushBack = condPushBack;
1146 while (*line == ' ' || *line == '\t')
1149 if (info == NULL && (info = dflt_info) == NULL) {
1150 /* Scan for the entry for .if - it can't be first */
1151 for (info = ifs; ; info++)
1152 if (info->form[0] == 0)
1157 if_info = info != NULL ? info : ifs + 4;
1159 condPushBack = TOK_NONE;
1161 rval = do_Cond_EvalExpression(value);
1163 if (rval == COND_INVALID && eprint)
1164 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", line);
1166 if_info = sv_if_info;
1167 condExpr = sv_condExpr;
1168 condPushBack = sv_condPushBack;
1174 do_Cond_EvalExpression(Boolean *value)
1177 switch (CondE(TRUE)) {
1179 if (CondToken(TRUE) == TOK_EOF) {
1185 if (CondToken(TRUE) == TOK_EOF) {
1195 return COND_INVALID;
1200 *-----------------------------------------------------------------------
1202 * Evaluate the conditional in the passed line. The line
1204 * .<cond-type> <expr>
1205 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1206 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1207 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1208 * and parenthetical groupings thereof.
1211 * line Line to parse
1214 * COND_PARSE if should parse lines after the conditional
1215 * COND_SKIP if should skip lines after the conditional
1216 * COND_INVALID if not a valid conditional.
1221 * Note that the states IF_ACTIVE and ELSE_ACTIVE are only different in order
1222 * to detect splurious .else lines (as are SKIP_TO_ELSE and SKIP_TO_ENDIF)
1223 * otherwise .else could be treated as '.elif 1'.
1225 *-----------------------------------------------------------------------
1228 Cond_Eval(char *line)
1230 #define MAXIF 128 /* maximum depth of .if'ing */
1231 #define MAXIF_BUMP 32 /* how much to grow by */
1233 IF_ACTIVE, /* .if or .elif part active */
1234 ELSE_ACTIVE, /* .else part active */
1235 SEARCH_FOR_ELIF, /* searching for .elif/else to execute */
1236 SKIP_TO_ELSE, /* has been true, but not seen '.else' */
1237 SKIP_TO_ENDIF /* nothing else to execute */
1239 static enum if_states *cond_state = NULL;
1240 static unsigned int max_if_depth = MAXIF;
1242 const struct If *ifp;
1245 int level; /* Level at which to report errors. */
1246 enum if_states state;
1248 level = PARSE_FATAL;
1250 cond_state = bmake_malloc(max_if_depth * sizeof(*cond_state));
1251 cond_state[0] = IF_ACTIVE;
1253 /* skip leading character (the '.') and any whitespace */
1254 for (line++; *line == ' ' || *line == '\t'; line++)
1257 /* Find what type of if we're dealing with. */
1258 if (line[0] == 'e') {
1259 if (line[1] != 'l') {
1260 if (!istoken(line + 1, "ndif", 4))
1261 return COND_INVALID;
1262 /* End of conditional section */
1263 if (cond_depth == cond_min_depth) {
1264 Parse_Error(level, "if-less endif");
1267 /* Return state for previous conditional */
1269 return cond_state[cond_depth] <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1272 /* Quite likely this is 'else' or 'elif' */
1274 if (istoken(line, "se", 2)) {
1276 if (cond_depth == cond_min_depth) {
1277 Parse_Error(level, "if-less else");
1281 state = cond_state[cond_depth];
1283 case SEARCH_FOR_ELIF:
1284 state = ELSE_ACTIVE;
1288 Parse_Error(PARSE_WARNING, "extra else");
1293 state = SKIP_TO_ENDIF;
1296 cond_state[cond_depth] = state;
1297 return state <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1299 /* Assume for now it is an elif */
1304 if (line[0] != 'i' || line[1] != 'f')
1305 /* Not an ifxxx or elifxxx line */
1306 return COND_INVALID;
1309 * Figure out what sort of conditional it is -- what its default
1310 * function is, etc. -- by looking in the table of valid "ifs"
1313 for (ifp = ifs; ; ifp++) {
1314 if (ifp->form == NULL)
1315 return COND_INVALID;
1316 if (istoken(ifp->form, line, ifp->formlen)) {
1317 line += ifp->formlen;
1322 /* Now we know what sort of 'if' it is... */
1325 if (cond_depth == cond_min_depth) {
1326 Parse_Error(level, "if-less elif");
1329 state = cond_state[cond_depth];
1330 if (state == SKIP_TO_ENDIF || state == ELSE_ACTIVE) {
1331 Parse_Error(PARSE_WARNING, "extra elif");
1332 cond_state[cond_depth] = SKIP_TO_ENDIF;
1335 if (state != SEARCH_FOR_ELIF) {
1336 /* Either just finished the 'true' block, or already SKIP_TO_ELSE */
1337 cond_state[cond_depth] = SKIP_TO_ELSE;
1342 if (cond_depth + 1 >= max_if_depth) {
1344 * This is rare, but not impossible.
1345 * In meta mode, dirdeps.mk (only runs at level 0)
1346 * can need more than the default.
1348 max_if_depth += MAXIF_BUMP;
1349 cond_state = bmake_realloc(cond_state, max_if_depth *
1350 sizeof(*cond_state));
1352 state = cond_state[cond_depth];
1354 if (state > ELSE_ACTIVE) {
1355 /* If we aren't parsing the data, treat as always false */
1356 cond_state[cond_depth] = SKIP_TO_ELSE;
1361 /* And evaluate the conditional expresssion */
1362 if (Cond_EvalExpression(ifp, line, &value, 1) == COND_INVALID) {
1363 /* Syntax error in conditional, error message already output. */
1364 /* Skip everything to matching .endif */
1365 cond_state[cond_depth] = SKIP_TO_ELSE;
1370 cond_state[cond_depth] = SEARCH_FOR_ELIF;
1373 cond_state[cond_depth] = IF_ACTIVE;
1380 *-----------------------------------------------------------------------
1382 * Make sure everything's clean at the end of a makefile.
1388 * Parse_Error will be called if open conditionals are around.
1390 *-----------------------------------------------------------------------
1393 Cond_restore_depth(unsigned int saved_depth)
1395 int open_conds = cond_depth - cond_min_depth;
1397 if (open_conds != 0 || saved_depth > cond_depth) {
1398 Parse_Error(PARSE_FATAL, "%d open conditional%s", open_conds,
1399 open_conds == 1 ? "" : "s");
1400 cond_depth = cond_min_depth;
1403 cond_min_depth = saved_depth;
1407 Cond_save_depth(void)
1409 int depth = cond_min_depth;
1411 cond_min_depth = cond_depth;