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
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
47 * Functions to handle conditionals in a makefile.
50 * Cond_Eval Evaluate the conditional in the passed line.
62 * The parsing of conditional expressions is based on this grammar:
67 * T -> defined(variable)
73 * T -> $(varspec) op value
74 * T -> $(varspec) == "string"
75 * T -> $(varspec) != "string"
78 * op -> == | != | > | < | >= | <=
80 * 'symbol' is some other symbol to which the default function (condDefProc)
83 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
84 * will return And for '&' and '&&', Or for '|' and '||', Not for '!',
85 * LParen for '(', RParen for ')' and will evaluate the other terminal
86 * symbols, using either the default function or the function given in the
87 * terminal, and return the result as either True or False.
89 * All Non-Terminal functions (CondE, CondF and CondT) return Err on error.
92 And, Or, Not, True, False, LParen, RParen, EndOfFile, None, Err
96 * Structures to handle elegantly the different forms of #if's. The
97 * last two fields are stored in condInvert and condDefProc, respectively.
99 static void CondPushBack(Token);
100 static int CondGetArg(char **, char **, char *, Boolean);
101 static Boolean CondDoDefined(int, char *);
102 static int CondStrMatch(void *, void *);
103 static Boolean CondDoMake(int, char *);
104 static Boolean CondDoExists(int, char *);
105 static Boolean CondDoTarget(int, char *);
106 static char * CondCvtArg(char *, double *);
107 static Token CondToken(Boolean);
108 static Token CondT(Boolean);
109 static Token CondF(Boolean);
110 static Token CondE(Boolean);
113 char *form; /* Form of if */
114 int formlen; /* Length of form */
115 Boolean doNot; /* TRUE if default function should be negated */
116 Boolean (*defProc)(int, char *); /* Default function to apply */
118 { "ifdef", 5, FALSE, CondDoDefined },
119 { "ifndef", 6, TRUE, CondDoDefined },
120 { "ifmake", 6, FALSE, CondDoMake },
121 { "ifnmake", 7, TRUE, CondDoMake },
122 { "if", 2, FALSE, CondDoDefined },
123 { NULL, 0, FALSE, NULL }
126 static Boolean condInvert; /* Invert the default function */
127 static Boolean (*condDefProc) /* Default function to apply */
129 static char *condExpr; /* The expression to parse */
130 static Token condPushBack=None; /* Single push-back token used in
133 #define MAXIF 30 /* greatest depth of #if'ing */
135 static Boolean condStack[MAXIF]; /* Stack of conditionals's values */
136 static int condTop = MAXIF; /* Top-most conditional */
137 static int skipIfLevel=0; /* Depth of skipped conditionals */
138 static Boolean skipLine = FALSE; /* Whether the parse module is skipping
142 *-----------------------------------------------------------------------
144 * Push back the most recent token read. We only need one level of
145 * this, so the thing is just stored in 'condPushback'.
151 * condPushback is overwritten.
153 *-----------------------------------------------------------------------
157 Token t; /* Token to push back into the "stream" */
163 *-----------------------------------------------------------------------
165 * Find the argument of a built-in function.
168 * The length of the argument and the address of the argument.
171 * The pointer is set to point to the closing parenthesis of the
174 *-----------------------------------------------------------------------
177 CondGetArg (linePtr, argPtr, func, parens)
181 Boolean parens; /* TRUE if arg should be bounded by parens */
189 while (*cp != '(' && *cp != '\0') {
199 * No arguments whatsoever. Because 'make' and 'defined' aren't really
200 * "reserved words", we don't print a message. I think this is better
201 * than hitting the user with a warning message every time s/he uses
202 * the word 'make' or 'defined' at the beginning of a symbol...
208 while (*cp == ' ' || *cp == '\t') {
213 * Create a buffer for the argument and start it out at 16 characters
214 * long. Why 16? Why not?
218 while ((strchr(" \t)&|", *cp) == (char *)NULL) && (*cp != '\0')) {
221 * Parse the variable spec and install it as part of the argument
222 * if it's valid. We tell Var_Parse to complain on an undefined
223 * variable, so we don't do it too. Nor do we return an error,
224 * though perhaps we should...
230 cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &doFree);
232 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
238 Buf_AddByte(buf, (Byte)*cp);
243 Buf_AddByte(buf, (Byte)'\0');
244 *argPtr = (char *)Buf_GetAll(buf, &argLen);
245 Buf_Destroy(buf, FALSE);
247 while (*cp == ' ' || *cp == '\t') {
250 if (parens && *cp != ')') {
251 Parse_Error (PARSE_WARNING, "Missing closing parenthesis for %s()",
256 * Advance pointer past close parenthesis.
266 *-----------------------------------------------------------------------
268 * Handle the 'defined' function for conditionals.
271 * TRUE if the given variable is defined.
276 *-----------------------------------------------------------------------
279 CondDoDefined (argLen, arg)
283 char savec = arg[argLen];
288 if (Var_Value (arg, VAR_CMD, &p1) != (char *)NULL) {
299 *-----------------------------------------------------------------------
301 * Front-end for Str_Match so it returns 0 on match and non-zero
302 * on mismatch. Callback function for CondDoMake via Lst_Find
305 * 0 if string matches pattern
310 *-----------------------------------------------------------------------
313 CondStrMatch(string, pattern)
317 return(!Str_Match((char *) string,(char *) pattern));
321 *-----------------------------------------------------------------------
323 * Handle the 'make' function for conditionals.
326 * TRUE if the given target is being made.
331 *-----------------------------------------------------------------------
334 CondDoMake (argLen, arg)
338 char savec = arg[argLen];
342 if (Lst_Find (create, (void *)arg, CondStrMatch) == NULL) {
352 *-----------------------------------------------------------------------
354 * See if the given file exists.
357 * TRUE if the file exists and FALSE if it does not.
362 *-----------------------------------------------------------------------
365 CondDoExists (argLen, arg)
369 char savec = arg[argLen];
374 path = Dir_FindFile(arg, dirSearchPath);
375 if (path != (char *)NULL) {
386 *-----------------------------------------------------------------------
388 * See if the given node exists and is an actual target.
391 * TRUE if the node exists as a target and FALSE if it does not.
396 *-----------------------------------------------------------------------
399 CondDoTarget (argLen, arg)
403 char savec = arg[argLen];
408 gn = Targ_FindNode(arg, TARG_NOCREATE);
409 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(str, value)
443 if ((*str == '0') && (str[1] == 'x')) {
446 for (str += 2, i = 0; ; str++) {
448 if (isdigit((unsigned char) *str))
450 else if (isxdigit((unsigned char) *str))
451 x = 10 + *str - isupper((unsigned char) *str) ? 'A' : 'a';
461 *value = strtod(str, &eptr);
467 *-----------------------------------------------------------------------
469 * Return the next token from the input.
472 * A Token for the next lexical token in the stream.
475 * condPushback will be set back to None if it is used.
477 *-----------------------------------------------------------------------
485 if (condPushBack == None) {
486 while (*condExpr == ' ' || *condExpr == '\t') {
499 if (condExpr[1] == '|') {
506 if (condExpr[1] == '&') {
528 * Parse the variable spec and skip over it, saving its
532 lhs = Var_Parse(condExpr, VAR_CMD, doEval,&varSpecLen,&doFree);
533 if (lhs == var_Error) {
535 * Even if !doEval, we still report syntax errors, which
536 * is what getting var_Error back with !doEval means.
540 condExpr += varSpecLen;
542 if (!isspace((unsigned char) *condExpr) &&
543 strchr("!=><", *condExpr) == NULL) {
549 for (cp = lhs; *cp; cp++)
550 Buf_AddByte(buf, (Byte)*cp);
555 for (;*condExpr && !isspace((unsigned char) *condExpr);
557 Buf_AddByte(buf, (Byte)*condExpr);
559 Buf_AddByte(buf, (Byte)'\0');
560 lhs = (char *)Buf_GetAll(buf, &varSpecLen);
561 Buf_Destroy(buf, FALSE);
567 * Skip whitespace to get to the operator
569 while (isspace((unsigned char) *condExpr))
573 * Make sure the operator is a valid one. If it isn't a
574 * known relational operator, pretend we got a
583 if (condExpr[1] == '=') {
595 while (isspace((unsigned char) *condExpr)) {
598 if (*condExpr == '\0') {
599 Parse_Error(PARSE_WARNING,
600 "Missing right-hand-side of operator");
607 * Doing a string comparison. Only allow == and != for
616 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
617 Parse_Error(PARSE_WARNING,
618 "String comparison operator should be either == or !=");
623 qt = *rhs == '"' ? 1 : 0;
626 ((qt && (*cp != '"')) ||
627 (!qt && strchr(" \t)", *cp) == NULL)) &&
628 (*cp != '\0'); cp++) {
629 if ((*cp == '\\') && (cp[1] != '\0')) {
631 * Backslash escapes things -- skip over next
632 * character, if it exists.
635 Buf_AddByte(buf, (Byte)*cp);
636 } else if (*cp == '$') {
640 cp2 = Var_Parse(cp, VAR_CMD, doEval,&len, &freeIt);
641 if (cp2 != var_Error) {
642 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
648 Buf_AddByte(buf, (Byte)*cp);
651 Buf_AddByte(buf, (Byte)*cp);
655 Buf_AddByte(buf, (Byte)0);
657 string = (char *)Buf_GetAll(buf, (int *)0);
658 Buf_Destroy(buf, FALSE);
661 printf("lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
665 * Null-terminate rhs and perform the comparison.
666 * t is set to the result.
669 t = strcmp(lhs, string) ? False : True;
671 t = strcmp(lhs, string) ? True : False;
674 if (rhs == condExpr) {
675 if (!qt && *cp == ')')
682 * rhs is either a float or an integer. Convert both the
683 * lhs and the rhs to a double and compare the two.
688 if (*CondCvtArg(lhs, &left) != '\0')
689 goto do_string_compare;
694 string = Var_Parse(rhs, VAR_CMD, doEval,&len,&freeIt);
695 if (string == var_Error) {
698 if (*CondCvtArg(string, &right) != '\0') {
701 goto do_string_compare;
709 char *c = CondCvtArg(rhs, &right);
710 if (*c != '\0' && !isspace(*c))
711 goto do_string_compare;
712 if (rhs == condExpr) {
714 * Skip over the right-hand side
716 while(!isspace((unsigned char) *condExpr) &&
717 (*condExpr != '\0')) {
724 printf("left = %f, right = %f, op = %.2s\n", left,
730 Parse_Error(PARSE_WARNING,
734 t = (left != right ? True : False);
738 Parse_Error(PARSE_WARNING,
742 t = (left == right ? True : False);
746 t = (left <= right ? True : False);
748 t = (left < right ? True : False);
753 t = (left >= right ? True : False);
755 t = (left > right ? True : False);
766 Boolean (*evalProc)(int, char *);
767 Boolean invert = FALSE;
771 if (strncmp (condExpr, "defined", 7) == 0) {
773 * Use CondDoDefined to evaluate the argument and
774 * CondGetArg to extract the argument from the 'function
777 evalProc = CondDoDefined;
779 arglen = CondGetArg (&condExpr, &arg, "defined", TRUE);
784 } else if (strncmp (condExpr, "make", 4) == 0) {
786 * Use CondDoMake to evaluate the argument and
787 * CondGetArg to extract the argument from the 'function
790 evalProc = CondDoMake;
792 arglen = CondGetArg (&condExpr, &arg, "make", TRUE);
797 } else if (strncmp (condExpr, "exists", 6) == 0) {
799 * Use CondDoExists to evaluate the argument and
800 * CondGetArg to extract the argument from the
803 evalProc = CondDoExists;
805 arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
810 } else if (strncmp(condExpr, "empty", 5) == 0) {
812 * Use Var_Parse to parse the spec in parens and return
813 * True if the resulting string is empty.
822 condExpr[arglen] != '(' && condExpr[arglen] != '\0';
826 if (condExpr[arglen] != '\0') {
827 val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
828 doEval, &length, &doFree);
829 if (val == var_Error) {
833 * A variable is empty when it just contains
834 * spaces... 4/15/92, christos
837 for (p = val; *p && isspace((unsigned char)*p); p++)
839 t = (*p == '\0') ? True : False;
845 * Advance condExpr to beyond the closing ). Note that
846 * we subtract one from arglen + length b/c length
847 * is calculated from condExpr[arglen - 1].
849 condExpr += arglen + length - 1;
855 } else if (strncmp (condExpr, "target", 6) == 0) {
857 * Use CondDoTarget to evaluate the argument and
858 * CondGetArg to extract the argument from the
861 evalProc = CondDoTarget;
863 arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
870 * The symbol is itself the argument to the default
871 * function. We advance condExpr to the end of the symbol
872 * by hand (the next whitespace, closing paren or
873 * binary operator) and set to invert the evaluation
874 * function if condInvert is TRUE.
878 evalProc = condDefProc;
879 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
883 * Evaluate the argument using the set function. If invert
884 * is TRUE, we invert the sense of the function.
886 t = (!doEval || (* evalProc) (arglen, arg) ?
887 (invert ? False : True) :
888 (invert ? True : False));
901 *-----------------------------------------------------------------------
903 * Parse a single term in the expression. This consists of a terminal
904 * symbol or Not and a terminal symbol (not including the binary
906 * T -> defined(variable) | make(target) | exists(file) | symbol
910 * True, False or Err.
913 * Tokens are consumed.
915 *-----------------------------------------------------------------------
923 t = CondToken(doEval);
925 if (t == EndOfFile) {
927 * If we reached the end of the expression, the expression
931 } else if (t == LParen) {
937 if (CondToken(doEval) != RParen) {
941 } else if (t == Not) {
945 } else if (t == False) {
953 *-----------------------------------------------------------------------
955 * Parse a conjunctive factor (nice name, wot?)
962 * Tokens are consumed.
964 *-----------------------------------------------------------------------
974 o = CondToken(doEval);
980 * If T is False, the whole thing will be False, but we have to
981 * parse the r.h.s. anyway (to throw it away).
982 * If T is True, the result is the r.h.s., be it an Err or no.
1000 *-----------------------------------------------------------------------
1002 * Main expression production.
1006 * True, False or Err.
1009 * Tokens are, of course, consumed.
1011 *-----------------------------------------------------------------------
1021 o = CondToken(doEval);
1027 * A similar thing occurs for ||, except that here we make sure
1028 * the l.h.s. is False before we bother to evaluate the r.h.s.
1029 * Once again, if l is False, the result is the r.h.s. and once
1030 * again if l is True, we parse the r.h.s. to throw it away.
1035 (void) CondE(FALSE);
1048 *-----------------------------------------------------------------------
1050 * Evaluate the conditional in the passed line. The line
1052 * #<cond-type> <expr>
1053 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1054 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1055 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1056 * and parenthetical groupings thereof.
1059 * COND_PARSE if should parse lines after the conditional
1060 * COND_SKIP if should skip lines after the conditional
1061 * COND_INVALID if not a valid conditional.
1066 *-----------------------------------------------------------------------
1070 char *line; /* Line to parse */
1074 Boolean value = FALSE;
1075 int level; /* Level at which to report errors. */
1077 level = PARSE_FATAL;
1079 for (line++; *line == ' ' || *line == '\t'; line++) {
1084 * Find what type of if we're dealing with. The result is left
1085 * in ifp and isElse is set TRUE if it's an elif line.
1087 if (line[0] == 'e' && line[1] == 'l') {
1090 } else if (strncmp (line, "endif", 5) == 0) {
1092 * End of a conditional section. If skipIfLevel is non-zero, that
1093 * conditional was skipped, so lines following it should also be
1094 * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1095 * was read so succeeding lines should be parsed (think about it...)
1096 * so we return COND_PARSE, unless this endif isn't paired with
1099 if (skipIfLevel != 0) {
1103 if (condTop == MAXIF) {
1104 Parse_Error (level, "if-less endif");
1105 return (COND_INVALID);
1109 return (COND_PARSE);
1117 * Figure out what sort of conditional it is -- what its default
1118 * function is, etc. -- by looking in the table of valid "ifs"
1120 for (ifp = ifs; ifp->form != (char *)0; ifp++) {
1121 if (strncmp (ifp->form, line, ifp->formlen) == 0) {
1126 if (ifp->form == (char *) 0) {
1128 * Nothing fit. If the first word on the line is actually
1129 * "else", it's a valid conditional whose value is the inverse
1130 * of the previous if we parsed.
1132 if (isElse && (line[0] == 's') && (line[1] == 'e')) {
1133 if (condTop == MAXIF) {
1134 Parse_Error (level, "if-less else");
1135 return (COND_INVALID);
1136 } else if (skipIfLevel == 0) {
1137 value = !condStack[condTop];
1143 * Not a valid conditional type. No error...
1145 return (COND_INVALID);
1149 if (condTop == MAXIF) {
1150 Parse_Error (level, "if-less elif");
1151 return (COND_INVALID);
1152 } else if (skipIfLevel != 0) {
1154 * If skipping this conditional, just ignore the whole thing.
1155 * If we don't, the user might be employing a variable that's
1156 * undefined, for which there's an enclosing ifdef that
1161 } else if (skipLine) {
1163 * Don't even try to evaluate a conditional that's not an else if
1164 * we're skipping things...
1171 * Initialize file-global variables for parsing
1173 condDefProc = ifp->defProc;
1174 condInvert = ifp->doNot;
1176 line += ifp->formlen;
1178 while (*line == ' ' || *line == '\t') {
1183 condPushBack = None;
1185 switch (CondE(TRUE)) {
1187 if (CondToken(TRUE) == EndOfFile) {
1194 if (CondToken(TRUE) == EndOfFile) {
1201 Parse_Error (level, "Malformed conditional (%s)",
1203 return (COND_INVALID);
1210 } else if ((skipIfLevel != 0) || condStack[condTop]) {
1212 * If this is an else-type conditional, it should only take effect
1213 * if its corresponding if was evaluated and FALSE. If its if was
1214 * TRUE or skipped, we return COND_SKIP (and start skipping in case
1215 * we weren't already), leaving the stack unmolested so later elif's
1224 * This is the one case where we can definitely proclaim a fatal
1225 * error. If we don't, we're hosed.
1227 Parse_Error (PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1228 return (COND_INVALID);
1230 condStack[condTop] = value;
1232 return (value ? COND_PARSE : COND_SKIP);
1237 *-----------------------------------------------------------------------
1239 * Make sure everything's clean at the end of a makefile.
1245 * Parse_Error will be called if open conditionals are around.
1247 *-----------------------------------------------------------------------
1252 if (condTop != MAXIF) {
1253 Parse_Error(PARSE_FATAL, "%d open conditional%s", MAXIF-condTop,
1254 MAXIF-condTop == 1 ? "" : "s");