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
41 static char sccsid[] = "@(#)cond.c 8.2 (Berkeley) 1/2/94";
43 static const char rcsid[] =
44 "$FreeBSD: src/usr.bin/make/cond.c,v 1.12 1999/09/11 13:08:01 hoek Exp $";
50 * Functions to handle conditionals in a makefile.
53 * Cond_Eval Evaluate the conditional in the passed line.
65 * The parsing of conditional expressions is based on this grammar:
70 * T -> defined(variable)
76 * T -> $(varspec) op value
77 * T -> $(varspec) == "string"
78 * T -> $(varspec) != "string"
81 * op -> == | != | > | < | >= | <=
83 * 'symbol' is some other symbol to which the default function (condDefProc)
86 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
87 * will return And for '&' and '&&', Or for '|' and '||', Not for '!',
88 * LParen for '(', RParen for ')' and will evaluate the other terminal
89 * symbols, using either the default function or the function given in the
90 * terminal, and return the result as either True or False.
92 * All Non-Terminal functions (CondE, CondF and CondT) return Err on error.
95 And, Or, Not, True, False, LParen, RParen, EndOfFile, None, Err
99 * Structures to handle elegantly the different forms of #if's. The
100 * last two fields are stored in condInvert and condDefProc, respectively.
102 static void CondPushBack __P((Token));
103 static int CondGetArg __P((char **, char **, char *, Boolean));
104 static Boolean CondDoDefined __P((int, char *));
105 static int CondStrMatch __P((ClientData, ClientData));
106 static Boolean CondDoMake __P((int, char *));
107 static Boolean CondDoExists __P((int, char *));
108 static Boolean CondDoTarget __P((int, char *));
109 static char * CondCvtArg __P((char *, double *));
110 static Token CondToken __P((Boolean));
111 static Token CondT __P((Boolean));
112 static Token CondF __P((Boolean));
113 static Token CondE __P((Boolean));
116 char *form; /* Form of if */
117 int formlen; /* Length of form */
118 Boolean doNot; /* TRUE if default function should be negated */
119 Boolean (*defProc) __P((int, char *)); /* Default function to apply */
121 { "ifdef", 5, FALSE, CondDoDefined },
122 { "ifndef", 6, TRUE, CondDoDefined },
123 { "ifmake", 6, FALSE, CondDoMake },
124 { "ifnmake", 7, TRUE, CondDoMake },
125 { "if", 2, FALSE, CondDoDefined },
126 { NULL, 0, FALSE, NULL }
129 static Boolean condInvert; /* Invert the default function */
130 static Boolean (*condDefProc) /* Default function to apply */
132 static char *condExpr; /* The expression to parse */
133 static Token condPushBack=None; /* Single push-back token used in
136 #define MAXIF 30 /* greatest depth of #if'ing */
138 static Boolean condStack[MAXIF]; /* Stack of conditionals's values */
139 static int condTop = MAXIF; /* Top-most conditional */
140 static int skipIfLevel=0; /* Depth of skipped conditionals */
141 static Boolean skipLine = FALSE; /* Whether the parse module is skipping
145 *-----------------------------------------------------------------------
147 * Push back the most recent token read. We only need one level of
148 * this, so the thing is just stored in 'condPushback'.
154 * condPushback is overwritten.
156 *-----------------------------------------------------------------------
160 Token t; /* Token to push back into the "stream" */
166 *-----------------------------------------------------------------------
168 * Find the argument of a built-in function.
171 * The length of the argument and the address of the argument.
174 * The pointer is set to point to the closing parenthesis of the
177 *-----------------------------------------------------------------------
180 CondGetArg (linePtr, argPtr, func, parens)
184 Boolean parens; /* TRUE if arg should be bounded by parens */
192 while (*cp != '(' && *cp != '\0') {
202 * No arguments whatsoever. Because 'make' and 'defined' aren't really
203 * "reserved words", we don't print a message. I think this is better
204 * than hitting the user with a warning message every time s/he uses
205 * the word 'make' or 'defined' at the beginning of a symbol...
211 while (*cp == ' ' || *cp == '\t') {
216 * Create a buffer for the argument and start it out at 16 characters
217 * long. Why 16? Why not?
221 while ((strchr(" \t)&|", *cp) == (char *)NULL) && (*cp != '\0')) {
224 * Parse the variable spec and install it as part of the argument
225 * if it's valid. We tell Var_Parse to complain on an undefined
226 * variable, so we don't do it too. Nor do we return an error,
227 * though perhaps we should...
233 cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &doFree);
235 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
241 Buf_AddByte(buf, (Byte)*cp);
246 Buf_AddByte(buf, (Byte)'\0');
247 *argPtr = (char *)Buf_GetAll(buf, &argLen);
248 Buf_Destroy(buf, FALSE);
250 while (*cp == ' ' || *cp == '\t') {
253 if (parens && *cp != ')') {
254 Parse_Error (PARSE_WARNING, "Missing closing parenthesis for %s()",
259 * Advance pointer past close parenthesis.
269 *-----------------------------------------------------------------------
271 * Handle the 'defined' function for conditionals.
274 * TRUE if the given variable is defined.
279 *-----------------------------------------------------------------------
282 CondDoDefined (argLen, arg)
286 char savec = arg[argLen];
291 if (Var_Value (arg, VAR_CMD, &p1) != (char *)NULL) {
302 *-----------------------------------------------------------------------
304 * Front-end for Str_Match so it returns 0 on match and non-zero
305 * on mismatch. Callback function for CondDoMake via Lst_Find
308 * 0 if string matches pattern
313 *-----------------------------------------------------------------------
316 CondStrMatch(string, pattern)
320 return(!Str_Match((char *) string,(char *) pattern));
324 *-----------------------------------------------------------------------
326 * Handle the 'make' function for conditionals.
329 * TRUE if the given target is being made.
334 *-----------------------------------------------------------------------
337 CondDoMake (argLen, arg)
341 char savec = arg[argLen];
345 if (Lst_Find (create, (ClientData)arg, CondStrMatch) == NILLNODE) {
355 *-----------------------------------------------------------------------
357 * See if the given file exists.
360 * TRUE if the file exists and FALSE if it does not.
365 *-----------------------------------------------------------------------
368 CondDoExists (argLen, arg)
372 char savec = arg[argLen];
377 path = Dir_FindFile(arg, dirSearchPath);
378 if (path != (char *)NULL) {
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 (argLen, arg)
406 char savec = arg[argLen];
411 gn = Targ_FindNode(arg, TARG_NOCREATE);
412 if ((gn != NILGNODE) && !OP_NOP(gn->type)) {
423 *-----------------------------------------------------------------------
425 * Convert the given number into a double. If the number begins
426 * with 0x, it is interpreted as a hexadecimal integer
427 * and converted to a double from there. All other strings just have
428 * strtod called on them.
431 * Sets 'value' to double value of string.
432 * Returns address of the first character after the last valid
433 * character of the converted number.
436 * Can change 'value' even if string is not a valid number.
439 *-----------------------------------------------------------------------
442 CondCvtArg(str, value)
446 if ((*str == '0') && (str[1] == 'x')) {
449 for (str += 2, i = 0; ; str++) {
451 if (isdigit((unsigned char) *str))
453 else if (isxdigit((unsigned char) *str))
454 x = 10 + *str - isupper((unsigned char) *str) ? 'A' : 'a';
464 *value = strtod(str, &eptr);
470 *-----------------------------------------------------------------------
472 * Return the next token from the input.
475 * A Token for the next lexical token in the stream.
478 * condPushback will be set back to None if it is used.
480 *-----------------------------------------------------------------------
488 if (condPushBack == None) {
489 while (*condExpr == ' ' || *condExpr == '\t') {
502 if (condExpr[1] == '|') {
509 if (condExpr[1] == '&') {
531 * Parse the variable spec and skip over it, saving its
535 lhs = Var_Parse(condExpr, VAR_CMD, doEval,&varSpecLen,&doFree);
536 if (lhs == var_Error) {
538 * Even if !doEval, we still report syntax errors, which
539 * is what getting var_Error back with !doEval means.
543 condExpr += varSpecLen;
545 if (!isspace((unsigned char) *condExpr) &&
546 strchr("!=><", *condExpr) == NULL) {
552 for (cp = lhs; *cp; cp++)
553 Buf_AddByte(buf, (Byte)*cp);
558 for (;*condExpr && !isspace((unsigned char) *condExpr);
560 Buf_AddByte(buf, (Byte)*condExpr);
562 Buf_AddByte(buf, (Byte)'\0');
563 lhs = (char *)Buf_GetAll(buf, &varSpecLen);
564 Buf_Destroy(buf, FALSE);
570 * Skip whitespace to get to the operator
572 while (isspace((unsigned char) *condExpr))
576 * Make sure the operator is a valid one. If it isn't a
577 * known relational operator, pretend we got a
586 if (condExpr[1] == '=') {
598 while (isspace((unsigned char) *condExpr)) {
601 if (*condExpr == '\0') {
602 Parse_Error(PARSE_WARNING,
603 "Missing right-hand-side of operator");
610 * Doing a string comparison. Only allow == and != for
619 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
620 Parse_Error(PARSE_WARNING,
621 "String comparison operator should be either == or !=");
626 qt = *rhs == '"' ? 1 : 0;
629 ((qt && (*cp != '"')) ||
630 (!qt && strchr(" \t)", *cp) == NULL)) &&
631 (*cp != '\0'); cp++) {
632 if ((*cp == '\\') && (cp[1] != '\0')) {
634 * Backslash escapes things -- skip over next
635 * character, if it exists.
638 Buf_AddByte(buf, (Byte)*cp);
639 } else if (*cp == '$') {
643 cp2 = Var_Parse(cp, VAR_CMD, doEval,&len, &freeIt);
644 if (cp2 != var_Error) {
645 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
651 Buf_AddByte(buf, (Byte)*cp);
654 Buf_AddByte(buf, (Byte)*cp);
658 Buf_AddByte(buf, (Byte)0);
660 string = (char *)Buf_GetAll(buf, (int *)0);
661 Buf_Destroy(buf, FALSE);
664 printf("lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
668 * Null-terminate rhs and perform the comparison.
669 * t is set to the result.
672 t = strcmp(lhs, string) ? False : True;
674 t = strcmp(lhs, string) ? True : False;
677 if (rhs == condExpr) {
678 if (!qt && *cp == ')')
685 * rhs is either a float or an integer. Convert both the
686 * lhs and the rhs to a double and compare the two.
691 if (*CondCvtArg(lhs, &left) != '\0')
692 goto do_string_compare;
697 string = Var_Parse(rhs, VAR_CMD, doEval,&len,&freeIt);
698 if (string == var_Error) {
701 if (*CondCvtArg(string, &right) != '\0') {
704 goto do_string_compare;
712 char *c = CondCvtArg(rhs, &right);
713 if (*c != '\0' && !isspace(*c))
714 goto do_string_compare;
715 if (rhs == condExpr) {
717 * Skip over the right-hand side
719 while(!isspace((unsigned char) *condExpr) &&
720 (*condExpr != '\0')) {
727 printf("left = %f, right = %f, op = %.2s\n", left,
733 Parse_Error(PARSE_WARNING,
737 t = (left != right ? True : False);
741 Parse_Error(PARSE_WARNING,
745 t = (left == right ? True : False);
749 t = (left <= right ? True : False);
751 t = (left < right ? True : False);
756 t = (left >= right ? True : False);
758 t = (left > right ? True : False);
769 Boolean (*evalProc) __P((int, char *));
770 Boolean invert = FALSE;
774 if (strncmp (condExpr, "defined", 7) == 0) {
776 * Use CondDoDefined to evaluate the argument and
777 * CondGetArg to extract the argument from the 'function
780 evalProc = CondDoDefined;
782 arglen = CondGetArg (&condExpr, &arg, "defined", TRUE);
787 } else if (strncmp (condExpr, "make", 4) == 0) {
789 * Use CondDoMake to evaluate the argument and
790 * CondGetArg to extract the argument from the 'function
793 evalProc = CondDoMake;
795 arglen = CondGetArg (&condExpr, &arg, "make", TRUE);
800 } else if (strncmp (condExpr, "exists", 6) == 0) {
802 * Use CondDoExists to evaluate the argument and
803 * CondGetArg to extract the argument from the
806 evalProc = CondDoExists;
808 arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
813 } else if (strncmp(condExpr, "empty", 5) == 0) {
815 * Use Var_Parse to parse the spec in parens and return
816 * True if the resulting string is empty.
825 condExpr[arglen] != '(' && condExpr[arglen] != '\0';
829 if (condExpr[arglen] != '\0') {
830 val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
831 doEval, &length, &doFree);
832 if (val == var_Error) {
836 * A variable is empty when it just contains
837 * spaces... 4/15/92, christos
840 for (p = val; *p && isspace((unsigned char)*p); p++)
842 t = (*p == '\0') ? True : False;
848 * Advance condExpr to beyond the closing ). Note that
849 * we subtract one from arglen + length b/c length
850 * is calculated from condExpr[arglen - 1].
852 condExpr += arglen + length - 1;
858 } else if (strncmp (condExpr, "target", 6) == 0) {
860 * Use CondDoTarget to evaluate the argument and
861 * CondGetArg to extract the argument from the
864 evalProc = CondDoTarget;
866 arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
873 * The symbol is itself the argument to the default
874 * function. We advance condExpr to the end of the symbol
875 * by hand (the next whitespace, closing paren or
876 * binary operator) and set to invert the evaluation
877 * function if condInvert is TRUE.
881 evalProc = condDefProc;
882 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
886 * Evaluate the argument using the set function. If invert
887 * is TRUE, we invert the sense of the function.
889 t = (!doEval || (* evalProc) (arglen, arg) ?
890 (invert ? False : True) :
891 (invert ? True : False));
904 *-----------------------------------------------------------------------
906 * Parse a single term in the expression. This consists of a terminal
907 * symbol or Not and a terminal symbol (not including the binary
909 * T -> defined(variable) | make(target) | exists(file) | symbol
913 * True, False or Err.
916 * Tokens are consumed.
918 *-----------------------------------------------------------------------
926 t = CondToken(doEval);
928 if (t == EndOfFile) {
930 * If we reached the end of the expression, the expression
934 } else if (t == LParen) {
940 if (CondToken(doEval) != RParen) {
944 } else if (t == Not) {
948 } else if (t == False) {
956 *-----------------------------------------------------------------------
958 * Parse a conjunctive factor (nice name, wot?)
965 * Tokens are consumed.
967 *-----------------------------------------------------------------------
977 o = CondToken(doEval);
983 * If T is False, the whole thing will be False, but we have to
984 * parse the r.h.s. anyway (to throw it away).
985 * If T is True, the result is the r.h.s., be it an Err or no.
1003 *-----------------------------------------------------------------------
1005 * Main expression production.
1009 * True, False or Err.
1012 * Tokens are, of course, consumed.
1014 *-----------------------------------------------------------------------
1024 o = CondToken(doEval);
1030 * A similar thing occurs for ||, except that here we make sure
1031 * the l.h.s. is False before we bother to evaluate the r.h.s.
1032 * Once again, if l is False, the result is the r.h.s. and once
1033 * again if l is True, we parse the r.h.s. to throw it away.
1038 (void) CondE(FALSE);
1051 *-----------------------------------------------------------------------
1053 * Evaluate the conditional in the passed line. The line
1055 * #<cond-type> <expr>
1056 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1057 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1058 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1059 * and parenthetical groupings thereof.
1062 * COND_PARSE if should parse lines after the conditional
1063 * COND_SKIP if should skip lines after the conditional
1064 * COND_INVALID if not a valid conditional.
1069 *-----------------------------------------------------------------------
1073 char *line; /* Line to parse */
1077 Boolean value = FALSE;
1078 int level; /* Level at which to report errors. */
1080 level = PARSE_FATAL;
1082 for (line++; *line == ' ' || *line == '\t'; line++) {
1087 * Find what type of if we're dealing with. The result is left
1088 * in ifp and isElse is set TRUE if it's an elif line.
1090 if (line[0] == 'e' && line[1] == 'l') {
1093 } else if (strncmp (line, "endif", 5) == 0) {
1095 * End of a conditional section. If skipIfLevel is non-zero, that
1096 * conditional was skipped, so lines following it should also be
1097 * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1098 * was read so succeeding lines should be parsed (think about it...)
1099 * so we return COND_PARSE, unless this endif isn't paired with
1102 if (skipIfLevel != 0) {
1106 if (condTop == MAXIF) {
1107 Parse_Error (level, "if-less endif");
1108 return (COND_INVALID);
1112 return (COND_PARSE);
1120 * Figure out what sort of conditional it is -- what its default
1121 * function is, etc. -- by looking in the table of valid "ifs"
1123 for (ifp = ifs; ifp->form != (char *)0; ifp++) {
1124 if (strncmp (ifp->form, line, ifp->formlen) == 0) {
1129 if (ifp->form == (char *) 0) {
1131 * Nothing fit. If the first word on the line is actually
1132 * "else", it's a valid conditional whose value is the inverse
1133 * of the previous if we parsed.
1135 if (isElse && (line[0] == 's') && (line[1] == 'e')) {
1136 if (condTop == MAXIF) {
1137 Parse_Error (level, "if-less else");
1138 return (COND_INVALID);
1139 } else if (skipIfLevel == 0) {
1140 value = !condStack[condTop];
1146 * Not a valid conditional type. No error...
1148 return (COND_INVALID);
1152 if (condTop == MAXIF) {
1153 Parse_Error (level, "if-less elif");
1154 return (COND_INVALID);
1155 } else if (skipIfLevel != 0) {
1157 * If skipping this conditional, just ignore the whole thing.
1158 * If we don't, the user might be employing a variable that's
1159 * undefined, for which there's an enclosing ifdef that
1164 } else if (skipLine) {
1166 * Don't even try to evaluate a conditional that's not an else if
1167 * we're skipping things...
1174 * Initialize file-global variables for parsing
1176 condDefProc = ifp->defProc;
1177 condInvert = ifp->doNot;
1179 line += ifp->formlen;
1181 while (*line == ' ' || *line == '\t') {
1186 condPushBack = None;
1188 switch (CondE(TRUE)) {
1190 if (CondToken(TRUE) == EndOfFile) {
1197 if (CondToken(TRUE) == EndOfFile) {
1204 Parse_Error (level, "Malformed conditional (%s)",
1206 return (COND_INVALID);
1213 } else if ((skipIfLevel != 0) || condStack[condTop]) {
1215 * If this is an else-type conditional, it should only take effect
1216 * if its corresponding if was evaluated and FALSE. If its if was
1217 * TRUE or skipped, we return COND_SKIP (and start skipping in case
1218 * we weren't already), leaving the stack unmolested so later elif's
1227 * This is the one case where we can definitely proclaim a fatal
1228 * error. If we don't, we're hosed.
1230 Parse_Error (PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1231 return (COND_INVALID);
1233 condStack[condTop] = value;
1235 return (value ? COND_PARSE : COND_SKIP);
1240 *-----------------------------------------------------------------------
1242 * Make sure everything's clean at the end of a makefile.
1248 * Parse_Error will be called if open conditionals are around.
1250 *-----------------------------------------------------------------------
1255 if (condTop != MAXIF) {
1256 Parse_Error(PARSE_FATAL, "%d open conditional%s", MAXIF-condTop,
1257 MAXIF-condTop == 1 ? "" : "s");