2 * Copyright (c) 1988, 1989, 1990, 1993
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 1988, 1989 by Adam de Boor
5 * Copyright (c) 1989 by Berkeley Softworks
8 * This code is derived from software contributed to Berkeley by
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 * @(#)cond.c 8.2 (Berkeley) 1/2/94
40 * $FreeBSD: src/usr.bin/make/cond.c,v 1.39 2005/02/07 07:49:16 harti Exp $
41 * $DragonFly: src/usr.bin/make/cond.c,v 1.36 2005/04/15 21:01:27 okumoto Exp $
45 * Functions to handle conditionals in a makefile.
48 * Cond_Eval Evaluate the conditional in the passed line.
69 * The parsing of conditional expressions is based on this grammar:
74 * T -> defined(variable)
80 * T -> $(varspec) op value
81 * T -> $(varspec) == "string"
82 * T -> $(varspec) != "string"
85 * op -> == | != | > | < | >= | <=
87 * 'symbol' is some other symbol to which the default function (condDefProc)
90 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
91 * will return And for '&' and '&&', Or for '|' and '||', Not for '!',
92 * LParen for '(', RParen for ')' and will evaluate the other terminal
93 * symbols, using either the default function or the function given in the
94 * terminal, and return the result as either True or False.
96 * All Non-Terminal functions (CondE, CondF and CondT) return Err on error.
111 typedef Boolean CondProc(int, char *);
114 * Structures to handle elegantly the different forms of #if's. The
115 * last two fields are stored in condInvert and condDefProc, respectively.
117 static void CondPushBack(Token);
118 static int CondGetArg(char **, char **, const char *, Boolean);
119 static CondProc CondDoDefined;
120 static CondProc CondDoMake;
121 static CondProc CondDoExists;
122 static CondProc CondDoTarget;
123 static char *CondCvtArg(char *, double *);
124 static Token CondToken(Boolean);
125 static Token CondT(Boolean);
126 static Token CondF(Boolean);
127 static Token CondE(Boolean);
129 static const struct If {
130 Boolean doNot; /* TRUE if default function should be negated */
131 CondProc *defProc; /* Default function to apply */
132 Boolean isElse; /* actually el<XXX> */
134 [COND_IF] = { FALSE, CondDoDefined, FALSE },
135 [COND_IFDEF] = { FALSE, CondDoDefined, FALSE },
136 [COND_IFNDEF] = { TRUE, CondDoDefined, FALSE },
137 [COND_IFMAKE] = { FALSE, CondDoMake, FALSE },
138 [COND_IFNMAKE] = { TRUE, CondDoMake, FALSE },
139 [COND_ELIF] = { FALSE, CondDoDefined, TRUE },
140 [COND_ELIFDEF] = { FALSE, CondDoDefined, TRUE },
141 [COND_ELIFNDEF] = { TRUE, CondDoDefined, TRUE },
142 [COND_ELIFMAKE] = { FALSE, CondDoMake, TRUE },
143 [COND_ELIFNMAKE] = { TRUE, CondDoMake, TRUE },
146 static Boolean condInvert; /* Invert the default function */
147 static CondProc *condDefProc; /* default function to apply */
148 static char *condExpr; /* The expression to parse */
149 static Token condPushBack = None; /* Single push-back token in parsing */
151 #define MAXIF 30 /* greatest depth of #if'ing */
153 static Boolean condStack[MAXIF]; /* Stack of conditionals's values */
154 static int condLineno[MAXIF]; /* Line numbers of the opening .if */
155 static int condTop = MAXIF; /* Top-most conditional */
156 static int skipIfLevel = 0; /* Depth of skipped conditionals */
157 static int skipIfLineno[MAXIF]; /* Line numbers of skipped .ifs */
158 Boolean skipLine = FALSE; /* Whether the parse module is skipping
163 * Push back the most recent token read. We only need one level of
164 * this, so the thing is just stored in 'condPushback'.
167 * condPushback is overwritten.
170 CondPushBack(Token t)
178 * Find the argument of a built-in function. parens is set to TRUE
179 * if the arguments are bounded by parens.
182 * The length of the argument and the address of the argument.
185 * The pointer is set to point to the closing parenthesis of the
189 CondGetArg(char **linePtr, char **argPtr, const char *func, Boolean parens)
197 while (*cp != '(' && *cp != '\0') {
207 * No arguments whatsoever. Because 'make' and 'defined'
208 * aren't really "reserved words", we don't print a message.
209 * I think this is better than hitting the user with a warning
210 * message every time s/he uses the word 'make' or 'defined'
211 * at the beginning of a symbol...
217 while (*cp == ' ' || *cp == '\t') {
222 * Create a buffer for the argument and start it out at 16 characters
223 * long. Why 16? Why not?
227 while ((strchr(" \t)&|", *cp) == NULL) && (*cp != '\0')) {
230 * Parse the variable spec and install it as part of
231 * the argument if it's valid. We tell Var_Parse to
232 * complain on an undefined variable, so we don't do
233 * it too. Nor do we return an error, though perhaps
240 cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &doFree);
242 Buf_Append(buf, cp2);
248 Buf_AddByte(buf, (Byte)*cp);
253 Buf_AddByte(buf, (Byte)'\0');
254 *argPtr = (char *)Buf_GetAll(buf, &argLen);
255 Buf_Destroy(buf, FALSE);
257 while (*cp == ' ' || *cp == '\t') {
260 if (parens && *cp != ')') {
261 Parse_Error(PARSE_WARNING,
262 "Missing closing parenthesis for %s()", func);
266 * Advance pointer past close parenthesis.
277 * Handle the 'defined' function for conditionals.
280 * TRUE if the given variable is defined.
283 CondDoDefined(int argLen, char *arg)
285 char savec = arg[argLen];
290 if (Var_Value(arg, VAR_CMD, &p1) != NULL) {
302 * Handle the 'make' function for conditionals.
305 * TRUE if the given target is being made.
308 CondDoMake(int argLen, char *arg)
310 char savec = arg[argLen];
316 LST_FOREACH(ln, &create) {
317 if (Str_Match(Lst_Datum(ln), arg)) {
328 * See if the given file exists.
331 * TRUE if the file exists and FALSE if it does not.
334 CondDoExists(int argLen, char *arg)
336 char savec = arg[argLen];
341 path = Path_FindFile(arg, &dirSearchPath);
354 * See if the given node exists and is an actual target.
357 * TRUE if the node exists as a target and FALSE if it does not.
360 CondDoTarget(int argLen, char *arg)
362 char savec = arg[argLen];
367 gn = Targ_FindNode(arg, TARG_NOCREATE);
368 if ((gn != NULL) && !OP_NOP(gn->type)) {
379 * Convert the given number into a double. If the number begins
380 * with 0x, it is interpreted as a hexadecimal integer
381 * and converted to a double from there. All other strings just have
382 * strtod called on them.
385 * Sets 'value' to double value of string.
386 * Returns address of the first character after the last valid
387 * character of the converted number.
390 * Can change 'value' even if string is not a valid number.
393 CondCvtArg(char *str, double *value)
396 if ((*str == '0') && (str[1] == 'x')) {
399 for (str += 2, i = 0; ; str++) {
402 if (isdigit((unsigned char)*str))
404 else if (isxdigit((unsigned char)*str))
406 isupper((unsigned char)*str) ? 'A' : 'a';
417 *value = strtod(str, &eptr);
424 * Return the next token from the input.
427 * A Token for the next lexical token in the stream.
430 * condPushback will be set back to None if it is used.
433 CondToken(Boolean doEval)
437 if (condPushBack == None) {
438 while (*condExpr == ' ' || *condExpr == '\t') {
451 if (condExpr[1] == '|') {
458 if (condExpr[1] == '&') {
476 size_t varSpecLen = 0;
480 * Parse the variable spec and skip over it, saving its
484 lhs = Var_Parse(condExpr, VAR_CMD, doEval,
485 &varSpecLen, &doFree);
486 if (lhs == var_Error) {
488 * Even if !doEval, we still report syntax
489 * errors, which is what getting var_Error
490 * back with !doEval means.
494 condExpr += varSpecLen;
496 if (!isspace((unsigned char)*condExpr) &&
497 strchr("!=><", *condExpr) == NULL) {
502 Buf_Append(buf, lhs);
508 !isspace((unsigned char)*condExpr);
510 Buf_AddByte(buf, (Byte)*condExpr);
512 Buf_AddByte(buf, (Byte)'\0');
513 lhs = (char *)Buf_GetAll(buf, &varSpecLen);
514 Buf_Destroy(buf, FALSE);
520 * Skip whitespace to get to the operator
522 while (isspace((unsigned char)*condExpr))
526 * Make sure the operator is a valid one. If it isn't a
527 * known relational operator, pretend we got a
536 if (condExpr[1] == '=') {
548 while (isspace((unsigned char)*condExpr)) {
551 if (*condExpr == '\0') {
552 Parse_Error(PARSE_WARNING,
553 "Missing right-hand-side of operator");
560 * Doing a string comparison. Only allow == and
561 * != for * operators.
569 if (((*op != '!') && (*op != '=')) ||
571 Parse_Error(PARSE_WARNING,
572 "String comparison operator should "
573 "be either == or !=");
578 qt = *rhs == '"' ? 1 : 0;
581 ((qt && (*cp != '"')) ||
582 (!qt && strchr(" \t)", *cp) == NULL)) &&
583 (*cp != '\0'); cp++) {
584 if ((*cp == '\\') && (cp[1] != '\0')) {
586 * Backslash escapes things --
587 * skip over next character, * if it exists.
590 Buf_AddByte(buf, (Byte)*cp);
592 } else if (*cp == '$') {
596 cp2 = Var_Parse(cp, VAR_CMD,
597 doEval, &len, &freeIt);
598 if (cp2 != var_Error) {
599 Buf_Append(buf, cp2);
609 Buf_AddByte(buf, (Byte)*cp);
613 string = Buf_Peel(buf);
615 DEBUGF(COND, ("lhs = \"%s\", rhs = \"%s\", "
616 "op = %.2s\n", lhs, string, op));
618 * Null-terminate rhs and perform the
619 * comparison. t is set to the result.
622 t = strcmp(lhs, string) ? False : True;
624 t = strcmp(lhs, string) ? True : False;
627 if (rhs == condExpr) {
628 if (!qt && *cp == ')')
635 * rhs is either a float or an integer.
636 * Convert both the lhs and the rhs to a
637 * double and compare the two.
642 if (*CondCvtArg(lhs, &left) != '\0')
643 goto do_string_compare;
648 string = Var_Parse(rhs, VAR_CMD, doEval,
650 if (string == var_Error) {
653 if (*CondCvtArg(string,
657 goto do_string_compare;
665 char *c = CondCvtArg(rhs, &right);
668 goto do_string_compare;
669 if (rhs == condExpr) {
671 * Skip over the right-hand side
677 DEBUGF(COND, ("left = %f, right = %f, "
678 "op = %.2s\n", left, right, op));
682 Parse_Error(PARSE_WARNING,
686 t = (left != right ? True : False);
690 Parse_Error(PARSE_WARNING,
694 t = (left == right ? True : False);
698 t = (left <= right?True:False);
700 t = (left < right?True:False);
705 t = (left >= right?True:False);
707 t = (left > right?True:False);
722 Boolean invert = FALSE;
726 if (strncmp(condExpr, "defined", 7) == 0) {
728 * Use CondDoDefined to evaluate the argument
729 * and CondGetArg to extract the argument from
730 * the 'function call'.
732 evalProc = CondDoDefined;
734 arglen = CondGetArg(&condExpr, &arg,
741 } else if (strncmp(condExpr, "make", 4) == 0) {
743 * Use CondDoMake to evaluate the argument and
744 * CondGetArg to extract the argument from the
747 evalProc = CondDoMake;
749 arglen = CondGetArg(&condExpr, &arg,
756 } else if (strncmp(condExpr, "exists", 6) == 0) {
758 * Use CondDoExists to evaluate the argument and
759 * CondGetArg to extract the argument from the
762 evalProc = CondDoExists;
764 arglen = CondGetArg(&condExpr, &arg,
771 } else if (strncmp(condExpr, "empty", 5) == 0) {
773 * Use Var_Parse to parse the spec in parens and
774 * return True if the resulting string is empty.
783 condExpr[arglen] != '(' &&
784 condExpr[arglen] != '\0'; arglen += 1)
787 if (condExpr[arglen] != '\0') {
789 val = Var_Parse(&condExpr[arglen - 1],
790 VAR_CMD, FALSE, &length, &doFree);
791 if (val == var_Error) {
795 * A variable is empty when it
796 * just contains spaces...
803 isspace((unsigned char)*p);
806 t = (*p == '\0') ? True : False;
812 * Advance condExpr to beyond the
813 * closing ). Note that we subtract
814 * one from arglen + length b/c length
816 * condExpr[arglen - 1].
818 condExpr += arglen + length - 1;
825 } else if (strncmp(condExpr, "target", 6) == 0) {
827 * Use CondDoTarget to evaluate the argument and
828 * CondGetArg to extract the argument from the
831 evalProc = CondDoTarget;
833 arglen = CondGetArg(&condExpr, &arg,
842 * The symbol is itself the argument to the
843 * default function. We advance condExpr to
844 * the end of the symbol by hand (the next
845 * whitespace, closing paren or binary operator)
846 * and set to invert the evaluation
847 * function if condInvert is TRUE.
851 evalProc = condDefProc;
852 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
856 * Evaluate the argument using the set function. If
857 * invert is TRUE, we invert the sense of the function.
859 t = (!doEval || (* evalProc) (arglen, arg) ?
860 (invert ? False : True) :
861 (invert ? True : False));
875 * Parse a single term in the expression. This consists of a terminal
876 * symbol or Not and a terminal symbol (not including the binary
878 * T -> defined(variable) | make(target) | exists(file) | symbol
882 * True, False or Err.
885 * Tokens are consumed.
888 CondT(Boolean doEval)
892 t = CondToken(doEval);
893 if (t == EndOfFile) {
895 * If we reached the end of the expression, the expression
899 } else if (t == LParen) {
905 if (CondToken(doEval) != RParen) {
909 } else if (t == Not) {
913 } else if (t == False) {
922 * Parse a conjunctive factor (nice name, wot?)
929 * Tokens are consumed.
932 CondF(Boolean doEval)
938 o = CondToken(doEval);
944 * If T is False, the whole thing will be False, but
945 * we have to parse the r.h.s. anyway (to throw it
946 * away). If T is True, the result is the r.h.s.,
947 * be it an Err or no.
966 * Main expression production.
970 * True, False or Err.
973 * Tokens are, of course, consumed.
976 CondE(Boolean doEval)
982 o = CondToken(doEval);
988 * A similar thing occurs for ||, except that here we
989 * make sure the l.h.s. is False before we bother to
990 * evaluate the r.h.s. Once again, if l is False, the
991 * result is the r.h.s. and once again if l is True,
992 * we parse the r.h.s. to throw it away.
1011 * Handle .if<X> and .elif<X> directives.
1012 * This function is called even when we're skipping.
1015 Cond_If(char *line, int code, int lineno)
1017 const struct If *ifp;
1023 if (condTop == MAXIF) {
1024 Parse_Error(PARSE_FATAL, "if-less elif");
1027 if (skipIfLevel != 0) {
1029 * If skipping this conditional, just ignore
1030 * the whole thing. If we don't, the user
1031 * might be employing a variable that's
1032 * undefined, for which there's an enclosing
1033 * ifdef that we're skipping...
1035 skipIfLineno[skipIfLevel - 1] = lineno;
1039 } else if (skipLine) {
1041 * Don't even try to evaluate a conditional that's
1042 * not an else if we're skipping things...
1044 skipIfLineno[skipIfLevel] = lineno;
1050 * Initialize file-global variables for parsing
1052 condDefProc = ifp->defProc;
1053 condInvert = ifp->doNot;
1055 while (*line == ' ' || *line == '\t') {
1060 condPushBack = None;
1062 switch (CondE(TRUE)) {
1064 if (CondToken(TRUE) != EndOfFile)
1070 if (CondToken(TRUE) != EndOfFile)
1076 err: Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", line);
1084 /* push this value */
1087 } else if (skipIfLevel != 0 || condStack[condTop]) {
1089 * If this is an else-type conditional, it should only take
1090 * effect if its corresponding if was evaluated and FALSE.
1091 * If its if was TRUE or skipped, we return COND_SKIP (and
1092 * start skipping in case we weren't already), leaving the
1093 * stack unmolested so later elif's don't screw up...
1101 * This is the one case where we can definitely proclaim a fatal
1102 * error. If we don't, we're hosed.
1104 Parse_Error(PARSE_FATAL, "Too many nested if's. %d max.",MAXIF);
1109 condStack[condTop] = value;
1110 condLineno[condTop] = lineno;
1116 * Handle .else statement.
1119 Cond_Else(char *line __unused, int code __unused, int lineno __unused)
1122 while (isspace((u_char)*line))
1125 if (*line != '\0') {
1126 Parse_Error(PARSE_WARNING, "junk after .else ignored '%s'", line);
1129 if (condTop == MAXIF) {
1130 Parse_Error(PARSE_FATAL, "if-less else");
1133 if (skipIfLevel != 0)
1136 if (skipIfLevel != 0 || condStack[condTop]) {
1138 * An else should only take effect if its corresponding if was
1139 * evaluated and FALSE.
1140 * If its if was TRUE or skipped, we return COND_SKIP (and
1141 * start skipping in case we weren't already), leaving the
1142 * stack unmolested so later elif's don't screw up...
1143 * XXX How does this work with two .else's?
1150 condStack[condTop] = !condStack[condTop];
1151 skipLine = !condStack[condTop];
1156 * Handle .endif statement.
1159 Cond_Endif(char *line __unused, int code __unused, int lineno __unused)
1162 while (isspace((u_char)*line))
1165 if (*line != '\0') {
1166 Parse_Error(PARSE_WARNING, "junk after .endif ignored '%s'", line);
1169 * End of a conditional section. If skipIfLevel is non-zero,
1170 * that conditional was skipped, so lines following it should
1171 * also be skipped. Hence, we return COND_SKIP. Otherwise,
1172 * the conditional was read so succeeding lines should be
1173 * parsed (think about it...) so we return COND_PARSE, unless
1174 * this endif isn't paired with a decent if.
1176 if (skipIfLevel != 0) {
1181 if (condTop == MAXIF) {
1182 Parse_Error(PARSE_FATAL, "if-less endif");
1193 * Make sure everything's clean at the end of a makefile.
1196 * Parse_Error will be called if open conditionals are around.
1203 if (condTop != MAXIF) {
1204 Parse_Error(PARSE_FATAL, "%d open conditional%s:",
1205 MAXIF - condTop + skipIfLevel,
1206 MAXIF - condTop + skipIfLevel== 1 ? "" : "s");
1208 for (level = skipIfLevel; level > 0; level--)
1209 Parse_Error(PARSE_FATAL, "\t%*sat line %d (skipped)",
1210 MAXIF - condTop + level + 1, "",
1211 skipIfLineno[level - 1]);
1212 for (level = condTop; level < MAXIF; level++)
1213 Parse_Error(PARSE_FATAL, "\t%*sat line %d "
1214 "(evaluated to %s)", MAXIF - level + skipIfLevel,
1215 "", condLineno[level],
1216 condStack[level] ? "true" : "false");