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.30 2005/02/18 01:23:22 okumoto Exp $
46 * Functions to handle conditionals in a makefile.
49 * Cond_Eval Evaluate the conditional in the passed line.
71 * The parsing of conditional expressions is based on this grammar:
76 * T -> defined(variable)
82 * T -> $(varspec) op value
83 * T -> $(varspec) == "string"
84 * T -> $(varspec) != "string"
87 * op -> == | != | > | < | >= | <=
89 * 'symbol' is some other symbol to which the default function (condDefProc)
92 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
93 * will return And for '&' and '&&', Or for '|' and '||', Not for '!',
94 * LParen for '(', RParen for ')' and will evaluate the other terminal
95 * symbols, using either the default function or the function given in the
96 * terminal, and return the result as either True or False.
98 * All Non-Terminal functions (CondE, CondF and CondT) return Err on error.
101 And, Or, Not, True, False, LParen, RParen, EndOfFile, None, Err
104 typedef Boolean CondProc(int, char *);
107 * Structures to handle elegantly the different forms of #if's. The
108 * last two fields are stored in condInvert and condDefProc, respectively.
110 static void CondPushBack(Token);
111 static int CondGetArg(char **, char **, const char *, Boolean);
112 static CondProc CondDoDefined;
113 static CondProc CondDoMake;
114 static CondProc CondDoExists;
115 static CondProc CondDoTarget;
116 static char *CondCvtArg(char *, double *);
117 static Token CondToken(Boolean);
118 static Token CondT(Boolean);
119 static Token CondF(Boolean);
120 static Token CondE(Boolean);
123 const char *form; /* Form of if */
124 int formlen; /* Length of form */
125 Boolean doNot; /* TRUE if default function should be negated */
126 CondProc *defProc; /* Default function to apply */
128 { "ifdef", 5, FALSE, CondDoDefined },
129 { "ifndef", 6, TRUE, CondDoDefined },
130 { "ifmake", 6, FALSE, CondDoMake },
131 { "ifnmake", 7, TRUE, CondDoMake },
132 { "if", 2, FALSE, CondDoDefined },
133 { NULL, 0, FALSE, NULL }
136 static Boolean condInvert; /* Invert the default function */
137 static Boolean (*condDefProc) /* Default function to apply */
139 static char *condExpr; /* The expression to parse */
140 static Token condPushBack=None; /* Single push-back token used in
143 #define MAXIF 30 /* greatest depth of #if'ing */
145 static Boolean condStack[MAXIF]; /* Stack of conditionals's values */
146 static int condLineno[MAXIF]; /* Line numbers of the opening .if */
147 static int condTop = MAXIF; /* Top-most conditional */
148 static int skipIfLevel=0; /* Depth of skipped conditionals */
149 static int skipIfLineno[MAXIF]; /* Line numbers of skipped .ifs */
150 static Boolean skipLine = FALSE; /* Whether the parse module is skipping
154 *-----------------------------------------------------------------------
156 * Push back the most recent token read. We only need one level of
157 * this, so the thing is just stored in 'condPushback'.
163 * condPushback is overwritten.
165 *-----------------------------------------------------------------------
168 CondPushBack(Token t)
175 *-----------------------------------------------------------------------
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
187 *-----------------------------------------------------------------------
190 CondGetArg(char **linePtr, char **argPtr, const char *func, Boolean parens)
198 while (*cp != '(' && *cp != '\0') {
208 * No arguments whatsoever. Because 'make' and 'defined' aren't really
209 * "reserved words", we don't print a message. I think this is better
210 * than hitting the user with a warning message every time s/he uses
211 * the word 'make' or 'defined' 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 the argument
231 * if it's valid. We tell Var_Parse to complain on an undefined
232 * variable, so we don't do it too. Nor do we return an error,
233 * though perhaps we should...
239 cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &doFree);
241 Buf_Append(buf, cp2);
247 Buf_AddByte(buf, (Byte)*cp);
252 Buf_AddByte(buf, (Byte)'\0');
253 *argPtr = (char *)Buf_GetAll(buf, &argLen);
254 Buf_Destroy(buf, FALSE);
256 while (*cp == ' ' || *cp == '\t') {
259 if (parens && *cp != ')') {
260 Parse_Error(PARSE_WARNING, "Missing closing parenthesis for %s()",
265 * Advance pointer past close parenthesis.
275 *-----------------------------------------------------------------------
277 * Handle the 'defined' function for conditionals.
280 * TRUE if the given variable is defined.
285 *-----------------------------------------------------------------------
288 CondDoDefined(int argLen, char *arg)
290 char savec = arg[argLen];
295 if (Var_Value(arg, VAR_CMD, &p1) != NULL) {
306 *-----------------------------------------------------------------------
308 * Front-end for Str_Match so it returns 0 on match and non-zero
309 * on mismatch. Callback function for CondDoMake via Lst_Find
312 * 0 if string matches pattern
317 *-----------------------------------------------------------------------
320 CondStrMatch(const void *string, const void *pattern)
323 return (!Str_Match(string, pattern));
327 *-----------------------------------------------------------------------
329 * Handle the 'make' function for conditionals.
332 * TRUE if the given target is being made.
337 *-----------------------------------------------------------------------
340 CondDoMake(int argLen, char *arg)
342 char savec = arg[argLen];
346 if (Lst_Find(&create, arg, CondStrMatch) == NULL) {
356 *-----------------------------------------------------------------------
358 * See if the given file exists.
361 * TRUE if the file exists and FALSE if it does not.
366 *-----------------------------------------------------------------------
369 CondDoExists(int argLen, char *arg)
371 char savec = arg[argLen];
376 path = Dir_FindFile(arg, &dirSearchPath);
388 *-----------------------------------------------------------------------
390 * See if the given node exists and is an actual target.
393 * TRUE if the node exists as a target and FALSE if it does not.
398 *-----------------------------------------------------------------------
401 CondDoTarget(int argLen, char *arg)
403 char savec = arg[argLen];
408 gn = Targ_FindNode(arg, TARG_NOCREATE);
409 if ((gn != NULL) && !OP_NOP(gn->type)) {
419 *-----------------------------------------------------------------------
421 * Convert the given number into a double. If the number begins
422 * with 0x, it is interpreted as a hexadecimal integer
423 * and converted to a double from there. All other strings just have
424 * strtod called on them.
427 * Sets 'value' to double value of string.
428 * Returns address of the first character after the last valid
429 * character of the converted number.
432 * Can change 'value' even if string is not a valid number.
435 *-----------------------------------------------------------------------
438 CondCvtArg(char *str, double *value)
440 if ((*str == '0') && (str[1] == 'x')) {
443 for (str += 2, i = 0; ; str++) {
445 if (isdigit((unsigned char)*str))
447 else if (isxdigit((unsigned char)*str))
448 x = 10 + *str - isupper((unsigned char)*str) ? 'A' : 'a';
458 *value = strtod(str, &eptr);
464 *-----------------------------------------------------------------------
466 * Return the next token from the input.
469 * A Token for the next lexical token in the stream.
472 * condPushback will be set back to None if it is used.
474 *-----------------------------------------------------------------------
477 CondToken(Boolean doEval)
481 if (condPushBack == None) {
482 while (*condExpr == ' ' || *condExpr == '\t') {
495 if (condExpr[1] == '|') {
502 if (condExpr[1] == '&') {
520 size_t varSpecLen = 0;
524 * Parse the variable spec and skip over it, saving its
528 lhs = Var_Parse(condExpr, VAR_CMD, doEval,
529 &varSpecLen, &doFree);
530 if (lhs == var_Error) {
532 * Even if !doEval, we still report syntax errors, which
533 * is what getting var_Error back with !doEval means.
537 condExpr += varSpecLen;
539 if (!isspace((unsigned char)*condExpr) &&
540 strchr("!=><", *condExpr) == NULL) {
545 Buf_Append(buf, lhs);
550 for (;*condExpr && !isspace((unsigned char) *condExpr);
552 Buf_AddByte(buf, (Byte)*condExpr);
554 Buf_AddByte(buf, (Byte)'\0');
555 lhs = (char *)Buf_GetAll(buf, &varSpecLen);
556 Buf_Destroy(buf, FALSE);
562 * Skip whitespace to get to the operator
564 while (isspace((unsigned char)*condExpr))
568 * Make sure the operator is a valid one. If it isn't a
569 * known relational operator, pretend we got a
578 if (condExpr[1] == '=') {
590 while (isspace((unsigned char)*condExpr)) {
593 if (*condExpr == '\0') {
594 Parse_Error(PARSE_WARNING,
595 "Missing right-hand-side of operator");
602 * Doing a string comparison. Only allow == and != for
611 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
612 Parse_Error(PARSE_WARNING,
613 "String comparison operator should be either == or !=");
618 qt = *rhs == '"' ? 1 : 0;
621 ((qt && (*cp != '"')) ||
622 (!qt && strchr(" \t)", *cp) == NULL)) &&
623 (*cp != '\0'); cp++) {
624 if ((*cp == '\\') && (cp[1] != '\0')) {
626 * Backslash escapes things -- skip over next
627 * character, if it exists.
630 Buf_AddByte(buf, (Byte)*cp);
631 } else if (*cp == '$') {
635 cp2 = Var_Parse(cp, VAR_CMD, doEval, &len, &freeIt);
636 if (cp2 != var_Error) {
637 Buf_Append(buf, cp2);
643 Buf_AddByte(buf, (Byte)*cp);
646 Buf_AddByte(buf, (Byte)*cp);
650 Buf_AddByte(buf, (Byte)0);
652 string = (char *)Buf_GetAll(buf, (size_t *)NULL);
653 Buf_Destroy(buf, FALSE);
655 DEBUGF(COND, ("lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
658 * Null-terminate rhs and perform the comparison.
659 * t is set to the result.
662 t = strcmp(lhs, string) ? False : True;
664 t = strcmp(lhs, string) ? True : False;
667 if (rhs == condExpr) {
668 if (!qt && *cp == ')')
675 * rhs is either a float or an integer. Convert both the
676 * lhs and the rhs to a double and compare the two.
681 if (*CondCvtArg(lhs, &left) != '\0')
682 goto do_string_compare;
687 string = Var_Parse(rhs, VAR_CMD, doEval, &len, &freeIt);
688 if (string == var_Error) {
691 if (*CondCvtArg(string, &right) != '\0') {
694 goto do_string_compare;
702 char *c = CondCvtArg(rhs, &right);
704 goto do_string_compare;
705 if (rhs == condExpr) {
707 * Skip over the right-hand side
713 DEBUGF(COND, ("left = %f, right = %f, op = %.2s\n", left,
718 Parse_Error(PARSE_WARNING,
722 t = (left != right ? True : False);
726 Parse_Error(PARSE_WARNING,
730 t = (left == right ? True : False);
734 t = (left <= right ? True : False);
736 t = (left < right ? True : False);
741 t = (left >= right ? True : False);
743 t = (left > right ? True : False);
757 Boolean invert = FALSE;
761 if (strncmp(condExpr, "defined", 7) == 0) {
763 * Use CondDoDefined to evaluate the argument and
764 * CondGetArg to extract the argument from the 'function
767 evalProc = CondDoDefined;
769 arglen = CondGetArg(&condExpr, &arg, "defined", TRUE);
774 } else if (strncmp(condExpr, "make", 4) == 0) {
776 * Use CondDoMake to evaluate the argument and
777 * CondGetArg to extract the argument from the 'function
780 evalProc = CondDoMake;
782 arglen = CondGetArg(&condExpr, &arg, "make", TRUE);
787 } else if (strncmp(condExpr, "exists", 6) == 0) {
789 * Use CondDoExists to evaluate the argument and
790 * CondGetArg to extract the argument from the
793 evalProc = CondDoExists;
795 arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
800 } else if (strncmp(condExpr, "empty", 5) == 0) {
802 * Use Var_Parse to parse the spec in parens and return
803 * True if the resulting string is empty.
812 condExpr[arglen] != '(' && condExpr[arglen] != '\0';
816 if (condExpr[arglen] != '\0') {
818 val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
819 FALSE, &length, &doFree);
820 if (val == var_Error) {
824 * A variable is empty when it just contains
825 * spaces... 4/15/92, christos
828 for (p = val; *p && isspace((unsigned char)*p); p++)
830 t = (*p == '\0') ? True : False;
836 * Advance condExpr to beyond the closing ). Note that
837 * we subtract one from arglen + length b/c length
838 * is calculated from condExpr[arglen - 1].
840 condExpr += arglen + length - 1;
846 } else if (strncmp(condExpr, "target", 6) == 0) {
848 * Use CondDoTarget to evaluate the argument and
849 * CondGetArg to extract the argument from the
852 evalProc = CondDoTarget;
854 arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
861 * The symbol is itself the argument to the default
862 * function. We advance condExpr to the end of the symbol
863 * by hand (the next whitespace, closing paren or
864 * binary operator) and set to invert the evaluation
865 * function if condInvert is TRUE.
869 evalProc = condDefProc;
870 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
874 * Evaluate the argument using the set function. If invert
875 * is TRUE, we invert the sense of the function.
877 t = (!doEval || (* evalProc) (arglen, arg) ?
878 (invert ? False : True) :
879 (invert ? True : False));
892 *-----------------------------------------------------------------------
894 * Parse a single term in the expression. This consists of a terminal
895 * symbol or Not and a terminal symbol (not including the binary
897 * T -> defined(variable) | make(target) | exists(file) | symbol
901 * True, False or Err.
904 * Tokens are consumed.
906 *-----------------------------------------------------------------------
909 CondT(Boolean doEval)
913 t = CondToken(doEval);
915 if (t == EndOfFile) {
917 * If we reached the end of the expression, the expression
921 } else if (t == LParen) {
927 if (CondToken(doEval) != RParen) {
931 } else if (t == Not) {
935 } else if (t == False) {
943 *-----------------------------------------------------------------------
945 * Parse a conjunctive factor (nice name, wot?)
952 * Tokens are consumed.
954 *-----------------------------------------------------------------------
957 CondF(Boolean doEval)
963 o = CondToken(doEval);
969 * If T is False, the whole thing will be False, but we have to
970 * parse the r.h.s. anyway (to throw it away).
971 * If T is True, the result is the r.h.s., be it an Err or no.
989 *-----------------------------------------------------------------------
991 * Main expression production.
995 * True, False or Err.
998 * Tokens are, of course, consumed.
1000 *-----------------------------------------------------------------------
1003 CondE(Boolean doEval)
1009 o = CondToken(doEval);
1015 * A similar thing occurs for ||, except that here we make sure
1016 * the l.h.s. is False before we bother to evaluate the r.h.s.
1017 * Once again, if l is False, the result is the r.h.s. and once
1018 * again if l is True, we parse the r.h.s. to throw it away.
1036 *-----------------------------------------------------------------------
1038 * Evaluate the conditional in the passed line. The line
1040 * #<cond-type> <expr>
1041 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1042 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1043 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1044 * and parenthetical groupings thereof.
1047 * COND_PARSE if should parse lines after the conditional
1048 * COND_SKIP if should skip lines after the conditional
1049 * COND_INVALID if not a valid conditional.
1054 *-----------------------------------------------------------------------
1057 Cond_Eval(char *line)
1061 Boolean value = FALSE;
1062 int level; /* Level at which to report errors. */
1065 level = PARSE_FATAL;
1066 lineno = curFile.lineno;
1068 for (line++; *line == ' ' || *line == '\t'; line++) {
1073 * Find what type of if we're dealing with. The result is left
1074 * in ifp and isElse is set TRUE if it's an elif line.
1076 if (line[0] == 'e' && line[1] == 'l') {
1079 } else if (strncmp(line, "endif", 5) == 0) {
1081 * End of a conditional section. If skipIfLevel is non-zero, that
1082 * conditional was skipped, so lines following it should also be
1083 * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1084 * was read so succeeding lines should be parsed (think about it...)
1085 * so we return COND_PARSE, unless this endif isn't paired with
1088 if (skipIfLevel != 0) {
1092 if (condTop == MAXIF) {
1093 Parse_Error(level, "if-less endif");
1094 return (COND_INVALID);
1098 return (COND_PARSE);
1106 * Figure out what sort of conditional it is -- what its default
1107 * function is, etc. -- by looking in the table of valid "ifs"
1109 for (ifp = ifs; ifp->form != NULL; ifp++) {
1110 if (strncmp(ifp->form, line, ifp->formlen) == 0) {
1115 if (ifp->form == NULL) {
1117 * Nothing fit. If the first word on the line is actually
1118 * "else", it's a valid conditional whose value is the inverse
1119 * of the previous if we parsed.
1121 if (isElse && (line[0] == 's') && (line[1] == 'e')) {
1122 if (condTop == MAXIF) {
1123 Parse_Error(level, "if-less else");
1124 return (COND_INVALID);
1125 } else if (skipIfLevel == 0) {
1126 value = !condStack[condTop];
1127 lineno = condLineno[condTop];
1133 * Not a valid conditional type. No error...
1135 return (COND_INVALID);
1139 if (condTop == MAXIF) {
1140 Parse_Error(level, "if-less elif");
1141 return (COND_INVALID);
1142 } else if (skipIfLevel != 0) {
1144 * If skipping this conditional, just ignore the whole thing.
1145 * If we don't, the user might be employing a variable that's
1146 * undefined, for which there's an enclosing ifdef that
1149 skipIfLineno[skipIfLevel - 1] = lineno;
1152 } else if (skipLine) {
1154 * Don't even try to evaluate a conditional that's not an else if
1155 * we're skipping things...
1157 skipIfLineno[skipIfLevel] = lineno;
1163 * Initialize file-global variables for parsing
1165 condDefProc = ifp->defProc;
1166 condInvert = ifp->doNot;
1168 line += ifp->formlen;
1170 while (*line == ' ' || *line == '\t') {
1175 condPushBack = None;
1177 switch (CondE(TRUE)) {
1179 if (CondToken(TRUE) == EndOfFile) {
1186 if (CondToken(TRUE) == EndOfFile) {
1193 Parse_Error(level, "Malformed conditional (%s)",
1195 return (COND_INVALID);
1202 } else if ((skipIfLevel != 0) || condStack[condTop]) {
1204 * If this is an else-type conditional, it should only take effect
1205 * if its corresponding if was evaluated and FALSE. If its if was
1206 * TRUE or skipped, we return COND_SKIP (and start skipping in case
1207 * we weren't already), leaving the stack unmolested so later elif's
1216 * This is the one case where we can definitely proclaim a fatal
1217 * error. If we don't, we're hosed.
1219 Parse_Error(PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1220 return (COND_INVALID);
1222 condStack[condTop] = value;
1223 condLineno[condTop] = lineno;
1225 return (value ? COND_PARSE : COND_SKIP);
1230 *-----------------------------------------------------------------------
1232 * Make sure everything's clean at the end of a makefile.
1238 * Parse_Error will be called if open conditionals are around.
1240 *-----------------------------------------------------------------------
1247 if (condTop != MAXIF) {
1248 Parse_Error(PARSE_FATAL, "%d open conditional%s:",
1249 MAXIF - condTop + skipIfLevel,
1250 MAXIF - condTop + skipIfLevel== 1 ? "" : "s");
1252 for (level = skipIfLevel; level > 0; level--)
1253 Parse_Error(PARSE_FATAL, "\t%*sat line %d (skipped)",
1254 MAXIF - condTop + level + 1, "", skipIfLineno[level - 1]);
1255 for (level = condTop; level < MAXIF; level++)
1256 Parse_Error(PARSE_FATAL, "\t%*sat line %d "
1257 "(evaluated to %s)", MAXIF - level + skipIfLevel, "",
1258 condLineno[level], condStack[level] ? "true" : "false");