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.12 2004/12/01 15:17:28 joerg Exp $
46 * Functions to handle conditionals in a makefile.
49 * Cond_Eval Evaluate the conditional in the passed line.
61 * The parsing of conditional expressions is based on this grammar:
66 * T -> defined(variable)
72 * T -> $(varspec) op value
73 * T -> $(varspec) == "string"
74 * T -> $(varspec) != "string"
77 * op -> == | != | > | < | >= | <=
79 * 'symbol' is some other symbol to which the default function (condDefProc)
82 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
83 * will return And for '&' and '&&', Or for '|' and '||', Not for '!',
84 * LParen for '(', RParen for ')' and will evaluate the other terminal
85 * symbols, using either the default function or the function given in the
86 * terminal, and return the result as either True or False.
88 * All Non-Terminal functions (CondE, CondF and CondT) return Err on error.
91 And, Or, Not, True, False, LParen, RParen, EndOfFile, None, Err
95 * Structures to handle elegantly the different forms of #if's. The
96 * last two fields are stored in condInvert and condDefProc, respectively.
98 static void CondPushBack(Token);
99 static int CondGetArg(char **, char **, char *, Boolean);
100 static Boolean CondDoDefined(int, char *);
101 static int CondStrMatch(void *, void *);
102 static Boolean CondDoMake(int, char *);
103 static Boolean CondDoExists(int, char *);
104 static Boolean CondDoTarget(int, char *);
105 static char * CondCvtArg(char *, double *);
106 static Token CondToken(Boolean);
107 static Token CondT(Boolean);
108 static Token CondF(Boolean);
109 static Token CondE(Boolean);
112 char *form; /* Form of if */
113 int formlen; /* Length of form */
114 Boolean doNot; /* TRUE if default function should be negated */
115 Boolean (*defProc)(int, char *); /* Default function to apply */
117 { "ifdef", 5, FALSE, CondDoDefined },
118 { "ifndef", 6, TRUE, CondDoDefined },
119 { "ifmake", 6, FALSE, CondDoMake },
120 { "ifnmake", 7, TRUE, CondDoMake },
121 { "if", 2, FALSE, CondDoDefined },
122 { NULL, 0, FALSE, NULL }
125 static Boolean condInvert; /* Invert the default function */
126 static Boolean (*condDefProc) /* Default function to apply */
128 static char *condExpr; /* The expression to parse */
129 static Token condPushBack=None; /* Single push-back token used in
132 #define MAXIF 30 /* greatest depth of #if'ing */
134 static Boolean condStack[MAXIF]; /* Stack of conditionals's values */
135 static int condLineno[MAXIF]; /* Line numbers of the opening .if */
136 static int condTop = MAXIF; /* Top-most conditional */
137 static int skipIfLevel=0; /* Depth of skipped conditionals */
138 static int skipIfLineno[MAXIF]; /* Line numbers of skipped .ifs */
139 static Boolean skipLine = FALSE; /* Whether the parse module is skipping
143 *-----------------------------------------------------------------------
145 * Push back the most recent token read. We only need one level of
146 * this, so the thing is just stored in 'condPushback'.
152 * condPushback is overwritten.
154 *-----------------------------------------------------------------------
157 CondPushBack (Token t)
163 *-----------------------------------------------------------------------
165 * Find the argument of a built-in function. parens is set to TRUE
166 * if the arguments are bounded by parens.
169 * The length of the argument and the address of the argument.
172 * The pointer is set to point to the closing parenthesis of the
175 *-----------------------------------------------------------------------
178 CondGetArg (char **linePtr, char **argPtr, char *func, Boolean parens)
186 while (*cp != '(' && *cp != '\0') {
196 * No arguments whatsoever. Because 'make' and 'defined' aren't really
197 * "reserved words", we don't print a message. I think this is better
198 * than hitting the user with a warning message every time s/he uses
199 * the word 'make' or 'defined' at the beginning of a symbol...
205 while (*cp == ' ' || *cp == '\t') {
210 * Create a buffer for the argument and start it out at 16 characters
211 * long. Why 16? Why not?
215 while ((strchr(" \t)&|", *cp) == (char *)NULL) && (*cp != '\0')) {
218 * Parse the variable spec and install it as part of the argument
219 * if it's valid. We tell Var_Parse to complain on an undefined
220 * variable, so we don't do it too. Nor do we return an error,
221 * though perhaps we should...
227 cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &doFree);
229 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
235 Buf_AddByte(buf, (Byte)*cp);
240 Buf_AddByte(buf, (Byte)'\0');
241 *argPtr = (char *)Buf_GetAll(buf, &argLen);
242 Buf_Destroy(buf, FALSE);
244 while (*cp == ' ' || *cp == '\t') {
247 if (parens && *cp != ')') {
248 Parse_Error (PARSE_WARNING, "Missing closing parenthesis for %s()",
253 * Advance pointer past close parenthesis.
263 *-----------------------------------------------------------------------
265 * Handle the 'defined' function for conditionals.
268 * TRUE if the given variable is defined.
273 *-----------------------------------------------------------------------
276 CondDoDefined (int argLen, char *arg)
278 char savec = arg[argLen];
283 if (Var_Value (arg, VAR_CMD, &p1) != (char *)NULL) {
294 *-----------------------------------------------------------------------
296 * Front-end for Str_Match so it returns 0 on match and non-zero
297 * on mismatch. Callback function for CondDoMake via Lst_Find
300 * 0 if string matches pattern
305 *-----------------------------------------------------------------------
308 CondStrMatch(void *string, void *pattern)
310 return(!Str_Match((char *) string,(char *) pattern));
314 *-----------------------------------------------------------------------
316 * Handle the 'make' function for conditionals.
319 * TRUE if the given target is being made.
324 *-----------------------------------------------------------------------
327 CondDoMake (int argLen, char *arg)
329 char savec = arg[argLen];
333 if (Lst_Find (create, (void *)arg, CondStrMatch) == NULL) {
343 *-----------------------------------------------------------------------
345 * See if the given file exists.
348 * TRUE if the file exists and FALSE if it does not.
353 *-----------------------------------------------------------------------
356 CondDoExists (int argLen, char *arg)
358 char savec = arg[argLen];
363 path = Dir_FindFile(arg, dirSearchPath);
364 if (path != (char *)NULL) {
375 *-----------------------------------------------------------------------
377 * See if the given node exists and is an actual target.
380 * TRUE if the node exists as a target and FALSE if it does not.
385 *-----------------------------------------------------------------------
388 CondDoTarget (int argLen, char *arg)
390 char savec = arg[argLen];
395 gn = Targ_FindNode(arg, TARG_NOCREATE);
396 if ((gn != NULL) && !OP_NOP(gn->type)) {
407 *-----------------------------------------------------------------------
409 * Convert the given number into a double. If the number begins
410 * with 0x, it is interpreted as a hexadecimal integer
411 * and converted to a double from there. All other strings just have
412 * strtod called on them.
415 * Sets 'value' to double value of string.
416 * Returns address of the first character after the last valid
417 * character of the converted number.
420 * Can change 'value' even if string is not a valid number.
423 *-----------------------------------------------------------------------
426 CondCvtArg(char *str, double *value)
428 if ((*str == '0') && (str[1] == 'x')) {
431 for (str += 2, i = 0; ; str++) {
433 if (isdigit((unsigned char) *str))
435 else if (isxdigit((unsigned char) *str))
436 x = 10 + *str - isupper((unsigned char) *str) ? 'A' : 'a';
446 *value = strtod(str, &eptr);
452 *-----------------------------------------------------------------------
454 * Return the next token from the input.
457 * A Token for the next lexical token in the stream.
460 * condPushback will be set back to None if it is used.
462 *-----------------------------------------------------------------------
465 CondToken(Boolean doEval)
469 if (condPushBack == None) {
470 while (*condExpr == ' ' || *condExpr == '\t') {
483 if (condExpr[1] == '|') {
490 if (condExpr[1] == '&') {
512 * Parse the variable spec and skip over it, saving its
516 lhs = Var_Parse(condExpr, VAR_CMD, doEval,&varSpecLen,&doFree);
517 if (lhs == var_Error) {
519 * Even if !doEval, we still report syntax errors, which
520 * is what getting var_Error back with !doEval means.
524 condExpr += varSpecLen;
526 if (!isspace((unsigned char) *condExpr) &&
527 strchr("!=><", *condExpr) == NULL) {
533 for (cp = lhs; *cp; cp++)
534 Buf_AddByte(buf, (Byte)*cp);
539 for (;*condExpr && !isspace((unsigned char) *condExpr);
541 Buf_AddByte(buf, (Byte)*condExpr);
543 Buf_AddByte(buf, (Byte)'\0');
544 lhs = (char *)Buf_GetAll(buf, &varSpecLen);
545 Buf_Destroy(buf, FALSE);
551 * Skip whitespace to get to the operator
553 while (isspace((unsigned char) *condExpr))
557 * Make sure the operator is a valid one. If it isn't a
558 * known relational operator, pretend we got a
567 if (condExpr[1] == '=') {
579 while (isspace((unsigned char) *condExpr)) {
582 if (*condExpr == '\0') {
583 Parse_Error(PARSE_WARNING,
584 "Missing right-hand-side of operator");
591 * Doing a string comparison. Only allow == and != for
600 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
601 Parse_Error(PARSE_WARNING,
602 "String comparison operator should be either == or !=");
607 qt = *rhs == '"' ? 1 : 0;
610 ((qt && (*cp != '"')) ||
611 (!qt && strchr(" \t)", *cp) == NULL)) &&
612 (*cp != '\0'); cp++) {
613 if ((*cp == '\\') && (cp[1] != '\0')) {
615 * Backslash escapes things -- skip over next
616 * character, if it exists.
619 Buf_AddByte(buf, (Byte)*cp);
620 } else if (*cp == '$') {
624 cp2 = Var_Parse(cp, VAR_CMD, doEval,&len, &freeIt);
625 if (cp2 != var_Error) {
626 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
632 Buf_AddByte(buf, (Byte)*cp);
635 Buf_AddByte(buf, (Byte)*cp);
639 Buf_AddByte(buf, (Byte)0);
641 string = (char *)Buf_GetAll(buf, (int *)0);
642 Buf_Destroy(buf, FALSE);
644 DEBUGF(COND, ("lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
647 * Null-terminate rhs and perform the comparison.
648 * t is set to the result.
651 t = strcmp(lhs, string) ? False : True;
653 t = strcmp(lhs, string) ? True : False;
656 if (rhs == condExpr) {
657 if (!qt && *cp == ')')
664 * rhs is either a float or an integer. Convert both the
665 * lhs and the rhs to a double and compare the two.
670 if (*CondCvtArg(lhs, &left) != '\0')
671 goto do_string_compare;
676 string = Var_Parse(rhs, VAR_CMD, doEval,&len,&freeIt);
677 if (string == var_Error) {
680 if (*CondCvtArg(string, &right) != '\0') {
683 goto do_string_compare;
691 char *c = CondCvtArg(rhs, &right);
693 goto do_string_compare;
694 if (rhs == condExpr) {
696 * Skip over the right-hand side
702 DEBUGF(COND, ("left = %f, right = %f, op = %.2s\n", left,
707 Parse_Error(PARSE_WARNING,
711 t = (left != right ? True : False);
715 Parse_Error(PARSE_WARNING,
719 t = (left == right ? True : False);
723 t = (left <= right ? True : False);
725 t = (left < right ? True : False);
730 t = (left >= right ? True : False);
732 t = (left > right ? True : False);
745 Boolean (*evalProc)(int, char *);
746 Boolean invert = FALSE;
750 if (strncmp (condExpr, "defined", 7) == 0) {
752 * Use CondDoDefined to evaluate the argument and
753 * CondGetArg to extract the argument from the 'function
756 evalProc = CondDoDefined;
758 arglen = CondGetArg (&condExpr, &arg, "defined", TRUE);
763 } else if (strncmp (condExpr, "make", 4) == 0) {
765 * Use CondDoMake to evaluate the argument and
766 * CondGetArg to extract the argument from the 'function
769 evalProc = CondDoMake;
771 arglen = CondGetArg (&condExpr, &arg, "make", TRUE);
776 } else if (strncmp (condExpr, "exists", 6) == 0) {
778 * Use CondDoExists to evaluate the argument and
779 * CondGetArg to extract the argument from the
782 evalProc = CondDoExists;
784 arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
789 } else if (strncmp(condExpr, "empty", 5) == 0) {
791 * Use Var_Parse to parse the spec in parens and return
792 * True if the resulting string is empty.
801 condExpr[arglen] != '(' && condExpr[arglen] != '\0';
805 if (condExpr[arglen] != '\0') {
806 val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
807 FALSE, &length, &doFree);
808 if (val == var_Error) {
812 * A variable is empty when it just contains
813 * spaces... 4/15/92, christos
816 for (p = val; *p && isspace((unsigned char)*p); p++)
818 t = (*p == '\0') ? True : False;
824 * Advance condExpr to beyond the closing ). Note that
825 * we subtract one from arglen + length b/c length
826 * is calculated from condExpr[arglen - 1].
828 condExpr += arglen + length - 1;
834 } else if (strncmp (condExpr, "target", 6) == 0) {
836 * Use CondDoTarget to evaluate the argument and
837 * CondGetArg to extract the argument from the
840 evalProc = CondDoTarget;
842 arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
849 * The symbol is itself the argument to the default
850 * function. We advance condExpr to the end of the symbol
851 * by hand (the next whitespace, closing paren or
852 * binary operator) and set to invert the evaluation
853 * function if condInvert is TRUE.
857 evalProc = condDefProc;
858 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
862 * Evaluate the argument using the set function. If invert
863 * is TRUE, we invert the sense of the function.
865 t = (!doEval || (* evalProc) (arglen, arg) ?
866 (invert ? False : True) :
867 (invert ? True : False));
880 *-----------------------------------------------------------------------
882 * Parse a single term in the expression. This consists of a terminal
883 * symbol or Not and a terminal symbol (not including the binary
885 * T -> defined(variable) | make(target) | exists(file) | symbol
889 * True, False or Err.
892 * Tokens are consumed.
894 *-----------------------------------------------------------------------
897 CondT(Boolean doEval)
901 t = CondToken(doEval);
903 if (t == EndOfFile) {
905 * If we reached the end of the expression, the expression
909 } else if (t == LParen) {
915 if (CondToken(doEval) != RParen) {
919 } else if (t == Not) {
923 } else if (t == False) {
931 *-----------------------------------------------------------------------
933 * Parse a conjunctive factor (nice name, wot?)
940 * Tokens are consumed.
942 *-----------------------------------------------------------------------
945 CondF(Boolean doEval)
951 o = CondToken(doEval);
957 * If T is False, the whole thing will be False, but we have to
958 * parse the r.h.s. anyway (to throw it away).
959 * If T is True, the result is the r.h.s., be it an Err or no.
977 *-----------------------------------------------------------------------
979 * Main expression production.
983 * True, False or Err.
986 * Tokens are, of course, consumed.
988 *-----------------------------------------------------------------------
991 CondE(Boolean doEval)
997 o = CondToken(doEval);
1003 * A similar thing occurs for ||, except that here we make sure
1004 * the l.h.s. is False before we bother to evaluate the r.h.s.
1005 * Once again, if l is False, the result is the r.h.s. and once
1006 * again if l is True, we parse the r.h.s. to throw it away.
1011 (void) CondE(FALSE);
1024 *-----------------------------------------------------------------------
1026 * Evaluate the conditional in the passed line. The line
1028 * #<cond-type> <expr>
1029 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1030 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1031 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1032 * and parenthetical groupings thereof.
1035 * COND_PARSE if should parse lines after the conditional
1036 * COND_SKIP if should skip lines after the conditional
1037 * COND_INVALID if not a valid conditional.
1042 *-----------------------------------------------------------------------
1045 Cond_Eval (char *line)
1049 Boolean value = FALSE;
1050 int level; /* Level at which to report errors. */
1053 level = PARSE_FATAL;
1054 lineno = curFile.lineno;
1056 for (line++; *line == ' ' || *line == '\t'; line++) {
1061 * Find what type of if we're dealing with. The result is left
1062 * in ifp and isElse is set TRUE if it's an elif line.
1064 if (line[0] == 'e' && line[1] == 'l') {
1067 } else if (strncmp (line, "endif", 5) == 0) {
1069 * End of a conditional section. If skipIfLevel is non-zero, that
1070 * conditional was skipped, so lines following it should also be
1071 * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1072 * was read so succeeding lines should be parsed (think about it...)
1073 * so we return COND_PARSE, unless this endif isn't paired with
1076 if (skipIfLevel != 0) {
1080 if (condTop == MAXIF) {
1081 Parse_Error (level, "if-less endif");
1082 return (COND_INVALID);
1086 return (COND_PARSE);
1094 * Figure out what sort of conditional it is -- what its default
1095 * function is, etc. -- by looking in the table of valid "ifs"
1097 for (ifp = ifs; ifp->form != (char *)0; ifp++) {
1098 if (strncmp (ifp->form, line, ifp->formlen) == 0) {
1103 if (ifp->form == (char *) 0) {
1105 * Nothing fit. If the first word on the line is actually
1106 * "else", it's a valid conditional whose value is the inverse
1107 * of the previous if we parsed.
1109 if (isElse && (line[0] == 's') && (line[1] == 'e')) {
1110 if (condTop == MAXIF) {
1111 Parse_Error (level, "if-less else");
1112 return (COND_INVALID);
1113 } else if (skipIfLevel == 0) {
1114 value = !condStack[condTop];
1115 lineno = condLineno[condTop];
1121 * Not a valid conditional type. No error...
1123 return (COND_INVALID);
1127 if (condTop == MAXIF) {
1128 Parse_Error (level, "if-less elif");
1129 return (COND_INVALID);
1130 } else if (skipIfLevel != 0) {
1132 * If skipping this conditional, just ignore the whole thing.
1133 * If we don't, the user might be employing a variable that's
1134 * undefined, for which there's an enclosing ifdef that
1137 skipIfLineno[skipIfLevel - 1] = lineno;
1140 } else if (skipLine) {
1142 * Don't even try to evaluate a conditional that's not an else if
1143 * we're skipping things...
1145 skipIfLineno[skipIfLevel] = lineno;
1151 * Initialize file-global variables for parsing
1153 condDefProc = ifp->defProc;
1154 condInvert = ifp->doNot;
1156 line += ifp->formlen;
1158 while (*line == ' ' || *line == '\t') {
1163 condPushBack = None;
1165 switch (CondE(TRUE)) {
1167 if (CondToken(TRUE) == EndOfFile) {
1174 if (CondToken(TRUE) == EndOfFile) {
1181 Parse_Error (level, "Malformed conditional (%s)",
1183 return (COND_INVALID);
1190 } else if ((skipIfLevel != 0) || condStack[condTop]) {
1192 * If this is an else-type conditional, it should only take effect
1193 * if its corresponding if was evaluated and FALSE. If its if was
1194 * TRUE or skipped, we return COND_SKIP (and start skipping in case
1195 * we weren't already), leaving the stack unmolested so later elif's
1204 * This is the one case where we can definitely proclaim a fatal
1205 * error. If we don't, we're hosed.
1207 Parse_Error (PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1208 return (COND_INVALID);
1210 condStack[condTop] = value;
1211 condLineno[condTop] = lineno;
1213 return (value ? COND_PARSE : COND_SKIP);
1218 *-----------------------------------------------------------------------
1220 * Make sure everything's clean at the end of a makefile.
1226 * Parse_Error will be called if open conditionals are around.
1228 *-----------------------------------------------------------------------
1235 if (condTop != MAXIF) {
1236 Parse_Error(PARSE_FATAL, "%d open conditional%s:",
1237 MAXIF - condTop + skipIfLevel,
1238 MAXIF - condTop + skipIfLevel== 1 ? "" : "s");
1240 for (level = skipIfLevel; level > 0; level--)
1241 Parse_Error(PARSE_FATAL, "\t%*sat line %d (skipped)",
1242 MAXIF - condTop + level + 1, "", skipIfLineno[level - 1]);
1243 for (level = condTop; level < MAXIF; level++)
1244 Parse_Error(PARSE_FATAL, "\t%*sat line %d "
1245 "(evaluated to %s)", MAXIF - level + skipIfLevel, "",
1246 condLineno[level], condStack[level] ? "true" : "false");