2 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
3 * Copyright (c) 1988, 1989 by Adam de Boor
4 * Copyright (c) 1989 by Berkeley Softworks
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * @(#)cond.c 8.2 (Berkeley) 1/2/94
39 * $FreeBSD: src/usr.bin/make/cond.c,v 1.12 1999/09/11 13:08:01 hoek Exp $
40 * $DragonFly: src/usr.bin/make/cond.c,v 1.3 2003/11/03 19:31:30 eirikn Exp $
45 * Functions to handle conditionals in a makefile.
48 * Cond_Eval Evaluate the conditional in the passed line.
60 * The parsing of conditional expressions is based on this grammar:
65 * T -> defined(variable)
71 * T -> $(varspec) op value
72 * T -> $(varspec) == "string"
73 * T -> $(varspec) != "string"
76 * op -> == | != | > | < | >= | <=
78 * 'symbol' is some other symbol to which the default function (condDefProc)
81 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
82 * will return And for '&' and '&&', Or for '|' and '||', Not for '!',
83 * LParen for '(', RParen for ')' and will evaluate the other terminal
84 * symbols, using either the default function or the function given in the
85 * terminal, and return the result as either True or False.
87 * All Non-Terminal functions (CondE, CondF and CondT) return Err on error.
90 And, Or, Not, True, False, LParen, RParen, EndOfFile, None, Err
94 * Structures to handle elegantly the different forms of #if's. The
95 * last two fields are stored in condInvert and condDefProc, respectively.
97 static void CondPushBack(Token);
98 static int CondGetArg(char **, char **, char *, Boolean);
99 static Boolean CondDoDefined(int, char *);
100 static int CondStrMatch(ClientData, ClientData);
101 static Boolean CondDoMake(int, char *);
102 static Boolean CondDoExists(int, char *);
103 static Boolean CondDoTarget(int, char *);
104 static char * CondCvtArg(char *, double *);
105 static Token CondToken(Boolean);
106 static Token CondT(Boolean);
107 static Token CondF(Boolean);
108 static Token CondE(Boolean);
111 char *form; /* Form of if */
112 int formlen; /* Length of form */
113 Boolean doNot; /* TRUE if default function should be negated */
114 Boolean (*defProc)(int, char *); /* Default function to apply */
116 { "ifdef", 5, FALSE, CondDoDefined },
117 { "ifndef", 6, TRUE, CondDoDefined },
118 { "ifmake", 6, FALSE, CondDoMake },
119 { "ifnmake", 7, TRUE, CondDoMake },
120 { "if", 2, FALSE, CondDoDefined },
121 { NULL, 0, FALSE, NULL }
124 static Boolean condInvert; /* Invert the default function */
125 static Boolean (*condDefProc) /* Default function to apply */
127 static char *condExpr; /* The expression to parse */
128 static Token condPushBack=None; /* Single push-back token used in
131 #define MAXIF 30 /* greatest depth of #if'ing */
133 static Boolean condStack[MAXIF]; /* Stack of conditionals's values */
134 static int condTop = MAXIF; /* Top-most conditional */
135 static int skipIfLevel=0; /* Depth of skipped conditionals */
136 static Boolean skipLine = FALSE; /* Whether the parse module is skipping
140 *-----------------------------------------------------------------------
142 * Push back the most recent token read. We only need one level of
143 * this, so the thing is just stored in 'condPushback'.
149 * condPushback is overwritten.
151 *-----------------------------------------------------------------------
155 Token t; /* Token to push back into the "stream" */
161 *-----------------------------------------------------------------------
163 * Find the argument of a built-in function.
166 * The length of the argument and the address of the argument.
169 * The pointer is set to point to the closing parenthesis of the
172 *-----------------------------------------------------------------------
175 CondGetArg (linePtr, argPtr, func, parens)
179 Boolean parens; /* TRUE if arg should be bounded by parens */
187 while (*cp != '(' && *cp != '\0') {
197 * No arguments whatsoever. Because 'make' and 'defined' aren't really
198 * "reserved words", we don't print a message. I think this is better
199 * than hitting the user with a warning message every time s/he uses
200 * the word 'make' or 'defined' at the beginning of a symbol...
206 while (*cp == ' ' || *cp == '\t') {
211 * Create a buffer for the argument and start it out at 16 characters
212 * long. Why 16? Why not?
216 while ((strchr(" \t)&|", *cp) == (char *)NULL) && (*cp != '\0')) {
219 * Parse the variable spec and install it as part of the argument
220 * if it's valid. We tell Var_Parse to complain on an undefined
221 * variable, so we don't do it too. Nor do we return an error,
222 * though perhaps we should...
228 cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &doFree);
230 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
236 Buf_AddByte(buf, (Byte)*cp);
241 Buf_AddByte(buf, (Byte)'\0');
242 *argPtr = (char *)Buf_GetAll(buf, &argLen);
243 Buf_Destroy(buf, FALSE);
245 while (*cp == ' ' || *cp == '\t') {
248 if (parens && *cp != ')') {
249 Parse_Error (PARSE_WARNING, "Missing closing parenthesis for %s()",
254 * Advance pointer past close parenthesis.
264 *-----------------------------------------------------------------------
266 * Handle the 'defined' function for conditionals.
269 * TRUE if the given variable is defined.
274 *-----------------------------------------------------------------------
277 CondDoDefined (argLen, arg)
281 char savec = arg[argLen];
286 if (Var_Value (arg, VAR_CMD, &p1) != (char *)NULL) {
297 *-----------------------------------------------------------------------
299 * Front-end for Str_Match so it returns 0 on match and non-zero
300 * on mismatch. Callback function for CondDoMake via Lst_Find
303 * 0 if string matches pattern
308 *-----------------------------------------------------------------------
311 CondStrMatch(string, pattern)
315 return(!Str_Match((char *) string,(char *) pattern));
319 *-----------------------------------------------------------------------
321 * Handle the 'make' function for conditionals.
324 * TRUE if the given target is being made.
329 *-----------------------------------------------------------------------
332 CondDoMake (argLen, arg)
336 char savec = arg[argLen];
340 if (Lst_Find (create, (ClientData)arg, CondStrMatch) == NILLNODE) {
350 *-----------------------------------------------------------------------
352 * See if the given file exists.
355 * TRUE if the file exists and FALSE if it does not.
360 *-----------------------------------------------------------------------
363 CondDoExists (argLen, arg)
367 char savec = arg[argLen];
372 path = Dir_FindFile(arg, dirSearchPath);
373 if (path != (char *)NULL) {
384 *-----------------------------------------------------------------------
386 * See if the given node exists and is an actual target.
389 * TRUE if the node exists as a target and FALSE if it does not.
394 *-----------------------------------------------------------------------
397 CondDoTarget (argLen, arg)
401 char savec = arg[argLen];
406 gn = Targ_FindNode(arg, TARG_NOCREATE);
407 if ((gn != NILGNODE) && !OP_NOP(gn->type)) {
418 *-----------------------------------------------------------------------
420 * Convert the given number into a double. If the number begins
421 * with 0x, it is interpreted as a hexadecimal integer
422 * and converted to a double from there. All other strings just have
423 * strtod called on them.
426 * Sets 'value' to double value of string.
427 * Returns address of the first character after the last valid
428 * character of the converted number.
431 * Can change 'value' even if string is not a valid number.
434 *-----------------------------------------------------------------------
437 CondCvtArg(str, 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 *-----------------------------------------------------------------------
483 if (condPushBack == None) {
484 while (*condExpr == ' ' || *condExpr == '\t') {
497 if (condExpr[1] == '|') {
504 if (condExpr[1] == '&') {
526 * Parse the variable spec and skip over it, saving its
530 lhs = Var_Parse(condExpr, VAR_CMD, doEval,&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, (int *)0);
656 Buf_Destroy(buf, FALSE);
659 printf("lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
663 * Null-terminate rhs and perform the comparison.
664 * t is set to the result.
667 t = strcmp(lhs, string) ? False : True;
669 t = strcmp(lhs, string) ? True : False;
672 if (rhs == condExpr) {
673 if (!qt && *cp == ')')
680 * rhs is either a float or an integer. Convert both the
681 * lhs and the rhs to a double and compare the two.
686 if (*CondCvtArg(lhs, &left) != '\0')
687 goto do_string_compare;
692 string = Var_Parse(rhs, VAR_CMD, doEval,&len,&freeIt);
693 if (string == var_Error) {
696 if (*CondCvtArg(string, &right) != '\0') {
699 goto do_string_compare;
707 char *c = CondCvtArg(rhs, &right);
708 if (*c != '\0' && !isspace(*c))
709 goto do_string_compare;
710 if (rhs == condExpr) {
712 * Skip over the right-hand side
714 while(!isspace((unsigned char) *condExpr) &&
715 (*condExpr != '\0')) {
722 printf("left = %f, right = %f, op = %.2s\n", left,
728 Parse_Error(PARSE_WARNING,
732 t = (left != right ? True : False);
736 Parse_Error(PARSE_WARNING,
740 t = (left == right ? True : False);
744 t = (left <= right ? True : False);
746 t = (left < right ? True : False);
751 t = (left >= right ? True : False);
753 t = (left > right ? True : False);
764 Boolean (*evalProc)(int, char *);
765 Boolean invert = FALSE;
769 if (strncmp (condExpr, "defined", 7) == 0) {
771 * Use CondDoDefined to evaluate the argument and
772 * CondGetArg to extract the argument from the 'function
775 evalProc = CondDoDefined;
777 arglen = CondGetArg (&condExpr, &arg, "defined", TRUE);
782 } else if (strncmp (condExpr, "make", 4) == 0) {
784 * Use CondDoMake to evaluate the argument and
785 * CondGetArg to extract the argument from the 'function
788 evalProc = CondDoMake;
790 arglen = CondGetArg (&condExpr, &arg, "make", TRUE);
795 } else if (strncmp (condExpr, "exists", 6) == 0) {
797 * Use CondDoExists to evaluate the argument and
798 * CondGetArg to extract the argument from the
801 evalProc = CondDoExists;
803 arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
808 } else if (strncmp(condExpr, "empty", 5) == 0) {
810 * Use Var_Parse to parse the spec in parens and return
811 * True if the resulting string is empty.
820 condExpr[arglen] != '(' && condExpr[arglen] != '\0';
824 if (condExpr[arglen] != '\0') {
825 val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
826 doEval, &length, &doFree);
827 if (val == var_Error) {
831 * A variable is empty when it just contains
832 * spaces... 4/15/92, christos
835 for (p = val; *p && isspace((unsigned char)*p); p++)
837 t = (*p == '\0') ? True : False;
843 * Advance condExpr to beyond the closing ). Note that
844 * we subtract one from arglen + length b/c length
845 * is calculated from condExpr[arglen - 1].
847 condExpr += arglen + length - 1;
853 } else if (strncmp (condExpr, "target", 6) == 0) {
855 * Use CondDoTarget to evaluate the argument and
856 * CondGetArg to extract the argument from the
859 evalProc = CondDoTarget;
861 arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
868 * The symbol is itself the argument to the default
869 * function. We advance condExpr to the end of the symbol
870 * by hand (the next whitespace, closing paren or
871 * binary operator) and set to invert the evaluation
872 * function if condInvert is TRUE.
876 evalProc = condDefProc;
877 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
881 * Evaluate the argument using the set function. If invert
882 * is TRUE, we invert the sense of the function.
884 t = (!doEval || (* evalProc) (arglen, arg) ?
885 (invert ? False : True) :
886 (invert ? True : False));
899 *-----------------------------------------------------------------------
901 * Parse a single term in the expression. This consists of a terminal
902 * symbol or Not and a terminal symbol (not including the binary
904 * T -> defined(variable) | make(target) | exists(file) | symbol
908 * True, False or Err.
911 * Tokens are consumed.
913 *-----------------------------------------------------------------------
921 t = CondToken(doEval);
923 if (t == EndOfFile) {
925 * If we reached the end of the expression, the expression
929 } else if (t == LParen) {
935 if (CondToken(doEval) != RParen) {
939 } else if (t == Not) {
943 } else if (t == False) {
951 *-----------------------------------------------------------------------
953 * Parse a conjunctive factor (nice name, wot?)
960 * Tokens are consumed.
962 *-----------------------------------------------------------------------
972 o = CondToken(doEval);
978 * If T is False, the whole thing will be False, but we have to
979 * parse the r.h.s. anyway (to throw it away).
980 * If T is True, the result is the r.h.s., be it an Err or no.
998 *-----------------------------------------------------------------------
1000 * Main expression production.
1004 * True, False or Err.
1007 * Tokens are, of course, consumed.
1009 *-----------------------------------------------------------------------
1019 o = CondToken(doEval);
1025 * A similar thing occurs for ||, except that here we make sure
1026 * the l.h.s. is False before we bother to evaluate the r.h.s.
1027 * Once again, if l is False, the result is the r.h.s. and once
1028 * again if l is True, we parse the r.h.s. to throw it away.
1033 (void) CondE(FALSE);
1046 *-----------------------------------------------------------------------
1048 * Evaluate the conditional in the passed line. The line
1050 * #<cond-type> <expr>
1051 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1052 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1053 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1054 * and parenthetical groupings thereof.
1057 * COND_PARSE if should parse lines after the conditional
1058 * COND_SKIP if should skip lines after the conditional
1059 * COND_INVALID if not a valid conditional.
1064 *-----------------------------------------------------------------------
1068 char *line; /* Line to parse */
1072 Boolean value = FALSE;
1073 int level; /* Level at which to report errors. */
1075 level = PARSE_FATAL;
1077 for (line++; *line == ' ' || *line == '\t'; line++) {
1082 * Find what type of if we're dealing with. The result is left
1083 * in ifp and isElse is set TRUE if it's an elif line.
1085 if (line[0] == 'e' && line[1] == 'l') {
1088 } else if (strncmp (line, "endif", 5) == 0) {
1090 * End of a conditional section. If skipIfLevel is non-zero, that
1091 * conditional was skipped, so lines following it should also be
1092 * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1093 * was read so succeeding lines should be parsed (think about it...)
1094 * so we return COND_PARSE, unless this endif isn't paired with
1097 if (skipIfLevel != 0) {
1101 if (condTop == MAXIF) {
1102 Parse_Error (level, "if-less endif");
1103 return (COND_INVALID);
1107 return (COND_PARSE);
1115 * Figure out what sort of conditional it is -- what its default
1116 * function is, etc. -- by looking in the table of valid "ifs"
1118 for (ifp = ifs; ifp->form != (char *)0; ifp++) {
1119 if (strncmp (ifp->form, line, ifp->formlen) == 0) {
1124 if (ifp->form == (char *) 0) {
1126 * Nothing fit. If the first word on the line is actually
1127 * "else", it's a valid conditional whose value is the inverse
1128 * of the previous if we parsed.
1130 if (isElse && (line[0] == 's') && (line[1] == 'e')) {
1131 if (condTop == MAXIF) {
1132 Parse_Error (level, "if-less else");
1133 return (COND_INVALID);
1134 } else if (skipIfLevel == 0) {
1135 value = !condStack[condTop];
1141 * Not a valid conditional type. No error...
1143 return (COND_INVALID);
1147 if (condTop == MAXIF) {
1148 Parse_Error (level, "if-less elif");
1149 return (COND_INVALID);
1150 } else if (skipIfLevel != 0) {
1152 * If skipping this conditional, just ignore the whole thing.
1153 * If we don't, the user might be employing a variable that's
1154 * undefined, for which there's an enclosing ifdef that
1159 } else if (skipLine) {
1161 * Don't even try to evaluate a conditional that's not an else if
1162 * we're skipping things...
1169 * Initialize file-global variables for parsing
1171 condDefProc = ifp->defProc;
1172 condInvert = ifp->doNot;
1174 line += ifp->formlen;
1176 while (*line == ' ' || *line == '\t') {
1181 condPushBack = None;
1183 switch (CondE(TRUE)) {
1185 if (CondToken(TRUE) == EndOfFile) {
1192 if (CondToken(TRUE) == EndOfFile) {
1199 Parse_Error (level, "Malformed conditional (%s)",
1201 return (COND_INVALID);
1208 } else if ((skipIfLevel != 0) || condStack[condTop]) {
1210 * If this is an else-type conditional, it should only take effect
1211 * if its corresponding if was evaluated and FALSE. If its if was
1212 * TRUE or skipped, we return COND_SKIP (and start skipping in case
1213 * we weren't already), leaving the stack unmolested so later elif's
1222 * This is the one case where we can definitely proclaim a fatal
1223 * error. If we don't, we're hosed.
1225 Parse_Error (PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1226 return (COND_INVALID);
1228 condStack[condTop] = value;
1230 return (value ? COND_PARSE : COND_SKIP);
1235 *-----------------------------------------------------------------------
1237 * Make sure everything's clean at the end of a makefile.
1243 * Parse_Error will be called if open conditionals are around.
1245 *-----------------------------------------------------------------------
1250 if (condTop != MAXIF) {
1251 Parse_Error(PARSE_FATAL, "%d open conditional%s", MAXIF-condTop,
1252 MAXIF-condTop == 1 ? "" : "s");