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.9 2004/11/12 22:57:04 dillon 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 condTop = MAXIF; /* Top-most conditional */
136 static int skipIfLevel=0; /* Depth of skipped conditionals */
137 static Boolean skipLine = FALSE; /* Whether the parse module is skipping
141 *-----------------------------------------------------------------------
143 * Push back the most recent token read. We only need one level of
144 * this, so the thing is just stored in 'condPushback'.
150 * condPushback is overwritten.
152 *-----------------------------------------------------------------------
155 CondPushBack (Token t)
161 *-----------------------------------------------------------------------
163 * Find the argument of a built-in function. parens is set to TRUE
164 * if the arguments are bounded by parens.
167 * The length of the argument and the address of the argument.
170 * The pointer is set to point to the closing parenthesis of the
173 *-----------------------------------------------------------------------
176 CondGetArg (char **linePtr, char **argPtr, char *func, Boolean parens)
184 while (*cp != '(' && *cp != '\0') {
194 * No arguments whatsoever. Because 'make' and 'defined' aren't really
195 * "reserved words", we don't print a message. I think this is better
196 * than hitting the user with a warning message every time s/he uses
197 * the word 'make' or 'defined' at the beginning of a symbol...
203 while (*cp == ' ' || *cp == '\t') {
208 * Create a buffer for the argument and start it out at 16 characters
209 * long. Why 16? Why not?
213 while ((strchr(" \t)&|", *cp) == (char *)NULL) && (*cp != '\0')) {
216 * Parse the variable spec and install it as part of the argument
217 * if it's valid. We tell Var_Parse to complain on an undefined
218 * variable, so we don't do it too. Nor do we return an error,
219 * though perhaps we should...
225 cp2 = Var_Parse(cp, VAR_CMD, TRUE, &len, &doFree);
227 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
233 Buf_AddByte(buf, (Byte)*cp);
238 Buf_AddByte(buf, (Byte)'\0');
239 *argPtr = (char *)Buf_GetAll(buf, &argLen);
240 Buf_Destroy(buf, FALSE);
242 while (*cp == ' ' || *cp == '\t') {
245 if (parens && *cp != ')') {
246 Parse_Error (PARSE_WARNING, "Missing closing parenthesis for %s()",
251 * Advance pointer past close parenthesis.
261 *-----------------------------------------------------------------------
263 * Handle the 'defined' function for conditionals.
266 * TRUE if the given variable is defined.
271 *-----------------------------------------------------------------------
274 CondDoDefined (int argLen, char *arg)
276 char savec = arg[argLen];
281 if (Var_Value (arg, VAR_CMD, &p1) != (char *)NULL) {
292 *-----------------------------------------------------------------------
294 * Front-end for Str_Match so it returns 0 on match and non-zero
295 * on mismatch. Callback function for CondDoMake via Lst_Find
298 * 0 if string matches pattern
303 *-----------------------------------------------------------------------
306 CondStrMatch(void *string, void *pattern)
308 return(!Str_Match((char *) string,(char *) pattern));
312 *-----------------------------------------------------------------------
314 * Handle the 'make' function for conditionals.
317 * TRUE if the given target is being made.
322 *-----------------------------------------------------------------------
325 CondDoMake (int argLen, char *arg)
327 char savec = arg[argLen];
331 if (Lst_Find (create, (void *)arg, CondStrMatch) == NULL) {
341 *-----------------------------------------------------------------------
343 * See if the given file exists.
346 * TRUE if the file exists and FALSE if it does not.
351 *-----------------------------------------------------------------------
354 CondDoExists (int argLen, char *arg)
356 char savec = arg[argLen];
361 path = Dir_FindFile(arg, dirSearchPath);
362 if (path != (char *)NULL) {
373 *-----------------------------------------------------------------------
375 * See if the given node exists and is an actual target.
378 * TRUE if the node exists as a target and FALSE if it does not.
383 *-----------------------------------------------------------------------
386 CondDoTarget (int argLen, char *arg)
388 char savec = arg[argLen];
393 gn = Targ_FindNode(arg, TARG_NOCREATE);
394 if ((gn != NULL) && !OP_NOP(gn->type)) {
405 *-----------------------------------------------------------------------
407 * Convert the given number into a double. If the number begins
408 * with 0x, it is interpreted as a hexadecimal integer
409 * and converted to a double from there. All other strings just have
410 * strtod called on them.
413 * Sets 'value' to double value of string.
414 * Returns address of the first character after the last valid
415 * character of the converted number.
418 * Can change 'value' even if string is not a valid number.
421 *-----------------------------------------------------------------------
424 CondCvtArg(char *str, double *value)
426 if ((*str == '0') && (str[1] == 'x')) {
429 for (str += 2, i = 0; ; str++) {
431 if (isdigit((unsigned char) *str))
433 else if (isxdigit((unsigned char) *str))
434 x = 10 + *str - isupper((unsigned char) *str) ? 'A' : 'a';
444 *value = strtod(str, &eptr);
450 *-----------------------------------------------------------------------
452 * Return the next token from the input.
455 * A Token for the next lexical token in the stream.
458 * condPushback will be set back to None if it is used.
460 *-----------------------------------------------------------------------
463 CondToken(Boolean doEval)
467 if (condPushBack == None) {
468 while (*condExpr == ' ' || *condExpr == '\t') {
481 if (condExpr[1] == '|') {
488 if (condExpr[1] == '&') {
510 * Parse the variable spec and skip over it, saving its
514 lhs = Var_Parse(condExpr, VAR_CMD, doEval,&varSpecLen,&doFree);
515 if (lhs == var_Error) {
517 * Even if !doEval, we still report syntax errors, which
518 * is what getting var_Error back with !doEval means.
522 condExpr += varSpecLen;
524 if (!isspace((unsigned char) *condExpr) &&
525 strchr("!=><", *condExpr) == NULL) {
531 for (cp = lhs; *cp; cp++)
532 Buf_AddByte(buf, (Byte)*cp);
537 for (;*condExpr && !isspace((unsigned char) *condExpr);
539 Buf_AddByte(buf, (Byte)*condExpr);
541 Buf_AddByte(buf, (Byte)'\0');
542 lhs = (char *)Buf_GetAll(buf, &varSpecLen);
543 Buf_Destroy(buf, FALSE);
549 * Skip whitespace to get to the operator
551 while (isspace((unsigned char) *condExpr))
555 * Make sure the operator is a valid one. If it isn't a
556 * known relational operator, pretend we got a
565 if (condExpr[1] == '=') {
577 while (isspace((unsigned char) *condExpr)) {
580 if (*condExpr == '\0') {
581 Parse_Error(PARSE_WARNING,
582 "Missing right-hand-side of operator");
589 * Doing a string comparison. Only allow == and != for
598 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
599 Parse_Error(PARSE_WARNING,
600 "String comparison operator should be either == or !=");
605 qt = *rhs == '"' ? 1 : 0;
608 ((qt && (*cp != '"')) ||
609 (!qt && strchr(" \t)", *cp) == NULL)) &&
610 (*cp != '\0'); cp++) {
611 if ((*cp == '\\') && (cp[1] != '\0')) {
613 * Backslash escapes things -- skip over next
614 * character, if it exists.
617 Buf_AddByte(buf, (Byte)*cp);
618 } else if (*cp == '$') {
622 cp2 = Var_Parse(cp, VAR_CMD, doEval,&len, &freeIt);
623 if (cp2 != var_Error) {
624 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
630 Buf_AddByte(buf, (Byte)*cp);
633 Buf_AddByte(buf, (Byte)*cp);
637 Buf_AddByte(buf, (Byte)0);
639 string = (char *)Buf_GetAll(buf, (int *)0);
640 Buf_Destroy(buf, FALSE);
642 DEBUGF(COND, ("lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
645 * Null-terminate rhs and perform the comparison.
646 * t is set to the result.
649 t = strcmp(lhs, string) ? False : True;
651 t = strcmp(lhs, string) ? True : False;
654 if (rhs == condExpr) {
655 if (!qt && *cp == ')')
662 * rhs is either a float or an integer. Convert both the
663 * lhs and the rhs to a double and compare the two.
668 if (*CondCvtArg(lhs, &left) != '\0')
669 goto do_string_compare;
674 string = Var_Parse(rhs, VAR_CMD, doEval,&len,&freeIt);
675 if (string == var_Error) {
678 if (*CondCvtArg(string, &right) != '\0') {
681 goto do_string_compare;
689 char *c = CondCvtArg(rhs, &right);
691 goto do_string_compare;
692 if (rhs == condExpr) {
694 * Skip over the right-hand side
700 DEBUGF(COND, ("left = %f, right = %f, op = %.2s\n", left,
705 Parse_Error(PARSE_WARNING,
709 t = (left != right ? True : False);
713 Parse_Error(PARSE_WARNING,
717 t = (left == right ? True : False);
721 t = (left <= right ? True : False);
723 t = (left < right ? True : False);
728 t = (left >= right ? True : False);
730 t = (left > right ? True : False);
741 Boolean (*evalProc)(int, char *);
742 Boolean invert = FALSE;
746 if (strncmp (condExpr, "defined", 7) == 0) {
748 * Use CondDoDefined to evaluate the argument and
749 * CondGetArg to extract the argument from the 'function
752 evalProc = CondDoDefined;
754 arglen = CondGetArg (&condExpr, &arg, "defined", TRUE);
759 } else if (strncmp (condExpr, "make", 4) == 0) {
761 * Use CondDoMake to evaluate the argument and
762 * CondGetArg to extract the argument from the 'function
765 evalProc = CondDoMake;
767 arglen = CondGetArg (&condExpr, &arg, "make", TRUE);
772 } else if (strncmp (condExpr, "exists", 6) == 0) {
774 * Use CondDoExists to evaluate the argument and
775 * CondGetArg to extract the argument from the
778 evalProc = CondDoExists;
780 arglen = CondGetArg(&condExpr, &arg, "exists", TRUE);
785 } else if (strncmp(condExpr, "empty", 5) == 0) {
787 * Use Var_Parse to parse the spec in parens and return
788 * True if the resulting string is empty.
797 condExpr[arglen] != '(' && condExpr[arglen] != '\0';
801 if (condExpr[arglen] != '\0') {
802 val = Var_Parse(&condExpr[arglen - 1], VAR_CMD,
803 doEval, &length, &doFree);
804 if (val == var_Error) {
808 * A variable is empty when it just contains
809 * spaces... 4/15/92, christos
812 for (p = val; *p && isspace((unsigned char)*p); p++)
814 t = (*p == '\0') ? True : False;
820 * Advance condExpr to beyond the closing ). Note that
821 * we subtract one from arglen + length b/c length
822 * is calculated from condExpr[arglen - 1].
824 condExpr += arglen + length - 1;
830 } else if (strncmp (condExpr, "target", 6) == 0) {
832 * Use CondDoTarget to evaluate the argument and
833 * CondGetArg to extract the argument from the
836 evalProc = CondDoTarget;
838 arglen = CondGetArg(&condExpr, &arg, "target", TRUE);
845 * The symbol is itself the argument to the default
846 * function. We advance condExpr to the end of the symbol
847 * by hand (the next whitespace, closing paren or
848 * binary operator) and set to invert the evaluation
849 * function if condInvert is TRUE.
853 evalProc = condDefProc;
854 arglen = CondGetArg(&condExpr, &arg, "", FALSE);
858 * Evaluate the argument using the set function. If invert
859 * is TRUE, we invert the sense of the function.
861 t = (!doEval || (* evalProc) (arglen, arg) ?
862 (invert ? False : True) :
863 (invert ? True : False));
876 *-----------------------------------------------------------------------
878 * Parse a single term in the expression. This consists of a terminal
879 * symbol or Not and a terminal symbol (not including the binary
881 * T -> defined(variable) | make(target) | exists(file) | symbol
885 * True, False or Err.
888 * Tokens are consumed.
890 *-----------------------------------------------------------------------
893 CondT(Boolean doEval)
897 t = CondToken(doEval);
899 if (t == EndOfFile) {
901 * If we reached the end of the expression, the expression
905 } else if (t == LParen) {
911 if (CondToken(doEval) != RParen) {
915 } else if (t == Not) {
919 } else if (t == False) {
927 *-----------------------------------------------------------------------
929 * Parse a conjunctive factor (nice name, wot?)
936 * Tokens are consumed.
938 *-----------------------------------------------------------------------
941 CondF(Boolean doEval)
947 o = CondToken(doEval);
953 * If T is False, the whole thing will be False, but we have to
954 * parse the r.h.s. anyway (to throw it away).
955 * If T is True, the result is the r.h.s., be it an Err or no.
973 *-----------------------------------------------------------------------
975 * Main expression production.
979 * True, False or Err.
982 * Tokens are, of course, consumed.
984 *-----------------------------------------------------------------------
987 CondE(Boolean doEval)
993 o = CondToken(doEval);
999 * A similar thing occurs for ||, except that here we make sure
1000 * the l.h.s. is False before we bother to evaluate the r.h.s.
1001 * Once again, if l is False, the result is the r.h.s. and once
1002 * again if l is True, we parse the r.h.s. to throw it away.
1007 (void) CondE(FALSE);
1020 *-----------------------------------------------------------------------
1022 * Evaluate the conditional in the passed line. The line
1024 * #<cond-type> <expr>
1025 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1026 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1027 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1028 * and parenthetical groupings thereof.
1031 * COND_PARSE if should parse lines after the conditional
1032 * COND_SKIP if should skip lines after the conditional
1033 * COND_INVALID if not a valid conditional.
1038 *-----------------------------------------------------------------------
1041 Cond_Eval (char *line)
1045 Boolean value = FALSE;
1046 int level; /* Level at which to report errors. */
1048 level = PARSE_FATAL;
1050 for (line++; *line == ' ' || *line == '\t'; line++) {
1055 * Find what type of if we're dealing with. The result is left
1056 * in ifp and isElse is set TRUE if it's an elif line.
1058 if (line[0] == 'e' && line[1] == 'l') {
1061 } else if (strncmp (line, "endif", 5) == 0) {
1063 * End of a conditional section. If skipIfLevel is non-zero, that
1064 * conditional was skipped, so lines following it should also be
1065 * skipped. Hence, we return COND_SKIP. Otherwise, the conditional
1066 * was read so succeeding lines should be parsed (think about it...)
1067 * so we return COND_PARSE, unless this endif isn't paired with
1070 if (skipIfLevel != 0) {
1074 if (condTop == MAXIF) {
1075 Parse_Error (level, "if-less endif");
1076 return (COND_INVALID);
1080 return (COND_PARSE);
1088 * Figure out what sort of conditional it is -- what its default
1089 * function is, etc. -- by looking in the table of valid "ifs"
1091 for (ifp = ifs; ifp->form != (char *)0; ifp++) {
1092 if (strncmp (ifp->form, line, ifp->formlen) == 0) {
1097 if (ifp->form == (char *) 0) {
1099 * Nothing fit. If the first word on the line is actually
1100 * "else", it's a valid conditional whose value is the inverse
1101 * of the previous if we parsed.
1103 if (isElse && (line[0] == 's') && (line[1] == 'e')) {
1104 if (condTop == MAXIF) {
1105 Parse_Error (level, "if-less else");
1106 return (COND_INVALID);
1107 } else if (skipIfLevel == 0) {
1108 value = !condStack[condTop];
1114 * Not a valid conditional type. No error...
1116 return (COND_INVALID);
1120 if (condTop == MAXIF) {
1121 Parse_Error (level, "if-less elif");
1122 return (COND_INVALID);
1123 } else if (skipIfLevel != 0) {
1125 * If skipping this conditional, just ignore the whole thing.
1126 * If we don't, the user might be employing a variable that's
1127 * undefined, for which there's an enclosing ifdef that
1132 } else if (skipLine) {
1134 * Don't even try to evaluate a conditional that's not an else if
1135 * we're skipping things...
1142 * Initialize file-global variables for parsing
1144 condDefProc = ifp->defProc;
1145 condInvert = ifp->doNot;
1147 line += ifp->formlen;
1149 while (*line == ' ' || *line == '\t') {
1154 condPushBack = None;
1156 switch (CondE(TRUE)) {
1158 if (CondToken(TRUE) == EndOfFile) {
1165 if (CondToken(TRUE) == EndOfFile) {
1172 Parse_Error (level, "Malformed conditional (%s)",
1174 return (COND_INVALID);
1181 } else if ((skipIfLevel != 0) || condStack[condTop]) {
1183 * If this is an else-type conditional, it should only take effect
1184 * if its corresponding if was evaluated and FALSE. If its if was
1185 * TRUE or skipped, we return COND_SKIP (and start skipping in case
1186 * we weren't already), leaving the stack unmolested so later elif's
1195 * This is the one case where we can definitely proclaim a fatal
1196 * error. If we don't, we're hosed.
1198 Parse_Error (PARSE_FATAL, "Too many nested if's. %d max.", MAXIF);
1199 return (COND_INVALID);
1201 condStack[condTop] = value;
1203 return (value ? COND_PARSE : COND_SKIP);
1208 *-----------------------------------------------------------------------
1210 * Make sure everything's clean at the end of a makefile.
1216 * Parse_Error will be called if open conditionals are around.
1218 *-----------------------------------------------------------------------
1223 if (condTop != MAXIF) {
1224 Parse_Error(PARSE_FATAL, "%d open conditional%s", MAXIF-condTop,
1225 MAXIF-condTop == 1 ? "" : "s");