1 /* $NetBSD: cond.c,v 1.235 2021/01/10 21:20:46 rillig Exp $ */
4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * Copyright (c) 1988, 1989 by Adam de Boor
37 * Copyright (c) 1989 by Berkeley Softworks
38 * All rights reserved.
40 * This code is derived from software contributed to Berkeley by
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. All advertising materials mentioning features or use of this software
52 * must display the following acknowledgement:
53 * This product includes software developed by the University of
54 * California, Berkeley and its contributors.
55 * 4. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
73 * Handling of conditionals in a makefile.
76 * Cond_EvalLine Evaluate the conditional directive, such as
77 * '.if <cond>', '.elifnmake <cond>', '.else', '.endif'.
80 * Evaluate the conditional, which is either the argument
81 * of one of the .if directives or the condition in a
82 * ':?then:else' variable modifier.
86 * Save and restore the nesting of the conditions, at
87 * the start and end of including another makefile, to
88 * ensure that in each makefile the conditional
89 * directives are well-balanced.
97 /* "@(#)cond.c 8.2 (Berkeley) 1/2/94" */
98 MAKE_RCSID("$NetBSD: cond.c,v 1.235 2021/01/10 21:20:46 rillig Exp $");
101 * The parsing of conditional expressions is based on this grammar:
106 * T -> defined(variable)
109 * T -> empty(varspec)
111 * T -> commands(name)
113 * T -> $(varspec) op value
114 * T -> $(varspec) == "string"
115 * T -> $(varspec) != "string"
119 * op -> == | != | > | < | >= | <=
121 * 'symbol' is some other symbol to which the default function is applied.
123 * The tokens are scanned by CondToken, which returns:
124 * TOK_AND for '&' or '&&'
125 * TOK_OR for '|' or '||'
129 * Other terminal symbols are evaluated using either the default function or
130 * the function given in the terminal, they return either TOK_TRUE or
133 * TOK_FALSE is 0 and TOK_TRUE 1 so we can directly assign C comparisons.
135 * All non-terminal functions (CondParser_Expr, CondParser_Factor and
136 * CondParser_Term) return either TOK_FALSE, TOK_TRUE, or TOK_ERROR on error.
139 TOK_FALSE = 0, TOK_TRUE = 1, TOK_AND, TOK_OR, TOK_NOT,
140 TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
143 typedef struct CondParser {
144 const struct If *if_info; /* Info for current statement */
145 const char *p; /* The remaining condition to parse */
146 Token curr; /* Single push-back token used in parsing */
149 * Whether an error message has already been printed for this
150 * condition. The first available error message is usually the most
151 * specific one, therefore it makes sense to suppress the standard
152 * "Malformed conditional" message.
154 Boolean printedError;
157 static Token CondParser_Expr(CondParser *par, Boolean);
159 static unsigned int cond_depth = 0; /* current .if nesting level */
160 static unsigned int cond_min_depth = 0; /* depth at makefile open */
163 * Indicate when we should be strict about lhs of comparisons.
164 * In strict mode, the lhs must be a variable expression or a string literal
165 * in quotes. In non-strict mode it may also be an unquoted string literal.
167 * TRUE when CondEvalExpression is called from Cond_EvalLine (.if etc)
168 * FALSE when CondEvalExpression is called from ApplyModifier_IfElse
169 * since lhs is already expanded, and at that point we cannot tell if
170 * it was a variable reference or not.
172 static Boolean lhsStrict;
175 is_token(const char *str, const char *tok, size_t len)
177 return strncmp(str, tok, len) == 0 && !ch_isalpha(str[len]);
181 ToToken(Boolean cond)
183 return cond ? TOK_TRUE : TOK_FALSE;
186 /* Push back the most recent token read. We only need one level of this. */
188 CondParser_PushBack(CondParser *par, Token t)
190 assert(par->curr == TOK_NONE);
191 assert(t != TOK_NONE);
197 CondParser_SkipWhitespace(CondParser *par)
199 cpp_skip_whitespace(&par->p);
203 * Parse the argument of a built-in function.
206 * *pp initially points at the '(',
207 * upon successful return it points right after the ')'.
209 * *out_arg receives the argument as string.
211 * func says whether the argument belongs to an actual function, or
212 * whether the parsed argument is passed to the default function.
214 * Return the length of the argument, or 0 on error.
217 ParseFuncArg(const char **pp, Boolean doEval, const char *func,
226 p++; /* Skip opening '(' - verified by caller */
229 *out_arg = NULL; /* Missing closing parenthesis: */
230 return 0; /* .if defined( */
235 Buf_InitSize(&argBuf, 16);
240 if (ch == '\0' || ch == ' ' || ch == '\t')
242 if ((ch == '&' || ch == '|') && paren_depth == 0)
246 * Parse the variable expression and install it as
247 * part of the argument if it's valid. We tell
248 * Var_Parse to complain on an undefined variable,
249 * (XXX: but Var_Parse ignores that request)
250 * so we don't need to do it. Nor do we return an
251 * error, though perhaps we should.
253 VarEvalFlags eflags = doEval
254 ? VARE_WANTRES | VARE_UNDEFERR
257 (void)Var_Parse(&p, VAR_CMDLINE, eflags, &nestedVal);
258 /* TODO: handle errors */
259 Buf_AddStr(&argBuf, nestedVal.str);
260 FStr_Done(&nestedVal);
265 else if (ch == ')' && --paren_depth < 0)
267 Buf_AddByte(&argBuf, *p);
271 *out_arg = Buf_GetAll(&argBuf, &argLen);
272 Buf_Destroy(&argBuf, FALSE);
276 if (func != NULL && *p++ != ')') {
277 Parse_Error(PARSE_WARNING,
278 "Missing closing parenthesis for %s()",
280 /* The PARSE_FATAL follows in CondEvalExpression. */
288 /* Test whether the given variable is defined. */
291 FuncDefined(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
293 FStr value = Var_Value(arg, VAR_CMDLINE);
294 Boolean result = value.str != NULL;
299 /* See if the given target is being made. */
302 FuncMake(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
306 for (ln = opts.create.first; ln != NULL; ln = ln->next)
307 if (Str_Match(ln->datum, arg))
312 /* See if the given file exists. */
315 FuncExists(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
320 path = Dir_FindFile(arg, &dirSearchPath);
321 DEBUG2(COND, "exists(%s) result is \"%s\"\n",
322 arg, path != NULL ? path : "");
323 result = path != NULL;
328 /* See if the given node exists and is an actual target. */
331 FuncTarget(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
333 GNode *gn = Targ_FindNode(arg);
334 return gn != NULL && GNode_IsTarget(gn);
338 * See if the given node exists and is an actual target with commands
339 * associated with it.
343 FuncCommands(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
345 GNode *gn = Targ_FindNode(arg);
346 return gn != NULL && GNode_IsTarget(gn) && !Lst_IsEmpty(&gn->commands);
350 * Convert the given number into a double.
351 * We try a base 10 or 16 integer conversion first, if that fails
352 * then we try a floating point conversion instead.
355 * Returns TRUE if the conversion succeeded.
356 * Sets 'out_value' to the converted number.
359 TryParseNumber(const char *str, double *out_value)
362 unsigned long ul_val;
366 if (str[0] == '\0') { /* XXX: why is an empty string a number? */
371 ul_val = strtoul(str, &end, str[1] == 'x' ? 16 : 10);
372 if (*end == '\0' && errno != ERANGE) {
373 *out_value = str[0] == '-' ? -(double)-ul_val : (double)ul_val;
377 if (*end != '\0' && *end != '.' && *end != 'e' && *end != 'E')
378 return FALSE; /* skip the expensive strtod call */
379 dbl_val = strtod(str, &end);
383 *out_value = dbl_val;
388 is_separator(char ch)
390 return ch == '\0' || ch_isspace(ch) || strchr("!=><)", ch) != NULL;
394 * Parse a string from a variable reference or an optionally quoted
395 * string. This is called for the lhs and rhs of string comparisons.
398 * Returns the string, absent any quotes, or NULL on error.
399 * Sets out_quoted if the string was quoted.
402 /* coverity:[+alloc : arg-*4] */
404 CondParser_String(CondParser *par, Boolean doEval, Boolean strictLHS,
405 FStr *out_str, Boolean *out_quoted)
410 const char *nested_p;
414 VarParseResult parseResult;
417 str = FStr_InitRefer(NULL);
418 *out_quoted = quoted = par->p[0] == '"';
423 while (par->p[0] != '\0' && str.str == NULL) {
427 if (par->p[0] != '\0') {
428 Buf_AddByte(&buf, par->p[0]);
434 par->p++; /* skip the closing quote */
437 Buf_AddByte(&buf, par->p[0]); /* likely? */
440 case ')': /* see is_separator */
449 Buf_AddByte(&buf, par->p[0]);
453 /* if we are in quotes, an undefined variable is ok */
455 doEval && !quoted ? VARE_WANTRES | VARE_UNDEFERR :
456 doEval ? VARE_WANTRES :
460 atStart = nested_p == start;
461 parseResult = Var_Parse(&nested_p, VAR_CMDLINE, eflags,
463 /* TODO: handle errors */
464 if (str.str == var_Error) {
465 if (parseResult == VPR_ERR)
466 par->printedError = TRUE;
468 * XXX: Can there be any situation in which
469 * a returned var_Error requires freeIt?
473 * Even if !doEval, we still report syntax
474 * errors, which is what getting var_Error
475 * back with !doEval means.
477 str = FStr_InitRefer(NULL);
483 * If the '$' started the string literal (which means
484 * no quotes), and the variable expression is followed
485 * by a space, looks like a comparison operator or is
486 * the end of the expression, we are done.
488 if (atStart && is_separator(par->p[0]))
491 Buf_AddStr(&buf, str.str);
493 str = FStr_InitRefer(NULL); /* not finished yet */
496 if (strictLHS && !quoted && *start != '$' &&
497 !ch_isdigit(*start)) {
499 * The left-hand side must be quoted,
500 * a variable reference or a number.
502 str = FStr_InitRefer(NULL);
505 Buf_AddByte(&buf, par->p[0]);
511 str = FStr_InitOwn(Buf_GetAll(&buf, NULL));
513 Buf_Destroy(&buf, FALSE);
518 const char *form; /* Form of if */
519 size_t formlen; /* Length of form */
520 Boolean doNot; /* TRUE if default function should be negated */
521 /* The default function to apply on unquoted bare words. */
522 Boolean (*defProc)(size_t, const char *);
525 /* The different forms of .if directives. */
526 static const struct If ifs[] = {
527 { "def", 3, FALSE, FuncDefined },
528 { "ndef", 4, TRUE, FuncDefined },
529 { "make", 4, FALSE, FuncMake },
530 { "nmake", 5, TRUE, FuncMake },
531 { "", 0, FALSE, FuncDefined },
532 { NULL, 0, FALSE, NULL }
539 If_Eval(const struct If *if_info, const char *arg, size_t arglen)
541 Boolean res = if_info->defProc(arglen, arg);
542 return if_info->doNot ? !res : res;
546 * Evaluate a "comparison without operator", such as in ".if ${VAR}" or
550 EvalNotEmpty(CondParser *par, const char *value, Boolean quoted)
554 /* For .ifxxx "...", check for non-empty string. */
556 return value[0] != '\0';
558 /* For .ifxxx <number>, compare against zero */
559 if (TryParseNumber(value, &num))
562 /* For .if ${...}, check for non-empty string. This is different from
563 * the evaluation function from that .if variant, which would test
564 * whether a variable of the given name were defined. */
565 /* XXX: Whitespace should count as empty, just as in ParseEmptyArg. */
566 if (par->if_info->form[0] == '\0')
567 return value[0] != '\0';
569 /* For the other variants of .ifxxx ${...}, use its default function. */
570 return If_Eval(par->if_info, value, strlen(value));
573 /* Evaluate a numerical comparison, such as in ".if ${VAR} >= 9". */
575 EvalCompareNum(double lhs, const char *op, double rhs)
577 DEBUG3(COND, "lhs = %f, rhs = %f, op = %.2s\n", lhs, rhs, op);
582 Parse_Error(PARSE_WARNING, "Unknown operator");
583 /* The PARSE_FATAL follows in CondEvalExpression. */
586 return ToToken(lhs != rhs);
589 Parse_Error(PARSE_WARNING, "Unknown operator");
590 /* The PARSE_FATAL follows in CondEvalExpression. */
593 return ToToken(lhs == rhs);
595 return ToToken(op[1] == '=' ? lhs <= rhs : lhs < rhs);
597 return ToToken(op[1] == '=' ? lhs >= rhs : lhs > rhs);
603 EvalCompareStr(const char *lhs, const char *op, const char *rhs)
605 if (!((op[0] == '!' || op[0] == '=') && op[1] == '=')) {
606 Parse_Error(PARSE_WARNING,
607 "String comparison operator "
608 "must be either == or !=");
609 /* The PARSE_FATAL follows in CondEvalExpression. */
613 DEBUG3(COND, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n", lhs, rhs, op);
614 return ToToken((*op == '=') == (strcmp(lhs, rhs) == 0));
617 /* Evaluate a comparison, such as "${VAR} == 12345". */
619 EvalCompare(const char *lhs, Boolean lhsQuoted, const char *op,
620 const char *rhs, Boolean rhsQuoted)
624 if (!rhsQuoted && !lhsQuoted)
625 if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
626 return EvalCompareNum(left, op, right);
628 return EvalCompareStr(lhs, op, rhs);
632 * Parse a comparison condition such as:
640 CondParser_Comparison(CondParser *par, Boolean doEval)
645 Boolean lhsQuoted, rhsQuoted;
648 * Parse the variable spec and skip over it, saving its
651 CondParser_String(par, doEval, lhsStrict, &lhs, &lhsQuoted);
655 CondParser_SkipWhitespace(par);
663 if (par->p[1] == '=')
669 /* Unknown operator, compare against an empty string or 0. */
670 t = ToToken(doEval && EvalNotEmpty(par, lhs.str, lhsQuoted));
674 CondParser_SkipWhitespace(par);
676 if (par->p[0] == '\0') {
677 Parse_Error(PARSE_WARNING,
678 "Missing right-hand-side of operator");
679 /* The PARSE_FATAL follows in CondEvalExpression. */
683 CondParser_String(par, doEval, FALSE, &rhs, &rhsQuoted);
692 t = EvalCompare(lhs.str, lhsQuoted, op, rhs.str, rhsQuoted);
702 * The argument to empty() is a variable name, optionally followed by
703 * variable modifiers.
707 ParseEmptyArg(const char **pp, Boolean doEval,
708 const char *func MAKE_ATTR_UNUSED, char **out_arg)
713 /* We do all the work here and return the result as the length */
716 (*pp)--; /* Make (*pp)[1] point to the '('. */
717 (void)Var_Parse(pp, VAR_CMDLINE, doEval ? VARE_WANTRES : VARE_NONE,
719 /* TODO: handle errors */
720 /* If successful, *pp points beyond the closing ')' now. */
722 if (val.str == var_Error) {
728 * A variable is empty when it just contains spaces...
731 cpp_skip_whitespace(&val.str);
734 * For consistency with the other functions we can't generate the
737 magic_res = val.str[0] != '\0' ? 2 : 1;
744 FuncEmpty(size_t arglen, const char *arg MAKE_ATTR_UNUSED)
746 /* Magic values ahead, see ParseEmptyArg. */
751 CondParser_Func(CondParser *par, Boolean doEval, Token *out_token)
753 static const struct fn_def {
756 size_t (*fn_parse)(const char **, Boolean, const char *,
758 Boolean (*fn_eval)(size_t, const char *);
760 { "defined", 7, ParseFuncArg, FuncDefined },
761 { "make", 4, ParseFuncArg, FuncMake },
762 { "exists", 6, ParseFuncArg, FuncExists },
763 { "empty", 5, ParseEmptyArg, FuncEmpty },
764 { "target", 6, ParseFuncArg, FuncTarget },
765 { "commands", 8, ParseFuncArg, FuncCommands }
767 const struct fn_def *fn;
770 const char *cp = par->p;
771 const struct fn_def *fns_end = fns + sizeof fns / sizeof fns[0];
773 for (fn = fns; fn != fns_end; fn++) {
774 if (!is_token(cp, fn->fn_name, fn->fn_name_len))
777 cp += fn->fn_name_len;
778 cpp_skip_whitespace(&cp);
782 arglen = fn->fn_parse(&cp, doEval, fn->fn_name, &arg);
783 if (arglen == 0 || arglen == (size_t)-1) {
785 *out_token = arglen == 0 ? TOK_FALSE : TOK_ERROR;
789 /* Evaluate the argument using the required function. */
790 *out_token = ToToken(!doEval || fn->fn_eval(arglen, arg));
800 * Parse a function call, a number, a variable expression or a string
804 CondParser_LeafToken(CondParser *par, Boolean doEval)
812 if (CondParser_Func(par, doEval, &t))
815 /* Push anything numeric through the compare expression */
817 if (ch_isdigit(cp[0]) || cp[0] == '-' || cp[0] == '+')
818 return CondParser_Comparison(par, doEval);
821 * Most likely we have a naked token to apply the default function to.
822 * However ".if a == b" gets here when the "a" is unquoted and doesn't
823 * start with a '$'. This surprises people.
824 * If what follows the function argument is a '=' or '!' then the
825 * syntax would be invalid if we did "defined(a)" - so instead treat
828 arglen = ParseFuncArg(&cp, doEval, NULL, &arg);
830 cpp_skip_whitespace(&cp1);
831 if (*cp1 == '=' || *cp1 == '!')
832 return CondParser_Comparison(par, doEval);
836 * Evaluate the argument using the default function.
837 * This path always treats .if as .ifdef. To get here, the character
838 * after .if must have been taken literally, so the argument cannot
839 * be empty - even if it contained a variable expansion.
841 t = ToToken(!doEval || If_Eval(par->if_info, arg, arglen));
846 /* Return the next token or comparison result from the parser. */
848 CondParser_Token(CondParser *par, Boolean doEval)
854 par->curr = TOK_NONE;
858 cpp_skip_hspace(&par->p);
872 if (par->p[0] == '|')
874 else if (opts.strict) {
875 Parse_Error(PARSE_FATAL, "Unknown operator '|'");
876 par->printedError = TRUE;
883 if (par->p[0] == '&')
885 else if (opts.strict) {
886 Parse_Error(PARSE_FATAL, "Unknown operator '&'");
887 par->printedError = TRUE;
896 case '#': /* XXX: see unit-tests/cond-token-plain.mk */
897 case '\n': /* XXX: why should this end the condition? */
898 /* Probably obsolete now, from 1993-03-21. */
904 return CondParser_Comparison(par, doEval);
907 return CondParser_LeafToken(par, doEval);
912 * Parse a single term in the expression. This consists of a terminal symbol
913 * or TOK_NOT and a term (not including the binary operators):
915 * T -> defined(variable) | make(target) | exists(file) | symbol
919 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
922 CondParser_Term(CondParser *par, Boolean doEval)
926 t = CondParser_Token(par, doEval);
930 * If we reached the end of the expression, the expression
934 } else if (t == TOK_LPAREN) {
938 t = CondParser_Expr(par, doEval);
939 if (t != TOK_ERROR) {
940 if (CondParser_Token(par, doEval) != TOK_RPAREN) {
944 } else if (t == TOK_NOT) {
945 t = CondParser_Term(par, doEval);
948 } else if (t == TOK_FALSE) {
956 * Parse a conjunctive factor (nice name, wot?)
961 * TOK_TRUE, TOK_FALSE or TOK_ERROR
964 CondParser_Factor(CondParser *par, Boolean doEval)
968 l = CondParser_Term(par, doEval);
969 if (l != TOK_ERROR) {
970 o = CondParser_Token(par, doEval);
976 * If T is TOK_FALSE, the whole thing will be
977 * TOK_FALSE, but we have to parse the r.h.s. anyway
978 * (to throw it away). If T is TOK_TRUE, the result
979 * is the r.h.s., be it a TOK_ERROR or not.
982 l = CondParser_Factor(par, doEval);
984 (void)CondParser_Factor(par, FALSE);
990 CondParser_PushBack(par, o);
997 * Main expression production.
1002 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
1005 CondParser_Expr(CondParser *par, Boolean doEval)
1009 l = CondParser_Factor(par, doEval);
1010 if (l != TOK_ERROR) {
1011 o = CondParser_Token(par, doEval);
1017 * A similar thing occurs for ||, except that here
1018 * we make sure the l.h.s. is TOK_FALSE before we
1019 * bother to evaluate the r.h.s. Once again, if l
1020 * is TOK_FALSE, the result is the r.h.s. and once
1021 * again if l is TOK_TRUE, we parse the r.h.s. to
1024 if (l == TOK_FALSE) {
1025 l = CondParser_Expr(par, doEval);
1027 (void)CondParser_Expr(par, FALSE);
1033 CondParser_PushBack(par, o);
1039 static CondEvalResult
1040 CondParser_Eval(CondParser *par, Boolean *value)
1044 DEBUG1(COND, "CondParser_Eval: %s\n", par->p);
1046 res = CondParser_Expr(par, TRUE);
1047 if (res != TOK_FALSE && res != TOK_TRUE)
1048 return COND_INVALID;
1050 if (CondParser_Token(par, FALSE) != TOK_EOF)
1051 return COND_INVALID;
1053 *value = res == TOK_TRUE;
1058 * Evaluate the condition, including any side effects from the variable
1059 * expressions in the condition. The condition consists of &&, ||, !,
1060 * function(arg), comparisons and parenthetical groupings thereof.
1063 * COND_PARSE if the condition was valid grammatically
1064 * COND_INVALID if not a valid conditional.
1066 * (*value) is set to the boolean value of the condition
1068 static CondEvalResult
1069 CondEvalExpression(const struct If *info, const char *cond, Boolean *value,
1070 Boolean eprint, Boolean strictLHS)
1073 CondEvalResult rval;
1075 lhsStrict = strictLHS;
1077 cpp_skip_hspace(&cond);
1079 par.if_info = info != NULL ? info : ifs + PLAIN_IF_INDEX;
1081 par.curr = TOK_NONE;
1082 par.printedError = FALSE;
1084 rval = CondParser_Eval(&par, value);
1086 if (rval == COND_INVALID && eprint && !par.printedError)
1087 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", cond);
1093 * Evaluate a condition in a :? modifier, such as
1094 * ${"${VAR}" == value:?yes:no}.
1097 Cond_EvalCondition(const char *cond, Boolean *out_value)
1099 return CondEvalExpression(NULL, cond, out_value, FALSE, FALSE);
1103 IsEndif(const char *p)
1105 return p[0] == 'e' && p[1] == 'n' && p[2] == 'd' &&
1106 p[3] == 'i' && p[4] == 'f' && !ch_isalpha(p[5]);
1110 * Evaluate the conditional directive in the line, which is one of:
1125 * In these directives, <cond> consists of &&, ||, !, function(arg),
1126 * comparisons, expressions, bare words, numbers and strings, and
1127 * parenthetical groupings thereof.
1130 * COND_PARSE to continue parsing the lines that follow the
1131 * conditional (when <cond> evaluates to TRUE)
1132 * COND_SKIP to skip the lines after the conditional
1133 * (when <cond> evaluates to FALSE, or when a previous
1134 * branch has already been taken)
1135 * COND_INVALID if the conditional was not valid, either because of
1136 * a syntax error or because some variable was undefined
1137 * or because the condition could not be evaluated
1140 Cond_EvalLine(const char *line)
1142 typedef enum IfState {
1144 /* None of the previous <cond> evaluated to TRUE. */
1147 /* The previous <cond> evaluated to TRUE.
1148 * The lines following this condition are interpreted. */
1149 IFS_ACTIVE = 1 << 0,
1151 /* The previous directive was an '.else'. */
1152 IFS_SEEN_ELSE = 1 << 1,
1154 /* One of the previous <cond> evaluated to TRUE. */
1155 IFS_WAS_ACTIVE = 1 << 2
1159 static enum IfState *cond_states = NULL;
1160 static unsigned int cond_states_cap = 128;
1162 const struct If *ifp;
1166 const char *p = line;
1168 if (cond_states == NULL) {
1169 cond_states = bmake_malloc(
1170 cond_states_cap * sizeof *cond_states);
1171 cond_states[0] = IFS_ACTIVE;
1174 p++; /* skip the leading '.' */
1175 cpp_skip_hspace(&p);
1177 if (IsEndif(p)) { /* It is an '.endif'. */
1179 Parse_Error(PARSE_FATAL,
1180 "The .endif directive does not take arguments.");
1183 if (cond_depth == cond_min_depth) {
1184 Parse_Error(PARSE_FATAL, "if-less endif");
1188 /* Return state for previous conditional */
1190 return cond_states[cond_depth] & IFS_ACTIVE
1191 ? COND_PARSE : COND_SKIP;
1194 /* Parse the name of the directive, such as 'if', 'elif', 'endif'. */
1198 * Unknown directive. It might still be a
1199 * transformation rule like '.elisp.scm',
1200 * therefore no error message here.
1202 return COND_INVALID;
1205 /* Quite likely this is 'else' or 'elif' */
1207 if (is_token(p, "se", 2)) { /* It is an 'else'. */
1210 Parse_Error(PARSE_FATAL,
1211 "The .else directive "
1212 "does not take arguments.");
1214 if (cond_depth == cond_min_depth) {
1215 Parse_Error(PARSE_FATAL, "if-less else");
1219 state = cond_states[cond_depth];
1220 if (state == IFS_INITIAL) {
1221 state = IFS_ACTIVE | IFS_SEEN_ELSE;
1223 if (state & IFS_SEEN_ELSE)
1224 Parse_Error(PARSE_WARNING,
1226 state = IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1228 cond_states[cond_depth] = state;
1230 return state & IFS_ACTIVE ? COND_PARSE : COND_SKIP;
1232 /* Assume for now it is an elif */
1237 if (p[0] != 'i' || p[1] != 'f') {
1239 * Unknown directive. It might still be a transformation rule
1240 * like '.elisp.scm', therefore no error message here.
1242 return COND_INVALID; /* Not an ifxxx or elifxxx line */
1246 * Figure out what sort of conditional it is -- what its default
1247 * function is, etc. -- by looking in the table of valid "ifs"
1250 for (ifp = ifs;; ifp++) {
1251 if (ifp->form == NULL) {
1253 * TODO: Add error message about unknown directive,
1254 * since there is no other known directive that starts
1255 * with 'el' or 'if'.
1257 * Example: .elifx 123
1259 return COND_INVALID;
1261 if (is_token(p, ifp->form, ifp->formlen)) {
1267 /* Now we know what sort of 'if' it is... */
1270 if (cond_depth == cond_min_depth) {
1271 Parse_Error(PARSE_FATAL, "if-less elif");
1274 state = cond_states[cond_depth];
1275 if (state & IFS_SEEN_ELSE) {
1276 Parse_Error(PARSE_WARNING, "extra elif");
1277 cond_states[cond_depth] =
1278 IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
1281 if (state != IFS_INITIAL) {
1282 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1287 if (cond_depth + 1 >= cond_states_cap) {
1289 * This is rare, but not impossible.
1290 * In meta mode, dirdeps.mk (only runs at level 0)
1291 * can need more than the default.
1293 cond_states_cap += 32;
1294 cond_states = bmake_realloc(cond_states,
1296 sizeof *cond_states);
1298 state = cond_states[cond_depth];
1300 if (!(state & IFS_ACTIVE)) {
1302 * If we aren't parsing the data,
1303 * treat as always false.
1305 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1310 /* And evaluate the conditional expression */
1311 if (CondEvalExpression(ifp, p, &value, TRUE, TRUE) == COND_INVALID) {
1312 /* Syntax error in conditional, error message already output. */
1313 /* Skip everything to matching .endif */
1314 /* XXX: An extra '.else' is not detected in this case. */
1315 cond_states[cond_depth] = IFS_WAS_ACTIVE;
1320 cond_states[cond_depth] = IFS_INITIAL;
1323 cond_states[cond_depth] = IFS_ACTIVE;
1328 Cond_restore_depth(unsigned int saved_depth)
1330 unsigned int open_conds = cond_depth - cond_min_depth;
1332 if (open_conds != 0 || saved_depth > cond_depth) {
1333 Parse_Error(PARSE_FATAL, "%u open conditional%s",
1334 open_conds, open_conds == 1 ? "" : "s");
1335 cond_depth = cond_min_depth;
1338 cond_min_depth = saved_depth;
1342 Cond_save_depth(void)
1344 unsigned int depth = cond_min_depth;
1346 cond_min_depth = cond_depth;