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
42 #include <sys/cdefs.h>
48 * Functions to handle conditionals in a makefile.
51 * Cond_Eval Evaluate the conditional in the passed line.
63 * The parsing of conditional expressions is based on this grammar:
68 * T -> defined(variable)
74 * T -> $(varspec) op value
75 * T -> $(varspec) == "string"
76 * T -> $(varspec) != "string"
79 * op -> == | != | > | < | >= | <=
81 * 'symbol' is some other symbol to which the default function (condDefProc)
84 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken)
85 * will return And for '&' and '&&', Or for '|' and '||', Not for '!',
86 * LParen for '(', RParen for ')' and will evaluate the other terminal
87 * symbols, using either the default function or the function given in the
88 * terminal, and return the result as either True or False.
90 * All Non-Terminal functions (CondE, CondF and CondT) return Err on error.
93 And, Or, Not, True, False, LParen, RParen, EndOfFile, None, Err
97 * Structures to handle elegantly the different forms of #if's. The
98 * last two fields are stored in condInvert and condDefProc, respectively.
100 static void CondPushBack __P((Token));
101 static int CondGetArg __P((char **, char **, char *, Boolean));
102 static Boolean CondDoDefined __P((int, char *));
103 static int CondStrMatch __P((void *, void *));
104 static Boolean CondDoMake __P((int, char *));
105 static Boolean CondDoExists __P((int, char *));
106 static Boolean CondDoTarget __P((int, char *));
107 static char * CondCvtArg __P((char *, double *));
108 static Token CondToken __P((Boolean));
109 static Token CondT __P((Boolean));
110 static Token CondF __P((Boolean));
111 static Token CondE __P((Boolean));
114 char *form; /* Form of if */
115 int formlen; /* Length of form */
116 Boolean doNot; /* TRUE if default function should be negated */
117 Boolean (*defProc) __P((int, char *)); /* Default function to apply */
119 { "ifdef", 5, FALSE, CondDoDefined },
120 { "ifndef", 6, TRUE, CondDoDefined },
121 { "ifmake", 6, FALSE, CondDoMake },
122 { "ifnmake", 7, TRUE, CondDoMake },
123 { "if", 2, FALSE, CondDoDefined },
124 { NULL, 0, FALSE, NULL }
127 static Boolean condInvert; /* Invert the default function */
128 static Boolean (*condDefProc) /* Default function to apply */
130 static char *condExpr; /* The expression to parse */
131 static Token condPushBack=None; /* Single push-back token used in
134 #define MAXIF 30 /* greatest depth of #if'ing */
136 static Boolean condStack[MAXIF]; /* Stack of conditionals's values */
137 static int condTop = MAXIF; /* Top-most conditional */
138 static int skipIfLevel=0; /* Depth of skipped conditionals */
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 *-----------------------------------------------------------------------
158 Token t; /* Token to push back into the "stream" */
164 *-----------------------------------------------------------------------
166 * Find the argument of a built-in function.
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 (linePtr, argPtr, func, parens)
182 Boolean parens; /* TRUE if arg should be bounded by parens */
190 while (*cp != '(' && *cp != '\0') {
200 * No arguments whatsoever. Because 'make' and 'defined' aren't really
201 * "reserved words", we don't print a message. I think this is better
202 * than hitting the user with a warning message every time s/he uses
203 * the word 'make' or 'defined' at the beginning of a symbol...
209 while (*cp == ' ' || *cp == '\t') {
214 * Create a buffer for the argument and start it out at 16 characters
215 * long. Why 16? Why not?
219 while ((strchr(" \t)&|", *cp) == (char *)NULL) && (*cp != '\0')) {
222 * Parse the variable spec and install it as part of the argument
223 * if it's valid. We tell Var_Parse to complain on an undefined
224 * variable, so we don't do it too. Nor do we return an error,
225 * though perhaps we should...
231 cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &doFree);
233 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
239 Buf_AddByte(buf, (Byte)*cp);
244 Buf_AddByte(buf, (Byte)'\0');
245 *argPtr = (char *)Buf_GetAll(buf, &argLen);
246 Buf_Destroy(buf, FALSE);
248 while (*cp == ' ' || *cp == '\t') {
251 if (parens && *cp != ')') {
252 Parse_Error (PARSE_WARNING, "Missing closing parenthesis for %s()",
257 * Advance pointer past close parenthesis.
267 *-----------------------------------------------------------------------
269 * Handle the 'defined' function for conditionals.
272 * TRUE if the given variable is defined.
277 *-----------------------------------------------------------------------
280 CondDoDefined (argLen, arg)
284 char savec = arg[argLen];
289 if (Var_Value (arg, VAR_CMD, &p1) != (char *)NULL) {
300 *-----------------------------------------------------------------------
302 * Front-end for Str_Match so it returns 0 on match and non-zero
303 * on mismatch. Callback function for CondDoMake via Lst_Find
306 * 0 if string matches pattern
311 *-----------------------------------------------------------------------
314 CondStrMatch(string, pattern)
318 return(!Str_Match((char *) string,(char *) pattern));
322 *-----------------------------------------------------------------------
324 * Handle the 'make' function for conditionals.
327 * TRUE if the given target is being made.
332 *-----------------------------------------------------------------------
335 CondDoMake (argLen, arg)
339 char savec = arg[argLen];
343 if (Lst_Find (create, (void *)arg, CondStrMatch) == NULL) {
353 *-----------------------------------------------------------------------
355 * See if the given file exists.
358 * TRUE if the file exists and FALSE if it does not.
363 *-----------------------------------------------------------------------
366 CondDoExists (argLen, arg)
370 char savec = arg[argLen];
375 path = Dir_FindFile(arg, dirSearchPath);
376 if (path != (char *)NULL) {
387 *-----------------------------------------------------------------------
389 * See if the given node exists and is an actual target.
392 * TRUE if the node exists as a target and FALSE if it does not.
397 *-----------------------------------------------------------------------
400 CondDoTarget (argLen, arg)
404 char savec = arg[argLen];
409 gn = Targ_FindNode(arg, TARG_NOCREATE);
410 if ((gn != NULL) && !OP_NOP(gn->type)) {
421 *-----------------------------------------------------------------------
423 * Convert the given number into a double. If the number begins
424 * with 0x, it is interpreted as a hexadecimal integer
425 * and converted to a double from there. All other strings just have
426 * strtod called on them.
429 * Sets 'value' to double value of string.
430 * Returns address of the first character after the last valid
431 * character of the converted number.
434 * Can change 'value' even if string is not a valid number.
437 *-----------------------------------------------------------------------
440 CondCvtArg(str, value)
444 if ((*str == '0') && (str[1] == 'x')) {
447 for (str += 2, i = 0; ; str++) {
449 if (isdigit((unsigned char) *str))
451 else if (isxdigit((unsigned char) *str))
452 x = 10 + *str - isupper((unsigned char) *str) ? 'A' : 'a';
462 *value = strtod(str, &eptr);
468 *-----------------------------------------------------------------------
470 * Return the next token from the input.
473 * A Token for the next lexical token in the stream.
476 * condPushback will be set back to None if it is used.
478 *-----------------------------------------------------------------------
486 if (condPushBack == None) {
487 while (*condExpr == ' ' || *condExpr == '\t') {
500 if (condExpr[1] == '|') {
507 if (condExpr[1] == '&') {
529 * Parse the variable spec and skip over it, saving its
533 lhs = Var_Parse(condExpr, VAR_CMD, doEval,&varSpecLen,&doFree);
534 if (lhs == var_Error) {
536 * Even if !doEval, we still report syntax errors, which
537 * is what getting var_Error back with !doEval means.
541 condExpr += varSpecLen;
543 if (!isspace((unsigned char) *condExpr) &&
544 strchr("!=><", *condExpr) == NULL) {
550 for (cp = lhs; *cp; cp++)
551 Buf_AddByte(buf, (Byte)*cp);
556 for (;*condExpr && !isspace((unsigned char) *condExpr);
558 Buf_AddByte(buf, (Byte)*condExpr);
560 Buf_AddByte(buf, (Byte)'\0');
561 lhs = (char *)Buf_GetAll(buf, &varSpecLen);
562 Buf_Destroy(buf, FALSE);
568 * Skip whitespace to get to the operator
570 while (isspace((unsigned char) *condExpr))
574 * Make sure the operator is a valid one. If it isn't a
575 * known relational operator, pretend we got a
584 if (condExpr[1] == '=') {
596 while (isspace((unsigned char) *condExpr)) {
599 if (*condExpr == '\0') {
600 Parse_Error(PARSE_WARNING,
601 "Missing right-hand-side of operator");
608 * Doing a string comparison. Only allow == and != for
617 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
618 Parse_Error(PARSE_WARNING,
619 "String comparison operator should be either == or !=");
624 qt = *rhs == '"' ? 1 : 0;
627 ((qt && (*cp != '"')) ||
628 (!qt && strchr(" \t)", *cp) == NULL)) &&
629 (*cp != '\0'); cp++) {
630 if ((*cp == '\\') && (cp[1] != '\0')) {
632 * Backslash escapes things -- skip over next
633 * character, if it exists.
636 Buf_AddByte(buf, (Byte)*cp);
637 } else if (*cp == '$') {
641 cp2 = Var_Parse(cp, VAR_CMD, doEval,&len, &freeIt);
642 if (cp2 != var_Error) {
643 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
649 Buf_AddByte(buf, (Byte)*cp);
652 Buf_AddByte(buf, (Byte)*cp);
656 Buf_AddByte(buf, (Byte)0);
658 string = (char *)Buf_GetAll(buf, (int *)0);
659 Buf_Destroy(buf, FALSE);
662 printf("lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
666 * Null-terminate rhs and perform the comparison.
667 * t is set to the result.
670 t = strcmp(lhs, string) ? False : True;
672 t = strcmp(lhs, string) ? True : False;
675 if (rhs == condExpr) {
676 if (!qt && *cp == ')')
683 * rhs is either a float or an integer. Convert both the
684 * lhs and the rhs to a double and compare the two.
689 if (*CondCvtArg(lhs, &left) != '\0')
690 goto do_string_compare;
695 string = Var_Parse(rhs, VAR_CMD, doEval,&len,&freeIt);
696 if (string == var_Error) {
699 if (*CondCvtArg(string, &right) != '\0') {
702 goto do_string_compare;
710 char *c = CondCvtArg(rhs, &right);
711 if (*c != '\0' && !isspace(*c))
712 goto do_string_compare;
713 if (rhs == condExpr) {
715 * Skip over the right-hand side
717 while(!isspace((unsigned char) *condExpr) &&
718 (*condExpr != '\0')) {
725 printf("left = %f, right = %f, op = %.2s\n", left,
731 Parse_Error(PARSE_WARNING,
735 t = (left != right ? True : False);
739 Parse_Error(PARSE_WARNING,
743 t = (left == right ? True : False);
747 t = (left <= right ? True : False);
749 t = (left < right ? True : False);
754 t = (left >= right ? True : False);
756 t = (left > right ? True : False);
767 Boolean (*evalProc) __P((int, char *));
768 Boolean invert = FALSE;
772 if (strncmp (condExpr, "defined", 7) == 0) {
774 * Use CondDoDefined to evaluate the argument and
775 * CondGetArg to extract the argument from the 'function
778 evalProc = CondDoDefined;
780 arglen = CondGetArg (&condExpr, &arg, "defined", TRUE);
785 } else if (strncmp (condExpr, "make", 4) == 0) {
787 * Use CondDoMake to evaluate the argument and
788 * CondGetArg to extract the argument from the 'function
791 evalProc = CondDoMake;
793 arglen = CondGetArg (&condExpr, &arg, "make", TRUE);
798 } else if (strncmp (condExpr, "exists", 6) == 0) {
800 * Use CondDoExists to evaluate the argument and
801 * CondGetArg to extract the argument from the
804 evalProc = CondDoExists;
806 arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
811 } else if (strncmp(condExpr, "empty", 5) == 0) {
813 * Use Var_Parse to parse the spec in parens and return
814 * True if the resulting string is empty.
823 condExpr[arglen] != '(' && condExpr[arglen] != '\0';
827 if (condExpr[arglen] != '\0') {
828 val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
829 doEval, &length, &doFree);
830 if (val == var_Error) {
834 * A variable is empty when it just contains
835 * spaces... 4/15/92, christos
838 for (p = val; *p && isspace((unsigned char)*p); p++)
840 t = (*p == '\0') ? True : False;
846 * Advance condExpr to beyond the closing ). Note that
847 * we subtract one from arglen + length b/c length
848 * is calculated from condExpr[arglen - 1].
850 condExpr += arglen + length - 1;
856 } else if (strncmp (condExpr, "target", 6) == 0) {
858 * Use CondDoTarget to evaluate the argument and
859 * CondGetArg to extract the argument from the
862 evalProc = CondDoTarget;
864 arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
871 * The symbol is itself the argument to the default
872 * function. We advance condExpr to the end of the symbol
873 * by hand (the next whitespace, closing paren or
874 * binary operator) and set to invert the evaluation
875 * function if condInvert is TRUE.
879 evalProc = condDefProc;
880 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
884 * Evaluate the argument using the set function. If invert
885 * is TRUE, we invert the sense of the function.
887 t = (!doEval || (* evalProc) (arglen, arg) ?
888 (invert ? False : True) :
889 (invert ? True : False));
902 *-----------------------------------------------------------------------
904 * Parse a single term in the expression. This consists of a terminal
905 * symbol or Not and a terminal symbol (not including the binary
907 * T -> defined(variable) | make(target) | exists(file) | symbol
911 * True, False or Err.
914 * Tokens are consumed.
916 *-----------------------------------------------------------------------
924 t = CondToken(doEval);
926 if (t == EndOfFile) {
928 * If we reached the end of the expression, the expression
932 } else if (t == LParen) {
938 if (CondToken(doEval) != RParen) {
942 } else if (t == Not) {
946 } else if (t == False) {
954 *-----------------------------------------------------------------------
956 * Parse a conjunctive factor (nice name, wot?)
963 * Tokens are consumed.
965 *-----------------------------------------------------------------------
975 o = CondToken(doEval);
981 * If T is False, the whole thing will be False, but we have to
982 * parse the r.h.s. anyway (to throw it away).
983 * If T is True, the result is the r.h.s., be it an Err or no.
1001 *-----------------------------------------------------------------------
1003 * Main expression production.
1007 * True, False or Err.
1010 * Tokens are, of course, consumed.
1012 *-----------------------------------------------------------------------
1022 o = CondToken(doEval);
1028 * A similar thing occurs for ||, except that here we make sure
1029 * the l.h.s. is False before we bother to evaluate the r.h.s.
1030 * Once again, if l is False, the result is the r.h.s. and once
1031 * again if l is True, we parse the r.h.s. to throw it away.
1036 (void) CondE(FALSE);
1049 *-----------------------------------------------------------------------
1051 * Evaluate the conditional in the passed line. The line
1053 * #<cond-type> <expr>
1054 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1055 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1056 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1057 * and parenthetical groupings thereof.
1060 * COND_PARSE if should parse lines after the conditional
1061 * COND_SKIP if should skip lines after the conditional
1062 * COND_INVALID if not a valid conditional.
1067 *-----------------------------------------------------------------------
1071 char *line; /* Line to parse */
1075 Boolean value = FALSE;
1076 int level; /* Level at which to report errors. */
1078 level = PARSE_FATAL;
1080 for (line++; *line == ' ' || *line == '\t'; line++) {
1085 * Find what type of if we're dealing with. The result is left
1086 * in ifp and isElse is set TRUE if it's an elif line.
1088 if (line[0] == 'e' && line[1] == 'l') {
1091 } else if (strncmp (line, "endif", 5) == 0) {
1093 * End of a conditional section. If skipIfLevel is non-zero, that
1094 * conditional was skipped, so lines following it should also be
1095 * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1096 * was read so succeeding lines should be parsed (think about it...)
1097 * so we return COND_PARSE, unless this endif isn't paired with
1100 if (skipIfLevel != 0) {
1104 if (condTop == MAXIF) {
1105 Parse_Error (level, "if-less endif");
1106 return (COND_INVALID);
1110 return (COND_PARSE);
1118 * Figure out what sort of conditional it is -- what its default
1119 * function is, etc. -- by looking in the table of valid "ifs"
1121 for (ifp = ifs; ifp->form != (char *)0; ifp++) {
1122 if (strncmp (ifp->form, line, ifp->formlen) == 0) {
1127 if (ifp->form == (char *) 0) {
1129 * Nothing fit. If the first word on the line is actually
1130 * "else", it's a valid conditional whose value is the inverse
1131 * of the previous if we parsed.
1133 if (isElse && (line[0] == 's') && (line[1] == 'e')) {
1134 if (condTop == MAXIF) {
1135 Parse_Error (level, "if-less else");
1136 return (COND_INVALID);
1137 } else if (skipIfLevel == 0) {
1138 value = !condStack[condTop];
1144 * Not a valid conditional type. No error...
1146 return (COND_INVALID);
1150 if (condTop == MAXIF) {
1151 Parse_Error (level, "if-less elif");
1152 return (COND_INVALID);
1153 } else if (skipIfLevel != 0) {
1155 * If skipping this conditional, just ignore the whole thing.
1156 * If we don't, the user might be employing a variable that's
1157 * undefined, for which there's an enclosing ifdef that
1162 } else if (skipLine) {
1164 * Don't even try to evaluate a conditional that's not an else if
1165 * we're skipping things...
1172 * Initialize file-global variables for parsing
1174 condDefProc = ifp->defProc;
1175 condInvert = ifp->doNot;
1177 line += ifp->formlen;
1179 while (*line == ' ' || *line == '\t') {
1184 condPushBack = None;
1186 switch (CondE(TRUE)) {
1188 if (CondToken(TRUE) == EndOfFile) {
1195 if (CondToken(TRUE) == EndOfFile) {
1202 Parse_Error (level, "Malformed conditional (%s)",
1204 return (COND_INVALID);
1211 } else if ((skipIfLevel != 0) || condStack[condTop]) {
1213 * If this is an else-type conditional, it should only take effect
1214 * if its corresponding if was evaluated and FALSE. If its if was
1215 * TRUE or skipped, we return COND_SKIP (and start skipping in case
1216 * we weren't already), leaving the stack unmolested so later elif's
1225 * This is the one case where we can definitely proclaim a fatal
1226 * error. If we don't, we're hosed.
1228 Parse_Error (PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1229 return (COND_INVALID);
1231 condStack[condTop] = value;
1233 return (value ? COND_PARSE : COND_SKIP);
1238 *-----------------------------------------------------------------------
1240 * Make sure everything's clean at the end of a makefile.
1246 * Parse_Error will be called if open conditionals are around.
1248 *-----------------------------------------------------------------------
1253 if (condTop != MAXIF) {
1254 Parse_Error(PARSE_FATAL, "%d open conditional%s", MAXIF-condTop,
1255 MAXIF-condTop == 1 ? "" : "s");