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.12.2.1 2003/07/22 08:03:13 ru Exp $
41 * $DragonFly: src/usr.bin/make/cond.c,v 1.22 2005/01/09 23:14:42 okumoto Exp $
46 * Functions to handle conditionals in a makefile.
49 * Cond_Eval Evaluate the conditional in the passed line.
72 * The parsing of conditional expressions is based on this grammar:
77 * T -> defined(variable)
83 * T -> $(varspec) op value
84 * T -> $(varspec) == "string"
85 * T -> $(varspec) != "string"
88 * op -> == | != | > | < | >= | <=
90 * 'symbol' is some other symbol to which the default function (condDefProc)
93 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
94 * will return And for '&' and '&&', Or for '|' and '||', Not for '!',
95 * LParen for '(', RParen for ')' and will evaluate the other terminal
96 * symbols, using either the default function or the function given in the
97 * terminal, and return the result as either True or False.
99 * All Non-Terminal functions (CondE, CondF and CondT) return Err on error.
102 And, Or, Not, True, False, LParen, RParen, EndOfFile, None, Err
105 typedef Boolean CondProc(int, char *);
108 * Structures to handle elegantly the different forms of #if's. The
109 * last two fields are stored in condInvert and condDefProc, respectively.
111 static void CondPushBack(Token);
112 static int CondGetArg(char **, char **, const char *, Boolean);
113 static CondProc CondDoDefined;
114 static CondProc CondDoMake;
115 static CondProc CondDoExists;
116 static CondProc CondDoTarget;
117 static char *CondCvtArg(char *, double *);
118 static Token CondToken(Boolean);
119 static Token CondT(Boolean);
120 static Token CondF(Boolean);
121 static Token CondE(Boolean);
124 const char *form; /* Form of if */
125 int formlen; /* Length of form */
126 Boolean doNot; /* TRUE if default function should be negated */
127 CondProc *defProc; /* Default function to apply */
129 { "ifdef", 5, FALSE, CondDoDefined },
130 { "ifndef", 6, TRUE, CondDoDefined },
131 { "ifmake", 6, FALSE, CondDoMake },
132 { "ifnmake", 7, TRUE, CondDoMake },
133 { "if", 2, FALSE, CondDoDefined },
134 { NULL, 0, FALSE, NULL }
137 static Boolean condInvert; /* Invert the default function */
138 static Boolean (*condDefProc) /* Default function to apply */
140 static char *condExpr; /* The expression to parse */
141 static Token condPushBack=None; /* Single push-back token used in
144 #define MAXIF 30 /* greatest depth of #if'ing */
146 static Boolean condStack[MAXIF]; /* Stack of conditionals's values */
147 static int condLineno[MAXIF]; /* Line numbers of the opening .if */
148 static int condTop = MAXIF; /* Top-most conditional */
149 static int skipIfLevel=0; /* Depth of skipped conditionals */
150 static int skipIfLineno[MAXIF]; /* Line numbers of skipped .ifs */
151 static Boolean skipLine = FALSE; /* Whether the parse module is skipping
155 *-----------------------------------------------------------------------
157 * Push back the most recent token read. We only need one level of
158 * this, so the thing is just stored in 'condPushback'.
164 * condPushback is overwritten.
166 *-----------------------------------------------------------------------
169 CondPushBack(Token t)
176 *-----------------------------------------------------------------------
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
188 *-----------------------------------------------------------------------
191 CondGetArg(char **linePtr, char **argPtr, const char *func, Boolean parens)
199 while (*cp != '(' && *cp != '\0') {
209 * No arguments whatsoever. Because 'make' and 'defined' aren't really
210 * "reserved words", we don't print a message. I think this is better
211 * than hitting the user with a warning message every time s/he uses
212 * the word 'make' or 'defined' at the beginning of a symbol...
218 while (*cp == ' ' || *cp == '\t') {
223 * Create a buffer for the argument and start it out at 16 characters
224 * long. Why 16? Why not?
228 while ((strchr(" \t)&|", *cp) == NULL) && (*cp != '\0')) {
231 * Parse the variable spec and install it as part of the argument
232 * if it's valid. We tell Var_Parse to complain on an undefined
233 * variable, so we don't do it too. Nor do we return an error,
234 * though perhaps we should...
240 cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &doFree);
242 Buf_AddBytes(buf, strlen(cp2), (Byte *)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, "Missing closing parenthesis for %s()",
266 * Advance pointer past close parenthesis.
276 *-----------------------------------------------------------------------
278 * Handle the 'defined' function for conditionals.
281 * TRUE if the given variable is defined.
286 *-----------------------------------------------------------------------
289 CondDoDefined(int argLen, char *arg)
291 char savec = arg[argLen];
296 if (Var_Value(arg, VAR_CMD, &p1) != NULL) {
307 *-----------------------------------------------------------------------
309 * Front-end for Str_Match so it returns 0 on match and non-zero
310 * on mismatch. Callback function for CondDoMake via Lst_Find
313 * 0 if string matches pattern
318 *-----------------------------------------------------------------------
321 CondStrMatch(const void *string, const void *pattern)
324 return (!Str_Match(string, pattern));
328 *-----------------------------------------------------------------------
330 * Handle the 'make' function for conditionals.
333 * TRUE if the given target is being made.
338 *-----------------------------------------------------------------------
341 CondDoMake(int argLen, char *arg)
343 char savec = arg[argLen];
347 if (Lst_Find(&create, arg, CondStrMatch) == NULL) {
357 *-----------------------------------------------------------------------
359 * See if the given file exists.
362 * TRUE if the file exists and FALSE if it does not.
367 *-----------------------------------------------------------------------
370 CondDoExists(int argLen, char *arg)
372 char savec = arg[argLen];
377 path = Dir_FindFile(arg, &dirSearchPath);
389 *-----------------------------------------------------------------------
391 * See if the given node exists and is an actual target.
394 * TRUE if the node exists as a target and FALSE if it does not.
399 *-----------------------------------------------------------------------
402 CondDoTarget(int argLen, char *arg)
404 char savec = arg[argLen];
409 gn = Targ_FindNode(arg, TARG_NOCREATE);
410 if ((gn != NULL) && !OP_NOP(gn->type)) {
420 *-----------------------------------------------------------------------
422 * Convert the given number into a double. If the number begins
423 * with 0x, it is interpreted as a hexadecimal integer
424 * and converted to a double from there. All other strings just have
425 * strtod called on them.
428 * Sets 'value' to double value of string.
429 * Returns address of the first character after the last valid
430 * character of the converted number.
433 * Can change 'value' even if string is not a valid number.
436 *-----------------------------------------------------------------------
439 CondCvtArg(char *str, double *value)
441 if ((*str == '0') && (str[1] == 'x')) {
444 for (str += 2, i = 0; ; str++) {
446 if (isdigit((unsigned char)*str))
448 else if (isxdigit((unsigned char)*str))
449 x = 10 + *str - isupper((unsigned char)*str) ? 'A' : 'a';
459 *value = strtod(str, &eptr);
465 *-----------------------------------------------------------------------
467 * Return the next token from the input.
470 * A Token for the next lexical token in the stream.
473 * condPushback will be set back to None if it is used.
475 *-----------------------------------------------------------------------
478 CondToken(Boolean doEval)
482 if (condPushBack == None) {
483 while (*condExpr == ' ' || *condExpr == '\t') {
496 if (condExpr[1] == '|') {
503 if (condExpr[1] == '&') {
525 * Parse the variable spec and skip over it, saving its
529 lhs = Var_Parse(condExpr, VAR_CMD, doEval,
530 &varSpecLen, &doFree);
531 if (lhs == var_Error) {
533 * Even if !doEval, we still report syntax errors, which
534 * is what getting var_Error back with !doEval means.
538 condExpr += varSpecLen;
540 if (!isspace((unsigned char)*condExpr) &&
541 strchr("!=><", *condExpr) == NULL) {
547 for (cp = lhs; *cp; cp++)
548 Buf_AddByte(buf, (Byte)*cp);
553 for (;*condExpr && !isspace((unsigned char) *condExpr);
555 Buf_AddByte(buf, (Byte)*condExpr);
557 Buf_AddByte(buf, (Byte)'\0');
558 lhs = (char *)Buf_GetAll(buf, &varSpecLen);
559 Buf_Destroy(buf, FALSE);
565 * Skip whitespace to get to the operator
567 while (isspace((unsigned char)*condExpr))
571 * Make sure the operator is a valid one. If it isn't a
572 * known relational operator, pretend we got a
581 if (condExpr[1] == '=') {
593 while (isspace((unsigned char)*condExpr)) {
596 if (*condExpr == '\0') {
597 Parse_Error(PARSE_WARNING,
598 "Missing right-hand-side of operator");
605 * Doing a string comparison. Only allow == and != for
614 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
615 Parse_Error(PARSE_WARNING,
616 "String comparison operator should be either == or !=");
621 qt = *rhs == '"' ? 1 : 0;
624 ((qt && (*cp != '"')) ||
625 (!qt && strchr(" \t)", *cp) == NULL)) &&
626 (*cp != '\0'); cp++) {
627 if ((*cp == '\\') && (cp[1] != '\0')) {
629 * Backslash escapes things -- skip over next
630 * character, if it exists.
633 Buf_AddByte(buf, (Byte)*cp);
634 } else if (*cp == '$') {
638 cp2 = Var_Parse(cp, VAR_CMD, doEval, &len, &freeIt);
639 if (cp2 != var_Error) {
640 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
646 Buf_AddByte(buf, (Byte)*cp);
649 Buf_AddByte(buf, (Byte)*cp);
653 Buf_AddByte(buf, (Byte)0);
655 string = (char *)Buf_GetAll(buf, (size_t *)NULL);
656 Buf_Destroy(buf, FALSE);
658 DEBUGF(COND, ("lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
661 * Null-terminate rhs and perform the comparison.
662 * t is set to the result.
665 t = strcmp(lhs, string) ? False : True;
667 t = strcmp(lhs, string) ? True : False;
670 if (rhs == condExpr) {
671 if (!qt && *cp == ')')
678 * rhs is either a float or an integer. Convert both the
679 * lhs and the rhs to a double and compare the two.
684 if (*CondCvtArg(lhs, &left) != '\0')
685 goto do_string_compare;
690 string = Var_Parse(rhs, VAR_CMD, doEval, &len, &freeIt);
691 if (string == var_Error) {
694 if (*CondCvtArg(string, &right) != '\0') {
697 goto do_string_compare;
705 char *c = CondCvtArg(rhs, &right);
707 goto do_string_compare;
708 if (rhs == condExpr) {
710 * Skip over the right-hand side
716 DEBUGF(COND, ("left = %f, right = %f, op = %.2s\n", left,
721 Parse_Error(PARSE_WARNING,
725 t = (left != right ? True : False);
729 Parse_Error(PARSE_WARNING,
733 t = (left == right ? True : False);
737 t = (left <= right ? True : False);
739 t = (left < right ? True : False);
744 t = (left >= right ? True : False);
746 t = (left > right ? True : False);
760 Boolean invert = FALSE;
764 if (strncmp(condExpr, "defined", 7) == 0) {
766 * Use CondDoDefined to evaluate the argument and
767 * CondGetArg to extract the argument from the 'function
770 evalProc = CondDoDefined;
772 arglen = CondGetArg(&condExpr, &arg, "defined", TRUE);
777 } else if (strncmp(condExpr, "make", 4) == 0) {
779 * Use CondDoMake to evaluate the argument and
780 * CondGetArg to extract the argument from the 'function
783 evalProc = CondDoMake;
785 arglen = CondGetArg(&condExpr, &arg, "make", TRUE);
790 } else if (strncmp(condExpr, "exists", 6) == 0) {
792 * Use CondDoExists to evaluate the argument and
793 * CondGetArg to extract the argument from the
796 evalProc = CondDoExists;
798 arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
803 } else if (strncmp(condExpr, "empty", 5) == 0) {
805 * Use Var_Parse to parse the spec in parens and return
806 * True if the resulting string is empty.
815 condExpr[arglen] != '(' && condExpr[arglen] != '\0';
819 if (condExpr[arglen] != '\0') {
820 val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
821 FALSE, &length, &doFree);
822 if (val == var_Error) {
826 * A variable is empty when it just contains
827 * spaces... 4/15/92, christos
830 for (p = val; *p && isspace((unsigned char)*p); p++)
832 t = (*p == '\0') ? True : False;
838 * Advance condExpr to beyond the closing ). Note that
839 * we subtract one from arglen + length b/c length
840 * is calculated from condExpr[arglen - 1].
842 condExpr += arglen + length - 1;
848 } else if (strncmp(condExpr, "target", 6) == 0) {
850 * Use CondDoTarget to evaluate the argument and
851 * CondGetArg to extract the argument from the
854 evalProc = CondDoTarget;
856 arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
863 * The symbol is itself the argument to the default
864 * function. We advance condExpr to the end of the symbol
865 * by hand (the next whitespace, closing paren or
866 * binary operator) and set to invert the evaluation
867 * function if condInvert is TRUE.
871 evalProc = condDefProc;
872 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
876 * Evaluate the argument using the set function. If invert
877 * is TRUE, we invert the sense of the function.
879 t = (!doEval || (* evalProc) (arglen, arg) ?
880 (invert ? False : True) :
881 (invert ? True : False));
894 *-----------------------------------------------------------------------
896 * Parse a single term in the expression. This consists of a terminal
897 * symbol or Not and a terminal symbol (not including the binary
899 * T -> defined(variable) | make(target) | exists(file) | symbol
903 * True, False or Err.
906 * Tokens are consumed.
908 *-----------------------------------------------------------------------
911 CondT(Boolean doEval)
915 t = CondToken(doEval);
917 if (t == EndOfFile) {
919 * If we reached the end of the expression, the expression
923 } else if (t == LParen) {
929 if (CondToken(doEval) != RParen) {
933 } else if (t == Not) {
937 } else if (t == False) {
945 *-----------------------------------------------------------------------
947 * Parse a conjunctive factor (nice name, wot?)
954 * Tokens are consumed.
956 *-----------------------------------------------------------------------
959 CondF(Boolean doEval)
965 o = CondToken(doEval);
971 * If T is False, the whole thing will be False, but we have to
972 * parse the r.h.s. anyway (to throw it away).
973 * If T is True, the result is the r.h.s., be it an Err or no.
991 *-----------------------------------------------------------------------
993 * Main expression production.
997 * True, False or Err.
1000 * Tokens are, of course, consumed.
1002 *-----------------------------------------------------------------------
1005 CondE(Boolean doEval)
1011 o = CondToken(doEval);
1017 * A similar thing occurs for ||, except that here we make sure
1018 * the l.h.s. is False before we bother to evaluate the r.h.s.
1019 * Once again, if l is False, the result is the r.h.s. and once
1020 * again if l is True, we parse the r.h.s. to throw it away.
1038 *-----------------------------------------------------------------------
1040 * Evaluate the conditional in the passed line. The line
1042 * #<cond-type> <expr>
1043 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1044 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1045 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1046 * and parenthetical groupings thereof.
1049 * COND_PARSE if should parse lines after the conditional
1050 * COND_SKIP if should skip lines after the conditional
1051 * COND_INVALID if not a valid conditional.
1056 *-----------------------------------------------------------------------
1059 Cond_Eval(char *line)
1063 Boolean value = FALSE;
1064 int level; /* Level at which to report errors. */
1067 level = PARSE_FATAL;
1068 lineno = curFile.lineno;
1070 for (line++; *line == ' ' || *line == '\t'; line++) {
1075 * Find what type of if we're dealing with. The result is left
1076 * in ifp and isElse is set TRUE if it's an elif line.
1078 if (line[0] == 'e' && line[1] == 'l') {
1081 } else if (strncmp(line, "endif", 5) == 0) {
1083 * End of a conditional section. If skipIfLevel is non-zero, that
1084 * conditional was skipped, so lines following it should also be
1085 * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1086 * was read so succeeding lines should be parsed (think about it...)
1087 * so we return COND_PARSE, unless this endif isn't paired with
1090 if (skipIfLevel != 0) {
1094 if (condTop == MAXIF) {
1095 Parse_Error(level, "if-less endif");
1096 return (COND_INVALID);
1100 return (COND_PARSE);
1108 * Figure out what sort of conditional it is -- what its default
1109 * function is, etc. -- by looking in the table of valid "ifs"
1111 for (ifp = ifs; ifp->form != NULL; ifp++) {
1112 if (strncmp(ifp->form, line, ifp->formlen) == 0) {
1117 if (ifp->form == NULL) {
1119 * Nothing fit. If the first word on the line is actually
1120 * "else", it's a valid conditional whose value is the inverse
1121 * of the previous if we parsed.
1123 if (isElse && (line[0] == 's') && (line[1] == 'e')) {
1124 if (condTop == MAXIF) {
1125 Parse_Error(level, "if-less else");
1126 return (COND_INVALID);
1127 } else if (skipIfLevel == 0) {
1128 value = !condStack[condTop];
1129 lineno = condLineno[condTop];
1135 * Not a valid conditional type. No error...
1137 return (COND_INVALID);
1141 if (condTop == MAXIF) {
1142 Parse_Error(level, "if-less elif");
1143 return (COND_INVALID);
1144 } else if (skipIfLevel != 0) {
1146 * If skipping this conditional, just ignore the whole thing.
1147 * If we don't, the user might be employing a variable that's
1148 * undefined, for which there's an enclosing ifdef that
1151 skipIfLineno[skipIfLevel - 1] = lineno;
1154 } else if (skipLine) {
1156 * Don't even try to evaluate a conditional that's not an else if
1157 * we're skipping things...
1159 skipIfLineno[skipIfLevel] = lineno;
1165 * Initialize file-global variables for parsing
1167 condDefProc = ifp->defProc;
1168 condInvert = ifp->doNot;
1170 line += ifp->formlen;
1172 while (*line == ' ' || *line == '\t') {
1177 condPushBack = None;
1179 switch (CondE(TRUE)) {
1181 if (CondToken(TRUE) == EndOfFile) {
1188 if (CondToken(TRUE) == EndOfFile) {
1195 Parse_Error(level, "Malformed conditional (%s)",
1197 return (COND_INVALID);
1204 } else if ((skipIfLevel != 0) || condStack[condTop]) {
1206 * If this is an else-type conditional, it should only take effect
1207 * if its corresponding if was evaluated and FALSE. If its if was
1208 * TRUE or skipped, we return COND_SKIP (and start skipping in case
1209 * we weren't already), leaving the stack unmolested so later elif's
1218 * This is the one case where we can definitely proclaim a fatal
1219 * error. If we don't, we're hosed.
1221 Parse_Error(PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1222 return (COND_INVALID);
1224 condStack[condTop] = value;
1225 condLineno[condTop] = lineno;
1227 return (value ? COND_PARSE : COND_SKIP);
1232 *-----------------------------------------------------------------------
1234 * Make sure everything's clean at the end of a makefile.
1240 * Parse_Error will be called if open conditionals are around.
1242 *-----------------------------------------------------------------------
1249 if (condTop != MAXIF) {
1250 Parse_Error(PARSE_FATAL, "%d open conditional%s:",
1251 MAXIF - condTop + skipIfLevel,
1252 MAXIF - condTop + skipIfLevel== 1 ? "" : "s");
1254 for (level = skipIfLevel; level > 0; level--)
1255 Parse_Error(PARSE_FATAL, "\t%*sat line %d (skipped)",
1256 MAXIF - condTop + level + 1, "", skipIfLineno[level - 1]);
1257 for (level = condTop; level < MAXIF; level++)
1258 Parse_Error(PARSE_FATAL, "\t%*sat line %d "
1259 "(evaluated to %s)", MAXIF - level + skipIfLevel, "",
1260 condLineno[level], condStack[level] ? "true" : "false");