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.51 2005/09/24 07:38:03 okumoto Exp $
45 * Functions to handle conditionals in a makefile.
48 * Cond_Eval Evaluate the conditional in the passed line.
68 * The parsing of conditional expressions is based on this grammar:
73 * T -> defined(variable)
79 * T -> $(varspec) op value
80 * T -> $(varspec) == "string"
81 * T -> $(varspec) != "string"
84 * op -> == | != | > | < | >= | <=
86 * 'symbol' is some other symbol to which the default function (condDefProc)
89 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
90 * will return And for '&' and '&&', Or for '|' and '||', Not for '!',
91 * LParen for '(', RParen for ')' and will evaluate the other terminal
92 * symbols, using either the default function or the function given in the
93 * terminal, and return the result as either True or False.
95 * All Non-Terminal functions (CondE, CondF and CondT) return Err on error.
110 typedef bool CondProc(Parser *, int, char *);
113 * Structures to handle elegantly the different forms of #if's. The
114 * last two fields are stored in condInvert and condDefProc, respectively.
116 static void CondPushBack(Token);
117 static int CondGetArg(char **, char **, const char *, bool);
118 static CondProc CondDoDefined;
119 static CondProc CondDoMake;
120 static CondProc CondDoExists;
121 static CondProc CondDoTarget;
122 static char *CondCvtArg(char *, double *);
123 static Token CondToken(Parser *, bool);
124 static Token CondT(Parser *, bool);
125 static Token CondF(Parser *, bool);
126 static Token CondE(Parser *, bool);
128 static const struct If {
129 bool doNot; /* true if default function should be negated */
130 CondProc *defProc; /* Default function to apply */
131 bool isElse; /* actually el<XXX> */
133 [COND_IF] = { false, CondDoDefined, false },
134 [COND_IFDEF] = { false, CondDoDefined, false },
135 [COND_IFNDEF] = { true, CondDoDefined, false },
136 [COND_IFMAKE] = { false, CondDoMake, false },
137 [COND_IFNMAKE] = { true, CondDoMake, false },
138 [COND_ELIF] = { false, CondDoDefined, true },
139 [COND_ELIFDEF] = { false, CondDoDefined, true },
140 [COND_ELIFNDEF] = { true, CondDoDefined, true },
141 [COND_ELIFMAKE] = { false, CondDoMake, true },
142 [COND_ELIFNMAKE] = { true, CondDoMake, true },
145 static bool condInvert; /* Invert the default function */
146 static CondProc *condDefProc; /* default function to apply */
147 static char *condExpr; /* The expression to parse */
148 static Token condPushBack = None; /* Single push-back token in parsing */
150 #define MAXIF 30 /* greatest depth of #if'ing */
152 static bool condStack[MAXIF]; /* Stack of conditionals's values */
153 static int condLineno[MAXIF]; /* Line numbers of the opening .if */
154 static int condTop = MAXIF; /* Top-most conditional */
155 static int skipIfLevel = 0; /* Depth of skipped conditionals */
156 static int skipIfLineno[MAXIF]; /* Line numbers of skipped .ifs */
157 bool skipLine = false; /* Whether the parse module is skipping
162 * Push back the most recent token read. We only need one level of
163 * this, so the thing is just stored in 'condPushback'.
166 * condPushback is overwritten.
169 CondPushBack(Token t)
177 * Find the argument of a built-in function. parens is set to true
178 * if the arguments are bounded by parens.
181 * The length of the argument and the address of the argument.
184 * The pointer is set to point to the closing parenthesis of the
188 CondGetArg(char **linePtr, char **argPtr, const char *func, bool parens)
196 while (*cp != OPEN_PAREN && *cp != '\0') {
199 if (*cp == OPEN_PAREN) {
206 * No arguments whatsoever. Because 'make' and 'defined'
207 * aren't really "reserved words", we don't print a message.
208 * I think this is better than hitting the user with a warning
209 * message every time s/he uses the word 'make' or 'defined'
210 * at the beginning of a symbol...
216 while (*cp == ' ' || *cp == '\t') {
221 * Create a buffer for the argument and start it out at 16 characters
222 * long. Why 16? Why not?
226 while ((strchr(" \t)&|", *cp) == NULL) && (*cp != '\0')) {
229 * Parse the variable spec and install it as part of
230 * the argument if it's valid. We tell Var_Parse to
231 * complain on an undefined variable, so we don't do
232 * it too. Nor do we return an error, though perhaps
239 cp2 = Var_Parse(cp, VAR_CMD, true, &len, &doFree);
241 Buf_Append(buf, cp2);
247 Buf_AddByte(buf, *cp);
252 while (*cp == ' ' || *cp == '\t') {
256 Buf_AddByte(buf, '\0');
257 *argPtr = Buf_Data(buf);
258 argLen = Buf_Size(buf);
259 Buf_Destroy(buf, false);
262 if (*cp == CLOSE_PAREN) {
264 * Advance pointer past close parenthesis.
270 Parse_Error(PARSE_WARNING,
271 "Missing closing parenthesis for %s()", func);
273 /* XXX memory leak of argPtr? */
283 * Handle the 'defined' function for conditionals.
286 * true if the given variable is defined.
289 CondDoDefined(Parser *parser __unused, int argLen, char *arg)
291 char savec = arg[argLen];
295 if (Var_Value(arg, VAR_CMD) != NULL) {
306 * Handle the 'make' function for conditionals.
309 * true if the given target is being made.
312 CondDoMake(Parser *parser, int argLen, char *arg)
314 char savec = arg[argLen];
320 LST_FOREACH(ln, parser->create) {
321 if (Str_Match(Lst_Datum(ln), arg)) {
332 * See if the given file exists.
335 * true if the file exists and false if it does not.
338 CondDoExists(Parser *parser __unused, int argLen, char *arg)
340 char savec = arg[argLen];
345 path = Path_FindFile(arg, &dirSearchPath);
358 * See if the given node exists and is an actual target.
361 * true if the node exists as a target and false if it does not.
364 CondDoTarget(Parser *parser __unused, int argLen, char *arg)
366 char savec = arg[argLen];
371 gn = Targ_FindNode(arg, TARG_NOCREATE);
372 if ((gn != NULL) && !OP_NOP(gn->type)) {
383 * Convert the given number into a double. If the number begins
384 * with 0x, it is interpreted as a hexadecimal integer
385 * and converted to a double from there. All other strings just have
386 * strtod called on them.
389 * Sets 'value' to double value of string.
390 * Returns address of the first character after the last valid
391 * character of the converted number.
394 * Can change 'value' even if string is not a valid number.
397 CondCvtArg(char *str, double *value)
400 if ((*str == '0') && (str[1] == 'x')) {
403 for (str += 2, i = 0; ; str++) {
406 if (isdigit((unsigned char)*str))
408 else if (isxdigit((unsigned char)*str))
410 isupper((unsigned char)*str) ? 'A' : 'a';
421 *value = strtod(str, &eptr);
428 * Return the next token from the input.
431 * A Token for the next lexical token in the stream.
434 * condPushback will be set back to None if it is used.
437 CondToken(Parser *parser, bool doEval)
441 if (condPushBack != None) {
447 while (*condExpr == ' ' || *condExpr == '\t') {
461 if (condExpr[1] == '|') {
468 if (condExpr[1] == '&') {
487 size_t varSpecLen = 0;
491 * Parse the variable spec and skip over it, saving
495 lhs = Var_Parse(condExpr, VAR_CMD, doEval,
496 &varSpecLen, &doFree);
497 if (lhs == var_Error) {
499 * Even if !doEval, we still report syntax
500 * errors, which is what getting var_Error
501 * back with !doEval means.
505 condExpr += varSpecLen;
507 if (!isspace((unsigned char)*condExpr) &&
508 strchr("!=><", *condExpr) == NULL) {
513 Buf_Append(buf, lhs);
519 !isspace((unsigned char)*condExpr);
521 Buf_AddByte(buf, *condExpr);
523 Buf_AddByte(buf, '\0');
525 Buf_Destroy(buf, false);
531 * Skip whitespace to get to the operator
533 while (isspace((unsigned char)*condExpr))
537 * Make sure the operator is a valid one. If it isn't
538 * a known relational operator, pretend we got a != 0
547 if (condExpr[1] == '=') {
552 while (isspace((unsigned char)*condExpr)) {
555 if (*condExpr == '\0') {
556 Parse_Error(PARSE_WARNING,
557 "Missing right-hand-side of operator");
570 * Doing a string comparison. Only allow ==
571 * and != for * operators.
579 if (((*op != '!') && (*op != '=')) ||
581 Parse_Error(PARSE_WARNING,
582 "String comparison operator should "
583 "be either == or !=");
587 qt = *rhs == '"' ? 1 : 0;
590 ((qt && (*cp != '"')) ||
591 (!qt && strchr(" \t)", *cp) == NULL)) &&
592 (*cp != '\0'); cp++) {
593 if ((*cp == '\\') && (cp[1] != '\0')) {
595 * Backslash escapes things
601 Buf_AddByte(buf, *cp);
603 } else if (*cp == '$') {
607 cp2 = Var_Parse(cp, VAR_CMD,
608 doEval, &len, &freeIt);
609 if (cp2 != var_Error) {
610 Buf_Append(buf, cp2);
616 Buf_AddByte(buf, *cp);
619 Buf_AddByte(buf, *cp);
623 string = Buf_Peel(buf);
625 DEBUGF(COND, ("lhs = \"%s\", rhs = \"%s\", "
626 "op = %.2s\n", lhs, string, op));
628 * Null-terminate rhs and perform the
629 * comparison. t is set to the result.
632 t = strcmp(lhs, string) ? False : True;
634 t = strcmp(lhs, string) ? True : False;
637 if (rhs == condExpr) {
638 if (*cp == '\0' || (!qt && *cp == CLOSE_PAREN))
645 * rhs is either a float or an integer.
646 * Convert both the lhs and the rhs to a
647 * double and compare the two.
652 if (*CondCvtArg(lhs, &left) != '\0')
653 goto do_string_compare;
658 string = Var_Parse(rhs, VAR_CMD, doEval,
660 if (string == var_Error) {
663 if (*CondCvtArg(string,
667 goto do_string_compare;
675 char *c = CondCvtArg(rhs, &right);
678 goto do_string_compare;
679 if (rhs == condExpr) {
681 * Skip over the right-hand
688 DEBUGF(COND, ("left = %f, right = %f, "
689 "op = %.2s\n", left, right, op));
693 Parse_Error(PARSE_WARNING,
697 t = (left != right ? True : False);
701 Parse_Error(PARSE_WARNING,
705 t = (left == right ? True : False);
709 t = (left <= right ? True : False);
711 t = (left < right ? True : False);
716 t = (left >= right ? True : False);
718 t = (left > right ? True : False);
737 if (strncmp(condExpr, "defined", 7) == 0) {
739 * Use CondDoDefined to evaluate the argument
740 * and CondGetArg to extract the argument
741 * from the 'function call'.
743 evalProc = CondDoDefined;
745 arglen = CondGetArg(&condExpr, &arg,
751 } else if (strncmp(condExpr, "make", 4) == 0) {
753 * Use CondDoMake to evaluate the argument
754 * and CondGetArg to extract the argument
755 * from the 'function call'.
757 evalProc = CondDoMake;
759 arglen = CondGetArg(&condExpr, &arg,
765 } else if (strncmp(condExpr, "exists", 6) == 0) {
767 * Use CondDoExists to evaluate the argument
768 * and CondGetArg to extract the argument
769 * from the 'function call'.
771 evalProc = CondDoExists;
773 arglen = CondGetArg(&condExpr, &arg,
779 } else if (strncmp(condExpr, "empty", 5) == 0) {
781 * Use Var_Parse to parse the spec in parens
782 * and return True if the resulting string is
792 condExpr[arglen] != OPEN_PAREN &&
793 condExpr[arglen] != '\0'; arglen += 1)
796 if (condExpr[arglen] != '\0') {
798 val = Var_Parse(&condExpr[arglen - 1],
799 VAR_CMD, false, &length, &doFree);
800 if (val == var_Error) {
804 * A variable is empty when
805 * it just contains spaces...
812 isspace((unsigned char)*p);
815 t = (*p == '\0') ? True : False;
821 * Advance condExpr to beyond the
822 * closing ). Note that we subtract
823 * one from arglen + length b/c
824 * length is calculated from
825 * condExpr[arglen - 1].
827 condExpr += arglen + length - 1;
834 } else if (strncmp(condExpr, "target", 6) == 0) {
836 * Use CondDoTarget to evaluate the argument
837 * and CondGetArg to extract the argument
838 * from the 'function call'.
840 evalProc = CondDoTarget;
842 arglen = CondGetArg(&condExpr, &arg,
850 * The symbol is itself the argument to the
851 * default function. We advance condExpr to
852 * the end of the symbol by hand (the next
853 * whitespace, closing paren or binary
854 * operator) and set to invert the evaluation
855 * function if condInvert is true.
859 evalProc = condDefProc;
860 arglen = CondGetArg(&condExpr, &arg, "", false);
864 * Evaluate the argument using the set function. If
865 * invert is true, we invert the sense of the
868 t = (!doEval || evalProc(parser, arglen, arg) ?
869 (invert ? False : True) :
870 (invert ? True : False));
880 * Parse a single term in the expression. This consists of a terminal
881 * symbol or Not and a terminal symbol (not including the binary
883 * T -> defined(variable) | make(target) | exists(file) | symbol
887 * True, False or Err.
890 * Tokens are consumed.
893 CondT(Parser *parser, bool doEval)
897 t = CondToken(parser, doEval);
898 if (t == EndOfFile) {
900 * If we reached the end of the expression, the expression
904 } else if (t == LParen) {
908 t = CondE(parser, doEval);
910 if (CondToken(parser, doEval) != RParen) {
914 } else if (t == Not) {
915 t = CondT(parser, doEval);
918 } else if (t == False) {
927 * Parse a conjunctive factor (nice name, wot?)
934 * Tokens are consumed.
937 CondF(Parser *parser, bool doEval)
941 l = CondT(parser, doEval);
943 o = CondToken(parser, doEval);
949 * If T is False, the whole thing will be False, but
950 * we have to parse the r.h.s. anyway (to throw it
951 * away). If T is True, the result is the r.h.s.,
952 * be it an Err or no.
955 l = CondF(parser, doEval);
957 CondF(parser, false);
971 * Main expression production.
975 * True, False or Err.
978 * Tokens are, of course, consumed.
981 CondE(Parser *parser, bool doEval)
985 l = CondF(parser, doEval);
987 o = CondToken(parser, doEval);
993 * A similar thing occurs for ||, except that here we
994 * make sure the l.h.s. is False before we bother to
995 * evaluate the r.h.s. Once again, if l is False, the
996 * result is the r.h.s. and once again if l is True,
997 * we parse the r.h.s. to throw it away.
1000 l = CondE(parser, doEval);
1002 CondE(parser, false);
1016 * Handle .if<X> and .elif<X> directives.
1017 * This function is called even when we're skipping.
1020 Cond_If(Parser *parser, char *line, int code, int lineno)
1022 const struct If *ifp;
1028 if (condTop == MAXIF) {
1029 Parse_Error(PARSE_FATAL, "if-less elif");
1032 if (skipIfLevel != 0) {
1034 * If skipping this conditional, just ignore
1035 * the whole thing. If we don't, the user
1036 * might be employing a variable that's
1037 * undefined, for which there's an enclosing
1038 * ifdef that we're skipping...
1040 skipIfLineno[skipIfLevel - 1] = lineno;
1044 } else if (skipLine) {
1046 * Don't even try to evaluate a conditional that's
1047 * not an else if we're skipping things...
1049 skipIfLineno[skipIfLevel] = lineno;
1055 * Initialize file-global variables for parsing
1057 condDefProc = ifp->defProc;
1058 condInvert = ifp->doNot;
1060 while (*line == ' ' || *line == '\t') {
1065 condPushBack = None;
1067 switch (CondE(parser, true)) {
1069 if (CondToken(parser, true) != EndOfFile)
1075 if (CondToken(parser, true) != EndOfFile)
1081 err: Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", line);
1089 /* push this value */
1092 } else if (skipIfLevel != 0 || condStack[condTop]) {
1094 * If this is an else-type conditional, it should only take
1095 * effect if its corresponding if was evaluated and false.
1096 * If its if was true or skipped, we return COND_SKIP (and
1097 * start skipping in case we weren't already), leaving the
1098 * stack unmolested so later elif's don't screw up...
1106 * This is the one case where we can definitely proclaim a fatal
1107 * error. If we don't, we're hosed.
1109 Parse_Error(PARSE_FATAL, "Too many nested if's. %d max.",MAXIF);
1114 condStack[condTop] = value;
1115 condLineno[condTop] = lineno;
1121 * Handle .else statement.
1124 Cond_Else(Parser *parser __unused, char *line __unused, int code __unused, int lineno __unused)
1127 while (isspace((u_char)*line))
1130 if (*line != '\0' && (warn_flags & WARN_DIRSYNTAX)) {
1131 Parse_Error(PARSE_WARNING, "junk after .else ignored '%s'",
1135 if (condTop == MAXIF) {
1136 Parse_Error(PARSE_FATAL, "if-less else");
1139 if (skipIfLevel != 0)
1142 if (skipIfLevel != 0 || condStack[condTop]) {
1144 * An else should only take effect if its corresponding if was
1145 * evaluated and false.
1146 * If its if was true or skipped, we return COND_SKIP (and
1147 * start skipping in case we weren't already), leaving the
1148 * stack unmolested so later elif's don't screw up...
1149 * XXX How does this work with two .else's?
1156 condStack[condTop] = !condStack[condTop];
1157 skipLine = !condStack[condTop];
1162 * Handle .endif statement.
1165 Cond_Endif(Parser *parser __unused, char *line __unused, int code __unused, int lineno __unused)
1168 while (isspace((u_char)*line))
1171 if (*line != '\0' && (warn_flags & WARN_DIRSYNTAX)) {
1172 Parse_Error(PARSE_WARNING, "junk after .endif ignored '%s'",
1177 * End of a conditional section. If skipIfLevel is non-zero,
1178 * that conditional was skipped, so lines following it should
1179 * also be skipped. Hence, we return COND_SKIP. Otherwise,
1180 * the conditional was read so succeeding lines should be
1181 * parsed (think about it...) so we return COND_PARSE, unless
1182 * this endif isn't paired with a decent if.
1184 if (skipIfLevel != 0) {
1189 if (condTop == MAXIF) {
1190 Parse_Error(PARSE_FATAL, "if-less endif");
1201 * Make sure everything's clean at the end of a makefile.
1204 * Parse_Error will be called if open conditionals are around.
1207 Cond_End(Parser *parser __unused, char *line __unused, int code __unused, int lineno __unused)
1211 if (condTop != MAXIF) {
1212 Parse_Error(PARSE_FATAL, "%d open conditional%s:",
1213 MAXIF - condTop + skipIfLevel,
1214 MAXIF - condTop + skipIfLevel== 1 ? "" : "s");
1216 for (level = skipIfLevel; level > 0; level--)
1217 Parse_Error(PARSE_FATAL, "\t%*sat line %d (skipped)",
1218 MAXIF - condTop + level + 1, "",
1219 skipIfLineno[level - 1]);
1220 for (level = condTop; level < MAXIF; level++)
1221 Parse_Error(PARSE_FATAL, "\t%*sat line %d "
1222 "(evaluated to %s)", MAXIF - level + skipIfLevel,
1223 "", condLineno[level],
1224 condStack[level] ? "true" : "false");