1 /* $NetBSD: cond.c,v 1.106 2020/08/29 13:38:48 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.106 2020/08/29 13:38:48 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.106 2020/08/29 13:38:48 rillig Exp $");
87 * Functions to handle conditionals in a makefile.
90 * Cond_Eval Evaluate the conditional in the passed line.
100 * The parsing of conditional expressions is based on this grammar:
105 * T -> defined(variable)
108 * T -> empty(varspec)
110 * T -> commands(name)
112 * T -> $(varspec) op value
113 * T -> $(varspec) == "string"
114 * T -> $(varspec) != "string"
118 * op -> == | != | > | < | >= | <=
120 * 'symbol' is some other symbol to which the default function is applied.
122 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
123 * will return TOK_AND for '&' and '&&', TOK_OR for '|' and '||',
124 * TOK_NOT for '!', TOK_LPAREN for '(', TOK_RPAREN for ')' and will evaluate
125 * the other terminal symbols, using either the default function or the
126 * function given in the terminal, and return the result as either TOK_TRUE
129 * TOK_FALSE is 0 and TOK_TRUE 1 so we can directly assign C comparisons.
131 * All Non-Terminal functions (CondE, CondF and CondT) return TOK_ERROR on
135 TOK_FALSE = 0, TOK_TRUE = 1, TOK_AND, TOK_OR, TOK_NOT,
136 TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
139 static Token CondE(Boolean);
140 static CondEvalResult do_Cond_EvalExpression(Boolean *);
142 static const struct If *if_info; /* Info for current statement */
143 static const char *condExpr; /* The expression to parse */
144 static Token condPushBack = TOK_NONE; /* Single push-back token used in
147 static unsigned int cond_depth = 0; /* current .if nesting level */
148 static unsigned int cond_min_depth = 0; /* depth at makefile open */
151 * Indicate when we should be strict about lhs of comparisons.
152 * TRUE when Cond_EvalExpression is called from Cond_Eval (.if etc)
153 * FALSE when Cond_EvalExpression is called from var.c:ApplyModifiers
154 * since lhs is already expanded and we cannot tell if
155 * it was a variable reference or not.
157 static Boolean lhsStrict;
160 istoken(const char *str, const char *tok, size_t len)
162 return strncmp(str, tok, len) == 0 && !isalpha((unsigned char)str[len]);
165 /* Push back the most recent token read. We only need one level of
166 * this, so the thing is just stored in 'condPushback'. */
168 CondPushBack(Token t)
174 * Parse the argument of a built-in function.
177 * The length of the argument.
178 * *argPtr receives the argument as string.
179 * *linePtr is updated to point behind the ')' of the function call.
182 CondGetArg(Boolean doEval, const char **linePtr, char **argPtr,
193 /* Skip opening '(' - verified by caller */
198 * No arguments whatsoever. Because 'make' and 'defined' aren't really
199 * "reserved words", we don't print a message. I think this is better
200 * than hitting the user with a warning message every time s/he uses
201 * the word 'make' or 'defined' at the beginning of a symbol...
207 while (*cp == ' ' || *cp == '\t') {
212 * Create a buffer for the argument and start it out at 16 characters
213 * long. Why 16? Why not?
220 if (ch == 0 || ch == ' ' || ch == '\t')
222 if ((ch == '&' || ch == '|') && paren_depth == 0)
226 * Parse the variable spec and install it as part of the argument
227 * if it's valid. We tell Var_Parse to complain on an undefined
228 * variable, so we don't do it too. Nor do we return an error,
229 * though perhaps we should...
233 VarEvalFlags eflags = VARE_UNDEFERR | (doEval ? VARE_WANTRES : 0);
234 const char *cp2 = Var_Parse(cp, VAR_CMD, eflags, &len, &freeIt);
235 Buf_AddStr(&buf, cp2);
242 else if (ch == ')' && --paren_depth < 0)
244 Buf_AddByte(&buf, *cp);
248 *argPtr = Buf_GetAll(&buf, &argLen);
249 Buf_Destroy(&buf, FALSE);
251 while (*cp == ' ' || *cp == '\t') {
255 if (func != NULL && *cp++ != ')') {
256 Parse_Error(PARSE_WARNING, "Missing closing parenthesis for %s()",
265 /* Test whether the given variable is defined. */
267 CondDoDefined(int argLen MAKE_ATTR_UNUSED, const char *arg)
270 Boolean result = Var_Value(arg, VAR_CMD, &freeIt) != NULL;
275 /* Wrapper around Str_Match, to be used by Lst_Find. */
277 CondFindStrMatch(const void *string, const void *pattern)
279 return Str_Match(string, pattern);
282 /* See if the given target is being made. */
284 CondDoMake(int argLen MAKE_ATTR_UNUSED, const char *arg)
286 return Lst_Find(create, CondFindStrMatch, arg) != NULL;
289 /* See if the given file exists. */
291 CondDoExists(int argLen MAKE_ATTR_UNUSED, const char *arg)
296 path = Dir_FindFile(arg, dirSearchPath);
298 fprintf(debug_file, "exists(%s) result is \"%s\"\n",
299 arg, path ? path : "");
310 /* See if the given node exists and is an actual target. */
312 CondDoTarget(int argLen MAKE_ATTR_UNUSED, const char *arg)
316 gn = Targ_FindNode(arg, TARG_NOCREATE);
317 return gn != NULL && !OP_NOP(gn->type);
320 /* See if the given node exists and is an actual target with commands
321 * associated with it. */
323 CondDoCommands(int argLen MAKE_ATTR_UNUSED, const char *arg)
327 gn = Targ_FindNode(arg, TARG_NOCREATE);
328 return gn != NULL && !OP_NOP(gn->type) && !Lst_IsEmpty(gn->commands);
332 * Convert the given number into a double.
333 * We try a base 10 or 16 integer conversion first, if that fails
334 * then we try a floating point conversion instead.
337 * Sets 'value' to double value of string.
338 * Returns TRUE if the conversion succeeded.
341 CondCvtArg(const char *str, double *value)
352 l_val = strtoul(str, &eptr, str[1] == 'x' ? 16 : 10);
354 if (ech == 0 && errno != ERANGE) {
355 d_val = str[0] == '-' ? -(double)-l_val : (double)l_val;
357 if (ech != 0 && ech != '.' && ech != 'e' && ech != 'E')
359 d_val = strtod(str, &eptr);
369 * Get a string from a variable reference or an optionally quoted
370 * string. This is called for the lhs and rhs of string compares.
373 * Returns the string, absent any quotes, or NULL on error.
374 * Sets quoted if the string was quoted.
375 * Sets freeIt if needed.
378 * Moves condExpr past the end of this token.
380 /* coverity:[+alloc : arg-*2] */
382 CondGetString(Boolean doEval, Boolean *quoted, void **freeIt, Boolean strictLHS)
395 *quoted = qt = *condExpr == '"' ? 1 : 0;
398 for (start = condExpr; *condExpr && str == NULL; condExpr++) {
401 if (condExpr[1] != '\0') {
403 Buf_AddByte(&buf, *condExpr);
408 condExpr++; /* we don't want the quotes */
411 Buf_AddByte(&buf, *condExpr); /* likely? */
423 Buf_AddByte(&buf, *condExpr);
426 /* if we are in quotes, then an undefined variable is ok */
427 eflags = ((!qt && doEval) ? VARE_UNDEFERR : 0) |
428 (doEval ? VARE_WANTRES : 0);
429 str = Var_Parse(condExpr, VAR_CMD, eflags, &len, freeIt);
430 if (str == var_Error) {
436 * Even if !doEval, we still report syntax errors, which
437 * is what getting var_Error back with !doEval means.
444 * If the '$' was first char (no quotes), and we are
445 * followed by space, the operator or end of expression,
448 if ((condExpr == start + len) &&
449 (*condExpr == '\0' ||
450 isspace((unsigned char)*condExpr) ||
451 strchr("!=><)", *condExpr))) {
455 * Nope, we better copy str to buf
457 for (cp = str; *cp; cp++) {
458 Buf_AddByte(&buf, *cp);
464 str = NULL; /* not finished yet */
465 condExpr--; /* don't skip over next char */
468 if (strictLHS && !qt && *start != '$' &&
469 !isdigit((unsigned char)*start)) {
470 /* lhs must be quoted, a variable reference or number */
478 Buf_AddByte(&buf, *condExpr);
483 *freeIt = Buf_GetAll(&buf, NULL);
486 Buf_Destroy(&buf, FALSE);
490 /* The different forms of #if's. */
491 static const struct If {
492 const char *form; /* Form of if */
493 size_t formlen; /* Length of form */
494 Boolean doNot; /* TRUE if default function should be negated */
495 Boolean (*defProc)(int, const char *); /* Default function to apply */
497 { "def", 3, FALSE, CondDoDefined },
498 { "ndef", 4, TRUE, CondDoDefined },
499 { "make", 4, FALSE, CondDoMake },
500 { "nmake", 5, TRUE, CondDoMake },
501 { "", 0, FALSE, CondDoDefined },
502 { NULL, 0, FALSE, NULL }
506 * Return the next token from the input.
509 * condPushback will be set back to TOK_NONE if it is used.
512 compare_expression(Boolean doEval)
526 lhsFree = rhsFree = NULL;
527 lhsQuoted = rhsQuoted = FALSE;
530 * Parse the variable spec and skip over it, saving its
533 lhs = CondGetString(doEval, &lhsQuoted, &lhsFree, lhsStrict);
538 * Skip whitespace to get to the operator
540 while (isspace((unsigned char)*condExpr))
544 * Make sure the operator is a valid one. If it isn't a
545 * known relational operator, pretend we got a
554 if (condExpr[1] == '=') {
565 /* For .ifxxx "..." check for non-empty string. */
570 /* For .ifxxx <number> compare against zero */
571 if (CondCvtArg(lhs, &left)) {
575 /* For .if ${...} check for non-empty string (defProc is ifdef). */
576 if (if_info->form[0] == 0) {
580 /* Otherwise action default test ... */
581 t = if_info->defProc(strlen(lhs), lhs) != if_info->doNot;
585 while (isspace((unsigned char)*condExpr))
588 if (*condExpr == '\0') {
589 Parse_Error(PARSE_WARNING,
590 "Missing right-hand-side of operator");
594 rhs = CondGetString(doEval, &rhsQuoted, &rhsFree, FALSE);
603 if (rhsQuoted || lhsQuoted) {
605 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
606 Parse_Error(PARSE_WARNING,
607 "String comparison operator should be either == or !=");
612 fprintf(debug_file, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
616 * Null-terminate rhs and perform the comparison.
617 * t is set to the result.
620 t = strcmp(lhs, rhs) == 0;
622 t = strcmp(lhs, rhs) != 0;
626 * rhs is either a float or an integer. Convert both the
627 * lhs and the rhs to a double and compare the two.
630 if (!CondCvtArg(lhs, &left) || !CondCvtArg(rhs, &right))
631 goto do_string_compare;
634 fprintf(debug_file, "left = %f, right = %f, op = %.2s\n", left,
640 Parse_Error(PARSE_WARNING,
648 Parse_Error(PARSE_WARNING,
678 get_mpt_arg(Boolean doEval, const char **linePtr, char **argPtr,
679 const char *func MAKE_ATTR_UNUSED)
682 * Use Var_Parse to parse the spec in parens and return
683 * TOK_TRUE if the resulting string is empty.
688 const char *cp = *linePtr;
690 /* We do all the work here and return the result as the length */
693 val = Var_Parse(cp - 1, VAR_CMD, doEval ? VARE_WANTRES : 0, &length,
696 * Advance *linePtr to beyond the closing ). Note that
697 * we subtract one because 'length' is calculated from 'cp - 1'.
699 *linePtr = cp - 1 + length;
701 if (val == var_Error) {
706 /* A variable is empty when it just contains spaces... 4/15/92, christos */
707 while (isspace((unsigned char)val[0]))
711 * For consistency with the other functions we can't generate the
714 length = *val ? 2 : 1;
720 CondDoEmpty(int arglen, const char *arg MAKE_ATTR_UNUSED)
726 compare_function(Boolean doEval)
728 static const struct fn_def {
731 int (*fn_getarg)(Boolean, const char **, char **, const char *);
732 Boolean (*fn_proc)(int, const char *);
734 { "defined", 7, CondGetArg, CondDoDefined },
735 { "make", 4, CondGetArg, CondDoMake },
736 { "exists", 6, CondGetArg, CondDoExists },
737 { "empty", 5, get_mpt_arg, CondDoEmpty },
738 { "target", 6, CondGetArg, CondDoTarget },
739 { "commands", 8, CondGetArg, CondDoCommands },
740 { NULL, 0, NULL, NULL },
742 const struct fn_def *fn_def;
746 const char *cp = condExpr;
749 for (fn_def = fn_defs; fn_def->fn_name != NULL; fn_def++) {
750 if (!istoken(cp, fn_def->fn_name, fn_def->fn_name_len))
752 cp += fn_def->fn_name_len;
753 /* There can only be whitespace before the '(' */
754 while (isspace((unsigned char)*cp))
759 arglen = fn_def->fn_getarg(doEval, &cp, &arg, fn_def->fn_name);
762 return arglen < 0 ? TOK_ERROR : TOK_FALSE;
764 /* Evaluate the argument using the required function. */
765 t = !doEval || fn_def->fn_proc(arglen, arg);
771 /* Push anything numeric through the compare expression */
773 if (isdigit((unsigned char)cp[0]) || strchr("+-", cp[0]))
774 return compare_expression(doEval);
777 * Most likely we have a naked token to apply the default function to.
778 * However ".if a == b" gets here when the "a" is unquoted and doesn't
779 * start with a '$'. This surprises people.
780 * If what follows the function argument is a '=' or '!' then the syntax
781 * would be invalid if we did "defined(a)" - so instead treat as an
784 arglen = CondGetArg(doEval, &cp, &arg, NULL);
785 for (cp1 = cp; isspace((unsigned char)*cp1); cp1++)
787 if (*cp1 == '=' || *cp1 == '!')
788 return compare_expression(doEval);
792 * Evaluate the argument using the default function.
793 * This path always treats .if as .ifdef. To get here the character
794 * after .if must have been taken literally, so the argument cannot
795 * be empty - even if it contained a variable expansion.
797 t = !doEval || if_info->defProc(arglen, arg) != if_info->doNot;
803 CondToken(Boolean doEval)
809 condPushBack = TOK_NONE;
813 while (*condExpr == ' ' || *condExpr == '\t') {
828 if (condExpr[1] == '|') {
835 if (condExpr[1] == '&') {
852 return compare_expression(doEval);
855 return compare_function(doEval);
860 *-----------------------------------------------------------------------
862 * Parse a single term in the expression. This consists of a terminal
863 * symbol or TOK_NOT and a terminal symbol (not including the binary
865 * T -> defined(variable) | make(target) | exists(file) | symbol
869 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
872 * Tokens are consumed.
874 *-----------------------------------------------------------------------
877 CondT(Boolean doEval)
881 t = CondToken(doEval);
885 * If we reached the end of the expression, the expression
889 } else if (t == TOK_LPAREN) {
894 if (t != TOK_ERROR) {
895 if (CondToken(doEval) != TOK_RPAREN) {
899 } else if (t == TOK_NOT) {
903 } else if (t == TOK_FALSE) {
911 *-----------------------------------------------------------------------
913 * Parse a conjunctive factor (nice name, wot?)
917 * TOK_TRUE, TOK_FALSE or TOK_ERROR
920 * Tokens are consumed.
922 *-----------------------------------------------------------------------
925 CondF(Boolean doEval)
930 if (l != TOK_ERROR) {
931 o = CondToken(doEval);
937 * If T is TOK_FALSE, the whole thing will be TOK_FALSE, but we have to
938 * parse the r.h.s. anyway (to throw it away).
939 * If T is TOK_TRUE, the result is the r.h.s., be it an TOK_ERROR or no.
957 *-----------------------------------------------------------------------
959 * Main expression production.
963 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
966 * Tokens are, of course, consumed.
968 *-----------------------------------------------------------------------
971 CondE(Boolean doEval)
976 if (l != TOK_ERROR) {
977 o = CondToken(doEval);
983 * A similar thing occurs for ||, except that here we make sure
984 * the l.h.s. is TOK_FALSE before we bother to evaluate the r.h.s.
985 * Once again, if l is TOK_FALSE, the result is the r.h.s. and once
986 * again if l is TOK_TRUE, we parse the r.h.s. to throw it away.
988 if (l == TOK_FALSE) {
1003 static CondEvalResult
1004 do_Cond_EvalExpression(Boolean *value)
1007 switch (CondE(TRUE)) {
1009 if (CondToken(TRUE) == TOK_EOF) {
1015 if (CondToken(TRUE) == TOK_EOF) {
1025 return COND_INVALID;
1029 *-----------------------------------------------------------------------
1030 * Cond_EvalExpression --
1031 * Evaluate an expression in the passed line. The expression
1032 * consists of &&, ||, !, make(target), defined(variable)
1033 * and parenthetical groupings thereof.
1036 * COND_PARSE if the condition was valid grammatically
1037 * COND_INVALID if not a valid conditional.
1039 * (*value) is set to the boolean value of the condition
1042 * Any effects from evaluating the variables.
1043 *-----------------------------------------------------------------------
1046 Cond_EvalExpression(const struct If *info, char *line, Boolean *value,
1047 int eprint, Boolean strictLHS)
1049 static const struct If *dflt_info;
1050 const struct If *sv_if_info = if_info;
1051 const char *sv_condExpr = condExpr;
1052 Token sv_condPushBack = condPushBack;
1055 lhsStrict = strictLHS;
1057 while (*line == ' ' || *line == '\t')
1060 if (info == NULL && (info = dflt_info) == NULL) {
1061 /* Scan for the entry for .if - it can't be first */
1062 for (info = ifs;; info++)
1063 if (info->form[0] == 0)
1067 assert(info != NULL);
1071 condPushBack = TOK_NONE;
1073 rval = do_Cond_EvalExpression(value);
1075 if (rval == COND_INVALID && eprint)
1076 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", line);
1078 if_info = sv_if_info;
1079 condExpr = sv_condExpr;
1080 condPushBack = sv_condPushBack;
1087 *-----------------------------------------------------------------------
1089 * Evaluate the conditional in the passed line. The line
1091 * .<cond-type> <expr>
1092 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1093 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1094 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1095 * and parenthetical groupings thereof.
1098 * line Line to parse
1101 * COND_PARSE if should parse lines after the conditional
1102 * COND_SKIP if should skip lines after the conditional
1103 * COND_INVALID if not a valid conditional.
1105 * Note that the states IF_ACTIVE and ELSE_ACTIVE are only different in order
1106 * to detect spurious .else lines (as are SKIP_TO_ELSE and SKIP_TO_ENDIF),
1107 * otherwise .else could be treated as '.elif 1'.
1108 *-----------------------------------------------------------------------
1111 Cond_Eval(char *line)
1113 enum { MAXIF = 128 }; /* maximum depth of .if'ing */
1114 enum { MAXIF_BUMP = 32 }; /* how much to grow by */
1116 IF_ACTIVE, /* .if or .elif part active */
1117 ELSE_ACTIVE, /* .else part active */
1118 SEARCH_FOR_ELIF, /* searching for .elif/else to execute */
1119 SKIP_TO_ELSE, /* has been true, but not seen '.else' */
1120 SKIP_TO_ENDIF /* nothing else to execute */
1122 static enum if_states *cond_state = NULL;
1123 static unsigned int max_if_depth = MAXIF;
1125 const struct If *ifp;
1128 int level; /* Level at which to report errors. */
1129 enum if_states state;
1131 level = PARSE_FATAL;
1133 cond_state = bmake_malloc(max_if_depth * sizeof(*cond_state));
1134 cond_state[0] = IF_ACTIVE;
1136 /* skip leading character (the '.') and any whitespace */
1137 for (line++; *line == ' ' || *line == '\t'; line++)
1140 /* Find what type of if we're dealing with. */
1141 if (line[0] == 'e') {
1142 if (line[1] != 'l') {
1143 if (!istoken(line + 1, "ndif", 4))
1144 return COND_INVALID;
1145 /* End of conditional section */
1146 if (cond_depth == cond_min_depth) {
1147 Parse_Error(level, "if-less endif");
1150 /* Return state for previous conditional */
1152 return cond_state[cond_depth] <= ELSE_ACTIVE
1153 ? COND_PARSE : COND_SKIP;
1156 /* Quite likely this is 'else' or 'elif' */
1158 if (istoken(line, "se", 2)) {
1160 if (cond_depth == cond_min_depth) {
1161 Parse_Error(level, "if-less else");
1165 state = cond_state[cond_depth];
1167 case SEARCH_FOR_ELIF:
1168 state = ELSE_ACTIVE;
1172 Parse_Error(PARSE_WARNING, "extra else");
1177 state = SKIP_TO_ENDIF;
1180 cond_state[cond_depth] = state;
1181 return state <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1183 /* Assume for now it is an elif */
1188 if (line[0] != 'i' || line[1] != 'f')
1189 /* Not an ifxxx or elifxxx line */
1190 return COND_INVALID;
1193 * Figure out what sort of conditional it is -- what its default
1194 * function is, etc. -- by looking in the table of valid "ifs"
1197 for (ifp = ifs;; ifp++) {
1198 if (ifp->form == NULL)
1199 return COND_INVALID;
1200 if (istoken(ifp->form, line, ifp->formlen)) {
1201 line += ifp->formlen;
1206 /* Now we know what sort of 'if' it is... */
1209 if (cond_depth == cond_min_depth) {
1210 Parse_Error(level, "if-less elif");
1213 state = cond_state[cond_depth];
1214 if (state == SKIP_TO_ENDIF || state == ELSE_ACTIVE) {
1215 Parse_Error(PARSE_WARNING, "extra elif");
1216 cond_state[cond_depth] = SKIP_TO_ENDIF;
1219 if (state != SEARCH_FOR_ELIF) {
1220 /* Either just finished the 'true' block, or already SKIP_TO_ELSE */
1221 cond_state[cond_depth] = SKIP_TO_ELSE;
1226 if (cond_depth + 1 >= max_if_depth) {
1228 * This is rare, but not impossible.
1229 * In meta mode, dirdeps.mk (only runs at level 0)
1230 * can need more than the default.
1232 max_if_depth += MAXIF_BUMP;
1233 cond_state = bmake_realloc(cond_state,
1234 max_if_depth * sizeof(*cond_state));
1236 state = cond_state[cond_depth];
1238 if (state > ELSE_ACTIVE) {
1239 /* If we aren't parsing the data, treat as always false */
1240 cond_state[cond_depth] = SKIP_TO_ELSE;
1245 /* And evaluate the conditional expresssion */
1246 if (Cond_EvalExpression(ifp, line, &value, 1, TRUE) == COND_INVALID) {
1247 /* Syntax error in conditional, error message already output. */
1248 /* Skip everything to matching .endif */
1249 cond_state[cond_depth] = SKIP_TO_ELSE;
1254 cond_state[cond_depth] = SEARCH_FOR_ELIF;
1257 cond_state[cond_depth] = IF_ACTIVE;
1262 Cond_restore_depth(unsigned int saved_depth)
1264 int open_conds = cond_depth - cond_min_depth;
1266 if (open_conds != 0 || saved_depth > cond_depth) {
1267 Parse_Error(PARSE_FATAL, "%d open conditional%s", open_conds,
1268 open_conds == 1 ? "" : "s");
1269 cond_depth = cond_min_depth;
1272 cond_min_depth = saved_depth;
1276 Cond_save_depth(void)
1278 int depth = cond_min_depth;
1280 cond_min_depth = cond_depth;